diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..c24adea2 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +core/expression/tests/** text eol=lf diff --git a/Cargo.lock b/Cargo.lock index 041bca5b..bb6eb1f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6198,6 +6198,7 @@ dependencies = [ "ahash 0.8.12", "hipstr", "nohash-hasher", + "recursive", "rust_decimal", "rust_decimal_macros", "serde", diff --git a/core/expression/Cargo.toml b/core/expression/Cargo.toml index 24cdabe7..3040c2e2 100644 --- a/core/expression/Cargo.toml +++ b/core/expression/Cargo.toml @@ -5,6 +5,7 @@ name = "zen-expression" license = "MIT" version = "2.1.6" edition = "2021" +rust-version = "1.88" repository = "https://github.com/gorules/zen.git" homepage = "https://gorules.io" @@ -63,4 +64,8 @@ name = "unary" [[bench]] harness = false -name = "isolate" \ No newline at end of file +name = "isolate" + +[[bench]] +harness = false +name = "lane" \ No newline at end of file diff --git a/core/expression/benches/lane.rs b/core/expression/benches/lane.rs new file mode 100644 index 00000000..f97982e6 --- /dev/null +++ b/core/expression/benches/lane.rs @@ -0,0 +1,1664 @@ +use rust_decimal::Decimal; +use serde_json::Value; +use std::collections::BTreeMap; +use std::hint::black_box; +use std::time::{Duration, Instant}; +use zen_expression::lane::{Column, Columns, LaneProgram, LaneRunner, Values}; +use zen_expression::variable::VariableType; +use zen_expression::vm::VM; +use zen_expression::{ExpressionKind, Isolate, Scope, Variable}; + +const ROWS: usize = 512; +const GRAPHS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../test-data/graphs"); + +struct Case { + source: String, + scopes: Vec, +} + +struct Bench; + +enum Data { + I64(Vec), + Dec(Vec), + Bool(Vec), + Str(Vec), + Dict(Vec, Vec), + ListDec(Vec, Vec), + ListI64(Vec, Vec), + ListStr(Vec, Vec), + ListStruct(Vec, Vec<(String, Field, Vec)>, usize), + Any(Vec), +} + +enum Field { + Scaled(Vec, Vec), + Utf8(Vec, Vec), + Bool(Vec), + Any(Vec), +} + +impl Field { + fn of(cells: &[Option]) -> (Field, Vec) { + let mut valid = vec![0u64; cells.len().div_ceil(64).max(1)]; + cells + .iter() + .enumerate() + .filter(|(_, c)| c.as_ref().is_some_and(|v| !matches!(v, Variable::Null))) + .for_each(|(i, _)| valid[i / 64] |= 1 << (i % 64)); + let present: Vec<&Variable> = cells + .iter() + .flatten() + .filter(|v| !matches!(v, Variable::Null)) + .collect(); + let field = match present.first() { + Some(Variable::Number(_)) + if present.iter().all( + |v| matches!(v, Variable::Number(n) if i64::try_from(n.mantissa()).is_ok()), + ) => + { + let parts: Vec<(i64, u8)> = cells + .iter() + .map(|c| match c { + Some(Variable::Number(n)) => { + (i64::try_from(n.mantissa()).unwrap_or(0), n.scale() as u8) + } + _ => (0, 0), + }) + .collect(); + Field::Scaled( + parts.iter().map(|p| p.0).collect(), + parts.iter().map(|p| p.1).collect(), + ) + } + Some(Variable::String(_)) + if present.iter().all(|v| matches!(v, Variable::String(_))) => + { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for c in cells { + if let Some(Variable::String(t)) = c { + data.extend_from_slice(t.as_bytes()); + } + offsets.push(data.len() as i32); + } + Field::Utf8(offsets, data) + } + Some(Variable::Bool(_)) if present.iter().all(|v| matches!(v, Variable::Bool(_))) => { + let mut bits = vec![0u64; cells.len().div_ceil(64).max(1)]; + cells + .iter() + .enumerate() + .filter(|(_, c)| matches!(c, Some(Variable::Bool(true)))) + .for_each(|(i, _)| bits[i / 64] |= 1 << (i % 64)); + Field::Bool(bits) + } + _ => Field::Any( + cells + .iter() + .map(|c| c.clone().unwrap_or(Variable::Null)) + .collect(), + ), + }; + (field, valid) + } + + fn values(&self) -> Values<'_> { + match self { + Field::Scaled(mant, scale) => Values::Scaled { mant, scale }, + Field::Utf8(offsets, data) => Values::Utf8 { offsets, data }, + Field::Bool(bits) => Values::Bool { bits, offset: 0 }, + Field::Any(values) => Values::Any(values), + } + } +} + +struct Table { + rows: usize, + keys: Vec, + data: Vec, + valid: Vec>, +} + +impl Table { + fn flatten(value: &Variable, prefix: String, out: &mut BTreeMap) { + match value { + Variable::Object(map) if !map.borrow().is_empty() => { + for (k, v) in map.borrow().iter() { + let path = if prefix.is_empty() { + k.to_string() + } else { + format!("{prefix}.{k}") + }; + Self::flatten(v, path, out); + } + } + v if !prefix.is_empty() => { + out.insert(prefix, v.clone()); + } + _ => {} + } + } + + fn build(scopes: &[Scope]) -> Self { + let flat: Vec> = scopes + .iter() + .map(|s| { + let mut m = BTreeMap::new(); + Self::flatten(s.base(), String::new(), &mut m); + m + }) + .collect(); + let mut keys: Vec = flat.iter().flat_map(|m| m.keys().cloned()).collect(); + keys.sort(); + keys.dedup(); + let rows = scopes.len(); + let mut data = Vec::new(); + let mut valid = Vec::new(); + for key in &keys { + let values: Vec> = flat.iter().map(|m| m.get(key)).collect(); + let mut bits = vec![0u64; rows.div_ceil(64)]; + for (i, v) in values.iter().enumerate() { + if v.is_some_and(|v| !matches!(v, Variable::Null)) { + bits[i / 64] |= 1 << (i % 64); + } + } + let present: Vec<&Variable> = values + .iter() + .flatten() + .copied() + .filter(|v| !matches!(v, Variable::Null)) + .collect(); + let all = + |f: fn(&Variable) -> bool| !present.is_empty() && present.iter().all(|v| f(v)); + let integral = |v: &Variable| matches!(v, Variable::Number(n) if n.scale() == 0 && i64::try_from(n.mantissa()).is_ok()); + let column = if !present.is_empty() && present.iter().all(|v| integral(v)) { + Data::I64( + values + .iter() + .map(|v| match v { + Some(Variable::Number(n)) => i64::try_from(n.mantissa()).unwrap_or(0), + _ => 0, + }) + .collect(), + ) + } else if all(|v| matches!(v, Variable::Number(_))) { + Data::Dec( + values + .iter() + .map(|v| match v { + Some(Variable::Number(n)) => *n, + _ => Decimal::ZERO, + }) + .collect(), + ) + } else if all(|v| matches!(v, Variable::Bool(_))) { + let mut words = vec![0u64; rows.div_ceil(64)]; + for (i, v) in values.iter().enumerate() { + if matches!(v, Some(Variable::Bool(true))) { + words[i / 64] |= 1 << (i % 64); + } + } + Data::Bool(words) + } else if all(|v| matches!(v, Variable::String(_))) + && std::env::var("LANE_DICT").is_ok() + { + let mut distinct: Vec = Vec::new(); + let codes = values + .iter() + .map(|v| { + let text = v.and_then(|v| v.as_str()).unwrap_or_default(); + match distinct.iter().position(|d| d == text) { + Some(i) => i as i32, + None => { + distinct.push(text.to_string()); + (distinct.len() - 1) as i32 + } + } + }) + .collect(); + Data::Dict(codes, distinct) + } else if all(|v| matches!(v, Variable::String(_))) { + Data::Str( + values + .iter() + .map(|v| v.and_then(|v| v.as_str()).unwrap_or_default().to_string()) + .collect(), + ) + } else if std::env::var("LANE_ANY_LISTS").is_err() + && all( + |v| matches!(v, Variable::Array(a) if a.borrow().iter().all(|x| matches!(x, Variable::Number(_)))), + ) + { + let mut offsets = vec![0i32]; + let mut items = Vec::new(); + for v in &values { + if let Some(Variable::Array(a)) = v { + items.extend(a.borrow().iter().map(|x| match x { + Variable::Number(n) => *n, + _ => Decimal::ZERO, + })); + } + offsets.push(items.len() as i32); + } + match items + .iter() + .all(|n| n.scale() == 0 && i64::try_from(n.mantissa()).is_ok()) + { + true => Data::ListI64( + offsets, + items + .iter() + .map(|n| i64::try_from(n.mantissa()).unwrap_or(0)) + .collect(), + ), + false => Data::ListDec(offsets, items), + } + } else if std::env::var("LANE_ANY_LISTS").is_err() + && all( + |v| matches!(v, Variable::Array(a) if a.borrow().iter().all(|x| matches!(x, Variable::String(_)))), + ) + { + let mut offsets = vec![0i32]; + let mut items = Vec::new(); + for v in &values { + if let Some(Variable::Array(a)) = v { + items.extend( + a.borrow() + .iter() + .map(|x| x.as_str().unwrap_or_default().to_string()), + ); + } + offsets.push(items.len() as i32); + } + Data::ListStr(offsets, items) + } else if std::env::var("LANE_ANY_LISTS").is_err() + && all( + |v| matches!(v, Variable::Array(a) if a.borrow().iter().all(|x| matches!(x, Variable::Object(_)))), + ) + { + let mut offsets = vec![0i32]; + let mut items: Vec = Vec::new(); + for v in &values { + if let Some(Variable::Array(a)) = v { + items.extend(a.borrow().iter().cloned()); + } + offsets.push(items.len() as i32); + } + let mut names: Vec = Vec::new(); + for item in &items { + if let Variable::Object(o) = item { + for (k, _) in o.borrow().iter() { + if !names.iter().any(|n| n.as_str() == k.as_ref() as &str) { + names.push(k.to_string()); + } + } + } + } + let fields = names + .into_iter() + .map(|name| { + let cells: Vec> = items + .iter() + .map(|item| match item { + Variable::Object(o) => o.borrow().get_str(&name).cloned(), + _ => None, + }) + .collect(); + let (field, valid) = Field::of(&cells); + (name, field, valid) + }) + .collect(); + Data::ListStruct(offsets, fields, items.len()) + } else { + Data::Any( + values + .iter() + .map(|v| v.cloned().unwrap_or(Variable::Null)) + .collect(), + ) + }; + data.push(column); + valid.push(bits); + } + Self { + rows, + keys, + data, + valid, + } + } + + fn fields(&self) -> Vec)>> { + self.data + .iter() + .map(|d| match d { + Data::ListStruct(_, fields, _) => fields + .iter() + .map(|(name, field, valid)| { + ( + name.as_str(), + Column::with_validity(field.values(), valid, 0), + ) + }) + .collect(), + _ => Vec::new(), + }) + .collect() + } + + fn children<'a>( + &'a self, + texts: &'a [(Vec, Vec)], + fields: &'a [Vec<(&'a str, Column<'a>)>], + ) -> Vec> { + self.data + .iter() + .enumerate() + .map(|(i, d)| match d { + Data::ListStruct(_, _, len) => Column::new(Values::Struct { + fields: &fields[i], + len: *len, + }), + Data::ListDec(_, items) => Column::new(Values::Dec(items)), + Data::ListI64(_, items) => Column::new(Values::I64(items)), + Data::ListStr(..) | Data::Dict(..) => Column::new(Values::Utf8 { + offsets: &texts[i].0, + data: &texts[i].1, + }), + _ => Column::new(Values::Any(&[])), + }) + .collect() + } + + fn columns<'a>( + &'a self, + texts: &'a [(Vec, Vec)], + children: &'a [Column<'a>], + ) -> Columns<'a> { + let mut columns = Columns::new(self.rows); + for (i, ((key, data), valid)) in self + .keys + .iter() + .zip(&self.data) + .zip(&self.valid) + .enumerate() + { + let values = match data { + Data::I64(v) => Values::I64(v), + Data::Dec(v) => Values::Dec(v), + Data::Bool(bits) => Values::Bool { bits, offset: 0 }, + Data::Str(_) => Values::Utf8 { + offsets: &texts[i].0, + data: &texts[i].1, + }, + Data::ListDec(offsets, _) + | Data::ListI64(offsets, _) + | Data::ListStr(offsets, _) + | Data::ListStruct(offsets, _, _) => Values::List { + offsets, + child: (&children[i]).into(), + }, + Data::Dict(keys, _) => Values::Dict { + keys, + values: (&children[i]).into(), + }, + Data::Any(v) => Values::Any(v), + }; + columns = columns.column(key, Column::with_validity(values, valid, 0)); + } + columns + } + + fn texts(&self) -> Vec<(Vec, Vec)> { + self.data + .iter() + .map(|d| match d { + Data::Str(v) | Data::ListStr(_, v) | Data::Dict(_, v) => { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for text in v { + data.extend_from_slice(text.as_bytes()); + offsets.push(data.len() as i32); + } + (offsets, data) + } + _ => (Vec::new(), Vec::new()), + }) + .collect() + } +} + +impl Bench { + fn cases() -> Vec { + let mut names: Vec<_> = std::fs::read_dir(GRAPHS) + .map(|d| d.flatten().map(|e| e.path()).collect()) + .unwrap_or_default(); + names.sort(); + let mut out = Vec::new(); + for path in names { + let Ok(raw) = std::fs::read_to_string(&path) else { + continue; + }; + let Ok(doc) = serde_json::from_str::(&raw) else { + continue; + }; + let inputs: Vec = doc["tests"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| t.get("input").cloned()) + .map(Variable::from) + .collect(); + if inputs.is_empty() { + continue; + } + for node in doc["nodes"].as_array().into_iter().flatten() { + if node["type"] != "expressionNode" { + continue; + } + for e in node["content"]["expressions"] + .as_array() + .into_iter() + .flatten() + { + let Some(source) = e["value"].as_str() else { + continue; + }; + let scopes: Vec = (0..ROWS) + .map(|i| Scope::new(inputs[i % inputs.len()].depth_clone(64))) + .collect(); + let ok = scopes.iter().take(inputs.len()).all(|s| { + let mut iso = Isolate::new(); + iso.set_environment(s.base().clone()); + matches!(iso.run_standard(source), Ok(v) if v != Variable::Null) + }); + if ok && !source.contains("date(") { + out.push(Case { + source: source.to_string(), + scopes, + }); + } + } + } + } + out + } + + fn timed(budget: Duration, mut f: impl FnMut()) -> f64 { + f(); + let start = Instant::now(); + let mut n = 0u64; + while start.elapsed() < budget { + f(); + n += 1; + } + start.elapsed().as_nanos() as f64 / n as f64 + } + + fn median(mut v: Vec) -> f64 { + v.sort_by(|a, b| a.total_cmp(b)); + v.get(v.len() / 2).copied().unwrap_or(0.0) + } + + fn geomean(v: &[f64]) -> f64 { + (v.iter().map(|x| x.ln()).sum::() / v.len() as f64).exp() + } +} + +fn micro() -> bool { + let Ok(list) = std::env::var("LANE_EXPR") else { + return false; + }; + let input = Variable::from(serde_json::json!({ + "a": 5, "b": 7, "s": "gold", "flag": true, "items": [1, 2, 3, 4, 5, 6, 7, 8], + "tags": ["x", "diabetes", "y"], "o": {"x": 1, "y": {"z": 2}}, "d1": "2025-03-15T10:30:00Z", "d2": "2025-03-15", "d3": "2025-03-15 10:30:00", + "objs": [{"x": 1, "k": "a"}, {"x": 5, "k": "b"}, {"x": 9, "k": "c"}, {"x": 2, "k": "a"}], + "email": "john.doe@example.com", "phone": "+1-555-0100" + })); + let rows: usize = std::env::var("LANE_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(ROWS); + let mut runner = LaneRunner::new(); + let budget = Duration::from_millis(300); + for entry in list.split('|') { + let (reference, source) = match entry.split_once(':') { + Some(("u", rest)) => (Some(Variable::Number(5.into())), rest), + Some(("us", rest)) => (Some(Variable::String("gold".into())), rest), + _ => (None, entry), + }; + let vary = std::env::var("LANE_VARY").is_ok(); + let scopes: Vec = (0..rows) + .map(|i| { + let base = match vary { + true => { + let mut value = input.depth_clone(64); + if let Variable::Object(o) = &mut value { + let mut o = o.borrow_mut(); + let day = |k: usize| { + format!("20{:02}-{:02}-{:02}", 10 + k % 15, 1 + k % 12, 1 + k % 28) + }; + o.insert( + "a".into(), + Variable::Number(Decimal::from(((i * 7919) % 97) as i64 - 40)), + ); + o.insert( + "b".into(), + Variable::Number(Decimal::from(((i * 104729) % 89) as i64 - 30)), + ); + o.insert( + "d1".into(), + Variable::String( + format!("{}T{:02}:30:00Z", day(i), i % 24).as_str().into(), + ), + ); + o.insert( + "d2".into(), + Variable::String(day(i * 31 + 7).as_str().into()), + ); + o.insert( + "s".into(), + Variable::String( + ["gold", "silver", "Bronze", "platinum"][i % 4].into(), + ), + ); + } + value + } + false => input.depth_clone(64), + }; + let mut scope = Scope::new(base); + if let Some(r) = &reference { + scope.set_local(Variable::dollar_key(), r.clone()); + } + scope + }) + .collect(); + let program = match reference { + Some(_) => LaneProgram::unary(source), + None => LaneProgram::standard(source), + } + .expect("lane compile") + .specialize(&scopes) + .expect("specialize"); + let mut vm = VM::new(); + let s = match reference { + Some(_) => { + let expression = Isolate::new().compile_unary(source).expect("compile"); + Bench::timed(budget, || { + for scope in &scopes { + black_box(expression.evaluate_with_scope(scope, &mut vm).is_ok()); + } + }) + } + None => { + let expression = Isolate::new().compile_standard(source).expect("compile"); + Bench::timed(budget, || { + for scope in &scopes { + black_box(expression.evaluate_with_scope(scope, &mut vm).is_ok()); + } + }) + } + } / rows as f64; + if std::env::var("LANE_DUMP").is_ok() { + for step in &program.program().steps { + println!(" {:?}", step); + } + } + let profile = std::env::var("LANE_PROFILE").is_ok(); + let one = Bench::timed( + if profile { + Duration::from_secs(4) + } else { + budget + }, + || { + for scope in &scopes { + black_box(runner.evaluate_one(&program, scope).is_ok()); + } + }, + ) / rows as f64; + if profile { + println!("{source} lane-w1 {one:.1}"); + continue; + } + let batch = Bench::timed(budget, || { + let mut n = 0usize; + runner.evaluate_with(&program, &scopes, |_, r| n += r.is_ok() as usize); + black_box(n); + }) / rows as f64; + let table = Table::build(&scopes); + let texts = table.texts(); + let fields = table.fields(); + let children = table.children(&texts, &fields); + let columns = table.columns(&texts, &children); + let columnar = match reference { + Some(_) => None, + None => LaneProgram::standard(source) + .ok() + .and_then(|p| p.specialize_columns(&columns).ok()), + }; + let mut out = zen_expression::lane::Output::new(); + if let (Ok(_), Some(p)) = (std::env::var("LANE_PROFILE_COLS"), &columnar) { + let ns = Bench::timed(Duration::from_secs(4), || { + runner.evaluate_columns_into(p, &columns, &mut out); + black_box(out.len()); + }) / rows as f64; + println!("{entry} cols {ns:.1}"); + continue; + } + let cols = match &columnar { + Some(p) => { + Bench::timed(budget, || { + runner.evaluate_columns_into(p, &columns, &mut out); + black_box(out.len()); + }) / rows as f64 + } + None => f64::NAN, + }; + if std::env::var("LANE_TABLE").is_ok() { + let generic = match reference { + Some(_) => LaneProgram::unary(source), + None => LaneProgram::standard(source), + } + .expect("lane compile"); + let cold1 = Bench::timed(budget, || { + for scope in &scopes { + black_box(runner.evaluate_one(&generic, scope).is_ok()); + } + }) / rows as f64; + let cold64 = Bench::timed(budget, || { + let mut n = 0usize; + runner.evaluate_with(&generic, &scopes, |_, r| n += r.is_ok() as usize); + black_box(n); + }) / rows as f64; + println!( + "TSV\t{entry}\t{s:.1}\t{cold1:.1}\t{cold64:.1}\t{one:.1}\t{batch:.1}\t{cols:.1}" + ); + continue; + } + println!( + "{:50} ops {:3} stack {s:7.1} lane-w1 {one:7.1} lane-w64 {batch:7.1} cols {cols:6.1} | w1 {:5.2}x w64 {:5.2}x cols {:5.1}x", + entry, + program.program().steps.len(), + s / one, + s / batch, + s / cols + ); + } + true +} + +fn cells() -> bool { + if std::env::var("LANE_CELLS").is_err() { + return false; + } + let mut state = 0x1234_5678_9ABC_DEF1u64; + let mut next = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + for rules in [100usize, 1000, 8000] { + let cells: Vec = (0..rules) + .map(|r| match (next(10), r + 1 == rules) { + (_, true) | (0..=2, _) => String::new(), + (3 | 4, _) => format!( + "'{}'", + ["US", "GB", "DE", "FR", "ES", "IT", "NL", "PL"][next(8) as usize] + ), + (5 | 6, _) => format!( + "{} {}", + ["<", "<=", ">", ">="][next(4) as usize], + next(20) * 5 + ), + (7, _) => format!("[{}..{}]", next(10) * 5, 50 + next(10) * 5), + (8, _) => format!( + "'{}', '{}'", + ["US", "GB"][next(2) as usize], + ["DE", "FR"][next(2) as usize] + ), + _ => "$ > limit".to_string(), + }) + .collect(); + let refs: Vec> = cells.iter().map(|c| Some(c.as_str())).collect(); + let set = zen_expression::lane::CellSet::compile(&refs).expect("cells"); + let values: Vec = (0..ROWS) + .map(|i| match i % 2 { + 0 => Variable::from(serde_json::json!( + ["US", "GB", "DE", "SE"][next(4) as usize] + )), + _ => Variable::from(serde_json::json!(next(100))), + }) + .collect(); + let envs: Vec = (0..ROWS) + .map(|_| Scope::new(serde_json::json!({"limit": next(50)}).into())) + .collect(); + let exprs: Vec>> = + cells + .iter() + .map(|c| (!c.is_empty()).then(|| Isolate::new().compile_unary(c).expect("unary"))) + .collect(); + let mut vm = VM::new(); + let stack = Bench::timed(Duration::from_millis(400), || { + let mut hits = 0usize; + for (value, env) in values.iter().zip(&envs).take(64) { + let mut scope = Scope::new(env.base().clone()); + scope.set_local(Variable::dollar_key(), value.clone()); + for e in &exprs { + hits += match e { + None => 1, + Some(e) => e.evaluate_with_scope(&scope, &mut vm).unwrap_or(false) as usize, + }; + } + } + black_box(hits); + }) / 64.0; + let mut runner = LaneRunner::new(); + let mut out = Vec::new(); + let lane = Bench::timed(Duration::from_millis(400), || { + set.evaluate(&mut runner, &values, &envs, &mut out); + black_box(out.len()); + }) / ROWS as f64; + println!("cells rules {rules:5}: evaluate every cell (stack VM) {stack:10.0} ns/row | cell set {lane:8.1} ns/row | {:6.1}x", stack / lane); + } + true +} + +fn nodes() -> bool { + if std::env::var("LANE_NODES").is_err() { + return false; + } + let mut names: Vec<_> = std::fs::read_dir(GRAPHS) + .map(|d| d.flatten().map(|e| e.path()).collect()) + .unwrap_or_default(); + names.sort(); + let (mut stack_all, mut one_all, mut batch_all) = (Vec::new(), Vec::new(), Vec::new()); + let mut runner = LaneRunner::new(); + for path in names { + let Ok(raw) = std::fs::read_to_string(&path) else { + continue; + }; + let Ok(doc) = serde_json::from_str::(&raw) else { + continue; + }; + let inputs: Vec = doc["tests"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| t.get("input").cloned()) + .map(Variable::from) + .collect(); + if inputs.is_empty() { + continue; + } + for node in doc["nodes"].as_array().into_iter().flatten() { + if node["type"] != "expressionNode" + || node["content"]["inputField"] + .as_str() + .is_some_and(|s| !s.is_empty()) + { + continue; + } + let entries: Vec<(String, String)> = node["content"]["expressions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| { + Some(( + e["key"].as_str()?.to_string(), + e["value"].as_str()?.to_string(), + )) + }) + .filter(|(k, v)| !k.is_empty() && !v.is_empty()) + .collect(); + if entries.is_empty() { + continue; + } + let refs: Vec<(&str, &str)> = entries + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + let Ok(program) = LaneProgram::compile_many(&refs, true) else { + continue; + }; + let scopes: Vec = (0..ROWS) + .map(|i| Scope::new(inputs[i % inputs.len()].depth_clone(64))) + .collect(); + let program = program.specialize(&scopes).expect("specialize"); + let codes: Vec<( + String, + zen_expression::Expression, + )> = entries + .iter() + .filter_map(|(k, v)| Some((k.clone(), Isolate::new().compile_standard(v).ok()?))) + .collect(); + if codes.len() != entries.len() { + continue; + } + let mut vm = VM::new(); + let budget = Duration::from_millis(80); + let stack = Bench::timed(budget, || { + for scope in &scopes { + let mut scope = scope.clone(); + let dollar = Variable::empty_object(); + scope.set_local(Variable::dollar_key(), dollar.clone()); + for (key, e) in &codes { + match e.evaluate_with_scope(&scope, &mut vm) { + Ok(v) => { + dollar.dot_insert(key, v); + } + Err(_) => break, + } + } + black_box(&dollar); + } + }) / ROWS as f64; + let one = Bench::timed(budget, || { + for scope in &scopes { + runner.evaluate_many(&program, std::slice::from_ref(scope), None, |_, r| { + black_box(r.is_some()); + }); + } + }) / ROWS as f64; + let batch = Bench::timed(budget, || { + runner.evaluate_many(&program, &scopes, None, |_, r| { + black_box(r.is_some()); + }); + }) / ROWS as f64; + stack_all.push(stack); + one_all.push(one); + batch_all.push(batch); + } + } + let r1: Vec = stack_all.iter().zip(&one_all).map(|(s, l)| s / l).collect(); + let r64: Vec = stack_all + .iter() + .zip(&batch_all) + .map(|(s, l)| s / l) + .collect(); + println!( + "expression nodes {} | median ns/row: stack {:.0}, lane w1 {:.0}, lane w64 {:.0} | stack/lane geomean: w1 {:.2}x, w64 {:.2}x | sums: stack {:.0}, w1 {:.0}, w64 {:.0}", + stack_all.len(), + Bench::median(stack_all.clone()), + Bench::median(one_all.clone()), + Bench::median(batch_all.clone()), + Bench::geomean(&r1), + Bench::geomean(&r64), + stack_all.iter().sum::(), + one_all.iter().sum::(), + batch_all.iter().sum::() + ); + true +} + +fn main() { + if scenarios() { + return; + } + if nodes() { + return; + } + if cells() { + return; + } + if micro() { + return; + } + let filter = std::env::args().nth(1).filter(|a| !a.starts_with('-')); + let budget = Duration::from_millis(60); + let cases = Bench::cases(); + let (mut stack, mut w1, mut w64, mut cols, mut outs) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut typing: Vec<[f64; 9]> = Vec::new(); + let mut runner = LaneRunner::new(); + for case in &cases { + if let Some(f) = &filter { + if !case.source.contains(f.as_str()) { + continue; + } + } + let expression = Isolate::new() + .compile_standard(&case.source) + .expect("compile"); + let generic = LaneProgram::standard(&case.source).expect("lane compile"); + let program = generic.specialize(&case.scopes).expect("specialize"); + let mut vm = VM::new(); + let only_columns = std::env::var("LANE_ONLY_COLUMNS").is_ok(); + let budget = if only_columns { + Duration::from_millis(1) + } else { + budget + }; + let s = Bench::timed(budget, || { + for scope in &case.scopes { + black_box(expression.evaluate_with_scope(scope, &mut vm).is_ok()); + } + }) / ROWS as f64; + let one = Bench::timed(budget, || { + for scope in &case.scopes { + black_box(runner.evaluate_one(&program, scope).is_ok()); + } + }) / ROWS as f64; + let batch = Bench::timed(budget, || { + let mut n = 0usize; + runner.evaluate_with(&program, &case.scopes, |_, r| n += r.is_ok() as usize); + black_box(n); + }) / ROWS as f64; + let table = Table::build(&case.scopes); + let texts = table.texts(); + let fields = table.fields(); + let children = table.children(&texts, &fields); + let columns = table.columns(&texts, &children); + let columnar = generic.specialize_columns(&columns).expect("specialize"); + let col = Bench::timed( + if only_columns { + Duration::from_millis(300) + } else { + budget + }, + || { + let mut n = 0usize; + runner.evaluate_columns(&columnar, &columns, |_, r| n += r.is_ok() as usize); + black_box(n); + }, + ) / ROWS as f64; + let mut out = zen_expression::lane::Output::new(); + let typed = Bench::timed( + if only_columns { + Duration::from_millis(300) + } else { + budget + }, + || { + runner.evaluate_columns_into(&columnar, &columns, &mut out); + black_box(out.len()); + }, + ) / ROWS as f64; + if std::env::var("LANE_DEBUG").is_ok() { + let p = columnar.program(); + let bound: Vec = p + .site_keys + .iter() + .map(|k| { + k.as_deref() + .map_or(zen_expression::lane::Binding::Row, |k| columns.bind(k)) + }) + .collect(); + println!( + "keys {:?} bound {:?} rows {} kinds {:?}", + p.site_keys, + bound, + p.needs_rows(&bound), + p.kinds + ); + for (k, c) in &columns.columns { + if k.contains("status") || k.contains("watch") { + println!(" column {k} {:?}", c.kind()); + } + } + } + if std::env::var("LANE_DUMP").is_ok() { + println!("input {:?}", case.scopes[0].base().to_value()); + for step in &program.program().steps { + println!(" {:?}", step); + } + } + if filter.is_some() { + println!("{:70} stack {s:8.1} lane-w1 {one:8.1} lane-w64 {batch:8.1} columns {col:8.1} typed {typed:8.1}", &case.source[..case.source.len().min(70)]); + } + stack.push(s); + w1.push(one); + w64.push(batch); + cols.push(col); + outs.push(typed); + if std::env::var("LANE_TYPING").is_ok() { + let first = VariableType::from(&case.scopes[0].base().to_value()); + let typed_program = + LaneProgram::compile_typed(&case.source, ExpressionKind::Standard, &first) + .expect("typed"); + let leg = |p: &LaneProgram, runner: &mut LaneRunner| { + let w1 = Bench::timed(budget, || { + for scope in &case.scopes { + black_box(runner.evaluate_one(p, scope).is_ok()); + } + }) / ROWS as f64; + let w64 = Bench::timed(budget, || { + let mut n = 0usize; + runner.evaluate_with(p, &case.scopes, |_, r| n += r.is_ok() as usize); + black_box(n); + }) / ROWS as f64; + (w1, w64) + }; + let (g1, g64) = leg(&generic, &mut runner); + let (t1, t64) = leg(&typed_program, &mut runner); + let gc = Bench::timed(budget, || { + runner.evaluate_columns_into(&generic, &columns, &mut out); + black_box(out.len()); + }) / ROWS as f64; + typing.push([s, one, batch, typed, g1, g64, gc, t1, t64]); + } + } + let r1: Vec = stack.iter().zip(&w1).map(|(s, l)| s / l).collect(); + let r64: Vec = stack.iter().zip(&w64).map(|(s, l)| s / l).collect(); + let rc: Vec = stack.iter().zip(&cols).map(|(s, l)| s / l).collect(); + let ro: Vec = stack.iter().zip(&outs).map(|(s, l)| s / l).collect(); + if !typing.is_empty() { + let labels = [ + "speculated w1", + "speculated w64", + "column-typed output", + "generic w1", + "generic w64", + "generic columns output", + "compile_typed w1", + "compile_typed w64", + ]; + for (i, label) in labels.iter().enumerate() { + let ratios: Vec = typing.iter().map(|t| t[0] / t[i + 1]).collect(); + let times: Vec = typing.iter().map(|t| t[i + 1]).collect(); + println!( + "typing | {label:24} geomean {:5.2}x median {:5.2}x | median {:6.1} ns/row", + Bench::geomean(&ratios), + Bench::median(ratios.clone()), + Bench::median(times) + ); + } + } + println!( + "typed output: median {:.1} ns/row, stack/typed geomean {:.2}x, median {:.2}x, sum {:.0}", + Bench::median(outs.clone()), + Bench::geomean(&ro), + Bench::median(ro.clone()), + outs.iter().sum::() + ); + println!( + "columns: median {:.1} ns/row, stack/columns geomean {:.2}x, median {:.2}x, sum {:.0}", + Bench::median(cols.clone()), + Bench::geomean(&rc), + Bench::median(rc.clone()), + cols.iter().sum::() + ); + println!( + "{} expressions | median ns/eval: stack {:.1}, lane w1 {:.1}, lane w64 {:.1} | stack/lane geomean: w1 {:.2}x, w64 {:.2}x | sums: stack {:.0}, w1 {:.0}, w64 {:.0}", + stack.len(), + Bench::median(stack.clone()), + Bench::median(w1.clone()), + Bench::median(w64.clone()), + Bench::geomean(&r1), + Bench::geomean(&r64), + stack.iter().sum::(), + w1.iter().sum::(), + w64.iter().sum::() + ); +} + +struct Scenario { + source: String, + origin: &'static str, + category: &'static str, + unary: bool, + scopes: Vec, +} + +impl Scenario { + const NAMES: [&'static str; 20] = [ + "anna", "ben", "carla", "dino", "eva", "filip", "greta", "hugo", "ines", "jan", "kira", + "lars", "mona", "nils", "olga", "petar", "quinn", "rosa", "stefan", "tea", + ]; + const TIERS: [&'static str; 4] = ["gold", "silver", "bronze", "platinum"]; + const COUNTRIES: [&'static str; 6] = ["US", "DE", "GB", "FR", "HR", "JP"]; + const TAGS: [&'static str; 6] = ["vip", "new", "risk", "promo", "b2b", "trial"]; + + fn next(state: &mut u64) -> u64 { + *state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + *state >> 33 + } + + fn row(i: usize) -> Variable { + let mut r = 0x9e37_79b9_u64.wrapping_mul(i as u64 + 1); + let mut n = |m: u64| Self::next(&mut r) % m; + let dec = |m: i64, s: u32| Variable::Number(Decimal::new(m, s)); + let name = format!("{}{}", Self::NAMES[n(20) as usize], n(37)); + let tags: Vec = (0..n(5)) + .map(|_| Variable::String(Self::TAGS[n(6) as usize].into())) + .collect(); + let nums: Vec = (0..n(7)) + .map(|_| dec(n(100000) as i64 - 20000, 2)) + .collect(); + let items: Vec = (0..n(6)) + .map(|k| { + let item = Variable::empty_object(); + item.dot_insert( + "sku", + Variable::String(format!("SKU-{k}{}", n(90)).as_str().into()), + ); + item.dot_insert("qty", dec(n(9) as i64 + 1, 0)); + item.dot_insert("price", dec(n(20000) as i64 + 99, 2)); + item + }) + .collect(); + let row = Variable::empty_object(); + row.dot_insert("amount", dec(n(1_000_000) as i64, 2)); + row.dot_insert("qty", dec(n(50) as i64 + 1, 0)); + row.dot_insert("price", dec(n(50_000) as i64 + 1, 2)); + row.dot_insert("rate", dec(n(2_000) as i64, 4)); + row.dot_insert("age", dec(n(73) as i64 + 18, 0)); + row.dot_insert("score", dec(n(551) as i64 + 300, 0)); + row.dot_insert("name", Variable::String(name.as_str().into())); + row.dot_insert( + "email", + Variable::String( + format!("{name}@{}.com", Self::TIERS[n(4) as usize]) + .as_str() + .into(), + ), + ); + row.dot_insert("tier", Variable::String(Self::TIERS[n(4) as usize].into())); + row.dot_insert( + "country", + Variable::String(Self::COUNTRIES[n(6) as usize].into()), + ); + row.dot_insert("active", Variable::Bool(n(2) == 1)); + row.dot_insert( + "created", + Variable::String( + format!("2024-{:02}-{:02}", n(12) + 1, n(28) + 1) + .as_str() + .into(), + ), + ); + row.dot_insert("tags", Variable::from_array(tags)); + row.dot_insert("nums", Variable::from_array(nums)); + row.dot_insert("items", Variable::from_array(items)); + let accounts: Vec = (0..n(8)) + .map(|_| { + let account = Variable::empty_object(); + account.dot_insert("balance", dec(n(500000) as i64, 2)); + account.dot_insert( + "kind", + Variable::String(["savings", "checking", "loan"][n(3) as usize].into()), + ); + account.dot_insert("active", Variable::Bool(n(4) != 0)); + account + }) + .collect(); + row.dot_insert("accounts", Variable::from_array(accounts)); + row.dot_insert("customer.age", dec(n(73) as i64 + 18, 0)); + row.dot_insert( + "customer.country", + Variable::String(Self::COUNTRIES[n(6) as usize].into()), + ); + row.dot_insert( + "customer.tier", + Variable::String(Self::TIERS[n(4) as usize].into()), + ); + row.dot_insert( + "customer.address.city", + Variable::String(Self::NAMES[n(20) as usize].into()), + ); + row.dot_insert( + "customer.address.zip", + Variable::String(format!("{:05}", n(99999)).as_str().into()), + ); + row + } + + fn synthetic() -> Vec<(&'static str, &'static str, bool)> { + vec![ + ("access", "amount", false), + ("access", "customer.address.city", false), + ("access", "customer.age", false), + ("access", "items[0].price ?? 0", false), + ("arithmetic", "amount * 1.2", false), + ("arithmetic", "qty * price", false), + ("arithmetic", "(amount - 100) / 3", false), + ("arithmetic", "round(amount * rate, 2)", false), + ("arithmetic", "amount % 7", false), + ("arithmetic", "abs(amount - 5000) + floor(rate * 10)", false), + ("arithmetic", "qty * price * (1 - rate) + 4.99", false), + ("logic", "age >= 18 and active", false), + ("logic", "score > 700 or tier == 'gold'", false), + ("logic", "amount > 100 and amount < 5000", false), + ("logic", "not active", false), + ("logic", "age > 30 ? 'adult' : 'young'", false), + ("logic", "missing ?? 'none'", false), + ( + "logic", + "score >= 750 ? 'A' : score >= 650 ? 'B' : score >= 550 ? 'C' : 'D'", + false, + ), + ("membership", "country in ['US', 'DE', 'GB']", false), + ("membership", "age in [18..65]", false), + ("membership", "tier not in ['bronze', 'silver']", false), + ("membership", "score in (500..700]", false), + ("string", "upper(name)", false), + ("string", "name + ' ' + tier", false), + ("string", "startsWith(email, 'a')", false), + ("string", "contains(name, 'an')", false), + ("string", "len(name)", false), + ("string", "lower(tier) == 'gold'", false), + ("string", "split(email, '@')[1]", false), + ("string", "matches(email, '^[a-z]+[0-9]*@')", false), + ("template", "`${name} (${tier})`", false), + ("template", "`${amount} USD`", false), + ("date", "d(created).year()", false), + ("date", "d(created).add(30, 'd').format('%Y-%m-%d')", false), + ("date", "d(created).isBefore(d('2024-06-01'))", false), + ("date", "d(created).diff(d('2024-01-01'), 'day')", false), + ("date", "d(created).startOf('month')", false), + ("date", "d().diff(d(created), 'day') > 90", false), + ("closure", "sum(nums)", false), + ("closure", "map(items, #.qty * #.price)", false), + ("closure", "sum(map(items, #.qty * #.price))", false), + ("closure", "filter(tags, # != 'trial')", false), + ("closure", "some(tags, # == 'vip')", false), + ("closure", "count(items, #.qty > 2)", false), + ("closure", "len(tags)", false), + ("closure", "'vip' in tags", false), + ( + "struct", + "sum(map(filter(accounts, #.active), #.balance))", + false, + ), + ("struct", "sum(map(accounts, #.balance))", false), + ("struct", "count(accounts, #.kind == 'loan')", false), + ("struct", "some(accounts, #.balance > 4000)", false), + ("struct", "all(accounts, #.active)", false), + ( + "struct", + "map(accounts, #.kind == 'loan' ? 'L' : 'O')", + false, + ), + ("struct", "sum(map(accounts, #.balance * rate))", false), + ("struct", "map(accounts, #.balance * 2)", false), + ( + "struct", + "len(filter(accounts, #.balance > 1000 and #.active))", + false, + ), + ("struct", "sum(map(items, #.qty * #.price))", false), + ("object", "{total: amount, net: amount * 0.8}", false), + ("object", "[amount, qty, price]", false), + ("object", "{name: name, tags: tags, n: len(tags)}", false), + ("conversion", "string(amount)", false), + ("conversion", "number(string(qty))", false), + ("unary", "> 100", true), + ("unary", "[10..5000]", true), + ("unary", "'US', 'DE', 'GB'", true), + ("unary", "startsWith($, 'a')", true), + ] + } + + fn unary_reference(row: &Variable, source: &str) -> Variable { + let key = match source { + s if s.contains("'US'") => "country", + s if s.contains("startsWith") => "name", + _ => "amount", + }; + row.dot(key).unwrap_or(Variable::Null) + } + + fn category(source: &str) -> &'static str { + let s = source; + if s.contains("d(") || s.contains("date(") || s.contains("time(") { + return "date"; + } + if s.contains('#') + || [ + "map(", "filter(", "some(", "all(", "none(", "count(", "sum(", "one(", + ] + .iter() + .any(|f| s.contains(f)) + { + return "closure"; + } + if s.contains('`') { + return "template"; + } + if s.trim_start().starts_with('{') || s.trim_start().starts_with('[') { + return "object"; + } + if [ + "upper(", + "lower(", + "startsWith(", + "endsWith(", + "contains(", + "len(", + "trim(", + "split(", + "matches(", + "extract(", + ] + .iter() + .any(|f| s.contains(f)) + || s.contains("' +") + || s.contains("+ '") + { + return "string"; + } + if s.contains(" in ") { + return "membership"; + } + if ["string(", "number(", "bool("] + .iter() + .any(|f| s.contains(f)) + { + return "conversion"; + } + if [" and ", " or ", "==", "!=", ">", "<", "?", "not "] + .iter() + .any(|f| s.contains(f)) + { + return "logic"; + } + if s.chars().any(|c| "+-*/%^".contains(c)) + || ["round(", "floor(", "ceil(", "abs(", "max(", "min("] + .iter() + .any(|f| s.contains(f)) + { + return "arithmetic"; + } + "access" + } + + fn all() -> Vec { + let mut out: Vec = Bench::cases() + .into_iter() + .map(|c| Scenario { + category: Self::category(&c.source), + source: c.source, + origin: "corpus", + unary: false, + scopes: c.scopes, + }) + .collect(); + let rows: Vec = (0..ROWS).map(Self::row).collect(); + for (category, source, unary) in Self::synthetic() { + let scopes = rows + .iter() + .map(|row| { + let mut scope = Scope::new(row.depth_clone(64)); + if unary { + scope.set_local(Variable::dollar_key(), Self::unary_reference(row, source)); + } + scope + }) + .collect(); + out.push(Scenario { + source: source.to_string(), + origin: "synthetic", + category, + unary, + scopes, + }); + } + out + } +} + +fn scenarios() -> bool { + let Ok(target) = std::env::var("LANE_SCENARIOS") else { + return false; + }; + let only = std::env::var("LANE_SCENARIO").ok(); + let category = std::env::var("LANE_CATEGORY").ok(); + let matching = std::env::var("LANE_MATCH").ok(); + let seconds: f64 = std::env::var("LANE_SECONDS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(4.0); + let budget = Duration::from_millis( + std::env::var("LANE_BUDGET_MS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(60), + ); + let cases: Vec = Scenario::all() + .into_iter() + .filter(|c| category.as_ref().is_none_or(|k| c.category == k)) + .filter(|c| { + matching + .as_ref() + .is_none_or(|m| c.source.contains(m.as_str())) + }) + .collect(); + let mut runner = LaneRunner::new(); + struct Prepared<'a> { + case: &'a Scenario, + stack: Option>, + unary: Option>, + generic: LaneProgram, + program: LaneProgram, + } + let prepared: Vec = cases + .iter() + .filter_map(|case| { + let mut isolate = Isolate::new(); + let (stack, unary, generic) = match case.unary { + true => ( + None, + Some(isolate.compile_unary(&case.source).ok()?), + LaneProgram::unary(&case.source).ok()?, + ), + false => ( + Some(isolate.compile_standard(&case.source).ok()?), + None, + LaneProgram::standard(&case.source).ok()?, + ), + }; + let program = generic.specialize(&case.scopes).ok()?; + Some(Prepared { + case, + stack, + unary, + generic, + program, + }) + }) + .collect(); + let stack_rows = |p: &Prepared, vm: &mut VM| { + for scope in &p.case.scopes { + match (&p.stack, &p.unary) { + (Some(e), _) => black_box(e.evaluate_with_scope(scope, vm).is_ok()), + (_, Some(e)) => black_box(e.evaluate_with_scope(scope, vm).is_ok()), + _ => false, + }; + } + }; + let isolate_rows = |p: &Prepared| { + let mut isolate = Isolate::new(); + for scope in &p.case.scopes { + isolate.set_environment(scope.base().clone()); + if let Some(reference) = scope.get(&Variable::dollar_key()) { + isolate.set_local(Variable::dollar_key(), reference.clone()); + } + match p.case.unary { + true => black_box(isolate.run_unary(&p.case.source).is_ok()), + false => black_box(isolate.run_standard(&p.case.source).is_ok()), + }; + } + }; + if let Some(only) = only { + let mut vm = VM::new(); + let tables: Vec> = prepared + .iter() + .map(|p| (!p.case.unary).then(|| Table::build(&p.case.scopes))) + .collect(); + let texts: Vec, Vec)>> = tables + .iter() + .map(|t| t.as_ref().map(Table::texts).unwrap_or_default()) + .collect(); + let fields: Vec>> = tables + .iter() + .map(|t| t.as_ref().map(Table::fields).unwrap_or_default()) + .collect(); + let children: Vec> = tables + .iter() + .zip(texts.iter().zip(&fields)) + .map(|(t, (x, f))| t.as_ref().map(|t| t.children(x, f)).unwrap_or_default()) + .collect(); + let columns: Vec> = tables + .iter() + .zip(texts.iter().zip(&children)) + .map(|(t, (x, c))| t.as_ref().map(|t| t.columns(x, c))) + .collect(); + let columnar: Vec> = prepared + .iter() + .zip(&columns) + .map(|(p, c)| { + c.as_ref() + .and_then(|c| p.generic.specialize_columns(c).ok()) + }) + .collect(); + let mut out = zen_expression::lane::Output::new(); + let start = Instant::now(); + while start.elapsed().as_secs_f64() < seconds { + for (i, p) in prepared.iter().enumerate() { + match only.as_str() { + "stack" => stack_rows(p, &mut vm), + "isolate" => isolate_rows(p), + "lane_single" => { + for scope in &p.case.scopes { + black_box(runner.evaluate_one(&p.program, scope).is_ok()); + } + } + "lane_batch" => { + let mut n = 0usize; + runner.evaluate_with(&p.program, &p.case.scopes, |_, r| { + n += r.is_ok() as usize + }); + black_box(n); + } + "lane_columns" => { + if let (Some(program), Some(columns)) = (&columnar[i], &columns[i]) { + let mut n = 0usize; + runner + .evaluate_columns(program, columns, |_, r| n += r.is_ok() as usize); + black_box(n); + } + } + "lane_typed" => { + if let (Some(program), Some(columns)) = (&columnar[i], &columns[i]) { + runner.evaluate_columns_into(program, columns, &mut out); + black_box(out.len()); + } + } + _ => return true, + } + } + } + return true; + } + let mut lines = Vec::new(); + let mut vm = VM::new(); + let per = |ns: f64| ns / ROWS as f64; + let compile = |f: &mut dyn FnMut()| { + let start = Instant::now(); + let mut n = 0u32; + while start.elapsed() < Duration::from_millis(15) { + f(); + n += 1; + } + start.elapsed().as_nanos() as f64 / n as f64 + }; + for p in &prepared { + let case = p.case; + let stack = per(Bench::timed(budget, || stack_rows(p, &mut vm))); + let isolate = per(Bench::timed(budget, || isolate_rows(p))); + let single = per(Bench::timed(budget, || { + for scope in &case.scopes { + black_box(runner.evaluate_one(&p.program, scope).is_ok()); + } + })); + let single_generic = per(Bench::timed(budget, || { + for scope in &case.scopes { + black_box(runner.evaluate_one(&p.generic, scope).is_ok()); + } + })); + let batch = per(Bench::timed(budget, || { + let mut n = 0usize; + runner.evaluate_with(&p.program, &case.scopes, |_, r| n += r.is_ok() as usize); + black_box(n); + })); + let (mut columns_ns, mut typed_ns, mut specialize_columns_ns) = (None, None, None); + if !case.unary { + let table = Table::build(&case.scopes); + let texts = table.texts(); + let fields = table.fields(); + let children = table.children(&texts, &fields); + let columns = table.columns(&texts, &children); + if let Ok(columnar) = p.generic.specialize_columns(&columns) { + columns_ns = Some(per(Bench::timed(budget, || { + let mut n = 0usize; + runner.evaluate_columns(&columnar, &columns, |_, r| n += r.is_ok() as usize); + black_box(n); + }))); + let mut out = zen_expression::lane::Output::new(); + typed_ns = Some(per(Bench::timed(budget, || { + runner.evaluate_columns_into(&columnar, &columns, &mut out); + black_box(out.len()); + }))); + specialize_columns_ns = Some(compile(&mut || { + black_box(p.generic.specialize_columns(&columns).is_ok()); + })); + } + } + let stack_compile = compile(&mut || { + let mut isolate = Isolate::new(); + match case.unary { + true => black_box(isolate.compile_unary(&case.source).is_ok()), + false => black_box(isolate.compile_standard(&case.source).is_ok()), + }; + }); + let lane_compile = compile(&mut || { + match case.unary { + true => black_box(LaneProgram::unary(&case.source).is_ok()), + false => black_box(LaneProgram::standard(&case.source).is_ok()), + }; + }); + let specialize = compile(&mut || { + black_box(p.generic.specialize(&case.scopes[..64]).is_ok()); + }); + let errors = case + .scopes + .iter() + .filter(|scope| match (&p.stack, &p.unary) { + (Some(e), _) => e.evaluate_with_scope(scope, &mut vm).is_err(), + (_, Some(e)) => e.evaluate_with_scope(scope, &mut vm).is_err(), + _ => false, + }) + .count(); + let opt = |v: Option| v.map_or(Value::Null, |v| serde_json::json!(v)); + lines.push(serde_json::json!({ + "source": case.source, + "origin": case.origin, + "category": case.category, + "unary": case.unary, + "error_rows": errors, + "ns": { + "stack": stack, + "isolate": isolate, + "lane_single": single, + "lane_single_generic": single_generic, + "lane_batch": batch, + "lane_columns": opt(columns_ns), + "lane_typed": opt(typed_ns), + }, + "compile_ns": { + "stack": stack_compile, + "lane": lane_compile, + "specialize_rows": specialize, + "specialize_columns": opt(specialize_columns_ns), + }, + })); + eprintln!("{:10} {:9} stack {stack:7.1} single {single:7.1} batch {batch:7.1} columns {:7.1} | {}", case.category, case.origin, columns_ns.unwrap_or(0.0), &case.source[..case.source.len().min(60)]); + } + let _ = std::fs::write(&target, serde_json::to_string(&lines).unwrap_or_default()); + true +} diff --git a/core/expression/src/config.rs b/core/expression/src/config.rs new file mode 100644 index 00000000..21810aff --- /dev/null +++ b/core/expression/src/config.rs @@ -0,0 +1,22 @@ +use std::sync::atomic::AtomicBool; + +#[derive(Debug)] +pub struct ZenExpressionConfig { + pub lane: AtomicBool, +} + +impl ZenExpressionConfig { + const fn new() -> Self { + Self { + lane: AtomicBool::new(false), + } + } +} + +impl Default for ZenExpressionConfig { + fn default() -> Self { + Self::new() + } +} + +pub static ZEN_EXPRESSION_CONFIG: ZenExpressionConfig = ZenExpressionConfig::new(); diff --git a/core/expression/src/functions/internal.rs b/core/expression/src/functions/internal.rs index c9a02723..d5c72444 100644 --- a/core/expression/src/functions/internal.rs +++ b/core/expression/src/functions/internal.rs @@ -691,7 +691,10 @@ pub(crate) mod imp { let center_num = a.get(center).context("Index out of bounds")?; Ok(V::Number(*center_num)) } else { - let center_left = a.get(center - 1).context("Index out of bounds")?; + let center_left = center + .checked_sub(1) + .and_then(|i| a.get(i)) + .context("Index out of bounds")?; let center_right = a.get(center).context("Index out of bounds")?; let median = center_left diff --git a/core/expression/src/isolate.rs b/core/expression/src/isolate.rs index c7c59b6e..5f7b239c 100644 --- a/core/expression/src/isolate.rs +++ b/core/expression/src/isolate.rs @@ -1,6 +1,7 @@ use ahash::HashMap; use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; +use std::sync::atomic::Ordering; use std::sync::Arc; use thiserror::Error; @@ -11,7 +12,7 @@ use crate::parser::{Parser, ParserError}; use crate::scope::Scope; use crate::variable::Variable; use crate::vm::{VMError, VM}; -use crate::{Expression, ExpressionKind}; +use crate::{Expression, ExpressionKind, ZEN_EXPRESSION_CONFIG}; use bumpalo::Bump; use zen_types::symbol::Symbol; @@ -31,6 +32,7 @@ pub struct Isolate { scope: Scope, references: HashMap, cache: Option>, + lane: crate::lane::Backend, } impl Isolate { @@ -45,6 +47,7 @@ impl Isolate { scope: Scope::default(), references: Default::default(), cache: None, + lane: Default::default(), } } @@ -142,6 +145,10 @@ impl Isolate { } pub fn run_standard(&mut self, source: &str) -> Result { + if ZEN_EXPRESSION_CONFIG.lane.load(Ordering::Relaxed) { + return self.lane.run(source, ExpressionKind::Standard, &self.scope); + } + let cached = self .cache .as_ref() @@ -171,6 +178,14 @@ impl Isolate { } pub fn run_unary(&mut self, source: &str) -> Result { + if ZEN_EXPRESSION_CONFIG.lane.load(Ordering::Relaxed) { + return self + .lane + .run(source, ExpressionKind::Unary, &self.scope)? + .as_bool() + .ok_or(IsolateError::ValueCastError); + } + let cached = self .cache .as_ref() diff --git a/core/expression/src/lane/bits.rs b/core/expression/src/lane/bits.rs new file mode 100644 index 00000000..2260f43d --- /dev/null +++ b/core/expression/src/lane/bits.rs @@ -0,0 +1,191 @@ +pub struct Bits; + +impl Bits { + #[inline] + pub fn word(bits: &[u64], at: usize, width: usize) -> u64 { + let all = match width >= 64 { + true => u64::MAX, + false => (1u64 << width) - 1, + }; + if at == usize::MAX { + return all; + } + let (word, shift) = (at / 64, at % 64); + let low = bits.get(word).copied().unwrap_or(0) >> shift; + let high = match shift { + 0 => 0, + _ => bits.get(word + 1).copied().unwrap_or(0) << (64 - shift), + }; + (low | high) & all + } + + #[inline] + pub fn on(bits: &mut [u64], row: usize) { + if let Some(word) = bits.get_mut(row >> 6) { + *word |= 1 << (row & 63); + } + } + + #[inline(always)] + pub fn each(word: u64, base: usize, mut f: impl FnMut(usize)) { + let mut word = word; + while word != 0 { + f(base + word.trailing_zeros() as usize); + word &= word - 1; + } + } + + pub fn range(bits: &[u64], lo: usize, hi: usize, ones: bool) -> bool { + let mut i = lo; + while i < hi { + let (w, s) = (i / 64, i % 64); + let e = (s + (hi - i)).min(64); + let mask = if e - s == 64 { + u64::MAX + } else { + ((1u64 << (e - s)) - 1) << s + }; + let v = bits.get(w).copied().unwrap_or(0) & mask; + if (ones && v != mask) || (!ones && v != 0) { + return false; + } + i += e - s; + } + true + } + + #[inline] + pub fn get(bits: &[u64], row: usize) -> bool { + bits.get(row >> 6).is_some_and(|w| w >> (row & 63) & 1 == 1) + } + + #[inline] + pub fn set(bits: &mut [u64], row: usize, on: bool) { + if let Some(word) = bits.get_mut(row >> 6) { + *word = (*word & !(1 << (row & 63))) | (u64::from(on) << (row & 63)); + } + } + + pub fn ones(rows: usize) -> Vec { + let mut bits = vec![u64::MAX; rows.div_ceil(64)]; + Self::trim(&mut bits, rows); + bits + } + + pub fn trim(bits: &mut [u64], rows: usize) { + if let (Some(last), tail @ 1..) = (bits.last_mut(), rows & 63) { + *last &= (1u64 << tail) - 1; + } + } + + pub fn of(rows: usize, mut f: impl FnMut(usize) -> bool) -> Vec { + let mut bits = vec![0u64; rows.div_ceil(64)]; + for (w, word) in bits.iter_mut().enumerate() { + let base = w << 6; + let mut value = 0u64; + for bit in 0..(rows - base).min(64) { + value |= u64::from(f(base + bit)) << bit; + } + *word = value; + } + bits + } + + pub fn window(bits: &[u64], offset: usize, rows: usize) -> Vec { + match offset { + 0 if bits.len() >= rows.div_ceil(64) => { + let mut out = bits[..rows.div_ceil(64)].to_vec(); + Self::trim(&mut out, rows); + out + } + _ => (0..rows.div_ceil(64)) + .map(|w| Self::word(bits, offset + (w << 6), (rows - (w << 6)).min(64))) + .collect(), + } + } + + pub fn partial(validity: Option<(&[u64], usize)>, rows: usize) -> Option<(&[u64], usize)> { + validity.filter(|(bits, offset)| !Self::full(bits, *offset, rows)) + } + + pub fn validity(validity: Option<(&[u64], usize)>, rows: usize) -> Option> { + Self::partial(validity, rows).map(|(bits, offset)| Self::window(bits, offset, rows)) + } + + pub fn present(validity: Option<(&[u64], usize)>, rows: usize) -> Vec { + match validity { + Some((bits, offset)) => Self::window(bits, offset, rows), + None => Self::ones(rows), + } + } + + pub fn gather(bits: &[u64], positions: &[usize]) -> Vec { + Self::of(positions.len(), |i| Self::get(bits, positions[i])) + } + + pub fn fill(bits: &mut [u64], start: usize, len: usize) { + let end = start + len; + let mut at = start; + while at < end { + let (word, bit) = (at >> 6, at & 63); + let take = (64 - bit).min(end - at); + let mask = match take { + 64 => u64::MAX, + t => ((1u64 << t) - 1) << bit, + }; + if let Some(w) = bits.get_mut(word) { + *w |= mask; + } + at += take; + } + } + + pub fn splice(bits: &mut [u64], start: usize, source: &[u64], len: usize) { + let mut at = 0; + while at < len { + let take = (len - at).min(64); + let word = Self::word(source, at, take); + let (dst, bit) = ((start + at) >> 6, (start + at) & 63); + if let Some(w) = bits.get_mut(dst) { + *w |= word << bit; + } + if bit > 0 { + if let Some(w) = bits.get_mut(dst + 1) { + *w |= word >> (64 - bit); + } + } + at += take; + } + } + + pub fn full(bits: &[u64], offset: usize, len: usize) -> bool { + Self::range(bits, offset, offset + len, true) + } + + pub fn rows(bits: &[u64]) -> impl Iterator + '_ { + bits.iter().enumerate().flat_map(|(w, &word)| { + let mut word = word; + std::iter::from_fn(move || { + (word != 0).then(|| { + let at = word.trailing_zeros() as usize; + word &= word - 1; + w * 64 + at + }) + }) + }) + } + + #[inline] + pub fn or(into: &mut [u64], from: &[u64]) { + into.iter_mut().zip(from).for_each(|(a, b)| *a |= b); + } + + #[inline] + pub fn and(into: &mut [u64], from: &[u64]) { + into.iter_mut().zip(from).for_each(|(a, b)| *a &= b); + } + + pub fn none(bits: &[u64]) -> bool { + bits.iter().all(|w| *w == 0) + } +} diff --git a/core/expression/src/lane/builtins/arrays.rs b/core/expression/src/lane/builtins/arrays.rs new file mode 100644 index 00000000..d0acb64f --- /dev/null +++ b/core/expression/src/lane/builtins/arrays.rs @@ -0,0 +1,167 @@ +use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Outcome, Params}; +use crate::variable::{Variable, VariableMap}; + +pub(crate) struct Arrays; + +impl Arrays { + const ARRAY: &'static [(&'static str, bool)] = &[("array", false)]; + + pub(crate) const FLATTEN: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Array| { + Ok(a.with(|values| { + let mut flat = Vec::with_capacity(values.len()); + for v in values { + match v { + Variable::Array(inner) => flat.extend(inner.borrow().iter().cloned()), + v => flat.push(v.clone()), + } + } + Variable::from_array(flat) + })) + }) + }], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + pub(crate) const MERGE: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Array| a.with(Self::merge))], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + fn merge(values: &[Variable]) -> Result { + let Some(first) = values.iter().find(|item| !matches!(item, Variable::Null)) else { + return Ok(Variable::empty_object()); + }; + let capacity = values + .iter() + .map(|item| match item { + Variable::Object(o) => o.borrow().len(), + Variable::Array(a) => a.borrow().len(), + _ => 0, + }) + .sum(); + match first { + Variable::Array(_) => { + let mut merged = Vec::with_capacity(capacity); + for item in values { + match item { + Variable::Array(inner) => merged.extend(inner.borrow().iter().cloned()), + Variable::Null => {} + _ => return Err("Expected array of arrays".to_string()), + } + } + Ok(Variable::from_array(merged)) + } + Variable::Object(_) => { + let mut merged = VariableMap::with_capacity(capacity); + for item in values { + match item { + Variable::Object(o) => { + for (key, value) in o.borrow().iter() { + merged.insert(key.clone(), value.clone()); + } + } + Variable::Null => {} + _ => return Err("Expected array of objects".to_string()), + } + } + Ok(Variable::from_object(merged)) + } + other => Err(format!( + "merge expects an array of arrays or objects, got {}", + other.type_name() + )), + } + } + + pub(crate) const MERGE_DEEP: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Array| { + a.with(|values| { + let mut result = Variable::empty_object(); + for item in values { + match item { + Variable::Object(_) => result = Self::deep(&result, item), + Variable::Null => {} + _ => return Err("Expected array of objects".to_string()), + } + } + Ok(result) + }) + }) + }], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn deep(base: &Variable, patch: &Variable) -> Variable { + match (base, patch) { + (Variable::Object(a), Variable::Object(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + let mut merged = VariableMap::with_capacity(a.len() + b.len()); + for (key, value) in a.iter() { + merged.insert(key.clone(), value.clone()); + } + for (key, value) in b.iter() { + let entry = merged + .get(key) + .map(|existing| Self::deep(existing, value)) + .unwrap_or_else(|| value.clone()); + merged.insert(key.clone(), entry); + } + Variable::from_object(merged) + } + (Variable::Array(a), Variable::Array(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + let mut merged = Vec::with_capacity(a.len() + b.len()); + merged.extend(a.iter().cloned()); + merged.extend(b.iter().cloned()); + Variable::from_array(merged) + } + (_, patch) => patch.clone(), + } + } + + pub(crate) const KEYS: Builtin = Builtin { + overloads: &[Self::keys], + fail: |_| "Argument on 0 position out of bounds".to_string(), + }; + + fn keys(args: &[Arg]) -> Outcome { + Apply::one(args, |a: Arg| match a { + Arg::Var(Variable::Array(_)) | Arg::List(_) => { + let len = match a { + Arg::List(l) => l.end - l.start, + Arg::Var(Variable::Array(v)) => v.borrow().len(), + _ => 0, + }; + Ok(Variable::from_array( + (0..len).map(|i| Variable::Number(i.into())).collect(), + )) + } + Arg::Var(Variable::Object(o)) => Ok(Variable::from_array( + o.borrow() + .iter() + .map(|(key, _)| Variable::String(key.as_str().into())) + .collect(), + )), + other => Err(format!( + "Cannot determine keys of type {}", + other.type_name() + )), + }) + } + + pub(crate) const VALUES: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: &Variable| match a { + Variable::Object(o) => { + Ok(Variable::from_array(o.borrow().values().cloned().collect())) + } + _ => Err("Argument on 0 is not a object".to_string()), + }) + }], + fail: |args| Params::fail(args, &[("object", false)]), + }; +} diff --git a/core/expression/src/lane/builtins/convert.rs b/core/expression/src/lane/builtins/convert.rs new file mode 100644 index 00000000..1153125a --- /dev/null +++ b/core/expression/src/lane/builtins/convert.rs @@ -0,0 +1,113 @@ +use crate::lane::builtins::{Apply, Arg, Builtin, Params}; +use crate::lane::date::Date; +use crate::variable::Variable; +use chrono_tz::Tz; +use rust_decimal::Decimal; +use std::str::FromStr; + +pub(crate) struct Convert; + +impl Convert { + fn parse(s: &str) -> Option { + let s = s.trim(); + Decimal::from_str_exact(s) + .or_else(|_| Decimal::from_scientific(s)) + .ok() + } + + fn truthy(s: &str) -> bool { + match s.trim() { + "true" => true, + "false" => false, + _ => s.is_empty(), + } + } + + pub(crate) const TYPE: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Arg| Ok(a.type_name()))], + fail: |_| "Argument on 0 position out of bounds".to_string(), + }; + + pub(crate) const BOOL: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| { + Ok(match a { + Arg::Null => false, + Arg::Bool(b) => b, + Arg::Num(n) => !n.is_zero(), + Arg::Str(s) => Self::truthy(s), + Arg::Var(v) if Date::sourced(v) => { + Self::truthy(Date::source(v).unwrap_or_default()) + } + Arg::Date(_) | Arg::Var(_) | Arg::List(_) => true, + }) + }) + }], + fail: |_| "Argument on 0 position out of bounds".to_string(), + }; + + pub(crate) const STRING: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| match a { + Arg::Null => Ok("null".to_string()), + Arg::Bool(b) => Ok(b.to_string()), + Arg::Num(n) => Ok(n.to_string()), + Arg::Str(s) => Ok(s.to_string()), + Arg::Date(d) => Ok(d.to_string()), + Arg::Var(v @ Variable::Dynamic(d)) if Date::of(v).is_some() => Ok(d.to_string()), + other => Err(format!( + "Cannot convert type {} to string", + other.type_name() + )), + }) + }], + fail: |_| "Argument on 0 position out of bounds".to_string(), + }; + + pub(crate) const NUMBER: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| match a { + Arg::Num(n) => Ok(n), + Arg::Str(s) => Self::parse(s).ok_or_else(|| "Invalid number".to_string()), + Arg::Bool(true) => Ok(Decimal::ONE), + Arg::Bool(false) => Ok(Decimal::ZERO), + other => Err(format!( + "Cannot convert type {} to number", + other.type_name() + )), + }) + }], + fail: |_| "Argument on 0 position out of bounds".to_string(), + }; + + pub(crate) const IS_NUMERIC: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| { + Ok(match a { + Arg::Num(_) => true, + Arg::Str(s) => Self::parse(s).is_some(), + _ => false, + }) + }) + }], + fail: |_| "Argument on 0 position out of bounds".to_string(), + }; + + pub(crate) const DATE: Builtin = Builtin { + overloads: &[|args| { + Apply::two(args, |value: Option, zone: Option<&str>| { + let zone = match zone { + Some(z) => Some(Tz::from_str(z).map_err(|_| "Invalid timezone".to_string())?), + None => None, + }; + Ok(match value { + Some(Arg::Date(d)) => zone.map_or(d, |zone| d.tz(zone)), + Some(Arg::Str(s)) => Date::text(s, zone), + Some(v) => Date::new(v.variable(), zone), + None => Date::now(), + }) + }) + }], + fail: |args| Params::fail(args, &[("value", true), ("string", true)]), + }; +} diff --git a/core/expression/src/lane/builtins/dates.rs b/core/expression/src/lane/builtins/dates.rs new file mode 100644 index 00000000..5643c42a --- /dev/null +++ b/core/expression/src/lane/builtins/dates.rs @@ -0,0 +1,408 @@ +use crate::functions::{DateMethod, MethodKind}; +use crate::lane::builtins::{Arg, Builtin, Fail, Out, Outcome}; +use crate::lane::date::Date; +use crate::lane::date::{Duration, DurationUnit}; +use crate::variable::Variable; +use chrono::{Datelike, Timelike}; +use chrono_tz::Tz; +use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; +use rust_decimal::Decimal; +use std::borrow::Cow; +use std::str::FromStr; + +pub(crate) struct Dates; + +pub(crate) enum Shift { + Add(Duration), + Sub(Duration), + Start(DurationUnit), + End(DurationUnit), +} + +impl Shift { + #[inline] + pub(crate) fn apply(&self, date: &Date) -> Date { + match self { + Shift::Add(d) => date.add(d.clone()), + Shift::Sub(d) => date.sub(d.clone()), + Shift::Start(unit) => date.start_of(*unit), + Shift::End(unit) => date.end_of(*unit), + } + } +} + +#[derive(Clone, Copy)] +enum Compare { + Same, + Before, + After, + SameOrBefore, + SameOrAfter, +} + +#[derive(Clone, Copy)] +enum Part { + Second, + Minute, + Hour, + Day, + Weekday, + DayOfYear, + Week, + Month, + Quarter, + Year, + Timestamp, + OffsetName, + IsValid, + IsYesterday, + IsToday, + IsTomorrow, + IsLeapYear, +} + +impl Dates { + const NEVER: fn(&[Arg]) -> Fail = + |_| "Argument on 0 position is not a valid dynamic".to_string(); + + fn this(args: &[Arg]) -> Result { + args.first() + .and_then(Arg::date) + .ok_or_else(|| "Argument on 0 position is not a valid dynamic".to_string()) + } + + fn var<'a>(args: &[Arg<'a>], pos: usize) -> Result, Fail> { + args.get(pos) + .copied() + .ok_or_else(|| format!("Argument on {pos} position out of bounds")) + } + + fn ostr<'a>(args: &[Arg<'a>], pos: usize) -> Result>, Fail> { + match args.get(pos) { + None => Ok(None), + Some(a) => a + .text() + .map(Some) + .ok_or_else(|| format!("Argument on {pos} is not a string")), + } + } + + fn str<'a>(args: &[Arg<'a>], pos: usize) -> Result, Fail> { + Self::ostr(args, pos)? + .ok_or_else(|| format!("Argument on {pos} position is not a valid string")) + } + + fn number(args: &[Arg], pos: usize) -> Result { + match args.get(pos) { + None => Err(format!("Argument on {pos} position is not a valid number")), + Some(Arg::Num(n)) => Ok(*n), + Some(_) => Err(format!("Argument on {pos} is not a number")), + } + } + + fn unit(args: &[Arg], pos: usize) -> Result { + DurationUnit::parse(&Self::str(args, pos)?) + .ok_or_else(|| "Invalid duration unit".to_string()) + } + + fn unit_opt(args: &[Arg], pos: usize) -> Result, Fail> { + match Self::ostr(args, pos)? { + None => Ok(None), + Some(u) => DurationUnit::parse(&u) + .map(Some) + .ok_or_else(|| "Invalid duration unit".to_string()), + } + } + + fn duration(args: &[Arg], from: usize) -> Result { + match Self::var(args, from)? { + Arg::Str(s) => Duration::parse(s).map_err(|e| e.to_string()), + Arg::Num(n) => { + let unit = Self::unit(args, from + 1)?; + Duration::from_unit(n, unit).ok_or_else(|| "Invalid duration unit".to_string()) + } + _ => Err("Invalid duration arguments".to_string()), + } + } + + fn other(args: &[Arg]) -> Result { + Ok(match Self::var(args, 1)? { + Arg::Date(d) => d, + Arg::Str(s) => Date::text(s, None), + other => Date::new(other.variable(), None), + }) + } + + fn date(d: Date) -> Out { + Out::Date(d) + } + + fn run(f: impl FnOnce() -> Result) -> Outcome { + Some(f()) + } + + pub(crate) const ADD: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| Ok(Self::date(Self::this(args)?.add(Self::duration(args, 1)?)))) + }], + fail: Self::NEVER, + }; + + pub(crate) const SUB: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| Ok(Self::date(Self::this(args)?.sub(Self::duration(args, 1)?)))) + }], + fail: Self::NEVER, + }; + + pub(crate) const SET: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| { + let this = Self::this(args)?; + let unit = Self::unit(args, 1)?; + let value = Self::number(args, 2)? + .to_u32() + .ok_or_else(|| "Invalid duration value".to_string())?; + Ok(Self::date(this.set(value, unit))) + }) + }], + fail: Self::NEVER, + }; + + pub(crate) const FORMAT: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| { + let this = Self::this(args)?; + Ok(this.format(Self::ostr(args, 1)?.as_deref()).into()) + }) + }], + fail: Self::NEVER, + }; + + pub(crate) const START_OF: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| Ok(Self::date(Self::this(args)?.start_of(Self::unit(args, 1)?)))) + }], + fail: Self::NEVER, + }; + + pub(crate) const END_OF: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| Ok(Self::date(Self::this(args)?.end_of(Self::unit(args, 1)?)))) + }], + fail: Self::NEVER, + }; + + pub(crate) const DIFF: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| { + let this = Self::this(args)?; + let other = Self::other(args)?; + let unit = Self::unit_opt(args, 2)?; + Ok(match this.diff(&other, unit).and_then(Decimal::from_i64) { + Some(n) => Out::Num(n), + None => Out::Var(Variable::Null), + }) + }) + }], + fail: Self::NEVER, + }; + + pub(crate) const TZ: Builtin = Builtin { + overloads: &[|args| { + Self::run(|| { + let this = Self::this(args)?; + let zone = Tz::from_str(&Self::str(args, 1)?) + .map_err(|_| "Invalid timezone".to_string())?; + Ok(Self::date(this.tz(zone))) + }) + }], + fail: Self::NEVER, + }; + + fn compare(args: &[Arg], op: Compare) -> Outcome { + Self::run(|| { + let this = Self::this(args)?; + let other = Self::other(args)?; + let unit = Self::unit_opt(args, 2)?; + Ok(Out::Bool(match op { + Compare::Same => this.is_same(&other, unit), + Compare::Before => this.is_before(&other, unit), + Compare::After => this.is_after(&other, unit), + Compare::SameOrBefore => this.is_same_or_before(&other, unit), + Compare::SameOrAfter => this.is_same_or_after(&other, unit), + })) + }) + } + + pub(crate) const IS_SAME: Builtin = Builtin { + overloads: &[|args| Self::compare(args, Compare::Same)], + fail: Self::NEVER, + }; + + pub(crate) const IS_BEFORE: Builtin = Builtin { + overloads: &[|args| Self::compare(args, Compare::Before)], + fail: Self::NEVER, + }; + + pub(crate) const IS_AFTER: Builtin = Builtin { + overloads: &[|args| Self::compare(args, Compare::After)], + fail: Self::NEVER, + }; + + pub(crate) const IS_SAME_OR_BEFORE: Builtin = Builtin { + overloads: &[|args| Self::compare(args, Compare::SameOrBefore)], + fail: Self::NEVER, + }; + + pub(crate) const IS_SAME_OR_AFTER: Builtin = Builtin { + overloads: &[|args| Self::compare(args, Compare::SameOrAfter)], + fail: Self::NEVER, + }; + + pub(crate) fn shift(method: &MethodKind, args: &[Arg]) -> Option { + let MethodKind::DateMethod(method) = method; + match method { + DateMethod::Add => Self::duration(args, 1).ok().map(Shift::Add), + DateMethod::Sub => Self::duration(args, 1).ok().map(Shift::Sub), + DateMethod::StartOf if args.len() == 2 => Self::unit(args, 1).ok().map(Shift::Start), + DateMethod::EndOf if args.len() == 2 => Self::unit(args, 1).ok().map(Shift::End), + _ => None, + } + } + + pub(crate) fn part_of(method: &MethodKind, date: &Date) -> Option { + let MethodKind::DateMethod(method) = method; + let dt = date.0?; + Some(match method { + DateMethod::Second => dt.second() as i64, + DateMethod::Minute => dt.minute() as i64, + DateMethod::Hour => dt.hour() as i64, + DateMethod::Day => dt.day() as i64, + DateMethod::Weekday => dt.weekday().number_from_monday() as i64, + DateMethod::DayOfYear => dt.ordinal() as i64, + DateMethod::Week => dt.iso_week().week() as i64, + DateMethod::Month => dt.month() as i64, + DateMethod::Quarter => dt.quarter() as i64, + DateMethod::Year => dt.year() as i64, + DateMethod::Timestamp => dt.timestamp_millis(), + _ => return None, + }) + } + + pub(crate) fn order(method: &MethodKind, this: &Date, other: &Date) -> Option { + let MethodKind::DateMethod(method) = method; + Some(match method { + DateMethod::IsSame => this.is_same(other, None), + DateMethod::IsBefore => this.is_before(other, None), + DateMethod::IsAfter => this.is_after(other, None), + DateMethod::IsSameOrBefore => this.is_same_or_before(other, None), + DateMethod::IsSameOrAfter => this.is_same_or_after(other, None), + _ => return None, + }) + } + + fn part(args: &[Arg], part: Part) -> Outcome { + Self::run(|| { + let this = Self::this(args)?; + if let Part::IsValid = part { + return Ok(Out::Bool(this.is_valid())); + } + let Some(dt) = this.0 else { + return Ok(Out::Var(Variable::Null)); + }; + Ok(match part { + Part::Second => Out::Num(dt.second().into()), + Part::Minute => Out::Num(dt.minute().into()), + Part::Hour => Out::Num(dt.hour().into()), + Part::Day => Out::Num(dt.day().into()), + Part::Weekday => Out::Num(dt.weekday().number_from_monday().into()), + Part::DayOfYear => Out::Num(dt.ordinal().into()), + Part::Week => Out::Num(dt.iso_week().week().into()), + Part::Month => Out::Num(dt.month().into()), + Part::Quarter => Out::Num(dt.quarter().into()), + Part::Year => Out::Num(dt.year().into()), + Part::Timestamp => Out::Num(dt.timestamp_millis().into()), + Part::IsValid => Out::Bool(true), + Part::IsYesterday => { + Out::Bool(this.is_same(&Date::yesterday(), Some(DurationUnit::Day))) + } + Part::IsToday => Out::Bool(this.is_same(&Date::now(), Some(DurationUnit::Day))), + Part::IsTomorrow => { + Out::Bool(this.is_same(&Date::tomorrow(), Some(DurationUnit::Day))) + } + Part::IsLeapYear => Out::Bool(dt.date_naive().leap_year()), + Part::OffsetName => dt.timezone().name().into(), + }) + }) + } + + pub(crate) const SECOND: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Second)], + fail: Self::NEVER, + }; + pub(crate) const MINUTE: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Minute)], + fail: Self::NEVER, + }; + pub(crate) const HOUR: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Hour)], + fail: Self::NEVER, + }; + pub(crate) const DAY: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Day)], + fail: Self::NEVER, + }; + pub(crate) const WEEKDAY: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Weekday)], + fail: Self::NEVER, + }; + pub(crate) const DAY_OF_YEAR: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::DayOfYear)], + fail: Self::NEVER, + }; + pub(crate) const WEEK: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Week)], + fail: Self::NEVER, + }; + pub(crate) const MONTH: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Month)], + fail: Self::NEVER, + }; + pub(crate) const QUARTER: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Quarter)], + fail: Self::NEVER, + }; + pub(crate) const YEAR: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Year)], + fail: Self::NEVER, + }; + pub(crate) const TIMESTAMP: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::Timestamp)], + fail: Self::NEVER, + }; + pub(crate) const OFFSET_NAME: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::OffsetName)], + fail: Self::NEVER, + }; + pub(crate) const IS_VALID: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::IsValid)], + fail: Self::NEVER, + }; + pub(crate) const IS_YESTERDAY: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::IsYesterday)], + fail: Self::NEVER, + }; + pub(crate) const IS_TODAY: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::IsToday)], + fail: Self::NEVER, + }; + pub(crate) const IS_TOMORROW: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::IsTomorrow)], + fail: Self::NEVER, + }; + pub(crate) const IS_LEAP_YEAR: Builtin = Builtin { + overloads: &[|a| Self::part(a, Part::IsLeapYear)], + fail: Self::NEVER, + }; +} diff --git a/core/expression/src/lane/builtins/functions.rs b/core/expression/src/lane/builtins/functions.rs new file mode 100644 index 00000000..f1265add --- /dev/null +++ b/core/expression/src/lane/builtins/functions.rs @@ -0,0 +1,203 @@ +use crate::functions::{ + DateMethod as M, DeprecatedFunction as D, FunctionKind, InternalFunction as F, MethodKind, +}; +use crate::lane::builtins::arrays::Arrays; +use crate::lane::builtins::convert::Convert; +use crate::lane::builtins::dates::Dates; +use crate::lane::builtins::legacy::Legacy; +use crate::lane::builtins::math::Math; +use crate::lane::builtins::text::Text; +use crate::lane::builtins::{Arg, Builtin, Fail, Out}; +use crate::lane::exec::{CallFault, Fault}; +use crate::lane::ops::Ops; +use crate::vm::VMError; +use smallvec::SmallVec; +use std::borrow::Cow; + +pub(crate) struct Builtins; + +impl Builtins { + pub(crate) fn of(kind: &FunctionKind) -> Option<&'static Builtin> { + let function = match kind { + FunctionKind::Internal(function) => function, + FunctionKind::Deprecated(function) => { + return Some(match function { + D::Date => &Legacy::DATE, + D::Time => &Legacy::TIME, + D::Duration => &Legacy::DURATION, + D::Year => &Legacy::YEAR, + D::DayOfWeek => &Legacy::DAY_OF_WEEK, + D::DayOfMonth => &Legacy::DAY_OF_MONTH, + D::DayOfYear => &Legacy::DAY_OF_YEAR, + D::WeekOfYear => &Legacy::WEEK_OF_YEAR, + D::MonthOfYear => &Legacy::MONTH_OF_YEAR, + D::MonthString => &Legacy::MONTH_STRING, + D::DateString => &Legacy::DATE_STRING, + D::WeekdayString => &Legacy::WEEKDAY_STRING, + D::StartOf => &Legacy::START_OF, + D::EndOf => &Legacy::END_OF, + }) + } + FunctionKind::Closure(_) => return None, + }; + Some(match function { + F::Len => &Text::LEN, + F::Contains => &Text::CONTAINS, + F::Upper => &Text::UPPER, + F::Lower => &Text::LOWER, + F::Trim => &Text::TRIM, + F::StartsWith => &Text::STARTS_WITH, + F::EndsWith => &Text::ENDS_WITH, + F::Matches => &Text::MATCHES, + F::Extract => &Text::EXTRACT, + F::FuzzyMatch => &Text::FUZZY_MATCH, + F::Split => &Text::SPLIT, + F::Abs => &Math::ABS, + F::Sum => &Math::SUM, + F::Avg => &Math::AVG, + F::Min => &Math::MIN, + F::Max => &Math::MAX, + F::Rand => &Math::RAND, + F::Median => &Math::MEDIAN, + F::Mode => &Math::MODE, + F::Floor => &Math::FLOOR, + F::Ceil => &Math::CEIL, + F::Round => &Math::ROUND, + F::Trunc => &Math::TRUNC, + F::Flatten => &Arrays::FLATTEN, + F::Merge => &Arrays::MERGE, + F::MergeDeep => &Arrays::MERGE_DEEP, + F::Keys => &Arrays::KEYS, + F::Values => &Arrays::VALUES, + F::IsNumeric => &Convert::IS_NUMERIC, + F::String => &Convert::STRING, + F::Number => &Convert::NUMBER, + F::Bool => &Convert::BOOL, + F::Type => &Convert::TYPE, + F::Date => &Convert::DATE, + }) + } + + pub(crate) fn method(kind: &MethodKind) -> &'static Builtin { + let MethodKind::DateMethod(method) = kind; + match method { + M::Add => &Dates::ADD, + M::Sub => &Dates::SUB, + M::Set => &Dates::SET, + M::Format => &Dates::FORMAT, + M::StartOf => &Dates::START_OF, + M::EndOf => &Dates::END_OF, + M::Diff => &Dates::DIFF, + M::Tz => &Dates::TZ, + M::IsSame => &Dates::IS_SAME, + M::IsBefore => &Dates::IS_BEFORE, + M::IsAfter => &Dates::IS_AFTER, + M::IsSameOrBefore => &Dates::IS_SAME_OR_BEFORE, + M::IsSameOrAfter => &Dates::IS_SAME_OR_AFTER, + M::Second => &Dates::SECOND, + M::Minute => &Dates::MINUTE, + M::Hour => &Dates::HOUR, + M::Day => &Dates::DAY, + M::DayOfYear => &Dates::DAY_OF_YEAR, + M::Week => &Dates::WEEK, + M::Weekday => &Dates::WEEKDAY, + M::Month => &Dates::MONTH, + M::Quarter => &Dates::QUARTER, + M::Year => &Dates::YEAR, + M::Timestamp => &Dates::TIMESTAMP, + M::OffsetName => &Dates::OFFSET_NAME, + M::IsValid => &Dates::IS_VALID, + M::IsYesterday => &Dates::IS_YESTERDAY, + M::IsToday => &Dates::IS_TODAY, + M::IsTomorrow => &Dates::IS_TOMORROW, + M::IsLeapYear => &Dates::IS_LEAP_YEAR, + } + } + + fn attempt(builtin: &Builtin, args: &[Arg]) -> Option> { + builtin.overloads.iter().find_map(|overload| overload(args)) + } + + #[cold] + #[inline(never)] + fn textual(builtin: &Builtin, args: &[Arg]) -> Option> { + let texts: SmallVec<[Option>; 4]> = args + .iter() + .map(|a| a.date().and_then(|_| a.text())) + .collect(); + if texts.iter().all(Option::is_none) { + return None; + } + [1, 0].into_iter().find_map(|from| { + let converted: SmallVec<[Arg; 4]> = args + .iter() + .zip(&texts) + .enumerate() + .map(|(i, (a, text))| match text { + Some(text) if i >= from => Arg::Str(text), + _ => *a, + }) + .collect(); + Self::attempt(builtin, &converted) + }) + } + + #[inline] + fn resolve(builtin: &Builtin, args: &[Arg]) -> Result { + Self::attempt(builtin, args) + .or_else(|| Self::textual(builtin, args)) + .unwrap_or_else(|| Err((builtin.fail)(args))) + } + + pub(crate) fn call_method( + builtin: &Builtin, + kind: &MethodKind, + args: &[Arg], + ) -> Result { + Self::resolve(builtin, args).map_err(|message| { + Ops::error("CallMethod", format!("Method `{kind}` failed: {message}")) + }) + } + + #[inline] + pub(crate) fn call_hinted( + builtin: &'static Builtin, + kind: &FunctionKind, + args: &[Arg], + hint: &mut usize, + ) -> Result { + let failed = |message: Fail| CallFault::message(kind, message); + if let Some(overload) = builtin.overloads.get(*hint) { + if let Some(result) = overload(args) { + return result.map_err(failed); + } + } + for (index, overload) in builtin.overloads.iter().enumerate() { + if let Some(result) = overload(args) { + *hint = index; + return result.map_err(failed); + } + } + match Self::textual(builtin, args) { + Some(result) => result.map_err(failed), + None => Err(CallFault::fail(kind, builtin, args)), + } + } + + pub(crate) fn raw(builtin: &Builtin, args: &[Arg]) -> Result { + Self::resolve(builtin, args) + } + + pub(crate) fn call( + builtin: &Builtin, + kind: &FunctionKind, + args: &[Arg], + ) -> Result { + Self::resolve(builtin, args).map_err(|message| { + Ops::error( + "CallFunction", + format!("Function `{kind}` failed: {message}"), + ) + }) + } +} diff --git a/core/expression/src/lane/builtins/legacy.rs b/core/expression/src/lane/builtins/legacy.rs new file mode 100644 index 00000000..1459dcb8 --- /dev/null +++ b/core/expression/src/lane/builtins/legacy.rs @@ -0,0 +1,190 @@ +use crate::lane::builtins::{Apply, Arg, Builtin, Fail, Params}; +use crate::lane::date::helpers::{date_time, date_time_end_of, date_time_start_of, time, DateUnit}; +use crate::variable::Variable; +use chrono::{Datelike, NaiveDateTime, Timelike}; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; + +pub(crate) struct Legacy; + +impl Legacy { + const ANY: fn(&[Arg]) -> Fail = |_| "Argument on 0 position out of bounds".to_string(); + + fn convert(timestamp: Arg) -> Result { + let instant = timestamp + .date() + .and_then(|date| date.0) + .map(|date| date.naive_local()); + let converted = match timestamp { + Arg::Str(s) => date_time(s).ok(), + Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => match timestamp.text() { + Some(text) => date_time(&text).ok().or(instant), + None => instant, + }, + #[allow(deprecated)] + Arg::Num(n) => n + .to_i64() + .and_then(|n| NaiveDateTime::from_timestamp_opt(n, 0)), + _ => None, + }; + converted.ok_or_else(|| "Failed to convert value to date time".to_string()) + } + + pub(crate) const DATE: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| match a { + Arg::Str(s) => { + let dt = date_time(s).map_err(|e| e.to_string())?; + #[allow(deprecated)] + Ok(Decimal::from(dt.timestamp())) + } + Arg::Num(n) => n + .to_i64() + .map(Decimal::from) + .ok_or_else(|| "Number overflow".to_string()), + other => Self::convert(other) + .map_err(|_| "Unsupported type for date function".to_string()) + .map(|dt| { + #[allow(deprecated)] + Decimal::from(dt.timestamp()) + }), + }) + }], + fail: Self::ANY, + }; + + pub(crate) const TIME: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| match a { + Arg::Str(s) => Ok(Decimal::from( + time(s) + .map_err(|e| e.to_string())? + .num_seconds_from_midnight(), + )), + Arg::Num(n) => n + .to_u32() + .map(Decimal::from) + .ok_or_else(|| "Number overflow".to_string()), + Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => { + match a.text().map(|text| time(&text)) { + Some(Ok(time)) => Ok(Decimal::from(time.num_seconds_from_midnight())), + _ => Self::convert(a) + .map(|dt| Decimal::from(dt.time().num_seconds_from_midnight())), + } + } + _ => Err("Unsupported type for time function".to_string()), + }) + }], + fail: Self::ANY, + }; + + pub(crate) const DURATION: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Arg| match a { + Arg::Str(s) => Ok(Decimal::from( + humantime::parse_duration(s) + .map_err(|e| e.to_string())? + .as_secs(), + )), + Arg::Num(n) => n + .to_u64() + .map(Decimal::from) + .ok_or_else(|| "Number overflow".to_string()), + _ => Err("Unsupported type for duration function".to_string()), + }) + }], + fail: Self::ANY, + }; + + pub(crate) const YEAR: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.year()).into())) + }], + fail: Self::ANY, + }; + + pub(crate) const DAY_OF_WEEK: Builtin = Builtin { + overloads: &[|args| { + Some( + Self::convert(*args.first()?) + .map(|t| Decimal::from(t.weekday().number_from_monday()).into()), + ) + }], + fail: Self::ANY, + }; + + pub(crate) const DAY_OF_MONTH: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.day()).into())) + }], + fail: Self::ANY, + }; + + pub(crate) const DAY_OF_YEAR: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.ordinal()).into())) + }], + fail: Self::ANY, + }; + + pub(crate) const WEEK_OF_YEAR: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.iso_week().week()).into())) + }], + fail: Self::ANY, + }; + + pub(crate) const MONTH_OF_YEAR: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.month()).into())) + }], + fail: Self::ANY, + }; + + pub(crate) const MONTH_STRING: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| t.format("%b").to_string().into())) + }], + fail: Self::ANY, + }; + + pub(crate) const WEEKDAY_STRING: Builtin = Builtin { + overloads: &[|args| { + Some(Self::convert(*args.first()?).map(|t| t.weekday().to_string().into())) + }], + fail: Self::ANY, + }; + + pub(crate) const DATE_STRING: Builtin = Builtin { + overloads: &[|args| Some(Self::convert(*args.first()?).map(|t| t.to_string().into()))], + fail: Self::ANY, + }; + + pub(crate) const START_OF: Builtin = Builtin { + overloads: &[|args| { + Apply::two(args, |timestamp: Arg, unit: &str| { + let datetime = Self::convert(timestamp)?; + let unit = DateUnit::try_from(unit).map_err(|_| "Invalid date unit".to_string())?; + let result = date_time_start_of(datetime, unit) + .ok_or_else(|| "Failed to calculate start of period".to_string())?; + #[allow(deprecated)] + Ok(Decimal::from(result.timestamp())) + }) + }], + fail: |args| Params::fail(args, &[("value", false), ("string", false)]), + }; + + pub(crate) const END_OF: Builtin = Builtin { + overloads: &[|args| { + Apply::two(args, |timestamp: Arg, unit: &str| { + let datetime = Self::convert(timestamp)?; + let unit = DateUnit::try_from(unit).map_err(|_| "Invalid date unit".to_string())?; + let result = date_time_end_of(datetime, unit) + .ok_or_else(|| "Failed to calculate end of period".to_string())?; + #[allow(deprecated)] + Ok(Decimal::from(result.timestamp())) + }) + }], + fail: |args| Params::fail(args, &[("value", false), ("string", false)]), + }; +} diff --git a/core/expression/src/lane/builtins/math.rs b/core/expression/src/lane/builtins/math.rs new file mode 100644 index 00000000..bdace8d9 --- /dev/null +++ b/core/expression/src/lane/builtins/math.rs @@ -0,0 +1,219 @@ +use crate::lane::builtins::{Apply, Array, Builtin, Fail, Params}; +use crate::lane::date::Date; +use crate::lane::date::DynamicVariableExt; +use crate::variable::Variable; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::{Decimal, RoundingStrategy}; +use std::collections::BTreeMap; + +pub(crate) struct Math; + +enum Extreme { + Numbers(Vec), + Dates(Vec<(Date, Variable)>), +} + +impl Math { + const NUMBER: &'static [(&'static str, bool)] = &[("number", false)]; + const PLACES: &'static [(&'static str, bool)] = &[("number", false), ("number", true)]; + const ARRAY: &'static [(&'static str, bool)] = &[("array", false)]; + + fn places(places: Option) -> Result { + match places { + Some(p) => p + .to_u32() + .ok_or_else(|| "Invalid number of decimal places".to_string()), + None => Ok(0), + } + } + + fn numbers(a: &Array) -> Result, Fail> { + a.numbers() + .map(|n| n.into_owned()) + .ok_or_else(|| "Expected a number array".to_string()) + } + + fn total(values: &[Decimal]) -> Result { + values + .iter() + .try_fold(Decimal::ZERO, |acc, v| acc.checked_add(*v)) + .ok_or_else(|| "Number overflow".to_string()) + } + + pub(crate) const ABS: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.abs()))], + fail: |args| Params::fail(args, Self::NUMBER), + }; + + pub(crate) const CEIL: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.ceil()))], + fail: |args| Params::fail(args, Self::NUMBER), + }; + + pub(crate) const FLOOR: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.floor()))], + fail: |args| Params::fail(args, Self::NUMBER), + }; + + pub(crate) const ROUND: Builtin = Builtin { + overloads: &[|args| { + Apply::two(args, |a: Decimal, places: Option| { + Ok(a.round_dp_with_strategy( + Self::places(places)?, + RoundingStrategy::MidpointAwayFromZero, + )) + }) + }], + fail: |args| Params::fail(args, Self::PLACES), + }; + + pub(crate) const TRUNC: Builtin = Builtin { + overloads: &[|args| { + Apply::two(args, |a: Decimal, places: Option| { + Ok(a.trunc_with_scale(Self::places(places)?)) + }) + }], + fail: |args| Params::fail(args, Self::PLACES), + }; + + pub(crate) const RAND: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Decimal| { + let upper = a + .round() + .to_i64() + .ok_or_else(|| "Invalid upper range".to_string())?; + Ok(Decimal::from(fastrand::i64(0..=upper))) + }) + }], + fail: |args| Params::fail(args, Self::NUMBER), + }; + + pub(crate) const SUM: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Array| { + let numbers = a + .numbers() + .ok_or_else(|| "Expected a number array".to_string())?; + Self::total(&numbers) + }) + }], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + pub(crate) const AVG: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Array| { + let numbers = a + .numbers() + .ok_or_else(|| "Expected a number array".to_string())?; + let sum = Self::total(&numbers)?; + sum.checked_div(Decimal::from(numbers.len())) + .ok_or_else(|| "Empty array".to_string()) + }) + }], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + pub(crate) const MEDIAN: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Array| { + let mut values = Self::numbers(&a)?; + values.sort(); + let center = values.len() / 2; + match values.len() % 2 { + 1 => values + .get(center) + .copied() + .ok_or_else(|| "Index out of bounds".to_string()), + _ => { + let left = center + .checked_sub(1) + .and_then(|i| values.get(i)) + .ok_or_else(|| "Index out of bounds".to_string())?; + let right = values + .get(center) + .ok_or_else(|| "Index out of bounds".to_string())?; + let total = left + .checked_add(*right) + .ok_or_else(|| "Number overflow".to_string())?; + Ok(total / Decimal::TWO) + } + } + }) + }], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + pub(crate) const MODE: Builtin = Builtin { + overloads: &[|args| { + Apply::one(args, |a: Array| { + let mut counts = BTreeMap::new(); + for n in Self::numbers(&a)? { + *counts.entry(n).or_insert(0usize) += 1; + } + counts + .into_iter() + .max_by_key(|&(_, count)| count) + .map(|(n, _)| n) + .ok_or_else(|| "Empty array".to_string()) + }) + }], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + fn extreme(a: &Array) -> Result { + a.with(|values| { + let numeric = values.first().and_then(Variable::as_number).is_some(); + match numeric { + true => values + .iter() + .map(Variable::as_number) + .collect::>>() + .map(Extreme::Numbers) + .ok_or_else(|| "Expected a number array".to_string()), + false => values + .iter() + .map(|v| match v { + Variable::Dynamic(d) => d.as_date().map(|date| (date, v.clone())), + _ => None, + }) + .collect::>>() + .map(Extreme::Dates) + .ok_or_else(|| "Expected a number array".to_string()), + } + }) + } + + fn pick(a: Array, largest: bool) -> Result { + let empty = || "Empty array".to_string(); + match (Self::extreme(&a)?, largest) { + (Extreme::Numbers(n), true) => { + n.into_iter().max().map(Variable::Number).ok_or_else(empty) + } + (Extreme::Numbers(n), false) => { + n.into_iter().min().map(Variable::Number).ok_or_else(empty) + } + (Extreme::Dates(d), true) => d + .into_iter() + .max_by(|a, b| a.0.cmp(&b.0)) + .map(|(_, original)| original) + .ok_or_else(empty), + (Extreme::Dates(d), false) => d + .into_iter() + .min_by(|a, b| a.0.cmp(&b.0)) + .map(|(_, original)| original) + .ok_or_else(empty), + } + } + + pub(crate) const MIN: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Array| Self::pick(a, false))], + fail: |args| Params::fail(args, Self::ARRAY), + }; + + pub(crate) const MAX: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: Array| Self::pick(a, true))], + fail: |args| Params::fail(args, Self::ARRAY), + }; +} diff --git a/core/expression/src/lane/builtins/mod.rs b/core/expression/src/lane/builtins/mod.rs new file mode 100644 index 00000000..b8210971 --- /dev/null +++ b/core/expression/src/lane/builtins/mod.rs @@ -0,0 +1,362 @@ +mod arrays; +mod convert; +pub(crate) mod dates; +mod functions; +mod legacy; +mod math; +mod text; + +pub(crate) use dates::Dates; +pub(crate) use functions::Builtins; +pub(crate) use text::{Text, TextKernel}; + +use crate::lane::columns::{Column, Values}; +use crate::lane::date::Date; +use crate::lane::date::DynamicVariableExt; +use crate::variable::Variable; +use rust_decimal::Decimal; +use std::borrow::Cow; +use zen_types::rccell::RcCell; + +#[derive(Debug, Clone, Copy)] +pub(crate) struct ListView<'a> { + pub child: &'a Column<'a>, + pub start: usize, + pub end: usize, +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Arg<'a> { + Null, + Num(Decimal), + Bool(bool), + Str(&'a str), + Date(Date), + Var(&'a Variable), + List(ListView<'a>), +} + +impl<'a> Arg<'a> { + pub(crate) fn of(v: &'a Variable) -> Self { + match v { + Variable::Null => Arg::Null, + Variable::Number(n) => Arg::Num(*n), + Variable::Bool(b) => Arg::Bool(*b), + Variable::String(s) => Arg::Str(s.as_str()), + Variable::Dynamic(d) => match d.as_date() { + Some(date) if !Date::sourced(v) => Arg::Date(date), + _ => Arg::Var(v), + }, + v => Arg::Var(v), + } + } + + pub(crate) fn date(&self) -> Option { + match self { + Arg::Date(d) => Some(*d), + Arg::Var(Variable::Dynamic(d)) => d.as_date(), + _ => None, + } + } + + pub(crate) fn text(&self) -> Option> { + match self { + Arg::Str(s) => Some(Cow::Borrowed(s)), + Arg::Date(d) => d.rendered().map(Cow::Owned), + Arg::Var(v @ Variable::Dynamic(_)) => v.as_str().map(Cow::Borrowed), + _ => None, + } + } + + pub(crate) fn coerce_date(&self) -> Option { + match self { + Arg::Str(s) => Some(Date::from_text(s)), + other => other.date(), + } + } + + pub(crate) fn type_name(&self) -> &'static str { + match self { + Arg::Null => "null", + Arg::Num(_) => "number", + Arg::Bool(_) => "bool", + Arg::Str(_) => "string", + Arg::Date(_) => "date", + Arg::Var(v) => v.type_name(), + Arg::List(_) => "array", + } + } + + pub(crate) fn variable(&self) -> Variable { + match self { + Arg::Null => Variable::Null, + Arg::Num(n) => Variable::Number(*n), + Arg::Bool(b) => Variable::Bool(*b), + Arg::Str(s) => Variable::String((*s).into()), + Arg::Date(d) => d.variable(), + Arg::Var(v) => (*v).clone(), + Arg::List(l) => { + Variable::from_array((l.start..l.end).map(|i| l.child.variable(i)).collect()) + } + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Array<'a> { + Var(&'a RcCell>), + List(ListView<'a>), +} + +impl<'a> Array<'a> { + pub(crate) fn len(&self) -> usize { + match self { + Array::Var(a) => a.borrow().len(), + Array::List(l) => l.end - l.start, + } + } + + pub(crate) fn numbers(&self) -> Option> { + match self { + Array::List(l) => match l.child.values { + Values::Dec(values) if (l.start..l.end).all(|i| l.child.valid(i)) => { + values.get(l.start..l.end).map(Cow::Borrowed) + } + _ => (l.start..l.end) + .map(|i| l.child.valid(i).then(|| l.child.number(i)).flatten()) + .collect::>>() + .map(Cow::Owned), + }, + Array::Var(a) => a + .borrow() + .iter() + .map(Variable::as_number) + .collect::>>() + .map(Cow::Owned), + } + } + + pub(crate) fn variables(&self) -> Vec { + match self { + Array::Var(a) => a.borrow().clone(), + Array::List(l) => (l.start..l.end).map(|i| l.child.variable(i)).collect(), + } + } + + pub(crate) fn with(&self, f: impl FnOnce(&[Variable]) -> T) -> T { + match self { + Array::Var(a) => f(&a.borrow()), + Array::List(_) => f(&self.variables()), + } + } + + pub(crate) fn any(&self, mut f: impl FnMut(Arg) -> bool) -> bool { + match self { + Array::Var(a) => a.borrow().iter().any(|v| f(Arg::of(v))), + Array::List(l) => (l.start..l.end).any(|i| { + let v = l.child.variable(i); + f(Arg::of(&v)) + }), + } + } +} + +pub(crate) trait FromArg<'a>: Sized { + fn from_arg(a: Option>) -> Option; +} + +impl<'a> FromArg<'a> for &'a str { + fn from_arg(a: Option>) -> Option { + match a? { + Arg::Str(s) => Some(s), + _ => None, + } + } +} + +impl<'a> FromArg<'a> for Decimal { + fn from_arg(a: Option>) -> Option { + match a? { + Arg::Num(n) => Some(n), + _ => None, + } + } +} + +impl<'a> FromArg<'a> for bool { + fn from_arg(a: Option>) -> Option { + match a? { + Arg::Bool(b) => Some(b), + _ => None, + } + } +} + +impl<'a> FromArg<'a> for Array<'a> { + fn from_arg(a: Option>) -> Option { + match a? { + Arg::Var(Variable::Array(a)) => Some(Array::Var(a)), + Arg::List(l) => Some(Array::List(l)), + _ => None, + } + } +} + +impl<'a> FromArg<'a> for Arg<'a> { + fn from_arg(a: Option>) -> Option { + a + } +} + +impl<'a, T: FromArg<'a>> FromArg<'a> for Option { + fn from_arg(a: Option>) -> Option { + match a { + None => Some(None), + Some(a) => T::from_arg(Some(a)).map(Some), + } + } +} + +#[derive(Debug, Clone)] +pub(crate) enum Out { + Num(Decimal), + Bool(bool), + Str(zen_types::symbol::Symbol), + Date(Date), + Var(Variable), +} + +impl Out { + pub(crate) fn variable(self) -> Variable { + match self { + Out::Num(n) => Variable::Number(n), + Out::Bool(b) => Variable::Bool(b), + Out::Str(s) => Variable::String(s), + Out::Date(d) => d.variable(), + Out::Var(v) => v, + } + } +} + +impl From for Out { + fn from(n: Decimal) -> Self { + Out::Num(n) + } +} + +impl From for Out { + fn from(n: usize) -> Self { + Out::Num(n.into()) + } +} + +impl From for Out { + fn from(b: bool) -> Self { + Out::Bool(b) + } +} + +impl From for Out { + fn from(s: String) -> Self { + Out::Str(zen_types::symbol::Symbol::from(s.as_str())) + } +} + +impl From<&str> for Out { + fn from(s: &str) -> Self { + Out::Str(zen_types::symbol::Symbol::from(s)) + } +} + +impl From for Out { + fn from(d: Date) -> Self { + Out::Date(d) + } +} + +impl From for Out { + fn from(v: Variable) -> Self { + Out::Var(v) + } +} + +pub(crate) type Fail = String; + +pub(crate) type Outcome = Option>; + +pub(crate) type Overload = for<'a> fn(&[Arg<'a>]) -> Outcome; + +pub(crate) struct Apply; + +impl Apply { + #[inline(always)] + pub(crate) fn one<'a, A, R>(args: &[Arg<'a>], f: impl FnOnce(A) -> Result) -> Outcome + where + A: FromArg<'a>, + R: Into, + { + let a = A::from_arg(args.first().copied())?; + Some(f(a).map(Into::into)) + } + + #[inline(always)] + pub(crate) fn two<'a, A, B, R>( + args: &[Arg<'a>], + f: impl FnOnce(A, B) -> Result, + ) -> Outcome + where + A: FromArg<'a>, + B: FromArg<'a>, + R: Into, + { + let a = A::from_arg(args.first().copied())?; + let b = B::from_arg(args.get(1).copied())?; + Some(f(a, b).map(Into::into)) + } +} + +pub(crate) struct Params; + +impl Params { + pub(crate) fn fail(args: &[Arg], wants: &[(&str, bool)]) -> Fail { + for (pos, (want, optional)) in wants.iter().enumerate() { + let matches = |a: &Arg| match *want { + "string" => a.text().is_some(), + "number" => matches!(a, Arg::Num(_)), + "bool" => matches!(a, Arg::Bool(_)), + "array" => matches!(a, Arg::Var(Variable::Array(_)) | Arg::List(_)), + "object" => matches!(a, Arg::Var(Variable::Object(_))), + _ => true, + }; + match (args.get(pos), optional) { + (None, true) => {} + (None, false) => { + return format!("Argument on {pos} position is not a valid {want}") + } + (Some(a), _) if !matches(a) => return format!("Argument on {pos} is not a {want}"), + (Some(_), _) => {} + } + } + "No overload matches provided arguments".to_string() + } +} + +pub(crate) struct Builtin { + pub(crate) overloads: &'static [Overload], + pub(crate) fail: fn(&[Arg]) -> Fail, +} + +impl<'a> FromArg<'a> for &'a Variable { + fn from_arg(a: Option>) -> Option { + match a? { + Arg::Var(v) => Some(v), + _ => None, + } + } +} + +impl<'a> FromArg<'a> for Date { + fn from_arg(a: Option>) -> Option { + a?.date() + } +} diff --git a/core/expression/src/lane/builtins/text.rs b/core/expression/src/lane/builtins/text.rs new file mode 100644 index 00000000..bf3e7926 --- /dev/null +++ b/core/expression/src/lane/builtins/text.rs @@ -0,0 +1,328 @@ +use crate::functions::{FunctionKind, InternalFunction}; +use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Out, Outcome, Params}; +use crate::variable::Variable; +#[cfg(not(feature = "regex-lite"))] +use regex::Regex; +#[cfg(feature = "regex-lite")] +use regex_lite::Regex; +use rust_decimal::prelude::FromPrimitive; +use rust_decimal::Decimal; + +pub(crate) struct Text; + +#[derive(Clone, Copy)] +pub(crate) enum TextKernel { + Test(TextTest), + Map(TextMap), + Size, +} + +#[derive(Clone, Copy)] +pub(crate) enum TextTest { + Contains, + Starts, + Ends, +} + +impl TextTest { + #[inline(always)] + pub(crate) fn apply(self, a: &str, b: &str) -> bool { + match self { + TextTest::Contains => match (b.as_bytes(), a.len() <= 64) { + ([byte], true) => a.as_bytes().iter().any(|c| c == byte), + _ => a.contains(b), + }, + TextTest::Starts => a.starts_with(b), + TextTest::Ends => a.ends_with(b), + } + } +} + +#[derive(Clone, Copy)] +pub(crate) enum TextMap { + Lower, + Upper, + Trim, +} + +impl TextMap { + #[inline] + pub(crate) fn apply(self, a: &str, out: &mut String) -> Option<(usize, usize)> { + match self { + TextMap::Lower => Text::lower(a, out), + TextMap::Upper => Text::upper(a, out), + TextMap::Trim => Text::trim(a, out), + } + } + + #[inline] + pub(crate) fn unchanged(self, a: &str) -> bool { + match self { + TextMap::Trim => { + !a.starts_with(char::is_whitespace) && !a.ends_with(char::is_whitespace) + } + TextMap::Lower | TextMap::Upper => false, + } + } + + pub(crate) fn bytewise(self) -> Option { + match self { + TextMap::Lower => Some(str::make_ascii_lowercase), + TextMap::Upper => Some(str::make_ascii_uppercase), + TextMap::Trim => None, + } + } +} + +struct Patterns; + +impl Patterns { + const CAPACITY: usize = 256; + + thread_local! { + static CACHE: std::cell::RefCell> = Default::default(); + } + + fn with(pattern: &str, f: impl FnOnce(&Regex) -> T) -> Result { + Self::CACHE.with_borrow_mut(|cache| { + if let Some(regex) = cache.get(pattern) { + return Ok(f(regex)); + } + let regex = + Regex::new(pattern).map_err(|_| "Invalid regular expression".to_string())?; + if cache.len() >= Self::CAPACITY { + cache.clear(); + } + let out = f(®ex); + cache.insert(pattern.to_string(), regex); + Ok(out) + }) + } +} + +impl Text { + pub(crate) fn kernel(kind: &FunctionKind) -> Option { + let FunctionKind::Internal(function) = kind else { + return None; + }; + Some(match function { + InternalFunction::Contains => TextKernel::Test(TextTest::Contains), + InternalFunction::StartsWith => TextKernel::Test(TextTest::Starts), + InternalFunction::EndsWith => TextKernel::Test(TextTest::Ends), + InternalFunction::Lower => TextKernel::Map(TextMap::Lower), + InternalFunction::Upper => TextKernel::Map(TextMap::Upper), + InternalFunction::Trim => TextKernel::Map(TextMap::Trim), + InternalFunction::Len => TextKernel::Size, + _ => return None, + }) + } + + fn lower(a: &str, out: &mut String) -> Option<(usize, usize)> { + match a.is_ascii() { + true if !a.bytes().any(|b| b.is_ascii_uppercase()) => Some((0, a.len())), + true => { + let start = out.len(); + out.push_str(a); + if let Some(tail) = out.get_mut(start..) { + tail.make_ascii_lowercase(); + } + None + } + false => { + out.push_str(&a.to_lowercase()); + None + } + } + } + + fn upper(a: &str, out: &mut String) -> Option<(usize, usize)> { + match a.is_ascii() { + true if !a.bytes().any(|b| b.is_ascii_lowercase()) => Some((0, a.len())), + true => { + let start = out.len(); + out.push_str(a); + if let Some(tail) = out.get_mut(start..) { + tail.make_ascii_uppercase(); + } + None + } + false => { + out.push_str(&a.to_uppercase()); + None + } + } + } + + fn trim(a: &str, _: &mut String) -> Option<(usize, usize)> { + let start = a.len() - a.trim_start().len(); + Some((start, start + a[start..].trim_end().len())) + } + + const TWO: &'static [(&'static str, bool)] = &[("string", false), ("string", false)]; + const ONE: &'static [(&'static str, bool)] = &[("string", false)]; + + pub(crate) const LEN: Builtin = Builtin { + overloads: &[Self::len_str, Self::len_array], + fail: Self::len_fail, + }; + + fn len_str(args: &[Arg]) -> Outcome { + Apply::one(args, |a: &str| Ok(a.len())) + } + + fn len_array(args: &[Arg]) -> Outcome { + Apply::one(args, |a: Array| Ok(a.len())) + } + + fn len_fail(args: &[Arg]) -> Fail { + match args.first() { + Some(a) => format!("Cannot determine len of type {}", a.type_name()), + None => "Argument on 0 position out of bounds".to_string(), + } + } + + pub(crate) const CONTAINS: Builtin = Builtin { + overloads: &[Self::contains_str, Self::contains_array], + fail: Self::contains_fail, + }; + + fn contains_str(args: &[Arg]) -> Outcome { + Apply::two(args, |a: &str, b: &str| Ok(a.contains(b))) + } + + fn contains_array(args: &[Arg]) -> Outcome { + Apply::two(args, |a: Array, b: Arg| { + Ok(a.any(|x| match (x, b) { + (Arg::Num(x), Arg::Num(y)) => x == y, + (Arg::Str(x), Arg::Str(y)) => x == y, + (Arg::Bool(x), Arg::Bool(y)) => x == y, + (Arg::Null, Arg::Null) => true, + (x, y) => match (x.date(), y.date()) { + (Some(d), _) => d.is_valid() && y.coerce_date() == Some(d), + (None, Some(d)) => d.is_valid() && x.coerce_date() == Some(d), + (None, None) => false, + }, + })) + }) + } + + fn contains_fail(args: &[Arg]) -> Fail { + match (args.first(), args.get(1)) { + (Some(a), Some(b)) => format!( + "Cannot determine contains for type {} and {}", + a.type_name(), + b.type_name() + ), + (None, _) => "Argument on 0 position out of bounds".to_string(), + (_, None) => "Argument on 1 position out of bounds".to_string(), + } + } + + pub(crate) const STARTS_WITH: Builtin = Builtin { + overloads: &[|args| Apply::two(args, |a: &str, b: &str| Ok(a.starts_with(b)))], + fail: |args| Params::fail(args, Self::TWO), + }; + + pub(crate) const ENDS_WITH: Builtin = Builtin { + overloads: &[|args| Apply::two(args, |a: &str, b: &str| Ok(a.ends_with(b)))], + fail: |args| Params::fail(args, Self::TWO), + }; + + pub(crate) const MATCHES: Builtin = Builtin { + overloads: &[|args| { + Apply::two(args, |a: &str, b: &str| { + Patterns::with(b, |regex| regex.is_match(a)) + }) + }], + fail: |args| Params::fail(args, Self::TWO), + }; + + pub(crate) const UPPER: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: &str| Ok(a.to_uppercase()))], + fail: |args| Params::fail(args, Self::ONE), + }; + + pub(crate) const LOWER: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: &str| Ok(a.to_lowercase()))], + fail: |args| Params::fail(args, Self::ONE), + }; + + pub(crate) const TRIM: Builtin = Builtin { + overloads: &[|args| Apply::one(args, |a: &str| Ok(Out::from(a.trim())))], + fail: |args| Params::fail(args, Self::ONE), + }; + + pub(crate) const EXTRACT: Builtin = Builtin { + overloads: &[Self::extract], + fail: |args| Params::fail(args, Self::TWO), + }; + + fn extract(args: &[Arg]) -> Outcome { + Apply::two(args, |a: &str, b: &str| { + let captures: Vec = Patterns::with(b, |regex| { + regex + .captures(a) + .map(|capture| { + capture + .iter() + .flatten() + .map(|c| Variable::String(c.as_str().into())) + .collect() + }) + .unwrap_or_default() + })?; + Ok(Variable::from_array(captures)) + }) + } + + pub(crate) const SPLIT: Builtin = Builtin { + overloads: &[Self::split], + fail: |args| Params::fail(args, Self::TWO), + }; + + fn split(args: &[Arg]) -> Outcome { + Apply::two(args, |a: &str, b: &str| { + Ok(Variable::from_array( + a.split(b).map(|s| Variable::String(s.into())).collect(), + )) + }) + } + + pub(crate) const FUZZY_MATCH: Builtin = Builtin { + overloads: &[Self::fuzzy], + fail: |args| Params::fail(args, &[("value", false), ("string", false)]), + }; + + fn similarity(a: &str, b: &str) -> Decimal { + Decimal::from_f64(strsim::normalized_damerau_levenshtein(a, b)).unwrap_or(Decimal::ZERO) + } + + fn fuzzy(args: &[Arg]) -> Outcome { + Apply::two(args, |a: Arg, b: &str| match a { + Arg::Str(a) => Ok(Variable::Number(Self::similarity(a, b))), + Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => match a.text() { + Some(a) => Ok(Variable::Number(Self::similarity(&a, b))), + None => Err("Fuzzy match not available for type".to_string()), + }, + Arg::Var(Variable::Array(_)) | Arg::List(_) => { + let items = match a { + Arg::List(l) => Array::List(l), + Arg::Var(Variable::Array(v)) => Array::Var(v), + _ => return Err("Fuzzy match not available for type".to_string()), + }; + items.with(|values| { + values + .iter() + .map(|v| { + v.as_str() + .map(|s| Variable::Number(Self::similarity(s, b))) + .ok_or_else(|| "Expected string array".to_string()) + }) + .collect::, _>>() + .map(Variable::from_array) + }) + } + _ => Err("Fuzzy match not available for type".to_string()), + }) + } +} diff --git a/core/expression/src/lane/cells.rs b/core/expression/src/lane/cells.rs new file mode 100644 index 00000000..5bbb2206 --- /dev/null +++ b/core/expression/src/lane/cells.rs @@ -0,0 +1,1050 @@ +use crate::lane::date::DynamicVariableExt; +use crate::lane::{Binding, Column, Columns, Kind, LaneProgram, LaneRunner, Values}; +use crate::lane::{Bits, ShortKey}; +use crate::lexer::{ComparisonOperator, Lexer, LogicalOperator, Operator}; +use crate::parser::{Node, Parser}; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::IsolateError; +use ahash::HashMap; +use bumpalo::Bump; +use rust_decimal::Decimal; +use std::sync::Arc; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Num(Decimal), + Str(Arc), + Bool(bool), + Null, +} + +impl Key { + fn literal(node: &Node) -> Option { + match node { + Node::Number(n) => Some(Key::Num(n.normalize())), + Node::String(s) => Some(Key::Str(Arc::from(*s))), + Node::Bool(b) => Some(Key::Bool(*b)), + Node::Null => Some(Key::Null), + _ => None, + } + } +} + +enum Shape { + Equal(Vec), + Range(Vec), + Other, +} + +impl Shape { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn classify(node: &Node) -> Shape { + if let Some(keys) = Self::equalities(node) { + return Shape::Equal(keys); + } + match node { + Node::Binary { + left: Node::Identifier("$"), + operator: + Operator::Comparison( + ComparisonOperator::LessThan + | ComparisonOperator::LessThanOrEqual + | ComparisonOperator::GreaterThan + | ComparisonOperator::GreaterThanOrEqual, + ), + right: Node::Number(k), + } => Shape::Range(vec![*k]), + Node::Binary { + left: Node::Identifier("$"), + operator: Operator::Comparison(ComparisonOperator::In), + right: + Node::Interval { + left: Node::Number(a), + right: Node::Number(b), + .. + }, + } => Shape::Range(vec![*a, *b]), + Node::Binary { + left, + operator: Operator::Logical(LogicalOperator::And | LogicalOperator::Or), + right, + } => match (Self::classify(left), Self::classify(right)) { + (Shape::Range(mut a), Shape::Range(b)) => { + a.extend(b); + Shape::Range(a) + } + _ => Shape::Other, + }, + Node::Parenthesized(inner) => match Self::classify(inner) { + range @ Shape::Range(_) => range, + _ => Shape::Other, + }, + _ => Shape::Other, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn equalities(node: &Node) -> Option> { + match node { + Node::Binary { + left: Node::Identifier("$"), + operator: Operator::Comparison(ComparisonOperator::Equal), + right, + } => Key::literal(right).map(|k| vec![k]), + Node::Binary { + left, + operator: Operator::Logical(LogicalOperator::Or), + right, + } => { + let mut keys = Self::equalities(left)?; + keys.extend(Self::equalities(right)?); + Some(keys) + } + Node::Parenthesized(inner) => Self::equalities(inner), + _ => None, + } + } +} + +struct Other { + program: LaneProgram, + rules: Vec, +} + +type Keyed = (u64, Box<[u8]>, Vec); + +pub struct CellEnv<'a> { + pub scopes: &'a [Scope], + pub columns: &'a Columns<'a>, + pub bind: &'a dyn Fn(&str) -> Binding, +} + +struct Scaling { + mult: i64, + bounds: Vec, +} + +pub struct Pieces { + pub bits: Vec>, + null: u32, + truth: [u32; 2], + keys: Vec<(u64, usize, Box<[u8]>, u32)>, + text: u32, + regions: Vec, + other: u32, + pub failed: u32, +} + +impl Pieces { + fn intern(bits: &mut Vec>, piece: Vec) -> u32 { + match bits.iter().position(|b| *b == piece) { + Some(at) => at as u32, + None => { + bits.push(piece); + (bits.len() - 1) as u32 + } + } + } + + #[inline] + fn text(&self, text: &[u8]) -> u32 { + let (word, len) = (ShortKey::of(text), text.len()); + self.keys + .iter() + .find(|(w, l, key, _)| *w == word && *l == len && (len <= 8 || key.as_ref() == text)) + .map_or(self.text, |(_, _, _, piece)| *piece) + } + + pub fn len(&self) -> usize { + self.bits.len() + } + + pub fn is_empty(&self) -> bool { + self.bits.is_empty() + } +} + +pub struct CellSet { + rules: usize, + words: usize, + always: Vec, + strs: HashMap, Vec>, + few: Option>, + scaled: Option<(u32, Vec)>, + bools: [Option>; 2], + null: Option>, + bounds: Vec, + regions: Vec>, + others: Vec, + owners: Vec>, + optimistic: Vec, +} + +impl CellSet { + const FEW: usize = 8; + + fn prefix(text: &[u8]) -> u64 { + text.iter() + .take(7) + .enumerate() + .fold((text.len().min(255) as u64) << 56, |word, (at, byte)| { + word | u64::from(*byte) << (at * 8) + }) + } + + fn text(&self, text: &[u8]) -> Option<&Vec> { + match &self.few { + Some(few) => { + let prefix = Self::prefix(text); + few.iter() + .find(|(p, k, _)| *p == prefix && (text.len() < 8 || k.as_ref() == text)) + .map(|(_, _, v)| v) + } + None => self.strs.get(text), + } + } + + fn scaled_bounds(bounds: &[Decimal]) -> Option<(u32, Vec)> { + let scale = bounds.iter().map(Decimal::scale).max().unwrap_or(0); + if scale > 18 { + return None; + } + bounds + .iter() + .map(|b| { + b.mantissa() + .checked_mul(10i128.checked_pow(scale - b.scale())?) + }) + .collect::>>() + .map(|v| (scale, v)) + } + + fn scaling(&self, scale: u8) -> Option { + let (target, bounds) = self.scaled.as_ref()?; + let (mult, lift) = match (scale as u32).checked_sub(*target) { + None => (10i64.checked_pow(target - scale as u32)?, 1i128), + Some(up) => (1, 10i128.checked_pow(up)?), + }; + let bounds = bounds + .iter() + .map(|b| b.checked_mul(lift).and_then(|b| i64::try_from(b).ok())) + .collect::>>()?; + Some(Scaling { mult, bounds }) + } + + #[inline] + fn scaled_region( + &self, + cached: &mut Vec>>, + (mant, scale): (i64, u8), + ) -> Option { + let at = scale as usize; + if cached.len() <= at { + cached.resize_with(at + 1, || None); + } + let scaling = cached[at] + .get_or_insert_with(|| self.scaling(scale)) + .as_ref()?; + Some(Self::region_of( + &scaling.bounds, + mant.checked_mul(scaling.mult)?, + )) + } + + #[inline] + fn region_of(bounds: &[i64], value: i64) -> usize { + match bounds.len() <= 16 { + true => { + let (mut below, mut equal) = (0usize, false); + for bound in bounds { + below += usize::from(*bound < value); + equal |= *bound == value; + } + below * 2 + usize::from(equal) + } + false => match bounds.binary_search(&value) { + Ok(i) => i * 2 + 1, + Err(i) => i * 2, + }, + } + } + + fn numbers(&self, column: &Column, rows: usize, out: &mut [u64]) -> bool { + let words = self.words; + let parts = |row: usize| -> Option<(i64, u8)> { + match column.values { + Values::Scaled { mant, scale } => Some((*mant.get(row)?, *scale.get(row)?)), + Values::I64(values) => Some((*values.get(row)?, 0)), + Values::Dec(values) => { + let d = values.get(row)?; + Some(( + i64::try_from(d.mantissa()).ok()?, + u8::try_from(d.scale()).ok()?, + )) + } + _ => None, + } + }; + if !matches!( + column.values, + Values::Scaled { .. } | Values::I64(_) | Values::Dec(_) + ) || column.len() < rows + { + return false; + } + if self.regions.is_empty() { + for (row, bits) in out.chunks_exact_mut(words).enumerate().take(rows) { + bits.copy_from_slice(&self.always); + if !column.valid(row) { + if let Some(matched) = &self.null { + Bits::or(bits, matched); + } + } + } + return true; + } + if self.scaled.is_none() { + return false; + } + let mut cached: Vec>> = Vec::new(); + for (row, bits) in out.chunks_exact_mut(words).enumerate().take(rows) { + if !column.valid(row) { + bits.copy_from_slice(&self.always); + if let Some(matched) = &self.null { + Bits::or(bits, matched); + } + continue; + } + let fast = parts(row).and_then(|part| self.scaled_region(&mut cached, part)); + match fast.and_then(|region| self.regions.get(region)) { + Some(region) => bits + .iter_mut() + .zip(self.always.iter().zip(region)) + .for_each(|(b, (a, r))| *b = a | r), + None => self.row_bits(column, row, (true, false, false), bits), + } + } + true + } + + fn set(bits: &mut [u64], rule: usize) { + bits[rule / 64] |= 1 << (rule % 64); + } + + pub fn compile(cells: &[Option<&str>]) -> Result { + let rules = cells.len(); + let words = rules.div_ceil(64).max(1); + let mut always = vec![0u64; words]; + let mut equal: HashMap> = HashMap::default(); + let mut ranges: Vec<(Arc, Vec)> = Vec::new(); + let mut others: Vec<(Arc, Vec)> = Vec::new(); + let mut bounds: Vec = Vec::new(); + + for (rule, cell) in cells.iter().enumerate() { + let source = match cell.map(str::trim) { + None | Some("") => { + Self::set(&mut always, rule); + continue; + } + Some(s) => s, + }; + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let shape = match lexer.tokenize(&bump, source).ok().and_then(|tokens| { + Parser::try_new(&tokens, &bump) + .ok() + .map(|p| p.unary().parse()) + }) { + Some(parsed) if parsed.error().is_ok() => Shape::classify(parsed.root), + _ => Shape::Other, + }; + match shape { + Shape::Equal(keys) => { + for key in keys { + let bits = equal.entry(key).or_insert_with(|| vec![0u64; words]); + Self::set(bits, rule); + } + } + Shape::Range(points) => { + bounds.extend(points); + match ranges.iter_mut().find(|(s, _)| s.as_ref() == source) { + Some((_, r)) => r.push(rule), + None => ranges.push((Arc::from(source), vec![rule])), + } + } + Shape::Other => match others.iter_mut().find(|(s, _)| s.as_ref() == source) { + Some((_, r)) => r.push(rule), + None => others.push((Arc::from(source), vec![rule])), + }, + } + } + + let mut nums: Vec<(Decimal, Vec)> = Vec::new(); + let mut strs: HashMap, Vec> = HashMap::default(); + let mut bools: [Option>; 2] = [None, None]; + let mut null: Option> = None; + for (key, bits) in equal { + match key { + Key::Num(n) => { + bounds.push(n); + nums.push((n, bits)); + } + Key::Str(s) => { + strs.insert(Box::from(s.as_bytes()), bits); + } + Key::Bool(b) => bools[usize::from(b)] = Some(bits), + Key::Null => null = Some(bits), + } + } + + bounds.sort(); + bounds.dedup_by(|a, b| a == b); + let regions = match bounds.is_empty() { + true => Vec::new(), + false => { + let mut isolate = super::Session::new(); + (0..bounds.len() * 2 + 1) + .map(|region| { + let mut bits = vec![0u64; words]; + if !ranges.is_empty() { + let probe = Self::probe(&bounds, region); + isolate.set_environment(Variable::empty_object()); + let _ = isolate.set_reference_value(Variable::Number(probe)); + for (source, rules) in &ranges { + if isolate.run_unary(source).unwrap_or(false) { + rules.iter().for_each(|r| Self::set(&mut bits, *r)); + } + } + } + if region % 2 == 1 { + for (n, matched) in &nums { + if *n == bounds[region / 2] { + Bits::or(&mut bits, matched); + } + } + } + bits + }) + .collect() + } + }; + + let others: Vec = others + .into_iter() + .filter_map(|(source, rules)| { + let mut bits = vec![0u64; words]; + rules.iter().for_each(|r| Self::set(&mut bits, *r)); + LaneProgram::unary(&source).ok().map(|program| Other { + program, + rules: bits, + }) + }) + .collect(); + let mut owners = vec![None; rules]; + let mut optimistic = vec![0u64; words]; + for (index, other) in others.iter().enumerate() { + Bits::or(&mut optimistic, &other.rules); + for (rule, owner) in owners.iter_mut().enumerate() { + if other.rules[rule / 64] >> (rule % 64) & 1 == 1 { + *owner = Some(index); + } + } + } + + Ok(Self { + rules, + words, + always, + few: (strs.len() <= Self::FEW).then(|| { + strs.iter() + .map(|(k, v)| (Self::prefix(k), k.clone(), v.clone())) + .collect() + }), + scaled: Self::scaled_bounds(&bounds), + strs, + bools, + null, + bounds, + regions, + others, + owners, + optimistic, + }) + } + + fn probe(bounds: &[Decimal], region: usize) -> Decimal { + let i = region / 2; + if region % 2 == 1 { + return bounds[i]; + } + match (i.checked_sub(1).map(|j| bounds[j]), bounds.get(i)) { + (None, Some(b)) => b.checked_sub(Decimal::ONE).unwrap_or(*b), + (Some(a), None) => a.checked_add(Decimal::ONE).unwrap_or(a), + (Some(a), Some(b)) => b + .checked_sub(a) + .and_then(|gap| a.checked_add(gap / Decimal::TWO)) + .filter(|m| a < *m && *m < *b) + .unwrap_or_else(|| a / Decimal::TWO + *b / Decimal::TWO), + (None, None) => Decimal::ZERO, + } + } + + pub fn rules(&self) -> usize { + self.rules + } + + pub fn words(&self) -> usize { + self.words + } + + pub fn evaluate( + &self, + runner: &mut LaneRunner, + values: &[Variable], + envs: &[Scope], + out: &mut Vec, + ) { + let columns = Columns::new(values.len()); + let env = CellEnv { + scopes: envs, + columns: &columns, + bind: &|_| Binding::Row, + }; + self.evaluate_within(runner, values, &env, None, out) + } + + pub fn programs(&self) -> impl Iterator { + self.others.iter().map(|o| &o.program) + } + + pub fn scopes(values: &[Variable], env: &CellEnv) -> Vec { + values + .iter() + .enumerate() + .map(|(row, value)| Self::scope(value, env.scopes.get(row))) + .collect() + } + + fn run( + program: &LaneProgram, + runner: &mut LaneRunner, + scopes: &[Scope], + env: &CellEnv, + rows: &[usize], + mut sink: impl FnMut(usize, Option), + ) { + runner.evaluate_bound( + program, + scopes, + env.columns, + env.bind, + Some(rows), + |row, result| { + sink( + row, + result + .ok() + .map(|values| matches!(values.as_slice(), [Variable::Bool(true)])), + ) + }, + ); + } + + pub fn evaluate_within( + &self, + runner: &mut LaneRunner, + values: &[Variable], + env: &CellEnv, + within: Option<&[u64]>, + out: &mut Vec, + ) { + let words = self.words; + self.indexed(values, out); + if self.others.is_empty() { + return; + } + let scopes = Self::scopes(values, env); + for other in &self.others { + let rows: Vec = match within { + None => (0..values.len()).collect(), + Some(mask) => (0..values.len()) + .filter(|&row| { + mask[row * words..(row + 1) * words] + .iter() + .zip(&other.rules) + .any(|(m, r)| m & r != 0) + }) + .collect(), + }; + if rows.is_empty() { + continue; + } + Self::run(&other.program, runner, &scopes, env, &rows, |row, pass| { + if pass == Some(true) { + Bits::or(&mut out[row * words..(row + 1) * words], &other.rules); + } + }); + } + } + + pub fn test( + &self, + runner: &mut LaneRunner, + other: usize, + scopes: &[Scope], + env: &CellEnv, + rows: &[usize], + mut sink: impl FnMut(usize, Option), + ) { + let Some(other) = self.others.get(other) else { + rows.iter().for_each(|&row| sink(row, Some(false))); + return; + }; + Self::run(&other.program, runner, scopes, env, rows, sink); + } + + fn matched(&self, value: &Variable) -> Option<&Vec> { + match value { + Variable::String(s) => self.text(s.as_bytes()), + Variable::Bool(b) => self.bools[usize::from(*b)].as_ref(), + Variable::Null => self.null.as_ref(), + _ => None, + } + } + + fn dated(&self, value: &Variable, bits: &mut [u64]) { + let Variable::Dynamic(dynamic) = value else { + return; + }; + let Some(date) = dynamic.as_date() else { + return; + }; + let keys: Box)>> = match &self.few { + Some(few) => Box::new(few.iter().map(|(_, k, v)| (k.as_ref(), v))), + None => Box::new(self.strs.iter().map(|(k, v)| (k.as_ref(), v))), + }; + for (key, matched) in keys { + let text = Variable::String(String::from_utf8_lossy(key).as_ref().into()); + if date.matches(&text) { + Bits::or(bits, matched); + } + } + } + + fn region_at(&self, n: &Decimal) -> usize { + match self.bounds.binary_search(n) { + Ok(i) => i * 2 + 1, + Err(i) => i * 2, + } + } + + fn region(&self, n: &Decimal) -> Option<&Vec> { + self.regions.get(self.region_at(n)) + } + + pub fn indexed_column(&self, column: &Column, rows: usize, out: &mut Vec) { + let words = self.words; + out.clear(); + out.resize(rows * words, 0); + let numeric = matches!(column.kind(), Kind::Num); + let text = matches!(column.kind(), Kind::Str); + let boolean = matches!(column.values, Values::Bool { .. }); + if column.is_empty() && rows > 0 { + let (first, rest) = out.split_at_mut(words); + self.row_bits(column, 0, (numeric, text, boolean), first); + rest.chunks_exact_mut(words) + .for_each(|chunk| chunk.copy_from_slice(first)); + return; + } + if let Values::Dict { keys, values } = column.values { + let dictionary = values.column(); + let size = dictionary.len(); + if keys.len() >= rows && size <= rows.saturating_mul(2) + 64 { + let mut table = Vec::new(); + self.indexed_column(&dictionary, size, &mut table); + for (row, bits) in out.chunks_exact_mut(words).enumerate() { + let code = usize::try_from(keys[row]).ok().filter(|&c| c < size); + match (column.valid(row), code) { + (true, Some(code)) => { + bits.copy_from_slice(&table[code * words..(code + 1) * words]) + } + _ => self.row_bits(column, row, (numeric, text, boolean), bits), + } + } + return; + } + } + if numeric && self.numbers(column, rows, out) { + return; + } + if words == 1 && self.indexed_word(column, rows, out) { + return; + } + for row in 0..rows { + self.row_bits( + column, + row, + (numeric, text, boolean), + &mut out[row * words..(row + 1) * words], + ); + } + } + + fn indexed_word(&self, column: &Column, rows: usize, out: &mut [u64]) -> bool { + let always = self.always[0]; + let null = self.null.as_ref().map_or(0, |m| m[0]); + let word = |matched: Option<&Vec>| matched.map_or(0, |m| m[0]); + let texts = |offsets: &[i32], data: &[u8], out: &mut [u64]| { + for (row, bits) in out.iter_mut().enumerate().take(rows) { + *bits = always + | match column.valid(row) { + false => null, + true => { + let (a, b) = (offsets[row] as usize, offsets[row + 1] as usize); + word(data.get(a..b).and_then(|t| self.text(t))) + } + }; + } + }; + match column.values { + Values::Bool { bits, offset } => { + let on = word(self.bools[1].as_ref()); + let off = word(self.bools[0].as_ref()); + for (row, out) in out.iter_mut().enumerate().take(rows) { + *out = always + | match column.valid(row) { + false => null, + true => match bits + .get((offset + row) / 64) + .map(|w| w >> ((offset + row) % 64) & 1 == 1) + { + Some(true) => on, + Some(false) => off, + None => 0, + }, + }; + } + } + Values::Text { offsets, data } if offsets.len() > rows => { + texts(offsets, data.as_bytes(), out) + } + Values::Utf8 { offsets, data } if offsets.len() > rows => texts(offsets, data, out), + _ => return false, + } + true + } + + fn row_bits( + &self, + column: &Column, + row: usize, + (numeric, text, boolean): (bool, bool, bool), + bits: &mut [u64], + ) { + bits.copy_from_slice(&self.always); + if !column.valid(row) { + if let Some(matched) = &self.null { + Bits::or(bits, matched); + } + return; + } + match (numeric, text, boolean) { + (true, _, _) => { + let Some(n) = column.number(row) else { + if let Some(matched) = &self.null { + Bits::or(bits, matched); + } + return; + }; + if let Some(region) = self.region(&n) { + Bits::or(bits, region); + } + } + (_, true, _) => { + let matched = match column.bytes(row) { + Some(text) => self.text(text), + None => self.null.as_ref(), + }; + if let Some(matched) = matched { + Bits::or(bits, matched); + } + } + (_, _, true) => { + if let Some(matched) = column + .boolean(row) + .and_then(|b| self.bools[usize::from(b)].as_ref()) + { + Bits::or(bits, matched); + } + } + _ => { + let value = column.variable(row); + if let Some(matched) = self.matched(&value) { + Bits::or(bits, matched); + } + self.dated(&value, bits); + if let Variable::Number(n) = &value { + if let Some(region) = self.region(n) { + Bits::or(bits, region); + } + } + } + } + } + + pub fn pieces(&self, empty: &[u64]) -> Option { + if !self.others.is_empty() || self.strs.len() > 64 { + return None; + } + let mut bits: Vec> = Vec::new(); + let with = |extra: Option<&Vec>| { + let mut piece = self.always.clone(); + if let Some(extra) = extra { + Bits::or(&mut piece, extra); + } + piece + }; + let null = Pieces::intern(&mut bits, with(self.null.as_ref())); + let truth = [ + Pieces::intern(&mut bits, with(self.bools[0].as_ref())), + Pieces::intern(&mut bits, with(self.bools[1].as_ref())), + ]; + let keys = self + .strs + .iter() + .map(|(key, matched)| { + let piece = Pieces::intern(&mut bits, with(Some(matched))); + (ShortKey::of(key), key.len(), key.clone(), piece) + }) + .collect(); + let text = Pieces::intern(&mut bits, with(None)); + let regions = self + .regions + .iter() + .map(|r| Pieces::intern(&mut bits, with(Some(r)))) + .collect(); + let other = text; + let failed = Pieces::intern(&mut bits, empty.to_vec()); + Some(Pieces { + bits, + null, + truth, + keys, + text, + regions, + other, + failed, + }) + } + + fn piece_of(&self, pieces: &Pieces, value: &Variable) -> u32 { + match value { + Variable::Null => pieces.null, + Variable::Bool(b) => pieces.truth[usize::from(*b)], + Variable::String(s) => pieces.text(s.as_bytes()), + Variable::Number(n) => self.number_piece(pieces, n), + Variable::Dynamic(dynamic) => match dynamic.as_date() { + Some(date) => pieces + .keys + .iter() + .find(|(_, _, key, _)| { + date.matches(&Variable::String( + String::from_utf8_lossy(key).as_ref().into(), + )) + }) + .map_or(pieces.other, |(_, _, _, piece)| *piece), + None => pieces.other, + }, + _ => pieces.other, + } + } + + fn number_piece(&self, pieces: &Pieces, n: &Decimal) -> u32 { + pieces + .regions + .get(self.region_at(n)) + .copied() + .unwrap_or(pieces.other) + } + + fn numbers_into( + &self, + pieces: &Pieces, + column: &Column, + parts: impl Iterator>, + out: &mut [u32], + ) { + if pieces.regions.is_empty() { + for (row, piece) in out.iter_mut().enumerate() { + *piece = match column.valid(row) { + true => pieces.other, + false => pieces.null, + }; + } + return; + } + let mut cached: Vec>> = Vec::new(); + for ((row, piece), part) in out.iter_mut().enumerate().zip(parts) { + if !column.valid(row) { + *piece = pieces.null; + continue; + } + let fast = part.and_then(|part| self.scaled_region(&mut cached, part)); + *piece = match fast { + Some(region) => pieces.regions.get(region).copied().unwrap_or(pieces.other), + None => match column.number(row) { + Some(n) => self.number_piece(pieces, &n), + None => pieces.null, + }, + }; + } + } + + pub fn classify(&self, pieces: &Pieces, column: &Column, rows: usize, out: &mut [u32]) { + let out = &mut out[..rows]; + if column.is_empty() { + out.fill(pieces.null); + return; + } + match column.values { + Values::Text { offsets, data } if offsets.len() > rows => { + let data = data.as_bytes(); + for (row, (piece, pair)) in out.iter_mut().zip(offsets.windows(2)).enumerate() { + *piece = match column.valid(row) { + false => pieces.null, + true => match data.get(pair[0] as usize..pair[1] as usize) { + Some(text) => pieces.text(text), + None => pieces.text, + }, + }; + } + } + Values::Text { .. } + | Values::Utf8 { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) => { + for (row, piece) in out.iter_mut().enumerate() { + *piece = match (column.valid(row), column.bytes(row)) { + (true, Some(text)) => pieces.text(text), + (true, None) => pieces.text, + (false, _) => pieces.null, + }; + } + } + Values::Bool { bits, offset } => { + for (row, piece) in out.iter_mut().enumerate() { + *piece = match column.valid(row) { + true => { + pieces.truth[usize::from( + bits.get((offset + row) / 64) + .is_some_and(|w| w >> ((offset + row) % 64) & 1 == 1), + )] + } + false => pieces.null, + }; + } + } + Values::Scaled { mant, scale } if mant.len() >= rows && scale.len() >= rows => self + .numbers_into( + pieces, + column, + mant.iter().zip(scale).map(|(m, s)| Some((*m, *s))), + out, + ), + Values::I64(values) if values.len() >= rows => { + self.numbers_into(pieces, column, values.iter().map(|v| Some((*v, 0u8))), out) + } + Values::Dec(values) if values.len() >= rows => self.numbers_into( + pieces, + column, + values.iter().map(|d| { + Some(( + i64::try_from(d.mantissa()).ok()?, + u8::try_from(d.scale()).ok()?, + )) + }), + out, + ), + Values::Dict { keys, values } => { + let dictionary = values.column(); + let size = dictionary.len(); + let mut coded = vec![0u32; size]; + self.classify(pieces, &dictionary, size, &mut coded); + for (row, piece) in out.iter_mut().enumerate() { + let code = keys + .get(row) + .and_then(|k| usize::try_from(*k).ok()) + .filter(|c| *c < size); + *piece = match (column.valid(row), code) { + (true, Some(code)) => coded[code], + _ => pieces.null, + }; + } + } + _ => { + for (row, piece) in out.iter_mut().enumerate() { + *piece = self.piece_of(pieces, &column.variable(row)); + } + } + } + } + + pub fn evaluate_indexed_column(&self, column: &Column, rows: usize, out: &mut Vec) { + self.indexed_column(column, rows, out); + for row in 0..rows { + Bits::or( + &mut out[row * self.words..(row + 1) * self.words], + &self.optimistic, + ); + } + } + + pub fn peelable(&self) -> bool { + self.others.iter().all(|other| { + let p = other.program.program(); + !p.opaque() + && !p.writes_env + && p.site_keys.iter().all(|key| key.as_deref() == Some("$")) + }) + } + + pub fn others(&self) -> usize { + self.others.len() + } + + pub fn other(&self, index: usize) -> Option<(&LaneProgram, &[u64])> { + self.others + .get(index) + .map(|other| (&other.program, other.rules.as_slice())) + } + + pub fn owner(&self, rule: usize) -> Option { + self.owners.get(rule).copied().flatten() + } + + pub fn evaluate_indexed(&self, values: &[Variable], out: &mut Vec) { + self.indexed(values, out); + for row in 0..values.len() { + Bits::or( + &mut out[row * self.words..(row + 1) * self.words], + &self.optimistic, + ); + } + } + + fn scope(value: &Variable, env: Option<&Scope>) -> Scope { + let mut scope = Scope::new(env.map_or(Variable::Null, |e| e.base().clone())); + if let Some(env) = env { + for (k, v) in env.locals() { + scope.set_local(k.clone(), v.clone()); + } + } + scope.set_local(Variable::dollar_key(), value.clone()); + scope + } + + fn indexed(&self, values: &[Variable], out: &mut Vec) { + self.indexed_column(&Column::new(Values::Any(values)), values.len(), out); + } +} diff --git a/core/expression/src/lane/columns.rs b/core/expression/src/lane/columns.rs new file mode 100644 index 00000000..2227655c --- /dev/null +++ b/core/expression/src/lane/columns.rs @@ -0,0 +1,631 @@ +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::program::{Binding, Kind}; +use crate::lane::Bits; +use crate::variable::Variable; +use rust_decimal::prelude::FromPrimitive; +use rust_decimal::Decimal; +use std::str::FromStr; +use zen_types::path::DotPath; + +#[derive(Debug, Clone, Copy)] +pub enum Values<'a> { + Dec(&'a [Decimal]), + Scaled { + mant: &'a [i64], + scale: &'a [u8], + }, + I64(&'a [i64]), + F64(&'a [f64]), + Bool { + bits: &'a [u64], + offset: usize, + }, + Utf8 { + offsets: &'a [i32], + data: &'a [u8], + }, + Text { + offsets: &'a [i32], + data: &'a str, + }, + LargeUtf8 { + offsets: &'a [i64], + data: &'a [u8], + }, + Strs(&'a [&'a str]), + Dict { + keys: &'a [i32], + values: Dictionary<'a>, + }, + List { + offsets: &'a [i32], + child: Dictionary<'a>, + }, + Struct { + fields: &'a [(&'a str, Column<'a>)], + len: usize, + }, + Any(&'a [Variable]), +} + +#[derive(Debug, Clone, Copy)] +pub enum Dictionary<'a> { + Column(&'a Column<'a>), + Text { offsets: &'a [i32], data: &'a str }, + Scaled { mant: &'a [i64], scale: &'a [u8] }, + Bool { bits: &'a [u64] }, + Any(&'a [Variable]), +} + +impl<'a> From<&'a Column<'a>> for Dictionary<'a> { + fn from(column: &'a Column<'a>) -> Self { + Dictionary::Column(column) + } +} + +impl<'a> Dictionary<'a> { + pub fn column(self) -> Column<'a> { + match self { + Dictionary::Column(column) => *column, + Dictionary::Text { offsets, data } => Column::new(Values::Text { offsets, data }), + Dictionary::Scaled { mant, scale } => Column::new(Values::Scaled { mant, scale }), + Dictionary::Bool { bits } => Column::new(Values::Bool { bits, offset: 0 }), + Dictionary::Any(values) => Column::new(Values::Any(values)), + } + } + + pub fn len(self) -> usize { + self.column().len() + } + + pub fn is_empty(self) -> bool { + self.len() == 0 + } + + pub fn kind(self) -> Kind { + self.column().kind() + } + + pub fn valid(self, row: usize) -> bool { + self.column().valid(row) + } + + pub fn number(self, row: usize) -> Option { + self.column().number(row) + } + + pub fn boolean(self, row: usize) -> Option { + self.column().boolean(row) + } + + pub fn text(self, row: usize) -> Option<&'a str> { + self.column().text(row) + } + + pub fn variable(self, row: usize) -> Variable { + self.column().variable(row) + } + + pub fn equals(self, row: usize, k: &Variable) -> bool { + self.column().equals(row, k) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Column<'a> { + pub values: Values<'a>, + pub validity: Option<(&'a [u64], usize)>, +} + +impl<'a> Column<'a> { + pub fn new(values: Values<'a>) -> Self { + Self { + values, + validity: None, + } + } + + pub fn with_validity(values: Values<'a>, bits: &'a [u64], offset: usize) -> Self { + Self { + values, + validity: Some((bits, offset)), + } + } + + pub fn kind(&self) -> Kind { + match self.values { + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => Kind::Num, + Values::Bool { .. } => Kind::Bool, + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) => Kind::Str, + Values::Dict { values, .. } => values.kind(), + Values::List { child, .. } => match child.column().values { + Values::Scaled { .. } + | Values::Text { .. } + | Values::Bool { .. } + | Values::Utf8 { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) + | Values::I64(_) + | Values::Dec(_) + if child.column().validity.is_none() => + { + Kind::List + } + _ => Kind::Dyn, + }, + Values::Struct { .. } | Values::Any(_) => Kind::Dyn, + } + } + + pub(crate) fn valid_mask(&self, start: usize, width: usize) -> M { + match self.validity { + None => M::all(width), + Some((bits, offset)) => Self::mask(bits, offset + start, width), + } + } + + pub(crate) fn mask(bits: &[u64], at: usize, width: usize) -> M { + let mut mask = M::none(width); + for i in 0..width.div_ceil(64) { + let take = (width - i * 64).min(64); + mask.set_word(i, Bits::word(bits, at + i * 64, take)); + } + mask + } + + #[inline] + pub fn range(&self, row: usize) -> Option<(usize, usize)> { + let Values::List { offsets, .. } = self.values else { + return None; + }; + match (self.valid(row), offsets.get(row), offsets.get(row + 1)) { + (true, Some(a), Some(b)) => { + let a = usize::try_from(*a).unwrap_or(0); + Some((a, usize::try_from(*b).unwrap_or(0).max(a))) + } + _ => None, + } + } + + #[inline] + pub fn valid(&self, row: usize) -> bool { + match self.validity { + None => true, + Some((bits, offset)) => Bits::get(bits, offset + row), + } + } + + #[inline] + pub fn code(&self, row: usize) -> Option { + match self.values { + Values::Dict { keys, .. } => keys.get(row).and_then(|k| usize::try_from(*k).ok()), + _ => None, + } + } + + pub fn len(&self) -> usize { + match self.values { + Values::Dec(v) => v.len(), + Values::Scaled { mant, .. } => mant.len(), + Values::I64(v) => v.len(), + Values::F64(v) => v.len(), + Values::Bool { bits, offset } => (bits.len() * 64).saturating_sub(offset), + Values::Utf8 { offsets, .. } => offsets.len().saturating_sub(1), + Values::Text { offsets, .. } => offsets.len().saturating_sub(1), + Values::LargeUtf8 { offsets, .. } => offsets.len().saturating_sub(1), + Values::Strs(v) => v.len(), + Values::Dict { keys, .. } => keys.len(), + Values::List { offsets, .. } => offsets.len().saturating_sub(1), + Values::Struct { len, .. } => len, + Values::Any(v) => v.len(), + } + } + + pub fn field(&self, name: &str) -> Option<&'a Column<'a>> { + match self.values { + Values::Struct { fields, .. } => { + fields.iter().find(|(n, _)| *n == name).map(|(_, c)| c) + } + _ => None, + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline] + pub fn number(&self, row: usize) -> Option { + match self.values { + Values::Dec(v) => v.get(row).copied(), + Values::Scaled { mant, scale } => { + Some(Decimal::new(*mant.get(row)?, *scale.get(row)? as u32)) + } + Values::I64(v) => v.get(row).map(|n| Decimal::from(*n)), + Values::F64(v) => v.get(row).and_then(|f| Self::float(*f)), + Values::Dict { values, .. } => { + let code = self.code(row)?; + values.valid(code).then(|| values.number(code)).flatten() + } + Values::Any(v) => match v.get(row) { + Some(Variable::Number(n)) => Some(*n), + _ => None, + }, + _ => None, + } + } + + fn float(f: f64) -> Option { + if !f.is_finite() { + return None; + } + let mut buffer = [0u8; 512]; + let mut cursor = std::io::Cursor::new(&mut buffer[..]); + let written = std::io::Write::write_fmt(&mut cursor, format_args!("{f}")).is_ok(); + let len = cursor.position() as usize; + written + .then(|| std::str::from_utf8(&buffer[..len]).ok()) + .flatten() + .and_then(|text| Decimal::from_str(text).ok()) + .or_else(|| Decimal::from_f64(f)) + } + + #[inline] + pub fn boolean(&self, row: usize) -> Option { + match self.values { + Values::Bool { bits, offset } => Some(Bits::get(bits, offset + row)), + Values::Dict { values, .. } => { + let code = self.code(row)?; + values.valid(code).then(|| values.boolean(code)).flatten() + } + _ => None, + } + } + + pub(crate) fn texts(&self, base: usize, n: usize) -> Option> { + match self.values { + Values::Utf8 { offsets, data } => { + let window = offsets.get(base..=base + n)?; + let (first, last) = (*window.first()? as usize, *window.last()? as usize); + window.windows(2).all(|w| w[0] <= w[1]).then_some(())?; + let block = std::str::from_utf8(data.get(first..last)?).ok()?; + Some(Texts::Utf8(block, window, first)) + } + Values::Text { offsets, data } => { + let window = offsets.get(base..=base + n)?; + let (first, last) = (*window.first()? as usize, *window.last()? as usize); + window.windows(2).all(|w| w[0] <= w[1]).then_some(())?; + Some(Texts::Utf8(data.get(first..last)?, window, first)) + } + Values::LargeUtf8 { offsets, data } => { + let window = offsets.get(base..=base + n)?; + let (first, last) = (*window.first()? as usize, *window.last()? as usize); + window.windows(2).all(|w| w[0] <= w[1]).then_some(())?; + let block = std::str::from_utf8(data.get(first..last)?).ok()?; + Some(Texts::Large(block, window, first)) + } + Values::Strs(v) => v.get(base..base + n).map(Texts::Strs), + _ => None, + } + } + + pub fn bytes(&self, row: usize) -> Option<&'a [u8]> { + match self.values { + Values::Utf8 { offsets, data } => { + let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize); + data.get(a..b) + } + Values::Text { offsets, data } => { + let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize); + data.as_bytes().get(a..b) + } + Values::LargeUtf8 { offsets, data } => { + let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize); + data.get(a..b) + } + _ => self.text(row).map(str::as_bytes), + } + } + + #[inline] + pub fn parts(&self, row: usize) -> Option<(i64, u8)> { + match self.values { + Values::Scaled { mant, scale } => Some((*mant.get(row)?, *scale.get(row)?)), + Values::I64(v) => Some((*v.get(row)?, 0)), + Values::Dec(v) => crate::lane::Scaled::parts(v.get(row)?), + Values::Dict { + keys, + values: Dictionary::Scaled { mant, scale }, + } => { + let code = usize::try_from(*keys.get(row)?).ok()?; + Some((*mant.get(code)?, *scale.get(code)?)) + } + _ => None, + } + } + + pub fn scaled(&self, row: usize) -> Option<(i128, u32)> { + match self.values { + Values::Scaled { mant, scale } => { + Some((*mant.get(row)? as i128, *scale.get(row)? as u32)) + } + Values::I64(v) => Some((*v.get(row)? as i128, 0)), + Values::Dec(v) => v.get(row).map(|d| (d.mantissa(), d.scale())), + _ => None, + } + } + + pub fn text(&self, row: usize) -> Option<&'a str> { + match self.values { + Values::Utf8 { offsets, data } => { + let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize); + std::str::from_utf8(data.get(a..b)?).ok() + } + Values::Text { offsets, data } => { + let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize); + data.get(a..b) + } + Values::LargeUtf8 { offsets, data } => { + let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize); + std::str::from_utf8(data.get(a..b)?).ok() + } + Values::Strs(v) => v.get(row).copied(), + Values::Dict { values, .. } => { + let code = self.code(row)?; + values.valid(code).then(|| values.text(code)).flatten() + } + _ => None, + } + } + + pub fn equals(&self, row: usize, k: &Variable) -> bool { + if !self.valid(row) { + return matches!(k, Variable::Null); + } + match (self.values, k) { + ( + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_), + Variable::Number(n), + ) => self + .number(row) + .is_some_and(|m| crate::lane::ops::Ops::same_number(&m, n)), + ( + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_), + Variable::Null, + ) => self.number(row).is_none(), + (Values::Bool { .. }, Variable::Bool(b)) => self.boolean(row) == Some(*b), + ( + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_), + Variable::String(s), + ) => self.bytes(row) == Some(s.as_bytes()), + (Values::Any(v), k) => v + .get(row) + .is_some_and(|v| crate::lane::ops::Ops::equal(v, k)), + (Values::Dict { values, .. }, k) => { + self.code(row).is_some_and(|code| values.equals(code, k)) + } + (Values::List { .. }, _) => false, + _ => false, + } + } + + pub fn borrowed(&self, row: usize) -> Option<&'a Variable> { + if !self.valid(row) { + return None; + } + match self.values { + Values::Any(values) => values.get(row), + Values::Dict { + values: Dictionary::Any(values), + .. + } => values.get(self.code(row)?), + _ => None, + } + } + + pub fn variable(&self, row: usize) -> Variable { + if !self.valid(row) { + return Variable::Null; + } + match self.values { + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => { + self.number(row).map_or(Variable::Null, Variable::Number) + } + Values::Bool { .. } => self.boolean(row).map_or(Variable::Null, Variable::Bool), + Values::Any(v) => v.get(row).cloned().unwrap_or(Variable::Null), + Values::Dict { values, .. } => self + .code(row) + .map_or(Variable::Null, |code| values.variable(code)), + Values::List { child, .. } => { + let items = self + .range(row) + .map(|(a, b)| (a..b).map(|i| child.variable(i)).collect()) + .unwrap_or_default(); + Variable::from_array(items) + } + Values::Struct { fields, .. } => { + let mut map = zen_types::variable::VariableMap::with_capacity(fields.len()); + for (name, column) in fields { + let value = column.variable(row); + if !matches!(value, Variable::Null) || column.valid(row) { + map.insert(zen_types::symbol::Symbol::from(*name), value); + } + } + Variable::from_object(map) + } + _ => self + .text(row) + .map_or(Variable::Null, |s| Variable::String(s.into())), + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct Columns<'a> { + pub rows: usize, + pub columns: Vec<(&'a str, Column<'a>)>, +} + +impl<'a> Columns<'a> { + pub fn new(rows: usize) -> Self { + Self { + rows, + columns: Vec::new(), + } + } + + pub fn column(mut self, path: &'a str, column: Column<'a>) -> Self { + self.columns.push((path, column)); + self + } + + pub fn find(&self, path: &str) -> Option { + self.columns.iter().rposition(|(p, _)| *p == path) + } + + pub fn bind(&self, path: &str) -> Binding { + let covered = self.columns.iter().any(|(p, _)| DotPath::nested(p, path)); + match (covered, self.find(path)) { + (true, _) => Binding::Row, + (false, Some(i)) => Binding::Column(i), + (false, None) => Binding::Absent, + } + } + + pub fn row_of(&self, roots: &[std::sync::Arc], row: usize) -> Variable { + let object = Variable::empty_object(); + for (path, column) in &self.columns { + let wanted = roots.iter().any(|root| { + path.strip_prefix(root.as_ref()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.')) + }); + if !wanted { + continue; + } + let nested = matches!(column.values, Values::Any(_)) + && self + .columns + .iter() + .any(|(other, _)| DotPath::under(other, path)); + let value = match nested { + true => column.variable(row).depth_clone(usize::MAX), + false => column.variable(row), + }; + if !matches!(value, Variable::Null) || column.valid(row) { + object.dot_insert(path, value); + } + } + object + } + + pub fn row(&self, row: usize) -> Variable { + let object = Variable::empty_object(); + for (path, column) in &self.columns { + let value = match column.values { + Values::Any(_) => column.variable(row).depth_clone(usize::MAX), + _ => column.variable(row), + }; + if !matches!(value, Variable::Null) || column.valid(row) { + object.dot_insert(path, value); + } + } + object + } +} + +pub(crate) enum Texts<'a> { + Utf8(&'a str, &'a [i32], usize), + Large(&'a str, &'a [i64], usize), + Strs(&'a [&'a str]), +} + +impl<'a> Texts<'a> { + #[inline] + pub(crate) fn each_bytes(&self, lanes: M, mut f: impl FnMut(usize, &'a [u8])) { + match self { + Texts::Utf8(block, offsets, first) => { + let block = block.as_bytes(); + for lane in Lanes::of(lanes) { + let range = offsets + .get(lane) + .zip(offsets.get(lane + 1)) + .and_then(|(a, b)| { + (*a as usize) + .checked_sub(*first) + .zip((*b as usize).checked_sub(*first)) + }); + if let Some(x) = range.and_then(|(a, b)| block.get(a..b)) { + f(lane, x); + } + } + } + Texts::Large(block, offsets, first) => { + let block = block.as_bytes(); + for lane in Lanes::of(lanes) { + let range = offsets + .get(lane) + .zip(offsets.get(lane + 1)) + .and_then(|(a, b)| { + (*a as usize) + .checked_sub(*first) + .zip((*b as usize).checked_sub(*first)) + }); + if let Some(x) = range.and_then(|(a, b)| block.get(a..b)) { + f(lane, x); + } + } + } + Texts::Strs(v) => { + for lane in Lanes::of(lanes) { + if let Some(x) = v.get(lane) { + f(lane, x.as_bytes()); + } + } + } + } + } +} + +#[cfg(test)] +mod float_tests { + use super::Column; + use rust_decimal::prelude::FromPrimitive; + use rust_decimal::Decimal; + use std::str::FromStr; + + #[test] + fn stack_formatting_matches_heap_formatting() { + let mut state = 0xBB67AE8584CAA73Bu64; + for i in 0..300_000u64 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let f = match i % 4 { + 0 => f64::from_bits(state), + 1 => (state % 10_000_000) as f64 / 100.0, + 2 => (state as i64 as f64) * 1e-30, + _ => f64::from_bits(state % 0x0010_0000_0000_0000), + }; + let expected = f + .is_finite() + .then(|| { + Decimal::from_str(&format!("{f}")) + .ok() + .or_else(|| Decimal::from_f64(f)) + }) + .flatten(); + let got = Column::float(f); + assert_eq!( + got.map(|d| d.serialize()), + expected.map(|d| d.serialize()), + "{f:e}" + ); + } + } +} diff --git a/core/expression/src/lane/compile.rs b/core/expression/src/lane/compile.rs new file mode 100644 index 00000000..f1a997ad --- /dev/null +++ b/core/expression/src/lane/compile.rs @@ -0,0 +1,2321 @@ +use crate::compiler::{Compare, CompilerError, FetchFastTarget}; +use crate::functions::registry::FunctionRegistry; +use crate::functions::{ClosureFunction, FunctionKind, InternalFunction, MethodRegistry}; +use crate::intellisense::type_provider::TypesProvider; +use crate::lane::date::Date; +use crate::lane::effect::{Effect, Literal}; +use crate::lane::ops::Ops; +use crate::lane::program::{ + Binary, ClosureOp, Const, FoldOp, Input, Kind, Layout, Load, LoadCall, MaskId, NumCmp, NumOp, + ObjectKey, Op, Operand, Program, Reg, Step, Subject, SwitchOp, +}; +use crate::lexer::{ArithmeticOperator, ComparisonOperator, LogicalOperator, Operator}; +use crate::parser::Node; +use crate::variable::{Variable, VariableType}; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; +use std::sync::Arc; +use zen_types::path::DotPath; + +type Result = std::result::Result; + +#[derive(Default)] +struct Builder { + program: Program, + free: [Vec; 6], + pinned: Vec, + fixed: Vec, + mask: MaskId, + imports: Vec<(Reg, Reg)>, + element_key: Option, +} + +impl Builder { + fn alloc(&mut self, kind: Kind) -> Reg { + match self.free[kind as usize].pop() { + Some(r) => r, + None => self.fresh(kind), + } + } + + fn fresh(&mut self, kind: Kind) -> Reg { + self.program.regs += 1; + self.program.kinds.push(kind); + self.program.regs - 1 + } + + fn kind(&self, r: Reg) -> Kind { + self.program.kinds[r as usize] + } + + fn pin(&mut self, kind: Kind) -> Reg { + let r = self.fresh(kind); + self.pinned.push(r); + self.fixed.push(r); + r + } + + fn seal(mut self) -> Program { + self.program.pinned = vec![false; self.program.regs as usize]; + for r in &self.pinned { + self.program.pinned[*r as usize] = true; + } + self.program.fixed = vec![false; self.program.regs as usize]; + for r in &self.fixed { + self.program.fixed[*r as usize] = true; + } + self.program + } + + fn release(&mut self, r: Reg) { + let free = &mut self.free[self.program.kinds[r as usize] as usize]; + if !self.pinned.contains(&r) && !free.contains(&r) { + free.push(r); + } + } + + fn mask(&mut self) -> MaskId { + self.program.masks += 1; + self.program.masks + } + + fn emit(&mut self, op: Op) { + self.program.steps.push(Step { + mask: self.mask, + op, + }); + } +} + +pub type Hints = ahash::HashMap; + +pub struct LaneCompiler<'a> { + stack: Vec, + aliases: Vec>, + writes_env: bool, + hints: Option<&'a Hints>, + types: Option<&'a TypesProvider>, + keys: Vec, + site_keys: Vec>, + shared: Option>, + dollar: Option>, + named: Option>, + folding: bool, + pure: ahash::HashMap, + assigning: ahash::HashMap, + unresolved: bool, + indexing: bool, +} + +impl<'a> LaneCompiler<'a> { + pub fn compile(root: &'a Node<'a>) -> Result { + Self::compile_with(root, None) + } + + pub fn compile_with(root: &'a Node<'a>, hints: Option<&'a Hints>) -> Result { + Self::compile_typed(root, hints, None) + } + + pub(crate) fn compile_typed( + root: &'a Node<'a>, + hints: Option<&'a Hints>, + types: Option<&'a TypesProvider>, + ) -> Result { + Self::build(root, hints, types, false) + } + + fn build( + root: &'a Node<'a>, + hints: Option<&'a Hints>, + types: Option<&'a TypesProvider>, + folding: bool, + ) -> Result { + let mut compiler = LaneCompiler { + stack: vec![Builder::default()], + aliases: Vec::new(), + writes_env: false, + hints, + types, + keys: Vec::new(), + site_keys: Vec::new(), + shared: None, + dollar: None, + named: None, + folding, + pure: Default::default(), + assigning: Default::default(), + unresolved: false, + indexing: false, + }; + let (out, layout) = match Self::shaped(root) { + true => { + let layout = compiler.layout(root, &mut Vec::new())?; + (Reg::default(), Some(layout)) + } + false => (compiler.node(root)?, None), + }; + let mut builder = compiler.stack.pop().unwrap_or_default(); + builder.program.out = out; + builder.program.layout = layout; + builder.program.writes_env = compiler.writes_env; + let mut program = builder.seal(); + program.keys = compiler.keys; + let sites = compiler.site_keys.len() as u32; + program.site_keys = compiler.site_keys; + program.finish(sites); + Ok(program) + } + + fn shaped(node: &Node) -> bool { + match node { + Node::Array(_) => true, + Node::Object(pairs) => { + let keys: Vec<&str> = pairs + .iter() + .filter_map(|(k, _)| match k { + Node::String(k) => Some(*k), + _ => None, + }) + .collect(); + keys.len() == pairs.len() + && keys.iter().enumerate().all(|(i, k)| !keys[..i].contains(k)) + } + _ => false, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn layout(&mut self, node: &'a Node<'a>, used: &mut Vec) -> Result { + if !Self::shaped(node) { + let reg = self.node(node)?; + let reg = match !self.top().pinned.contains(®) && used.contains(®) { + true => { + let kind = self.top().kind(reg); + let copy = self.top().fresh(kind); + self.emit(Op::Move { + dst: copy, + src: reg, + }); + copy + } + false => reg, + }; + used.push(reg); + return Ok(Layout::Value(reg)); + } + match node { + Node::Array(items) => Ok(Layout::List( + items + .iter() + .map(|n| self.layout(n, used)) + .collect::>>()? + .into(), + )), + Node::Object(pairs) => { + let mut fields = Vec::with_capacity(pairs.len()); + for (key, value) in pairs.iter() { + let Node::String(key) = key else { + return Err(CompilerError::UnexpectedErrorNode); + }; + fields.push((Arc::from(*key), self.layout(value, used)?)); + } + Ok(Layout::Struct(fields.into())) + } + _ => Err(CompilerError::UnexpectedErrorNode), + } + } + + pub fn compile_many( + roots: &[(&'a str, &'a Node<'a>)], + chain: bool, + hints: Option<&'a Hints>, + ) -> Result { + let assigns = roots.iter().any(|(_, n)| Self::assigns(n)); + let nested = roots + .iter() + .any(|(a, _)| roots.iter().any(|(b, _)| DotPath::under(b, a))); + let resolvable = + chain && !assigns && !nested && roots.iter().all(|(_, n)| Self::dollar_static(n)); + match Self::compile_entries(roots, chain, hints, assigns, resolvable) { + Ok(program) => Ok(program), + Err(CompilerError::UnexpectedErrorNode) if resolvable => { + Self::compile_entries(roots, chain, hints, assigns, false) + } + Err(e) => Err(e), + } + } + + pub fn compile_isolated( + roots: &[(&'a str, &'a Node<'a>)], + hints: Option<&'a Hints>, + ) -> Result { + let mut program = Self::compile_entries(roots, false, hints, true, false)?; + program.isolated = true; + Ok(program) + } + + fn compile_entries( + roots: &[(&'a str, &'a Node<'a>)], + chain: bool, + hints: Option<&'a Hints>, + assigns: bool, + resolvable: bool, + ) -> Result { + let dynamic = chain && !resolvable; + let mut compiler = LaneCompiler { + stack: vec![Builder::default()], + aliases: Vec::new(), + writes_env: dynamic, + hints, + types: None, + keys: Vec::new(), + site_keys: Vec::new(), + shared: (!assigns).then(Vec::new), + dollar: resolvable.then(Vec::new), + named: None, + folding: false, + pure: Default::default(), + assigning: Default::default(), + unresolved: false, + indexing: chain, + }; + let mut outputs = Vec::with_capacity(roots.len()); + for (index, (key, root)) in roots.iter().enumerate() { + if dynamic && assigns && index > 0 { + compiler.emit(Op::Rewind); + } + compiler.emit(Op::Stage { + index: index as u32, + }); + let out = compiler.node(root)?; + if compiler.unresolved { + return Err(CompilerError::UnexpectedErrorNode); + } + let out = match compiler.top().pinned.contains(&out) { + true => { + let kind = compiler.top().kind(out); + let copy = compiler.alloc_kind(kind); + compiler.emit(Op::Move { + dst: copy, + src: out, + }); + copy + } + false => out, + }; + compiler.top().pinned.push(out); + outputs.push(out); + if let Some(dollar) = compiler.dollar.as_mut() { + match dollar.iter_mut().find(|(k, _)| k == key) { + Some(entry) => entry.1 = out, + None => dollar.push((key.to_string(), out)), + } + } + if dynamic { + compiler.emit(Op::DollarInsert { + key: Arc::from(*key), + value: out, + }); + if let Some(shared) = compiler.shared.as_mut() { + shared.retain(|(k, _)| k != "env:$" && !k.starts_with("path:$")); + } + } + } + if outputs.is_empty() { + let out = compiler.constant(Const::Null); + outputs.push(out); + } + let mut builder = compiler.stack.pop().unwrap_or_default(); + builder.program.out = outputs.last().copied().unwrap_or_default(); + builder.program.outputs = outputs; + builder.program.writes_env = compiler.writes_env; + builder.program.chain = dynamic; + let mut program = builder.seal(); + program.keys = compiler.keys; + let sites = compiler.site_keys.len() as u32; + program.site_keys = compiler.site_keys; + program.finish(sites); + Ok(program) + } + + pub fn compile_named( + roots: &[(&'a str, &'a Node<'a>, bool)], + hints: Option<&'a Hints>, + ) -> Result { + let keyed: Vec<&str> = roots + .iter() + .map(|(k, _, _)| *k) + .filter(|k| !k.is_empty()) + .collect(); + let nested = keyed + .iter() + .any(|a| keyed.iter().any(|b| DotPath::under(b, a))); + if nested || roots.iter().any(|(_, n, _)| Self::assigns(n)) { + return Err(CompilerError::UnexpectedErrorNode); + } + let mut compiler = LaneCompiler { + stack: vec![Builder::default()], + aliases: Vec::new(), + writes_env: false, + hints, + types: None, + keys: Vec::new(), + site_keys: Vec::new(), + shared: Some(Vec::new()), + dollar: None, + named: Some(Vec::new()), + folding: false, + pure: Default::default(), + assigning: Default::default(), + unresolved: false, + indexing: false, + }; + let mut outputs = Vec::with_capacity(roots.len()); + for (key, root, output) in roots.iter() { + if *output { + compiler.emit(Op::Stage { + index: outputs.len() as u32, + }); + } + let out = compiler.node(root)?; + if compiler.unresolved || compiler.writes_env { + return Err(CompilerError::UnexpectedErrorNode); + } + let out = match compiler.top().pinned.contains(&out) { + true => { + let kind = compiler.top().kind(out); + let copy = compiler.alloc_kind(kind); + compiler.emit(Op::Move { + dst: copy, + src: out, + }); + copy + } + false => out, + }; + compiler.top().pinned.push(out); + if *output { + outputs.push(out); + } + if let (false, Some(named)) = (key.is_empty(), compiler.named.as_mut()) { + match named.iter_mut().find(|(k, _)| k == key) { + Some(entry) => entry.1 = out, + None => named.push((key.to_string(), out)), + } + } + } + if outputs.is_empty() { + let out = compiler.constant(Const::Null); + outputs.push(out); + } + let mut builder = compiler.stack.pop().unwrap_or_default(); + builder.program.out = outputs.last().copied().unwrap_or_default(); + builder.program.outputs = outputs; + let mut program = builder.seal(); + program.keys = compiler.keys; + let sites = compiler.site_keys.len() as u32; + program.site_keys = compiler.site_keys; + program.finish(sites); + Ok(program) + } + + fn named_relation(&self, node: &Node) -> Option<(Reg, Vec>)> { + let named = self.named.as_ref().filter(|n| !n.is_empty())?; + let path = match node { + Node::Root => return Some((Reg::MAX, Vec::new())), + Node::Identifier(_) | Node::Member { .. } => self.member_fast(node)?, + _ => return None, + }; + let mut segments: Vec> = Vec::with_capacity(path.len()); + let mut opaque = false; + for target in &path { + match target { + FetchFastTarget::Begin => {} + FetchFastTarget::String(s) if !s.contains('.') && !s.is_empty() => { + segments.push(s.clone()) + } + FetchFastTarget::Root => return Some((Reg::MAX, Vec::new())), + _ => { + opaque = true; + break; + } + } + } + if segments.first().is_some_and(|s| s.starts_with('$')) { + return Some((Reg::MAX, Vec::new())); + } + let key = segments.join("."); + let (k, reg) = named.iter().find(|(k, _)| DotPath::overlaps(k, &key))?; + let inside = DotPath::within(&key, k); + match ( + inside && !opaque && self.stack.len() == 1, + k.split('.').count(), + ) { + (true, depth) => Some((*reg, segments[depth..].to_vec())), + (false, _) => Some((Reg::MAX, Vec::new())), + } + } + + fn resolve_named(&mut self, node: &'a Node<'a>) -> Option> { + let (mut reg, rest) = self.named_relation(node)?; + if reg == Reg::MAX { + self.unresolved = true; + return Some(Ok(self.constant(Const::Null))); + } + for key in &rest { + let site = self.site(None); + let dst = self.alloc(); + self.emit(Op::Field { + dst, + src: reg, + key: key.clone(), + site, + nested: false, + }); + reg = dst; + } + Some(Ok(reg)) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(crate) fn dollar_static(node: &Node) -> bool { + let mut base = node; + let mut chain = false; + let mut dotted = false; + while let Node::Member { + node: inner, + property: Node::String(segment), + } = base + { + dotted |= segment.contains('.') || segment.is_empty(); + base = inner; + chain = true; + } + if chain && matches!(base, Node::Identifier("$")) { + return !dotted; + } + let ok = std::cell::Cell::new(true); + match node { + Node::Identifier("$") | Node::Root => false, + Node::Closure { body, .. } => Self::dollar_static(body), + Node::Member { node, property } => { + Self::dollar_static(node) && Self::dollar_static(property) + } + Node::Parenthesized(n) | Node::Unary { node: n, .. } => Self::dollar_static(n), + Node::Binary { left, right, .. } | Node::Interval { left, right, .. } => { + Self::dollar_static(left) && Self::dollar_static(right) + } + Node::Conditional { + condition, + on_true, + on_false, + } => { + Self::dollar_static(condition) + && Self::dollar_static(on_true) + && Self::dollar_static(on_false) + } + Node::Array(items) | Node::TemplateString(items) => { + items.iter().all(|n| Self::dollar_static(n)) + } + Node::Object(pairs) => pairs + .iter() + .all(|(k, v)| Self::dollar_static(k) && Self::dollar_static(v)), + Node::FunctionCall { arguments, .. } => { + arguments.iter().all(|n| Self::dollar_static(n)) + } + Node::MethodCall { + this, arguments, .. + } => Self::dollar_static(this) && arguments.iter().all(|n| Self::dollar_static(n)), + Node::Slice { node, to, from } => { + Self::dollar_static(node) + && to.is_none_or(|n| Self::dollar_static(n)) + && from.is_none_or(|n| Self::dollar_static(n)) + } + Node::Assignments { .. } | Node::Error { .. } => false, + _ => ok.get(), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn dollar_rooted(node: &Node) -> bool { + match node { + Node::Member { node, .. } => Self::dollar_rooted(node), + Node::Identifier(v) => *v == "$", + _ => false, + } + } + + fn resolve_dollar(&mut self, node: &'a Node<'a>) -> Option> { + let dollar = self.dollar.as_ref().filter(|d| !d.is_empty())?; + let mut segments = Vec::new(); + let mut base = node; + while let Node::Member { + node: inner, + property: Node::String(p), + } = base + { + segments.push(*p); + base = inner; + } + if !matches!(base, Node::Identifier("$")) || segments.is_empty() { + return None; + } + segments.reverse(); + let found = (1..=segments.len()).rev().find_map(|i| { + let key = segments[..i].join("."); + dollar.iter().find(|(k, _)| *k == key).map(|(_, r)| (*r, i)) + }); + let Some((reg, used)) = found else { + let interior = (1..=segments.len()).any(|i| { + let prefix = format!("{}.", segments[..i].join(".")); + dollar.iter().any(|(k, _)| k.starts_with(&prefix)) + }); + if interior { + self.unresolved = true; + } + return Some(Ok(self.constant(Const::Null))); + }; + let mut reg = self.imported(reg); + for key in &segments[used..] { + let site = self.site(None); + let dst = self.alloc(); + self.emit(Op::Field { + dst, + src: reg, + key: Arc::from(*key), + site, + nested: false, + }); + reg = dst; + } + if used == segments.len() { + let kind = self.top().kind(reg); + let dst = self.alloc_kind(kind); + self.emit(Op::Move { dst, src: reg }); + reg = dst; + } + Some(Ok(reg)) + } + + fn cached_load(&mut self, key: &Option) -> Option { + let key = key.as_ref()?; + if self.stack.len() != 1 { + return None; + } + let shared = self.shared.as_ref()?; + shared.iter().find(|(k, _)| k == key).map(|(_, r)| *r) + } + + fn remember_load(&mut self, key: Option, reg: Reg) { + if self.stack.len() != 1 || self.top().mask != 0 { + return; + } + let (Some(key), true) = (key, self.shared.is_some()) else { + return; + }; + self.top().pinned.push(reg); + if let Some(shared) = self.shared.as_mut() { + shared.push((key, reg)); + } + } + + fn top(&mut self) -> &mut Builder { + let last = self.stack.len() - 1; + &mut self.stack[last] + } + + fn alloc(&mut self) -> Reg { + self.top().alloc(Kind::Dyn) + } + + fn site(&mut self, key: Option) -> u32 { + self.site_keys.push(key); + (self.site_keys.len() - 1) as u32 + } + + fn indexed(path: &[FetchFastTarget]) -> Option { + let at = path + .iter() + .position(|p| matches!(p, FetchFastTarget::Number(_)))?; + let keyed = Self::path_key(&path[..at]).is_some(); + let rest = path[at..] + .iter() + .all(|p| matches!(p, FetchFastTarget::Number(_) | FetchFastTarget::String(_))); + (keyed && rest).then_some(at) + } + + fn loaded(&mut self, path: &[FetchFastTarget]) -> Reg { + let share = Self::path_key(path).map(|k| format!("path:{k}")); + if let Some(reg) = self.cached_load(&share) { + return reg; + } + let kind = self.hint(path); + let dst = self.alloc_kind(kind); + let site = self.site(Self::path_key(path)); + self.emit(Op::Path { + dst, + path: path.into(), + site, + }); + self.remember_load(share, dst); + dst + } + + fn path_key(path: &[FetchFastTarget]) -> Option { + let mut key = String::new(); + for p in path { + match p { + FetchFastTarget::Begin => {} + FetchFastTarget::String(s) if s.contains('.') => return None, + FetchFastTarget::String(s) => { + if !key.is_empty() { + key.push('.'); + } + key.push_str(s); + } + _ => return None, + } + } + (!key.is_empty()).then_some(key) + } + + fn alloc_kind(&mut self, kind: Kind) -> Reg { + self.top().alloc(kind) + } + + fn kind(&mut self, r: Reg) -> Kind { + self.top().kind(r) + } + + fn hint(&mut self, path: &[FetchFastTarget]) -> Kind { + let mut key = String::new(); + for p in path { + match p { + FetchFastTarget::Begin => {} + FetchFastTarget::String(s) => { + if !key.is_empty() { + key.push('.'); + } + key.push_str(s); + } + _ => return Kind::Dyn, + } + } + self.hint_key(key) + } + + fn hint_key(&mut self, key: String) -> Kind { + let kind = self + .hints + .and_then(|h| h.get(&key).copied()) + .unwrap_or(Kind::Dyn); + if !self.keys.contains(&key) { + self.keys.push(key); + } + kind + } + + fn returns(t: &VariableType) -> Kind { + match t { + VariableType::Number => Kind::Num, + VariableType::Bool => Kind::Bool, + VariableType::String => Kind::Str, + VariableType::Date => Kind::Date, + _ => Kind::Dyn, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn type_kind(t: &VariableType) -> Option { + match t { + VariableType::Number => Some(Kind::Num), + VariableType::Bool => Some(Kind::Bool), + VariableType::String | VariableType::Const(_) | VariableType::Enum(..) => { + Some(Kind::Str) + } + VariableType::Nullable(inner) => Self::type_kind(inner), + _ => None, + } + } + + fn node_kind(&self, node: &Node) -> Option { + self.types + .and_then(|t| t.get_type(node)) + .and_then(|t| Self::type_kind(&t.kind)) + } + + fn element_kind(&self, node: &Node) -> Option { + let info = self.types?.get_type(node)?; + match &info.kind { + VariableType::Array(inner) => Self::type_kind(inner), + VariableType::Nullable(inner) => match inner.as_ref() { + VariableType::Array(inner) => Self::type_kind(inner), + _ => None, + }, + _ => None, + } + } + + fn pointer_key(&self, depth: u32) -> Option { + let level = self.stack.len() - 1; + let target = level.checked_sub(depth as usize).filter(|t| *t >= 1)?; + self.stack[target].element_key.clone() + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn node_key(&self, node: &Node) -> Option { + match node { + Node::Identifier("$") if self.dollar.as_ref().is_some_and(|d| !d.is_empty()) => None, + Node::Identifier(v) => match self.lookup_alias(v) { + Some(depth) => self.pointer_key(depth), + None => Some(v.to_string()), + }, + Node::Pointer => self.pointer_key(0), + Node::Parenthesized(inner) => self.node_key(inner), + Node::Member { + node, + property: Node::String(p), + } if !p.contains('.') => self.node_key(node).map(|k| format!("{k}.{p}")), + Node::FunctionCall { + kind: FunctionKind::Closure(ClosureFunction::Filter), + arguments, + } => arguments.first().and_then(|list| self.node_key(list)), + _ => None, + } + } + + fn release(&mut self, r: Reg) { + self.top().release(r) + } + + fn release_all(&mut self, regs: &[Reg]) { + regs.iter().for_each(|r| self.release(*r)); + } + + fn emit(&mut self, op: Op) { + self.top().emit(op) + } + + fn under(&mut self, mask: MaskId, f: impl FnOnce(&mut Self) -> Result) -> Result { + let saved = std::mem::replace(&mut self.top().mask, mask); + let out = f(self); + self.top().mask = saved; + out + } + + fn const_id(&mut self, value: Const) -> u32 { + let consts = &mut self.top().program.consts; + match consts.iter().position(|c| c.same(&value)) { + Some(i) => i as u32, + None => { + consts.push(value); + (consts.len() - 1) as u32 + } + } + } + + fn constant(&mut self, value: Const) -> Reg { + let kind = match value { + Const::Number(_) => Kind::Num, + Const::Bool(_) => Kind::Bool, + Const::String(_) => Kind::Str, + Const::Date(_) => Kind::Date, + _ => Kind::Dyn, + }; + let id = self.const_id(value); + let dst = match kind { + Kind::Str | Kind::Dyn => self.top().pin(kind), + _ => self.alloc_kind(kind), + }; + self.emit(Op::Const { dst, id }); + dst + } + + fn load_of(&self, node: &'a Node<'a>) -> Option<(Load, Option)> { + if self.dollar.is_some() && Self::dollar_rooted(node) { + return None; + } + if self.named_relation(node).is_some() { + return None; + } + match node { + Node::Identifier(v) if self.lookup_alias(v).is_none() => { + Some((Load::Env(Arc::from(*v)), Some(v.to_string()))) + } + Node::Member { .. } => self + .member_fast(node) + .filter(|p| !matches!(p.first(), Some(FetchFastTarget::Root))) + .map(|p| { + let key = Self::path_key(&p); + (Load::Path(p.into()), key) + }), + _ => None, + } + } + + fn fail(&mut self, error: crate::vm::VMError) -> Reg { + let dst = self.alloc(); + self.emit(Op::Fail { error }); + dst + } + + fn unary(&mut self, a: Reg, kind: Kind, make: impl FnOnce(Reg, Reg) -> Op) -> Reg { + self.release(a); + let dst = self.alloc_kind(kind); + self.emit(make(dst, a)); + dst + } + + fn result_kind(op: Binary) -> Kind { + match op { + Binary::Add => Kind::Dyn, + Binary::Subtract + | Binary::Multiply + | Binary::Divide + | Binary::Modulo + | Binary::Exponent => Kind::Num, + Binary::Equal | Binary::In | Binary::Compare(_) => Kind::Bool, + } + } + + fn binary(&mut self, op: Binary, a: Reg, b: Reg) -> Reg { + self.release(a); + self.release(b); + let dst = self.alloc_kind(Self::result_kind(op)); + self.emit(Op::Binary { dst, op, a, b }); + dst + } + + fn num_operand(&mut self, node: &'a Node<'a>) -> Result { + match Const::number(node) { + Some(n) => Ok(Operand::Num(n)), + None => Ok(Operand::Reg(self.node(node)?)), + } + } + + fn numeric(&mut self, o: Operand) -> bool { + match o { + Operand::Num(_) => true, + Operand::Reg(r) => self.kind(r) == Kind::Num, + } + } + + fn materialize(&mut self, o: Operand) -> Reg { + match o { + Operand::Reg(r) => r, + Operand::Num(n) => self.constant(Const::Number(n)), + } + } + + fn release_operand(&mut self, o: Operand) { + if let Operand::Reg(r) = o { + self.release(r); + } + } + + fn typed_binary(&mut self, op: Binary, left: &'a Node<'a>, right: &'a Node<'a>) -> Result { + let num = match op { + Binary::Add => Some(NumOp::Add), + Binary::Subtract => Some(NumOp::Subtract), + Binary::Multiply => Some(NumOp::Multiply), + Binary::Divide => Some(NumOp::Divide), + Binary::Modulo => Some(NumOp::Modulo), + _ => None, + }; + let cmp = match op { + Binary::Compare(c) => Some(NumCmp::Order(c)), + Binary::Equal => Some(NumCmp::Equal), + _ => None, + }; + + if let ( + Binary::In, + Node::Interval { + left: lo, + right: hi, + left_bracket, + right_bracket, + }, + ) = (op, right) + { + if let (Some(lo), Some(hi)) = (Const::number(lo), Const::number(hi)) { + let a = self.node(left)?; + self.release(a); + let dst = self.alloc_kind(Kind::Bool); + self.emit(Op::InRange { + dst, + a, + lo, + hi, + left: *left_bracket, + right: *right_bracket, + }); + return Ok(dst); + } + } + if let (Binary::In, Node::Array(_)) = (op, right) { + if let Some(value) = Const::of(right) { + let a = self.node(left)?; + let id = self.const_id(value); + self.release(a); + let dst = self.alloc_kind(Kind::Bool); + self.emit(Op::InConst { dst, a, id }); + return Ok(dst); + } + } + if op == Binary::In { + if let Some((load, key)) = self.load_of(right) { + let a = self.node(left)?; + let site = self.site(key); + self.release(a); + let dst = self.alloc_kind(Kind::Bool); + self.emit(Op::LoadIn { dst, a, load, site }); + return Ok(dst); + } + } + if num.is_none() && cmp.is_none() { + let a = self.node(left)?; + let b = self.operand(op, right)?; + return Ok(self.binary(op, a, b)); + } + + if op == Binary::Equal { + if let Some(value) = Self::literal(right) { + return self.compare_const(left, value, false); + } + } + + let a = self.num_operand(left)?; + let b = self.num_operand(right)?; + if let (Binary::Add, Operand::Reg(x), Operand::Reg(y)) = (op, a, b) { + if self.kind(x) == Kind::Str && self.kind(y) == Kind::Str { + self.release(x); + self.release(y); + let dst = self.alloc_kind(Kind::Str); + self.emit(Op::Concat { dst, a: x, b: y }); + return Ok(dst); + } + } + if self.numeric(a) + && self.numeric(b) + && !(matches!(a, Operand::Num(_)) && matches!(b, Operand::Num(_))) + { + self.release_operand(a); + self.release_operand(b); + return Ok(match (num, cmp) { + (Some(op), _) => { + let dst = self.alloc_kind(Kind::Num); + self.emit(Op::Num { dst, op, a, b }); + dst + } + (_, Some(op)) => { + let dst = self.alloc_kind(Kind::Bool); + self.emit(Op::Cmp { dst, op, a, b }); + dst + } + _ => unreachable!(), + }); + } + + let (a, b) = (self.materialize(a), self.materialize(b)); + Ok(self.binary(op, a, b)) + } + + fn literal(node: &Node) -> Option { + if let Some(n) = Const::number(node) { + return Some(Const::Number(n)); + } + match node { + Node::Null => Some(Const::Null), + Node::Bool(b) => Some(Const::Bool(*b)), + Node::String(s) => Some(Const::String(Arc::from(*s))), + _ => None, + } + } + + fn compare_const(&mut self, left: &'a Node<'a>, value: Const, not: bool) -> Result { + let fused = match value { + Const::String(_) => self.load_of(left), + _ => None, + }; + match fused { + Some((load, key)) => { + let memo = match (&key, &value) { + (Some(key), Const::String(text)) if !key.starts_with('$') => { + Some(format!("eq:{not}:{}:{key}:{text}", text.len())) + } + _ => None, + }; + if let Some(reg) = self.cached_load(&memo) { + return Ok(reg); + } + let site = self.site(key); + let dst = self.alloc_kind(Kind::Bool); + let id = self.const_id(value); + self.emit(Op::LoadEq { + dst, + load, + site, + id, + not, + }); + self.remember_load(memo, dst); + Ok(dst) + } + None => { + let a = self.node(left)?; + Ok(self.eq_const(a, value, not)) + } + } + } + + fn eq_const(&mut self, a: Reg, value: Const, not: bool) -> Reg { + self.release(a); + let dst = self.alloc_kind(Kind::Bool); + let id = self.const_id(value.clone()); + self.emit(Op::EqConst { + dst, + a, + value, + id, + not, + }); + dst + } + + fn lookup_alias(&self, name: &str) -> Option { + self.aliases + .iter() + .enumerate() + .rev() + .find_map(|(index, &alias)| { + alias.and_then(|a| (a == name).then_some((self.aliases.len() - 1 - index) as u32)) + }) + } + + fn imported(&mut self, mut reg: Reg) -> Reg { + for j in 1..self.stack.len() { + let kind = self.stack[j - 1].kind(reg); + let builder = &mut self.stack[j]; + reg = match builder.imports.iter().find(|(p, _)| *p == reg) { + Some((_, c)) => *c, + None => { + let c = builder.pin(kind); + builder.imports.push((reg, c)); + c + } + }; + } + reg + } + + fn pointer(&mut self, depth: u32) -> Reg { + let level = self.stack.len() - 1; + let Some(target) = level.checked_sub(depth as usize).filter(|t| *t >= 1) else { + return self.fail(Ops::error( + "Pointer", + format!("Scope depth {} out of bounds", depth), + )); + }; + + let mut reg = self.stack[target].program.element.unwrap_or_default(); + for j in target + 1..=level { + let kind = self.stack[j - 1].kind(reg); + let builder = &mut self.stack[j]; + reg = match builder.imports.iter().find(|(p, _)| *p == reg) { + Some((_, c)) => *c, + None => { + let c = builder.pin(kind); + builder.imports.push((reg, c)); + c + } + }; + } + reg + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn member_fast(&self, node: &'a Node<'a>) -> Option> { + match node { + Node::Root => Some(vec![FetchFastTarget::Root]), + Node::Identifier("$") if self.dollar.as_ref().is_some_and(|d| !d.is_empty()) => None, + Node::Identifier(v) => self.lookup_alias(v).is_none().then(|| { + vec![ + FetchFastTarget::Begin, + FetchFastTarget::String(Arc::from(*v)), + ] + }), + Node::Member { node, property } => { + let mut path = self.member_fast(node)?; + match property { + Node::String(v) => { + path.push(FetchFastTarget::String(Arc::from(*v))); + Some(path) + } + Node::Number(v) => { + path.push(FetchFastTarget::Number(v.to_u32()?)); + Some(path) + } + _ => None, + } + } + _ => None, + } + } + + fn arg(&mut self, node: &'a Node<'a>) -> Result { + Ok(match Self::literal(node) { + Some(value) => Input::Const(self.const_id(value)), + None => Input::Reg(self.node(node)?), + }) + } + + fn release_args(&mut self, args: &[Input]) { + for a in args { + if let Input::Reg(r) = a { + self.release(*r); + } + } + } + + fn load_call(&mut self, kind: &FunctionKind, arguments: &[&'a Node<'a>]) -> Option { + let (first, rest) = arguments.split_first()?; + let literals: Vec = rest + .iter() + .map(|a| Self::literal(a)) + .collect::>()?; + let (load, key) = self.load_of(first)?; + let site = self.site(key); + let args: Box<[u32]> = literals.into_iter().map(|c| self.const_id(c)).collect(); + let returns = FunctionRegistry::get_definition(kind) + .map(|f| Self::returns(&f.return_type())) + .unwrap_or(Kind::Dyn); + let memo = self.top().program.memos; + self.top().program.memos = memo.checked_add(1)?; + let loaded = match &load { + Load::Env(key) => self.hint(&[FetchFastTarget::String(key.clone())]), + Load::Path(path) => self.hint(path), + }; + let scratch = self.alloc_kind(self.node_kind(first).unwrap_or(loaded)); + let dst = self.alloc_kind(returns); + self.release(scratch); + let call = Op::Call { + dst, + kind: kind.clone(), + args: std::iter::once(Input::Reg(scratch)) + .chain(args.iter().map(|id| Input::Const(*id))) + .collect(), + }; + self.emit(Op::LoadCall(Box::new(LoadCall { + dst, + load, + site, + kind: kind.clone(), + args, + memo, + scratch, + call, + }))); + Some(dst) + } + + fn extreme( + &mut self, + kind: &FunctionKind, + largest: bool, + items: &[&'a Node<'a>], + ) -> Result { + let operands = items + .iter() + .map(|n| self.num_operand(n)) + .collect::>>()?; + if operands.iter().all(|o| self.numeric(*o)) { + operands.iter().for_each(|o| self.release_operand(*o)); + let dst = self.alloc_kind(Kind::Num); + self.emit(Op::Extreme { + dst, + items: operands.into(), + largest, + }); + return Ok(dst); + } + let regs: Vec = operands.into_iter().map(|o| self.materialize(o)).collect(); + self.release_all(®s); + let array = self.alloc(); + self.emit(Op::Array { + dst: array, + items: regs.into(), + }); + Ok(self.call(kind.clone(), vec![Input::Reg(array)])) + } + + fn call(&mut self, kind: FunctionKind, args: Vec) -> Reg { + let listed = + matches!(args.as_slice(), [Input::Reg(r)] if self.top().kind(*r) == Kind::List); + self.release_args(&args); + let returns = match &kind { + FunctionKind::Internal(InternalFunction::Max | InternalFunction::Min) if listed => { + Kind::Num + } + _ => FunctionRegistry::get_definition(&kind) + .map(|f| Self::returns(&f.return_type())) + .unwrap_or(Kind::Dyn), + }; + let dst = self.alloc_kind(returns); + self.emit(Op::Call { + dst, + kind, + args: args.into(), + }); + dst + } + + fn element_field(body: &Program) -> Option> { + match body.steps.as_slice() { + [Step { + op: Op::Field { dst, src, key, .. }, + .. + }] if Some(*src) == body.element && *dst == body.out => Some(key.clone()), + _ => None, + } + } + + fn fold_region(&mut self, start: usize, mask: MaskId, function: InternalFunction, dst: Reg) { + if self.top().kind(dst) != Kind::Num { + return; + } + let steps = &self.top().program.steps[start..]; + if steps.iter().any(|step| step.mask != mask) { + return; + } + let plain = |c: &ClosureOp| c.imports.is_empty() && !c.sequential; + let shape = match steps { + [Step { + op: Op::Closure(filter), + .. + }, Step { + op: Op::Closure(map), + .. + }, Step { + op: Op::Call { dst: out, args, .. }, + .. + }] if filter.kind == ClosureFunction::Filter + && map.kind == ClosureFunction::Map + && map.source.is_none() + && map.list == filter.dst + && plain(filter) + && plain(map) + && *out == dst + && matches!(args.as_ref(), [Input::Reg(r)] if *r == map.dst) => + { + filter + .source + .as_ref() + .map(|(_, site)| *site) + .zip(Self::element_field(&filter.body)) + .zip(Self::element_field(&map.body)) + .map(|((site, filter), field)| (site, Some(filter), field)) + } + [Step { + op: Op::Closure(map), + .. + }, Step { + op: Op::Call { dst: out, args, .. }, + .. + }] if map.kind == ClosureFunction::Map + && plain(map) + && *out == dst + && matches!(args.as_ref(), [Input::Reg(r)] if *r == map.dst) => + { + map.source + .as_ref() + .map(|(_, site)| *site) + .zip(Self::element_field(&map.body)) + .map(|(site, field)| (site, None, field)) + } + _ => None, + }; + let Some((site, filter, field)) = shape else { + return; + }; + let rest = self.top().mask(); + let builder = self.top(); + builder.program.steps[start..] + .iter_mut() + .for_each(|step| step.mask = rest); + builder.program.steps.insert( + start, + Step { + mask, + op: Op::Fold(Box::new(FoldOp { + dst, + function, + site, + filter, + field, + rest, + })), + }, + ); + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn unwrap(node: &'a Node<'a>) -> &'a Node<'a> { + match node { + Node::Parenthesized(inner) => Self::unwrap(inner), + other => other, + } + } + + fn equality(node: &'a Node<'a>) -> Option<(&'a Node<'a>, &'a str)> { + match Self::unwrap(node) { + Node::Binary { + left, + operator: Operator::Comparison(ComparisonOperator::Equal), + right, + } => match (Self::unwrap(left), Self::unwrap(right)) { + (subject, Node::String(text)) => Some((subject, text)), + (inner @ Node::Binary { .. }, Node::Bool(true)) => match Self::unwrap(inner) { + Node::Binary { + left, + operator: Operator::Comparison(ComparisonOperator::Equal), + right, + } => match Self::unwrap(right) { + Node::String(text) => Some((Self::unwrap(left), *text)), + _ => None, + }, + _ => None, + }, + _ => None, + }, + _ => None, + } + } + + fn switch_arms( + &self, + node: &'a Node<'a>, + ) -> Option<(&'a Node<'a>, Vec<(&'a str, Const)>, Const)> { + let mut arms = Vec::new(); + let mut subject: Option<(&'a Node<'a>, String)> = None; + let mut current = node; + let fallback = loop { + match Self::unwrap(current) { + Node::Conditional { + condition, + on_true, + on_false, + } => { + let (target, text) = Self::equality(condition)?; + let key = Self::path_key(&self.member_fast(target)?)?; + match &subject { + Some((_, k)) if *k != key => return None, + Some(_) => {} + None => subject = Some((target, key)), + } + arms.push((text, Self::literal(Self::unwrap(on_true))?)); + current = on_false; + } + other => break Self::literal(other)?, + } + }; + let (target, _) = subject?; + (arms.len() >= 2).then_some((target, arms, fallback)) + } + + fn switch(&mut self, node: &'a Node<'a>) -> Result { + let Some((subject, arms, fallback)) = self.switch_arms(node) else { + return Err(CompilerError::UnexpectedErrorNode); + }; + let kinds: Vec = arms + .iter() + .map(|(_, value)| value) + .chain(std::iter::once(&fallback)) + .map(|value| match value { + Const::Number(_) => Kind::Num, + Const::Bool(_) => Kind::Bool, + Const::String(_) => Kind::Str, + _ => Kind::Dyn, + }) + .collect(); + let kind = match kinds.iter().all(|k| *k == kinds[0]) { + true => kinds[0], + false => Kind::Dyn, + }; + let cases: Box<[Arc]> = arms.iter().map(|(text, _)| Arc::from(*text)).collect(); + let values: Box<[u32]> = arms + .into_iter() + .map(|(_, value)| value) + .chain(std::iter::once(fallback)) + .map(|value| self.const_id(value)) + .collect(); + let dst = self.alloc_kind(kind); + let switch = |subject: Subject, rest: MaskId| { + Op::Switch(Box::new(SwitchOp { + dst, + subject, + cases: cases.clone(), + values: values.clone(), + rest, + })) + }; + match self.load_of(subject) { + Some((_, key)) => { + let site = self.site(key); + let rest = self.top().mask(); + self.emit(switch(Subject::Site(site), rest)); + self.under(rest, |c| { + let a = c.node(subject)?; + c.release(a); + c.emit(switch(Subject::Reg(a), rest)); + Ok(()) + })?; + } + None => { + let a = self.node(subject)?; + self.release(a); + self.emit(switch(Subject::Reg(a), 0)); + } + } + Ok(dst) + } + + fn string(&mut self, a: Reg) -> Reg { + self.call( + FunctionKind::Internal(InternalFunction::String), + vec![Input::Reg(a)], + ) + } + + fn branch(&mut self, cond: Reg, opcode: &'static str) -> (MaskId, MaskId) { + let on_true = self.top().mask(); + let on_false = self.top().mask(); + self.emit(Op::Branch { + cond, + opcode, + on_true, + on_false, + }); + (on_true, on_false) + } + + fn merge(&mut self, mask: MaskId, a: Reg, b: Reg) -> Reg { + self.release(a); + self.release(b); + let (ka, kb) = (self.kind(a), self.kind(b)); + let dst = self.alloc_kind(if ka == kb { ka } else { Kind::Dyn }); + self.emit(Op::Merge { dst, mask, a, b }); + dst + } + + fn fold(&mut self, node: &'a Node<'a>) -> Option { + let value = self.fold_value(node)?; + Some(self.constant(value)) + } + + pub(crate) fn folder() -> Self { + LaneCompiler { + stack: vec![Builder::default()], + aliases: Vec::new(), + writes_env: false, + hints: None, + types: None, + keys: Vec::new(), + site_keys: Vec::new(), + shared: None, + dollar: None, + named: None, + folding: false, + pure: Default::default(), + assigning: Default::default(), + unresolved: false, + indexing: false, + } + } + + pub(crate) fn fold_value(&mut self, node: &'a Node<'a>) -> Option { + if self.folding || Self::literal(node).is_some() || !self.pure(node) { + return None; + } + let program = Self::build(node, None, None, true).ok()?; + Some(match crate::lane::LaneRunner::constant(&program)? { + Variable::Null => Const::Null, + Variable::Bool(b) => Const::Bool(b), + Variable::Number(n) => Const::Number(n), + Variable::String(s) => Const::String(Arc::from(s.as_str())), + v @ Variable::Dynamic(_) if !Date::sourced(&v) => Const::Date(Date::of(&v)?.0), + _ => return None, + }) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn pure(&mut self, node: &'a Node<'a>) -> bool { + let key = node as *const Node as usize; + if let Some(known) = self.pure.get(&key) { + return *known; + } + let pure = match node { + Node::Null | Node::Bool(_) | Node::Number(_) | Node::String(_) => true, + Node::Pointer + | Node::Identifier(_) + | Node::Root + | Node::Closure { .. } + | Node::Assignments { .. } + | Node::Error { .. } => false, + Node::Array(items) | Node::TemplateString(items) => items.iter().all(|n| self.pure(n)), + Node::Object(pairs) => pairs.iter().all(|(k, v)| self.pure(k) && self.pure(v)), + Node::Parenthesized(n) | Node::Unary { node: n, .. } => self.pure(n), + Node::Member { node, property } => self.pure(node) && self.pure(property), + Node::Slice { node, from, to } => { + self.pure(node) + && from.is_none_or(|n| self.pure(n)) + && to.is_none_or(|n| self.pure(n)) + } + Node::Interval { left, right, .. } | Node::Binary { left, right, .. } => { + self.pure(left) && self.pure(right) + } + Node::Conditional { + condition, + on_true, + on_false, + } => self.pure(condition) && self.pure(on_true) && self.pure(on_false), + Node::FunctionCall { kind, arguments } => { + Self::pure_call(kind, arguments) && arguments.iter().all(|n| self.pure(n)) + } + Node::MethodCall { + kind, + this, + arguments, + } => { + let crate::functions::MethodKind::DateMethod(method) = kind; + let format = match (method, *arguments) { + (crate::functions::DateMethod::Format, [Node::String(pattern)]) => { + Effect::formats(pattern) + } + (crate::functions::DateMethod::Format, []) => true, + (crate::functions::DateMethod::Format, _) => false, + _ => true, + }; + format + && Effect::method(kind) == Effect::Pure + && self.pure(this) + && arguments.iter().all(|n| self.pure(n)) + } + }; + self.pure.insert(key, pure); + pure + } + + fn pure_call(kind: &FunctionKind, arguments: &[&Node]) -> bool { + let literals = arguments.iter().map(|node| match node { + Node::String(text) => Literal::Text(text), + Node::Null | Node::Bool(_) | Node::Number(_) => Literal::Constant, + _ => Literal::Computed, + }); + Effect::call(kind, literals) == Effect::Pure + } + + pub(crate) fn assigns(node: &Node) -> bool { + let found = std::cell::Cell::new(false); + let found_ref = &found; + node.walk(move |n| { + if matches!(n, Node::Assignments { .. }) { + found_ref.set(true); + } + }); + found.get() + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn has_assignments(&mut self, node: &Node) -> bool { + let key = node as *const Node as usize; + if let Some(&known) = self.assigning.get(&key) { + return known; + } + let mut found = matches!(node, Node::Assignments { .. }); + Self::children(node, &mut |child| found |= self.has_assignments(child)); + self.assigning.insert(key, found); + found + } + + fn children<'n>(node: &Node<'n>, visit: &mut dyn FnMut(&'n Node<'n>)) { + match node { + Node::Null + | Node::Bool(_) + | Node::Number(_) + | Node::String(_) + | Node::Pointer + | Node::Identifier(_) + | Node::Root => {} + Node::Error { node, .. } => node.iter().for_each(|n| visit(n)), + Node::TemplateString(parts) | Node::Array(parts) => parts.iter().for_each(|n| visit(n)), + Node::Object(pairs) => pairs.iter().for_each(|(k, v)| { + visit(k); + visit(v); + }), + Node::Assignments { list, output } => { + list.iter().for_each(|(k, v)| { + visit(k); + visit(v); + }); + output.iter().for_each(|n| visit(n)); + } + Node::Closure { body, .. } => visit(body), + Node::Parenthesized(inner) => visit(inner), + Node::Member { node, property } => { + visit(node); + visit(property); + } + Node::Slice { node, to, from } => { + visit(node); + to.iter().for_each(|n| visit(n)); + from.iter().for_each(|n| visit(n)); + } + Node::Interval { left, right, .. } | Node::Binary { left, right, .. } => { + visit(left); + visit(right); + } + Node::Unary { node, .. } => visit(node), + Node::FunctionCall { arguments, .. } => arguments.iter().for_each(|n| visit(n)), + Node::MethodCall { + this, arguments, .. + } => { + visit(this); + arguments.iter().for_each(|n| visit(n)); + } + Node::Conditional { + on_true, + condition, + on_false, + } => { + visit(condition); + visit(on_true); + visit(on_false); + } + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn node(&mut self, node: &'a Node<'a>) -> Result { + if self.named.is_some() { + if let Some(resolved) = self.resolve_named(node) { + return resolved; + } + } + if self.dollar.is_some() { + if let Some(resolved) = self.resolve_dollar(node) { + return resolved; + } + } + if let Some(folded) = self.fold(node) { + return Ok(folded); + } + Ok(match node { + Node::Null => self.constant(Const::Null), + Node::Bool(v) => self.constant(Const::Bool(*v)), + Node::Number(v) => self.constant(Const::Number(*v)), + Node::String(v) => self.constant(Const::String(Arc::from(*v))), + Node::Pointer => self.pointer(0), + Node::Root => { + let dst = self.alloc(); + self.emit(Op::RootEnv { dst }); + dst + } + Node::Array(items) if !items.is_empty() && Const::of(node).is_some() => { + let id = self.const_id(Const::of(node).unwrap_or(Const::Null)); + let dst = self.alloc_kind(Kind::Dyn); + self.emit(Op::Const { dst, id }); + dst + } + Node::Array(items) => { + let regs = items + .iter() + .map(|n| self.node(n)) + .collect::>>()?; + self.release_all(®s); + let dst = self.alloc(); + self.emit(Op::Array { + dst, + items: regs.into(), + }); + dst + } + Node::Object(pairs) => { + let mut regs = Vec::with_capacity(pairs.len()); + for (key, value) in pairs.iter() { + let k = match key { + Node::String(k) => ObjectKey::Static(Arc::from(*k)), + _ => { + let k = self.node(key)?; + ObjectKey::Reg(self.string(k)) + } + }; + let v = self.node(value)?; + regs.push((k, v)); + } + regs.iter().for_each(|(k, v)| { + if let ObjectKey::Reg(k) = k { + self.release(*k); + } + self.release(*v); + }); + let dst = self.alloc(); + self.emit(Op::Object { + dst, + pairs: regs.into(), + }); + dst + } + Node::Assignments { list, output } => { + self.writes_env = true; + let object = self.alloc(); + self.emit(Op::AssignBegin { dst: object }); + for (key, value) in list.iter() { + let k = self.node(key)?; + let v = self.node(value)?; + self.emit(Op::AssignStep { + object, + key: k, + value: v, + }); + self.release(k); + self.release(v); + } + match output { + Some(output) => { + let out = self.node(output)?; + self.release(object); + out + } + None => object, + } + } + Node::Identifier(v) => match self.lookup_alias(v) { + Some(depth) => self.pointer(depth), + None => { + let share = Some(format!("env:{v}")); + if let Some(reg) = self.cached_load(&share) { + return Ok(reg); + } + let hinted = self.hint(&[FetchFastTarget::String(Arc::from(*v))]); + let kind = self.node_kind(node).unwrap_or(hinted); + let dst = self.alloc_kind(kind); + let site = self.site(Some(v.to_string())); + self.emit(Op::Env { + dst, + key: Arc::from(*v), + site, + }); + self.remember_load(share, dst); + dst + } + }, + Node::Closure { body, alias } => { + self.aliases.push(*alias); + let out = self.node(body); + self.aliases.pop(); + out? + } + Node::Parenthesized(v) => self.node(v)?, + Node::Member { node: n, property } => match self.member_fast(node) { + Some(path) + if self.indexing + && Self::path_key(&path).is_none() + && Self::indexed(&path).is_some() => + { + let at = Self::indexed(&path).unwrap_or(path.len()); + let (head, tail) = path.split_at(at); + let mut reg = self.loaded(head); + for target in tail { + let key = match target { + FetchFastTarget::Number(index) => Const::Number(Decimal::from(*index)), + FetchFastTarget::String(key) => Const::String(key.clone()), + _ => Const::Null, + }; + let b = self.constant(key); + self.release(reg); + self.release(b); + let dst = self.alloc(); + self.emit(Op::Fetch { dst, a: reg, b }); + reg = dst; + } + reg + } + Some(path) => { + let share = Self::path_key(&path).map(|k| format!("path:{k}")); + if let Some(reg) = self.cached_load(&share) { + return Ok(reg); + } + let hinted = self.hint(&path); + let kind = self.node_kind(node).unwrap_or(hinted); + let dst = self.alloc_kind(kind); + let site = self.site(Self::path_key(&path)); + self.emit(Op::Path { + dst, + path: path.into(), + site, + }); + self.remember_load(share, dst); + dst + } + None => match property { + Node::String(key) => { + let hinted = match self.node_key(node) { + Some(k) => self.hint_key(k), + None => Kind::Dyn, + }; + let kind = self.node_kind(node).unwrap_or(hinted); + let src = self.node(n)?; + self.release(src); + let dst = self.alloc_kind(kind); + let site = self.site(None); + self.emit(Op::Field { + dst, + src, + key: Arc::from(*key), + site, + nested: false, + }); + dst + } + _ => { + let a = self.node(n)?; + let b = self.node(property)?; + self.release(a); + self.release(b); + let dst = self.alloc(); + self.emit(Op::Fetch { dst, a, b }); + dst + } + }, + }, + Node::TemplateString(parts) => { + let mut regs = Vec::with_capacity(parts.len()); + for part in parts.iter() { + let arg = match part { + Node::String(text) => { + Input::Const(self.const_id(Const::String(Arc::from(*text)))) + } + _ => { + let r = self.node(part)?; + Input::Reg(self.string(r)) + } + }; + regs.push(arg); + } + self.release_args(®s); + let dst = self.alloc_kind(Kind::Str); + self.emit(Op::Join { + dst, + parts: regs.into(), + }); + dst + } + Node::Slice { node, to, from } => { + let a = self.node(node)?; + let to = match to { + Some(t) => self.node(t)?, + None => { + let len = self.alloc(); + self.emit(Op::Len { dst: len, a }); + let one = self.constant(Const::Number(Decimal::ONE)); + self.binary(Binary::Subtract, len, one) + } + }; + let from = match from { + Some(f) => self.node(f)?, + None => self.constant(Const::Number(Decimal::ZERO)), + }; + self.release_all(&[a, to, from]); + let dst = self.alloc(); + self.emit(Op::Slice { dst, a, to, from }); + dst + } + Node::Interval { + left, + right, + left_bracket, + right_bracket, + } => { + let a = self.node(left)?; + let b = self.node(right)?; + self.release_all(&[a, b]); + let dst = self.alloc(); + self.emit(Op::Interval { + dst, + a, + b, + left: *left_bracket, + right: *right_bracket, + }); + dst + } + Node::Conditional { + condition, + on_true, + on_false, + } if Self::literal(on_true).is_some() && Self::literal(on_false).is_some() => { + let cond = self.node(condition)?; + let (a, b) = (Self::literal(on_true), Self::literal(on_false)); + let (a, b) = (a.unwrap_or(Const::Null), b.unwrap_or(Const::Null)); + let kind = match (&a, &b) { + (Const::Number(_), Const::Number(_)) => Kind::Num, + (Const::Bool(_), Const::Bool(_)) => Kind::Bool, + (Const::String(_), Const::String(_)) => Kind::Str, + _ => Kind::Dyn, + }; + let (a, b) = (self.const_id(a), self.const_id(b)); + self.release(cond); + let dst = self.alloc_kind(kind); + self.emit(Op::SelectConst { dst, cond, a, b }); + dst + } + Node::Conditional { .. } if self.switch_arms(node).is_some() => self.switch(node)?, + Node::Conditional { + condition, + on_true, + on_false, + } => { + let cond = self.node(condition)?; + let (t, f) = self.branch(cond, "JumpIfFalse"); + self.release(cond); + let a = self.under(t, |c| c.node(on_true))?; + let b = self.under(f, |c| c.node(on_false))?; + self.merge(t, a, b) + } + Node::Unary { .. } if Const::number(node).is_some() => { + let n = Const::number(node).unwrap_or_default(); + self.constant(Const::Number(n)) + } + Node::Unary { node, operator } => { + let a = self.node(node)?; + match *operator { + Operator::Arithmetic(ArithmeticOperator::Add) => a, + Operator::Arithmetic(ArithmeticOperator::Subtract) => { + self.unary(a, Kind::Num, |dst, a| Op::Negate { dst, a }) + } + Operator::Logical(LogicalOperator::Not) => { + self.unary(a, Kind::Bool, |dst, a| Op::Not { dst, a }) + } + _ => { + return Err(CompilerError::UnknownUnaryOperator { + operator: operator.to_string(), + }) + } + } + } + Node::Binary { + left, + right, + operator, + } => self.binary_node(left, *operator, right)?, + Node::FunctionCall { kind, arguments } => match kind { + FunctionKind::Internal(_) | FunctionKind::Deprecated(_) => { + let function = FunctionRegistry::get_definition(kind).ok_or_else(|| { + CompilerError::UnknownFunction { + name: kind.to_string(), + } + })?; + let min = function.required_parameters(); + let max = min + function.optional_parameters(); + if arguments.len() < min || arguments.len() > max { + return Err(CompilerError::InvalidFunctionCall { + name: kind.to_string(), + message: "Invalid number of arguments".to_string(), + }); + } + if let ( + FunctionKind::Internal(f @ (InternalFunction::Max | InternalFunction::Min)), + [node], + ) = (kind, arguments) + { + if let Node::Array(items) = node { + if !items.is_empty() { + return self.extreme(kind, *f == InternalFunction::Max, items); + } + } + } + if let Some(dst) = self.load_call(kind, arguments) { + return Ok(dst); + } + if let ( + FunctionKind::Internal( + function @ (InternalFunction::Sum + | InternalFunction::Avg + | InternalFunction::Min + | InternalFunction::Max), + ), + [Node::FunctionCall { + kind: FunctionKind::Closure(ClosureFunction::Map), + .. + }], + ) = (kind, *arguments) + { + let (start, mask) = (self.top().program.steps.len(), self.top().mask); + let args = arguments + .iter() + .map(|a| self.arg(a)) + .collect::>>()?; + let dst = self.call(kind.clone(), args); + self.fold_region(start, mask, *function, dst); + return Ok(dst); + } + let args = arguments + .iter() + .map(|a| self.arg(a)) + .collect::>>()?; + self.call(kind.clone(), args) + } + FunctionKind::Closure(closure) => { + let argument = |index: usize| { + arguments.get(index).copied().ok_or_else(|| { + CompilerError::ArgumentNotFound { + index, + function: kind.to_string(), + } + }) + }; + let list_node = argument(0)?; + let element_key = self.node_key(list_node).map(|k| format!("{k}[]")); + let source = self + .load_of(list_node) + .map(|(load, key)| (load, self.site(key))); + let list = match source { + Some(_) => self.alloc(), + None => self.node(list_node)?, + }; + let body = argument(1)?; + let (body, alias) = match body { + Node::Closure { body, alias } => (*body, *alias), + other => (other, None), + }; + let sequential = self.has_assignments(body); + let hinted = match element_key.clone() { + Some(key) => self.hint_key(key), + None => Kind::Dyn, + }; + let element_kind = self.element_kind(list_node).unwrap_or(hinted); + let mut child = Builder::default(); + child.program.element = Some(child.pin(element_kind)); + child.element_key = element_key; + self.stack.push(child); + self.aliases.push(alias); + let out = self.node(body); + self.aliases.pop(); + let mut child = self.stack.pop().unwrap_or_default(); + child.program.out = out?; + let imports: Box<[(Reg, Reg)]> = std::mem::take(&mut child.imports).into(); + let body = child.seal(); + self.release(list); + let dst = self.alloc_kind(match closure { + ClosureFunction::Count => Kind::Num, + ClosureFunction::One + | ClosureFunction::Some + | ClosureFunction::All + | ClosureFunction::None => Kind::Bool, + ClosureFunction::Map | ClosureFunction::Filter => Kind::List, + _ => Kind::Dyn, + }); + self.emit(Op::Closure(Box::new(ClosureOp { + kind: *closure, + dst, + list, + source, + body, + imports, + sequential, + select: false, + }))); + dst + } + }, + Node::MethodCall { + kind, + this, + arguments, + } => { + let method = MethodRegistry::get_definition(kind).ok_or_else(|| { + CompilerError::UnknownFunction { + name: kind.to_string(), + } + })?; + let this = self.node(this)?; + let min = method.required_parameters() - 1; + let max = min + method.optional_parameters(); + if arguments.len() < min || arguments.len() > max { + return Err(CompilerError::InvalidMethodCall { + name: kind.to_string(), + message: "Invalid number of arguments".to_string(), + }); + } + let mut args = vec![Input::Reg(this)]; + for a in arguments.iter() { + args.push(self.arg(a)?); + } + self.release_args(&args); + let dst = self.alloc_kind(Self::returns(&method.return_type())); + self.emit(Op::Method { + dst, + kind: kind.clone(), + args: args.into(), + }); + dst + } + Node::Error { .. } => return Err(CompilerError::UnexpectedErrorNode), + }) + } + + fn equalities( + &self, + left: &'a Node<'a>, + right: &'a Node<'a>, + ) -> Option<(&'a Node<'a>, Vec)> { + let mut leaves = Vec::new(); + Self::or_leaves(left, &mut leaves); + Self::or_leaves(right, &mut leaves); + let mut subject: Option<(&'a Node<'a>, String)> = None; + let mut values = Vec::with_capacity(leaves.len()); + for leaf in leaves { + let Node::Binary { + left: l, + operator: Operator::Comparison(ComparisonOperator::Equal), + right: r, + } = leaf + else { + return None; + }; + let key = self.node_key(l)?; + match &subject { + Some((_, k)) if *k != key => return None, + Some(_) => {} + None => subject = Some((*l, key)), + } + values.push(Self::literal(r)?); + } + subject.map(|(node, _)| (node, values)) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn or_leaves(node: &'a Node<'a>, out: &mut Vec<&'a Node<'a>>) { + match node { + Node::Binary { + left, + operator: Operator::Logical(LogicalOperator::Or), + right, + } => { + Self::or_leaves(left, out); + Self::or_leaves(right, out); + } + Node::Parenthesized(inner) => Self::or_leaves(inner, out), + other => out.push(other), + } + } + + fn operand(&mut self, op: Binary, node: &'a Node<'a>) -> Result { + match (op, node) { + (Binary::In, Node::Array(_)) => match Const::of(node) { + Some(value) => Ok(self.constant(value)), + None => self.node(node), + }, + _ => self.node(node), + } + } + + fn binary_node( + &mut self, + left: &'a Node<'a>, + operator: Operator, + right: &'a Node<'a>, + ) -> Result { + let simple = |op: Binary| Some(op); + let op = match operator { + Operator::Comparison(ComparisonOperator::Equal) => simple(Binary::Equal), + Operator::Comparison(ComparisonOperator::In) => simple(Binary::In), + Operator::Comparison(ComparisonOperator::LessThan) => { + simple(Binary::Compare(Compare::Less)) + } + Operator::Comparison(ComparisonOperator::LessThanOrEqual) => { + simple(Binary::Compare(Compare::LessOrEqual)) + } + Operator::Comparison(ComparisonOperator::GreaterThan) => { + simple(Binary::Compare(Compare::More)) + } + Operator::Comparison(ComparisonOperator::GreaterThanOrEqual) => { + simple(Binary::Compare(Compare::MoreOrEqual)) + } + Operator::Arithmetic(ArithmeticOperator::Add) => simple(Binary::Add), + Operator::Arithmetic(ArithmeticOperator::Subtract) => simple(Binary::Subtract), + Operator::Arithmetic(ArithmeticOperator::Multiply) => simple(Binary::Multiply), + Operator::Arithmetic(ArithmeticOperator::Divide) => simple(Binary::Divide), + Operator::Arithmetic(ArithmeticOperator::Modulus) => simple(Binary::Modulo), + Operator::Arithmetic(ArithmeticOperator::Power) => simple(Binary::Exponent), + _ => None, + }; + if let Operator::Logical(LogicalOperator::Or) = operator { + if let Some((subject, values)) = self.equalities(left, right) { + let a = self.node(subject)?; + let id = self.const_id(Const::Array(values)); + self.release(a); + let dst = self.alloc_kind(Kind::Bool); + self.emit(Op::EqAny { dst, a, id }); + return Ok(dst); + } + } + if let Some(op) = op { + return self.typed_binary(op, left, right); + } + + Ok(match operator { + Operator::Comparison(ComparisonOperator::NotEqual) => match Self::literal(right) { + Some(value) => self.compare_const(left, value, true)?, + None => { + let eq = self.typed_binary(Binary::Equal, left, right)?; + self.unary(eq, Kind::Bool, |dst, a| Op::Not { dst, a }) + } + }, + Operator::Comparison(ComparisonOperator::NotIn) => { + let is_in = self.typed_binary(Binary::In, left, right)?; + self.unary(is_in, Kind::Bool, |dst, a| Op::Not { dst, a }) + } + Operator::Logical(LogicalOperator::Or) => { + let a = self.node(left)?; + let (t, f) = self.branch(a, "JumpIfTrue"); + let b = self.under(f, |c| c.node(right))?; + self.merge(t, a, b) + } + Operator::Logical(LogicalOperator::And) => { + let a = self.node(left)?; + let (t, f) = self.branch(a, "JumpIfFalse"); + let b = self.under(t, |c| c.node(right))?; + self.merge(f, a, b) + } + Operator::Logical(LogicalOperator::NullishCoalescing) => { + let a = self.node(left)?; + if let Some(value) = Const::of(right) { + let kind = match (&value, self.kind(a)) { + (Const::Number(_), Kind::Num | Kind::Dyn) => Kind::Num, + (Const::Bool(_), Kind::Bool | Kind::Dyn) => Kind::Bool, + (Const::String(_), Kind::Str | Kind::Dyn) => Kind::Str, + (Const::Array(items), Kind::List) if items.is_empty() => Kind::List, + _ => Kind::Dyn, + }; + let id = self.const_id(value); + self.release(a); + let dst = self.alloc_kind(kind); + self.emit(Op::Coalesce { dst, a, id }); + return Ok(dst); + } + let null = self.top().mask(); + let other = self.top().mask(); + self.emit(Op::NullBranch { a, null, other }); + let b = self.under(null, |c| c.node(right))?; + self.merge(other, a, b) + } + _ => { + return Err(CompilerError::UnknownBinaryOperator { + operator: operator.to_string(), + }) + } + }) + } +} diff --git a/core/expression/src/lane/date/duration.rs b/core/expression/src/lane/date/duration.rs new file mode 100644 index 00000000..124dcba9 --- /dev/null +++ b/core/expression/src/lane/date/duration.rs @@ -0,0 +1,63 @@ +use crate::lane::date::duration_parser::{DurationParseError, DurationParser}; +use crate::lane::date::duration_unit::DurationUnit; +use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; +use rust_decimal::Decimal; +use std::ops::Neg; + +#[derive(Debug, Clone, Default)] +pub(crate) struct Duration { + pub seconds: i64, + pub months: i32, + pub years: i32, +} + +impl Duration { + pub fn parse(s: &str) -> Result { + DurationParser { + iter: s.chars(), + src: s, + duration: Duration::default(), + } + .parse() + } + + pub fn from_unit(n: Decimal, unit: DurationUnit) -> Option { + if let Some(secs) = unit.as_secs() { + return Some(Self { + seconds: n.checked_mul(Decimal::from_u64(secs)?)?.to_i64()?, + ..Default::default() + }); + }; + + match unit { + DurationUnit::Month => Some(Duration { + months: n.to_i32()?, + ..Default::default() + }), + DurationUnit::Quarter => Some(Duration { + months: n.to_i32()? * 3, + ..Default::default() + }), + DurationUnit::Year => Some(Duration { + years: n.to_i32()?, + ..Default::default() + }), + _ => None, + } + } + + pub fn negate(self) -> Self { + Self { + years: self.years.neg(), + months: self.months.neg(), + seconds: self.seconds.neg(), + } + } + + pub fn day() -> Self { + Self { + seconds: DurationUnit::Day.as_secs().unwrap_or_default() as i64, + ..Default::default() + } + } +} diff --git a/core/expression/src/lane/date/duration_parser.rs b/core/expression/src/lane/date/duration_parser.rs new file mode 100644 index 00000000..7d137a75 --- /dev/null +++ b/core/expression/src/lane/date/duration_parser.rs @@ -0,0 +1,137 @@ +use crate::lane::date::duration::Duration; +use crate::lane::date::duration_unit::DurationUnit; +use rust_decimal::prelude::ToPrimitive; +use std::str::Chars; +use thiserror::Error; + +#[derive(Debug, PartialEq, Clone, Error)] +pub(crate) enum DurationParseError { + #[error("Invalid character at {0}")] + InvalidCharacter(usize), + #[error("Expected number at {0}")] + NumberExpected(usize), + #[error("Unknown time unit {unit}")] + UnknownUnit { + start: usize, + end: usize, + value: u64, + unit: String, + }, + #[error("Number is too large")] + NumberOverflow, + #[error("Value is empty")] + Empty, +} + +pub(crate) struct DurationParser<'a> { + pub iter: Chars<'a>, + pub src: &'a str, + pub duration: Duration, +} + +impl DurationParser<'_> { + fn off(&self) -> usize { + self.src.len() - self.iter.as_str().len() + } + + fn parse_first_char(&mut self) -> Result, DurationParseError> { + let off = self.off(); + for c in self.iter.by_ref() { + match c { + '0'..='9' => { + return Ok(Some(c as u64 - '0' as u64)); + } + c if c.is_whitespace() => continue, + _ => { + return Err(DurationParseError::NumberExpected(off)); + } + } + } + Ok(None) + } + fn parse_unit(&mut self, n: u64, start: usize, end: usize) -> Result<(), DurationParseError> { + let unit = DurationUnit::parse(&self.src[start..end]).ok_or_else(|| { + DurationParseError::UnknownUnit { + start, + end, + unit: self.src[start..end].to_string(), + value: n, + } + })?; + + match unit { + DurationUnit::Quarter => { + self.duration.months = n.to_i32().ok_or(DurationParseError::NumberOverflow)? * 3 + } + DurationUnit::Month => { + self.duration.months = n.to_i32().ok_or(DurationParseError::NumberOverflow)? + } + DurationUnit::Year => { + self.duration.years = n.to_i32().ok_or(DurationParseError::NumberOverflow)? + } + _ => {} + } + + if let Some(secs) = unit.as_secs() { + self.duration.seconds = self + .duration + .seconds + .checked_add( + secs.to_i64() + .ok_or(DurationParseError::NumberOverflow)? + .checked_mul(n.to_i64().ok_or(DurationParseError::NumberOverflow)?) + .ok_or(DurationParseError::NumberOverflow)?, + ) + .ok_or(DurationParseError::NumberOverflow)? + } + + Ok(()) + } + + pub fn parse(mut self) -> Result { + let mut n = self.parse_first_char()?.ok_or(DurationParseError::Empty)?; + 'outer: loop { + let mut off = self.off(); + while let Some(c) = self.iter.next() { + match c { + '0'..='9' => { + n = n + .checked_mul(10) + .and_then(|x| x.checked_add(c as u64 - '0' as u64)) + .ok_or(DurationParseError::NumberOverflow)?; + } + c if c.is_whitespace() => {} + 'a'..='z' | 'A'..='Z' => { + break; + } + _ => { + return Err(DurationParseError::InvalidCharacter(off)); + } + } + off = self.off(); + } + let start = off; + let mut off = self.off(); + while let Some(c) = self.iter.next() { + match c { + '0'..='9' => { + self.parse_unit(n, start, off)?; + n = c as u64 - '0' as u64; + continue 'outer; + } + c if c.is_whitespace() => break, + 'a'..='z' | 'A'..='Z' => {} + _ => { + return Err(DurationParseError::InvalidCharacter(off)); + } + } + off = self.off(); + } + self.parse_unit(n, start, off)?; + n = match self.parse_first_char()? { + Some(n) => n, + None => return Ok(self.duration), + }; + } + } +} diff --git a/core/expression/src/lane/date/duration_unit.rs b/core/expression/src/lane/date/duration_unit.rs new file mode 100644 index 00000000..4427428d --- /dev/null +++ b/core/expression/src/lane/date/duration_unit.rs @@ -0,0 +1,44 @@ +#[derive(Debug, Clone, Copy)] +pub(crate) enum DurationUnit { + Second, + Minute, + Hour, + Day, + Week, + Month, + Quarter, + Year, +} + +impl DurationUnit { + pub fn parse(unit: &str) -> Option { + match unit { + "seconds" | "second" | "secs" | "sec" | "s" => Some(Self::Second), + "minutes" | "minute" | "min" | "mins" | "m" => Some(Self::Minute), + "hours" | "hour" | "hr" | "hrs" | "h" => Some(Self::Hour), + "days" | "day" | "d" => Some(Self::Day), + "weeks" | "week" | "w" => Some(Self::Week), + "months" | "month" | "mo" | "M" => Some(Self::Month), + "quarters" | "quarter" | "qtr" | "q" => Some(Self::Quarter), + "years" | "year" | "y" => Some(Self::Year), + _ => None, + } + } + + pub fn as_secs(&self) -> Option { + match self { + DurationUnit::Second => Some(1), + DurationUnit::Minute => Some(60), + DurationUnit::Hour => Some(3600), + DurationUnit::Day => Some(86_400), + DurationUnit::Week => Some(86_400 * 7), + DurationUnit::Quarter => None, + DurationUnit::Month => None, + DurationUnit::Year => None, + } + } + + pub fn as_millis(&self) -> Option { + self.as_secs().map(|s| s as f64 * 1000_f64) + } +} diff --git a/core/expression/src/lane/date/helpers.rs b/core/expression/src/lane/date/helpers.rs new file mode 100644 index 00000000..ee301bcc --- /dev/null +++ b/core/expression/src/lane/date/helpers.rs @@ -0,0 +1,262 @@ +use crate::lane::date::utc_now; +use crate::vm::VMError; +use chrono::format::{parse, Item, ParseResult, Parsed, StrftimeItems}; +use chrono::{DateTime, Datelike, Days, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday}; +use once_cell::sync::Lazy; + +type VMResult = Result; + +#[allow(clippy::unwrap_used)] +static ZERO_TIME: Lazy = Lazy::new(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap()); + +static DATE_TIME: &str = "%Y-%m-%d %H:%M:%S"; +static DATE: &str = "%Y-%m-%d"; +static TIME_HMS: &str = "%H:%M:%S"; +static TIME_HM: &str = "%H:%M"; +static TIME_H: &str = "%H"; + +static DATE_TIME_ITEMS: Lazy>> = Lazy::new(|| { + StrftimeItems::new(DATE_TIME) + .parse_to_owned() + .unwrap_or_default() +}); +static DATE_ITEMS: Lazy>> = Lazy::new(|| { + StrftimeItems::new(DATE) + .parse_to_owned() + .unwrap_or_default() +}); + +pub(crate) struct Formats; + +impl Formats { + fn date_time(s: &str) -> ParseResult { + let mut parsed = Parsed::new(); + parse(&mut parsed, s, DATE_TIME_ITEMS.iter())?; + parsed.to_naive_datetime_with_offset(0) + } + + fn date(s: &str) -> ParseResult { + let mut parsed = Parsed::new(); + parse(&mut parsed, s, DATE_ITEMS.iter())?; + parsed.to_naive_date() + } +} + +pub(crate) struct IsoDate; + +impl IsoDate { + fn digits(bytes: &[u8]) -> Option { + bytes.iter().try_fold(0u32, |acc, c| { + c.is_ascii_digit().then(|| acc * 10 + (c - b'0') as u32) + }) + } + + pub(crate) fn utc(s: &str) -> bool { + s.as_bytes().get(10) == Some(&b'T') + } + + pub(crate) fn parse(s: &str) -> Option { + let b = s.as_bytes(); + if b.len() < 10 || b[4] != b'-' || b[7] != b'-' { + return None; + } + let date = NaiveDate::from_ymd_opt( + Self::digits(&b[0..4])? as i32, + Self::digits(&b[5..7])?, + Self::digits(&b[8..10])?, + )?; + let time = match &b[10..] { + [] => (0, 0, 0), + [sep, h1, h2, b':', m1, m2, b':', s1, s2, rest @ ..] + if (*sep == b' ' && rest.is_empty()) || (*sep == b'T' && rest == b"Z") => + { + ( + Self::digits(&[*h1, *h2])?, + Self::digits(&[*m1, *m2])?, + Self::digits(&[*s1, *s2])?, + ) + } + _ => return None, + }; + date.and_hms_opt(time.0, time.1, time.2) + } +} + +pub(crate) fn date_time(str: &str) -> VMResult { + if str == "now" { + return Ok(utc_now().naive_utc()); + } + + if let Some(parsed) = IsoDate::parse(str) { + return Ok(parsed); + } + + Formats::date_time(str) + .or_else(|_| Formats::date(str).map(|c| c.and_time(*ZERO_TIME))) + .or_else(|_| DateTime::parse_from_rfc3339(str).map(|dt| dt.naive_utc())) + .map_err(|_| VMError::ParseDateTimeErr { + timestamp: str.to_string(), + }) +} + +pub(crate) fn time(str: &str) -> VMResult { + let now = utc_now(); + + if str == "now" { + return Ok(now.naive_utc().time()); + } + + NaiveTime::parse_from_str(str, DATE_TIME) + .or(NaiveTime::parse_from_str(str, TIME_HMS)) + .or(NaiveTime::parse_from_str(str, TIME_HM)) + .or(NaiveTime::parse_from_str(str, TIME_H)) + .or(DateTime::parse_from_rfc3339(str).map(|dt| dt.naive_utc().time())) + .map_err(|_| VMError::ParseDateTimeErr { + timestamp: str.to_string(), + }) +} + +pub(crate) enum DateUnit { + Second, + Minute, + Hour, + Day, + Week, + Month, + Year, +} + +impl TryFrom<&str> for DateUnit { + type Error = VMError; + + fn try_from(value: &str) -> Result { + match value { + "s" | "second" | "seconds" => Ok(Self::Second), + "m" | "minute" | "minutes" => Ok(Self::Minute), + "h" | "hour" | "hours" => Ok(Self::Hour), + "d" | "day" | "days" => Ok(Self::Day), + "w" | "week" | "weeks" => Ok(Self::Week), + "M" | "month" | "months" => Ok(Self::Month), + "y" | "year" | "years" => Ok(Self::Year), + _ => Err(VMError::OpcodeErr { + opcode: "DateUnit".into(), + message: "Unknown date unit".into(), + }), + } + } +} + +pub(crate) fn date_time_start_of(date: NaiveDateTime, unit: DateUnit) -> Option { + match unit { + DateUnit::Second => Some(date), + DateUnit::Minute => date.with_second(0), + DateUnit::Hour => date.with_second(0)?.with_minute(0), + DateUnit::Day => date.with_second(0)?.with_minute(0)?.with_hour(0), + DateUnit::Week => date + .with_second(0)? + .with_minute(0)? + .with_hour(0)? + .checked_sub_days(Days::new(date.weekday().num_days_from_monday() as u64)), + DateUnit::Month => date + .with_second(0)? + .with_minute(0)? + .with_hour(0)? + .with_day0(0), + DateUnit::Year => date + .with_second(0)? + .with_minute(0)? + .with_hour(0)? + .with_day0(0)? + .with_month0(0), + } +} + +pub(crate) fn date_time_end_of(date: NaiveDateTime, unit: DateUnit) -> Option { + match unit { + DateUnit::Second => Some(date), + DateUnit::Minute => date.with_second(59), + DateUnit::Hour => date.with_second(59)?.with_minute(59), + DateUnit::Day => date.with_second(59)?.with_minute(59)?.with_hour(23), + DateUnit::Week => date + .with_second(59)? + .with_minute(59)? + .with_hour(23)? + .checked_add_days(Days::new(Weekday::Sun as u64 - date.weekday() as u64)), + DateUnit::Month => date + .with_second(59)? + .with_minute(59)? + .with_hour(23)? + .with_day(get_month_days(&date)? as u32), + DateUnit::Year => date + .with_second(59)? + .with_minute(59)? + .with_hour(23)? + .with_day(get_month_days(&date)? as u32)? + .with_month0(11), + } +} + +fn get_month_days(date: &NaiveDateTime) -> Option { + Some( + NaiveDate::from_ymd_opt( + match date.month() { + 12 => date.year() + 1, + _ => date.year(), + }, + match date.month() { + 12 => 1, + _ => date.month() + 1, + }, + 1, + )? + .signed_duration_since(NaiveDate::from_ymd_opt(date.year(), date.month(), 1)?) + .num_days(), + ) +} + +#[cfg(test)] +mod iso_tests { + use super::{IsoDate, DATE, DATE_TIME, ZERO_TIME}; + use chrono::{DateTime, NaiveDate, NaiveDateTime}; + + fn chrono_chain(s: &str) -> Option { + NaiveDateTime::parse_from_str(s, DATE_TIME) + .or_else(|_| NaiveDate::parse_from_str(s, DATE).map(|c| c.and_time(*ZERO_TIME))) + .or_else(|_| DateTime::parse_from_rfc3339(s).map(|dt| dt.naive_utc())) + .ok() + } + + #[test] + fn iso_fast_path_agrees_with_chrono() { + let mut state = 0x2545F4914F6CDD1Du64; + let mut next = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let mut checked = 0; + for _ in 0..200_000 { + let year = 1900 + next(250); + let month = next(14); + let day = next(33); + let (h, m, sec) = (next(26), next(62), next(62)); + let s = match next(8) { + 0 => format!("{year:04}-{month:02}-{day:02}"), + 1 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}:{sec:02}"), + 2 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}Z"), + 3 => format!("{year:04}-{month}-{day}"), + 4 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}+02:00"), + 5 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}"), + 6 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}.5Z"), + _ => format!("{year:04}-{month:02}-{day:02}x"), + }; + let fast = IsoDate::parse(&s); + if fast.is_some() { + checked += 1; + assert_eq!(fast, chrono_chain(&s), "{s}"); + } + } + assert!(checked > 10_000); + } +} diff --git a/core/expression/src/lane/date/mod.rs b/core/expression/src/lane/date/mod.rs new file mode 100644 index 00000000..98dc55cb --- /dev/null +++ b/core/expression/src/lane/date/mod.rs @@ -0,0 +1,970 @@ +pub(crate) use crate::lane::date::duration::Duration; +pub(crate) use crate::lane::date::duration_unit::DurationUnit; +use crate::variable::DynamicVariable; +use crate::Variable; +use chrono::{DateTime, SecondsFormat, Utc}; +use chrono_tz::Tz; +use serde_json::Value; +use std::any::Any; +use std::fmt::{Display, Formatter}; +use std::rc::Rc; +use std::sync::OnceLock; + +mod duration; +mod duration_parser; +mod duration_unit; +pub(crate) mod helpers; + +#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Ord, Eq)] +pub(crate) struct Date(pub Option>); + +impl DynamicVariable for Date { + fn type_name(&self) -> &'static str { + "date" + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn to_value(&self) -> Value { + match self.0 { + None => Value::String(String::from("Invalid date")), + Some(d) => Value::String(d.to_rfc3339_opts(SecondsFormat::Secs, true)), + } + } +} + +impl Display for Date { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match &self.0 { + None => write!(f, "Invalid date"), + Some(d) => write!(f, "{}", d.to_rfc3339_opts(SecondsFormat::Secs, true)), + } + } +} + +impl From>> for Date { + fn from(value: Option>) -> Self { + Self(value) + } +} + +struct Formats; + +impl Formats { + const CAPACITY: usize = 256; + + thread_local! { + static CACHE: std::cell::RefCell< + ahash::HashMap>>>, + > = Default::default(); + } + + fn with(format: &str, f: impl FnOnce(Option<&[chrono::format::Item<'static>]>) -> T) -> T { + Self::CACHE.with_borrow_mut(|cache| { + if !cache.contains_key(format) { + if cache.len() >= Self::CAPACITY { + cache.clear(); + } + let items = chrono::format::StrftimeItems::new(format) + .parse_to_owned() + .ok(); + cache.insert(format.to_string(), items); + } + f(cache.get(format).and_then(|items| items.as_deref())) + }) + } +} + +impl Date { + pub fn now() -> Self { + Self(Some(helper::now())) + } + + pub fn yesterday() -> Self { + Self::now().sub(Duration::day()) + } + + pub fn tomorrow() -> Self { + Self::now().add(Duration::day()) + } + + pub fn new(var: Variable, tz_opt: Option) -> Self { + Self(helper::parse_date(var, tz_opt)) + } + + pub(crate) fn text(str: &str, tz_opt: Option) -> Self { + Self(helper::parse_str(str, tz_opt.unwrap_or_else(helper::tz))) + } + + pub fn is_valid(&self) -> bool { + self.0.is_some() + } + + pub fn tz(&self, timezone: Tz) -> Self { + let Some(date_time) = &self.0 else { + return *self; + }; + + Self(Some(date_time.with_timezone(&timezone))) + } + + pub fn format(&self, format: Option<&str>) -> String { + let Some(date_time) = &self.0 else { + return self.to_string(); + }; + + match format { + None => date_time.to_string(), + Some(fmt) => Formats::with(fmt, |items| { + let mut out = String::with_capacity(32); + let written = items.map(|items| { + std::fmt::Write::write_fmt( + &mut out, + format_args!("{}", date_time.format_with_items(items.iter())), + ) + }); + match written { + Some(Ok(())) => out, + _ => date_time.format(fmt).to_string(), + } + }), + } + } + + pub fn add(&self, duration: Duration) -> Self { + let Some(date_time) = &self.0 else { + return Self(None); + }; + + Self(helper::add_duration(*date_time, duration)) + } + + pub fn sub(&self, duration: Duration) -> Self { + let Some(date_time) = &self.0 else { + return Self(None); + }; + + Self(helper::add_duration(*date_time, duration.negate())) + } + + pub fn start_of(&self, unit: DurationUnit) -> Self { + let Some(date_time) = &self.0 else { + return Self(None); + }; + + Self(helper::start_of(*date_time, unit)) + } + + pub fn end_of(&self, unit: DurationUnit) -> Self { + let Some(date_time) = &self.0 else { + return Self(None); + }; + + Self(helper::end_of(*date_time, unit)) + } + + pub fn diff(&self, date_time: &Self, unit: Option) -> Option { + let (dt1, dt2) = match (self.0, date_time.0) { + (Some(a), Some(b)) => (a, b), + _ => return None, + }; + + helper::diff(dt1, dt2, unit) + } + + pub fn set(&self, value: u32, unit: DurationUnit) -> Self { + let Some(date_time) = self.0 else { + return Self(None); + }; + + Self(helper::set(date_time, value, unit)) + } + + pub fn is_same(&self, other: &Self, unit: Option) -> bool { + let (dt1, dt2) = match (self.0, other.0) { + (Some(a), Some(b)) => (a, b), + _ => return false, + }; + + helper::is_same(dt1, dt2, unit).unwrap_or(false) + } + + pub fn is_before(&self, other: &Self, unit: Option) -> bool { + let (dt1, dt2) = match (self.0, other.0) { + (Some(a), Some(b)) => (a, b), + _ => return false, + }; + + helper::is_before(dt1, dt2, unit).unwrap_or(false) + } + + pub fn is_after(&self, other: &Self, unit: Option) -> bool { + let (dt1, dt2) = match (self.0, other.0) { + (Some(a), Some(b)) => (a, b), + _ => return false, + }; + + helper::is_after(dt1, dt2, unit).unwrap_or(false) + } + + pub fn is_same_or_before(&self, other: &Self, unit: Option) -> bool { + self.is_before(other, unit) || self.is_same(other, unit) + } + + pub fn is_same_or_after(&self, other: &Self, unit: Option) -> bool { + self.is_after(other, unit) || self.is_same(other, unit) + } +} + +mod helper { + use crate::lane::date::{utc_now, Duration, DurationUnit, DynamicVariableExt}; + use crate::Variable; + use chrono::{ + DateTime, Datelike, Days, FixedOffset, LocalResult, Month, Months, NaiveDate, + NaiveDateTime, Offset, TimeDelta, TimeZone, Timelike, + }; + use chrono_tz::Tz; + use rust_decimal::prelude::ToPrimitive; + use std::ops::Deref; + use std::str::FromStr; + use std::sync::OnceLock; + + pub(super) fn tz() -> Tz { + static CACHED_TZ: OnceLock = OnceLock::new(); + + *CACHED_TZ.get_or_init(|| { + iana_time_zone::get_timezone() + .ok() + .and_then(|tz| Tz::from_str(&tz).ok()) + .unwrap_or(Tz::UTC) + }) + } + + pub fn now() -> DateTime { + now_tz(tz()) + } + + pub fn now_tz(tz: Tz) -> DateTime { + utc_now().with_timezone(&tz) + } + + pub fn parse_date(var: Variable, tz_opt: Option) -> Option> { + match var { + Variable::Number(n) => { + let tz = tz_opt.unwrap_or_else(tz); + let n_i64 = n.to_i64()?; + let date_time = match tz.timestamp_millis_opt(n_i64) { + LocalResult::Single(date_time) => date_time, + LocalResult::Ambiguous(date_time, _) => date_time, + LocalResult::None => return None, + }; + + Some(date_time) + } + Variable::String(str) => parse_str(str.deref(), tz_opt.unwrap_or_else(tz)), + Variable::Dynamic(d) => { + let date = d.as_date()?; + let source = d + .as_any() + .downcast_ref::() + .and_then(|v| v.source()); + match (tz_opt, source) { + (Some(tz), Some(text)) => parse_text(text, tz), + (Some(tz), None) => date.0.map(|date_time| date_time.with_timezone(&tz)), + (None, _) => date.0, + } + } + _ => None, + } + } + + pub(crate) fn parse_str(str: &str, tz: Tz) -> Option> { + parse_text(str, tz).or_else(|| zone_now(str)) + } + + #[cold] + #[inline(never)] + fn zone_now(str: &str) -> Option> { + Tz::from_str(str).ok().map(now_tz) + } + + pub(crate) fn from_text(str: &str) -> Option> { + parse_text(str, tz()) + } + + #[inline] + pub(crate) fn parse_text(str: &str, tz: Tz) -> Option> { + use crate::lane::date::helpers::IsoDate; + match IsoDate::parse(str) { + Some(naive) if IsoDate::utc(str) => Some(tz.from_utc_datetime(&naive)), + Some(naive) => resolve_local(naive, tz), + None => parse_slow(str, tz), + } + } + + const LENIENT: [&str; 2] = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"]; + + const SHAPED: [(&str, &str); 11] = [ + ("9999-99-99T99:99:99", "%Y-%m-%dT%H:%M:%S%.f"), + ("9999-99-99T99:99", "%Y-%m-%dT%H:%M"), + ("9999-99-99 99:99:99", "%Y-%m-%d %H:%M:%S%.f"), + ("99999999T999999", "%Y%m%dT%H%M%S%.f"), + ("99999999T9999", "%Y%m%dT%H%M"), + ("9999/99/99 99:99:99", "%Y/%m/%d %H:%M:%S%.f"), + ("9999/99/99 99:99", "%Y/%m/%d %H:%M"), + ("99999999", "%Y%m%d"), + ("9999/99/99", "%Y/%m/%d"), + ("9999-99", "%Y-%m"), + ("9999", "%Y"), + ]; + + fn shape(value: &str) -> String { + let seconds = value + .rfind('.') + .filter(|&dot| { + dot + 1 < value.len() && value[dot + 1..].bytes().all(|b| b.is_ascii_digit()) + }) + .map_or(value, |dot| &value[..dot]); + seconds + .chars() + .map(|c| if c.is_ascii_digit() { '9' } else { c }) + .collect() + } + + fn parse_shaped(value: &str) -> Option { + let shape = shape(value); + let (_, format) = SHAPED.iter().find(|(pattern, _)| *pattern == shape)?; + match *format { + "%Y" => NaiveDate::from_ymd_opt(value.parse().ok()?, 1, 1)?.and_hms_opt(0, 0, 0), + "%Y-%m" => NaiveDate::parse_from_str(&format!("{value}-01"), "%Y-%m-%d") + .ok()? + .and_hms_opt(0, 0, 0), + format if !format.contains("%H") => NaiveDate::parse_from_str(value, format) + .ok()? + .and_hms_opt(0, 0, 0), + format => NaiveDateTime::parse_from_str(value, format).ok(), + } + } + + fn split_offset(value: &str) -> Option<(&str, FixedOffset)> { + if let Some(local) = value.strip_suffix('Z') { + return Some((local, FixedOffset::east_opt(0)?)); + } + let time = value.find('T')?; + let sign_at = value[time..].rfind(['+', '-'])? + time; + let digits: String = value[sign_at + 1..].chars().filter(|c| *c != ':').collect(); + let valid = matches!(value.len() - sign_at - 1, 2 | 4 | 5) + && matches!(digits.len(), 2 | 4) + && digits.bytes().all(|b| b.is_ascii_digit()); + if !valid { + return None; + } + let hours: i32 = digits[..2].parse().ok()?; + let minutes: i32 = match &digits[2..] { + "" => 0, + minutes => minutes.parse().ok()?, + }; + let sign = if value.as_bytes()[sign_at] == b'-' { + -1 + } else { + 1 + }; + let seconds = sign * (hours * 3600 + minutes * 60); + Some((&value[..sign_at], FixedOffset::east_opt(seconds)?)) + } + + #[inline] + pub(crate) fn resolve_local(naive: NaiveDateTime, tz: Tz) -> Option> { + tz.from_local_datetime(&naive) + .earliest() + .or_else(|| skip_gap(naive, tz)) + } + + #[cold] + #[inline(never)] + fn skip_gap(naive: NaiveDateTime, tz: Tz) -> Option> { + let before = tz + .from_local_datetime(&naive.checked_sub_signed(TimeDelta::hours(3))?) + .earliest()?; + Some(tz.from_utc_datetime(&naive.checked_sub_offset(before.offset().fix())?)) + } + + #[cold] + #[inline(never)] + pub(crate) fn parse_slow(value: &str, tz: Tz) -> Option> { + if let Ok(date_time) = DateTime::parse_from_rfc3339(value) { + return Some(date_time.with_timezone(&tz)); + } + if let Some(naive) = LENIENT + .iter() + .find_map(|format| NaiveDateTime::parse_from_str(value, format).ok()) + .or_else(|| { + NaiveDate::parse_from_str(value, "%Y-%m-%d") + .ok()? + .and_hms_opt(0, 0, 0) + }) + { + return resolve_local(naive, tz); + } + match split_offset(value) { + Some((local, offset)) if local.contains('T') => { + let naive = parse_shaped(local)?; + let utc = naive.checked_sub_offset(offset)?; + (utc.year().abs() <= 9999).then(|| tz.from_utc_datetime(&utc)) + } + _ => { + let naive = parse_shaped(value)?; + (naive.year().abs() <= 9999).then(|| resolve_local(naive, tz))? + } + } + } + + pub fn add_duration(date_time: DateTime, duration: Duration) -> Option> { + let tz = date_time.timezone(); + match Calendar::fixed_utc(tz) { + true => Some(tz.from_utc_datetime(&Calendar::shift(date_time.naive_utc(), duration)?)), + false => Calendar::shift(date_time, duration), + } + } + + pub fn start_of(date_time: DateTime, unit: DurationUnit) -> Option> { + let tz = date_time.timezone(); + match Calendar::fixed_utc(tz) { + true => Some(tz.from_utc_datetime(&Calendar::start_of(date_time.naive_utc(), unit)?)), + false => Calendar::start_of(date_time, unit), + } + } + + pub fn end_of(date_time: DateTime, unit: DurationUnit) -> Option> { + let tz = date_time.timezone(); + match Calendar::fixed_utc(tz) { + true => Some(tz.from_utc_datetime(&Calendar::end_of(date_time.naive_utc(), unit)?)), + false => Calendar::end_of(date_time, unit), + } + } + + pub(crate) trait Clock: Datelike + Timelike + Sized { + fn add_days(self, days: Days) -> Option; + fn sub_days(self, days: Days) -> Option; + fn plus(self, delta: TimeDelta) -> Option; + fn add_months(self, months: Months) -> Option; + fn sub_months(self, months: Months) -> Option; + } + + impl Clock for DateTime { + fn add_days(self, days: Days) -> Option { + self.checked_add_days(days) + } + + fn sub_days(self, days: Days) -> Option { + self.checked_sub_days(days) + } + + fn plus(self, delta: TimeDelta) -> Option { + self.checked_add_signed(delta) + } + + fn add_months(self, months: Months) -> Option { + self.checked_add_months(months) + } + + fn sub_months(self, months: Months) -> Option { + self.checked_sub_months(months) + } + } + + impl Clock for NaiveDateTime { + fn add_days(self, days: Days) -> Option { + self.checked_add_days(days) + } + + fn sub_days(self, days: Days) -> Option { + self.checked_sub_days(days) + } + + fn plus(self, delta: TimeDelta) -> Option { + self.checked_add_signed(delta) + } + + fn add_months(self, months: Months) -> Option { + self.checked_add_months(months) + } + + fn sub_months(self, months: Months) -> Option { + self.checked_sub_months(months) + } + } + + pub(crate) struct Calendar; + + impl Calendar { + pub(crate) fn shift(mut date_time: T, duration: Duration) -> Option { + date_time = date_time.plus(TimeDelta::try_seconds(duration.seconds)?)?; + date_time = match duration.months < 0 { + true => date_time.sub_months(Months::new(duration.months.unsigned_abs()))?, + false => date_time.add_months(Months::new(duration.months.unsigned_abs()))?, + }; + date_time.with_year(date_time.year().checked_add(duration.years)?) + } + + pub(crate) fn fixed_utc(tz: Tz) -> bool { + matches!( + tz, + Tz::UTC + | Tz::Etc__UTC + | Tz::Etc__GMT + | Tz::GMT + | Tz::Etc__Universal + | Tz::Universal + | Tz::Zulu + | Tz::Etc__Zulu + | Tz::UCT + | Tz::Etc__UCT + ) + } + + pub(crate) fn start_of(date_time: T, unit: DurationUnit) -> Option { + Some(match unit { + DurationUnit::Second => date_time.with_nanosecond(0)?, + DurationUnit::Minute => date_time.with_second(0)?.with_nanosecond(0)?, + DurationUnit::Hour => date_time + .with_minute(0)? + .with_second(0)? + .with_nanosecond(0)?, + DurationUnit::Day => date_time + .with_hour(0)? + .with_minute(0)? + .with_second(0)? + .with_nanosecond(0)?, + DurationUnit::Week => { + let weekday = date_time.weekday().num_days_from_monday(); + + date_time + .sub_days(Days::new(weekday.to_u64()?))? + .with_hour(0)? + .with_minute(0)? + .with_second(0)? + .with_nanosecond(0)? + } + DurationUnit::Month => date_time + .with_day0(0)? + .with_hour(0)? + .with_minute(0)? + .with_second(0)? + .with_nanosecond(0)?, + DurationUnit::Quarter => date_time + .with_month0((date_time.quarter() - 1) * 3)? + .with_day0(0)? + .with_hour(0)? + .with_minute(0)? + .with_second(0)? + .with_nanosecond(0)?, + DurationUnit::Year => date_time + .with_month0(0)? + .with_day0(0)? + .with_hour(0)? + .with_minute(0)? + .with_second(0)? + .with_nanosecond(0)?, + }) + } + + pub(crate) fn end_of(mut date_time: T, unit: DurationUnit) -> Option { + date_time = date_time.with_nanosecond(999_999_999)?; + + Some(match unit { + DurationUnit::Second => date_time, + DurationUnit::Minute => date_time.with_second(59)?, + DurationUnit::Hour => date_time.with_minute(59)?.with_second(59)?, + DurationUnit::Day => date_time.with_hour(23)?.with_minute(59)?.with_second(59)?, + DurationUnit::Week => { + let days_until_sunday = 6 - date_time.weekday().num_days_from_monday(); + + date_time + .add_days(Days::new(days_until_sunday.to_u64()?))? + .with_hour(23)? + .with_minute(59)? + .with_second(59)? + } + DurationUnit::Month => { + let month = Month::try_from(date_time.month().to_u8()?).ok()?; + let days_in_month = month.num_days(date_time.year())?.to_u32()?; + + date_time + .with_day(days_in_month)? + .with_hour(23)? + .with_minute(59)? + .with_second(59)? + } + DurationUnit::Quarter => { + let new_month_index = date_time.quarter() * 3; + let month = Month::try_from(new_month_index.to_u8()?).ok()?; + let days_in_month = month.num_days(date_time.year())?.to_u32()?; + + date_time + .with_month(month.number_from_month())? + .with_day(days_in_month)? + .with_hour(23)? + .with_minute(59)? + .with_second(59)? + } + DurationUnit::Year => { + let year = date_time.year(); + let month = Month::December; + let days_in_month = month.num_days(year)?.to_u32()?; + + date_time + .with_month(month.number_from_month())? + .with_day(days_in_month)? + .with_hour(23)? + .with_minute(59)? + .with_second(59)? + } + }) + } + } + + pub fn diff(a: DateTime, b: DateTime, maybe_unit: Option) -> Option { + let zone_delta = (b.offset().fix().local_minus_utc() as i64 + - a.offset().fix().local_minus_utc() as i64) + * 1000; + + let diff_ms = a.timestamp_millis() - b.timestamp_millis(); + let Some(unit) = maybe_unit else { + return Some(diff_ms); + }; + + let result = match unit { + DurationUnit::Year => month_diff(a, b) / 12.0, + DurationUnit::Month => month_diff(a, b), + DurationUnit::Quarter => month_diff(a, b) / 3.0, + DurationUnit::Week => { + (diff_ms - zone_delta) as f64 / DurationUnit::Week.as_millis().unwrap_or_default() + } + DurationUnit::Day => { + (diff_ms - zone_delta) as f64 / DurationUnit::Day.as_millis().unwrap_or_default() + } + DurationUnit::Hour => { + diff_ms as f64 / DurationUnit::Hour.as_millis().unwrap_or_default() + } + DurationUnit::Minute => { + diff_ms as f64 / DurationUnit::Minute.as_millis().unwrap_or_default() + } + DurationUnit::Second => { + diff_ms as f64 / DurationUnit::Second.as_millis().unwrap_or_default() + } + }; + + Some(if result < 0.0 { + result.ceil() as i64 + } else { + result.floor() as i64 + }) + } + + pub fn set(date_time: DateTime, value: u32, unit: DurationUnit) -> Option> { + match unit { + DurationUnit::Second => date_time.with_second(value), + DurationUnit::Minute => date_time.with_minute(value), + DurationUnit::Hour => date_time.with_hour(value), + DurationUnit::Day => date_time.with_day(value), + DurationUnit::Month => date_time.with_month(value), + DurationUnit::Year => date_time.with_year(value.to_i32()?), + DurationUnit::Week | DurationUnit::Quarter => Some(date_time), + } + } + + pub fn is_same(a: DateTime, b: DateTime, unit: Option) -> Option { + match unit { + Some(unit) => { + let start_a = start_of(a, unit)?; + let end_a = end_of(a, unit)?; + + Some(start_a <= b && b <= end_a) + } + None => Some(a.timestamp_millis() == b.timestamp_millis()), + } + } + + pub fn is_before(a: DateTime, b: DateTime, unit: Option) -> Option { + match unit { + Some(unit) => { + let end_a = end_of(a, unit)?; + Some(end_a < b) + } + None => Some(a < b), + } + } + + pub fn is_after(a: DateTime, b: DateTime, unit: Option) -> Option { + match unit { + Some(unit) => { + let start_a = start_of(a, unit)?; + Some(b < start_a) + } + None => Some(a > b), + } + } + + fn month_diff(a: DateTime, b: DateTime) -> f64 { + if a.day() < b.day() { + return -month_diff(b, a); + } + + let whole_month_diff = ((b.year() - a.year()) * 12) + (b.month() as i32 - a.month() as i32); + let anchor = add_months_to_date(a, whole_month_diff); + let c = (b.timestamp_millis() - anchor.timestamp_millis()) < 0; + let anchor2 = add_months_to_date(a, whole_month_diff + if c { -1 } else { 1 }); + + let numerator = b.timestamp_millis() - anchor.timestamp_millis(); + let denominator = if c { + anchor.timestamp_millis() - anchor2.timestamp_millis() + } else { + anchor2.timestamp_millis() - anchor.timestamp_millis() + }; + + let fractional = if denominator != 0 { + numerator as f64 / denominator as f64 + } else { + 0.0 + }; + + -((whole_month_diff as f64) + fractional) + } + + fn add_months_to_date(date: DateTime, months: i32) -> DateTime { + if months >= 0 { + date.checked_add_months(Months::new(months as u32)) + } else { + date.checked_sub_months(Months::new((-months) as u32)) + } + .unwrap_or(date) + } +} + +pub(crate) trait DynamicVariableExt { + fn as_date(&self) -> Option; +} + +impl DynamicVariableExt for dyn DynamicVariable { + fn as_date(&self) -> Option { + let any = self.as_any(); + any.downcast_ref::() + .copied() + .or_else(|| any.downcast_ref::().map(|d| Date(d.0))) + } +} + +impl Date { + pub(crate) fn of(v: &Variable) -> Option { + match v { + Variable::Dynamic(d) => d.as_date(), + _ => None, + } + } + + pub(crate) fn variable(self) -> Variable { + Variable::Dynamic(Rc::new(crate::vm::VmDate::from(self.0))) + } + + pub(crate) fn coerce(v: &Variable) -> Option { + match v { + Variable::Dynamic(d) => d.as_date(), + Variable::String(text) => Some(Self::from_text(text)), + _ => None, + } + } + + pub(crate) fn parses(text: &str) -> bool { + helper::parse_text(text, helper::tz()).is_some() + } + + pub(crate) fn from_text(text: &str) -> Date { + Date(helper::from_text(text)) + } + + pub(crate) fn matches(&self, other: &Variable) -> bool { + self.0.is_some() && Self::coerce(other).is_some_and(|other| other == *self) + } + + pub(crate) fn rendered(&self) -> Option { + self.0 + .map(|date_time| date_time.to_rfc3339_opts(SecondsFormat::Secs, true)) + } + + pub(crate) fn source(v: &Variable) -> Option<&str> { + match v { + Variable::Dynamic(d) => d.as_any().downcast_ref::()?.source(), + _ => None, + } + } + + pub(crate) fn sourced(v: &Variable) -> bool { + Self::source(v).is_some() + } + + #[inline] + pub(crate) fn textual(v: Variable) -> Variable { + match &v { + Variable::Dynamic(d) => match d.as_text() { + Some(text) => Variable::String(text.into()), + None => v, + }, + _ => v, + } + } +} + +pub(crate) fn utc_now() -> DateTime { + static CURRENT_DATE_VALUE: OnceLock>> = OnceLock::new(); + + CURRENT_DATE_VALUE + .get_or_init(|| match std::env::var("__ZEN_MOCK_UTC_TIME") { + Ok(v) => v.parse::>().ok(), + Err(_) => None, + }) + .unwrap_or_else(Utc::now) +} + +#[cfg(test)] +mod format_tests { + use super::Date; + use crate::Variable; + + #[test] + fn cached_formats_match_chrono() { + let formats = [ + "%Y-%m-%d", + "%d/%m/%Y %H:%M:%S", + "%A, %B %e %Y", + "%j %U %W %u", + "%s", + "%+", + "%.3f %Z %z", + "YYYY-MM-DD", + "%%", + "", + "%Y%m%d%H%M%S", + "%-d.%-m.%y", + ]; + let dates = [ + "2025-03-15T10:30:00Z", + "1999-12-31 23:59:59", + "2024-02-29", + "2025-10-26 02:30:00", + ]; + for date in dates { + let vm = Date::new(Variable::String(date.into()), None); + let Some(dt) = vm.0 else { continue }; + for format in formats { + for _ in 0..2 { + assert_eq!( + vm.format(Some(format)), + dt.format(format).to_string(), + "{date} {format}" + ); + } + } + } + } +} + +#[cfg(test)] +mod parse_tests { + use super::helper::{parse_slow, parse_text}; + use chrono_tz::Tz; + + #[test] + fn iso_fast_path_agrees_with_text_parsing() { + let mut state = 0x853C49E6748FEA9Bu64; + let mut next = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let zones = [ + Tz::UTC, + Tz::Europe__Berlin, + Tz::America__New_York, + Tz::Asia__Kolkata, + ]; + for _ in 0..200_000 { + let year = 1900 + next(250); + let (month, day) = (next(14), next(33)); + let (h, m, sec) = (next(26), next(62), next(62)); + let text = match next(7) { + 0 => format!("{year:04}-{month:02}-{day:02}"), + 1 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}:{sec:02}"), + 2 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}Z"), + 3 => format!("{year:04}-03-{:02} 02:{m:02}:00", 25 + next(7)), + 4 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}+02:00"), + 5 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}"), + _ => format!("{year:04}-{month}-{day}"), + }; + let tz = zones[next(zones.len() as u64) as usize]; + assert_eq!(parse_text(&text, tz), parse_slow(&text, tz), "{text} {tz}"); + } + } +} + +#[cfg(test)] +mod calendar_tests { + use super::helper::{add_duration, end_of, start_of, Calendar}; + use super::DurationUnit; + use chrono::{TimeZone, Utc}; + use chrono_tz::Tz; + + #[test] + fn fixed_utc_shortcut_matches_chained_steps() { + let units = [ + DurationUnit::Second, + DurationUnit::Minute, + DurationUnit::Hour, + DurationUnit::Day, + DurationUnit::Week, + DurationUnit::Month, + DurationUnit::Quarter, + DurationUnit::Year, + ]; + let mut state = 0x6A09E667F3BCC909u64; + let mut next = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + for _ in 0..50_000 { + let seconds = next(8_000_000_000) as i64 - 2_000_000_000; + let nanos = next(1_000_000_000) as u32; + let Some(instant) = Utc.timestamp_opt(seconds, nanos).single() else { + continue; + }; + for tz in [Tz::UTC, Tz::Etc__UTC, Tz::GMT] { + let date_time = instant.with_timezone(&tz); + for unit in units { + assert_eq!( + start_of(date_time, unit), + Calendar::start_of(date_time, unit), + "{date_time} {unit:?}" + ); + assert_eq!( + end_of(date_time, unit), + Calendar::end_of(date_time, unit), + "{date_time} {unit:?}" + ); + let amount = rust_decimal::Decimal::from(next(80) as i64 - 40); + if let Some(duration) = super::Duration::from_unit(amount, unit) { + assert_eq!( + add_duration(date_time, duration.clone()), + Calendar::shift(date_time, duration), + "{date_time} {amount} {unit:?}" + ); + } + } + } + } + } +} diff --git a/core/expression/src/lane/effect.rs b/core/expression/src/lane/effect.rs new file mode 100644 index 00000000..04a997ac --- /dev/null +++ b/core/expression/src/lane/effect.rs @@ -0,0 +1,80 @@ +use crate::functions::{ + DateMethod, DeprecatedFunction, FunctionKind, InternalFunction, MethodKind, +}; +use crate::lane::date::Date; +use chrono_tz::Tz; +use std::str::FromStr; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Effect { + Pure, + Clock, + Random, +} + +#[derive(Clone, Copy)] +pub(crate) enum Literal<'a> { + Text(&'a str), + Constant, + Computed, +} + +impl Effect { + pub(crate) fn function(kind: &FunctionKind) -> Self { + match kind { + FunctionKind::Internal(InternalFunction::Rand) => Effect::Random, + FunctionKind::Internal(InternalFunction::Date) => Effect::Clock, + FunctionKind::Deprecated(DeprecatedFunction::Duration) => Effect::Pure, + FunctionKind::Deprecated(_) => Effect::Clock, + FunctionKind::Internal(_) | FunctionKind::Closure(_) => Effect::Pure, + } + } + + pub(crate) fn method(kind: &MethodKind) -> Self { + match kind { + MethodKind::DateMethod( + DateMethod::IsToday | DateMethod::IsYesterday | DateMethod::IsTomorrow, + ) => Effect::Clock, + MethodKind::DateMethod(_) => Effect::Pure, + } + } + + pub(crate) fn call<'a>( + kind: &FunctionKind, + mut literals: impl Iterator>, + ) -> Self { + match kind { + FunctionKind::Internal(InternalFunction::Date) => match literals.next() { + None | Some(Literal::Computed) => Effect::Clock, + Some(Literal::Constant) => Effect::Pure, + Some(Literal::Text(text)) if Date::parses(text) || Tz::from_str(text).is_err() => { + Effect::Pure + } + Some(Literal::Text(_)) => Effect::Clock, + }, + FunctionKind::Deprecated(DeprecatedFunction::Duration) => Effect::Pure, + FunctionKind::Deprecated(_) => { + match literals.all(|l| !matches!(l, Literal::Computed | Literal::Text("now"))) { + true => Effect::Pure, + false => Effect::Clock, + } + } + _ => Self::function(kind), + } + } + + pub(crate) fn formats(pattern: &str) -> bool { + use chrono::TimeZone; + let Ok(items) = chrono::format::StrftimeItems::new(pattern).parse_to_owned() else { + return false; + }; + Tz::UTC.timestamp_opt(0, 0).earliest().is_some_and(|date| { + let mut out = String::new(); + std::fmt::Write::write_fmt( + &mut out, + format_args!("{}", date.format_with_items(items.iter())), + ) + .is_ok() + }) + } +} diff --git a/core/expression/src/lane/exec/closure.rs b/core/expression/src/lane/exec/closure.rs new file mode 100644 index 00000000..1c649d4f --- /dev/null +++ b/core/expression/src/lane/exec/closure.rs @@ -0,0 +1,1474 @@ +use super::context::Context; +use super::frame::{Fallbacks, Fault}; +use super::frame::{Frame, Scratch}; +use super::Executor; +use crate::functions::ClosureFunction; +use crate::lane::builtins::Out; +use crate::lane::columns::{Column, Values}; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +use crate::lane::output::Item; +use crate::lane::program::{ClosureOp, FoldOp, Kind, Op, Reg, Step}; +use crate::lane::scaled::Scaled; +use crate::lane::Bits; +use crate::variable::Variable; +use crate::vm::VMError; + +#[derive(Debug)] +pub(super) enum Pending { + Array(Variable), + Child { start: usize, end: usize }, +} + +impl Pending { + pub(super) fn len(&self) -> usize { + match self { + Pending::Array(Variable::Array(arr)) => arr.borrow().len(), + Pending::Array(_) => 0, + Pending::Child { start, end } => end - start, + } + } +} + +pub(super) type Results<'a> = ( + &'a mut [Variable], + &'a [(u32, VMError)], + &'a [u64], + &'a [u64], +); + +pub(super) struct Outcomes<'a> { + pub(super) values: &'a mut [Variable], + pub(super) failures: &'a [(u32, VMError)], + pub(super) truths: &'a [u64], + pub(super) settled: &'a [u64], + pub(super) offset: usize, + pub(super) next: usize, +} + +impl<'a> Outcomes<'a> { + pub(super) fn new(scratch: Results<'a>, start: usize, end: usize) -> Self { + let (results, failures, truths, settled) = scratch; + let lo = failures.partition_point(|(i, _)| (*i as usize) < start); + let hi = failures.partition_point(|(i, _)| (*i as usize) < end); + Self { + values: &mut results[start..end], + failures: &failures[lo..hi], + truths, + settled, + offset: start, + next: 0, + } + } + + pub(super) fn len(&self) -> usize { + self.values.len() + } + + pub(super) fn take(&mut self, i: usize) -> Result { + match self.failures.get(self.next) { + Some((at, e)) if *at as usize == self.offset + i => { + self.next += 1; + Err(e.clone()) + } + _ => Ok(std::mem::replace(&mut self.values[i], Variable::Null)), + } + } + + pub(super) fn tally(&self) -> Option<(usize, usize)> { + let (start, end) = (self.offset, self.offset + self.values.len()); + let mut trues = 0usize; + let mut at = start; + while at < end { + let (word, shift) = (at / 64, at % 64); + let take = (64 - shift).min(end - at); + let mask = match take { + 64 => u64::MAX, + n => ((1u64 << n) - 1) << shift, + }; + if self.settled.get(word).copied().unwrap_or(0) & mask != mask { + return None; + } + trues += (self.truths.get(word).copied().unwrap_or(0) & mask).count_ones() as usize; + at += take; + } + Some((trues, end - start)) + } + + pub(super) fn decide(&self, kind: ClosureFunction) -> Option> { + let (trues, len) = self.tally()?; + Some(match kind { + ClosureFunction::Some => (trues > 0).then_some(true), + ClosureFunction::All => (trues < len).then_some(false), + _ => (trues > 0).then_some(false), + }) + } + + pub(super) fn peek(&mut self, i: usize) -> Result, VMError> { + let at = self.offset + i; + if Bits::get(self.settled, at) { + return Ok(Some(Bits::get(self.truths, at))); + } + match self.failures.get(self.next) { + Some((at, e)) if *at as usize == self.offset + i => { + self.next += 1; + Err(e.clone()) + } + _ => Ok(match self.values[i] { + Variable::Bool(b) => Some(b), + _ => None, + }), + } + } + + pub(super) fn truth(&mut self, i: usize) -> Result { + match self.peek(i)? { + Some(b) => Ok(b), + None => Ops::truthy(&self.take(i)?, "JumpIfFalse"), + } + } + + pub(super) fn verdict( + &mut self, + kind: ClosureFunction, + i: usize, + ) -> Result, VMError> { + match (self.peek(i)?, kind) { + (Some(b), ClosureFunction::Some) => Ok(b.then_some(true)), + (Some(b), ClosureFunction::All) => Ok((!b).then_some(false)), + (Some(b), _) => Ok(b.then_some(false)), + (None, _) => Executor::verdict(kind, self.take(i)), + } + } +} + +impl Executor { + pub(super) fn ones(words: &[u64], a: usize, b: usize) -> usize { + let mut count = 0usize; + let mut at = a; + while at < b { + let (word, shift) = (at / 64, at % 64); + let take = (64 - shift).min(b - at); + let mask = match take { + 64 => u64::MAX, + n => ((1u64 << n) - 1) << shift, + }; + count += (words.get(word).copied().unwrap_or(0) & mask).count_ones() as usize; + at += take; + } + count + } + + pub(super) fn sweep( + c: &ClosureOp, + active: M, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) -> bool { + if c.sequential || matches!(c.kind, ClosureFunction::FlatMap) || active.is_empty() { + return false; + } + let source = match Self::selection(c, f, ctx) { + Some(child) => Some((child, None)), + None => Self::list_children(c, ctx).map(|(child, column)| (child, Some(column))), + }; + let Some((child, column)) = source else { + return false; + }; + let child = &child; + let mut picks: Vec = Vec::new(); + let mut ranges = std::mem::take(&mut f.ranges); + ranges.clear(); + ranges.resize(f.width, (0, 0)); + let (mut lo, mut hi) = (None, 0usize); + for lane in Lanes::of(active) { + let range = match &column { + Some(column) => column.range(ctx.base + f.rows[lane] as usize), + None => match f.generic(c.list, lane) { + true => None, + false => { + let (x, y) = f.lists[f.at(c.list, lane)]; + let a = picks.len(); + f.items.rows(x as usize, y as usize).map(|rows| { + picks.extend(rows.iter().map(|r| *r as u32)); + (a, picks.len()) + }) + } + }, + }; + let Some((a, b)) = range else { + f.ranges = ranges; + return false; + }; + match lo { + None => lo = Some(a), + Some(_) if a != hi => return false, + Some(_) => {} + } + ranges[lane] = (a, b); + hi = b; + } + let Some(lo) = lo else { + return false; + }; + let total = hi - lo; + let selected = column.is_none(); + let index = |v: usize| match selected { + true => picks.get(v).copied().unwrap_or_default() as usize, + false => v, + }; + let (element, out) = (c.body.element.unwrap_or_default(), c.body.out as usize); + let predicate = !matches!(c.kind, ClosureFunction::Map); + if !predicate && f.kinds[c.dst as usize] != Kind::List { + return false; + } + let items = f.items.len(); + if !predicate && Self::project(c, child, f, lo..lo + total, selected.then_some(&picks)) { + let base = c.dst as usize * f.width; + for lane in Lanes::of(active) { + let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo); + f.lists[base + lane] = ((items + a) as u32, (items + b) as u32); + } + f.boxed[c.dst as usize] &= !active; + f.ranges = ranges; + return true; + } + let mut scratch = std::mem::take(&mut f.scratch); + let Scratch { + truths, + results, + rows, + parents, + .. + } = &mut scratch; + truths.clear(); + truths.resize(total.div_ceil(64), 0); + results.clear(); + parents.clear(); + rows.clear(); + let pure = c.imports.is_empty() && c.body.pure(); + match pure { + true => rows.extend(0..total.min(M::LANES) as u32), + false => { + for lane in Lanes::of(active) { + let (a, b) = ranges[lane]; + parents.extend(std::iter::repeat_n(lane as u32, b - a)); + rows.extend(std::iter::repeat_n(f.rows[lane], b - a)); + } + } + } + let projected = predicate + && Self::project_truths(c, child, truths, lo..lo + total, selected.then_some(&picks)); + if predicate && !projected { + truths.fill(0); + } + let mut ok = true; + let mut start = match projected { + true => total, + false => 0, + }; + while start < total { + let end = (start + M::LANES).min(total); + let width = end - start; + let Some(frame) = rest.first_mut() else { + ok = false; + break; + }; + match pure { + true => Self::enter(&c.body, frame, &rows[..end - start], None), + false => Self::enter( + &c.body, + frame, + &rows[start..end], + Some((f, &parents[start..end], &c.imports)), + ), + } + let viewed = + Self::elements(c, frame, child, ctx, width, |lane| index(lo + start + lane)); + if !viewed && (selected || !Self::fill_dense(frame, element, child, lo + start)) { + Self::fill_with(frame, element, child, M::all(width), |_, lane| { + index(lo + start + lane) + }); + } + Self::execute(&c.body, rest, ctx); + let frame = &mut rest[0]; + let all = M::all(width); + if frame.alive & !frame.boxed[out] & all != all { + ok = false; + break; + } + match (predicate, frame.kinds[out]) { + (true, Kind::Bool) => Self::put_bits(truths, start, width, frame.bits[out] & all), + (true, _) => { + ok = false; + break; + } + (false, _) => { + let (kind, base) = (frame.kinds[out], out * frame.width); + let clean = !frame.boxed[out] & !frame.wide[out]; + if kind == Kind::Num && clean == M::all(width) { + f.items.extend_nums( + &frame.mant[base..base + width], + &frame.scales[base..base + width], + ); + start = end; + continue; + } + for lane in 0..width { + let item = match (kind, clean.get(lane)) { + (Kind::Num, true) => { + Item::Num(frame.mant[base + lane], frame.scales[base + lane]) + } + (Kind::Bool, true) => Item::Bool(frame.bits[out].get(lane)), + (Kind::Str, true) => { + let (x, y) = frame.spans[base + lane]; + let text = + frame.arena.get(x as usize..y as usize).unwrap_or_default(); + let (origin, end) = f.intern(text); + Item::Text(origin, end) + } + _ => Item::Value(frame.take(out as Reg, lane)), + }; + f.items.push(item); + } + } + } + start = end; + } + if ok && predicate && !matches!(c.kind, ClosureFunction::Filter) { + let d = c.dst as usize; + let (base, kind) = (d * f.width, f.kinds[d]); + let mut word = f.none(); + for lane in Lanes::of(active) { + let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo); + let n = Self::ones(truths, a, b); + match (c.kind, kind) { + (ClosureFunction::Count, Kind::Num) => { + f.mant[base + lane] = n as i64; + f.scales[base + lane] = 0; + } + ( + ClosureFunction::One + | ClosureFunction::Some + | ClosureFunction::All + | ClosureFunction::None, + Kind::Bool, + ) => word.put(lane, c.kind.holds(n, b - a)), + _ => {} + } + } + match kind { + Kind::Num => f.wide[d] &= !active, + _ => f.bits[d] = (f.bits[d] & !active) | word, + } + f.boxed[d] &= !active; + ok = matches!(kind, Kind::Num | Kind::Bool); + } else if ok && !predicate { + let base = c.dst as usize * f.width; + for lane in Lanes::of(active) { + let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo); + f.lists[base + lane] = ((items + a) as u32, (items + b) as u32); + } + f.boxed[c.dst as usize] &= !active; + } else if ok + && f.kinds[c.dst as usize] == Kind::List + && c.select + && !selected + && matches!(child.values, Values::Struct { .. }) + { + let base = c.dst as usize * f.width; + let mut at = f.items.len(); + f.items.extend_rows(truths, 0, total, lo); + for lane in Lanes::of(active) { + let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo); + let end = at + Self::ones(truths, a, b); + f.lists[base + lane] = (at as u32, end as u32); + at = end; + } + ctx.register(f.program, c.dst, *child); + f.boxed[c.dst as usize] &= !active; + } else if ok && f.kinds[c.dst as usize] == Kind::List { + let base = c.dst as usize * f.width; + for lane in Lanes::of(active) { + let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo); + let start = f.items.len() as u32; + match (child.values, child.validity.is_some()) { + (Values::Struct { .. }, _) if c.select => { + for i in (a..b).filter(|i| Bits::get(truths, *i)) { + f.items.push(Item::Row(index(lo + i) as u32)); + } + } + (Values::I64(v), false) if !selected && lo + b <= v.len() => f + .items + .extend_selected(v.get(lo..).unwrap_or_default(), truths, a, b), + _ => { + for i in (a..b).filter(|i| Bits::get(truths, *i)) { + let item = Self::child_item(child, index(lo + i), f); + f.items.push(item); + } + } + } + f.lists[base + lane] = (start, f.items.len() as u32); + } + if c.select && matches!(child.values, Values::Struct { .. }) { + ctx.register(f.program, c.dst, *child); + } + f.boxed[c.dst as usize] &= !active; + } else if ok { + for lane in Lanes::of(active) { + let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo); + let value = match c.kind { + ClosureFunction::Filter => Variable::from_array( + (a..b) + .filter(|i| Bits::get(truths, *i)) + .map(|i| child.variable(index(lo + i))) + .collect(), + ), + kind => { + let n = Self::ones(truths, a, b); + match kind { + ClosureFunction::Count => Variable::Number(n.into()), + kind => Variable::Bool(kind.holds(n, b - a)), + } + } + }; + f.set(c.dst, lane, value); + } + } + if !ok { + f.items.truncate(items); + } + f.scratch = scratch; + f.ranges = ranges; + ok + } + + fn projected<'c>(c: &ClosureOp, child: &Column<'c>, kind: Kind) -> Option> { + let ( + Some(element), + [Step { + op: Op::Field { dst, src, key, .. }, + .. + }], + ) = (c.body.element, c.body.steps.as_slice()) + else { + return None; + }; + let plain = *src == element + && *dst == c.body.out + && c.body.kinds.get(*dst as usize) == Some(&kind) + && c.imports.is_empty() + && child.validity.is_none(); + child.field(key).filter(|_| plain).copied() + } + + fn project_truths( + c: &ClosureOp, + child: &Column, + truths: &mut [u64], + span: std::ops::Range, + picks: Option<&[u32]>, + ) -> bool { + let Some(field) = Self::projected(c, child, Kind::Bool) else { + return false; + }; + let Values::Bool { bits, offset } = field.values else { + return false; + }; + for (k, i) in span.enumerate() { + let row = match picks { + Some(picks) => picks.get(i).map(|p| *p as usize), + None => Some(i), + }; + let valid = row.filter(|row| { + field + .validity + .is_none_or(|(valid, at)| Bits::get(valid, at + row)) + }); + match (valid, truths.get_mut(k / 64)) { + (Some(row), Some(word)) => { + *word |= (Bits::get(bits, offset + row) as u64) << (k % 64) + } + _ => return false, + } + } + true + } + + fn project( + c: &ClosureOp, + child: &Column, + f: &mut Frame, + span: std::ops::Range, + picks: Option<&[u32]>, + ) -> bool { + let Some(field) = Self::projected(c, child, Kind::Num) else { + return false; + }; + let valid = match (field.validity, picks) { + (None, _) => true, + (Some(_), None) => span.clone().all(|i| field.valid(i)), + (Some(_), Some(picks)) => picks + .get(span.clone()) + .is_some_and(|picks| picks.iter().all(|p| field.valid(*p as usize))), + }; + if !valid { + return false; + } + let items = f.items.len(); + let done = match (field.values, picks) { + (Values::Scaled { mant, scale }, None) => mant + .get(span.clone()) + .zip(scale.get(span)) + .map(|(m, s)| f.items.extend_nums(m, s)) + .is_some(), + (Values::Scaled { mant, scale }, Some(picks)) => picks.get(span).is_some_and(|picks| { + f.items.extend_parts(picks.iter().map(|p| { + let p = *p as usize; + mant.get(p).zip(scale.get(p)).map(|(m, s)| (*m, *s)) + })) + }), + (Values::I64(values), None) => values + .get(span) + .is_some_and(|values| f.items.extend_parts(values.iter().map(|n| Some((*n, 0))))), + (Values::I64(values), Some(picks)) => picks.get(span).is_some_and(|picks| { + f.items.extend_parts( + picks + .iter() + .map(|p| values.get(*p as usize).map(|n| (*n, 0))), + ) + }), + (Values::Dec(values), None) => values + .get(span) + .is_some_and(|values| f.items.extend_parts(values.iter().map(Scaled::parts))), + (Values::Dec(values), Some(picks)) => picks.get(span).is_some_and(|picks| { + f.items.extend_parts( + picks + .iter() + .map(|p| values.get(*p as usize).and_then(Scaled::parts)), + ) + }), + _ => false, + }; + if !done { + f.items.truncate(items); + } + done + } + + pub(super) fn child_item(child: &Column, index: usize, f: &mut Frame) -> Item { + match (child.values, child.valid(index)) { + (Values::I64(v), true) => v + .get(index) + .map_or(Item::Value(Variable::Null), |n| Item::Num(*n, 0)), + (Values::Dec(v), true) => match v.get(index).and_then(Scaled::parts) { + Some((m, s)) => Item::Num(m, s), + None => Item::Value(child.variable(index)), + }, + ( + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_), + true, + ) => match child.text(index) { + Some(text) => { + let (origin, end) = f.intern(text); + Item::Text(origin, end) + } + None => Item::Value(child.variable(index)), + }, + _ => Item::Value(child.variable(index)), + } + } + + pub(super) fn closure( + c: &ClosureOp, + active: M, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) { + if Self::sweep(c, active, f, rest, ctx) { + return; + } + if let Some(column) = Self::selection(c, f, ctx) { + return Self::selected(c, &column, active, f, rest, ctx); + } + let decisive = matches!( + c.kind, + ClosureFunction::Some | ClosureFunction::All | ClosureFunction::None + ); + if decisive { + return Self::decisive(c, active, f, rest, ctx); + } + + let mut scratch = std::mem::take(&mut f.scratch); + scratch.items.clear(); + scratch.slots.clear(); + scratch.spans.clear(); + let children = Self::list_children(c, ctx); + if let Some((child, column)) = children { + let child = &child; + let lanes = Lanes::of(active).filter(|lane| { + let row = ctx.base + f.rows[*lane] as usize; + column.range(row).is_some() + }); + let covered = lanes.fold(f.none(), |mut acc, lane| { + acc.set(lane); + acc + }); + if covered == active { + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + let (a, b) = column + .range(row) + .map_or((0, 0), |(a, b)| (a as u32, b as u32)); + let start = scratch.slots.len(); + scratch.slots.extend((a..b).map(|i| (lane as u32, i))); + scratch.spans.push((lane, start, scratch.slots.len())); + } + Self::body(c, &mut scratch, Some(child), f, rest, ctx); + let Scratch { + slots, + spans, + results, + failures, + truths, + settled, + .. + } = &mut scratch; + for (lane, start, end) in spans.iter().copied() { + let out = Outcomes::new((results, failures, truths, settled), start, end); + let r = + Self::finish(c.kind, out, |i| child.variable(slots[start + i].1 as usize)); + f.put(c.dst, lane, r); + } + f.scratch = scratch; + return; + } + } + for lane in Lanes::of(active) { + if let Some((child, column)) = children { + let child = &child; + let row = ctx.base + f.rows[lane] as usize; + if let Some((a, b)) = column.range(row) { + let start = scratch.items.len(); + scratch + .items + .extend((a..b).map(|i| (lane as u32, child.variable(i)))); + scratch.spans.push((lane, start, scratch.items.len())); + continue; + } + } + match Self::list_of(c, lane, f, ctx) { + Ok(Variable::Array(arr)) => { + let start = scratch.items.len(); + scratch + .items + .extend(arr.borrow().iter().map(|v| (lane as u32, v.clone()))); + scratch.spans.push((lane, start, scratch.items.len())); + } + Ok(_) => f.fail(lane, Ops::error("Begin", "Unsupported type")), + Err(e) => f.fail(lane, e), + } + } + + Self::body(c, &mut scratch, None, f, rest, ctx); + let Scratch { + items, + spans, + results, + failures, + truths, + settled, + .. + } = &mut scratch; + for (lane, start, end) in spans.iter().copied() { + let out = Outcomes::new((results, failures, truths, settled), start, end); + let r = Self::finish(c.kind, out, |i| items[start + i].1.clone()); + f.put(c.dst, lane, r); + } + f.scratch = scratch; + } + + pub(super) fn elements<'c, M: LaneSet>( + c: &ClosureOp, + frame: &mut Frame, + child: &Column<'c>, + ctx: &mut Context<'c>, + width: usize, + index: impl Fn(usize) -> usize, + ) -> bool { + let (Values::Struct { .. }, Some(element)) = (child.values, c.body.element) else { + return false; + }; + ctx.register(c.body.id, element, *child); + if !frame.views.contains(&element) { + frame.views.push(element); + } + frame.elements.clear(); + frame + .elements + .extend((0..width).map(|lane| index(lane) as u32)); + if c.body.whole(element) { + Self::fill_with(frame, element, child, M::all(width), |_, lane| index(lane)); + } + true + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + + pub(super) fn body<'c, M: LaneSet>( + c: &ClosureOp, + scratch: &mut Scratch, + column: Option<&Column<'c>>, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context<'c>, + ) { + let element = c.body.element.unwrap_or_default(); + let out = c.body.out; + let chunk = if c.sequential { 1 } else { M::LANES }; + let keep = matches!(c.kind, ClosureFunction::Filter); + let Scratch { + items, + slots, + results, + failures, + rows, + parents, + truths, + settled, + .. + } = scratch; + results.clear(); + failures.clear(); + let total = match column { + Some(_) => slots.len(), + None => items.len(), + }; + let predicate = !matches!(c.kind, ClosureFunction::Map | ClosureFunction::FlatMap); + let words = total.div_ceil(64); + for bits in [&mut *truths, &mut *settled] { + bits.clear(); + bits.resize(words, 0); + } + let mut start = 0; + while start < total { + let end = (start + chunk).min(total); + let width = end - start; + rows.clear(); + parents.clear(); + for j in start..end { + let parent = match column { + Some(_) => slots[j].0, + None => items[j].0, + }; + parents.push(parent); + rows.push(f.rows[parent as usize]); + } + let Some(child) = rest.first_mut() else { + break; + }; + Self::enter(&c.body, child, rows, Some((f, parents, &c.imports))); + match column { + Some(column) => { + let slots = &slots[start..end]; + if !Self::elements(c, child, column, ctx, width, |lane| slots[lane].1 as usize) + { + Self::fill_with(child, element, column, M::all(width), |_, lane| { + slots[lane].1 as usize + }); + } + } + None => { + for (lane, (_, value)) in items[start..end].iter_mut().enumerate() { + let value = match keep { + true => value.clone(), + false => std::mem::replace(value, Variable::Null), + }; + child.set(element, lane, value); + } + } + } + Self::execute(&c.body, rest, ctx); + let child = &mut rest[0]; + let o = out as usize; + let (kind, boxed, bits) = (child.kinds[o], child.boxed[o], child.bits[o]); + let ok = match (predicate, kind) { + (true, Kind::Bool) => child.alive & !boxed & M::all(width), + _ => f.none(), + }; + Self::put_bits(settled, start, width, ok); + Self::put_bits(truths, start, width, bits & ok); + for lane in 0..width { + if ok.get(lane) { + results.push(Variable::Null); + continue; + } + if !child.alive.get(lane) { + results.push(Variable::Null); + let e = child.errors[lane] + .take() + .map(Fault::vm) + .unwrap_or_else(Fallbacks::error); + failures.push(((start + lane) as u32, e)); + continue; + } + results.push(match (kind, boxed.get(lane)) { + (Kind::Bool, false) => Variable::Bool(bits.get(lane)), + (Kind::Num, false) => Variable::Number(child.number(out, lane)), + _ => child.take(out, lane), + }); + } + start = end; + } + } + + #[inline] + pub(super) fn put_bits(words: &mut [u64], start: usize, width: usize, value: M) { + for i in 0..width.div_ceil(64) { + let chunk = (width - i * 64).min(64); + let bits = value.word(i); + let at = start + i * 64; + let (word, shift) = (at / 64, at % 64); + if let Some(w) = words.get_mut(word) { + *w |= bits << shift; + } + if shift > 0 && shift + chunk > 64 { + if let Some(w) = words.get_mut(word + 1) { + *w |= bits >> (64 - shift); + } + } + } + } + + pub(super) fn decisive( + c: &ClosureOp, + active: M, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) { + if active.count() == 1 { + let lane = active.first().unwrap_or_default(); + let r = match Self::list_of(c, lane, f, ctx) { + Ok(list @ Variable::Array(_)) => Self::single(c, lane, &list, f, rest, ctx), + Ok(_) => Err(Ops::error("Begin", "Unsupported type")), + Err(e) => Err(e), + }; + f.put(c.dst, lane, r); + return; + } + let mut scratch = std::mem::take(&mut f.scratch); + let mut lists = std::mem::take(&mut scratch.lists); + let mut done = std::mem::take(&mut scratch.done); + lists.clear(); + let children = Self::list_children(c, ctx); + for lane in Lanes::of(active) { + if let Some((_, column)) = children { + let row = ctx.base + f.rows[lane] as usize; + if let Some((a, b)) = column.range(row) { + lists.push((lane, Pending::Child { start: a, end: b }, 0)); + continue; + } + } + match Self::list_of(c, lane, f, ctx) { + Ok(list @ Variable::Array(_)) => lists.push((lane, Pending::Array(list), 0)), + Ok(_) => f.fail(lane, Ops::error("Begin", "Unsupported type")), + Err(e) => f.fail(lane, e), + } + } + + if lists.len() == 1 && matches!(lists.first(), Some((_, Pending::Array(_), _))) { + if let Some((lane, Pending::Array(list), _)) = lists.pop() { + let r = Self::single(c, lane, &list, f, rest, ctx); + f.put(c.dst, lane, r); + } + scratch.lists = lists; + scratch.done = done; + f.scratch = scratch; + return; + } + + let typed = match children { + Some(_) => lists + .iter() + .all(|(_, list, _)| matches!(list, Pending::Child { .. })), + None => false, + }; + let column = children.filter(|_| typed).map(|(child, _)| child); + let mut step = 1usize; + while !lists.is_empty() { + scratch.items.clear(); + scratch.slots.clear(); + scratch.spans.clear(); + for (index, (lane, list, next)) in lists.iter().enumerate() { + let end = (*next + step).min(list.len()); + let (start, stop) = match (list, children) { + (Pending::Array(Variable::Array(arr)), _) => { + let arr = arr.borrow(); + let start = scratch.items.len(); + scratch + .items + .extend(arr[*next..end].iter().map(|v| (*lane as u32, v.clone()))); + (start, scratch.items.len()) + } + (Pending::Child { start: base, .. }, Some(_)) if typed => { + let start = scratch.slots.len(); + let (a, b) = ((base + *next) as u32, (base + end) as u32); + scratch.slots.extend((a..b).map(|i| (*lane as u32, i))); + (start, scratch.slots.len()) + } + (Pending::Child { start: base, .. }, Some((child, _))) => { + let start = scratch.items.len(); + scratch.items.extend( + (base + *next..base + end).map(|i| (*lane as u32, child.variable(i))), + ); + (start, scratch.items.len()) + } + _ => continue, + }; + scratch.spans.push((index, start, stop)); + } + Self::body(c, &mut scratch, column.as_ref(), f, rest, ctx); + + done.clear(); + for (index, start, end) in scratch.spans.iter().copied() { + let (lane, list, next) = &mut lists[index]; + let mut decided = None; + let results = ( + scratch.results.as_mut_slice(), + scratch.failures.as_slice(), + scratch.truths.as_slice(), + scratch.settled.as_slice(), + ); + let mut out = Outcomes::new(results, start, end); + let settled = out.decide(c.kind); + if let Some(verdict) = settled { + decided = verdict.map(|b| Ok(Variable::Bool(b))); + } + for i in (0..out.len()).filter(|_| settled.is_none()) { + match out.verdict(c.kind, i) { + Ok(Some(b)) => { + decided = Some(Ok(Variable::Bool(b))); + break; + } + Ok(None) => {} + Err(e) => { + decided = Some(Err(e)); + break; + } + } + } + let len = list.len(); + *next += end - start; + let decided = decided.or_else(|| { + (*next >= len) + .then(|| Ok(Variable::Bool(!matches!(c.kind, ClosureFunction::Some)))) + }); + if let Some(r) = decided { + f.put(c.dst, *lane, r); + done.push(index); + } + } + done.iter().rev().for_each(|i| { + lists.swap_remove(*i); + }); + if !c.sequential { + step = match column { + Some(_) => M::LANES, + None => (step * 8).min(M::LANES), + }; + } + } + scratch.lists = lists; + scratch.done = done; + f.scratch = scratch; + } + + fn selection<'c, M: LaneSet>( + c: &ClosureOp, + f: &Frame, + ctx: &Context<'c>, + ) -> Option> { + match (&c.source, f.kinds.get(c.list as usize)) { + (None, Some(Kind::List)) => ctx.view(f.program, c.list), + _ => None, + } + } + + fn selected<'c, M: LaneSet>( + c: &ClosureOp, + column: &Column<'c>, + active: M, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context<'c>, + ) { + let base = c.list as usize * f.width; + let rows = Lanes::of(active).all(|lane| { + let (a, b) = f.lists[base + lane]; + !f.generic(c.list, lane) && (a..b).all(|i| f.items.row(i as usize).is_some()) + }); + let mut scratch = std::mem::take(&mut f.scratch); + scratch.items.clear(); + scratch.slots.clear(); + scratch.spans.clear(); + for lane in Lanes::of(active) { + let (a, b) = f.lists[base + lane]; + match (rows, f.generic(c.list, lane)) { + (true, _) => { + let start = scratch.slots.len(); + scratch.slots.extend( + (a..b) + .filter_map(|i| f.items.row(i as usize)) + .map(|row| (lane as u32, row)), + ); + scratch.spans.push((lane, start, scratch.slots.len())); + } + (false, true) => { + let start = scratch.items.len(); + if let Variable::Array(items) = f.value(c.list, lane) { + scratch + .items + .extend(items.borrow().iter().map(|v| (lane as u32, v.clone()))); + } + scratch.spans.push((lane, start, scratch.items.len())); + } + (false, false) => { + let start = scratch.items.len(); + for i in a..b { + let value = match f.items.row(i as usize) { + Some(row) => column.variable(row as usize), + None => f.items.get(i as usize).variable(&f.arena), + }; + scratch.items.push((lane as u32, value)); + } + scratch.spans.push((lane, start, scratch.items.len())); + } + } + } + Self::body(c, &mut scratch, rows.then_some(column), f, rest, ctx); + let Scratch { + items, + slots, + spans, + results, + failures, + truths, + settled, + .. + } = &mut scratch; + for (lane, start, end) in spans.iter().copied() { + let out = Outcomes::new((results, failures, truths, settled), start, end); + let r = match rows { + true => Self::finish(c.kind, out, |i| { + column.variable(slots[start + i].1 as usize) + }), + false => Self::finish(c.kind, out, |i| items[start + i].1.clone()), + }; + f.put(c.dst, lane, r); + } + f.scratch = scratch; + } + + pub(super) fn fold(op: &FoldOp, active: M, f: &mut Frame, ctx: &Context) { + let done = Self::fold_lanes(op, active, f, ctx); + f.masks[op.rest as usize] = active & !done; + } + + fn fold_lanes(op: &FoldOp, active: M, f: &mut Frame, ctx: &Context) -> M { + let none = f.none(); + let Some(Some(column)) = ctx.column(op.site) else { + return none; + }; + let Values::List { child, .. } = column.values else { + return none; + }; + let child = child.column(); + if !matches!(child.values, Values::Struct { .. }) + || child.validity.is_some() + || f.kind(op.dst) != Kind::Num + { + return none; + } + let Some(input) = FoldInput::of(&child, &op.field, op.filter.as_deref()) else { + return none; + }; + let function = op.function; + let done = match (function, input.valid, input.filter, input.numbers) { + (crate::functions::InternalFunction::Sum, None, None, Numbers::Scaled(mant, scale)) => { + Self::fold_rows(op, column, active, f, ctx, |a, b| { + FoldInput::sum_scaled(mant.get(a..b)?, scale.get(a..b)?) + }) + } + (crate::functions::InternalFunction::Sum, _, _, Numbers::Decs(values)) => { + Self::fold_rows(op, column, active, f, ctx, |a, b| { + input.walk(a, b, |i| Scaled::parts(values.get(i)?)) + }) + } + (crate::functions::InternalFunction::Sum, _, _, Numbers::Scaled(mant, scale)) => { + Self::fold_rows(op, column, active, f, ctx, |a, b| { + input.walk(a, b, |i| Some((*mant.get(i)?, *scale.get(i)?))) + }) + } + (crate::functions::InternalFunction::Sum, _, _, _) => { + Self::fold_rows(op, column, active, f, ctx, |a, b| input.sum(a, b)) + } + _ => Self::fold_rows(op, column, active, f, ctx, |a, b| { + if !(a..b).all(|i| input.kept(i).is_some()) { + return None; + } + let values = (a..b) + .filter(|i| input.kept(*i) == Some(true)) + .map(|i| input.number(i)); + match Self::reduce(function, values) { + Some(Out::Num(n)) => Scaled::parts(&n), + _ => None, + } + }), + }; + let d = op.dst as usize; + f.wide[d] &= !done; + f.boxed[d] &= !done; + done + } + + #[inline(always)] + fn fold_rows( + op: &FoldOp, + column: &Column, + active: M, + f: &mut Frame, + ctx: &Context, + total: impl Fn(usize, usize) -> Option<(i64, u8)>, + ) -> M { + let mut done = f.none(); + let base = op.dst as usize * f.width; + let offsets = match (column.values, column.validity) { + (Values::List { offsets, .. }, None) => Some(offsets), + _ => None, + }; + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + let range = match offsets { + Some(offsets) => match (offsets.get(row), offsets.get(row + 1)) { + (Some(&a), Some(&b)) if 0 <= a && a <= b => Some((a as usize, b as usize)), + _ => column.range(row), + }, + None => column.range(row), + }; + if let Some((m, s)) = range.and_then(|(a, b)| total(a, b)) { + f.mant[base + lane] = m; + f.scales[base + lane] = s; + done.set(lane); + } + } + done + } + + pub(super) fn list_children<'c>( + c: &ClosureOp, + ctx: &Context<'c>, + ) -> Option<(Column<'c>, Column<'c>)> { + let (_, site) = c.source.as_ref()?; + match ctx.column(*site) { + Some(Some(column)) => match column.values { + Values::List { child, .. } => Some((child.column(), *column)), + _ => None, + }, + _ => None, + } + } + + pub(super) fn list_of( + c: &ClosureOp, + lane: usize, + f: &mut Frame, + ctx: &Context, + ) -> Result { + let Some((load, site)) = &c.source else { + return f.with(c.list, lane, Ops::elements); + }; + let value = match ctx.column(*site) { + Some(Some(column)) => column.variable(ctx.base + f.rows[lane] as usize), + Some(None) => Variable::Null, + None => Self::row_value(load, *site, lane, f, ctx)?, + }; + Ops::elements(&value) + } + + pub(super) fn single( + c: &ClosureOp, + lane: usize, + list: &Variable, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) -> Result { + let fallback = Ok(Variable::Bool(!matches!(c.kind, ClosureFunction::Some))); + let Variable::Array(arr) = list else { + return fallback; + }; + let len = arr.borrow().len(); + if len == 0 { + return fallback; + } + let element = c.body.element.unwrap_or_default(); + let (rows, parents) = ([f.rows[lane]], [lane as u32]); + let Some(child) = rest.first_mut() else { + return fallback; + }; + Self::enter(&c.body, child, &rows, Some((f, &parents, &c.imports))); + for i in 0..len { + let Some(item) = arr.borrow().get(i).cloned() else { + break; + }; + let child = &mut rest[0]; + child.restart(); + child.set(element, 0, item); + Self::execute(&c.body, rest, ctx); + let child = &mut rest[0]; + let r = match child.alive.get(0) { + true => Ok(child.take(c.body.out, 0)), + _ => Err(child.errors[0] + .take() + .map(Fault::vm) + .unwrap_or_else(Fallbacks::error)), + }; + if let Some(b) = Self::verdict(c.kind, r)? { + return Ok(Variable::Bool(b)); + } + } + fallback + } + + pub(super) fn finish( + kind: ClosureFunction, + mut out: Outcomes, + item: impl Fn(usize) -> Variable, + ) -> Result { + match kind { + ClosureFunction::Map | ClosureFunction::FlatMap => { + if let Some((_, e)) = out.failures.first() { + return Err(e.clone()); + } + let values: Vec = out + .values + .iter_mut() + .map(|v| std::mem::replace(v, Variable::Null)) + .collect(); + match kind { + ClosureFunction::Map => Ok(Variable::from_array(values)), + _ => Ops::flatten(Variable::from_array(values)), + } + } + ClosureFunction::Filter => { + let mut kept = Vec::new(); + for i in 0..out.len() { + if out.truth(i)? { + kept.push(item(i)); + } + } + Ok(Variable::from_array(kept)) + } + ClosureFunction::Count | ClosureFunction::One => { + let count = match out.tally() { + Some((trues, _)) => trues, + None => { + let mut count = 0usize; + for i in 0..out.len() { + if out.truth(i)? { + count += 1; + } + } + count + } + }; + Ok(match kind { + ClosureFunction::One => Variable::Bool(count == 1), + _ => Variable::Number(count.into()), + }) + } + ClosureFunction::All | ClosureFunction::Some | ClosureFunction::None + if out.tally().is_some() => + { + let decided = out.decide(kind).flatten(); + Ok(Variable::Bool( + decided.unwrap_or(!matches!(kind, ClosureFunction::Some)), + )) + } + ClosureFunction::All | ClosureFunction::Some | ClosureFunction::None => { + for i in 0..out.len() { + if let Some(b) = out.verdict(kind, i)? { + return Ok(Variable::Bool(b)); + } + } + Ok(Variable::Bool(!matches!(kind, ClosureFunction::Some))) + } + } + } + + pub(super) fn verdict( + kind: ClosureFunction, + r: Result, + ) -> Result, VMError> { + r.and_then(|v| match kind { + ClosureFunction::Some => Ops::truthy(&v, "JumpIfTrue").map(|t| t.then_some(true)), + ClosureFunction::All => Ops::truthy(&v, "JumpIfFalse").map(|t| (!t).then_some(false)), + _ => Ops::not(v) + .and_then(|n| Ops::truthy(&n, "JumpIfFalse")) + .map(|t| (!t).then_some(false)), + }) + } +} + +impl ClosureFunction { + pub(super) fn holds(self, trues: usize, total: usize) -> bool { + match self { + ClosureFunction::One => trues == 1, + ClosureFunction::Some => trues > 0, + ClosureFunction::All => trues == total, + _ => trues == 0, + } + } +} + +#[derive(Clone, Copy)] +enum Numbers<'c> { + Scaled(&'c [i64], &'c [u8]), + Ints(&'c [i64]), + Decs(&'c [rust_decimal::Decimal]), + Other(Column<'c>), +} + +type Bitmap<'c> = Option<(&'c [u64], usize)>; + +struct FoldInput<'c> { + numbers: Numbers<'c>, + valid: Bitmap<'c>, + filter: Option<(&'c [u64], usize, Bitmap<'c>)>, +} + +impl<'c> FoldInput<'c> { + fn of(child: &Column<'c>, field: &str, filter: Option<&str>) -> Option { + let column = *child.field(field)?; + let numbers = match column.values { + Values::Scaled { mant, scale } => Numbers::Scaled(mant, scale), + Values::I64(values) => Numbers::Ints(values), + Values::Dec(values) => Numbers::Decs(values), + _ => Numbers::Other(column), + }; + let filter = match filter { + None => None, + Some(key) => match child.field(key).copied() { + Some(Column { + values: Values::Bool { bits, offset }, + validity, + }) => Some((bits, offset, validity)), + _ => return None, + }, + }; + Some(Self { + numbers, + valid: column.validity, + filter, + }) + } + + #[inline(always)] + fn number(&self, i: usize) -> Option<(i64, u8)> { + if let Some((bits, offset)) = self.valid { + if !Bits::get(bits, offset + i) { + return None; + } + } + match self.numbers { + Numbers::Scaled(mant, scale) => Some((*mant.get(i)?, *scale.get(i)?)), + Numbers::Ints(values) => Some((*values.get(i)?, 0)), + Numbers::Decs(values) => Scaled::parts(values.get(i)?), + Numbers::Other(column) => Executor::child_number(&column, i), + } + } + + #[inline(always)] + fn kept(&self, i: usize) -> Option { + let Some((bits, offset, valid)) = self.filter else { + return Some(true); + }; + if let Some((mask, at)) = valid { + if !Bits::get(mask, at + i) { + return None; + } + } + Some(Bits::get(bits, offset + i)) + } + + #[inline(always)] + fn accumulate(acc: (i64, u8), x: (i64, u8)) -> Option<(i64, u8)> { + match (acc.0 == 0, x.0 == 0, acc.1 == x.1) { + (true, _, _) => Some(x), + (false, true, _) => Some(acc), + (false, false, true) => Some((acc.0.checked_add(x.0)?, acc.1)), + (false, false, false) => Scaled::add(acc, x, false), + } + } + + #[inline] + fn sum(&self, a: usize, b: usize) -> Option<(i64, u8)> { + match (self.valid, self.filter, self.numbers) { + (None, None, Numbers::Scaled(mant, scale)) => { + Self::sum_scaled(mant.get(a..b)?, scale.get(a..b)?) + } + (_, _, Numbers::Scaled(mant, scale)) => { + self.walk(a, b, |i| Some((*mant.get(i)?, *scale.get(i)?))) + } + (_, _, Numbers::Ints(values)) => self.walk(a, b, |i| Some((*values.get(i)?, 0))), + (_, _, Numbers::Decs(values)) => self.walk(a, b, |i| Scaled::parts(values.get(i)?)), + (_, _, Numbers::Other(column)) => { + self.walk(a, b, |i| Executor::child_number(&column, i)) + } + } + } + + #[inline(always)] + fn sum_scaled(mant: &[i64], scale: &[u8]) -> Option<(i64, u8)> { + let mut acc = (0i64, 0u8); + for (m, s) in mant.iter().zip(scale) { + acc = match *s == acc.1 { + true => (acc.0.checked_add(*m)?, acc.1), + false => Self::accumulate(acc, (*m, *s))?, + }; + } + Some(acc) + } + + #[inline(always)] + fn walk( + &self, + a: usize, + b: usize, + number: impl Fn(usize) -> Option<(i64, u8)>, + ) -> Option<(i64, u8)> { + let mut acc = (0i64, 0u8); + for i in a..b { + let kept = self.kept(i)?; + let valid = self + .valid + .is_none_or(|(bits, offset)| Bits::get(bits, offset + i)); + let x = match (kept, valid, number(i)) { + (false, _, _) => (0, acc.1), + (true, true, Some(x)) => x, + (true, _, _) => return None, + }; + acc = match x.1 == acc.1 { + true => (acc.0.checked_add(x.0)?, acc.1), + false => Self::accumulate(acc, x)?, + }; + } + Some(acc) + } +} diff --git a/core/expression/src/lane/exec/context.rs b/core/expression/src/lane/exec/context.rs new file mode 100644 index 00000000..12b62e2a --- /dev/null +++ b/core/expression/src/lane/exec/context.rs @@ -0,0 +1,122 @@ +use crate::lane::columns::{Column, Columns, Values}; +use crate::lane::program::{Binding, Program, Reg}; +use crate::scope::Scope; + +pub enum Envs<'a> { + Shared(&'a [Scope]), + Owned(Vec), +} + +impl Envs<'_> { + #[inline] + pub(super) fn get(&self, row: u32) -> &Scope { + match self { + Envs::Shared(s) => &s[row as usize], + Envs::Owned(s) => &s[row as usize], + } + } + + pub(super) fn get_mut(&mut self, row: u32) -> Option<&mut Scope> { + match self { + Envs::Shared(_) => None, + Envs::Owned(s) => s.get_mut(row as usize), + } + } +} + +pub struct Context<'a> { + pub roots: Envs<'a>, + pub envs: Envs<'a>, + pub columns: Option<&'a Columns<'a>>, + pub bound: &'a [Binding], + pub base: usize, + pub(super) views: Vec<(u64, Reg, Column<'a>)>, + pub(super) texts: Vec<(*const u8, Option<&'a str>)>, +} + +impl<'a> Context<'a> { + pub fn new(program: &Program, roots: &'a [Scope]) -> Self { + let envs = match program.writes_env { + true => Envs::Owned(roots.to_vec()), + false => Envs::Shared(roots), + }; + let roots = match program.chain { + true => Envs::Owned(roots.to_vec()), + false => Envs::Shared(roots), + }; + Self { + roots, + envs, + columns: None, + bound: &[], + base: 0, + views: Vec::new(), + texts: Vec::new(), + } + } + + pub fn columnar( + program: &Program, + roots: &'a [Scope], + columns: &'a Columns<'a>, + bound: &'a [Binding], + base: usize, + ) -> Self { + let mut ctx = Self::new(program, roots); + ctx.columns = Some(columns); + ctx.bound = bound; + ctx.base = base; + ctx + } + + pub(super) fn view(&self, program: u64, reg: Reg) -> Option> { + self.views + .iter() + .rev() + .find(|(p, r, _)| *p == program && *r == reg) + .map(|(_, _, c)| *c) + } + + pub(super) fn text(&mut self, column: Column<'a>) -> Column<'a> { + let Values::Utf8 { offsets, data } = column.values else { + return column; + }; + let key = data.as_ptr(); + let text = match self.texts.iter().find(|(k, _)| *k == key) { + Some((_, text)) => *text, + None => { + let text = std::str::from_utf8(data).ok(); + self.texts.push((key, text)); + text + } + }; + match text { + Some(data) => Column { + values: Values::Text { offsets, data }, + validity: column.validity, + }, + None => column, + } + } + + pub(super) fn register(&mut self, program: u64, reg: Reg, column: Column<'a>) { + match self + .views + .iter_mut() + .find(|(p, r, _)| *p == program && *r == reg) + { + Some(slot) => slot.2 = column, + None => self.views.push((program, reg, column)), + } + } + + #[inline] + pub(super) fn column(&self, site: u32) -> Option>> { + let columns = self.columns?; + match self.bound.get(site as usize)? { + Binding::Column(index) => Some(columns.columns.get(*index).map(|(_, c)| c)), + Binding::Absent => Some(None), + Binding::Row => None, + } + } +} diff --git a/core/expression/src/lane/exec/date.rs b/core/expression/src/lane/exec/date.rs new file mode 100644 index 00000000..0eac42d4 --- /dev/null +++ b/core/expression/src/lane/exec/date.rs @@ -0,0 +1,115 @@ +use super::frame::Frame; +use super::Executor; +use crate::functions::{FunctionKind, InternalFunction, MethodKind}; +use crate::lane::builtins::{Arg, Dates}; +use crate::lane::date::Date; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::program::{Input, Kind, Reg}; +use std::str::FromStr; + +impl Executor { + pub(super) fn date_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let mut done = f.none(); + let zone = match (kind, args) { + (FunctionKind::Internal(InternalFunction::Date), [Input::Reg(_)]) => None, + (FunctionKind::Internal(InternalFunction::Date), [Input::Reg(_), Input::Const(id)]) => { + match f.consts[*id as usize].as_str().map(chrono_tz::Tz::from_str) { + Some(Ok(zone)) => Some(zone), + _ => return done, + } + } + _ => return done, + }; + let Some(Input::Reg(a)) = args.first().copied() else { + return done; + }; + if f.kind(a) != Kind::Str || f.kind(dst) != Kind::Date { + return done; + } + let mut last: Option<((u32, u32), Date)> = None; + for lane in Lanes::of(active & !f.boxed[a as usize]) { + let span = f.spans[f.at(a, lane)]; + let text = f + .arena + .get(span.0 as usize..span.1 as usize) + .unwrap_or_default(); + let date = match &last { + Some((prev, date)) + if f.arena.get(prev.0 as usize..prev.1 as usize) == Some(text) => + { + *date + } + _ => Date::text(text, zone), + }; + let at = f.at(dst, lane); + f.dates[at] = date; + f.boxed[dst as usize].unset(lane); + last = Some((span, date)); + done.set(lane); + } + done + } + + pub(super) fn date_method( + dst: Reg, + kind: &MethodKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let mut done = f.none(); + match (args, f.kind(dst)) { + ([Input::Reg(this)], Kind::Num) if f.kind(*this) == Kind::Date => { + for lane in Lanes::of(active & !f.boxed[*this as usize]) { + let date = &f.dates[f.at(*this, lane)]; + if let Some(n) = Dates::part_of(kind, date) { + f.put_scaled(dst, lane, n, 0); + done.set(lane); + } + } + } + ([Input::Reg(this), rest @ ..], Kind::Date) + if f.kind(*this) == Kind::Date + && rest.iter().all(|a| matches!(a, Input::Const(_))) => + { + let consts: smallvec::SmallVec<[Arg; 4]> = std::iter::once(Arg::Null) + .chain(rest.iter().map(|a| match a { + Input::Const(id) => Arg::of(&f.consts[*id as usize]), + Input::Reg(_) => Arg::Null, + })) + .collect(); + let Some(shift) = Dates::shift(kind, &consts) else { + return done; + }; + for lane in Lanes::of(active & !f.boxed[*this as usize]) { + let date = shift.apply(&f.dates[f.at(*this, lane)]); + let at = f.at(dst, lane); + f.dates[at] = date; + f.boxed[dst as usize].unset(lane); + done.set(lane); + } + } + ([Input::Reg(this), Input::Reg(other)], Kind::Bool) + if f.kind(*this) == Kind::Date && f.kind(*other) == Kind::Date => + { + let lanes = active & !f.boxed[*this as usize] & !f.boxed[*other as usize]; + for lane in Lanes::of(lanes) { + let (x, y) = (&f.dates[f.at(*this, lane)], &f.dates[f.at(*other, lane)]); + if let Some(hit) = Dates::order(kind, x, y) { + f.bits[dst as usize].put(lane, hit); + f.boxed[dst as usize].unset(lane); + done.set(lane); + } + } + } + _ => {} + } + done + } +} diff --git a/core/expression/src/lane/exec/export.rs b/core/expression/src/lane/exec/export.rs new file mode 100644 index 00000000..07615652 --- /dev/null +++ b/core/expression/src/lane/exec/export.rs @@ -0,0 +1,445 @@ +use super::frame::Frame; +use super::frame::{Fallbacks, Fault}; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::output::{Output, Shape}; +use crate::lane::program::{Kind, Layout, Program, Reg}; +use crate::variable::Variable; +use crate::vm::VMError; +use std::rc::Rc; +use zen_types::symbol::Symbol; +use zen_types::variable::Shape as MapShape; + +impl Frame { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(super) fn collect_shapes(layout: &Layout, out: &mut Vec>>) { + match layout { + Layout::Value(_) => {} + Layout::Struct(fields) => { + let keys: Vec = fields + .iter() + .rev() + .map(|(key, _)| Symbol::from(key.as_ref())) + .collect(); + let distinct = keys + .iter() + .enumerate() + .all(|(i, k)| keys[..i].iter().all(|x| x.as_str() != k.as_str())); + out.push((distinct && keys.len() <= 32).then(|| MapShape::of(keys.iter()))); + fields + .iter() + .rev() + .for_each(|(_, field)| Self::collect_shapes(field, out)); + } + Layout::List(items) => items + .iter() + .for_each(|item| Self::collect_shapes(item, out)), + } + } + + pub(super) fn assemble_taken( + &mut self, + layout: &Layout, + lane: usize, + mut next: Option<&mut usize>, + ) -> Variable { + match layout { + Layout::Value(reg) => self.take(*reg, lane), + Layout::Struct(fields) => { + let shape = next.as_deref_mut().and_then(|n| { + *n += 1; + self.shapes.get(*n - 1).cloned().flatten() + }); + if let Some(shape) = shape { + let values: Vec = fields + .iter() + .rev() + .map(|(_, f)| self.assemble_taken(f, lane, next.as_deref_mut())) + .collect(); + return Variable::from_object(crate::variable::VariableMap::from_shape( + shape, values, + )); + } + let mut map = crate::variable::VariableMap::with_capacity(fields.len()); + for (key, field) in fields.iter().rev() { + let value = self.assemble_taken(field, lane, next.as_deref_mut()); + map.insert(Symbol::from(key.as_ref()), value); + } + Variable::from_object(map) + } + Layout::List(items) => { + let values = items + .iter() + .map(|i| self.assemble_taken(i, lane, next.as_deref_mut())) + .collect(); + Variable::from_array(values) + } + } + } + + fn child(&mut self, layout: &Layout, lane: usize, out: &mut Output, at: usize, failed: bool) { + match layout { + Layout::Struct(_) | Layout::List(_) => self.nested(layout, lane, out, at, failed), + _ => self.cell(layout, lane, out, at, failed), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn nested(&mut self, layout: &Layout, lane: usize, out: &mut Output, at: usize, failed: bool) { + self.cell(layout, lane, out, at, failed) + } + + pub(super) fn cell( + &mut self, + layout: &Layout, + lane: usize, + out: &mut Output, + at: usize, + failed: bool, + ) { + if failed { + out.fail_at(at); + } + match (layout, &mut out.shape) { + (Layout::Struct(fields), Shape::Struct(outputs)) => { + for ((_, field), (_, output)) in fields.iter().zip(outputs.iter_mut()) { + self.child(field, lane, output, at, failed); + } + } + (Layout::List(items), Shape::List(child)) => { + let width = items.len(); + for (i, item) in items.iter().enumerate() { + self.child(item, lane, child, at * width + i, failed); + } + } + _ if failed => {} + (Layout::Value(reg), Shape::Scalar) => self.scalar(*reg, lane, out, at), + (layout, _) => { + let value = self.assemble_taken(layout, lane, None); + match out.kind() { + Kind::Dyn => out.values[at] = value, + _ => out.box_at(at, value), + } + } + } + } + + pub(super) fn scalar(&mut self, reg: Reg, lane: usize, out: &mut Output, at: usize) { + let kind = out.kind(); + if kind == Kind::Dyn { + out.values[at] = self.take(reg, lane); + return; + } + let wide = kind == Kind::Num && self.wide[reg as usize].get(lane); + if self.kind(reg) != kind || self.boxed[reg as usize].get(lane) || wide { + let value = self.take(reg, lane); + out.box_at(at, value); + return; + } + let i = self.at(reg, lane); + match kind { + Kind::Num => { + out.mant[at] = self.mant[i]; + out.scale[at] = self.scales[i]; + } + Kind::Bool => out.set_bit(at, self.bits[reg as usize].get(lane)), + Kind::Date => out.dates[at] = self.dates[i].0, + Kind::List => self.push_list(i, out), + _ => { + let (a, b) = self.spans[i]; + out.push_text(self.arena.get(a as usize..b as usize).unwrap_or_default()); + } + } + } + + pub(super) fn bulk_lists(&self, base: usize, n: usize, out: &mut Output) -> bool { + let Some(spans) = self.lists.get(base..base + n) else { + return false; + }; + let Some((a, b)) = Self::block(spans) else { + return false; + }; + let Some((mant, scales)) = self.items.numbers(a, b) else { + return false; + }; + out.extend_lists(mant, scales, spans.iter().map(|(_, end)| end - a as u32)) + } + + pub(super) fn push_list(&self, at: usize, out: &mut Output) { + let (a, b) = self.lists[at]; + if let Shape::List(child) = &mut out.shape { + match self.items.numbers(a as usize, b as usize) { + Some((mant, scales)) => child.extend_nums(mant, scales), + None => { + for i in a as usize..b as usize { + child.push_item(&self.items.get(i), &self.arena); + } + } + } + } + out.close(); + } + + pub fn export(&mut self, program: &Program, out: &mut Output, start: usize, n: usize) { + let failed = !self.alive & M::all(n); + match &program.layout { + Some(layout) => self.export_shape(layout, out, start, n, failed), + None => self.export_value(program.out, out, start, n, failed), + } + for lane in Lanes::of(failed) { + let fault = self.errors[lane].take().unwrap_or_else(Fallbacks::fault); + out.errors.push(( + (start + lane) as u32, + crate::lane::output::Failure::new(fault), + )); + } + } + + pub fn export_outputs( + &mut self, + program: &Program, + outs: &mut [Output], + start: usize, + n: usize, + mut failure: impl FnMut(usize, usize, Fault), + ) { + if program.isolated { + self.revive(); + } + let failed = !self.alive & M::all(n); + match ( + program.outputs.is_empty(), + &program.layout, + outs.first_mut(), + ) { + (true, Some(layout), Some(out)) => self.export_shape(layout, out, start, n, failed), + (true, None, Some(out)) => self.export_value(program.out, out, start, n, failed), + _ => { + for (reg, out) in program.outputs.iter().zip(outs.iter_mut()) { + self.export_value(*reg, out, start, n, failed); + } + } + } + for (lane, stage, fault) in self.soft.drain(..) { + failure(start + lane, stage as usize, fault); + } + for lane in Lanes::of(failed) { + let fault = self.errors[lane].take().unwrap_or_else(Fallbacks::fault); + failure(start + lane, self.stages[lane] as usize, fault); + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(super) fn export_shape( + &mut self, + layout: &Layout, + out: &mut Output, + start: usize, + n: usize, + failed: M, + ) { + if let Layout::Value(reg) = layout { + if out.kind() == self.kinds[*reg as usize] && !matches!(out.shape, Shape::Struct(_)) { + return self.export_value(*reg, out, start, n, failed); + } + } + match (layout, &mut out.shape) { + (Layout::Struct(fields), Shape::Struct(outputs)) => { + for ((_, field), (_, output)) in fields.iter().zip(outputs.iter_mut()) { + self.export_shape(field, output, start, n, failed); + } + (failed).store(&mut out.failed, start / 64); + } + (Layout::List(items), Shape::List(child)) + if failed.is_empty() && self.strided(items, child.kind(), n) => + { + let width = items.len(); + for (i, item) in items.iter().enumerate() { + let Layout::Value(reg) = item else { + continue; + }; + let base = *reg as usize * self.width; + for lane in 0..n { + let at = (start + lane) * width + i; + match child.kind() { + Kind::Num => { + child.mant[at] = self.mant[base + lane]; + child.scale[at] = self.scales[base + lane]; + } + _ => child.set_bit(at, self.bits[*reg as usize].get(lane)), + } + } + } + } + _ => { + for lane in 0..n { + self.cell(layout, lane, out, start + lane, failed.get(lane)); + } + } + } + } + + pub(super) fn strided(&self, items: &[Layout], kind: Kind, n: usize) -> bool { + let lanes = M::all(n); + matches!(kind, Kind::Num | Kind::Bool) + && items.iter().all(|item| match item { + Layout::Value(reg) => { + let r = *reg as usize; + self.kinds[r] == kind && ((self.boxed[r] | self.wide[r]) & lanes).is_empty() + } + _ => false, + }) + } + + pub(super) fn export_value( + &mut self, + reg: Reg, + out: &mut Output, + start: usize, + n: usize, + failed: M, + ) { + let r = reg as usize; + let word = start / 64; + let lanes = M::all(n); + let base = r * self.width; + let boxed = match self.kinds[r] { + Kind::Num => { + out.mant[start..start + n].copy_from_slice(&self.mant[base..base + n]); + out.scale[start..start + n].copy_from_slice(&self.scales[base..base + n]); + (self.boxed[r] | self.wide[r]) & lanes & !failed + } + Kind::Bool => { + (self.bits[r] & lanes & !failed).store(&mut out.bits, word); + self.boxed[r] & lanes & !failed + } + Kind::Dyn => { + for lane in Lanes::of(lanes & !failed) { + out.values[start + lane] = self.take(reg, lane); + } + self.none() + } + Kind::List => { + let boxed = self.boxed[r] & lanes & !failed; + let plain = lanes & !failed & !boxed; + if plain != lanes || !self.bulk_lists(base, n, out) { + for lane in 0..n { + match plain.get(lane) { + true => self.push_list(base + lane, out), + _ => out.close(), + } + } + } + boxed + } + Kind::Date => { + for (o, d) in out.dates[start..start + n] + .iter_mut() + .zip(&self.dates[base..base + n]) + { + *o = d.0; + } + self.boxed[r] & lanes & !failed + } + Kind::Str if out.coding() => { + let boxed = self.boxed[r] & lanes & !failed; + let plain = lanes & !failed & !boxed; + let mut seen: Vec<((u32, u32), i32)> = Vec::new(); + for lane in 0..n { + if !plain.get(lane) { + out.push_empty(); + continue; + } + let span = self.spans[base + lane]; + match (out.coding(), seen.iter().find(|(s, _)| *s == span)) { + (true, Some((_, code))) => out.push_code(*code), + _ => { + out.push_text( + self.arena + .get(span.0 as usize..span.1 as usize) + .unwrap_or_default(), + ); + if let Some(code) = out.last_code() { + seen.push((span, code)); + } + } + } + } + boxed + } + Kind::Str => { + let boxed = self.boxed[r] & lanes & !failed; + let spans = &self.spans[base..base + n]; + let clean = failed.is_empty() && boxed.is_empty(); + if let (true, Some(first)) = (clean, spans.first().copied()) { + if spans.iter().all(|span| *span == first) { + let text = self + .arena + .get(first.0 as usize..first.1 as usize) + .unwrap_or_default() + .as_bytes(); + let origin = out.data.len(); + out.data.extend_from_slice(text); + while out.data.len() - origin < text.len() * n { + let have = out.data.len() - origin; + let take = have.min(text.len() * n - have); + out.data.extend_from_within(origin..origin + take); + } + out.offsets + .extend((1..=n).map(|i| (origin + i * text.len()) as u32)); + return self.export_rest(out, start, failed, self.none(), reg); + } + } + if let (true, Some((a, b))) = (clean, Self::block(spans)) { + if let Some(text) = self.arena.get(a..b) { + let shift = out.data.len() as i64 - a as i64; + out.data.extend_from_slice(text.as_bytes()); + out.offsets + .extend(spans.iter().map(|(_, end)| (*end as i64 + shift) as u32)); + return self.export_rest(out, start, failed, self.none(), reg); + } + } + let plain = lanes & !failed & !boxed; + for lane in 0..n { + if plain.get(lane) { + let (a, b) = self.spans[base + lane]; + if let Some(text) = self.arena.get(a as usize..b as usize) { + out.data.extend_from_slice(text.as_bytes()); + } + } + out.offsets.push(out.data.len() as u32); + } + boxed + } + }; + self.export_rest(out, start, failed, boxed, reg) + } + + pub(super) fn export_rest( + &mut self, + out: &mut Output, + start: usize, + failed: M, + boxed: M, + reg: Reg, + ) { + for lane in Lanes::of(boxed) { + let v = self.take(reg, lane); + out.extra.push(((start + lane) as u32, v)); + } + (boxed).store(&mut out.boxed, start / 64); + (failed).store(&mut out.failed, start / 64); + } + + pub fn take_result(&mut self, program: &Program, lane: usize) -> Result { + match self.alive.get(lane) { + true => Ok(match &program.layout { + Some(layout) => self.assemble_taken(layout, lane, Some(&mut 0)), + None => self.take(program.out, lane), + }), + _ => Err(self.errors[lane] + .take() + .map(Fault::vm) + .unwrap_or_else(Fallbacks::error)), + } + } +} diff --git a/core/expression/src/lane/exec/frame.rs b/core/expression/src/lane/exec/frame.rs new file mode 100644 index 00000000..1ea5e5da --- /dev/null +++ b/core/expression/src/lane/exec/frame.rs @@ -0,0 +1,958 @@ +use super::closure::Pending; +use crate::lane::builtins::{Arg, Out}; +use crate::lane::date::Date; +use crate::lane::mask::{LaneSet, Lanes, Mask}; +use crate::lane::ops::Ops; +use crate::lane::output::Items; +use crate::lane::program::{Const, Input, Kind, Operand, Program, Reg}; +use crate::lane::scaled::Scaled; +use crate::variable::Variable; +use crate::vm::VMError; +use rust_decimal::Decimal; +use std::rc::Rc; +use zen_types::symbol::Symbol; +use zen_types::variable::{Shape as MapShape, ShapeHint}; + +#[derive(Debug, Default)] +pub struct Frame { + pub(super) program: u64, + pub(super) capacity: usize, + pub(super) width: usize, + pub(super) kinds: Vec, + pub(super) pinned: Vec, + pub(super) fixed: Vec, + pub(super) filled: Vec, + pub(super) regs: Vec, + pub(super) mant: Vec, + pub(super) spans: Vec<(u32, u32)>, + pub(super) lists: Vec<(u32, u32)>, + pub(super) items: Items, + pub(super) arena: String, + pub(super) ranges: Vec<(usize, usize)>, + pub(super) dicts: Vec>, + pub(super) shared: Vec>, + pub(super) scales: Vec, + pub(super) wide: Vec, + pub(super) nums: Vec, + pub(super) dates: Vec, + pub(super) bits: Vec, + pub(super) boxed: Vec, + pub(super) masks: Vec, + pub(super) alive: M, + pub(super) dense: bool, + pub(super) errors: Vec>, + pub(super) rows: Vec, + pub(super) parents: Vec, + pub(super) scratch: Scratch, + pub(super) hints: Vec, + pub(super) consts: Vec, + pub(super) text: String, + pub(super) buffers: Buffers, + pub(super) memo: Vec>>>, + pub(super) owner: u64, + pub(super) parked: Vec<(u64, Caches)>, + pub(super) shapes: Vec>>, + pub(super) stage: u32, + pub(super) stages: Vec, + pub(super) soft: Vec<(usize, u32, Fault)>, + pub(super) views: Vec, + pub(super) elements: Vec, + pub(super) prefixes: Vec, + pub(super) picks: Vec, +} + +#[derive(Debug, Default)] +pub(super) struct Prefixes { + pub(super) id: Option<(usize, usize, usize)>, + pub(super) words: Vec, + pub(super) lens: Vec, +} + +#[derive(Debug, Default)] +pub(super) struct Caches { + pub(super) memo: Vec>>>, + pub(super) dicts: Vec>, + pub(super) shared: Vec>, +} + +impl Caches { + pub(super) fn clear_spans(&mut self) { + self.dicts.iter_mut().for_each(Vec::clear); + self.shared.iter_mut().for_each(Vec::clear); + } +} + +pub(super) const SEGMENTS: usize = 8; + +#[derive(Debug, Default)] +pub(super) struct Buffers { + pub(super) m: Vec, + pub(super) s: Vec, + pub(super) ka: Vec, + pub(super) sa: Vec, + pub(super) kb: Vec, + pub(super) sb: Vec, +} + +#[derive(Debug, Default)] +pub(super) struct Scratch { + pub(super) items: Vec<(u32, Variable)>, + pub(super) slots: Vec<(u32, u32)>, + pub(super) truths: Vec, + pub(super) settled: Vec, + pub(super) spans: Vec<(usize, usize, usize)>, + pub(super) results: Vec, + pub(super) failures: Vec<(u32, VMError)>, + pub(super) rows: Vec, + pub(super) parents: Vec, + pub(super) lists: Vec<(usize, Pending, usize)>, + pub(super) done: Vec, +} + +#[derive(Debug, Clone)] +pub enum Fault { + Vm(VMError), + Unsupported(&'static str), + Call(Box), +} + +#[derive(Debug, Clone)] +pub struct CallFault { + kind: crate::functions::FunctionKind, + detail: CallDetail, +} + +#[derive(Clone)] +enum CallDetail { + Message(String), + Fail(&'static crate::lane::builtins::Builtin, Box<[Variable]>), +} + +impl std::fmt::Debug for CallDetail { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + CallDetail::Message(message) => f.debug_tuple("Message").field(message).finish(), + CallDetail::Fail(_, values) => f.debug_tuple("Fail").field(values).finish(), + } + } +} + +impl CallFault { + pub(crate) fn message(kind: &crate::functions::FunctionKind, message: String) -> Fault { + Fault::Call(Box::new(CallFault { + kind: kind.clone(), + detail: CallDetail::Message(message), + })) + } + + pub(crate) fn fail( + kind: &crate::functions::FunctionKind, + builtin: &'static crate::lane::builtins::Builtin, + args: &[crate::lane::builtins::Arg], + ) -> Fault { + Fault::Call(Box::new(CallFault { + kind: kind.clone(), + detail: CallDetail::Fail(builtin, args.iter().map(|a| a.variable()).collect()), + })) + } + + fn error(&self) -> VMError { + let message = match &self.detail { + CallDetail::Message(message) => message.clone(), + CallDetail::Fail(builtin, values) => { + let args: smallvec::SmallVec<[crate::lane::builtins::Arg; 4]> = + values.iter().map(crate::lane::builtins::Arg::of).collect(); + (builtin.fail)(&args) + } + }; + crate::lane::ops::Ops::error( + "CallFunction", + format!("Function `{}` failed: {message}", self.kind), + ) + } +} + +impl Fault { + pub fn vm(self) -> VMError { + match self { + Fault::Vm(error) => error, + Fault::Unsupported(opcode) => crate::lane::ops::Ops::unsupported(opcode), + Fault::Call(call) => call.error(), + } + } +} + +pub struct Fallbacks; + +impl Fallbacks { + thread_local! { + static REACHED: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub fn reached() -> usize { + Self::REACHED.get() + } + + pub(crate) fn error() -> VMError { + Self::REACHED.set(Self::REACHED.get() + 1); + VMError::NumberConversionError + } + + pub(crate) fn fault() -> Fault { + Fault::Vm(Self::error()) + } +} + +impl Frame { + pub(super) const ARENA: usize = 1 << 20; + + #[inline] + pub(super) fn text_at(&self, reg: Reg, lane: usize) -> &str { + let (a, b) = self.spans[self.at(reg, lane)]; + self.arena.get(a as usize..b as usize).unwrap_or_default() + } + + #[inline] + pub(super) fn intern(&mut self, text: &str) -> (u32, u32) { + let start = self.arena.len() as u32; + self.arena.push_str(text); + (start, self.arena.len() as u32) + } + + #[inline] + pub(super) fn put_scaled(&mut self, reg: Reg, lane: usize, mant: i64, scale: u8) { + let at = self.at(reg, lane); + self.mant[at] = mant; + self.scales[at] = scale; + self.wide[reg as usize].unset(lane); + self.boxed[reg as usize].unset(lane); + } + + #[inline] + pub(super) fn put_mask(&mut self, reg: Reg, lanes: M, word: M) { + let r = reg as usize; + self.bits[r] = (self.bits[r] & !lanes) | word; + self.boxed[r] &= !lanes; + } + + #[inline] + pub(super) fn fill_typed(&mut self, reg: Reg, lanes: M, value: &Variable) -> bool { + match (self.kind(reg), value) { + (Kind::Num, Variable::Number(n)) => self.fill_num(reg, lanes, *n), + (Kind::Str, Variable::String(text)) => self.fill_text(reg, lanes, text), + (Kind::Bool, Variable::Bool(b)) => self.fill_bool(reg, lanes, *b), + (Kind::List, Variable::Array(items)) if items.borrow().is_empty() => { + let start = self.items.len() as u32; + for lane in Lanes::of(lanes) { + let at = self.at(reg, lane); + self.lists[at] = (start, start); + } + self.boxed[reg as usize] &= !lanes; + } + _ => return false, + } + true + } + + #[inline] + pub(super) fn split(&mut self, cond: Reg, active: M, opcode: &str) -> (M, M) { + let (mut t, mut e) = (self.none(), self.none()); + let mut slow = active; + if self.kind(cond) == Kind::Bool { + let boxed = self.boxed[cond as usize]; + let bits = self.bits[cond as usize]; + t = active & !boxed & bits; + e = active & !boxed & !bits; + slow = active & boxed; + } + for lane in Lanes::of(slow) { + match self.with(cond, lane, |v| Ops::truthy(v, opcode)) { + Ok(true) => t.set(lane), + Ok(false) => e.set(lane), + Err(err) => self.fail(lane, err), + } + } + (t, e) + } + + #[inline] + pub(super) fn fill_text(&mut self, reg: Reg, lanes: M, text: &str) { + let span = self.intern(text); + let base = reg as usize * self.width; + for lane in Lanes::of(lanes) { + self.spans[base + lane] = span; + } + self.boxed[reg as usize] &= !lanes; + } + + pub(super) fn box_lists(&mut self, args: &[Input], lanes: M) { + for input in args { + let Input::Reg(r) = *input else { + continue; + }; + if self.kinds[r as usize] != Kind::List { + continue; + } + for lane in Lanes::of(lanes & !self.boxed[r as usize]) { + let value = self.list_value(r, lane); + let at = self.at(r, lane); + self.regs[at] = value; + self.boxed[r as usize].set(lane); + } + } + } + + pub(super) fn list_value(&self, reg: Reg, lane: usize) -> Variable { + let (a, b) = self.lists[self.at(reg, lane)]; + Variable::from_array( + (a as usize..b as usize) + .map(|i| self.items.variable(i, &self.arena)) + .collect(), + ) + } + + #[inline] + pub(super) fn put_text(&mut self, reg: Reg, lane: usize, text: &str) { + let span = self.intern(text); + let at = self.at(reg, lane); + self.spans[at] = span; + } + + pub(super) fn park(&mut self, id: u64) { + if self.owner == id { + return; + } + let current = Caches { + memo: std::mem::take(&mut self.memo), + dicts: std::mem::take(&mut self.dicts), + shared: std::mem::take(&mut self.shared), + }; + self.parked.push((self.owner, current)); + let next = match self.parked.iter().position(|(owner, _)| *owner == id) { + Some(i) => self.parked.swap_remove(i).1, + None => Caches::default(), + }; + if self.parked.len() > Self::PARKED { + self.parked.remove(0); + } + self.memo = next.memo; + self.dicts = next.dicts; + self.shared = next.shared; + self.owner = id; + } + + pub(super) fn prepare(&mut self, program: &Program, width: usize) { + self.park(program.id); + if self.program != program.id || self.capacity < width { + let size = program.regs as usize * width.max(self.capacity); + if self.regs.len() < size { + self.regs.resize(size, Variable::Null); + self.mant.resize(size, 0); + self.spans.resize(size, (0, 0)); + self.lists.resize(size, (0, 0)); + self.scales.resize(size, 0); + self.nums.resize(size, Decimal::ZERO); + self.dates.resize(size, Date(None)); + } + self.capacity = width.max(self.capacity); + self.kinds.clear(); + self.kinds.extend_from_slice(&program.kinds); + self.pinned.clear(); + self.pinned.extend_from_slice(&program.pinned); + self.fixed.clear(); + self.fixed.extend_from_slice(&program.fixed); + self.consts.clear(); + self.consts + .extend(program.consts.iter().map(Const::variable)); + let hints = program.sites as usize * SEGMENTS; + self.hints.clear(); + self.hints.resize(hints, ShapeHint::default()); + self.masks.clear(); + self.masks + .resize(program.masks as usize + 1, M::none(width)); + if self.errors.len() < self.capacity { + self.errors.resize(self.capacity, None); + } + if self.stages.len() < self.capacity { + self.stages.resize(self.capacity, 0); + } + self.width = usize::MAX; + self.program = program.id; + self.shapes.clear(); + if let Some(layout) = &program.layout { + Self::collect_shapes(layout, &mut self.shapes); + } + } + if self.arena.len() > Self::ARENA || self.items.len() > Self::ARENA { + self.arena.clear(); + self.items.clear(); + self.dicts.iter_mut().for_each(Vec::clear); + self.shared.iter_mut().for_each(Vec::clear); + self.parked + .iter_mut() + .for_each(|(_, caches)| caches.clear_spans()); + self.filled.iter_mut().for_each(|w| *w = M::none(width)); + } + if self.width != width || self.filled.len() != program.regs as usize { + let regs = program.regs as usize; + for bits in [ + &mut self.filled, + &mut self.bits, + &mut self.boxed, + &mut self.wide, + ] { + bits.clear(); + bits.resize(regs, M::none(width)); + } + } + self.width = width; + self.stage = 0; + self.soft.clear(); + self.prefixes.iter_mut().for_each(|p| p.id = None); + self.masks.iter_mut().for_each(|m| *m = M::none(width)); + self.alive = M::all(width); + self.masks[0] = self.alive; + } + + pub(super) fn restart(&mut self) { + self.stage = 0; + self.soft.clear(); + let width = self.width; + self.masks.iter_mut().for_each(|m| *m = M::none(width)); + self.alive = M::all(self.width); + self.masks[0] = self.alive; + } + + pub fn forget(&mut self) { + self.memo.iter_mut().for_each(Vec::clear); + self.dicts.iter_mut().for_each(Vec::clear); + self.shared.iter_mut().for_each(Vec::clear); + self.parked.clear(); + } + + const PARKED: usize = 8; + const INLINE_TEXT: usize = 256; + + pub(super) const UNSET: (u32, u32) = (u32::MAX, u32::MAX); + + pub(super) fn cached( + cache: &mut Vec>, + slot: usize, + size: usize, + ) -> &mut Vec<(u32, u32)> { + if cache.len() <= slot { + cache.resize_with(slot + 1, Vec::new); + } + let entries = &mut cache[slot]; + if entries.len() < size { + entries.resize(size, Self::UNSET); + } + entries + } + + pub fn restrict(&mut self, mask: M) { + self.masks[0] &= mask; + } + + pub fn stage_of(&self, lane: usize) -> u32 { + self.stages[lane] + } + + pub fn active(&self, lane: usize) -> bool { + self.masks[0].get(lane) + } + + pub fn outputs(&self, program: &Program, lane: usize) -> Vec { + program + .outputs + .iter() + .map(|r| self.value(*r, lane)) + .collect() + } + + #[inline] + pub(super) fn none(&self) -> M { + M::none(self.width) + } + + #[inline] + pub(super) fn at(&self, reg: Reg, lane: usize) -> usize { + reg as usize * self.width + lane + } + + #[inline] + pub(super) fn kind(&self, reg: Reg) -> Kind { + self.kinds[reg as usize] + } + + #[inline] + pub(super) fn generic(&self, reg: Reg, lane: usize) -> bool { + matches!(self.kinds[reg as usize], Kind::Dyn) || self.boxed[reg as usize].get(lane) + } + + #[inline] + pub(super) fn value(&self, reg: Reg, lane: usize) -> Variable { + let at = self.at(reg, lane); + match self.generic(reg, lane) { + true => self.regs[at].clone(), + false => match self.kinds[reg as usize] { + Kind::Num => Variable::Number(self.number(reg, lane)), + Kind::Str => Variable::String(Symbol::from(self.text_at(reg, lane))), + Kind::List => self.list_value(reg, lane), + Kind::Date => self.dates[at].variable(), + _ => Variable::Bool(self.bits[reg as usize].get(lane)), + }, + } + } + + #[inline] + pub(super) fn with(&self, reg: Reg, lane: usize, f: impl FnOnce(&Variable) -> T) -> T { + match self.generic(reg, lane) { + true => f(&self.regs[self.at(reg, lane)]), + false => f(&self.value(reg, lane)), + } + } + + #[inline] + pub(super) fn take(&mut self, reg: Reg, lane: usize) -> Variable { + if self.pinned[reg as usize] { + return self.value(reg, lane); + } + match self.generic(reg, lane) { + true => { + let at = self.at(reg, lane); + std::mem::replace(&mut self.regs[at], Variable::Null) + } + false => self.value(reg, lane), + } + } + + #[inline] + pub(super) fn set(&mut self, reg: Reg, lane: usize, value: Variable) { + let at = self.at(reg, lane); + let r = reg as usize; + match (self.kinds[r], value) { + (Kind::Dyn, v) => self.regs[at] = v, + (Kind::Str, Variable::String(text)) if text.len() <= Self::INLINE_TEXT => { + self.put_text(reg, lane, &text); + self.boxed[r].unset(lane); + } + (Kind::Num, Variable::Number(n)) => { + self.put_number(reg, lane, n); + self.boxed[r].unset(lane); + } + (Kind::Bool, Variable::Bool(b)) => { + self.bits[r].put(lane, b); + self.boxed[r].unset(lane); + } + (Kind::Date, v) => match Date::of(&v).filter(|_| !Date::sourced(&v)) { + Some(d) => { + self.dates[at] = d; + self.boxed[r].unset(lane); + } + None => { + self.regs[at] = v; + self.boxed[r].set(lane); + } + }, + (_, v) => { + self.regs[at] = v; + self.boxed[r].set(lane); + } + } + } + + #[inline] + pub(super) fn store(&mut self, reg: Reg, lane: usize, value: &Variable) { + let r = reg as usize; + match (self.kinds[r], value) { + (Kind::Num, Variable::Number(n)) => { + self.put_number(reg, lane, *n); + self.boxed[r].unset(lane); + } + (Kind::Str, Variable::String(text)) if text.len() <= Self::INLINE_TEXT => { + self.put_text(reg, lane, text); + self.boxed[r].unset(lane); + } + (Kind::Bool, Variable::Bool(b)) => { + self.bits[r].put(lane, *b); + self.boxed[r].unset(lane); + } + (_, v) => self.set(reg, lane, v.clone()), + } + } + + pub(super) fn arg_view(&self, reg: Reg, lane: usize) -> Arg<'_> { + let r = reg as usize; + let boxed = self.boxed[r].get(lane); + match (self.kinds[r], boxed) { + (Kind::Num, false) => Arg::Num(self.number(reg, lane)), + (Kind::Bool, false) => Arg::Bool(self.bits[r].get(lane)), + (Kind::Str, false) => Arg::Str(self.text_at(reg, lane)), + (Kind::Date, false) => Arg::Date(self.dates[self.at(reg, lane)]), + _ => Arg::of(&self.regs[self.at(reg, lane)]), + } + } + + #[inline] + pub(super) fn fill_num(&mut self, reg: Reg, active: M, n: Decimal) { + let base = reg as usize * self.width; + let r = reg as usize; + match (Scaled::parts(&n), active == M::all(self.width)) { + (Some((m, s)), true) => { + self.mant[base..base + self.width].fill(m); + self.scales[base..base + self.width].fill(s); + self.wide[r] &= !active; + } + (Some((m, s)), false) => { + for lane in Lanes::of(active) { + self.mant[base + lane] = m; + self.scales[base + lane] = s; + } + self.wide[r] &= !active; + } + (None, _) => { + Lanes::of(active).for_each(|lane| self.nums[base + lane] = n); + self.wide[r] |= active; + } + } + self.boxed[r] &= !active; + } + + #[inline] + pub(super) fn number(&self, reg: Reg, lane: usize) -> Decimal { + let at = self.at(reg, lane); + match self.wide[reg as usize].get(lane) { + true => self.nums[at], + false => Scaled::decimal(self.mant[at], self.scales[at]), + } + } + + #[inline] + pub(super) fn put_number(&mut self, reg: Reg, lane: usize, n: Decimal) { + let at = self.at(reg, lane); + match Scaled::parts(&n) { + Some((m, s)) => { + self.mant[at] = m; + self.scales[at] = s; + self.wide[reg as usize].unset(lane); + } + None => { + self.nums[at] = n; + self.wide[reg as usize].set(lane); + } + } + } + + #[inline] + pub(super) fn fill_bool(&mut self, reg: Reg, active: M, b: bool) { + let word = if b { active } else { self.none() }; + self.put_mask(reg, active, word); + } + + #[inline] + pub(super) fn typed(&self, reg: Reg) -> M { + match self.kinds[reg as usize] { + Kind::Dyn => self.none(), + _ => !self.boxed[reg as usize], + } + } + + fn pick(values: &mut [T], width: usize, pick: M, at: (usize, usize, usize)) { + let (d, a, b) = at; + for w in 0..width.div_ceil(64) { + let (bits, lo) = (pick.word(w), w * 64); + for j in 0..(width - lo).min(64) { + let lane = lo + j; + let from = match (bits >> j) & 1 { + 1 => a + lane, + _ => b + lane, + }; + values[d + lane] = values[from]; + } + } + } + + pub(super) fn select_typed(&mut self, dst: Reg, a: Reg, b: Reg, pick: M) -> bool { + let width = self.width; + let all = M::all(width); + let (d, ra, rb) = (dst as usize, a as usize, b as usize); + let kind = self.kinds[d]; + let other = all & !pick; + let clean = self.kinds[ra] == kind + && self.kinds[rb] == kind + && (self.boxed[ra] & pick).is_empty() + && (self.boxed[rb] & other).is_empty(); + let at = (d * width, ra * width, rb * width); + match (clean, kind) { + (true, Kind::Num) + if (self.wide[ra] & pick).is_empty() && (self.wide[rb] & other).is_empty() => + { + Self::pick(&mut self.mant, width, pick, at); + Self::pick(&mut self.scales, width, pick, at); + self.wide[d] &= !all; + } + (true, Kind::Str) => Self::pick(&mut self.spans, width, pick, at), + _ => return false, + } + self.boxed[d] &= !all; + true + } + + pub(super) fn select_const(&mut self, dst: Reg, pick: M, a: &Variable, b: &Variable) -> bool { + let width = self.width; + let all = M::all(width); + let base = dst as usize * width; + match (self.kinds[dst as usize], a, b) { + (Kind::Num, Variable::Number(x), Variable::Number(y)) => { + let (Some(x), Some(y)) = (Scaled::parts(x), Scaled::parts(y)) else { + return false; + }; + for w in 0..width.div_ceil(64) { + let (bits, lo) = (pick.word(w), w * 64); + for j in 0..(width - lo).min(64) { + let (m, s) = match (bits >> j) & 1 { + 1 => x, + _ => y, + }; + self.mant[base + lo + j] = m; + self.scales[base + lo + j] = s; + } + } + self.wide[dst as usize] &= !all; + } + (Kind::Str, Variable::String(x), Variable::String(y)) => { + let (x, y) = (self.intern(x), self.intern(y)); + for w in 0..width.div_ceil(64) { + let (bits, lo) = (pick.word(w), w * 64); + for j in 0..(width - lo).min(64) { + self.spans[base + lo + j] = match (bits >> j) & 1 { + 1 => x, + _ => y, + }; + } + } + } + _ => return false, + } + self.boxed[dst as usize] &= !all; + true + } + + #[inline] + pub(super) fn copy_typed(&mut self, dst: Reg, src: Reg, lanes: M) { + let (d, s) = (dst as usize, src as usize); + let (db, sb) = (d * self.width, s * self.width); + if lanes == M::all(self.width) && d != s { + let width = self.width; + match self.kinds[s] { + Kind::Num => { + self.mant.copy_within(sb..sb + width, db); + self.scales.copy_within(sb..sb + width, db); + for lane in Lanes::of(self.wide[s]) { + self.nums[db + lane] = self.nums[sb + lane]; + } + self.wide[d] = self.wide[s]; + } + Kind::Str => self.spans.copy_within(sb..sb + width, db), + Kind::List => self.lists.copy_within(sb..sb + width, db), + Kind::Date => { + for lane in 0..width { + self.dates[db + lane] = self.dates[sb + lane]; + } + } + _ => self.bits[d] = self.bits[s], + } + self.boxed[d] &= !lanes; + return; + } + match self.kinds[s] { + Kind::Num => { + for w in 0..lanes.words() { + let (word, at) = (lanes.word(w), w * 64); + match word { + 0 => {} + u64::MAX => { + self.mant.copy_within(sb + at..sb + at + 64, db + at); + self.scales.copy_within(sb + at..sb + at + 64, db + at); + } + mut bits => { + while bits != 0 { + let lane = at + bits.trailing_zeros() as usize; + self.mant[db + lane] = self.mant[sb + lane]; + self.scales[db + lane] = self.scales[sb + lane]; + bits &= bits - 1; + } + } + } + } + for lane in Lanes::of(lanes & self.wide[s]) { + self.nums[db + lane] = self.nums[sb + lane]; + } + self.wide[d] = (self.wide[d] & !lanes) | (self.wide[s] & lanes); + } + Kind::Str => { + for lane in Lanes::of(lanes) { + self.spans[db + lane] = self.spans[sb + lane]; + } + } + Kind::List => { + for lane in Lanes::of(lanes) { + self.lists[db + lane] = self.lists[sb + lane]; + } + } + Kind::Date => { + for lane in Lanes::of(lanes) { + self.dates[db + lane] = self.dates[sb + lane]; + } + } + _ => self.bits[d] = (self.bits[d] & !lanes) | (self.bits[s] & lanes), + } + self.boxed[d] &= !lanes; + } + + pub(super) fn block(spans: &[(u32, u32)]) -> Option<(usize, usize)> { + let (first, last) = (spans.first()?, spans.last()?); + spans + .windows(2) + .all(|w| w[0].1 == w[1].0) + .then_some((first.0 as usize, last.1 as usize)) + } + + #[inline] + pub(super) fn num(&self, o: Operand, lane: usize) -> Decimal { + match o { + Operand::Num(n) => n, + Operand::Reg(r) => self.number(r, lane), + } + } + + #[inline] + pub(super) fn operand_boxed(&self, o: Operand) -> M { + match o { + Operand::Num(_) => self.none(), + Operand::Reg(r) => match self.kinds[r as usize] { + Kind::Num => self.boxed[r as usize], + _ => M::all(self.width), + }, + } + } + + #[inline] + pub(super) fn side<'s>( + &'s self, + o: Operand, + m: &'s mut Vec, + sc: &'s mut Vec, + ) -> Option<(&'s [i64], &'s [u8])> { + let width = self.width; + match o { + Operand::Num(n) => { + let (mm, ss) = Scaled::parts(&n)?; + if m.len() < width { + m.resize(width, 0); + sc.resize(width, 0); + } + m[..width].fill(mm); + sc[..width].fill(ss); + Some((&m[..width], &sc[..width])) + } + Operand::Reg(r) => { + let base = r as usize * width; + Some(( + &self.mant[base..base + width], + &self.scales[base..base + width], + )) + } + } + } + + #[inline] + pub(super) fn operand_wide(&self, o: Operand) -> M { + match o { + Operand::Num(_) => self.none(), + Operand::Reg(r) => self.wide[r as usize], + } + } + + #[inline] + pub(super) fn uniform(s: &[u8], lanes: M) -> Option { + let first = *s.get(lanes.first()?)?; + if lanes == M::all(s.len()) { + return (s.iter().fold(0u8, |acc, x| acc | (x ^ first)) == 0).then_some(first); + } + let mixed = s.iter().enumerate().fold(0u8, |acc, (lane, x)| { + acc | ((x ^ first) & (lanes.get(lane) as u8).wrapping_neg()) + }); + (mixed == 0).then_some(first) + } + + #[inline] + pub(super) fn operand_value(&mut self, o: Operand, lane: usize) -> Variable { + match o { + Operand::Num(n) => Variable::Number(n), + Operand::Reg(r) => self.take(r, lane), + } + } + + #[inline] + pub(super) fn fail(&mut self, lane: usize, error: VMError) { + self.fault(lane, Fault::Vm(error)); + } + + pub(super) fn revive(&mut self) { + let dead = self.masks[0] & !self.alive; + for lane in Lanes::of(dead) { + if let Some(fault) = self.errors[lane].take() { + self.soft.push((lane, self.stages[lane], fault)); + } + } + self.alive |= dead; + } + + pub(super) fn fault(&mut self, lane: usize, fault: Fault) { + if self.alive.get(lane) { + self.alive.unset(lane); + self.errors[lane] = Some(fault); + self.stages[lane] = self.stage; + } + } + + #[inline] + pub(super) fn write(&mut self, reg: Reg, lane: usize, result: Result) { + let r = reg as usize; + match (self.kinds[r], result) { + (Kind::Num, Ok(Out::Num(n))) => { + self.put_number(reg, lane, n); + self.boxed[r].unset(lane); + } + (Kind::Bool, Ok(Out::Bool(b))) => { + self.bits[r].put(lane, b); + self.boxed[r].unset(lane); + } + (Kind::Date, Ok(Out::Date(d))) => { + let at = self.at(reg, lane); + self.dates[at] = d; + self.boxed[r].unset(lane); + } + (_, Ok(out)) => self.set(reg, lane, out.variable()), + (_, Err(e)) => self.fail(lane, e), + } + } + + #[inline] + pub(super) fn write_call(&mut self, reg: Reg, lane: usize, result: Result) { + match result { + Ok(out) => self.write(reg, lane, Ok(out)), + Err(fault) => self.fault(lane, fault), + } + } + + #[inline] + pub(super) fn put(&mut self, reg: Reg, lane: usize, result: Result) { + match result { + Ok(v) => self.set(reg, lane, v), + Err(e) => self.fail(lane, e), + } + } +} diff --git a/core/expression/src/lane/exec/load.rs b/core/expression/src/lane/exec/load.rs new file mode 100644 index 00000000..6589d834 --- /dev/null +++ b/core/expression/src/lane/exec/load.rs @@ -0,0 +1,1445 @@ +use super::context::Context; +use super::frame::{Fault, Frame, SEGMENTS}; +use super::Executor; +use crate::compiler::FetchFastTarget; +use crate::functions::{FunctionKind, InternalFunction}; +use crate::lane::builtins::{Arg, Builtins, ListView, Out, Text, TextKernel}; +use crate::lane::columns::{Column, Dictionary, Values}; +use crate::lane::effect::Effect; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +use crate::lane::output::Item; +use crate::lane::program::{Kind, Load, LoadCall, Reg}; +use crate::lane::scaled::Scaled; +use crate::lane::Bits; +use crate::lane::ShortKey; +use crate::variable::Variable; +use crate::vm::VMError; +use rust_decimal::Decimal; +use std::sync::Arc; +use zen_types::variable::ShapeHint; + +impl Executor { + const MEMO: usize = 256; + + #[inline(never)] + pub(super) fn load_call( + c: &LoadCall, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + let Some(builtin) = Builtins::of(&c.kind) else { + let e = Ops::error("CallFunction", format!("Function `{}` not found", c.kind)); + for lane in Lanes::of(active) { + f.fail(lane, e.clone()); + } + return; + }; + let consts: smallvec::SmallVec<[Variable; 2]> = c + .args + .iter() + .map(|id| f.consts[*id as usize].clone()) + .collect(); + let mut hint = 0usize; + let mut call = |first: Arg| -> Result { + let mut args: smallvec::SmallVec<[Arg; 4]> = smallvec::SmallVec::new(); + args.push(first); + args.extend(consts.iter().map(Arg::of)); + Builtins::call_hinted(builtin, &c.kind, &args, &mut hint) + }; + let column = ctx.column(c.site); + if let Some(Some(col)) = column { + let cheap = matches!(col.values, Values::Dict { .. }) + && f.kind(c.scratch) == Kind::Str + && matches!( + Text::kernel(&c.kind), + Some(TextKernel::Test(_) | TextKernel::Size) + ); + let rows = ctx.columns.map_or(0, |c| c.rows); + let wide = matches!(col.values, Values::Dict { values, .. } if values.len() > Self::MEMO || values.len() * 4 > rows * 3); + if cheap + || wide + || !matches!( + col.values, + Values::Dict { .. } | Values::Any(_) | Values::List { .. } + ) + { + Self::column_load(&c.site, &c.scratch, active, f, ctx); + Self::step(&c.call, active, f, &mut [], ctx); + return; + } + } + let mut done = f.none(); + if let ( + true, + Some(Some( + list @ Column { + values: Values::List { offsets, child }, + .. + }, + )), + ) = (c.args.is_empty(), column) + { + let len = matches!(c.kind, FunctionKind::Internal(InternalFunction::Len)); + let function = Self::reducer(&c.kind); + let child = &child.column(); + if len || function.is_some() { + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + let (Some(a), Some(b), true) = + (offsets.get(row), offsets.get(row + 1), list.valid(row)) + else { + continue; + }; + let a = usize::try_from(*a).unwrap_or(0); + let b = usize::try_from(*b).unwrap_or(0).max(a); + let int = match (len, function, child.values) { + (true, ..) => i64::try_from(b - a).ok().map(|n| (n, 0)), + (false, Some(InternalFunction::Sum), _) if a == b => Some((0, 0)), + (false, Some(function), Values::I64(v)) if child.validity.is_none() => v + .get(a..b) + .and_then(|items| Self::reduce_ints(function, items)) + .map(|n| (n, 0)), + (false, Some(function), Values::Scaled { mant, scale }) + if child.validity.is_none() => + { + mant.get(a..b) + .zip(scale.get(a..b)) + .and_then(|(mant, scale)| { + Self::reduce_scaled(function, mant, scale) + }) + } + _ => None, + }; + match (int, function, f.kind(c.dst)) { + (Some((v, s)), Some(InternalFunction::Avg), _) => { + let r = Scaled::decimal(v, s) + .checked_div(Decimal::from(b - a)) + .map(Out::Num); + if let Some(out) = r { + f.write(c.dst, lane, Ok(out)); + done.set(lane); + continue; + } + } + (Some((v, s)), _, Kind::Num) => { + let at = f.at(c.dst, lane); + f.mant[at] = v; + f.scales[at] = s; + f.wide[c.dst as usize].unset(lane); + f.boxed[c.dst as usize].unset(lane); + done.set(lane); + continue; + } + (Some((v, s)), _, _) => { + f.write(c.dst, lane, Ok(Out::Num(Scaled::decimal(v, s)))); + done.set(lane); + continue; + } + _ => {} + } + let out = function.and_then(|function| { + Self::reduce(function, (a..b).map(|i| Self::child_number(child, i))) + }); + if let (false, Some(out)) = (len, out) { + f.write(c.dst, lane, Ok(out)); + done.set(lane); + } + } + } + } + if let ( + FunctionKind::Internal(InternalFunction::Contains), + [Variable::String(needle)], + Some(Some( + list @ Column { + values: Values::List { offsets, child }, + .. + }, + )), + ) = (&c.kind, consts.as_slice(), column) + { + let child = child.column(); + if matches!( + child.values, + Values::Text { .. } + | Values::Utf8 { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) + ) { + let needle = needle.as_bytes(); + for lane in Lanes::of(active & !done) { + let row = ctx.base + f.rows[lane] as usize; + let (Some(a), Some(b), true) = + (offsets.get(row), offsets.get(row + 1), list.valid(row)) + else { + continue; + }; + let (a, b) = ( + usize::try_from(*a).unwrap_or(0), + usize::try_from(*b).unwrap_or(0), + ); + let hit = (a..b).any(|i| child.valid(i) && child.bytes(i) == Some(needle)); + f.write(c.dst, lane, Ok(Out::Bool(hit))); + done.set(lane); + } + } + } + let slot = c.memo as usize; + if f.memo.len() <= slot { + f.memo.resize_with(slot + 1, Vec::new); + } + let text = f.kind(c.dst) == Kind::Str; + let pure = Effect::function(&c.kind) != Effect::Random; + for lane in Lanes::of(active & !done) { + let mut share = None; + let r = match column { + Some(Some(col)) => { + let row = ctx.base + f.rows[lane] as usize; + match (col.values, col.valid(row), col.code(row)) { + (Values::Dict { values, .. }, true, Some(code)) if text && pure => { + let span = Frame::::cached(&mut f.shared, slot, values.len()) + .get(code) + .copied(); + if let Some(span) = span.filter(|s| *s != Frame::::UNSET) { + let at = f.at(c.dst, lane); + f.spans[at] = span; + f.boxed[c.dst as usize].unset(lane); + continue; + } + share = Some(code); + let memo = &mut f.memo[slot]; + if memo.len() < values.len() { + memo.resize(values.len(), None); + } + match memo.get(code) { + Some(Some(done)) => done.clone(), + _ => { + let r = + Self::with_column_arg(&values.column(), code, &mut call); + if let Some(entry) = f.memo[slot].get_mut(code) { + *entry = Some(r.clone()); + } + r + } + } + } + (Values::Dict { values, .. }, true, Some(code)) if pure => { + let memo = &mut f.memo[slot]; + if memo.len() < values.len() { + memo.resize(values.len(), None); + } + match memo.get(code) { + Some(Some(done)) => done.clone(), + _ => { + let r = + Self::with_column_arg(&values.column(), code, &mut call); + if let Some(entry) = f.memo[slot].get_mut(code) { + *entry = Some(r.clone()); + } + r + } + } + } + _ => Self::with_column_arg(col, row, &mut call), + } + } + Some(None) => call(Arg::Null), + None => Self::with_row_value(&c.load, c.site, lane, f, ctx, |v| match v { + Ok(v) => call(Arg::of(v)), + Err(e) => Err(Fault::Vm(e)), + }), + }; + f.write_call(c.dst, lane, r); + if let (Some(code), false, true) = + (share, f.boxed[c.dst as usize].get(lane), f.alive.get(lane)) + { + let span = f.spans[f.at(c.dst, lane)]; + if let Some(entry) = f.shared.get_mut(slot).and_then(|e| e.get_mut(code)) { + *entry = span; + } + } + } + } + + pub(super) fn with_column_arg(col: &Column, row: usize, f: impl FnOnce(Arg) -> T) -> T { + if !col.valid(row) { + return f(Arg::Null); + } + match col.values { + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) => match col.text(row) { + Some(text) => f(Arg::Str(text)), + None => f(Arg::Null), + }, + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => { + match col.number(row) { + Some(n) => f(Arg::Num(n)), + None => f(Arg::Null), + } + } + Values::Bool { .. } => match col.boolean(row) { + Some(b) => f(Arg::Bool(b)), + None => f(Arg::Null), + }, + Values::List { child, .. } => { + let (start, end) = col.range(row).unwrap_or_default(); + let child = child.column(); + f(Arg::List(ListView { + child: &child, + start, + end, + })) + } + _ => match col.borrowed(row) { + Some(value) => f(Arg::of(value)), + None => { + let value = col.variable(row); + f(Arg::of(&value)) + } + }, + } + } + + pub(super) fn with_row_value( + load: &Load, + site: u32, + lane: usize, + f: &mut Frame, + ctx: &Context, + then: impl FnOnce(Result<&Variable, VMError>) -> T, + ) -> T { + let slot = site as usize * SEGMENTS; + let row = f.rows[lane]; + let env = ctx.envs.get(row); + let null = Variable::Null; + match load { + Load::Env(key) => match env.local_str(key) { + Some(v) => then(Ok(v)), + None => match env.base() { + Variable::Object(o) => { + let o = o.borrow(); + then(Ok(o.get_hinted(&mut f.hints[slot], key).unwrap_or(&null))) + } + Variable::Null => then(Ok(&null)), + _ => then(Err(Ops::error("FetchEnv", "Unsupported type"))), + }, + }, + Load::Path(_) => match Self::row_value(load, site, lane, f, ctx) { + Ok(v) => then(Ok(&v)), + Err(e) => then(Err(e)), + }, + } + } + + pub(super) fn row_value( + load: &Load, + site: u32, + lane: usize, + f: &mut Frame, + ctx: &Context, + ) -> Result { + let row = f.rows[lane]; + match load { + Load::Env(key) => Self::lookup(key, site, row, f, ctx, |_, r| r.cloned()), + Load::Path(path) => { + let env = ctx.envs.get(row); + let slot = site as usize * SEGMENTS; + Ok(match Self::simple(path) && env.locals().is_empty() { + true => { + Self::path_with(env.base(), &path[1..], &mut f.hints[slot..], |v| v.clone()) + } + false => Ops::fetch_fast(path, ctx.roots.get(row), env), + }) + } + } + } + + #[inline(never)] + pub(super) fn column_load( + site: &u32, + dst: &Reg, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + match ctx.column(*site).flatten() { + Some( + column @ Column { + values: Values::Dict { keys, values }, + .. + }, + ) if f.kind(*dst) == Kind::Str => { + let base = *dst as usize * f.width; + let mut slow = f.none(); + let cache = Frame::::cached(&mut f.dicts, *site as usize, values.len()); + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + let code = keys.get(row).and_then(|k| usize::try_from(*k).ok()); + let (Some(code), true) = (code, column.valid(row)) else { + slow.set(lane); + continue; + }; + let span = match cache.get(code) { + Some(span) if *span != Frame::::UNSET => *span, + _ => match values.valid(code).then(|| values.text(code)).flatten() { + Some(text) => { + let start = f.arena.len() as u32; + f.arena.push_str(text); + let span = (start, f.arena.len() as u32); + if let Some(entry) = cache.get_mut(code) { + *entry = span; + } + span + } + None => { + slow.set(lane); + continue; + } + }, + }; + f.spans[base + lane] = span; + } + f.boxed[*dst as usize] &= !(active & !slow); + Self::fill_slow(f, *dst, column, slow, |f, lane| { + ctx.base + f.rows[lane] as usize + }); + } + Some(column) => Self::fill(f, *dst, column, ctx.base, active), + None if f.kind(*dst) == Kind::Dyn && active == M::all(f.width) => { + let base = *dst as usize * f.width; + f.regs[base..base + f.width].fill(Variable::Null); + } + None => { + for lane in Lanes::of(active) { + f.set(*dst, lane, Variable::Null); + } + } + } + } + + #[inline(never)] + pub(super) fn env( + dst: &Reg, + key: &Arc, + site: &u32, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + let slot = *site as usize * SEGMENTS; + for lane in Lanes::of(active) { + let env = ctx.envs.get(f.rows[lane]); + if let Some(v) = env.local_str(key) { + let v = v.clone(); + f.set(*dst, lane, v); + continue; + } + match env.base() { + Variable::Object(o) => { + let o = o.borrow(); + match o.get_hinted(&mut f.hints[slot], key) { + Some(v) => f.store(*dst, lane, v), + None => f.set(*dst, lane, Variable::Null), + } + } + Variable::Null => f.set(*dst, lane, Variable::Null), + _ => f.fail(lane, Ops::error("FetchEnv", "Unsupported type")), + } + } + } + + #[inline(never)] + pub(super) fn path( + dst: &Reg, + path: &[FetchFastTarget], + site: &u32, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + let slot = *site as usize * SEGMENTS; + let simple = Self::simple(path); + let mut hints = std::mem::take(&mut f.hints); + for lane in Lanes::of(active) { + let row = f.rows[lane]; + let env = ctx.envs.get(row); + if simple && env.locals().is_empty() { + Self::path_with(env.base(), &path[1..], &mut hints[slot..], |v| { + f.store(*dst, lane, v) + }); + continue; + } + let v = Ops::fetch_fast(path, ctx.roots.get(row), env); + f.set(*dst, lane, v); + } + f.hints = hints; + } + + #[inline(never)] + pub(super) fn field( + dst: &Reg, + src: &Reg, + key: &Arc, + site: &u32, + active: M, + f: &mut Frame, + ) { + let slot = *site as usize * SEGMENTS; + for lane in Lanes::of(active) { + let object = match f.generic(*src, lane) { + true => match &f.regs[f.at(*src, lane)] { + Variable::Object(o) => Some(o.clone()), + _ => None, + }, + false => None, + }; + match object { + Some(o) => { + let o = o.borrow(); + match o.get_hinted(&mut f.hints[slot], key) { + Some(v) => f.store(*dst, lane, v), + None => f.set(*dst, lane, Variable::Null), + } + } + None => f.set(*dst, lane, Variable::Null), + } + } + } + + pub(super) fn view_field( + dst: &Reg, + src: &Reg, + key: &Arc, + nested: bool, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + let Some(parent) = ctx.view(f.program, *src) else { + return; + }; + let Some(field) = parent.field(key).copied() else { + for lane in Lanes::of(active) { + f.set(*dst, lane, Variable::Null); + } + return; + }; + let field = ctx.text(field); + if let (true, Values::Struct { .. }, None) = (nested, field.values, parent.validity) { + ctx.register(f.program, *dst, field); + f.views.push(*dst); + return; + } + Self::fill_with(f, *dst, &field, active, |f, lane| { + f.elements.get(lane).copied().unwrap_or_default() as usize + }); + if parent.validity.is_some() { + for lane in Lanes::of(active) { + let index = f.elements.get(lane).copied().unwrap_or_default() as usize; + if !parent.valid(index) { + f.set(*dst, lane, Variable::Null); + } + } + } + } + + fn eq_cached( + f: &mut Frame, + offsets: &[i32], + data: &[u8], + k: &[u8], + base: usize, + ) -> Option { + let width = f.width; + let window = offsets.get(base..=base + width)?; + let at = Self::prefixes(f, offsets, data, base)?; + let entry = &f.prefixes[at]; + let (n, key) = (u32::try_from(k.len()).ok()?, ShortKey::of(k)); + let long = k.len() > 8; + let mut word = M::none(width); + for (chunk, (lens, words)) in entry + .lens + .chunks(64) + .zip(entry.words.chunks(64)) + .enumerate() + { + let mut bits = 0u64; + for (i, (len, prefix)) in lens.iter().zip(words).enumerate() { + bits |= (((*len == n) & (*prefix == key)) as u64) << i; + } + if long { + let lo = chunk * 64; + Bits::each(bits, 0, |i| { + let lane = lo + i; + if data.get(window[lane] as usize..window[lane + 1] as usize) != Some(k) { + bits &= !(1u64 << i); + } + }); + } + word.set_word(chunk, bits); + } + Some(word) + } + + pub(super) fn prefixes( + f: &mut Frame, + offsets: &[i32], + data: &[u8], + base: usize, + ) -> Option { + let width = f.width; + let window = offsets.get(base..=base + width)?; + let id = Some((data.as_ptr() as usize, offsets.as_ptr() as usize, base)); + let at = match f.prefixes.iter().position(|p| p.id == id) { + Some(at) => at, + None => { + let at = match f.prefixes.iter().position(|p| p.id.is_none()) { + Some(at) => at, + None if f.prefixes.len() < 8 => { + f.prefixes.push(Default::default()); + f.prefixes.len() - 1 + } + None => 0, + }; + let entry = &mut f.prefixes[at]; + entry.id = id; + entry.words.resize(width, 0); + entry.lens.resize(width, 0); + for ((w, len), prefix) in window + .windows(2) + .zip(entry.lens.iter_mut()) + .zip(entry.words.iter_mut()) + { + let (a, b) = (w[0] as usize, w[1] as usize); + let size = b.wrapping_sub(a); + let fits = a <= b && b <= data.len(); + *prefix = match fits { + true => ShortKey::at(data, a, size), + false => 0, + }; + *len = match fits { + true => u32::try_from(size).unwrap_or(u32::MAX), + false => u32::MAX, + }; + } + at + } + }; + Some(at) + } + + fn same(x: &[u8], k: &[u8]) -> bool { + x.len() == k.len() && x.iter().zip(k).all(|(a, b)| a == b) + } + + #[inline(never)] + #[allow(clippy::too_many_arguments)] + pub(super) fn load_eq( + dst: &Reg, + load: &Load, + site: &u32, + id: &u32, + not: &bool, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + let k = f.consts[*id as usize].clone(); + let d = *dst as usize; + let mut word = f.none(); + match ctx.column(*site) { + Some(Some(column)) if matches!(column.values, Values::Dict { values, .. } if values.len() <= Self::MEMO) => + { + let mut matched = [0u64; 4]; + if let Values::Dict { values, .. } = column.values { + for code in 0..values.len() { + matched[code / 64] |= (values.equals(code, &k) as u64) << (code % 64); + } + } + let null = matches!(k, Variable::Null); + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + let hit = match (column.valid(row), column.code(row)) { + (false, _) => null, + (true, Some(code)) => Bits::get(&matched, code), + (true, None) => false, + }; + word.put(lane, hit); + } + } + Some(Some(column)) => { + let bytes = match column.values { + Values::Text { offsets, data } => Some((offsets, data.as_bytes())), + Values::Utf8 { offsets, data } => Some((offsets, data)), + _ => None, + }; + let texts = match (&k, f.dense, bytes) { + (Variable::String(_), true, None) => column.texts(ctx.base, f.width), + _ => None, + }; + let window = match (f.dense, bytes, k.as_str()) { + (true, Some((offsets, data)), Some(k)) => { + Self::eq_cached(f, offsets, data, k.as_bytes(), ctx.base) + .map(|w: M| w & column.valid_mask(ctx.base, f.width)) + } + _ => None, + }; + match (texts, bytes, k.as_str()) { + _ if window.is_some() => word = window.unwrap_or(word), + (Some(texts), _, Some(k)) => { + let valid = active & column.valid_mask(ctx.base, f.width); + let k = k.as_bytes(); + texts.each_bytes(valid, |lane, x| word.put(lane, Self::same(x, k))); + } + (None, Some((offsets, data)), Some(k)) => { + let k = k.as_bytes(); + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + let hit = + match (column.valid(row), offsets.get(row), offsets.get(row + 1)) { + (true, Some(&a), Some(&b)) => { + (b - a) as usize == k.len() + && data + .get(a as usize..b as usize) + .is_some_and(|x| Self::same(x, k)) + } + _ => false, + }; + word.put(lane, hit); + } + } + _ => { + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + word.put(lane, column.equals(row, &k)); + } + } + } + } + Some(None) => { + if matches!(k, Variable::Null) { + word = active; + } + } + None => { + let slot = *site as usize * SEGMENTS; + for lane in Lanes::of(active) { + let row = f.rows[lane]; + let env = ctx.envs.get(row); + let hit = match load { + Load::Env(key) => Self::lookup(key, *site, row, f, ctx, |_, r| { + r.map(|v| Ops::equal(v, &k)) + }), + Load::Path(path) => match Self::simple(path) && env.locals().is_empty() { + true => Ok(Self::path_with( + env.base(), + &path[1..], + &mut f.hints[slot..], + |v| Ops::equal(v, &k), + )), + false => Ok(Ops::equal( + &Ops::fetch_fast(path, ctx.roots.get(row), env), + &k, + )), + }, + }; + match hit { + Ok(h) => word.put(lane, h), + Err(e) => f.fail(lane, e), + } + } + } + } + let word = if *not { !word & active } else { word & active }; + f.put_mask(d as Reg, active, word); + } + + #[inline(never)] + pub(super) fn load_in( + dst: &Reg, + a: &Reg, + load: &Load, + site: &u32, + active: M, + f: &mut Frame, + ctx: &mut Context, + ) { + let list = match ctx.column(*site) { + Some(Some(column)) => match column.values { + Values::List { child, .. } if Self::scannable(&child.column()) => { + Some((column, child.column())) + } + _ => None, + }, + _ => None, + }; + for lane in Lanes::of(active) { + let hit = match list { + Some((column, child)) => { + let row = ctx.base + f.rows[lane] as usize; + match (column.valid(row), column.range(row)) { + (true, Some((from, to))) => { + f.with(*a, lane, |needle| Self::scan(needle, &child, from, to)) + } + _ => None, + } + } + None => None, + }; + let result = match hit { + Some(hit) => Ok(hit), + None => { + let haystack = match ctx.column(*site) { + Some(Some(column)) => Ok(column.variable(ctx.base + f.rows[lane] as usize)), + Some(None) => Ok(Variable::Null), + None => Self::row_value(load, *site, lane, f, ctx), + }; + haystack.and_then(|h| Ops::membership(f.take(*a, lane), &h)) + } + }; + f.put(*dst, lane, result.map(Variable::Bool)); + } + } + + fn scannable(child: &Column) -> bool { + matches!( + child.values, + Values::Strs(_) + | Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::I64(_) + | Values::Dec(_) + | Values::Scaled { .. } + | Values::Bool { .. } + ) + } + + fn scan(needle: &Variable, child: &Column, from: usize, to: usize) -> Option { + let mut items = from..to; + Some(match needle { + Variable::Null => items.any(|i| !child.valid(i)), + Variable::Number(n) => items.any(|i| { + child.valid(i) && child.number(i).is_some_and(|x| Ops::same_number(&x, n)) + }), + Variable::String(s) => { + items.any(|i| child.valid(i) && child.text(i) == Some(s.as_ref())) + } + Variable::Bool(b) => items.any(|i| child.valid(i) && child.boolean(i) == Some(*b)), + _ => return None, + }) + } + + #[inline(never)] + pub(super) fn coalesce(dst: &Reg, a: &Reg, id: &u32, active: M, f: &mut Frame) { + let typed = match f.kind(*dst) == f.kind(*a) && f.kind(*a) != Kind::Dyn { + true => active & f.typed(*a), + false => f.none(), + }; + f.copy_typed(*dst, *a, typed); + let mut null = f.none(); + for lane in Lanes::of(active & !typed) { + match f.with(*a, lane, |v| matches!(v, Variable::Null)) { + true => null.set(lane), + false => { + let v = f.take(*a, lane); + f.set(*dst, lane, v); + } + } + } + if null.is_empty() { + return; + } + let value = f.consts[*id as usize].clone(); + if f.fill_typed(*dst, null, &value) { + return; + } + match value { + fallback @ (Variable::Array(_) | Variable::Object(_)) => { + for lane in Lanes::of(null) { + f.set(*dst, lane, fallback.depth_clone(usize::MAX)); + } + } + fallback => { + for lane in Lanes::of(null) { + f.set(*dst, lane, fallback.clone()); + } + } + } + } + + #[inline] + pub(super) fn lookup( + key: &str, + site: u32, + row: u32, + f: &mut Frame, + ctx: &Context, + then: impl FnOnce(&mut Frame, Result<&Variable, VMError>) -> T, + ) -> T { + let env = ctx.envs.get(row); + if let Some(v) = env.local_str(key) { + return then(f, Ok(v)); + } + match env.base() { + Variable::Object(o) => { + let o = o.borrow(); + match o.get_hinted(&mut f.hints[site as usize * SEGMENTS], key) { + Some(v) => then(f, Ok(v)), + None => then(f, Ok(&Variable::Null)), + } + } + Variable::Null => then(f, Ok(&Variable::Null)), + _ => then(f, Err(Ops::error("FetchEnv", "Unsupported type"))), + } + } + + pub(super) fn simple(path: &[FetchFastTarget]) -> bool { + matches!(path.first(), Some(FetchFastTarget::Begin)) + && path.len() <= SEGMENTS + && path[1..] + .iter() + .all(|p| matches!(p, FetchFastTarget::String(_))) + } + + const SHALLOW: usize = 64; + + pub(super) fn path_with( + base: &Variable, + path: &[FetchFastTarget], + hints: &mut [ShapeHint], + then: impl FnOnce(&Variable) -> T, + ) -> T { + match path.len() < Self::SHALLOW { + true => Self::walk_path(base, path, hints, then), + false => Self::deep_path(base, path, hints, then), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn deep_path( + base: &Variable, + path: &[FetchFastTarget], + hints: &mut [ShapeHint], + then: impl FnOnce(&Variable) -> T, + ) -> T { + Self::walk_path(base, path, hints, then) + } + + fn walk_path( + base: &Variable, + path: &[FetchFastTarget], + hints: &mut [ShapeHint], + then: impl FnOnce(&Variable) -> T, + ) -> T { + let Some((FetchFastTarget::String(key), rest)) = path.split_first() else { + return then(base); + }; + let Variable::Object(o) = base else { + return then(&Variable::Null); + }; + let o = o.borrow(); + let (hint, tail) = hints.split_at_mut(1); + match o.get_hinted(&mut hint[0], key) { + Some(next) => Self::path_with(next, rest, tail, then), + None => then(&Variable::Null), + } + } + + pub(super) fn fill( + f: &mut Frame, + dst: Reg, + column: &Column, + base: usize, + active: M, + ) { + if f.dense && active == M::all(f.width) && Self::fill_dense(f, dst, column, base) { + return; + } + Self::fill_with(f, dst, column, active, |f, lane| { + base + f.rows[lane] as usize + }) + } + + pub(super) fn fill_dense( + f: &mut Frame, + dst: Reg, + column: &Column, + base: usize, + ) -> bool { + let width = f.width; + let d = dst as usize; + let at = d * width; + let all = M::all(width); + let valid: M = column.valid_mask(base, width); + let mut slow = all & !valid; + match (f.kind(dst), column.values) { + (Kind::Num, Values::I64(values)) => { + let Some(src) = values.get(base..base + width) else { + return false; + }; + f.mant[at..at + width].copy_from_slice(src); + f.scales[at..at + width].fill(0); + } + (Kind::Num, Values::Scaled { mant, scale }) => { + let (Some(m), Some(sc)) = + (mant.get(base..base + width), scale.get(base..base + width)) + else { + return false; + }; + f.mant[at..at + width].copy_from_slice(m); + f.scales[at..at + width].copy_from_slice(sc); + } + (Kind::Num, Values::Dec(values)) => { + let Some(src) = values.get(base..base + width) else { + return false; + }; + for (lane, n) in src.iter().enumerate() { + match Scaled::parts(n) { + Some((m, sc)) => { + f.mant[at + lane] = m; + f.scales[at + lane] = sc; + } + None => slow.set(lane), + } + } + } + (Kind::Bool, Values::Bool { bits, offset }) => { + f.bits[d] = Column::mask(bits, offset + base, width); + } + (Kind::Dyn, Values::Any(values)) => { + let Some(src) = values.get(base..base + width) else { + return false; + }; + f.regs[at..at + width].clone_from_slice(src); + } + ( + Kind::Num, + Values::Dict { + keys, + values: Dictionary::Scaled { mant, scale }, + }, + ) => { + let Some(codes) = keys.get(base..base + width) else { + return false; + }; + for (lane, code) in codes.iter().enumerate() { + match usize::try_from(*code) + .ok() + .and_then(|c| Some((*mant.get(c)?, *scale.get(c)?))) + { + Some((m, sc)) => { + f.mant[at + lane] = m; + f.scales[at + lane] = sc; + } + None => slow.set(lane), + } + } + } + ( + Kind::Bool, + Values::Dict { + keys, + values: Dictionary::Bool { bits }, + }, + ) => { + let Some(codes) = keys.get(base..base + width) else { + return false; + }; + let mut word = f.none(); + for (lane, code) in codes.iter().enumerate() { + match usize::try_from(*code) + .ok() + .and_then(|c| bits.get(c / 64).map(|w| w >> (c % 64) & 1 == 1)) + { + Some(b) => word.put(lane, b), + None => slow.set(lane), + } + } + f.bits[d] = word; + } + (Kind::Str, Values::Utf8 { .. } | Values::Text { .. }) => { + let (offsets, text) = match column.values { + Values::Text { offsets, data } => { + let (Some(first), Some(last)) = + (offsets.get(base), offsets.get(base + width)) + else { + return false; + }; + let Some(text) = data.get(*first as usize..*last as usize) else { + return false; + }; + (offsets, text) + } + Values::Utf8 { offsets, data } => { + let (Some(first), Some(last)) = + (offsets.get(base), offsets.get(base + width)) + else { + return false; + }; + let Some(text) = data + .get(*first as usize..*last as usize) + .and_then(|b| std::str::from_utf8(b).ok()) + else { + return false; + }; + (offsets, text) + } + _ => return false, + }; + let first = &offsets[base]; + let window = &offsets[base..=base + width]; + let monotonic = window.windows(2).fold(true, |ok, w| ok & (w[0] <= w[1])); + let bounded = monotonic + && (text.is_ascii() + || window.iter().all(|o| { + usize::try_from(o - first).is_ok_and(|i| text.is_char_boundary(i)) + })); + if !bounded { + return false; + } + let start = f.arena.len() as i64 - *first as i64; + f.arena.push_str(text); + for (lane, pair) in offsets[base..=base + width].windows(2).enumerate() { + f.spans[at + lane] = ( + (start + pair[0] as i64) as u32, + (start + pair[1] as i64) as u32, + ); + } + } + (Kind::Str, Values::Strs(texts)) => { + let Some(texts) = texts.get(base..base + width) else { + return false; + }; + for (lane, text) in texts.iter().enumerate() { + let span = f.intern(text); + f.spans[at + lane] = span; + } + } + _ => return false, + } + let fast = all & !slow; + if f.kind(dst) != Kind::Dyn { + f.boxed[d] &= !fast; + } + if f.kind(dst) == Kind::Num { + f.wide[d] &= !fast; + } + Self::fill_slow(f, dst, column, slow, |_, lane| base + lane); + true + } + + #[inline] + pub(super) fn fill_with( + f: &mut Frame, + dst: Reg, + column: &Column, + active: M, + index: impl Fn(&Frame, usize) -> usize, + ) { + let kind = f.kind(dst); + let d = dst as usize; + let at = d * f.width; + let mut slow = f.none(); + match (kind, column.values) { + (Kind::Num, Values::Dec(values)) => { + for lane in Lanes::of(active) { + let row = index(f, lane); + match (column.valid(row), values.get(row)) { + (true, Some(n)) => match Scaled::parts(n) { + Some((m, s)) => { + f.mant[at + lane] = m; + f.scales[at + lane] = s; + } + None => slow.set(lane), + }, + _ => slow.set(lane), + } + } + } + (Kind::Num, Values::Scaled { mant, scale }) => { + for lane in Lanes::of(active) { + let row = index(f, lane); + match (column.valid(row), mant.get(row), scale.get(row)) { + (true, Some(m), Some(s)) => { + f.mant[at + lane] = *m; + f.scales[at + lane] = *s; + } + _ => slow.set(lane), + } + } + } + (Kind::Num, Values::I64(values)) => { + for lane in Lanes::of(active) { + let row = index(f, lane); + match (column.valid(row), values.get(row)) { + (true, Some(n)) => { + f.mant[at + lane] = *n; + f.scales[at + lane] = 0; + } + _ => slow.set(lane), + } + } + } + ( + Kind::Str, + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) + | Values::Dict { .. }, + ) => { + for lane in Lanes::of(active) { + let row = index(f, lane); + match (column.valid(row), column.text(row)) { + (true, Some(t)) => f.put_text(dst, lane, t), + _ => slow.set(lane), + } + } + } + ( + Kind::Num, + Values::Dict { + keys, + values: Dictionary::Scaled { mant, scale }, + }, + ) => { + for lane in Lanes::of(active) { + let row = index(f, lane); + let parts = keys + .get(row) + .and_then(|code| usize::try_from(*code).ok()) + .and_then(|c| Some((*mant.get(c)?, *scale.get(c)?))); + match (column.valid(row), parts) { + (true, Some((m, s))) => { + f.mant[at + lane] = m; + f.scales[at + lane] = s; + } + _ => slow.set(lane), + } + } + } + (Kind::Dyn, Values::Any(values)) => { + for lane in Lanes::of(active) { + let row = index(f, lane); + match (column.valid(row), values.get(row)) { + (true, Some(value)) => f.regs[at + lane] = value.clone(), + _ => slow.set(lane), + } + } + } + ( + Kind::Bool, + Values::Bool { .. } + | Values::Dict { + values: Dictionary::Bool { .. }, + .. + }, + ) => { + let mut word = f.none(); + for lane in Lanes::of(active) { + let row = index(f, lane); + match (column.valid(row), column.boolean(row)) { + (true, Some(b)) => word.put(lane, b), + _ => slow.set(lane), + } + } + f.bits[d] = (f.bits[d] & !active) | word; + } + (Kind::List, Values::List { offsets, child }) => { + let child = child.column(); + if child.validity.is_some() + || !matches!( + child.values, + Values::Scaled { .. } + | Values::Text { .. } + | Values::Bool { .. } + | Values::Utf8 { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) + | Values::I64(_) + | Values::Dec(_) + ) + { + slow = active; + } else { + for lane in Lanes::of(active) { + let row = index(f, lane); + let range = offsets + .get(row) + .zip(offsets.get(row + 1)) + .map(|(a, b)| (*a as usize, (*b as usize).max(*a as usize))); + let (true, Some((a, b))) = (column.valid(row), range) else { + slow.set(lane); + continue; + }; + let start = f.items.len() as u32; + match child.values { + Values::Scaled { mant, scale } => { + match mant.get(a..b).zip(scale.get(a..b)) { + Some((m, sc)) => f.items.extend_nums(m, sc), + None => { + slow.set(lane); + continue; + } + } + } + Values::Text { offsets: co, data } => { + for i in a..b { + let text = co + .get(i) + .zip(co.get(i + 1)) + .and_then(|(x, y)| data.get(*x as usize..*y as usize)) + .unwrap_or_default(); + let (x, y) = f.intern(text); + f.items.push(Item::Text(x, y)); + } + } + Values::Bool { bits, offset } => { + for i in a..b { + f.items.push(Item::Bool(Bits::get(bits, offset + i))); + } + } + Values::I64(values) => match values.get(a..b) { + Some(values) => { + values.iter().for_each(|v| f.items.push(Item::Num(*v, 0))) + } + None => { + slow.set(lane); + continue; + } + }, + Values::Dec(values) => match values.get(a..b) { + Some(values) => values.iter().for_each(|v| { + f.items.push(match Scaled::parts(v) { + Some((m, s)) => Item::Num(m, s), + None => Item::Value(Variable::Number(*v)), + }) + }), + None => { + slow.set(lane); + continue; + } + }, + Values::Utf8 { offsets: co, data } + if Self::block( + f, + co.get(a..=b).map(|o| o.iter().map(|x| *x as i64)), + data, + ) => {} + Values::LargeUtf8 { offsets: co, data } + if Self::block( + f, + co.get(a..=b).map(|o| o.iter().copied()), + data, + ) => {} + Values::Utf8 { .. } | Values::LargeUtf8 { .. } | Values::Strs(_) => { + if (a..b).any(|i| child.text(i).is_none()) { + slow.set(lane); + continue; + } + for i in a..b { + let (x, y) = f.intern(child.text(i).unwrap_or_default()); + f.items.push(Item::Text(x, y)); + } + } + _ => { + slow.set(lane); + continue; + } + } + f.lists[at + lane] = (start, f.items.len() as u32); + } + } + } + _ => slow = active, + } + if kind != Kind::Dyn { + f.boxed[d] &= !(active & !slow); + } + if kind == Kind::Num { + f.wide[d] &= !(active & !slow); + } + Self::fill_slow(f, dst, column, slow, index); + } + + fn block( + f: &mut Frame, + offsets: Option + Clone>, + data: &[u8], + ) -> bool { + let Some(offsets) = offsets else { + return false; + }; + let mut bounds = offsets.clone(); + let (Some(first), Some(last)) = (bounds.next(), offsets.clone().last()) else { + return false; + }; + let (Ok(lo), Ok(hi)) = (usize::try_from(first), usize::try_from(last)) else { + return false; + }; + let Some(text) = data + .get(lo..hi) + .and_then(|bytes| std::str::from_utf8(bytes).ok()) + else { + return false; + }; + let mut previous = lo; + for offset in offsets.clone() { + let Ok(at) = usize::try_from(offset) else { + return false; + }; + if at < previous || at > hi || !text.is_char_boundary(at - lo) { + return false; + } + previous = at; + } + let base = f.arena.len(); + f.arena.push_str(text); + let mut start = lo; + for end in offsets.skip(1) { + let end = end as usize; + let (x, y) = ((base + start - lo) as u32, (base + end - lo) as u32); + f.items.push(Item::Text(x, y)); + start = end; + } + true + } + + pub(super) fn fill_slow( + f: &mut Frame, + dst: Reg, + column: &Column, + slow: M, + index: impl Fn(&Frame, usize) -> usize, + ) { + let kind = f.kind(dst); + for lane in Lanes::of(slow) { + let row = index(f, lane); + if !column.valid(row) { + f.set(dst, lane, Variable::Null); + continue; + } + match kind { + Kind::Num => match column.number(row) { + Some(n) => { + f.put_number(dst, lane, n); + f.boxed[dst as usize].unset(lane); + } + None => f.set(dst, lane, column.variable(row)), + }, + Kind::Bool => match column.boolean(row) { + Some(b) => f.set(dst, lane, Variable::Bool(b)), + None => f.set(dst, lane, column.variable(row)), + }, + Kind::Dyn | Kind::Str | Kind::Date | Kind::List => { + f.set(dst, lane, column.variable(row)) + } + } + } + } +} diff --git a/core/expression/src/lane/exec/mod.rs b/core/expression/src/lane/exec/mod.rs new file mode 100644 index 00000000..2dffa08e --- /dev/null +++ b/core/expression/src/lane/exec/mod.rs @@ -0,0 +1,1149 @@ +use crate::lane::ShortKey; +mod closure; +mod context; +mod date; +mod export; +mod frame; +mod load; +mod number; +mod switch; +mod text; + +use crate::functions::{FunctionKind, InternalFunction}; +use crate::lane::builtins::{Arg, Builtins, Out}; +use crate::lane::interval::{Interval, IntervalData}; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +use crate::lane::output::Item; +use crate::lane::program::{ + Binary, Const, Input, Kind, NumCmp, ObjectKey, Op, Operand, Program, Reg, +}; +use crate::lane::scaled::Scaled; +use crate::variable::Variable; +use rust_decimal::Decimal; +use zen_types::symbol::Symbol; + +pub use context::Context; +pub use frame::{CallFault, Fallbacks, Fault, Frame}; + +pub(super) type Parent<'a, M> = (&'a Frame, &'a [u32], &'a [(Reg, Reg)]); + +pub struct Executor; + +impl Executor { + fn member_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let (FunctionKind::Internal(InternalFunction::Contains), [Input::Reg(a), b]) = (kind, args) + else { + return f.none(); + }; + let constant = match b { + Input::Const(id) => match f.consts.get(*id as usize).cloned() { + Some(Variable::String(needle)) => Some(needle), + _ => return f.none(), + }, + Input::Reg(r) if f.kind(*r) == Kind::Str => None, + Input::Reg(_) => return f.none(), + }; + let (mut word, mut done) = (f.none(), f.none()); + for lane in Lanes::of(active) { + let needle: &str = match (&constant, b) { + (Some(needle), _) => needle.as_str(), + (None, Input::Reg(r)) if !f.generic(*r, lane) => f.text_at(*r, lane), + _ => continue, + }; + let needle_bytes = needle.as_bytes(); + if f.kind(*a) == Kind::List && !f.generic(*a, lane) { + let (lo, hi) = f.lists[f.at(*a, lane)]; + let mut hit = Some(false); + for i in lo as usize..hi as usize { + match f.items.get(i) { + Item::Text(x, y) => { + if f.arena.as_bytes().get(x as usize..y as usize) == Some(needle_bytes) + { + hit = Some(true); + break; + } + } + Item::Value(Variable::String(s)) if s.as_str() == needle => { + hit = Some(true); + break; + } + Item::Value(Variable::Dynamic(_)) => { + hit = None; + break; + } + _ => {} + } + } + if let Some(hit) = hit { + word.put(lane, hit); + done.set(lane); + } + continue; + } + if !f.generic(*a, lane) { + continue; + } + let Variable::Array(items) = &f.regs[f.at(*a, lane)] else { + continue; + }; + let items = items.borrow(); + if items + .iter() + .any(|item| matches!(item, Variable::Dynamic(_))) + { + continue; + } + word.put( + lane, + items + .iter() + .any(|item| matches!(item, Variable::String(s) if s.as_str() == needle)), + ); + done.set(lane); + } + match f.kind(dst) { + Kind::Bool => { + let d = dst as usize; + f.bits[d] = (f.bits[d] & !done) | word; + f.boxed[d] &= !done; + } + _ => { + for lane in Lanes::of(done) { + f.set(dst, lane, Variable::Bool(word.get(lane))); + } + } + } + done + } + + fn length_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let (FunctionKind::Internal(InternalFunction::Len), [Input::Reg(a)]) = (kind, args) else { + return f.none(); + }; + if f.kind(*a) != Kind::List { + return f.none(); + } + let mut done = f.none(); + for lane in Lanes::of(active) { + if f.generic(*a, lane) { + continue; + } + let (lo, hi) = f.lists[f.at(*a, lane)]; + let n = hi.saturating_sub(lo) as i64; + match f.kind(dst) { + Kind::Num => { + f.put_scaled(dst, lane, n, 0); + } + _ => f.set(dst, lane, Variable::Number(n.into())), + } + done.set(lane); + } + done + } + + #[inline] + fn equal_lane(f: &Frame, a: Reg, b: Reg, lane: usize) -> Option { + let typed = |reg: Reg, value: &Variable| match (f.kind(reg), value) { + (Kind::List, _) => Some(false), + (Kind::Str, Variable::String(s)) => Some(f.text_at(reg, lane) == s.as_str()), + (Kind::Str, Variable::Dynamic(_)) => None, + (Kind::Str, _) => Some(false), + (Kind::Num, Variable::Number(n)) => Some(Ops::same_number(&f.number(reg, lane), n)), + (Kind::Num, _) => Some(false), + (Kind::Bool, Variable::Bool(x)) => Some(f.bits[reg as usize].get(lane) == *x), + (Kind::Bool, _) => Some(false), + _ => None, + }; + match (f.generic(a, lane), f.generic(b, lane)) { + (true, true) => Some(Ops::equal(&f.regs[f.at(a, lane)], &f.regs[f.at(b, lane)])), + (false, true) => typed(a, &f.regs[f.at(b, lane)]), + (true, false) => typed(b, &f.regs[f.at(a, lane)]), + (false, false) => match (f.kind(a), f.kind(b)) { + (Kind::List, _) | (_, Kind::List) => Some(false), + (Kind::Str, Kind::Str) => Some(f.text_at(a, lane) == f.text_at(b, lane)), + (Kind::Num, Kind::Num) => { + Some(Ops::same_number(&f.number(a, lane), &f.number(b, lane))) + } + (Kind::Bool, Kind::Bool) => { + Some(f.bits[a as usize].get(lane) == f.bits[b as usize].get(lane)) + } + _ => None, + }, + } + } + + fn eq_text(f: &Frame, reg: Reg, k: &[u8], lanes: M) -> M { + let base = reg as usize * f.width; + let arena = f.arena.as_bytes(); + let n = k.len(); + let key = (n <= 8).then(|| (ShortKey::of(k), ShortKey::mask(n))); + let mut memo = [((u32::MAX, u32::MAX), false); 4]; + let mut word = f.none(); + for lane in Lanes::of(lanes) { + let span = f.spans[base + lane]; + let slot = (span.0 as usize ^ (span.1 as usize).rotate_left(2)) & 3; + let hit = match memo[slot].0 == span { + true => memo[slot].1, + false => { + let (a, b) = (span.0 as usize, span.1 as usize); + let hit = match ( + arena.get(a..b), + key, + arena + .get(a..a + 8) + .and_then(|x| <[u8; 8]>::try_from(x).ok()), + ) { + (None, _, _) => f.text_at(reg, lane).as_bytes() == k, + (Some(x), _, _) if x.len() != n => false, + (Some(_), Some((key, keep)), Some(bytes)) => { + u64::from_le_bytes(bytes) & keep == key + } + (Some(x), _, _) => x == k, + }; + memo[slot] = (span, hit); + hit + } + }; + word.put(lane, hit); + } + word + } + + pub fn run( + program: &Program, + frames: &mut [Frame], + ctx: &mut Context, + rows: &[u32], + ) { + let Some((frame, _)) = frames.split_first_mut() else { + return; + }; + Self::enter(program, frame, rows, None); + Self::execute(program, frames, ctx); + } + + pub fn enter_top(program: &Program, frame: &mut Frame, rows: &[u32]) { + Self::enter(program, frame, rows, None); + } + + pub fn execute_top(program: &Program, frames: &mut [Frame], ctx: &mut Context) { + Self::execute(program, frames, ctx); + } + + pub(super) fn enter( + program: &Program, + frame: &mut Frame, + rows: &[u32], + parent: Option>, + ) { + let width = rows.len(); + frame.prepare(program, width); + frame.views.clear(); + frame.rows.clear(); + frame.rows.extend_from_slice(rows); + frame.dense = parent.is_none() + && rows + .iter() + .zip(0u32..) + .fold(0u32, |acc, (r, i)| acc | (r ^ i)) + == 0; + if let Some((parent, parents, imports)) = parent { + frame.parents.clear(); + frame.parents.extend_from_slice(parents); + for (from, to) in imports { + for (lane, p) in parents.iter().enumerate() { + let value = parent.value(*from, *p as usize); + frame.set(*to, lane, value); + } + } + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(super) fn execute( + program: &Program, + frames: &mut [Frame], + ctx: &mut Context, + ) { + let Some((frame, rest)) = frames.split_first_mut() else { + return; + }; + for step in &program.steps { + if program.isolated && matches!(step.op, Op::Stage { .. }) { + frame.revive(); + } + let active = frame.masks[step.mask as usize] & frame.alive; + if active.is_empty() { + continue; + } + if !frame.views.is_empty() { + if let Some(dst) = step.op.dst() { + frame.views.retain(|r| *r != dst); + } + } + Self::step(&step.op, active, frame, rest, ctx); + } + } + + pub(super) fn step( + op: &Op, + active: M, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) { + match op { + Op::Const { dst, id } if matches!(f.kind(*dst), Kind::Num | Kind::Bool) => { + match (f.kind(*dst), &f.consts[*id as usize]) { + (Kind::Num, Variable::Number(n)) => f.fill_num(*dst, active, *n), + (Kind::Bool, Variable::Bool(b)) => f.fill_bool(*dst, active, *b), + _ => Self::cold(op, active, f, rest, ctx), + } + } + Op::Branch { + cond, + opcode, + on_true, + on_false, + } => { + let (t, e) = f.split(*cond, active, opcode); + f.masks[*on_true as usize] = t; + f.masks[*on_false as usize] = e; + } + Op::Merge { dst, mask, a, b } + if f.kind(*dst) == Kind::Bool + && f.kind(*a) == Kind::Bool + && f.kind(*b) == Kind::Bool => + { + let m = f.masks[*mask as usize]; + let (ta, tb) = (active & m, active & !m); + let (d, ra, rb) = (*dst as usize, *a as usize, *b as usize); + let bits = (f.bits[ra] & ta) | (f.bits[rb] & tb); + let boxed = (f.boxed[ra] & ta) | (f.boxed[rb] & tb); + for lane in Lanes::of(boxed) { + let src = if ta.get(lane) { *a } else { *b }; + let v = f.take(src, lane); + let at = f.at(*dst, lane); + f.regs[at] = v; + } + f.bits[d] = (f.bits[d] & !active) | bits; + f.boxed[d] = (f.boxed[d] & !active) | boxed; + } + Op::Stage { index } => f.stage = *index, + Op::Num { dst, op, a, b } => Self::num(*op, *dst, *a, *b, active, f), + Op::Cmp { dst, op, a, b } => Self::cmp(*op, *dst, *a, *b, active, f), + Op::Env { site, dst, .. } | Op::Path { site, dst, .. } + if ctx.column(*site).is_some() => + { + Self::column_load(site, dst, active, f, ctx) + } + Op::Env { dst, key, site } => Self::env(dst, key, site, active, f, ctx), + Op::Path { dst, path, site } => Self::path(dst, path, site, active, f, ctx), + Op::Field { + dst, + src, + key, + nested, + .. + } if f.views.contains(src) => Self::view_field(dst, src, key, *nested, active, f, ctx), + Op::Field { + dst, + src, + key, + site, + .. + } => Self::field(dst, src, key, site, active, f), + Op::LoadEq { + dst, + load, + site, + id, + not, + } => Self::load_eq(dst, load, site, id, not, active, f, ctx), + Op::LoadIn { dst, a, load, site } => Self::load_in(dst, a, load, site, active, f, ctx), + Op::Coalesce { dst, a, id } => Self::coalesce(dst, a, id, active, f), + Op::LoadCall(c) => Self::load_call(c, active, f, ctx), + Op::Fold(fold) => Self::fold(fold, active, f, ctx), + Op::Switch(switch) => Self::switch(switch, active, f, ctx), + _ => Self::cold(op, active, f, rest, ctx), + } + } + + #[inline(never)] + fn static_object( + dst: Reg, + pairs: &[(ObjectKey, Reg)], + active: M, + f: &mut Frame, + ) -> bool { + if pairs.len() >= 32 { + return false; + } + let mut template = crate::variable::VariableMap::with_capacity(pairs.len()); + for (key, _) in pairs.iter().rev() { + let ObjectKey::Static(key) = key else { + return false; + }; + template.insert(Symbol::from(key.as_ref()), Variable::Null); + } + let Some(shape) = template + .shape() + .filter(|_| template.len() == pairs.len()) + .cloned() + else { + return false; + }; + for lane in Lanes::of(active) { + let values: Vec = pairs.iter().rev().map(|(_, v)| f.take(*v, lane)).collect(); + f.set( + dst, + lane, + Variable::from_object(crate::variable::VariableMap::from_shape( + shape.clone(), + values, + )), + ); + } + true + } + + fn boxed_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let FunctionKind::Internal(function) = kind else { + return f.none(); + }; + let mut done = f.none(); + match (function, args) { + (InternalFunction::Contains, [Input::Reg(a), Input::Const(id)]) + if f.kind(*a) == Kind::Dyn => + { + let Variable::String(needle) = f.consts[*id as usize].clone() else { + return done; + }; + for lane in Lanes::of(active) { + let found = f.with(*a, lane, |value| match value { + Variable::String(text) => Some(text.contains(needle.as_ref() as &str)), + Variable::Array(items) => { + let items = items.borrow(); + items + .iter() + .all(|item| matches!(item, Variable::String(_) | Variable::Null)) + .then(|| items.iter().any(|item| matches!(item, Variable::String(text) if text.as_ref() as &str == needle.as_ref() as &str))) + } + _ => None, + }); + if let Some(found) = found { + f.write(dst, lane, Ok(Out::Bool(found))); + done.set(lane); + } + } + } + (InternalFunction::Len, [Input::Reg(a)]) if f.kind(*a) == Kind::Dyn => { + for lane in Lanes::of(active) { + let len = f.with(*a, lane, |value| match value { + Variable::String(text) => Some(text.len()), + Variable::Array(items) => Some(items.borrow().len()), + _ => None, + }); + if let Some(len) = len { + f.write(dst, lane, Ok(Out::Num(Decimal::from(len)))); + done.set(lane); + } + } + } + _ => {} + } + done + } + + fn identity_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let (FunctionKind::Internal(InternalFunction::Bool), [Input::Reg(a)]) = (kind, args) else { + return f.none(); + }; + let (a, d) = (*a as usize, dst as usize); + if f.kind(a as Reg) != Kind::Bool || f.kind(dst) != Kind::Bool { + return f.none(); + } + let lanes = active & !f.boxed[a]; + let bits = f.bits[a]; + f.bits[d] = (bits & lanes) | (f.bits[d] & !lanes); + f.boxed[d] &= !lanes; + lanes + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(super) fn cold( + op: &Op, + active: M, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) { + match op { + Op::Const { dst, id } => { + let r = *dst as usize; + let pinned = f.fixed[r]; + let missing = match pinned { + true => active & !f.filled[r], + false => active, + }; + if missing.any() { + let v = f.consts[*id as usize].clone(); + match (f.kind(*dst), &v) { + (Kind::Str, Variable::String(text)) => { + let start = f.arena.len() as u32; + f.arena.push_str(text); + let span = (start, f.arena.len() as u32); + for lane in Lanes::of(missing) { + let at = f.at(*dst, lane); + f.spans[at] = span; + } + f.boxed[r] &= !missing; + } + _ => { + for lane in Lanes::of(missing) { + let value = match pinned { + true => v.clone(), + false => v.deep_clone(), + }; + f.set(*dst, lane, value); + } + } + } + if pinned { + f.filled[r] |= missing; + } + } + } + Op::SelectConst { dst, cond, a, b } => { + let (va, vb) = (f.consts[*a as usize].clone(), f.consts[*b as usize].clone()); + let (mut t, mut e) = (f.none(), f.none()); + let mut slow = active; + if f.kind(*cond) == Kind::Bool { + let boxed = f.boxed[*cond as usize]; + let bits = f.bits[*cond as usize]; + t = active & !boxed & bits; + e = active & !boxed & !bits; + slow = active & boxed; + } + for lane in Lanes::of(slow) { + match f.with(*cond, lane, |v| Ops::truthy(v, "JumpIfFalse")) { + Ok(true) => t.set(lane), + Ok(false) => e.set(lane), + Err(err) => f.fail(lane, err), + } + } + let all = M::all(f.width); + if slow.is_empty() && (t | e) == all && f.select_const(*dst, t, &va, &vb) { + return; + } + for (lanes, v) in [(t, va), (e, vb)] { + match (f.kind(*dst), v) { + (Kind::Num, Variable::Number(n)) => f.fill_num(*dst, lanes, n), + (Kind::Str, Variable::String(text)) => f.fill_text(*dst, lanes, &text), + (Kind::Bool, Variable::Bool(b)) => f.fill_bool(*dst, lanes, b), + (_, v) => { + for lane in Lanes::of(lanes) { + f.set(*dst, lane, v.clone()); + } + } + } + } + } + Op::Not { dst, a } if f.kind(*a) == Kind::Bool && f.kind(*dst) == Kind::Bool => { + let (d, r) = (*dst as usize, *a as usize); + let fast = active & !f.boxed[r]; + f.bits[d] = (f.bits[d] & !fast) | (!f.bits[r] & fast); + f.boxed[d] &= !fast; + for lane in Lanes::of(active & f.boxed[r]) { + let v = Ops::not(f.take(*a, lane)); + f.put(*dst, lane, v); + } + } + Op::Not { dst, a } => { + for lane in Lanes::of(active) { + let r = Ops::not(f.take(*a, lane)); + f.put(*dst, lane, r); + } + } + Op::NullBranch { a, null, other } => { + let typed = active & f.typed(*a); + let (mut n, mut o) = (f.none(), typed); + for lane in Lanes::of(active & !typed) { + match f.with(*a, lane, |v| matches!(v, Variable::Null)) { + true => n.set(lane), + false => o.set(lane), + } + } + f.masks[*null as usize] = n; + f.masks[*other as usize] = o; + } + Op::Merge { dst, mask, a, b } => { + let m = f.masks[*mask as usize]; + let kind = f.kind(*dst); + let (ta, tb) = match (kind == f.kind(*a), kind == f.kind(*b)) { + _ if kind == Kind::Dyn => (f.none(), f.none()), + (ka, kb) => ( + if ka { + active & m & f.typed(*a) + } else { + f.none() + }, + if kb { + active & !m & f.typed(*b) + } else { + f.none() + }, + ), + }; + if active == M::all(f.width) + && (ta | tb) == active + && f.select_typed(*dst, *a, *b, m) + { + return; + } + if ta.any() { + f.copy_typed(*dst, *a, ta); + } + if tb.any() { + f.copy_typed(*dst, *b, tb); + } + for lane in Lanes::of(active & !ta & !tb) { + let src = if m.get(lane) { *a } else { *b }; + let v = f.take(src, lane); + f.set(*dst, lane, v); + } + } + Op::Move { dst, src } => { + let typed = match f.kind(*dst) == f.kind(*src) { + true => active & f.typed(*src), + false => f.none(), + }; + if typed.any() { + f.copy_typed(*dst, *src, typed); + } + for lane in Lanes::of(active & !typed) { + let v = f.value(*src, lane); + f.set(*dst, lane, v); + } + } + Op::EqConst { + dst, + a, + value, + id, + not, + } => { + let d = *dst as usize; + let mut word = f.none(); + let mut slow = active; + if let (Kind::Bool, Const::Bool(k)) = (f.kind(*a), value) { + let r = *a as usize; + let bits = if *k { f.bits[r] } else { !f.bits[r] }; + word = active & !f.boxed[r] & bits; + slow = active & f.boxed[r]; + } + if let (Kind::Str, Const::String(k)) = (f.kind(*a), value) { + let fast = active & !f.boxed[*a as usize]; + word = Self::eq_text(f, *a, k.as_bytes(), fast); + slow = active & f.boxed[*a as usize]; + } + if let (Kind::Num, Const::Number(k)) = (f.kind(*a), value) { + let fast = active & !f.boxed[*a as usize]; + let (done, hits) = Self::scaled_cmp( + NumCmp::Equal, + Operand::Reg(*a), + Operand::Num(*k), + fast, + f, + ); + word |= hits; + for lane in Lanes::of(fast & !done) { + if Ops::same_number(&f.number(*a, lane), k) { + word.set(lane); + } + } + slow = active & f.boxed[*a as usize]; + } + if slow.any() { + let k = f.consts[*id as usize].clone(); + for lane in Lanes::of(slow) { + if f.with(*a, lane, |v| Ops::equal(v, &k)) { + word.set(lane); + } + } + } + let word = if *not { !word & active } else { word }; + f.bits[d] = (f.bits[d] & !active) | word; + f.boxed[d] &= !active; + } + Op::InRange { + dst, + a, + lo, + hi, + left, + right, + } => { + let interval = Interval { + left_bracket: *left, + right_bracket: *right, + left: IntervalData::Number(*lo), + right: IntervalData::Number(*hi), + }; + let includes = |n: Decimal| { + interval + .includes(IntervalData::Number(n)) + .map_err(|err| Ops::error("In", err.to_string())) + }; + let d = *dst as usize; + let typed = match f.kind(*a) { + Kind::Num => active & !f.boxed[*a as usize], + _ => f.none(), + }; + let (done, mut word) = Self::within(*a, *lo, *hi, *left, *right, typed, f); + for lane in Lanes::of(typed & !done) { + match includes(f.number(*a, lane)) { + Ok(h) => word.put(lane, h), + Err(e) => f.fail(lane, e), + } + } + let mut generic = None; + for lane in Lanes::of(active & !typed) { + let r = match f.take(*a, lane) { + Variable::Number(n) => includes(n), + x => match generic.get_or_insert_with(|| { + Ops::interval( + &Variable::Number(*lo), + &Variable::Number(*hi), + *left, + *right, + ) + }) { + Ok(range) => Ops::membership(x, range), + Err(e) => Err(e.clone()), + }, + }; + match r { + Ok(h) => word.put(lane, h), + Err(e) => f.fail(lane, e), + } + } + f.bits[d] = (f.bits[d] & !active) | (word & active); + f.boxed[d] &= !active; + } + Op::EqAny { dst, a, id } => { + let d = *dst as usize; + let (done, mut word) = Self::any_number(*a, *id, active, f); + if let Variable::Array(list) = &f.consts[*id as usize] { + let list = list.borrow(); + for lane in Lanes::of(active & !done) { + let hit = f.with(*a, lane, |x| list.iter().any(|k| Ops::equal(x, k))); + word.put(lane, hit); + } + } + f.bits[d] = (f.bits[d] & !active) | word; + f.boxed[d] &= !active; + } + Op::InConst { dst, a, id } => { + let (done, word) = Self::any_number(*a, *id, active, f); + let d = *dst as usize; + f.bits[d] = (f.bits[d] & !done) | word; + f.boxed[d] &= !done; + for lane in Lanes::of(active & !done) { + let x = f.take(*a, lane); + let r = Ops::membership(x, &f.consts[*id as usize]).map(Variable::Bool); + f.put(*dst, lane, r); + } + } + Op::RootEnv { dst } => { + for lane in Lanes::of(active) { + let v = ctx.envs.get(f.rows[lane]).materialize(); + f.set(*dst, lane, v); + } + } + Op::Fetch { dst, a, b } => { + for lane in Lanes::of(active) { + let r = Ops::fetch(f.take(*a, lane), f.take(*b, lane)); + f.put(*dst, lane, r); + } + } + Op::Negate { dst, a } => Self::negate(*dst, *a, active, f), + Op::Binary { + dst, + op: Binary::Compare(c), + a, + b, + } => { + for lane in Lanes::of(active) { + let (x, y) = (f.take(*a, lane), f.take(*b, lane)); + match Ops::compared(&x, &y, *c) { + Some(hit) => f.set(*dst, lane, Variable::Bool(hit)), + None => f.fault(lane, Fault::Unsupported("Compare")), + } + } + } + Op::Binary { + dst, + op: Binary::Equal, + a, + b, + } => { + let (mut word, mut done) = (f.none(), f.none()); + for lane in Lanes::of(active) { + if let Some(hit) = Self::equal_lane(f, *a, *b, lane) { + word.put(lane, hit); + done.set(lane); + } + } + match f.kind(*dst) { + Kind::Bool => { + let d = *dst as usize; + f.bits[d] = (f.bits[d] & !done) | word; + f.boxed[d] &= !done; + } + _ => { + for lane in Lanes::of(done) { + f.set(*dst, lane, Variable::Bool(word.get(lane))); + } + } + } + for lane in Lanes::of(active & !done) { + let (x, y) = (f.take(*a, lane), f.take(*b, lane)); + f.put(*dst, lane, Ok(Variable::Bool(Ops::equal(&x, &y)))); + } + } + Op::Binary { dst, op, a, b } => { + let unsupported = match op { + Binary::Subtract => Some("Subtract"), + Binary::Multiply => Some("Multiply"), + Binary::Divide => Some("Divide"), + Binary::Modulo => Some("Modulo"), + _ => None, + }; + for lane in Lanes::of(active) { + let (x, y) = (f.take(*a, lane), f.take(*b, lane)); + if let (false, Some(opcode)) = ( + matches!((&x, &y), (Variable::Number(_), Variable::Number(_))), + unsupported, + ) { + f.fault(lane, Fault::Unsupported(opcode)); + continue; + } + let r = match op { + Binary::Add => Ops::add(x, y), + Binary::Subtract => Ops::subtract(x, y), + Binary::Multiply => Ops::multiply(x, y), + Binary::Divide => Ops::divide(x, y), + Binary::Modulo => Ops::modulo(x, y), + Binary::Exponent => Ops::exponent(x, y), + Binary::Equal => Ok(Variable::Bool(Ops::equal(&x, &y))), + Binary::In => Ops::membership(x, &y).map(Variable::Bool), + Binary::Compare(c) => Ops::compare(&x, &y, *c).map(Variable::Bool), + }; + f.put(*dst, lane, r); + } + } + Op::Interval { + dst, + a, + b, + left, + right, + } => { + for lane in Lanes::of(active) { + let r = Ops::interval(&f.value(*a, lane), &f.value(*b, lane), *left, *right); + f.put(*dst, lane, r); + } + } + Op::Slice { dst, a, to, from } => { + for lane in Lanes::of(active) { + let r = Ops::slice(f.take(*a, lane), f.take(*to, lane), f.take(*from, lane)); + f.put(*dst, lane, r); + } + } + Op::Len { dst, a } => { + for lane in Lanes::of(active) { + let r = f.with(*a, lane, Ops::len); + f.put(*dst, lane, r); + } + } + Op::Array { dst, items } => { + for lane in Lanes::of(active) { + let arr = items.iter().map(|r| f.take(*r, lane)).collect(); + f.set(*dst, lane, Variable::from_array(arr)); + } + } + Op::Object { dst, pairs } if Self::static_object(*dst, pairs, active, f) => {} + Op::Object { dst, pairs } => { + for lane in Lanes::of(active) { + let mut map = crate::variable::VariableMap::with_capacity(pairs.len()); + let mut failed = None; + for (k, v) in pairs.iter().rev() { + let key = match k { + ObjectKey::Static(k) => Ok(Symbol::from(k.as_ref())), + ObjectKey::Reg(k) => Ops::object_key(f.take(*k, lane)), + }; + match key { + Ok(key) => { + map.insert(key, f.take(*v, lane)); + } + Err(e) => { + failed = Some(e); + break; + } + } + } + match failed { + Some(e) => f.fail(lane, e), + None => f.set(*dst, lane, Variable::from_object(map)), + } + } + } + Op::Join { dst, parts } => Self::join(*dst, parts, active, f), + Op::Extreme { + dst, + items, + largest, + } => Self::extreme(*dst, items, *largest, active, f), + Op::Concat { dst, a, b } => { + let typed = match f.kind(*dst) { + Kind::Str => active & !f.boxed[*a as usize] & !f.boxed[*b as usize], + _ => f.none(), + }; + let (ba, bb, bd) = ( + *a as usize * f.width, + *b as usize * f.width, + *dst as usize * f.width, + ); + let mut text = std::mem::take(&mut f.text); + text.clear(); + let origin = f.arena.len() as u32; + let (arena, spans) = (f.arena.as_str(), &mut f.spans); + for lane in Lanes::of(typed) { + let before = text.len() as u32; + for (x, y) in [spans[ba + lane], spans[bb + lane]] { + text.push_str(arena.get(x as usize..y as usize).unwrap_or_default()); + } + spans[bd + lane] = (origin + before, origin + text.len() as u32); + } + f.arena.push_str(&text); + f.text = text; + f.boxed[*dst as usize] &= !typed; + for lane in Lanes::of(active & !typed) { + let r = Ops::add(f.take(*a, lane), f.take(*b, lane)); + f.put(*dst, lane, r); + } + } + Op::Call { + dst, + kind: FunctionKind::Internal(InternalFunction::String), + args, + } if matches!(**args, [Input::Reg(a)] if matches!(f.kind(a), Kind::Str | Kind::Num)) + && f.kind(*dst) == Kind::Str => + { + let [Input::Reg(a)] = **args else { return }; + let typed = match f.kind(a) { + Kind::Str => { + let typed = active & f.typed(a); + f.copy_typed(*dst, a, typed); + typed + } + _ => { + let typed = active & !f.boxed[a as usize] & !f.wide[a as usize]; + let (ba, bd) = (a as usize * f.width, *dst as usize * f.width); + for lane in Lanes::of(typed) { + let start = f.arena.len() as u32; + Scaled::write(f.mant[ba + lane], f.scales[ba + lane], &mut f.arena); + f.spans[bd + lane] = (start, f.arena.len() as u32); + } + f.boxed[*dst as usize] &= !typed; + typed + } + }; + let kind = FunctionKind::Internal(InternalFunction::String); + let Some(builtin) = Builtins::of(&kind) else { + return; + }; + let mut null = None; + for lane in Lanes::of(active & !typed) { + if f.with(a, lane, |value| matches!(value, Variable::Null)) { + let r = null + .get_or_insert_with(|| Builtins::call(builtin, &kind, &[Arg::Null])) + .clone(); + f.write(*dst, lane, r); + continue; + } + let r = { + let value = f.arg_view(a, lane); + Builtins::call(builtin, &kind, &[value]) + }; + f.write(*dst, lane, r); + } + } + Op::Call { dst, kind, args } => { + let Some(builtin) = Builtins::of(kind) else { + let e = Ops::error("CallFunction", format!("Function `{kind}` not found")); + for lane in Lanes::of(active) { + f.fail(lane, e.clone()); + } + return; + }; + let mut done = Self::text_call(*dst, kind, args, active, f); + if done.is_empty() { + done = Self::number_call(*dst, kind, args, active, f) + | Self::list_call(*dst, kind, args, active, f) + | Self::date_call(*dst, kind, args, active, f); + } + done |= Self::member_call(*dst, kind, args, active & !done, f); + done |= Self::length_call(*dst, kind, args, active & !done, f); + done |= Self::identity_call(*dst, kind, args, active & !done, f); + done |= Self::boxed_call(*dst, kind, args, active & !done, f); + let mut hint = 0usize; + let rest = active & !done; + if rest.any() && args.iter().all(|a| matches!(a, Input::Const(_))) { + let result = { + let values: smallvec::SmallVec<[Arg; 4]> = args + .iter() + .filter_map(|a| match *a { + Input::Const(id) => Some(Arg::of(&f.consts[id as usize])), + Input::Reg(_) => None, + }) + .collect(); + Builtins::call_hinted(builtin, kind, &values, &mut hint) + }; + for lane in Lanes::of(rest) { + let copy = match &result { + Ok(Out::Var(value @ (Variable::Array(_) | Variable::Object(_)))) => { + Ok(Out::Var(value.deep_clone())) + } + other => other.clone(), + }; + f.write_call(*dst, lane, copy); + } + return; + } + f.box_lists(args, active & !done); + for lane in Lanes::of(active & !done) { + let result = { + let values: smallvec::SmallVec<[Arg; 4]> = args + .iter() + .map(|a| match *a { + Input::Const(id) => Arg::of(&f.consts[id as usize]), + Input::Reg(r) => f.arg_view(r, lane), + }) + .collect(); + Builtins::call_hinted(builtin, kind, &values, &mut hint) + }; + f.write_call(*dst, lane, result); + } + } + Op::Method { dst, kind, args } => { + let builtin = Builtins::method(kind); + f.box_lists(args, active); + let done = Self::date_method(*dst, kind, args, active, f); + for lane in Lanes::of(active & !done) { + let result = { + let values: smallvec::SmallVec<[Arg; 4]> = args + .iter() + .map(|a| match *a { + Input::Const(id) => Arg::of(&f.consts[id as usize]), + Input::Reg(r) => f.arg_view(r, lane), + }) + .collect(); + Builtins::call_method(builtin, kind, &values) + }; + f.write(*dst, lane, result); + } + } + Op::AssignBegin { dst } => { + for lane in Lanes::of(active) { + f.set(*dst, lane, Variable::empty_object()); + } + } + Op::AssignStep { object, key, value } => { + for lane in Lanes::of(active) { + let key = match Ops::assigned_key(f.take(*key, lane)) { + Ok(k) => k, + Err(e) => { + f.fail(lane, e); + continue; + } + }; + let (obj, val) = (f.value(*object, lane), f.take(*value, lane)); + let r = match ctx.envs.get_mut(f.rows[lane]) { + Some(env) => Ops::assign(env, &obj, &key, val), + None => Err(Ops::error( + "AssignedObjectStep", + "Failed to mutate existing env", + )), + }; + if let Err(e) = r { + f.fail(lane, e); + } + } + } + Op::Closure(closure) => Self::closure(closure, active, f, rest, ctx), + Op::Rewind => { + for lane in Lanes::of(active) { + let row = f.rows[lane]; + let root = ctx.roots.get(row).clone(); + if let Some(env) = ctx.envs.get_mut(row) { + *env = root; + } + } + } + Op::DollarInsert { key, value } => { + for lane in Lanes::of(active) { + let row = f.rows[lane]; + let v = f.value(*value, lane); + let Some(root) = ctx.roots.get_mut(row) else { + continue; + }; + let dollar = match root.local(&Variable::dollar_key()) { + Some(existing @ Variable::Object(_)) => existing.shallow_clone(), + _ => { + let created = Variable::empty_object(); + root.set_local(Variable::dollar_key(), created.clone()); + created + } + }; + let _ = dollar.dot_insert(key, v); + if let Some(env) = ctx.envs.get_mut(row) { + env.set_local(Variable::dollar_key(), dollar); + } + } + } + Op::Fail { error } => { + for lane in Lanes::of(active) { + f.fail(lane, error.clone()); + } + } + _ => {} + } + } +} diff --git a/core/expression/src/lane/exec/number.rs b/core/expression/src/lane/exec/number.rs new file mode 100644 index 00000000..e69ba5e9 --- /dev/null +++ b/core/expression/src/lane/exec/number.rs @@ -0,0 +1,782 @@ +use super::frame::Fault; +use super::frame::{Buffers, Frame}; +use super::Executor; +use crate::compiler::Compare; +use crate::functions::{FunctionKind, InternalFunction}; +use crate::lane::builtins::{Arg, Builtins, Out}; +use crate::lane::columns::{Column, Values}; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +use crate::lane::program::{Input, Kind, NumCmp, NumOp, Operand, Reg}; +use crate::lane::scaled::{Kernel, Scaled}; +use crate::lexer::Bracket; +use crate::variable::Variable; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; + +impl Executor { + pub(super) fn reducer(kind: &FunctionKind) -> Option { + match kind { + FunctionKind::Internal( + function @ (InternalFunction::Sum + | InternalFunction::Avg + | InternalFunction::Min + | InternalFunction::Max), + ) => Some(*function), + _ => None, + } + } + + pub(super) fn reduce( + function: InternalFunction, + mut values: impl Iterator>, + ) -> Option { + let first = values.next()??; + let (mut acc, mut len) = (first, 1usize); + if matches!(function, InternalFunction::Sum | InternalFunction::Avg) { + acc = Scaled::add((0, 0), first, false)?; + } + for value in values { + let x = value?; + len += 1; + acc = match function { + InternalFunction::Sum | InternalFunction::Avg => Scaled::add(acc, x, false)?, + InternalFunction::Max if Scaled::compare(x, acc)?.is_ge() => x, + InternalFunction::Min if Scaled::compare(x, acc)?.is_lt() => x, + _ => acc, + }; + } + let total = Scaled::decimal(acc.0, acc.1); + Some(Out::Num(match function { + InternalFunction::Avg => total.checked_div(Decimal::from(len))?, + _ => total, + })) + } + + pub(super) fn reduce_items( + function: InternalFunction, + numbers: Option<(&[i64], &[u8])>, + ) -> Option<(i64, u8)> { + let (mant, scales) = numbers?; + let scale = *scales.first()?; + let uniform = scales.iter().all(|s| *s == scale); + match function { + InternalFunction::Sum if uniform => match Self::reduce_ints(function, mant)? { + 0 if scale > 0 => None, + total => Some((total, scale)), + }, + InternalFunction::Min | InternalFunction::Max if uniform => { + Some((Self::reduce_ints(function, mant)?, scale)) + } + _ => None, + } + } + + pub(super) fn reduce_ints(function: InternalFunction, items: &[i64]) -> Option { + let first = *items.first()?; + match function { + InternalFunction::Min => Some(items.iter().copied().fold(first, i64::min)), + InternalFunction::Max => Some(items.iter().copied().fold(first, i64::max)), + _ => i64::try_from(items.iter().map(|x| *x as i128).sum::()).ok(), + } + } + + pub(super) fn reduce_scaled( + function: InternalFunction, + mant: &[i64], + scale: &[u8], + ) -> Option<(i64, u8)> { + let (&first, &unit) = (mant.first()?, scale.first()?); + if scale.iter().any(|s| *s != unit) { + return None; + } + match function { + InternalFunction::Min => Some((mant.iter().copied().fold(first, i64::min), unit)), + InternalFunction::Max => Some((mant.iter().copied().fold(first, i64::max), unit)), + _ => i64::try_from(mant.iter().map(|x| *x as i128).sum::()) + .ok() + .map(|n| (n, unit)), + } + } + + pub(super) fn child_number(child: &Column, index: usize) -> Option<(i64, u8)> { + match (child.values, child.valid(index)) { + (Values::I64(v), true) => v.get(index).map(|n| (*n, 0)), + (Values::Dec(v), true) => v.get(index).and_then(Scaled::parts), + (Values::Scaled { mant, scale }, true) => Some((*mant.get(index)?, *scale.get(index)?)), + _ => None, + } + } + + pub(super) fn list_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let (Some(function), [Input::Reg(a)]) = (Self::reducer(kind), args) else { + return f.none(); + }; + if f.kind(*a) != Kind::List { + return f.none(); + } + let mut done = f.none(); + for lane in Lanes::of(active & !f.boxed[*a as usize]) { + let (x, y) = f.lists[f.at(*a, lane)]; + if let Some((v, scale)) = + Self::reduce_items(function, f.items.numbers(x as usize, y as usize)) + { + match f.kind(dst) { + Kind::Num => { + f.put_scaled(dst, lane, v, scale); + } + _ => f.write(dst, lane, Ok(Out::Num(Scaled::decimal(v, scale)))), + } + done.set(lane); + continue; + } + let values = (x as usize..y as usize).map(|i| f.items.number(i)); + if let Some(out) = Self::reduce(function, values) { + f.write(dst, lane, Ok(out)); + done.set(lane); + } + } + done + } + + pub(super) fn number_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let FunctionKind::Internal(function) = kind else { + return f.none(); + }; + let (a, places) = match args { + [Input::Reg(a)] => (*a, None), + [Input::Reg(a), Input::Const(id)] => match &f.consts[*id as usize] { + Variable::Number(n) => match n.to_u32().filter(|p| *p <= 28) { + Some(p) => (*a, Some(p as u8)), + None => return f.none(), + }, + _ => return f.none(), + }, + _ => return f.none(), + }; + let op: fn(i64, u8, u8) -> Option<(i64, u8)> = match (function, places) { + (InternalFunction::Abs, None) => |m, s, _| Scaled::abs(m, s), + (InternalFunction::Floor, None) => |m, s, _| Scaled::floor(m, s), + (InternalFunction::Ceil, None) => |m, s, _| Scaled::ceil(m, s), + (InternalFunction::Round, _) => Scaled::round, + (InternalFunction::Trunc, _) => Scaled::trunc, + _ => return f.none(), + }; + if f.kind(a) != Kind::Num || f.kind(dst) != Kind::Num { + return f.none(); + } + let places = places.unwrap_or(0); + let lanes = active & !f.boxed[a as usize] & !f.wide[a as usize]; + let (from, base) = (a as usize * f.width, dst as usize * f.width); + let mut done = f.none(); + for lane in Lanes::of(lanes) { + if let Some((m, s)) = op(f.mant[from + lane], f.scales[from + lane], places) { + f.mant[base + lane] = m; + f.scales[base + lane] = s; + done.set(lane); + } + } + f.wide[dst as usize] &= !done; + f.boxed[dst as usize] &= !done; + done + } + + #[inline(never)] + pub(super) fn scaled_num( + op: NumOp, + dst: Reg, + a: Operand, + b: Operand, + lanes: M, + f: &mut Frame, + ) -> M { + let ok = lanes & !f.operand_wide(a) & !f.operand_wide(b); + if ok.is_empty() { + return f.none(); + } + let width = f.width; + let mut buffers = std::mem::take(&mut f.buffers); + let Buffers { + m, + s, + ka, + sa, + kb, + sb, + } = &mut buffers; + if m.len() < width { + m.resize(width, 0); + s.resize(width, 0); + } + let (m, s) = (&mut m[..width], &mut s[..width]); + let mut done = f.none(); + if let (Some((xa, ya)), Some((xb, yb))) = (f.side(a, ka, sa), f.side(b, kb, sb)) { + let uniform = (ok == M::all(width)) + .then(|| Frame::::uniform(ya, ok).zip(Frame::::uniform(yb, ok))) + .flatten(); + let vector = match (uniform, op, ok == M::all(width)) { + (Some((x, y)), NumOp::Multiply, _) => !Kernel::multiply((xa, x), (xb, y), m, s), + (Some((x, y)), NumOp::Subtract, _) => !Kernel::add((xa, x), (xb, y), true, m, s), + (Some((x, y)), _, _) => !Kernel::add((xa, x), (xb, y), false, m, s), + (None, NumOp::Multiply, true) => !Kernel::multiply_mixed((xa, ya), (xb, yb), m, s), + (None, NumOp::Add | NumOp::Subtract, true) => { + !Kernel::add_mixed((xa, ya), (xb, yb), op == NumOp::Subtract, m, s) + } + _ => false, + }; + done = match vector { + true => ok, + false => { + let mut done = f.none(); + for lane in Lanes::of(ok) { + let (x, y) = ((xa[lane], ya[lane]), (xb[lane], yb[lane])); + if let Some((mm, sc)) = op.scaled(x, y) { + m[lane] = mm; + s[lane] = sc; + done.set(lane); + } + } + done + } + }; + } + let base = dst as usize * width; + match done == M::all(width) { + true => { + f.mant[base..base + width].copy_from_slice(m); + f.scales[base..base + width].copy_from_slice(s); + } + false => { + for lane in Lanes::of(done) { + f.mant[base + lane] = m[lane]; + f.scales[base + lane] = s[lane]; + } + } + } + f.wide[dst as usize] &= !done; + f.buffers = buffers; + done + } + + const NARROW: usize = 8; + + #[inline] + pub(super) fn scaled_at( + o: Operand, + lane: usize, + f: &Frame, + ) -> Option<(i64, u8)> { + match o { + Operand::Num(n) => Scaled::parts(&n), + Operand::Reg(r) => { + let at = f.at(r, lane); + (!f.wide[r as usize].get(lane)).then(|| (f.mant[at], f.scales[at])) + } + } + } + + pub(super) fn extreme( + dst: Reg, + items: &[Operand], + largest: bool, + active: M, + f: &mut Frame, + ) { + let mut slow = f.none(); + for lane in Lanes::of(active) { + let mut best: Option<(i64, u8)> = None; + let mut ok = true; + for o in items { + let boxed = matches!(o, Operand::Reg(r) if f.boxed[*r as usize].get(lane)); + let Some(x) = Self::scaled_at(*o, lane, f).filter(|_| !boxed) else { + ok = false; + break; + }; + best = match best.map(|b| Scaled::compare(x, b).map(|o| (b, o))) { + None => Some(x), + Some(None) => { + ok = false; + break; + } + Some(Some((b, order))) => match largest { + true => Some(if order.is_ge() { x } else { b }), + false => Some(if order.is_lt() { x } else { b }), + }, + }; + } + match (ok, best) { + (true, Some((m, s))) => { + f.put_scaled(dst, lane, m, s); + } + _ => slow.set(lane), + } + } + if slow.is_empty() { + return; + } + let kind = FunctionKind::Internal(if largest { + InternalFunction::Max + } else { + InternalFunction::Min + }); + let Some(builtin) = Builtins::of(&kind) else { + return; + }; + for lane in Lanes::of(slow) { + let values: Vec = items + .iter() + .map(|o| match o { + Operand::Num(n) => Variable::Number(*n), + Operand::Reg(r) => f.value(*r, lane), + }) + .collect(); + let array = Variable::from_array(values); + let r = Builtins::call(builtin, &kind, &[Arg::of(&array)]); + f.write(dst, lane, r); + } + } + + pub(super) fn lane_num( + op: NumOp, + dst: Reg, + a: Operand, + b: Operand, + lanes: M, + f: &mut Frame, + ) -> M { + let mut done = f.none(); + for lane in Lanes::of(lanes) { + let (Some(x), Some(y)) = (Self::scaled_at(a, lane, f), Self::scaled_at(b, lane, f)) + else { + continue; + }; + if let Some((m, s)) = op.scaled(x, y) { + f.put_scaled(dst, lane, m, s); + done.set(lane); + } + } + done + } + + pub(super) fn divide_const( + dst: Reg, + a: Operand, + divisor: Decimal, + lanes: M, + f: &mut Frame, + ) -> M { + let Some(parts) = Scaled::parts(&divisor) else { + return Self::lane_num(NumOp::Divide, dst, a, Operand::Num(divisor), lanes, f); + }; + let power = Scaled::power(parts); + let width = f.width; + if let (Some(k), Operand::Reg(r)) = (power, a) { + let source = r as usize; + if lanes == M::all(width) + && (f.wide[source] & lanes).is_empty() + && f.kinds[source] == Kind::Num + { + let (from, to) = (source * width, dst as usize * width); + if from != to { + f.mant.copy_within(from..from + width, to); + f.scales.copy_within(from..from + width, to); + } + let mut failed = f.none(); + let (mant, scales) = (&mut f.mant[to..to + width], &mut f.scales[to..to + width]); + for (chunk, (mant, scales)) in + mant.chunks_mut(64).zip(scales.chunks_mut(64)).enumerate() + { + let mut bits = 0u64; + for (i, (m, s)) in mant.iter_mut().zip(scales.iter_mut()).enumerate() { + match Scaled::divide_power((*m, *s), k, parts.1) { + Some((q, scale)) => { + *m = q; + *s = scale; + } + None => bits |= 1 << i, + } + } + failed.set_word(chunk, bits); + } + let done = lanes & !failed; + f.wide[dst as usize] &= !done; + f.boxed[dst as usize] &= !done; + return done; + } + } + let mut done = f.none(); + for lane in Lanes::of(lanes) { + let Some(x) = Self::scaled_at(a, lane, f) else { + continue; + }; + let result = match power { + Some(k) => Scaled::divide_power(x, k, parts.1), + None => Scaled::divide(x, parts), + }; + if let Some((m, s)) = result { + f.put_scaled(dst, lane, m, s); + done.set(lane); + } + } + done + } + + pub(super) fn lane_cmp( + op: NumCmp, + a: Operand, + b: Operand, + lanes: M, + f: &Frame, + ) -> (M, M) { + let (mut done, mut word) = (f.none(), f.none()); + for lane in Lanes::of(lanes) { + let (Some(x), Some(y)) = (Self::scaled_at(a, lane, f), Self::scaled_at(b, lane, f)) + else { + continue; + }; + if let Some(o) = Scaled::compare(x, y) { + word.put(lane, op.test(o)); + done.set(lane); + } + } + (done, word) + } + + pub(super) fn num( + op: NumOp, + dst: Reg, + a: Operand, + b: Operand, + active: M, + f: &mut Frame, + ) { + let slow = active & (f.operand_boxed(a) | f.operand_boxed(b)); + let fast = active & !slow; + let d = dst as usize; + f.boxed[d] &= !fast; + let done = match (op, f.width < Self::NARROW, b) { + (NumOp::Add | NumOp::Subtract | NumOp::Multiply, false, _) => { + Self::scaled_num(op, dst, a, b, fast, f) + } + (NumOp::Divide, _, Operand::Num(n)) => Self::divide_const(dst, a, n, fast, f), + _ => Self::lane_num(op, dst, a, b, fast, f), + }; + for lane in Lanes::of(fast & !done) { + let (x, y) = (f.num(a, lane), f.num(b, lane)); + let r = match op { + NumOp::Add => x.checked_add(y).ok_or("Add"), + NumOp::Subtract => x.checked_sub(y).ok_or("Subtract"), + NumOp::Multiply => x.checked_mul(y).ok_or("Multiply"), + NumOp::Divide => x.checked_div(y).ok_or(""), + NumOp::Modulo => x.checked_rem(y).ok_or(""), + }; + match r { + Ok(v) => f.put_number(dst, lane, v), + Err("") => f.set(dst, lane, Variable::Null), + Err(name) => f.fail(lane, Ops::error(name, "Number overflow")), + } + } + for lane in Lanes::of(slow) { + let (x, y) = (f.operand_value(a, lane), f.operand_value(b, lane)); + let numeric = matches!((&x, &y), (Variable::Number(_), Variable::Number(_))); + let unsupported = match op { + NumOp::Add => None, + NumOp::Subtract => Some("Subtract"), + NumOp::Multiply => Some("Multiply"), + NumOp::Divide => Some("Divide"), + NumOp::Modulo => Some("Modulo"), + }; + if let (false, Some(opcode)) = (numeric, unsupported) { + f.fault(lane, Fault::Unsupported(opcode)); + continue; + } + let r = match op { + NumOp::Add => Ops::add(x, y), + NumOp::Subtract => Ops::subtract(x, y), + NumOp::Multiply => Ops::multiply(x, y), + NumOp::Divide => Ops::divide(x, y), + NumOp::Modulo => Ops::modulo(x, y), + }; + f.put(dst, lane, r); + } + } + + fn constant_cmp( + op: NumCmp, + a: Operand, + b: Operand, + ok: M, + f: &Frame, + ) -> Option { + let (reg, n, op) = match (a, b) { + (Operand::Reg(r), Operand::Num(n)) => (r, n, op), + (Operand::Num(n), Operand::Reg(r)) => (r, n, op.mirrored()), + _ => return None, + }; + let base = reg as usize * f.width; + let values = f.mant.get(base..base + f.width)?; + let scale = Frame::::uniform(f.scales.get(base..base + f.width)?, ok)?; + let (k, s) = Scaled::parts(&n)?; + match Threshold::of(op, scale, k, s)? { + Threshold::At(op, k) => Some(Kernel::threshold::(values, k, |o| op.test(o))), + Threshold::Never => Some(f.none()), + } + } + + pub(super) fn negate(dst: Reg, a: Reg, active: M, f: &mut Frame) { + let typed = match (f.kind(a), f.kind(dst)) { + (Kind::Num, Kind::Num) => active & !f.boxed[a as usize], + _ => f.none(), + }; + let wide = f.wide[a as usize]; + let sb = a as usize * f.width; + for lane in Lanes::of(typed) { + let (m, s) = (f.mant[sb + lane], f.scales[sb + lane]); + match (wide.get(lane), m) { + (false, m) if m != 0 && m != i64::MIN => f.put_scaled(dst, lane, -m, s), + (false, m) => f.put_number(dst, lane, -Scaled::decimal(m, s)), + (true, _) => { + let n = f.nums[sb + lane]; + f.put_number(dst, lane, -n); + } + } + } + f.boxed[dst as usize] &= !typed; + for lane in Lanes::of(active & !typed) { + let r = Ops::negate(f.take(a, lane)); + f.put(dst, lane, r); + } + } + + pub(super) fn scaled_cmp( + op: NumCmp, + a: Operand, + b: Operand, + lanes: M, + f: &mut Frame, + ) -> (M, M) { + let ok = lanes & !f.operand_wide(a) & !f.operand_wide(b); + if ok.is_empty() { + return (f.none(), f.none()); + } + if let Some(word) = Self::constant_cmp(op, a, b, ok, f) { + return (ok, word & ok); + } + let mut buffers = std::mem::take(&mut f.buffers); + let Buffers { ka, sa, kb, sb, .. } = &mut buffers; + let mut out = (f.none(), f.none()); + if let (Some((xa, ya)), Some((xb, yb))) = (f.side(a, ka, sa), f.side(b, kb, sb)) { + let vector = Frame::::uniform(ya, ok) + .zip(Frame::::uniform(yb, ok)) + .and_then(|(x, y)| Kernel::compare::((xa, x), (xb, y), |o| op.test(o))); + out = match vector { + Some(word) => (ok, word & ok), + None => { + let (mut done, mut word) = (f.none(), f.none()); + for lane in Lanes::of(ok) { + if let Some(o) = Scaled::compare((xa[lane], ya[lane]), (xb[lane], yb[lane])) + { + word.put(lane, op.test(o)); + done.set(lane); + } + } + (done, word) + } + }; + } + f.buffers = buffers; + out + } + + pub(super) fn any_number(a: Reg, id: u32, active: M, f: &mut Frame) -> (M, M) { + let lanes = match (f.kind(a), &f.consts[id as usize]) { + (Kind::Num | Kind::Str, Variable::Array(_)) => active & !f.boxed[a as usize], + _ => return (f.none(), f.none()), + }; + if f.kind(a) == Kind::Str { + let Variable::Array(list) = &f.consts[id as usize] else { + return (f.none(), f.none()); + }; + let list = list.borrow(); + let texts: smallvec::SmallVec<[&str; 8]> = + list.iter().filter_map(Variable::as_str).collect(); + let mut word = f.none(); + for lane in Lanes::of(lanes) { + let x = f.text_at(a, lane); + word.put(lane, texts.contains(&x)); + } + return (lanes, word); + } + let numbers: smallvec::SmallVec<[Decimal; 8]> = match &f.consts[id as usize] { + Variable::Array(list) => list + .borrow() + .iter() + .filter_map(Variable::as_number) + .collect(), + _ => return (f.none(), f.none()), + }; + let (mut done, mut word) = (lanes, f.none()); + for k in numbers { + let (d, w) = + Self::scaled_cmp(NumCmp::Equal, Operand::Reg(a), Operand::Num(k), lanes, f); + done &= d; + word |= w; + } + (done, word & done) + } + + pub(super) fn within( + a: Reg, + lo: Decimal, + hi: Decimal, + left: Bracket, + right: Bracket, + lanes: M, + f: &mut Frame, + ) -> (M, M) { + let order = |k: Decimal, f: &mut Frame| { + let (d1, less) = Self::scaled_cmp( + NumCmp::Order(Compare::Less), + Operand::Reg(a), + Operand::Num(k), + lanes, + f, + ); + let (d2, equal) = + Self::scaled_cmp(NumCmp::Equal, Operand::Reg(a), Operand::Num(k), lanes, f); + (d1 & d2, less, equal) + }; + let (d1, lt_lo, eq_lo) = order(lo, f); + let (d2, lt_hi, eq_hi) = order(hi, f); + let done = d1 & d2; + let (gt_lo, gt_hi) = (!lt_lo & !eq_lo, !lt_hi & !eq_hi); + let (first, open) = match left { + Bracket::LeftParenthesis => (gt_lo, false), + Bracket::LeftSquareBracket => (gt_lo | eq_lo, false), + Bracket::RightParenthesis => (lt_lo, true), + Bracket::RightSquareBracket => (lt_lo | eq_lo, true), + _ => return (f.none(), f.none()), + }; + let second = match right { + Bracket::RightParenthesis => lt_hi, + Bracket::RightSquareBracket => lt_hi | eq_hi, + Bracket::LeftParenthesis => gt_hi, + Bracket::LeftSquareBracket => gt_hi | eq_hi, + _ => return (f.none(), f.none()), + }; + let word = match open { + true => first | second, + false => first & second, + }; + (done, word & done) + } + + #[inline(never)] + pub(super) fn cmp( + op: NumCmp, + dst: Reg, + a: Operand, + b: Operand, + active: M, + f: &mut Frame, + ) { + let slow = active & (f.operand_boxed(a) | f.operand_boxed(b)); + let fast = active & !slow; + let d = dst as usize; + let (done, mut word) = match f.width < Self::NARROW { + true => Self::lane_cmp(op, a, b, fast, f), + false => Self::scaled_cmp(op, a, b, fast, f), + }; + for lane in Lanes::of(fast & !done) { + let (x, y) = (f.num(a, lane), f.num(b, lane)); + let hit = match op { + NumCmp::Order(c) => Ops::ordered_number(&x, &y, c), + NumCmp::Equal => Ops::same_number(&x, &y), + }; + word.put(lane, hit); + } + f.put_mask(d as Reg, fast, word); + for lane in Lanes::of(slow) { + let (x, y) = (f.operand_value(a, lane), f.operand_value(b, lane)); + match op { + NumCmp::Order(c) => match Ops::compared(&x, &y, c) { + Some(hit) => f.set(dst, lane, Variable::Bool(hit)), + None => f.fault(lane, Fault::Unsupported("Compare")), + }, + NumCmp::Equal => f.set(dst, lane, Variable::Bool(Ops::equal(&x, &y))), + } + } + } +} + +impl NumOp { + #[inline(always)] + pub(crate) fn scaled(self, x: (i64, u8), y: (i64, u8)) -> Option<(i64, u8)> { + match self { + NumOp::Multiply => Scaled::multiply(x, y), + NumOp::Subtract => Scaled::add(x, y, true), + NumOp::Divide => Scaled::divide(x, y), + NumOp::Modulo => Scaled::remainder(x, y), + NumOp::Add => Scaled::add(x, y, false), + } + } +} + +impl NumCmp { + pub(super) fn mirrored(self) -> Self { + match self { + NumCmp::Order(Compare::More) => NumCmp::Order(Compare::Less), + NumCmp::Order(Compare::Less) => NumCmp::Order(Compare::More), + NumCmp::Order(Compare::MoreOrEqual) => NumCmp::Order(Compare::LessOrEqual), + NumCmp::Order(Compare::LessOrEqual) => NumCmp::Order(Compare::MoreOrEqual), + NumCmp::Equal => NumCmp::Equal, + } + } + + #[inline(always)] + pub(crate) fn test(self, o: std::cmp::Ordering) -> bool { + match self { + NumCmp::Equal => o.is_eq(), + NumCmp::Order(Compare::More) => o.is_gt(), + NumCmp::Order(Compare::MoreOrEqual) => o.is_ge(), + NumCmp::Order(Compare::Less) => o.is_lt(), + NumCmp::Order(Compare::LessOrEqual) => o.is_le(), + } + } +} + +pub(super) enum Threshold { + At(NumCmp, i64), + Never, +} + +impl Threshold { + pub(super) fn of(op: NumCmp, scale: u8, k: i64, s: u8) -> Option { + if s <= scale { + let k = k.checked_mul(*Scaled::POW10.get((scale - s) as usize)?)?; + return Some(Threshold::At(op, k)); + } + let p = *Scaled::POW10.get((s - scale) as usize)?; + let floor = k.div_euclid(p); + let exact = k.rem_euclid(p) == 0; + let ceil = floor + (!exact) as i64; + Some(match op { + NumCmp::Order(Compare::More | Compare::LessOrEqual) => Threshold::At(op, floor), + NumCmp::Order(Compare::MoreOrEqual | Compare::Less) => Threshold::At(op, ceil), + NumCmp::Equal if exact => Threshold::At(op, floor), + NumCmp::Equal => Threshold::Never, + }) + } +} diff --git a/core/expression/src/lane/exec/switch.rs b/core/expression/src/lane/exec/switch.rs new file mode 100644 index 00000000..a62451f6 --- /dev/null +++ b/core/expression/src/lane/exec/switch.rs @@ -0,0 +1,229 @@ +use super::context::Context; +use super::frame::Frame; +use super::Executor; +use crate::lane::columns::Values; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +use crate::lane::program::{Kind, Subject, SwitchOp}; +use crate::lane::scaled::Scaled; +use crate::lane::ShortKey; +use crate::variable::Variable; +use zen_types::symbol::Symbol; + +impl Executor { + pub(super) fn switch(op: &SwitchOp, active: M, f: &mut Frame, ctx: &Context) { + let mut picks = std::mem::take(&mut f.picks); + picks.clear(); + picks.resize(f.width, 0); + let done = match op.subject { + Subject::Site(site) => Self::switch_column(op, site, active, f, ctx, &mut picks), + Subject::Reg(reg) => Self::switch_register(op, reg, active, f, &mut picks), + }; + if done.any() { + Self::switch_write(op, done, f, &picks); + } + f.picks = picks; + if let Subject::Site(_) = op.subject { + f.masks[op.rest as usize] = active & !done; + } + } + + fn switch_column( + op: &SwitchOp, + site: u32, + active: M, + f: &mut Frame, + ctx: &Context, + picks: &mut [u8], + ) -> M { + let fallback = op.cases.len() as u8; + let width = f.width; + let Some(Some(column)) = ctx.column(site) else { + return f.none(); + }; + let text = match column.values { + Values::Utf8 { offsets, data } => Some((offsets, data)), + Values::Text { offsets, data } => Some((offsets, data.as_bytes())), + _ => None, + }; + match (column.values, text) { + (_, Some((offsets, data))) if f.dense => { + let Some(at) = Self::prefixes(f, offsets, data, ctx.base) else { + return f.none(); + }; + let Some(window) = offsets.get(ctx.base..=ctx.base + width) else { + return f.none(); + }; + let keys: Vec<(u32, u64, &[u8])> = op + .cases + .iter() + .map(|case| { + ( + u32::try_from(case.len()).unwrap_or(u32::MAX), + ShortKey::of(case.as_bytes()), + case.as_bytes(), + ) + }) + .collect(); + let valid: M = column.valid_mask(ctx.base, width); + let entry = &f.prefixes[at]; + let long = keys.iter().any(|(_, _, text)| text.len() > 8); + for (lane, ((pick, len), word)) in picks + .iter_mut() + .zip(&entry.lens) + .zip(&entry.words) + .enumerate() + { + let mut chosen = fallback; + for (case, (n, key, _)) in keys.iter().enumerate().rev() { + let hit = (*n == *len) & (*key == *word); + chosen = [chosen, case as u8][hit as usize]; + } + if long && chosen != fallback && keys[chosen as usize].2.len() > 8 { + let text = data.get(window[lane] as usize..window[lane + 1] as usize); + chosen = keys + .iter() + .position(|(_, _, case)| text == Some(*case)) + .map_or(fallback, |at| at as u8); + } + *pick = chosen; + } + for lane in Lanes::of(active & !valid) { + picks[lane] = fallback; + } + active + } + (Values::Dict { keys, values }, _) if values.len() <= 256 => { + let codes: Vec = (0..values.len()) + .map(|code| { + op.cases + .iter() + .position(|case| { + values.equals(code, &Variable::String(Symbol::from(case.as_ref()))) + }) + .map_or(fallback, |at| at as u8) + }) + .collect(); + for lane in Lanes::of(active) { + let row = ctx.base + f.rows[lane] as usize; + picks[lane] = match ( + column.valid(row), + keys.get(row).and_then(|k| usize::try_from(*k).ok()), + ) { + (true, Some(code)) => codes.get(code).copied().unwrap_or(fallback), + _ => fallback, + }; + } + active + } + _ => f.none(), + } + } + + fn switch_register( + op: &SwitchOp, + reg: u32, + active: M, + f: &mut Frame, + picks: &mut [u8], + ) -> M { + let fallback = op.cases.len() as u8; + let typed = match f.kind(reg) { + Kind::Str => active & !f.boxed[reg as usize], + _ => f.none(), + }; + let mut memo = [((u32::MAX, u32::MAX), fallback); 4]; + let base = reg as usize * f.width; + for lane in Lanes::of(typed) { + let span = f.spans[base + lane]; + let slot = (span.0 as usize ^ (span.1 as usize).rotate_left(2)) & 3; + picks[lane] = match memo[slot].0 == span { + true => memo[slot].1, + false => { + let text = f.text_at(reg, lane); + let pick = op + .cases + .iter() + .position(|case| case.as_ref() == text) + .map_or(fallback, |at| at as u8); + memo[slot] = (span, pick); + pick + } + }; + } + let cases: Vec = op + .cases + .iter() + .map(|case| Variable::String(Symbol::from(case.as_ref()))) + .collect(); + for lane in Lanes::of(active & !typed) { + picks[lane] = f + .with(reg, lane, |value| { + cases.iter().position(|case| Ops::equal(value, case)) + }) + .map_or(fallback, |at| at as u8); + } + active + } + + fn switch_write(op: &SwitchOp, lanes: M, f: &mut Frame, picks: &[u8]) { + let (d, width) = (op.dst as usize, f.width); + let base = d * width; + let values: Vec = op + .values + .iter() + .map(|id| f.consts[*id as usize].clone()) + .collect(); + let strings: Option> = values.iter().map(|v| v.as_str()).collect(); + let numbers: Option> = values + .iter() + .map(|v| match v { + Variable::Number(n) => Scaled::parts(n), + _ => None, + }) + .collect(); + let bools: Option> = values.iter().map(Variable::as_bool).collect(); + match (f.kinds[d], strings, numbers, bools) { + (Kind::Str, Some(texts), _, _) => { + let spans: Vec<(u32, u32)> = texts.iter().map(|text| f.intern(text)).collect(); + match lanes == M::all(width) { + true => f.spans[base..base + width] + .iter_mut() + .zip(picks) + .for_each(|(span, pick)| *span = spans[*pick as usize]), + false => Lanes::of(lanes) + .for_each(|lane| f.spans[base + lane] = spans[picks[lane] as usize]), + } + f.boxed[d] &= !lanes; + } + (Kind::Num, _, Some(parts), _) => { + match lanes == M::all(width) { + true => f.mant[base..base + width] + .iter_mut() + .zip(f.scales[base..base + width].iter_mut()) + .zip(picks) + .for_each(|((m, s), pick)| (*m, *s) = parts[*pick as usize]), + false => Lanes::of(lanes).for_each(|lane| { + let (m, s) = parts[picks[lane] as usize]; + f.mant[base + lane] = m; + f.scales[base + lane] = s; + }), + } + f.wide[d] &= !lanes; + f.boxed[d] &= !lanes; + } + (Kind::Bool, _, _, Some(flags)) => { + let mut word = f.none(); + for lane in Lanes::of(lanes) { + word.put(lane, flags[picks[lane] as usize]); + } + f.put_mask(op.dst, lanes, word); + } + _ => { + for lane in Lanes::of(lanes) { + f.set(op.dst, lane, values[picks[lane] as usize].clone()); + } + } + } + } +} diff --git a/core/expression/src/lane/exec/text.rs b/core/expression/src/lane/exec/text.rs new file mode 100644 index 00000000..4f066aaa --- /dev/null +++ b/core/expression/src/lane/exec/text.rs @@ -0,0 +1,223 @@ +use super::frame::Frame; +use super::Executor; +use crate::functions::FunctionKind; +use crate::lane::builtins::{Text, TextKernel}; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +use crate::lane::program::{Input, Kind, Reg}; +use crate::variable::Variable; +use zen_types::symbol::Symbol; + +impl Executor { + pub(super) fn text_call( + dst: Reg, + kind: &FunctionKind, + args: &[Input], + active: M, + f: &mut Frame, + ) -> M { + let Some(kernel) = Text::kernel(kind) else { + return f.none(); + }; + let (a, k) = match (kernel, args) { + (TextKernel::Test(_), [Input::Reg(a), Input::Const(id)]) => { + match &f.consts[*id as usize] { + Variable::String(k) => (*a, Some(k.clone())), + _ => return f.none(), + } + } + (TextKernel::Map(_) | TextKernel::Size, [Input::Reg(a)]) => (*a, None), + _ => return f.none(), + }; + if f.kind(a) != Kind::Str { + return f.none(); + } + Self::text_kernel(kernel, dst, a, active, k.as_deref(), f) + } + + pub(super) fn text_kernel( + kernel: TextKernel, + dst: Reg, + a: Reg, + lanes: M, + k: Option<&str>, + f: &mut Frame, + ) -> M { + let d = dst as usize; + let (base, from) = (d * f.width, a as usize * f.width); + let done = lanes & !f.boxed[a as usize]; + match kernel { + TextKernel::Test(op) => { + let (Some(k), Kind::Bool) = (k, f.kind(dst)) else { + return f.none(); + }; + let mut word = f.none(); + for lane in Lanes::of(done) { + word.put(lane, op.apply(f.text_at(a, lane), k)); + } + f.bits[d] = (f.bits[d] & !done) | word; + } + TextKernel::Size => { + if f.kind(dst) != Kind::Num { + return f.none(); + } + for lane in Lanes::of(done) { + let (x, y) = f.spans[from + lane]; + f.mant[base + lane] = (y - x) as i64; + f.scales[base + lane] = 0; + } + f.wide[d] &= !done; + } + TextKernel::Map(op) => { + if f.kind(dst) != Kind::Str { + return f.none(); + } + let spans = &f.spans[from..from + f.width]; + let block = (done == M::all(f.width)) + .then(|| Frame::::block(spans)) + .flatten() + .and_then(|(x, y)| f.arena.get(x..y).map(|t| (x, y, t))); + let bulk = match (op.bytewise(), block) { + (Some(bytewise), Some((x, y, text))) if text.is_ascii() => { + Some((Some(bytewise), x, y)) + } + (None, Some((x, y, text))) + if spans.iter().all(|(p, q)| { + op.unchanged( + text.get(*p as usize - x..*q as usize - x) + .unwrap_or_default(), + ) + }) => + { + Some((None, x, y)) + } + _ => None, + }; + match bulk { + Some((None, _, _)) => { + for lane in 0..f.width { + f.spans[base + lane] = f.spans[from + lane]; + } + } + Some((Some(bytewise), x, y)) => { + let origin = f.arena.len(); + f.arena.extend_from_within(x..y); + if let Some(tail) = f.arena.get_mut(origin..) { + bytewise(tail); + } + let shift = origin as u32 - x as u32; + for lane in 0..f.width { + let (p, q) = f.spans[from + lane]; + f.spans[base + lane] = (p + shift, q + shift); + } + } + None => { + let mut scratch = std::mem::take(&mut f.text); + scratch.clear(); + let origin = f.arena.len() as u32; + let (arena, spans) = (&f.arena, &mut f.spans); + for lane in Lanes::of(done) { + let before = scratch.len() as u32; + let (x, y) = spans[from + lane]; + let text = arena.get(x as usize..y as usize).unwrap_or_default(); + spans[base + lane] = match op.apply(text, &mut scratch) { + Some((p, q)) => (x + p as u32, x + q as u32), + None => (origin + before, origin + scratch.len() as u32), + }; + } + f.arena.push_str(&scratch); + f.text = scratch; + } + } + } + } + f.boxed[d] &= !done; + done + } + + pub(super) fn join(dst: Reg, parts: &[Input], active: M, f: &mut Frame) { + let texts = f.kind(dst) == Kind::Str + && parts.iter().all(|p| match p { + Input::Const(id) => matches!(f.consts[*id as usize], Variable::String(_)), + Input::Reg(r) => f.kind(*r) == Kind::Str, + }); + let typed = match texts { + true => parts.iter().fold(active, |acc, p| match p { + Input::Reg(r) => acc & !f.boxed[*r as usize], + Input::Const(_) => acc, + }), + false => f.none(), + }; + if typed.any() { + let mut text = std::mem::take(&mut f.text); + text.clear(); + let origin = f.arena.len() as u32; + let base = dst as usize * f.width; + let (arena, spans, consts, width) = + (f.arena.as_str(), &mut f.spans, &f.consts, f.width); + for lane in Lanes::of(typed) { + let before = text.len() as u32; + for part in parts { + let piece = match part { + Input::Const(id) => consts[*id as usize].as_str().unwrap_or_default(), + Input::Reg(r) => { + let (x, y) = spans[*r as usize * width + lane]; + arena.get(x as usize..y as usize).unwrap_or_default() + } + }; + text.push_str(piece); + } + spans[base + lane] = (origin + before, origin + text.len() as u32); + } + f.arena.push_str(&text); + f.text = text; + f.boxed[dst as usize] &= !typed; + } + Self::join_rows(dst, parts, active & !typed, f); + } + + pub(super) fn join_rows(dst: Reg, parts: &[Input], active: M, f: &mut Frame) { + let mut text = std::mem::take(&mut f.text); + let typed = f.kind(dst) == Kind::Str; + for lane in Lanes::of(active) { + text.clear(); + let mut failed = None; + for (i, p) in parts.iter().enumerate() { + let pushed = match p { + Input::Const(id) => Self::push_text(&mut text, &f.consts[*id as usize]), + Input::Reg(r) if f.kind(*r) == Kind::Str && !f.boxed[*r as usize].get(lane) => { + text.push_str(f.text_at(*r, lane)); + true + } + Input::Reg(r) => f.with(*r, lane, |v| Self::push_text(&mut text, v)), + }; + if !pushed { + failed = Some(i); + break; + } + } + match (failed, typed) { + (Some(i), _) => f.fail( + lane, + Ops::error("Join", format!("Unexpected type in array on index {i}")), + ), + (None, true) => { + f.put_text(dst, lane, &text); + f.boxed[dst as usize].unset(lane); + } + (None, false) => f.set(dst, lane, Variable::String(Symbol::from(text.as_str()))), + } + } + f.text = text; + } + + pub(super) fn push_text(text: &mut String, v: &Variable) -> bool { + match v { + Variable::String(s) => { + text.push_str(s); + true + } + _ => false, + } + } +} diff --git a/core/expression/src/lane/interval.rs b/core/expression/src/lane/interval.rs new file mode 100644 index 00000000..f58031db --- /dev/null +++ b/core/expression/src/lane/interval.rs @@ -0,0 +1,117 @@ +use crate::lane::date::Date; +use crate::lexer::Bracket; +use crate::variable::DynamicVariable; +use crate::Variable; +use anyhow::anyhow; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; +use serde_json::Value; +use std::any::Any; +use std::fmt::{Display, Formatter}; + +#[derive(Debug, Clone)] +pub(crate) struct Interval { + pub left_bracket: Bracket, + pub right_bracket: Bracket, + pub left: IntervalData, + pub right: IntervalData, +} + +impl DynamicVariable for Interval { + fn type_name(&self) -> &'static str { + "interval" + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn to_value(&self) -> Value { + Value::String(self.to_string()) + } +} + +impl Interval { + pub fn to_array(&self) -> Option> { + let (left, right) = match (&self.left, &self.right) { + (IntervalData::Number(l), IntervalData::Number(r)) => (*l, *r), + _ => return None, + }; + + let start = match &self.left_bracket { + Bracket::LeftParenthesis => left.to_i64()? + 1, + Bracket::LeftSquareBracket => left.to_i64()?, + _ => return None, + }; + + let end = match &self.right_bracket { + Bracket::RightParenthesis => right.to_i64()? - 1, + Bracket::RightSquareBracket => right.to_i64()?, + _ => return None, + }; + + let list = (start..=end) + .map(|n| Variable::Number(Decimal::from(n))) + .collect::>(); + + Some(list) + } + + pub fn includes(&self, v: IntervalData) -> anyhow::Result { + let mut is_open = false; + let l = &self.left; + let r = &self.right; + + let first = match &self.left_bracket { + Bracket::LeftParenthesis => l < &v, + Bracket::LeftSquareBracket => l <= &v, + Bracket::RightParenthesis => { + is_open = true; + l > &v + } + Bracket::RightSquareBracket => { + is_open = true; + l >= &v + } + _ => return Err(anyhow!("Unsupported bracket")), + }; + + let second = match &self.right_bracket { + Bracket::RightParenthesis => r > &v, + Bracket::RightSquareBracket => r >= &v, + Bracket::LeftParenthesis => r < &v, + Bracket::LeftSquareBracket => r <= &v, + _ => return Err(anyhow!("Unsupported bracket")), + }; + + let open_stmt = is_open && (first || second); + let closed_stmt = !is_open && first && second; + + Ok(open_stmt || closed_stmt) + } +} + +impl Display for Interval { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}{}..{}{}", + self.left_bracket, self.left, self.right, self.right_bracket + ) + } +} + +#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq)] +pub(crate) enum IntervalData { + Number(Decimal), + Date(Date), +} + +impl Display for IntervalData { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + IntervalData::Number(n) => write!(f, "{n}"), + IntervalData::Date(d) => write!(f, "{d}"), + } + } +} diff --git a/core/expression/src/lane/kernel.rs b/core/expression/src/lane/kernel.rs new file mode 100644 index 00000000..2ce67749 --- /dev/null +++ b/core/expression/src/lane/kernel.rs @@ -0,0 +1,2090 @@ +use crate::compiler::Compare; +use crate::functions::registry::FunctionRegistry; +use crate::functions::{ + ClosureFunction, DateMethod, FunctionKind, InternalFunction, MethodKind, MethodRegistry, +}; +use crate::lane::builtins::{Arg, Builtins, Dates, Out}; +use crate::lane::columns::Columns; +use crate::lane::compile::{Hints, LaneCompiler}; +use crate::lane::date::Date; +use crate::lane::interval::{Interval, IntervalData}; +use crate::lane::ops::Ops; +use crate::lane::program::{Binding, Const, Kind, NumCmp, NumOp, Program}; +use crate::lane::scaled::Scaled; +use crate::lexer::{ArithmeticOperator, ComparisonOperator, LogicalOperator, Operator}; +use crate::parser::Node; +use crate::scope::Scope; +use crate::variable::Variable; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; +use smallvec::SmallVec; +use std::cell::RefCell; +use std::str::FromStr; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use zen_types::path::DotPath; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +type Sc = (i64, u8); +type NumFn = Box Option + Send + Sync>; +type BoolFn = Box Option + Send + Sync>; +type ValFn = Box Option + Send + Sync>; +type DateFn = Box Option + Send + Sync>; + +struct Slot(AtomicU64); + +impl Slot { + const LIMIT: u64 = 1 << 55; + const ABSENT: u64 = 0xFF; + + fn new() -> Self { + Self(AtomicU64::new(0)) + } + + #[inline(always)] + fn get<'v>(&self, map: &'v VariableMap, key: &str) -> Option<&'v Variable> { + let Some((shape, values)) = map.slots() else { + return map.get_str(key); + }; + let id = shape.id(); + if id >= Self::LIMIT { + return map.get_str(key); + } + let tag = (id + 1) << 8; + let packed = self.0.load(Ordering::Relaxed); + if packed & !Self::ABSENT == tag { + return match packed & Self::ABSENT { + Self::ABSENT => None, + index => values.get(index as usize), + }; + } + let index = shape.index_of(key); + let stored = match index { + Some(i) if (i as u64) < Self::ABSENT => i as u64, + Some(_) => return index.and_then(|i| values.get(i)), + None => Self::ABSENT, + }; + self.0.store(tag | stored, Ordering::Relaxed); + index.and_then(|i| values.get(i)) + } +} + +enum Step { + Key(Box, Slot), + Index(usize), +} + +pub(crate) struct Env<'a> { + row: usize, + columns: Option<&'a Columns<'a>>, + bound: &'a [Binding], + outs: &'a [Variable], + current: Option<&'a RefCell>, + roots: Option<&'a RefCell>, +} + +impl Env<'_> { + const EMPTY: Env<'static> = Env { + row: 0, + columns: None, + bound: &[], + outs: &[], + current: None, + roots: None, + }; +} + +pub(crate) struct Cx<'a> { + scope: &'a Scope, + env: &'a Env<'a>, + element: Option<&'a Variable>, + up: Option<&'a Cx<'a>>, +} + +impl<'a> Cx<'a> { + #[inline] + fn pointer(&self, depth: u32) -> Option<&'a Variable> { + let mut cx = self; + for _ in 0..depth { + cx = cx.up?; + } + cx.element + } + + #[inline] + fn child<'b>(&'b self, element: &'b Variable) -> Cx<'b> { + Cx { + scope: self.scope, + env: self.env, + element: Some(element), + up: Some(self), + } + } +} + +enum Origin { + Env(Box, Slot, usize), + Out(usize), + Pointer(u32), + Root, +} + +enum Root<'a> { + Env(&'a str), + Pointer(u32), + Root, +} + +struct Load { + origin: Origin, + rest: Box<[Step]>, + bound: usize, +} + +impl Load { + #[inline(always)] + fn with(&self, cx: &Cx, f: impl FnOnce(&Variable) -> Option) -> Option { + let Origin::Env(key, slot, id) = &self.origin else { + return self.elsewhere(cx, f); + }; + let env = cx.env; + if !env.bound.is_empty() { + match env.bound.get(*id) { + Some(Binding::Column(index)) => { + let (_, column) = env.columns?.columns.get(*index)?; + return Self::walk( + &column.variable(env.row), + self.rest.get(self.bound..).unwrap_or_default(), + f, + ); + } + Some(Binding::Absent) => return f(&Variable::Null), + _ => {} + } + } + match env.current { + Some(cell) => self.scoped(&cell.borrow(), key, slot, f), + None => self.scoped(cx.scope, key, slot, f), + } + } + + #[inline(always)] + fn scoped( + &self, + scope: &Scope, + key: &str, + slot: &Slot, + f: impl FnOnce(&Variable) -> Option, + ) -> Option { + if !scope.locals().is_empty() { + if let Some(v) = scope.local_str(key) { + return Self::walk(v, &self.rest, f); + } + } + match scope.base() { + Variable::Object(o) => { + let o = o.borrow(); + match slot.get(&o, key) { + Some(v) => Self::walk(v, &self.rest, f), + None => f(&Variable::Null), + } + } + Variable::Null => f(&Variable::Null), + _ => None, + } + } + + #[inline(never)] + fn elsewhere(&self, cx: &Cx, f: impl FnOnce(&Variable) -> Option) -> Option { + match &self.origin { + Origin::Out(index) => Self::walk(cx.env.outs.get(*index)?, &self.rest, f), + Origin::Pointer(depth) => Self::walk(cx.pointer(*depth)?, &self.rest, f), + Origin::Root => { + let root = match cx.env.roots { + Some(cell) => cell.borrow().materialize(), + None => cx.scope.materialize(), + }; + Self::walk(&root, &self.rest, f) + } + Origin::Env(..) => None, + } + } + + #[inline] + fn walk(v: &Variable, rest: &[Step], f: impl FnOnce(&Variable) -> Option) -> Option { + let Some((step, tail)) = rest.split_first() else { + return f(v); + }; + match (step, v) { + (Step::Key(key, slot), Variable::Object(o)) => { + let o = o.borrow(); + match slot.get(&o, key) { + Some(next) => Self::walk(next, tail, f), + None => f(&Variable::Null), + } + } + (Step::Key(..), _) => f(&Variable::Null), + (Step::Index(_), Variable::Dynamic(_)) => None, + (Step::Index(i), Variable::Array(a)) => { + let a = a.borrow(); + match a.get(*i) { + Some(next) => Self::walk(next, tail, f), + None => f(&Variable::Null), + } + } + (Step::Index(i), Variable::String(s)) => { + let next = i + .checked_add(1) + .and_then(|end| s.get(*i..end)) + .map_or(Variable::Null, |c| Variable::String(c.into())); + Self::walk(&next, tail, f) + } + (Step::Index(_), _) => f(&Variable::Null), + } + } +} + +enum Code { + Const(Const), + Load(Arc), + Num(NumFn), + Bool(BoolFn), + Date(DateFn), + Val(ValFn), +} + +impl Code { + fn numeric(&self) -> bool { + match self { + Code::Num(_) => true, + Code::Const(Const::Number(n)) => Scaled::parts(n).is_some(), + _ => false, + } + } + + fn boolean_typed(&self) -> bool { + matches!(self, Code::Bool(_) | Code::Const(Const::Bool(_))) + } + + fn dated(&self) -> bool { + matches!(self, Code::Date(_) | Code::Const(Const::Date(_))) + } + + fn guardable(&self) -> bool { + self.numeric() || matches!(self, Code::Load(_)) + } + + fn date(self) -> DateFn { + match self { + Code::Date(f) => f, + Code::Const(Const::Date(d)) => Box::new(move |_| Some(Date(d))), + _ => Box::new(|_| None), + } + } + + fn scaled(&self) -> Option { + match self { + Code::Const(Const::Number(n)) => Scaled::parts(n), + _ => None, + } + } + + fn num(self) -> NumFn { + match self { + Code::Num(f) => f, + Code::Const(Const::Number(n)) => match Scaled::parts(&n) { + Some(k) => Box::new(move |_| Some(k)), + None => Box::new(|_| None), + }, + Code::Const(_) | Code::Bool(_) | Code::Date(_) => Box::new(|_| None), + Code::Load(l) => Box::new(move |s| { + l.with(s, |v| match v { + Variable::Number(n) => Scaled::parts(n), + _ => None, + }) + }), + Code::Val(f) => Box::new(move |s| match f(s)? { + Variable::Number(n) => Scaled::parts(&n), + _ => None, + }), + } + } + + fn boolean(self) -> BoolFn { + match self { + Code::Bool(f) => f, + Code::Const(Const::Bool(b)) => Box::new(move |_| Some(b)), + Code::Const(_) | Code::Num(_) | Code::Date(_) => Box::new(|_| None), + Code::Load(l) => Box::new(move |s| { + l.with(s, |v| match v { + Variable::Bool(b) => Some(*b), + _ => None, + }) + }), + Code::Val(f) => Box::new(move |s| match f(s)? { + Variable::Bool(b) => Some(b), + _ => None, + }), + } + } + + fn val(self) -> ValFn { + match self { + Code::Val(f) => f, + Code::Num(f) => { + Box::new(move |s| f(s).map(|(m, sc)| Variable::Number(Scaled::decimal(m, sc)))) + } + Code::Bool(f) => Box::new(move |s| f(s).map(Variable::Bool)), + Code::Date(f) => Box::new(move |s| f(s).map(Date::variable)), + Code::Load(l) => Box::new(move |s| l.with(s, |v| Some(v.clone()))), + Code::Const(c) => match c { + Const::Null => Box::new(|_| Some(Variable::Null)), + Const::Bool(b) => Box::new(move |_| Some(Variable::Bool(b))), + Const::Number(n) => Box::new(move |_| Some(Variable::Number(n))), + c => Box::new(move |_| Some(c.variable())), + }, + } + } + + fn view( + self, + f: impl Fn(&Cx, &Variable) -> Option + Send + Sync + 'static, + ) -> Box Option + Send + Sync> { + match self { + Code::Load(l) => Box::new(move |s| l.with(s, |v| f(s, v))), + other => { + let g = other.val(); + Box::new(move |s| { + let v = g(s)?; + f(s, &v) + }) + } + } + } +} + +enum Held { + Var(Variable), + Date(Date), +} + +impl Held { + #[inline] + fn arg(&self) -> Arg<'_> { + match self { + Held::Var(v) => Arg::of(v), + Held::Date(d) => Arg::Date(*d), + } + } +} + +type HeldFn = Box Option + Send + Sync>; + +struct Members { + nums: Vec, + strs: Vec>, + bools: [bool; 2], + null: bool, +} + +impl Members { + fn of(items: &[Const]) -> Self { + let mut members = Members { + nums: Vec::new(), + strs: Vec::new(), + bools: [false; 2], + null: false, + }; + for item in items { + match item { + Const::Number(n) => members.nums.push(*n), + Const::String(s) => members.strs.push(Box::from(s.as_ref())), + Const::Bool(b) => members.bools[*b as usize] = true, + Const::Null => members.null = true, + Const::Array(_) | Const::Date(_) => {} + } + } + members + } + + #[inline] + fn test(&self, v: &Variable) -> Option { + match v { + Variable::Number(n) => Some(self.nums.iter().any(|x| Ops::same_number(n, x))), + Variable::String(s) => Some(self.strs.iter().any(|x| x.as_ref() == s.as_str())), + Variable::Bool(b) => Some(self.bools[*b as usize]), + Variable::Null => Some(self.null), + _ => None, + } + } +} + +enum Mode { + Plain, + Owned, + Dynamic { keys: Box<[Box]>, rewind: bool }, +} + +pub(crate) struct Kernel { + entries: Vec, + keys: Vec>>, + sites: Vec>, + mode: Mode, +} + +impl std::fmt::Debug for Kernel { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Kernel") + } +} + +pub(crate) type Values = SmallVec<[Variable; 4]>; + +impl Kernel { + const DEPTH: usize = 192; + + fn builder<'h, 'a>(hints: Option<&'h Hints>) -> KernelBuilder<'h, 'a> { + KernelBuilder { + hints, + folder: LaneCompiler::folder(), + depth: 0, + keys: Vec::new(), + dollar: None, + unresolved: false, + aliases: Vec::new(), + owned: false, + indexing: false, + } + } + + pub(crate) fn compile<'a>( + root: &'a Node<'a>, + hints: Option<&Hints>, + program: &Program, + ) -> Option { + let mut builder = Self::builder(hints); + builder.owned = LaneCompiler::assigns(root); + let code = builder.node(root)?; + let mode = match builder.owned { + true => Mode::Owned, + false => Mode::Plain, + }; + Some(Self::finish(vec![code.val()], builder.keys, program, mode)) + } + + pub(crate) fn compile_many<'a>( + roots: &[(&'a str, &'a Node<'a>)], + chain: bool, + hints: Option<&Hints>, + program: &Program, + ) -> Option { + if roots.is_empty() { + return None; + } + let assigns = roots.iter().any(|(_, n)| LaneCompiler::assigns(n)); + let nested = roots + .iter() + .any(|(a, _)| roots.iter().any(|(b, _)| DotPath::under(b, a))); + let resolvable = chain + && !assigns + && !nested + && roots.iter().all(|(_, n)| LaneCompiler::dollar_static(n)); + if resolvable { + if let Some(kernel) = Self::entries(roots, hints, program, true, false) { + return Some(kernel); + } + } + Self::entries(roots, hints, program, false, chain) + } + + fn entries<'a>( + roots: &[(&'a str, &'a Node<'a>)], + hints: Option<&Hints>, + program: &Program, + resolvable: bool, + dynamic: bool, + ) -> Option { + let assigns = roots.iter().any(|(_, n)| LaneCompiler::assigns(n)); + let mut builder = Self::builder(hints); + builder.dollar = resolvable.then(Vec::new); + builder.owned = assigns; + builder.indexing = resolvable || dynamic; + let mut entries = Vec::with_capacity(roots.len()); + for (index, (key, root)) in roots.iter().enumerate() { + entries.push(builder.node(root)?.val()); + if builder.unresolved { + return None; + } + if let Some(dollar) = builder.dollar.as_mut() { + match dollar.iter_mut().find(|(k, _)| k == key) { + Some(entry) => entry.1 = index, + None => dollar.push((key.to_string(), index)), + } + } + } + let mode = match (dynamic, assigns) { + (true, rewind) => Mode::Dynamic { + keys: roots.iter().map(|(k, _)| Box::from(*k)).collect(), + rewind, + }, + (false, true) => Mode::Owned, + (false, false) => Mode::Plain, + }; + Some(Self::finish(entries, builder.keys, program, mode)) + } + + fn finish( + entries: Vec, + keys: Vec>>, + program: &Program, + mode: Mode, + ) -> Self { + let sites = keys + .iter() + .map(|key| { + let key = key.as_deref()?; + program + .site_keys + .iter() + .position(|k| k.as_deref() == Some(key)) + }) + .collect(); + Self { + entries, + keys, + sites, + mode, + } + } + + pub(crate) fn bind(&self, bind: &dyn Fn(&str) -> Binding) -> Vec { + self.keys + .iter() + .map(|key| key.as_deref().map_or(Binding::Row, bind)) + .collect() + } + + pub(crate) fn bind_sites(&self, bound: &[Binding]) -> Vec { + self.sites + .iter() + .map(|site| { + site.and_then(|i| bound.get(i).copied()) + .unwrap_or(Binding::Row) + }) + .collect() + } + + #[inline(always)] + pub(crate) fn run(&self, scope: &Scope) -> Option { + match (self.entries.as_slice(), &self.mode) { + ([entry], Mode::Plain) => entry(&Cx { + scope, + env: &Env::EMPTY, + element: None, + up: None, + }), + _ => self.run_all(scope, 0, None, &[])?.pop(), + } + } + + #[inline] + pub(crate) fn run_all( + &self, + scope: &Scope, + row: usize, + columns: Option<&Columns>, + bound: &[Binding], + ) -> Option { + let mut values = Values::new(); + let (current, roots, bound) = match &self.mode { + Mode::Plain => (None, None, bound), + Mode::Owned => (Some(RefCell::new(scope.clone())), None, &[][..]), + Mode::Dynamic { .. } => ( + Some(RefCell::new(scope.clone())), + Some(RefCell::new(scope.clone())), + &[][..], + ), + }; + for (index, entry) in self.entries.iter().enumerate() { + if let (Mode::Dynamic { rewind: true, .. }, Some(current), Some(roots), true) = + (&self.mode, ¤t, &roots, index > 0) + { + *current.borrow_mut() = roots.borrow().clone(); + } + let env = Env { + row, + columns, + bound, + outs: &values, + current: current.as_ref(), + roots: roots.as_ref(), + }; + let value = entry(&Cx { + scope, + env: &env, + element: None, + up: None, + })?; + if let (Mode::Dynamic { keys, .. }, Some(current), Some(roots)) = + (&self.mode, ¤t, &roots) + { + Self::insert_dollar(keys.get(index)?, &value, current, roots)?; + } + values.push(value); + } + Some(values) + } + + fn insert_dollar( + key: &str, + value: &Variable, + current: &RefCell, + roots: &RefCell, + ) -> Option<()> { + let mut root = roots.borrow_mut(); + let dollar = match root.local(&Variable::dollar_key()) { + Some(existing @ Variable::Object(_)) => existing.shallow_clone(), + _ => { + let created = Variable::empty_object(); + root.set_local(Variable::dollar_key(), created.clone()); + created + } + }; + let _ = dollar.dot_insert(key, value.clone()); + current + .borrow_mut() + .set_local(Variable::dollar_key(), dollar); + Some(()) + } +} + +struct KernelBuilder<'h, 'a> { + hints: Option<&'h Hints>, + folder: LaneCompiler<'a>, + depth: usize, + keys: Vec>>, + dollar: Option>, + unresolved: bool, + aliases: Vec>, + owned: bool, + indexing: bool, +} + +impl<'h, 'a> KernelBuilder<'h, 'a> { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn node(&mut self, node: &'a Node<'a>) -> Option { + self.depth += 1; + let code = match self.depth > Kernel::DEPTH { + true => None, + false => self.compile(node), + }; + self.depth -= 1; + code + } + + fn compile(&mut self, node: &'a Node<'a>) -> Option { + if let Some(n) = Const::number(node) { + return Some(Code::Const(Const::Number(n))); + } + match node { + Node::Null => return Some(Code::Const(Const::Null)), + Node::Bool(b) => return Some(Code::Const(Const::Bool(*b))), + Node::String(s) => return Some(Code::Const(Const::String(Arc::from(*s)))), + Node::Parenthesized(inner) => return self.node(inner), + _ => {} + } + if let Some(resolved) = self.resolve_dollar(node) { + return Some(resolved); + } + if let Some(value) = self.folder.fold_value(node) { + return Some(Code::Const(value)); + } + match node { + Node::Root => Some(Code::Val(Box::new(|s| { + Some(match s.env.current { + Some(cell) => cell.borrow().materialize(), + None => s.scope.materialize(), + }) + }))), + Node::Assignments { list, output } => self.assignments(list, *output), + Node::Identifier(_) | Node::Member { .. } | Node::Pointer + if self.path(node).is_some() => + { + let (root, rest) = self.path(node)?; + Some(match root { + Root::Env(key) => self.load(key, rest), + Root::Root => Code::Val( + Code::Load(Arc::new(Load { + origin: Origin::Root, + rest: rest + .iter() + .map(|p| match p { + Node::String(k) => Step::Key(Box::from(*k), Slot::new()), + Node::Number(n) => { + Step::Index(n.to_u32().map_or(usize::MAX, |i| i as usize)) + } + _ => Step::Index(usize::MAX), + }) + .collect(), + bound: 0, + })) + .val(), + ), + Root::Pointer(depth) => Code::Load(Arc::new(Load { + origin: Origin::Pointer(depth), + rest: rest + .iter() + .filter_map(|p| match p { + Node::String(k) => Some(Step::Key(Box::from(*k), Slot::new())), + _ => None, + }) + .collect(), + bound: 0, + })), + }) + } + Node::Object(pairs) => self.object(pairs), + Node::Member { + node: object, + property: Node::String(key), + } => { + let key: Box = Box::from(*key); + let slot = Slot::new(); + Some(Code::Val(self.node(object)?.view(move |_, v| { + Some(match v { + Variable::Object(o) => slot + .get(&o.borrow(), &key) + .cloned() + .unwrap_or(Variable::Null), + _ => Variable::Null, + }) + }))) + } + Node::Member { + node: object, + property, + } => { + let (a, b) = (self.node(object)?.val(), self.node(property)?.val()); + Some(Code::Val(Box::new(move |s| Ops::fetch(a(s)?, b(s)?).ok()))) + } + Node::Array(items) => { + let items = items + .iter() + .map(|n| self.node(n).map(Code::val)) + .collect::>>()?; + Some(Code::Val(Box::new(move |s| { + let values = items.iter().map(|f| f(s)).collect::>>()?; + Some(Variable::from_array(values)) + }))) + } + Node::TemplateString(parts) => self.template(parts), + Node::Slice { node, to, from } => { + let a = self.node(node)?.val(); + let to = match to { + Some(t) => Some(self.node(t)?.val()), + None => None, + }; + let from = match from { + Some(f) => Some(self.node(f)?.val()), + None => None, + }; + Some(Code::Val(Box::new(move |s| { + let a = a(s)?; + let to = match &to { + Some(t) => t(s)?, + None => Ops::subtract(Ops::len(&a).ok()?, Variable::Number(Decimal::ONE)) + .ok()?, + }; + let from = match &from { + Some(f) => f(s)?, + None => Variable::Number(Decimal::ZERO), + }; + Ops::slice(a, to, from).ok() + }))) + } + Node::Interval { + left, + right, + left_bracket, + right_bracket, + } => { + let (a, b) = (self.node(left)?.val(), self.node(right)?.val()); + let (l, r) = (*left_bracket, *right_bracket); + Some(Code::Val(Box::new(move |s| { + Ops::interval(&a(s)?, &b(s)?, l, r).ok() + }))) + } + Node::Conditional { + condition, + on_true, + on_false, + } => { + let c = self.node(condition)?.boolean(); + let (t, f) = (self.node(on_true)?, self.node(on_false)?); + Some( + match ( + t.numeric(), + f.numeric(), + t.boolean_typed(), + f.boolean_typed(), + ) { + (true, true, _, _) => { + let (t, f) = (t.num(), f.num()); + Code::Num(Box::new(move |s| if c(s)? { t(s) } else { f(s) })) + } + (_, _, true, true) => { + let (t, f) = (t.boolean(), f.boolean()); + Code::Bool(Box::new(move |s| if c(s)? { t(s) } else { f(s) })) + } + _ => { + let (t, f) = (t.val(), f.val()); + Code::Val(Box::new(move |s| if c(s)? { t(s) } else { f(s) })) + } + }, + ) + } + Node::Unary { node, operator } => { + let a = self.node(node)?; + match operator { + Operator::Arithmetic(ArithmeticOperator::Add) => Some(a), + Operator::Arithmetic(ArithmeticOperator::Subtract) => Some(match a.numeric() { + true => { + let a = a.num(); + Code::Num(Box::new(move |s| { + let (m, sc) = a(s)?; + (m != 0).then_some(())?; + Some((m.checked_neg()?, sc)) + })) + } + false => { + let a = a.val(); + Code::Val(Box::new(move |s| Ops::negate(a(s)?).ok())) + } + }), + Operator::Logical(LogicalOperator::Not) => { + let a = a.boolean(); + Some(Code::Bool(Box::new(move |s| a(s).map(|b| !b)))) + } + _ => None, + } + } + Node::Binary { + left, + operator, + right, + } => self.binary(left, *operator, right), + Node::FunctionCall { kind, arguments } => self.call(kind, arguments), + Node::MethodCall { + kind, + this, + arguments, + } => self.method(kind, this, arguments), + _ => None, + } + } + + fn assignments( + &mut self, + list: &'a [(&'a Node<'a>, &'a Node<'a>)], + output: Option<&'a Node<'a>>, + ) -> Option { + let steps = list + .iter() + .map(|(k, v)| Some((self.node(k)?.val(), self.node(v)?.val()))) + .collect::>>()?; + let output = match output { + Some(o) => Some(self.node(o)?.val()), + None => None, + }; + Some(Code::Val(Box::new(move |s| { + let object = Variable::empty_object(); + for (key, value) in &steps { + let key = Ops::assigned_key(key(s)?).ok()?; + let value = value(s)?; + let cell = s.env.current?; + Ops::assign(&mut cell.borrow_mut(), &object, &key, value).ok()?; + } + match &output { + Some(o) => o(s), + None => Some(object), + } + }))) + } + + fn lookup_alias(&self, name: &str) -> Option { + self.aliases + .iter() + .rev() + .position(|alias| *alias == Some(name)) + .map(|depth| depth as u32) + } + + fn object(&mut self, pairs: &'a [(&'a Node<'a>, &'a Node<'a>)]) -> Option { + enum Key { + Static(Box), + Dynamic(ValFn), + } + let string = Builtins::of(&FunctionKind::Internal(InternalFunction::String))?; + let mut compiled = Vec::with_capacity(pairs.len()); + for (key, value) in pairs.iter() { + let key = match key { + Node::String(k) => Key::Static(Box::from(*k)), + other => Key::Dynamic(self.node(other)?.val()), + }; + compiled.push((key, self.node(value)?.val())); + } + Some(Code::Val(Box::new(move |s| { + let mut pairs: SmallVec<[(Symbol, Variable); 8]> = + SmallVec::with_capacity(compiled.len()); + for (key, value) in compiled.iter() { + let key = match key { + Key::Static(k) => Symbol::from(k.as_ref()), + Key::Dynamic(f) => { + let k = f(s)?; + let text = Builtins::raw(string, &[Arg::of(&k)]).ok()?.variable(); + Ops::object_key(text).ok()? + } + }; + pairs.push((key, value(s)?)); + } + let mut map = crate::variable::VariableMap::with_capacity(pairs.len()); + for (key, value) in pairs.into_iter().rev() { + map.insert(key, value); + } + Some(Variable::from_object(map)) + }))) + } + + fn each_owned(v: &Variable, each: &mut dyn FnMut(&Variable) -> Option) -> Option<()> { + let list = match v { + Variable::Array(_) => v.clone(), + other => Ops::elements(other).ok()?, + }; + let Variable::Array(items) = &list else { + return None; + }; + let mut index = 0; + loop { + let Some(item) = items.borrow().get(index).cloned() else { + return Some(()); + }; + if !each(&item)? { + return Some(()); + } + index += 1; + } + } + + fn each(v: &Variable, each: &mut dyn FnMut(&Variable) -> Option) -> Option<()> { + let owned; + let items = match v { + Variable::Array(a) => a, + other => { + owned = Ops::elements(other).ok()?; + match &owned { + Variable::Array(a) => a, + _ => return None, + } + } + }; + let items = items.borrow(); + for item in items.iter() { + if !each(item)? { + break; + } + } + Some(()) + } + + fn closure(&mut self, kind: ClosureFunction, arguments: &'a [&'a Node<'a>]) -> Option { + let [list, body] = arguments else { + return None; + }; + let (body, alias) = match body { + Node::Closure { body, alias } => (*body, *alias), + other => (*other, None), + }; + let each: fn(&Variable, &mut dyn FnMut(&Variable) -> Option) -> Option<()> = + match self.owned { + true => Self::each_owned, + false => Self::each, + }; + let list = self.node(list)?; + self.aliases.push(alias); + let body = self.node(body); + self.aliases.pop(); + let body = body?; + Some(match kind { + ClosureFunction::Some | ClosureFunction::All | ClosureFunction::None => { + let body = body.boolean(); + Code::Bool(list.view(move |s, v| { + let mut verdict = !matches!(kind, ClosureFunction::Some); + each(v, &mut |item| { + let hit = body(&s.child(item))?; + match (kind, hit) { + (ClosureFunction::Some, true) => verdict = true, + (ClosureFunction::All, false) | (ClosureFunction::None, true) => { + verdict = false + } + _ => return Some(true), + } + Some(false) + })?; + Some(verdict) + })) + } + ClosureFunction::Count | ClosureFunction::One => { + let body = body.boolean(); + let count = list.view(move |s, v| { + let mut count = 0i64; + each(v, &mut |item| { + count += body(&s.child(item))? as i64; + Some(true) + })?; + Some(count) + }); + match kind { + ClosureFunction::One => Code::Bool(Box::new(move |s| count(s).map(|n| n == 1))), + _ => Code::Num(Box::new(move |s| count(s).map(|n| (n, 0)))), + } + } + ClosureFunction::Filter => { + let body = body.boolean(); + Code::Val(list.view(move |s, v| { + let mut kept = Vec::new(); + each(v, &mut |item| { + if body(&s.child(item))? { + kept.push(item.clone()); + } + Some(true) + })?; + Some(Variable::from_array(kept)) + })) + } + ClosureFunction::Map | ClosureFunction::FlatMap => { + let body = body.val(); + Code::Val(list.view(move |s, v| { + let mut values = Vec::new(); + each(v, &mut |item| { + values.push(body(&s.child(item))?); + Some(true) + })?; + let array = Variable::from_array(values); + match kind { + ClosureFunction::Map => Some(array), + _ => Ops::flatten(array).ok(), + } + })) + } + }) + } + + fn resolve_dollar(&mut self, node: &'a Node<'a>) -> Option { + if !self.aliases.is_empty() { + return None; + } + let dollar = self.dollar.as_ref().filter(|d| !d.is_empty())?; + let mut segments = Vec::new(); + let mut base = node; + while let Node::Member { + node: inner, + property: Node::String(p), + } = base + { + segments.push(*p); + base = inner; + } + if !matches!(base, Node::Identifier("$")) || segments.is_empty() { + return None; + } + segments.reverse(); + let found = (1..=segments.len()).rev().find_map(|i| { + let key = segments[..i].join("."); + dollar + .iter() + .find(|(k, _)| *k == key) + .map(|(_, index)| (*index, i)) + }); + let Some((index, used)) = found else { + let interior = (1..=segments.len()).any(|i| { + let prefix = format!("{}.", segments[..i].join(".")); + dollar.iter().any(|(k, _)| k.starts_with(&prefix)) + }); + if interior { + self.unresolved = true; + } + return Some(Code::Const(Const::Null)); + }; + let rest: Box<[Step]> = segments[used..] + .iter() + .map(|key| Step::Key(Box::from(*key), Slot::new())) + .collect(); + Some(Code::Load(Arc::new(Load { + origin: Origin::Out(index), + rest, + bound: 0, + }))) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn path(&self, node: &'a Node<'a>) -> Option<(Root<'a>, Vec<&'a Node<'a>>)> { + match node { + Node::Identifier("$") if self.dollar.as_ref().is_some_and(|d| !d.is_empty()) => None, + Node::Identifier(v) => match self.lookup_alias(v) { + Some(depth) => Some((Root::Pointer(depth), Vec::new())), + None => Some((Root::Env(v), Vec::new())), + }, + Node::Pointer if !self.aliases.is_empty() => Some((Root::Pointer(0), Vec::new())), + Node::Root => Some((Root::Root, Vec::new())), + Node::Member { node, property } => { + let (root, mut rest) = self.path(node)?; + match (&root, property) { + (_, Node::String(_)) => rest.push(property), + (Root::Env(_) | Root::Root, Node::Number(n)) if n.to_u32().is_some() => { + rest.push(property) + } + _ => return None, + } + Some((root, rest)) + } + _ => None, + } + } + + fn load(&mut self, key: &'a str, rest: Vec<&'a Node<'a>>) -> Code { + let mut name = key.to_string(); + let mut keyed = true; + let mut dotted = false; + let steps: Box<[Step]> = rest + .iter() + .map(|p| match p { + Node::String(s) => { + dotted |= s.contains('.'); + name.push('.'); + name.push_str(s); + Step::Key(Box::from(*s), Slot::new()) + } + _ => { + keyed = false; + let index = match p { + Node::Number(n) => n.to_u32().map_or(usize::MAX, |i| i as usize), + _ => usize::MAX, + }; + Step::Index(index) + } + }) + .collect(); + let leading = rest + .iter() + .take_while(|p| matches!(p, Node::String(_))) + .count(); + let (bind_key, bound) = match (keyed, dotted) { + (true, false) => (Some(Box::::from(name.as_str())), steps.len()), + (false, false) if self.indexing => { + let prefix: Vec<&str> = std::iter::once(key) + .chain(rest.iter().take(leading).filter_map(|p| match p { + Node::String(s) => Some(*s), + _ => None, + })) + .collect(); + (Some(Box::::from(prefix.join(".").as_str())), leading) + } + _ => (None, steps.len()), + }; + let id = self.keys.len(); + self.keys.push(bind_key); + let code = Code::Load(Arc::new(Load { + origin: Origin::Env(Box::from(key), Slot::new(), id), + rest: steps, + bound, + })); + let hint = match keyed { + true => self.hints.and_then(|h| h.get(&name).copied()), + false => None, + }; + match (hint, code, self.owned) { + (Some(Kind::Num), code @ Code::Load(_), _) => Code::Num(code.num()), + (Some(Kind::Bool), code @ Code::Load(_), _) => Code::Bool(code.boolean()), + (_, code @ Code::Load(_), true) => Code::Val(code.val()), + (_, code, _) => code, + } + } + + fn template(&mut self, parts: &'a [&'a Node<'a>]) -> Option { + enum Part { + Text(Box), + Num(NumFn), + Value(ValFn), + } + let string = Builtins::of(&FunctionKind::Internal(InternalFunction::String))?; + let parts = parts + .iter() + .map(|p| match p { + Node::String(text) => Some(Part::Text(Box::from(*text))), + other => self.node(other).map(|c| match c.numeric() { + true => Part::Num(c.num()), + false => Part::Value(c.val()), + }), + }) + .collect::>>()?; + Some(Code::Val(Box::new(move |s| { + let mut out = String::new(); + for part in &parts { + match part { + Part::Text(t) => out.push_str(t), + Part::Num(f) => { + let (m, sc) = f(s)?; + Scaled::write(m, sc, &mut out); + } + Part::Value(f) => match f(s)? { + Variable::String(t) => out.push_str(t.as_str()), + Variable::Number(n) if Scaled::parts(&n).is_some() => { + let (m, sc) = Scaled::parts(&n)?; + Scaled::write(m, sc, &mut out); + } + v => match Builtins::raw(string, &[Arg::of(&v)]).ok()?.variable() { + Variable::String(t) => out.push_str(t.as_str()), + _ => return None, + }, + }, + } + } + Some(Variable::String(Symbol::from(out.as_str()))) + }))) + } + + fn held(code: Code) -> HeldFn { + match code { + Code::Date(f) => Box::new(move |s| f(s).map(Held::Date)), + Code::Const(Const::Date(d)) => Box::new(move |_| Some(Held::Date(Date(d)))), + other => { + let f = other.val(); + Box::new(move |s| f(s).map(Held::Var)) + } + } + } + + fn typed_out(returns: Kind, f: Box Option + Send + Sync>) -> Code { + match returns { + Kind::Date => Code::Date(Box::new(move |s| match f(s)? { + Out::Date(d) => Some(d), + Out::Var(v) => Date::of(&v).filter(|_| !Date::sourced(&v)), + _ => None, + })), + _ => Code::Val(Box::new(move |s| f(s).map(Out::variable))), + } + } + + fn returns(t: &crate::variable::VariableType) -> Kind { + match t { + crate::variable::VariableType::Date => Kind::Date, + _ => Kind::Dyn, + } + } + + fn call(&mut self, kind: &FunctionKind, arguments: &'a [&'a Node<'a>]) -> Option { + let function = match kind { + FunctionKind::Internal(function) => function, + FunctionKind::Closure(closure) => return self.closure(*closure, arguments), + FunctionKind::Deprecated(_) => { + let builtin = Builtins::of(kind)?; + let returns = FunctionRegistry::get_definition(kind) + .map(|f| Self::returns(&f.return_type())) + .unwrap_or(Kind::Dyn); + let codes = arguments + .iter() + .map(|a| self.node(a)) + .collect::>>()?; + return self.generic_call(builtin, returns, codes); + } + }; + match (function, arguments) { + (InternalFunction::Date, []) => {} + (InternalFunction::Date, [first, ..]) if Const::of(first).is_some() => {} + (InternalFunction::Date, [text]) => return self.date_of(kind, text, None), + (InternalFunction::Date, [text, Node::String(zone)]) => { + let parsed = chrono_tz::Tz::from_str(zone).ok()?; + return self.date_of(kind, text, Some((parsed, zone))); + } + (InternalFunction::Max | InternalFunction::Min, [Node::Array(items)]) + if !items.is_empty() => + { + return self.extreme(kind, *function == InternalFunction::Max, items) + } + _ => {} + } + let builtin = Builtins::of(kind)?; + let returns = FunctionRegistry::get_definition(kind) + .map(|f| Self::returns(&f.return_type())) + .unwrap_or(Kind::Dyn); + let codes = arguments + .iter() + .map(|a| self.node(a)) + .collect::>>()?; + let codes = match Self::fast_call(*function, builtin, codes) { + Ok(code) => return Some(code), + Err(codes) => codes, + }; + if returns != Kind::Date { + match Self::borrowed_call(builtin, codes) { + Ok(code) => return Some(code), + Err(codes) => return self.generic_call(builtin, returns, codes), + } + } + self.generic_call(builtin, returns, codes) + } + + fn const_arg(c: &Const) -> Option> { + Some(match c { + Const::Null => Arg::Null, + Const::Bool(b) => Arg::Bool(*b), + Const::Number(n) => Arg::Num(*n), + Const::String(t) => Arg::Str(t), + Const::Date(d) => Arg::Date(Date(*d)), + Const::Array(_) => return None, + }) + } + + fn borrowed_call( + builtin: &'static crate::lane::builtins::Builtin, + codes: Vec, + ) -> Result> { + let call = move |views: &[Arg]| Builtins::raw(builtin, views).ok().map(Out::variable); + let mut codes = codes; + match codes.as_slice() { + [Code::Load(_)] => { + let Some(Code::Load(l)) = codes.pop() else { + return Err(codes); + }; + Ok(Code::Val(Box::new(move |s| { + l.with(s, |v| call(&[Arg::of(v)])) + }))) + } + [Code::Load(_), Code::Const(c)] if Self::const_arg(c).is_some() => { + let (Some(Code::Const(c)), Some(Code::Load(l))) = (codes.pop(), codes.pop()) else { + return Err(codes); + }; + Ok(Code::Val(Box::new(move |s| { + l.with(s, |v| call(&[Arg::of(v), Self::const_arg(&c)?])) + }))) + } + [Code::Load(_), Code::Load(_)] => { + let (Some(Code::Load(b)), Some(Code::Load(a))) = (codes.pop(), codes.pop()) else { + return Err(codes); + }; + Ok(Code::Val(Box::new(move |s| { + a.with(s, |x| b.with(s, |y| call(&[Arg::of(x), Arg::of(y)]))) + }))) + } + _ => Err(codes), + } + } + + fn fast_call( + function: InternalFunction, + builtin: &'static crate::lane::builtins::Builtin, + codes: Vec, + ) -> Result> { + let mut codes = codes; + let places = match codes.as_slice() { + [_, Code::Const(Const::Number(n))] => { + n.to_u32().filter(|p| *p <= 28).map(|p| Some(p as u8)) + } + [_] => Some(None), + _ => None, + }; + let numeric: Option Option> = match (function, places) { + (InternalFunction::Abs, Some(None)) => Some(|m, s, _| Scaled::abs(m, s)), + (InternalFunction::Floor, Some(None)) => Some(|m, s, _| Scaled::floor(m, s)), + (InternalFunction::Ceil, Some(None)) => Some(|m, s, _| Scaled::ceil(m, s)), + (InternalFunction::Round, Some(_)) => Some(Scaled::round), + (InternalFunction::Trunc, Some(_)) => Some(Scaled::trunc), + _ => None, + }; + if let (Some(op), Some(first)) = (numeric, codes.first()) { + if first.guardable() { + let places = places.flatten().unwrap_or(0); + codes.truncate(1); + let Some(a) = codes.pop() else { + return Err(codes); + }; + let a = a.num(); + return Ok(Code::Num(Box::new(move |s| { + let (m, sc) = a(s)?; + op(m, sc, places) + }))); + } + } + match (function, codes.as_slice()) { + (InternalFunction::Len, [Code::Load(_)]) => { + let Some(Code::Load(l)) = codes.pop() else { + return Err(codes); + }; + Ok(Code::Val(Box::new(move |s| { + l.with(s, |v| match v { + Variable::String(t) => Some(Variable::Number(Decimal::from(t.len()))), + Variable::Array(a) => { + Some(Variable::Number(Decimal::from(a.borrow().len()))) + } + other => Builtins::raw(builtin, &[Arg::of(other)]) + .ok() + .map(Out::variable), + }) + }))) + } + ( + InternalFunction::StartsWith + | InternalFunction::EndsWith + | InternalFunction::Contains, + [Code::Load(_), Code::Const(Const::String(_))], + ) => { + let (Some(Code::Const(needle)), Some(Code::Load(l))) = (codes.pop(), codes.pop()) + else { + return Err(codes); + }; + let Const::String(needle) = &needle else { + return Err(codes); + }; + let needle = needle.clone(); + let test: fn(&str, &str) -> bool = match function { + InternalFunction::StartsWith => |a, b| a.starts_with(b), + InternalFunction::EndsWith => |a, b| a.ends_with(b), + _ => |a, b| a.contains(b), + }; + Ok(Code::Val(Box::new(move |s| { + l.with(s, |v| match v { + Variable::String(t) => Some(Variable::Bool(test(t.as_str(), &needle))), + other => Builtins::raw(builtin, &[Arg::of(other), Arg::Str(&needle)]) + .ok() + .map(Out::variable), + }) + }))) + } + _ => Err(codes), + } + } + + fn generic_call( + &mut self, + builtin: &'static crate::lane::builtins::Builtin, + returns: Kind, + codes: Vec, + ) -> Option { + let args: Vec = codes.into_iter().map(Self::held).collect(); + Some(Self::typed_out( + returns, + Box::new(move |s| { + let values = args + .iter() + .map(|f| f(s)) + .collect::>>()?; + let views: SmallVec<[Arg; 4]> = values.iter().map(Held::arg).collect(); + Builtins::raw(builtin, &views).ok() + }), + )) + } + + fn date_of( + &mut self, + kind: &FunctionKind, + text: &'a Node<'a>, + zone: Option<(chrono_tz::Tz, &str)>, + ) -> Option { + let builtin = Builtins::of(kind)?; + let zone_text: Option> = zone.map(|(_, z)| Box::from(z)); + let zone = zone.map(|(z, _)| z); + Some(Code::Date(self.node(text)?.view(move |_, v| match v { + Variable::String(t) => Some(Date::text(t.as_str(), zone)), + other => { + let mut views: SmallVec<[Arg; 2]> = SmallVec::new(); + views.push(Arg::of(other)); + if let Some(z) = &zone_text { + views.push(Arg::Str(z)); + } + match Builtins::raw(builtin, &views).ok()? { + Out::Date(d) => Some(d), + Out::Var(v) => Date::of(&v).filter(|_| !Date::sourced(&v)), + _ => None, + } + } + }))) + } + + fn extreme( + &mut self, + kind: &FunctionKind, + largest: bool, + items: &'a [&'a Node<'a>], + ) -> Option { + let builtin = Builtins::of(kind)?; + let items = items + .iter() + .map(|n| self.node(n).map(Code::val)) + .collect::>>()?; + Some(Code::Val(Box::new(move |s| { + let values = items + .iter() + .map(|f| f(s)) + .collect::>>()?; + let mut best: Option = None; + let mut fast = true; + for v in &values { + let Some(x) = (match v { + Variable::Number(n) => Scaled::parts(n), + _ => None, + }) else { + fast = false; + break; + }; + best = match best { + None => Some(x), + Some(b) => { + let order = Scaled::compare(x, b)?; + Some(match largest { + true if order.is_ge() => x, + false if order.is_lt() => x, + _ => b, + }) + } + }; + } + if let (true, Some((m, sc))) = (fast, best) { + return Some(Variable::Number(Scaled::decimal(m, sc))); + } + let array = Variable::from_array(values.into_vec()); + Builtins::raw(builtin, &[Arg::of(&array)]) + .ok() + .map(Out::variable) + }))) + } + + fn method( + &mut self, + kind: &MethodKind, + this: &'a Node<'a>, + arguments: &'a [&'a Node<'a>], + ) -> Option { + let MethodKind::DateMethod(method) = kind; + let builtin = Builtins::method(kind); + let returns = MethodRegistry::get_definition(kind) + .map(|m| Self::returns(&m.return_type())) + .unwrap_or(Kind::Dyn); + let this = self.node(this)?; + let parts = matches!( + method, + DateMethod::Second + | DateMethod::Minute + | DateMethod::Hour + | DateMethod::Day + | DateMethod::Weekday + | DateMethod::DayOfYear + | DateMethod::Week + | DateMethod::Month + | DateMethod::Quarter + | DateMethod::Year + | DateMethod::Timestamp + ); + if this.dated() && arguments.is_empty() && parts { + let this = this.date(); + let kind = kind.clone(); + return Some(Code::Num(Box::new(move |s| { + Dates::part_of(&kind, &this(s)?).map(|n| (n, 0)) + }))); + } + if this.dated() && !arguments.is_empty() { + let consts: Option> = arguments + .iter() + .map(|a| Const::of(a).map(|c| c.variable())) + .collect(); + if let Some(consts) = consts { + let views: SmallVec<[Arg; 4]> = std::iter::once(Arg::Null) + .chain(consts.iter().map(Arg::of)) + .collect(); + if let Some(shift) = Dates::shift(kind, &views) { + let this = this.date(); + return Some(Code::Date(Box::new(move |s| Some(shift.apply(&this(s)?))))); + } + } + } + if let [other] = arguments { + let probe = Date(None); + if this.dated() && Dates::order(kind, &probe, &probe).is_some() { + let other = self.node(other)?; + if other.dated() { + let (this, other, kind) = (this.date(), other.date(), kind.clone()); + return Some(Code::Bool(Box::new(move |s| { + Dates::order(&kind, &this(s)?, &other(s)?) + }))); + } + return self.method_call( + kind, + builtin, + returns, + this, + std::iter::once(other).collect(), + ); + } + } + let args = arguments + .iter() + .map(|a| self.node(a)) + .collect::>>()?; + self.method_call(kind, builtin, returns, this, args) + } + + fn method_call( + &mut self, + kind: &MethodKind, + builtin: &'static crate::lane::builtins::Builtin, + returns: Kind, + this: Code, + args: Vec, + ) -> Option { + let kind = kind.clone(); + let this = Self::held(this); + let args: Vec = args.into_iter().map(Self::held).collect(); + Some(Self::typed_out( + returns, + Box::new(move |s| { + let mut values: SmallVec<[Held; 4]> = SmallVec::new(); + values.push(this(s)?); + for f in &args { + values.push(f(s)?); + } + let views: SmallVec<[Arg; 4]> = values.iter().map(Held::arg).collect(); + Builtins::call_method(builtin, &kind, &views).ok() + }), + )) + } + + fn binary( + &mut self, + left: &'a Node<'a>, + operator: Operator, + right: &'a Node<'a>, + ) -> Option { + match operator { + Operator::Logical(LogicalOperator::And) => { + let a = self.node(left)?.boolean(); + let b = self.node(right)?; + Some(match b.boolean_typed() { + true => { + let b = b.boolean(); + Code::Bool(Box::new(move |s| if a(s)? { b(s) } else { Some(false) })) + } + false => { + let b = b.val(); + Code::Val(Box::new(move |s| { + if a(s)? { + b(s) + } else { + Some(Variable::Bool(false)) + } + })) + } + }) + } + Operator::Logical(LogicalOperator::Or) => { + let a = self.node(left)?.boolean(); + let b = self.node(right)?; + Some(match b.boolean_typed() { + true => { + let b = b.boolean(); + Code::Bool(Box::new(move |s| if a(s)? { Some(true) } else { b(s) })) + } + false => { + let b = b.val(); + Code::Val(Box::new(move |s| { + if a(s)? { + Some(Variable::Bool(true)) + } else { + b(s) + } + })) + } + }) + } + Operator::Logical(LogicalOperator::NullishCoalescing) => { + let a = self.node(left)?; + if a.numeric() || a.boolean_typed() { + return Some(a); + } + let (a, b) = (a.val(), self.node(right)?.val()); + Some(Code::Val(Box::new(move |s| match a(s)? { + Variable::Null => b(s), + v => Some(v), + }))) + } + Operator::Comparison(ComparisonOperator::Equal) => self.equal(left, right, false), + Operator::Comparison(ComparisonOperator::NotEqual) => self.equal(left, right, true), + Operator::Comparison(ComparisonOperator::In) => self.member(left, right, false), + Operator::Comparison(ComparisonOperator::NotIn) => self.member(left, right, true), + Operator::Comparison(c) => { + let order = match c { + ComparisonOperator::LessThan => Compare::Less, + ComparisonOperator::LessThanOrEqual => Compare::LessOrEqual, + ComparisonOperator::GreaterThan => Compare::More, + ComparisonOperator::GreaterThanOrEqual => Compare::MoreOrEqual, + _ => return None, + }; + self.compare(left, right, order) + } + Operator::Arithmetic(op) => self.arithmetic(left, op, right), + _ => None, + } + } + + fn negated(code: BoolFn, not: bool) -> Code { + match not { + true => Code::Bool(Box::new(move |s| code(s).map(|b| !b))), + false => Code::Bool(code), + } + } + + fn equal(&mut self, left: &'a Node<'a>, right: &'a Node<'a>, not: bool) -> Option { + let (a, b) = (self.node(left)?, self.node(right)?); + let test: BoolFn = match (a, b) { + (x, y) if x.dated() && y.dated() => { + let (x, y) = (x.date(), y.date()); + Box::new(move |s| { + let (p, q) = (x(s)?, y(s)?); + Some(p == q) + }) + } + (x, Code::Const(c)) | (Code::Const(c), x) + if !matches!(c, Const::Array(_) | Const::Date(_)) => + { + Self::eq_const(x, c) + } + (x, y) if x.numeric() && y.numeric() => { + let (x, y) = (x.num(), y.num()); + Box::new(move |s| Scaled::compare(x(s)?, y(s)?).map(|o| o.is_eq())) + } + (x, y) => { + let y = y.val(); + x.view(move |s, a| { + let b = y(s)?; + Some(Ops::equal(a, &b)) + }) + } + }; + Some(Self::negated(test, not)) + } + + fn eq_const(x: Code, c: Const) -> BoolFn { + match &c { + Const::Number(k) => match (x.numeric(), Scaled::parts(k)) { + (true, Some(k)) => { + let x = x.num(); + Box::new(move |s| Scaled::compare(x(s)?, k).map(|o| o.is_eq())) + } + _ => { + let k = *k; + x.view(move |_, v| { + Some(match v { + Variable::Number(n) => Ops::same_number(n, &k), + _ => false, + }) + }) + } + }, + Const::String(t) => { + let t = t.clone(); + x.view(move |_, v| { + Some(match v { + Variable::String(s) => s.as_str() == t.as_ref(), + Variable::Dynamic(_) => { + Ops::equal(v, &Variable::String(Symbol::from(t.as_ref()))) + } + _ => false, + }) + }) + } + Const::Bool(b) => { + let b = *b; + match x.boolean_typed() { + true => { + let x = x.boolean(); + Box::new(move |s| x(s).map(|v| v == b)) + } + false => x.view(move |_, v| Some(matches!(v, Variable::Bool(v) if *v == b))), + } + } + Const::Null => x.view(|_, v| Some(matches!(v, Variable::Null))), + _ => x.view(move |_, v| Some(Ops::equal(v, &c.variable()))), + } + } + + fn compare(&mut self, left: &'a Node<'a>, right: &'a Node<'a>, order: Compare) -> Option { + let (a, b) = (self.node(left)?, self.node(right)?); + if a.dated() && b.dated() { + let (a, b) = (a.date(), b.date()); + return Some(Code::Bool(Box::new(move |s| { + let (x, y) = (a(s)?, b(s)?); + (x.0.is_some() && y.0.is_some()).then(|| Ops::ordered(&x, &y, order)) + }))); + } + let test = NumCmp::Order(order); + if a.numeric() && b.numeric() { + let f: BoolFn = match (a.scaled(), b.scaled()) { + (_, Some(k)) => { + let a = a.num(); + Box::new(move |s| Scaled::compare(a(s)?, k).map(|o| test.test(o))) + } + (Some(k), _) => { + let b = b.num(); + Box::new(move |s| Scaled::compare(k, b(s)?).map(|o| test.test(o))) + } + _ => { + let (a, b) = (a.num(), b.num()); + Box::new(move |s| Scaled::compare(a(s)?, b(s)?).map(|o| test.test(o))) + } + }; + return Some(Code::Bool(f)); + } + let f: BoolFn = match (a, b) { + (x, Code::Const(Const::Number(k))) => x.view(move |_, v| match v { + Variable::Number(n) => Some(Ops::ordered_number(n, &k, order)), + other => Ops::compare(other, &Variable::Number(k), order).ok(), + }), + (Code::Const(Const::Number(k)), y) => y.view(move |_, v| match v { + Variable::Number(n) => Some(Ops::ordered_number(&k, n, order)), + other => Ops::compare(&Variable::Number(k), other, order).ok(), + }), + (x, y) => { + let y = y.val(); + x.view(move |s, a| { + let b = y(s)?; + Ops::compare(a, &b, order).ok() + }) + } + }; + Some(Code::Bool(f)) + } + + fn member(&mut self, left: &'a Node<'a>, right: &'a Node<'a>, not: bool) -> Option { + if let Node::Interval { + left: lo, + right: hi, + left_bracket, + right_bracket, + } = right + { + if let (Some(lo), Some(hi)) = (Const::number(lo), Const::number(hi)) { + let interval = Interval { + left_bracket: *left_bracket, + right_bracket: *right_bracket, + left: IntervalData::Number(lo), + right: IntervalData::Number(hi), + }; + let a = self.node(left)?; + let test: BoolFn = match a.numeric() { + true => { + let a = a.num(); + Box::new(move |s| { + let (m, sc) = a(s)?; + interval + .includes(IntervalData::Number(Scaled::decimal(m, sc))) + .ok() + }) + } + false => a.view(move |_, v| match v { + Variable::Number(n) => interval.includes(IntervalData::Number(*n)).ok(), + _ => None, + }), + }; + return Some(Self::negated(test, not)); + } + } + let constant = Const::of(right); + if let (Node::Array(_), Some(Const::Array(items))) = (right, constant.as_ref()) { + if !items.iter().any(|i| matches!(i, Const::Date(_))) { + let members = Members::of(items); + let a = self.node(left)?; + let test: BoolFn = match ( + a.numeric(), + items.iter().all(|i| matches!(i, Const::Number(_))), + ) { + (true, true) => { + let keys: Vec = members.nums.iter().filter_map(Scaled::parts).collect(); + match keys.len() == members.nums.len() { + true => { + let a = a.num(); + Box::new(move |s| { + let x = a(s)?; + keys.iter().try_fold(false, |hit, k| { + Some(hit || Scaled::compare(x, *k)?.is_eq()) + }) + }) + } + false => a.view(move |_, v| members.test(v)), + } + } + _ => a.view(move |_, v| members.test(v)), + }; + return Some(Self::negated(test, not)); + } + } + let (a, b) = (self.node(left)?, self.node(right)?.val()); + let test = a.view(move |s, x| { + let y = b(s)?; + Ops::membership(x.clone(), &y).ok() + }); + Some(Self::negated(test, not)) + } + + fn wide(op: NumOp, a: Sc, b: Sc) -> Option { + let (x, y) = (Scaled::decimal(a.0, a.1), Scaled::decimal(b.0, b.1)); + let r = match op { + NumOp::Add => x.checked_add(y), + NumOp::Subtract => x.checked_sub(y), + NumOp::Multiply => x.checked_mul(y), + NumOp::Divide | NumOp::Modulo => None, + }?; + Scaled::parts(&r) + } + + fn arithmetic( + &mut self, + left: &'a Node<'a>, + op: ArithmeticOperator, + right: &'a Node<'a>, + ) -> Option { + if op == ArithmeticOperator::Add && Self::textual(left, right) { + let mut parts = Vec::new(); + self.addends(left, &mut parts)?; + parts.push(self.node(right)?.val()); + return Some(Code::Val(Self::concat(parts))); + } + let (a, b) = (self.node(left)?, self.node(right)?); + let op = match op { + ArithmeticOperator::Add => NumOp::Add, + ArithmeticOperator::Subtract => NumOp::Subtract, + ArithmeticOperator::Multiply => NumOp::Multiply, + ArithmeticOperator::Divide => NumOp::Divide, + ArithmeticOperator::Modulus => NumOp::Modulo, + ArithmeticOperator::Power => { + let (a, b) = (a.val(), b.val()); + return Some(Code::Val(Box::new(move |s| { + Ops::exponent(a(s)?, b(s)?).ok() + }))); + } + }; + let typed = match op { + NumOp::Divide | NumOp::Modulo => false, + NumOp::Add => (a.numeric() || b.numeric()) && a.guardable() && b.guardable(), + _ => a.guardable() && b.guardable(), + }; + if !typed { + let (a, b) = (a.val(), b.val()); + return Some(Code::Val(Box::new(move |s| Self::boxed(op, a(s)?, b(s)?)))); + } + let f: NumFn = match (a.scaled(), b.scaled()) { + (_, Some(k)) => { + let a = a.num(); + Box::new(move |s| { + let x = a(s)?; + op.scaled(x, k).or_else(|| Self::wide(op, x, k)) + }) + } + (Some(k), _) => { + let b = b.num(); + Box::new(move |s| { + let y = b(s)?; + op.scaled(k, y).or_else(|| Self::wide(op, k, y)) + }) + } + _ => { + let (a, b) = (a.num(), b.num()); + Box::new(move |s| { + let (x, y) = (a(s)?, b(s)?); + op.scaled(x, y).or_else(|| Self::wide(op, x, y)) + }) + } + }; + Some(Code::Num(f)) + } + + fn textual(left: &Node, right: &Node) -> bool { + let text = |n: &Node| matches!(n, Node::String(_) | Node::TemplateString(_)); + let mut node = left; + let mut any = text(right); + while let Node::Binary { + left, + operator: Operator::Arithmetic(ArithmeticOperator::Add), + right, + } = node + { + any |= text(right); + node = left; + } + any || text(node) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn addends(&mut self, node: &'a Node<'a>, out: &mut Vec) -> Option<()> { + match node { + Node::Binary { + left, + operator: Operator::Arithmetic(ArithmeticOperator::Add), + right, + } if self.folder.fold_value(node).is_none() => { + self.depth += 1; + let done = match self.depth > Kernel::DEPTH { + true => None, + false => self.addends(left, out), + }; + self.depth -= 1; + done?; + out.push(self.node(right)?.val()); + Some(()) + } + other => { + out.push(self.node(other)?.val()); + Some(()) + } + } + } + + fn concat(parts: Vec) -> ValFn { + Box::new(move |s| { + let values = parts + .iter() + .map(|f| f(s)) + .collect::>>()?; + if values.iter().all(|v| matches!(v, Variable::String(_))) { + let mut out = String::new(); + for v in &values { + if let Variable::String(t) = v { + out.push_str(t.as_str()); + } + } + return Some(Variable::String(Symbol::from(out.as_str()))); + } + let mut values = values.into_iter(); + let first = values.next()?; + values.try_fold(first, |acc, v| Ops::add(acc, v).ok()) + }) + } + + #[inline] + fn boxed(op: NumOp, x: Variable, y: Variable) -> Option { + if let (Variable::Number(p), Variable::Number(q)) = (&x, &y) { + if let Some((m, sc)) = Scaled::parts(p) + .zip(Scaled::parts(q)) + .and_then(|(u, v)| op.scaled(u, v)) + { + return Some(Variable::Number(Scaled::decimal(m, sc))); + } + } + match op { + NumOp::Add => Ops::add(x, y), + NumOp::Subtract => Ops::subtract(x, y), + NumOp::Multiply => Ops::multiply(x, y), + NumOp::Divide => Ops::divide(x, y), + NumOp::Modulo => Ops::modulo(x, y), + } + .ok() + } +} diff --git a/core/expression/src/lane/key.rs b/core/expression/src/lane/key.rs new file mode 100644 index 00000000..8d7c16f1 --- /dev/null +++ b/core/expression/src/lane/key.rs @@ -0,0 +1,58 @@ +pub struct ShortKey; + +impl ShortKey { + #[inline(always)] + pub fn of(bytes: &[u8]) -> u64 { + match bytes.first_chunk::<8>() { + Some(head) => u64::from_le_bytes(*head), + None => bytes + .iter() + .enumerate() + .fold(0u64, |key, (i, b)| key | u64::from(*b) << (8 * i)), + } + } + + #[inline(always)] + pub fn mask(len: usize) -> u64 { + match len { + 0 => 0, + 1..=7 => (1u64 << (8 * len)) - 1, + _ => u64::MAX, + } + } + + #[inline(always)] + pub fn at(data: &[u8], lo: usize, len: usize) -> u64 { + match data.get(lo..).and_then(<[u8]>::first_chunk::<8>) { + Some(word) => u64::from_le_bytes(*word) & Self::mask(len), + None => data.get(lo..lo + len.min(8)).map_or(0, Self::of), + } + } +} + +#[cfg(test)] +mod tests { + use super::ShortKey; + + #[test] + fn short_keys_match_their_padded_prefix() { + let data = b"abcdefghijkl"; + for lo in 0..data.len() { + for len in 0..=data.len() - lo { + let head = &data[lo..lo + len.min(8)]; + let mut padded = [0u8; 8]; + padded[..head.len()].copy_from_slice(head); + assert_eq!( + ShortKey::at(data, lo, len), + u64::from_le_bytes(padded), + "{lo} {len}" + ); + assert_eq!( + ShortKey::of(&data[lo..lo + len]), + u64::from_le_bytes(padded), + "{lo} {len}" + ); + } + } + } +} diff --git a/core/expression/src/lane/mask.rs b/core/expression/src/lane/mask.rs new file mode 100644 index 00000000..1be1a1eb --- /dev/null +++ b/core/expression/src/lane/mask.rs @@ -0,0 +1,473 @@ +use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; + +pub const LANES: usize = 1024; +const WORDS: usize = LANES / 64; + +#[derive(Clone, Copy, Debug)] +pub struct Mask { + words: [u64; WORDS], + used: u8, +} + +impl Default for Mask { + fn default() -> Self { + Self::none(LANES) + } +} + +impl Mask { + #[inline] + pub fn span(width: usize) -> usize { + width.div_ceil(64).clamp(1, WORDS) + } + + #[inline] + pub fn none(width: usize) -> Self { + Self { + words: [0; WORDS], + used: Self::span(width) as u8, + } + } + + #[inline] + pub fn all(width: usize) -> Self { + let mut mask = Self::none(width); + if width <= 64 { + mask.words[0] = if width == 64 { + u64::MAX + } else { + (1u64 << width) - 1 + }; + return mask; + } + let full = width / 64; + mask.words[..full.min(WORDS)].fill(u64::MAX); + if full < WORDS && !width.is_multiple_of(64) { + mask.words[full] = (1u64 << (width % 64)) - 1; + } + mask + } + + #[inline] + pub fn used(&self) -> &[u64] { + &self.words[..self.used as usize] + } + + #[inline] + pub fn used_mut(&mut self) -> &mut [u64] { + &mut self.words[..self.used as usize] + } + + #[inline(always)] + pub fn word(&self, index: usize) -> u64 { + self.words[index & (WORDS - 1)] + } + + #[inline(always)] + pub fn set_word(&mut self, index: usize, word: u64) { + self.words[index & (WORDS - 1)] = word; + } + + #[inline(always)] + pub fn get(&self, lane: usize) -> bool { + self.words[(lane >> 6) & (WORDS - 1)] >> (lane & 63) & 1 == 1 + } + + #[inline(always)] + pub fn set(&mut self, lane: usize) { + self.words[(lane >> 6) & (WORDS - 1)] |= 1 << (lane & 63); + } + + #[inline(always)] + pub fn unset(&mut self, lane: usize) { + self.words[(lane >> 6) & (WORDS - 1)] &= !(1 << (lane & 63)); + } + + #[inline(always)] + pub fn put(&mut self, lane: usize, on: bool) { + let w = &mut self.words[(lane >> 6) & (WORDS - 1)]; + *w = (*w & !(1 << (lane & 63))) | ((on as u64) << (lane & 63)); + } + + #[inline(always)] + pub fn is_empty(&self) -> bool { + match self.used { + 1 => self.words[0] == 0, + _ => self.used().iter().all(|w| *w == 0), + } + } + + #[inline] + pub fn count(&self) -> usize { + self.used().iter().map(|w| w.count_ones() as usize).sum() + } + + #[inline] + pub fn first(&self) -> Option { + self.used() + .iter() + .enumerate() + .find(|(_, w)| **w != 0) + .map(|(i, w)| i * 64 + w.trailing_zeros() as usize) + } + + #[inline(always)] + fn zip(self, other: Mask, f: impl Fn(u64, u64) -> u64) -> Mask { + if self.used == 1 && other.used == 1 { + let mut out = self; + out.words[0] = f(self.words[0], other.words[0]); + return out; + } + let mut out = if self.used >= other.used { self } else { other }; + for i in 0..out.used as usize { + out.words[i] = f(self.words[i], other.words[i]); + } + out + } +} + +impl PartialEq for Mask { + #[inline] + fn eq(&self, other: &Mask) -> bool { + let used = self.used.max(other.used) as usize; + self.words[..used] == other.words[..used] + } +} + +impl Eq for Mask {} + +impl BitAnd for Mask { + type Output = Mask; + + #[inline] + fn bitand(self, other: Mask) -> Mask { + self.zip(other, |a, b| a & b) + } +} + +impl BitOr for Mask { + type Output = Mask; + + #[inline] + fn bitor(self, other: Mask) -> Mask { + self.zip(other, |a, b| a | b) + } +} + +impl Not for Mask { + type Output = Mask; + + #[inline(always)] + fn not(self) -> Mask { + let mut out = self; + if out.used == 1 { + out.words[0] = !out.words[0]; + return out; + } + for w in out.used_mut() { + *w = !*w; + } + out + } +} + +impl BitAndAssign for Mask { + #[inline] + fn bitand_assign(&mut self, other: Mask) { + *self = *self & other; + } +} + +impl BitOrAssign for Mask { + #[inline] + fn bitor_assign(&mut self, other: Mask) { + *self = *self | other; + } +} + +pub trait LaneSet: + Copy + + Eq + + std::fmt::Debug + + Default + + BitAnd + + BitOr + + Not + + BitAndAssign + + BitOrAssign +{ + const LANES: usize; + + fn none(width: usize) -> Self; + fn all(width: usize) -> Self; + fn words(&self) -> usize; + fn word(&self, index: usize) -> u64; + fn set_word(&mut self, index: usize, word: u64); + fn get(&self, lane: usize) -> bool; + fn set(&mut self, lane: usize); + fn unset(&mut self, lane: usize); + fn put(&mut self, lane: usize, on: bool); + fn is_empty(&self) -> bool; + fn count(&self) -> usize; + fn first(&self) -> Option; + + #[inline] + fn any(&self) -> bool { + !self.is_empty() + } + + #[inline] + fn store(&self, target: &mut [u64], at: usize) { + for i in 0..self.words() { + if let Some(slot) = target.get_mut(at + i) { + *slot = self.word(i); + } + } + } +} + +impl LaneSet for Mask { + const LANES: usize = LANES; + + #[inline(always)] + fn none(width: usize) -> Self { + Mask::none(width) + } + + #[inline(always)] + fn all(width: usize) -> Self { + Mask::all(width) + } + + #[inline(always)] + fn words(&self) -> usize { + self.used as usize + } + + #[inline(always)] + fn word(&self, index: usize) -> u64 { + Mask::word(self, index) + } + + #[inline(always)] + fn set_word(&mut self, index: usize, word: u64) { + Mask::set_word(self, index, word) + } + + #[inline(always)] + fn get(&self, lane: usize) -> bool { + Mask::get(self, lane) + } + + #[inline(always)] + fn set(&mut self, lane: usize) { + Mask::set(self, lane) + } + + #[inline(always)] + fn unset(&mut self, lane: usize) { + Mask::unset(self, lane) + } + + #[inline(always)] + fn put(&mut self, lane: usize, on: bool) { + Mask::put(self, lane, on) + } + + #[inline(always)] + fn is_empty(&self) -> bool { + Mask::is_empty(self) + } + + #[inline(always)] + fn count(&self) -> usize { + Mask::count(self) + } + + #[inline(always)] + fn first(&self) -> Option { + Mask::first(self) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub struct Word(u64); + +impl LaneSet for Word { + const LANES: usize = 64; + + #[inline] + fn none(_: usize) -> Self { + Word(0) + } + + #[inline] + fn all(width: usize) -> Self { + Word(if width >= 64 { + u64::MAX + } else { + (1u64 << width) - 1 + }) + } + + #[inline] + fn words(&self) -> usize { + 1 + } + + #[inline(always)] + fn word(&self, index: usize) -> u64 { + if index == 0 { + self.0 + } else { + 0 + } + } + + #[inline(always)] + fn set_word(&mut self, index: usize, word: u64) { + if index == 0 { + self.0 = word; + } + } + + #[inline(always)] + fn get(&self, lane: usize) -> bool { + self.0 >> (lane & 63) & 1 == 1 + } + + #[inline(always)] + fn set(&mut self, lane: usize) { + self.0 |= 1 << (lane & 63); + } + + #[inline(always)] + fn unset(&mut self, lane: usize) { + self.0 &= !(1 << (lane & 63)); + } + + #[inline(always)] + fn put(&mut self, lane: usize, on: bool) { + self.0 = (self.0 & !(1 << (lane & 63))) | ((on as u64) << (lane & 63)); + } + + #[inline] + fn is_empty(&self) -> bool { + self.0 == 0 + } + + #[inline] + fn count(&self) -> usize { + self.0.count_ones() as usize + } + + #[inline] + fn first(&self) -> Option { + (self.0 != 0).then(|| self.0.trailing_zeros() as usize) + } +} + +impl BitAnd for Word { + type Output = Word; + + #[inline] + fn bitand(self, other: Word) -> Word { + Word(self.0 & other.0) + } +} + +impl BitOr for Word { + type Output = Word; + + #[inline] + fn bitor(self, other: Word) -> Word { + Word(self.0 | other.0) + } +} + +impl Not for Word { + type Output = Word; + + #[inline] + fn not(self) -> Word { + Word(!self.0) + } +} + +impl BitAndAssign for Word { + #[inline] + fn bitand_assign(&mut self, other: Word) { + self.0 &= other.0; + } +} + +impl BitOrAssign for Word { + #[inline] + fn bitor_assign(&mut self, other: Word) { + self.0 |= other.0; + } +} + +pub struct Lanes { + mask: M, + index: usize, + current: u64, +} + +impl Lanes { + #[inline] + pub fn of(mask: M) -> Self { + Self { + current: mask.word(0), + mask, + index: 0, + } + } +} + +impl Iterator for Lanes { + type Item = usize; + + #[inline] + fn next(&mut self) -> Option { + loop { + if self.current != 0 { + let bit = self.current.trailing_zeros() as usize; + self.current &= self.current - 1; + return Some(self.index * 64 + bit); + } + self.index += 1; + if self.index >= self.mask.words() { + return None; + } + self.current = self.mask.word(self.index); + } + } +} + +#[cfg(test)] +mod tests { + use super::{LaneSet, Mask, Word}; + + #[test] + fn lanes_and_ops() { + let mut m = Mask::none(300); + for lane in [0, 63, 64, 129, 299] { + m.set(lane); + } + assert_eq!( + super::Lanes::of(m).collect::>(), + vec![0, 63, 64, 129, 299] + ); + assert_eq!(m.count(), 5); + assert_eq!(m.first(), Some(0)); + let all = Mask::all(300); + assert_eq!(all.count(), 300); + assert_eq!((!m & all).count(), 295); + assert!(Mask::none(1).is_empty()); + assert_eq!(Mask::all(64).count(), 64); + assert_eq!(Mask::all(1024).count(), 1024); + let w = Word::all(10) & !Word::none(10); + assert_eq!(super::Lanes::of(w).count(), 10); + } +} diff --git a/core/expression/src/lane/mod.rs b/core/expression/src/lane/mod.rs new file mode 100644 index 00000000..09c22a8c --- /dev/null +++ b/core/expression/src/lane/mod.rs @@ -0,0 +1,1401 @@ +mod bits; +pub(crate) mod builtins; +mod cells; +mod columns; +mod compile; +pub(crate) mod date; +pub(crate) mod effect; +mod exec; +mod interval; +mod kernel; +mod key; +mod mask; +mod ops; +mod output; +mod program; +pub(crate) mod scaled; +mod session; +mod source; + +#[doc(hidden)] +pub use bits::Bits; +#[doc(hidden)] +pub use cells::{CellEnv, CellSet, Pieces}; +pub use columns::{Column, Columns, Dictionary, Values}; +#[doc(hidden)] +pub use compile::{Hints, LaneCompiler}; +#[doc(hidden)] +pub use exec::{Context, Executor, Fallbacks, Fault, Frame}; +#[doc(hidden)] +pub use key::ShortKey; +#[doc(hidden)] +pub use mask::{LaneSet, Mask, Word, LANES}; +pub use output::{Cell, Output, Shape}; +#[doc(hidden)] +pub use program::{ + Binary, Binding, ClosureOp, Const, FoldOp, Kind, Layout, Op, Program, Reg, Step, Subject, + SwitchOp, +}; +#[doc(hidden)] +pub use scaled::Scaled; +pub use session::{Programs, Session}; +#[doc(hidden)] +pub use source::SourceInfo; + +use crate::lexer::Lexer; +use crate::parser::{Node, Parser}; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::{ExpressionKind, IsolateError}; +use bumpalo::Bump; +use kernel::Kernel; +use std::sync::{Arc, OnceLock}; + +#[derive(Debug, Clone)] +enum Source { + Single(std::sync::Arc), + Many(std::sync::Arc<[(String, String)]>, bool), + Cells(std::sync::Arc<[(String, Option)]>), + Fused(std::sync::Arc<[Fusion]>), +} + +#[derive(Debug, Clone)] +#[doc(hidden)] +pub enum Fusion { + Output { + key: String, + source: String, + }, + Hidden { + key: String, + source: String, + }, + Rules { + key: String, + rules: Vec<(Vec<(String, String)>, String)>, + }, +} + +#[derive(Debug, Clone)] +pub struct LaneProgram { + program: Program, + kind: ExpressionKind, + source: Source, + constant: Option, + hints: Option>, + kernel: OnceLock>>, +} + +impl LaneProgram { + pub fn compile(source: &str, kind: ExpressionKind) -> Result { + Self::compile_with(source, kind, None) + } + + pub fn compile_with( + source: &str, + kind: ExpressionKind, + hints: Option<&Hints>, + ) -> Result { + Self::single(source, kind, hints) + } + + fn single( + source: &str, + kind: ExpressionKind, + hints: Option<&Hints>, + ) -> Result { + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let tokens = lexer.tokenize(&bump, source)?; + let parser = Parser::try_new(&tokens, &bump)?; + let parsed = match kind { + ExpressionKind::Standard => parser.standard().parse(), + ExpressionKind::Unary => parser.unary().parse(), + }; + parsed.error()?; + let program = LaneCompiler::compile_with(parsed.root, hints)?; + let constant = match kind { + ExpressionKind::Standard => Const::of(parsed.root), + ExpressionKind::Unary => None, + }; + Ok(Self { + program, + kind, + source: Source::Single(source.into()), + constant, + hints: hints.map(|h| Arc::new(h.clone())), + kernel: OnceLock::new(), + }) + } + + fn recompile(&self, hints: &Hints) -> Result { + match &self.source { + Source::Single(source) => Self::compile_with(source, self.kind.clone(), Some(hints)), + Source::Many(entries, chain) => { + let refs: Vec<(&str, &str)> = entries + .iter() + .map(|(k, s)| (k.as_str(), s.as_str())) + .collect(); + Self::compile_many_with(&refs, *chain, Some(hints)) + } + Source::Cells(cells) => { + let refs: Vec<(&str, Option<&str>)> = cells + .iter() + .map(|(s, f)| (s.as_str(), f.as_deref())) + .collect(); + Self::compile_cells_with(&refs, Some(hints)) + } + Source::Fused(entries) => Self::compile_fused_with(entries, Some(hints)), + } + } + + pub fn source(&self) -> Option<&str> { + match &self.source { + Source::Single(source) => Some(source), + _ => None, + } + } + + pub fn compile_cells(cells: &[(&str, Option<&str>)]) -> Result { + Self::compile_cells_with(cells, None) + } + + fn compile_cells_with( + cells: &[(&str, Option<&str>)], + hints: Option<&Hints>, + ) -> Result { + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let mut roots = Vec::with_capacity(cells.len()); + for (index, (source, field)) in cells.iter().enumerate() { + let tokens = lexer.tokenize(&bump, source)?; + let parser = Parser::try_new(&tokens, &bump)?; + let root = match field { + Some(field) => { + let parsed = parser.unary().parse(); + parsed.error()?; + let tokens = lexer.tokenize(&bump, field)?; + let target = Parser::try_new(&tokens, &bump)?.standard().parse(); + target.error()?; + Self::rooted(&bump, parsed.root, target.root) + .ok_or_else(|| Self::unsupported("cell"))? + } + None => { + let parsed = parser.standard().parse(); + parsed.error()?; + parsed.root + } + }; + let key: &str = bump.alloc_str(&format!("c{index}")); + roots.push((key, root)); + } + let program = LaneCompiler::compile_isolated(&roots, hints)?; + let owned: Vec<(String, Option)> = cells + .iter() + .map(|(s, f)| (s.to_string(), f.map(str::to_string))) + .collect(); + Ok(Self { + program, + kind: ExpressionKind::Standard, + source: Source::Cells(owned.into()), + constant: None, + hints: None, + kernel: OnceLock::from(None), + }) + } + + fn unsupported(what: &str) -> IsolateError { + IsolateError::VMError { + source: crate::vm::VMError::OpcodeErr { + opcode: "Compile".to_string(), + message: format!("{what} is not supported in a combined cell program"), + }, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn rooted<'b>(bump: &'b Bump, node: &'b Node<'b>, root: &'b Node<'b>) -> Option<&'b Node<'b>> { + let map = |n: &'b Node<'b>| Self::rooted(bump, n, root); + let list = |items: &'b [&'b Node<'b>]| -> Option<&'b [&'b Node<'b>]> { + let mapped: Vec<&'b Node<'b>> = items.iter().map(|n| map(n)).collect::>()?; + Some(bump.alloc_slice_copy(&mapped)) + }; + let rebuilt = match node { + Node::Identifier("$") => return Some(root), + Node::Null + | Node::Bool(_) + | Node::Number(_) + | Node::String(_) + | Node::Pointer + | Node::Identifier(_) + | Node::Root => return Some(node), + Node::TemplateString(parts) => Node::TemplateString(list(parts)?), + Node::Array(items) => Node::Array(list(items)?), + Node::Object(pairs) => { + let mapped: Vec<(&'b Node<'b>, &'b Node<'b>)> = pairs + .iter() + .map(|(k, v)| Some((map(k)?, map(v)?))) + .collect::>()?; + Node::Object(bump.alloc_slice_copy(&mapped)) + } + Node::Closure { body, alias } => Node::Closure { + body: map(body)?, + alias: *alias, + }, + Node::Parenthesized(inner) => Node::Parenthesized(map(inner)?), + Node::Member { node, property } => Node::Member { + node: map(node)?, + property: map(property)?, + }, + Node::Slice { node, from, to } => Node::Slice { + node: map(node)?, + from: match from { + Some(n) => Some(map(n)?), + None => None, + }, + to: match to { + Some(n) => Some(map(n)?), + None => None, + }, + }, + Node::Interval { + left, + right, + left_bracket, + right_bracket, + } => Node::Interval { + left: map(left)?, + right: map(right)?, + left_bracket: *left_bracket, + right_bracket: *right_bracket, + }, + Node::Conditional { + condition, + on_true, + on_false, + } => Node::Conditional { + condition: map(condition)?, + on_true: map(on_true)?, + on_false: map(on_false)?, + }, + Node::Unary { node, operator } => Node::Unary { + node: map(node)?, + operator: *operator, + }, + Node::Binary { + left, + operator, + right, + } => Node::Binary { + left: map(left)?, + operator: *operator, + right: map(right)?, + }, + Node::FunctionCall { kind, arguments } => Node::FunctionCall { + kind: kind.clone(), + arguments: list(arguments)?, + }, + Node::MethodCall { + kind, + this, + arguments, + } => Node::MethodCall { + kind: kind.clone(), + this: map(this)?, + arguments: list(arguments)?, + }, + Node::Assignments { .. } | Node::Error { .. } => return None, + }; + Some(bump.alloc(rebuilt)) + } + + pub fn compile_typed( + source: &str, + kind: ExpressionKind, + input: &crate::variable::VariableType, + ) -> Result { + use crate::intellisense::scope::IntelliSenseScope; + use crate::intellisense::type_provider::TypesProvider; + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let tokens = lexer.tokenize(&bump, source)?; + let parser = Parser::try_new(&tokens, &bump)?; + let parsed = match kind { + ExpressionKind::Standard => parser.standard().parse(), + ExpressionKind::Unary => parser.unary().parse(), + }; + parsed.error()?; + let scope = IntelliSenseScope { + pointer_data: input.shallow_clone(), + root_data: input.shallow_clone(), + current_data: input.shallow_clone(), + ..Default::default() + }; + let types = TypesProvider::generate(parsed.root, scope, false); + let program = LaneCompiler::compile_typed(parsed.root, None, Some(&types))?; + Ok(Self { + program, + kind, + source: Source::Single(source.into()), + constant: None, + hints: None, + kernel: OnceLock::new(), + }) + } + + pub fn compile_fused(entries: &[Fusion]) -> Result { + Self::compile_fused_with(entries, None) + } + + fn compile_fused_with(entries: &[Fusion], hints: Option<&Hints>) -> Result { + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let mut roots: Vec<(&str, &Node, bool)> = Vec::with_capacity(entries.len()); + for entry in entries { + let (key, root, output) = match entry { + Fusion::Output { key, source } | Fusion::Hidden { key, source } => { + let tokens = lexer.tokenize(&bump, source)?; + let parsed = Parser::try_new(&tokens, &bump)?.standard().parse(); + parsed.error()?; + ( + key.as_str(), + parsed.root, + matches!(entry, Fusion::Output { .. }), + ) + } + Fusion::Rules { key, rules } => { + let mut targets: Vec<(&str, &Node)> = Vec::new(); + for (field, _) in rules.iter().flat_map(|(cells, _)| cells.iter()) { + if targets.iter().any(|(f, _)| *f == field.as_str()) { + continue; + } + let tokens = lexer.tokenize(&bump, field)?; + let parsed = Parser::try_new(&tokens, &bump)?.standard().parse(); + parsed.error()?; + targets.push((field.as_str(), parsed.root)); + } + let mut chain: &Node = bump.alloc(Node::Null); + for (cells, value) in rules.iter().rev() { + let tokens = lexer.tokenize(&bump, value)?; + let parsed = Parser::try_new(&tokens, &bump)?.standard().parse(); + parsed.error()?; + let on_true = parsed.root; + let mut condition: Option<&Node> = None; + for (field, cell) in cells { + let tokens = lexer.tokenize(&bump, cell)?; + let parsed = Parser::try_new(&tokens, &bump)?.unary().parse(); + parsed.error()?; + let closure = std::cell::Cell::new(false); + parsed.root.walk(|node| { + if matches!(node, Node::Closure { .. }) { + closure.set(true); + } + }); + if closure.get() { + return Err(Self::unsupported("closure in rule")); + } + let target = targets + .iter() + .find(|(f, _)| *f == field.as_str()) + .map(|(_, node)| *node) + .ok_or_else(|| Self::unsupported("rule"))?; + let test = Self::rooted(&bump, parsed.root, target) + .ok_or_else(|| Self::unsupported("rule"))?; + condition = Some(match condition { + None => test, + Some(left) => bump.alloc(Node::Binary { + left, + operator: crate::lexer::Operator::Logical( + crate::lexer::LogicalOperator::And, + ), + right: test, + }), + }); + } + chain = bump.alloc(Node::Conditional { + condition: condition.unwrap_or_else(|| bump.alloc(Node::Bool(true))), + on_true, + on_false: chain, + }); + } + (key.as_str(), chain, true) + } + }; + roots.push((key, root, output)); + } + let program = LaneCompiler::compile_named(&roots, hints)?; + Ok(Self { + program, + kind: ExpressionKind::Standard, + source: Source::Fused(entries.to_vec().into()), + constant: None, + hints: hints.map(|h| Arc::new(h.clone())), + kernel: OnceLock::from(None), + }) + } + + pub fn compile_many(entries: &[(&str, &str)], chain: bool) -> Result { + Self::compile_many_with(entries, chain, None) + } + + fn compile_many_with( + entries: &[(&str, &str)], + chain: bool, + hints: Option<&Hints>, + ) -> Result { + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let mut roots = Vec::with_capacity(entries.len()); + for (key, source) in entries { + let tokens = lexer.tokenize(&bump, source)?; + let parsed = Parser::try_new(&tokens, &bump)?.standard().parse(); + parsed.error()?; + roots.push((*key, parsed.root)); + } + let program = LaneCompiler::compile_many(&roots, chain, hints)?; + let owned: Vec<(String, String)> = entries + .iter() + .map(|(k, s)| (k.to_string(), s.to_string())) + .collect(); + Ok(Self { + program, + kind: ExpressionKind::Standard, + source: Source::Many(owned.into(), chain), + constant: None, + hints: hints.map(|h| Arc::new(h.clone())), + kernel: OnceLock::new(), + }) + } + + pub fn specialize(&self, samples: &[Scope]) -> Result { + let mut hints = Hints::default(); + for key in &self.program.keys { + let segments: Vec<&str> = key.split('.').collect(); + let mut counts = [0usize; 5]; + for scope in samples { + Self::observe(scope.base(), &segments, &mut counts); + } + if let Some(kind) = Self::vote(counts) { + hints.insert(key.clone(), kind); + } + } + self.recompile(&hints) + } + + fn vote(counts: [usize; 5]) -> Option { + let [num, bool, str, other, _] = counts; + let total = num + bool + str + other; + match total { + 0 => None, + _ if num * 2 > total => Some(Kind::Num), + _ if bool * 2 > total => Some(Kind::Bool), + _ if str * 2 > total => Some(Kind::Str), + _ => None, + } + } + + fn column_hint(columns: &Columns, key: &str) -> Option { + let segments: Vec<&str> = key.split('.').collect(); + for split in (1..=segments.len()).rev() { + let last = segments[split - 1]; + let (name, each) = match last.strip_suffix("[]") { + Some(name) => (name, true), + None => (last, false), + }; + let mut path = segments[..split - 1].join("."); + if !path.is_empty() { + path.push('.'); + } + path.push_str(name); + let Some(i) = columns.find(&path) else { + continue; + }; + let column = &columns.columns[i].1; + let rest = &segments[split..]; + if let (true, true, Values::List { child, .. }) = (each, rest.is_empty(), column.values) + { + return match child.kind() { + Kind::Dyn => None, + kind => Some(kind), + }; + } + if let (true, Values::List { child, .. }) = (each, column.values) { + let mut field = Some(child.column()); + for segment in rest { + field = field.and_then(|f| f.field(segment).copied()); + } + if let Some(field) = field { + return match field.kind() { + Kind::Dyn => None, + kind => Some(kind), + }; + } + } + let mut counts = [0usize; 5]; + for row in 0..columns.rows.min(256) { + let value = column.variable(row); + match (each, &value) { + (true, Variable::Array(items)) => { + for item in items.borrow().iter().take(64) { + Self::observe(item, rest, &mut counts); + } + } + (true, _) => {} + (false, v) => Self::observe(v, rest, &mut counts), + } + } + return Self::vote(counts); + } + None + } + + pub fn specialize_bound( + &self, + columns: &Columns, + bind: &dyn Fn(&str) -> Binding, + ) -> Result { + let mut hints = Hints::default(); + for key in &self.program.keys { + let kind = match bind(key) { + Binding::Column(i) => { + columns + .columns + .get(i) + .and_then(|(name, column)| match column.kind() { + Kind::Dyn => Self::column_hint(columns, name), + kind => Some(kind), + }) + } + _ => match columns.find(key).map(|i| columns.columns[i].1.kind()) { + Some(Kind::Dyn) | None => Self::column_hint(columns, key), + other => other, + }, + }; + if let Some(kind) = kind { + hints.insert(key.clone(), kind); + } + } + self.recompile(&hints) + } + + pub fn specialize_columns(&self, columns: &Columns) -> Result { + let mut hints = Hints::default(); + for key in &self.program.keys { + let exact = columns.find(key).map(|i| columns.columns[i].1.kind()); + let kind = match exact { + Some(Kind::Dyn) | None => Self::column_hint(columns, key), + other => other, + }; + if let Some(kind) = kind { + hints.insert(key.clone(), kind); + } + } + self.recompile(&hints) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn observe(value: &Variable, segments: &[&str], counts: &mut [usize; 5]) { + let Some((segment, rest)) = segments.split_first() else { + match value { + Variable::Number(_) => counts[0] += 1, + Variable::Bool(_) => counts[1] += 1, + Variable::String(_) => counts[2] += 1, + Variable::Null => counts[4] += 1, + _ => counts[3] += 1, + } + return; + }; + let (name, each) = match segment.strip_suffix("[]") { + Some(name) => (name, true), + None => (*segment, false), + }; + let next = match value { + Variable::Object(o) => o.borrow().get_str(name).cloned().unwrap_or(Variable::Null), + _ => Variable::Null, + }; + match (each, &next) { + (true, Variable::Array(items)) => { + for item in items.borrow().iter().take(64) { + Self::observe(item, rest, counts); + } + } + (true, _) => {} + (false, v) => Self::observe(v, rest, counts), + } + } + + pub fn object_fields(source: &str) -> Option> { + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let tokens = lexer.tokenize(&bump, source).ok()?; + let parsed = Parser::try_new(&tokens, &bump) + .ok()? + .with_metadata() + .standard() + .parse(); + parsed.error().ok()?; + let metadata = parsed.metadata.as_ref()?; + let Node::Object(pairs) = parsed.root else { + return None; + }; + let mut fields: Vec<(String, String)> = Vec::with_capacity(pairs.len()); + for (key, value) in pairs.iter() { + let Node::String(key) = key else { + return None; + }; + if key.is_empty() || key.contains('.') || fields.iter().any(|(k, _)| k == key) { + return None; + } + let (a, b) = metadata.get(&(*value as *const Node as usize))?.span; + let fragment = source.get(a as usize..b as usize)?; + let inner = Bump::new(); + let mut relexer = Lexer::new(); + let retokens = relexer.tokenize(&inner, fragment).ok()?; + let reparsed = Parser::try_new(&retokens, &inner).ok()?.standard().parse(); + if reparsed.error().is_err() || reparsed.root != *value { + return None; + } + fields.push((key.to_string(), fragment.to_string())); + } + Some(fields) + } + + pub fn standard(source: &str) -> Result { + Self::compile(source, ExpressionKind::Standard) + } + + pub fn unary(source: &str) -> Result { + Self::compile(source, ExpressionKind::Unary) + } + + pub fn kind(&self) -> &ExpressionKind { + &self.kind + } + + pub fn path(&self) -> Option<&str> { + let p = &self.program; + match (p.steps.as_slice(), &p.layout, p.outputs.is_empty()) { + ([step], None, true) => match &step.op { + Op::Env { dst, site, .. } | Op::Path { dst, site, .. } if *dst == p.out => { + p.site_keys.get(*site as usize)?.as_deref() + } + _ => None, + }, + _ => None, + } + } + + pub fn literal(&self) -> Option { + if let Some(constant) = &self.constant { + return Some(constant.variable()); + } + let p = &self.program; + match (p.steps.as_slice(), &p.layout, p.outputs.is_empty()) { + ([step], None, true) => match step.op { + Op::Const { dst, id } if dst == p.out => { + p.consts.get(id as usize).map(Const::variable) + } + _ => None, + }, + _ => None, + } + } + + pub fn program(&self) -> &Program { + &self.program + } + + pub fn without_kernel(&self) -> Self { + let mut program = self.clone(); + program.kernel = OnceLock::from(None); + program + } + + pub fn try_kernel(&self, scope: &Scope) -> Option { + self.kernel()?.run(scope) + } + + pub fn has_kernel(&self) -> bool { + self.kernel().is_some() + } + + fn kernel(&self) -> Option<&Kernel> { + self.kernel.get_or_init(|| self.build_kernel()).as_deref() + } + + fn build_kernel(&self) -> Option> { + if self.program.isolated { + return None; + } + let bump = Bump::new(); + let mut lexer = Lexer::new(); + match &self.source { + Source::Single(source) => { + let tokens = lexer.tokenize(&bump, source).ok()?; + let parser = Parser::try_new(&tokens, &bump).ok()?; + let parsed = match self.kind { + ExpressionKind::Standard => parser.standard().parse(), + ExpressionKind::Unary => parser.unary().parse(), + }; + parsed.error().ok()?; + Kernel::compile(parsed.root, self.hints.as_deref(), &self.program).map(Arc::new) + } + Source::Many(entries, chain) => { + let mut roots = Vec::with_capacity(entries.len()); + for (key, source) in entries.iter() { + let tokens = lexer.tokenize(&bump, source).ok()?; + let parsed = Parser::try_new(&tokens, &bump).ok()?.standard().parse(); + parsed.error().ok()?; + roots.push((key.as_str(), parsed.root)); + } + Kernel::compile_many(&roots, *chain, self.hints.as_deref(), &self.program) + .map(Arc::new) + } + Source::Cells(_) | Source::Fused(_) => None, + } + } +} + +#[derive(Debug, Default)] +pub struct LaneRunner { + frames: Vec>, + wide: Vec>, + rows: Vec, + scopes: Vec, +} + +impl LaneRunner { + pub fn new() -> Self { + Self::default() + } + + fn frames(&mut self, program: &Program) { + if self.frames.len() < program.frames { + self.frames.resize_with(program.frames, Frame::default); + } + } + + fn wide(&mut self, program: &Program) { + if self.wide.len() < program.frames { + self.wide.resize_with(program.frames, Frame::default); + } + } + + thread_local! { + static FOLD: std::cell::RefCell>> = Default::default(); + } + + pub(crate) fn constant(program: &Program) -> Option { + Self::FOLD.with_borrow_mut(|frames| { + if frames.len() < program.frames { + frames.resize_with(program.frames, Frame::default); + } + let roots = [Scope::default()]; + let mut ctx = Context::new(program, &roots); + Executor::run(program, frames, &mut ctx, &[0]); + frames.first_mut()?.take_result(program, 0).ok() + }) + } + + pub fn evaluate_one( + &mut self, + program: &LaneProgram, + scope: &Scope, + ) -> Result { + if let Some(value) = program.kernel().and_then(|k| k.run(scope)) { + return Ok(value); + } + let p = &program.program; + self.frames(p); + let roots = std::slice::from_ref(scope); + let mut ctx = Context::new(p, roots); + Executor::run(p, &mut self.frames, &mut ctx, &[0]); + self.frames[0] + .take_result(p, 0) + .map_err(|source| IsolateError::VMError { source }) + } + + pub fn evaluate( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + ) -> Vec> { + let mut out = Vec::with_capacity(scopes.len()); + self.evaluate_with(program, scopes, |_, r| out.push(r)); + out + } + + pub fn evaluate_with( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + mut sink: impl FnMut(usize, Result), + ) { + if let Some(kernel) = program.kernel() { + return self.evaluate_kernel(program, kernel, scopes, sink); + } + let p = &program.program; + self.frames(p); + for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() { + self.rows.clear(); + self.rows.extend(0..roots.len() as u32); + let mut ctx = Context::new(p, roots); + Executor::run(p, &mut self.frames, &mut ctx, &self.rows); + let frame = &mut self.frames[0]; + for lane in 0..roots.len() { + let result = frame + .take_result(p, lane) + .map_err(|source| IsolateError::VMError { source }); + sink(chunk * Word::LANES + lane, result); + } + } + } + + fn evaluate_kernel( + &mut self, + program: &LaneProgram, + kernel: &Kernel, + scopes: &[Scope], + mut sink: impl FnMut(usize, Result), + ) { + let p = &program.program; + let mut values: Vec> = Vec::with_capacity(Word::LANES); + let mut misses = 0usize; + for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() { + let start = chunk * Word::LANES; + values.clear(); + self.rows.clear(); + match misses * 4 > start.max(Word::LANES) { + true => self.rows.extend(0..roots.len() as u32), + false => { + for (lane, scope) in roots.iter().enumerate() { + let value = kernel.run(scope); + if value.is_none() { + self.rows.push(lane as u32); + } + values.push(value); + } + misses += self.rows.len(); + } + } + if self.rows.is_empty() { + for (lane, value) in values.drain(..).enumerate() { + sink(start + lane, Ok(value.unwrap_or_default())); + } + continue; + } + values.resize(roots.len(), None); + self.frames(p); + let mut ctx = Context::new(p, roots); + Executor::run(p, &mut self.frames, &mut ctx, &self.rows); + let frame = &mut self.frames[0]; + let mut slow = 0usize; + for (lane, value) in values.drain(..).enumerate() { + let result = match value { + Some(value) => Ok(value), + None => { + slow += 1; + frame + .take_result(p, slow - 1) + .map_err(|source| IsolateError::VMError { source }) + } + }; + sink(start + lane, result); + } + } + } + + const SMALL: usize = 4; + + pub fn evaluate_many( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + mask: Option<&[bool]>, + mut sink: impl FnMut(usize, Option, (usize, IsolateError)>>), + ) { + let Some(kernel) = program.kernel() else { + return self.evaluate_many_lane(program, scopes, mask, sink); + }; + let wanted = |row: usize| mask.is_none_or(|m| m.get(row).copied().unwrap_or(false)); + let mut values: Vec> = Vec::with_capacity(scopes.len()); + let mut slow = vec![false; scopes.len()]; + let (mut tried, mut misses) = (0usize, 0usize); + for (row, scope) in scopes.iter().enumerate() { + if !wanted(row) { + values.push(None); + continue; + } + let value = match tried >= Word::LANES && misses * 4 > tried { + true => None, + false => { + tried += 1; + kernel.run_all(scope, row, None, &[]) + } + }; + if value.is_none() { + misses += 1; + slow[row] = true; + } + values.push(value); + } + let mut lane: Vec, (usize, IsolateError)>>> = Vec::new(); + if slow.iter().any(|s| *s) { + lane.resize_with(scopes.len(), || None); + self.evaluate_many_lane(program, scopes, Some(&slow), |row, result| { + if let Some(slot) = lane.get_mut(row) { + *slot = result; + } + }); + } + for (row, value) in values.into_iter().enumerate() { + match (value, wanted(row)) { + (_, false) => sink(row, None), + (Some(value), true) => sink(row, Some(Ok(value.into_vec()))), + (None, true) => sink(row, lane.get_mut(row).and_then(Option::take)), + } + } + } + + fn kernel_rows( + kernel: &Kernel, + scopes: &[Scope], + columns: &Columns, + bound: &[Binding], + subset: Option<&[usize]>, + ) -> Option> { + let total = subset.map_or(scopes.len(), <[usize]>::len); + (0..total) + .map(|at| { + let row = subset.map_or(at, |list| list[at]); + let scope = scopes.get(row)?; + kernel + .run_all(scope, row, Some(columns), bound) + .map(|values| (row, values)) + }) + .collect() + } + + fn evaluate_many_lane( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + mask: Option<&[bool]>, + mut sink: impl FnMut(usize, Option, (usize, IsolateError)>>), + ) { + let p = &program.program; + self.frames(p); + for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() { + let start = chunk * Word::LANES; + self.rows.clear(); + self.rows.extend(0..roots.len() as u32); + let mut ctx = Context::new(p, roots); + let Some((frame, _)) = self.frames.split_first_mut() else { + return; + }; + Executor::enter_top(p, frame, &self.rows); + if let Some(mask) = mask { + let mut bits = Word::none(roots.len()); + for l in (0..roots.len()).filter(|l| mask.get(start + l).copied().unwrap_or(false)) + { + bits.set(l); + } + frame.restrict(bits); + } + Executor::execute_top(p, &mut self.frames, &mut ctx); + let frame = &mut self.frames[0]; + for lane in 0..roots.len() { + if !frame.active(lane) { + sink(start + lane, None); + continue; + } + let result = match frame.take_result(p, lane) { + Ok(_) => Ok(frame.outputs(p, lane)), + Err(source) => Err(( + frame.stage_of(lane) as usize, + IsolateError::VMError { source }, + )), + }; + sink(start + lane, Some(result)); + } + } + } + + pub fn evaluate_bound( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + columns: &Columns, + bind: &dyn Fn(&str) -> Binding, + subset: Option<&[usize]>, + mut sink: impl FnMut(usize, Result, (usize, IsolateError)>), + ) { + let p = &program.program; + let total = subset.map_or(scopes.len(), <[usize]>::len); + if let (true, Some(kernel)) = (total <= Self::SMALL, program.kernel()) { + let bound = kernel.bind(bind); + if let Some(rows) = Self::kernel_rows(kernel, scopes, columns, &bound, subset) { + let many = !p.outputs.is_empty(); + for (row, mut values) in rows { + let values = match many { + true => values.into_vec(), + false => values.pop().into_iter().collect(), + }; + sink(row, Ok(values)); + } + return; + } + } + let bound: Vec = p + .site_keys + .iter() + .map(|k| match (p.writes_env, k.as_deref()) { + (true, _) | (_, None) => Binding::Row, + (false, Some(k)) => bind(k), + }) + .collect(); + let total = subset.map_or(scopes.len(), <[usize]>::len); + match total <= Word::LANES { + true => { + self.frames(p); + self.frames.iter_mut().for_each(Frame::forget); + let (frames, rows) = (&mut self.frames, &mut self.rows); + Self::bound_blocks( + p, + frames, + rows, + scopes, + columns, + &bound, + subset, + Word::LANES, + &mut sink, + ); + } + false => { + self.wide(p); + self.wide.iter_mut().for_each(Frame::forget); + let (frames, rows) = (&mut self.wide, &mut self.rows); + Self::bound_blocks( + p, frames, rows, scopes, columns, &bound, subset, LANES, &mut sink, + ); + } + } + } + + #[allow(clippy::too_many_arguments)] + pub fn evaluate_bound_into( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + columns: &Columns, + bind: &dyn Fn(&str) -> Binding, + subset: Option<&[usize]>, + outs: &mut Vec, + failure: impl FnMut(usize, usize, Fault), + ) { + let p = &program.program; + let bound: Vec = p + .site_keys + .iter() + .map(|k| match (p.writes_env, k.as_deref()) { + (true, _) | (_, None) => Binding::Row, + (false, Some(k)) => bind(k), + }) + .collect(); + self.evaluate_sites(program, scopes, columns, &bound, subset, outs, failure) + } + + #[allow(clippy::too_many_arguments)] + pub fn evaluate_sites( + &mut self, + program: &LaneProgram, + scopes: &[Scope], + columns: &Columns, + bound: &[Binding], + subset: Option<&[usize]>, + outs: &mut Vec, + mut failure: impl FnMut(usize, usize, Fault), + ) { + let p = &program.program; + let total = subset.map_or(scopes.len(), <[usize]>::len); + let regs: Vec = match p.outputs.is_empty() { + true => vec![p.out], + false => p.outputs.clone(), + }; + let listed = p.layout.is_some() || regs.iter().any(|r| p.kinds[*r as usize] == Kind::List); + if let (true, false, Some(kernel)) = (total <= Self::SMALL, listed, program.kernel()) { + let kbound = kernel.bind_sites(bound); + if let Some(rows) = Self::kernel_rows(kernel, scopes, columns, &kbound, subset) { + outs.resize_with(regs.len(), Output::new); + for (reg, out) in regs.iter().zip(outs.iter_mut()) { + out.reset(p.kinds[*reg as usize], total); + } + for (at, (_, values)) in rows.into_iter().enumerate() { + let skip = values.len().saturating_sub(regs.len()); + for (out, value) in outs.iter_mut().zip(values.into_iter().skip(skip)) { + out.put(at, value); + } + } + return; + } + } + outs.resize_with(regs.len(), Output::new); + for (reg, out) in regs.iter().zip(outs.iter_mut()) { + match (&p.layout, p.outputs.is_empty()) { + (Some(layout), true) => out.reset_layout(layout, &p.kinds, total), + _ => out.reset(p.kinds[*reg as usize], total), + } + } + let mut sink = |at: usize, stage: usize, fault| failure(at, stage, fault); + match total <= Word::LANES { + true => { + self.frames(p); + self.frames.iter_mut().for_each(Frame::forget); + let (frames, rows) = (&mut self.frames, &mut self.rows); + Self::export_blocks( + p, + frames, + rows, + scopes, + columns, + bound, + subset, + Word::LANES, + outs, + &mut sink, + ); + } + false => { + self.wide(p); + self.wide.iter_mut().for_each(Frame::forget); + let (frames, rows) = (&mut self.wide, &mut self.rows); + Self::export_blocks( + p, frames, rows, scopes, columns, bound, subset, LANES, outs, &mut sink, + ); + } + } + } + + #[allow(clippy::too_many_arguments)] + fn export_blocks( + p: &Program, + frames: &mut [Frame], + rows: &mut Vec, + scopes: &[Scope], + columns: &Columns, + bound: &[Binding], + subset: Option<&[usize]>, + width: usize, + outs: &mut [Output], + sink: &mut dyn FnMut(usize, usize, Fault), + ) { + let total = subset.map_or(scopes.len(), <[usize]>::len); + let mut start = 0; + while start < total { + let n = (total - start).min(width); + rows.clear(); + let (roots, base) = match subset { + None => { + rows.extend(0..n as u32); + (&scopes[start..start + n], start) + } + Some(list) => { + rows.extend(list[start..start + n].iter().map(|&r| r as u32)); + (scopes, 0) + } + }; + let mut ctx = Context::columnar(p, roots, columns, bound, base); + Executor::run(p, frames, &mut ctx, rows); + let Some(frame) = frames.first_mut() else { + return; + }; + frame.export_outputs(p, outs, start, n, &mut *sink); + start += n; + } + } + + #[allow(clippy::too_many_arguments)] + fn bound_blocks( + p: &Program, + frames: &mut [Frame], + rows: &mut Vec, + scopes: &[Scope], + columns: &Columns, + bound: &[Binding], + subset: Option<&[usize]>, + width: usize, + sink: &mut impl FnMut(usize, Result, (usize, IsolateError)>), + ) { + let many = !p.outputs.is_empty(); + let total = subset.map_or(scopes.len(), <[usize]>::len); + let mut start = 0; + while start < total { + let n = (total - start).min(width); + rows.clear(); + let (roots, base) = match subset { + None => { + rows.extend(0..n as u32); + (&scopes[start..start + n], start) + } + Some(list) => { + rows.extend(list[start..start + n].iter().map(|&r| r as u32)); + (scopes, 0) + } + }; + let mut ctx = Context::columnar(p, roots, columns, bound, base); + Executor::run(p, frames, &mut ctx, rows); + let Some(frame) = frames.first_mut() else { + return; + }; + for lane in 0..n { + let row = match subset { + None => start + lane, + Some(list) => list[start + lane], + }; + let result = match frame.take_result(p, lane) { + Ok(value) => Ok(match many { + true => frame.outputs(p, lane), + false => vec![value], + }), + Err(source) => Err(( + frame.stage_of(lane) as usize, + IsolateError::VMError { source }, + )), + }; + sink(row, result); + } + start += n; + } + } + + pub fn evaluate_columns( + &mut self, + program: &LaneProgram, + columns: &Columns, + mut sink: impl FnMut(usize, Result), + ) { + let p = &program.program; + self.columnar(p, columns, |frame, start, n| { + for lane in 0..n { + let result = frame + .take_result(p, lane) + .map_err(|source| IsolateError::VMError { source }); + sink(start + lane, result); + } + }); + } + + pub fn evaluate_columns_into( + &mut self, + program: &LaneProgram, + columns: &Columns, + out: &mut Output, + ) { + let p = &program.program; + match &p.layout { + Some(layout) => out.reset_layout(layout, &p.kinds, columns.rows), + None => out.reset(p.kinds[p.out as usize], columns.rows), + } + self.columnar(p, columns, |frame, start, n| frame.export(p, out, start, n)); + } + + pub fn evaluate_columns_many( + &mut self, + program: &LaneProgram, + columns: &Columns, + outs: &mut Vec, + mut failure: impl FnMut(usize, usize, Fault), + ) { + let p = &program.program; + let regs: &[Reg] = match p.outputs.is_empty() { + true => std::slice::from_ref(&p.out), + false => &p.outputs, + }; + outs.resize_with(regs.len(), Output::new); + for (reg, out) in regs.iter().zip(outs.iter_mut()) { + match (&p.layout, p.outputs.is_empty()) { + (Some(layout), true) => out.reset_layout(layout, &p.kinds, columns.rows), + _ => out.reset(p.kinds[*reg as usize], columns.rows), + } + } + self.columnar(p, columns, |frame, start, n| { + frame.export_outputs(p, outs, start, n, &mut failure) + }); + } + + fn columnar( + &mut self, + p: &Program, + columns: &Columns, + mut chunk: impl FnMut(&mut Frame, usize, usize), + ) { + self.wide(p); + let bound: Vec = p + .site_keys + .iter() + .map(|k| match (p.writes_env, k.as_deref()) { + (true, _) | (_, None) => Binding::Row, + (false, Some(k)) => columns.bind(k), + }) + .collect(); + let rows = p.needs_rows(&bound); + let roots = match rows { + true => p.row_roots(&bound), + false => None, + }; + self.wide.iter_mut().for_each(Frame::forget); + let mut start = 0; + while start < columns.rows { + let n = (columns.rows - start).min(LANES); + self.rows.clear(); + self.rows.extend(0..n as u32); + self.scopes.clear(); + if rows { + self.scopes.extend((start..start + n).map(|r| { + Scope::new(match &roots { + Some(roots) => columns.row_of(roots, r), + None => columns.row(r), + }) + })); + } + let mut ctx = Context::columnar(p, &self.scopes, columns, &bound, start); + Executor::run(p, &mut self.wide, &mut ctx, &self.rows); + chunk(&mut self.wide[0], start, n); + start += n; + } + } +} + +#[derive(Debug, Default)] +pub(crate) struct Backend { + standard: ahash::HashMap, + unary: ahash::HashMap, +} + +impl Backend { + thread_local! { + static RUNNER: std::cell::RefCell = std::cell::RefCell::new(LaneRunner::new()); + } + + pub(crate) fn run( + &mut self, + source: &str, + kind: ExpressionKind, + scope: &Scope, + ) -> Result { + let programs = match kind { + ExpressionKind::Standard => &mut self.standard, + ExpressionKind::Unary => &mut self.unary, + }; + if !programs.contains_key(source) { + let program = LaneProgram::compile(source, kind)?; + programs.insert(source.to_string(), program); + } + let program = &programs[source]; + let mut runner = Self::RUNNER.take(); + let result = runner.evaluate_one(program, scope); + Self::RUNNER.set(runner); + result + } +} diff --git a/core/expression/src/lane/ops.rs b/core/expression/src/lane/ops.rs new file mode 100644 index 00000000..9a4b5fe4 --- /dev/null +++ b/core/expression/src/lane/ops.rs @@ -0,0 +1,433 @@ +use crate::compiler::{Compare, FetchFastTarget}; +use crate::lane::builtins::{Arg, Builtins, Out, Text}; +use crate::lane::date::{Date, DynamicVariableExt}; +use crate::lane::interval::{Interval, IntervalData}; +use crate::lexer::Bracket; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::variable::Variable::*; +use crate::vm::VMError; +use crate::vm::VMError::*; +use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; +use rust_decimal::{Decimal, MathematicalOps}; +use std::rc::Rc; +use std::string::String as StdString; +use zen_types::symbol::Symbol; + +pub(crate) struct Ops; + +type VMResult = Result; + +impl Ops { + pub(crate) fn error(opcode: &str, message: impl Into) -> VMError { + OpcodeErr { + opcode: opcode.into(), + message: message.into(), + } + } + + pub(crate) fn unsupported(opcode: &str) -> VMError { + Self::error(opcode, "Unsupported type") + } + + pub(crate) fn fetch(a: Variable, b: Variable) -> VMResult { + 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() + .ok_or_else(|| Self::error("Fetch", "Failed to convert to usize"))?; + Ok(a.borrow().get(index).cloned().unwrap_or(Null)) + } + (String(str), Number(n)) => { + let index = n + .to_usize() + .ok_or_else(|| Self::error("Fetch", "Failed to convert to usize"))?; + let slice = index.checked_add(1).and_then(|end| str.get(index..end)); + Ok(slice.map_or(Null, |s| String(s.into()))) + } + _ => Ok(Null), + } + } + + pub(crate) fn step( + v: Variable, + target: &FetchFastTarget, + root: &Scope, + env: &Scope, + ) -> Variable { + match target { + FetchFastTarget::Root => root.materialize(), + FetchFastTarget::Begin => env.materialize(), + FetchFastTarget::String(key) => match v { + Object(obj) => obj.borrow().get_str(key).cloned().unwrap_or(Null), + _ => Null, + }, + FetchFastTarget::Number(num) => match Date::textual(v) { + Array(arr) => arr.borrow().get(*num as usize).cloned().unwrap_or(Null), + String(str) => { + let index = *num as usize; + str.get(index..index + 1) + .map(|slice| String(slice.into())) + .unwrap_or(Null) + } + _ => Null, + }, + } + } + + pub(crate) fn fetch_fast(path: &[FetchFastTarget], root: &Scope, env: &Scope) -> Variable { + let mut steps = path.iter(); + let first = match steps.next() { + Some(FetchFastTarget::Root) => root.materialize(), + Some(FetchFastTarget::Begin) => match steps.clone().next() { + Some(FetchFastTarget::String(key)) => { + steps.next(); + env.get_str(key).unwrap_or(Null) + } + _ => env.materialize(), + }, + _ => Null, + }; + + steps.fold(first, |v, p| Self::step(v, p, root, env)) + } + + pub(crate) fn negate(a: Variable) -> VMResult { + match a { + Number(n) => Ok(Number(-n)), + _ => Err(Self::unsupported("Negate")), + } + } + + pub(crate) fn not(a: Variable) -> VMResult { + match a { + Bool(b) => Ok(Bool(!b)), + _ => Err(Self::unsupported("Not")), + } + } + + pub(crate) fn equal(a: &Variable, b: &Variable) -> bool { + match (a, b) { + (Number(a), Number(b)) => Self::same_number(a, b), + (Bool(a), Bool(b)) => a == b, + (String(a), String(b)) => a == b, + (Null, Null) => true, + (Dynamic(a), Dynamic(b)) => { + let (a, b) = (a.as_date(), b.as_date()); + a.is_some() && b.is_some() && a == b + } + (Dynamic(a), b @ String(_)) | (b @ String(_), Dynamic(a)) => { + a.as_date().is_some_and(|a| a.matches(b)) + } + _ => false, + } + } + + pub(crate) fn truthy(a: &Variable, opcode: &str) -> VMResult { + match a { + Bool(b) => Ok(*b), + _ => Err(Self::unsupported(opcode)), + } + } + + pub(crate) fn membership(a: Variable, b: &Variable) -> VMResult { + let a = match b { + Object(_) => Date::textual(a), + _ => a, + }; + match (a, b) { + (Number(a), Array(b)) => Ok(b + .borrow() + .iter() + .any(|b| matches!(b, Number(b) if Self::same_number(&a, b)))), + (Number(v), Dynamic(d)) => { + let Some(i) = d.as_any().downcast_ref::() else { + return Err(Self::unsupported("In")); + }; + i.includes(IntervalData::Number(v)) + .map_err(|err| Self::error("In", err.to_string())) + } + (Dynamic(d), Dynamic(i)) => { + let Some(d) = d.as_date() else { + return Err(Self::unsupported("In")); + }; + let Some(i) = i.as_any().downcast_ref::() else { + return Err(Self::unsupported("In")); + }; + i.includes(IntervalData::Date(d)) + .map_err(|err| Self::error("In", err.to_string())) + } + (Dynamic(a), Array(arr)) => { + let Some(a) = a.as_date() else { + return Err(Self::unsupported("In")); + }; + Ok(arr.borrow().iter().any(|b| a.matches(b))) + } + (String(a), Array(b)) => { + let text = String(a.clone()); + Ok(b.borrow().iter().any(|b| match b { + String(b) => &a == b, + Dynamic(d) => d.as_date().is_some_and(|d| d.matches(&text)), + _ => false, + })) + } + (String(a), Object(b)) => Ok(b.borrow().contains_key_str(a.as_str())), + (Bool(a), Array(b)) => Ok(b.borrow().iter().any(|b| matches!(b, Bool(b) if a == *b))), + (Null, Array(b)) => Ok(b.borrow().iter().any(|b| matches!(b, Null))), + _ => Err(Self::unsupported("In")), + } + } + + #[inline] + pub(crate) fn order(a: &Decimal, b: &Decimal) -> std::cmp::Ordering { + match a.scale() == b.scale() { + true => a.mantissa().cmp(&b.mantissa()), + false => a.cmp(b), + } + } + + #[inline] + pub(crate) fn same_number(a: &Decimal, b: &Decimal) -> bool { + Self::order(a, b).is_eq() + } + + #[inline] + pub(crate) fn ordered_number(a: &Decimal, b: &Decimal, comparison: Compare) -> bool { + let o = Self::order(a, b); + match comparison { + Compare::More => o.is_gt(), + Compare::MoreOrEqual => o.is_ge(), + Compare::Less => o.is_lt(), + Compare::LessOrEqual => o.is_le(), + } + } + + pub(crate) fn ordered(a: &T, b: &T, comparison: Compare) -> bool { + match comparison { + Compare::More => a > b, + Compare::MoreOrEqual => a >= b, + Compare::Less => a < b, + Compare::LessOrEqual => a <= b, + } + } + + pub(crate) fn compared(a: &Variable, b: &Variable, comparison: Compare) -> Option { + match (a, b) { + (Number(a), Number(b)) => Some(Self::ordered_number(a, b, comparison)), + (Dynamic(_), _) | (_, Dynamic(_)) => Self::compare(a, b, comparison).ok(), + _ => None, + } + } + + pub(crate) fn compare(a: &Variable, b: &Variable, comparison: Compare) -> VMResult { + match (a, b) { + (Number(a), Number(b)) => Ok(Self::ordered_number(a, b, comparison)), + (Dynamic(a), Dynamic(b)) => match (a.as_date(), b.as_date()) { + (Some(a), Some(b)) => Ok(Self::ordered(&a, &b, comparison)), + _ => Err(Self::unsupported("Compare")), + }, + (Dynamic(_), String(_)) | (String(_), Dynamic(_)) => { + let valid = |date: &Date| date.is_valid(); + match (Date::coerce(a).filter(valid), Date::coerce(b).filter(valid)) { + (Some(a), Some(b)) => Ok(Self::ordered(&a, &b, comparison)), + _ => Err(Self::unsupported("Compare")), + } + } + _ => Err(Self::unsupported("Compare")), + } + } + + pub(crate) fn add(a: Variable, b: Variable) -> VMResult { + match (Date::textual(a), Date::textual(b)) { + (Number(a), Number(b)) => a + .checked_add(b) + .map(Number) + .ok_or_else(|| Self::error("Add", "Number overflow")), + (String(a), String(b)) => { + let mut c = StdString::with_capacity(a.len() + b.len()); + c.push_str(a.as_ref()); + c.push_str(b.as_ref()); + Ok(String(c.as_str().into())) + } + _ => Err(Self::unsupported("Add")), + } + } + + pub(crate) fn subtract(a: Variable, b: Variable) -> VMResult { + match (a, b) { + (Number(a), Number(b)) => a + .checked_sub(b) + .map(Number) + .ok_or_else(|| Self::error("Subtract", "Number overflow")), + _ => Err(Self::unsupported("Subtract")), + } + } + + pub(crate) fn multiply(a: Variable, b: Variable) -> VMResult { + match (a, b) { + (Number(a), Number(b)) => a + .checked_mul(b) + .map(Number) + .ok_or_else(|| Self::error("Multiply", "Number overflow")), + _ => Err(Self::unsupported("Multiply")), + } + } + + pub(crate) fn divide(a: Variable, b: Variable) -> VMResult { + match (a, b) { + (Number(a), Number(b)) => Ok(a.checked_div(b).map_or(Null, Number)), + _ => Err(Self::unsupported("Divide")), + } + } + + pub(crate) fn modulo(a: Variable, b: Variable) -> VMResult { + match (a, b) { + (Number(a), Number(b)) => Ok(a.checked_rem(b).map_or(Null, Number)), + _ => Err(Self::unsupported("Modulo")), + } + } + + pub(crate) fn exponent(a: Variable, b: Variable) -> VMResult { + match (a, b) { + (Number(a), Number(b)) => a + .checked_powd(b) + .or_else(|| Decimal::from_f64(a.to_f64()?.powf(b.to_f64()?))) + .map(Number) + .ok_or_else(|| Self::error("Exponent", "Failed to calculate exponent")), + _ => Err(Self::unsupported("Exponent")), + } + } + + pub(crate) fn interval( + a: &Variable, + b: &Variable, + left_bracket: Bracket, + right_bracket: Bracket, + ) -> VMResult { + let (left, right) = match (a, b) { + (Number(a), Number(b)) => (IntervalData::Number(*a), IntervalData::Number(*b)), + (Dynamic(a), Dynamic(b)) => match (a.as_date(), b.as_date()) { + (Some(a), Some(b)) => (IntervalData::Date(a), IntervalData::Date(b)), + _ => return Err(Self::unsupported("Interval")), + }, + _ => return Err(Self::unsupported("Interval")), + }; + + Ok(Dynamic(Rc::new(Interval { + left_bracket, + right_bracket, + left, + right, + }))) + } + + pub(crate) fn slice(current: Variable, to: Variable, from: Variable) -> VMResult { + let (Number(f), Number(t)) = (from, to) else { + return Err(Self::unsupported("Slice")); + }; + + let from = f + .to_usize() + .ok_or_else(|| Self::error("Slice", "Failed to get range from"))?; + let to = t + .to_usize() + .ok_or_else(|| Self::error("Slice", "Failed to get range to"))?; + + match Date::textual(current) { + Array(a) => { + let arr = a.borrow(); + let slice = arr + .get(from..=to) + .ok_or_else(|| Self::error("Slice", "Index out of range"))?; + Ok(Variable::from_array(slice.to_vec())) + } + String(s) => { + let slice = s + .get(from..=to) + .ok_or_else(|| Self::error("Slice", "Index out of range"))?; + Ok(String(slice.into())) + } + _ => Err(Self::unsupported("Slice")), + } + } + + pub(crate) fn object_key(key: Variable) -> VMResult { + match key { + String(key) => Ok(Symbol::from(key.as_str())), + _ => Err(Self::error("Object", "Unexpected key value")), + } + } + + pub(crate) fn assigned_key(key: Variable) -> VMResult { + match key { + String(key) => Ok(key), + _ => Err(Self::error("AssignedObjectStep", "Unexpected key value")), + } + } + + pub(crate) fn assign( + env: &mut Scope, + assigned: &Variable, + key: &Symbol, + value: Variable, + ) -> VMResult<()> { + if !matches!(env.base(), Object(_)) { + return Err(Self::error( + "AssignedObjectStep", + "Failed to mutate existing env", + )); + } + + match key.contains('.') { + false => env.set_local(Symbol::from(key.as_str()), value.clone()), + true => { + let Some(new_env) = env + .materialize() + .dot_insert_detached(key.as_ref(), value.clone()) + else { + return Err(Self::error( + "AssignedObjectStep", + "Failed to mutate existing env", + )); + }; + *env = Scope::new(new_env); + } + } + + assigned.dot_insert(key.as_ref(), value); + Ok(()) + } + + pub(crate) fn len(current: &Variable) -> VMResult { + Builtins::raw(&Text::LEN, &[Arg::of(current)]) + .map(Out::variable) + .map_err(|message| Self::error("Len", message)) + } + + pub(crate) fn flatten(current: Variable) -> VMResult { + let Array(a) = current else { + return Err(Self::unsupported("Flatten")); + }; + + let arr = a.borrow(); + let mut flat = Vec::with_capacity(arr.len()); + arr.iter().for_each(|v| match v { + Array(b) => b.borrow().iter().for_each(|v| flat.push(v.clone())), + _ => flat.push(v.clone()), + }); + + Ok(Variable::from_array(flat)) + } + + pub(crate) fn elements(list: &Variable) -> VMResult { + match list { + Array(_) => Ok(list.clone()), + _ => list + .dynamic::() + .and_then(|s| s.to_array()) + .map(Variable::from_array) + .ok_or_else(|| Self::unsupported("Begin")), + } + } +} diff --git a/core/expression/src/lane/output.rs b/core/expression/src/lane/output.rs new file mode 100644 index 00000000..fb87bee7 --- /dev/null +++ b/core/expression/src/lane/output.rs @@ -0,0 +1,806 @@ +use crate::lane::date::Date; +use crate::lane::program::{Kind, Layout}; +use crate::lane::Bits; +use crate::variable::{Variable, VariableMap}; +use crate::vm::VMError; +use chrono::DateTime; +use chrono_tz::Tz; +use rust_decimal::Decimal; +use std::sync::Arc; +use zen_types::symbol::Symbol; + +#[derive(Debug)] +pub enum Cell<'a> { + Number(Decimal), + Bool(bool), + Str(&'a str), + Date(Option>), + Value(&'a Variable), + Struct(&'a [(Arc, Output)], usize), + List(&'a Output, usize, usize), + Error(&'a VMError), +} + +#[derive(Debug, Clone)] +pub(crate) enum Item { + Num(i64, u8), + Text(u32, u32), + Bool(bool), + Value(Variable), + Row(u32), +} + +impl Item { + pub(crate) fn variable(&self, arena: &str) -> Variable { + match self { + Item::Num(m, s) => Variable::Number(Decimal::new(*m, *s as u32)), + Item::Text(a, b) => Variable::String(Symbol::from( + arena.get(*a as usize..*b as usize).unwrap_or_default(), + )), + Item::Bool(b) => Variable::Bool(*b), + Item::Value(v) => v.clone(), + Item::Row(_) => Variable::Null, + } + } +} + +#[derive(Debug, Default)] +pub(crate) struct Items { + tags: Vec, + payload: Vec, + scales: Vec, + values: Vec, +} + +impl Items { + const NUM: u8 = 0; + const TEXT: u8 = 1; + const BOOL: u8 = 2; + const VALUE: u8 = 3; + const ROW: u8 = 4; + + pub(crate) fn len(&self) -> usize { + self.tags.len() + } + + pub(crate) fn clear(&mut self) { + self.tags.clear(); + self.payload.clear(); + self.scales.clear(); + self.values.clear(); + } + + pub(crate) fn truncate(&mut self, len: usize) { + self.tags.truncate(len); + self.payload.truncate(len); + self.scales.truncate(len); + let kept = self.tags.iter().filter(|t| **t == Self::VALUE).count(); + self.values.truncate(kept); + } + + pub(crate) fn push(&mut self, item: Item) { + let (tag, payload, scale) = match item { + Item::Num(m, s) => (Self::NUM, m, s), + Item::Text(a, b) => (Self::TEXT, ((a as i64) << 32) | b as i64, 0), + Item::Bool(b) => (Self::BOOL, b as i64, 0), + Item::Value(v) => { + self.values.push(v); + (Self::VALUE, self.values.len() as i64 - 1, 0) + } + Item::Row(index) => (Self::ROW, index as i64, 0), + }; + self.tags.push(tag); + self.payload.push(payload); + self.scales.push(scale); + } + + pub(crate) fn extend_nums(&mut self, mant: &[i64], scales: &[u8]) { + self.tags.resize(self.tags.len() + mant.len(), Self::NUM); + self.payload.extend_from_slice(mant); + self.scales.extend_from_slice(scales); + } + + pub(crate) fn get(&self, index: usize) -> Item { + let (Some(tag), Some(payload), Some(scale)) = ( + self.tags.get(index), + self.payload.get(index), + self.scales.get(index), + ) else { + return Item::Value(Variable::Null); + }; + match *tag { + Self::NUM => Item::Num(*payload, *scale), + Self::TEXT => Item::Text((*payload >> 32) as u32, *payload as u32), + Self::BOOL => Item::Bool(*payload != 0), + Self::ROW => Item::Row(*payload as u32), + _ => Item::Value( + self.values + .get(*payload as usize) + .cloned() + .unwrap_or(Variable::Null), + ), + } + } + + pub(crate) fn row(&self, index: usize) -> Option { + match self.tags.get(index) { + Some(&Self::ROW) => self.payload.get(index).map(|p| *p as u32), + _ => None, + } + } + + pub(crate) fn number(&self, index: usize) -> Option<(i64, u8)> { + match self.tags.get(index) { + Some(&Self::NUM) => Some((*self.payload.get(index)?, *self.scales.get(index)?)), + _ => None, + } + } + + pub(crate) fn extend_selected(&mut self, values: &[i64], truths: &[u64], a: usize, b: usize) { + let (Some(values), Some(words)) = (values.get(a..b), truths.get(a / 64..b.div_ceil(64))) + else { + return; + }; + let start = self.payload.len(); + self.payload.resize(start + values.len() + 1, 0); + let (out, first) = (&mut self.payload[start..], a / 64); + let mut k = 0; + for (i, v) in (a..b).zip(values) { + out[k] = *v; + k += ((words[i / 64 - first] >> (i % 64)) & 1) as usize; + } + self.payload.truncate(start + k); + self.tags.resize(start + k, Self::NUM); + self.scales.resize(start + k, 0); + } + + pub(crate) fn extend_parts(&mut self, parts: impl Iterator>) -> bool { + let start = self.payload.len(); + for part in parts { + let Some((m, s)) = part else { + self.payload.truncate(start); + self.scales.truncate(start); + return false; + }; + self.payload.push(m); + self.scales.push(s); + } + self.tags.resize(self.payload.len(), Self::NUM); + true + } + + pub(crate) fn extend_rows(&mut self, truths: &[u64], a: usize, b: usize, offset: usize) { + let Some(words) = truths.get(a / 64..b.div_ceil(64)) else { + return; + }; + let start = self.payload.len(); + self.payload.resize(start + (b - a) + 1, 0); + let (out, first) = (&mut self.payload[start..], a / 64); + let mut k = 0; + for i in a..b { + out[k] = (offset + i) as i64; + k += ((words[i / 64 - first] >> (i % 64)) & 1) as usize; + } + self.payload.truncate(start + k); + self.tags.resize(start + k, Self::ROW); + self.scales.resize(start + k, 0); + } + + pub(crate) fn rows(&self, a: usize, b: usize) -> Option<&[i64]> { + let tags = self.tags.get(a..b)?; + tags.iter() + .all(|t| *t == Self::ROW) + .then(|| self.payload.get(a..b)) + .flatten() + } + + pub(crate) fn numbers(&self, a: usize, b: usize) -> Option<(&[i64], &[u8])> { + let tags = self.tags.get(a..b)?; + tags.iter() + .all(|t| *t == Self::NUM) + .then(|| self.payload.get(a..b).zip(self.scales.get(a..b))) + .flatten() + } + + pub(crate) fn variable(&self, index: usize, arena: &str) -> Variable { + self.get(index).variable(arena) + } +} + +#[derive(Debug, Default)] +pub enum Shape { + #[default] + Scalar, + Struct(Vec<(Arc, Output)>), + List(Box), +} + +#[derive(Debug)] +pub struct Output { + rows: usize, + kind: Kind, + pending: bool, + pub(crate) shape: Shape, + pub(crate) mant: Vec, + pub(crate) scale: Vec, + pub(crate) dates: Vec>>, + pub(crate) bits: Vec, + pub(crate) boxed: Vec, + pub(crate) failed: Vec, + pub(crate) values: Vec, + pub(crate) offsets: Vec, + pub(crate) data: Vec, + pub(crate) extra: Vec<(u32, Variable)>, + pub(crate) errors: Vec<(u32, Failure)>, + prefer: bool, + coding: bool, + coded: Coded, +} + +#[derive(Debug, Default)] +struct Coded { + keys: Vec, + offsets: Vec, + data: String, +} + +impl Coded { + const CAP: usize = 64; + + fn clear(&mut self) { + self.keys.clear(); + self.offsets.clear(); + self.offsets.push(0); + self.data.clear(); + } + + fn entry(&self, code: usize) -> Option<&str> { + let (a, b) = ( + *self.offsets.get(code)? as usize, + *self.offsets.get(code + 1)? as usize, + ); + self.data.get(a..b) + } + + fn intern(&mut self, text: &str) -> Option { + let count = self.offsets.len() - 1; + if let Some(code) = (0..count).find(|&code| self.entry(code) == Some(text)) { + return Some(code as i32); + } + if count >= Self::CAP { + return None; + } + self.data.push_str(text); + self.offsets.push(self.data.len() as i32); + Some(count as i32) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct Failure { + fault: crate::lane::exec::Fault, + error: std::cell::OnceCell, +} + +impl Failure { + pub(crate) fn new(fault: crate::lane::exec::Fault) -> Self { + Self { + fault, + error: std::cell::OnceCell::new(), + } + } + + fn error(&self) -> &VMError { + self.error.get_or_init(|| self.fault.clone().vm()) + } +} + +impl Default for Output { + fn default() -> Self { + Self { + rows: 0, + kind: Kind::Dyn, + pending: false, + shape: Shape::Scalar, + mant: Vec::new(), + scale: Vec::new(), + dates: Vec::new(), + bits: Vec::new(), + boxed: Vec::new(), + failed: Vec::new(), + values: Vec::new(), + offsets: Vec::new(), + data: Vec::new(), + extra: Vec::new(), + errors: Vec::new(), + prefer: false, + coding: false, + coded: Coded::default(), + } + } +} + +impl Output { + pub fn new() -> Self { + Self::default() + } + + pub(crate) fn reset(&mut self, kind: Kind, rows: usize) { + let words = rows.div_ceil(64); + self.rows = rows; + self.kind = kind; + self.pending = false; + let child = match std::mem::take(&mut self.shape) { + Shape::List(child) => Some(child), + _ => None, + }; + self.mant.clear(); + self.scale.clear(); + self.dates.clear(); + self.values.clear(); + self.offsets.clear(); + self.data.clear(); + self.extra.clear(); + self.errors.clear(); + self.coding = self.prefer && kind == Kind::Str; + if self.coding { + self.coded.clear(); + } + match kind { + Kind::Num => { + self.mant.resize(rows, 0); + self.scale.resize(rows, 0); + } + Kind::Dyn => self.values.resize(rows, Variable::Null), + Kind::Str => { + self.offsets.reserve(rows + 1); + self.data.reserve(rows * 4); + self.offsets.push(0) + } + Kind::Date => self.dates.resize(rows, None), + Kind::Bool => {} + Kind::List => { + self.offsets.push(0); + let mut child = child.unwrap_or_default(); + child.open(); + self.shape = Shape::List(child); + } + } + for bits in [&mut self.bits, &mut self.boxed, &mut self.failed] { + bits.clear(); + bits.resize(words, 0); + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(crate) fn reset_layout(&mut self, layout: &Layout, kinds: &[Kind], rows: usize) { + match layout { + Layout::Value(reg) => self.reset(kinds[*reg as usize], rows), + Layout::Struct(fields) => { + self.reset(Kind::Bool, rows); + let mut outputs = match std::mem::take(&mut self.shape) { + Shape::Struct(outputs) if outputs.len() == fields.len() => outputs, + _ => fields + .iter() + .map(|(k, _)| (k.clone(), Output::new())) + .collect(), + }; + for ((key, output), (name, field)) in outputs.iter_mut().zip(fields.iter()) { + key.clone_from(name); + output.reset_layout(field, kinds, rows); + } + self.shape = Shape::Struct(outputs); + } + Layout::List(items) => { + let mut child = match std::mem::take(&mut self.shape) { + Shape::List(child) => child, + _ => Box::default(), + }; + self.reset(Kind::Bool, rows); + let width = items.len(); + match Self::uniform(items, kinds) { + Some(kind) => child.reset(kind, rows * width), + None => child.reset(Kind::Dyn, rows * width), + } + self.offsets.extend((0..=rows).map(|r| (r * width) as u32)); + self.shape = Shape::List(child); + } + } + } + + fn open(&mut self) { + self.reset(Kind::Dyn, 0); + self.pending = true; + } + + fn grow(&mut self) -> usize { + let row = self.rows; + self.rows += 1; + if row.is_multiple_of(64) { + for bits in [&mut self.bits, &mut self.boxed, &mut self.failed] { + bits.push(0); + } + } + row + } + + pub(crate) fn extend_nums(&mut self, mant: &[i64], scales: &[u8]) { + if self.pending { + self.pending = false; + self.kind = Kind::Num; + } + if self.kind != Kind::Num { + for (m, s) in mant.iter().zip(scales) { + self.push_item(&Item::Num(*m, *s), ""); + } + return; + } + self.rows += mant.len(); + let words = self.rows.div_ceil(64); + for bits in [&mut self.bits, &mut self.boxed, &mut self.failed] { + bits.resize(words, 0); + } + self.mant.extend_from_slice(mant); + self.scale.extend_from_slice(scales); + } + + pub(crate) fn push_item(&mut self, item: &Item, arena: &str) { + if self.pending { + self.pending = false; + self.kind = match item { + Item::Num(..) => Kind::Num, + Item::Text(..) => { + self.offsets.push(0); + Kind::Str + } + Item::Bool(_) => Kind::Bool, + Item::Value(_) | Item::Row(_) => Kind::Dyn, + }; + } + let row = self.grow(); + match (self.kind, item) { + (Kind::Num, Item::Num(m, s)) => { + self.mant.push(*m); + self.scale.push(*s); + } + (Kind::Str, Item::Text(a, b)) => { + self.push_text(arena.get(*a as usize..*b as usize).unwrap_or_default()) + } + (Kind::Bool, Item::Bool(b)) => self.set_bit(row, *b), + (Kind::Dyn, item) => self.values.push(item.variable(arena)), + (kind, item) => { + match kind { + Kind::Num => { + self.mant.push(0); + self.scale.push(0); + } + Kind::Date => self.dates.push(None), + _ => {} + } + self.box_at(row, item.variable(arena)); + } + } + } + + pub(crate) fn extend_lists( + &mut self, + mant: &[i64], + scales: &[u8], + ends: impl Iterator, + ) -> bool { + let Shape::List(child) = &mut self.shape else { + return false; + }; + let base = child.rows as u32; + child.extend_nums(mant, scales); + self.offsets.extend(ends.map(|end| base + end)); + true + } + + pub(crate) fn close(&mut self) { + if let Shape::List(child) = &self.shape { + self.offsets.push(child.rows as u32); + } + } + + pub(crate) fn uniform(items: &[Layout], kinds: &[Kind]) -> Option { + let mut kinds = items.iter().map(|item| match item { + Layout::Value(reg) => Some(kinds[*reg as usize]), + _ => None, + }); + let first = kinds.next().flatten()?; + kinds.all(|k| k == Some(first)).then_some(first) + } + + pub fn len(&self) -> usize { + self.rows + } + + pub fn is_empty(&self) -> bool { + self.rows == 0 + } + + pub fn kind(&self) -> Kind { + self.kind + } + + pub fn shape(&self) -> &Shape { + &self.shape + } + + pub fn fields(&self) -> &[(Arc, Output)] { + match &self.shape { + Shape::Struct(fields) => fields, + _ => &[], + } + } + + pub fn child(&self) -> Option<&Output> { + match &self.shape { + Shape::List(child) => Some(child), + _ => None, + } + } + + pub fn mantissas(&self) -> &[i64] { + &self.mant + } + + pub fn scales(&self) -> &[u8] { + &self.scale + } + + pub fn dates(&self) -> &[Option>] { + &self.dates + } + + pub fn bools(&self) -> &[u64] { + &self.bits + } + + pub fn offsets(&self) -> &[u32] { + &self.offsets + } + + pub fn data(&self) -> &[u8] { + &self.data + } + + pub fn prefer_codes(&mut self) { + self.prefer = true; + } + + pub fn prefer_text(&mut self) { + self.prefer = false; + } + + pub fn codes(&self) -> Option<(&[i32], &[i32], &str)> { + (self.coding && self.kind == Kind::Str).then_some(( + self.coded.keys.as_slice(), + self.coded.offsets.as_slice(), + self.coded.data.as_str(), + )) + } + + pub(crate) fn coding(&self) -> bool { + self.coding + } + + pub(crate) fn push_code(&mut self, code: i32) { + self.coded.keys.push(code); + } + + pub(crate) fn last_code(&self) -> Option { + self.coded.keys.last().copied().filter(|_| self.coding) + } + + fn spill(&mut self) { + self.coding = false; + let keys = std::mem::take(&mut self.coded.keys); + for key in &keys { + let text = usize::try_from(*key) + .ok() + .and_then(|code| self.coded.entry(code)) + .unwrap_or_default(); + self.data.extend_from_slice(text.as_bytes()); + self.offsets.push(self.data.len() as u32); + } + self.coded.keys = keys; + } + + pub(crate) fn push_empty(&mut self) { + match self.coding { + true => self.coded.keys.push(-1), + false => self.offsets.push(self.data.len() as u32), + } + } + + pub fn text(&self, row: usize) -> Option<&str> { + if self.coding { + return match *self.coded.keys.get(row)? { + code if code < 0 => Some(""), + code => self.coded.entry(code as usize), + }; + } + let (a, b) = ( + *self.offsets.get(row)? as usize, + *self.offsets.get(row + 1)? as usize, + ); + std::str::from_utf8(self.data.get(a..b)?).ok() + } + + pub fn boxed(&self) -> &[u64] { + &self.boxed + } + + pub fn failed(&self) -> &[u64] { + &self.failed + } + + pub fn boxed_values(&self) -> &[(u32, Variable)] { + &self.extra + } + + pub fn take_numbers(&mut self) -> (Vec, Vec) { + ( + std::mem::take(&mut self.mant), + std::mem::take(&mut self.scale), + ) + } + + pub fn take_values(&mut self) -> Vec { + std::mem::take(&mut self.values) + } + + pub fn take_bits(&mut self) -> Vec { + std::mem::take(&mut self.bits) + } + + pub fn take_text(&mut self) -> (Vec, Vec) { + if self.coding { + self.spill(); + } + ( + std::mem::take(&mut self.offsets), + std::mem::take(&mut self.data), + ) + } + + pub(crate) fn fail_at(&mut self, at: usize) { + if let Some(w) = self.failed.get_mut(at / 64) { + *w |= 1 << (at % 64); + } + match (&self.shape, self.kind) { + (Shape::Scalar, Kind::Str) => self.push_empty(), + (Shape::List(_), Kind::List) => self.close(), + _ => {} + } + } + + pub(crate) fn put(&mut self, at: usize, value: Variable) { + match (self.kind, value) { + (Kind::Dyn, value) => { + if let Some(slot) = self.values.get_mut(at) { + *slot = value; + } + } + (Kind::Num, Variable::Number(n)) + if crate::lane::scaled::Scaled::parts(&n).is_some() => + { + if let (Some((m, s)), Some(mant), Some(scale)) = ( + crate::lane::scaled::Scaled::parts(&n), + self.mant.get_mut(at), + self.scale.get_mut(at), + ) { + *mant = m; + *scale = s; + } + } + (Kind::Bool, Variable::Bool(b)) => self.set_bit(at, b), + (Kind::Str, Variable::String(text)) => self.push_text(text.as_str()), + (Kind::Date, value) + if !crate::lane::date::Date::sourced(&value) + && crate::lane::date::Date::of(&value).is_some() => + { + if let (Some(date), Some(slot)) = + (crate::lane::date::Date::of(&value), self.dates.get_mut(at)) + { + *slot = date.0; + } + } + (_, value) => self.box_at(at, value), + } + } + + pub(crate) fn box_at(&mut self, at: usize, value: Variable) { + if let Some(w) = self.boxed.get_mut(at / 64) { + *w |= 1 << (at % 64); + } + match self.kind { + Kind::Str => self.push_empty(), + Kind::List => self.close(), + _ => {} + } + self.extra.push((at as u32, value)); + } + + pub(crate) fn set_bit(&mut self, at: usize, on: bool) { + Bits::set(&mut self.bits, at, on); + } + + pub(crate) fn push_text(&mut self, text: &str) { + if self.coding { + match self.coded.intern(text) { + Some(code) => return self.coded.keys.push(code), + None => self.spill(), + } + } + self.data.extend_from_slice(text.as_bytes()); + self.offsets.push(self.data.len() as u32); + } + + fn find(entries: &[(u32, T)], row: usize) -> Option<&T> { + entries + .binary_search_by_key(&(row as u32), |(r, _)| *r) + .ok() + .map(|i| &entries[i].1) + } + + pub fn get(&self, row: usize) -> Option> { + if row >= self.rows { + return None; + } + if Bits::get(&self.failed, row) { + return Self::find(&self.errors, row).map(|failure| Cell::Error(failure.error())); + } + if self.kind != Kind::Dyn && Bits::get(&self.boxed, row) { + return Self::find(&self.extra, row).map(Cell::Value); + } + match &self.shape { + Shape::Struct(fields) => return Some(Cell::Struct(fields, row)), + Shape::List(child) => { + let (a, b) = ( + *self.offsets.get(row)? as usize, + *self.offsets.get(row + 1)? as usize, + ); + return Some(Cell::List(child, a, b)); + } + Shape::Scalar => {} + } + if self.kind == Kind::Dyn { + return self.values.get(row).map(Cell::Value); + } + if Bits::get(&self.boxed, row) { + return Self::find(&self.extra, row).map(Cell::Value); + } + Some(match self.kind { + Kind::Num => Cell::Number(Decimal::new(self.mant[row], self.scale[row] as u32)), + Kind::Str => Cell::Str(self.text(row)?), + Kind::Date => Cell::Date(*self.dates.get(row)?), + _ => Cell::Bool(Bits::get(&self.bits, row)), + }) + } + + pub fn variable(&self, row: usize) -> Option> { + Some(match self.get(row)? { + Cell::Number(n) => Ok(Variable::Number(n)), + Cell::Bool(b) => Ok(Variable::Bool(b)), + Cell::Str(s) => Ok(Variable::String(s.into())), + Cell::Date(d) => Ok(Date(d).variable()), + Cell::Value(v) => Ok(v.clone()), + Cell::Struct(fields, row) => { + let mut map = VariableMap::with_capacity(fields.len()); + for (key, field) in fields.iter().rev() { + map.insert(Symbol::from(key.as_ref()), field.variable(row)?.ok()?); + } + Ok(Variable::from_object(map)) + } + Cell::List(child, a, b) => Ok(Variable::from_array( + (a..b) + .map(|i| child.variable(i)?.ok()) + .collect::>>()?, + )), + Cell::Error(e) => Err(e.clone()), + }) + } +} diff --git a/core/expression/src/lane/program.rs b/core/expression/src/lane/program.rs new file mode 100644 index 00000000..9b57f47f --- /dev/null +++ b/core/expression/src/lane/program.rs @@ -0,0 +1,972 @@ +use crate::compiler::{Compare, FetchFastTarget}; +use crate::functions::{ClosureFunction, FunctionKind, MethodKind}; +use crate::lane::effect::Effect; +use crate::lexer::Bracket; +use crate::variable::Variable; +use crate::vm::VMError; +use rust_decimal::Decimal; +use std::sync::Arc; +use zen_types::path::DotPath; +use zen_types::symbol::Symbol; + +pub type Reg = u32; +pub type MaskId = u32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Kind { + Dyn, + Num, + Bool, + Str, + Date, + List, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Binding { + Column(usize), + Absent, + Row, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Operand { + Reg(Reg), + Num(Decimal), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NumOp { + Add, + Subtract, + Multiply, + Divide, + Modulo, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NumCmp { + Order(Compare), + Equal, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Const { + Null, + Bool(bool), + Number(Decimal), + String(Arc), + Array(Vec), + Date(Option>), +} + +impl Drop for Const { + fn drop(&mut self) { + let Const::Array(items) = self else { + return; + }; + if !items.iter().any(|item| matches!(item, Const::Array(_))) { + return; + } + let mut pending = std::mem::take(items); + while let Some(mut item) = pending.pop() { + if let Const::Array(inner) = &mut item { + pending.append(inner); + } + } + } +} + +impl Const { + pub fn same(&self, other: &Const) -> bool { + match (self, other) { + (Const::Number(a), Const::Number(b)) => a.serialize() == b.serialize(), + (Const::Date(a), Const::Date(b)) => { + let key = |d: chrono::DateTime| { + (d.timestamp(), d.timestamp_subsec_nanos(), d.timezone()) + }; + a.map(key) == b.map(key) + } + (Const::Array(a), Const::Array(b)) => { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.same(y)) + } + (a, b) => a == b, + } + } + + pub fn variable(&self) -> Variable { + match self { + Const::Null => Variable::Null, + Const::Bool(b) => Variable::Bool(*b), + Const::Number(n) => Variable::Number(*n), + Const::String(s) => Variable::String(Symbol::from(s.as_ref())), + Const::Array(items) => Variable::from_array( + items + .iter() + .map(|item| match item { + Const::Array(_) => item.nested_variable(), + _ => item.variable(), + }) + .collect(), + ), + Const::Date(d) => crate::lane::date::Date(*d).variable(), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn nested_variable(&self) -> Variable { + self.variable() + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub fn number(node: &crate::parser::Node) -> Option { + use crate::lexer::{ArithmeticOperator, Operator}; + use crate::parser::Node; + match node { + Node::Number(n) => Some(*n), + Node::Parenthesized(inner) => Const::number(inner), + Node::Unary { + node, + operator: Operator::Arithmetic(ArithmeticOperator::Subtract), + } => Const::number(node).map(|n| -n), + Node::Unary { + node, + operator: Operator::Arithmetic(ArithmeticOperator::Add), + } => Const::number(node), + _ => None, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub fn of(node: &crate::parser::Node) -> Option { + use crate::parser::Node; + if let Some(n) = Const::number(node) { + return Some(Const::Number(n)); + } + match node { + Node::Null => Some(Const::Null), + Node::Bool(b) => Some(Const::Bool(*b)), + Node::String(s) => Some(Const::String(Arc::from(*s))), + Node::Array(items) => items + .iter() + .map(|n| Const::of(n)) + .collect::>>() + .map(Const::Array), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Binary { + Add, + Subtract, + Multiply, + Divide, + Modulo, + Exponent, + Equal, + In, + Compare(Compare), +} + +#[derive(Debug, Clone)] +pub enum Op { + Const { + dst: Reg, + id: u32, + }, + Env { + dst: Reg, + key: Arc, + site: u32, + }, + RootEnv { + dst: Reg, + }, + Path { + dst: Reg, + path: Box<[FetchFastTarget]>, + site: u32, + }, + Fetch { + dst: Reg, + a: Reg, + b: Reg, + }, + Negate { + dst: Reg, + a: Reg, + }, + Not { + dst: Reg, + a: Reg, + }, + Binary { + dst: Reg, + op: Binary, + a: Reg, + b: Reg, + }, + Interval { + dst: Reg, + a: Reg, + b: Reg, + left: Bracket, + right: Bracket, + }, + InRange { + dst: Reg, + a: Reg, + lo: Decimal, + hi: Decimal, + left: Bracket, + right: Bracket, + }, + Slice { + dst: Reg, + a: Reg, + to: Reg, + from: Reg, + }, + Len { + dst: Reg, + a: Reg, + }, + Array { + dst: Reg, + items: Box<[Reg]>, + }, + Object { + dst: Reg, + pairs: Box<[(ObjectKey, Reg)]>, + }, + Join { + dst: Reg, + parts: Box<[Input]>, + }, + Concat { + dst: Reg, + a: Reg, + b: Reg, + }, + Extreme { + dst: Reg, + items: Box<[Operand]>, + largest: bool, + }, + Call { + dst: Reg, + kind: FunctionKind, + args: Box<[Input]>, + }, + Method { + dst: Reg, + kind: MethodKind, + args: Box<[Input]>, + }, + Branch { + cond: Reg, + opcode: &'static str, + on_true: MaskId, + on_false: MaskId, + }, + NullBranch { + a: Reg, + null: MaskId, + other: MaskId, + }, + Merge { + dst: Reg, + mask: MaskId, + a: Reg, + b: Reg, + }, + Move { + dst: Reg, + src: Reg, + }, + AssignBegin { + dst: Reg, + }, + AssignStep { + object: Reg, + key: Reg, + value: Reg, + }, + Closure(Box), + Fail { + error: VMError, + }, + Num { + dst: Reg, + op: NumOp, + a: Operand, + b: Operand, + }, + Cmp { + dst: Reg, + op: NumCmp, + a: Operand, + b: Operand, + }, + EqConst { + dst: Reg, + a: Reg, + value: Const, + id: u32, + not: bool, + }, + Field { + dst: Reg, + src: Reg, + key: Arc, + site: u32, + nested: bool, + }, + LoadEq { + dst: Reg, + load: Load, + site: u32, + id: u32, + not: bool, + }, + LoadIn { + dst: Reg, + a: Reg, + load: Load, + site: u32, + }, + LoadCall(Box), + EqAny { + dst: Reg, + a: Reg, + id: u32, + }, + InConst { + dst: Reg, + a: Reg, + id: u32, + }, + Coalesce { + dst: Reg, + a: Reg, + id: u32, + }, + SelectConst { + dst: Reg, + cond: Reg, + a: u32, + b: u32, + }, + Stage { + index: u32, + }, + Rewind, + DollarInsert { + key: Arc, + value: Reg, + }, + Fold(Box), + Switch(Box), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Subject { + Reg(Reg), + Site(u32), +} + +#[derive(Debug, Clone)] +pub struct SwitchOp { + pub dst: Reg, + pub subject: Subject, + pub cases: Box<[Arc]>, + pub values: Box<[u32]>, + pub rest: MaskId, +} + +#[derive(Debug, Clone)] +pub struct FoldOp { + pub dst: Reg, + pub function: crate::functions::InternalFunction, + pub site: u32, + pub filter: Option>, + pub field: Arc, + pub rest: MaskId, +} + +#[derive(Debug, Clone)] +pub struct LoadCall { + pub dst: Reg, + pub load: Load, + pub site: u32, + pub kind: FunctionKind, + pub args: Box<[u32]>, + pub memo: u32, + pub scratch: Reg, + pub call: Op, +} + +#[derive(Debug, Clone, Copy)] +pub enum Input { + Reg(Reg), + Const(u32), +} + +#[derive(Debug, Clone)] +pub enum ObjectKey { + Static(Arc), + Reg(Reg), +} + +#[derive(Debug, Clone)] +pub enum Load { + Env(Arc), + Path(Box<[FetchFastTarget]>), +} + +#[derive(Debug)] +pub struct ClosureOp { + pub kind: ClosureFunction, + pub dst: Reg, + pub list: Reg, + pub source: Option<(Load, u32)>, + pub body: Program, + pub imports: Box<[(Reg, Reg)]>, + pub sequential: bool, + pub select: bool, +} + +impl Clone for ClosureOp { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn clone(&self) -> Self { + Self { + kind: self.kind, + dst: self.dst, + list: self.list, + source: self.source.clone(), + body: self.body.clone(), + imports: self.imports.clone(), + sequential: self.sequential, + select: self.select, + } + } +} + +#[derive(Debug, Clone)] +pub struct Step { + pub mask: MaskId, + pub op: Op, +} + +impl Drop for Program { + fn drop(&mut self) { + let mut pending = Vec::new(); + Self::detach(self, &mut pending); + while let Some(mut body) = pending.pop() { + Self::detach(&mut body, &mut pending); + } + } +} + +impl Program { + fn detach(program: &mut Program, pending: &mut Vec) { + for step in &mut program.steps { + if let Op::Closure(closure) = &mut step.op { + if closure + .body + .steps + .iter() + .any(|s| matches!(s.op, Op::Closure(_))) + { + pending.push(std::mem::take(&mut closure.body)); + } + } + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct Program { + pub steps: Vec, + pub regs: u32, + pub masks: u32, + pub out: Reg, + pub element: Option, + pub writes_env: bool, + pub chain: bool, + pub frames: usize, + pub kinds: Vec, + pub sites: u32, + pub id: u64, + pub pinned: Vec, + pub fixed: Vec, + pub keys: Vec, + pub site_keys: Vec>, + pub rows: bool, + pub consts: Vec, + pub outputs: Vec, + pub memos: u32, + pub layout: Option, + pub isolated: bool, +} + +#[derive(Debug, Clone)] +pub enum Layout { + Value(Reg), + Struct(Box<[(Arc, Layout)]>), + List(Box<[Layout]>), +} + +impl Op { + pub(crate) fn dst(&self) -> Option { + match self { + Op::Const { dst, .. } + | Op::Env { dst, .. } + | Op::RootEnv { dst } + | Op::Path { dst, .. } + | Op::Fetch { dst, .. } + | Op::Negate { dst, .. } + | Op::Not { dst, .. } + | Op::Binary { dst, .. } + | Op::Interval { dst, .. } + | Op::InRange { dst, .. } + | Op::Slice { dst, .. } + | Op::Len { dst, .. } + | Op::Array { dst, .. } + | Op::Object { dst, .. } + | Op::Join { dst, .. } + | Op::Concat { dst, .. } + | Op::Extreme { dst, .. } + | Op::Call { dst, .. } + | Op::Method { dst, .. } + | Op::Merge { dst, .. } + | Op::Move { dst, .. } + | Op::AssignBegin { dst } + | Op::Num { dst, .. } + | Op::Cmp { dst, .. } + | Op::EqConst { dst, .. } + | Op::Field { dst, .. } + | Op::LoadEq { dst, .. } + | Op::LoadIn { dst, .. } + | Op::EqAny { dst, .. } + | Op::InConst { dst, .. } + | Op::Coalesce { dst, .. } + | Op::SelectConst { dst, .. } => Some(*dst), + Op::Closure(c) => Some(c.dst), + Op::Fold(fold) => Some(fold.dst), + Op::Switch(switch) => Some(switch.dst), + Op::LoadCall(call) => Some(call.dst), + Op::Branch { .. } + | Op::NullBranch { .. } + | Op::AssignStep { .. } + | Op::Fail { .. } + | Op::Stage { .. } + | Op::Rewind + | Op::DollarInsert { .. } => None, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub(crate) fn reads(&self, reg: Reg) -> bool { + let input = |i: &Input| matches!(i, Input::Reg(r) if *r == reg); + let operand = |o: &Operand| matches!(o, Operand::Reg(r) if *r == reg); + match self { + Op::Const { .. } + | Op::Env { .. } + | Op::RootEnv { .. } + | Op::Path { .. } + | Op::LoadEq { .. } + | Op::Fail { .. } + | Op::Stage { .. } + | Op::Rewind + | Op::Fold(_) + | Op::AssignBegin { .. } => false, + Op::Fetch { a, b, .. } + | Op::Binary { a, b, .. } + | Op::Interval { a, b, .. } + | Op::Concat { a, b, .. } + | Op::Merge { a, b, .. } => *a == reg || *b == reg, + Op::Negate { a, .. } + | Op::Not { a, .. } + | Op::InRange { a, .. } + | Op::Len { a, .. } + | Op::NullBranch { a, .. } + | Op::EqConst { a, .. } + | Op::LoadIn { a, .. } + | Op::EqAny { a, .. } + | Op::InConst { a, .. } + | Op::Coalesce { a, .. } => *a == reg, + Op::Slice { a, to, from, .. } => *a == reg || *to == reg || *from == reg, + Op::Array { items, .. } => items.contains(®), + Op::Object { pairs, .. } => pairs + .iter() + .any(|(k, v)| *v == reg || matches!(k, ObjectKey::Reg(r) if *r == reg)), + Op::Join { parts, .. } => parts.iter().any(input), + Op::Extreme { items, .. } => items.iter().any(operand), + Op::Call { args, .. } | Op::Method { args, .. } => args.iter().any(input), + Op::Branch { cond, .. } | Op::SelectConst { cond, .. } => *cond == reg, + Op::Move { src, .. } | Op::Field { src, .. } => *src == reg, + Op::AssignStep { object, key, value } => *object == reg || *key == reg || *value == reg, + Op::Closure(c) => c.list == reg || c.imports.iter().any(|(from, _)| *from == reg), + Op::Switch(switch) => switch.subject == Subject::Reg(reg), + Op::Num { a, b, .. } | Op::Cmp { a, b, .. } => operand(a) || operand(b), + Op::LoadCall(call) => { + call.args.contains(®) || call.scratch == reg || call.call.reads(reg) + } + Op::DollarInsert { value, .. } => *value == reg, + } + } +} + +impl Program { + pub(crate) fn whole(&self, reg: Reg) -> bool { + self.out == reg + || self.outputs.contains(®) + || self.steps.iter().any(|step| { + !matches!(&step.op, Op::Field { src, .. } if *src == reg) && step.op.reads(reg) + }) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub fn finish(&mut self, sites: u32) { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + self.sites = sites; + self.id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let flags: Vec = self + .steps + .iter() + .enumerate() + .map(|(at, step)| match &step.op { + Op::Closure(c) => { + matches!(c.kind, ClosureFunction::Filter) && self.selects(at, c.dst) + } + Op::Field { dst, .. } => self.fields_only(at, *dst), + _ => false, + }) + .collect(); + for (step, flag) in self.steps.iter_mut().zip(flags) { + match &mut step.op { + Op::Closure(c) => { + c.select = flag; + c.body.finish(sites); + } + Op::Field { nested, .. } => *nested = flag, + _ => {} + } + } + self.frames = self.depth() + 1; + } + + fn fields_only(&self, at: usize, reg: Reg) -> bool { + let mask = self.steps[at].mask; + for step in &self.steps[at + 1..] { + let read = + !matches!(&step.op, Op::Field { src, .. } if *src == reg) && step.op.reads(reg); + if read { + return false; + } + if step.op.dst() == Some(reg) && step.mask == mask { + return true; + } + } + self.out != reg && !self.outputs.contains(®) + } + + fn selects(&self, at: usize, reg: Reg) -> bool { + let mask = self.steps[at].mask; + for step in &self.steps[at + 1..] { + let allowed = match &step.op { + Op::Closure(c) if c.list == reg => { + c.source.is_none() && !c.imports.iter().any(|(from, _)| *from == reg) + } + Op::Len { a, .. } if *a == reg => true, + Op::Call { + kind: FunctionKind::Internal(crate::functions::InternalFunction::Len), + args, + .. + } if matches!(args.as_ref(), [Input::Reg(r)] if *r == reg) => true, + op => !op.reads(reg), + }; + if !allowed { + return false; + } + if step.op.dst() == Some(reg) && step.mask == mask { + return true; + } + } + self.out != reg && !self.outputs.contains(®) + } + + pub fn pure(&self) -> bool { + self.steps.iter().all(|step| { + !matches!( + step.op, + Op::Env { .. } + | Op::Path { .. } + | Op::RootEnv { .. } + | Op::LoadEq { .. } + | Op::LoadIn { .. } + | Op::LoadCall(_) + | Op::AssignBegin { .. } + | Op::AssignStep { .. } + | Op::Closure(_) + | Op::Rewind + | Op::DollarInsert { .. } + ) + }) + } + + pub fn opaque(&self) -> bool { + self.opaque_with(&self.site_keys) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub fn stable(&self) -> bool { + self.steps.iter().all(|step| match &step.op { + Op::Call { kind, .. } => Effect::function(kind) != Effect::Random, + Op::LoadCall(call) => Effect::function(&call.kind) != Effect::Random, + Op::Closure(closure) => closure.body.stable(), + _ => true, + }) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub fn timeless(&self) -> bool { + self.steps.iter().all(|step| match &step.op { + Op::Call { kind, .. } => Effect::function(kind) == Effect::Pure, + Op::LoadCall(call) => Effect::function(&call.kind) == Effect::Pure, + Op::Method { kind, .. } => Effect::method(kind) == Effect::Pure, + Op::Closure(closure) => closure.body.timeless(), + _ => true, + }) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn opaque_with(&self, keys: &[Option]) -> bool { + let unkeyed = |site: u32| keys.get(site as usize).is_none_or(Option::is_none); + self.steps.iter().any(|step| match &step.op { + Op::Env { site, .. } + | Op::Path { site, .. } + | Op::LoadEq { site, .. } + | Op::LoadIn { site, .. } => unkeyed(*site), + Op::LoadCall(c) => unkeyed(c.site), + Op::RootEnv { .. } + | Op::AssignBegin { .. } + | Op::AssignStep { .. } + | Op::Rewind + | Op::DollarInsert { .. } => true, + Op::Closure(c) => { + c.source.as_ref().is_some_and(|(_, site)| unkeyed(*site)) + || c.body.opaque_with(keys) + } + _ => false, + }) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + pub fn needs_rows(&self, bound: &[Binding]) -> bool { + self.steps + .iter() + .any(|step| Self::op_needs_rows(&step.op, bound)) + } + + fn op_needs_rows(op: &Op, bound: &[Binding]) -> bool { + match op { + Op::Env { site, .. } + | Op::Path { site, .. } + | Op::LoadEq { site, .. } + | Op::LoadIn { site, .. } => { + matches!(bound.get(*site as usize), None | Some(Binding::Row)) + } + Op::RootEnv { .. } + | Op::AssignBegin { .. } + | Op::AssignStep { .. } + | Op::Rewind + | Op::DollarInsert { .. } => true, + Op::Closure(c) => { + c.source.as_ref().is_some_and(|(_, site)| { + matches!(bound.get(*site as usize), None | Some(Binding::Row)) + }) || c.body.needs_rows(bound) + } + Op::LoadCall(c) => matches!(bound.get(c.site as usize), None | Some(Binding::Row)), + _ => false, + } + } + + pub fn row_roots(&self, bound: &[Binding]) -> Option>> { + let mut roots = Vec::new(); + self.collect_roots(bound, &mut roots).then_some(roots) + } + + fn root_of(load: &Load) -> Option> { + match load { + Load::Env(key) => Some(key.clone()), + Load::Path(path) => match path.as_ref() { + [FetchFastTarget::Begin, FetchFastTarget::String(key), ..] => Some(key.clone()), + _ => None, + }, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn collect_roots(&self, bound: &[Binding], roots: &mut Vec>) -> bool { + let rowed = |site: u32| matches!(bound.get(site as usize), None | Some(Binding::Row)); + let add = |load: Load, roots: &mut Vec>| match Self::root_of(&load) { + Some(root) => { + if !roots.contains(&root) { + roots.push(root); + } + true + } + None => false, + }; + for step in &self.steps { + let ok = match &step.op { + Op::Env { key, site, .. } if rowed(*site) => add(Load::Env(key.clone()), roots), + Op::Path { path, site, .. } if rowed(*site) => add(Load::Path(path.clone()), roots), + Op::LoadEq { load, site, .. } | Op::LoadIn { load, site, .. } if rowed(*site) => { + add(load.clone(), roots) + } + Op::LoadCall(c) if rowed(c.site) => add(c.load.clone(), roots), + Op::RootEnv { .. } + | Op::AssignBegin { .. } + | Op::AssignStep { .. } + | Op::Rewind + | Op::DollarInsert { .. } => false, + Op::Closure(c) => { + let source = match &c.source { + Some((load, site)) if rowed(*site) => add(load.clone(), roots), + _ => true, + }; + source && c.body.collect_roots(bound, roots) + } + _ => true, + }; + if !ok { + return false; + } + } + true + } + + fn site_of(op: &Op) -> Option { + match op { + Op::Env { site, .. } + | Op::Path { site, .. } + | Op::LoadEq { site, .. } + | Op::LoadIn { site, .. } => Some(*site), + Op::LoadCall(call) => Some(call.site), + Op::Closure(c) => c.source.as_ref().map(|(_, site)| *site), + Op::Fold(fold) => Some(fold.site), + Op::Switch(switch) => match switch.subject { + Subject::Site(site) => Some(site), + Subject::Reg(_) => None, + }, + _ => None, + } + } + + pub fn source_fields(&self, key: &str) -> Option>> { + let mut fields = Vec::new(); + self.collect_fields(key, &self.site_keys, &mut fields) + .then_some(fields) + } + + fn collect_fields( + &self, + key: &str, + keys: &[Option], + fields: &mut Vec>, + ) -> bool { + let related = |other: &str| { + other == key || DotPath::indexed(other, key) || DotPath::indexed(key, other) + }; + let site_key = |site: u32| keys.get(site as usize).and_then(|k| k.as_deref()); + let mut lists: Vec = Vec::new(); + for step in &self.steps { + let op = &step.op; + let source = Self::site_of(op).and_then(site_key); + let derived = match op { + Op::Closure(c) + if source == Some(key) || (c.source.is_none() && lists.contains(&c.list)) => + { + let element = c.body.element; + let clean = c.imports.iter().all(|(from, _)| !lists.contains(from)) + && element != Some(c.body.out) + && c.body.steps.iter().all(|inner| match (&inner.op, element) { + (Op::Field { src, key, .. }, Some(el)) if *src == el => { + if !fields.contains(key) { + fields.push(key.clone()); + } + true + } + (op, Some(el)) => !op.reads(el), + (_, None) => true, + }); + if !clean { + return false; + } + matches!(c.kind, ClosureFunction::Filter) + } + Op::Fold(fold) if source == Some(key) => { + for field in std::iter::once(&fold.field).chain(fold.filter.iter()) { + if !fields.contains(field) { + fields.push(field.clone()); + } + } + false + } + _ if source.is_some_and(related) => return false, + Op::Len { .. } => false, + Op::Call { + kind: FunctionKind::Internal(crate::functions::InternalFunction::Len), + .. + } => false, + op if lists.iter().any(|r| op.reads(*r)) => return false, + _ => false, + }; + if let Op::Closure(c) = op { + if !c.body.collect_nested(key, keys) { + return false; + } + } + if let Some(dst) = op.dst() { + lists.retain(|r| *r != dst); + if derived { + lists.push(dst); + } + } + } + true + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn collect_nested(&self, key: &str, keys: &[Option]) -> bool { + let related = |other: &str| { + other == key || DotPath::indexed(other, key) || DotPath::indexed(key, other) + }; + self.steps.iter().all(|step| { + let own = Self::site_of(&step.op) + .and_then(|site| keys.get(site as usize).and_then(|k| k.as_deref())) + .is_none_or(|k| !related(k)); + let nested = match &step.op { + Op::Closure(c) => c.body.collect_nested(key, keys), + _ => true, + }; + own && nested + }) + } + + pub fn depth(&self) -> usize { + self.steps + .iter() + .filter_map(|s| match &s.op { + Op::Closure(c) => Some(c.body.frames), + _ => None, + }) + .max() + .unwrap_or(0) + } +} diff --git a/core/expression/src/lane/scaled.rs b/core/expression/src/lane/scaled.rs new file mode 100644 index 00000000..8347aa21 --- /dev/null +++ b/core/expression/src/lane/scaled.rs @@ -0,0 +1,847 @@ +use crate::lane::mask::LaneSet; +use rust_decimal::Decimal; + +pub struct Scaled; + +impl Scaled { + pub(crate) const POW10: [i64; 19] = [ + 1, + 10, + 100, + 1_000, + 10_000, + 100_000, + 1_000_000, + 10_000_000, + 100_000_000, + 1_000_000_000, + 10_000_000_000, + 100_000_000_000, + 1_000_000_000_000, + 10_000_000_000_000, + 100_000_000_000_000, + 1_000_000_000_000_000, + 10_000_000_000_000_000, + 100_000_000_000_000_000, + 1_000_000_000_000_000_000, + ]; + + #[inline] + pub(crate) fn decimal(m: i64, s: u8) -> Decimal { + Decimal::new(m, s as u32) + } + + #[inline] + fn signed(input: i64, result: (i64, u8)) -> Option<(i64, u8)> { + (result.0 != 0 || input >= 0).then_some(result) + } + + pub(crate) fn divide(a: (i64, u8), b: (i64, u8)) -> Option<(i64, u8)> { + let ((m1, s1), (m2, s2)) = (a, b); + if m2 == 0 { + return None; + } + if m1 == 0 { + return Some((0, 0)); + } + if m2.unsigned_abs() > u32::MAX as u64 { + let (n, d) = (m1 as i128, m2 as i128); + if n % d != 0 { + return None; + } + let q = n / d; + return match s1 >= s2 { + true => i64::try_from(q).ok().map(|q| (q, s1 - s2)), + false => { + let q = q.checked_mul(10i128.checked_pow((s2 - s1) as u32)?)?; + i64::try_from(q).ok().map(|q| (q, 0)) + } + }; + } + Self::terminating(m1, s1, m2, s2) + } + + fn terminating(m1: i64, s1: u8, m2: i64, s2: u8) -> Option<(i64, u8)> { + const LOW64: u128 = 1 << 64; + const LIMIT: u128 = 1 << 96; + let d = u32::try_from(m2.unsigned_abs()).ok()? as u64; + let negative = (m1 < 0) != (m2 < 0); + let n = m1.unsigned_abs(); + let first = n % d; + if first != 0 { + let mut odd = d >> d.trailing_zeros(); + while odd % 5 == 0 { + odd /= 5; + } + if odd > 1 && n % odd != 0 { + return None; + } + } + let mut q = (n / d) as u128; + let mut r = first; + let mut scale = s1 as i32 - s2 as i32; + loop { + let power = match r { + 0 if scale >= 0 => break, + 0 => 9.min(-scale), + _ if scale == 28 => { + let twice = r << 1; + if twice > d || (twice == d && q & 1 == 1) { + q += 1; + if q >= LIMIT { + return None; + } + } + break; + } + _ if q >= LOW64 => return None, + _ if scale > 19 => 28 - scale, + _ => 9, + }; + scale += power; + let factor = Self::POW10[power as usize] as u64; + q = q.checked_mul(factor as u128).filter(|q| *q < LIMIT)?; + let scaled = r * factor; + q += (scaled / d) as u128; + r = scaled % d; + if q >= LIMIT { + return None; + } + } + if first != 0 { + Self::unscale(&mut q, &mut scale); + } + let q = i64::try_from(q).ok()?; + Some((if negative { -q } else { q }, scale as u8)) + } + + #[inline] + fn unscale(q: &mut u128, scale: &mut i32) { + while *q & 0xFFFF_FFFF == 0 && *scale >= 8 && Self::strip(q, 100_000_000) { + *scale -= 8; + } + for (bits, step, power) in [(0xF, 4, 10_000u64), (0x3, 2, 100), (0x1, 1, 10)] { + if *q & bits == 0 && *scale >= step && Self::strip(q, power) { + *scale -= step; + } + } + } + + pub(crate) fn power(divisor: (i64, u8)) -> Option { + let m = divisor.0; + (m > 0).then_some(())?; + (0..=9u32).find(|&k| Self::POW10[k as usize] == m) + } + + #[inline] + pub(crate) fn divide_power(a: (i64, u8), k: u32, s2: u8) -> Option<(i64, u8)> { + let (m1, s1) = a; + if m1 == 0 { + return Some((0, 0)); + } + let scale = s1 as i32 - s2 as i32; + if !(0..=19).contains(&scale) { + return Self::divide(a, (Self::POW10[k as usize], s2)); + } + if k >= 2 && m1 % 10 != 0 && m1 != i64::MIN { + return Some((m1, (scale + k as i32) as u8)); + } + let (mut m, mut t) = (m1.unsigned_abs(), 0u32); + while t < k && m % 10 == 0 { + m /= 10; + t += 1; + } + let (q, scale) = match (t == k, 9 - k + t == 8, m.trailing_zeros() >= 24) { + (true, _, _) => (m, scale), + (false, true, true) => (m, scale + 1), + (false, true, false) => (m.checked_mul(10)?, scale + 2), + (false, false, _) => (m, scale + (k - t) as i32), + }; + let q = i64::try_from(q).ok()?; + Some((if m1 < 0 { -q } else { q }, scale as u8)) + } + + #[inline] + fn strip(q: &mut u128, power: u64) -> bool { + match u64::try_from(*q) { + Ok(small) if small % power == 0 => { + *q = (small / power) as u128; + true + } + Ok(_) => false, + Err(_) if *q % power as u128 == 0 => { + *q /= power as u128; + true + } + Err(_) => false, + } + } + + pub(crate) fn remainder(a: (i64, u8), b: (i64, u8)) -> Option<(i64, u8)> { + let ((m1, s1), (m2, s2)) = (a, b); + if m1 == 0 || m2 == 0 { + return None; + } + let top = s1.max(s2); + let x = Self::rescale(m1, s1, top)?; + let y = Self::rescale(m2, s2, top)?; + if x.unsigned_abs() < y.unsigned_abs() { + return Some((m1, s1)); + } + let r = x.checked_rem(y)?; + (r != 0).then_some((r, top)) + } + + pub(crate) fn abs(m: i64, s: u8) -> Option<(i64, u8)> { + Some((m.checked_abs()?, s)) + } + + pub(crate) fn trunc(m: i64, s: u8, places: u8) -> Option<(i64, u8)> { + let r = match places >= s { + true => ( + m.checked_mul(*Self::POW10.get((places - s) as usize)?)?, + places, + ), + false => (m / Self::POW10.get((s - places) as usize)?, places), + }; + Self::signed(m, r) + } + + pub(crate) fn round(m: i64, s: u8, places: u8) -> Option<(i64, u8)> { + if places >= s { + return Some((m, s)); + } + let f = *Self::POW10.get((s - places) as usize)?; + let (q, r) = (m / f, m % f); + let up = r.unsigned_abs() >= (f as u64).div_ceil(2); + let q = match (up, m < 0) { + (true, true) => q.checked_sub(1)?, + (true, false) => q.checked_add(1)?, + _ => q, + }; + Self::signed(m, (q, places)) + } + + pub(crate) fn floor(m: i64, s: u8) -> Option<(i64, u8)> { + let f = *Self::POW10.get(s as usize)?; + let (q, r) = (m / f, m % f); + Self::signed(m, (if r < 0 { q.checked_sub(1)? } else { q }, 0)) + } + + pub(crate) fn ceil(m: i64, s: u8) -> Option<(i64, u8)> { + let f = *Self::POW10.get(s as usize)?; + let (q, r) = (m / f, m % f); + Self::signed(m, (if r > 0 { q.checked_add(1)? } else { q }, 0)) + } + + pub(crate) fn write(m: i64, s: u8, out: &mut String) { + let mut digits = [0u8; 48]; + let mut n = m.unsigned_abs(); + let mut len = 0usize; + while n > 0 || len <= s as usize { + digits[len] = b'0' + (n % 10) as u8; + n /= 10; + len += 1; + } + if m < 0 { + out.push('-'); + } + for i in (0..len).rev() { + out.push(digits[i] as char); + if i == s as usize && s > 0 { + out.push('.'); + } + } + } + + #[inline(always)] + pub fn parts(d: &Decimal) -> Option<(i64, u8)> { + let unpacked = d.unpack(); + let wide = u64::from(unpacked.mid) << 32 | u64::from(unpacked.lo); + let scale = u8::try_from(unpacked.scale).ok()?; + match (unpacked.hi, unpacked.negative) { + (0, false) => Some((i64::try_from(wide).ok()?, scale)), + (0, true) if wide != 0 => Some((0i64.checked_sub_unsigned(wide)?, scale)), + _ => None, + } + } + + #[inline] + pub(crate) fn rescale(m: i64, from: u8, to: u8) -> Option { + m.checked_mul(*Self::POW10.get((to - from) as usize)?) + } + + #[inline] + pub(crate) fn add(a: (i64, u8), b: (i64, u8), subtract: bool) -> Option<(i64, u8)> { + match (a.0 == 0, b.0 == 0) { + (true, _) => match subtract { + true => Some((b.0.checked_neg()?, b.1)), + false => Some(b), + }, + (false, true) => Some(a), + (false, false) => { + let s = a.1.max(b.1); + let (x, y) = (Self::rescale(a.0, a.1, s)?, Self::rescale(b.0, b.1, s)?); + let m = match subtract { + true => x.checked_sub(y)?, + false => x.checked_add(y)?, + }; + Some((m, s)) + } + } + } + + #[inline] + pub(crate) fn multiply(a: (i64, u8), b: (i64, u8)) -> Option<(i64, u8)> { + if a.0 == 0 || b.0 == 0 { + return Some((0, 0)); + } + let s = a.1 + b.1; + (s <= 28).then_some(())?; + Some((a.0.checked_mul(b.0)?, s)) + } + + #[inline] + pub(crate) fn compare(a: (i64, u8), b: (i64, u8)) -> Option { + if a.1 == b.1 { + return Some(a.0.cmp(&b.0)); + } + let s = a.1.max(b.1); + let up = |m: i64, from: u8| -> Option { + (m as i128).checked_mul(10i128.checked_pow((s - from) as u32)?) + }; + Some(up(a.0, a.1)?.cmp(&up(b.0, b.1)?)) + } +} + +pub(crate) struct Kernel; + +impl Kernel { + #[inline] + pub(crate) fn add( + a: (&[i64], u8), + b: (&[i64], u8), + subtract: bool, + m: &mut [i64], + s: &mut [u8], + ) -> bool { + let ((xa, sa), (xb, sb)) = (a, b); + if sa == sb { + let mut flag = 0i64; + for ((o, x), y) in m.iter_mut().zip(xa).zip(xb) { + let r = match subtract { + true => x.wrapping_sub(*y), + false => x.wrapping_add(*y), + }; + flag |= match subtract { + true => (x ^ y) & (x ^ r), + false => (x ^ r) & (y ^ r), + }; + *o = r; + } + s.fill(sa); + return flag < 0; + } + let (top, up_a) = (sa.max(sb), sa < sb); + let Some(f) = Scaled::POW10.get((top - sa.min(sb)) as usize).copied() else { + return true; + }; + match (subtract, up_a) { + (true, true) => Self::mixed::(xa, xb, f, (sa, sb, top), m, s), + (true, false) => Self::mixed::(xa, xb, f, (sa, sb, top), m, s), + (false, true) => Self::mixed::(xa, xb, f, (sa, sb, top), m, s), + (false, false) => Self::mixed::(xa, xb, f, (sa, sb, top), m, s), + } + } + + #[inline(always)] + fn mixed( + xa: &[i64], + xb: &[i64], + f: i64, + (sa, sb, top): (u8, u8, u8), + m: &mut [i64], + s: &mut [u8], + ) -> bool { + let mut flag = false; + for (((o, sc), x), y) in m.iter_mut().zip(s.iter_mut()).zip(xa).zip(xb) { + let (x, y) = (*x, *y); + let ((p, o1), (q, o2)) = match UP_A { + true => (x.overflowing_mul(f), (y, false)), + false => ((x, false), y.overflowing_mul(f)), + }; + let (r, o3) = match SUB { + true => p.overflowing_sub(q), + false => p.overflowing_add(q), + }; + let negated = if SUB { y.wrapping_neg() } else { y }; + let (zx, zy) = (x == 0, y == 0); + *o = if zx { + negated + } else if zy { + x + } else { + r + }; + *sc = if zx { + sb + } else if zy { + sa + } else { + top + }; + flag |= (!zx & !zy & (o1 | o2 | o3)) | (zx & SUB & (y == i64::MIN)); + } + flag + } + + #[inline] + pub(crate) fn multiply(a: (&[i64], u8), b: (&[i64], u8), m: &mut [i64], s: &mut [u8]) -> bool { + let ((xa, sa), (xb, sb)) = (a, b); + let top = sa + sb; + if top > 28 { + return true; + } + let mut flag = false; + for (((o, sc), x), y) in m.iter_mut().zip(s.iter_mut()).zip(xa).zip(xb) { + let (r, of) = x.overflowing_mul(*y); + flag |= of; + *o = r; + *sc = if r == 0 { 0 } else { top }; + } + flag + } + + #[inline] + pub(crate) fn add_mixed( + a: (&[i64], &[u8]), + b: (&[i64], &[u8]), + subtract: bool, + m: &mut [i64], + s: &mut [u8], + ) -> bool { + let ((xa, sa), (xb, sb)) = (a, b); + let mut flag = false; + for (((((o, sc), x), y), p), q) in m + .iter_mut() + .zip(s.iter_mut()) + .zip(xa) + .zip(xb) + .zip(sa) + .zip(sb) + { + let top = (*p).max(*q); + let (ka, kb) = ((top - p) as usize, (top - q) as usize); + let fa = Scaled::POW10[ka.min(18)] as i128; + let fb = Scaled::POW10[kb.min(18)] as i128; + let (wx, wy) = (*x as i128 * fa, *y as i128 * fb); + let r = match subtract { + true => wx - wy, + false => wx + wy, + }; + let both = *x != 0 && *y != 0; + let outside = |v: i128| v < i64::MIN as i128 || v > i64::MAX as i128; + let general = outside(r) || outside(wx) || outside(wy) || ka > 18 || kb > 18; + let negate = *x == 0 && subtract && *y == i64::MIN; + flag |= (both && general) | negate; + let (rm, rs) = match (*x == 0, *y == 0) { + (true, _) => (if subtract { y.wrapping_neg() } else { *y }, *q), + (false, true) => (*x, *p), + (false, false) => (r as i64, top), + }; + *o = rm; + *sc = rs; + } + flag + } + + pub(crate) fn multiply_mixed( + a: (&[i64], &[u8]), + b: (&[i64], &[u8]), + m: &mut [i64], + s: &mut [u8], + ) -> bool { + let ((xa, sa), (xb, sb)) = (a, b); + let mut flag = false; + for (((((o, sc), x), y), p), q) in m + .iter_mut() + .zip(s.iter_mut()) + .zip(xa) + .zip(xb) + .zip(sa) + .zip(sb) + { + let (r, of) = x.overflowing_mul(*y); + let top = p + q; + flag |= of | (top > 28); + *o = r; + *sc = if r == 0 { 0 } else { top }; + } + flag + } + + #[inline] + pub(crate) fn threshold( + values: &[i64], + k: i64, + hit: impl Fn(std::cmp::Ordering) -> bool, + ) -> M { + let mut mask = M::none(values.len()); + for (w, chunk) in values.chunks(64).enumerate() { + let mut word = 0u64; + for (j, eight) in chunk.chunks(8).enumerate() { + let mut bytes = [0u8; 8]; + for (b, x) in bytes.iter_mut().zip(eight) { + *b = hit(x.cmp(&k)) as u8; + } + let packed = u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56; + word |= packed << (j * 8); + } + mask.set_word(w, word); + } + mask + } + + pub(crate) fn compare( + a: (&[i64], u8), + b: (&[i64], u8), + hit: impl Fn(std::cmp::Ordering) -> bool, + ) -> Option { + let ((xa, sa), (xb, sb)) = (a, b); + let mut mask = M::none(xa.len()); + let (fa, fb) = match sa == sb { + true => (1, 1), + false => { + let top = sa.max(sb); + ( + *Scaled::POW10.get((top - sa) as usize)?, + *Scaled::POW10.get((top - sb) as usize)?, + ) + } + }; + for (w, (ca, cb)) in xa.chunks(64).zip(xb.chunks(64)).enumerate() { + let mut word = 0u64; + match sa == sb { + true => { + for (i, (x, y)) in ca.iter().zip(cb).enumerate() { + word |= (hit(x.cmp(y)) as u64) << i; + } + } + false => { + for (i, (x, y)) in ca.iter().zip(cb).enumerate() { + word |= (hit((*x as i128 * fa as i128).cmp(&(*y as i128 * fb as i128))) + as u64) + << i; + } + } + } + mask.set_word(w, word); + } + Some(mask) + } +} + +#[cfg(test)] +mod tests { + use super::{Kernel, Scaled}; + use rust_decimal::Decimal; + use std::cmp::Ordering; + + struct Rng(u64); + + impl Rng { + fn next(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n + } + + fn mantissa(&mut self) -> i64 { + match self.next(8) { + 0 => 0, + 1 => i64::MAX - self.next(3) as i64, + 2 => i64::MIN + self.next(3) as i64, + 3 => (self.next(1 << 62) as i64) * if self.next(2) == 0 { 1 } else { -1 }, + _ => self.next(20_000) as i64 - 10_000, + } + } + + fn scale(&mut self) -> u8 { + match self.next(6) { + 0 => self.next(29) as u8, + _ => self.next(4) as u8, + } + } + } + + fn exact(m: i64, s: u8, d: Decimal) -> bool { + Scaled::parts(&d).is_some_and(|(dm, ds)| dm == m && ds == s) + && Scaled::decimal(m, s).to_string() == d.to_string() + } + + #[test] + fn rounding_matches_rust_decimal() { + use rust_decimal::RoundingStrategy; + let mut rng = Rng(0xD1B54A32D192ED03); + let exact = |r: Option<(i64, u8)>, d: Decimal, what: &str| { + if let Some((m, s)) = r { + assert_eq!(Scaled::decimal(m, s).to_string(), d.to_string(), "{what}"); + assert_eq!(Scaled::parts(&d), Some((m, s)), "{what} parts"); + } + }; + for _ in 0..300_000 { + let (m, s) = (rng.mantissa(), rng.scale()); + let x = Decimal::new(m, s as u32); + let places = rng.next(6) as u8; + if !(x.is_zero() && x.is_sign_negative()) { + exact(Scaled::abs(m, s), x.abs(), &format!("abs {x}")); + exact( + Scaled::trunc(m, s, places), + x.trunc_with_scale(places as u32), + &format!("trunc {x} {places}"), + ); + exact( + Scaled::round(m, s, places), + x.round_dp_with_strategy(places as u32, RoundingStrategy::MidpointAwayFromZero), + &format!("round {x} {places}"), + ); + exact(Scaled::floor(m, s), x.floor(), &format!("floor {x}")); + exact(Scaled::ceil(m, s), x.ceil(), &format!("ceil {x}")); + } + } + } + + #[test] + fn divide_matches_rust_decimal() { + let mut rng = Rng(0x94D049BB133111EB); + let mut checked = 0usize; + for _ in 0..500_000 { + let (m1, s1) = (rng.mantissa() / (1 + rng.next(1000) as i64), rng.scale()); + let (m2, s2) = ( + match rng.next(3) { + 0 => rng.next(20) as i64 - 10, + 1 => [2, 4, 5, 8, 10, 16, 25, 40, 100, 125][rng.next(10) as usize], + _ => rng.mantissa() / (1 + rng.next(100_000) as i64), + }, + rng.scale(), + ); + let (x, y) = (Decimal::new(m1, s1 as u32), Decimal::new(m2, s2 as u32)); + if let Some((m, s)) = Scaled::divide((m1, s1), (m2, s2)) { + let expected = x.checked_div(y).unwrap_or_default(); + assert_eq!( + Scaled::decimal(m, s).to_string(), + expected.to_string(), + "{x} / {y}" + ); + checked += 1; + } + } + assert!(checked > 10_000, "{checked}"); + } + + #[test] + fn remainder_matches_rust_decimal() { + let mut rng = Rng(0xBF58476D1CE4E5B9); + let mut checked = 0usize; + for _ in 0..500_000 { + let (m1, s1) = (rng.mantissa() / (1 + rng.next(1000) as i64), rng.scale()); + let (m2, s2) = (rng.next(200) as i64 - 100, rng.scale()); + let (x, y) = (Decimal::new(m1, s1 as u32), Decimal::new(m2, s2 as u32)); + if let Some((m, s)) = Scaled::remainder((m1, s1), (m2, s2)) { + let expected = x.checked_rem(y).unwrap_or_default(); + assert_eq!( + Scaled::decimal(m, s).to_string(), + expected.to_string(), + "{x} % {y}" + ); + checked += 1; + } + } + assert!(checked > 10_000, "{checked}"); + } + + #[test] + fn write_matches_decimal_display() { + let mut rng = Rng(0x9E3779B97F4A7C15); + let mut out = String::new(); + for _ in 0..200_000 { + let (m, s) = (rng.mantissa(), rng.scale()); + out.clear(); + Scaled::write(m, s, &mut out); + assert_eq!(out, Decimal::new(m, s as u32).to_string(), "{m}e-{s}"); + } + } + + #[test] + fn division_matches_rust_decimal() { + let mut rng = Rng(0x9E3779B97F4A7C15); + let mut hits = 0usize; + for round in 0..2_000_000 { + let (sa, sb) = (rng.scale(), rng.scale()); + let a = rng.mantissa(); + let b = match round % 3 { + 0 => { + [ + 1, 2, 4, 5, 8, 10, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 1000, 3, 6, 7, + 12, 1024, 3125, + ][rng.next(23) as usize] + * if rng.next(2) == 0 { 1 } else { -1 } + } + _ => rng.mantissa(), + }; + let (x, y) = (Decimal::new(a, sa as u32), Decimal::new(b, sb as u32)); + if let Some((m, s)) = Scaled::divide((a, sa), (b, sb)) { + let expected = x.checked_div(y); + assert!( + expected.is_some_and(|e| exact(m, s, e)), + "divide {x} / {y} -> {m}e-{s} vs {expected:?}" + ); + hits += 1; + } + } + assert!(hits > 500_000, "{hits}"); + } + + #[test] + fn power_division_matches_general_division() { + let mut rng = Rng(0x51A3_77E1_9C2B_0D45); + for round in 0..2_000_000 { + let (sa, sb) = (rng.scale(), rng.scale()); + let a = match round % 6 { + 0 => rng.mantissa() % 1_000_000, + 1 => (rng.mantissa() % 100_000) * Scaled::POW10[rng.next(8) as usize], + 2 => (rng.mantissa() % 4096) << (20 + rng.next(12)), + 3 => ((rng.mantissa() % 4096) << 24) * Scaled::POW10[rng.next(4) as usize], + _ => rng.mantissa(), + }; + let k = rng.next(10) as u32; + let b = Scaled::POW10[k as usize]; + assert_eq!(Scaled::power((b, sb)), Some(k)); + assert_eq!( + Scaled::divide_power((a, sa), k, sb), + Scaled::divide((a, sa), (b, sb)), + "{a}e-{sa} / {b}e-{sb}" + ); + } + } + + #[test] + fn mixed_multiply_matches_scalar_multiply() { + let mut rng = Rng(0x0DDB_A11C_AFE5_1234); + for _ in 0..50_000 { + let a: Vec = (0..64).map(|_| rng.mantissa()).collect(); + let b: Vec = (0..64).map(|_| rng.mantissa()).collect(); + let sa: Vec = (0..64).map(|_| rng.scale()).collect(); + let sb: Vec = (0..64).map(|_| rng.scale()).collect(); + let (mut m, mut s) = (vec![0i64; 64], vec![0u8; 64]); + if Kernel::multiply_mixed((&a, &sa), (&b, &sb), &mut m, &mut s) { + continue; + } + for i in 0..64 { + assert_eq!( + Scaled::multiply((a[i], sa[i]), (b[i], sb[i])), + Some((m[i], s[i])) + ); + } + } + } + + #[test] + fn mixed_add_matches_scalar_add() { + let mut rng = Rng(0x7A11_5EED_0BAD_F00D); + let mut checked = 0usize; + for round in 0..50_000 { + let small = round % 2 == 0; + let pick = |rng: &mut Rng| match (small, rng.next(5)) { + (_, 0) => 0, + (true, _) => rng.mantissa() % 100_000, + (false, _) => rng.mantissa(), + }; + let width = 8; + let a: Vec = (0..width).map(|_| pick(&mut rng)).collect(); + let b: Vec = (0..width).map(|_| pick(&mut rng)).collect(); + let sa: Vec = (0..width) + .map(|_| if small { rng.scale() % 8 } else { rng.scale() }) + .collect(); + let sb: Vec = (0..width) + .map(|_| if small { rng.scale() % 8 } else { rng.scale() }) + .collect(); + let (mut m, mut s) = (vec![0i64; width], vec![0u8; width]); + for subtract in [false, true] { + if Kernel::add_mixed((&a, &sa), (&b, &sb), subtract, &mut m, &mut s) { + continue; + } + checked += 1; + for i in 0..width { + assert_eq!( + Scaled::add((a[i], sa[i]), (b[i], sb[i]), subtract), + Some((m[i], s[i])) + ); + } + } + } + assert!(checked > 10_000, "{checked}"); + } + + #[test] + fn kernels_match_rust_decimal() { + let mut rng = Rng(0x2545F4914F6CDD1D); + let mut checked = 0usize; + for _ in 0..20_000 { + let (sa, sb) = (rng.scale(), rng.scale()); + let a: Vec = (0..64).map(|_| rng.mantissa()).collect(); + let b: Vec = (0..64).map(|_| rng.mantissa()).collect(); + let (mut m, mut s) = (vec![0i64; 64], vec![0u8; 64]); + for op in 0..3 { + let overflow = match op { + 0 => Kernel::add((&a, sa), (&b, sb), false, &mut m, &mut s), + 1 => Kernel::add((&a, sa), (&b, sb), true, &mut m, &mut s), + _ => Kernel::multiply((&a, sa), (&b, sb), &mut m, &mut s), + }; + for i in 0..64 { + let (x, y) = (Decimal::new(a[i], sa as u32), Decimal::new(b[i], sb as u32)); + let expected = match op { + 0 => x.checked_add(y), + 1 => x.checked_sub(y), + _ => x.checked_mul(y), + }; + let lane = match op { + 0 => Scaled::add((a[i], sa), (b[i], sb), false), + 1 => Scaled::add((a[i], sa), (b[i], sb), true), + _ => Scaled::multiply((a[i], sa), (b[i], sb)), + }; + if let (Some((lm, ls)), Some(e)) = (lane, expected) { + assert!( + exact(lm, ls, e), + "lane op {op}: {x} {y} -> {lm}e-{ls} vs {e}" + ); + checked += 1; + } + if !overflow { + let e = expected.unwrap_or_default(); + assert!( + expected.is_some() && exact(m[i], s[i], e), + "kernel op {op}: {x} {y} -> {}e-{} vs {e}", + m[i], + s[i] + ); + } + } + } + let hit = |o: Ordering| o.is_lt(); + if let Some(word) = Kernel::compare::((&a, sa), (&b, sb), hit) + { + for i in 0..64 { + let (x, y) = (Decimal::new(a[i], sa as u32), Decimal::new(b[i], sb as u32)); + assert_eq!(word.get(i), x < y, "compare {x} {y}"); + assert_eq!( + Scaled::compare((a[i], sa), (b[i], sb)).map(|o| o.is_lt()), + Some(x < y) + ); + } + } + } + assert!(checked > 1_000_000); + } +} diff --git a/core/expression/src/lane/session.rs b/core/expression/src/lane/session.rs new file mode 100644 index 00000000..50a919cf --- /dev/null +++ b/core/expression/src/lane/session.rs @@ -0,0 +1,168 @@ +use crate::lane::{LaneProgram, LaneRunner}; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::{ExpressionKind, IsolateError}; +use ahash::HashMap; +use std::cell::RefCell; +use std::sync::Arc; +use zen_types::symbol::Symbol; + +#[derive(Debug, Clone, Default)] +pub struct Programs { + standard: HashMap, Option>, + unary: HashMap, Option>, +} + +impl Programs { + pub fn new() -> Self { + Self::default() + } + + pub fn compile<'s>(sources: impl IntoIterator) -> Self { + let mut programs = Self::new(); + for (source, kind) in sources { + programs.insert(source, kind); + } + programs + } + + pub fn insert(&mut self, source: &str, kind: ExpressionKind) -> Option<&LaneProgram> { + let map = match kind { + ExpressionKind::Standard => &mut self.standard, + ExpressionKind::Unary => &mut self.unary, + }; + if !map.contains_key(source) { + let program = LaneProgram::compile(source, kind).ok(); + map.insert(Arc::from(source), program); + } + map.get(source).and_then(Option::as_ref) + } + + pub fn get(&self, source: &str, kind: &ExpressionKind) -> Option> { + let map = match kind { + ExpressionKind::Standard => &self.standard, + ExpressionKind::Unary => &self.unary, + }; + map.get(source).map(Option::as_ref) + } + + pub fn len(&self) -> usize { + self.standard.len() + self.unary.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +#[derive(Debug, Default)] +pub struct Session { + scope: Scope, + references: HashMap, + programs: Option>, + fallback: Programs, +} + +impl Session { + thread_local! { + static RUNNER: RefCell = RefCell::new(LaneRunner::new()); + } + + pub fn new() -> Self { + Self::default() + } + + pub fn with_environment(variable: Variable) -> Self { + let mut session = Self::new(); + session.set_environment(variable); + session + } + + pub fn with_programs(mut self, programs: Option>) -> Self { + self.programs = programs; + self + } + + pub fn set_programs(&mut self, programs: Arc) { + self.programs = Some(programs); + } + + pub fn set_environment(&mut self, variable: Variable) { + self.scope.set_base(variable); + self.references.clear(); + } + + pub fn scope(&self) -> &Scope { + &self.scope + } + + pub fn set_local(&mut self, name: Symbol, value: Variable) { + self.scope.set_local(name, value); + } + + pub fn insert_dollar(&mut self, path: &str, value: Variable) { + let dollar = match self.scope.local(&Variable::dollar_key()) { + Some(existing @ Variable::Object(_)) => existing.shallow_clone(), + _ => { + let created = Variable::empty_object(); + self.scope + .set_local(Variable::dollar_key(), created.clone()); + created + } + }; + + let _ = dollar.dot_insert(path, value); + } + + pub fn set_reference(&mut self, reference: &str) -> Result<(), IsolateError> { + let value = match self.references.get(reference) { + Some(value) => value.clone(), + None => { + let result = self.run_standard(reference)?; + self.references + .insert(reference.to_string(), result.clone()); + result + } + }; + + self.set_reference_value(value) + } + + pub fn set_reference_value(&mut self, value: Variable) -> Result<(), IsolateError> { + self.scope.set_local(Variable::dollar_key(), value); + + Ok(()) + } + + pub fn get_reference(&self, reference: &str) -> Option { + self.references.get(reference).cloned() + } + + pub fn run_standard(&mut self, source: &str) -> Result { + self.run(source, ExpressionKind::Standard) + } + + pub fn run_unary(&mut self, source: &str) -> Result { + self.run(source, ExpressionKind::Unary)? + .as_bool() + .ok_or(IsolateError::ValueCastError) + } + + fn run(&mut self, source: &str, kind: ExpressionKind) -> Result { + let program = match self.programs.as_deref().and_then(|p| p.get(source, &kind)) { + Some(program) => program, + None => self.fallback.insert(source, kind.clone()), + }; + match program { + Some(program) => Self::evaluate(program, &self.scope), + None => Self::evaluate(&LaneProgram::compile(source, kind)?, &self.scope), + } + } + + fn evaluate(program: &LaneProgram, scope: &Scope) -> Result { + let mut runner = Self::RUNNER.take(); + let result = runner.evaluate_one(program, scope); + Self::RUNNER.set(runner); + result + } +} diff --git a/core/expression/src/lane/source.rs b/core/expression/src/lane/source.rs new file mode 100644 index 00000000..9be540c9 --- /dev/null +++ b/core/expression/src/lane/source.rs @@ -0,0 +1,73 @@ +use crate::lexer::Lexer; +use crate::parser::{Node, Parser}; +use bumpalo::Bump; +use std::cell::Cell; + +pub struct SourceInfo; + +impl SourceInfo { + fn any(source: &str, test: fn(&Node) -> bool) -> bool { + Self::scan(source, false, test) + } + + fn scan(source: &str, unary: bool, test: fn(&Node) -> bool) -> bool { + if source.trim().is_empty() { + return false; + } + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let Ok(tokens) = lexer.tokenize(&bump, source) else { + return true; + }; + let Ok(parser) = Parser::try_new(&tokens, &bump) else { + return true; + }; + let parsed = match unary { + true => parser.unary().parse(), + false => parser.standard().parse(), + }; + if parsed.error().is_err() { + return true; + } + let found = Cell::new(false); + let found_ref = &found; + parsed.root.walk(move |node| { + if test(node) { + found_ref.set(true); + } + }); + found.get() + } + + pub fn reads_dollar(source: &str) -> bool { + Self::any(source, |node| matches!(node, Node::Identifier("$"))) + } + + pub fn reads_env(source: &str) -> bool { + Self::scan(source, true, |node| match node { + Node::Identifier(name) => *name != "$", + Node::Root => true, + _ => false, + }) + } + + pub fn reads_nodes_unary(source: &str) -> bool { + Self::scan(source, true, |node| { + matches!(node, Node::Identifier("$nodes") | Node::Root) + }) + } + + pub fn reads_root_unary(source: &str) -> bool { + Self::scan(source, true, |node| matches!(node, Node::Root)) + } + + pub fn reads_root(source: &str) -> bool { + Self::any(source, |node| matches!(node, Node::Root)) + } + + pub fn reads_nodes(source: &str) -> bool { + Self::any(source, |node| { + matches!(node, Node::Identifier("$nodes") | Node::Root) + }) + } +} diff --git a/core/expression/src/lib.rs b/core/expression/src/lib.rs index a5eff1eb..9c1ec8f5 100644 --- a/core/expression/src/lib.rs +++ b/core/expression/src/lib.rs @@ -57,6 +57,7 @@ #![forbid(unsafe_code)] +mod config; mod isolate; pub mod compiler; @@ -65,14 +66,18 @@ mod exports; pub mod expression; pub mod functions; pub mod intellisense; +pub mod lane; pub mod lexer; pub mod parser; pub mod scope; pub mod slot; +#[doc(hidden)] +pub mod typed; pub mod validate; pub mod variable; pub mod vm; +pub use config::{ZenExpressionConfig, ZEN_EXPRESSION_CONFIG}; pub use dates::DateValue; pub use exports::{ compile_expression, compile_unary_expression, evaluate_expression, evaluate_unary_expression, diff --git a/core/expression/src/parser/ast.rs b/core/expression/src/parser/ast.rs index 51edb404..b425fed5 100644 --- a/core/expression/src/parser/ast.rs +++ b/core/expression/src/parser/ast.rs @@ -72,6 +72,7 @@ pub enum Node<'a> { } impl<'a> Node<'a> { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] pub fn walk(&self, mut func: F) where F: FnMut(&Self) + Clone, @@ -194,6 +195,7 @@ impl<'a> Node<'a> { } } + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] pub(crate) fn member_key(&self, vec: &mut BumpVec<&'a str>) -> Option<()> { match self { Node::Member { node, property } => { diff --git a/core/expression/src/parser/parser.rs b/core/expression/src/parser/parser.rs index 7c4c8601..2a351c8e 100644 --- a/core/expression/src/parser/parser.rs +++ b/core/expression/src/parser/parser.rs @@ -41,7 +41,7 @@ pub struct Parser<'arena, 'token_ref, Flavor> { current: Cell>>, pub(crate) bump: &'arena Bump, position: Cell, - depth: Cell, + depth: Cell, marker_flavor: PhantomData, has_range_operator: bool, pub(crate) node_metadata: @@ -150,7 +150,7 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { target_token.is_some() } - pub(crate) fn depth(&self) -> u8 { + pub(crate) fn depth(&self) -> u32 { self.depth.get() } @@ -604,6 +604,7 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { } } + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] pub(crate) fn with_postfix( &self, node: &'arena Node<'arena>, diff --git a/core/expression/src/typed/batch.rs b/core/expression/src/typed/batch.rs new file mode 100644 index 00000000..9fd7d986 --- /dev/null +++ b/core/expression/src/typed/batch.rs @@ -0,0 +1,837 @@ +use crate::lane::date::Date; +use crate::lane::Bits; +use crate::lane::ShortKey; +use crate::lane::{Column, Values}; +use crate::typed::hir::{ColumnDef, Dict, Hir, Kind, Unsupported}; +use crate::typed::kernel::K; +use crate::typed::num::Dec; +use crate::typed::output::Outputs; +use rust_decimal::Decimal; +use std::borrow::Cow; + +#[derive(Clone, Debug, Default)] +pub struct Batch<'b> { + rows: usize, + columns: Vec>, + lists: Vec>, +} + +#[derive(Clone, Debug)] +pub struct List<'b> { + offsets: &'b [i32], + validity: Option<(&'b [u64], usize)>, + faults: Option<(&'b [u64], usize)>, + fields: Vec>, +} + +#[derive(Clone, Debug)] +pub(crate) enum Scales<'x> { + Fixed(u8), + Each(Cow<'x, [u8]>), +} + +#[derive(Clone, Debug)] +pub(crate) enum Text<'x> { + Str { + offsets: &'x [i32], + data: &'x [u8], + }, + Dict { + keys: &'x [i32], + offsets: &'x [i32], + data: &'x [u8], + }, +} + +#[derive(Clone, Debug)] +pub(crate) enum Data<'x> { + Num { + mant: Cow<'x, [i64]>, + scale: Scales<'x>, + }, + Bool { + bits: Cow<'x, [u64]>, + offset: usize, + }, + Codes(Vec), + Text(Text<'x>), +} + +#[derive(Clone, Debug)] +pub(crate) struct Feed<'x> { + pub(crate) data: Data<'x>, + pub(crate) validity: Option<(&'x [u64], usize)>, + pub(crate) holes: Option>, + pub(crate) faults: Option>, + pub(crate) wide: Option<(Vec, Vec<(usize, Decimal)>)>, + pub(crate) fixed: Option, +} + +#[derive(Clone, Debug)] +pub(crate) struct Lists { + pub(crate) offsets: Vec, + pub(crate) parent: Vec, + pub(crate) root: Vec, + pub(crate) null: Option>, + pub(crate) faulted: Option>, +} + +#[derive(Clone, Debug)] +pub(crate) struct Feeds<'x> { + pub(crate) rows: usize, + pub(crate) columns: Vec>, + pub(crate) fields: Vec>>, + pub(crate) classes: Vec>, + pub(crate) lists: Vec, + pub(crate) parents: Vec>, + pub(crate) now: Date, +} + +#[derive(Clone, Debug)] +pub(crate) struct Matcher<'d> { + keys: Vec<(usize, u64)>, + lengths: u64, + values: Cow<'d, [Box]>, + other: i32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Origin { + Col(u16), + Field(u16, u16), +} + +impl<'b> Batch<'b> { + pub fn new(rows: usize) -> Self { + Self { + rows, + columns: Vec::new(), + lists: Vec::new(), + } + } + + pub fn column(mut self, column: Column<'b>) -> Self { + self.columns.push(column); + self + } + + pub fn list(mut self, list: List<'b>) -> Self { + self.lists.push(list); + self + } + + pub fn push_column(&mut self, column: Column<'b>) { + self.columns.push(column); + } + + pub fn push_list(&mut self, list: List<'b>) { + self.lists.push(list); + } + + pub fn rows(&self) -> usize { + self.rows + } +} + +impl<'b> List<'b> { + pub fn new( + offsets: &'b [i32], + validity: Option<(&'b [u64], usize)>, + fields: Vec>, + ) -> Self { + Self { + offsets, + validity, + faults: None, + fields, + } + } + + pub fn faults(self, bits: &'b [u64], offset: usize) -> Self { + Self { + faults: Some((bits, offset)), + ..self + } + } +} + +impl Lists { + pub(crate) fn len(&self) -> usize { + self.parent.len() + } + + pub(crate) fn owners(&self) -> usize { + self.offsets.len().saturating_sub(1) + } +} + +impl<'x> Text<'x> { + #[inline] + pub(crate) fn get(&self, at: usize) -> Option<&'x [u8]> { + let entry = match self { + Text::Str { offsets, data } => (offsets, data, at), + Text::Dict { + keys, + offsets, + data, + } => (offsets, data, usize::try_from(*keys.get(at)?).ok()?), + }; + let (offsets, data, i) = entry; + let (lo, hi) = ( + usize::try_from(*offsets.get(i)?).ok()?, + usize::try_from(*offsets.get(i + 1)?).ok()?, + ); + data.get(lo..hi) + } +} + +impl<'x> Feed<'x> { + #[inline] + pub(crate) fn valid_word(&self, at: usize, width: usize) -> u64 { + let valid = match self.validity { + None => match width >= 64 { + true => u64::MAX, + false => (1u64 << width) - 1, + }, + Some((bits, offset)) => Bits::word(bits, offset + at, width), + }; + match &self.holes { + None => valid, + Some(holes) => valid & !Bits::word(holes, at, width), + } + } + + #[inline] + pub(crate) fn valid(&self, at: usize) -> bool { + self.valid_word(at, 1) == 1 + } + + #[inline] + pub(crate) fn fault_word(&self, w: usize) -> u64 { + self.faults + .as_ref() + .and_then(|f| f.get(w)) + .copied() + .unwrap_or(0) + } + + #[cfg(test)] + pub(crate) fn num(&self, at: usize) -> Option { + match &self.data { + Data::Num { mant, scale } => { + let m = *mant.get(at)?; + let s = match scale { + Scales::Fixed(s) => *s, + Scales::Each(each) => *each.get(at)?, + }; + Some(Dec::new(m, s)) + } + _ => None, + } + } + + pub(crate) fn text(&self) -> Option<&Text<'x>> { + match &self.data { + Data::Text(t) => Some(t), + _ => None, + } + } + + fn new(data: Data<'x>, validity: Option<(&'x [u64], usize)>) -> Self { + Self { + data, + validity, + holes: None, + faults: None, + wide: None, + fixed: None, + } + } + + fn fault(&mut self, at: usize, len: usize) { + let faults = self.faults.get_or_insert_with(|| vec![0u64; K::words(len)]); + Bits::set(faults, at, true); + } + + fn hole(&mut self, at: usize, len: usize) { + let holes = self.holes.get_or_insert_with(|| vec![0u64; K::words(len)]); + Bits::set(holes, at, true); + } + + fn of( + column: &Column<'x>, + def: &ColumnDef, + base: usize, + len: usize, + ) -> Result { + let short = || Unsupported::new(format!("column {} is shorter than its rows", def.path)); + if column.len() < base + len { + return Err(short()); + } + let validity = column.validity.map(|(bits, offset)| (bits, offset + base)); + let feed = match (def.ty.kind, column.values) { + (Kind::Num(_), Values::Scaled { mant, scale }) if scale.len() >= base + len => { + let feed = Self::new( + Data::Num { + mant: Cow::Borrowed(&mant[base..base + len]), + scale: Scales::Each(Cow::Borrowed(&scale[base..base + len])), + }, + validity, + ); + feed.scan(len) + } + (Kind::Num(_), Values::I64(values)) => { + let mut feed = Self::new( + Data::Num { + mant: Cow::Borrowed(&values[base..base + len]), + scale: Scales::Fixed(0), + }, + validity, + ); + feed.fixed = Some(0); + feed + } + (Kind::Num(_), Values::Dec(values)) => { + let mut mant = Vec::with_capacity(len); + let mut scale = Vec::with_capacity(len); + let mut wide: Vec<(usize, Decimal)> = Vec::new(); + for (i, d) in values[base..base + len].iter().enumerate() { + let parts = Dec::from_decimal(d); + if parts.is_none() && column.valid(base + i) { + wide.push((i, *d)); + } + let p = parts.unwrap_or(Dec::ZERO); + mant.push(p.mant); + scale.push(p.scale); + } + let mut feed = Self::new( + Data::Num { + mant: Cow::Owned(mant), + scale: Scales::Each(Cow::Owned(scale)), + }, + validity, + ); + if !wide.is_empty() { + let mut bits = vec![0u64; K::words(len)]; + wide.iter() + .for_each(|(i, _)| Bits::set(&mut bits, *i, true)); + feed.wide = Some((bits, wide)); + } + feed.scan(len) + } + (Kind::Num(_), Values::Dict { keys, values }) => { + let dict = values.column(); + let Values::Scaled { + mant: dm, + scale: ds, + } = dict.values + else { + return Err(Unsupported::new(format!( + "column {}: numeric dictionary", + def.path + ))); + }; + let mut mant = Vec::with_capacity(len); + let mut scale = Vec::with_capacity(len); + let mut bad = Vec::new(); + for (i, k) in keys[base..base + len].iter().enumerate() { + let entry = usize::try_from(*k) + .ok() + .and_then(|k| Some((*dm.get(k)?, *ds.get(k)?, dict.valid(k)))); + let (m, s, ok) = entry.unwrap_or((0, 0, false)); + if !ok && column.valid(base + i) { + bad.push(i); + } + mant.push(m); + scale.push(s); + } + let mut feed = Self::new( + Data::Num { + mant: Cow::Owned(mant), + scale: Scales::Each(Cow::Owned(scale)), + }, + validity, + ); + for i in bad { + feed.hole(i, len); + } + feed.scan(len) + } + (Kind::Bool, Values::Bool { bits, offset }) + if bits.len() * 64 >= offset + base + len => + { + Self::new( + Data::Bool { + bits: Cow::Borrowed(bits), + offset: offset + base, + }, + validity, + ) + } + (Kind::Bool, Values::Dict { keys, values }) => { + let dict = values.column(); + let mut bits = vec![0u64; K::words(len)]; + let mut bad = Vec::new(); + let mut holes = Vec::new(); + for (i, k) in keys[base..base + len].iter().enumerate() { + let entry = usize::try_from(*k) + .ok() + .filter(|k| *k < dict.len() && dict.valid(*k)); + match entry.map(|k| dict.boolean(k)) { + Some(Some(b)) => Bits::set(&mut bits, i, b), + Some(None) if column.valid(base + i) => bad.push(i), + None if column.valid(base + i) => holes.push(i), + _ => {} + } + } + let mut feed = Self::new( + Data::Bool { + bits: Cow::Owned(bits), + offset: 0, + }, + validity, + ); + for i in bad { + feed.fault(i, len); + } + for i in holes { + feed.hole(i, len); + } + feed + } + (Kind::Text, Values::Text { offsets, data }) if offsets.len() > base + len => { + Self::new( + Data::Text(Text::Str { + offsets: &offsets[base..], + data: data.as_bytes(), + }), + validity, + ) + } + (Kind::Text, Values::Utf8 { offsets, data }) if offsets.len() > base + len => { + Self::new( + Data::Text(Text::Str { + offsets: &offsets[base..], + data, + }), + validity, + ) + } + (Kind::Text, Values::Dict { keys, values }) => { + let dict = values.column(); + let (offsets, data) = match dict.values { + Values::Text { offsets, data } => (offsets, data.as_bytes()), + Values::Utf8 { offsets, data } => (offsets, data), + _ => { + return Err(Unsupported::new(format!( + "column {}: text dictionary", + def.path + ))) + } + }; + let entries = offsets.len().saturating_sub(1); + let keys = &keys[base..base + len]; + let mut feed = Self::new( + Data::Text(Text::Dict { + keys, + offsets, + data, + }), + validity, + ); + let (lo, hi) = keys + .iter() + .fold((i32::MAX, i32::MIN), |(lo, hi), k| (lo.min(*k), hi.max(*k))); + let clean = keys.is_empty() + || (lo >= 0 && (hi as usize) < entries && dict.validity.is_none()); + let bad: Vec = match clean { + true => Vec::new(), + false => keys + .iter() + .enumerate() + .filter(|(i, k)| { + usize::try_from(**k).map_or(true, |k| k >= entries || !dict.valid(k)) + && column.valid(base + i) + }) + .map(|(i, _)| i) + .collect(), + }; + for i in bad { + feed.hole(i, len); + } + feed + } + (kind, _) => { + return Err(Unsupported::new(format!( + "column {}: values do not fit {kind}", + def.path + ))) + } + }; + Ok(feed) + } + + fn scan(mut self, len: usize) -> Self { + let Data::Num { + scale: Scales::Each(each), + .. + } = &self.data + else { + return self; + }; + let mut fixed: Option = None; + let mut mixed = false; + let plain = self.validity.is_none() + && self.holes.is_none() + && self.faults.is_none() + && self.wide.is_none(); + if plain && !each.is_empty() { + let s = each[0]; + fixed = Some(s); + mixed = each.iter().fold(0u8, |acc, x| acc | (x ^ s)) != 0; + } + for (w, chunk) in each.chunks(64).enumerate().filter(|_| !plain) { + let wide = self + .wide + .as_ref() + .map_or(0, |(bits, _)| bits.get(w).copied().unwrap_or(0)); + let mut valid = self.valid_word(w * 64, chunk.len()) & !self.fault_word(w) & !wide; + if valid == 0 { + continue; + } + if valid == u64::MAX >> (64 - chunk.len()) { + let s = *fixed.get_or_insert(chunk[0]); + if chunk.iter().fold(0u8, |acc, x| acc | (x ^ s)) != 0 { + mixed = true; + break; + } + continue; + } + while valid != 0 { + let i = valid.trailing_zeros() as usize; + valid &= valid - 1; + let s = *fixed.get_or_insert(chunk[i]); + if chunk[i] != s { + mixed = true; + break; + } + } + if mixed { + break; + } + } + self.fixed = match mixed { + true => None, + false => Some(fixed.unwrap_or(0)), + }; + if len == 0 { + self.fixed = Some(0); + } + self + } + + fn classify(&self, dict: &Dict, len: usize) -> Feed<'x> { + let matcher = Matcher::new(dict); + let codes = match &self.data { + Data::Text(Text::Dict { + keys, + offsets, + data, + }) => { + let entries = offsets.len().saturating_sub(1); + let remap: Vec = (0..entries) + .map(|i| matcher.code(Text::Str { offsets, data }.get(i))) + .collect(); + keys.iter() + .map(|k| { + usize::try_from(*k) + .ok() + .and_then(|k| remap.get(k)) + .copied() + .unwrap_or(matcher.other) + }) + .collect() + } + Data::Text(Text::Str { offsets, data }) => match offsets.get(..=len) { + Some(offsets) => offsets + .windows(2) + .map(|w| matcher.at(data, w[0] as usize, w[1] as usize)) + .collect(), + None => vec![matcher.other; len], + }, + _ => vec![matcher.other; len], + }; + Feed { + data: Data::Codes(codes), + validity: self.validity, + holes: self.holes.clone(), + faults: self.faults.clone(), + wide: None, + fixed: None, + } + } +} + +impl<'d> Matcher<'d> { + pub(crate) fn new(dict: &'d Dict) -> Self { + let keys = dict + .values + .iter() + .map(|v| (v.len(), ShortKey::of(v.as_bytes()))) + .collect(); + let lengths = dict + .values + .iter() + .fold(0u64, |mask, v| mask | 1u64 << v.len().min(63)); + Self { + keys, + lengths, + values: Cow::Borrowed(&dict.values), + other: dict.values.len() as i32, + } + } + + pub(crate) fn owned(dict: &Dict) -> Matcher<'static> { + let Matcher { + keys, + lengths, + values, + other, + } = Matcher::new(dict); + Matcher { + keys, + lengths, + values: Cow::Owned(values.into_owned()), + other, + } + } + + #[inline] + fn at(&self, data: &[u8], lo: usize, hi: usize) -> i32 { + let len = hi.wrapping_sub(lo); + if hi > data.len() || lo > hi || self.lengths & 1u64 << len.min(63) == 0 { + return self.other; + } + let key = ShortKey::at(data, lo, len); + for (i, k) in self.keys.iter().enumerate() { + if *k == (len, key) && (len <= 8 || self.values[i].as_bytes() == &data[lo..hi]) { + return i as i32; + } + } + self.other + } + + #[inline] + pub(crate) fn code(&self, bytes: Option<&[u8]>) -> i32 { + let Some(bytes) = bytes else { + return self.other; + }; + let len = bytes.len(); + if self.lengths & 1u64 << len.min(63) == 0 { + return self.other; + } + let key = ShortKey::of(bytes); + for (i, k) in self.keys.iter().enumerate() { + if *k == (len, key) && (len <= 8 || self.values[i].as_bytes() == bytes) { + return i as i32; + } + } + self.other + } +} + +impl<'x> Feeds<'x> { + pub(crate) fn new( + hir: &Hir, + classes: &[(Origin, u16)], + batch: &Batch<'x>, + ) -> Result { + let schema = &hir.schema; + if batch.columns.len() != schema.columns.len() || batch.lists.len() != schema.lists.len() { + return Err(Unsupported::new("batch does not match the program schema")); + } + let rows = batch.rows; + let mut columns = Vec::with_capacity(batch.columns.len()); + for (column, def) in batch.columns.iter().zip(&schema.columns) { + columns.push(Feed::of(column, def, 0, rows)?); + } + let mut fields = Vec::with_capacity(batch.lists.len()); + let mut lists = Vec::with_capacity(batch.lists.len()); + for (list, def) in batch.lists.iter().zip(&schema.lists) { + let owners = match def.parent { + None => rows, + Some(p) => lists.get(p as usize).map(Lists::len).ok_or_else(|| { + Unsupported::new(format!("list {} before its parent", def.path)) + })?, + }; + if list.fields.len() != def.fields.len() || list.offsets.len() <= owners { + return Err(Unsupported::new(format!( + "list {} does not match the program schema", + def.path + ))); + } + let base = list.offsets[0]; + let sorted = base >= 0 + && list.offsets[..=owners] + .windows(2) + .fold(true, |ok, w| ok & (w[0] <= w[1])); + let total = usize::try_from(list.offsets[owners] as i64 - base as i64) + .ok() + .filter(|_| sorted) + .ok_or_else(|| Unsupported::new("list offsets"))?; + if list.fields.iter().any(|c| c.len() < base as usize + total) { + return Err(Unsupported::new(format!( + "list {} is shorter than its offsets", + def.path + ))); + } + let offsets: Vec = list.offsets[..=owners].iter().map(|o| o - base).collect(); + let mut parent = vec![0u32; total]; + for (r, w) in offsets.windows(2).enumerate() { + parent[w[0] as usize..w[1] as usize].fill(r as u32); + } + let root = match def.parent.and_then(|p| lists.get(p as usize)) { + None => parent.clone(), + Some(up) => parent + .iter() + .map(|&o| up.root.get(o as usize).copied().unwrap_or(0)) + .collect(), + }; + let base = base as usize; + let marks = |bits: Option<(&[u64], usize)>, on: bool| -> Option> { + let (bits, offset) = bits?; + let mut out: Option> = None; + for o in 0..owners { + if Bits::get(bits, offset + o) == on { + Bits::set( + out.get_or_insert_with(|| vec![0u64; K::words(owners)]), + o, + true, + ); + } + } + out + }; + let null = marks(list.validity, false); + if let Some(null) = &null { + if (0..owners).any(|o| Bits::get(null, o) && offsets[o] != offsets[o + 1]) { + return Err(Unsupported::new(format!( + "list {} has elements under null entries", + def.path + ))); + } + } + let faulted = marks(list.faults, true); + let len = parent.len(); + let mut feeds = Vec::with_capacity(list.fields.len()); + for (column, def) in list.fields.iter().zip(&def.fields) { + feeds.push(Feed::of(column, def, base, len)?); + } + fields.push(feeds); + lists.push(Lists { + offsets, + parent, + root, + null, + faulted, + }); + } + let parents = schema.lists.iter().map(|l| l.parent).collect(); + let mut feeds = Self { + rows, + columns, + fields, + classes: Vec::with_capacity(classes.len()), + lists, + parents, + now: Date(None), + }; + for (origin, dict) in classes { + let class = { + let (source, len) = match *origin { + Origin::Col(c) => (feeds.columns.get(c as usize), rows), + Origin::Field(l, f) => ( + feeds.fields.get(l as usize).and_then(|x| x.get(f as usize)), + feeds.lists.get(l as usize).map_or(0, Lists::len), + ), + }; + let source = source.ok_or_else(|| Unsupported::new("classify source"))?; + source.classify(hir.dict(*dict), len) + }; + feeds.classes.push(class); + } + Ok(feeds) + } + + pub(crate) fn prefaults(&self, out: &mut Outputs, select: Option<&[u64]>) { + let mut rows: Vec = Vec::new(); + for feed in &self.columns { + if let Some(faults) = &feed.faults { + rows.extend((0..self.rows).filter(|&r| Bits::get(faults, r))); + } + } + for (at, (list, feeds)) in self.lists.iter().zip(&self.fields).enumerate() { + for feed in feeds { + if let Some(faults) = &feed.faults { + rows.extend( + (0..list.len()) + .filter(|&e| Bits::get(faults, e)) + .map(|e| list.root[e] as usize), + ); + } + } + if let Some(faulted) = &list.faulted { + rows.extend( + (0..list.owners()) + .filter(|&o| Bits::get(faulted, o)) + .map(|o| self.row_of(at, o)), + ); + } + } + rows.retain(|&r| select.is_none_or(|sel| Bits::get(sel, r))); + if rows.is_empty() { + return; + } + let (slots, faults) = out.parts(); + for &row in &rows { + faults.set(row); + for slot in slots.iter_mut() { + slot.fault.set(row); + } + } + } + + pub(crate) fn sig(&self, hir: &Hir, into: &mut Vec>) { + into.clear(); + for (feed, def) in self.columns.iter().zip(&hir.schema.columns) { + into.push(Self::fixed(def.ty.kind, feed)); + } + for (list, def) in self.fields.iter().zip(&hir.schema.lists) { + for (feed, field) in list.iter().zip(&def.fields) { + into.push(Self::fixed(field.ty.kind, feed)); + } + } + } + + fn fixed(kind: Kind, feed: &Feed) -> Option { + match kind { + Kind::Num(None) => feed.fixed, + _ => None, + } + } + + pub(crate) fn row_of(&self, list: usize, owner: usize) -> usize { + let up = self.parents.get(list).copied().flatten(); + match up.and_then(|p| self.lists.get(p as usize)) { + Some(parent) => parent.root.get(owner).map_or(owner, |r| *r as usize), + None => owner, + } + } + + pub(crate) fn len(&self, scope: crate::typed::hir::Scope) -> usize { + match scope { + crate::typed::hir::Scope::Row => self.rows, + crate::typed::hir::Scope::Elem(l) => self.lists.get(l as usize).map_or(0, Lists::len), + } + } +} diff --git a/core/expression/src/typed/build.rs b/core/expression/src/typed/build.rs new file mode 100644 index 00000000..dd767c8c --- /dev/null +++ b/core/expression/src/typed/build.rs @@ -0,0 +1,1693 @@ +use crate::typed::batch::Matcher; +use crate::typed::hir::{ + Arith, Clock, Cmp, Fold, Func, Hir, Kind, Lit, NodeId, Op, Scope, Unsupported, +}; +use crate::typed::ins::{Arg, Arm, BufDef, FixOp, Guard, Ins, Pattern, Rep, Src, Tab, R}; +use crate::typed::kernel::K; +use crate::typed::lookup::Lookup; +use crate::typed::num::Dec; +use std::collections::HashMap; +use std::sync::Arc; + +#[derive(Clone, Copy, Debug)] +pub(crate) struct Passes { + pub(crate) fold: bool, + pub(crate) factor: bool, + pub(crate) skip: bool, + pub(crate) reuse: bool, + pub(crate) elide: bool, + pub(crate) skip_min: u32, + pub(crate) lookup_min: usize, +} + +pub(crate) struct Stage { + pub(crate) scope: Scope, + pub(crate) code: Vec, +} + +pub(crate) struct Built { + pub(crate) stages: Vec, + pub(crate) nregs: usize, + pub(crate) consts: Vec<(R, Rep, Lit)>, + pub(crate) defs: Vec, +} + +pub(crate) struct Build<'h> { + hir: &'h Hir, + sig: &'h [Option], + classes: &'h HashMap, + bases: Vec, + passes: Passes, + rep: Vec, + level: Vec, + stage: Vec, + keys: Vec<(u32, Scope)>, + users: Vec>, + outs: Vec>, + keeps: Vec>, + period: u32, + cross: Vec, + acc: Vec, + code: Vec>, + cur: usize, + vreg: HashMap<(usize, NodeId), R>, + next: usize, + pinned: Vec, + consts: Vec<(R, Rep, Lit)>, + const_of: HashMap<(Lit, Rep), R>, + defs: Vec, + buf_of: Vec>, + sel_need: Vec, + picks: HashMap)>>, +} + +impl Passes { + pub(crate) const ALL: Passes = Passes { + fold: true, + factor: true, + skip: true, + reuse: true, + elide: true, + skip_min: 2, + lookup_min: 128, + }; +} + +impl Rep { + fn of_kind(kind: Kind, fixed: Option) -> Rep { + match kind { + Kind::Num(Some(s)) => Rep::Fix(s), + Kind::Num(None) => fixed.map_or(Rep::Dyn, Rep::Fix), + Kind::Bool => Rep::Bool, + Kind::Code(_) => Rep::Code, + Kind::Text => Rep::Text, + Kind::Date => Rep::Date, + Kind::Null => Rep::Null, + } + } +} + +impl<'h> Build<'h> { + pub(crate) fn plan( + hir: &'h Hir, + sig: &'h [Option], + classes: &'h HashMap, + passes: Passes, + ) -> Result { + let mut b = Build::new(hir, sig, classes, passes)?; + b.emit_all()?; + b.finish() + } + + fn new( + hir: &'h Hir, + sig: &'h [Option], + classes: &'h HashMap, + passes: Passes, + ) -> Result { + let n = hir.nodes.len(); + let mut bases = Vec::with_capacity(hir.schema.lists.len()); + let mut base = hir.schema.columns.len(); + for l in &hir.schema.lists { + bases.push(base); + base += l.fields.len(); + } + let mut users: Vec> = vec![Vec::new(); n]; + for (i, node) in hir.nodes.iter().enumerate() { + for inp in node.op.inputs() { + let u = users + .get_mut(inp as usize) + .ok_or_else(|| Unsupported::new("typed: bad input"))?; + if u.last() != Some(&(i as NodeId)) { + u.push(i as NodeId); + } + } + } + let mut outs = vec![Vec::new(); n]; + let mut keeps = vec![Vec::new(); n]; + for (k, o) in hir.outputs.iter().enumerate() { + outs.get_mut(o.node as usize) + .ok_or_else(|| Unsupported::new("typed: bad output"))? + .push(k); + if let Some(keep) = o.collect.and_then(|c| c.keep) { + keeps + .get_mut(keep as usize) + .ok_or_else(|| Unsupported::new("typed: bad keep"))? + .push(k); + } + } + let deepest = (0..hir.schema.lists.len()) + .map(|l| hir.schema.depth(Scope::Elem(l as u16))) + .max() + .unwrap_or(0); + let mut b = Build { + hir, + sig, + classes, + bases, + passes, + rep: Vec::with_capacity(n), + level: vec![0; n], + stage: vec![usize::MAX; n], + keys: Vec::new(), + users, + outs, + keeps, + period: (deepest + 1).max(2), + cross: vec![false; n], + acc: vec![usize::MAX; n], + code: Vec::new(), + cur: 0, + vreg: HashMap::new(), + next: 0, + pinned: Vec::new(), + consts: Vec::new(), + const_of: HashMap::new(), + defs: Vec::new(), + buf_of: vec![None; n], + sel_need: vec![false; n], + picks: HashMap::new(), + }; + for i in 0..n { + let r = b.rep_of(i)?; + b.rep.push(r); + } + for (i, node) in hir.nodes.iter().enumerate() { + if let Op::Pick(sel, arms) = &node.op { + let plan = b.pick_plan(arms); + if plan.iter().any(|(a, _)| !matches!(a, Arm::Node(_))) { + if let Some(x) = b.sel_need.get_mut(*sel as usize) { + *x = true; + } + } + b.picks.insert(i as NodeId, plan); + } + } + b.levels()?; + b.stages()?; + Ok(b) + } + + fn is_const(&self, i: NodeId) -> bool { + matches!(self.hir.nodes[i as usize].op, Op::Const(_)) + } + + fn konst_num(&self, i: NodeId) -> Option { + match &self.hir.nodes[i as usize].op { + Op::Const(Lit::Num(d)) => Some(*d), + _ => None, + } + } + + fn rep_of(&self, i: usize) -> Result { + let hir = self.hir; + let node = &hir.nodes[i]; + let r = |x: &NodeId| self.rep[*x as usize]; + Ok(match &node.op { + Op::Column(c) => { + let def = hir + .schema + .columns + .get(*c as usize) + .ok_or_else(|| Unsupported::new("typed: column"))?; + Rep::of_kind(def.ty.kind, self.sig.get(*c as usize).copied().flatten()) + } + Op::Field(l, f) => { + let def = hir + .schema + .lists + .get(*l as usize) + .and_then(|x| x.fields.get(*f as usize)) + .ok_or_else(|| Unsupported::new("typed: field"))?; + let at = self.bases.get(*l as usize).map(|b| b + *f as usize); + Rep::of_kind( + def.ty.kind, + at.and_then(|a| self.sig.get(a).copied().flatten()), + ) + } + Op::Parent(a) | Op::Neg(a) => r(a), + Op::Const(lit) => Rep::of_lit(lit), + Op::Classify(..) => Rep::Code, + Op::Str(_) | Op::Decode(_) | Op::Concat(_) | Op::Clock(Clock::Text, _) => Rep::Text, + Op::Clock(Clock::Matches, _) => Rep::Bool, + Op::Clock(Clock::Now | Clock::Coerce | Clock::Strict, _) => Rep::Date, + Op::Host(..) => Rep::of_kind(node.ty.kind, None), + Op::Call(Func::Upper | Func::Lower | Func::Trim, _) => Rep::Text, + Op::Call(Func::Contains | Func::Matches, _) => Rep::Bool, + Op::Not(_) + | Op::Cmp(..) + | Op::And(..) + | Op::Or(..) + | Op::InSet(..) + | Op::InRange(..) => Rep::Bool, + Op::Arith(op, a, b) => match (op, r(a), r(b)) { + (Arith::Add | Arith::Sub, Rep::Fix(x), Rep::Fix(y)) if x == y => Rep::Fix(x), + (Arith::Mul, Rep::Fix(0), Rep::Fix(0)) => Rep::Fix(0), + _ => Rep::Dyn, + }, + Op::If(_, t, e) => Rep::join(r(t), r(e))?, + Op::Coalesce(a, b) => Rep::join(r(a), r(b))?, + Op::Pick(_, arms) => arms + .iter() + .try_fold(Rep::Null, |acc, a| Rep::join(acc, r(a)))?, + Op::Fold { + fold: Fold::Sum, + value: Some(v), + .. + } => match r(v) { + Rep::Fix(0) => Rep::Fix(0), + _ => Rep::Dyn, + }, + Op::Fold { + fold: Fold::Sum | Fold::Min | Fold::Max | Fold::Avg, + value: None, + .. + } => return Err(Unsupported::new("typed: fold without value")), + Op::Fold { + fold: Fold::Min | Fold::Max, + value: Some(v), + .. + } => match r(v) { + Rep::Fix(s) => Rep::Fix(s), + Rep::Date => Rep::Date, + _ => Rep::Dyn, + }, + Op::Fold { + fold: Fold::Avg, .. + } => Rep::Dyn, + Op::Fold { fold, .. } if fold.quantifier() => Rep::Bool, + Op::Fold { .. } | Op::FirstMatch { .. } | Op::Call(Func::Len, _) => Rep::Fix(0), + Op::Call(Func::StartsWith | Func::EndsWith, _) => Rep::Bool, + Op::Call(Func::Abs, args) => args.first().map_or(Rep::Dyn, r), + Op::Call(Func::Floor | Func::Ceil, _) => Rep::Fix(0), + Op::Call(Func::Round(p), args) => match args.first().map(r) { + Some(Rep::Fix(s)) => Rep::Fix(s.min(*p)), + _ => Rep::Dyn, + }, + Op::Call(Func::Trunc(p), _) => Rep::Fix(*p), + Op::Call(Func::Min | Func::Max, args) => match args.split_first() { + Some((first, rest)) + if matches!(r(first), Rep::Fix(_) | Rep::Date) + && rest.iter().all(|a| r(a) == r(first)) => + { + r(first) + } + _ => Rep::Dyn, + }, + }) + } + + fn depth(&self, scope: Scope) -> u32 { + self.hir.schema.depth(scope) + } + + fn round(&self, level: u32, depth: u32) -> u32 { + let p = self.period; + level + (depth % p + p - level % p) % p + } + + fn levels(&mut self) -> Result<(), Unsupported> { + let hir = self.hir; + let schema = &hir.schema; + for (i, node) in hir.nodes.iter().enumerate() { + if matches!(node.op, Op::Const(_)) { + continue; + } + let depth = self.depth(node.scope); + let mut l = match node.op { + Op::Field(..) => depth, + Op::Fold { .. } => depth + 2, + _ => 0, + }; + for inp in node.op.inputs() { + if self.is_const(inp) { + continue; + } + let s = hir.nodes[inp as usize].scope; + let bump = match &node.op { + _ if s == node.scope => 0, + Op::Fold { .. } if schema.owner(s) == Some(node.scope) => 1, + Op::Parent(_) if schema.owner(node.scope) == Some(s) => 1, + _ => return Err(Unsupported::new("typed: scope crossing")), + }; + l = l.max(self.level[inp as usize] + bump); + } + self.level[i] = self.round(l, depth); + } + for i in (0..hir.nodes.len()).rev() { + let node = &hir.nodes[i]; + if matches!(node.op, Op::Const(_)) + || node.scope != Scope::Row + || self.users[i].is_empty() + { + continue; + } + let mut latest = u32::MAX; + for &u in &self.users[i] { + let lu = match hir.nodes[u as usize].scope { + Scope::Row => self.level[u as usize], + Scope::Elem(_) => self.level[u as usize].saturating_sub(1), + }; + latest = latest.min(lu); + } + let l = latest - latest % self.period; + if l > self.level[i] && latest != u32::MAX { + self.level[i] = l; + } + } + Ok(()) + } + + fn scope_ord(s: Scope) -> u32 { + match s { + Scope::Row => 0, + Scope::Elem(l) => 1 + l as u32, + } + } + + fn const_level(&self, scope: Scope) -> u32 { + self.depth(scope) + } + + fn accumulates(&self, i: usize) -> u32 { + let node = &self.hir.nodes[i]; + let Op::Fold { list, .. } = node.op else { + return 0; + }; + let base = self.depth(Scope::Elem(list)); + node.op + .inputs() + .into_iter() + .filter(|x| !self.is_const(*x)) + .map(|x| self.level[x as usize]) + .fold(base, u32::max) + } + + fn stages(&mut self) -> Result<(), Unsupported> { + let hir = self.hir; + let mut keys: Vec<(u32, Scope)> = Vec::new(); + let mut add = |k: (u32, Scope)| { + if !keys.contains(&k) { + keys.push(k); + } + }; + for (i, node) in hir.nodes.iter().enumerate() { + if matches!(node.op, Op::Const(_)) { + continue; + } + add((self.level[i], node.scope)); + if let Op::Fold { list, .. } = node.op { + add((self.accumulates(i), Scope::Elem(list))); + } + } + for o in &hir.outputs { + let keep = o + .collect + .and_then(|c| c.keep) + .is_some_and(|k| self.is_const(k)); + if self.is_const(o.node) || keep { + add((self.const_level(o.scope), o.scope)); + } + } + keys.sort_by_key(|(l, s)| (*l, Self::scope_ord(*s))); + let find = |k: (u32, Scope)| { + keys.iter() + .position(|x| *x == k) + .ok_or_else(|| Unsupported::new("typed: stage")) + }; + for (i, node) in hir.nodes.iter().enumerate() { + if matches!(node.op, Op::Const(_)) { + continue; + } + self.stage[i] = find((self.level[i], node.scope))?; + if let Op::Fold { list, .. } = node.op { + self.acc[i] = find((self.accumulates(i), Scope::Elem(list)))?; + } + } + for (i, node) in hir.nodes.iter().enumerate() { + if matches!(node.op, Op::Const(_)) { + continue; + } + for &u in &self.users[i] { + if self.direct(i as NodeId) && !self.wants(u, i as NodeId) { + continue; + } + let cs = match hir.nodes[u as usize].op { + Op::Fold { .. } => self.acc[u as usize], + _ => self.stage[u as usize], + }; + if cs != self.stage[i] { + self.cross[i] = true; + } + } + match node.op { + Op::Fold { + list, fold, empty, .. + } => { + let def = BufDef { + scope: node.scope, + fold: Some((list, fold, self.rep[i], empty)), + stage: self.acc[i], + }; + self.buf_of[i] = Some(self.new_buf(def)?); + } + _ if self.cross[i] => { + self.buf_of[i] = Some(self.new_buf(BufDef { + scope: node.scope, + fold: None, + stage: self.stage[i], + })?); + } + _ => {} + } + } + self.keys = keys; + Ok(()) + } + + fn new_buf(&mut self, def: BufDef) -> Result { + let id = u16::try_from(self.defs.len()).map_err(|_| Unsupported::new("typed: buffers"))?; + self.defs.push(def); + Ok(id) + } + + fn fresh(&mut self) -> Result { + let r = R::try_from(self.next).map_err(|_| Unsupported::new("typed: registers"))?; + self.next += 1; + self.pinned.push(false); + Ok(r) + } + + fn emit(&mut self, ins: Ins) { + self.code[self.cur].push(ins); + } + + fn konst(&mut self, lit: Lit, rep: Rep) -> Result { + if let Some(r) = self.const_of.get(&(lit.clone(), rep)) { + return Ok(*r); + } + let r = self.fresh()?; + self.pinned[r as usize] = true; + self.consts.push((r, rep, lit.clone())); + self.const_of.insert((lit, rep), r); + Ok(r) + } + + fn konst_node(&mut self, i: NodeId) -> Result { + match &self.hir.nodes[i as usize].op { + Op::Const(lit) => self.konst(lit.clone(), self.rep[i as usize]), + _ => Err(Unsupported::new("typed: not a constant")), + } + } + + fn buf(&self, i: NodeId) -> Result { + self.buf_of[i as usize].ok_or_else(|| Unsupported::new("typed: missing buffer")) + } + + fn slot(k: usize) -> Result { + u16::try_from(k).map_err(|_| Unsupported::new("typed: slots")) + } + + fn emit_all(&mut self) -> Result<(), Unsupported> { + let hir = self.hir; + for s in 0..self.keys.len() { + self.cur = s; + self.code.push(Vec::new()); + let (level, scope) = self.keys[s]; + for (k, o) in hir.outputs.iter().enumerate() { + if o.scope != scope || self.const_level(scope) != level { + continue; + } + if self.is_const(o.node) { + let src = self.konst_node(o.node)?; + self.emit(Ins::Out { + slot: Self::slot(k)?, + src, + rep: self.rep[o.node as usize], + scope: o.scope, + }); + } + if let Some(keep) = o.collect.and_then(|c| c.keep).filter(|k| self.is_const(*k)) { + let src = self.konst_node(keep)?; + self.emit(Ins::Keep { + slot: Self::slot(k)?, + src, + }); + } + } + for i in 0..hir.nodes.len() { + if self.stage[i] != s { + continue; + } + let feeds = self.users[i].iter().any(|&u| self.acc[u as usize] == s); + if !self.outs[i].is_empty() || !self.keeps[i].is_empty() || self.cross[i] || feeds { + self.ensure(i as NodeId)?; + } + } + for f in 0..hir.nodes.len() { + if self.acc[f] != s { + continue; + } + let Op::Fold { + fold, + list, + filter, + value, + .. + } = hir.nodes[f].op + else { + continue; + }; + let filter = filter.map(|x| self.val(x)).transpose()?; + let value = match (fold, value) { + (Fold::Count, _) | (_, None) => None, + (_, Some(v)) => Some((self.val(v)?, self.rep[v as usize])), + }; + let buf = self.buf(f as NodeId)?; + self.emit(Ins::Fold { + fold, + buf, + list, + filter, + value, + }); + } + } + Ok(()) + } + + fn val(&mut self, i: NodeId) -> Result { + let at = i as usize; + if self.is_const(i) { + return self.konst_node(i); + } + if let Some(r) = self.vreg.get(&(self.cur, i)) { + return Ok(*r); + } + if self.stage[at] == self.cur { + self.ensure(i)?; + return self + .vreg + .get(&(self.cur, i)) + .copied() + .ok_or_else(|| Unsupported::new("typed: ensure")); + } + if self.hir.nodes[at].scope != self.keys[self.cur].1 { + return Err(Unsupported::new("typed: cross-scope read")); + } + let buf = self.buf(i)?; + let d = self.fresh()?; + self.emit(Ins::Fill { + dst: d, + buf, + rep: self.rep[at], + }); + self.vreg.insert((self.cur, i), d); + Ok(d) + } + + fn direct(&self, i: NodeId) -> bool { + self.rep[i as usize] == Rep::Text + && matches!(self.hir.nodes[i as usize].op, Op::Column(_) | Op::Field(..)) + } + + fn wants(&self, u: NodeId, i: NodeId) -> bool { + let user = &self.hir.nodes[u as usize]; + let argful = match &user.op { + Op::Classify(..) | Op::Concat(_) | Op::Str(_) | Op::Host(..) | Op::Clock(..) => true, + Op::Call(f, _) => f.text(), + Op::Cmp(_, a, b) => { + self.rep[*a as usize] == Rep::Text && self.rep[*b as usize] == Rep::Text + } + _ => false, + }; + !(argful && user.scope == self.hir.nodes[i as usize].scope) + } + + fn arg(&mut self, i: NodeId) -> Result { + let scope = self.keys[self.cur].1; + let direct = self.direct(i); + match &self.hir.nodes[i as usize].op { + Op::Column(c) if direct && scope == Scope::Row => Ok(Arg::Src(Src::Col(*c))), + Op::Field(l, f) if direct && scope == Scope::Elem(*l) => { + Ok(Arg::Src(Src::Field(*l, *f))) + } + Op::Const(Lit::Text(s)) => Ok(Arg::Lit(s.clone())), + _ => Ok(Arg::Reg(self.val(i)?)), + } + } + + fn args(&mut self, args: &[NodeId]) -> Result, Unsupported> { + let mut out = Vec::with_capacity(args.len()); + for a in args { + out.push((self.arg(*a)?, self.rep[*a as usize])); + } + Ok(out) + } + + fn pattern(&self, i: NodeId) -> Result, Unsupported> { + match &self.hir.nodes[i as usize].op { + Op::Const(Lit::Text(s)) => Pattern::new(s) + .map(Box::new) + .map_err(|_| Unsupported::new("typed: invalid pattern")), + _ => Err(Unsupported::new("typed: pattern is not a literal")), + } + } + + fn cost(&self, i: usize) -> u32 { + let rep = self.rep[i]; + match &self.hir.nodes[i].op { + Op::Const(_) => 0, + Op::Arith(Arith::Div, _, b) => match self.konst_num(*b).and_then(Dec::power) { + Some(_) => 4, + None => 30, + }, + Op::Arith(Arith::Rem | Arith::Pow, ..) | Op::Host(..) | Op::Clock(..) => 30, + Op::Arith(Arith::Mul, ..) if rep != Rep::Dyn => 2, + Op::Arith(..) | Op::Neg(_) if rep == Rep::Dyn => 6, + Op::Call(..) => 4, + _ => 1, + } + } + + fn excl(&self, x: NodeId, r: NodeId) -> Vec { + let ok = |m: usize| { + !matches!(self.hir.nodes[m].op, Op::Const(_)) + && self.stage[m] == self.cur + && self.outs[m].is_empty() + && self.keeps[m].is_empty() + && !self.cross[m] + && !self.direct(m as NodeId) + && !self.vreg.contains_key(&(self.cur, m as NodeId)) + && !self.users[m].is_empty() + }; + let r = r as usize; + if !ok(r) || self.users[r].iter().any(|&u| u != x) { + return Vec::new(); + } + let mut mark = vec![false; self.hir.nodes.len()]; + mark[r] = true; + let mut set = vec![r as NodeId]; + for m in (0..r).rev() { + if ok(m) && self.users[m].iter().all(|&u| mark[u as usize]) { + mark[m] = true; + set.push(m as NodeId); + } + } + set.reverse(); + set + } + + fn arms(&mut self, x: NodeId, guards: Vec<(Guard, NodeId)>) -> Result, Unsupported> { + let mut plans = Vec::with_capacity(guards.len()); + for (g, r) in guards { + let set = match self.passes.skip { + true => self.excl(x, r), + false => Vec::new(), + }; + let cost: u32 = set.iter().map(|m| self.cost(*m as usize)).sum(); + let skip = !set.is_empty() && cost >= self.passes.skip_min; + plans.push((g, r, set, skip)); + } + for (_, _, set, skip) in &plans { + if !*skip { + continue; + } + for &m in set { + if matches!( + self.hir.nodes[m as usize].op, + Op::Parent(_) | Op::Fold { .. } + ) { + continue; + } + for inp in self.hir.nodes[m as usize].op.inputs() { + if !set.contains(&inp) + && !self.is_const(inp) + && (!self.direct(inp) || self.wants(m, inp)) + { + self.val(inp)?; + } + } + } + } + let mut regs = Vec::with_capacity(plans.len()); + for (g, r, _, skip) in plans { + if skip { + let at = self.code[self.cur].len(); + self.emit(Ins::Skip { guard: g, len: 0 }); + let v = self.val(r)?; + let len = u32::try_from(self.code[self.cur].len() - at - 1) + .map_err(|_| Unsupported::new("typed: skip"))?; + if let Some(Ins::Skip { len: l, .. }) = self.code[self.cur].get_mut(at) { + *l = len; + } + regs.push(v); + } else { + regs.push(self.val(r)?); + } + } + Ok(regs) + } + + fn mul_const(&self, arm: NodeId) -> Option<(NodeId, Dec)> { + let (x, c) = match self.hir.nodes[arm as usize].op { + Op::Arith(Arith::Mul, a, b) => match (self.konst_num(a), self.konst_num(b)) { + (None, Some(c)) => (a, c), + (Some(c), None) => (b, c), + _ => return None, + }, + _ => return None, + }; + matches!(self.rep[x as usize], Rep::Fix(_)).then_some((x, c)) + } + + fn pick_plan(&self, arms: &[NodeId]) -> Vec<(Arm, Vec)> { + let mut nodes: Vec<(NodeId, Vec)> = Vec::new(); + for (k, a) in arms.iter().enumerate() { + let k = k as u16; + match nodes.iter_mut().find(|g| g.0 == *a) { + Some(g) => g.1.push(k), + None => nodes.push((*a, vec![k])), + } + } + if !self.passes.factor || arms.len() >= Tab::MAX { + return nodes + .into_iter() + .map(|(n, idx)| (Arm::Node(n), idx)) + .collect(); + } + let lit = |n: NodeId| matches!(&self.hir.nodes[n as usize].op, Op::Const(l) if !matches!(l, Lit::Text(_) | Lit::Date(_))); + let mut plan = Vec::new(); + if nodes.iter().filter(|(n, _)| lit(*n)).count() >= 2 { + let mut idx: Vec = nodes + .iter() + .filter(|(n, _)| lit(*n)) + .flat_map(|(_, i)| i.clone()) + .collect(); + idx.sort_unstable(); + nodes.retain(|(n, _)| !lit(*n)); + plan.push((Arm::Tab, idx)); + } + let mut xs: Vec = Vec::new(); + for (n, _) in &nodes { + if let Some((x, _)) = self.mul_const(*n) { + if !xs.contains(&x) + && nodes + .iter() + .filter(|(m, _)| self.mul_const(*m).map(|p| p.0) == Some(x)) + .count() + >= 2 + { + xs.push(x); + } + } + } + for x in xs { + let mut idx: Vec = nodes + .iter() + .filter(|(m, _)| self.mul_const(*m).map(|p| p.0) == Some(x)) + .flat_map(|(_, i)| i.clone()) + .collect(); + idx.sort_unstable(); + nodes.retain(|(m, _)| self.mul_const(*m).map(|p| p.0) != Some(x)); + plan.push((Arm::Mul(x), idx)); + } + nodes + .into_iter() + .map(|(n, idx)| (Arm::Node(n), idx)) + .chain(plan) + .collect() + } + + fn table(&self, arms: &[NodeId], idx: &[u16], filler: bool) -> (Tab, Rep) { + let mut entries: Vec> = vec![None; arms.len() + 1]; + let mut rep = Rep::Null; + let mut first = None; + for &k in idx { + let lit = match &self.hir.nodes[arms[k as usize] as usize].op { + Op::Const(l) => Some(l.clone()), + _ => self.mul_const(arms[k as usize]).map(|(_, c)| Lit::Num(c)), + }; + if let Some(l) = &lit { + rep = Rep::join(rep, Rep::of_lit(l)).unwrap_or(Rep::Dyn); + first.get_or_insert_with(|| l.clone()); + } + entries[k as usize] = lit; + } + if filler { + for e in entries.iter_mut().take(arms.len()) { + if e.is_none() { + *e = first.clone(); + } + } + } + (Tab::new(&entries), rep) + } + + fn needs_sel(&self, i: NodeId) -> bool { + let at = i as usize; + self.sel_need[at] + || !self.passes.elide + || !self.outs[at].is_empty() + || self.cross[at] + || self.users[at] + .iter() + .any(|&u| match &self.hir.nodes[u as usize].op { + Op::Pick(s, arms) => *s != i || arms.contains(&i), + _ => true, + }) + } + + fn arith(&mut self, op: Arith, a: NodeId, b: NodeId, rep: Rep) -> Result { + let (ra, rb) = (self.rep[a as usize], self.rep[b as usize]); + let power = match op { + Arith::Div => self + .konst_num(b) + .and_then(|d| d.power().map(|k| (k, d.scale))), + _ => None, + }; + let va = self.val(a)?; + let d = self.fresh()?; + let ins = match (op, rep, power) { + (Arith::Add, Rep::Fix(_), _) => Ins::Fix { + op: FixOp::Add, + dst: d, + a: va, + b: self.val(b)?, + rep, + }, + (Arith::Sub, Rep::Fix(_), _) => Ins::Fix { + op: FixOp::Sub, + dst: d, + a: va, + b: self.val(b)?, + rep, + }, + (Arith::Mul, Rep::Fix(_), _) => Ins::Fix { + op: FixOp::Mul, + dst: d, + a: va, + b: self.val(b)?, + rep, + }, + (Arith::Div, _, Some((k, by))) => Ins::DivPow { + dst: d, + a: va, + ra, + k, + by, + }, + _ => Ins::Num { + op, + dst: d, + a: va, + ra, + b: self.val(b)?, + rb, + }, + }; + self.emit(ins); + Ok(d) + } + + fn select(&self, t: NodeId, e: NodeId, rep: Rep) -> Option<(i64, i64)> { + let lit = |n: NodeId| match (&self.hir.nodes[n as usize].op, rep) { + (Op::Const(Lit::Num(d)), Rep::Fix(s)) if d.scale == s => Some(d.mant), + (Op::Const(Lit::Code(_, c)), Rep::Code) => Some(*c as i64), + (Op::Const(Lit::Bool(b)), Rep::Bool) => Some(*b as i64), + _ => None, + }; + lit(t).zip(lit(e)) + } + + fn flip(op: Cmp) -> Cmp { + match op { + Cmp::Lt => Cmp::Gt, + Cmp::Le => Cmp::Ge, + Cmp::Gt => Cmp::Lt, + Cmp::Ge => Cmp::Le, + other => other, + } + } + + fn cmp_num(&mut self, op: Cmp, a: NodeId, b: NodeId) -> Result { + let (ra, rb) = (self.rep[a as usize], self.rep[b as usize]); + if self.passes.fold { + if let Some(k) = self.konst_num(b) { + let va = self.val(a)?; + let (tab, fits) = K::table(k); + return Ok(Ins::CmpNumK { + op, + dst: self.fresh()?, + a: va, + ra, + k, + tab, + fits, + }); + } + if let Some(k) = self.konst_num(a) { + let vb = self.val(b)?; + let (tab, fits) = K::table(k); + return Ok(Ins::CmpNumK { + op: Self::flip(op), + dst: self.fresh()?, + a: vb, + ra: rb, + k, + tab, + fits, + }); + } + } + let (va, vb) = (self.val(a)?, self.val(b)?); + Ok(Ins::CmpNum { + op, + dst: self.fresh()?, + a: va, + ra, + b: vb, + rb, + }) + } + + fn cmp(&mut self, op: Cmp, a: NodeId, b: NodeId) -> Result { + let (ra, rb) = (self.rep[a as usize], self.rep[b as usize]); + let eq = matches!(op, Cmp::Eq | Cmp::Ne); + let ne = op == Cmp::Ne; + let up = |x: Option, s: u8| x.and_then(|d| d.upscale(s)); + let ins = match (ra, rb) { + (Rep::Fix(x), Rep::Fix(y)) if x == y => { + let (va, vb) = (self.val(a)?, self.val(b)?); + Ins::CmpFix { + op, + dst: self.fresh()?, + a: va, + b: vb, + rep: ra, + } + } + (Rep::Fix(x), Rep::Fix(y)) + if self.passes.fold && x < y && up(self.konst_num(a), y).is_some() => + { + let u = + up(self.konst_num(a), y).ok_or_else(|| Unsupported::new("typed: upscale"))?; + let k = self.konst(Lit::Num(u), Rep::Fix(y))?; + let vb = self.val(b)?; + Ins::CmpFix { + op, + dst: self.fresh()?, + a: k, + b: vb, + rep: rb, + } + } + (Rep::Fix(x), Rep::Fix(y)) + if self.passes.fold && y < x && up(self.konst_num(b), x).is_some() => + { + let u = + up(self.konst_num(b), x).ok_or_else(|| Unsupported::new("typed: upscale"))?; + let k = self.konst(Lit::Num(u), Rep::Fix(x))?; + let va = self.val(a)?; + Ins::CmpFix { + op, + dst: self.fresh()?, + a: va, + b: k, + rep: ra, + } + } + (x, y) if x.num() && y.num() => self.cmp_num(op, a, b)?, + (Rep::Code, Rep::Code) if eq => { + let (va, vb) = (self.val(a)?, self.val(b)?); + Ins::EqCode { + ne, + dst: self.fresh()?, + a: va, + b: vb, + } + } + (Rep::Bool, Rep::Bool) if eq => { + let (va, vb) = (self.val(a)?, self.val(b)?); + Ins::EqBool { + ne, + dst: self.fresh()?, + a: va, + b: vb, + } + } + (Rep::Text, Rep::Text) if eq => { + let (x, y) = (self.arg(a)?, self.arg(b)?); + Ins::EqText { + ne, + dst: self.fresh()?, + a: x, + b: y, + } + } + (Rep::Text, Rep::Null) | (Rep::Null, Rep::Text) if eq => { + let (va, vb) = (self.val(a)?, self.val(b)?); + Ins::CmpGen { + op, + dst: self.fresh()?, + a: va, + ra, + b: vb, + rb, + } + } + (Rep::Text, _) | (_, Rep::Text) => return Err(Unsupported::new("typed: text compare")), + _ => { + let (va, vb) = (self.val(a)?, self.val(b)?); + Ins::CmpGen { + op, + dst: self.fresh()?, + a: va, + ra, + b: vb, + rb, + } + } + }; + let d = ins + .dst() + .ok_or_else(|| Unsupported::new("typed: compare"))?; + self.emit(ins); + Ok(d) + } + + fn pick( + &mut self, + i: NodeId, + sel: NodeId, + arms: &[NodeId], + rep: Rep, + ) -> Result { + if !matches!(self.hir.nodes[sel as usize].op, Op::FirstMatch { .. }) + || self.stage[sel as usize] != self.cur + { + return Err(Unsupported::new("typed: pick without local firstmatch")); + } + let vs = self.val(sel)?; + let plan = self.picks.get(&i).cloned().unwrap_or_default(); + if let [(Arm::Tab, idx)] = plan.as_slice() { + if idx.len() == arms.len() { + let (tab, _) = self.table(arms, idx, false); + let d = self.fresh()?; + self.emit(Ins::PickTab { + dst: d, + sel: vs, + tab, + rep, + }); + return Ok(d); + } + } + let mut out: Vec<(R, Rep, Vec)> = Vec::new(); + let mut guards = Vec::new(); + for (arm, idx) in &plan { + match arm { + Arm::Node(n) => guards.push((Guard::Masks(vs, idx.clone()), *n, idx.clone())), + Arm::Tab => { + let (tab, tr) = self.table(arms, idx, false); + let t = self.fresh()?; + self.emit(Ins::PickTab { + dst: t, + sel: vs, + tab, + rep: tr, + }); + out.push((t, tr, idx.clone())); + } + Arm::Mul(x) => { + let (tab, tr) = self.table(arms, idx, true); + let t = self.fresh()?; + self.emit(Ins::PickTab { + dst: t, + sel: vs, + tab, + rep: tr, + }); + let vx = self.val(*x)?; + let d = self.fresh()?; + let mr = match (self.rep[*x as usize], tr) { + (Rep::Fix(0), Rep::Fix(0)) => { + self.emit(Ins::Fix { + op: FixOp::Mul, + dst: d, + a: vx, + b: t, + rep: Rep::Fix(0), + }); + Rep::Fix(0) + } + (rx, _) => { + self.emit(Ins::Num { + op: Arith::Mul, + dst: d, + a: vx, + ra: rx, + b: t, + rb: tr, + }); + Rep::Dyn + } + }; + out.push((d, mr, idx.clone())); + } + } + } + let regs = self.arms(i, guards.iter().map(|(g, n, _)| (g.clone(), *n)).collect())?; + for ((_, n, idx), r) in guards.into_iter().zip(regs) { + out.push((r, self.rep[n as usize], idx)); + } + let d = self.fresh()?; + self.emit(Ins::Pick { + dst: d, + sel: vs, + arms: out, + rep, + }); + Ok(d) + } + + fn ensure(&mut self, i: NodeId) -> Result<(), Unsupported> { + let cur = self.cur; + if self.vreg.contains_key(&(cur, i)) { + return Ok(()); + } + let hir = self.hir; + let at = i as usize; + let node = &hir.nodes[at]; + let rep = self.rep[at]; + let rof = |b: &Build, x: &NodeId| b.rep[*x as usize]; + let v = match &node.op { + Op::Const(_) => self.konst_node(i)?, + Op::Column(c) => { + let d = self.fresh()?; + self.emit(Ins::Load { + dst: d, + src: Src::Col(*c), + rep, + }); + d + } + Op::Field(l, f) => { + let d = self.fresh()?; + self.emit(Ins::Load { + dst: d, + src: Src::Field(*l, *f), + rep, + }); + d + } + Op::Classify(a, dict) => match self.classes.get(&i).copied() { + Some(k) => { + let d = self.fresh()?; + self.emit(Ins::Load { + dst: d, + src: Src::Class(k), + rep, + }); + d + } + None => { + let x = self.arg(*a)?; + let matcher = Box::new(Matcher::owned(hir.dict(*dict))); + let d = self.fresh()?; + self.emit(Ins::Class { + dst: d, + a: x, + matcher, + }); + d + } + }, + Op::Str(a) => { + let x = self.arg(*a)?; + let d = self.fresh()?; + self.emit(Ins::Str { + dst: d, + a: x, + rep: self.rep[*a as usize], + }); + d + } + Op::Decode(a) => { + let Kind::Code(dict) = hir.nodes[*a as usize].ty.kind else { + return Err(Unsupported::new("typed: decode")); + }; + let values: Arc<[Box]> = hir.dict(dict).values.clone().into(); + let va = self.val(*a)?; + let d = self.fresh()?; + self.emit(Ins::Decode { + dst: d, + a: va, + values, + }); + d + } + Op::Concat(parts) => { + let mut args = Vec::with_capacity(parts.len()); + for p in parts { + args.push(self.arg(*p)?); + } + let d = self.fresh()?; + self.emit(Ins::Concat { + dst: d, + parts: args, + }); + d + } + Op::Parent(a) if self.is_const(*a) => self.konst_node(*a)?, + Op::Parent(a) => { + let Scope::Elem(list) = node.scope else { + return Err(Unsupported::new("typed: parent outside element scope")); + }; + let buf = self.buf(*a)?; + let d = self.fresh()?; + self.emit(Ins::Gather { + dst: d, + buf, + list, + rep, + }); + d + } + Op::Fold { .. } => { + let buf = self.buf(i)?; + let d = self.fresh()?; + self.emit(Ins::Fill { dst: d, buf, rep }); + d + } + Op::Neg(a) => { + let va = self.val(*a)?; + let d = self.fresh()?; + self.emit(Ins::Neg { dst: d, a: va, rep }); + d + } + Op::Not(a) => { + let va = self.val(*a)?; + let d = self.fresh()?; + self.emit(Ins::Not { dst: d, a: va }); + d + } + Op::Arith(op, a, b) => self.arith(*op, *a, *b, rep)?, + Op::Cmp(op, a, b) => self.cmp(*op, *a, *b)?, + Op::And(a, b) | Op::Or(a, b) => { + let and = matches!(node.op, Op::And(..)); + let va = self.val(*a)?; + let g = if and { + Guard::True(va) + } else { + Guard::False(va) + }; + let vb = self + .arms(i, vec![(g, *b)])? + .first() + .copied() + .ok_or_else(|| Unsupported::new("typed: arm"))?; + let d = self.fresh()?; + self.emit(if and { + Ins::And { + dst: d, + a: va, + b: vb, + } + } else { + Ins::Or { + dst: d, + a: va, + b: vb, + } + }); + d + } + Op::If(c, t, e) if self.passes.fold && self.select(*t, *e, rep).is_some() => { + let (tv, ev) = self + .select(*t, *e, rep) + .ok_or_else(|| Unsupported::new("typed: select"))?; + let vc = self.val(*c)?; + let d = self.fresh()?; + self.emit(Ins::SelK { + dst: d, + c: vc, + t: tv, + e: ev, + rep, + }); + d + } + Op::If(c, t, e) => { + let vc = self.val(*c)?; + let vs = self.arms(i, vec![(Guard::True(vc), *t), (Guard::False(vc), *e)])?; + let (rt, re) = (rof(self, t), rof(self, e)); + let d = self.fresh()?; + self.emit(Ins::Blend { + dst: d, + c: vc, + t: vs[0], + rt, + e: vs[1], + re, + rep, + }); + d + } + Op::Coalesce(a, b) => { + let va = self.val(*a)?; + let vb = self + .arms(i, vec![(Guard::Null(va), *b)])? + .first() + .copied() + .ok_or_else(|| Unsupported::new("typed: arm"))?; + let (ra, rb) = (rof(self, a), rof(self, b)); + let d = self.fresh()?; + self.emit(Ins::Coalesce { + dst: d, + a: va, + ra, + b: vb, + rb, + rep, + }); + d + } + Op::InSet(a, set) => { + let ra = rof(self, a); + let va = self.val(*a)?; + let mut bits = 0u64; + let mut null = false; + let mut fast = ra == Rep::Code; + for lit in set { + match lit { + Lit::Code(_, c) if (0..64).contains(c) => bits |= 1u64 << c, + Lit::Null => null = true, + _ => fast = false, + } + } + let d = self.fresh()?; + match fast { + true => self.emit(Ins::InCode { + dst: d, + a: va, + set: bits, + null, + }), + false if ra == Rep::Text => return Err(Unsupported::new("typed: text in-set")), + false => self.emit(Ins::InGen { + dst: d, + a: va, + ra, + set: set.clone(), + }), + } + d + } + Op::InRange(a, r) => { + let ra = rof(self, a); + let va = self.val(*a)?; + let d = self.fresh()?; + let fixed = match (ra, self.passes.fold) { + (Rep::Fix(s), true) => r.lo.upscale(s).zip(r.hi.upscale(s)), + _ => None, + }; + match fixed { + Some((lo, hi)) => { + let lo = if r.lo_closed { + Some(lo.mant) + } else { + lo.mant.checked_add(1) + }; + let hi = if r.hi_closed { + Some(hi.mant) + } else { + hi.mant.checked_sub(1) + }; + let (lo, span, empty) = match lo.zip(hi) { + Some((l, h)) if h >= l => (l, h.wrapping_sub(l) as u64, false), + _ => (0, 0, true), + }; + self.emit(Ins::InRangeFix { + dst: d, + a: va, + lo, + span, + empty, + range: *r, + }) + } + None => self.emit(Ins::InRangeGen { + dst: d, + a: va, + ra, + range: *r, + }), + } + d + } + Op::FirstMatch { conds, strict } => match self.lookup(conds, *strict) { + Some(tab) => self.looked(tab)?, + None => { + let mut vs = Vec::with_capacity(conds.len()); + for c in conds { + vs.push(self.val(*c)?); + } + let sel = self.needs_sel(i); + let d = self.fresh()?; + self.emit(Ins::First { + dst: d, + conds: vs, + sel, + strict: *strict, + }); + d + } + }, + Op::Pick(sel, arms) => self.pick(i, *sel, arms, rep)?, + Op::Clock(Clock::Now, _) => { + let d = self.fresh()?; + self.emit(Ins::Now { dst: d }); + d + } + Op::Clock(clock, args) => { + let args = self.args(args)?; + let d = self.fresh()?; + self.emit(Ins::Clock { + clock: *clock, + dst: d, + args, + }); + d + } + Op::Host(host, args) => { + let fixed = args.iter().skip(1).all(|a| self.is_const(*a)); + let args = self.args(args)?; + let d = self.fresh()?; + self.emit(Ins::Host { + host: *host, + dst: d, + args, + rep, + fixed, + }); + d + } + Op::Call(func, args) if !func.text() => { + let mut vs = Vec::with_capacity(args.len()); + for a in args { + vs.push((self.val(*a)?, self.rep[*a as usize])); + } + let d = self.fresh()?; + self.emit(Ins::Math { + func: *func, + dst: d, + args: vs, + rep, + }); + d + } + Op::Call(func, args) => { + let a = self.arg( + *args + .first() + .ok_or_else(|| Unsupported::new("typed: call"))?, + )?; + let ins = match func { + Func::Matches => { + let pattern = self.pattern( + *args.get(1).ok_or_else(|| Unsupported::new("typed: call"))?, + )?; + Ins::Matches { + dst: self.fresh()?, + a, + pattern, + } + } + f if f.mapping() => Ins::Map { + func: *f, + dst: self.fresh()?, + a, + }, + f => { + let b = args.get(1).map(|x| self.arg(*x)).transpose()?; + Ins::Text { + func: *f, + dst: self.fresh()?, + a, + b, + } + } + }; + let d = ins.dst().ok_or_else(|| Unsupported::new("typed: call"))?; + self.emit(ins); + d + } + }; + self.vreg.insert((cur, i), v); + if self.cross[at] && !matches!(node.op, Op::Fold { .. }) { + let buf = self.buf(i)?; + self.emit(Ins::Spill { src: v, buf, rep }); + } + for k in self.outs[at].clone() { + self.emit(Ins::Out { + slot: Self::slot(k)?, + src: v, + rep, + scope: hir.outputs[k].scope, + }); + } + for k in self.keeps[at].clone() { + self.emit(Ins::Keep { + slot: Self::slot(k)?, + src: v, + }); + } + Ok(()) + } + + fn lookup(&self, conds: &[NodeId], strict: bool) -> Option { + if !self.passes.fold { + return None; + } + let tab = Lookup::plan(self.hir, conds, strict, self.passes.lookup_min)?; + tab.keys + .iter() + .filter_map(|k| k.node) + .all(|n| self.stage[n as usize] == self.cur || self.is_const(n)) + .then_some(tab) + } + + fn looked(&mut self, mut tab: Lookup) -> Result { + let mut keys = Vec::with_capacity(tab.keys.len()); + let mut reps = Vec::with_capacity(tab.keys.len()); + for key in &tab.keys { + match key.node { + Some(n) => { + keys.push(Some((self.val(n)?, self.rep[n as usize]))); + reps.push(self.rep[n as usize]); + } + None => { + keys.push(None); + reps.push(Rep::Null); + } + } + } + tab.fix(&reps); + let d = self.fresh()?; + self.emit(Ins::Lookup { + dst: d, + keys, + tab: Box::new(tab), + }); + Ok(d) + } + + fn finish(self) -> Result { + let Build { + mut code, + keys, + next, + pinned, + consts, + defs, + passes, + .. + } = self; + let mut phys: Vec = (0..next).map(|v| v as R).collect(); + let mut nphys = next; + if passes.reuse { + let mut top = 0usize; + for (v, p) in pinned.iter().enumerate() { + if *p { + phys[v] = top as R; + top += 1; + } + } + let base = top; + let mut most = base; + for stage in &code { + let mut last = vec![usize::MAX; next]; + for (pc, ins) in stage.iter().enumerate() { + let mut copy = ins.clone(); + copy.regs(&mut |r, def| { + if !def { + last[*r as usize] = pc; + } + }); + } + let mut free: Vec = Vec::new(); + let mut top = base; + for (pc, ins) in stage.iter().enumerate() { + let mut uses = Vec::new(); + let mut defs = Vec::new(); + let mut copy = ins.clone(); + copy.regs(&mut |r, def| if def { defs.push(*r) } else { uses.push(*r) }); + for d in defs { + let p = match free.pop() { + Some(p) => p, + None => { + top += 1; + R::try_from(top - 1) + .map_err(|_| Unsupported::new("typed: registers"))? + } + }; + phys[d as usize] = p; + if last[d as usize] == usize::MAX { + free.push(p); + } + } + uses.sort_unstable(); + uses.dedup(); + for u in uses { + if !pinned[u as usize] && last[u as usize] == pc { + free.push(phys[u as usize]); + } + } + } + most = most.max(top); + } + nphys = most; + } + for stage in &mut code { + for ins in stage.iter_mut() { + ins.regs(&mut |r, _| *r = phys[*r as usize]); + } + } + let consts = consts + .into_iter() + .map(|(v, rep, lit)| (phys[v as usize], rep, lit)) + .collect(); + let stages = code + .into_iter() + .zip(keys) + .map(|(code, (_, scope))| Stage { scope, code }) + .collect(); + Ok(Built { + stages, + nregs: nphys, + consts, + defs, + }) + } +} diff --git a/core/expression/src/typed/date.rs b/core/expression/src/typed/date.rs new file mode 100644 index 00000000..23c86553 --- /dev/null +++ b/core/expression/src/typed/date.rs @@ -0,0 +1,378 @@ +use crate::functions::{DateMethod, FunctionKind, InternalFunction, MethodKind}; +use crate::lane::builtins::{Arg as Given, Builtin, Builtins, Dates, Out}; +use crate::lane::date::Date; +use crate::lane::Bits; +use crate::typed::exec::{Buf, Exec, Others, Reg}; +use crate::typed::hir::{Clock, Host}; +use crate::typed::ins::{Arg, Ins, Rep}; +use crate::typed::num::{Dec, N}; +use crate::typed::text::TV; +use crate::variable::Variable; +use smallvec::SmallVec; + +#[derive(Clone, Copy)] +enum DV<'a, 'x> { + Text(TV<'a, 'x>), + Reg(&'a Reg, Rep), +} + +impl Host { + pub(crate) fn builtin(self) -> Option<&'static Builtin> { + match self { + Host::Construct => Builtins::of(&FunctionKind::Internal(InternalFunction::Date)), + Host::Legacy(function) => Builtins::of(&FunctionKind::Deprecated(function)), + Host::Method(method) => Some(Builtins::method(&MethodKind::DateMethod(method))), + } + } +} + +impl<'a, 'x> DV<'a, 'x> { + #[inline] + fn given(self, start: usize, i: usize) -> Option> { + match self { + DV::Text(text) => match text.get(start, i) { + None => Some(Given::Null), + Some(bytes) => std::str::from_utf8(bytes).ok().map(Given::Str), + }, + DV::Reg(r, _) if !Bits::get(&r.valid, i) => Some(Given::Null), + DV::Reg(r, rep) => Some(match rep { + Rep::Fix(_) | Rep::Dyn => Given::Num(r.num(rep, i).decimal()), + Rep::Bool => Given::Bool(Bits::get(&r.bits, i)), + Rep::Date => Given::Date(r.date(i)), + Rep::Null => Given::Null, + Rep::Text | Rep::Code => return None, + }), + } + } + + #[inline] + fn bad(self, start: usize, w: usize) -> u64 { + match self { + DV::Text(text) => text.bad(start, w), + DV::Reg(r, _) => r.fault[w], + } + } +} + +impl Reg { + pub(crate) fn stamps(&mut self) { + if self.dates.len() < Reg::LANES { + self.dates.resize(Reg::LANES, Date(None)); + } + } + + #[inline] + pub(crate) fn date(&self, i: usize) -> Date { + self.dates.get(i).copied().unwrap_or(Date(None)) + } + + #[inline] + fn store(&mut self, rep: Rep, i: usize, out: Out) -> bool { + match (rep, out) { + (_, Out::Var(Variable::Null)) => Bits::set(&mut self.valid, i, false), + (Rep::Date, Out::Date(date)) => self.dates[i] = date, + (Rep::Fix(_) | Rep::Dyn, Out::Num(n)) => self.keep(rep, i, N::of(n)), + (Rep::Bool, Out::Bool(b)) => Bits::set(&mut self.bits, i, b), + (Rep::Text, Out::Str(s)) => self.push(i, s.as_bytes()), + _ => return false, + } + true + } +} + +impl Buf { + pub(crate) fn stamps(&mut self) { + if self.dates.len() < self.mant.len() { + self.dates.resize(self.mant.len(), Date(None)); + } + } +} + +impl<'e, 'x> Exec<'e, 'x> { + fn same(a: &Given, b: &Given) -> bool { + match (a, b) { + (Given::Null, Given::Null) => true, + (Given::Num(x), Given::Num(y)) => { + x.mantissa() == y.mantissa() && x.scale() == y.scale() + } + (Given::Bool(x), Given::Bool(y)) => x == y, + (Given::Str(x), Given::Str(y)) => x == y, + (Given::Date(x), Given::Date(y)) => { + x == y && x.0.map(|at| at.timezone()) == y.0.map(|at| at.timezone()) + } + _ => false, + } + } + + fn dated<'a>(&'a self, arg: &'a Arg, rep: Rep, regs: &'a Others) -> DV<'a, 'x> { + match (arg, rep) { + (Arg::Reg(r), rep) if rep != Rep::Text => DV::Reg(®s[*r as usize], rep), + _ => DV::Text(self.view(arg, regs)), + } + } + + fn broken(d: &mut Reg, lanes: Vec) { + lanes + .into_iter() + .for_each(|i| Bits::set(&mut d.fault, i, true)); + } + + pub(crate) fn date(&self, ins: &Ins, regs: &mut [Reg], act: Option<&[u64; Reg::WORDS]>) { + let (n, words, start) = (self.n, self.words.min(Reg::WORDS), self.start); + match ins { + Ins::Now { dst } => Self::def(regs, *dst, |d, _| { + d.stamps(); + d.dates[..n].fill(self.feeds.now); + d.valid[..words].fill(u64::MAX); + d.fault[..words].fill(0); + }), + Ins::Host { + host, + dst, + args, + rep, + fixed, + } => Self::def(regs, *dst, |d, regs| { + let views: SmallVec<[DV; 4]> = + args.iter().map(|(a, r)| self.dated(a, *r, regs)).collect(); + for w in 0..words { + d.valid[w] = u64::MAX; + d.fault[w] = + views.iter().fold(0, |acc, v| acc | v.bad(start, w)) & self.tail(w); + } + match rep { + Rep::Text => d.texts(n), + Rep::Date => d.stamps(), + _ => {} + } + let Some(builtin) = host.builtin() else { + for w in 0..words { + d.fault[w] = self.tail(w); + } + return; + }; + let skip = d.fault; + let mut broken = Vec::new(); + if let (Host::Construct, [DV::Text(text)]) = (host, views.as_slice()) { + d.stamps(); + let mut last: Option<(&[u8], Date)> = None; + self.each(act, &skip, |i| { + let bytes = text.get(start, i); + let date = match (bytes, last) { + (Some(b), Some((prev, date))) if prev == b => Some(date), + (Some(b), _) => { + std::str::from_utf8(b).ok().map(|t| Date::text(t, None)) + } + (None, _) => Some(Date(None)), + }; + match date { + Some(date) => { + d.dates[i] = date; + last = bytes.map(|b| (b, date)); + } + None => broken.push(i), + } + }); + Self::broken(d, broken); + return; + } + if let (Host::Method(method), true) = (host, *fixed) { + if let Some(broken) = self.quick(*method, &views, *rep, d, act) { + Self::broken(d, broken); + return; + } + } + let mut given: SmallVec<[Given; 4]> = SmallVec::new(); + let mut seen: SmallVec<[Given; 4]> = SmallVec::new(); + let mut last: Option> = None; + self.each(act, &skip, |i| { + given.clear(); + for v in &views { + match v.given(start, i) { + Some(g) => given.push(g), + None => { + broken.push(i); + return; + } + } + } + let repeated = last.is_some() + && seen.len() == given.len() + && seen.iter().zip(&given).all(|(a, b)| Self::same(a, b)); + if !repeated { + last = Some(Builtins::raw(builtin, &given).ok()); + seen.clear(); + seen.extend(given.iter().copied()); + } + let stored = last + .clone() + .flatten() + .is_some_and(|out| d.store(*rep, i, out)); + if !stored { + broken.push(i); + } + }); + Self::broken(d, broken); + }), + Ins::Clock { clock, dst, args } => Self::def(regs, *dst, |d, regs| { + let views: SmallVec<[DV; 2]> = + args.iter().map(|(a, r)| self.dated(a, *r, regs)).collect(); + for w in 0..words { + d.valid[w] = u64::MAX; + d.fault[w] = + views.iter().fold(0, |acc, v| acc | v.bad(start, w)) & self.tail(w); + } + let skip = d.fault; + let mut broken = Vec::new(); + match (clock, views.as_slice()) { + (Clock::Coerce, [text]) => { + d.stamps(); + self.each(act, &skip, |i| match text.given(start, i) { + Some(Given::Str(t)) => match Date::from_text(t) { + date if date.is_valid() => d.dates[i] = date, + _ => broken.push(i), + }, + _ => broken.push(i), + }); + } + (Clock::Strict, [date]) => { + d.stamps(); + self.each(act, &skip, |i| match date.given(start, i) { + Some(Given::Date(x)) if x.is_valid() => d.dates[i] = x, + _ => broken.push(i), + }); + } + (Clock::Text, [date]) => { + d.texts(n); + let mut last = None; + self.each(act, &skip, |i| match date.given(start, i) { + Some(Given::Date(x)) => { + let key = (x, x.0.map(|at| at.timezone())); + if last.as_ref().is_none_or(|(seen, _)| *seen != key) { + last = Some((key, x.rendered())); + } + match last.as_ref().and_then(|(_, text)| text.as_deref()) { + Some(text) => d.push(i, text.as_bytes()), + None => broken.push(i), + } + } + _ => Bits::set(&mut d.valid, i, false), + }); + } + (Clock::Matches, [date, text]) => { + self.bools(act, &mut d.bits, |i| { + match (date.given(start, i), text.given(start, i)) { + (Some(Given::Date(x)), Some(Given::Str(t))) => { + x.is_valid() && Date::from_text(t) == x + } + (Some(Given::Date(x)), Some(Given::Date(y))) => { + x.is_valid() && x == y + } + _ => false, + } + }); + } + _ => { + for w in 0..words { + d.fault[w] = self.tail(w); + } + } + } + Self::broken(d, broken); + }), + _ => {} + } + } + + fn quick( + &self, + method: DateMethod, + views: &[DV], + rep: Rep, + d: &mut Reg, + act: Option<&[u64; Reg::WORDS]>, + ) -> Option> { + let (start, skip) = (self.start, d.fault); + let kind = MethodKind::DateMethod(method); + let (this, rest) = views.split_first()?; + let mut consts: SmallVec<[Given; 4]> = SmallVec::new(); + consts.push(Given::Null); + for v in rest { + consts.push(v.given(start, 0)?); + } + let mut broken = Vec::new(); + let part = matches!( + method, + DateMethod::Second + | DateMethod::Minute + | DateMethod::Hour + | DateMethod::Day + | DateMethod::Weekday + | DateMethod::DayOfYear + | DateMethod::Week + | DateMethod::Month + | DateMethod::Quarter + | DateMethod::Year + | DateMethod::Timestamp + ); + match rep { + Rep::Date => { + let shift = Dates::shift(&kind, &consts)?; + self.each(act, &skip, |i| match this.given(start, i) { + Some(Given::Date(x)) => d.dates[i] = shift.apply(&x), + _ => broken.push(i), + }); + } + Rep::Fix(_) | Rep::Dyn if part && rest.is_empty() => { + self.each(act, &skip, |i| match this.given(start, i) { + Some(Given::Date(x)) => match Dates::part_of(&kind, &x) { + Some(n) => d.keep(rep, i, N::Dec(Dec::int(n))), + None => Bits::set(&mut d.valid, i, false), + }, + _ => broken.push(i), + }); + } + _ => return None, + } + Some(broken) + } + + pub(crate) fn blend_dates(&self, d: &mut Reg, m: &[u64], t: &Reg, e: &Reg) { + d.stamps(); + for i in 0..self.n { + d.dates[i] = match Bits::get(m, i) { + true => t.date(i), + false => e.date(i), + }; + } + } + + pub(crate) fn pick_dates(&self, d: &mut Reg, m: &[u64], a: &Reg) { + for (w, &word) in m.iter().enumerate() { + Bits::each(word & a.valid[w], w * 64, |i| d.dates[i] = a.date(i)); + } + } + + pub(crate) fn gather_dates(&self, d: &mut Reg, b: &Buf, parent: &[u32]) { + d.stamps(); + for (i, &p) in parent.iter().enumerate() { + d.dates[i] = b.dates.get(p as usize).copied().unwrap_or(Date(None)); + } + } + + pub(crate) fn fill_dates(&self, d: &mut Reg, b: &Buf) { + d.stamps(); + for i in 0..self.n { + d.dates[i] = b.dates.get(self.start + i).copied().unwrap_or(Date(None)); + } + } + + pub(crate) fn spill_dates(&self, r: &Reg, b: &mut Buf) { + b.stamps(); + for i in 0..self.n { + if let Some(slot) = b.dates.get_mut(self.start + i) { + *slot = r.date(i); + } + } + } +} diff --git a/core/expression/src/typed/exec.rs b/core/expression/src/typed/exec.rs new file mode 100644 index 00000000..38ebf666 --- /dev/null +++ b/core/expression/src/typed/exec.rs @@ -0,0 +1,2077 @@ +use crate::lane::date::Date; +use crate::lane::Bits; +use crate::typed::batch::{Data, Feed, Feeds, Lists, Scales}; +use crate::typed::hir::{Arith, Cmp, Fold, Func, Lit, Range, Scope}; +use crate::typed::ins::{FixOp, Guard, Ins, Rep, Src, Tab, R}; +use crate::typed::kernel::K; +use crate::typed::lookup::{Domain, Lookup}; +use crate::typed::num::{Dec, N}; +use crate::typed::output::{Data as SlotData, Outputs}; +use rust_decimal::Decimal; +use std::cmp::Ordering; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum V { + Null, + Num(Dec), + Big(Decimal), + Bool(bool), + Code(i32), + Date(Date), + Other, +} + +#[derive(Clone)] +pub(crate) struct Reg { + pub(crate) mant: Vec, + pub(crate) scale: Vec, + pub(crate) codes: Vec, + pub(crate) bits: [u64; Reg::WORDS], + pub(crate) valid: [u64; Reg::WORDS], + pub(crate) fault: [u64; Reg::WORDS], + pub(crate) wide: [u64; Reg::WORDS], + pub(crate) big: Vec, + pub(crate) masks: Vec, + pub(crate) text: Vec, + pub(crate) span: Vec<(u32, u32)>, + pub(crate) dates: Vec, +} + +#[derive(Clone, Default)] +pub(crate) struct Buf { + pub(crate) mant: Vec, + pub(crate) scale: Vec, + pub(crate) codes: Vec, + pub(crate) bits: Vec, + pub(crate) valid: Vec, + pub(crate) fault: Vec, + pub(crate) wide: Vec, + pub(crate) big: Vec, + pub(crate) any: bool, + pub(crate) text: Vec, + pub(crate) span: Vec<(u32, u32)>, + pub(crate) dates: Vec, +} + +pub(crate) struct Others<'r> { + lo: &'r [Reg], + hi: &'r [Reg], + at: usize, +} + +pub(crate) struct Exec<'e, 'x> { + pub(crate) feeds: &'e Feeds<'x>, + pub(crate) select: Option<&'e [u64]>, + pub(crate) start: usize, + pub(crate) n: usize, + pub(crate) words: usize, +} + +pub(crate) type Stack = Vec<(usize, [u64; Reg::WORDS])>; + +impl V { + fn lit(lit: &Lit) -> V { + match lit { + Lit::Null => V::Null, + Lit::Num(d) => V::Num(*d), + Lit::Bool(b) => V::Bool(*b), + Lit::Code(_, c) => V::Code(*c), + Lit::Text(_) => V::Other, + Lit::Date(d) => V::Date(d.date()), + } + } + + fn number(self) -> Option { + match self { + V::Num(d) => Some(N::Dec(d)), + V::Big(d) => Some(N::Big(d)), + _ => None, + } + } + + fn same(self, other: V) -> bool { + if let (Some(x), Some(y)) = (self.number(), other.number()) { + return x.compare(y) == Ordering::Equal; + } + match (self, other) { + (V::Other, _) | (_, V::Other) => false, + (x, y) => x == y, + } + } +} + +impl Range { + #[inline] + fn holds(&self, x: N) -> bool { + let (lo, hi) = (x.compare(N::Dec(self.lo)), x.compare(N::Dec(self.hi))); + let above = lo == Ordering::Greater || (self.lo_closed && lo == Ordering::Equal); + let below = hi == Ordering::Less || (self.hi_closed && hi == Ordering::Equal); + above && below + } +} + +impl Rep { + #[inline] + pub(crate) fn scale_at(self, reg: &Reg, i: usize) -> u8 { + match self { + Rep::Fix(s) => s, + Rep::Dyn => reg.scale[i], + _ => 0, + } + } +} + +impl std::ops::Index for Others<'_> { + type Output = Reg; + + #[inline(always)] + fn index(&self, i: usize) -> &Reg { + if i < self.at { + &self.lo[i] + } else { + &self.hi[i - self.at - 1] + } + } +} + +impl Buf { + pub(crate) fn sized(&mut self, len: usize) { + let words = K::words(len); + self.mant.resize(len, 0); + self.scale.resize(len, 0); + self.codes.resize(len, 0); + self.bits.resize(words, 0); + self.valid.resize(words, 0); + self.fault.resize(words, 0); + self.wide.clear(); + self.wide.resize(words, 0); + self.any = false; + self.text.clear(); + } + + #[inline] + pub(crate) fn num(&self, rep: Rep, r: usize) -> N { + match self.any && Bits::get(&self.wide, r) { + true => N::Big(self.big.get(r).copied().unwrap_or_default()), + false => N::Dec(Dec::new( + self.mant[r], + match rep { + Rep::Fix(s) => s, + _ => self.scale[r], + }, + )), + } + } + + #[inline] + pub(crate) fn keep(&mut self, rep: Rep, r: usize, n: N) { + match n { + N::Dec(d) if rep == Rep::Dyn || rep == Rep::Fix(d.scale) => { + self.mant[r] = d.mant; + self.scale[r] = d.scale; + if self.any { + Bits::set(&mut self.wide, r, false); + } + } + n => { + if self.big.len() < self.mant.len() { + self.big.resize(self.mant.len(), Decimal::ZERO); + } + self.big[r] = n.decimal(); + self.mant[r] = 0; + self.scale[r] = 0; + self.any = true; + Bits::set(&mut self.wide, r, true); + } + } + } + + pub(crate) fn finish(&mut self, fold: Fold, rep: Rep) { + let len = self.mant.len(); + for r in 0..len { + if Bits::get(&self.fault, r) { + continue; + } + let seen = self.codes[r]; + match fold { + Fold::Any if seen == 0 => Bits::set(&mut self.bits, r, false), + Fold::All | Fold::None if seen == 0 => Bits::set(&mut self.bits, r, true), + Fold::One => Bits::set(&mut self.bits, r, self.mant[r] == 1), + Fold::Min | Fold::Max if seen == 0 => Bits::set(&mut self.fault, r, true), + Fold::Avg if seen == 0 => Bits::set(&mut self.fault, r, true), + Fold::Avg => match self + .num(rep, r) + .arith(Arith::Div, N::Dec(Dec::int(i64::from(seen)))) + { + Ok(Some(q)) => self.keep(rep, r, q), + _ => Bits::set(&mut self.fault, r, true), + }, + _ => {} + } + } + } +} + +impl Reg { + pub(crate) const LANES: usize = 1024; + pub(crate) const WORDS: usize = 16; + + pub(crate) fn new() -> Self { + Reg { + mant: vec![0; Self::LANES], + scale: vec![0; Self::LANES], + codes: vec![0; Self::LANES], + bits: [0; Self::WORDS], + valid: [0; Self::WORDS], + fault: [0; Self::WORDS], + wide: [0; Self::WORDS], + big: Vec::new(), + masks: Vec::new(), + text: Vec::new(), + span: Vec::new(), + dates: Vec::new(), + } + } + + pub(crate) fn fill(&mut self, rep: Rep, lit: &Lit) { + self.valid.fill(u64::MAX); + self.fault.fill(0); + self.wide.fill(0); + match lit { + Lit::Num(d) => { + self.mant.fill(d.mant); + self.scale.fill(d.scale); + } + Lit::Bool(b) => self.bits.fill(if *b { u64::MAX } else { 0 }), + Lit::Code(_, c) => self.codes.fill(*c), + Lit::Text(t) => self.literal(t), + Lit::Date(d) => self.dates = vec![d.date(); Self::LANES], + Lit::Null => self.valid.fill(0), + } + if rep == Rep::Null { + self.valid.fill(0); + } + } + + #[inline] + fn ok(&self, i: usize) -> bool { + Bits::get(&self.valid, i) + } + + #[inline] + fn bad(&self, i: usize) -> bool { + Bits::get(&self.fault, i) + } + + #[inline] + fn v(&self, rep: Rep, i: usize) -> V { + if !self.ok(i) { + return V::Null; + } + if self.wide(i) { + return V::Big(self.big.get(i).copied().unwrap_or_default()); + } + match rep { + Rep::Fix(s) => V::Num(Dec::new(self.mant[i], s)), + Rep::Dyn => V::Num(Dec::new(self.mant[i], self.scale[i])), + Rep::Bool => V::Bool(Bits::get(&self.bits, i)), + Rep::Code => V::Code(self.codes[i]), + Rep::Date => V::Date(self.date(i)), + Rep::Text | Rep::Null => V::Null, + } + } + + #[inline] + fn put(&mut self, i: usize, d: Dec) { + self.mant[i] = d.mant; + self.scale[i] = d.scale; + } + + #[inline] + fn wide(&self, i: usize) -> bool { + Bits::get(&self.wide, i) + } + + #[inline] + pub(crate) fn num(&self, rep: Rep, i: usize) -> N { + match self.wide(i) { + true => N::Big(self.big.get(i).copied().unwrap_or_default()), + false => N::Dec(Dec::new(self.mant[i], rep.scale_at(self, i))), + } + } + + #[inline] + pub(crate) fn keep(&mut self, rep: Rep, i: usize, n: N) { + match n { + N::Dec(d) if rep == Rep::Dyn || rep == Rep::Fix(d.scale) => { + self.put(i, d); + Bits::set(&mut self.wide, i, false); + } + n => { + if self.big.len() < Self::LANES { + self.big.resize(Self::LANES, Decimal::ZERO); + } + self.big[i] = n.decimal(); + self.put(i, Dec::ZERO); + Bits::set(&mut self.wide, i, true); + } + } + } + + #[inline] + fn widened(&self, words: usize) -> bool { + self.wide[..words].iter().any(|w| *w != 0) + } + + #[inline] + fn adopt(&mut self, from: &Reg, mask: &[u64]) { + for (w, &m) in mask.iter().enumerate() { + let bits = m & from.wide[w]; + self.wide[w] |= bits; + Bits::each(bits, w * 64, |i| { + if self.big.len() < Self::LANES { + self.big.resize(Self::LANES, Decimal::ZERO); + } + self.big[i] = from.big.get(i).copied().unwrap_or_default(); + }); + } + } +} + +impl<'e, 'x> Exec<'e, 'x> { + #[cfg(test)] + thread_local! { + pub(crate) static PROFILE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + } + + #[inline] + pub(crate) fn tail(&self, w: usize) -> u64 { + let rem = self.n - w * 64; + if rem >= 64 { + u64::MAX + } else { + (1u64 << rem) - 1 + } + } + + pub(crate) fn feed(&self, src: Src) -> Option<&'e Feed<'x>> { + match src { + Src::Col(c) => self.feeds.columns.get(c as usize), + Src::Field(l, f) => self + .feeds + .fields + .get(l as usize) + .and_then(|l| l.get(f as usize)), + Src::Class(k) => self.feeds.classes.get(k as usize), + } + } + + #[inline(always)] + fn num( + &self, + op: Arith, + d: &mut Reg, + act: Option<&[u64; Reg::WORDS]>, + ovf: &mut [u64; Reg::WORDS], + x: impl Fn(usize) -> Dec, + y: impl Fn(usize) -> Dec, + ) { + let words = self.words.min(Reg::WORDS); + if act.is_none() && matches!(op, Arith::Add | Arith::Sub | Arith::Mul) { + let (mant, scale) = (&mut d.mant, &mut d.scale); + K::pack_idx(self.n, &mut ovf[..words], |i| { + let (p, q) = (x(i), y(i)); + let (r, s, o) = match op { + Arith::Mul => K::mul(p.mant, q.mant, p.scale, q.scale), + _ => K::add(op == Arith::Sub, p.mant, q.mant, p.scale, q.scale), + }; + mant[i] = r; + scale[i] = s; + o + }); + return; + } + let skip = d.fault; + self.each(act, &skip, |i| match x(i).arith(op, y(i)) { + Ok(Some(q)) => d.put(i, q), + Ok(None) => Bits::set(&mut d.valid, i, false), + Err(_) => Bits::set(ovf, i, true), + }); + } + + fn redo( + &self, + d: &mut Reg, + act: Option<&[u64; Reg::WORDS]>, + ovf: &[u64; Reg::WORDS], + rep: Rep, + mut f: impl FnMut(usize) -> Result, ()>, + ) { + let words = self.words.min(Reg::WORDS); + let mut m = [0u64; Reg::WORDS]; + for w in 0..words { + m[w] = ovf[w] & !d.fault[w]; + } + if m[..words].iter().all(|w| *w == 0) { + return; + } + self.over(act, &m, |i| match f(i) { + Ok(Some(v)) => { + Bits::set(&mut d.valid, i, true); + d.keep(rep, i, v) + } + Ok(None) => Bits::set(&mut d.valid, i, false), + Err(()) => Bits::set(&mut d.fault, i, true), + }); + } + + #[inline(always)] + fn over( + &self, + act: Option<&[u64; Reg::WORDS]>, + mask: &[u64; Reg::WORDS], + mut f: impl FnMut(usize), + ) { + for w in 0..self.words.min(Reg::WORDS) { + Bits::each( + act.map_or(u64::MAX, |a| a[w]) & self.tail(w) & mask[w], + w * 64, + &mut f, + ); + } + } + + fn patch(&self, d: &mut Reg, a: &Reg, b: Option<&Reg>, mut f: impl FnMut(usize) -> bool) { + for w in 0..self.words.min(Reg::WORDS) { + let (bw, bv) = b.map_or((0, u64::MAX), |b| (b.wide[w], b.valid[w])); + Bits::each((a.wide[w] | bw) & a.valid[w] & bv & self.tail(w), 0, |j| { + let bit = 1u64 << j; + match f(w * 64 + j) { + true => d.bits[w] |= bit, + false => d.bits[w] &= !bit, + } + }); + } + } + + #[inline] + pub(crate) fn def(regs: &mut [Reg], dst: R, f: impl FnOnce(&mut Reg, &Others)) { + let at = dst as usize; + let (lo, rest) = regs.split_at_mut(at); + if let Some((d, hi)) = rest.split_first_mut() { + d.wide = [0; Reg::WORDS]; + f(d, &Others { lo, hi, at }); + } + } + + fn strict1(&self, d: &mut Reg, a: &Reg) { + for w in 0..self.words.min(Reg::WORDS) { + d.fault[w] = a.fault[w] | !a.valid[w]; + d.valid[w] = u64::MAX; + } + } + + fn strict2(&self, d: &mut Reg, a: &Reg, b: &Reg) { + for w in 0..self.words.min(Reg::WORDS) { + d.fault[w] = a.fault[w] | b.fault[w] | !a.valid[w] | !b.valid[w]; + d.valid[w] = u64::MAX; + } + } + + fn eq_meta(&self, d: &mut Reg, a: &Reg, b: &Reg, ne: bool) { + for w in 0..self.words.min(Reg::WORDS) { + let (va, vb) = (a.valid[w], b.valid[w]); + let eq = (va & vb & d.bits[w]) | (!va & !vb); + d.bits[w] = if ne { !eq } else { eq }; + d.fault[w] = a.fault[w] | b.fault[w]; + d.valid[w] = u64::MAX; + } + } + + pub(crate) fn mask_of( + &self, + guard: &Guard, + regs: &[Reg], + parent: Option<&[u64; Reg::WORDS]>, + ) -> [u64; Reg::WORDS] { + let mut out = [0u64; Reg::WORDS]; + for (w, o) in out.iter_mut().enumerate().take(self.words.min(Reg::WORDS)) { + let m = match guard { + Guard::True(c) => { + let c = ®s[*c as usize]; + c.bits[w] & c.valid[w] & !c.fault[w] + } + Guard::False(c) => { + let c = ®s[*c as usize]; + !c.bits[w] & c.valid[w] & !c.fault[w] + } + Guard::Null(c) => { + let c = ®s[*c as usize]; + !c.valid[w] & !c.fault[w] + } + Guard::Masks(s, idx) => { + let s = ®s[*s as usize]; + idx.iter().fold(0, |acc, k| { + acc | s + .masks + .get(*k as usize * Reg::WORDS + w) + .copied() + .unwrap_or(0) + }) + } + }; + *o = m & self.tail(w) & parent.map_or(u64::MAX, |p| p[w]); + } + out + } + + #[inline(always)] + pub(crate) fn bools( + &self, + act: Option<&[u64; Reg::WORDS]>, + bits: &mut [u64; Reg::WORDS], + mut f: impl FnMut(usize) -> bool, + ) { + let words = self.words.min(Reg::WORDS); + match act { + None => K::pack_idx(self.n, &mut bits[..words], f), + Some(_) => { + bits[..words].fill(0); + let none = [0u64; Reg::WORDS]; + self.each(act, &none, |i| { + if f(i) { + Bits::set(bits, i, true); + } + }); + } + } + } + + #[inline(always)] + pub(crate) fn each( + &self, + act: Option<&[u64; Reg::WORDS]>, + skip: &[u64; Reg::WORDS], + mut f: impl FnMut(usize), + ) { + for w in 0..self.words.min(Reg::WORDS) { + Bits::each( + act.map_or(u64::MAX, |a| a[w]) & self.tail(w) & !skip[w], + w * 64, + &mut f, + ); + } + } + + pub(crate) fn run( + &self, + code: &[Ins], + regs: &mut [Reg], + bufs: &mut [Buf], + scratch: &mut [i64], + stack: &mut Stack, + out: &mut Outputs, + ) { + stack.clear(); + let mut pc = 0; + while pc < code.len() { + while stack.last().is_some_and(|top| pc >= top.0) { + stack.pop(); + } + match &code[pc] { + Ins::Skip { guard, len } => { + let m = self.mask_of(guard, regs, stack.last().map(|t| &t.1)); + if m.iter().all(|w| *w == 0) { + pc += *len as usize; + } else { + stack.push((pc + 1 + *len as usize, m)); + } + } + ins => { + #[cfg(test)] + let t = std::time::Instant::now(); + self.step(ins, regs, bufs, scratch, stack.last().map(|t| &t.1), out); + #[cfg(test)] + let took = t.elapsed().as_nanos(); + #[cfg(test)] + Self::PROFILE.with_borrow_mut(|p| { + if let Some(p) = p { + let name = format!("{ins:?}") + .split([' ', '{']) + .next() + .unwrap_or("") + .to_string(); + let e = p.entry(name).or_insert((0, 0)); + e.0 += took; + e.1 += 1; + } + }); + } + } + pc += 1; + } + } + + #[allow(clippy::needless_range_loop)] + pub(crate) fn step( + &self, + ins: &Ins, + regs: &mut [Reg], + bufs: &mut [Buf], + scratch: &mut [i64], + act: Option<&[u64; Reg::WORDS]>, + out: &mut Outputs, + ) { + let (n, words, start) = (self.n, self.words.min(Reg::WORDS), self.start); + match ins { + Ins::Skip { .. } => {} + Ins::Load { dst, src, rep } => { + let Some(feed) = self.feed(*src) else { + return; + }; + Self::def(regs, *dst, |d, _| self.load(d, feed, *rep)); + } + Ins::Gather { + dst, + buf, + list, + rep, + } => { + let Some(l) = self.feeds.lists.get(*list as usize) else { + return; + }; + let parent = &l.parent[start..start + n]; + let b = &bufs[*buf as usize]; + Self::def(regs, *dst, |d, _| { + match rep { + Rep::Fix(_) => { + for (o, &p) in d.mant[..n].iter_mut().zip(parent) { + *o = b.mant[p as usize]; + } + } + Rep::Dyn => { + for (i, &p) in parent.iter().enumerate() { + d.mant[i] = b.mant[p as usize]; + d.scale[i] = b.scale[p as usize]; + } + } + Rep::Code => { + for (o, &p) in d.codes[..n].iter_mut().zip(parent) { + *o = b.codes[p as usize]; + } + } + Rep::Bool => K::pack1(parent, &mut d.bits[..words], |p| { + Bits::get(&b.bits, p as usize) + }), + Rep::Text => self.gather_text(d, b, parent), + Rep::Date => self.gather_dates(d, b, parent), + Rep::Null => {} + } + let (r0, r1) = ( + parent.first().map_or(0, |p| *p as usize), + parent.last().map_or(0, |p| *p as usize + 1), + ); + if Bits::range(&b.valid, r0, r1, true) && Bits::range(&b.fault, r0, r1, false) { + d.valid[..words].fill(u64::MAX); + d.fault[..words].fill(0); + } else { + K::pack1(parent, &mut d.valid[..words], |p| { + Bits::get(&b.valid, p as usize) + }); + K::pack1(parent, &mut d.fault[..words], |p| { + Bits::get(&b.fault, p as usize) + }); + } + if b.any && !Bits::range(&b.wide, r0, r1, false) { + for (i, &p) in parent.iter().enumerate() { + if Bits::get(&b.wide, p as usize) { + d.keep( + Rep::Dyn, + i, + N::Big(b.big.get(p as usize).copied().unwrap_or_default()), + ); + } + } + } + }); + } + Ins::Fill { dst, buf, rep } => { + let b = &bufs[*buf as usize]; + let w0 = start / 64; + Self::def(regs, *dst, |d, _| { + d.valid[..words].copy_from_slice(&b.valid[w0..w0 + words]); + d.fault[..words].copy_from_slice(&b.fault[w0..w0 + words]); + if b.any && !Bits::range(&b.wide, start, start + n, false) { + for i in 0..n { + if Bits::get(&b.wide, start + i) { + d.keep( + Rep::Dyn, + i, + N::Big(b.big.get(start + i).copied().unwrap_or_default()), + ); + } + } + } + match rep { + Rep::Fix(_) => d.mant[..n].copy_from_slice(&b.mant[start..start + n]), + Rep::Dyn => { + d.mant[..n].copy_from_slice(&b.mant[start..start + n]); + d.scale[..n].copy_from_slice(&b.scale[start..start + n]); + } + Rep::Code => d.codes[..n].copy_from_slice(&b.codes[start..start + n]), + Rep::Bool => d.bits[..words].copy_from_slice(&b.bits[w0..w0 + words]), + Rep::Text => self.fill_text(d, b), + Rep::Date => self.fill_dates(d, b), + Rep::Null => {} + } + }); + } + Ins::Spill { src, buf, rep } => { + let r = ®s[*src as usize]; + let b = &mut bufs[*buf as usize]; + let w0 = start / 64; + b.valid[w0..w0 + words].copy_from_slice(&r.valid[..words]); + b.fault[w0..w0 + words].copy_from_slice(&r.fault[..words]); + b.wide[w0..w0 + words].copy_from_slice(&r.wide[..words]); + if r.widened(words) { + if b.big.len() < b.mant.len() { + b.big.resize(b.mant.len(), Decimal::ZERO); + } + b.any = true; + for i in 0..n { + if r.wide(i) { + b.big[start + i] = r.big.get(i).copied().unwrap_or_default(); + } + } + } + match rep { + Rep::Fix(_) => b.mant[start..start + n].copy_from_slice(&r.mant[..n]), + Rep::Dyn => { + b.mant[start..start + n].copy_from_slice(&r.mant[..n]); + b.scale[start..start + n].copy_from_slice(&r.scale[..n]); + } + Rep::Code => b.codes[start..start + n].copy_from_slice(&r.codes[..n]), + Rep::Bool => b.bits[w0..w0 + words].copy_from_slice(&r.bits[..words]), + Rep::Text => self.spill_text(r, b), + Rep::Date => self.spill_dates(r, b), + Rep::Null => {} + } + } + Ins::Fix { op, dst, a, b, rep } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + self.strict2(d, a, b); + let mut ovf = [0u64; Reg::WORDS]; + let (x, y, o, f) = ( + &a.mant[..n], + &b.mant[..n], + &mut d.mant[..n], + &mut ovf[..words], + ); + match op { + FixOp::Add => K::ovf2(x, y, o, f, i64::overflowing_add), + FixOp::Sub => K::ovf2(x, y, o, f, i64::overflowing_sub), + FixOp::Mul => K::ovf2(x, y, o, f, i64::overflowing_mul), + } + for w in 0..words { + ovf[w] |= a.wide[w] | b.wide[w]; + } + let op = match op { + FixOp::Add => Arith::Add, + FixOp::Sub => Arith::Sub, + FixOp::Mul => Arith::Mul, + }; + let rep = *rep; + self.redo(d, act, &ovf, rep, |i| { + a.num(rep, i).arith(op, b.num(rep, i)).map_err(|_| ()) + }); + }), + Ins::Neg { dst, a, rep } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + self.strict1(d, a); + let mut ovf = [0u64; Reg::WORDS]; + K::ovf1(&a.mant[..n], &mut d.mant[..n], &mut ovf[..words], |x| { + (x.wrapping_neg(), (x == 0) | (x == i64::MIN)) + }); + if *rep == Rep::Dyn { + d.scale[..n].copy_from_slice(&a.scale[..n]); + } + for w in 0..words { + ovf[w] |= a.wide[w]; + } + let rep = *rep; + self.redo(d, act, &ovf, rep, |i| Ok(Some(a.num(rep, i).neg()))); + }), + Ins::Num { + op, + dst, + a, + ra, + b, + rb, + } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + self.strict2(d, a, b); + let (am, bm) = (&a.mant[..n], &b.mant[..n]); + let mut ovf = [0u64; Reg::WORDS]; + let (op, ra, rb) = (*op, *ra, *rb); + if act.is_none() && matches!(op, Arith::Add | Arith::Sub | Arith::Mul) { + let (mut pa, mut pb) = ([0u8; Reg::LANES], [0u8; Reg::LANES]); + let (asc, bsc) = ( + Self::scales(ra, a, &mut pa, n), + Self::scales(rb, b, &mut pb, n), + ); + let (sub, mul) = (op == Arith::Sub, op == Arith::Mul); + let (dm, ds, df) = (&mut d.mant[..n], &mut d.scale[..n], &mut ovf[..words]); + match mul { + true => K::dyn2(am, bm, asc, bsc, dm, ds, df, K::mul), + false => K::dyn2(am, bm, asc, bsc, dm, ds, df, |x, y, p, q| { + K::add(sub, x, y, p, q) + }), + } + } else { + self.num( + op, + d, + act, + &mut ovf, + |i| Dec::new(am[i], ra.scale_at(a, i)), + |i| Dec::new(bm[i], rb.scale_at(b, i)), + ); + } + for w in 0..words { + ovf[w] |= a.wide[w] | b.wide[w]; + } + self.redo(d, act, &ovf, Rep::Dyn, |i| { + a.num(ra, i).arith(op, b.num(rb, i)).map_err(|_| ()) + }); + }), + Ins::DivPow { dst, a, ra, k, by } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + self.strict1(d, a); + let (k, by, ra) = (*k, *by, *ra); + let mut ovf = [0u64; Reg::WORDS]; + let mut slow_lane = + |i: usize, d: &mut Reg| match Dec::new(a.mant[i], ra.scale_at(a, i)) + .div_power(k, by) + { + Ok(q) => d.put(i, q), + Err(_) => Bits::set(&mut ovf, i, true), + }; + let mut slow = [0u64; Reg::WORDS]; + let shift = match ra { + Rep::Fix(sa) => sa as i32 - by as i32, + _ => -1, + }; + let fast = act.is_none() && k >= 2 && (0..=19).contains(&shift); + let mut even = [0u64; Reg::WORDS]; + if fast { + K::pack1(&a.mant[..n], &mut even[..words], |m| { + (m % 10 != 0) & (m != i64::MIN) + }); + d.mant[..n].copy_from_slice(&a.mant[..n]); + d.scale[..n].fill((shift + k as i32) as u8); + for (w, word) in even.iter_mut().enumerate().take(words) { + *word |= d.fault[w]; + } + } + let (mant, scale) = (&mut d.mant, &mut d.scale); + let mut quick = |i: usize| { + let (m, t, bad) = + K::div_pow(a.mant[i], ra.scale_at(a, i) as i32 - by as i32, k); + mant[i] = m; + scale[i] = t; + bad + }; + match (fast, act) { + (true, _) => self.each(None, &even, |i| Bits::set(&mut slow, i, quick(i))), + (false, None) => K::pack_idx(n, &mut slow[..words], quick), + (false, Some(_)) => { + let skip = d.fault; + self.each(act, &skip, |i| Bits::set(&mut slow, i, quick(i))); + } + } + for (w, word) in slow.iter_mut().enumerate().take(words) { + *word = !(*word & !d.fault[w]); + } + self.each(None, &slow, |i| slow_lane(i, d)); + for w in 0..words { + ovf[w] |= a.wide[w]; + } + let divisor = N::Dec(Dec::new(Dec::POW10[k as usize], by)); + self.redo(d, act, &ovf, Rep::Dyn, |i| { + a.num(ra, i).arith(Arith::Div, divisor).map_err(|_| ()) + }); + }), + Ins::PickTab { dst, sel, tab, rep } => Self::def(regs, *dst, |d, regs| { + let s = ®s[*sel as usize]; + let sm = &s.mant[..n]; + match rep { + Rep::Fix(_) => { + for (o, &x) in d.mant[..n].iter_mut().zip(sm) { + *o = tab.mant[(x as usize) & 255]; + } + } + Rep::Dyn => { + for ((o, c), &x) in + d.mant[..n].iter_mut().zip(d.scale[..n].iter_mut()).zip(sm) + { + *o = tab.mant[(x as usize) & 255]; + *c = tab.scale[(x as usize) & 255]; + } + } + Rep::Code => { + for (o, &x) in d.codes[..n].iter_mut().zip(sm) { + *o = tab.codes[(x as usize) & 255]; + } + } + Rep::Bool => K::pack1(sm, &mut d.bits[..words], |x| { + Tab::bit(&tab.flag, x as usize) + }), + Rep::Text | Rep::Date | Rep::Null => {} + } + K::pack1(sm, &mut d.valid[..words], |x| Tab::bit(&tab.ok, x as usize)); + d.fault[..words].copy_from_slice(&s.fault[..words]); + }), + Ins::CmpFix { op, dst, a, b, rep } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + let (x, y, o) = (&a.mant[..n], &b.mant[..n], &mut d.bits[..words]); + match op { + Cmp::Eq | Cmp::Ne => K::pack2(x, y, o, |x, y| x == y), + Cmp::Lt => K::pack2(x, y, o, |x, y| x < y), + Cmp::Le => K::pack2(x, y, o, |x, y| x <= y), + Cmp::Gt => K::pack2(x, y, o, |x, y| x > y), + Cmp::Ge => K::pack2(x, y, o, |x, y| x >= y), + } + let (op, rep) = (*op, *rep); + self.patch(d, a, Some(b), |i| { + K::ord(op, a.num(rep, i).compare(b.num(rep, i))) + }); + match op { + Cmp::Eq | Cmp::Ne => self.eq_meta(d, a, b, op == Cmp::Ne), + _ => self.strict2(d, a, b), + } + }), + Ins::CmpNum { + op, + dst, + a, + ra, + b, + rb, + } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + let (am, bm, asc, bsc) = (&a.mant[..n], &b.mant[..n], &a.scale[..n], &b.scale[..n]); + let (op, ra, rb) = (*op, *ra, *rb); + let f = |i: usize| { + let x = match ra { + Rep::Fix(p) => Dec::new(am[i], p), + _ => Dec::new(am[i], asc[i]), + }; + let y = match rb { + Rep::Fix(q) => Dec::new(bm[i], q), + _ => Dec::new(bm[i], bsc[i]), + }; + K::ord(op, x.compare(y)) + }; + self.bools(act, &mut d.bits, f); + self.patch(d, a, Some(b), |i| { + K::ord(op, a.num(ra, i).compare(b.num(rb, i))) + }); + match op { + Cmp::Eq | Cmp::Ne => self.eq_meta(d, a, b, op == Cmp::Ne), + _ => self.strict2(d, a, b), + } + }), + Ins::CmpNumK { + op, + dst, + a, + ra, + k, + tab, + fits, + } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + let (am, asc) = (&a.mant[..n], &a.scale[..n]); + let (op, fits, k) = (*op, *fits, *k); + let o = &mut d.bits[..words]; + let slow = |m: i64, s: u8| match tab.get(s as usize) { + Some(c) if (fits >> s) & 1 != 0 => K::ord(op, m.cmp(c)), + _ => K::ord(op, Dec::new(m, s).compare(k)), + }; + match *ra { + Rep::Fix(s) if (fits >> s) & 1 != 0 => K::cmp_k(op, am, tab[s as usize], o), + Rep::Fix(s) => K::pack1(am, o, |m| slow(m, s)), + _ => K::pack2(am, asc, o, slow), + } + let ra = *ra; + self.patch(d, a, None, |i| K::ord(op, a.num(ra, i).compare(N::Dec(k)))); + for w in 0..words { + match op { + Cmp::Eq | Cmp::Ne => { + let eq = a.valid[w] & d.bits[w]; + d.bits[w] = if op == Cmp::Ne { !eq } else { eq }; + d.fault[w] = a.fault[w]; + } + _ => d.fault[w] = a.fault[w] | !a.valid[w], + } + d.valid[w] = u64::MAX; + } + }), + Ins::CmpGen { + op, + dst, + a, + ra, + b, + rb, + } if matches!((ra, rb), (Rep::Null, _) | (_, Rep::Null)) => { + Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + for w in 0..words { + let va = if *ra == Rep::Null { 0 } else { a.valid[w] }; + let vb = if *rb == Rep::Null { 0 } else { b.valid[w] }; + let (both, none) = (va & vb, !(va | vb)); + d.valid[w] = u64::MAX; + d.fault[w] = a.fault[w] | b.fault[w]; + d.bits[w] = match op { + Cmp::Eq => none, + Cmp::Ne => !none, + _ => 0, + }; + if !matches!(op, Cmp::Eq | Cmp::Ne) { + d.fault[w] |= !both & self.tail(w); + } + } + }) + } + Ins::CmpGen { + op, + dst, + a, + ra, + b, + rb, + } if matches!((ra, rb), (Rep::Fix(_) | Rep::Dyn, Rep::Fix(_) | Rep::Dyn)) => { + Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + let equality = matches!(op, Cmp::Eq | Cmp::Ne); + for w in 0..words { + let tail = self.tail(w); + let mut hit = 0u64; + for j in 0..(n - w * 64).min(64) { + let i = w * 64 + j; + let order = a.num(*ra, i).compare(b.num(*rb, i)); + hit |= u64::from(K::ord(*op, order)) << j; + } + let both = a.valid[w] & b.valid[w]; + let none = !(a.valid[w] | b.valid[w]); + d.bits[w] = match op { + Cmp::Eq => (hit & both) | none, + Cmp::Ne => !(hit & both) & !none, + _ => hit & both, + }; + d.valid[w] = u64::MAX; + d.fault[w] = + a.fault[w] | b.fault[w] | if equality { 0 } else { !both & tail }; + } + }) + } + Ins::CmpGen { + op, + dst, + a, + ra, + b, + rb, + } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + for w in 0..words { + d.fault[w] = a.fault[w] | b.fault[w]; + d.valid[w] = u64::MAX; + d.bits[w] = 0; + } + for i in 0..n { + let (x, y) = (a.v(*ra, i), b.v(*rb, i)); + let r = match (op, x, y) { + (Cmp::Eq, x, y) => Some(x.same(y)), + (Cmp::Ne, x, y) => Some(!x.same(y)), + (_, V::Date(x), V::Date(y)) => Some(K::ord(*op, x.cmp(&y))), + (_, x, y) => x + .number() + .zip(y.number()) + .map(|(x, y)| K::ord(*op, x.compare(y))), + }; + match r { + Some(v) => Bits::set(&mut d.bits, i, v), + None => Bits::set(&mut d.fault, i, true), + } + } + }), + Ins::EqCode { ne, dst, a, b } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + K::pack2( + &a.codes[..n], + &b.codes[..n], + &mut d.bits[..words], + |x, y| x == y, + ); + self.eq_meta(d, a, b, *ne); + }), + Ins::EqBool { ne, dst, a, b } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + for w in 0..words { + d.bits[w] = !(a.bits[w] ^ b.bits[w]); + } + self.eq_meta(d, a, b, *ne); + }), + Ins::EqText { .. } + | Ins::Text { .. } + | Ins::Matches { .. } + | Ins::Map { .. } + | Ins::Concat { .. } + | Ins::Str { .. } + | Ins::Decode { .. } + | Ins::Class { .. } => self.text(ins, regs, act), + Ins::Now { .. } | Ins::Host { .. } | Ins::Clock { .. } => self.date(ins, regs, act), + Ins::InCode { dst, a, set, null } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + let set = *set; + K::pack1(&a.codes[..n], &mut d.bits[..words], |c| { + ((set >> (c & 63)) & 1 != 0) & ((c as u32) < 64) + }); + let nm = if *null { u64::MAX } else { 0 }; + for w in 0..words { + d.bits[w] = (a.valid[w] & d.bits[w]) | (!a.valid[w] & nm); + d.fault[w] = a.fault[w]; + d.valid[w] = u64::MAX; + } + }), + Ins::InGen { dst, a, ra, set } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + for w in 0..words { + d.fault[w] = a.fault[w]; + d.valid[w] = u64::MAX; + d.bits[w] = 0; + } + for i in 0..n { + let x = a.v(*ra, i); + Bits::set(&mut d.bits, i, set.iter().any(|l| x.same(V::lit(l)))); + } + }), + Ins::InRangeFix { + dst, + a, + lo, + span, + empty, + range, + } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + let (lo, span) = (*lo, *span); + match empty { + true => d.bits[..words].fill(0), + false => K::pack1(&a.mant[..n], &mut d.bits[..words], |x| { + (x.wrapping_sub(lo) as u64) <= span + }), + } + self.patch(d, a, None, |i| range.holds(a.num(Rep::Dyn, i))); + self.strict1(d, a); + }), + Ins::InRangeGen { dst, a, ra, range } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + self.strict1(d, a); + for w in 0..words { + let mut hit = 0u64; + for j in 0..(n - w * 64).min(64) { + let i = w * 64 + j; + hit |= u64::from(range.holds(a.num(*ra, i))) << j; + } + d.bits[w] = hit & a.valid[w]; + } + }), + Ins::Not { dst, a } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + self.strict1(d, a); + for w in 0..words { + d.bits[w] = !a.bits[w]; + } + }), + Ins::And { dst, a, b } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + for w in 0..words { + let at = a.bits[w] & a.valid[w]; + let af = !a.bits[w] & a.valid[w]; + d.bits[w] = at & b.bits[w]; + d.valid[w] = af | (at & b.valid[w]); + d.fault[w] = a.fault[w] | !a.valid[w] | (at & b.fault[w]); + } + }), + Ins::Or { dst, a, b } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + for w in 0..words { + let at = a.bits[w] & a.valid[w]; + let af = !a.bits[w] & a.valid[w]; + d.bits[w] = at | (af & b.bits[w]); + d.valid[w] = at | (af & b.valid[w]); + d.fault[w] = a.fault[w] | !a.valid[w] | (af & b.fault[w]); + } + }), + Ins::Blend { + dst, + c, + t, + rt, + e, + re, + rep, + } => Self::def(regs, *dst, |d, regs| { + let (c, t, e) = (®s[*c as usize], ®s[*t as usize], ®s[*e as usize]); + let mut ct = [0u64; Reg::WORDS]; + for w in 0..words { + ct[w] = c.bits[w] & c.valid[w]; + let cf = !c.bits[w] & c.valid[w]; + d.valid[w] = (ct[w] & t.valid[w]) | (cf & e.valid[w]); + d.fault[w] = + c.fault[w] | !c.valid[w] | (ct[w] & t.fault[w]) | (cf & e.fault[w]); + } + self.values(d, &ct[..words], (t, *rt), (e, *re), *rep); + if rep.num() && (t.widened(words) || e.widened(words)) { + let mut cf = [0u64; Reg::WORDS]; + for w in 0..words { + cf[w] = !c.bits[w] & c.valid[w]; + } + d.adopt(t, &ct[..words]); + d.adopt(e, &cf[..words]); + } + }), + Ins::SelK { dst, c, t, e, rep } => Self::def(regs, *dst, |d, regs| { + let c = ®s[*c as usize]; + let mut ct = [0u64; Reg::WORDS]; + for w in 0..words { + ct[w] = c.bits[w] & c.valid[w]; + d.valid[w] = c.valid[w]; + d.fault[w] = c.fault[w] | !c.valid[w]; + } + let (t, e) = (*t, *e); + match rep { + Rep::Fix(_) => K::select(&ct[..words], t, e, &mut d.mant[..n]), + Rep::Code => K::select(&ct[..words], t as i32, e as i32, &mut d.codes[..n]), + Rep::Bool => { + let (tb, eb) = ( + if t != 0 { u64::MAX } else { 0 }, + if e != 0 { u64::MAX } else { 0 }, + ); + for w in 0..words { + d.bits[w] = (ct[w] & tb) | (!ct[w] & eb); + } + } + _ => {} + } + }), + Ins::Coalesce { + dst, + a, + ra, + b, + rb, + rep, + } => Self::def(regs, *dst, |d, regs| { + let (a, b) = (®s[*a as usize], ®s[*b as usize]); + let mut m = [0u64; Reg::WORDS]; + for w in 0..words { + m[w] = a.valid[w]; + d.valid[w] = a.valid[w] | b.valid[w]; + d.fault[w] = a.fault[w] | (!a.valid[w] & b.fault[w]); + } + self.values(d, &m[..words], (a, *ra), (b, *rb), *rep); + if rep.num() && (a.widened(words) || b.widened(words)) { + let mut e = [0u64; Reg::WORDS]; + for w in 0..words { + e[w] = !a.valid[w]; + } + d.adopt(a, &m[..words]); + d.adopt(b, &e[..words]); + } + }), + Ins::Lookup { dst, keys, tab } => Self::def(regs, *dst, |d, regs| { + let (rules, rw) = (tab.rules, tab.words); + if d.masks.len() < (rules + 1) * Reg::WORDS { + d.masks.resize((rules + 1) * Reg::WORDS, 0); + } + for ci in 0..=rules { + d.masks[ci * Reg::WORDS..ci * Reg::WORDS + words].fill(0); + } + d.valid[..words].fill(u64::MAX); + d.fault[..words].fill(0); + for (r, _) in keys.iter().flatten() { + let x = ®s[*r as usize]; + for w in 0..words { + d.fault[w] |= x.fault[w]; + } + } + let mut full = [0u64; Lookup::WORDS]; + for (w, f) in full.iter_mut().enumerate().take(rw) { + *f = match rules - w * 64 { + left if left >= 64 => u64::MAX, + left => (1u64 << left) - 1, + }; + } + if rw == 1 { + let (mut acc, mut bad, mut at) = ( + [full[0]; Reg::LANES], + [0u64; Reg::LANES], + [0usize; Reg::LANES], + ); + for (key, reg) in tab.keys.iter().zip(keys) { + Self::indexes( + key, + reg.map(|(r, rep)| (®s[r as usize], rep)), + &mut at[..n], + ); + if key.bad.iter().any(|b| *b != 0) { + for ((a, b), &v) in + acc[..n].iter_mut().zip(bad[..n].iter_mut()).zip(&at[..n]) + { + *b |= *a & key.bad[v]; + } + } + let hit = &key.hit[..]; + for (a, &v) in acc[..n].iter_mut().zip(&at[..n]) { + *a &= hit.get(v).copied().unwrap_or(0); + } + } + for i in 0..n { + let m = acc[i] | bad[i]; + let sel = match m { + 0 => rules, + m => m.trailing_zeros() as usize, + }; + if (bad[i] & m & m.wrapping_neg()) != 0 { + Bits::set(&mut d.fault, i, true); + } + d.mant[i] = sel as i64; + d.masks[sel * Reg::WORDS + i / 64] |= 1u64 << (i % 64); + } + return; + } + let mut at = [0usize; Reg::LANES]; + let mut acc = vec![[0u64; Lookup::WORDS]; n]; + let mut bad = vec![[0u64; Lookup::WORDS]; n]; + acc.iter_mut().for_each(|a| *a = full); + for (key, reg) in tab.keys.iter().zip(keys) { + Self::indexes( + key, + reg.map(|(r, rep)| (®s[r as usize], rep)), + &mut at[..n], + ); + for i in 0..n { + let v = at[i]; + let (h, b) = ( + &key.hit[v * rw..(v + 1) * rw], + &key.bad[v * rw..(v + 1) * rw], + ); + for w in 0..rw { + bad[i][w] |= acc[i][w] & b[w]; + acc[i][w] &= h[w]; + } + } + } + for i in 0..n { + let first = (0..rw).find_map(|w| { + let m = acc[i][w] | bad[i][w]; + (m != 0).then(|| { + ( + w * 64 + m.trailing_zeros() as usize, + (bad[i][w] >> m.trailing_zeros()) & 1 == 1, + ) + }) + }); + let sel = match first { + Some((rule, true)) => { + Bits::set(&mut d.fault, i, true); + rule + } + Some((rule, false)) => rule, + None => rules, + }; + d.mant[i] = sel as i64; + d.masks[sel * Reg::WORDS + i / 64] |= 1u64 << (i % 64); + } + }), + Ins::First { + dst, + conds, + sel, + strict, + } => Self::def(regs, *dst, |d, regs| { + let k = conds.len(); + if d.masks.len() < (k + 1) * Reg::WORDS { + d.masks.resize((k + 1) * Reg::WORDS, 0); + } + let mut rem = [0u64; Reg::WORDS]; + let mut bad = [0u64; Reg::WORDS]; + for (w, r) in rem.iter_mut().enumerate().take(words) { + *r = self.tail(w); + } + for (ci, c) in conds.iter().enumerate() { + let c = ®s[*c as usize]; + let m = &mut d.masks[ci * Reg::WORDS..ci * Reg::WORDS + words]; + for w in 0..words { + let hit = c.bits[w] & c.valid[w] & !c.fault[w] & rem[w]; + m[w] = hit; + let fail = match strict { + true => (!c.valid[w] | c.fault[w]) & rem[w], + false => 0, + }; + bad[w] |= fail; + rem[w] &= !(hit | fail); + } + } + d.masks[k * Reg::WORDS..k * Reg::WORDS + words].copy_from_slice(&rem[..words]); + if *sel { + for ci in 0..=k { + let (masks, mant) = ( + &d.masks[ci * Reg::WORDS..ci * Reg::WORDS + words], + &mut d.mant[..n], + ); + K::fill_masked(masks, ci as i64, mant); + } + } + d.valid[..words].fill(u64::MAX); + d.fault[..words].copy_from_slice(&bad[..words]); + }), + Ins::Pick { + dst, + sel, + arms, + rep, + } => Self::def(regs, *dst, |d, regs| { + let s = ®s[*sel as usize]; + for w in 0..words { + d.valid[w] = 0; + d.fault[w] = s.fault[w]; + } + match rep { + Rep::Text => d.texts(n), + Rep::Date => d.stamps(), + _ => {} + } + let mut m = [0u64; Reg::WORDS]; + for (arm, ra, idx) in arms { + let a = ®s[*arm as usize]; + for (w, mw) in m.iter_mut().enumerate().take(words) { + *mw = idx.iter().fold(0, |acc, k| { + acc | s + .masks + .get(*k as usize * Reg::WORDS + w) + .copied() + .unwrap_or(0) + }); + d.valid[w] |= *mw & a.valid[w]; + d.fault[w] |= *mw & a.fault[w]; + } + let m = &m[..words]; + if rep.num() && a.widened(words) { + d.adopt(a, m); + } + match rep { + Rep::Fix(_) => K::copy_masked(m, &a.mant[..n], &mut d.mant[..n]), + Rep::Dyn => { + K::copy_masked(m, &a.mant[..n], &mut d.mant[..n]); + match ra { + Rep::Dyn => K::copy_masked(m, &a.scale[..n], &mut d.scale[..n]), + other => K::fill_masked(m, other.scale_at(a, 0), &mut d.scale[..n]), + } + } + Rep::Code => K::copy_masked(m, &a.codes[..n], &mut d.codes[..n]), + Rep::Bool => { + for (w, mw) in m.iter().enumerate() { + d.bits[w] = (d.bits[w] & !mw) | (a.bits[w] & mw); + } + } + Rep::Text => self.pick_text(d, m, a), + Rep::Date => self.pick_dates(d, m, a), + Rep::Null => {} + } + } + }), + Ins::Fold { + fold, + buf, + list, + filter, + value, + } => self.fold( + *fold, + &mut bufs[*buf as usize], + *list, + (*filter, *value), + regs, + scratch, + ), + Ins::Math { + func, + dst, + args, + rep, + } => Self::def(regs, *dst, |d, regs| { + let (func, rep) = (*func, *rep); + d.valid[..words].fill(u64::MAX); + d.fault[..words].fill(0); + for (a, _) in args { + let a = ®s[*a as usize]; + for w in 0..words { + d.fault[w] |= a.fault[w] | !a.valid[w]; + } + } + let skip = d.fault; + match (func, args.as_slice()) { + (Func::Min | Func::Max, _) if rep == Rep::Date => { + d.stamps(); + self.each(act, &skip, |i| { + let mut best: Option = None; + for (a, _) in args { + let x = regs[*a as usize].date(i); + let take = best.is_none_or(|b| match func { + Func::Min => x < b, + _ => x >= b, + }); + if take { + best = Some(x); + } + } + if let Some(b) = best { + d.dates[i] = b; + } + }); + } + (Func::Min | Func::Max, _) => self.each(act, &skip, |i| { + let mut best: Option = None; + for (a, ra) in args { + let x = regs[*a as usize].num(*ra, i); + best = Some(match best { + None => x, + Some(b) => { + let order = x.compare(b); + let take = match func { + Func::Min => order == Ordering::Less, + _ => order != Ordering::Less, + }; + if take { + x + } else { + b + } + } + }); + } + if let Some(b) = best { + d.keep(rep, i, b); + } + }), + (_, [(a, ra)]) => { + let (a, ra) = (®s[*a as usize], *ra); + self.each(act, &skip, |i| { + let fast = match a.wide(i) { + false => Dec::new(a.mant[i], ra.scale_at(a, i)) + .func(func) + .filter(|r| rep == Rep::Dyn || rep == Rep::Fix(r.scale)), + true => None, + }; + match fast { + Some(r) => d.put(i, r), + None => d.keep(rep, i, a.num(ra, i).func(func)), + } + }); + } + _ => {} + } + }), + Ins::Out { + slot, + src, + rep, + scope, + } => self.out(*slot, ®s[*src as usize], *rep, *scope, out), + Ins::Keep { slot, src } => { + let r = ®s[*src as usize]; + let w0 = start / 64; + if let Some(s) = out.slot_mut(*slot as usize) { + for w in 0..words { + if let Some(k) = s.keep.get_mut(w0 + w) { + *k = r.bits[w] & r.valid[w] & !r.fault[w] & self.tail(w); + } + } + } + } + } + } + + fn indexes(key: &crate::typed::lookup::Key, reg: Option<(&Reg, Rep)>, at: &mut [usize]) { + let Some((x, rep)) = reg else { + at.fill(0); + return; + }; + let null = key.null(); + match &key.domain { + Domain::Codes(_) => at + .iter_mut() + .zip(&x.codes) + .for_each(|(a, c)| *a = key.code(*c)), + Domain::Bools => at + .iter_mut() + .enumerate() + .for_each(|(i, a)| *a = usize::from(Bits::get(&x.bits, i))), + Domain::Unit => at.fill(0), + Domain::Points(_) => match &key.fixed { + Some((_, mants)) if mants.len() <= 32 => { + let n = at.len(); + at.fill(0); + for p in mants { + for (a, m) in at.iter_mut().zip(&x.mant[..n]) { + *a += usize::from(*p < *m) * 2 + usize::from(*p == *m); + } + } + } + _ => at.iter_mut().enumerate().for_each(|(i, a)| { + *a = key + .mant(x.mant[i]) + .unwrap_or_else(|| key.num(x.num(rep, i))) + }), + }, + } + for (w, chunk) in at.chunks_mut(64).enumerate() { + let odd = !x.valid[w] | x.wide[w]; + if odd == 0 { + continue; + } + for (j, a) in chunk.iter_mut().enumerate() { + if (odd >> j) & 1 == 1 { + *a = match x.ok(w * 64 + j) { + false => null, + true => key.num(x.num(rep, w * 64 + j)), + }; + } + } + } + } + + #[inline(always)] + fn scales<'r>(rep: Rep, reg: &'r Reg, buf: &'r mut [u8; Reg::LANES], n: usize) -> &'r [u8] { + match rep { + Rep::Fix(s) => { + buf[..n].fill(s); + &buf[..n] + } + _ => ®.scale[..n], + } + } + + fn load(&self, d: &mut Reg, feed: &Feed, rep: Rep) { + let (n, words, start) = (self.n, self.words.min(Reg::WORDS), self.start); + let w0 = start / 64; + for w in 0..words { + let take = (n - w * 64).min(64); + d.valid[w] = feed.valid_word(start + w * 64, take); + d.fault[w] = feed.fault_word(w0 + w); + } + match (&feed.data, rep) { + (Data::Num { mant, .. }, Rep::Fix(_)) => { + d.mant[..n].copy_from_slice(&mant[start..start + n]) + } + (Data::Num { mant, scale }, _) => { + d.mant[..n].copy_from_slice(&mant[start..start + n]); + match scale { + Scales::Fixed(s) => d.scale[..n].fill(*s), + Scales::Each(each) => d.scale[..n].copy_from_slice(&each[start..start + n]), + } + } + (Data::Bool { bits, offset }, _) => { + for w in 0..words { + let take = (n - w * 64).min(64); + d.bits[w] = Bits::word(bits, offset + start + w * 64, take); + } + } + (Data::Codes(codes), _) => d.codes[..n].copy_from_slice(&codes[start..start + n]), + (Data::Text(text), _) => self.load_text(d, text), + } + if let Some((bits, values)) = &feed.wide { + for w in 0..words { + let take = (n - w * 64).min(64); + Bits::each( + Bits::word(bits, start + w * 64, take) & d.valid[w] & !d.fault[w], + w * 64, + |i| { + if let Ok(at) = values.binary_search_by_key(&(start + i), |(row, _)| *row) { + d.keep(Rep::Dyn, i, N::Big(values[at].1)); + } + }, + ); + } + } + } + + fn values(&self, d: &mut Reg, m: &[u64], (t, rt): (&Reg, Rep), (e, re): (&Reg, Rep), rep: Rep) { + let n = self.n; + match rep { + Rep::Fix(_) => K::blend(m, &t.mant[..n], &e.mant[..n], &mut d.mant[..n]), + Rep::Dyn => { + K::blend(m, &t.mant[..n], &e.mant[..n], &mut d.mant[..n]); + match (rt, re) { + (Rep::Dyn, Rep::Dyn) => { + K::blend(m, &t.scale[..n], &e.scale[..n], &mut d.scale[..n]) + } + (Rep::Dyn, x) => { + d.scale[..n].fill(x.scale_at(e, 0)); + K::copy_masked(m, &t.scale[..n], &mut d.scale[..n]); + } + (x, Rep::Dyn) => { + d.scale[..n].copy_from_slice(&e.scale[..n]); + K::fill_masked(m, x.scale_at(t, 0), &mut d.scale[..n]); + } + (x, y) => { + d.scale[..n].fill(y.scale_at(e, 0)); + K::fill_masked(m, x.scale_at(t, 0), &mut d.scale[..n]); + } + } + } + Rep::Code => K::blend(m, &t.codes[..n], &e.codes[..n], &mut d.codes[..n]), + Rep::Bool => { + for (w, mw) in m.iter().enumerate() { + d.bits[w] = (t.bits[w] & mw) | (e.bits[w] & !mw); + } + } + Rep::Text => self.blend_text(d, m, t, e), + Rep::Date => self.blend_dates(d, m, t, e), + Rep::Null => {} + } + } + + fn fold( + &self, + fold: Fold, + b: &mut Buf, + list: u16, + (filter, value): (Option, Option<(R, Rep)>), + regs: &[Reg], + scratch: &mut [i64], + ) { + let Some(l) = self.feeds.lists.get(list as usize) else { + return; + }; + if self.n == 0 { + return; + } + let (s0, s1) = (self.start, self.start + self.n); + let (r0, r1) = (l.parent[s0] as usize, l.parent[s1 - 1] as usize); + let filter = filter.map(|f| ®s[f as usize]); + let value = value.map(|(v, rep)| (®s[v as usize], rep)); + let words = self.words.min(Reg::WORDS); + let wide = b.any || value.is_some_and(|(v, _)| v.widened(words)); + if wide || !matches!(fold, Fold::Sum | Fold::Count) { + for r in r0..=r1 { + let lo = (l.offsets[r] as usize).max(s0) - s0; + let hi = (l.offsets[r + 1] as usize).min(s1) - s0; + self.tally(fold, b, r, lo..hi, filter, value); + } + return; + } + let mark = match (fold, value) { + (Fold::Sum, Some((v, Rep::Dyn))) => return self.sum_dyn(b, l, filter, value, v), + (Fold::Sum, Some((_, Rep::Fix(s)))) if s > 0 => Some(s), + (Fold::Sum, Some((_, Rep::Fix(_)))) | (Fold::Count, _) => None, + _ => return, + }; + let sum = fold == Fold::Sum; + let (keep, bad) = self.kept(filter, value.filter(|_| sum).map(|(v, _)| v)); + let n = self.n; + if scratch.len() < 2 * Reg::LANES + 1 { + return; + } + let (vals, pre) = scratch.split_at_mut(Reg::LANES); + match (sum, value) { + (true, Some((v, _))) => K::mask(&keep[..words], &v.mant[..n], &mut vals[..n]), + _ => { + for (&w, co) in keep[..words].iter().zip(vals[..n].chunks_mut(64)) { + for (j, o) in co.iter_mut().enumerate() { + *o = ((w >> j) & 1) as i64; + } + } + } + } + let big = vals[..n].iter().fold(0u64, |m, v| m.max(v.unsigned_abs())); + let safe = big + .checked_mul(n as u64) + .is_some_and(|t| t < i64::MAX as u64); + for (w, &bw) in bad.iter().enumerate().take(words) { + Bits::each(bw, w * 64, |i| { + Bits::set(&mut b.fault, l.parent[s0 + i] as usize, true) + }); + } + if safe { + pre[0] = 0; + let mut acc = 0i64; + for (p, v) in pre[1..=n].iter_mut().zip(&vals[..n]) { + acc = acc.wrapping_add(*v); + *p = acc; + } + } + for r in r0..=r1 { + let lo = (l.offsets[r] as usize).max(s0) - s0; + let hi = (l.offsets[r + 1] as usize).min(s1) - s0; + if lo >= hi { + continue; + } + let part = match safe { + true => Some(pre[hi] - pre[lo]), + false => { + let (mut acc, mut ovf) = (0i64, false); + for v in &vals[lo..hi] { + let (x, o) = acc.overflowing_add(*v); + acc = x; + ovf |= o; + } + (!ovf).then_some(acc) + } + }; + match part.and_then(|p| b.mant[r].checked_add(p)) { + Some(x) => b.mant[r] = x, + None => { + self.tally(fold, b, r, lo..hi, filter, value); + continue; + } + } + if let Some(s) = mark { + if filter.is_none() || !Bits::range(&keep, lo, hi, false) { + b.scale[r] = s; + } + } + } + } + + fn tally( + &self, + fold: Fold, + b: &mut Buf, + r: usize, + range: std::ops::Range, + filter: Option<&Reg>, + value: Option<(&Reg, Rep)>, + ) { + let rep = match (fold, value) { + (Fold::Sum, Some((_, Rep::Fix(0)))) => Rep::Fix(0), + (Fold::Min | Fold::Max, Some((_, rep))) => rep, + _ => Rep::Dyn, + }; + for i in range { + if Bits::get(&b.fault, r) { + return; + } + if let Some(f) = filter { + if !f.ok(i) || f.bad(i) { + Bits::set(&mut b.fault, r, true); + return; + } + if !Bits::get(&f.bits, i) { + continue; + } + } + if fold == Fold::Count { + b.mant[r] += 1; + continue; + } + let Some((v, vr)) = value else { + Bits::set(&mut b.fault, r, true); + return; + }; + if matches!(fold, Fold::Any | Fold::All | Fold::None) && b.codes[r] != 0 { + match filter { + Some(_) => continue, + None => return, + } + } + if !v.ok(i) || v.bad(i) { + Bits::set(&mut b.fault, r, true); + return; + } + match fold { + Fold::Any | Fold::All | Fold::None => { + let bit = Bits::get(&v.bits, i); + if bit != (fold == Fold::All) { + b.codes[r] = 1; + Bits::set(&mut b.bits, r, fold == Fold::Any); + } + } + Fold::One => b.mant[r] += i64::from(Bits::get(&v.bits, i)), + Fold::Min | Fold::Max if vr == Rep::Date => { + b.stamps(); + let x = v.date(i); + let best = b.dates.get(r).copied().unwrap_or(Date(None)); + let take = b.codes[r] == 0 + || match fold { + Fold::Min => x < best, + _ => x >= best, + }; + if take { + if let Some(slot) = b.dates.get_mut(r) { + *slot = x; + } + } + b.codes[r] = 1; + } + Fold::Min | Fold::Max => { + let x = v.num(vr, i); + let take = b.codes[r] == 0 || { + let order = x.compare(b.num(rep, r)); + match fold { + Fold::Min => order == Ordering::Less, + _ => order != Ordering::Less, + } + }; + if take { + b.keep(rep, r, x); + } + b.codes[r] = 1; + } + _ => match b.num(rep, r).arith(Arith::Add, v.num(vr, i)) { + Ok(Some(x)) => { + b.keep(rep, r, x); + b.codes[r] = b.codes[r].saturating_add(1); + } + _ => { + Bits::set(&mut b.fault, r, true); + return; + } + }, + } + } + } + + fn kept( + &self, + filter: Option<&Reg>, + value: Option<&Reg>, + ) -> ([u64; Reg::WORDS], [u64; Reg::WORDS]) { + let words = self.words.min(Reg::WORDS); + let mut keep = [0u64; Reg::WORDS]; + let mut bad = [0u64; Reg::WORDS]; + for w in 0..words { + let (k, x) = match filter { + Some(f) => ( + f.bits[w] & f.valid[w] & !f.fault[w], + !f.valid[w] | f.fault[w], + ), + None => (u64::MAX, 0), + }; + let y = match value { + Some(v) => k & (!v.valid[w] | v.fault[w]), + None => 0, + }; + keep[w] = k & self.tail(w); + bad[w] = (x | y) & self.tail(w); + } + (keep, bad) + } + + fn sum_dyn( + &self, + b: &mut Buf, + l: &Lists, + filter: Option<&Reg>, + value: Option<(&Reg, Rep)>, + v: &Reg, + ) { + let (n, s0) = (self.n, self.start); + let s1 = s0 + n; + let (r0, r1) = (l.parent[s0] as usize, l.parent[s1 - 1] as usize); + let (keep, bad) = self.kept(filter, Some(v)); + let (mant, scale) = (&v.mant[..n], &v.scale[..n]); + for (w, &bw) in bad.iter().enumerate().take(self.words.min(Reg::WORDS)) { + Bits::each(bw, w * 64, |i| { + Bits::set(&mut b.fault, l.parent[s0 + i] as usize, true) + }); + } + for r in r0..=r1 { + let lo = (l.offsets[r] as usize).max(s0) - s0; + let hi = (l.offsets[r + 1] as usize).min(s1) - s0; + let (mut m, mut s, mut o) = (b.mant[r], b.scale[r], false); + for j in lo..hi { + let k = (keep[j / 64] >> (j % 64)) & 1 == 1; + let (x, t, f) = K::add(false, m, mant[j], s, scale[j]); + m = if k { x } else { m }; + s = if k { t } else { s }; + o |= k & f; + } + match o { + true => self.tally(Fold::Sum, b, r, lo..hi, filter, value), + false => { + b.mant[r] = m; + b.scale[r] = s; + } + } + } + } + + fn out(&self, slot: u16, r: &Reg, rep: Rep, scope: Scope, out: &mut Outputs) { + let (n, words, start) = (self.n, self.words.min(Reg::WORDS), self.start); + let w0 = start / 64; + let (slots, faults) = out.parts(); + let Some(s) = slots.get_mut(slot as usize) else { + return; + }; + match &mut s.data { + SlotData::Num { mant, scale } => match rep { + Rep::Fix(x) => { + mant[start..start + n].copy_from_slice(&r.mant[..n]); + scale[start..start + n].fill(x); + } + Rep::Dyn => { + mant[start..start + n].copy_from_slice(&r.mant[..n]); + scale[start..start + n].copy_from_slice(&r.scale[..n]); + } + _ => {} + }, + SlotData::Bool(bits) => bits[w0..w0 + words].copy_from_slice(&r.bits[..words]), + SlotData::Code(codes) => codes[start..start + n].copy_from_slice(&r.codes[..n]), + SlotData::Text { span, data } => self.out_text(r, span, data), + SlotData::Date(dates) => { + for (o, i) in dates[start..start + n].iter_mut().zip(0..n) { + *o = r.date(i).0; + } + } + } + match rep { + Rep::Null => s.valid[w0..w0 + words].fill(0), + _ => s.valid[w0..w0 + words].copy_from_slice(&r.valid[..words]), + } + if rep.num() && r.widened(words) { + for w in 0..words { + Bits::each( + r.wide[w] & r.valid[w] & !r.fault[w] & self.tail(w), + w * 64, + |i| { + s.wide + .push((start + i, r.big.get(i).copied().unwrap_or_default())) + }, + ); + } + } + let parent = match scope { + Scope::Row => None, + Scope::Elem(l) => self.feeds.lists.get(l as usize).map(|l| &l.root), + }; + for w in 0..words { + Bits::each(r.fault[w] & self.tail(w), start + w * 64, |i| { + let row = match parent { + Some(p) => p[i] as usize, + None => i, + }; + if self.select.is_none_or(|sel| Bits::get(sel, row)) { + faults.set(row); + s.fault.set(row); + } + }); + } + } +} diff --git a/core/expression/src/typed/hir.rs b/core/expression/src/typed/hir.rs new file mode 100644 index 00000000..2b03639e --- /dev/null +++ b/core/expression/src/typed/hir.rs @@ -0,0 +1,665 @@ +use crate::functions::{DateMethod, DeprecatedFunction}; +use crate::lane::date::Date; +use crate::typed::num::Dec; +use chrono::{DateTime, SecondsFormat}; +use chrono_tz::Tz; +use std::fmt; + +pub type NodeId = u32; +pub type DictId = u16; +pub type ListId = u16; +pub type ColId = u16; +pub type FieldId = u16; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Num(Option), + Bool, + Code(DictId), + Text, + Date, + Null, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Ty { + pub kind: Kind, + pub nullable: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Scope { + Row, + Elem(ListId), +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Lit { + Null, + Num(Dec), + Bool(bool), + Code(DictId, i32), + Text(String), + Date(Stamp), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Stamp(Option<(i64, u32, Tz)>); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Host { + Construct, + Method(DateMethod), + Legacy(DeprecatedFunction), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Clock { + Now, + Coerce, + Strict, + Matches, + Text, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Arith { + Add, + Sub, + Mul, + Div, + Rem, + Pow, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Cmp { + Eq, + Ne, + Lt, + Le, + Gt, + Ge, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Fold { + Sum, + Count, + Any, + All, + None, + One, + Min, + Max, + Avg, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Func { + StartsWith, + EndsWith, + Len, + Abs, + Floor, + Ceil, + Round(u8), + Trunc(u8), + Min, + Max, + Upper, + Lower, + Trim, + Contains, + Matches, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Range { + pub lo: Dec, + pub lo_closed: bool, + pub hi: Dec, + pub hi_closed: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Op { + Column(ColId), + Field(ListId, FieldId), + Parent(NodeId), + Const(Lit), + Neg(NodeId), + Not(NodeId), + Arith(Arith, NodeId, NodeId), + Cmp(Cmp, NodeId, NodeId), + And(NodeId, NodeId), + Or(NodeId, NodeId), + If(NodeId, NodeId, NodeId), + Coalesce(NodeId, NodeId), + InSet(NodeId, Vec), + InRange(NodeId, Range), + Fold { + fold: Fold, + list: ListId, + filter: Option, + value: Option, + empty: bool, + }, + FirstMatch { + conds: Vec, + strict: bool, + }, + Pick(NodeId, Vec), + Call(Func, Vec), + Classify(NodeId, DictId), + Str(NodeId), + Decode(NodeId), + Concat(Vec), + Host(Host, Vec), + Clock(Clock, Vec), +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Node { + pub op: Op, + pub ty: Ty, + pub scope: Scope, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Collect { + pub list: ListId, + pub keep: Option, + pub item: NodeId, + pub empty: bool, +} + +#[derive(Clone, Debug)] +pub struct Output { + pub name: String, + pub node: NodeId, + pub scope: Scope, + pub ty: Ty, + pub collect: Option, +} + +#[derive(Clone, Debug)] +pub struct ColumnDef { + pub path: String, + pub ty: Ty, +} + +#[derive(Clone, Debug)] +pub struct ListDef { + pub path: String, + pub alias: Option, + pub fields: Vec, + pub parent: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DictKind { + Literals, + Classes, +} + +#[derive(Clone, Debug)] +pub struct Dict { + pub kind: DictKind, + pub values: Vec>, +} + +#[derive(Clone, Debug, Default)] +pub struct Schema { + pub columns: Vec, + pub lists: Vec, + pub dicts: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct Hir { + pub schema: Schema, + pub nodes: Vec, + pub outputs: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Unsupported(pub String); + +impl fmt::Display for Unsupported { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "unsupported: {}", self.0) + } +} + +impl std::error::Error for Unsupported {} + +impl Unsupported { + pub fn new(what: impl Into) -> Self { + Self(what.into()) + } +} + +impl Ty { + pub const fn new(kind: Kind, nullable: bool) -> Self { + Self { kind, nullable } + } + + pub const fn num(scale: Option) -> Self { + Self::new(Kind::Num(scale), false) + } + + pub const fn boolean() -> Self { + Self::new(Kind::Bool, false) + } +} + +impl Dict { + pub fn code(&self, value: &str) -> Option { + self.values + .iter() + .position(|v| v.as_ref() == value) + .and_then(|i| i32::try_from(i).ok()) + } + + pub fn text(&self, code: i32) -> Option<&str> { + usize::try_from(code) + .ok() + .and_then(|i| self.values.get(i)) + .map(|v| v.as_ref()) + } +} + +impl Schema { + pub fn column(&self, path: &str) -> Option { + self.columns + .iter() + .position(|c| c.path == path) + .and_then(|i| ColId::try_from(i).ok()) + } + + pub fn list(&self, path: &str) -> Option { + self.lists + .iter() + .position(|l| l.parent.is_none() && l.path == path) + .and_then(|i| ListId::try_from(i).ok()) + } + + pub fn field(&self, list: ListId, name: &str) -> Option { + self.lists + .get(list as usize)? + .fields + .iter() + .position(|f| f.path == name) + .and_then(|i| FieldId::try_from(i).ok()) + } + + pub fn nested(&self, parent: ListId, name: &str) -> Option { + self.lists + .iter() + .position(|l| l.parent == Some(parent) && l.path == name) + .and_then(|i| ListId::try_from(i).ok()) + } + + pub fn owner(&self, scope: Scope) -> Option { + match scope { + Scope::Row => None, + Scope::Elem(l) => Some( + self.lists + .get(l as usize)? + .parent + .map_or(Scope::Row, Scope::Elem), + ), + } + } + + pub fn depth(&self, scope: Scope) -> u32 { + let mut depth = 0; + let mut at = scope; + while let Some(up) = self.owner(at) { + depth += 1; + at = up; + } + depth + } + + pub fn within(&self, inner: Scope, outer: Scope) -> bool { + let mut at = Some(inner); + while let Some(scope) = at { + if scope == outer { + return true; + } + at = self.owner(scope); + } + false + } + + pub fn chain(&self, list: ListId) -> Vec<&str> { + let mut chain = Vec::new(); + let mut at = Some(list); + while let Some(l) = at.and_then(|l| self.lists.get(l as usize)) { + chain.push(l.path.as_str()); + at = l.parent; + } + chain.reverse(); + chain + } +} + +impl Op { + pub fn inputs(&self) -> Vec { + match self { + Op::Column(_) | Op::Field(..) | Op::Const(_) => Vec::new(), + Op::Parent(a) + | Op::Neg(a) + | Op::Not(a) + | Op::InSet(a, _) + | Op::InRange(a, _) + | Op::Classify(a, _) + | Op::Str(a) + | Op::Decode(a) => vec![*a], + Op::Arith(_, a, b) + | Op::Cmp(_, a, b) + | Op::And(a, b) + | Op::Or(a, b) + | Op::Coalesce(a, b) => vec![*a, *b], + Op::If(c, t, e) => vec![*c, *t, *e], + Op::Fold { filter, value, .. } => filter.iter().chain(value.iter()).copied().collect(), + Op::FirstMatch { conds, .. } => conds.clone(), + Op::Pick(sel, arms) => std::iter::once(*sel).chain(arms.iter().copied()).collect(), + Op::Call(_, args) | Op::Concat(args) | Op::Host(_, args) | Op::Clock(_, args) => { + args.clone() + } + } + } + + pub fn remap(&self, f: impl Fn(NodeId) -> NodeId) -> Op { + match self { + Op::Column(_) | Op::Field(..) | Op::Const(_) => self.clone(), + Op::Parent(a) => Op::Parent(f(*a)), + Op::Neg(a) => Op::Neg(f(*a)), + Op::Not(a) => Op::Not(f(*a)), + Op::Classify(a, d) => Op::Classify(f(*a), *d), + Op::Str(a) => Op::Str(f(*a)), + Op::Decode(a) => Op::Decode(f(*a)), + Op::Concat(args) => Op::Concat(args.iter().map(|a| f(*a)).collect()), + Op::Arith(op, a, b) => Op::Arith(*op, f(*a), f(*b)), + Op::Cmp(op, a, b) => Op::Cmp(*op, f(*a), f(*b)), + Op::And(a, b) => Op::And(f(*a), f(*b)), + Op::Or(a, b) => Op::Or(f(*a), f(*b)), + Op::If(c, t, e) => Op::If(f(*c), f(*t), f(*e)), + Op::Coalesce(a, b) => Op::Coalesce(f(*a), f(*b)), + Op::InSet(a, set) => Op::InSet(f(*a), set.clone()), + Op::InRange(a, r) => Op::InRange(f(*a), *r), + Op::Fold { + fold, + list, + filter, + value, + empty, + } => Op::Fold { + fold: *fold, + list: *list, + filter: filter.map(&f), + value: value.map(&f), + empty: *empty, + }, + Op::FirstMatch { conds, strict } => Op::FirstMatch { + conds: conds.iter().map(|c| f(*c)).collect(), + strict: *strict, + }, + Op::Pick(sel, arms) => Op::Pick(f(*sel), arms.iter().map(|a| f(*a)).collect()), + Op::Call(func, args) => Op::Call(*func, args.iter().map(|a| f(*a)).collect()), + Op::Host(host, args) => Op::Host(*host, args.iter().map(|a| f(*a)).collect()), + Op::Clock(clock, args) => Op::Clock(*clock, args.iter().map(|a| f(*a)).collect()), + } + } +} + +impl Fold { + pub fn quantifier(self) -> bool { + matches!(self, Fold::Any | Fold::All | Fold::None | Fold::One) + } +} + +impl Func { + pub fn text(self) -> bool { + matches!( + self, + Func::StartsWith + | Func::EndsWith + | Func::Len + | Func::Upper + | Func::Lower + | Func::Trim + | Func::Contains + | Func::Matches + ) + } + + pub fn mapping(self) -> bool { + matches!(self, Func::Upper | Func::Lower | Func::Trim) + } +} + +impl Stamp { + pub(crate) fn of(date: Date) -> Self { + Self( + date.0 + .map(|at| (at.timestamp(), at.timestamp_subsec_nanos(), at.timezone())), + ) + } + + pub(crate) fn date(self) -> Date { + Date(self.0.and_then(|(secs, nanos, zone)| { + DateTime::from_timestamp(secs, nanos).map(|at| at.with_timezone(&zone)) + })) + } + + pub fn is_valid(self) -> bool { + self.0.is_some() + } +} + +impl fmt::Display for Stamp { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.date().0 { + Some(at) => write!(f, "{}", at.to_rfc3339_opts(SecondsFormat::Secs, true)), + None => write!(f, "Invalid date"), + } + } +} + +impl Hir { + pub fn node(&self, id: NodeId) -> &Node { + &self.nodes[id as usize] + } + + pub fn dict(&self, id: DictId) -> &Dict { + &self.schema.dicts[id as usize] + } + + pub fn output(&self, name: &str) -> Option { + self.outputs.iter().position(|o| o.name == name) + } +} + +impl fmt::Display for Kind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Kind::Num(Some(s)) => write!(f, "num/{s}"), + Kind::Num(None) => write!(f, "num/*"), + Kind::Bool => write!(f, "bool"), + Kind::Code(d) => write!(f, "code#{d}"), + Kind::Text => write!(f, "text"), + Kind::Date => write!(f, "date"), + Kind::Null => write!(f, "null"), + } + } +} + +impl fmt::Display for Ty { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.nullable { + true => write!(f, "{}?", self.kind), + false => write!(f, "{}", self.kind), + } + } +} + +impl fmt::Display for Scope { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Scope::Row => write!(f, "row"), + Scope::Elem(l) => write!(f, "elem{l}"), + } + } +} + +impl fmt::Display for Lit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Lit::Null => write!(f, "null"), + Lit::Num(d) => write!(f, "{d}"), + Lit::Bool(b) => write!(f, "{b}"), + Lit::Code(d, c) => write!(f, "code#{d}:{c}"), + Lit::Text(t) => write!(f, "{t:?}"), + Lit::Date(d) => write!(f, "date {d}"), + } + } +} + +impl Hir { + fn body(&self, op: &Op) -> String { + let ids = |xs: &[NodeId]| { + xs.iter() + .map(|x| format!("%{x}")) + .collect::>() + .join(", ") + }; + match op { + Op::Column(c) => format!( + "column {}", + self.schema + .columns + .get(*c as usize) + .map_or("?", |c| c.path.as_str()) + ), + Op::Field(l, x) => { + format!( + "field {l}.{}", + self.schema + .lists + .get(*l as usize) + .and_then(|l| l.fields.get(*x as usize)) + .map_or("?", |c| c.path.as_str()) + ) + } + Op::Parent(a) => format!("parent %{a}"), + Op::Const(l) => format!("const {l}"), + Op::Neg(a) => format!("neg %{a}"), + Op::Not(a) => format!("not %{a}"), + Op::Classify(a, d) => format!("classify %{a} dict {d}"), + Op::Str(a) => format!("string %{a}"), + Op::Decode(a) => format!("decode %{a}"), + Op::Concat(args) => format!("concat [{}]", ids(args)), + Op::Arith(op, a, b) => format!("{op:?} %{a}, %{b}").to_lowercase(), + Op::Cmp(op, a, b) => format!("{op:?} %{a}, %{b}").to_lowercase(), + Op::And(a, b) => format!("and %{a}, %{b}"), + Op::Or(a, b) => format!("or %{a}, %{b}"), + Op::If(c, t, e) => format!("if %{c} then %{t} else %{e}"), + Op::Coalesce(a, b) => format!("coalesce %{a}, %{b}"), + Op::InSet(a, set) => format!( + "inset %{a} [{}]", + set.iter() + .map(|l| l.to_string()) + .collect::>() + .join(", ") + ), + Op::InRange(a, r) => format!( + "inrange %{a} {}{}..{}{}", + if r.lo_closed { "[" } else { "(" }, + r.lo, + r.hi, + if r.hi_closed { "]" } else { ")" } + ), + Op::Fold { + fold, + list, + filter, + value, + empty, + } => format!( + "fold {fold:?}{} list {list} filter {} value {}", + if *empty { " empty" } else { "" }, + filter.map_or("-".to_string(), |x| format!("%{x}")), + value.map_or("-".to_string(), |x| format!("%{x}")) + ) + .to_lowercase(), + Op::FirstMatch { conds, strict } => format!( + "firstmatch{} [{}]", + if *strict { " strict" } else { "" }, + ids(conds) + ), + Op::Pick(sel, arms) => format!("pick %{sel} [{}]", ids(arms)), + Op::Call(func, args) => format!("call {func:?}({})", ids(args)).to_lowercase(), + Op::Host(host, args) => format!("host {host:?}({})", ids(args)).to_lowercase(), + Op::Clock(clock, args) => format!("clock {clock:?}({})", ids(args)).to_lowercase(), + } + } +} + +impl fmt::Display for Hir { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (i, c) in self.schema.columns.iter().enumerate() { + writeln!(f, "column {i} {} : {}", c.path, c.ty)?; + } + for (l, list) in self.schema.lists.iter().enumerate() { + match list.parent { + Some(p) => writeln!(f, "list {l} {} in {p}", list.path)?, + None => writeln!( + f, + "list {l} {} as {}", + list.path, + list.alias.as_deref().unwrap_or("-") + )?, + } + for (i, c) in list.fields.iter().enumerate() { + writeln!(f, " field {i} {} : {}", c.path, c.ty)?; + } + } + for (d, dict) in self.schema.dicts.iter().enumerate() { + writeln!(f, "dict {d} {:?} {:?}", dict.kind, dict.values)?; + } + for (i, node) in self.nodes.iter().enumerate() { + writeln!( + f, + "%{i} = {} : {} @{}", + self.body(&node.op), + node.ty, + node.scope + )?; + } + for (i, o) in self.outputs.iter().enumerate() { + match o.collect { + Some(c) => writeln!( + f, + "out {i} {:?} = collect list {} keep {}{} %{} : {} @{}", + o.name, + c.list, + c.keep.map_or("-".to_string(), |k| format!("%{k}")), + if c.empty { " empty" } else { "" }, + o.node, + o.ty, + o.scope + )?, + None => writeln!( + f, + "out {i} {:?} = %{} : {} @{}", + o.name, o.node, o.ty, o.scope + )?, + } + } + Ok(()) + } +} diff --git a/core/expression/src/typed/ins.rs b/core/expression/src/typed/ins.rs new file mode 100644 index 00000000..f856c96e --- /dev/null +++ b/core/expression/src/typed/ins.rs @@ -0,0 +1,559 @@ +use crate::typed::batch::Matcher; +use crate::typed::hir::{ + Arith, Clock, Cmp, Fold, Func, Host, Lit, NodeId, Range, Scope, Unsupported, +}; +use crate::typed::lookup::Lookup; +use crate::typed::num::Dec; +use std::fmt; +use std::sync::Arc; + +#[cfg(not(feature = "regex-lite"))] +pub(crate) use regex::Regex as Pattern; +#[cfg(feature = "regex-lite")] +pub(crate) use regex_lite::Regex as Pattern; + +pub(crate) type R = u16; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Rep { + Fix(u8), + Dyn, + Bool, + Code, + Text, + Date, + Null, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Src { + Col(u16), + Field(u16, u16), + Class(u16), +} + +#[derive(Clone, Debug)] +pub(crate) enum Arg { + Src(Src), + Lit(String), + Reg(R), +} + +#[derive(Clone, Copy, Debug)] +pub(crate) enum FixOp { + Add, + Sub, + Mul, +} + +#[derive(Clone, Debug)] +pub(crate) enum Guard { + True(R), + False(R), + Null(R), + Masks(R, Vec), +} + +#[derive(Clone, Debug)] +pub(crate) enum Ins { + Load { + dst: R, + src: Src, + rep: Rep, + }, + Gather { + dst: R, + buf: u16, + list: u16, + rep: Rep, + }, + Fill { + dst: R, + buf: u16, + rep: Rep, + }, + Spill { + src: R, + buf: u16, + rep: Rep, + }, + Fix { + op: FixOp, + dst: R, + a: R, + b: R, + rep: Rep, + }, + Neg { + dst: R, + a: R, + rep: Rep, + }, + Num { + op: Arith, + dst: R, + a: R, + ra: Rep, + b: R, + rb: Rep, + }, + DivPow { + dst: R, + a: R, + ra: Rep, + k: u32, + by: u8, + }, + CmpFix { + op: Cmp, + dst: R, + a: R, + b: R, + rep: Rep, + }, + CmpGen { + op: Cmp, + dst: R, + a: R, + ra: Rep, + b: R, + rb: Rep, + }, + CmpNum { + op: Cmp, + dst: R, + a: R, + ra: Rep, + b: R, + rb: Rep, + }, + CmpNumK { + op: Cmp, + dst: R, + a: R, + ra: Rep, + k: Dec, + tab: Vec, + fits: u32, + }, + PickTab { + dst: R, + sel: R, + tab: Tab, + rep: Rep, + }, + SelK { + dst: R, + c: R, + t: i64, + e: i64, + rep: Rep, + }, + EqCode { + ne: bool, + dst: R, + a: R, + b: R, + }, + EqBool { + ne: bool, + dst: R, + a: R, + b: R, + }, + EqText { + ne: bool, + dst: R, + a: Arg, + b: Arg, + }, + InCode { + dst: R, + a: R, + set: u64, + null: bool, + }, + InGen { + dst: R, + a: R, + ra: Rep, + set: Vec, + }, + InRangeFix { + dst: R, + a: R, + lo: i64, + span: u64, + empty: bool, + range: Range, + }, + InRangeGen { + dst: R, + a: R, + ra: Rep, + range: Range, + }, + Not { + dst: R, + a: R, + }, + And { + dst: R, + a: R, + b: R, + }, + Or { + dst: R, + a: R, + b: R, + }, + Blend { + dst: R, + c: R, + t: R, + rt: Rep, + e: R, + re: Rep, + rep: Rep, + }, + Coalesce { + dst: R, + a: R, + ra: Rep, + b: R, + rb: Rep, + rep: Rep, + }, + First { + dst: R, + conds: Vec, + sel: bool, + strict: bool, + }, + Lookup { + dst: R, + keys: Vec>, + tab: Box, + }, + Pick { + dst: R, + sel: R, + arms: Vec<(R, Rep, Vec)>, + rep: Rep, + }, + Skip { + guard: Guard, + len: u32, + }, + Fold { + fold: Fold, + buf: u16, + list: u16, + filter: Option, + value: Option<(R, Rep)>, + }, + Text { + func: Func, + dst: R, + a: Arg, + b: Option, + }, + Map { + func: Func, + dst: R, + a: Arg, + }, + Str { + dst: R, + a: Arg, + rep: Rep, + }, + Decode { + dst: R, + a: R, + values: Arc<[Box]>, + }, + Concat { + dst: R, + parts: Vec, + }, + Class { + dst: R, + a: Arg, + matcher: Box>, + }, + Matches { + dst: R, + a: Arg, + pattern: Box, + }, + Math { + func: Func, + dst: R, + args: Vec<(R, Rep)>, + rep: Rep, + }, + Now { + dst: R, + }, + Host { + host: Host, + dst: R, + args: Vec<(Arg, Rep)>, + rep: Rep, + fixed: bool, + }, + Clock { + clock: Clock, + dst: R, + args: Vec<(Arg, Rep)>, + }, + Out { + slot: u16, + src: R, + rep: Rep, + scope: Scope, + }, + Keep { + slot: u16, + src: R, + }, +} + +#[derive(Clone)] +pub(crate) struct Tab { + pub(crate) len: usize, + pub(crate) mant: Box<[i64; 256]>, + pub(crate) scale: Box<[u8; 256]>, + pub(crate) codes: Box<[i32; 256]>, + pub(crate) flag: [u64; 4], + pub(crate) ok: [u64; 4], +} + +#[derive(Clone, Debug)] +pub(crate) enum Arm { + Node(NodeId), + Tab, + Mul(NodeId), +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct BufDef { + pub(crate) scope: Scope, + pub(crate) fold: Option<(u16, Fold, Rep, bool)>, + pub(crate) stage: usize, +} + +impl Rep { + pub(crate) fn of_lit(lit: &Lit) -> Rep { + match lit { + Lit::Null => Rep::Null, + Lit::Num(d) => Rep::Fix(d.scale), + Lit::Bool(_) => Rep::Bool, + Lit::Code(..) => Rep::Code, + Lit::Text(_) => Rep::Text, + Lit::Date(_) => Rep::Date, + } + } + + pub(crate) fn join(a: Rep, b: Rep) -> Result { + match (a, b) { + (x, y) if x == y => Ok(x), + (Rep::Null, x) | (x, Rep::Null) => Ok(x), + (Rep::Fix(_) | Rep::Dyn, Rep::Fix(_) | Rep::Dyn) => Ok(Rep::Dyn), + (x, y) => Err(Unsupported::new(format!( + "typed: cannot join {x:?} and {y:?}" + ))), + } + } + + pub(crate) fn num(self) -> bool { + matches!(self, Rep::Fix(_) | Rep::Dyn) + } +} + +impl Arg { + fn visit(&mut self, f: &mut impl FnMut(&mut R, bool)) { + if let Arg::Reg(r) = self { + f(r, false); + } + } +} + +impl Tab { + pub(crate) const MAX: usize = 255; + + pub(crate) fn new(entries: &[Option]) -> Tab { + let mut t = Tab { + len: entries.len().min(256), + mant: Box::new([0; 256]), + scale: Box::new([0; 256]), + codes: Box::new([0; 256]), + flag: [0; 4], + ok: [0; 4], + }; + for (k, e) in entries.iter().enumerate().take(256) { + let (mant, scale, code, flag, ok) = match e { + Some(Lit::Num(d)) => (d.mant, d.scale, 0, false, true), + Some(Lit::Code(_, c)) => (0, 0, *c, false, true), + Some(Lit::Bool(b)) => (0, 0, 0, *b, true), + _ => (0, 0, 0, false, false), + }; + t.mant[k] = mant; + t.scale[k] = scale; + t.codes[k] = code; + t.flag[k >> 6] |= (flag as u64) << (k & 63); + t.ok[k >> 6] |= (ok as u64) << (k & 63); + } + t + } + + #[inline(always)] + pub(crate) fn bit(set: &[u64; 4], x: usize) -> bool { + (set[(x >> 6) & 3] >> (x & 63)) & 1 != 0 + } +} + +impl fmt::Debug for Tab { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let items: Vec = (0..self.len) + .map(|k| match Tab::bit(&self.ok, k) { + false => "null".to_string(), + true => format!( + "{}e-{}|c{}|{}", + self.mant[k], + self.scale[k], + self.codes[k], + Tab::bit(&self.flag, k) + ), + }) + .collect(); + write!(f, "[{}]", items.join(", ")) + } +} + +impl Ins { + pub(crate) fn regs(&mut self, f: &mut impl FnMut(&mut R, bool)) { + match self { + Ins::Load { dst, .. } + | Ins::Gather { dst, .. } + | Ins::Fill { dst, .. } + | Ins::Now { dst } => f(dst, true), + Ins::Host { dst, args, .. } | Ins::Clock { dst, args, .. } => { + for (a, _) in args.iter_mut() { + a.visit(f); + } + f(dst, true); + } + Ins::EqText { dst, a, b, .. } => { + a.visit(f); + b.visit(f); + f(dst, true); + } + Ins::Text { dst, a, b, .. } => { + a.visit(f); + if let Some(b) = b { + b.visit(f); + } + f(dst, true); + } + Ins::Map { dst, a, .. } + | Ins::Str { dst, a, .. } + | Ins::Class { dst, a, .. } + | Ins::Matches { dst, a, .. } => { + a.visit(f); + f(dst, true); + } + Ins::Concat { dst, parts } => { + for p in parts.iter_mut() { + p.visit(f); + } + f(dst, true); + } + Ins::Spill { src, .. } | Ins::Out { src, .. } | Ins::Keep { src, .. } => f(src, false), + Ins::Fix { dst, a, b, .. } + | Ins::Num { dst, a, b, .. } + | Ins::CmpNum { dst, a, b, .. } + | Ins::CmpFix { dst, a, b, .. } + | Ins::CmpGen { dst, a, b, .. } + | Ins::EqCode { dst, a, b, .. } + | Ins::EqBool { dst, a, b, .. } + | Ins::And { dst, a, b } + | Ins::Or { dst, a, b } + | Ins::Coalesce { dst, a, b, .. } => { + f(a, false); + f(b, false); + f(dst, true); + } + Ins::Neg { dst, a, .. } + | Ins::DivPow { dst, a, .. } + | Ins::CmpNumK { dst, a, .. } + | Ins::PickTab { dst, sel: a, .. } + | Ins::SelK { dst, c: a, .. } + | Ins::InCode { dst, a, .. } + | Ins::InGen { dst, a, .. } + | Ins::InRangeFix { dst, a, .. } + | Ins::InRangeGen { dst, a, .. } + | Ins::Decode { dst, a, .. } + | Ins::Not { dst, a } => { + f(a, false); + f(dst, true); + } + Ins::Math { dst, args, .. } => { + for (a, _) in args.iter_mut() { + f(a, false); + } + f(dst, true); + } + Ins::Blend { dst, c, t, e, .. } => { + f(c, false); + f(t, false); + f(e, false); + f(dst, true); + } + Ins::Lookup { dst, keys, .. } => { + for (r, _) in keys.iter_mut().flatten() { + f(r, false); + } + f(dst, true); + } + Ins::First { dst, conds, .. } => { + for c in conds.iter_mut() { + f(c, false); + } + f(dst, true); + } + Ins::Pick { dst, sel, arms, .. } => { + f(sel, false); + for a in arms.iter_mut() { + f(&mut a.0, false); + } + f(dst, true); + } + Ins::Skip { guard, .. } => match guard { + Guard::True(r) | Guard::False(r) | Guard::Null(r) | Guard::Masks(r, _) => { + f(r, false) + } + }, + Ins::Fold { filter, value, .. } => { + if let Some(r) = filter { + f(r, false); + } + if let Some((r, _)) = value { + f(r, false); + } + } + } + } + + pub(crate) fn dst(&self) -> Option { + let mut d = None; + let mut copy = self.clone(); + copy.regs(&mut |r, def| { + if def { + d = Some(*r); + } + }); + d + } +} diff --git a/core/expression/src/typed/kernel.rs b/core/expression/src/typed/kernel.rs new file mode 100644 index 00000000..e077e3d1 --- /dev/null +++ b/core/expression/src/typed/kernel.rs @@ -0,0 +1,444 @@ +use crate::lane::Bits; +use crate::typed::hir::Cmp; +use crate::typed::num::Dec; +use std::cmp::Ordering; + +pub(crate) struct K; + +pub(crate) trait Lane: + Copy + + std::ops::BitAnd + + std::ops::BitOr + + std::ops::Not +{ + fn splat(bit: u64) -> Self; +} + +impl Lane for i64 { + #[inline(always)] + fn splat(bit: u64) -> Self { + (bit as i64).wrapping_neg() + } +} + +impl Lane for i32 { + #[inline(always)] + fn splat(bit: u64) -> Self { + (bit as i32).wrapping_neg() + } +} + +impl Lane for u8 { + #[inline(always)] + fn splat(bit: u64) -> Self { + (bit as u8).wrapping_neg() + } +} + +impl K { + const MAGIC: u64 = 0x0102_0408_1020_4080; + pub(crate) const P10: [i64; 32] = { + let mut t = [0i64; 32]; + let mut k = 0; + while k < Dec::POW10.len() { + t[k] = Dec::POW10[k]; + k += 1; + } + t + }; + + #[inline(always)] + pub(crate) fn bits(bytes: &[u8; 64]) -> u64 { + let mut m = 0u64; + for (k, c) in bytes.as_chunks::<8>().0.iter().enumerate() { + m |= (u64::from_le_bytes(*c).wrapping_mul(Self::MAGIC) >> 56) << (k * 8); + } + m + } + + #[inline(always)] + pub(crate) fn pack1(a: &[A], out: &mut [u64], f: impl Fn(A) -> bool) { + let (full, rem) = a.as_chunks::<64>(); + let mut o = out.iter_mut(); + for (c, w) in full.iter().zip(&mut o) { + let mut bytes = [0u8; 64]; + for (b, &x) in bytes.iter_mut().zip(c) { + *b = f(x) as u8; + } + *w = Self::bits(&bytes); + } + if let Some(w) = o.next() { + let mut m = 0u64; + for (j, &x) in rem.iter().enumerate() { + m |= (f(x) as u64) << j; + } + *w = m; + } + } + + #[inline(always)] + pub(crate) fn pack2( + a: &[A], + b: &[B], + out: &mut [u64], + f: impl Fn(A, B) -> bool, + ) { + let (fa, ra) = a.as_chunks::<64>(); + let (fb, rb) = b.as_chunks::<64>(); + let mut o = out.iter_mut(); + for ((x, y), w) in fa.iter().zip(fb).zip(&mut o) { + let mut bytes = [0u8; 64]; + for ((b, &x), &y) in bytes.iter_mut().zip(x).zip(y) { + *b = f(x, y) as u8; + } + *w = Self::bits(&bytes); + } + if let Some(w) = o.next() { + let mut m = 0u64; + for (j, (&x, &y)) in ra.iter().zip(rb).enumerate() { + m |= (f(x, y) as u64) << j; + } + *w = m; + } + } + + #[inline(always)] + pub(crate) fn ovf1( + a: &[i64], + out: &mut [i64], + fault: &mut [u64], + f: impl Fn(i64) -> (i64, bool), + ) { + let (fa, ra) = a.as_chunks::<64>(); + let (fo, ro) = out.as_chunks_mut::<64>(); + let mut fw = fault.iter_mut(); + for ((x, o), w) in fa.iter().zip(fo.iter_mut()).zip(&mut fw) { + let mut bytes = [0u8; 64]; + for ((b, o), &x) in bytes.iter_mut().zip(o.iter_mut()).zip(x) { + let (r, v) = f(x); + *o = r; + *b = v as u8; + } + *w |= Self::bits(&bytes); + } + if let Some(w) = fw.next() { + let mut m = 0u64; + for (j, (o, &x)) in ro.iter_mut().zip(ra).enumerate() { + let (r, v) = f(x); + *o = r; + m |= (v as u64) << j; + } + *w |= m; + } + } + + #[inline(always)] + pub(crate) fn ovf2( + a: &[i64], + b: &[i64], + out: &mut [i64], + fault: &mut [u64], + f: impl Fn(i64, i64) -> (i64, bool), + ) { + let (fa, ra) = a.as_chunks::<64>(); + let (fb, rb) = b.as_chunks::<64>(); + let (fo, ro) = out.as_chunks_mut::<64>(); + let mut fw = fault.iter_mut(); + for (((x, y), o), w) in fa.iter().zip(fb).zip(fo.iter_mut()).zip(&mut fw) { + let mut bytes = [0u8; 64]; + for (((b, o), &x), &y) in bytes.iter_mut().zip(o.iter_mut()).zip(x).zip(y) { + let (r, v) = f(x, y); + *o = r; + *b = v as u8; + } + *w |= Self::bits(&bytes); + } + if let Some(w) = fw.next() { + let mut m = 0u64; + for (j, ((o, &x), &y)) in ro.iter_mut().zip(ra).zip(rb).enumerate() { + let (r, v) = f(x, y); + *o = r; + m |= (v as u64) << j; + } + *w |= m; + } + } + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(crate) fn dyn2( + a: &[i64], + b: &[i64], + sa: &[u8], + sb: &[u8], + out: &mut [i64], + scale: &mut [u8], + fault: &mut [u64], + f: impl Fn(i64, i64, u8, u8) -> (i64, u8, bool), + ) { + let (fa, ra) = a.as_chunks::<64>(); + let (fb, rb) = b.as_chunks::<64>(); + let (ga, qa) = sa.as_chunks::<64>(); + let (gb, qb) = sb.as_chunks::<64>(); + let (fo, ro) = out.as_chunks_mut::<64>(); + let (go, qo) = scale.as_chunks_mut::<64>(); + let mut fw = fault.iter_mut(); + for ((((((x, y), p), q), o), s), w) in fa + .iter() + .zip(fb) + .zip(ga) + .zip(gb) + .zip(fo.iter_mut()) + .zip(go.iter_mut()) + .zip(&mut fw) + { + let mut bytes = [0u8; 64]; + for ((((((b, o), s), &x), &y), &p), &q) in bytes + .iter_mut() + .zip(o.iter_mut()) + .zip(s.iter_mut()) + .zip(x) + .zip(y) + .zip(p) + .zip(q) + { + let (r, t, v) = f(x, y, p, q); + *o = r; + *s = t; + *b = v as u8; + } + *w |= Self::bits(&bytes); + } + if let Some(w) = fw.next() { + let mut m = 0u64; + for (j, (((((o, s), &x), &y), &p), &q)) in ro + .iter_mut() + .zip(qo.iter_mut()) + .zip(ra) + .zip(rb) + .zip(qa) + .zip(qb) + .enumerate() + { + let (r, t, v) = f(x, y, p, q); + *o = r; + *s = t; + m |= (v as u64) << j; + } + *w |= m; + } + } + + #[inline(always)] + pub(crate) fn add(sub: bool, x: i64, y: i64, p: u8, q: u8) -> (i64, u8, bool) { + let s = p.max(q); + let fa = Self::P10[((s - p) & 31) as usize]; + let fb = Self::P10[((s - q) & 31) as usize]; + let (xa, o1) = x.overflowing_mul(fa); + let (xb, o2) = y.overflowing_mul(fb); + let (r, o3) = if sub { + xa.overflowing_sub(xb) + } else { + xa.overflowing_add(xb) + }; + let (zx, zy) = (x == 0, y == 0); + let ny = if sub { y.wrapping_neg() } else { y }; + let m = if zx { + ny + } else if zy { + x + } else { + r + }; + let t = if zx { + q + } else if zy { + p + } else { + s + }; + let o = (!zx & !zy & (o1 | o2 | o3 | (fa == 0) | (fb == 0))) | (zx & sub & (y == i64::MIN)); + (m, t, o) + } + + #[inline(always)] + pub(crate) fn mul(x: i64, y: i64, p: u8, q: u8) -> (i64, u8, bool) { + let (r, of) = x.overflowing_mul(y); + let s = p.wrapping_add(q); + let zero = (x == 0) | (y == 0); + let m = if zero { 0 } else { r }; + let t = if zero { 0 } else { s }; + (m, t, !zero & (of | (s > Dec::MAX_SCALE))) + } + + #[inline(always)] + pub(crate) fn div_pow(m: i64, sc: i32, k: u32) -> (i64, u8, bool) { + if m == 0 { + return (0, 0, false); + } + if !(0..=19).contains(&sc) || m == i64::MIN { + return (m, 0, true); + } + if k >= 2 && m % 10 != 0 { + return (m, (sc + k as i32) as u8, false); + } + let (mut a, mut t) = (m.unsigned_abs(), 0u32); + while t < k && a % 10 == 0 { + a /= 10; + t += 1; + } + let (q, s) = match k - t { + 0 => (a, sc), + 1 if a.trailing_zeros() >= 24 => (a, sc + 1), + 1 => match a.checked_mul(10).filter(|x| *x <= i64::MAX as u64) { + Some(x) => (x, sc + 2), + None => return (m, 0, true), + }, + left => (a, sc + left as i32), + }; + let q = q as i64; + (if m < 0 { -q } else { q }, s as u8, false) + } + + #[inline(always)] + pub(crate) fn pack_idx(n: usize, out: &mut [u64], mut f: impl FnMut(usize) -> bool) { + for (w, o) in out.iter_mut().enumerate() { + let base = w * 64; + let end = (base + 64).min(n); + if end - base == 64 { + let mut bytes = [0u8; 64]; + for (j, b) in bytes.iter_mut().enumerate() { + *b = f(base + j) as u8; + } + *o = Self::bits(&bytes); + } else { + let mut m = 0u64; + for j in 0..end.saturating_sub(base) { + m |= (f(base + j) as u64) << j; + } + *o = m; + } + } + } + + #[inline(always)] + pub(crate) fn select(m: &[u64], t: T, e: T, out: &mut [T]) { + for (&w, co) in m.iter().zip(out.chunks_mut(64)) { + for (j, o) in co.iter_mut().enumerate() { + let k = T::splat((w >> j) & 1); + *o = (t & k) | (e & !k); + } + } + } + + #[inline(always)] + pub(crate) fn mask(m: &[u64], src: &[i64], out: &mut [i64]) { + for ((&w, cs), co) in m.iter().zip(src.chunks(64)).zip(out.chunks_mut(64)) { + for (j, (o, &x)) in co.iter_mut().zip(cs).enumerate() { + *o = x & i64::splat((w >> j) & 1); + } + } + } + + pub(crate) fn table(k: Dec) -> (Vec, u32) { + let mut tab = vec![0i64; Dec::MAX_SCALE as usize + 1]; + let mut fits = 0u32; + for (s, t) in tab.iter_mut().enumerate() { + if let Some(u) = k.upscale(s as u8) { + *t = u.mant; + fits |= 1 << s; + } + } + (tab, fits) + } + + #[inline(always)] + pub(crate) fn ord(op: Cmp, o: Ordering) -> bool { + match op { + Cmp::Eq | Cmp::Ne => o == Ordering::Equal, + Cmp::Lt => o == Ordering::Less, + Cmp::Le => o != Ordering::Greater, + Cmp::Gt => o == Ordering::Greater, + Cmp::Ge => o != Ordering::Less, + } + } + + #[inline(always)] + pub(crate) fn cmp_k(op: Cmp, x: &[i64], c: i64, out: &mut [u64]) { + match op { + Cmp::Eq | Cmp::Ne => Self::pack1(x, out, |m| m == c), + Cmp::Lt => Self::pack1(x, out, |m| m < c), + Cmp::Le => Self::pack1(x, out, |m| m <= c), + Cmp::Gt => Self::pack1(x, out, |m| m > c), + Cmp::Ge => Self::pack1(x, out, |m| m >= c), + } + } + + #[inline(always)] + pub(crate) fn blend(m: &[u64], t: &[T], e: &[T], out: &mut [T]) { + for (((&w, ct), ce), co) in m + .iter() + .zip(t.chunks(64)) + .zip(e.chunks(64)) + .zip(out.chunks_mut(64)) + { + if ct.len() == 64 { + for (j, ((o, &x), &y)) in co.iter_mut().zip(ct).zip(ce).enumerate().take(64) { + let k = T::splat((w >> j) & 1); + *o = (x & k) | (y & !k); + } + } else { + for (j, ((o, &x), &y)) in co.iter_mut().zip(ct).zip(ce).enumerate() { + let k = T::splat((w >> j) & 1); + *o = (x & k) | (y & !k); + } + } + } + } + + #[inline(always)] + pub(crate) fn copy_masked(m: &[u64], src: &[T], out: &mut [T]) { + let n = out.len(); + for (w, &mw) in m.iter().enumerate() { + if mw == 0 { + continue; + } + let base = w * 64; + let end = (base + 64).min(n); + if mw == u64::MAX && end - base == 64 { + out[base..end].copy_from_slice(&src[base..end]); + continue; + } + Bits::each(mw, base, |i| { + if i < end { + out[i] = src[i]; + } + }); + } + } + + #[inline(always)] + pub(crate) fn fill_masked(m: &[u64], v: T, out: &mut [T]) { + let n = out.len(); + for (w, &mw) in m.iter().enumerate() { + if mw == 0 { + continue; + } + let base = w * 64; + let end = (base + 64).min(n); + if mw == u64::MAX && end - base == 64 { + out[base..end].fill(v); + continue; + } + Bits::each(mw, base, |i| { + if i < end { + out[i] = v; + } + }); + } + } + + pub(crate) fn words(n: usize) -> usize { + n.div_ceil(64) + } +} diff --git a/core/expression/src/typed/lookup.rs b/core/expression/src/typed/lookup.rs new file mode 100644 index 00000000..1d47bd65 --- /dev/null +++ b/core/expression/src/typed/lookup.rs @@ -0,0 +1,416 @@ +use crate::lane::Bits; +use crate::typed::hir::{Cmp, Hir, Kind, Lit, NodeId, Op, Range}; +use crate::typed::ins::Rep; +use crate::typed::kernel::K; +use crate::typed::num::{Dec, N}; +use std::cmp::Ordering; + +#[derive(Clone, Debug)] +pub(crate) struct Lookup { + pub(crate) keys: Vec, + pub(crate) rules: usize, + pub(crate) words: usize, +} + +#[derive(Clone, Debug)] +pub(crate) struct Key { + pub(crate) node: Option, + pub(crate) domain: Domain, + pub(crate) hit: Vec, + pub(crate) bad: Vec, + pub(crate) fixed: Option<(u8, Vec)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Domain { + Unit, + Bools, + Codes(usize), + Points(Vec), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Val { + Null, + Num(N), + Bool(bool), + Code(i32), + Fault, +} + +struct Test { + rule: usize, + key: Option, + node: NodeId, +} + +impl Lookup { + pub(crate) const RULES: usize = 256; + pub(crate) const WORDS: usize = 4; + const POINTS: usize = 512; + + pub(crate) fn plan(hir: &Hir, conds: &[NodeId], strict: bool, least: usize) -> Option { + let rules = conds.len(); + if rules == 0 || rules > Self::RULES { + return None; + } + let mut tests: Vec = Vec::new(); + for (rule, &cond) in conds.iter().enumerate() { + let mut chain = Vec::new(); + Self::chain(hir, cond, &mut chain); + for node in chain { + let mut keys = Vec::new(); + Self::keys(hir, node, &mut keys)?; + match keys.as_slice() { + [] => tests.push(Test { + rule, + key: None, + node, + }), + [key] => tests.push(Test { + rule, + key: Some(*key), + node, + }), + _ => return None, + } + } + } + if tests.len() < least { + return None; + } + let order = Self::order(&tests, rules, strict)?; + let words = rules.div_ceil(64); + let mut keys = Vec::with_capacity(order.len()); + for key in order { + let domain = Self::domain(hir, key, &tests)?; + let values = Self::values(&domain)?; + let mut hit = vec![0u64; values.len() * words]; + let mut bad = vec![0u64; values.len() * words]; + for (at, value) in values.iter().enumerate() { + for rule in 0..rules { + let mut state = Val::Bool(true); + for test in tests.iter().filter(|t| t.rule == rule && t.key == key) { + if state != Val::Bool(true) { + break; + } + state = Self::eval(hir, test.node, key, *value)?; + } + match state { + Val::Bool(true) => { + Bits::set(&mut hit[at * words..(at + 1) * words], rule, true) + } + Val::Bool(false) => {} + _ if strict => { + Bits::set(&mut bad[at * words..(at + 1) * words], rule, true) + } + _ => {} + } + } + } + keys.push(Key { + node: key, + domain, + hit, + bad, + fixed: None, + }); + } + Some(Lookup { keys, rules, words }) + } + + pub(crate) fn fix(&mut self, reps: &[Rep]) { + for (key, rep) in self.keys.iter_mut().zip(reps) { + if let (Domain::Points(points), Rep::Fix(s)) = (&key.domain, rep) { + key.fixed = points + .iter() + .map(|p| p.upscale(*s).map(|u| u.mant)) + .collect::>>() + .map(|m| (*s, m)); + } + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn chain(hir: &Hir, node: NodeId, out: &mut Vec) { + match hir.node(node).op { + Op::And(a, b) => { + Self::chain(hir, a, out); + Self::chain(hir, b, out); + } + _ => out.push(node), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn keys(hir: &Hir, node: NodeId, out: &mut Vec) -> Option<()> { + let n = hir.node(node); + if matches!(n.ty.kind, Kind::Code(_)) && !matches!(n.op, Op::Const(_)) { + if !out.contains(&node) { + out.push(node); + } + return Some(()); + } + match &n.op { + Op::Const(Lit::Text(_)) => return None, + Op::Const(_) => {} + Op::Column(_) | Op::Field(..) if matches!(n.ty.kind, Kind::Num(_) | Kind::Bool) => { + if !out.contains(&node) { + out.push(node); + } + } + Op::Cmp(..) + | Op::InSet(..) + | Op::InRange(..) + | Op::Not(_) + | Op::And(..) + | Op::Or(..) + | Op::If(..) + | Op::Coalesce(..) => { + for input in n.op.inputs() { + Self::keys(hir, input, out)?; + } + } + _ => return None, + } + Some(()) + } + + fn order(tests: &[Test], rules: usize, strict: bool) -> Option>> { + let mut keys: Vec> = Vec::new(); + for t in tests { + if !keys.contains(&t.key) { + keys.push(t.key); + } + } + if !strict { + return Some(keys); + } + let mut before: Vec<(usize, usize)> = Vec::new(); + for rule in 0..rules { + let mut seen: Vec = Vec::new(); + for t in tests.iter().filter(|t| t.rule == rule) { + let k = keys.iter().position(|x| *x == t.key)?; + match seen.last() { + Some(last) if *last == k => continue, + _ if seen.contains(&k) => return None, + _ => {} + } + for &s in &seen { + if !before.contains(&(s, k)) { + before.push((s, k)); + } + } + seen.push(k); + } + } + let mut left: Vec = (0..keys.len()).collect(); + let mut ordered = Vec::with_capacity(keys.len()); + while !left.is_empty() { + let at = left + .iter() + .position(|k| !before.iter().any(|(a, b)| b == k && left.contains(a)))?; + ordered.push(keys[left.remove(at)]); + } + Some(ordered) + } + + fn domain(hir: &Hir, key: Option, tests: &[Test]) -> Option { + let Some(key) = key else { + return Some(Domain::Unit); + }; + let node = hir.node(key); + match (&node.op, node.ty.kind) { + (_, Kind::Code(d)) => Some(Domain::Codes( + hir.schema.dicts.get(d as usize)?.values.len(), + )), + (_, Kind::Bool) => Some(Domain::Bools), + (_, Kind::Num(_)) => { + let mut points: Vec = Vec::new(); + for t in tests.iter().filter(|t| t.key == Some(key)) { + Self::points(hir, t.node, &mut points); + } + points.sort_by(|a, b| a.compare(*b)); + points.dedup_by(|a, b| a.compare(*b) == Ordering::Equal); + (points.len() <= Self::POINTS).then_some(Domain::Points(points)) + } + _ => None, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn points(hir: &Hir, node: NodeId, out: &mut Vec) { + match &hir.node(node).op { + Op::Const(Lit::Num(d)) => out.push(*d), + Op::InRange(_, r) => out.extend([r.lo, r.hi]), + Op::InSet(_, set) => out.extend(set.iter().filter_map(|l| match l { + Lit::Num(d) => Some(*d), + _ => None, + })), + _ => {} + } + for input in hir.node(node).op.inputs() { + Self::points(hir, input, out); + } + } + + fn values(domain: &Domain) -> Option> { + Some(match domain { + Domain::Unit => vec![Val::Null], + Domain::Bools => vec![Val::Bool(false), Val::Bool(true), Val::Null], + Domain::Codes(k) => (0..=*k as i32) + .map(Val::Code) + .chain(std::iter::once(Val::Null)) + .collect(), + Domain::Points(points) => { + let mut values = Vec::with_capacity(2 * points.len() + 2); + let one = N::Dec(Dec::int(1)); + let two = N::Dec(Dec::int(2)); + for (j, p) in points.iter().enumerate() { + let below = match j { + 0 => N::Dec(*p) + .arith(crate::typed::hir::Arith::Sub, one) + .ok()??, + _ => { + let sum = N::Dec(points[j - 1]) + .arith(crate::typed::hir::Arith::Add, N::Dec(*p)) + .ok()??; + sum.arith(crate::typed::hir::Arith::Div, two).ok()?? + } + }; + values.push(Val::Num(below)); + values.push(Val::Num(N::Dec(*p))); + } + let above = match points.last() { + Some(p) => N::Dec(*p) + .arith(crate::typed::hir::Arith::Add, one) + .ok()??, + None => N::Dec(Dec::ZERO), + }; + values.push(Val::Num(above)); + values.push(Val::Null); + values + } + }) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn eval(hir: &Hir, node: NodeId, key: Option, value: Val) -> Option { + if Some(node) == key { + return Some(value); + } + let ev = |n: NodeId| Self::eval(hir, n, key, value); + Some(match &hir.node(node).op { + Op::Const(Lit::Null) => Val::Null, + Op::Const(Lit::Num(d)) => Val::Num(N::Dec(*d)), + Op::Const(Lit::Bool(b)) => Val::Bool(*b), + Op::Const(Lit::Code(_, c)) => Val::Code(*c), + Op::Cmp(op, a, b) => { + let (x, y) = (ev(*a)?, ev(*b)?); + match (op, x, y) { + (_, Val::Fault, _) | (_, _, Val::Fault) => Val::Fault, + (Cmp::Eq | Cmp::Ne, x, y) => Val::Bool(Self::same(x, y) == (*op == Cmp::Eq)), + (_, Val::Num(x), Val::Num(y)) => Val::Bool(K::ord(*op, x.compare(y))), + _ => Val::Fault, + } + } + Op::InSet(a, set) => match ev(*a)? { + Val::Fault => Val::Fault, + x => Val::Bool(set.iter().any(|l| Self::same(x, Self::lit(l)))), + }, + Op::InRange(a, r) => match ev(*a)? { + Val::Num(x) => Val::Bool(Self::within(x, r)), + _ => Val::Fault, + }, + Op::Not(a) => match ev(*a)? { + Val::Bool(b) => Val::Bool(!b), + _ => Val::Fault, + }, + Op::And(a, b) => match ev(*a)? { + Val::Bool(false) => Val::Bool(false), + Val::Bool(true) => ev(*b)?, + _ => Val::Fault, + }, + Op::Or(a, b) => match ev(*a)? { + Val::Bool(true) => Val::Bool(true), + Val::Bool(false) => ev(*b)?, + _ => Val::Fault, + }, + Op::If(c, t, e) => match ev(*c)? { + Val::Bool(true) => ev(*t)?, + Val::Bool(false) => ev(*e)?, + _ => Val::Fault, + }, + Op::Coalesce(a, b) => match ev(*a)? { + Val::Null => ev(*b)?, + x => x, + }, + _ => return None, + }) + } + + fn lit(lit: &Lit) -> Val { + match lit { + Lit::Null => Val::Null, + Lit::Num(d) => Val::Num(N::Dec(*d)), + Lit::Bool(b) => Val::Bool(*b), + Lit::Code(_, c) => Val::Code(*c), + Lit::Text(_) | Lit::Date(_) => Val::Fault, + } + } + + fn same(x: Val, y: Val) -> bool { + match (x, y) { + (Val::Num(a), Val::Num(b)) => a.compare(b) == Ordering::Equal, + (Val::Fault, _) | (_, Val::Fault) => false, + (a, b) => a == b, + } + } + + fn within(x: N, r: &Range) -> bool { + let (lo, hi) = (x.compare(N::Dec(r.lo)), x.compare(N::Dec(r.hi))); + let above = lo == Ordering::Greater || (r.lo_closed && lo == Ordering::Equal); + let below = hi == Ordering::Less || (r.hi_closed && hi == Ordering::Equal); + above && below + } +} + +impl Key { + #[inline] + pub(crate) fn null(&self) -> usize { + match &self.domain { + Domain::Unit => 0, + Domain::Bools => 2, + Domain::Codes(k) => k + 1, + Domain::Points(points) => 2 * points.len() + 1, + } + } + + #[inline] + pub(crate) fn code(&self, code: i32) -> usize { + match &self.domain { + Domain::Codes(k) => usize::try_from(code).map_or(*k, |c| c.min(*k)), + _ => 0, + } + } + + #[inline] + pub(crate) fn mant(&self, m: i64) -> Option { + let (_, mants) = self.fixed.as_ref()?; + Some(match mants.binary_search(&m) { + Ok(j) => 2 * j + 1, + Err(j) => 2 * j, + }) + } + + #[inline] + pub(crate) fn num(&self, x: N) -> usize { + match &self.domain { + Domain::Points(points) => match points.binary_search_by(|p| N::Dec(*p).compare(x)) { + Ok(j) => 2 * j + 1, + Err(j) => 2 * j, + }, + _ => 0, + } + } +} diff --git a/core/expression/src/typed/lower.rs b/core/expression/src/typed/lower.rs new file mode 100644 index 00000000..8bc90944 --- /dev/null +++ b/core/expression/src/typed/lower.rs @@ -0,0 +1,2753 @@ +use crate::functions::defs::FunctionDefinition; +use crate::functions::{ + ClosureFunction, DateMethod, DeprecatedFunction, FunctionKind, FunctionRegistry, + InternalFunction, MethodKind, MethodRegistry, +}; +use crate::lane::builtins::{Arg as Given, Builtins, Out}; +use crate::lane::date::Date; +use crate::lane::effect::{Effect, Literal}; +use crate::lane::Fusion; +use crate::lexer::{ + ArithmeticOperator, Bracket, ComparisonOperator, Lexer, LogicalOperator, Operator, +}; +use crate::parser::{Node as Ast, Parser}; +use crate::typed::hir::{ + Arith, Clock, Cmp, Collect, ColumnDef, Dict, DictId, DictKind, Fold, Func, Hir, Host, Kind, + ListDef, ListId, Lit, Node, NodeId, Op, Output, Range, Schema, Scope, Stamp, Ty, Unsupported, +}; +use crate::typed::ins::Pattern; +use crate::typed::num::Dec; +use crate::variable::Variable; +use bumpalo::Bump; +use std::collections::HashMap; +use std::sync::Arc; + +type Lowered = Result; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Class { + Num, + Bool, + Text, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Resolved { + Column(Class), + Keyed(Class, Arc), + Output(usize), + List { fields: Vec<(Arc, Class)> }, + KeyedList(Arc, Vec<(Arc, Class)>), + Absent, + Unsupported, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hit { + Strict, + Lenient, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TableRule { + pub cells: Vec>, + pub values: Vec>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TableSpec { + pub inputs: Vec>, + pub outputs: Vec, + pub rules: Vec, + pub hit: Hit, + pub selector: bool, +} + +pub trait Resolve { + fn path(&mut self, path: &str) -> Resolved; + fn alias(&mut self, field: &str) -> Resolved; + fn nested(&mut self, chain: &[&str]) -> Resolved { + let _ = chain; + Resolved::Unsupported + } + fn novel(&mut self) -> bool { + false + } +} + +pub struct Lowering { + schema: Schema, + nodes: Vec, + index: HashMap, + outputs: Vec, + names: Vec<(String, Named)>, + absent: Vec, + literal: Option, + classes: Vec<(NodeId, DictId)>, + member: Option, + units: usize, + graph: bool, + local: usize, + novel: usize, + lone: bool, +} + +struct Mark { + nodes: usize, + outputs: usize, + names: usize, + absent: usize, + columns: usize, + fields: Vec, + dicts: Vec, + literal: Option, + classes: usize, + novel: usize, +} + +#[derive(Clone, Copy)] +struct Ctx { + scope: Scope, + pointer: Option, + item: Option, + dollar: Option, + list: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Seq { + list: ListId, + keep: Option, + value: Option, + empty: bool, + pure: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Named { + Node(NodeId), + Seq(Seq), +} + +enum Base<'a> { + Ident(&'a str), + Pointer, + Dollar, +} + +impl Class { + fn ty(self) -> Ty { + match self { + Class::Num => Ty::new(Kind::Num(None), true), + Class::Bool => Ty::new(Kind::Bool, true), + Class::Text => Ty::new(Kind::Text, true), + } + } +} + +impl TableRule { + fn value(&self, at: usize) -> Option<&str> { + self.values + .get(at) + .and_then(Option::as_deref) + .filter(|v| !v.trim().is_empty()) + } +} + +impl Lowering { + const DEPTH: u32 = 3; + const NATIVE_INPUTS: usize = 1; + + pub fn new(member: Option<(&str, &str)>) -> Self { + let mut schema = Schema::default(); + let member = member.map(|(alias, path)| { + schema.lists.push(ListDef { + path: path.to_string(), + alias: Some(alias.to_string()), + fields: Vec::new(), + parent: None, + }); + 0 + }); + Self { + schema, + nodes: Vec::new(), + index: HashMap::new(), + outputs: Vec::new(), + names: Vec::new(), + absent: Vec::new(), + literal: None, + classes: Vec::new(), + member, + units: 0, + graph: false, + local: 0, + novel: 0, + lone: false, + } + } + + pub fn graph() -> Self { + Self { + graph: true, + ..Self::new(None) + } + } + + pub fn unit( + &mut self, + entries: &[Fusion], + resolve: &mut dyn Resolve, + ) -> Result<(), Unsupported> { + let mark = self.mark(); + self.local = self.names.len(); + let result = entries + .iter() + .try_for_each(|entry| self.entry(entry, resolve)); + self.settle(mark, result, resolve) + } + + pub fn table( + &mut self, + spec: &TableSpec, + resolve: &mut dyn Resolve, + ) -> Result<(), Unsupported> { + let mark = self.mark(); + self.local = self.names.len(); + let result = self.tabled(spec, resolve); + self.settle(mark, result, resolve) + } + + fn settle( + &mut self, + mark: Mark, + result: Result<(), Unsupported>, + resolve: &mut dyn Resolve, + ) -> Result<(), Unsupported> { + if resolve.novel() { + self.novel += 1; + } + let fresh = self.novel > mark.novel; + let result = match result { + Ok(()) if self.units > 0 && (fresh || self.lone) => { + Err(Unsupported::new("isolated: new typed coverage")) + } + other => other, + }; + match result { + Ok(()) => { + self.units += 1; + self.lone |= fresh; + } + Err(_) => self.rollback(mark), + } + result + } + + fn widen(&mut self) { + self.novel += 1; + } + + pub fn units(&self) -> usize { + self.units + } + + pub fn outputs(&self) -> usize { + self.outputs.len() + } + + pub fn retain(&mut self, mut keep: impl FnMut(usize) -> bool) { + let mut at = 0; + self.outputs.retain(|_| { + at += 1; + keep(at - 1) + }); + } + + pub fn finish(mut self) -> Hir { + self.prune(); + Hir { + schema: self.schema, + nodes: self.nodes, + outputs: self.outputs, + } + } + + fn mark(&self) -> Mark { + Mark { + nodes: self.nodes.len(), + outputs: self.outputs.len(), + names: self.names.len(), + absent: self.absent.len(), + columns: self.schema.columns.len(), + fields: self.schema.lists.iter().map(|l| l.fields.len()).collect(), + dicts: self.schema.dicts.iter().map(|d| d.values.len()).collect(), + literal: self.literal, + classes: self.classes.len(), + novel: self.novel, + } + } + + fn rollback(&mut self, mark: Mark) { + self.nodes.truncate(mark.nodes); + self.index.retain(|_, id| (*id as usize) < mark.nodes); + self.outputs.truncate(mark.outputs); + self.names.truncate(mark.names); + self.absent.truncate(mark.absent); + self.schema.columns.truncate(mark.columns); + self.schema.lists.truncate(mark.fields.len()); + for (list, len) in self.schema.lists.iter_mut().zip(&mark.fields) { + list.fields.truncate(*len); + } + self.schema.dicts.truncate(mark.dicts.len()); + for (dict, len) in self.schema.dicts.iter_mut().zip(&mark.dicts) { + dict.values.truncate(*len); + } + self.literal = mark.literal; + self.classes.truncate(mark.classes); + self.novel = mark.novel; + } + + fn prune(&mut self) { + let mut live = vec![false; self.nodes.len()]; + for o in &self.outputs { + live[o.node as usize] = true; + if let Some(c) = o.collect { + live[c.item as usize] = true; + if let Some(k) = c.keep { + live[k as usize] = true; + } + } + } + for id in (0..self.nodes.len()).rev() { + if live[id] { + for input in self.nodes[id].op.inputs() { + live[input as usize] = true; + } + } + } + let mut remap = vec![0 as NodeId; self.nodes.len()]; + let mut kept = Vec::with_capacity(self.nodes.len()); + for (id, node) in std::mem::take(&mut self.nodes).into_iter().enumerate() { + if live[id] { + remap[id] = kept.len() as NodeId; + kept.push(Node { + op: node.op.remap(|x| remap[x as usize]), + ty: node.ty, + scope: node.scope, + }); + } + } + self.nodes = kept; + self.index.clear(); + for o in &mut self.outputs { + o.node = remap[o.node as usize]; + if let Some(c) = &mut o.collect { + c.item = remap[c.item as usize]; + c.keep = c.keep.map(|k| remap[k as usize]); + } + } + } + + fn ctx(&self) -> Ctx { + match self.member { + Some(list) => Ctx { + scope: Scope::Elem(list), + pointer: None, + item: None, + dollar: None, + list: None, + }, + None => Ctx { + scope: Scope::Row, + pointer: None, + item: None, + dollar: None, + list: None, + }, + } + } + + fn entry(&mut self, entry: &Fusion, r: &mut dyn Resolve) -> Result<(), Unsupported> { + let ctx = self.ctx(); + match entry { + Fusion::Output { key, source } => self.parsed( + source, + false, + ctx, + r, + |this, ast, ctx, r| match Self::listy(ast) { + true => { + let seq = this.seq(ast, ctx, r)?; + this.collect(key, seq, ctx.scope) + } + false => match this.expr(ast, ctx, r) { + Ok(id) => this.output(key, id, ctx.scope, true), + Err(e) if Self::passable(ast) => match this.seq(ast, ctx, r) { + Ok(seq) => this.collect(key, seq, ctx.scope), + Err(_) => Err(e), + }, + Err(e) => Err(e), + }, + }, + ), + Fusion::Hidden { key, source } => { + let id = self.parse(source, false, ctx, r)?; + self.output(key, id, ctx.scope, false) + } + Fusion::Rules { .. } => Err(Unsupported::new("rules outside a table")), + } + } + + fn tabled(&mut self, spec: &TableSpec, r: &mut dyn Resolve) -> Result<(), Unsupported> { + if spec.rules.is_empty() || spec.outputs.is_empty() { + return Err(Unsupported::new("empty table")); + } + let ctx = self.ctx(); + let mut targets: Vec> = vec![None; spec.inputs.len()]; + let mut conds = Vec::with_capacity(spec.rules.len()); + let mut folded = false; + for rule in &spec.rules { + let mut cond: Option = None; + for (at, cell) in rule.cells.iter().enumerate() { + let Some(cell) = cell.as_deref().filter(|c| !c.is_empty()) else { + continue; + }; + if cell.trim().is_empty() { + return Err(Unsupported::new("blank table cell")); + } + let test = match ( + spec.inputs.get(at).and_then(Option::as_deref), + targets.get(at).copied().flatten(), + ) { + (Some(_), Some(target)) => self.parse(cell, true, target, r)?, + (Some(field), None) => { + let target = self.target(field, ctx, r)?; + targets[at] = Some(target); + self.parse(cell, true, target, r)? + } + (None, _) => self.parse(cell, false, ctx, r)?, + }; + self.require(test, |k| k == Kind::Bool, "table cell")?; + let test = match spec.hit { + Hit::Lenient => self.guarded(test)?, + Hit::Strict => test, + }; + if spec.hit == Hit::Lenient && self.lit(test) == Some(&Lit::Bool(false)) { + self.widen(); + folded = true; + cond = Some(test); + break; + } + cond = Some(match cond { + None => test, + Some(left) => self.logic(true, left, test)?, + }); + } + conds.push(match cond { + Some(c) => c, + None => self.konst(Lit::Bool(true)), + }); + } + if folded + && spec.inputs.len() <= Self::NATIVE_INPUTS + && conds.iter().all(|c| self.lit(*c).is_some()) + { + return Err(Unsupported::new("constant table")); + } + let total = conds + .iter() + .any(|c| self.nodes[*c as usize].op == Op::Const(Lit::Bool(true))); + let (scope, conds) = match self.member { + Some(_) => ( + ctx.scope, + conds + .iter() + .map(|c| self.parent(*c, ctx.scope)) + .collect::, _>>()?, + ), + None => self.scoped(&conds)?, + }; + let sel = self.add( + Op::FirstMatch { + conds, + strict: spec.hit == Hit::Strict, + }, + Ty::num(Some(0)), + scope, + ); + let mut picks = Vec::with_capacity(spec.outputs.len()); + for at in 0..spec.outputs.len() { + let mut arms = Vec::with_capacity(spec.rules.len()); + for rule in &spec.rules { + arms.push(match rule.value(at) { + Some(source) => self.parse(source, false, ctx, r)?, + None => self.konst(Lit::Null), + }); + } + picks.push(self.picked(sel, arms, total)?); + } + if spec.selector { + picks.push(sel); + } + let names = spec + .outputs + .iter() + .map(String::as_str) + .chain(std::iter::repeat("")); + for (name, pick) in names.zip(picks) { + self.output(name, pick, ctx.scope, true)?; + } + Ok(()) + } + + fn target(&mut self, field: &str, ctx: Ctx, r: &mut dyn Resolve) -> Result { + match self.parse(field, false, ctx, r) { + Ok(target) => Ok(Ctx { + dollar: Some(target), + ..ctx + }), + Err(e) => { + self.widen(); + match self.parsed(field, false, ctx, r, |this, ast, ctx, r| { + this.seq(ast, ctx, r) + }) { + Ok(seq) => Ok(Ctx { + list: Some(seq), + ..ctx + }), + Err(_) => Err(e), + } + } + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn leftmost(&self, id: NodeId) -> Vec { + match &self.nodes[id as usize].op { + Op::And(a, _) | Op::Or(a, _) | Op::Not(a) => self.leftmost(*a), + Op::Cmp(Cmp::Lt | Cmp::Le | Cmp::Gt | Cmp::Ge, a, b) => vec![*a, *b], + Op::InRange(a, _) => vec![*a], + _ => Vec::new(), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn guarded(&mut self, id: NodeId) -> Lowered { + if let Op::And(a, b) = self.nodes[id as usize].op { + let (a, b) = (self.guarded(a)?, self.guarded(b)?); + return self.logic(true, a, b); + } + let operands = self.leftmost(id); + if operands.iter().any(|x| self.lit(*x) == Some(&Lit::Null)) { + self.widen(); + return Ok(self.konst(Lit::Bool(false))); + } + let null = self.konst(Lit::Null); + let mut valid: Option = None; + let nullable: Vec = operands + .into_iter() + .filter(|x| self.ty(*x).nullable) + .collect(); + for operand in nullable { + let present = self.compare(Cmp::Ne, operand, null)?; + valid = Some(match valid { + None => present, + Some(left) => self.logic(true, left, present)?, + }); + } + let Some(valid) = valid else { + return Ok(id); + }; + let no = self.konst(Lit::Bool(false)); + let (arms, ty) = self.unify(vec![id, no])?; + let (scope, ids) = self.scoped(&[valid, arms[0], arms[1]])?; + Ok(self.add(Op::If(ids[0], ids[1], ids[2]), ty, scope)) + } + + fn picked(&mut self, sel: NodeId, arms: Vec, total: bool) -> Lowered { + let (arms, mut ty) = self.unify(arms)?; + ty.nullable |= !total; + let ids: Vec = std::iter::once(sel).chain(arms).collect(); + let (scope, ids) = self.scoped(&ids)?; + Ok(self.add(Op::Pick(ids[0], ids[1..].to_vec()), ty, scope)) + } + + fn parse(&mut self, source: &str, unary: bool, ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + self.parsed(source, unary, ctx, r, |this, ast, ctx, r| { + this.expr(ast, ctx, r) + }) + } + + fn parsed( + &mut self, + source: &str, + unary: bool, + ctx: Ctx, + r: &mut dyn Resolve, + lower: impl FnOnce(&mut Self, &Ast, Ctx, &mut dyn Resolve) -> Result, + ) -> Result { + let bump = Bump::new(); + let mut lexer = Lexer::new(); + let tokens = lexer + .tokenize(&bump, source) + .map_err(|e| Unsupported::new(format!("lex {source:?}: {e}")))?; + let parser = Parser::try_new(&tokens, &bump) + .map_err(|e| Unsupported::new(format!("parse {source:?}: {e}")))?; + let parsed = match unary { + true => parser.unary().parse(), + false => parser.standard().parse(), + }; + parsed + .error() + .map_err(|e| Unsupported::new(format!("parse {source:?}: {e}")))?; + lower(self, parsed.root, ctx, r) + } + + fn output( + &mut self, + name: &str, + id: NodeId, + scope: Scope, + export: bool, + ) -> Result<(), Unsupported> { + if !export { + self.names.push((name.to_string(), Named::Node(id))); + return Ok(()); + } + let id = match self.kind(id) { + Kind::Text => match self.lit(id) { + Some(Lit::Text(text)) => { + let text = text.clone(); + let dict = self.literals(); + let code = self.code(dict, &text); + self.konst(Lit::Code(dict, code)) + } + _ => id, + }, + Kind::Code(d) if self.schema.dicts[d as usize].kind == DictKind::Classes => { + return Err(Unsupported::new(format!("class output {name}"))) + } + _ => id, + }; + let id = match (scope, self.nodes[id as usize].scope) { + (Scope::Elem(_), Scope::Row) => self.parent(id, scope)?, + (a, b) if a == b => id, + _ => return Err(Unsupported::new(format!("output {name} scope mismatch"))), + }; + if !name.is_empty() { + self.names.push((name.to_string(), Named::Node(id))); + } + let ty = self.nodes[id as usize].ty; + self.outputs.push(Output { + name: name.to_string(), + node: id, + scope, + ty, + collect: None, + }); + Ok(()) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn listy(ast: &Ast) -> bool { + match ast { + Ast::Parenthesized(inner) => Self::listy(inner), + Ast::FunctionCall { + kind: FunctionKind::Closure(ClosureFunction::Map | ClosureFunction::Filter), + .. + } => true, + _ => false, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn passable(ast: &Ast) -> bool { + match ast { + Ast::Parenthesized(inner) => Self::passable(inner), + Ast::Identifier(_) | Ast::Member { .. } => true, + Ast::Binary { + left, + operator: Operator::Logical(LogicalOperator::NullishCoalescing), + right: Ast::Array([]), + } => Self::passable(left), + _ => false, + } + } + + fn collect(&mut self, name: &str, seq: Seq, scope: Scope) -> Result<(), Unsupported> { + let inner = Scope::Elem(seq.list); + if self.schema.owner(inner) != Some(scope) { + return Err(Unsupported::new(format!( + "list output {name} outside its owner" + ))); + } + let item = self.item(seq)?; + let item = match self.kind(item) { + Kind::Text => match self.lit(item) { + Some(Lit::Text(text)) => { + let text = text.clone(); + let dict = self.literals(); + let code = self.code(dict, &text); + self.konst(Lit::Code(dict, code)) + } + _ => item, + }, + Kind::Code(d) if self.schema.dicts[d as usize].kind == DictKind::Classes => { + return Err(Unsupported::new(format!("class list output {name}"))) + } + _ => item, + }; + let item = self.parent(item, inner)?; + let node = match seq.keep { + None => item, + Some(keep) => { + let null = self.konst(Lit::Null); + let (arms, ty) = self.unify(vec![item, null])?; + let ids = [ + self.parent(keep, inner)?, + self.parent(arms[0], inner)?, + self.parent(arms[1], inner)?, + ]; + self.add(Op::If(ids[0], ids[1], ids[2]), ty, inner) + } + }; + let keep = seq.keep.map(|k| self.parent(k, inner)).transpose()?; + if !name.is_empty() { + self.names.push(( + name.to_string(), + Named::Seq(Seq { + value: Some(item), + keep, + pure: true, + ..seq + }), + )); + } + let ty = self.nodes[node as usize].ty; + let collect = Collect { + list: seq.list, + keep, + item, + empty: seq.empty, + }; + self.outputs.push(Output { + name: name.to_string(), + node, + scope: inner, + ty, + collect: Some(collect), + }); + Ok(()) + } + + fn add(&mut self, op: Op, ty: Ty, scope: Scope) -> NodeId { + let node = Node { op, ty, scope }; + if let Some(id) = self.index.get(&node) { + return *id; + } + let id = self.nodes.len() as NodeId; + self.index.insert(node.clone(), id); + self.nodes.push(node); + id + } + + fn konst(&mut self, lit: Lit) -> NodeId { + let ty = match &lit { + Lit::Null => Ty::new(Kind::Null, true), + Lit::Num(d) => Ty::num(Some(d.scale)), + Lit::Bool(_) => Ty::boolean(), + Lit::Code(d, _) => Ty::new(Kind::Code(*d), false), + Lit::Text(_) => Ty::new(Kind::Text, false), + Lit::Date(_) => Ty::new(Kind::Date, false), + }; + self.add(Op::Const(lit), ty, Scope::Row) + } + + fn dict(&mut self, kind: DictKind) -> Result { + let d = DictId::try_from(self.schema.dicts.len()) + .map_err(|_| Unsupported::new("too many dictionaries"))?; + self.schema.dicts.push(Dict { + kind, + values: Vec::new(), + }); + Ok(d) + } + + fn literals(&mut self) -> DictId { + if let Some(d) = self.literal { + return d; + } + let d = self.schema.dicts.len() as DictId; + self.schema.dicts.push(Dict { + kind: DictKind::Literals, + values: Vec::new(), + }); + self.literal = Some(d); + d + } + + fn code(&mut self, dict: DictId, text: &str) -> i32 { + let values = &mut self.schema.dicts[dict as usize].values; + match values.iter().position(|v| v.as_ref() == text) { + Some(i) => i as i32, + None => { + values.push(text.into()); + (values.len() - 1) as i32 + } + } + } + + fn lit(&self, id: NodeId) -> Option<&Lit> { + match &self.nodes[id as usize].op { + Op::Const(lit) => Some(lit), + _ => None, + } + } + + fn kind(&self, id: NodeId) -> Kind { + self.nodes[id as usize].ty.kind + } + + fn ty(&self, id: NodeId) -> Ty { + self.nodes[id as usize].ty + } + + fn require( + &self, + id: NodeId, + ok: impl Fn(Kind) -> bool, + what: &str, + ) -> Result<(), Unsupported> { + match ok(self.kind(id)) { + true => Ok(()), + false => Err(Unsupported::new(format!( + "{what}: unexpected type {}", + self.ty(id) + ))), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn parent(&mut self, id: NodeId, scope: Scope) -> Lowered { + let node = &self.nodes[id as usize]; + let (from, ty) = (node.scope, node.ty); + match self.schema.owner(scope) { + _ if from == scope || matches!(node.op, Op::Const(_)) => Ok(id), + Some(up) if self.schema.within(up, from) => { + let lifted = self.parent(id, up)?; + Ok(self.add(Op::Parent(lifted), ty, scope)) + } + _ => Err(Unsupported::new( + "scope: element value used outside its list", + )), + } + } + + fn scoped(&mut self, ids: &[NodeId]) -> Result<(Scope, Vec), Unsupported> { + let mut scope = Scope::Row; + for id in ids { + let node = &self.nodes[*id as usize]; + if matches!(node.op, Op::Const(_)) { + continue; + } + match ( + self.schema.within(node.scope, scope), + self.schema.within(scope, node.scope), + ) { + (true, _) => scope = node.scope, + (false, true) => {} + (false, false) => return Err(Unsupported::new("scope: two different lists")), + } + } + let mut lifted = Vec::with_capacity(ids.len()); + for id in ids { + lifted.push(self.parent(*id, scope)?); + } + Ok((scope, lifted)) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn expr(&mut self, ast: &Ast, ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + match ast { + Ast::Null => Ok(self.konst(Lit::Null)), + Ast::Bool(b) => Ok(self.konst(Lit::Bool(*b))), + Ast::Number(n) => { + let d = Dec::from_decimal(n) + .ok_or_else(|| Unsupported::new(format!("number literal {n} exceeds i64")))?; + Ok(self.konst(Lit::Num(d))) + } + Ast::String(s) => Ok(self.konst(Lit::Text(s.to_string()))), + Ast::Parenthesized(inner) => self.expr(inner, ctx, r), + Ast::Identifier(_) | Ast::Member { .. } | Ast::Pointer => self.path(ast, ctx, r), + Ast::Unary { node, operator } => { + let a = self.expr(node, ctx, r)?; + match operator { + Operator::Logical(LogicalOperator::Not) => self.not(a), + Operator::Arithmetic(ArithmeticOperator::Subtract) => self.neg(a), + Operator::Arithmetic(ArithmeticOperator::Add) => { + self.require(a, |k| matches!(k, Kind::Num(_)), "unary +")?; + Ok(a) + } + other => Err(Unsupported::new(format!("unary operator {other}"))), + } + } + Ast::Binary { + left, + operator, + right, + } => self.binary(left, *operator, right, ctx, r), + Ast::Conditional { + condition, + on_true, + on_false, + } => { + let c = self.expr(condition, ctx, r)?; + self.require(c, |k| k == Kind::Bool, "condition")?; + let t = self.expr(on_true, ctx, r)?; + let e = self.expr(on_false, ctx, r)?; + let (arms, ty) = self.unify(vec![t, e])?; + let (scope, ids) = self.scoped(&[c, arms[0], arms[1]])?; + Ok(self.add(Op::If(ids[0], ids[1], ids[2]), ty, scope)) + } + Ast::FunctionCall { kind, arguments } => self.call(kind, arguments, ctx, r), + Ast::TemplateString(parts) => self.template(parts, ctx, r), + Ast::MethodCall { + kind: MethodKind::DateMethod(method), + this, + arguments, + } => self.method(*method, this, arguments, ctx, r), + other => Err(Unsupported::new(format!( + "expression node {}", + <&'static str>::from(other) + ))), + } + } + + fn not(&mut self, a: NodeId) -> Lowered { + self.require(a, |k| k == Kind::Bool, "not")?; + if let Some(Lit::Bool(b)) = self.lit(a) { + let b = !*b; + return Ok(self.konst(Lit::Bool(b))); + } + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::Not(a), Ty::boolean(), scope)) + } + + fn neg(&mut self, a: NodeId) -> Lowered { + self.require(a, |k| matches!(k, Kind::Num(_)), "negation")?; + if let Some(Lit::Num(d)) = self.lit(a) { + if let Ok(n) = d.checked_neg() { + return Ok(self.konst(Lit::Num(n))); + } + } + let node = &self.nodes[a as usize]; + let (ty, scope) = (Ty::new(node.ty.kind, false), node.scope); + Ok(self.add(Op::Neg(a), ty, scope)) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn segments<'a>(ast: &'a Ast<'a>, out: &mut Vec<&'a str>) -> Result, Unsupported> { + match ast { + Ast::Identifier("$") => Ok(Base::Dollar), + Ast::Identifier(name) => Ok(Base::Ident(name)), + Ast::Pointer => Ok(Base::Pointer), + Ast::Member { + node, + property: Ast::String(segment), + } if !segment.contains('.') => { + let base = Self::segments(node, out)?; + out.push(segment); + Ok(base) + } + other => Err(Unsupported::new(format!( + "member access on {}", + <&'static str>::from(other) + ))), + } + } + + fn named(&self, path: &str) -> Option { + self.names + .iter() + .rev() + .find(|(name, _)| name == path) + .map(|(_, named)| *named) + } + + fn own(&self, path: &str) -> Option { + let from = match self.graph { + true => self.local.min(self.names.len()), + false => 0, + }; + self.names[from..] + .iter() + .rev() + .find(|(name, _)| name == path) + .map(|(_, named)| *named) + } + + fn scalar(named: Named, path: &str) -> Lowered { + match named { + Named::Node(id) => Ok(id), + Named::Seq(_) => Err(Unsupported::new(format!("list {path} used as a value"))), + } + } + + fn overlap(&self, path: &str) -> Result<(), Unsupported> { + let inside = |outer: &str, inner: &str| { + inner.len() > outer.len() + && inner.starts_with(outer) + && inner.as_bytes()[outer.len()] == b'.' + }; + match self + .names + .iter() + .any(|(name, _)| inside(name, path) || inside(path, name)) + { + true => Err(Unsupported::new(format!("{path} overlaps a written path"))), + false => Ok(()), + } + } + + fn path(&mut self, ast: &Ast, ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + let mut segments = Vec::new(); + let base = Self::segments(ast, &mut segments)?; + let rest = segments.join("."); + match base { + Base::Pointer => match (ctx.item, ctx.pointer, rest.is_empty()) { + (Some(item), _, true) => Ok(item), + (Some(_), _, false) => Err(Unsupported::new("member of a mapped element")), + (None, Some(list), _) => self.field(list, &rest, None, r), + (None, None, _) => Err(Unsupported::new("# outside a closure")), + }, + Base::Dollar if segments.is_empty() => ctx + .dollar + .ok_or_else(|| Unsupported::new("$ outside a table cell")), + Base::Dollar if ctx.dollar.is_some() => { + Err(Unsupported::new("member of $ in a table cell")) + } + Base::Dollar => Self::scalar( + self.own(&rest) + .ok_or_else(|| Unsupported::new(format!("unknown $.{rest}")))?, + &rest, + ), + Base::Ident(name) => { + let path = match rest.is_empty() { + true => name.to_string(), + false => format!("{name}.{rest}"), + }; + if self.graph { + return self.column(&path, r); + } + self.overlap(&path)?; + if let Some(named) = self.named(&path) { + return Self::scalar(named, &path); + } + if let Some(list) = self.member { + if self.schema.lists[list as usize].alias.as_deref() == Some(name) { + return match rest.is_empty() { + true => Err(Unsupported::new(format!("whole element {name}"))), + false => self.field(list, &rest, Some(&path), r), + }; + } + } + self.column(&path, r) + } + } + } + + fn column(&mut self, path: &str, r: &mut dyn Resolve) -> Lowered { + if self.graph { + return match r.path(path) { + Resolved::Keyed(class, key) => self.keyed(class, &key), + Resolved::Output(at) => match self.outputs.get(at) { + Some(Output { + collect: None, + node, + .. + }) => Ok(*node), + Some(_) => Err(Unsupported::new(format!("list {path} used as a value"))), + None => Err(Unsupported::new(format!("output {at} of {path}"))), + }, + Resolved::Absent => Ok(self.konst(Lit::Null)), + _ => Err(Unsupported::new(format!("path {path}"))), + }; + } + if let Some(c) = self.schema.column(path) { + let ty = self.schema.columns[c as usize].ty; + return Ok(self.add(Op::Column(c), ty, Scope::Row)); + } + if self.absent.iter().any(|a| a == path) { + return Ok(self.konst(Lit::Null)); + } + if self.schema.list(path).is_some() { + return Err(Unsupported::new(format!("list {path} used as a value"))); + } + match r.path(path) { + Resolved::Column(class) => { + let c = u16::try_from(self.schema.columns.len()) + .map_err(|_| Unsupported::new("too many columns"))?; + self.schema.columns.push(ColumnDef { + path: path.to_string(), + ty: class.ty(), + }); + Ok(self.add(Op::Column(c), class.ty(), Scope::Row)) + } + Resolved::Absent => { + self.absent.push(path.to_string()); + Ok(self.konst(Lit::Null)) + } + Resolved::Keyed(class, key) => self.keyed(class, &key), + Resolved::List { .. } | Resolved::KeyedList(..) => { + Err(Unsupported::new(format!("list {path} used as a value"))) + } + Resolved::Output(_) | Resolved::Unsupported => { + Err(Unsupported::new(format!("path {path}"))) + } + } + } + + fn keyed(&mut self, class: Class, key: &str) -> Lowered { + let c = match self.schema.column(key) { + Some(c) => c, + None => { + let c = u16::try_from(self.schema.columns.len()) + .map_err(|_| Unsupported::new("too many columns"))?; + self.schema.columns.push(ColumnDef { + path: key.to_string(), + ty: class.ty(), + }); + c + } + }; + let ty = self.schema.columns[c as usize].ty; + match ty == class.ty() { + true => Ok(self.add(Op::Column(c), ty, Scope::Row)), + false => Err(Unsupported::new(format!( + "column {key} read as two classes" + ))), + } + } + + fn field( + &mut self, + list: ListId, + name: &str, + member: Option<&str>, + r: &mut dyn Resolve, + ) -> Lowered { + if let Some(f) = self.schema.field(list, name) { + let ty = self.schema.lists[list as usize].fields[f as usize].ty; + return Ok(self.add(Op::Field(list, f), ty, Scope::Elem(list))); + } + let Some(path) = member else { + return Err(Unsupported::new(format!("unknown field {name}"))); + }; + if self.absent.iter().any(|a| a == path) { + return Ok(self.konst(Lit::Null)); + } + match r.alias(name) { + Resolved::Column(class) => { + let fields = &mut self.schema.lists[list as usize].fields; + let f = + u16::try_from(fields.len()).map_err(|_| Unsupported::new("too many fields"))?; + fields.push(ColumnDef { + path: name.to_string(), + ty: class.ty(), + }); + Ok(self.add(Op::Field(list, f), class.ty(), Scope::Elem(list))) + } + Resolved::Absent => { + self.absent.push(path.to_string()); + Ok(self.konst(Lit::Null)) + } + _ => Err(Unsupported::new(format!("member field {name}"))), + } + } + + fn binary( + &mut self, + left: &Ast, + operator: Operator, + right: &Ast, + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { + match operator { + Operator::Arithmetic(op) => { + let op = match op { + ArithmeticOperator::Add => Arith::Add, + ArithmeticOperator::Subtract => Arith::Sub, + ArithmeticOperator::Multiply => Arith::Mul, + ArithmeticOperator::Divide => Arith::Div, + ArithmeticOperator::Modulus => Arith::Rem, + ArithmeticOperator::Power => Arith::Pow, + }; + let a = self.expr(left, ctx, r)?; + let b = self.expr(right, ctx, r)?; + let dated = |this: &Self, x: NodeId| this.kind(x) == Kind::Date; + match op == Arith::Add + && (self.texty(a) || self.texty(b) || dated(self, a) || dated(self, b)) + { + true => { + let (a, b) = (self.rendered(a)?, self.rendered(b)?); + self.concat(vec![a, b]) + } + false => self.arith(op, a, b), + } + } + Operator::Comparison(ComparisonOperator::In | ComparisonOperator::NotIn) => { + let a = self.expr(left, ctx, r)?; + let test = match right { + Ast::Array(items) => self.inset(a, items, ctx, r)?, + Ast::Interval { + left: lo, + right: hi, + left_bracket, + right_bracket, + } => self.inrange(a, (lo, hi), (*left_bracket, *right_bracket), ctx, r)?, + other => { + let seq = self.seq(other, ctx, r)?; + self.member(a, seq)? + } + }; + match operator { + Operator::Comparison(ComparisonOperator::NotIn) => self.not(test), + _ => Ok(test), + } + } + Operator::Comparison(op) => { + let a = self.expr(left, ctx, r)?; + let b = self.expr(right, ctx, r)?; + let op = match op { + ComparisonOperator::Equal => Cmp::Eq, + ComparisonOperator::NotEqual => Cmp::Ne, + ComparisonOperator::LessThan => Cmp::Lt, + ComparisonOperator::LessThanOrEqual => Cmp::Le, + ComparisonOperator::GreaterThan => Cmp::Gt, + ComparisonOperator::GreaterThanOrEqual => Cmp::Ge, + other => return Err(Unsupported::new(format!("comparison {other}"))), + }; + self.compare(op, a, b) + } + Operator::Logical(LogicalOperator::And | LogicalOperator::Or) => { + let a = self.expr(left, ctx, r)?; + let b = self.expr(right, ctx, r)?; + self.logic(operator == Operator::Logical(LogicalOperator::And), a, b) + } + Operator::Logical(LogicalOperator::NullishCoalescing) => { + let a = self.expr(left, ctx, r)?; + let b = self.expr(right, ctx, r)?; + let nullable = self.ty(a).nullable && self.ty(b).nullable; + let (arms, ty) = self.unify(vec![a, b])?; + let (scope, ids) = self.scoped(&arms)?; + Ok(self.add( + Op::Coalesce(ids[0], ids[1]), + Ty::new(ty.kind, nullable), + scope, + )) + } + other => Err(Unsupported::new(format!("operator {other}"))), + } + } + + fn arith(&mut self, op: Arith, a: NodeId, b: NodeId) -> Lowered { + let (Kind::Num(sa), Kind::Num(sb)) = (self.kind(a), self.kind(b)) else { + return Err(Unsupported::new(format!( + "arithmetic between {} and {}", + self.ty(a), + self.ty(b) + ))); + }; + let divisor = match self.lit(b) { + Some(Lit::Num(d)) => Some(*d), + _ => None, + }; + let ty = match op { + Arith::Add | Arith::Sub => Ty::num(sa.filter(|x| sb == Some(*x))), + Arith::Mul => Ty::num((sa == Some(0) && sb == Some(0)).then_some(0)), + Arith::Div | Arith::Rem => { + Ty::new(Kind::Num(None), divisor.is_none_or(|d| d.is_zero())) + } + Arith::Pow if divisor.is_some_and(|d| d.scale == 0) => Ty::num(None), + Arith::Pow => return Err(Unsupported::new("exponent must be an integer literal")), + }; + let (scope, ids) = self.scoped(&[a, b])?; + Ok(self.add(Op::Arith(op, ids[0], ids[1]), ty, scope)) + } + + fn classify(&mut self, id: NodeId) -> Lowered { + self.require(id, |k| k == Kind::Text, "classify")?; + let dict = match self.classes.iter().find(|(n, _)| *n == id) { + Some((_, d)) => *d, + None => { + let d = self.dict(DictKind::Classes)?; + self.classes.push((id, d)); + d + } + }; + let node = &self.nodes[id as usize]; + let (nullable, scope) = (node.ty.nullable, node.scope); + Ok(self.add( + Op::Classify(id, dict), + Ty::new(Kind::Code(dict), nullable), + scope, + )) + } + + fn compare(&mut self, op: Cmp, a: NodeId, b: NodeId) -> Lowered { + let (ka, kb) = (self.kind(a), self.kind(b)); + let eq = matches!(op, Cmp::Eq | Cmp::Ne); + let plain = |x: NodeId, y: NodeId| match (self.lit(y), self.ty(x)) { + ( + Some(Lit::Bool(b)), + Ty { + kind: Kind::Bool, + nullable: false, + }, + ) if self.lit(x).is_none() => Some((x, *b)), + _ => None, + }; + if let (true, Some((x, b))) = (eq, plain(a, b).or_else(|| plain(b, a))) { + return match b == (op == Cmp::Eq) { + true => Ok(x), + false => self.not(x), + }; + } + if ka == Kind::Date || kb == Kind::Date { + return self.dated(op, a, b); + } + let (a, b) = match (ka, kb) { + (Kind::Text, Kind::Text) if eq => { + match (self.lit(a).is_some(), self.lit(b).is_some()) { + (true, true) => { + let equal = self.lit(a) == self.lit(b); + return Ok(self.konst(Lit::Bool(equal == (op == Cmp::Eq)))); + } + (false, true) => { + let x = self.classify(a)?; + let Kind::Code(d) = self.kind(x) else { + return Err(Unsupported::new("classify")); + }; + (x, self.coerce(b, d)?) + } + (true, false) => { + let y = self.classify(b)?; + let Kind::Code(d) = self.kind(y) else { + return Err(Unsupported::new("classify")); + }; + (self.coerce(a, d)?, y) + } + (false, false) => (a, b), + } + } + (Kind::Text, Kind::Null) if eq && self.direct(a) => (self.classify(a)?, b), + (Kind::Null, Kind::Text) if eq && self.direct(b) => (a, self.classify(b)?), + (Kind::Text, Kind::Null) | (Kind::Null, Kind::Text) if eq => (a, b), + (Kind::Code(d), Kind::Text) if eq && self.lit(b).is_some() => (a, self.coerce(b, d)?), + (Kind::Text, Kind::Code(d)) if eq && self.lit(a).is_some() => (self.coerce(a, d)?, b), + (Kind::Code(_), Kind::Text) if eq => (self.decode(a)?, b), + (Kind::Text, Kind::Code(_)) if eq => (a, self.decode(b)?), + (Kind::Code(x), Kind::Code(y)) if eq && x == y => (a, b), + (Kind::Num(_), Kind::Num(_)) | (Kind::Bool, Kind::Bool) if eq => (a, b), + (Kind::Null, _) | (_, Kind::Null) if eq => (a, b), + (Kind::Num(_), Kind::Num(_)) => (a, b), + (Kind::Null, Kind::Num(_) | Kind::Null) | (Kind::Num(_), Kind::Null) => { + self.widen(); + (a, b) + } + (x, y) + if eq + && Self::family(x) + .zip(Self::family(y)) + .is_some_and(|(p, q)| p != q) => + { + return self.mismatch(op, a, b) + } + _ => { + return Err(Unsupported::new(format!( + "compare {op:?} between {ka} and {kb}" + ))) + } + }; + let (scope, ids) = self.scoped(&[a, b])?; + Ok(self.add(Op::Cmp(op, ids[0], ids[1]), Ty::boolean(), scope)) + } + + fn family(kind: Kind) -> Option { + match kind { + Kind::Num(_) => Some(0), + Kind::Bool => Some(1), + Kind::Text | Kind::Code(_) => Some(2), + Kind::Date => Some(3), + Kind::Null => None, + } + } + + fn mismatch(&mut self, op: Cmp, a: NodeId, b: NodeId) -> Lowered { + if !(self.ty(a).nullable && self.ty(b).nullable) { + return Ok(self.konst(Lit::Bool(op == Cmp::Ne))); + } + let null = self.konst(Lit::Null); + let x = self.compare(Cmp::Eq, a, null)?; + let y = self.compare(Cmp::Eq, b, null)?; + let both = self.logic(true, x, y)?; + match op { + Cmp::Eq => Ok(both), + _ => self.not(both), + } + } + + fn coerce(&mut self, id: NodeId, dict: DictId) -> Lowered { + match self.lit(id) { + Some(Lit::Text(text)) => { + let text = text.clone(); + let code = self.code(dict, &text); + Ok(self.konst(Lit::Code(dict, code))) + } + _ if self.kind(id) == Kind::Code(dict) || self.kind(id) == Kind::Null => Ok(id), + _ => Err(Unsupported::new(format!( + "cannot code {} as dict {dict}", + self.ty(id) + ))), + } + } + + fn logic(&mut self, and: bool, a: NodeId, b: NodeId) -> Lowered { + self.require(a, |k| k == Kind::Bool, "logical operand")?; + self.require(b, |k| k == Kind::Bool, "logical operand")?; + let nullable = self.ty(b).nullable; + let (scope, ids) = self.scoped(&[a, b])?; + let op = match and { + true => Op::And(ids[0], ids[1]), + false => Op::Or(ids[0], ids[1]), + }; + Ok(self.add(op, Ty::new(Kind::Bool, nullable), scope)) + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn inset(&mut self, a: NodeId, items: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + if self.kind(a) == Kind::Date { + return self.dates_in(a, items, ctx, r); + } + if matches!(self.kind(a), Kind::Text | Kind::Code(_)) { + let mut dates = Vec::new(); + let mut rest = Vec::with_capacity(items.len()); + for item in items { + let id = self.expr(item, ctx, r)?; + match self.lit(id) { + Some(Lit::Date(_)) => dates.push(id), + _ => rest.push(*item), + } + } + if !dates.is_empty() { + let mut hit = self.inset(a, &rest, ctx, r)?; + for date in dates { + let found = self.belongs(date, a)?; + hit = self.logic(false, hit, found)?; + } + return Ok(hit); + } + } + let a = match self.kind(a) { + Kind::Text => self.classify(a)?, + _ => a, + }; + let kind = self.kind(a); + let mut set: Vec = Vec::new(); + for item in items { + let id = self.expr(item, ctx, r)?; + let lit = self + .lit(id) + .cloned() + .ok_or_else(|| Unsupported::new("in: non-literal set item"))?; + let lit = match (kind, lit) { + (_, Lit::Null) => Some(Lit::Null), + (Kind::Code(d), Lit::Text(t)) => Some(Lit::Code(d, self.code(d, &t))), + (Kind::Num(_), lit @ Lit::Num(_)) | (Kind::Bool, lit @ Lit::Bool(_)) => Some(lit), + _ => None, + }; + if let Some(lit) = lit { + if !set.contains(&lit) { + set.push(lit); + } + } + } + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::InSet(a, set), Ty::boolean(), scope)) + } + + fn inrange( + &mut self, + a: NodeId, + (lo, hi): (&Ast, &Ast), + (left, right): (Bracket, Bracket), + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { + if self.kind(a) == Kind::Date { + return self.date_range(a, (lo, hi), (left, right), ctx, r); + } + self.require(a, |k| matches!(k, Kind::Num(_)), "interval operand")?; + let lo = self.expr(lo, ctx, r)?; + let hi = self.expr(hi, ctx, r)?; + let (Some(Lit::Num(lo)), Some(Lit::Num(hi))) = + (self.lit(lo).cloned(), self.lit(hi).cloned()) + else { + return Err(Unsupported::new("interval bounds must be numeric literals")); + }; + let lo_closed = match left { + Bracket::LeftSquareBracket => true, + Bracket::LeftParenthesis => false, + other => return Err(Unsupported::new(format!("interval bracket {other}"))), + }; + let hi_closed = match right { + Bracket::RightSquareBracket => true, + Bracket::RightParenthesis => false, + other => return Err(Unsupported::new(format!("interval bracket {other}"))), + }; + let scope = self.nodes[a as usize].scope; + Ok(self.add( + Op::InRange( + a, + Range { + lo, + lo_closed, + hi, + hi_closed, + }, + ), + Ty::boolean(), + scope, + )) + } + + fn unify(&mut self, ids: Vec) -> Result<(Vec, Ty), Unsupported> { + let computed = ids + .iter() + .any(|id| self.kind(*id) == Kind::Text && self.lit(*id).is_none()); + let ids = match computed { + true => ids + .into_iter() + .map(|id| match self.kind(id) { + Kind::Code(_) => self.decode(id), + _ => Ok(id), + }) + .collect::, _>>()?, + false => ids, + }; + let mut dict: Option = None; + for id in &ids { + match self.kind(*id) { + Kind::Code(d) if dict.is_some_and(|x| x != d) => { + return Err(Unsupported::new("branches code different dictionaries")) + } + Kind::Code(d) => dict = Some(d), + _ => {} + } + } + let texts = !computed && ids.iter().any(|id| self.kind(*id) == Kind::Text); + if texts { + let d = match dict { + Some(d) => d, + None => self.literals(), + }; + if self.schema.dicts[d as usize].kind != DictKind::Literals { + return Err(Unsupported::new("dictionary mixing")); + } + dict = Some(d); + } + let mut out = Vec::with_capacity(ids.len()); + for id in ids { + out.push(match (self.kind(id), dict) { + (Kind::Text, Some(d)) => self.coerce(id, d)?, + _ => id, + }); + } + let mut kind: Option = None; + let mut nullable = false; + for id in &out { + let ty = self.ty(*id); + nullable |= ty.nullable; + kind = match (kind, ty.kind) { + (k, Kind::Null) => k, + (None, k) => Some(k), + (Some(Kind::Num(x)), Kind::Num(y)) => { + Some(Kind::Num(if x == y { x } else { None })) + } + (Some(x), y) if x == y => Some(x), + (Some(x), y) => { + return Err(Unsupported::new(format!("branches of type {x} and {y}"))) + } + }; + } + Ok(( + out, + Ty::new(kind.unwrap_or(Kind::Null), nullable || kind.is_none()), + )) + } + + fn call( + &mut self, + kind: &FunctionKind, + args: &[&Ast], + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { + match (kind, args) { + ( + FunctionKind::Internal( + f @ (InternalFunction::Sum + | InternalFunction::Min + | InternalFunction::Max + | InternalFunction::Avg), + ), + [arg], + ) if !matches!(arg, Ast::Array(_)) => { + let seq = self.seq(arg, ctx, r)?; + let value = self.item(seq)?; + let fold = match f { + InternalFunction::Sum => Fold::Sum, + InternalFunction::Min => Fold::Min, + InternalFunction::Max => Fold::Max, + _ => Fold::Avg, + }; + self.fold(fold, seq, seq.keep, Some(value)) + } + (FunctionKind::Closure(ClosureFunction::Count), [source, body]) => { + let seq = Self::pure(self.seq(source, ctx, r)?)?; + let test = self.predicate(seq, body, ctx, r)?; + let filter = match seq.keep { + None => test, + Some(keep) => self.logic(true, keep, test)?, + }; + self.fold(Fold::Count, seq, Some(filter), None) + } + (FunctionKind::Internal(InternalFunction::Contains), [Ast::Array(items), x]) => { + self.widen(); + let x = self.expr(x, ctx, r)?; + let items = self.literals_of(items, ctx, r)?; + let mut hits = Vec::with_capacity(items.len()); + for item in items { + hits.push(self.belongs(x, item)?); + } + self.chain(false, hits) + } + ( + FunctionKind::Closure( + c @ (ClosureFunction::Some | ClosureFunction::All | ClosureFunction::None), + ), + [Ast::Array(items), body], + ) => { + self.widen(); + let body = Self::closure(body)?; + let items = self.literals_of(items, ctx, r)?; + let mut tests = Vec::with_capacity(items.len()); + for item in items { + let test = self.expr( + body, + Ctx { + item: Some(item), + ..ctx + }, + r, + )?; + if self.ty(test) != Ty::boolean() { + return Err(Unsupported::new(format!( + "predicate: unexpected type {}", + self.ty(test) + ))); + } + tests.push(test); + } + match c { + ClosureFunction::Some => self.chain(false, tests), + ClosureFunction::All => self.chain(true, tests), + _ => { + let any = self.chain(false, tests)?; + self.not(any) + } + } + } + (FunctionKind::Internal(InternalFunction::Contains), [list, x]) => { + match self.seq(list, ctx, r) { + Ok(seq) => { + let x = self.expr(x, ctx, r)?; + self.member(x, seq) + } + Err(e) => { + let a = self.expr(list, ctx, r).map_err(|_| e)?; + let b = self.expr(x, ctx, r)?; + self.test(Func::Contains, a, b) + } + } + } + (FunctionKind::Internal(InternalFunction::Len), [arg]) => { + match self.seq(arg, ctx, r).and_then(Self::pure) { + Ok(seq) => self.fold(Fold::Count, seq, seq.keep, None), + Err(_) => { + let a = self.expr(arg, ctx, r)?; + let a = self.textual(a)?; + if let Some(Lit::Text(t)) = self.lit(a) { + let n = Dec::int(t.len() as i64); + return Ok(self.konst(Lit::Num(n))); + } + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::Call(Func::Len, vec![a]), Ty::num(Some(0)), scope)) + } + } + } + ( + FunctionKind::Internal( + f @ (InternalFunction::StartsWith + | InternalFunction::EndsWith + | InternalFunction::Matches), + ), + [a, b], + ) => { + let a = self.expr(a, ctx, r)?; + let b = self.expr(b, ctx, r)?; + let func = match f { + InternalFunction::StartsWith => Func::StartsWith, + InternalFunction::EndsWith => Func::EndsWith, + _ => Func::Matches, + }; + self.test(func, a, b) + } + (FunctionKind::Internal(InternalFunction::String), [arg]) => { + let a = self.expr(arg, ctx, r)?; + self.stringify(a) + } + ( + FunctionKind::Internal( + f + @ (InternalFunction::Upper | InternalFunction::Lower | InternalFunction::Trim), + ), + [arg], + ) => { + let a = self.expr(arg, ctx, r)?; + let func = match f { + InternalFunction::Upper => Func::Upper, + InternalFunction::Lower => Func::Lower, + _ => Func::Trim, + }; + self.mapped(func, a) + } + (FunctionKind::Internal(InternalFunction::Bool), [arg]) => { + let a = self.expr(arg, ctx, r)?; + match self.ty(a) { + Ty { + kind: Kind::Bool, + nullable: false, + } => Ok(a), + Ty { + kind: Kind::Bool, + nullable: true, + } => { + let no = self.konst(Lit::Bool(false)); + let (scope, ids) = self.scoped(&[a, no])?; + Ok(self.add(Op::Coalesce(ids[0], ids[1]), Ty::boolean(), scope)) + } + Ty { + kind: Kind::Null, .. + } => Ok(self.konst(Lit::Bool(false))), + ty => Err(Unsupported::new(format!("bool of {ty}"))), + } + } + ( + FunctionKind::Internal( + f @ (InternalFunction::Abs | InternalFunction::Floor | InternalFunction::Ceil), + ), + [arg], + ) => { + let a = self.expr(arg, ctx, r)?; + let Kind::Num(scale) = self.kind(a) else { + return Err(Unsupported::new(format!("{f:?} of {}", self.ty(a)))); + }; + let (func, ty) = match f { + InternalFunction::Abs => (Func::Abs, Ty::num(scale)), + InternalFunction::Floor => (Func::Floor, Ty::num(Some(0))), + _ => (Func::Ceil, Ty::num(Some(0))), + }; + self.math(func, vec![a], ty) + } + ( + FunctionKind::Internal(f @ (InternalFunction::Round | InternalFunction::Trunc)), + [arg, rest @ ..], + ) => { + let a = self.expr(arg, ctx, r)?; + let Kind::Num(scale) = self.kind(a) else { + return Err(Unsupported::new(format!("{f:?} of {}", self.ty(a)))); + }; + let places = match rest { + [] => 0, + [places] => { + let p = self.expr(places, ctx, r)?; + match self.lit(p) { + Some(Lit::Num(d)) + if d.scale == 0 + && (0..=i64::from(Dec::MAX_SCALE)).contains(&d.mant) => + { + d.mant as u8 + } + _ => { + return Err(Unsupported::new( + "decimal places must be a small integer literal", + )) + } + } + } + _ => return Err(Unsupported::new(format!("{f:?} arity"))), + }; + let (func, ty) = match f { + InternalFunction::Round => { + (Func::Round(places), Ty::num(scale.map(|s| s.min(places)))) + } + _ => (Func::Trunc(places), Ty::num(Some(places))), + }; + self.math(func, vec![a], ty) + } + ( + FunctionKind::Internal( + f @ (InternalFunction::Min + | InternalFunction::Max + | InternalFunction::Avg + | InternalFunction::Sum), + ), + [Ast::Array(items)], + ) => { + if items.is_empty() { + return Err(Unsupported::new("aggregate of an empty list")); + } + let mut args = Vec::with_capacity(items.len()); + for item in items.iter() { + args.push(self.expr(item, ctx, r)?); + } + let dates = matches!(f, InternalFunction::Min | InternalFunction::Max) + && args.iter().all(|a| self.kind(*a) == Kind::Date); + if !dates { + for a in &args { + self.require(*a, |k| matches!(k, Kind::Num(_)), "aggregate item")?; + } + } + match f { + InternalFunction::Min | InternalFunction::Max => { + let first = self.kind(args[0]); + let kind = match args.iter().all(|a| self.kind(*a) == first) { + true => first, + false => Kind::Num(None), + }; + let func = if *f == InternalFunction::Min { + Func::Min + } else { + Func::Max + }; + self.math(func, args, Ty::new(kind, false)) + } + _ => { + let zero = self.konst(Lit::Num(Dec::ZERO)); + let mut acc = zero; + for a in &args { + acc = self.arith(Arith::Add, acc, *a)?; + } + match f { + InternalFunction::Sum => Ok(acc), + _ => { + let count = self.konst(Lit::Num(Dec::int(args.len() as i64))); + self.arith(Arith::Div, acc, count) + } + } + } + } + } + ( + FunctionKind::Closure( + c @ (ClosureFunction::Some + | ClosureFunction::All + | ClosureFunction::None + | ClosureFunction::One), + ), + [source, body], + ) => { + let seq = Self::pure(self.seq(source, ctx, r)?)?; + let test = self.predicate(seq, body, ctx, r)?; + let fold = match c { + ClosureFunction::Some => Fold::Any, + ClosureFunction::All => Fold::All, + ClosureFunction::None => Fold::None, + _ => Fold::One, + }; + self.fold(fold, seq, seq.keep, Some(test)) + } + (FunctionKind::Internal(InternalFunction::Date), args) => self.construct(args, ctx, r), + (FunctionKind::Deprecated(f), args) => self.legacy(*f, args, ctx, r), + (kind, _) => Err(Unsupported::new(format!("function {kind:?}"))), + } + } + + fn literals_of( + &mut self, + items: &[&Ast], + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Result, Unsupported> { + let mut out = Vec::with_capacity(items.len()); + for item in items { + let id = self.expr(item, ctx, r)?; + match self.lit(id) { + Some(Lit::Num(_) | Lit::Bool(_) | Lit::Text(_) | Lit::Null) => out.push(id), + _ => return Err(Unsupported::new("list literal: non-literal item")), + } + } + Ok(out) + } + + fn chain(&mut self, and: bool, tests: Vec) -> Lowered { + let mut tests = tests.into_iter(); + let Some(mut acc) = tests.next() else { + return Ok(self.konst(Lit::Bool(and))); + }; + for test in tests { + acc = self.logic(and, acc, test)?; + } + Ok(acc) + } + + fn direct(&self, id: NodeId) -> bool { + matches!(self.nodes[id as usize].op, Op::Column(_) | Op::Field(..)) + } + + fn texty(&self, id: NodeId) -> bool { + match self.kind(id) { + Kind::Text => true, + Kind::Code(d) => self.schema.dicts[d as usize].kind == DictKind::Literals, + _ => false, + } + } + + fn decode(&mut self, id: NodeId) -> Lowered { + let Kind::Code(d) = self.kind(id) else { + return Err(Unsupported::new(format!("decode of {}", self.ty(id)))); + }; + let dict = &self.schema.dicts[d as usize]; + if dict.kind != DictKind::Literals { + return Err(Unsupported::new("dictionary mixing")); + } + if let Some(Lit::Code(_, c)) = self.lit(id) { + let text = dict + .text(*c) + .ok_or_else(|| Unsupported::new("decode of an unknown code"))? + .to_string(); + return Ok(self.konst(Lit::Text(text))); + } + let node = &self.nodes[id as usize]; + let (nullable, scope) = (node.ty.nullable, node.scope); + Ok(self.add(Op::Decode(id), Ty::new(Kind::Text, nullable), scope)) + } + + fn textual(&mut self, id: NodeId) -> Lowered { + match self.kind(id) { + Kind::Text => Ok(id), + Kind::Code(_) => self.decode(id), + _ => Err(Unsupported::new(format!( + "string function on {}", + self.ty(id) + ))), + } + } + + fn stringify(&mut self, a: NodeId) -> Lowered { + let text = match self.lit(a) { + Some(Lit::Text(_)) => return Ok(a), + Some(Lit::Null) => Some("null".to_string()), + Some(Lit::Bool(b)) => Some(b.to_string()), + Some(Lit::Num(d)) => Some(d.decimal().to_string()), + Some(Lit::Code(..)) => return self.decode(a), + Some(Lit::Date(d)) => Some(d.to_string()), + None => None, + }; + if let Some(text) = text { + return Ok(self.konst(Lit::Text(text))); + } + let a = match self.ty(a) { + Ty { + kind: Kind::Text, + nullable: false, + } => return Ok(a), + Ty { + kind: Kind::Code(_), + .. + } => self.decode(a)?, + Ty { + kind: Kind::Text | Kind::Num(_) | Kind::Bool | Kind::Null | Kind::Date, + .. + } => a, + }; + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::Str(a), Ty::new(Kind::Text, false), scope)) + } + + fn concat(&mut self, ids: Vec) -> Lowered { + let mut parts: Vec = Vec::with_capacity(ids.len()); + for id in ids { + let id = self.textual(id)?; + let nested = match &self.nodes[id as usize].op { + Op::Concat(inner) => inner.clone(), + _ => vec![id], + }; + for part in nested { + let joined = match (parts.last().and_then(|p| self.lit(*p)), self.lit(part)) { + (Some(Lit::Text(x)), Some(Lit::Text(y))) => Some(format!("{x}{y}")), + _ => None, + }; + match joined { + Some(text) => { + parts.pop(); + parts.push(self.konst(Lit::Text(text))); + } + None => parts.push(part), + } + } + } + if let [only] = parts.as_slice() { + if self.lit(*only).is_some() || !self.ty(*only).nullable { + return Ok(*only); + } + } + let (scope, ids) = self.scoped(&parts)?; + Ok(self.add(Op::Concat(ids), Ty::new(Kind::Text, false), scope)) + } + + fn template(&mut self, parts: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + if parts.is_empty() { + return Err(Unsupported::new("empty template")); + } + let mut ids = Vec::with_capacity(parts.len()); + for part in parts { + let id = self.expr(part, ctx, r)?; + ids.push(self.stringify(id)?); + } + self.concat(ids) + } + + fn mapped(&mut self, func: Func, a: NodeId) -> Lowered { + let a = self.textual(a)?; + if let Some(Lit::Text(t)) = self.lit(a) { + let text = match func { + Func::Upper => t.to_uppercase(), + Func::Lower => t.to_lowercase(), + _ => t.trim().to_string(), + }; + return Ok(self.konst(Lit::Text(text))); + } + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::Call(func, vec![a]), Ty::new(Kind::Text, false), scope)) + } + + fn test(&mut self, func: Func, a: NodeId, b: NodeId) -> Lowered { + let failing = |this: &mut Self, x: NodeId| { + let null = func != Func::Matches && this.kind(x) == Kind::Null; + if null { + this.widen(); + } + null + }; + let a = if failing(self, a) { + a + } else { + self.textual(a)? + }; + let b = if failing(self, b) { + b + } else { + self.textual(b)? + }; + if func == Func::Matches { + let Some(Lit::Text(pattern)) = self.lit(b) else { + return Err(Unsupported::new( + "matches: pattern must be a string literal", + )); + }; + Pattern::new(pattern).map_err(|_| Unsupported::new("matches: invalid pattern"))?; + } + if let (Some(Lit::Text(x)), Some(Lit::Text(y))) = (self.lit(a), self.lit(b)) { + let hit = match func { + Func::StartsWith => Some(x.starts_with(y.as_str())), + Func::EndsWith => Some(x.ends_with(y.as_str())), + Func::Contains => Some(x.contains(y.as_str())), + _ => None, + }; + if let Some(hit) = hit { + return Ok(self.konst(Lit::Bool(hit))); + } + } + let (scope, ids) = self.scoped(&[a, b])?; + Ok(self.add(Op::Call(func, ids), Ty::boolean(), scope)) + } + + fn math(&mut self, func: Func, args: Vec, ty: Ty) -> Lowered { + let (scope, ids) = self.scoped(&args)?; + Ok(self.add(Op::Call(func, ids), ty, scope)) + } + + fn closure<'a>(ast: &'a Ast<'a>) -> Result<&'a Ast<'a>, Unsupported> { + match ast { + Ast::Closure { body, alias: None } => Ok(body), + _ => Err(Unsupported::new("expected an unaliased closure")), + } + } + + fn inner(ctx: Ctx, seq: Seq) -> Ctx { + Ctx { + scope: Scope::Elem(seq.list), + pointer: Some(seq.list), + item: seq.value, + dollar: ctx.dollar, + list: ctx.list, + } + } + + fn lifted(&mut self, id: NodeId, list: ListId) -> Lowered { + self.parent(id, Scope::Elem(list)) + } + + fn pure(seq: Seq) -> Result { + match seq.pure { + true => Ok(seq), + false => Err(Unsupported::new("closure over a computed map")), + } + } + + fn item(&mut self, seq: Seq) -> Lowered { + match seq.value { + Some(value) => Ok(value), + None => match self.schema.field(seq.list, "") { + Some(f) => { + let ty = self.schema.lists[seq.list as usize].fields[f as usize].ty; + Ok(self.add(Op::Field(seq.list, f), ty, Scope::Elem(seq.list))) + } + None => Err(Unsupported::new("element of a list of objects")), + }, + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn seq(&mut self, ast: &Ast, ctx: Ctx, r: &mut dyn Resolve) -> Result { + match ast { + Ast::Parenthesized(inner) => self.seq(inner, ctx, r), + Ast::FunctionCall { + kind: FunctionKind::Closure(ClosureFunction::Filter), + arguments: [source, body], + } => { + let seq = Self::pure(self.seq(source, ctx, r)?)?; + let body = Self::closure(body)?; + let test = self.expr(body, Self::inner(ctx, seq), r)?; + self.require(test, |k| k == Kind::Bool, "filter")?; + let test = self.lifted(test, seq.list)?; + let keep = match seq.keep { + None => test, + Some(keep) => self.logic(true, keep, test)?, + }; + Ok(Seq { + keep: Some(keep), + ..seq + }) + } + Ast::FunctionCall { + kind: FunctionKind::Closure(ClosureFunction::Map), + arguments: [source, body], + } => { + let seq = Self::pure(self.seq(source, ctx, r)?)?; + let body = Self::closure(body)?; + let value = self.expr(body, Self::inner(ctx, seq), r)?; + let value = self.lifted(value, seq.list)?; + Ok(Seq { + value: Some(value), + pure: false, + ..seq + }) + } + Ast::Binary { + left, + operator: Operator::Logical(LogicalOperator::NullishCoalescing), + right: Ast::Array([]), + } => { + let seq = self.seq(left, ctx, r)?; + Ok(Seq { empty: true, ..seq }) + } + other => self.source(other, ctx, r), + } + } + + fn plain(list: ListId) -> Seq { + Seq { + list, + keep: None, + value: None, + empty: false, + pure: true, + } + } + + fn produced(&self, at: usize, path: &str) -> Result { + match self.outputs.get(at).and_then(|o| o.collect) { + Some(c) => Ok(Seq { + list: c.list, + keep: c.keep, + value: Some(c.item), + empty: c.empty, + pure: true, + }), + None => Err(Unsupported::new(format!("{path} is not a list"))), + } + } + + fn source(&mut self, ast: &Ast, ctx: Ctx, r: &mut dyn Resolve) -> Result { + let mut segments = Vec::new(); + let base = Self::segments(ast, &mut segments)?; + let rest = segments.join("."); + match base { + Base::Pointer => { + let parent = ctx + .pointer + .ok_or_else(|| Unsupported::new("# outside a closure"))?; + if ctx.item.is_some() || rest.is_empty() { + return Err(Unsupported::new("list of lists")); + } + Ok(Self::plain(self.nested(parent, &rest, r)?)) + } + Base::Dollar if rest.is_empty() && ctx.list.is_some() => { + ctx.list.ok_or_else(|| Unsupported::new("list source $")) + } + Base::Dollar if ctx.dollar.is_some() || rest.is_empty() => { + Err(Unsupported::new("list source $")) + } + Base::Dollar => match self.own(&rest) { + Some(Named::Seq(seq)) => Ok(seq), + _ => Err(Unsupported::new(format!("$.{rest} is not a list"))), + }, + Base::Ident(name) => { + let path = match rest.is_empty() { + true => name.to_string(), + false => format!("{name}.{rest}"), + }; + match self.graph { + true => self.keyed_list(&path, r), + false => self.root_list(name, &rest, &path, r), + } + } + } + } + + fn keyed_list(&mut self, path: &str, r: &mut dyn Resolve) -> Result { + match r.path(path) { + Resolved::KeyedList(key, fields) => { + if let Some(list) = self.schema.list(&key) { + return Ok(Self::plain(list)); + } + Ok(Self::plain(self.declare(key.to_string(), fields, None)?)) + } + Resolved::Output(at) => self.produced(at, path), + _ => Err(Unsupported::new(format!("{path} is not a list"))), + } + } + + fn root_list( + &mut self, + name: &str, + rest: &str, + path: &str, + r: &mut dyn Resolve, + ) -> Result { + self.overlap(path)?; + match self.named(path) { + Some(Named::Seq(seq)) => return Ok(seq), + Some(Named::Node(_)) => return Err(Unsupported::new(format!("{path} is not a list"))), + None => {} + } + if let Some(member) = self.member { + if self.schema.lists[member as usize].alias.as_deref() == Some(name) { + return match rest.is_empty() { + true => Err(Unsupported::new(format!("whole element {name}"))), + false => Ok(Self::plain(self.nested(member, rest, r)?)), + }; + } + } + if let Some(list) = self.schema.list(path) { + return Ok(Self::plain(list)); + } + if self.schema.column(path).is_some() { + return Err(Unsupported::new(format!("{path} is not a list"))); + } + match r.path(path) { + Resolved::List { fields } => { + Ok(Self::plain(self.declare(path.to_string(), fields, None)?)) + } + _ => Err(Unsupported::new(format!("{path} is not a list"))), + } + } + + fn nested( + &mut self, + parent: ListId, + field: &str, + r: &mut dyn Resolve, + ) -> Result { + if let Some(list) = self.schema.nested(parent, field) { + return Ok(list); + } + if self.schema.depth(Scope::Elem(parent)) >= Self::DEPTH { + return Err(Unsupported::new(format!("list {field} nested too deep"))); + } + if self.schema.field(parent, field).is_some() { + return Err(Unsupported::new(format!("{field} is not a list"))); + } + let mut chain = self.schema.chain(parent); + chain.push(field); + match r.nested(&chain) { + Resolved::List { fields } => self.declare(field.to_string(), fields, Some(parent)), + _ => Err(Unsupported::new(format!("nested list {field}"))), + } + } + + fn declare( + &mut self, + path: String, + fields: Vec<(Arc, Class)>, + parent: Option, + ) -> Result { + let l = ListId::try_from(self.schema.lists.len()) + .map_err(|_| Unsupported::new("too many lists"))?; + let fields = fields + .into_iter() + .map(|(name, class)| ColumnDef { + path: name.to_string(), + ty: class.ty(), + }) + .collect(); + self.schema.lists.push(ListDef { + path, + alias: None, + fields, + parent, + }); + Ok(l) + } + + fn predicate(&mut self, seq: Seq, body: &Ast, ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + let test = self.expr(Self::closure(body)?, Self::inner(ctx, seq), r)?; + self.require(test, |k| k == Kind::Bool, "predicate")?; + self.lifted(test, seq.list) + } + + fn member(&mut self, x: NodeId, seq: Seq) -> Lowered { + let seq = Self::pure(seq)?; + let item = self.item(seq)?; + let test = self.belongs(x, item)?; + let test = self.lifted(test, seq.list)?; + self.fold(Fold::Any, seq, seq.keep, Some(test)) + } + + fn fold( + &mut self, + fold: Fold, + seq: Seq, + filter: Option, + value: Option, + ) -> Lowered { + let list = seq.list; + let filter = filter.map(|f| self.lifted(f, list)).transpose()?; + let value = match value { + Some(id) => { + match (fold.quantifier(), fold) { + (true, _) => self.require(id, |k| k == Kind::Bool, "predicate")?, + (false, Fold::Min | Fold::Max) => { + self.require(id, |k| matches!(k, Kind::Num(_) | Kind::Date), "fold value")? + } + (false, _) => self.require(id, |k| matches!(k, Kind::Num(_)), "fold value")?, + } + Some(self.lifted(id, list)?) + } + None => None, + }; + let ty = match (fold, value) { + (Fold::Sum, Some(v)) => Ty::num((self.kind(v) == Kind::Num(Some(0))).then_some(0)), + (Fold::Min | Fold::Max, Some(v)) => Ty::new(self.kind(v), false), + (Fold::Avg, _) => Ty::num(None), + (Fold::Any | Fold::All | Fold::None | Fold::One, _) => Ty::boolean(), + _ => Ty::num(Some(0)), + }; + let scope = self + .schema + .owner(Scope::Elem(list)) + .ok_or_else(|| Unsupported::new("fold owner"))?; + Ok(self.add( + Op::Fold { + fold, + list, + filter, + value, + empty: seq.empty, + }, + ty, + scope, + )) + } +} + +impl Lowering { + fn returns(method: DateMethod) -> Ty { + match method { + DateMethod::Add + | DateMethod::Sub + | DateMethod::Set + | DateMethod::StartOf + | DateMethod::EndOf + | DateMethod::Tz => Ty::new(Kind::Date, false), + DateMethod::Format => Ty::new(Kind::Text, false), + DateMethod::OffsetName => Ty::new(Kind::Text, true), + DateMethod::IsSame + | DateMethod::IsBefore + | DateMethod::IsAfter + | DateMethod::IsSameOrBefore + | DateMethod::IsSameOrAfter + | DateMethod::IsValid => Ty::boolean(), + DateMethod::IsYesterday + | DateMethod::IsToday + | DateMethod::IsTomorrow + | DateMethod::IsLeapYear => Ty::new(Kind::Bool, true), + DateMethod::Diff + | DateMethod::Second + | DateMethod::Minute + | DateMethod::Hour + | DateMethod::Day + | DateMethod::DayOfYear + | DateMethod::Week + | DateMethod::Weekday + | DateMethod::Month + | DateMethod::Quarter + | DateMethod::Year + | DateMethod::Timestamp => Ty::new(Kind::Num(Some(0)), true), + } + } + + fn arity(def: &dyn FunctionDefinition, skip: usize, given: usize) -> Result<(), Unsupported> { + let least = def.required_parameters().saturating_sub(skip); + match (least..=least + def.optional_parameters()).contains(&given) { + true => Ok(()), + false => Err(Unsupported::new("call arity")), + } + } + + fn loose(&mut self, id: NodeId) -> Lowered { + match self.kind(id) { + Kind::Code(_) => self.decode(id), + _ => Ok(id), + } + } + + fn arguments( + &mut self, + arguments: &[&Ast], + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Result, Unsupported> { + let mut args = Vec::with_capacity(arguments.len()); + for a in arguments { + let id = self.expr(a, ctx, r)?; + args.push(self.loose(id)?); + } + Ok(args) + } + + fn method( + &mut self, + method: DateMethod, + this: &Ast, + arguments: &[&Ast], + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { + let def = MethodRegistry::get_definition(&MethodKind::DateMethod(method)) + .ok_or_else(|| Unsupported::new(format!("method {method}")))?; + Self::arity(def.as_ref(), 1, arguments.len())?; + let this = self.expr(this, ctx, r)?; + self.require(this, |k| k == Kind::Date, "method receiver")?; + let mut args = vec![this]; + args.extend(self.arguments(arguments, ctx, r)?); + if method == DateMethod::Format { + match args.get(1).map(|a| self.lit(*a)) { + None => {} + Some(Some(Lit::Text(pattern))) if Effect::formats(pattern) => {} + _ => return Err(Unsupported::new("format pattern")), + } + } + let pure = Effect::method(&MethodKind::DateMethod(method)) == Effect::Pure; + self.host(Host::Method(method), args, Self::returns(method), pure) + } + + fn construct(&mut self, arguments: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + let def = FunctionRegistry::get_definition(&FunctionKind::Internal(InternalFunction::Date)) + .ok_or_else(|| Unsupported::new("function d"))?; + Self::arity(def.as_ref(), 0, arguments.len())?; + if arguments.is_empty() { + return Ok(self.add( + Op::Clock(Clock::Now, Vec::new()), + Ty::new(Kind::Date, false), + ctx.scope, + )); + } + let args = self.arguments(arguments, ctx, r)?; + if let [only] = args.as_slice() { + if self.kind(*only) == Kind::Date { + return Ok(*only); + } + } + let pure = + self.effect(&FunctionKind::Internal(InternalFunction::Date), &args) == Effect::Pure; + self.host(Host::Construct, args, Ty::new(Kind::Date, false), pure) + } + + fn legacy( + &mut self, + function: DeprecatedFunction, + arguments: &[&Ast], + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { + let def = FunctionRegistry::get_definition(&FunctionKind::Deprecated(function)) + .ok_or_else(|| Unsupported::new(format!("function {function}")))?; + Self::arity(def.as_ref(), 0, arguments.len())?; + let args = self.arguments(arguments, ctx, r)?; + let ty = match function { + DeprecatedFunction::MonthString + | DeprecatedFunction::DateString + | DeprecatedFunction::WeekdayString => Ty::new(Kind::Text, true), + _ => Ty::new(Kind::Num(None), true), + }; + let pure = self.effect(&FunctionKind::Deprecated(function), &args) == Effect::Pure; + self.host(Host::Legacy(function), args, ty, pure) + } + + fn effect(&self, kind: &FunctionKind, args: &[NodeId]) -> Effect { + let literals = args.iter().map(|a| match self.lit(*a) { + Some(Lit::Text(text)) => Literal::Text(text), + Some(_) => Literal::Constant, + None => Literal::Computed, + }); + Effect::call(kind, literals) + } + + fn host(&mut self, host: Host, args: Vec, ty: Ty, pure: bool) -> Lowered { + if let Some(lit) = pure.then(|| self.folded(host, &args)).flatten() { + return Ok(self.konst(lit)); + } + let (scope, ids) = self.scoped(&args)?; + Ok(self.add(Op::Host(host, ids), ty, scope)) + } + + fn folded(&self, host: Host, args: &[NodeId]) -> Option { + let lits = args + .iter() + .map(|a| self.lit(*a)) + .collect::>>()?; + let given = lits + .iter() + .map(|lit| match lit { + Lit::Null => Some(Given::Null), + Lit::Num(d) => Some(Given::Num(d.decimal())), + Lit::Bool(b) => Some(Given::Bool(*b)), + Lit::Text(t) => Some(Given::Str(t.as_str())), + Lit::Date(d) => Some(Given::Date(d.date())), + Lit::Code(..) => None, + }) + .collect::>>()?; + match Builtins::raw(host.builtin()?, &given).ok()? { + Out::Num(n) => Dec::from_decimal(&n).map(Lit::Num), + Out::Bool(b) => Some(Lit::Bool(b)), + Out::Str(s) => Some(Lit::Text(s.to_string())), + Out::Date(d) => Some(Lit::Date(Stamp::of(d))), + Out::Var(Variable::Null) => Some(Lit::Null), + Out::Var(_) => None, + } + } + + fn rendered(&mut self, id: NodeId) -> Lowered { + if self.kind(id) != Kind::Date { + return Ok(id); + } + if let Some(Lit::Date(d)) = self.lit(id) { + if d.is_valid() { + let text = d.to_string(); + return Ok(self.konst(Lit::Text(text))); + } + } + let node = &self.nodes[id as usize]; + let (nullable, scope) = (node.ty.nullable, node.scope); + Ok(self.add( + Op::Clock(Clock::Text, vec![id]), + Ty::new(Kind::Text, nullable), + scope, + )) + } + + fn strict(&mut self, id: NodeId) -> NodeId { + if let Some(Lit::Date(d)) = self.lit(id) { + if d.is_valid() { + return id; + } + } + let scope = self.nodes[id as usize].scope; + self.add( + Op::Clock(Clock::Strict, vec![id]), + Ty::new(Kind::Date, false), + scope, + ) + } + + fn coerced(&mut self, id: NodeId) -> NodeId { + if let Some(Lit::Text(text)) = self.lit(id) { + let date = Date::from_text(text); + if date.is_valid() { + return self.konst(Lit::Date(Stamp::of(date))); + } + } + let scope = self.nodes[id as usize].scope; + self.add( + Op::Clock(Clock::Coerce, vec![id]), + Ty::new(Kind::Date, false), + scope, + ) + } + + fn dated(&mut self, op: Cmp, a: NodeId, b: NodeId) -> Lowered { + let (a, b) = (self.loose(a)?, self.loose(b)?); + let eq = matches!(op, Cmp::Eq | Cmp::Ne); + match (self.kind(a), self.kind(b)) { + (Kind::Date, Kind::Date) | (Kind::Date, Kind::Null) | (Kind::Null, Kind::Date) => { + let (scope, ids) = self.scoped(&[a, b])?; + Ok(self.add(Op::Cmp(op, ids[0], ids[1]), Ty::boolean(), scope)) + } + (Kind::Date, Kind::Text) | (Kind::Text, Kind::Date) => { + let flip = self.kind(a) == Kind::Text; + let (date, text) = if flip { (b, a) } else { (a, b) }; + if !eq { + let (x, y) = (self.strict(date), self.coerced(text)); + let (x, y) = if flip { (y, x) } else { (x, y) }; + let (scope, ids) = self.scoped(&[x, y])?; + return Ok(self.add(Op::Cmp(op, ids[0], ids[1]), Ty::boolean(), scope)); + } + let hit = match self.lit(text) { + Some(Lit::Text(t)) => { + let parsed = Date::from_text(t); + match parsed.is_valid() { + true => { + let other = self.konst(Lit::Date(Stamp::of(parsed))); + self.dated(Cmp::Eq, date, other)? + } + false => self.konst(Lit::Bool(false)), + } + } + _ => { + let (scope, ids) = self.scoped(&[date, text])?; + self.add(Op::Clock(Clock::Matches, ids), Ty::boolean(), scope) + } + }; + match op { + Cmp::Eq => Ok(hit), + _ => self.not(hit), + } + } + (x, y) + if eq + && Self::family(x) + .zip(Self::family(y)) + .is_some_and(|(p, q)| p != q) => + { + self.mismatch(op, a, b) + } + (x, y) => Err(Unsupported::new(format!( + "compare {op:?} between {x} and {y}" + ))), + } + } + + fn belongs(&mut self, x: NodeId, item: NodeId) -> Lowered { + let (x, item) = (self.loose(x)?, self.loose(item)?); + let (date, other) = match (self.kind(x), self.kind(item)) { + (Kind::Date, Kind::Date | Kind::Text) => (x, item), + (Kind::Text, Kind::Date) => (item, x), + _ => return self.compare(Cmp::Eq, x, item), + }; + let (scope, ids) = self.scoped(&[date, other])?; + let hit = self.add(Op::Clock(Clock::Matches, ids), Ty::boolean(), scope); + if !(self.ty(x).nullable && self.ty(item).nullable) { + return Ok(hit); + } + let null = self.konst(Lit::Null); + let (p, q) = ( + self.compare(Cmp::Eq, x, null)?, + self.compare(Cmp::Eq, item, null)?, + ); + let both = self.logic(true, p, q)?; + self.logic(false, both, hit) + } + + fn dates_in(&mut self, a: NodeId, items: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + let mut set: Vec = Vec::new(); + for item in items { + let id = self.expr(item, ctx, r)?; + let lit = match self + .lit(id) + .cloned() + .ok_or_else(|| Unsupported::new("in: non-literal set item"))? + { + Lit::Null => Some(Lit::Null), + Lit::Date(d) => d.is_valid().then_some(Lit::Date(d)), + Lit::Text(t) => { + let date = Date::from_text(&t); + date.is_valid().then(|| Lit::Date(Stamp::of(date))) + } + _ => None, + }; + if let Some(lit) = lit { + if !set.contains(&lit) { + set.push(lit); + } + } + } + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::InSet(a, set), Ty::boolean(), scope)) + } + + fn date_range( + &mut self, + a: NodeId, + (lo, hi): (&Ast, &Ast), + (left, right): (Bracket, Bracket), + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { + let lo = self.expr(lo, ctx, r)?; + let hi = self.expr(hi, ctx, r)?; + for bound in [lo, hi] { + if self.ty(bound) != Ty::new(Kind::Date, false) { + return Err(Unsupported::new("interval bounds must be dates")); + } + } + let low = match left { + Bracket::LeftSquareBracket => Cmp::Le, + Bracket::LeftParenthesis => Cmp::Lt, + other => return Err(Unsupported::new(format!("interval bracket {other}"))), + }; + let high = match right { + Bracket::RightSquareBracket => Cmp::Le, + Bracket::RightParenthesis => Cmp::Lt, + other => return Err(Unsupported::new(format!("interval bracket {other}"))), + }; + let first = self.dated(low, lo, a)?; + let second = self.dated(high, a, hi)?; + self.logic(true, first, second) + } +} diff --git a/core/expression/src/typed/mod.rs b/core/expression/src/typed/mod.rs new file mode 100644 index 00000000..c08d8dbc --- /dev/null +++ b/core/expression/src/typed/mod.rs @@ -0,0 +1,26 @@ +mod batch; +mod build; +mod date; +mod exec; +mod hir; +mod ins; +mod kernel; +mod lookup; +mod lower; +mod num; +mod output; +mod program; +#[cfg(test)] +mod tests; +mod text; + +pub use batch::{Batch, List}; +pub use hir::{ + Arith, Clock, Cmp, Collect, ColumnDef, Dict, DictId, DictKind, FieldId, Fold, Func, Hir, Host, + Kind, ListDef, ListId, Lit, Node, NodeId, Op, Output, Range, Schema, Scope, Stamp, Ty, + Unsupported, +}; +pub use lower::{Class, Hit, Lowering, Resolve, Resolved, TableRule, TableSpec}; +pub use num::{Dec, Fault}; +pub use output::{Data, Faults, Outputs, Slot}; +pub use program::Program; diff --git a/core/expression/src/typed/num.rs b/core/expression/src/typed/num.rs new file mode 100644 index 00000000..3e609e89 --- /dev/null +++ b/core/expression/src/typed/num.rs @@ -0,0 +1,267 @@ +use crate::lane::scaled::Scaled; +use crate::typed::hir::{Arith, Func}; +use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; +use rust_decimal::{Decimal, MathematicalOps, RoundingStrategy}; +use std::cmp::Ordering; +use std::fmt; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Dec { + pub mant: i64, + pub scale: u8, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Fault; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum N { + Dec(Dec), + Big(Decimal), +} + +pub(crate) struct Exact; + +impl Dec { + pub const MAX_SCALE: u8 = 28; + pub const ZERO: Dec = Dec { mant: 0, scale: 0 }; + pub const POW10: [i64; 19] = Scaled::POW10; + + #[inline] + pub const fn new(mant: i64, scale: u8) -> Self { + Self { mant, scale } + } + + #[inline] + pub const fn int(mant: i64) -> Self { + Self { mant, scale: 0 } + } + + #[inline] + pub fn is_zero(self) -> bool { + self.mant == 0 + } + + #[inline] + fn parts(self) -> (i64, u8) { + (self.mant, self.scale) + } + + #[inline] + fn of(parts: (i64, u8)) -> Self { + Self::new(parts.0, parts.1) + } + + #[inline] + pub fn checked_add(self, rhs: Self) -> Result { + Scaled::add(self.parts(), rhs.parts(), false) + .map(Self::of) + .ok_or(Fault) + } + + #[inline] + pub fn checked_sub(self, rhs: Self) -> Result { + Scaled::add(self.parts(), rhs.parts(), true) + .map(Self::of) + .ok_or(Fault) + } + + #[inline] + pub fn checked_mul(self, rhs: Self) -> Result { + Scaled::multiply(self.parts(), rhs.parts()) + .map(Self::of) + .ok_or(Fault) + } + + #[inline] + pub fn checked_neg(self) -> Result { + match self.mant { + 0 => Err(Fault), + m => m + .checked_neg() + .map(|m| Self::new(m, self.scale)) + .ok_or(Fault), + } + } + + #[inline] + pub fn checked_div(self, rhs: Self) -> Result, Fault> { + if rhs.mant == 0 { + return Ok(None); + } + let q = match Scaled::power(rhs.parts()) { + Some(k) => Scaled::divide_power(self.parts(), k, rhs.scale), + None => Scaled::divide(self.parts(), rhs.parts()), + }; + q.map(|q| Some(Self::of(q))).ok_or(Fault) + } + + #[inline] + pub fn checked_rem(self, rhs: Self) -> Result, Fault> { + if rhs.mant == 0 { + return Ok(None); + } + Scaled::remainder(self.parts(), rhs.parts()) + .map(|r| Some(Self::of(r))) + .ok_or(Fault) + } + + #[inline] + pub(crate) fn func(self, func: Func) -> Option { + let (m, s) = self.parts(); + match func { + Func::Abs => Scaled::abs(m, s), + Func::Floor => Scaled::floor(m, s), + Func::Ceil => Scaled::ceil(m, s), + Func::Round(p) => Scaled::round(m, s, p), + Func::Trunc(p) => Scaled::trunc(m, s, p), + _ => None, + } + .map(Self::of) + } + + #[inline] + pub(crate) fn arith(self, op: Arith, rhs: Self) -> Result, Fault> { + match op { + Arith::Add => self.checked_add(rhs).map(Some), + Arith::Sub => self.checked_sub(rhs).map(Some), + Arith::Mul => self.checked_mul(rhs).map(Some), + Arith::Div => self.checked_div(rhs), + Arith::Rem => self.checked_rem(rhs), + Arith::Pow => Err(Fault), + } + } + + #[inline] + pub fn div_power(self, k: u32, scale: u8) -> Result { + Scaled::divide_power(self.parts(), k, scale) + .map(Self::of) + .ok_or(Fault) + } + + pub fn power(self) -> Option { + Scaled::power(self.parts()) + } + + #[inline] + pub fn compare(self, rhs: Self) -> Ordering { + match Scaled::compare(self.parts(), rhs.parts()) { + Some(o) => o, + None => self.decimal().cmp(&rhs.decimal()), + } + } + + #[inline] + pub fn eq_value(self, rhs: Self) -> bool { + self.compare(rhs) == Ordering::Equal + } + + pub fn upscale(self, scale: u8) -> Option { + (scale >= self.scale).then_some(())?; + Scaled::rescale(self.mant, self.scale, scale).map(|m| Self::new(m, scale)) + } + + pub fn decimal(self) -> Decimal { + Scaled::decimal(self.mant, self.scale) + } + + pub fn from_decimal(d: &Decimal) -> Option { + Scaled::parts(d) + .filter(|(_, s)| *s <= Self::MAX_SCALE) + .map(Self::of) + } +} + +impl Exact { + pub(crate) fn arith(op: Arith, x: Decimal, y: Decimal) -> Result, Fault> { + match op { + Arith::Add => x.checked_add(y).map(Some).ok_or(Fault), + Arith::Sub => x.checked_sub(y).map(Some).ok_or(Fault), + Arith::Mul => x.checked_mul(y).map(Some).ok_or(Fault), + Arith::Div => Ok(x.checked_div(y)), + Arith::Rem => Ok(x.checked_rem(y)), + Arith::Pow => x + .checked_powd(y) + .or_else(|| Decimal::from_f64(x.to_f64()?.powf(y.to_f64()?))) + .map(Some) + .ok_or(Fault), + } + } + + pub(crate) fn func(func: Func, x: Decimal) -> Decimal { + match func { + Func::Abs => x.abs(), + Func::Floor => x.floor(), + Func::Ceil => x.ceil(), + Func::Round(p) => { + x.round_dp_with_strategy(u32::from(p), RoundingStrategy::MidpointAwayFromZero) + } + Func::Trunc(p) => x.trunc_with_scale(u32::from(p)), + _ => x, + } + } +} + +impl N { + #[inline] + pub(crate) fn decimal(self) -> Decimal { + match self { + N::Dec(d) => d.decimal(), + N::Big(d) => d, + } + } + + #[inline] + pub(crate) fn of(d: Decimal) -> N { + match Dec::from_decimal(&d) { + Some(n) => N::Dec(n), + None => N::Big(d), + } + } + + #[inline] + pub(crate) fn compare(self, rhs: N) -> Ordering { + match (self, rhs) { + (N::Dec(x), N::Dec(y)) => x.compare(y), + (x, y) => x.decimal().cmp(&y.decimal()), + } + } + + #[inline] + pub(crate) fn arith(self, op: Arith, rhs: N) -> Result, Fault> { + if let (N::Dec(x), N::Dec(y)) = (self, rhs) { + if let Ok(r) = x.arith(op, y) { + return Ok(r.map(N::Dec)); + } + } + Exact::arith(op, self.decimal(), rhs.decimal()).map(|r| r.map(N::of)) + } + + #[inline] + pub(crate) fn func(self, func: Func) -> N { + match self { + N::Dec(d) => match d.func(func) { + Some(r) => N::Dec(r), + None => N::of(Exact::func(func, d.decimal())), + }, + N::Big(d) => N::of(Exact::func(func, d)), + } + } + + #[inline] + pub(crate) fn neg(self) -> N { + match self { + N::Dec(d) => match d.checked_neg() { + Ok(r) => N::Dec(r), + Err(_) => N::of(-d.decimal()), + }, + N::Big(d) => N::of(-d), + } + } +} + +impl fmt::Display for Dec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.decimal()) + } +} diff --git a/core/expression/src/typed/output.rs b/core/expression/src/typed/output.rs new file mode 100644 index 00000000..940aeda0 --- /dev/null +++ b/core/expression/src/typed/output.rs @@ -0,0 +1,674 @@ +use crate::lane::date::Date; +use crate::lane::Bits; +use crate::typed::batch::Feeds; +use crate::typed::hir::{DictId, Hir, Kind, Scope, Unsupported}; +use crate::typed::kernel::K; +use crate::typed::num::Dec; +use crate::variable::Variable; +use chrono::DateTime; +use chrono_tz::Tz; +use rust_decimal::Decimal; + +#[derive(Clone, Debug)] +pub enum Data { + Num { + mant: Vec, + scale: Vec, + }, + Bool(Vec), + Code(Vec), + Text { + span: Vec<(u32, u32)>, + data: Vec, + }, + Date(Vec>>), +} + +#[derive(Clone, Debug)] +pub struct Slot { + pub name: String, + pub scope: Scope, + pub kind: Kind, + pub len: usize, + pub data: Data, + pub valid: Vec, + pub fault: Faults, + pub wide: Vec<(usize, Decimal)>, + pub offsets: Option>, + pub(crate) keep: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct Faults { + bits: Vec, + rows: usize, + any: bool, +} + +#[derive(Clone, Debug)] +pub struct Outputs { + rows: usize, + slots: Vec, + faults: Faults, +} + +impl Slot { + pub fn dict(&self) -> Option { + match self.kind { + Kind::Code(d) => Some(d), + _ => None, + } + } + + #[inline] + pub fn is_valid(&self, i: usize) -> bool { + Bits::get(&self.valid, i) + } + + pub fn num(&self, i: usize) -> Option { + match &self.data { + Data::Num { mant, scale } + if self.is_valid(i) + && self.wide.binary_search_by_key(&i, |(at, _)| *at).is_err() => + { + Some(Dec::new(*mant.get(i)?, *scale.get(i)?)) + } + _ => None, + } + } + + pub fn decimal(&self, i: usize) -> Option { + match self.wide.binary_search_by_key(&i, |(at, _)| *at) { + Ok(at) if self.is_valid(i) => self.wide.get(at).map(|(_, d)| *d), + Ok(_) => None, + Err(_) => match &self.data { + Data::Num { mant, scale } if self.is_valid(i) => { + Some(Dec::new(*mant.get(i)?, *scale.get(i)?).decimal()) + } + _ => None, + }, + } + } + + pub fn boolean(&self, i: usize) -> Option { + match &self.data { + Data::Bool(bits) if self.is_valid(i) => Some(Bits::get(bits, i)), + _ => None, + } + } + + pub fn code(&self, i: usize) -> Option { + match &self.data { + Data::Code(codes) if self.is_valid(i) => codes.get(i).copied(), + _ => None, + } + } + + pub fn text(&self, i: usize) -> Option<&str> { + match &self.data { + Data::Text { span, data } if self.is_valid(i) => { + let (lo, hi) = *span.get(i)?; + std::str::from_utf8(data.get(lo as usize..hi as usize)?).ok() + } + _ => None, + } + } + + pub fn date(&self, i: usize) -> Option>> { + match &self.data { + Data::Date(dates) if self.is_valid(i) => dates.get(i).copied(), + _ => None, + } + } + + pub fn variable(&self, i: usize) -> Variable { + match self.date(i) { + Some(date) => Date(date).variable(), + None => Variable::Null, + } + } + + pub fn take_text(&mut self) -> Option<(Vec, String, Vec)> { + let Data::Text { span, data } = &mut self.data else { + return None; + }; + let (span, data) = (std::mem::take(span), std::mem::take(data)); + let len = self.len.min(span.len()); + let mut offsets = Vec::with_capacity(len + 1); + offsets.push(0i32); + let packed = span[..len] + .iter() + .try_fold(0u32, |end, (lo, hi)| (end == *lo).then_some(*hi)); + let bytes = match packed { + Some(end) => { + let mut data = data; + data.truncate(end as usize); + offsets.extend( + span[..len] + .iter() + .map(|(_, hi)| i32::try_from(*hi).unwrap_or(i32::MAX)), + ); + data + } + None => { + let mut packed = Vec::with_capacity(data.len()); + for (at, (lo, hi)) in span[..len].iter().enumerate() { + if Bits::get(&self.valid, at) { + packed.extend_from_slice( + data.get(*lo as usize..*hi as usize).unwrap_or_default(), + ); + } + offsets.push(i32::try_from(packed.len()).unwrap_or(i32::MAX)); + } + packed + } + }; + let text = String::from_utf8(bytes) + .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()); + Some((offsets, text, std::mem::take(&mut self.valid))) + } + + pub fn take_num(&mut self) -> Option<(Vec, Vec, Vec)> { + match &mut self.data { + Data::Num { mant, scale } => Some(( + std::mem::take(mant), + std::mem::take(scale), + std::mem::take(&mut self.valid), + )), + _ => None, + } + } + + pub fn take_bool(&mut self) -> Option<(Vec, Vec)> { + match &mut self.data { + Data::Bool(bits) => Some((std::mem::take(bits), std::mem::take(&mut self.valid))), + _ => None, + } + } + + pub fn take_code(&mut self) -> Option<(Vec, Vec)> { + match &mut self.data { + Data::Code(codes) => Some((std::mem::take(codes), std::mem::take(&mut self.valid))), + _ => None, + } + } + + fn spread(&mut self, sources: &[u32]) { + let rows = sources.len(); + let pick = |id: u32| (id != u32::MAX).then_some(id as usize); + let mut valid = vec![0u64; K::words(rows)]; + for (row, &id) in sources.iter().enumerate() { + if pick(id).is_some_and(|at| Bits::get(&self.valid, at)) { + Bits::set(&mut valid, row, true); + } + } + self.data = match std::mem::replace(&mut self.data, Data::Bool(Vec::new())) { + Data::Num { mant, scale } => Data::Num { + mant: sources + .iter() + .map(|&id| pick(id).and_then(|at| mant.get(at).copied()).unwrap_or(0)) + .collect(), + scale: sources + .iter() + .map(|&id| pick(id).and_then(|at| scale.get(at).copied()).unwrap_or(0)) + .collect(), + }, + Data::Bool(bits) => { + let mut out = vec![0u64; K::words(rows)]; + for (row, &id) in sources.iter().enumerate() { + if pick(id).is_some_and(|at| Bits::get(&bits, at)) { + Bits::set(&mut out, row, true); + } + } + Data::Bool(out) + } + Data::Code(codes) => Data::Code( + sources + .iter() + .map(|&id| pick(id).and_then(|at| codes.get(at).copied()).unwrap_or(0)) + .collect(), + ), + Data::Text { span, data } => Data::Text { + span: sources + .iter() + .map(|&id| { + pick(id) + .and_then(|at| span.get(at).copied()) + .unwrap_or((0, 0)) + }) + .collect(), + data, + }, + Data::Date(dates) => Data::Date( + sources + .iter() + .map(|&id| pick(id).and_then(|at| dates.get(at).copied().flatten())) + .collect(), + ), + }; + if !self.wide.is_empty() { + let wide = std::mem::take(&mut self.wide); + self.wide = sources + .iter() + .enumerate() + .filter_map(|(row, &id)| { + let at = pick(id)?; + let found = wide.binary_search_by_key(&at, |(at, _)| *at).ok()?; + wide.get(found).map(|(_, d)| (row, *d)) + }) + .collect(); + } + self.valid = valid; + self.fault = self.fault.spread(sources); + self.len = rows; + } + + fn reset(&mut self, len: usize) { + self.len = len; + self.wide.clear(); + let words = K::words(len); + if let Some(offsets) = &mut self.offsets { + offsets.clear(); + self.keep.clear(); + self.keep.resize(words, u64::MAX); + } + self.valid.clear(); + self.valid.resize(words, u64::MAX); + match &mut self.data { + Data::Num { mant, scale } => { + mant.clear(); + mant.resize(len, 0); + scale.clear(); + scale.resize(len, 0); + } + Data::Bool(bits) => { + bits.clear(); + bits.resize(words, 0); + } + Data::Code(codes) => { + codes.clear(); + codes.resize(len, 0); + } + Data::Text { span, data } => { + span.clear(); + span.resize(len, (0, 0)); + data.clear(); + } + Data::Date(dates) => { + dates.clear(); + dates.resize(len, None); + } + } + } +} + +impl Faults { + fn spread(&self, sources: &[u32]) -> Self { + let mut bits = vec![0u64; K::words(sources.len())]; + let mut any = false; + if self.any { + for (row, &id) in sources.iter().enumerate() { + if id != u32::MAX && Bits::get(&self.bits, id as usize) { + Bits::set(&mut bits, row, true); + any = true; + } + } + } + Self { + bits, + rows: sources.len(), + any, + } + } + + pub(crate) fn reset(&mut self, rows: usize) { + self.bits.clear(); + self.bits.resize(K::words(rows), 0); + self.rows = rows; + self.any = false; + } + + #[inline] + pub(crate) fn set(&mut self, row: usize) { + self.any = true; + Bits::set(&mut self.bits, row, true); + } + + #[inline] + pub fn get(&self, row: usize) -> bool { + Bits::get(&self.bits, row) + } + + #[inline] + pub fn any(&self) -> bool { + self.any + } + + pub fn words(&self) -> &[u64] { + &self.bits + } + + pub fn count(&self) -> usize { + self.bits.iter().map(|w| w.count_ones() as usize).sum() + } + + pub fn iter(&self) -> impl Iterator + '_ { + let rows = self.rows; + Bits::rows(&self.bits).filter(move |r| *r < rows) + } +} + +impl Outputs { + pub(crate) fn new(hir: &Hir) -> Result { + let mut slots = Vec::with_capacity(hir.outputs.len()); + for o in &hir.outputs { + let data = match o.ty.kind { + Kind::Num(_) | Kind::Null => Data::Num { + mant: Vec::new(), + scale: Vec::new(), + }, + Kind::Bool => Data::Bool(Vec::new()), + Kind::Code(_) => Data::Code(Vec::new()), + Kind::Text => Data::Text { + span: Vec::new(), + data: Vec::new(), + }, + Kind::Date => Data::Date(Vec::new()), + }; + slots.push(Slot { + name: o.name.clone(), + scope: o.scope, + kind: o.ty.kind, + len: 0, + data, + valid: Vec::new(), + fault: Faults::default(), + wide: Vec::new(), + offsets: o.collect.map(|_| Vec::new()), + keep: Vec::new(), + }); + } + Ok(Self { + rows: 0, + slots, + faults: Faults::default(), + }) + } + + pub(crate) fn empty() -> Self { + Self { + rows: 0, + slots: Vec::new(), + faults: Faults::default(), + } + } + + pub(crate) fn reset(&mut self, rows: usize, len: impl Fn(Scope) -> usize) { + self.rows = rows; + self.faults.reset(rows); + for slot in &mut self.slots { + slot.reset(len(slot.scope)); + slot.fault.reset(rows); + } + } + + pub fn rows(&self) -> usize { + self.rows + } + + pub fn slots(&self) -> &[Slot] { + &self.slots + } + + pub fn slot(&self, at: usize) -> Option<&Slot> { + self.slots.get(at) + } + + pub fn slot_mut(&mut self, at: usize) -> Option<&mut Slot> { + self.slots.get_mut(at) + } + + pub fn faults(&self) -> &Faults { + &self.faults + } + + pub fn spread(&mut self, rows: usize, ids: &[u32], positions: Option<&[usize]>) -> bool { + let reps = self.rows; + if self + .slots + .iter() + .any(|slot| slot.offsets.is_some() || slot.len != reps) + || positions.is_some_and(|p| p.len() != ids.len()) + { + return false; + } + let mut sources = match positions { + None => ids.to_vec(), + Some(_) => vec![u32::MAX; rows], + }; + if let Some(positions) = positions { + positions + .iter() + .zip(ids) + .for_each(|(&row, &id)| sources[row] = id); + } + if sources.len() != rows + || sources + .iter() + .any(|&id| id != u32::MAX && id as usize >= reps) + { + return false; + } + self.rows = rows; + self.faults = self.faults.spread(&sources); + for slot in &mut self.slots { + slot.spread(&sources); + } + true + } + + pub(crate) fn parts(&mut self) -> (&mut [Slot], &mut Faults) { + (&mut self.slots, &mut self.faults) + } + + pub(crate) fn collect(&mut self, hir: &Hir, feeds: &Feeds, select: Option<&[u64]>) { + for (at, o) in hir.outputs.iter().enumerate() { + let Some(c) = o.collect else { + continue; + }; + let Some(list) = feeds.lists.get(c.list as usize) else { + continue; + }; + if let (false, Some(null)) = (c.empty, &list.null) { + for owner in (0..list.owners()).filter(|&o| Bits::get(null, o)) { + let row = feeds.row_of(c.list as usize, owner); + if select.is_none_or(|sel| Bits::get(sel, row)) { + self.faults.set(row); + if let Some(slot) = self.slots.get_mut(at) { + slot.fault.set(row); + } + } + } + } + if let Some(slot) = self.slots.get_mut(at) { + slot.compact(&list.offsets); + } + } + } +} + +impl Slot { + fn compact(&mut self, offsets: &[i32]) { + let len = self.len; + let kept: Vec = (0..len).filter(|&e| Bits::get(&self.keep, e)).collect(); + let mut out = Vec::with_capacity(offsets.len()); + let mut at = 0usize; + out.push(0i32); + for w in offsets.windows(2) { + let hi = usize::try_from(w[1]).unwrap_or(0); + while at < kept.len() && kept[at] < hi { + at += 1; + } + out.push(i32::try_from(at).unwrap_or(i32::MAX)); + } + if kept.len() != len { + let mut valid = vec![0u64; K::words(kept.len())]; + for (to, &from) in kept.iter().enumerate() { + Bits::set(&mut valid, to, Bits::get(&self.valid, from)); + } + self.valid = valid; + match &mut self.data { + Data::Num { mant, scale } => { + *mant = kept.iter().map(|&e| mant[e]).collect(); + *scale = kept.iter().map(|&e| scale[e]).collect(); + } + Data::Bool(bits) => { + let mut packed = vec![0u64; K::words(kept.len())]; + for (to, &from) in kept.iter().enumerate() { + Bits::set(&mut packed, to, Bits::get(bits, from)); + } + *bits = packed; + } + Data::Code(codes) => *codes = kept.iter().map(|&e| codes[e]).collect(), + Data::Text { span, .. } => *span = kept.iter().map(|&e| span[e]).collect(), + Data::Date(dates) => *dates = kept.iter().map(|&e| dates[e]).collect(), + } + let wide = std::mem::take(&mut self.wide); + self.wide = wide + .into_iter() + .filter_map(|(e, d)| kept.binary_search(&e).ok().map(|to| (to, d))) + .collect(); + self.len = kept.len(); + } + self.offsets = Some(out); + } +} + +#[cfg(test)] +mod tests { + use super::{Bits, Data, Faults, Outputs, Slot}; + use crate::typed::hir::{Kind, Scope}; + use crate::typed::kernel::K; + use rust_decimal::Decimal; + + struct Build; + + impl Build { + fn slot( + kind: Kind, + data: Data, + valid: &[bool], + faulted: &[usize], + wide: Vec<(usize, Decimal)>, + ) -> Slot { + let mut bits = vec![0u64; K::words(valid.len())]; + valid + .iter() + .enumerate() + .for_each(|(at, &on)| Bits::set(&mut bits, at, on)); + let mut fault = Faults::default(); + fault.reset(valid.len()); + faulted.iter().for_each(|&at| fault.set(at)); + Slot { + name: String::new(), + scope: Scope::Row, + kind, + len: valid.len(), + data, + valid: bits, + fault, + wide, + offsets: None, + keep: Vec::new(), + } + } + + fn reps() -> Outputs { + let num = Self::slot( + Kind::Num(None), + Data::Num { + mant: vec![15, 7, 0], + scale: vec![1, 0, 0], + }, + &[true, true, false], + &[2], + vec![(1, Decimal::MAX)], + ); + let text = Self::slot( + Kind::Text, + Data::Text { + span: vec![(0, 2), (2, 5), (5, 5)], + data: b"abxyz".to_vec(), + }, + &[true, true, false], + &[], + Vec::new(), + ); + let flag = Self::slot( + Kind::Bool, + Data::Bool(vec![0b101]), + &[true, false, true], + &[], + Vec::new(), + ); + let mut faults = Faults::default(); + faults.reset(3); + faults.set(2); + Outputs { + rows: 3, + slots: vec![num, text, flag], + faults, + } + } + } + + #[test] + fn spread_maps_every_row_to_its_representative() { + let mut out = Build::reps(); + assert!(out.spread(5, &[1, 0, 2, 1, 0], None)); + assert_eq!(out.rows(), 5); + let num = &out.slots()[0]; + assert_eq!( + (0..5).map(|at| num.decimal(at)).collect::>(), + vec![ + Some(Decimal::MAX), + Some(Decimal::new(15, 1)), + None, + Some(Decimal::MAX), + Some(Decimal::new(15, 1)) + ] + ); + assert_eq!(num.fault.iter().collect::>(), vec![2]); + assert_eq!(out.faults().iter().collect::>(), vec![2]); + let text = &out.slots()[1]; + assert_eq!( + (0..5).map(|at| text.text(at)).collect::>(), + vec![Some("xyz"), Some("ab"), None, Some("xyz"), Some("ab")] + ); + let flag = &out.slots()[2]; + assert_eq!( + (0..5).map(|at| flag.boolean(at)).collect::>(), + vec![None, Some(true), Some(true), None, Some(true)] + ); + } + + #[test] + fn spread_leaves_unselected_rows_invalid_and_unfaulted() { + let mut out = Build::reps(); + assert!(out.spread(6, &[2, 0, 1], Some(&[1, 3, 4]))); + let num = &out.slots()[0]; + assert_eq!( + (0..6).map(|at| num.is_valid(at)).collect::>(), + vec![false, false, false, true, true, false] + ); + assert_eq!(num.fault.iter().collect::>(), vec![1]); + assert_eq!(num.wide, vec![(4, Decimal::MAX)]); + } + + #[test] + fn spread_rejects_mismatched_ids() { + let mut out = Build::reps(); + assert!(!out.spread(2, &[0, 3], None)); + assert!(!out.spread(4, &[0, 1], Some(&[0]))); + } +} diff --git a/core/expression/src/typed/program.rs b/core/expression/src/typed/program.rs new file mode 100644 index 00000000..1bf763d4 --- /dev/null +++ b/core/expression/src/typed/program.rs @@ -0,0 +1,314 @@ +use crate::lane::date::Date; +use crate::typed::batch::{Batch, Feeds, Origin}; +use crate::typed::build::{Build, Built, Passes, Stage}; +use crate::typed::exec::{Buf, Exec, Reg, Stack}; +use crate::typed::hir::{Clock, DictId, Hir, Lit, NodeId, Op, Unsupported}; +use crate::typed::ins::{BufDef, Rep, R}; +use crate::typed::kernel::K; +use crate::typed::output::Outputs; +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, RwLock}; + +type Sig = Vec>; + +pub(crate) struct Plan { + id: u64, + stages: Vec, + nregs: usize, + consts: Vec<(R, Rep, Lit)>, + defs: Vec, +} + +pub struct Program { + hir: Hir, + passes: Passes, + classes: Vec<(Origin, DictId)>, + class_of: HashMap, + generic: Arc, + plans: RwLock)>>, + clock: bool, +} + +pub(crate) struct Machine { + files: Vec<(u64, Vec)>, + bufs: Vec, + scratch: Vec, + stack: Stack, + sig: Vec>, +} + +impl Plan { + fn new(built: Built) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(1); + let Built { + stages, + nregs, + consts, + defs, + } = built; + Self { + id: NEXT.fetch_add(1, Ordering::Relaxed), + stages, + nregs, + consts, + defs, + } + } + + #[cfg(test)] + pub(crate) fn dump(&self) -> String { + use std::fmt::Write as _; + let mut s = String::new(); + let _ = writeln!(s, "regs {} consts {}", self.nregs, self.consts.len()); + for (b, def) in self.defs.iter().enumerate() { + let _ = writeln!(s, "buf {b} {def:?}"); + } + for (i, stage) in self.stages.iter().enumerate() { + let _ = writeln!(s, "stage {i} @{}", stage.scope); + for (pc, ins) in stage.code.iter().enumerate() { + let _ = writeln!(s, " {pc:>3} {ins:?}"); + } + } + s + } + + pub(crate) fn instructions(&self) -> usize { + self.stages.iter().map(|s| s.code.len()).sum() + } +} + +impl Program { + const PLANS: usize = 16; + + pub fn new(hir: Hir) -> Result { + Self::with(hir, Passes::ALL) + } + + pub(crate) fn with(hir: Hir, passes: Passes) -> Result { + Outputs::new(&hir)?; + let mut classes: Vec<(Origin, DictId)> = Vec::new(); + let mut class_of = HashMap::new(); + for (i, node) in hir.nodes.iter().enumerate() { + let Op::Classify(a, d) = node.op else { + continue; + }; + let origin = match hir.nodes.get(a as usize).map(|n| &n.op) { + Some(Op::Column(c)) => Origin::Col(*c), + Some(Op::Field(l, f)) => Origin::Field(*l, *f), + _ => continue, + }; + let k = match classes.iter().position(|c| *c == (origin, d)) { + Some(k) => k, + None => { + classes.push((origin, d)); + classes.len() - 1 + } + }; + class_of.insert( + i as NodeId, + u16::try_from(k).map_err(|_| Unsupported::new("typed: classes"))?, + ); + } + let width = hir.schema.columns.len() + + hir + .schema + .lists + .iter() + .map(|l| l.fields.len()) + .sum::(); + let generic = Arc::new(Plan::new(Build::plan( + &hir, + &vec![None; width], + &class_of, + passes, + )?)); + let clock = hir + .nodes + .iter() + .any(|node| matches!(node.op, Op::Clock(Clock::Now, _))); + Ok(Self { + hir, + passes, + classes, + class_of, + generic, + plans: RwLock::new(Vec::new()), + clock, + }) + } + + pub fn hir(&self) -> &Hir { + &self.hir + } + + pub fn outputs(&self) -> Outputs { + Outputs::new(&self.hir).unwrap_or_else(|_| Outputs::empty()) + } + + pub fn run( + &self, + batch: &Batch, + out: &mut Outputs, + select: Option<&[u64]>, + ) -> Result<(), Unsupported> { + let mut feeds = Feeds::new(&self.hir, &self.classes, batch)?; + if self.clock { + feeds.now = Date::now(); + } + if out.slots().len() != self.hir.outputs.len() { + *out = Outputs::new(&self.hir)?; + } + out.reset(feeds.rows, |scope| feeds.len(scope)); + Machine::with(|machine| { + feeds.sig(&self.hir, &mut machine.sig); + let plan = self.plan(&machine.sig); + machine.exec(&plan, &feeds, out, select); + }); + feeds.prefaults(out, select); + out.collect(&self.hir, &feeds, select); + Ok(()) + } + + fn plan(&self, sig: &[Option]) -> Arc { + if sig.iter().all(Option::is_none) { + return self.generic.clone(); + } + if let Some(found) = self + .plans + .read() + .ok() + .and_then(|plans| plans.iter().find(|(s, _)| s == sig).map(|(_, p)| p.clone())) + { + return found; + } + let Ok(mut plans) = self.plans.write() else { + return self.generic.clone(); + }; + if let Some((_, p)) = plans.iter().find(|(s, _)| s == sig) { + return p.clone(); + } + if plans.len() >= Self::PLANS { + return self.generic.clone(); + } + match Build::plan(&self.hir, sig, &self.class_of, self.passes) { + Ok(built) => { + let plan = Arc::new(Plan::new(built)); + plans.push((sig.to_vec(), plan.clone())); + plan + } + Err(_) => self.generic.clone(), + } + } + + #[cfg(test)] + pub(crate) fn dump(&self, batch: &Batch) -> Result { + let feeds = Feeds::new(&self.hir, &self.classes, batch)?; + let mut sig = Vec::new(); + feeds.sig(&self.hir, &mut sig); + Ok(self.plan(&sig).dump()) + } + + pub fn instructions(&self) -> usize { + self.generic.instructions() + } +} + +impl Machine { + const FILES: usize = 8; + + thread_local! { + static MACHINE: RefCell = RefCell::new(Machine::new()); + } + + fn new() -> Self { + Self { + files: Vec::new(), + bufs: Vec::new(), + scratch: vec![0; 2 * Reg::LANES + 1], + stack: Vec::with_capacity(16), + sig: Vec::new(), + } + } + + fn with(f: impl FnOnce(&mut Machine) -> T) -> T { + Self::MACHINE.with(|cell| match cell.try_borrow_mut() { + Ok(mut machine) => f(&mut machine), + Err(_) => f(&mut Machine::new()), + }) + } + + fn exec(&mut self, plan: &Plan, feeds: &Feeds, out: &mut Outputs, select: Option<&[u64]>) { + let Machine { + files, + bufs, + scratch, + stack, + .. + } = self; + let at = match files.iter().position(|(id, _)| *id == plan.id) { + Some(at) => at, + None => { + if files.len() >= Self::FILES { + files.remove(0); + } + let mut regs = vec![Reg::new(); plan.nregs]; + for (r, rep, lit) in &plan.consts { + if let Some(reg) = regs.get_mut(*r as usize) { + reg.fill(*rep, lit); + } + } + files.push((plan.id, regs)); + files.len() - 1 + } + }; + let regs = &mut files[at].1; + if bufs.len() < plan.defs.len() { + bufs.resize_with(plan.defs.len(), Buf::default); + } + for (buf, def) in bufs.iter_mut().zip(&plan.defs) { + let len = feeds.len(def.scope); + buf.sized(len); + if let Some((list, _, _, empty)) = def.fold { + buf.mant.fill(0); + buf.scale.fill(0); + buf.codes.fill(0); + buf.bits.fill(0); + buf.fault.fill(0); + buf.valid.fill(u64::MAX); + if let Some(null) = feeds + .lists + .get(list as usize) + .and_then(|l| l.null.as_ref()) + .filter(|_| !empty) + { + for (f, n) in buf.fault.iter_mut().zip(null) { + *f |= n; + } + } + } + } + for (at, stage) in plan.stages.iter().enumerate() { + let len = feeds.len(stage.scope); + let mut start = 0; + while start < len { + let n = (len - start).min(Reg::LANES); + let exec = Exec { + feeds, + select, + start, + n, + words: K::words(n), + }; + exec.run(&stage.code, regs, bufs, scratch, stack, out); + start += Reg::LANES; + } + for (buf, def) in bufs.iter_mut().zip(&plan.defs) { + if let (Some((_, fold, rep, _)), true) = (def.fold, def.stage == at) { + buf.finish(fold, rep); + } + } + } + } +} diff --git a/core/expression/src/typed/tests/data.rs b/core/expression/src/typed/tests/data.rs new file mode 100644 index 00000000..5d343b96 --- /dev/null +++ b/core/expression/src/typed/tests/data.rs @@ -0,0 +1,486 @@ +use crate::lane::{Column, Dictionary, Values}; +use crate::typed::{Batch, Class, Dec, Hir, List, Resolve, Resolved}; +use crate::variable::Variable; +use rust_decimal::Decimal; +use std::sync::Arc; + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Value { + Null, + Num(Dec), + Bool(bool), + Str(String), + Items(Vec>), +} + +#[derive(Clone, Debug, PartialEq, Default)] +pub(crate) struct Row { + pub(crate) columns: Vec, + pub(crate) lists: Vec>>, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Enc { + Scaled, + I64, + Dec, + Bool, + Text, + Utf8, + Dict, + Items, +} + +#[derive(Clone, Debug)] +pub(crate) struct ColSpec { + pub(crate) path: &'static str, + pub(crate) class: Class, + pub(crate) enc: Enc, +} + +#[derive(Clone, Debug)] +pub(crate) struct ListSpec { + pub(crate) parent: Option, + pub(crate) path: &'static str, + pub(crate) alias: &'static str, + pub(crate) fields: Vec, +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct Spec { + pub(crate) columns: Vec, + pub(crate) lists: Vec, +} + +pub(crate) struct Mock<'s> { + pub(crate) spec: &'s Spec, + pub(crate) member: Option, +} + +enum Store { + Num { + mant: Vec, + scale: Vec, + }, + I64(Vec), + Dec(Vec), + Bool(Vec), + Text { + offsets: Vec, + data: String, + }, + Utf8 { + offsets: Vec, + data: Vec, + }, + Dict { + keys: Vec, + offsets: Vec, + data: String, + }, +} + +pub(crate) struct Owned { + store: Store, + validity: Option>, +} + +pub(crate) struct OwnedList { + offsets: Vec, + validity: Option>, + fields: Vec, +} + +pub(crate) struct Frame { + pub(crate) rows: usize, + columns: Vec, + lists: Vec, + parents: Vec>, +} + +impl ColSpec { + pub(crate) fn new(path: &'static str, class: Class, enc: Enc) -> Self { + Self { path, class, enc } + } +} + +impl ListSpec { + fn listed(&self) -> Resolved { + Resolved::List { + fields: self + .fields + .iter() + .filter(|f| f.enc != Enc::Items) + .map(|f| (Arc::from(f.path), f.class)) + .collect(), + } + } +} + +impl Spec { + pub(crate) fn nested(&self, parent: usize, field: &str) -> Option { + self.lists + .iter() + .position(|l| l.parent == Some(parent) && l.path == field) + } + + pub(crate) fn top(&self, path: &str) -> Option { + self.lists + .iter() + .position(|l| l.parent.is_none() && l.path == path) + } + + fn items(&self, list: usize, records: &[Vec]) -> Variable { + let def = &self.lists[list]; + let items = records + .iter() + .map(|record| match def.fields.as_slice() { + [only] if only.path.is_empty() => record + .first() + .map_or(Variable::Null, |v| self.value(list, 0, v)), + fields => { + let object = Variable::empty_object(); + for (at, (field, value)) in fields.iter().zip(record).enumerate() { + object.dot_insert(field.path, self.value(list, at, value)); + } + object + } + }) + .collect(); + Variable::from_array(items) + } + + fn value(&self, list: usize, field: usize, value: &Value) -> Variable { + match value { + Value::Items(records) => match self.lists[list] + .fields + .get(field) + .and_then(|f| self.nested(list, f.path)) + { + Some(nested) => self.items(nested, records), + None => Variable::Null, + }, + other => other.variable(), + } + } +} + +impl Resolve for Mock<'_> { + fn path(&mut self, path: &str) -> Resolved { + if let Some(c) = self.spec.columns.iter().find(|c| c.path == path) { + return Resolved::Column(c.class); + } + match self.spec.top(path) { + Some(at) if self.member == Some(at) => Resolved::Unsupported, + Some(at) => self.spec.lists[at].listed(), + None => Resolved::Absent, + } + } + + fn nested(&mut self, chain: &[&str]) -> Resolved { + let Some((first, rest)) = chain.split_first() else { + return Resolved::Unsupported; + }; + let Some(mut at) = self.spec.top(first) else { + return Resolved::Unsupported; + }; + for field in rest { + match self.spec.nested(at, field) { + Some(next) => at = next, + None => return Resolved::Unsupported, + } + } + self.spec.lists[at].listed() + } + + fn alias(&mut self, field: &str) -> Resolved { + let Some(list) = self.member.and_then(|m| self.spec.lists.get(m)) else { + return Resolved::Unsupported; + }; + match list.fields.iter().find(|f| f.path == field) { + Some(f) if f.enc == Enc::Items => Resolved::Unsupported, + Some(f) => Resolved::Column(f.class), + None => Resolved::Absent, + } + } +} + +impl Value { + pub(crate) fn variable(&self) -> Variable { + match self { + Value::Null => Variable::Null, + Value::Num(d) => Variable::Number(d.decimal()), + Value::Bool(b) => Variable::Bool(*b), + Value::Str(s) => Variable::String(s.as_str().into()), + Value::Items(_) => Variable::Null, + } + } +} + +impl Row { + pub(crate) fn null(records: &[Vec]) -> bool { + matches!(records, [only] if only.is_empty()) + } + + pub(crate) fn variable(&self, spec: &Spec) -> Variable { + let root = Variable::empty_object(); + for (def, value) in spec.columns.iter().zip(&self.columns) { + root.dot_insert(def.path, value.variable()); + } + let tops = spec + .lists + .iter() + .enumerate() + .filter(|(_, l)| l.parent.is_none()); + for ((at, def), records) in tops.zip(&self.lists) { + match Row::null(records) { + true => root.dot_insert(def.path, Variable::Null), + false => root.dot_insert(def.path, spec.items(at, records)), + }; + } + root + } +} + +impl Owned { + fn build(spec: &ColSpec, values: &[&Value], shift: usize) -> Self { + let n = values.len() + shift; + let mut validity = vec![u64::MAX; n.div_ceil(64)]; + let mut nulls = false; + let lead = std::iter::repeat_n(&Value::Null, shift); + let all: Vec<&Value> = lead.chain(values.iter().copied()).collect(); + for (i, v) in all.iter().enumerate() { + if matches!(v, Value::Null) { + validity[i / 64] &= !(1u64 << (i % 64)); + nulls = true; + } + } + let num = |v: &Value| match v { + Value::Num(d) => *d, + _ => Dec::new(0, 0), + }; + let text = |v: &Value| match v { + Value::Str(s) => s.clone(), + _ => String::new(), + }; + let store = match spec.enc { + Enc::Scaled => Store::Num { + mant: all.iter().map(|v| num(v).mant).collect(), + scale: all.iter().map(|v| num(v).scale).collect(), + }, + Enc::I64 => Store::I64(all.iter().map(|v| num(v).mant).collect()), + Enc::Dec => Store::Dec(all.iter().map(|v| num(v).decimal()).collect()), + Enc::Bool => { + let mut bits = vec![0u64; n.div_ceil(64)]; + for (i, v) in all.iter().enumerate() { + if matches!(v, Value::Bool(true)) { + bits[i / 64] |= 1u64 << (i % 64); + } + } + Store::Bool(bits) + } + Enc::Text | Enc::Utf8 => { + let mut offsets = vec![0i32]; + let mut data = String::new(); + for v in &all { + data.push_str(&text(v)); + offsets.push(data.len() as i32); + } + match spec.enc { + Enc::Text => Store::Text { offsets, data }, + _ => Store::Utf8 { + offsets, + data: data.into_bytes(), + }, + } + } + Enc::Items => Store::I64(vec![0; n]), + Enc::Dict => { + let mut entries: Vec = Vec::new(); + let mut keys = Vec::with_capacity(n); + for v in &all { + let t = text(v); + let k = match entries.iter().position(|e| *e == t) { + Some(k) => k, + None => { + entries.push(t); + entries.len() - 1 + } + }; + keys.push(k as i32); + } + entries.reverse(); + let last = entries.len() as i32 - 1; + let keys = keys.into_iter().map(|k| last - k).collect(); + let mut offsets = vec![0i32]; + let mut data = String::new(); + for e in &entries { + data.push_str(e); + offsets.push(data.len() as i32); + } + Store::Dict { + keys, + offsets, + data, + } + } + }; + Self { + store, + validity: nulls.then_some(validity), + } + } + + pub(crate) fn column(&self) -> Column<'_> { + let values = match &self.store { + Store::Num { mant, scale } => Values::Scaled { mant, scale }, + Store::I64(v) => Values::I64(v), + Store::Dec(v) => Values::Dec(v), + Store::Bool(bits) => Values::Bool { bits, offset: 0 }, + Store::Text { offsets, data } => Values::Text { offsets, data }, + Store::Utf8 { offsets, data } => Values::Utf8 { offsets, data }, + Store::Dict { + keys, + offsets, + data, + } => Values::Dict { + keys, + values: Dictionary::Text { offsets, data }, + }, + }; + match &self.validity { + Some(bits) => Column::with_validity(values, bits, 0), + None => Column::new(values), + } + } +} + +impl Frame { + pub(crate) fn new(hir: &Hir, spec: &Spec, rows: &[Row], shift: usize) -> Self { + let mut columns = Vec::with_capacity(hir.schema.columns.len()); + for def in &hir.schema.columns { + let at = spec + .columns + .iter() + .position(|c| c.path == def.path) + .expect("spec column"); + let values: Vec<&Value> = rows + .iter() + .map(|r| r.columns.get(at).unwrap_or(&Value::Null)) + .collect(); + columns.push(Owned::build(&spec.columns[at], &values, 0)); + } + let mut lists = Vec::with_capacity(hir.schema.lists.len()); + let mut specs: Vec = Vec::with_capacity(hir.schema.lists.len()); + let mut records: Vec>> = Vec::with_capacity(hir.schema.lists.len()); + for def in &hir.schema.lists { + let (l, owners): (usize, Vec>>>) = match def.parent { + None => { + let l = spec.top(&def.path).expect("spec list"); + let tops = spec.lists[..l] + .iter() + .filter(|x| x.parent.is_none()) + .count(); + let owners = rows + .iter() + .map(|r| match r.lists.get(tops) { + Some(items) if Row::null(items) => None, + Some(items) => Some(items.iter().collect()), + None => Some(Vec::new()), + }) + .collect(); + (l, owners) + } + Some(p) => { + let parent = specs[p as usize]; + let l = spec.nested(parent, &def.path).expect("spec nested list"); + let at = spec.lists[parent] + .fields + .iter() + .position(|f| f.path == def.path) + .expect("nested field"); + let owners = records[p as usize] + .iter() + .map(|record| match record.get(at) { + Some(Value::Items(items)) => Some(items.iter().collect()), + _ => None, + }) + .collect(); + (l, owners) + } + }; + let mut offsets = vec![shift as i32]; + let mut validity = vec![u64::MAX; owners.len().div_ceil(64).max(1)]; + let mut nulls = false; + let mut flat: Vec<&Vec> = Vec::new(); + for (o, owner) in owners.iter().enumerate() { + match owner { + Some(items) => flat.extend(items.iter().copied()), + None => { + validity[o / 64] &= !(1u64 << (o % 64)); + nulls = true; + } + } + offsets.push(shift as i32 + flat.len() as i32); + } + let mut fields = Vec::with_capacity(def.fields.len()); + for field in &def.fields { + let f = spec.lists[l] + .fields + .iter() + .position(|x| x.path == field.path) + .expect("spec field"); + let values: Vec<&Value> = flat + .iter() + .map(|record| record.get(f).unwrap_or(&Value::Null)) + .collect(); + fields.push(Owned::build(&spec.lists[l].fields[f], &values, shift)); + } + lists.push(OwnedList { + offsets, + validity: nulls.then_some(validity), + fields, + }); + specs.push(l); + records.push(flat); + } + Self { + rows: rows.len(), + columns, + lists, + parents: hir.schema.lists.iter().map(|l| l.parent).collect(), + } + } + + pub(crate) fn batch(&self) -> Batch<'_> { + let mut batch = Batch::new(self.rows); + for c in &self.columns { + batch.push_column(c.column()); + } + for l in &self.lists { + batch.push_list(List::new( + &l.offsets, + l.validity.as_deref().map(|bits| (bits, 0)), + l.fields.iter().map(Owned::column).collect(), + )); + } + batch + } + + pub(crate) fn range(&self, list: usize, row: usize) -> std::ops::Range { + let l = &self.lists[list]; + let base = l.offsets[0] as usize; + (l.offsets[row] as usize - base)..(l.offsets[row + 1] as usize - base) + } + + pub(crate) fn elements(&self, list: usize, row: usize) -> Vec { + match self.parents[list] { + None => self.range(list, row).collect(), + Some(p) => self + .elements(p as usize, row) + .into_iter() + .flat_map(|o| self.range(list, o)) + .collect(), + } + } +} diff --git a/core/expression/src/typed/tests/exact.rs b/core/expression/src/typed/tests/exact.rs new file mode 100644 index 00000000..f6d3439b --- /dev/null +++ b/core/expression/src/typed/tests/exact.rs @@ -0,0 +1,375 @@ +use crate::typed::batch::Feeds; +use crate::typed::build::Passes; +use crate::typed::tests::data::{Enc, Frame, Row, Value}; +use crate::typed::tests::interp::Interp; +use crate::typed::tests::oracle::{Oracle, RowResult, Val}; +use crate::typed::tests::workload::Workload; +use crate::typed::{Data, Dec, Hir, Kind, Outputs, Program, Scope, Slot}; +use std::time::Instant; + +struct Lab { + workload: Workload, + hir: Hir, + rows: Vec, + expected: Vec, +} + +#[derive(Debug, Default)] +struct Report { + faults: usize, + interp: usize, + mismatches: usize, + spurious: usize, + samples: Vec, +} + +impl Lab { + fn new(workload: Workload, rows: Vec) -> Self { + Workload::mock(); + let hir = workload.hir().expect("lowering"); + let oracle = Oracle::new(&workload, &hir); + let expected = rows + .iter() + .map(|r| oracle.run(r.variable(&workload.spec))) + .collect(); + Self { + workload, + hir, + rows, + expected, + } + } + + fn val(slot: &Slot, hir: &Hir, i: usize) -> Val { + match (&slot.data, slot.kind) { + (Data::Num { .. }, _) => slot.decimal(i).map_or(Val::Null, Val::Num), + (Data::Bool(_), _) => slot.boolean(i).map_or(Val::Null, Val::Bool), + (Data::Code(_), Kind::Code(d)) => slot.code(i).map_or(Val::Null, |c| { + hir.dict(d) + .text(c) + .map_or(Val::Other(format!("code {c}")), |t| Val::Str(t.to_string())) + }), + (Data::Code(_), _) => Val::Other("code without dict".to_string()), + (Data::Text { .. }, _) => slot.text(i).map_or(Val::Null, |t| Val::Str(t.to_string())), + (Data::Date(_), _) => match slot.date(i) { + Some(_) => Val::Other(format!("{}", slot.variable(i).to_value())), + None => Val::Null, + }, + } + } + + fn rows_of(out: &Outputs, hir: &Hir, frame: &Frame) -> Vec>> { + (0..frame.rows) + .map(|row| { + (!out.faults().get(row)).then(|| { + out.slots() + .iter() + .map(|slot| match (slot.offsets.as_deref(), slot.scope) { + (_, Scope::Row) => Self::val(slot, hir, row), + (None, Scope::Elem(l)) => Val::List( + frame + .elements(l as usize, row) + .into_iter() + .map(|e| Self::val(slot, hir, e)) + .collect(), + ), + (Some(offsets), Scope::Elem(l)) => { + let items = |o: usize| { + Val::List( + (offsets[o] as usize..offsets[o + 1] as usize) + .map(|e| Self::val(slot, hir, e)) + .collect(), + ) + }; + match hir.schema.owner(Scope::Elem(l)) { + Some(Scope::Elem(p)) => Val::List( + frame + .elements(p as usize, row) + .into_iter() + .map(items) + .collect(), + ), + _ => items(row), + } + } + }) + .collect() + }) + }) + .collect() + } + + fn same(got: &[Val], want: &[Val]) -> bool { + got.len() == want.len() + && got + .iter() + .zip(want) + .all(|(a, b)| a.to_string() == b.to_string()) + } + + fn verify(&self, program: &Program, size: usize) -> Report { + let mut report = Report::default(); + let mut out = program.outputs(); + for (chunk, start) in self.rows.chunks(size).zip((0..).step_by(size)) { + let shift = if size == 7 { 3 } else { 0 }; + let frame = Frame::new(&self.hir, &self.workload.spec, chunk, shift); + let batch = frame.batch(); + program.run(&batch, &mut out, None).expect("run"); + let typed = Self::rows_of(&out, &self.hir, &frame); + let mut feeds = Feeds::new(&self.hir, &[], &batch).expect("feeds"); + feeds.now = crate::lane::date::Date::now(); + let interp = Interp::run(&self.hir, &feeds); + for (i, (t, r)) in typed.iter().zip(&interp).enumerate() { + let row = start + i; + let want = &self.expected[row]; + report.faults += t.is_none() as usize; + report.spurious += (t.is_none() && want.is_ok()) as usize; + report.interp += r.is_none() as usize; + let mut check = |got: &Option>, who: &str| { + let ok = match (got, want) { + (None, _) => true, + (Some(g), Ok(w)) => Self::same(g, w), + (Some(_), Err(_)) => false, + }; + if !ok { + report.mismatches += 1; + if report.samples.len() < 5 { + let show = |v: &[Val]| { + v.iter() + .map(|x| x.to_string()) + .collect::>() + .join(" | ") + }; + report.samples.push(format!( + "{who} row {row} {:?}: got {} want {}", + self.rows[row], + got.as_deref().map_or("fault".to_string(), show), + want.as_deref().map_or_else(|e| format!("error {e}"), show) + )); + } + } + }; + check(t, "typed"); + check(r, "interp"); + if t.is_some() != r.is_some() && report.samples.len() < 5 { + report.samples.push(format!( + "fault disagreement row {row}: typed {} interp {}", + t.is_none(), + r.is_none() + )); + } + } + } + report + } + + fn check(&self, program: &Program, sizes: &[usize], clean: bool) { + for &size in sizes { + let r = self.verify(program, size); + assert_eq!( + r.mismatches, 0, + "{} @{size}: {:#?}", + self.workload.name, r.samples + ); + assert_eq!( + r.faults, r.interp, + "{} @{size}: typed faults {} vs interp {}: {:#?}", + self.workload.name, r.faults, r.interp, r.samples + ); + assert_eq!( + r.spurious, 0, + "{} @{size}: typed faults on rows the VM evaluates", + self.workload.name + ); + if clean { + assert_eq!(r.faults, 0, "{} @{size}", self.workload.name); + } + } + } +} + +struct Bench; + +impl Bench { + fn rows(name: &str, size: usize, reps: usize) -> f64 { + let mut workload = Workload::get(name); + for c in workload.spec.columns.iter_mut().chain( + workload + .spec + .lists + .iter_mut() + .flat_map(|l| l.fields.iter_mut()), + ) { + if c.enc == Enc::Dec { + c.enc = Enc::Scaled; + } + } + let hir = workload.hir().expect("lowering"); + let rows = workload.rows(size); + let frame = Frame::new(&hir, &workload.spec, &rows, 0); + let batch = frame.batch(); + let program = Program::new(hir).expect("program"); + let mut out = program.outputs(); + program.run(&batch, &mut out, None).expect("run"); + let mut best = f64::MAX; + for _ in 0..reps { + let t = Instant::now(); + for _ in 0..50 { + program.run(&batch, &mut out, None).expect("run"); + } + best = best.min(t.elapsed().as_nanos() as f64 / 50.0 / size as f64); + } + best + } +} + +const SIZES: [usize; 5] = [1024, 64, 16, 7, 1]; + +#[test] +fn workloads_match_vm_and_interp() { + for name in Workload::NAMES { + let workload = Workload::get(name); + let rows = workload.rows(1024); + let lab = Lab::new(workload, rows); + let program = Program::new(lab.hir.clone()).expect("program"); + lab.check(&program, &SIZES, !Workload::FAULTY.contains(&name)); + } +} + +#[test] +fn extremes_match_vm_and_interp() { + for name in Workload::NAMES { + let workload = Workload::get(name); + let rows = workload.mixed(300); + let lab = Lab::new(workload, rows); + let program = Program::new(lab.hir.clone()).expect("program"); + lab.check(&program, &SIZES, false); + } +} + +#[test] +fn passes_off_match_vm() { + let offs: [fn(&mut Passes); 7] = [ + |p| p.fold = false, + |p| p.factor = false, + |p| p.skip = false, + |p| p.reuse = false, + |p| p.elide = false, + |p| { + *p = Passes { + fold: false, + factor: false, + skip: false, + reuse: false, + elide: false, + skip_min: 2, + lookup_min: 128, + } + }, + |p| p.lookup_min = 1, + ]; + for name in Workload::NAMES { + let workload = Workload::get(name); + let rows = workload.mixed(200); + let lab = Lab::new(workload, rows); + for off in offs { + let mut passes = Passes::ALL; + off(&mut passes); + let program = Program::with(lab.hir.clone(), passes).expect("program"); + lab.check(&program, &[1024, 7], false); + } + } +} + +#[test] +fn untaken_arm_faults_are_masked() { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let huge = [ + i64::MAX / 3, + -(i64::MAX / 7), + 4_000_000_000_000_000_000, + 99_999_999_999, + 1, + ]; + for name in Workload::NAMES { + let workload = Workload::get(name); + let mut rows = workload.rows(600); + let mut bump = |v: &mut Value| { + if let Value::Num(d) = v { + match next() % 8 { + 0 | 1 => *v = Value::Num(Dec::new(huge[(next() % 5) as usize], d.scale)), + 2 => *v = Value::Null, + _ => {} + } + } + }; + for row in rows.iter_mut() { + row.columns.iter_mut().for_each(&mut bump); + row.lists.iter_mut().flatten().flatten().for_each(&mut bump); + } + let lab = Lab::new(workload, rows); + let program = Program::new(lab.hir.clone()).expect("program"); + for size in [1024, 64, 7, 1] { + let r = lab.verify(&program, size); + assert_eq!(r.mismatches, 0, "{name} @{size}: {:#?}", r.samples); + assert_eq!(r.faults, r.interp, "{name} @{size}: {:#?}", r.samples); + assert!(r.faults > 0, "{name} @{size}"); + } + } +} + +#[test] +#[ignore] +fn micro_bench() { + for name in Workload::NAMES { + let ns = Bench::rows(name, 1024, 15); + println!("{name} @1024: {ns:.1} ns/row"); + } +} + +#[test] +#[ignore] +fn profile_ops() { + use crate::typed::exec::Exec; + for name in Workload::NAMES { + Exec::PROFILE.with_borrow_mut(|p| *p = Some(Default::default())); + Bench::rows(name, 1024, 5); + let mut ops: Vec<(String, (u128, usize))> = Exec::PROFILE + .with_borrow_mut(|p| p.take()) + .unwrap_or_default() + .into_iter() + .collect(); + ops.sort_by_key(|o| std::cmp::Reverse(o.1 .0)); + let runs = 5.0 * 50.0 + 1.0; + println!("{name}"); + for (op, (ns, count)) in ops { + println!( + " {op:<12} {:>7.2} ns/row {:>6.1} per run", + ns as f64 / runs / 1024.0, + count as f64 / runs + ); + } + } +} + +#[test] +#[ignore] +fn dump_bytecode() { + for name in Workload::NAMES { + let workload = Workload::get(name); + let hir = workload.hir().expect("lowering"); + let rows = workload.rows(1024); + let frame = Frame::new(&hir, &workload.spec, &rows, 0); + let program = Program::new(hir.clone()).expect("program"); + println!( + "== {name}\n{hir}\n{}", + program.dump(&frame.batch()).expect("dump") + ); + } +} diff --git a/core/expression/src/typed/tests/interp.rs b/core/expression/src/typed/tests/interp.rs new file mode 100644 index 00000000..d533e9f6 --- /dev/null +++ b/core/expression/src/typed/tests/interp.rs @@ -0,0 +1,606 @@ +use crate::lane::builtins::{Arg as Given, Builtins, Out}; +use crate::lane::date::Date; +use crate::lane::Bits; +use crate::typed::batch::{Data, Feed, Feeds}; +use crate::typed::ins::Pattern; +use crate::typed::num::Exact; +use crate::typed::tests::oracle::Val; +use crate::typed::{Clock, Cmp, Fold, Func, Hir, Kind, Lit, NodeId, Op, Range, Scope}; +use crate::variable::Variable; +use rust_decimal::Decimal; +use std::borrow::Cow; +use std::cmp::Ordering; + +#[derive(Clone, Debug, PartialEq)] +enum V<'a> { + Null, + Num(Decimal), + Bool(bool), + Code(i32), + Text(Cow<'a, [u8]>), + Date(Date), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Fault; + +type R<'a> = Result, Fault>; + +pub(crate) struct Interp<'a, 'x> { + hir: &'a Hir, + feeds: &'a Feeds<'x>, + row: usize, + elem: Vec, + cache: Vec>>, +} + +impl<'a, 'x> Interp<'a, 'x> { + pub(crate) fn run(hir: &'a Hir, feeds: &'a Feeds<'x>) -> Vec>> { + let n = hir.nodes.len(); + let mut walk = Interp { + hir, + feeds, + row: 0, + elem: vec![0; hir.schema.lists.len()], + cache: vec![None; n], + }; + let mut out = Vec::with_capacity(feeds.rows); + for row in 0..feeds.rows { + walk.row = row; + walk.cache.fill(None); + let mut values = Vec::with_capacity(hir.outputs.len()); + let mut faulted = false; + for output in &hir.outputs { + let owner = match output.collect { + Some(_) => hir.schema.owner(output.scope).unwrap_or(Scope::Row), + None => output.scope, + }; + let value = match owner { + Scope::Row => walk.output(output), + Scope::Elem(l) => { + let mut items = Vec::new(); + let mut fault = false; + for e in walk.elements(l) { + walk.enter(l, e); + match walk.output(output) { + Ok(v) => items.push(v), + Err(Fault) => fault = true, + } + } + match fault { + true => Err(Fault), + false => Ok(Val::List(items)), + } + } + }; + match value { + Ok(v) => values.push(v), + Err(Fault) => faulted = true, + } + } + out.push((!faulted).then_some(values)); + } + out + } + + fn owner(&self, list: u16) -> usize { + match self.hir.schema.lists[list as usize].parent { + None => self.row, + Some(p) => self.elem[p as usize], + } + } + + fn elements(&self, list: u16) -> Vec { + match self.hir.schema.lists[list as usize].parent { + None => { + let l = &self.feeds.lists[list as usize]; + (l.offsets[self.row] as usize..l.offsets[self.row + 1] as usize).collect() + } + Some(p) => { + let l = &self.feeds.lists[list as usize]; + self.elements(p) + .into_iter() + .flat_map(|o| l.offsets[o] as usize..l.offsets[o + 1] as usize) + .collect() + } + } + } + + fn enter(&mut self, list: u16, e: usize) { + self.elem[list as usize] = e; + let schema = &self.hir.schema; + for (at, node) in self.hir.nodes.iter().enumerate() { + if schema.within(node.scope, Scope::Elem(list)) { + self.cache[at] = None; + } + } + } + + fn range(&self, list: u16, empty: bool) -> Result, Fault> { + let l = &self.feeds.lists[list as usize]; + let owner = self.owner(list); + if l.faulted.as_ref().is_some_and(|f| Bits::get(f, owner)) { + return Err(Fault); + } + match l.null.as_ref().is_some_and(|null| Bits::get(null, owner)) { + true if empty => Ok(0..0), + true => Err(Fault), + false => Ok(l.offsets[owner] as usize..l.offsets[owner + 1] as usize), + } + } + + fn output(&mut self, output: &crate::typed::Output) -> Result { + let Some(c) = output.collect else { + let v = self.eval(output.node)?; + return Ok(self.val(v, output.ty.kind)); + }; + let range = self.range(c.list, c.empty)?; + let saved = self.elem[c.list as usize]; + let mut items = Vec::new(); + let mut result = Ok(()); + for e in range { + self.enter(c.list, e); + let keep = match c.keep { + None => true, + Some(k) => match self.eval(k) { + Ok(V::Bool(b)) => b, + _ => { + result = Err(Fault); + break; + } + }, + }; + if !keep { + continue; + } + match self.eval(output.node) { + Ok(v) => items.push(self.val(v, output.ty.kind)), + Err(Fault) => { + result = Err(Fault); + break; + } + } + } + self.enter(c.list, saved); + result.map(|_| Val::List(items)) + } + + fn val(&self, v: V, kind: Kind) -> Val { + match (v, kind) { + (V::Null, _) => Val::Null, + (V::Num(d), _) => Val::Num(d), + (V::Bool(b), _) => Val::Bool(b), + (V::Code(c), Kind::Code(d)) => self + .hir + .dict(d) + .text(c) + .map_or(Val::Other(format!("code {c}")), |t| Val::Str(t.to_string())), + (V::Code(c), _) => Val::Other(format!("code {c}")), + (V::Text(t), _) => Val::Str(String::from_utf8_lossy(&t).to_string()), + (V::Date(d), _) => Val::Other(format!("{}", d.variable().to_value())), + } + } + + fn eval(&mut self, id: NodeId) -> R<'a> { + let at = id as usize; + if let Some(r) = &self.cache[at] { + return r.clone(); + } + let r = self.compute(id); + self.cache[at] = Some(r.clone()); + r + } + + fn read(feed: &'a Feed<'x>, i: usize) -> R<'a> { + if Bits::get(feed.faults.as_deref().unwrap_or(&[]), i) { + return Err(Fault); + } + if !feed.valid(i) { + return Ok(V::Null); + } + if let Some((bits, values)) = &feed.wide { + if Bits::get(bits, i) { + return Ok(values + .binary_search_by_key(&i, |(at, _)| *at) + .map_or(V::Null, |at| V::Num(values[at].1))); + } + } + Ok(match &feed.data { + Data::Num { .. } => feed.num(i).map_or(V::Null, |d| V::Num(d.decimal())), + Data::Bool { bits, offset } => V::Bool(Bits::get(bits, offset + i)), + Data::Codes(codes) => V::Code(codes[i]), + Data::Text(text) => text.get(i).map_or(V::Null, |t| V::Text(Cow::Borrowed(t))), + }) + } + + fn lit(lit: &'a Lit) -> V<'a> { + match lit { + Lit::Null => V::Null, + Lit::Num(d) => V::Num(d.decimal()), + Lit::Bool(b) => V::Bool(*b), + Lit::Code(_, c) => V::Code(*c), + Lit::Text(t) => V::Text(Cow::Borrowed(t.as_bytes())), + Lit::Date(d) => V::Date(d.date()), + } + } + + fn equal(a: &V, b: &V) -> bool { + a == b + } + + fn within(x: Decimal, r: &Range) -> bool { + let (lo, hi) = (x.cmp(&r.lo.decimal()), x.cmp(&r.hi.decimal())); + let above = lo == Ordering::Greater || (r.lo_closed && lo == Ordering::Equal); + let below = hi == Ordering::Less || (r.hi_closed && hi == Ordering::Equal); + above && below + } + + fn compute(&mut self, id: NodeId) -> R<'a> { + let hir = self.hir; + let node = &hir.nodes[id as usize]; + match &node.op { + Op::Column(c) => Self::read(&self.feeds.columns[*c as usize], self.row), + Op::Field(l, f) => Self::read( + &self.feeds.fields[*l as usize][*f as usize], + self.elem[*l as usize], + ), + Op::Parent(a) => self.eval(*a), + Op::Const(lit) => Ok(Self::lit(lit)), + Op::Classify(a, d) => match self.eval(*a)? { + V::Text(t) => { + let dict = hir.dict(*d); + Ok(V::Code( + dict.values + .iter() + .position(|v| v.as_bytes() == &*t) + .map_or(dict.values.len() as i32, |i| i as i32), + )) + } + _ => Ok(V::Null), + }, + Op::Neg(a) => match self.eval(*a)? { + V::Num(d) => Ok(V::Num(-d)), + _ => Err(Fault), + }, + Op::Not(a) => match self.eval(*a)? { + V::Bool(b) => Ok(V::Bool(!b)), + _ => Err(Fault), + }, + Op::Arith(op, a, b) => { + let (x, y) = (self.eval(*a)?, self.eval(*b)?); + let (V::Num(x), V::Num(y)) = (x, y) else { + return Err(Fault); + }; + match Exact::arith(*op, x, y) { + Ok(Some(q)) => Ok(V::Num(q)), + Ok(None) => Ok(V::Null), + Err(_) => Err(Fault), + } + } + Op::Cmp(op, a, b) => { + let (x, y) = (self.eval(*a)?, self.eval(*b)?); + match op { + Cmp::Eq => Ok(V::Bool(Self::equal(&x, &y))), + Cmp::Ne => Ok(V::Bool(!Self::equal(&x, &y))), + _ => { + let o = match (x, y) { + (V::Num(x), V::Num(y)) => x.cmp(&y), + (V::Date(x), V::Date(y)) => x.cmp(&y), + _ => return Err(Fault), + }; + Ok(V::Bool(match op { + Cmp::Lt => o == Ordering::Less, + Cmp::Le => o != Ordering::Greater, + Cmp::Gt => o == Ordering::Greater, + _ => o != Ordering::Less, + })) + } + } + } + Op::And(a, b) => match self.eval(*a)? { + V::Bool(false) => Ok(V::Bool(false)), + V::Bool(true) => self.eval(*b), + _ => Err(Fault), + }, + Op::Or(a, b) => match self.eval(*a)? { + V::Bool(true) => Ok(V::Bool(true)), + V::Bool(false) => self.eval(*b), + _ => Err(Fault), + }, + Op::If(c, t, e) => match self.eval(*c)? { + V::Bool(true) => self.eval(*t), + V::Bool(false) => self.eval(*e), + _ => Err(Fault), + }, + Op::Coalesce(a, b) => match self.eval(*a)? { + V::Null => self.eval(*b), + v => Ok(v), + }, + Op::InSet(a, set) => { + let x = self.eval(*a)?; + Ok(V::Bool( + set.iter().any(|lit| Self::equal(&x, &Self::lit(lit))), + )) + } + Op::InRange(a, r) => match self.eval(*a)? { + V::Num(x) => Ok(V::Bool(Self::within(x, r))), + _ => Err(Fault), + }, + Op::Fold { + fold, + list, + filter, + value, + empty, + } => { + let range = self.range(*list, *empty)?; + let saved = self.elem[*list as usize]; + let mut kept = Vec::new(); + let mut result = Ok(()); + for e in range { + self.enter(*list, e); + if let Some(f) = filter { + match self.eval(*f) { + Ok(V::Bool(true)) => {} + Ok(V::Bool(false)) => continue, + _ => { + result = Err(Fault); + break; + } + } + } + kept.push(e); + } + let mut values = Vec::new(); + let mut dates = Vec::new(); + let mut decided: Option = None; + let mut ones = 0; + if result.is_ok() && *fold != Fold::Count { + for e in kept.iter().copied() { + self.enter(*list, e); + let Some(v) = value else { + result = Err(Fault); + break; + }; + match (fold, self.eval(*v)) { + (Fold::Any | Fold::All | Fold::None | Fold::One, Ok(V::Bool(b))) => { + match fold { + Fold::Any if b => decided = Some(true), + Fold::All if !b => decided = Some(false), + Fold::None if b => decided = Some(false), + Fold::One => ones += i64::from(b), + _ => {} + } + } + (Fold::Sum | Fold::Min | Fold::Max | Fold::Avg, Ok(V::Num(d))) => { + values.push(d) + } + (Fold::Min | Fold::Max, Ok(V::Date(d))) => dates.push(d), + _ => { + result = Err(Fault); + break; + } + } + if decided.is_some() { + break; + } + } + } + self.enter(*list, saved); + result?; + let sum = || { + values + .iter() + .try_fold(Decimal::ZERO, |acc, v| acc.checked_add(*v)) + .ok_or(Fault) + }; + if matches!(fold, Fold::Min | Fold::Max) + && hir.nodes[id as usize].ty.kind == Kind::Date + { + let best = match fold { + Fold::Min => dates.into_iter().min(), + _ => dates.into_iter().max(), + }; + return best.map(V::Date).ok_or(Fault); + } + Ok(match fold { + Fold::Count => V::Num(Decimal::from(kept.len())), + Fold::Sum => V::Num(sum()?), + Fold::Any => V::Bool(decided.unwrap_or(false)), + Fold::All | Fold::None => V::Bool(decided.unwrap_or(true)), + Fold::One => V::Bool(ones == 1), + Fold::Min => V::Num(values.iter().copied().min().ok_or(Fault)?), + Fold::Max => V::Num(values.iter().copied().max().ok_or(Fault)?), + Fold::Avg => V::Num( + sum()? + .checked_div(Decimal::from(values.len())) + .ok_or(Fault)?, + ), + }) + } + Op::FirstMatch { conds, strict } => { + for (i, c) in conds.iter().enumerate() { + match (self.eval(*c), strict) { + (Ok(V::Bool(true)), _) => return Ok(V::Num(Decimal::from(i))), + (Ok(V::Bool(false)), _) | (Ok(_), false) | (Err(_), false) => {} + (Ok(_), true) | (Err(_), true) => return Err(Fault), + } + } + Ok(V::Num(Decimal::from(conds.len()))) + } + Op::Pick(sel, arms) => match self.eval(*sel)? { + V::Num(d) => match usize::try_from(d.mantissa()).ok().and_then(|i| arms.get(i)) { + Some(arm) => self.eval(*arm), + None => Ok(V::Null), + }, + _ => Err(Fault), + }, + Op::Call(func, args) => { + let mut vals = Vec::with_capacity(args.len()); + for a in args { + vals.push(self.eval(*a)?); + } + let text = |t: &[u8]| { + std::str::from_utf8(t) + .map(str::to_string) + .map_err(|_| Fault) + }; + match (func, vals.as_slice()) { + (Func::StartsWith, [V::Text(a), V::Text(b)]) => { + Ok(V::Bool(a.starts_with(&b[..]))) + } + (Func::EndsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.ends_with(&b[..]))), + (Func::Contains, [V::Text(a), V::Text(b)]) => { + Ok(V::Bool(text(a)?.contains(text(b)?.as_str()))) + } + (Func::Matches, [V::Text(a), V::Text(b)]) => Ok(V::Bool( + Pattern::new(&text(b)?) + .map_err(|_| Fault)? + .is_match(&text(a)?), + )), + (Func::Upper, [V::Text(a)]) => { + Ok(V::Text(Cow::Owned(text(a)?.to_uppercase().into_bytes()))) + } + (Func::Lower, [V::Text(a)]) => { + Ok(V::Text(Cow::Owned(text(a)?.to_lowercase().into_bytes()))) + } + (Func::Trim, [V::Text(a)]) => { + Ok(V::Text(Cow::Owned(text(a)?.trim().as_bytes().to_vec()))) + } + (Func::Len, [V::Text(a)]) => Ok(V::Num(Decimal::from(a.len()))), + (Func::Min | Func::Max, items) if node.ty.kind == Kind::Date => { + let dates = items + .iter() + .map(|v| { + if let V::Date(d) = v { + Ok(*d) + } else { + Err(Fault) + } + }) + .collect::, _>>()?; + let best = match func { + Func::Min => dates.into_iter().min(), + _ => dates.into_iter().max(), + }; + best.map(V::Date).ok_or(Fault) + } + (Func::Min, items) => items + .iter() + .map(|v| { + if let V::Num(d) = v { + Ok(*d) + } else { + Err(Fault) + } + }) + .collect::, _>>()? + .into_iter() + .min() + .map(V::Num) + .ok_or(Fault), + (Func::Max, items) => items + .iter() + .map(|v| { + if let V::Num(d) = v { + Ok(*d) + } else { + Err(Fault) + } + }) + .collect::, _>>()? + .into_iter() + .max() + .map(V::Num) + .ok_or(Fault), + (func, [V::Num(d)]) => Ok(V::Num(Exact::func(*func, *d))), + _ => Err(Fault), + } + } + Op::Str(a) => Ok(V::Text(Cow::Owned(match self.eval(*a)? { + V::Null => b"null".to_vec(), + V::Num(d) => d.to_string().into_bytes(), + V::Bool(b) => b.to_string().into_bytes(), + V::Text(t) => t.into_owned(), + V::Date(d) => d.to_string().into_bytes(), + V::Code(_) => return Err(Fault), + }))), + Op::Host(host, args) => { + let mut vals = Vec::with_capacity(args.len()); + for a in args { + vals.push(self.eval(*a)?); + } + let mut given = Vec::with_capacity(vals.len()); + for v in &vals { + given.push(match v { + V::Null => Given::Null, + V::Num(d) => Given::Num(*d), + V::Bool(b) => Given::Bool(*b), + V::Text(t) => Given::Str(std::str::from_utf8(t).map_err(|_| Fault)?), + V::Date(d) => Given::Date(*d), + V::Code(_) => return Err(Fault), + }); + } + match Builtins::raw(host.builtin().ok_or(Fault)?, &given).map_err(|_| Fault)? { + Out::Num(n) => Ok(V::Num(n)), + Out::Bool(b) => Ok(V::Bool(b)), + Out::Str(s) => Ok(V::Text(Cow::Owned(s.as_bytes().to_vec()))), + Out::Date(d) => Ok(V::Date(d)), + Out::Var(Variable::Null) => Ok(V::Null), + Out::Var(_) => Err(Fault), + } + } + Op::Clock(Clock::Now, _) => Ok(V::Date(self.feeds.now)), + Op::Clock(clock, args) => { + let mut vals = Vec::with_capacity(args.len()); + for a in args { + vals.push(self.eval(*a)?); + } + let parsed = |t: &[u8]| { + std::str::from_utf8(t) + .map(Date::from_text) + .map_err(|_| Fault) + }; + match (clock, vals.as_slice()) { + (Clock::Coerce, [V::Text(t)]) => match parsed(t)? { + d if d.is_valid() => Ok(V::Date(d)), + _ => Err(Fault), + }, + (Clock::Strict, [V::Date(d)]) if d.is_valid() => Ok(V::Date(*d)), + (Clock::Text, [V::Null]) => Ok(V::Null), + (Clock::Text, [V::Date(d)]) => d + .rendered() + .map(|t| V::Text(Cow::Owned(t.into_bytes()))) + .ok_or(Fault), + (Clock::Matches, [V::Date(d), V::Text(t)]) => { + Ok(V::Bool(d.is_valid() && parsed(t)? == *d)) + } + (Clock::Matches, [V::Date(d), V::Date(e)]) => { + Ok(V::Bool(d.is_valid() && d == e)) + } + (Clock::Matches, [_, _]) => Ok(V::Bool(false)), + _ => Err(Fault), + } + } + Op::Decode(a) => match (self.eval(*a)?, hir.nodes[*a as usize].ty.kind) { + (V::Null, _) => Ok(V::Null), + (V::Code(c), Kind::Code(d)) => hir + .dict(d) + .text(c) + .map(|t| V::Text(Cow::Owned(t.as_bytes().to_vec()))) + .ok_or(Fault), + _ => Err(Fault), + }, + Op::Concat(parts) => { + let mut out = Vec::new(); + for p in parts { + match self.eval(*p)? { + V::Text(t) => out.extend_from_slice(&t), + _ => return Err(Fault), + } + } + Ok(V::Text(Cow::Owned(out))) + } + } + } +} diff --git a/core/expression/src/typed/tests/lower.rs b/core/expression/src/typed/tests/lower.rs new file mode 100644 index 00000000..ae4db76e --- /dev/null +++ b/core/expression/src/typed/tests/lower.rs @@ -0,0 +1,625 @@ +use crate::lane::Fusion; +use crate::typed::tests::data::{ColSpec, Enc, ListSpec, Mock, Spec}; +use crate::typed::{ + Class, DictKind, Hir, Hit, Kind, Lit, Lowering, Op, Program, Resolve, Resolved, TableRule, + TableSpec, +}; +use std::sync::Arc; + +struct Anchor; + +enum Unit { + Fused(Vec), + Table(TableSpec), +} + +impl Anchor { + fn spec() -> Spec { + Spec { + columns: vec![ + ColSpec::new("customer.age", Class::Num, Enc::Scaled), + ColSpec::new("customer.income", Class::Num, Enc::Scaled), + ColSpec::new("customer.tier", Class::Text, Enc::Text), + ColSpec::new("customer.rate", Class::Num, Enc::Scaled), + ], + lists: vec![ListSpec { + parent: None, + path: "customer.accounts", + alias: "account", + fields: vec![ + ColSpec::new("balance", Class::Num, Enc::Scaled), + ColSpec::new("kind", Class::Text, Enc::Text), + ColSpec::new("active", Class::Bool, Enc::Bool), + ColSpec::new("fee", Class::Num, Enc::Scaled), + ColSpec::new("label", Class::Text, Enc::Text), + ], + }], + } + } + + fn out(key: &str, source: &str) -> Unit { + Unit::Fused(vec![Fusion::Output { + key: key.to_string(), + source: source.to_string(), + }]) + } + + fn member() -> Vec { + vec![ + Self::out("account.fee", "account.balance * customer.rate / 100 * (account.kind == 'loan' ? 2 : 1)"), + Self::out("account.label", "((account.kind == 'savings') == true) ? ('S') : (((account.kind == 'checking') == true) ? ('C') : ('L'))"), + ] + } + + fn root() -> Vec { + let cell = |cell: &str| (!cell.is_empty()).then(|| cell.to_string()); + let rule = |tier: &str, risk: &str, value: &str| TableRule { + cells: vec![cell(tier), cell(risk)], + values: vec![Some(value.to_string())], + }; + vec![ + Self::out("customer.total", "sum(map(filter(customer.accounts, #.active), #.balance))"), + Self::out("customer.fees", "sum(map(customer.accounts, #.fee))"), + Self::out( + "customer.risk", + "((customer.total > customer.income * 2) == true) ? ('high') : (((customer.total > customer.income) == true) ? ('mid') : ('low'))", + ), + Unit::Table(TableSpec { + inputs: vec![Some("customer.tier".to_string()), Some("customer.risk".to_string())], + outputs: vec!["customer.discount".to_string()], + rules: vec![ + rule("'gold'", "'low'", "0.15"), + rule("'gold'", "'mid'", "0.1"), + rule("'silver'", "'low'", "0.1"), + rule("'silver'", "'mid'", "0.05"), + rule("", "'low'", "0.02"), + rule("", "", "0"), + ], + hit: Hit::Strict, + selector: false, + }), + Self::out("customer.net", "customer.total - customer.fees - customer.discount"), + Unit::Fused(vec![ + Fusion::Output { key: String::new(), source: "customer.age >= 18".to_string() }, + Fusion::Output { key: String::new(), source: "customer.risk != 'high'".to_string() }, + ]), + ] + } + + fn lower(member: bool, units: Vec) -> Hir { + let spec = Self::spec(); + let mut lowering = Lowering::new(member.then_some(("account", "customer.accounts"))); + let mut mock = Mock { + spec: &spec, + member: member.then_some(0), + }; + for unit in units { + match unit { + Unit::Fused(entries) => lowering.unit(&entries, &mut mock), + Unit::Table(table) => lowering.table(&table, &mut mock), + } + .expect("unit"); + } + lowering.finish() + } + + const MEMBER: &'static str = r#"column 0 customer.rate : num/*? +list 0 customer.accounts as account + field 0 balance : num/*? + field 1 kind : text? +dict 0 Classes ["loan", "savings", "checking"] +dict 1 Literals ["C", "L", "S"] +%0 = field 0.balance : num/*? @elem0 +%1 = column customer.rate : num/*? @row +%2 = parent %1 : num/*? @elem0 +%3 = mul %0, %2 : num/* @elem0 +%4 = const 100 : num/0 @row +%5 = div %3, %4 : num/* @elem0 +%6 = field 0.kind : text? @elem0 +%7 = classify %6 dict 0 : code#0? @elem0 +%8 = const code#0:0 : code#0 @row +%9 = eq %7, %8 : bool @elem0 +%10 = const 2 : num/0 @row +%11 = const 1 : num/0 @row +%12 = if %9 then %10 else %11 : num/0 @elem0 +%13 = mul %5, %12 : num/* @elem0 +%14 = const code#0:1 : code#0 @row +%15 = eq %7, %14 : bool @elem0 +%16 = const code#0:2 : code#0 @row +%17 = eq %7, %16 : bool @elem0 +%18 = const code#1:0 : code#1 @row +%19 = const code#1:1 : code#1 @row +%20 = if %17 then %18 else %19 : code#1 @elem0 +%21 = const code#1:2 : code#1 @row +%22 = if %15 then %21 else %20 : code#1 @elem0 +out 0 "account.fee" = %13 : num/* @elem0 +out 1 "account.label" = %22 : code#1 @elem0 +"#; + + const ROOT: &'static str = r#"column 0 customer.income : num/*? +column 1 customer.tier : text? +column 2 customer.age : num/*? +list 0 customer.accounts as - + field 0 balance : num/*? + field 1 kind : text? + field 2 active : bool? + field 3 fee : num/*? + field 4 label : text? +dict 0 Literals ["mid", "low", "high"] +dict 1 Classes ["gold", "silver"] +%0 = field 0.active : bool? @elem0 +%1 = field 0.balance : num/*? @elem0 +%2 = fold sum list 0 filter %0 value %1 : num/* @row +%3 = field 0.fee : num/*? @elem0 +%4 = fold sum list 0 filter - value %3 : num/* @row +%5 = column customer.income : num/*? @row +%6 = const 2 : num/0 @row +%7 = mul %5, %6 : num/* @row +%8 = gt %2, %7 : bool @row +%9 = const true : bool @row +%10 = gt %2, %5 : bool @row +%11 = const code#0:0 : code#0 @row +%12 = const code#0:1 : code#0 @row +%13 = if %10 then %11 else %12 : code#0 @row +%14 = const code#0:2 : code#0 @row +%15 = if %8 then %14 else %13 : code#0 @row +%16 = column customer.tier : text? @row +%17 = classify %16 dict 1 : code#1? @row +%18 = const code#1:0 : code#1 @row +%19 = eq %17, %18 : bool @row +%20 = eq %15, %12 : bool @row +%21 = and %19, %20 : bool @row +%22 = eq %15, %11 : bool @row +%23 = and %19, %22 : bool @row +%24 = const code#1:1 : code#1 @row +%25 = eq %17, %24 : bool @row +%26 = and %25, %20 : bool @row +%27 = and %25, %22 : bool @row +%28 = firstmatch strict [%21, %23, %26, %27, %20, %9] : num/0 @row +%29 = const 0.15 : num/2 @row +%30 = const 0.1 : num/1 @row +%31 = const 0.05 : num/2 @row +%32 = const 0.02 : num/2 @row +%33 = const 0 : num/0 @row +%34 = pick %28 [%29, %30, %30, %31, %32, %33] : num/* @row +%35 = sub %2, %4 : num/* @row +%36 = sub %35, %34 : num/* @row +%37 = column customer.age : num/*? @row +%38 = const 18 : num/0 @row +%39 = ge %37, %38 : bool @row +%40 = ne %15, %14 : bool @row +out 0 "customer.total" = %2 : num/* @row +out 1 "customer.fees" = %4 : num/* @row +out 2 "customer.risk" = %15 : code#0 @row +out 3 "customer.discount" = %34 : num/* @row +out 4 "customer.net" = %36 : num/* @row +out 5 "" = %39 : bool @row +out 6 "" = %40 : bool @row +"#; +} + +struct Probe { + asked: Vec, +} + +impl Resolve for Probe { + fn path(&mut self, path: &str) -> Resolved { + self.asked.push(path.to_string()); + match path { + "c.n" | "c.m" => Resolved::Column(Class::Num), + "c.t" | "c.u" => Resolved::Column(Class::Text), + "c.b" => Resolved::Column(Class::Bool), + "c.f" => Resolved::Column(Class::Num), + "c.weird" => Resolved::Unsupported, + "c.xs" => Resolved::List { + fields: vec![(Arc::from(""), Class::Num)], + }, + "c.ts" => Resolved::List { + fields: vec![(Arc::from(""), Class::Text)], + }, + "c.items" => Resolved::List { + fields: vec![(Arc::from("q"), Class::Num), (Arc::from("n"), Class::Text)], + }, + _ => Resolved::Absent, + } + } + + fn alias(&mut self, _: &str) -> Resolved { + Resolved::Unsupported + } + + fn nested(&mut self, chain: &[&str]) -> Resolved { + match chain { + ["c.items", "subs", ..] => Resolved::List { + fields: vec![(Arc::from("v"), Class::Num)], + }, + _ => Resolved::Unsupported, + } + } +} + +impl Probe { + fn new() -> Self { + Self { asked: Vec::new() } + } + + fn unit( + lowering: &mut Lowering, + probe: &mut Probe, + key: &str, + source: &str, + ) -> Result<(), crate::typed::Unsupported> { + lowering.unit( + &[Fusion::Output { + key: key.to_string(), + source: source.to_string(), + }], + probe, + ) + } +} + +#[test] +fn anchor_member_group() { + let hir = Anchor::lower(true, Anchor::member()); + assert_eq!(hir.to_string(), Anchor::MEMBER); +} + +#[test] +fn anchor_root_group() { + let hir = Anchor::lower(false, Anchor::root()); + assert_eq!(hir.to_string(), Anchor::ROOT); +} + +#[test] +fn unit_rolls_back() { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit(&mut lowering, &mut probe, "c.x", "c.n + 1").expect("first"); + let failed = lowering.unit( + &[ + Fusion::Output { + key: "c.y".to_string(), + source: "c.m * 2".to_string(), + }, + Fusion::Output { + key: "c.z".to_string(), + source: "c.t == 'a' ? c.weird : 1".to_string(), + }, + ], + &mut probe, + ); + assert!(failed.is_err()); + assert_eq!((lowering.units(), lowering.outputs()), (1, 1)); + Probe::unit(&mut lowering, &mut probe, "c.w", "c.y ?? c.x").expect("third"); + let hir = lowering.finish(); + assert_eq!(hir.outputs.len(), 2); + assert!( + hir.schema + .columns + .iter() + .all(|c| c.path != "c.m" && c.path != "c.t"), + "{hir}" + ); + assert!(hir.schema.dicts.is_empty(), "{hir}"); + assert!(probe.asked.contains(&"c.y".to_string())); +} + +#[test] +fn text_compares_classify() { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit(&mut lowering, &mut probe, "c.a", "c.t == 'gold'").expect("eq"); + Probe::unit( + &mut lowering, + &mut probe, + "c.b", + "c.t in ['gold', 'silver']", + ) + .expect("in"); + Probe::unit(&mut lowering, &mut probe, "c.c", "'x' != c.t").expect("ne"); + Probe::unit(&mut lowering, &mut probe, "c.d", "c.t == null").expect("null"); + Probe::unit(&mut lowering, &mut probe, "c.e", "c.u not in ['a']").expect("other column"); + let hir = lowering.finish(); + let classify: Vec<_> = hir + .nodes + .iter() + .filter(|n| matches!(n.op, Op::Classify(..))) + .collect(); + assert_eq!(classify.len(), 2, "{hir}"); + assert!( + hir.schema.dicts.iter().all(|d| d.kind == DictKind::Classes), + "{hir}" + ); + assert_eq!( + hir.schema.dicts[0] + .values + .iter() + .map(|v| v.as_ref()) + .collect::>(), + ["gold", "silver", "x"] + ); + assert!(hir.outputs.iter().all(|o| o.ty.kind == Kind::Bool)); +} + +#[test] +fn strict_rules_lower_to_firstmatch() { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + let table = TableSpec { + inputs: vec![Some("c.n".to_string())], + outputs: vec!["c.r".to_string()], + rules: vec![ + TableRule { + cells: vec![Some("> 5".to_string())], + values: vec![Some("'hi'".to_string())], + }, + TableRule { + cells: vec![None], + values: vec![Some("'lo'".to_string())], + }, + ], + hit: Hit::Strict, + selector: false, + }; + lowering.table(&table, &mut probe).expect("rules"); + let hir = lowering.finish(); + assert!( + hir.nodes + .iter() + .any(|n| matches!(n.op, Op::FirstMatch { strict: true, .. })), + "{hir}" + ); + assert!(matches!(hir.outputs[0].ty.kind, Kind::Code(_))); + assert!(!hir.outputs[0].ty.nullable, "{hir}"); +} + +#[test] +fn unsupported_shapes() { + let cases = [ + ("text ordering", "c.t > 'a'"), + ("text plus number", "c.t + 1"), + ("text plus null", "c.t + null"), + ("pattern from a column", "matches(c.t, c.u)"), + ("invalid pattern", "matches(c.t, '(')"), + ("string of a list", "string(c.xs)"), + ("empty template", "``"), + ("unsupported path", "c.weird + 1"), + ("null arithmetic", "c.absent + 1"), + ("variable exponent", "c.n ^ c.n"), + ("fractional exponent", "c.n ^ 0.5"), + ("round to variable places", "round(c.n, c.n)"), + ("bool of a number", "bool(c.n)"), + ("min of nothing", "min([])"), + ("closure over a column", "sum(map(c.n, #))"), + ]; + for (what, source) in cases { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.o", source).is_err(), + "{what}: {source}" + ); + assert_eq!(lowering.outputs(), 0); + } + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit(&mut lowering, &mut probe, "c.o", "c.n + 1").expect("write"); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.p", "c.o.x").is_err(), + "read inside a written value" + ); + assert!(Probe::unit(&mut lowering, &mut probe, "c.o.x", "1").is_ok()); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.q", "c.o").is_err(), + "read of a partially written value" + ); +} + +#[test] +fn text_shapes() { + let supported = [ + "c.t == c.u", + "c.t", + "c.b ? c.t : 'x'", + "(c.n > 1 ? 'a' : 'b') == c.t", + "string(c.n)", + "`${c.t}:${c.n}`", + "c.t + '-' + upper(c.u)", + "contains(lower(c.t), 'x')", + "trim(c.t) in ['a', 'b']", + "matches(c.t, '^a+$')", + "c.t ?? 'none'", + "map(c.items, #.n)", + "count(c.items, #.n == c.t)", + "c.t in c.ts", + "map(c.ts, upper(#))", + "len(c.t + c.u)", + ]; + for source in supported { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.o", source).is_ok(), + "{source}" + ); + let hir = lowering.finish(); + Program::new(hir.clone()).unwrap_or_else(|e| panic!("{source}: {e}\n{hir}")); + } + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit( + &mut lowering, + &mut probe, + "c.a", + "'a' + 'b' + string(1.50) + `x${true}`", + ) + .expect("constant"); + Probe::unit( + &mut lowering, + &mut probe, + "c.b", + "upper('ß') + trim(' q ')", + ) + .expect("constant map"); + let hir = lowering.finish(); + let dict = &hir.schema.dicts[0]; + let texts: Vec<&str> = hir + .outputs + .iter() + .map(|o| match hir.node(o.node).op { + Op::Const(Lit::Code(_, c)) => dict.text(c).unwrap_or("?"), + _ => "?", + }) + .collect(); + assert_eq!(texts, ["ab1.50xtrue", "SSq"], "{hir}"); +} + +#[test] +fn list_shapes() { + let supported = [ + "sum(c.xs)", + "filter(c.xs, # > 1)", + "map(c.items, #.q * 2)", + "c.n in c.xs", + "'a' in c.ts", + "contains(c.xs, 1)", + "count(filter(c.items, #.q > 1), #.q < 5)", + "sum(map(c.items, sum(map(#.subs, #.v))))", + "c.xs ?? []", + "len(filter(c.xs, # > 0))", + ]; + for source in supported { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.o", source).is_ok(), + "{source}" + ); + let hir = lowering.finish(); + Program::new(hir.clone()).unwrap_or_else(|e| panic!("{source}: {e}\n{hir}")); + } + let unsupported = [ + ( + "filter over a computed map", + "filter(map(c.xs, # * 2), # > 1)", + ), + ( + "quantifier over a computed map", + "some(map(c.xs, # * 2), # > 1)", + ), + ("membership in a computed map", "1 in map(c.xs, # * 2)"), + ("objects as values", "filter(c.items, #.q > 1)"), + ("sum of objects", "sum(c.items)"), + ("list as a scalar", "c.xs + 1"), + ( + "nested too deep", + "sum(map(c.items, sum(map(#.subs, sum(map(#.deep, sum(map(#.deeper, #.v))))))))", + ), + ]; + for (what, source) in unsupported { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.o", source).is_err(), + "{what}: {source}" + ); + assert_eq!(lowering.outputs(), 0); + assert!( + lowering.finish().schema.lists.is_empty(), + "{what}: rolled back" + ); + } +} + +#[test] +fn absent_paths_read_null() { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit(&mut lowering, &mut probe, "c.o", "c.missing ?? c.n").expect("coalesce"); + Probe::unit(&mut lowering, &mut probe, "c.p", "c.missing == null").expect("compare"); + let hir = lowering.finish(); + assert_eq!(hir.schema.columns.len(), 1, "{hir}"); + assert_eq!(probe.asked.iter().filter(|p| *p == "c.missing").count(), 1); +} + +#[test] +fn date_shapes() { + let supported = [ + "d(c.t)", + "d()", + "d(c.n, 'Europe/Berlin')", + "d(c.t).add(c.n, 'day').format('%Y-%m-%d')", + "d(c.t).diff(c.u, 'month')", + "d(c.t) < d()", + "c.t >= d('2024-01-01')", + "d(c.t) == c.u", + "d(c.t) in [d('2024-01-01'), '2024-02-01', null]", + "d(c.t) in [d('2024-01-01')..d('2024-12-31'))", + "`${d(c.t)}`", + "'at ' + d(c.t)", + "count(c.ts, # < d())", + "max(map(c.ts, d(#)))", + "min([d(c.t), d(c.u)])", + "c.b ? d(c.t) : null", + "year(c.t) + date(c.n)", + "dateString(d(c.t))", + ]; + for source in supported { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.o", source).is_ok(), + "{source}" + ); + let hir = lowering.finish(); + Program::new(hir.clone()).unwrap_or_else(|e| panic!("{source}: {e}\n{hir}")); + } + let unsupported = [ + ("method on text", "c.t.year()"), + ("format from a column", "d(c.t).format(c.u)"), + ("invalid format", "d(c.t).format('%Q')"), + ("method arity", "d(c.t).add()"), + ("constructor arity", "d(c.t, 'UTC', 1)"), + ("ordering with a number", "d(c.t) < c.n"), + ("date plus number", "d(c.t) + 1"), + ("text interval", "c.t in [d('2024-01-01')..d('2024-12-31')]"), + ("mixed branches", "c.b ? d(c.t) : c.t"), + ("non-literal set item", "d(c.t) in [d(c.u)]"), + ]; + for (what, source) in unsupported { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!( + Probe::unit(&mut lowering, &mut probe, "c.o", source).is_err(), + "{what}: {source}" + ); + } + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit( + &mut lowering, + &mut probe, + "c.a", + "d('2024-01-31T10:00:00Z').add(1, 'month').format('%Y-%m-%d')", + ) + .expect("constant method"); + Probe::unit(&mut lowering, &mut probe, "c.b", "date('2024-01-01')").expect("constant legacy"); + Probe::unit(&mut lowering, &mut probe, "c.c", "d('nope').isValid()").expect("invalid constant"); + Probe::unit(&mut lowering, &mut probe, "c.d", "date('now')").expect("legacy now"); + let hir = lowering.finish(); + let consts: Vec = hir + .outputs + .iter() + .map(|o| match &hir.node(o.node).op { + Op::Const(Lit::Code(d, c)) => hir.dict(*d).text(*c).unwrap_or("?").to_string(), + Op::Const(lit) => lit.to_string(), + op => format!("{op:?}"), + }) + .collect(); + assert_eq!(consts[..3], ["2024-02-29", "1704067200", "false"], "{hir}"); + assert!( + matches!(hir.node(hir.outputs[3].node).op, Op::Host(..)), + "{hir}" + ); +} diff --git a/core/expression/src/typed/tests/mod.rs b/core/expression/src/typed/tests/mod.rs new file mode 100644 index 00000000..1de77bd8 --- /dev/null +++ b/core/expression/src/typed/tests/mod.rs @@ -0,0 +1,8 @@ +mod data; +mod exact; +mod interp; +mod lower; +mod num; +mod oracle; +mod scale; +mod workload; diff --git a/core/expression/src/typed/tests/num.rs b/core/expression/src/typed/tests/num.rs new file mode 100644 index 00000000..be13300a --- /dev/null +++ b/core/expression/src/typed/tests/num.rs @@ -0,0 +1,215 @@ +use crate::lane::scaled::Scaled; +use crate::typed::Dec; +use rust_decimal::Decimal; +use std::cmp::Ordering; + +struct Gen(u64); + +impl Gen { + fn next(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n + } + + fn sign(&mut self) -> i64 { + if self.next(2) == 0 { + 1 + } else { + -1 + } + } + + fn mantissa(&mut self) -> i64 { + match self.next(10) { + 0 | 1 => 0, + 2 => i64::MAX - self.next(3) as i64, + 3 => i64::MIN + self.next(3) as i64, + 4 => Dec::POW10[self.next(19) as usize] * self.sign(), + 5 => (self.next(1 << 62) as i64) * self.sign(), + 6 => (self.next(1000) as i64 * 10) * self.sign(), + _ => self.next(20_000) as i64 - 10_000, + } + } + + fn scale(&mut self) -> u8 { + match self.next(8) { + 0 => 28, + 1 => self.next(29) as u8, + _ => self.next(4) as u8, + } + } + + fn dec(&mut self) -> Dec { + Dec::new(self.mantissa(), self.scale()) + } +} + +struct Exact; + +impl Exact { + fn same(got: Dec, want: Decimal) -> bool { + Scaled::parts(&want) == Some((got.mant, got.scale)) + && got.decimal().to_string() == want.to_string() + } +} + +#[test] +fn num_matches_rust_decimal() { + let mut g = Gen(0xA5A5_5A5A_1234_5678); + let mut checked = [0usize; 5]; + for _ in 0..1_000_000 { + let (a, b) = (g.dec(), g.dec()); + let (x, y) = (a.decimal(), b.decimal()); + let ops: [(Result, Option); 3] = [ + (a.checked_add(b), x.checked_add(y)), + (a.checked_sub(b), x.checked_sub(y)), + (a.checked_mul(b), x.checked_mul(y)), + ]; + for (k, (got, want)) in ops.into_iter().enumerate() { + if let Ok(got) = got { + let want = want.unwrap_or_else(|| { + panic!("op {k}: {x} {y} -> {got} but rust_decimal overflows") + }); + assert!( + Exact::same(got, want), + "op {k}: {x} {y} -> {}e-{} vs {want}", + got.mant, + got.scale + ); + checked[k] += 1; + } + } + match a.checked_div(b) { + Ok(Some(q)) => { + let want = x + .checked_div(y) + .unwrap_or_else(|| panic!("{x} / {y} -> {q} but rust_decimal fails")); + assert!( + Exact::same(q, want), + "{x} / {y} -> {}e-{} vs {want}", + q.mant, + q.scale + ); + checked[3] += 1; + } + Ok(None) => assert!(b.is_zero(), "{x} / {y} gave null"), + Err(_) => assert!(!b.is_zero(), "{x} / {y} faulted on zero"), + } + match a.checked_neg() { + Ok(n) => assert!(Exact::same(n, -x), "-{x}"), + Err(_) => assert!(a.is_zero() || a.mant == i64::MIN, "-{x} faulted"), + } + assert_eq!(a.compare(b), x.cmp(&y), "{x} <=> {y}"); + assert_eq!(a.eq_value(b), x == y, "{x} == {y}"); + checked[4] += 1; + } + assert!(checked.iter().all(|c| *c > 100_000), "{checked:?}"); +} + +#[test] +fn powers_of_ten_divide_like_rust_decimal() { + let mut g = Gen(0x0F0F_F0F0_DEAD_BEEF); + let mut checked = 0usize; + for _ in 0..1_000_000 { + let a = g.dec(); + let k = g.next(10) as u32; + let by = Dec::new(Dec::POW10[k as usize], g.scale()); + assert_eq!(by.power(), Some(k)); + let want = a.decimal().checked_div(by.decimal()); + match a.checked_div(by) { + Ok(Some(q)) => { + assert!( + want.is_some_and(|w| Exact::same(q, w)), + "{a} / {by} -> {}e-{} vs {want:?}", + q.mant, + q.scale + ); + checked += 1; + } + Ok(None) => panic!("{a} / {by} gave null"), + Err(_) => {} + } + } + assert!(checked > 500_000, "{checked}"); +} + +#[test] +fn zero_rules_keep_rust_decimal_scale() { + let cases = [ + (Dec::new(0, 2), Dec::int(5), "5", "-5", "0"), + (Dec::int(5), Dec::new(0, 2), "5", "5", "0"), + (Dec::new(0, 2), Dec::new(0, 3), "0.000", "0.000", "0"), + (Dec::new(150, 2), Dec::int(2), "3.50", "-0.50", "3.00"), + ]; + for (a, b, sum, diff, prod) in cases { + assert_eq!( + a.checked_add(b).map(|d| d.to_string()), + Ok(sum.to_string()), + "{a} + {b}" + ); + assert_eq!( + a.checked_sub(b).map(|d| d.to_string()), + Ok(diff.to_string()), + "{a} - {b}" + ); + assert_eq!( + a.checked_mul(b).map(|d| d.to_string()), + Ok(prod.to_string()), + "{a} * {b}" + ); + assert_eq!( + a.checked_add(b).map(|d| d.to_string()), + Ok(a.decimal() + .checked_add(b.decimal()) + .map(|d| d.to_string()) + .unwrap_or_default()) + ); + } + let hundred = Dec::int(100); + assert_eq!( + Dec::int(150) + .checked_div(hundred) + .map(|q| q.map(|q| q.to_string())), + Ok(Some("1.50".to_string())) + ); + assert_eq!( + Dec::int(300) + .checked_div(hundred) + .map(|q| q.map(|q| q.to_string())), + Ok(Some("3".to_string())) + ); + assert_eq!( + Dec::new(0, 4) + .checked_div(hundred) + .map(|q| q.map(|q| q.to_string())), + Ok(Some("0".to_string())) + ); + assert_eq!(Dec::int(1).checked_div(Dec::ZERO), Ok(None)); + assert!(Dec::new(0, 2).checked_neg().is_err()); + assert_eq!(Dec::int(1).compare(Dec::new(100, 2)), Ordering::Equal); +} + +#[test] +fn power_kernel_matches_scaled() { + use crate::typed::kernel::K; + let mut g = Gen(0x1357_9BDF_2468_ACE0); + for round in 0..2_000_000u32 { + let m = match round % 4 { + 0 => g.mantissa() % 1_000_000, + 1 => (g.mantissa() % 100_000) * Dec::POW10[g.next(8) as usize], + 2 => ((g.mantissa() % 4096) << 24) * Dec::POW10[g.next(4) as usize], + _ => g.mantissa(), + }; + let (s, by, k) = (g.scale(), g.scale(), g.next(10) as u32); + let (q, t, slow) = K::div_pow(m, s as i32 - by as i32, k); + if !slow { + assert_eq!( + Some((q, t)), + Scaled::divide_power((m, s), k, by), + "{m}e-{s} / 10^{k}e-{by}" + ); + } + } +} diff --git a/core/expression/src/typed/tests/oracle.rs b/core/expression/src/typed/tests/oracle.rs new file mode 100644 index 00000000..ce58feb2 --- /dev/null +++ b/core/expression/src/typed/tests/oracle.rs @@ -0,0 +1,304 @@ +use crate::compiler::Opcode; +use crate::typed::tests::workload::{Block, Dialect, Workload}; +use crate::typed::{Hir, Scope}; +use crate::variable::Variable; +use crate::Isolate; +use rust_decimal::Decimal; +use std::fmt; +use std::sync::Arc; + +type Code = Arc<[Opcode]>; + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Val { + Null, + Num(Decimal), + Bool(bool), + Str(String), + List(Vec), + Other(String), +} + +pub(crate) type RowResult = Result, String>; + +struct TableRule { + cells: Vec>, + values: Vec>, +} + +struct Target { + name: String, + member: Option<(String, String)>, +} + +enum Step { + Expr { + key: String, + code: Code, + }, + Table { + keys: Vec, + inputs: Vec, + rules: Vec, + }, +} + +pub(crate) struct Oracle { + dialect: Dialect, + each: Option<(String, String)>, + steps: Vec, + outputs: Vec, +} + +impl Val { + pub(crate) fn of(value: &Variable) -> Val { + match value { + Variable::Null => Val::Null, + Variable::Number(n) => Val::Num(*n), + Variable::Bool(b) => Val::Bool(*b), + Variable::String(s) => Val::Str(s.to_string()), + Variable::Array(items) => Val::List(items.borrow().iter().map(Val::of).collect()), + other => Val::Other(format!("{}", other.to_value())), + } + } +} + +impl fmt::Display for Val { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Val::Null => write!(f, "null"), + Val::Num(n) => write!(f, "{n}"), + Val::Bool(b) => write!(f, "{b}"), + Val::Str(s) => write!(f, "{s:?}"), + Val::List(items) => write!( + f, + "[{}]", + items + .iter() + .map(|v| v.to_string()) + .collect::>() + .join(", ") + ), + Val::Other(s) => write!(f, "<{s}>"), + } + } +} + +impl Oracle { + pub(crate) fn new(workload: &Workload, hir: &Hir) -> Self { + let mut isolate = Isolate::new(); + let mut standard = |source: &str| -> Code { + isolate + .compile_standard(source) + .map(|e| e.bytecode().clone()) + .expect("standard source") + }; + let mut steps = Vec::with_capacity(workload.blocks.len()); + for block in &workload.blocks { + steps.push(match block { + Block::Expr { key, source } => Step::Expr { + key: key.clone(), + code: standard(source), + }, + Block::Table { + inputs, + outputs, + rules, + } => { + let inputs = inputs.iter().map(|s| standard(s)).collect(); + let mut compiled = Vec::with_capacity(rules.len()); + for rule in rules { + let cells = rule + .cells + .iter() + .map(|cell| match cell.trim().is_empty() { + true => None, + false => Some( + Isolate::new() + .compile_unary(cell) + .map(|e| e.bytecode().clone()) + .expect("unary cell"), + ), + }) + .collect(); + let values = (0..outputs.len()) + .map(|j| { + let source = rule.values.get(j).map(String::as_str).unwrap_or(""); + (!source.trim().is_empty()).then(|| standard(source)) + }) + .collect(); + compiled.push(TableRule { cells, values }); + } + Step::Table { + keys: outputs.clone(), + inputs, + rules: compiled, + } + } + }); + } + let each = workload + .member + .and_then(|m| workload.spec.lists.get(m)) + .map(|l| (l.path.to_string(), l.alias.to_string())); + let mut outputs = Vec::with_capacity(hir.outputs.len()); + for o in &hir.outputs { + let member = match (o.scope, &each) { + (Scope::Elem(_), Some((path, alias))) => { + let field = o + .name + .strip_prefix(&format!("{alias}.")) + .expect("member output") + .to_string(); + Some((path.clone(), field)) + } + _ => None, + }; + outputs.push(Target { + name: o.name.clone(), + member, + }); + } + Self { + dialect: workload.dialect, + each, + steps, + outputs, + } + } + + fn hit<'r>( + &self, + isolate: &mut Isolate, + inputs: &[Code], + rules: &'r [TableRule], + ) -> Result, String> { + for rule in rules { + let mut matched = true; + for (cell, input) in rule.cells.iter().zip(inputs) { + let Some(cell) = cell else { + continue; + }; + let outcome = isolate + .run_compiled(input) + .map_err(|e| e.to_string()) + .and_then(|value| { + let _ = isolate.set_reference_value(value); + isolate.run_unary_compiled(cell).map_err(|e| e.to_string()) + }); + let pass = match (outcome, self.dialect) { + (Ok(pass), _) => pass, + (Err(_), Dialect::Graph) => false, + (Err(e), Dialect::Policy) => return Err(e), + }; + if !pass { + matched = false; + break; + } + } + if matched { + return Ok(Some(rule)); + } + } + Ok(None) + } + + pub(crate) fn run(&self, input: Variable) -> RowResult { + let mut isolate = Isolate::new(); + let result = Variable::empty_object(); + isolate.set_environment(input.shallow_clone()); + for step in &self.steps { + match (step, &self.each) { + (Step::Expr { key, code }, None) => { + let value = isolate.run_compiled(code).map_err(|e| e.to_string())?; + self.write(&mut isolate, &input, &result, key, value); + } + (Step::Expr { key, code }, Some((path, alias))) => { + let items = match input.dot(path) { + Some(Variable::Array(items)) => items.borrow().clone(), + _ => Vec::new(), + }; + for item in items { + let env = Variable::empty_object(); + if let Variable::Object(root) = &input { + for (k, v) in root.borrow().iter() { + env.dot_insert(k, v.shallow_clone()); + } + } + env.dot_insert(alias, item.shallow_clone()); + let mut member = Isolate::new(); + member.set_environment(env.shallow_clone()); + let value = member.run_compiled(code).map_err(|e| e.to_string())?; + env.dot_insert(key, value); + } + } + ( + Step::Table { + keys, + inputs, + rules, + }, + _, + ) => { + let hit = self.hit(&mut isolate, inputs, rules)?; + let mut values = Vec::with_capacity(keys.len()); + match hit { + Some(rule) => { + for code in &rule.values { + values.push(match code { + Some(code) => { + isolate.run_compiled(code).map_err(|e| e.to_string())? + } + None => Variable::Null, + }); + } + } + None => values.resize(keys.len(), Variable::Null), + } + for (key, value) in keys.iter().zip(values) { + self.write(&mut isolate, &input, &result, key, value); + } + } + } + } + let mut row = Vec::with_capacity(self.outputs.len()); + for target in &self.outputs { + row.push(match &target.member { + None => match self.dialect { + Dialect::Policy => input.dot(&target.name).map_or(Val::Null, |v| Val::of(&v)), + Dialect::Graph => result.dot(&target.name).map_or(Val::Null, |v| Val::of(&v)), + }, + Some((list, field)) => match input.dot(list) { + Some(Variable::Array(items)) => Val::List( + items + .borrow() + .iter() + .map(|item| item.dot(field).map_or(Val::Null, |v| Val::of(&v))) + .collect(), + ), + _ => Val::List(Vec::new()), + }, + }); + } + Ok(row) + } + + fn write( + &self, + isolate: &mut Isolate, + input: &Variable, + result: &Variable, + key: &str, + value: Variable, + ) { + match self.dialect { + Dialect::Policy => { + input.dot_insert(key, value); + } + Dialect::Graph => { + isolate.insert_dollar(key, value.clone()); + result.dot_insert(key, value); + } + } + } +} diff --git a/core/expression/src/typed/tests/scale.rs b/core/expression/src/typed/tests/scale.rs new file mode 100644 index 00000000..75773f4f --- /dev/null +++ b/core/expression/src/typed/tests/scale.rs @@ -0,0 +1,674 @@ +use crate::typed::build::Passes; +use crate::typed::tests::data::{ColSpec, Enc, Frame, ListSpec, Mock, Row, Spec, Value}; +use crate::typed::tests::oracle::{Oracle, Val}; +use crate::typed::tests::workload::{Block, Dialect, Workload}; +use crate::typed::{Class, Data, Dec, Hir, Hit, Lowering, Program, Scope, TableRule, TableSpec}; + +struct Case { + workload: Workload, + hir: Hir, + program: Program, +} + +impl Case { + fn new(spec: Spec, blocks: &[(&str, &str)]) -> Self { + let blocks = blocks + .iter() + .map(|(k, s)| Block::Expr { + key: k.to_string(), + source: s.to_string(), + }) + .collect(); + let workload = Workload { + name: "case", + spec, + dialect: Dialect::Policy, + member: None, + blocks, + }; + let mut lowering = Lowering::new(None); + let mut mock = Mock { + spec: &workload.spec, + member: None, + }; + for block in &workload.blocks { + block + .lower(&mut lowering, &mut mock, Hit::Strict) + .expect("lowering"); + } + let hir = lowering.finish(); + let program = Program::new(hir.clone()).expect("program"); + Self { + workload, + hir, + program, + } + } + + fn nums(names: &[&'static str], enc: Enc) -> Spec { + Spec { + columns: names + .iter() + .map(|n| ColSpec::new(n, Class::Num, enc)) + .collect(), + lists: Vec::new(), + } + } + + fn run(&self, rows: &[Row], select: Option<&[u64]>) -> Vec>> { + let frame = Frame::new(&self.hir, &self.workload.spec, rows, 0); + let mut out = self.program.outputs(); + self.program + .run(&frame.batch(), &mut out, select) + .expect("run"); + (0..rows.len()) + .map(|r| { + (!out.faults().get(r)).then(|| { + out.slots() + .iter() + .map(|s| match (&s.data, s.scope) { + (Data::Num { .. }, Scope::Row) => { + s.decimal(r).map_or("null".to_string(), |d| d.to_string()) + } + (Data::Bool(_), Scope::Row) => { + s.boolean(r).map_or("null".to_string(), |b| b.to_string()) + } + _ => "?".to_string(), + }) + .collect() + }) + }) + .collect() + } + + fn vm(&self, rows: &[Row]) -> Vec>> { + let oracle = Oracle::new(&self.workload, &self.hir); + rows.iter() + .map(|r| { + oracle + .run(r.variable(&self.workload.spec)) + .ok() + .map(|v| v.iter().map(Val::to_string).collect()) + }) + .collect() + } + + fn check(&self, rows: &[Row]) -> Vec>> { + let typed = self.run(rows, None); + let vm = self.vm(rows); + for (r, (t, v)) in typed.iter().zip(&vm).enumerate() { + if let Some(t) = t { + assert_eq!(Some(t), v.as_ref(), "row {r}: {:?}", rows[r]); + } + } + typed + } + + fn d(m: i64, s: u8) -> Value { + Value::Num(Dec::new(m, s)) + } + + fn row(values: &[Value]) -> Row { + Row { + columns: values.to_vec(), + lists: Vec::new(), + } + } +} + +#[test] +fn zero_operand_scale() { + let blocks = [ + ("x.sum", "a + b"), + ("x.diff", "a - b"), + ("x.prod", "a * b"), + ("x.lit", "a + 5"), + ("x.cmp", "a == b"), + ]; + let fixed = [ + Case::row(&[Case::d(0, 2), Case::d(500, 2)]), + Case::row(&[Case::d(150, 2), Case::d(0, 2)]), + Case::row(&[Case::d(0, 2), Case::d(0, 2)]), + ]; + let mixed = [ + Case::row(&[Case::d(0, 2), Case::d(5, 0)]), + Case::row(&[Case::d(5, 0), Case::d(0, 2)]), + Case::row(&[Case::d(0, 2), Case::d(0, 3)]), + Case::row(&[Case::d(150, 2), Case::d(2, 0)]), + ]; + for enc in [Enc::Scaled, Enc::Dec] { + let case = Case::new(Case::nums(&["a", "b"], enc), &blocks); + let out = case.check(&fixed); + assert_eq!( + out[0].as_deref(), + Some(&["5.00", "-5.00", "0", "5", "false"].map(String::from)[..]) + ); + assert_eq!( + out[2].as_deref(), + Some(&["0.00", "0.00", "0", "5", "true"].map(String::from)[..]) + ); + let out = case.check(&mixed); + assert_eq!( + out[0].as_deref(), + Some(&["5", "-5", "0", "5", "false"].map(String::from)[..]) + ); + assert_eq!( + out[1].as_deref(), + Some(&["5", "5", "0", "10", "false"].map(String::from)[..]) + ); + assert_eq!( + out[2].as_deref(), + Some(&["0.000", "0.000", "0", "5", "true"].map(String::from)[..]) + ); + assert_eq!( + out[3].as_deref(), + Some(&["3.50", "-0.50", "3.00", "6.50", "false"].map(String::from)[..]) + ); + } +} + +#[test] +fn division_scale_matches_decimal() { + let blocks = [ + ("x.pow", "a / 100"), + ("x.one", "a / 10"), + ("x.quarter", "a / 4"), + ("x.div", "a / b"), + ("x.zero", "a / 0"), + ]; + let rows: Vec = [ + (150, 0), + (300, 0), + (0, 0), + (1, 0), + (7, 0), + (12345, 2), + (-150, 0), + (15, 1), + (1, 28), + (10, 0), + ] + .iter() + .zip([4, 3, 7, 1, 0, 8, -2, 5, 16, 3]) + .map(|((m, s), b)| Case::row(&[Case::d(*m, *s), Case::d(b, 0)])) + .collect(); + let case = Case::new(Case::nums(&["a", "b"], Enc::Scaled), &blocks); + let out = case.check(&rows); + assert_eq!(out[0].as_ref().map(|v| v[0].as_str()), Some("1.50")); + assert_eq!(out[1].as_ref().map(|v| v[0].as_str()), Some("3")); + assert_eq!(out[2].as_ref().map(|v| v[0].as_str()), Some("0")); + assert_eq!(out[4].as_ref().map(|v| v[3].as_str()), Some("null")); + assert!(out.iter().take(4).all(Option::is_some), "{out:?}"); + let fixed: Vec = (0..200) + .map(|i| Case::row(&[Case::d(i * 37 - 3000, 0), Case::d(i % 9 - 4, 0)])) + .collect(); + case.check(&fixed); +} + +#[test] +fn empty_list_sum_has_scale_zero() { + let spec = Spec { + columns: Vec::new(), + lists: vec![ListSpec { + parent: None, + path: "c.items", + alias: "item", + fields: vec![ + ColSpec::new("fee", Class::Num, Enc::Scaled), + ColSpec::new("on", Class::Bool, Enc::Bool), + ], + }], + }; + let case = Case::new( + spec, + &[ + ("c.sum", "sum(map(c.items, #.fee))"), + ("c.kept", "sum(map(filter(c.items, #.on), #.fee))"), + ], + ); + let item = |m: i64, s: u8, on: bool| vec![Case::d(m, s), Value::Bool(on)]; + let rows = vec![ + Row { + columns: Vec::new(), + lists: vec![Vec::new()], + }, + Row { + columns: Vec::new(), + lists: vec![vec![item(0, 2, true)]], + }, + Row { + columns: Vec::new(), + lists: vec![vec![item(125, 2, false), item(0, 2, true)]], + }, + Row { + columns: Vec::new(), + lists: vec![vec![item(125, 2, false), item(5, 2, false)]], + }, + ]; + let out = case.check(&rows); + let strs = |r: usize| out[r].clone().unwrap_or_default(); + assert_eq!(strs(0), ["0", "0"]); + assert_eq!(strs(1), ["0.00", "0.00"]); + assert_eq!(strs(2), ["1.25", "0.00"]); + assert_eq!(strs(3), ["1.30", "0"]); + let mixed: Vec = rows + .iter() + .cloned() + .chain([Row { + columns: Vec::new(), + lists: vec![vec![item(5, 1, true), item(0, 3, true)]], + }]) + .collect(); + case.check(&mixed); +} + +#[test] +fn dyn_sums_match_vm() { + let spec = Spec { + columns: Vec::new(), + lists: vec![ListSpec { + parent: None, + path: "c.items", + alias: "item", + fields: vec![ + ColSpec::new("fee", Class::Num, Enc::Scaled), + ColSpec::new("on", Class::Bool, Enc::Bool), + ], + }], + }; + let case = Case::new( + spec, + &[ + ("c.sum", "sum(map(c.items, #.fee))"), + ("c.kept", "sum(map(filter(c.items, #.on), #.fee))"), + ], + ); + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut pick = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let mants = [ + 0i64, 1, -1, 5, 15, -15, 150, -150, 1500, 7, 120, -120, 999_999, + ]; + let rows: Vec = (0..900) + .map(|r| { + let len = match r % 97 { + 0 => 700, + 1 => 1100, + _ => pick(9) as usize, + }; + let items = (0..len) + .map(|_| { + vec![ + Case::d(mants[pick(mants.len() as u64) as usize], pick(5) as u8), + Value::Bool(pick(3) != 0), + ] + }) + .collect(); + Row { + columns: Vec::new(), + lists: vec![items], + } + }) + .collect(); + let out = case.check(&rows); + assert!( + out.iter().filter(|r| r.is_none()).count() < rows.len() / 50, + "too many faulted rows" + ); + let cancel = vec![ + Row { + columns: Vec::new(), + lists: vec![vec![ + vec![Case::d(150, 2), Value::Bool(true)], + vec![Case::d(-15, 1), Value::Bool(true)], + vec![Case::d(7, 0), Value::Bool(true)], + ]], + }, + Row { + columns: Vec::new(), + lists: vec![vec![ + vec![Case::d(150, 2), Value::Bool(true)], + vec![Case::d(-15, 1), Value::Bool(true)], + vec![Case::d(0, 3), Value::Bool(true)], + ]], + }, + Row { + columns: Vec::new(), + lists: vec![vec![ + vec![Case::d(0, 3), Value::Bool(true)], + vec![Case::d(0, 1), Value::Bool(false)], + ]], + }, + Row { + columns: Vec::new(), + lists: vec![vec![ + vec![Case::d(i64::MAX, 0), Value::Bool(true)], + vec![Case::d(1, 2), Value::Bool(true)], + ]], + }, + ]; + let out = case.check(&cancel); + assert_eq!(out[0].as_deref(), Some(&["7", "7"].map(String::from)[..])); + assert_eq!( + out[1].as_deref(), + Some(&["0.000", "0.000"].map(String::from)[..]) + ); + assert_eq!( + out[2].as_deref(), + Some(&["0.0", "0.000"].map(String::from)[..]) + ); + assert_eq!( + out[3].as_deref(), + Some(&["9223372036854775807.01", "9223372036854775807.01"].map(String::from)[..]) + ); +} + +#[test] +fn negating_zero_is_exact() { + let case = Case::new( + Case::nums(&["a"], Enc::Scaled), + &[("x.neg", "-a"), ("x.lit", "-(a * 0)"), ("x.sum", "-a + 1")], + ); + let out = case.check(&[ + Case::row(&[Case::d(5, 1)]), + Case::row(&[Case::d(0, 2)]), + Case::row(&[Case::d(i64::MIN, 0)]), + ]); + assert!(out.iter().all(Option::is_some), "{out:?}"); + assert_eq!( + out[2].as_ref().map(|v| v[0].as_str()), + Some("9223372036854775808") + ); + let case = Case::new(Case::nums(&["a"], Enc::Scaled), &[("x.neg", "-a")]); + let out = case.check(&[ + Case::row(&[Case::d(5, 1)]), + Case::row(&[Case::d(0, 2)]), + Case::row(&[Value::Null]), + ]); + assert_eq!(out[0].as_deref(), Some(&["-0.5".to_string()][..])); + assert!(out[1].is_some()); + assert!(out[2].is_none()); +} + +#[test] +fn selection_mask_limits_faults() { + let case = Case::new( + Case::nums(&["a"], Enc::Scaled), + &[("x.big", "a * 1000000000000")], + ); + let rows: Vec = [i64::MAX / 10, 7, i64::MAX / 10, 3] + .iter() + .map(|m| Case::row(&[Case::d(*m, 0)])) + .collect(); + assert_eq!( + case.run(&rows, None).iter().filter(|r| r.is_none()).count(), + 2 + ); + let select = [0b0001u64]; + let out = case.run(&rows, Some(&select)); + assert_eq!( + out.iter().map(Option::is_none).collect::>(), + [true, false, false, false] + ); +} + +#[test] +fn member_outputs_with_offset_lists() { + let workload = Workload::get("W1"); + let hir = workload.hir().expect("lowering"); + let rows = workload.mixed(100); + let program = Program::new(hir.clone()).expect("program"); + let oracle = Oracle::new(&workload, &hir); + for shift in [0, 5, 64, 70] { + let frame = Frame::new(&hir, &workload.spec, &rows, shift); + let mut out = program.outputs(); + program.run(&frame.batch(), &mut out, None).expect("run"); + for (r, row) in rows.iter().enumerate() { + if out.faults().get(r) { + continue; + } + let want = oracle.run(row.variable(&workload.spec)).expect("vm"); + let Val::List(fees) = &want[0] else { + panic!("fee list"); + }; + let got: Vec = frame + .range(0, r) + .map(|e| { + out.slots()[0] + .decimal(e) + .map_or("null".to_string(), |d| d.to_string()) + }) + .collect(); + assert_eq!( + got, + fees.iter().map(Val::to_string).collect::>(), + "shift {shift} row {r}" + ); + } + } +} + +#[test] +fn outputs_move_out() { + let case = Case::new( + Case::nums(&["a"], Enc::Scaled), + &[("x.a", "a + 1"), ("x.b", "a > 1")], + ); + let frame = Frame::new( + &case.hir, + &case.workload.spec, + &[Case::row(&[Case::d(1, 0)]), Case::row(&[Value::Null])], + 0, + ); + let mut out = case.program.outputs(); + case.program + .run(&frame.batch(), &mut out, None) + .expect("run"); + let (mant, scale, valid) = out.slot_mut(0).and_then(|s| s.take_num()).expect("num"); + assert_eq!((mant[0], scale[0], valid[0] & 1), (2, 0, 1)); + assert!(out.faults().get(1)); + let (bits, _) = out.slot_mut(1).and_then(|s| s.take_bool()).expect("bool"); + assert_eq!(bits[0] & 1, 0); + case.program + .run(&frame.batch(), &mut out, None) + .expect("rerun"); + assert_eq!(out.slots()[0].num(0), Some(Dec::int(2))); +} + +#[test] +fn rules_fault_strictly() { + let spec = Spec { + columns: vec![ + ColSpec::new("c.score", Class::Num, Enc::Scaled), + ColSpec::new("c.tier", Class::Text, Enc::Text), + ], + lists: Vec::new(), + }; + let rule = |score: Option<&str>, tier: Option<&str>, value: &str| TableRule { + cells: vec![score.map(str::to_string), tier.map(str::to_string)], + values: vec![Some(value.to_string())], + }; + for hit in [Hit::Strict, Hit::Lenient] { + let table = TableSpec { + inputs: vec![Some("c.score".to_string()), Some("c.tier".to_string())], + outputs: vec!["c.pick".to_string()], + rules: vec![ + rule(Some("> 10"), Some("'gold'"), "1"), + rule(None, Some("'silver'"), "2"), + rule(None, None, "3"), + ], + hit, + selector: false, + }; + let mut lowering = Lowering::new(None); + lowering + .table( + &table, + &mut Mock { + spec: &spec, + member: None, + }, + ) + .expect("lowering"); + let hir = lowering.finish(); + let looked = Passes { + lookup_min: 1, + ..Passes::ALL + }; + let rows = [ + Case::row(&[Case::d(20, 0), Value::Str("gold".into())]), + Case::row(&[Case::d(5, 0), Value::Str("silver".into())]), + Case::row(&[Value::Null, Value::Str("silver".into())]), + Case::row(&[Case::d(20, 0), Value::Null]), + Case::row(&[Case::d(20, 0), Value::Str("bronze".into())]), + ]; + for program in [ + Program::new(hir.clone()).expect("program"), + Program::with(hir.clone(), looked).expect("program"), + ] { + let frame = Frame::new(&hir, &spec, &rows, 0); + let mut out = program.outputs(); + program.run(&frame.batch(), &mut out, None).expect("run"); + let got: Vec = (0..rows.len()) + .map(|r| { + if out.faults().get(r) { + "fault".to_string() + } else { + out.slots()[0] + .decimal(r) + .map_or("null".to_string(), |d| d.to_string()) + } + }) + .collect(); + match hit { + Hit::Strict => assert_eq!(got, ["1", "2", "fault", "3", "3"]), + Hit::Lenient => assert_eq!(got, ["1", "2", "2", "3", "3"]), + } + } + } +} + +struct Bounds; + +impl Bounds { + fn sync() {} +} + +#[test] +fn programs_share_across_threads() { + Bounds::sync::(); + let workload = Workload::get("W2"); + let hir = workload.hir().expect("lowering"); + let rows = workload.mixed(400); + let program = Program::new(hir.clone()).expect("program"); + let oracle = Oracle::new(&workload, &hir); + let expected: Vec = rows + .iter() + .map(|r| { + oracle + .run(r.variable(&workload.spec)) + .map(|v| format!("{v:?}")) + .unwrap_or_default() + }) + .collect(); + std::thread::scope(|scope| { + for size in [400, 64, 7, 1] { + let (program, rows, hir, spec, expected) = + (&program, &rows, &hir, &workload.spec, &expected); + scope.spawn(move || { + for (c, chunk) in rows.chunks(size).enumerate() { + let frame = Frame::new(hir, spec, chunk, 0); + let mut out = program.outputs(); + program.run(&frame.batch(), &mut out, None).expect("run"); + for r in (0..chunk.len()).filter(|r| !out.faults().get(*r)) { + let got: Vec = out + .slots() + .iter() + .map(|s| match &s.data { + Data::Num { .. } => s.decimal(r).map_or(Val::Null, Val::Num), + Data::Bool(_) => s.boolean(r).map_or(Val::Null, Val::Bool), + Data::Code(_) => { + s.code(r).zip(s.dict()).map_or(Val::Null, |(c, d)| { + Val::Str(hir.dict(d).text(c).unwrap_or("?").to_string()) + }) + } + Data::Text { .. } => { + s.text(r).map_or(Val::Null, |t| Val::Str(t.to_string())) + } + Data::Date(_) => s.date(r).map_or(Val::Null, |_| { + Val::Other(format!("{}", s.variable(r).to_value())) + }), + }) + .collect(); + assert_eq!( + format!("{got:?}"), + expected[c * size + r], + "size {size} row {}", + c * size + r + ); + } + } + }); + } + }); +} + +#[test] +fn signature_cap_falls_back_to_generic() { + let case = Case::new( + Case::nums(&["a", "b"], Enc::Scaled), + &[ + ("x.sum", "a + b"), + ("x.prod", "a * b"), + ("x.div", "a / 100"), + ("x.cmp", "a > b"), + ], + ); + for scale in 0..24u8 { + let rows: Vec = (0..40) + .map(|i| Case::row(&[Case::d(i * 7 - 100, scale), Case::d(i % 5, 2)])) + .collect(); + case.check(&rows); + } +} + +#[test] +fn wide_lanes_stay_exact() { + let blocks = [ + ("x.third", "a / 3"), + ("x.round", "round(a / 3, 2)"), + ("x.big", "a * 1000000000"), + ("x.back", "a * 1000000000 / 1000000000"), + ("x.cmp", "a / 3 > b"), + ]; + let case = Case::new(Case::nums(&["a", "b"], Enc::Scaled), &blocks); + let rows: Vec = [ + (10, 0), + (i64::MAX, 0), + (-7, 2), + (0, 3), + (1, 28), + (i64::MIN, 0), + ] + .iter() + .map(|(m, s)| Case::row(&[Case::d(*m, *s), Case::d(3, 0)])) + .collect(); + let out = case.check(&rows); + assert!(out.iter().all(Option::is_some), "{out:?}"); + assert_eq!( + out[0].as_ref().map(|v| v[0].as_str()), + Some("3.3333333333333333333333333333") + ); + assert_eq!(out[0].as_ref().map(|v| v[1].as_str()), Some("3.33")); + let frame = Frame::new(&case.hir, &case.workload.spec, &rows, 0); + let mut out = case.program.outputs(); + case.program + .run(&frame.batch(), &mut out, None) + .expect("run"); + assert!(!out.slots()[0].wide.is_empty()); + assert!(!out.slots()[2].wide.is_empty()); +} diff --git a/core/expression/src/typed/tests/workload.rs b/core/expression/src/typed/tests/workload.rs new file mode 100644 index 00000000..c3ad39b2 --- /dev/null +++ b/core/expression/src/typed/tests/workload.rs @@ -0,0 +1,2473 @@ +use crate::lane::Fusion; +use crate::typed::tests::data::{ColSpec, Enc, ListSpec, Mock, Row, Spec, Value}; +use crate::typed::{Class, Dec, Hir, Hit, Lowering, Resolve, TableRule, TableSpec, Unsupported}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Dialect { + Policy, + Graph, +} + +#[derive(Clone, Debug)] +pub(crate) struct Rule { + pub(crate) cells: Vec, + pub(crate) values: Vec, +} + +#[derive(Clone, Debug)] +pub(crate) enum Block { + Expr { + key: String, + source: String, + }, + Table { + inputs: Vec, + outputs: Vec, + rules: Vec, + }, +} + +#[derive(Clone, Debug)] +pub(crate) struct Workload { + pub(crate) name: &'static str, + pub(crate) spec: Spec, + pub(crate) dialect: Dialect, + pub(crate) member: Option, + pub(crate) blocks: Vec, +} + +pub(crate) struct Rng(u64); + +impl Rng { + pub(crate) fn new(seed: u64) -> Self { + Self(seed | 1) + } + + pub(crate) fn pick(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n + } +} + +struct AnchorCustomer { + age: u64, + income: u64, + tier: &'static str, + rate: u64, + accounts: Vec<(u64, &'static str, bool)>, +} + +impl Block { + pub(crate) fn lower( + &self, + lowering: &mut Lowering, + resolve: &mut dyn Resolve, + hit: Hit, + ) -> Result<(), Unsupported> { + match self { + Block::Expr { key, source } => lowering.unit( + &[Fusion::Output { + key: key.clone(), + source: source.clone(), + }], + resolve, + ), + Block::Table { + inputs, + outputs, + rules, + } => { + let spec = TableSpec { + inputs: inputs.iter().cloned().map(Some).collect(), + outputs: outputs.clone(), + rules: rules + .iter() + .map(|rule| TableRule { + cells: rule + .cells + .iter() + .map(|cell| (!cell.trim().is_empty()).then(|| cell.clone())) + .collect(), + values: rule + .values + .iter() + .map(|value| Some(value.clone())) + .collect(), + }) + .collect(), + hit, + selector: false, + }; + lowering.table(&spec, resolve) + } + } + } +} + +impl Workload { + pub(crate) const NAMES: [&'static str; 21] = [ + "W1", "W2", "W3", "W4", "W5", "W6", "W7", "W8", "W9", "W10", "W11", "W12", "W13", "W14", + "W15", "W16", "W17", "W18", "W19", "W20", "W21", + ]; + + pub(crate) const FAULTY: [&'static str; 13] = [ + "W6", "W8", "W9", "W10", "W11", "W12", "W13", "W15", "W17", "W18", "W19", "W20", "W21", + ]; + + const W20_SOURCE: &'static str = "(contains(['a', 'bb', null], w.s) ? 1 : 0) + (some(['a', 'c'], startsWith(w.k, #)) ? 10 : 0) + (none([1, 2.5], # == w.n) ? 100 : 0) + (all(['x', 'y'], w.s != #) ? 1000 : 0)"; + + const W21_RULES: [([&'static str; 4], [&'static str; 2]); 6] = [ + (["< 5", "", "", ""], ["'gone'", "1"]), + (["startsWith($, 'q')", "", "", ""], ["'text'", "2"]), + ( + ["", "", "contains([1, 2.5, 3], $)", ""], + ["'listed'", "w.n * 3"], + ), + ( + ["", "some(['a', 'bb'], # == $)", "", ""], + ["'some'", "w.n * 3"], + ), + (["", "", "> 7", "true"], ["'big'", "w.n - 1"]), + (["", "", "", ""], ["'rest'", "w.n * 3"]), + ]; + + const W14_KEYS: [(&'static str, &'static str); 48] = [ + ("p", "d(e.at)"), + ("ps", "string(d(e.at))"), + ("ms", "d(e.ms)"), + ("tzd", "d(e.at, 'America/New_York')"), + ("y", "d(e.at).year()"), + ("wd", "d(e.at).weekday()"), + ("add", "d(e.at).add(1, 'month')"), + ("addn", "d(e.at).add(e.n, 'day')"), + ("sub", "d(e.at).sub('1y 2d')"), + ("som", "d(e.at).startOf('month')"), + ("eow", "d(e.at).endOf('week')"), + ("fmt", "d(e.at).format('%Y-%m-%d %H:%M')"), + ("fmt0", "d(e.at).format()"), + ("diffd", "d(e.at).diff(d('2024-01-01'), 'day')"), + ("diffm", "d(e.at).diff(e.other, 'month')"), + ("diffms", "d(e.at).diff(d(e.other))"), + ("bef", "d(e.at).isBefore(d('2024-03-01'))"), + ("aft", "d(e.at).isAfter(e.other, 'day')"), + ("same", "d(e.at).isSame(d(e.other), 'month')"), + ("sob", "d(e.at).isSameOrBefore(d('2024-02-29'), 'year')"), + ("valid", "d(e.at).isValid()"), + ("leap", "d(e.at).isLeapYear()"), + ("lt", "d(e.at) < d('2024-06-01')"), + ("ge", "d(e.at) >= d(e.other)"), + ("eq", "d(e.at) == d(e.other)"), + ("eqs", "d(e.at) == e.other"), + ("nes", "d(e.at) != e.other"), + ("eqlit", "d(e.at) == '2024-01-15'"), + ("inl", "d(e.at) in [d('2024-01-15'), '2024-02-29', null]"), + ("rng", "d(e.at) in [d('2024-01-01')..d('2024-12-31'))"), + ("tpl", "`at ${d(e.at)} / ${$.y}`"), + ("pick", "e.n > 3 ? d(e.at) : d('2020-02-02')"), + ("coal", "($.pick ?? d()).isValid()"), + ("now", "d().diff(d(e.at), 'year')"), + ("tday", "d(e.at).isToday()"), + ("ts", "d(e.at).timestamp()"), + ("setd", "d(e.at).set('day', 31)"), + ("tz2", "d(e.at).tz('Asia/Kolkata').format('%H:%M %z')"), + ("fl", "count(items, d(#.on).isAfter(d(e.at)))"), + ("dts", "map(items, d(#.on).add(1, 'd'))"), + ("str", "string($.add)"), + ("mm", "max([d(e.at), d(e.other)])"), + ("offset", "d(e.at).offsetName()"), + ( + "dst", + "d(e.at, 'Europe/Berlin').add(1, 'day').format('%Y-%m-%d %H:%M %Z')", + ), + ("dsts", "d(e.at, 'America/New_York').startOf('day').hour()"), + ("nul", "(e.n > 4 ? d(e.at) : null) == null"), + ("same2", "$.p == $.ms or $.p < $.ms"), + ( + "lit", + "d('2024-03-10 02:30:00', 'America/New_York').add(e.n, 'h')", + ), + ]; + + const W15_KEYS: [(&'static str, &'static str); 4] = [ + ("mo", "d(e.at).month() + d(e.at).day() * 100"), + ("lts", "d(e.at) < e.other"), + ("lit", "e.other > d('2000-06-30')"), + ("cat", "'D:' + d(e.at).add(2, 'h')"), + ]; + + const W18_KEYS: [(&'static str, &'static str); 11] = [ + ("leg", "date(l.v)"), + ("legn", "date(l.n)"), + ("legy", "year(l.v) + monthOfYear(l.v) + dayOfMonth(l.v)"), + ("legw", "dayOfWeek(l.v) * 10 + weekOfYear(l.v)"), + ("legd", "dayOfYear(l.v)"), + ("legs", "dateString(l.v)"), + ("legm", "monthString(l.v) + weekdayString(l.v)"), + ("tm", "time(l.t)"), + ("so", "startOf(l.v, 'day') - endOf(l.v, 'month')"), + ("dur", "duration(l.d)"), + ("yd", "year(d(l.v))"), + ]; + + const W19_KEYS: [(&'static str, &'static str); 3] = [ + ("mx", "max(map(items, d(#.on)))"), + ("mn", "min(map(items, d(#.on)))"), + ("flt", "map(filter(items, #.on < d('2024-06-01')), #.on)"), + ]; + + const W16_KEYS: [(&'static str, &'static str); 5] = [ + ("item.due", "d(item.on).add(c.days, 'day')"), + ("item.late", "d(item.on) > d(c.start)"), + ("item.s", "string(d(item.on).startOf('month'))"), + ("item.w", "d(item.on).isSame(d(c.start), 'week')"), + ("item.f", "d(item.on).format('%Y-%m')"), + ]; + + const W17_KEYS: [(&'static str, &'static str); 6] = [ + ("c.first", "min(map(c.items, d(#.on)))"), + ("c.n", "count(c.items, #.on > d(c.start))"), + ("c.any", "some(c.items, d(#.on).isBefore(d()))"), + ("c.f", "d(c.start).format('%d.%m.%Y')"), + ( + "c.last", + "max(map(filter(c.items, d(#.on).isValid()), d(#.on)))", + ), + ("c.dts", "map(c.items, d(#.on).endOf('day'))"), + ]; + + const DATES: [&'static str; 30] = [ + "2024-01-15", + "2024-02-29", + "2023-02-28", + "2024-01-31", + "2023-12-31 23:59:59", + "2024-03-31T01:30:00Z", + "2025-03-30 02:30:00", + "2024-10-27 02:30:00", + "2024-03-10 02:30:00", + "2024-11-03 01:30:00", + "1900-01-01", + "1970-01-01T00:00:00Z", + "9999-12-31", + "0001-01-01", + "2024-06-15T12:00:00+05:30", + "2024-06-15T12:00:00.123456789Z", + "20240115", + "2024/01/15", + "2024", + "2024-07", + "2000-06-30", + "2024-12-31T23:59:59.999Z", + "2025-01-01 00:00", + "2024-12-30", + "2026-02-28 13:45:10", + "2024-13-01", + "nope", + "", + "2024-02-30", + "Europe/Berlin", + ]; + + const W11_KEYS: [(&'static str, &'static str); 41] = [ + ("s_amt", "string(u.amt)"), + ("s_qty", "string(u.qty)"), + ("s_flag", "string(u.flag)"), + ("s_tier", "string(u.tier)"), + ("s_big", "string(u.big * 1000000000000)"), + ("s_div", "string(u.amt / 3)"), + ("tpl", "`${u.name}-${u.qty}:${u.amt} ${u.flag}`"), + ("cat", "u.name + '/' + u.city"), + ("up", "upper(u.name)"), + ("lo", "lower(u.city)"), + ("tr", "trim(u.name)"), + ("has", "contains(lower(u.name), 'an')"), + ( + "sw", + "startsWith(upper(u.city), 'B') or endsWith($.tr, 'e')", + ), + ("ln", "len(trim(u.name)) + len($.cat)"), + ("tierz", "u.tier ?? 'none'"), + ("pick", "u.qty > 4 ? u.name : 'nobody'"), + ("same", "u.name == u.city"), + ("eqlit", "upper(u.name) == 'ANNA'"), + ("gold", "$.tierz in ['gold', 'none']"), + ("pass", "u.city"), + ("rx", "matches(u.name, '^[A-Z][a-z]+$')"), + ("lbl", "u.qty > 3 ? 'big' : 'small'"), + ("lbl2", "$.lbl + '!'"), + ("mix", "u.qty > 5 ? $.lbl : u.tier"), + ("lenz", "len(u.tier ?? '')"), + ("cmpcode", "$.lbl == u.tier"), + ("nul", "$.mix == null"), + ("names", "map(items, #.name)"), + ("upn", "map(items, upper(#.name) + ':' + string(#.qty))"), + ("cnt", "count(items, #.name == u.tier)"), + ("intag", "u.city in tags"), + ("anyb", "some(items, contains(lower(#.tag), 'b'))"), + ("ups", "map(tags, upper(#))"), + ("fq", "map(filter(items, startsWith(#.name, 'A')), #.qty)"), + ("tt", "map(items, #.tag ?? 'x')"), + ("tc", "count(tags, # == $.pass)"), + ("mixeq", "u.name == u.amt"), + ("mixne", "u.tier != u.flag"), + ("mixlit", "u.amt == 'x' or $.lbl == 3"), + ("snull", "string(u.tier) == 'null'"), + ("negz", "string(-u.qty) + string(-u.amt)"), + ]; + + const W12_KEYS: [(&'static str, &'static str); 6] = [ + ("item.label", "upper(item.name) + '-' + c.code"), + ("item.same", "item.name == c.code"), + ("item.s", "string(item.qty * c.rate)"), + ("item.t", "`${item.name}:${item.qty}`"), + ("item.k", "item.qty > 2 ? item.name : c.code"), + ("item.n", "len(item.label)"), + ]; + + const W13_KEYS: [(&'static str, &'static str); 7] = [ + ("c.full", "c.code + '!'"), + ("c.again", "lower(c.full) == 'ab!'"), + ("c.names", "map(c.items, #.name)"), + ("c.joined", "c.full + string(len(c.items))"), + ("c.any", "some(c.items, #.name == c.code)"), + ("c.lab", "map(c.items, trim(#.name) + string(c.rate))"), + ("c.pick", "c.rate > 1 ? c.full : c.code"), + ]; + + const NAMES_W11: [&'static str; 12] = [ + "Anna", + "bob", + " Cara ", + "Émile", + "straße", + "Džemal", + "", + "İstanbul", + "日本", + "x\u{a0}", + "\tTabe\n", + "Bart", + ]; + + const W8_KEYS: [(&'static str, &'static str); 24] = [ + ("total", "sum(xs)"), + ("mean", "avg(xs)"), + ("lo", "min(xs)"), + ("hi", "max(filter(xs, # > 0))"), + ("pos", "filter(xs, # > x.limit)"), + ("doubled", "map(xs, # * 2)"), + ("sumd", "sum($.doubled)"), + ("big", "filter($.doubled, # > 10)"), + ("cnt", "len(filter(xs, # >= 0))"), + ("has", "x.n in xs"), + ("vip", "'vip' in tags"), + ("nvip", "'vip' not in tags"), + ("c2", "contains(xs, 2)"), + ("qtys", "map(filter(items, #.ok), #.qty)"), + ("flags", "map(items, #.qty > 2)"), + ("ct", "count(filter(items, #.ok), #.price > x.limit)"), + ("sm", "sum(map(items ?? [], #.price * #.qty))"), + ("lbl", "map(items, #.ok ? 'Y' : 'N')"), + ("tc", "count(tags, # == 'a')"), + ("nn", "len(xs)"), + ("e", "sum(xs ?? [])"), + ("q", "some($.qtys, # > 3)"), + ("same", "xs ?? []"), + ("again", "$.pos"), + ]; + + const W9_KEYS: [(&'static str, &'static str); 11] = [ + ("c.total", "sum(map(c.companies, sum(map(#.depts, #.cost))))"), + ("c.heads", "sum(map(c.companies, sum(map(#.depts, len(#.emps)))))"), + ("c.pay", "sum(map(c.companies, sum(map(#.depts, sum(map(filter(#.emps, #.active), #.salary))))))"), + ("c.anyBig", "some(c.companies, some(#.depts, #.size > c.limit))"), + ("c.cnt", "count(c.companies, #.big and len(#.depts) > 1)"), + ("c.mx", "max(map(c.companies, #.rev))"), + ("c.rich", "map(filter(c.companies, #.rev > c.limit), #.rev)"), + ("c.sc", "sum(c.scores)"), + ("c.hit", "c.limit in c.scores"), + ("c.top", "map(c.companies, len(#.depts))"), + ("c.deep", "count(c.companies, some(#.depts, all(#.emps, #.active)))"), + ]; + + const W10_KEYS: [(&'static str, &'static str); 8] = [ + ("co.cost", "sum(map(co.depts, #.cost))"), + ("co.n", "len(co.depts)"), + ("co.big", "some(co.depts, #.size > co.rev)"), + ("co.pay", "sum(map(co.depts, sum(map(#.emps, #.salary))))"), + ("co.share", "co.rev / (sum(map(c.companies, #.rev)) + 1)"), + ("co.sizes", "map(co.depts, #.size * 2)"), + ("co.hit", "c.limit in c.scores"), + ("co.act", "count(co.depts, some(#.emps, #.active))"), + ]; + + const KINDS: [&'static str; 3] = ["savings", "checking", "loan"]; + const TIERS: [&'static str; 3] = ["gold", "silver", "bronze"]; + const REGIONS: [&'static str; 8] = ["US", "CA", "UK", "DE", "FR", "JP", "BR", "IN"]; + const COUNTRIES: [&'static str; 5] = ["US", "CA", "MX", "DE", "GB"]; + const SKUS: [&'static str; 4] = ["PRO", "STD", "BLK", "PROMO"]; + const W3_RULES: [([&'static str; 4], [&'static str; 2]); 30] = [ + ( + [">= 800", "> 150000", "'US', 'CA'", "true"], + ["'A'", "applicant.income * 0.5"], + ), + ( + [">= 800", "> 150000", "", "true"], + ["'A'", "applicant.income * 0.45"], + ), + ( + [">= 800", "[80000..150000]", "'US', 'CA', 'UK'", ""], + ["'A'", "applicant.income * 0.4"], + ), + ( + [">= 800", "", "", "true"], + ["'B'", "applicant.income * 0.35"], + ), + ( + [">= 800", "", "", "false"], + ["'B'", "applicant.income * 0.3"], + ), + ( + ["[740..800)", "> 120000", "'US'", "true"], + ["'B'", "applicant.income * 0.4"], + ), + ( + ["[740..800)", "> 120000", "'CA', 'UK', 'DE'", ""], + ["'B'", "applicant.income * 0.35"], + ), + ( + ["[740..800)", "[60000..120000]", "", "true"], + ["'B'", "applicant.income * 0.3 + 1000"], + ), + ( + ["[740..800)", "< 60000", "'IN', 'BR'", ""], + ["'C'", "applicant.income / 4"], + ), + ( + ["[740..800)", "", "", ""], + ["'C'", "applicant.income * 0.25"], + ), + ( + ["[670..740)", "> 100000", "'US', 'CA'", "true"], + ["'C'", "applicant.income * 0.3"], + ), + ( + ["[670..740)", "> 100000", "", "false"], + ["'C'", "applicant.income * 0.2"], + ), + ( + ["[670..740)", "[50000..100000]", "'DE', 'FR'", ""], + ["'C'", "applicant.income * 0.22"], + ), + ( + ["[670..740)", "[50000..100000]", "'JP'", "true"], + ["'C'", "applicant.score * 40"], + ), + ( + ["[670..740)", "< 50000", "", "true"], + ["'D'", "applicant.income / 5"], + ), + ( + ["[670..740)", "", "'IN', 'BR'", ""], + ["'D'", "applicant.income * 0.15"], + ), + ( + ["[580..670)", "> 90000", "", "true"], + ["'D'", "applicant.income * 0.2"], + ), + ( + ["[580..670)", "> 90000", "'US'", "false"], + ["'D'", "applicant.income * 0.12"], + ), + ( + ["[580..670)", "[40000..90000]", "'UK', 'DE', 'FR'", ""], + ["'D'", "applicant.income * 0.1 + 500"], + ), + ( + ["[580..670)", "[40000..90000]", "", "true"], + ["'D'", "applicant.score * 20"], + ), + (["[580..670)", "< 40000", "'JP'", ""], ["'E'", "5000"]), + ( + ["[580..670)", "", "", "false"], + ["'E'", "applicant.income * 0.05"], + ), + ( + ["[500..580)", "> 80000", "", "true"], + ["'E'", "applicant.income * 0.08"], + ), + ( + ["[500..580)", "> 80000", "'US', 'CA'", ""], + ["'E'", "applicant.income * 0.06"], + ), + (["[500..580)", "", "'IN'", "true"], ["'E'", "2500"]), + ( + ["[500..580)", "[20000..80000]", "", ""], + ["'F'", "applicant.income * 0.03"], + ), + ( + ["< 500", "> 100000", "", "true"], + ["'F'", "applicant.income * 0.02"], + ), + (["< 500", "", "'US', 'CA', 'UK'", "true"], ["'F'", "1000"]), + (["< 500", "[30000..100000]", "", "false"], ["'F'", "500"]), + (["[300..400)", "", "", ""], ["'X'", "0"]), + ]; + + const W5_KEYS: [(&'static str, &'static str); 18] = [ + ("r2", "round(m.x * 1.075, 2)"), + ("r0", "round(m.x / 3)"), + ("fl", "floor(m.x) + ceil(m.y)"), + ("tr", "trunc(m.y / 7, 3)"), + ("ab", "abs(m.x - m.y)"), + ("md", "m.n % 7"), + ("mx", "m.x % 0.3"), + ("pw", "m.x ^ 2"), + ("pw3", "m.n ^ 3 + m.y ^ -1"), + ("lo", "min([m.x, m.y, 10])"), + ("hi", "max([m.x, $.r2, m.n])"), + ("av", "avg([m.x, m.y])"), + ("sm", "sum([m.x, m.y, m.n])"), + ("b", "bool(m.flag) and m.x > 0"), + ("q3", "m.x / 3 > 1"), + ("neg", "-m.x"), + ("c", "$.q3 ? round($.av, 1) : $.lo"), + ("k", "m.n > 2 ? m.x / 7 : (m.n < -2 ? m.x * m.y : $.pw)"), + ]; + + const W6_KEYS: [(&'static str, &'static str); 10] = [ + ("c.any", "some(c.items, #.qty > 3)"), + ("c.all", "all(c.items, #.ok)"), + ("c.none", "none(c.items, #.price > c.limit)"), + ("c.one", "one(c.items, #.ok)"), + ("c.cnt", "count(c.items, #.qty > 2)"), + ("c.min", "min(map(c.items, #.price))"), + ("c.max", "max(map(filter(c.items, #.ok), #.qty * #.price))"), + ("c.avg", "avg(map(c.items, #.price))"), + ( + "c.sfilt", + "some(filter(c.items, #.ok), #.price / #.qty > 2)", + ), + ("c.total", "sum(map(c.items, #.price * #.qty / 3))"), + ]; + + const W7_KEYS: [(&'static str, &'static str); 4] = [ + ("item.r", "round(item.price * c.limit / 100, 2)"), + ( + "item.m", + "item.qty % 2 == 0 ? abs(item.price) : -item.price", + ), + ("item.w", "item.price / 3"), + ("item.f", "floor(item.w * 10) ^ 2"), + ]; + + const W4_KEYS: [(&'static str, &'static str); 11] = [ + ("subtotal", "order.qty * order.price"), + ("rate", "order.discount ?? 0"), + ("discounted", "$.subtotal - $.subtotal * $.rate / 100"), + ("heavy", "order.weight > 20"), + ("shipping", "$.heavy ? 25 : (order.express ? 15 : 5)"), + ("domestic", "order.country in ['US', 'CA']"), + ("tax", "$.domestic ? $.discounted * 0.07 : 0"), + ("promo", "startsWith(order.sku, 'PRO')"), + ( + "total", + "$.discounted + $.shipping + $.tax - ($.promo ? 5 : 0)", + ), + ("vip", "$.total >= 500 and not $.promo"), + ("skuLen", "len(order.sku)"), + ]; + + pub(crate) fn get(name: &str) -> Workload { + match name { + "W1" => Self::w1(), + "W2" => Self::w2(), + "W3" => Self::w3(), + "W5" => Self::w5(), + "W6" => Self::w6(), + "W7" => Self::w7(), + "W8" => Self::w8(), + "W9" => Self::w9(), + "W10" => Self::w10(), + "W11" => Self::w11(), + "W12" => Self::w12(), + "W13" => Self::w13(), + "W14" => Self::w14(), + "W15" => Self::w15(), + "W16" => Self::w16(), + "W17" => Self::w17(), + "W18" => Self::w18(), + "W19" => Self::w19(), + "W20" => Self::w20(), + "W21" => Self::w21(), + _ => Self::w4(), + } + } + + pub(crate) fn hir(&self) -> Result { + let member = self + .member + .and_then(|m| self.spec.lists.get(m)) + .map(|l| (l.alias, l.path)); + let mut lowering = Lowering::new(member); + let mut mock = Mock { + spec: &self.spec, + member: self.member, + }; + for block in &self.blocks { + let hit = match self.dialect { + Dialect::Policy => Hit::Strict, + Dialect::Graph => Hit::Lenient, + }; + block.lower(&mut lowering, &mut mock, hit)?; + } + Ok(lowering.finish()) + } + + pub(crate) fn rows(&self, count: usize) -> Vec { + match self.name { + "W1" => Self::anchor(count).iter().map(Self::w1_row).collect(), + "W2" => Self::anchor(count).iter().map(Self::w2_row).collect(), + "W3" => Self::w3_rows(count), + "W5" => Self::w5_rows(count), + "W6" | "W7" => Self::w6_rows(count), + "W8" => Self::w8_rows(count), + "W9" | "W10" => Self::w9_rows(count), + "W11" => Self::w11_rows(count), + "W12" | "W13" => Self::w12_rows(count), + "W14" | "W15" | "W19" => Self::w14_rows(count), + "W18" => Self::w18_rows(count), + "W20" | "W21" => Self::w20_rows(count), + "W16" | "W17" => Self::w16_rows(count), + _ => Self::w4_rows(count), + } + } + + pub(crate) fn extremes(&self) -> Vec { + match self.name { + "W1" => Self::w1_extremes(), + "W2" => Self::w2_extremes(), + "W3" => Self::w3_extremes(), + "W5" => Self::w5_extremes(), + "W6" | "W7" => Self::w6_extremes(), + "W8" => Self::w8_extremes(), + "W9" | "W10" => Self::w9_extremes(), + "W11" => Self::w11_extremes(), + "W12" | "W13" => Self::w12_extremes(), + "W14" | "W15" | "W19" => Self::w14_extremes(), + "W18" => Self::w18_extremes(), + "W20" | "W21" => Self::w20_extremes(), + "W16" | "W17" => Self::w16_extremes(), + _ => Self::w4_extremes(), + } + } + + pub(crate) fn mixed(&self, count: usize) -> Vec { + let mut rows = self.rows(count); + for (at, row) in self.extremes().into_iter().enumerate() { + let index = (at * 7 + 3).min(rows.len()); + rows.insert(index, row); + } + rows + } + + fn col(path: &'static str, class: Class, enc: Enc) -> ColSpec { + ColSpec::new(path, class, enc) + } + + fn expr(key: &str, source: &str) -> Block { + Block::Expr { + key: key.to_string(), + source: source.to_string(), + } + } + + fn n(mant: i64) -> Value { + Value::Num(Dec::int(mant)) + } + + fn d(mant: i64, scale: u8) -> Value { + Value::Num(Dec::new(mant, scale)) + } + + fn s(text: &str) -> Value { + Value::Str(text.to_string()) + } + + fn w1() -> Workload { + Workload { + name: "W1", + spec: Spec { + columns: vec![Self::col("customer.rate", Class::Num, Enc::Scaled)], + lists: vec![ListSpec { + parent: None, + path: "customer.accounts", + alias: "account", + fields: vec![ + Self::col("balance", Class::Num, Enc::Dec), + Self::col("kind", Class::Text, Enc::Dict), + ], + }], + }, + dialect: Dialect::Policy, + member: Some(0), + blocks: vec![ + Self::expr( + "account.fee", + "account.balance * customer.rate / 100 * (account.kind == 'loan' ? 2 : 1)", + ), + Self::expr( + "account.label", + "account.kind == 'savings' ? 'S' : (account.kind == 'checking' ? 'C' : 'L')", + ), + ], + } + } + + fn w2() -> Workload { + let rules = [ + ("'gold'", "'low'", "0.15"), + ("'gold'", "'mid'", "0.1"), + ("'silver'", "'low'", "0.1"), + ("'silver'", "'mid'", "0.05"), + ("", "'low'", "0.02"), + ("", "", "0"), + ]; + Workload { + name: "W2", + spec: Spec { + columns: vec![ + Self::col("customer.age", Class::Num, Enc::Scaled), + Self::col("customer.income", Class::Num, Enc::Dec), + Self::col("customer.tier", Class::Text, Enc::Text), + ], + lists: vec![ListSpec { + parent: None, + path: "customer.accounts", + alias: "account", + fields: vec![ + Self::col("balance", Class::Num, Enc::Scaled), + Self::col("active", Class::Bool, Enc::Bool), + Self::col("fee", Class::Num, Enc::Scaled), + ], + }], + }, + dialect: Dialect::Policy, + member: None, + blocks: vec![ + Self::expr("customer.total", "sum(map(filter(customer.accounts, #.active), #.balance))"), + Self::expr("customer.fees", "sum(map(customer.accounts, #.fee))"), + Self::expr("customer.risk", "customer.total > customer.income * 2 ? 'high' : (customer.total > customer.income ? 'mid' : 'low')"), + Block::Table { + inputs: vec!["customer.tier".to_string(), "customer.risk".to_string()], + outputs: vec!["customer.discount".to_string()], + rules: rules + .iter() + .map(|(tier, risk, value)| Rule { cells: vec![tier.to_string(), risk.to_string()], values: vec![value.to_string()] }) + .collect(), + }, + Self::expr("customer.net", "customer.total - customer.fees - customer.discount"), + Self::expr("customer.eligible", "customer.age >= 18 and customer.risk != 'high'"), + ], + } + } + + fn w3() -> Workload { + Workload { + name: "W3", + spec: Spec { + columns: vec![ + Self::col("applicant.score", Class::Num, Enc::I64), + Self::col("applicant.income", Class::Num, Enc::Scaled), + Self::col("applicant.region", Class::Text, Enc::Utf8), + Self::col("applicant.verified", Class::Bool, Enc::Bool), + ], + lists: Vec::new(), + }, + dialect: Dialect::Graph, + member: None, + blocks: vec![Block::Table { + inputs: [ + "applicant.score", + "applicant.income", + "applicant.region", + "applicant.verified", + ] + .iter() + .map(|s| s.to_string()) + .collect(), + outputs: vec!["band".to_string(), "limit".to_string()], + rules: Self::W3_RULES + .iter() + .map(|(cells, values)| Rule { + cells: cells.iter().map(|c| c.to_string()).collect(), + values: values.iter().map(|v| v.to_string()).collect(), + }) + .collect(), + }], + } + } + + fn w4() -> Workload { + Workload { + name: "W4", + spec: Spec { + columns: vec![ + Self::col("order.qty", Class::Num, Enc::I64), + Self::col("order.price", Class::Num, Enc::Scaled), + Self::col("order.discount", Class::Num, Enc::Dec), + Self::col("order.weight", Class::Num, Enc::Scaled), + Self::col("order.express", Class::Bool, Enc::Bool), + Self::col("order.country", Class::Text, Enc::Dict), + Self::col("order.sku", Class::Text, Enc::Text), + ], + lists: Vec::new(), + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W4_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w5() -> Workload { + Workload { + name: "W5", + spec: Spec { + columns: vec![ + Self::col("m.x", Class::Num, Enc::Scaled), + Self::col("m.y", Class::Num, Enc::Dec), + Self::col("m.n", Class::Num, Enc::I64), + Self::col("m.flag", Class::Bool, Enc::Bool), + ], + lists: Vec::new(), + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W5_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w6_spec() -> Spec { + Spec { + columns: vec![Self::col("c.limit", Class::Num, Enc::Scaled)], + lists: vec![ListSpec { + parent: None, + path: "c.items", + alias: "item", + fields: vec![ + Self::col("qty", Class::Num, Enc::I64), + Self::col("price", Class::Num, Enc::Dec), + Self::col("ok", Class::Bool, Enc::Bool), + ], + }], + } + } + + fn w6() -> Workload { + Workload { + name: "W6", + spec: Self::w6_spec(), + dialect: Dialect::Policy, + member: None, + blocks: Self::W6_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w7() -> Workload { + Workload { + name: "W7", + spec: Self::w6_spec(), + dialect: Dialect::Policy, + member: Some(0), + blocks: Self::W7_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn list( + parent: Option, + path: &'static str, + alias: &'static str, + fields: Vec, + ) -> ListSpec { + ListSpec { + parent, + path, + alias, + fields, + } + } + + fn w8() -> Workload { + Workload { + name: "W8", + spec: Spec { + columns: vec![ + Self::col("x.limit", Class::Num, Enc::Scaled), + Self::col("x.n", Class::Num, Enc::I64), + ], + lists: vec![ + Self::list(None, "xs", "x", vec![Self::col("", Class::Num, Enc::Dec)]), + Self::list( + None, + "tags", + "t", + vec![Self::col("", Class::Text, Enc::Dict)], + ), + Self::list( + None, + "items", + "item", + vec![ + Self::col("qty", Class::Num, Enc::I64), + Self::col("price", Class::Num, Enc::Scaled), + Self::col("ok", Class::Bool, Enc::Bool), + ], + ), + ], + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W8_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w9_spec() -> Spec { + Spec { + columns: vec![Self::col("c.limit", Class::Num, Enc::Scaled)], + lists: vec![ + Self::list( + None, + "c.companies", + "co", + vec![ + Self::col("rev", Class::Num, Enc::Scaled), + Self::col("big", Class::Bool, Enc::Bool), + Self::col("depts", Class::Num, Enc::Items), + ], + ), + Self::list( + Some(0), + "depts", + "d", + vec![ + Self::col("size", Class::Num, Enc::I64), + Self::col("cost", Class::Num, Enc::Scaled), + Self::col("emps", Class::Num, Enc::Items), + ], + ), + Self::list( + Some(1), + "emps", + "e", + vec![ + Self::col("salary", Class::Num, Enc::Dec), + Self::col("active", Class::Bool, Enc::Bool), + ], + ), + Self::list( + None, + "c.scores", + "s", + vec![Self::col("", Class::Num, Enc::Scaled)], + ), + ], + } + } + + fn w9() -> Workload { + Workload { + name: "W9", + spec: Self::w9_spec(), + dialect: Dialect::Policy, + member: None, + blocks: Self::W9_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w10() -> Workload { + Workload { + name: "W10", + spec: Self::w9_spec(), + dialect: Dialect::Policy, + member: Some(0), + blocks: Self::W10_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w11() -> Workload { + Workload { + name: "W11", + spec: Spec { + columns: vec![ + Self::col("u.name", Class::Text, Enc::Text), + Self::col("u.city", Class::Text, Enc::Utf8), + Self::col("u.tier", Class::Text, Enc::Dict), + Self::col("u.amt", Class::Num, Enc::Scaled), + Self::col("u.qty", Class::Num, Enc::I64), + Self::col("u.big", Class::Num, Enc::Dec), + Self::col("u.flag", Class::Bool, Enc::Bool), + ], + lists: vec![ + Self::list( + None, + "items", + "item", + vec![ + Self::col("name", Class::Text, Enc::Dict), + Self::col("qty", Class::Num, Enc::I64), + Self::col("tag", Class::Text, Enc::Text), + ], + ), + Self::list( + None, + "tags", + "t", + vec![Self::col("", Class::Text, Enc::Utf8)], + ), + ], + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W11_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w12_spec() -> Spec { + Spec { + columns: vec![ + Self::col("c.code", Class::Text, Enc::Text), + Self::col("c.rate", Class::Num, Enc::Scaled), + ], + lists: vec![Self::list( + None, + "c.items", + "item", + vec![ + Self::col("name", Class::Text, Enc::Dict), + Self::col("qty", Class::Num, Enc::I64), + ], + )], + } + } + + fn w12() -> Workload { + Workload { + name: "W12", + spec: Self::w12_spec(), + dialect: Dialect::Policy, + member: Some(0), + blocks: Self::W12_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w13() -> Workload { + Workload { + name: "W13", + spec: Self::w12_spec(), + dialect: Dialect::Policy, + member: None, + blocks: Self::W13_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + pub(crate) fn mock() { + static MOCK: std::sync::Once = std::sync::Once::new(); + MOCK.call_once(|| std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z")); + } + + fn w14_spec() -> Spec { + Spec { + columns: vec![ + Self::col("e.at", Class::Text, Enc::Text), + Self::col("e.other", Class::Text, Enc::Utf8), + Self::col("e.ms", Class::Num, Enc::Scaled), + Self::col("e.n", Class::Num, Enc::I64), + ], + lists: vec![Self::list( + None, + "items", + "item", + vec![Self::col("on", Class::Text, Enc::Dict)], + )], + } + } + + fn w14() -> Workload { + Self::mock(); + let rules = [ + ("< d('2000-01-01')", "'old'", "d('1999-12-31')"), + ( + "d($) in [d('2024-01-01')..d('2024-12-31')]", + "'y24'", + "d(e.at)", + ), + ("d($).isValid() == false", "'bad'", "null"), + ("> d('2025-01-01')", "'new'", "d(e.at).add(1, 'y')"), + ("", "'mid'", "d('2000-01-01')"), + ]; + let mut blocks: Vec = Self::W14_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(); + blocks.push(Block::Table { + inputs: vec!["e.at".to_string()], + outputs: vec!["band".to_string(), "since".to_string()], + rules: rules + .iter() + .map(|(cell, band, since)| Rule { + cells: vec![cell.to_string()], + values: vec![band.to_string(), since.to_string()], + }) + .collect(), + }); + Workload { + name: "W14", + spec: Self::w14_spec(), + dialect: Dialect::Graph, + member: None, + blocks, + } + } + + fn w15() -> Workload { + Self::mock(); + Workload { + name: "W15", + spec: Self::w14_spec(), + dialect: Dialect::Graph, + member: None, + blocks: Self::W15_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w19() -> Workload { + Self::mock(); + Workload { + name: "W19", + spec: Self::w14_spec(), + dialect: Dialect::Graph, + member: None, + blocks: Self::W19_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w20_spec() -> Spec { + Spec { + columns: vec![ + Self::col("w.n", Class::Num, Enc::Scaled), + Self::col("w.s", Class::Text, Enc::Text), + Self::col("w.k", Class::Text, Enc::Dict), + Self::col("w.b", Class::Bool, Enc::Bool), + ], + lists: Vec::new(), + } + } + + fn w20() -> Workload { + Workload { + name: "W20", + spec: Self::w20_spec(), + dialect: Dialect::Graph, + member: None, + blocks: vec![Self::expr("out", Self::W20_SOURCE)], + } + } + + fn w21() -> Workload { + Workload { + name: "W21", + spec: Self::w20_spec(), + dialect: Dialect::Graph, + member: None, + blocks: vec![Block::Table { + inputs: ["w.gone", "w.s", "w.n", "w.b"] + .iter() + .map(|s| s.to_string()) + .collect(), + outputs: vec!["out".to_string(), "v".to_string()], + rules: Self::W21_RULES + .iter() + .map(|(cells, values)| Rule { + cells: cells.iter().map(|c| c.to_string()).collect(), + values: values.iter().map(|v| v.to_string()).collect(), + }) + .collect(), + }], + } + } + + fn w20_rows(count: usize) -> Vec { + let mut rng = Rng::new(53); + let texts = ["a", "bb", "c", "ab", "x", "y", "ca"]; + (0..count) + .map(|_| { + let n = match rng.pick(9) { + 0 => Value::Null, + 1 => Self::d(25, 1), + _ => Self::d(rng.pick(2_000) as i64 - 300, rng.pick(3) as u8), + }; + let text = |rng: &mut Rng| match rng.pick(8) { + 0 => Value::Null, + _ => Self::s(texts[rng.pick(texts.len() as u64) as usize]), + }; + let (s, k) = (text(&mut rng), text(&mut rng)); + let b = match rng.pick(5) { + 0 => Value::Null, + pick => Value::Bool(pick % 2 == 0), + }; + Row { + columns: vec![n, s, k, b], + lists: Vec::new(), + } + }) + .collect() + } + + fn w20_extremes() -> Vec { + let row = |n: Value, s: Value, k: Value, b: Value| Row { + columns: vec![n, s, k, b], + lists: Vec::new(), + }; + vec![ + row(Value::Null, Value::Null, Value::Null, Value::Null), + row( + Self::n(i64::MAX), + Self::s(""), + Self::s("a"), + Value::Bool(true), + ), + row( + Self::d(i64::MIN + 1, 18), + Self::s("bb"), + Self::s("c"), + Value::Bool(false), + ), + row(Self::d(10, 1), Self::s("x"), Self::s("ab"), Value::Null), + ] + } + + fn w18() -> Workload { + Self::mock(); + Workload { + name: "W18", + spec: Spec { + columns: vec![ + Self::col("l.v", Class::Text, Enc::Text), + Self::col("l.n", Class::Num, Enc::I64), + Self::col("l.t", Class::Text, Enc::Dict), + Self::col("l.d", Class::Text, Enc::Utf8), + ], + lists: Vec::new(), + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W18_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w18_rows(count: usize) -> Vec { + let mut rng = Rng::new(47); + let days = [ + "2024-01-15", + "2024-01-15 10:30:00", + "2024-02-29T23:59:59Z", + "2023-12-31", + "1999-01-01 00:00:00", + "now", + "2024-06-15T12:00:00+05:30", + "x", + ]; + let times = ["10:30", "23:59:59", "00:00", "now", "07", "25:00"]; + let spans = ["1h", "1h 30m", "90min", "2d", "3 weeks", "x"]; + (0..count) + .map(|_| { + let mut pick = |pool: &[&str], bad: u64| match rng.pick(bad) { + 0 => Self::s(pool[pool.len() - 1]), + _ => Self::s(pool[rng.pick(pool.len() as u64 - 1) as usize]), + }; + let (v, t, d) = (pick(&days, 25), pick(×, 25), pick(&spans, 25)); + Row { + columns: vec![v, Self::n(rng.pick(2_000_000_000) as i64), t, d], + lists: Vec::new(), + } + }) + .collect() + } + + fn w18_extremes() -> Vec { + let row = |v: Value, n: i64, t: Value, d: Value| Row { + columns: vec![v, Self::n(n), t, d], + lists: Vec::new(), + }; + vec![ + row(Value::Null, 0, Value::Null, Value::Null), + row( + Self::s("9999-12-31 23:59:59"), + i64::MAX, + Self::s("24:00"), + Self::s(""), + ), + row( + Self::s("0001-01-01"), + -62_135_596_800, + Self::s("12:00:00.5"), + Self::s("1y"), + ), + row( + Self::s("2024-02-29"), + 951_782_400, + Self::s("now"), + Self::s("10s"), + ), + ] + } + + fn w16_spec() -> Spec { + Spec { + columns: vec![ + Self::col("c.start", Class::Text, Enc::Text), + Self::col("c.days", Class::Num, Enc::I64), + ], + lists: vec![Self::list( + None, + "c.items", + "item", + vec![ + Self::col("on", Class::Text, Enc::Dict), + Self::col("amt", Class::Num, Enc::Scaled), + ], + )], + } + } + + fn w16() -> Workload { + Self::mock(); + Workload { + name: "W16", + spec: Self::w16_spec(), + dialect: Dialect::Policy, + member: Some(0), + blocks: Self::W16_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn w17() -> Workload { + Self::mock(); + Workload { + name: "W17", + spec: Self::w16_spec(), + dialect: Dialect::Policy, + member: None, + blocks: Self::W17_KEYS + .iter() + .map(|(k, s)| Self::expr(k, s)) + .collect(), + } + } + + fn date(rng: &mut Rng, invalid: u64) -> Value { + match rng.pick(40) { + 0 => Value::Null, + _ => match rng.pick(invalid) { + 0 => Self::s(Self::DATES[25 + rng.pick(5) as usize]), + _ => Self::s(Self::DATES[rng.pick(25) as usize]), + }, + } + } + + fn w14_rows(count: usize) -> Vec { + let mut rng = Rng::new(41); + let stamps = [ + 0i64, + 1_700_000_000_000, + -86_400_000, + 951_782_400_000, + 253_402_300_799_000, + -62_135_596_800_000, + 1_711_846_800_000, + ]; + (0..count) + .map(|_| { + let items: Vec> = (0..rng.pick(5)) + .map(|_| vec![Self::date(&mut rng, 12)]) + .collect(); + let ms = match rng.pick(12) { + 0 => Value::Null, + 1 => Self::d(15, 1), + _ => Self::n( + stamps[rng.pick(stamps.len() as u64) as usize] + + rng.pick(86_400_000) as i64, + ), + }; + let columns = vec![ + Self::date(&mut rng, 10), + Self::date(&mut rng, 10), + ms, + Self::n(rng.pick(7) as i64), + ]; + Row { + columns, + lists: vec![items], + } + }) + .collect() + } + + fn w14_extremes() -> Vec { + let row = |at: &str, other: &str, ms: Value| Row { + columns: vec![Self::s(at), Self::s(other), ms, Self::n(3)], + lists: vec![vec![vec![Self::s(at)], vec![Self::s(other)]]], + }; + vec![ + row( + "9999-12-31 23:59:59", + "0001-01-01", + Self::n(8_210_298_412_799_999), + ), + row( + "-0001-01-01", + "+10000-01-01", + Self::n(-8_334_632_851_200_000), + ), + row( + "2024-02-29T23:59:59.999999999Z", + "2024-03-01", + Self::n(i64::MAX), + ), + row( + "2024-03-31 02:30:00", + "2024-03-31 03:30:00", + Self::n(i64::MIN), + ), + row("2024-01-31", "2024-02-29", Self::d(-15, 1)), + row("America/New_York", "UTC", Self::d(1, 28)), + Row { + columns: vec![Value::Null, Value::Null, Value::Null, Self::n(0)], + lists: vec![Vec::new()], + }, + ] + } + + fn w16_rows(count: usize) -> Vec { + let mut rng = Rng::new(43); + (0..count) + .map(|_| { + let items: Vec> = (0..rng.pick(5)) + .map(|_| vec![Self::date(&mut rng, 15), Self::d(rng.pick(1000) as i64, 2)]) + .collect(); + Row { + columns: vec![ + Self::date(&mut rng, 15), + Self::n(rng.pick(400) as i64 - 200), + ], + lists: vec![items], + } + }) + .collect() + } + + fn w16_extremes() -> Vec { + let row = |start: &str, days: i64, on: &[&str]| Row { + columns: vec![Self::s(start), Self::n(days)], + lists: vec![on.iter().map(|o| vec![Self::s(o), Self::n(1)]).collect()], + }; + vec![ + row("9999-12-31", 1, &["9999-12-31", "0001-01-01"]), + row("nope", 0, &["nope", ""]), + row("2024-02-29", -366, &["2024-02-29", "2023-02-28"]), + row( + "2025-03-30 02:30:00", + 1_000_000_000, + &["2025-03-30 02:30:00"], + ), + row("", 0, &[]), + ] + } + + fn text(rng: &mut Rng, pool: &[&str], nulls: u64) -> Value { + match rng.pick(nulls) { + 0 => Value::Null, + _ => Self::s(pool[rng.pick(pool.len() as u64) as usize]), + } + } + + fn w11_rows(count: usize) -> Vec { + let mut rng = Rng::new(31); + let tiers = ["gold", "silver", "big", "small", "Gold"]; + let cities = ["Berlin", "bonn", "Anna", " Bart", "Émile", "x\u{a0}", ""]; + let tags = ["b", "Berlin", "Anna", "Ünï", ""]; + (0..count) + .map(|_| { + let items: Vec> = match rng.pick(25) { + 0 => vec![Vec::new()], + _ => (0..rng.pick(5)) + .map(|_| { + vec![ + Self::text(&mut rng, &Self::NAMES_W11, 40), + Self::n(rng.pick(9) as i64), + Self::text(&mut rng, &tags, 40), + ] + }) + .collect(), + }; + let tg: Vec> = match rng.pick(30) { + 0 => vec![Vec::new()], + _ => (0..rng.pick(4)) + .map(|_| vec![Self::text(&mut rng, &cities, 40)]) + .collect(), + }; + let flag = match rng.pick(30) { + 0 => Value::Null, + k => Value::Bool(k % 2 == 0), + }; + let amt = match rng.pick(30) { + 0 => Value::Null, + _ => Self::d(rng.pick(200_001) as i64 - 100_000, rng.pick(4) as u8), + }; + let columns = vec![ + Self::text(&mut rng, &Self::NAMES_W11, 60), + Self::text(&mut rng, &cities, 60), + Self::text(&mut rng, &tiers, 5), + amt, + Self::n(rng.pick(10) as i64), + Self::d(rng.pick(2_000_001) as i64 - 1_000_000, rng.pick(3) as u8), + flag, + ]; + Row { + columns, + lists: vec![items, tg], + } + }) + .collect() + } + + fn w11_extremes() -> Vec { + let row = |name: Value, city: Value, tier: Value, amt: Value, qty: Value, big: Value| Row { + columns: vec![name, city, tier, amt, qty, big, Value::Bool(true)], + lists: vec![ + vec![vec![Self::s("Ab"), Self::n(1), Value::Null]], + vec![vec![Self::s("bonn")]], + ], + }; + let long = "ab".repeat(700); + vec![ + row( + Self::s(""), + Self::s(""), + Self::s(""), + Self::d(0, 3), + Self::n(0), + Self::d(0, 2), + ), + row( + Self::s(&long), + Self::s(&long), + Value::Null, + Self::n(i64::MAX), + Self::n(i64::MAX), + Self::n(i64::MAX), + ), + row( + Self::s("ß"), + Self::s("Dž"), + Self::s("gold"), + Self::d(1, 28), + Self::n(-1), + Self::n(i64::MIN), + ), + row( + Self::s("\u{1F600} x"), + Self::s("İ"), + Self::s("big"), + Self::d(-1, 28), + Self::n(7), + Self::d(-5, 1), + ), + row( + Self::s(" \u{2003}a\u{2003} "), + Self::s("\u{b}v\u{c}"), + Self::s("small"), + Self::n(i64::MIN), + Self::n(4), + Self::d(150, 2), + ), + row( + Self::s("Anna"), + Self::s("Anna"), + Self::s("small"), + Self::d(-1500, 3), + Self::n(6), + Self::d(1, 0), + ), + ] + } + + fn w12_rows(count: usize) -> Vec { + let mut rng = Rng::new(37); + let codes = ["AB", "ab", "Zoë", "", "q"]; + let names = ["ab", "AB", "q", "Zoë", "", " ab ", "ß"]; + (0..count) + .map(|r| { + let items: Vec> = match rng.pick(30) { + 0 => vec![Vec::new()], + _ => (0..if r % 113 == 5 { + 1100 + } else { + rng.pick(5) as usize + }) + .map(|_| { + vec![ + Self::text(&mut rng, &names, 50), + Self::n(rng.pick(6) as i64), + ] + }) + .collect(), + }; + let rate = match rng.pick(40) { + 0 => Value::Null, + _ => Self::d(rng.pick(400) as i64, rng.pick(3) as u8), + }; + Row { + columns: vec![Self::text(&mut rng, &codes, 40), rate], + lists: vec![items], + } + }) + .collect() + } + + fn w12_extremes() -> Vec { + let row = |code: Value, rate: Value, items: Vec<[Value; 2]>| Row { + columns: vec![code, rate], + lists: vec![items.into_iter().map(|i| i.to_vec()).collect()], + }; + vec![ + row(Self::s(""), Self::n(0), Vec::new()), + row( + Self::s("ab"), + Self::d(1, 28), + vec![ + [Self::s("ab"), Self::n(i64::MAX)], + [Self::s(""), Self::n(0)], + ], + ), + row(Value::Null, Self::n(2), vec![[Self::s("x"), Self::n(3)]]), + row( + Self::s("Dž"), + Self::n(i64::MAX), + vec![[Self::s("Dž"), Self::n(2)], [Value::Null, Self::n(1)]], + ), + row( + Self::s("\u{1F600}"), + Self::d(-5, 1), + vec![[Self::s("\u{1F600}"), Value::Null]], + ), + ] + } + + fn w8_rows(count: usize) -> Vec { + let mut rng = Rng::new(23); + let tags = ["a", "b", "vip", "c"]; + (0..count) + .map(|r| { + let xs: Vec> = match rng.pick(30) { + 0 => vec![Vec::new()], + _ => (0..if r % 97 == 3 { + 1300 + } else { + rng.pick(6) as usize + }) + .map(|_| match rng.pick(60) { + 0 => vec![Value::Null], + _ => vec![Self::d(rng.pick(4001) as i64 - 1000, rng.pick(3) as u8)], + }) + .collect(), + }; + let tg: Vec> = (0..rng.pick(4)) + .map(|_| vec![Self::s(tags[rng.pick(4) as usize])]) + .collect(); + let items: Vec> = match rng.pick(25) { + 0 => vec![Vec::new()], + _ => (0..rng.pick(5)) + .map(|_| { + let ok = match rng.pick(50) { + 0 => Value::Null, + k => Value::Bool(k % 3 != 0), + }; + vec![ + Self::n(rng.pick(8) as i64), + Self::d(rng.pick(50_000) as i64, 2), + ok, + ] + }) + .collect(), + }; + let limit = match rng.pick(40) { + 0 => Value::Null, + _ => Self::d(rng.pick(2000) as i64, 1), + }; + Row { + columns: vec![limit, Self::n(rng.pick(20) as i64 - 10)], + lists: vec![xs, tg, items], + } + }) + .collect() + } + + fn w8_extremes() -> Vec { + let row = |limit: Value, n: Value, xs: Vec, items: Vec<[Value; 3]>| Row { + columns: vec![limit, n], + lists: vec![ + xs.into_iter().map(|x| vec![x]).collect(), + vec![vec![Self::s("vip")]], + items.into_iter().map(|i| i.to_vec()).collect(), + ], + }; + let t = || Value::Bool(true); + vec![ + row(Self::n(1), Self::n(2), Vec::new(), Vec::new()), + row( + Self::n(1), + Value::Null, + vec![Value::Null, Self::n(3)], + Vec::new(), + ), + row( + Self::n(1), + Self::n(2), + vec![Self::n(i64::MAX), Self::n(i64::MAX)], + vec![[Self::n(i64::MAX), Self::n(3), t()]], + ), + row( + Self::d(5, 1), + Self::n(0), + vec![Self::d(1, 28), Self::d(-1, 28), Self::d(0, 3)], + vec![[Self::n(2), Self::d(0, 2), t()]], + ), + row( + Value::Null, + Self::n(2), + vec![Self::n(2), Self::d(20, 1)], + vec![[Self::n(1), Self::n(1), Value::Null]], + ), + row( + Self::n(1), + Self::n(7), + vec![Self::n(i64::MIN)], + vec![[Self::n(9), Self::n(i64::MIN), t()]], + ), + row( + Self::n(1), + Self::n(5), + vec![Self::d(15, 1), Self::d(150, 2), Self::n(-0)], + Vec::new(), + ), + ] + } + + fn w9_rows(count: usize) -> Vec { + let mut rng = Rng::new(29); + (0..count) + .map(|r| { + let companies: Vec> = match rng.pick(40) { + 0 => vec![Vec::new()], + _ => (0..if r % 131 == 7 { + 300 + } else { + rng.pick(5) as usize + }) + .map(|_| { + let depts = match rng.pick(20) { + 0 => Value::Null, + _ => Value::Items( + (0..rng.pick(4)) + .map(|_| { + let emps = match rng.pick(25) { + 0 => Value::Null, + _ => Value::Items( + (0..rng.pick(4)) + .map(|_| { + let active = match rng.pick(30) { + 0 => Value::Null, + k => Value::Bool(k % 2 == 0), + }; + vec![ + Self::d( + rng.pick(900_000) as i64, + rng.pick(3) as u8, + ), + active, + ] + }) + .collect(), + ), + }; + vec![ + Self::n(rng.pick(50) as i64), + Self::d(rng.pick(100_000) as i64, 2), + emps, + ] + }) + .collect(), + ), + }; + let big = match rng.pick(30) { + 0 => Value::Null, + k => Value::Bool(k % 2 == 1), + }; + vec![Self::d(rng.pick(1_000_000) as i64, 1), big, depts] + }) + .collect(), + }; + let scores: Vec> = match rng.pick(30) { + 0 => vec![Vec::new()], + _ => (0..rng.pick(5)) + .map(|_| vec![Self::d(rng.pick(300) as i64, 1)]) + .collect(), + }; + Row { + columns: vec![Self::d(rng.pick(400) as i64, 1)], + lists: vec![companies, scores], + } + }) + .collect() + } + + fn w9_extremes() -> Vec { + let emp = |salary: Value, active: Value| vec![salary, active]; + let dept = |size: Value, cost: Value, emps: Value| vec![size, cost, emps]; + let company = |rev: Value, big: Value, depts: Value| vec![rev, big, depts]; + let t = || Value::Bool(true); + let row = |limit: Value, companies: Vec>, scores: Vec| Row { + columns: vec![limit], + lists: vec![companies, scores.into_iter().map(|s| vec![s]).collect()], + }; + vec![ + row(Self::n(1), Vec::new(), Vec::new()), + row( + Self::n(1), + vec![company(Self::n(5), t(), Value::Items(Vec::new()))], + vec![Self::n(1)], + ), + row( + Self::n(1), + vec![company(Self::n(5), t(), Value::Null)], + vec![Self::n(2)], + ), + row( + Self::n(1), + vec![company( + Self::n(i64::MAX), + t(), + Value::Items(vec![dept( + Self::n(1), + Self::n(i64::MAX), + Value::Items(vec![ + emp(Self::n(i64::MAX), t()), + emp(Self::n(i64::MAX), t()), + ]), + )]), + )], + vec![Self::n(i64::MAX), Self::n(i64::MAX)], + ), + row( + Value::Null, + vec![company( + Self::n(3), + Value::Null, + Value::Items(vec![dept(Self::n(1), Self::n(2), Value::Null)]), + )], + vec![Value::Null], + ), + row( + Self::d(5, 1), + vec![company( + Self::d(-1, 28), + t(), + Value::Items(vec![dept( + Value::Null, + Self::d(0, 3), + Value::Items(vec![emp(Value::Null, t())]), + )]), + )], + vec![Self::d(5, 1), Self::d(50, 2)], + ), + row( + Self::n(-1), + vec![company( + Self::d(0, 2), + Value::Bool(false), + Value::Items(vec![dept(Self::n(1), Self::n(1), Value::Items(Vec::new()))]), + )], + Vec::new(), + ), + ] + } + + fn w5_rows(count: usize) -> Vec { + let mut rng = Rng::new(17); + (0..count) + .map(|_| { + let x = Self::d(rng.pick(2_000_001) as i64 - 1_000_000, rng.pick(5) as u8); + let y = match rng.pick(25) { + 0 => Self::d(0, rng.pick(3) as u8), + _ => Self::d(rng.pick(20_001) as i64 - 10_000, rng.pick(4) as u8), + }; + let n = Self::n(rng.pick(41) as i64 - 20); + let flag = match rng.pick(5) { + 0 => Value::Null, + k => Value::Bool(k % 2 == 0), + }; + Row { + columns: vec![x, y, n, flag], + lists: Vec::new(), + } + }) + .collect() + } + + fn w6_rows(count: usize) -> Vec { + let mut rng = Rng::new(19); + (0..count) + .map(|r| { + let len = match r % 211 { + 5 => 1500, + _ => rng.pick(7) as usize, + }; + let items = (0..len) + .map(|_| { + let qty = Self::n(rng.pick(8) as i64); + let price = Self::d(rng.pick(100_000) as i64, rng.pick(3) as u8); + let ok = match rng.pick(40) { + 0 => Value::Null, + k => Value::Bool(k % 3 != 0), + }; + vec![qty, price, ok] + }) + .collect(); + Row { + columns: vec![Self::d(rng.pick(50_000) as i64, 1)], + lists: vec![items], + } + }) + .collect() + } + + fn w5_extremes() -> Vec { + let row = |x: Value, y: Value, n: Value, flag: Value| Row { + columns: vec![x, y, n, flag], + lists: Vec::new(), + }; + let t = || Value::Bool(true); + vec![ + row(Self::n(i64::MAX), Self::n(1), Self::n(3), t()), + row(Self::n(i64::MIN), Self::d(-5, 1), Self::n(-3), t()), + row(Self::d(0, 2), Self::d(0, 3), Self::n(0), Value::Bool(false)), + row(Value::Null, Self::n(2), Self::n(1), t()), + row(Self::n(5), Value::Null, Self::n(1), Value::Null), + row(Self::n(5), Self::n(2), Value::Null, t()), + row(Self::d(1, 28), Self::d(-1, 28), Self::n(i64::MAX), t()), + row(Self::d(-25, 1), Self::d(-15, 1), Self::n(-1), t()), + row(Self::d(-4, 1), Self::d(5, 1), Self::n(7), t()), + row(Self::d(i64::MAX, 9), Self::d(i64::MIN, 4), Self::n(9), t()), + row(Self::n(10), Self::n(3), Self::n(2_000_000), t()), + ] + } + + fn w6_extremes() -> Vec { + let row = |limit: Value, items: Vec<[Value; 3]>| Row { + columns: vec![limit], + lists: vec![items.into_iter().map(|i| i.to_vec()).collect()], + }; + let t = || Value::Bool(true); + let f = || Value::Bool(false); + vec![ + row(Self::n(10), Vec::new()), + row(Value::Null, vec![[Self::n(1), Self::n(5), t()]]), + row( + Self::n(10), + vec![ + [Self::n(5), Self::n(i64::MAX), t()], + [Self::n(4), Self::n(i64::MAX), t()], + ], + ), + row( + Self::n(10), + vec![[Self::n(0), Self::n(7), t()], [Self::n(2), Self::n(9), f()]], + ), + row( + Self::n(10), + vec![ + [Self::n(1), Value::Null, t()], + [Self::n(5), Self::n(1), t()], + ], + ), + row( + Self::n(10), + vec![ + [Self::n(5), Self::n(1), t()], + [Self::n(1), Value::Null, Value::Null], + ], + ), + row( + Self::n(10), + vec![ + [Value::Null, Self::n(1), f()], + [Self::n(9), Self::n(3), t()], + ], + ), + row( + Self::d(1, 28), + vec![ + [Self::n(3), Self::d(-1, 28), t()], + [Self::n(3), Self::d(-0, 2), t()], + ], + ), + row( + Self::n(10), + vec![ + [Self::n(1), Self::d(15, 1), t()], + [Self::n(1), Self::n(15), t()], + [Self::n(1), Self::d(150, 2), f()], + ], + ), + row(Self::n(-1), vec![[Self::n(7), Self::n(i64::MIN), t()]]), + ] + } + + fn anchor(count: usize) -> Vec { + let mut rng = Rng::new(7); + (0..count) + .map(|_| { + let accounts = (0..rng.pick(8)) + .map(|_| { + let balance = rng.pick(5000); + let kind = Self::KINDS[rng.pick(3) as usize]; + let active = rng.pick(4) != 0; + (balance, kind, active) + }) + .collect(); + let age = 16 + rng.pick(64); + let income = 1000 + rng.pick(9000); + let tier = Self::TIERS[rng.pick(3) as usize]; + let rate = 1 + rng.pick(5); + AnchorCustomer { + age, + income, + tier, + rate, + accounts, + } + }) + .collect() + } + + fn w1_row(c: &AnchorCustomer) -> Row { + Row { + columns: vec![Self::n(c.rate as i64)], + lists: vec![c + .accounts + .iter() + .map(|(b, k, _)| vec![Self::n(*b as i64), Self::s(k)]) + .collect()], + } + } + + fn w2_row(c: &AnchorCustomer) -> Row { + Row { + columns: vec![ + Self::n(c.age as i64), + Self::n(c.income as i64), + Self::s(c.tier), + ], + lists: vec![c + .accounts + .iter() + .map(|(b, k, a)| { + let factor = if *k == "loan" { 2 } else { 1 }; + vec![ + Self::n(*b as i64), + Value::Bool(*a), + Self::d((*b * c.rate * factor) as i64, 2), + ] + }) + .collect()], + } + } + + fn w3_rows(count: usize) -> Vec { + let mut rng = Rng::new(11); + (0..count) + .map(|_| { + let score = 300 + rng.pick(551) as i64; + let income = (rng.pick(200_000) * 100 + rng.pick(100)) as i64; + let region = Self::REGIONS[rng.pick(8) as usize]; + let verified = rng.pick(3) != 0; + Row { + columns: vec![ + Self::n(score), + Self::d(income, 2), + Self::s(region), + Value::Bool(verified), + ], + lists: Vec::new(), + } + }) + .collect() + } + + fn w4_rows(count: usize) -> Vec { + let mut rng = Rng::new(13); + (0..count) + .map(|_| { + let qty = 1 + rng.pick(20) as i64; + let price = 100 + rng.pick(50_000) as i64; + let discount = match rng.pick(20) { + 0 => Value::Null, + _ => Self::n(rng.pick(31) as i64), + }; + let weight = 1 + rng.pick(500) as i64; + let express = rng.pick(3) == 0; + let country = Self::COUNTRIES[rng.pick(5) as usize]; + let sku = format!("{}-{}", Self::SKUS[rng.pick(4) as usize], rng.pick(100_000)); + Row { + columns: vec![ + Self::n(qty), + Self::d(price, 2), + discount, + Self::d(weight, 1), + Value::Bool(express), + Self::s(country), + Value::Str(sku), + ], + lists: Vec::new(), + } + }) + .collect() + } + + fn w1_extremes() -> Vec { + let row = |rate: Value, accounts: Vec<(Value, Value)>| Row { + columns: vec![rate], + lists: vec![accounts.into_iter().map(|(b, k)| vec![b, k]).collect()], + }; + vec![ + row( + Self::n(5), + vec![(Self::n(9_000_000_000_000_000_000), Self::s("loan"))], + ), + row( + Self::d(1, 9), + vec![ + (Self::d(125, 1), Self::s("checking")), + (Self::d(1, 28), Self::s("savings")), + ], + ), + row(Value::Null, vec![(Self::n(100), Self::s("loan"))]), + row( + Self::n(2), + vec![ + (Value::Null, Self::s("savings")), + (Self::n(3), Self::s("loan")), + ], + ), + row(Self::n(2), vec![(Self::n(50), Value::Null)]), + row(Self::n(3), Vec::new()), + row(Self::n(-7), vec![(Self::n(i64::MIN), Self::s("savings"))]), + row( + Self::n(4), + vec![ + (Self::d(i64::MAX, 2), Self::s("checking")), + (Self::n(-5), Self::s("loan")), + ], + ), + row( + Self::n(1), + vec![(Self::n(99_999_999_999_999_999), Self::s("loan"))], + ), + row( + Self::d(25, 1), + vec![ + (Self::d(-3333, 3), Self::s("loan")), + (Self::n(0), Self::s("checking")), + ], + ), + row(Value::Null, Vec::new()), + ] + } + + fn w2_extremes() -> Vec { + let row = + |age: Value, income: Value, tier: Value, accounts: Vec<(Value, Value, Value)>| Row { + columns: vec![age, income, tier], + lists: vec![accounts + .into_iter() + .map(|(b, a, f)| vec![b, a, f]) + .collect()], + }; + let t = || Value::Bool(true); + vec![ + row( + Self::n(30), + Self::n(1000), + Self::s("gold"), + vec![ + (Self::n(5_000_000_000_000_000_000), t(), Self::n(1)), + (Self::n(5_000_000_000_000_000_000), t(), Self::n(1)), + ], + ), + row( + Self::n(30), + Self::n(6_000_000_000_000_000_000), + Self::s("silver"), + vec![(Self::n(10), t(), Self::d(2, 1))], + ), + row( + Self::n(30), + Self::n(4000), + Self::s("gold"), + vec![(Self::n(10), Value::Null, Self::d(1, 1))], + ), + row( + Value::Null, + Self::n(4000), + Self::s("gold"), + vec![(Self::n(10), t(), Self::n(1))], + ), + row( + Self::n(40), + Self::n(4000), + Value::Null, + vec![(Self::n(10), t(), Self::n(1))], + ), + row( + Self::n(40), + Value::Null, + Self::s("bronze"), + vec![(Self::n(10), t(), Self::n(1))], + ), + row( + Self::n(40), + Self::n(4000), + Self::s("silver"), + vec![(Self::n(10), t(), Value::Null)], + ), + row(Self::n(40), Self::n(4000), Self::s("silver"), Vec::new()), + row( + Self::n(40), + Self::d(15, 1), + Self::s("gold"), + vec![ + (Self::d(125, 1), t(), Self::d(25, 2)), + (Self::d(1, 9), t(), Self::d(1, 28)), + (Self::n(7), Value::Bool(false), Self::n(0)), + ], + ), + row( + Self::n(40), + Self::n(4000), + Self::s("gold"), + vec![( + Self::n(9_000_000_000_000_000_000), + t(), + Self::n(-9_000_000_000_000_000_000), + )], + ), + row( + Self::d(175, 1), + Self::n(10), + Self::s("bronze"), + vec![(Self::n(15), t(), Self::n(0))], + ), + row( + Self::n(18), + Self::n(0), + Self::s("silver"), + vec![(Self::n(-1), t(), Self::n(0))], + ), + ] + } + + fn w3_extremes() -> Vec { + let row = |score: Value, income: Value, region: Value, verified: Value| Row { + columns: vec![score, income, region, verified], + lists: Vec::new(), + }; + let t = || Value::Bool(true); + vec![ + row(Value::Null, Self::d(5_000_000, 2), Self::s("US"), t()), + row(Self::n(810), Value::Null, Self::s("US"), t()), + row(Self::n(810), Self::d(i64::MAX, 2), Self::s("US"), t()), + row( + Self::n(720), + Self::d(i64::MAX - 7, 2), + Self::s("IN"), + Value::Bool(false), + ), + row( + Self::n(760), + Self::d(5_000_000, 2), + Value::Null, + Value::Null, + ), + row(Value::Null, Value::Null, Value::Null, Value::Null), + row( + Self::n(450), + Self::d(1, 2), + Self::s("JP"), + Value::Bool(false), + ), + row(Self::n(i64::MAX), Self::d(-5, 2), Self::s("US"), t()), + row(Self::n(690), Self::d(9_000_000_000, 2), Self::s("JP"), t()), + ] + } + + fn w4_extremes() -> Vec { + let row = |qty: Value, + price: Value, + discount: Value, + weight: Value, + express: Value, + country: Value, + sku: Value| Row { + columns: vec![qty, price, discount, weight, express, country, sku], + lists: Vec::new(), + }; + let sku = || Self::s("PRO-1"); + vec![ + row( + Self::n(i64::MAX / 10), + Self::d(100_000, 2), + Self::n(5), + Self::d(10, 1), + Value::Bool(false), + Self::s("US"), + sku(), + ), + row( + Self::n(2), + Self::d(1000, 2), + Value::Null, + Self::d(10, 1), + Value::Bool(true), + Self::s("CA"), + Value::Null, + ), + row( + Self::n(2), + Self::d(1000, 2), + Self::n(3), + Value::Null, + Value::Bool(true), + Self::s("CA"), + sku(), + ), + row( + Self::n(2), + Self::d(1000, 2), + Self::n(3), + Self::d(10, 1), + Value::Bool(true), + Value::Null, + Self::s(""), + ), + row( + Self::n(2), + Self::d(1000, 2), + Self::n(3), + Self::d(10, 1), + Value::Null, + Self::s("MX"), + Self::s("STD-9"), + ), + row( + Self::n(2), + Self::d(1000, 2), + Self::n(3), + Self::d(300, 1), + Value::Null, + Self::s("MX"), + Self::s("PROMO-77"), + ), + row( + Value::Null, + Value::Null, + Value::Null, + Value::Null, + Value::Null, + Value::Null, + Value::Null, + ), + row( + Self::n(1), + Self::d(9_000_000_000_000_000_000, 2), + Self::n(100), + Self::d(1, 1), + Value::Bool(false), + Self::s("US"), + sku(), + ), + row( + Self::n(3), + Self::d(4_000_000_000_000_000_000, 2), + Self::n(7), + Self::d(1, 1), + Value::Bool(false), + Self::s("US"), + sku(), + ), + row( + Self::n(-4), + Self::d(2500, 2), + Self::n(-10), + Self::d(-5, 1), + Value::Bool(true), + Self::s("GB"), + Self::s("PRÖ-ü"), + ), + ] + } +} diff --git a/core/expression/src/typed/text.rs b/core/expression/src/typed/text.rs new file mode 100644 index 00000000..b695fe55 --- /dev/null +++ b/core/expression/src/typed/text.rs @@ -0,0 +1,422 @@ +use crate::lane::scaled::Scaled; +use crate::lane::Bits; +use crate::typed::batch::{Feed, Text}; +use crate::typed::exec::{Buf, Exec, Others, Reg}; +use crate::typed::hir::Func; +use crate::typed::ins::{Arg, Ins, Rep}; +use crate::typed::kernel::K; + +#[derive(Clone, Copy)] +pub(crate) enum TV<'a, 'x> { + Lit(&'a [u8]), + Col(&'a Text<'x>, &'a Feed<'x>), + Reg(&'a Reg), + Missing, +} + +impl<'a, 'x> TV<'a, 'x> { + #[inline] + pub(crate) fn get(self, start: usize, i: usize) -> Option<&'a [u8]> { + match self { + TV::Lit(b) => Some(b), + TV::Col(text, feed) => match feed.valid(start + i) + && !Bits::get(feed.faults.as_deref().unwrap_or_default(), start + i) + { + true => text.get(start + i), + false => None, + }, + TV::Reg(r) => (Bits::get(&r.valid, i) && !Bits::get(&r.fault, i)).then(|| r.str(i)), + TV::Missing => None, + } + } + + #[inline] + pub(crate) fn ok(self, start: usize, w: usize) -> u64 { + match self { + TV::Lit(_) => u64::MAX, + TV::Col(_, feed) => { + feed.valid_word(start + w * 64, 64) & !feed.fault_word(start / 64 + w) + } + TV::Reg(r) => r.valid[w] & !r.fault[w], + TV::Missing => 0, + } + } + + #[inline] + pub(crate) fn bad(self, start: usize, w: usize) -> u64 { + match self { + TV::Col(_, feed) => feed.fault_word(start / 64 + w), + TV::Reg(r) => r.fault[w], + TV::Lit(_) | TV::Missing => 0, + } + } +} + +impl Reg { + pub(crate) fn texts(&mut self, n: usize) { + self.text.clear(); + if self.span.len() < Reg::LANES { + self.span.resize(Reg::LANES, (0, 0)); + } + self.span[..n].fill((0, 0)); + } + + #[inline] + pub(crate) fn str(&self, i: usize) -> &[u8] { + let (lo, hi) = self.span.get(i).copied().unwrap_or_default(); + self.text.get(lo as usize..hi as usize).unwrap_or_default() + } + + #[inline] + pub(crate) fn push(&mut self, i: usize, bytes: &[u8]) { + let lo = self.text.len() as u32; + self.text.extend_from_slice(bytes); + self.span[i] = (lo, self.text.len() as u32); + } + + pub(crate) fn literal(&mut self, text: &str) { + self.text.clear(); + self.text.extend_from_slice(text.as_bytes()); + self.span.clear(); + self.span.resize(Reg::LANES, (0, text.len() as u32)); + } +} + +impl Buf { + #[inline] + pub(crate) fn str(&self, i: usize) -> &[u8] { + let (lo, hi) = self.span.get(i).copied().unwrap_or_default(); + self.text.get(lo as usize..hi as usize).unwrap_or_default() + } + + pub(crate) fn spill(&mut self, at: usize, bytes: &[u8]) { + if self.span.len() < self.mant.len() { + self.span.resize(self.mant.len(), (0, 0)); + } + let lo = self.text.len() as u32; + self.text.extend_from_slice(bytes); + if let Some(s) = self.span.get_mut(at) { + *s = (lo, self.text.len() as u32); + } + } +} + +impl<'e, 'x> Exec<'e, 'x> { + pub(crate) fn view<'a>(&'a self, arg: &'a Arg, regs: &'a Others) -> TV<'a, 'x> { + match arg { + Arg::Lit(s) => TV::Lit(s.as_bytes()), + Arg::Reg(r) => TV::Reg(®s[*r as usize]), + Arg::Src(src) => match self.feed(*src) { + Some(feed) => match feed.text() { + Some(text) => TV::Col(text, feed), + None => TV::Missing, + }, + None => TV::Missing, + }, + } + } + + fn find(hay: &[u8], needle: &[u8]) -> bool { + needle.is_empty() || hay.windows(needle.len()).any(|w| w == needle) + } + + fn mapped(func: Func, bytes: &[u8], d: &mut Reg, i: usize) -> bool { + if bytes.is_ascii() && func != Func::Trim { + let lo = d.text.len(); + d.text.extend_from_slice(bytes); + let tail = &mut d.text[lo..]; + match func { + Func::Upper => tail.make_ascii_uppercase(), + _ => tail.make_ascii_lowercase(), + } + d.span[i] = (lo as u32, d.text.len() as u32); + return true; + } + let Ok(text) = std::str::from_utf8(bytes) else { + return false; + }; + match func { + Func::Upper => d.push(i, text.to_uppercase().as_bytes()), + Func::Lower => d.push(i, text.to_lowercase().as_bytes()), + _ => d.push(i, text.trim().as_bytes()), + } + true + } + + fn faults(&self, d: &mut Reg, views: &[TV]) { + for w in 0..self.words.min(Reg::WORDS) { + d.valid[w] = u64::MAX; + d.fault[w] = views.iter().fold(0, |acc, v| acc | !v.ok(self.start, w)) & self.tail(w); + } + } + + pub(crate) fn text(&self, ins: &Ins, regs: &mut [Reg], act: Option<&[u64; Reg::WORDS]>) { + let (n, words, start) = (self.n, self.words.min(Reg::WORDS), self.start); + match ins { + Ins::EqText { ne, dst, a, b } => Self::def(regs, *dst, |d, regs| { + let (x, y) = (self.view(a, regs), self.view(b, regs)); + for w in 0..words { + d.valid[w] = u64::MAX; + d.fault[w] = (x.bad(start, w) | y.bad(start, w)) & self.tail(w); + } + let ne = *ne; + self.bools(act, &mut d.bits, |i| { + (x.get(start, i) == y.get(start, i)) != ne + }); + }), + Ins::Text { func, dst, a, b } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + let y = b.as_ref().map_or(TV::Lit(b""), |b| self.view(b, regs)); + self.faults(d, &[x, y]); + match (func, x) { + (Func::Len, TV::Col(Text::Str { offsets, .. }, _)) => { + for (m, p) in d.mant[..n] + .iter_mut() + .zip(offsets[start..=start + n].windows(2)) + { + *m = (p[1] - p[0]) as i64; + } + } + (Func::Len, TV::Lit(l)) => d.mant[..n].fill(l.len() as i64), + (Func::Len, x) => { + for (i, m) in d.mant[..n].iter_mut().enumerate() { + *m = x.get(start, i).map_or(0, |t| t.len() as i64); + } + } + (Func::StartsWith, TV::Col(Text::Str { offsets, data }, _)) + if act.is_none() && matches!(y, TV::Lit(_)) => + { + let p = match y { + TV::Lit(p) => p, + _ => b"", + }; + let offs = &offsets[start..=start + n]; + K::pack_idx(n, &mut d.bits[..words], |i| { + let (lo, hi) = (offs[i] as usize, offs[i + 1] as usize); + hi >= lo + p.len() && data.get(lo..lo + p.len()).is_some_and(|h| h == p) + }); + } + (Func::StartsWith | Func::EndsWith | Func::Contains, _) => { + let func = *func; + self.bools(act, &mut d.bits, |i| { + match (x.get(start, i), y.get(start, i)) { + (Some(a), Some(b)) => match func { + Func::StartsWith => a.starts_with(b), + Func::EndsWith => a.ends_with(b), + _ => Self::find(a, b), + }, + _ => false, + } + }) + } + _ => {} + } + }), + Ins::Matches { dst, a, pattern } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + self.faults(d, &[x]); + d.bits[..words].fill(0); + let skip = d.fault; + let mut broken = Vec::new(); + self.each(act, &skip, |i| { + match x.get(start, i).map(std::str::from_utf8) { + Some(Ok(t)) => Bits::set(&mut d.bits, i, pattern.is_match(t)), + _ => broken.push(i), + } + }); + broken + .into_iter() + .for_each(|i| Bits::set(&mut d.fault, i, true)); + }), + Ins::Map { func, dst, a } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + self.faults(d, &[x]); + d.texts(n); + let skip = d.fault; + let mut broken = Vec::new(); + self.each(act, &skip, |i| { + let ok = x + .get(start, i) + .is_some_and(|bytes| Self::mapped(*func, bytes, d, i)); + if !ok { + broken.push(i); + } + }); + broken + .into_iter() + .for_each(|i| Bits::set(&mut d.fault, i, true)); + }), + Ins::Concat { dst, parts } => Self::def(regs, *dst, |d, regs| { + let views: Vec = parts.iter().map(|p| self.view(p, regs)).collect(); + self.faults(d, &views); + d.texts(n); + let skip = d.fault; + self.each(act, &skip, |i| { + let lo = d.text.len() as u32; + for v in &views { + d.text + .extend_from_slice(v.get(start, i).unwrap_or_default()); + } + d.span[i] = (lo, d.text.len() as u32); + }); + }), + Ins::Str { dst, a, rep } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + for w in 0..words { + d.valid[w] = u64::MAX; + d.fault[w] = x.bad(start, w) & self.tail(w); + } + d.texts(n); + let skip = d.fault; + let mut scratch = String::new(); + let mut broken = Vec::new(); + match (rep, x) { + (Rep::Text, x) => self.each(act, &skip, |i| { + d.push(i, x.get(start, i).unwrap_or(b"null")) + }), + (Rep::Fix(_) | Rep::Dyn, TV::Reg(r)) => self.each(act, &skip, |i| { + scratch.clear(); + match (Bits::get(&r.valid, i), Bits::get(&r.wide, i)) { + (false, _) => scratch.push_str("null"), + (true, true) => scratch.push_str(&r.num(*rep, i).decimal().to_string()), + (true, false) => match rep.scale_at(r, i) { + s if s <= 28 => Scaled::write(r.mant[i], s, &mut scratch), + _ => broken.push(i), + }, + } + d.push(i, scratch.as_bytes()); + }), + (Rep::Bool, TV::Reg(r)) => self.each(act, &skip, |i| { + let text: &[u8] = match (Bits::get(&r.valid, i), Bits::get(&r.bits, i)) { + (false, _) => b"null", + (true, true) => b"true", + (true, false) => b"false", + }; + d.push(i, text); + }), + (Rep::Date, TV::Reg(r)) => { + self.each(act, &skip, |i| match Bits::get(&r.valid, i) { + true => d.push(i, r.date(i).to_string().as_bytes()), + false => d.push(i, b"null"), + }) + } + (Rep::Null, _) => self.each(act, &skip, |i| d.push(i, b"null")), + _ => d.fault[..words].fill(u64::MAX), + } + broken + .into_iter() + .for_each(|i| Bits::set(&mut d.fault, i, true)); + }), + Ins::Decode { dst, a, values } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + d.valid[..words].copy_from_slice(&a.valid[..words]); + d.fault[..words].copy_from_slice(&a.fault[..words]); + d.texts(n); + let mut skip = [0u64; Reg::WORDS]; + for (w, s) in skip.iter_mut().enumerate().take(words) { + *s = !a.valid[w] | a.fault[w]; + } + let mut broken = Vec::new(); + self.each(act, &skip, |i| { + match usize::try_from(a.codes[i]).ok().and_then(|c| values.get(c)) { + Some(text) => d.push(i, text.as_bytes()), + None => broken.push(i), + } + }); + broken + .into_iter() + .for_each(|i| Bits::set(&mut d.fault, i, true)); + }), + Ins::Class { dst, a, matcher } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + for w in 0..words { + d.valid[w] = x.ok(start, w); + d.fault[w] = x.bad(start, w) & self.tail(w); + } + for (i, c) in d.codes[..n].iter_mut().enumerate() { + *c = matcher.code(x.get(start, i)); + } + }), + _ => {} + } + } + + pub(crate) fn load_text(&self, d: &mut Reg, text: &Text) { + let (n, start) = (self.n, self.start); + d.texts(n); + match text { + Text::Str { offsets, data } => { + let (lo, hi) = (offsets[start] as usize, offsets[start + n] as usize); + d.text + .extend_from_slice(data.get(lo..hi).unwrap_or_default()); + for (s, p) in d.span[..n] + .iter_mut() + .zip(offsets[start..=start + n].windows(2)) + { + *s = ( + (p[0] as usize).saturating_sub(lo) as u32, + (p[1] as usize).saturating_sub(lo) as u32, + ); + } + } + Text::Dict { .. } => { + for i in 0..n { + if Bits::get(&d.valid, i) { + d.push(i, text.get(start + i).unwrap_or_default()); + } + } + } + } + } + + pub(crate) fn gather_text(&self, d: &mut Reg, b: &Buf, parent: &[u32]) { + d.texts(self.n); + for (i, &p) in parent.iter().enumerate() { + d.push(i, b.str(p as usize)); + } + } + + pub(crate) fn fill_text(&self, d: &mut Reg, b: &Buf) { + d.texts(self.n); + for i in 0..self.n { + d.push(i, b.str(self.start + i)); + } + } + + pub(crate) fn spill_text(&self, r: &Reg, b: &mut Buf) { + for i in 0..self.n { + b.spill(self.start + i, r.str(i)); + } + } + + pub(crate) fn blend_text(&self, d: &mut Reg, m: &[u64], t: &Reg, e: &Reg) { + d.texts(self.n); + for i in 0..self.n { + let src = match Bits::get(m, i) { + true => t, + false => e, + }; + if Bits::get(&src.valid, i) { + d.push(i, src.str(i)); + } + } + } + + pub(crate) fn pick_text(&self, d: &mut Reg, m: &[u64], a: &Reg) { + for (w, &word) in m.iter().enumerate() { + Bits::each(word & a.valid[w], w * 64, |i| d.push(i, a.str(i))); + } + } + + pub(crate) fn out_text(&self, r: &Reg, span: &mut [(u32, u32)], data: &mut Vec) { + for i in 0..self.n { + let lo = data.len() as u32; + if Bits::get(&r.valid, i) && !Bits::get(&r.fault, i) { + data.extend_from_slice(r.str(i)); + } + if let Some(s) = span.get_mut(self.start + i) { + *s = (lo, data.len() as u32); + } + } + } +} diff --git a/core/expression/src/vm/vm.rs b/core/expression/src/vm/vm.rs index 22ed6e5a..e4596265 100644 --- a/core/expression/src/vm/vm.rs +++ b/core/expression/src/vm/vm.rs @@ -687,7 +687,9 @@ impl<'arena, 'parent_ref, 'bytecode_ref> VMInner<'parent_ref, 'bytecode_ref> { let str_capacity = parts .iter() - .fold(separator.len() * (parts.len() - 1), |acc, s| acc + s.len()); + .fold(separator.len() * parts.len().saturating_sub(1), |acc, s| { + acc + s.len() + }); let mut s = StdString::with_capacity(str_capacity); let mut it = parts.into_iter().peekable(); diff --git a/core/expression/tests/conformance/mod.rs b/core/expression/tests/conformance/mod.rs new file mode 100644 index 00000000..364ecdd9 --- /dev/null +++ b/core/expression/tests/conformance/mod.rs @@ -0,0 +1,521 @@ +#![allow(dead_code)] + +use rust_decimal::Decimal; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use zen_expression::{ExpressionKind, Isolate, IsolateError, Variable}; + +#[derive(Debug, Clone)] +pub enum Expected { + Value(Variable), + Error, +} + +#[derive(Debug, Clone)] +pub struct SpecCase { + pub file: String, + pub line: usize, + pub kind: ExpressionKind, + pub expression: String, + pub input: Option, + pub input_text: String, + pub expected: Expected, + pub expected_text: String, + pub note: Note, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Note { + None, + Bug(String), + Question(String), +} + +impl SpecCase { + pub fn location(&self) -> String { + format!("{}:{}", self.file, self.line) + } + + pub fn environment(&self) -> Variable { + self.input + .as_ref() + .map_or(Variable::Null, |v| v.depth_clone(64)) + } + + pub fn stack(&self) -> Result { + Spec::guard(|| self.run_stack(|e| e.to_string()).map(Spec::settle)) + } + + pub fn exact(&self) -> Result { + Spec::guard(|| self.run_stack(Spec::describe).map(Spec::settle)) + } + + fn run_stack(&self, render: impl Fn(&IsolateError) -> String) -> Result { + let mut isolate = Isolate::new(); + if let Some(input) = &self.input { + isolate.set_environment(input.depth_clone(64)); + } + match self.kind { + ExpressionKind::Standard => isolate + .run_standard(&self.expression) + .map_err(|e| render(&e)), + ExpressionKind::Unary => isolate + .run_unary(&self.expression) + .map(Variable::Bool) + .map_err(|e| render(&e)), + } + } + + pub fn verdict(&self, got: &Result) -> Option { + match (&self.expected, got) { + (Expected::Error, Err(e)) if !e.starts_with(Spec::PANIC) => None, + (Expected::Value(want), Ok(v)) if Spec::same(want, v) => None, + (_, got) => Some(format!( + "{} | {} | input {} | expected {} | got {}", + self.location(), + self.expression, + if self.input_text.is_empty() { + "-" + } else { + &self.input_text + }, + self.expected_text, + match got { + Ok(v) => Spec::render(v), + Err(e) => format!("!error ({e})"), + } + )), + } + } +} + +pub struct Spec; + +impl Spec { + pub const PANIC: &'static str = "PANIC"; + + pub fn no_fallbacks() { + assert_eq!( + zen_expression::lane::Fallbacks::reached(), + 0, + "lane reached a NumberConversionError fallback without a recorded fault" + ); + } + + pub fn describe(error: &IsolateError) -> String { + format!("{error} {error:?}") + } + + pub fn settle(v: Variable) -> Variable { + let _ = v.to_value(); + v + } + + pub fn guard(f: impl FnOnce() -> Result) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|payload| { + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string())) + .unwrap_or_default(); + Err(format!("{}: {message}", Self::PANIC)) + }) + } + + pub fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("spec") + } + + pub fn prepare() { + std::env::set_var( + "TZ", + std::env::var("SPEC_TZ").unwrap_or_else(|_| "UTC".to_string()), + ); + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + } + + pub fn files() -> Vec<(ExpressionKind, PathBuf)> { + let filter = std::env::var("SPEC_FILE").ok(); + let mut out = Vec::new(); + for (dir, kind) in [ + ("standard", ExpressionKind::Standard), + ("unary", ExpressionKind::Unary), + ] { + let Ok(entries) = std::fs::read_dir(Self::root().join(dir)) else { + continue; + }; + let mut paths: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "csv")) + .filter(|p| { + filter + .as_ref() + .is_none_or(|f| p.to_string_lossy().contains(f.as_str())) + }) + .collect(); + paths.sort(); + out.extend(paths.into_iter().map(|p| (kind.clone(), p))); + } + out + } + + pub fn cases() -> (Vec, Vec) { + let mut cases = Vec::new(); + let mut problems = Vec::new(); + for (kind, path) in Self::files() { + let name = path + .strip_prefix(Self::root()) + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(); + let text = match std::fs::read_to_string(&path) { + Ok(t) => t, + Err(e) => { + problems.push(format!("{name}: {e}")); + continue; + } + }; + let lines: Vec<&str> = text.lines().collect(); + let mut reader = csv::ReaderBuilder::new() + .delimiter(b';') + .has_headers(false) + .flexible(true) + .comment(Some(b'#')) + .from_reader(text.as_bytes()); + for record in reader.records() { + let record = match record { + Ok(r) => r, + Err(e) => { + problems.push(format!("{name}: {e}")); + continue; + } + }; + let mut line = record.position().map_or(0, |p| p.line() as usize); + while lines + .get(line.wrapping_sub(1)) + .is_some_and(|l| l.starts_with('#') || l.trim().is_empty()) + { + line += 1; + } + let field = |i: usize| record.get(i).unwrap_or_default().trim().to_string(); + let (expression, input_text, expected_text, note_text) = + (field(0), field(1), field(2), field(3)); + if expression.is_empty() || expression.starts_with("expression (") { + continue; + } + if record.len() < 3 { + problems.push(format!( + "{name}:{line}: expected 3 fields, got {}", + record.len() + )); + continue; + } + let input = match input_text.as_str() { + "" => None, + t => match Literal::parse(t) { + Ok(v) => Some(v), + Err(e) => { + problems.push(format!("{name}:{line}: input {t}: {e}")); + continue; + } + }, + }; + let expected = match expected_text.as_str() { + t if t.starts_with("!error") => Expected::Error, + t => match Literal::parse(t) { + Ok(v) => Expected::Value(v), + Err(e) => { + problems.push(format!("{name}:{line}: output {t}: {e}")); + continue; + } + }, + }; + let note = match note_text.split_once(':') { + None if note_text.is_empty() => Note::None, + Some(("bug", text)) => Note::Bug(text.trim().to_string()), + Some(("question", text)) => Note::Question(text.trim().to_string()), + _ => { + problems.push(format!("{name}:{line}: note must be `bug: ...` or `question: ...`, got {note_text:?}")); + continue; + } + }; + cases.push(SpecCase { + file: name.clone(), + line, + kind: kind.clone(), + expression, + input, + input_text, + expected, + expected_text, + note, + }); + } + } + (cases, problems) + } + + pub fn same(want: &Variable, got: &Variable) -> bool { + match (want, got) { + (Variable::Null, Variable::Null) => true, + (Variable::Bool(a), Variable::Bool(b)) => a == b, + (Variable::Number(a), Variable::Number(b)) => a == b, + (Variable::String(a), Variable::String(b)) => a == b, + (Variable::String(a), Variable::Dynamic(d)) => a.as_str() == d.to_string(), + (Variable::Dynamic(a), Variable::Dynamic(b)) => { + a.type_name() == b.type_name() && a.to_string() == b.to_string() + } + (Variable::Array(a), Variable::Array(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| Self::same(x, y)) + } + (Variable::Object(a), Variable::Object(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + a.len() == b.len() + && a.iter() + .all(|(k, x)| b.get(k).is_some_and(|y| Self::same(x, y))) + } + _ => false, + } + } + + pub fn render(v: &Variable) -> String { + match v { + Variable::Null => "null".to_string(), + Variable::Bool(b) => b.to_string(), + Variable::Number(n) => n.to_string(), + Variable::String(s) => Self::quote(s), + Variable::Dynamic(d) => Self::quote(&d.to_string()), + Variable::Array(a) => format!( + "[{}]", + a.borrow() + .iter() + .map(Self::render) + .collect::>() + .join(", ") + ), + Variable::Object(o) => { + let o = o.borrow(); + let mut entries: Vec<(String, String)> = o + .iter() + .map(|(k, v)| (k.to_string(), Self::render(v))) + .collect(); + entries.sort(); + format!( + "{{{}}}", + entries + .iter() + .map(|(k, v)| format!("{}: {v}", Self::quote(k))) + .collect::>() + .join(", ") + ) + } + } + } + + fn quote(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + } + out.push('"'); + out + } +} + +pub struct Literal<'a> { + text: &'a str, + at: usize, +} + +impl<'a> Literal<'a> { + pub fn parse(text: &'a str) -> Result { + let mut p = Literal { text, at: 0 }; + let v = p.value()?; + p.space(); + match p.at == p.text.len() { + true => Ok(v), + false => Err(format!("trailing input at {}", p.at)), + } + } + + fn rest(&self) -> &'a str { + self.text.get(self.at..).unwrap_or_default() + } + + fn peek(&self) -> Option { + self.rest().chars().next() + } + + fn space(&mut self) { + while self.peek().is_some_and(char::is_whitespace) { + self.at += 1; + } + } + + fn eat(&mut self, c: char) -> Result<(), String> { + self.space(); + match self.peek() { + Some(x) if x == c => { + self.at += c.len_utf8(); + Ok(()) + } + other => Err(format!("expected {c:?} at {}, found {other:?}", self.at)), + } + } + + fn value(&mut self) -> Result { + self.space(); + match self.peek() { + Some('[') => { + self.at += 1; + let mut items = Vec::new(); + loop { + self.space(); + if self.peek() == Some(']') { + self.at += 1; + break; + } + items.push(self.value()?); + self.space(); + match self.peek() { + Some(',') => self.at += 1, + Some(']') => {} + other => { + return Err(format!("expected , or ] at {}, found {other:?}", self.at)) + } + } + } + Ok(Variable::from_array(items)) + } + Some('{') => { + self.at += 1; + let object = Variable::empty_object(); + loop { + self.space(); + if self.peek() == Some('}') { + self.at += 1; + break; + } + let key = match self.peek() { + Some('"' | '\'') => self.string()?, + _ => match self.word() { + w if w.is_empty() => { + return Err(format!("expected key at {}", self.at)) + } + w => w, + }, + }; + self.eat(':')?; + let value = self.value()?; + if let Variable::Object(map) = &object { + map.borrow_mut().insert(key.as_str().into(), value); + } + self.space(); + match self.peek() { + Some(',') => self.at += 1, + Some('}') => {} + other => { + return Err(format!("expected , or }} at {}, found {other:?}", self.at)) + } + } + } + Ok(object) + } + Some('"' | '\'') => Ok(Variable::String(self.string()?.as_str().into())), + Some(c) if c == '-' || c == '+' || c.is_ascii_digit() || c == '.' => self.number(), + _ => match self.word().as_str() { + "date" => { + self.eat('(')?; + self.space(); + let text = self.string()?; + self.eat(')')?; + zen_expression::DateValue::from_text(&text) + .ok_or_else(|| format!("invalid date input {text:?}")) + } + "true" => Ok(Variable::Bool(true)), + "false" => Ok(Variable::Bool(false)), + "null" => Ok(Variable::Null), + other => Err(format!("unexpected {other:?} at {}", self.at)), + }, + } + } + + fn word(&mut self) -> String { + let start = self.at; + while self + .peek() + .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') + { + self.at += self.peek().map_or(1, char::len_utf8); + } + self.text + .get(start..self.at) + .unwrap_or_default() + .to_string() + } + + fn number(&mut self) -> Result { + let start = self.at; + while self + .peek() + .is_some_and(|c| c.is_ascii_digit() || matches!(c, '-' | '+' | '.' | 'e' | 'E' | '_')) + { + self.at += 1; + } + let raw: String = self + .text + .get(start..self.at) + .unwrap_or_default() + .chars() + .filter(|c| *c != '_' && *c != '+') + .collect(); + let parsed = match raw.contains(['e', 'E']) { + true => Decimal::from_scientific(&raw), + false => Decimal::from_str(&raw), + }; + parsed + .map(Variable::Number) + .map_err(|e| format!("number {raw:?}: {e}")) + } + + fn string(&mut self) -> Result { + let quote = self.peek().ok_or("expected string")?; + self.at += 1; + let mut out = String::new(); + loop { + let c = self.peek().ok_or("unterminated string")?; + self.at += c.len_utf8(); + match c { + c if c == quote => return Ok(out), + '\\' => { + let e = self.peek().ok_or("unterminated escape")?; + self.at += e.len_utf8(); + match e { + 'n' => out.push('\n'), + 't' => out.push('\t'), + 'r' => out.push('\r'), + '0' => out.push('\0'), + 'u' => { + let hex = self.text.get(self.at..self.at + 4).ok_or("short \\u")?; + let code = u32::from_str_radix(hex, 16).map_err(|e| e.to_string())?; + out.push(char::from_u32(code).ok_or("bad \\u")?); + self.at += 4; + } + other => out.push(other), + } + } + c => out.push(c), + } + } + } +} diff --git a/core/expression/tests/lane.rs b/core/expression/tests/lane.rs new file mode 100644 index 00000000..c048f7e4 --- /dev/null +++ b/core/expression/tests/lane.rs @@ -0,0 +1,4430 @@ +mod conformance; + +use rust_decimal::Decimal; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::ops::Index; +use zen_expression::lane::{Column, Columns, Fusion, LaneProgram, LaneRunner, Output, Values}; +use zen_expression::variable::VariableType; +use zen_expression::{ExpressionKind, Isolate, Scope, Variable}; + +struct Case { + expression: String, + input: Value, +} + +struct Differential { + kind: ExpressionKind, + runner: LaneRunner, + failures: Vec, + compared: usize, + outcomes: [usize; 3], +} + +impl Differential { + fn new(kind: ExpressionKind) -> Self { + std::env::set_var( + "TZ", + std::env::var("LANE_TZ").unwrap_or_else(|_| "UTC".to_string()), + ); + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + Self { + kind, + runner: LaneRunner::new(), + failures: Vec::new(), + compared: 0, + outcomes: [0; 3], + } + } + + fn cases(csv_data: &str) -> Vec { + let mut reader = csv::ReaderBuilder::new() + .delimiter(b';') + .from_reader(csv_data.as_bytes()); + reader + .records() + .flatten() + .filter(|row| !row.index(0).starts_with('#')) + .map(|row| Case { + expression: row.index(0).to_string(), + input: match row.index(1) { + "" => Value::Null, + s => serde_json5::from_str(s).unwrap_or(Value::Null), + }, + }) + .collect() + } + + fn stack(&self, expression: &str, input: &Value) -> Result { + match input.is_null() { + true => self.stack_of(expression, None), + false => self.stack_of(expression, Some(input.clone().into())), + } + } + + fn stack_of(&self, expression: &str, input: Option) -> Result { + let mut isolate = Isolate::new(); + if let Some(input) = input { + isolate.set_environment(input); + } + match self.kind { + ExpressionKind::Standard => isolate + .run_standard(expression) + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)), + ExpressionKind::Unary => isolate + .run_unary(expression) + .map(Value::Bool) + .map_err(|e| conformance::Spec::describe(&e)), + } + } + + fn lane( + &self, + result: Result, + ) -> Result { + match (self.kind.clone(), result) { + (ExpressionKind::Standard, r) => r + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)), + (ExpressionKind::Unary, Ok(v)) => v.as_bool().map(Value::Bool).ok_or_else(|| { + conformance::Spec::describe(&zen_expression::IsolateError::ValueCastError) + }), + (ExpressionKind::Unary, Err(e)) => Err(conformance::Spec::describe(&e)), + } + } + + fn scope(input: &Value) -> Scope { + match input { + Value::Null => Scope::default(), + v => Scope::new(v.clone().into()), + } + } + + fn check(&mut self, expression: &str, inputs: &[Value]) { + let program = LaneProgram::compile(expression, self.kind.clone()); + let expected: Vec> = + inputs.iter().map(|i| self.stack(expression, i)).collect(); + for exp in &expected { + match exp { + Ok(_) => self.outcomes[0] += 1, + Err(_) => self.outcomes[1] += 1, + } + } + let program = match program { + Ok(p) => p, + Err(e) => { + self.outcomes[2] += 1; + for (input, exp) in inputs.iter().zip(&expected) { + self.compared += 1; + if exp.as_ref().err() != Some(&conformance::Spec::describe(&e)) { + self.failures.push(format!( + "{expression} | input {input} | compile: lane {e} vs stack {exp:?}" + )); + } + } + return; + } + }; + + let scopes: Vec = inputs.iter().map(Self::scope).collect(); + if let Some(first) = inputs.first() { + let typed = LaneProgram::compile_typed( + expression, + self.kind.clone(), + &VariableType::from(first), + ) + .expect("typed compile"); + let batch = self.runner.evaluate(&typed, &scopes); + for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { + self.compared += 1; + let got = self.lane(got); + if &got != exp { + self.failures.push(format!( + "{expression} | input {input} | typed from first input | lane {got:?} vs stack {exp:?}" + )); + } + } + } + let specialized = program.specialize(&scopes).expect("specialize"); + for (input, exp) in inputs.iter().zip(&expected) { + let got = self.runner.evaluate_one(&specialized, &Self::scope(input)); + let got = self.lane(got); + self.compared += 1; + if &got != exp { + self.failures.push(format!( + "{expression} | input {input} | specialized | lane {got:?} vs stack {exp:?}" + )); + } + } + let batch = self.runner.evaluate(&specialized, &scopes); + for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { + self.compared += 1; + let got = self.lane(got); + if &got != exp { + self.failures.push(format!( + "{expression} | input {input} | specialized batch | lane {got:?} vs stack {exp:?}" + )); + } + } + let batch = self.runner.evaluate(&program, &scopes); + for ((input, exp), got) in inputs.iter().zip(&expected).zip(batch) { + self.compared += 1; + let got = self.lane(got); + if &got != exp { + self.failures.push(format!( + "{expression} | input {input} | width {} | lane {got:?} vs stack {exp:?}", + inputs.len().min(64) + )); + } + } + + for (input, exp) in inputs.iter().zip(&expected) { + let got = self.runner.evaluate_one(&program, &Self::scope(input)); + let got = self.lane(got); + self.compared += 1; + if &got != exp { + self.failures.push(format!( + "{expression} | input {input} | width 1 | lane {got:?} vs stack {exp:?}" + )); + } + } + } + + fn columns(&mut self, expression: &str, inputs: &[Value]) { + let Ok(program) = LaneProgram::compile(expression, self.kind.clone()) else { + return; + }; + let inputs: Vec = inputs + .iter() + .cycle() + .take(inputs.len().max(72)) + .cloned() + .collect(); + let inputs = inputs.as_slice(); + let owned = Owned::build(inputs); + let texts: Vec> = owned + .texts + .iter() + .map(|t| t.iter().map(String::as_str).collect()) + .collect(); + let children = owned.children(&texts); + let columns = owned.columns(&texts, &children); + let rows: Vec = (0..inputs.len()) + .map(|r| columns.row(r).to_value()) + .collect(); + let expected: Vec> = (0..inputs.len()) + .map(|r| self.stack_of(expression, Some(columns.row(r)))) + .collect(); + for program in [ + program.clone(), + program.specialize_columns(&columns).expect("specialize"), + ] { + let mut raw = Vec::new(); + self.runner + .evaluate_columns(&program, &columns, |i, r| raw.push((i, r))); + let mut got = vec![Err(String::new()); inputs.len()]; + for (i, r) in raw { + got[i] = self.lane_of(r); + } + for ((row, exp), got) in rows.iter().zip(&expected).zip(got) { + self.compared += 1; + if &got != exp { + self.failures.push(format!( + "{expression} | row {row} | columns | lane {got:?} vs stack {exp:?}" + )); + } + } + let mut out = Output::new(); + self.runner + .evaluate_columns_into(&program, &columns, &mut out); + for (i, (row, exp)) in rows.iter().zip(&expected).enumerate() { + self.compared += 1; + let got = match out.variable(i) { + Some(r) => self.lane_of( + r.map_err(|source| zen_expression::IsolateError::VMError { source }), + ), + None => Err("missing row".to_string()), + }; + if &got != exp { + self.failures.push(format!( + "{expression} | row {row} | columns-out | lane {got:?} vs stack {exp:?}" + )); + } + } + } + } + + fn lane_of( + &self, + result: Result, + ) -> Result { + self.lane(result) + } + + fn file(&mut self, csv_data: &str) { + let cases = Self::cases(csv_data); + let mut inputs: Vec = Vec::new(); + for case in &cases { + if !inputs.contains(&case.input) { + inputs.push(case.input.clone()); + } + } + for case in &cases { + self.check(&case.expression, std::slice::from_ref(&case.input)); + self.check(&case.expression, &inputs); + self.columns(&case.expression, &inputs); + } + } + + fn assert(self) { + eprintln!( + "compared {} | expected ok {} err {} | compile errors {}", + self.compared, self.outcomes[0], self.outcomes[1], self.outcomes[2] + ); + assert!(self.compared > 0); + let shown: Vec<&String> = self.failures.iter().take(40).collect(); + assert!( + self.failures.is_empty(), + "{} of {} comparisons differ:\n{}", + self.failures.len(), + self.compared, + shown + .iter() + .map(|s| s.as_str()) + .collect::>() + .join("\n") + ); + } +} + +struct Owned { + rows: usize, + keys: Vec, + data: Vec, + texts: Vec>, + valid: Vec>, +} + +enum OwnedValues { + I64(Vec), + Dec(Vec), + Bool(Vec), + Str(usize), + Utf8(Vec, Vec), + Dict(Vec, usize), + List(Vec, OwnedChild), + Any(Vec), +} + +enum OwnedChild { + I64(Vec), + Dec(Vec), + Str(usize), +} + +impl Owned { + fn flatten(value: &Value, prefix: String, out: &mut BTreeMap) { + match value { + Value::Object(map) if !map.is_empty() => { + for (k, v) in map { + let path = if prefix.is_empty() { + k.clone() + } else { + format!("{prefix}.{k}") + }; + Self::flatten(v, path, out); + } + } + v if !prefix.is_empty() => { + out.insert(prefix, v.clone()); + } + _ => {} + } + } + + fn build(inputs: &[Value]) -> Self { + let flat: Vec> = inputs + .iter() + .map(|v| { + let mut m = BTreeMap::new(); + Self::flatten(v, String::new(), &mut m); + m + }) + .collect(); + let mut keys: Vec = flat.iter().flat_map(|m| m.keys().cloned()).collect(); + keys.sort(); + keys.dedup(); + let rows = inputs.len(); + let mut data = Vec::new(); + let mut texts = Vec::new(); + let mut valid = Vec::new(); + for key in &keys { + let values: Vec> = flat.iter().map(|m| m.get(key)).collect(); + let mut bits = vec![0u64; rows.div_ceil(64).max(1)]; + for (i, v) in values.iter().enumerate() { + if v.is_some_and(|v| !v.is_null()) { + bits[i / 64] |= 1 << (i % 64); + } + } + let present: Vec<&Value> = values + .iter() + .flatten() + .copied() + .filter(|v| !v.is_null()) + .collect(); + let all = |f: fn(&Value) -> bool| !present.is_empty() && present.iter().all(|v| f(v)); + let column = if all(|v| v.as_i64().is_some() && !v.to_string().contains('.')) { + OwnedValues::I64( + values + .iter() + .map(|v| v.and_then(Value::as_i64).unwrap_or(0)) + .collect(), + ) + } else if all(Value::is_number) { + OwnedValues::Dec( + values + .iter() + .map(|v| match v.map(|v| Variable::from(v.clone())) { + Some(Variable::Number(n)) => n, + _ => Decimal::ZERO, + }) + .collect(), + ) + } else if all(Value::is_boolean) { + let mut words = vec![0u64; rows.div_ceil(64).max(1)]; + for (i, v) in values.iter().enumerate() { + if v.and_then(Value::as_bool) == Some(true) { + words[i / 64] |= 1 << (i % 64); + } + } + OwnedValues::Bool(words) + } else if all(Value::is_string) && key.len() % 2 == 1 { + let mut distinct: Vec = Vec::new(); + let codes = values + .iter() + .map(|v| { + let text = v.and_then(Value::as_str).unwrap_or_default(); + match distinct.iter().position(|d| d == text) { + Some(i) => i as i32, + None => { + distinct.push(text.to_string()); + (distinct.len() - 1) as i32 + } + } + }) + .collect(); + texts.push(distinct); + OwnedValues::Dict(codes, texts.len() - 1) + } else if all(Value::is_string) && key.len() % 4 == 0 { + let mut offsets = vec![0i32]; + let mut bytes = Vec::new(); + for v in &values { + bytes.extend_from_slice( + v.and_then(Value::as_str).unwrap_or_default().as_bytes(), + ); + offsets.push(bytes.len() as i32); + } + OwnedValues::Utf8(offsets, bytes) + } else if all(Value::is_string) { + texts.push( + values + .iter() + .map(|v| v.and_then(Value::as_str).unwrap_or_default().to_string()) + .collect(), + ); + OwnedValues::Str(texts.len() - 1) + } else if all(|v| v.as_array().is_some_and(|a| a.iter().all(Value::is_number))) + || all(|v| v.as_array().is_some_and(|a| a.iter().all(Value::is_string))) + { + let numbers = present + .iter() + .all(|v| v.as_array().is_some_and(|a| a.iter().all(Value::is_number))); + let mut offsets = vec![0i32]; + let mut items: Vec<&Value> = Vec::new(); + for v in &values { + if let Some(array) = v.and_then(Value::as_array) { + items.extend(array.iter()); + } + offsets.push(items.len() as i32); + } + let ints = items + .iter() + .all(|v| v.as_i64().is_some() && !v.to_string().contains('.')); + let child = match numbers { + true if ints && key.len() % 2 == 0 => { + OwnedChild::I64(items.iter().filter_map(|v| v.as_i64()).collect()) + } + true => OwnedChild::Dec( + items + .iter() + .map(|v| match Variable::from((*v).clone()) { + Variable::Number(n) => n, + _ => Decimal::ZERO, + }) + .collect(), + ), + false => { + texts.push( + items + .iter() + .map(|v| v.as_str().unwrap_or_default().to_string()) + .collect(), + ); + OwnedChild::Str(texts.len() - 1) + } + }; + OwnedValues::List(offsets, child) + } else { + OwnedValues::Any( + values + .iter() + .map(|v| v.map_or(Variable::Null, |v| Variable::from(v.clone()))) + .collect(), + ) + }; + data.push(column); + valid.push(bits); + } + Self { + rows, + keys, + data, + texts, + valid, + } + } + + fn children<'a>(&'a self, texts: &'a [Vec<&'a str>]) -> Vec> { + self.data + .iter() + .map(|data| match data { + OwnedValues::Dict(_, i) => Column::new(Values::Strs(&texts[*i])), + OwnedValues::List(_, OwnedChild::I64(v)) => Column::new(Values::I64(v)), + OwnedValues::List(_, OwnedChild::Dec(v)) => Column::new(Values::Dec(v)), + OwnedValues::List(_, OwnedChild::Str(i)) => Column::new(Values::Strs(&texts[*i])), + _ => Column::new(Values::Any(&[])), + }) + .collect() + } + + fn columns<'a>(&'a self, texts: &'a [Vec<&'a str>], children: &'a [Column<'a>]) -> Columns<'a> { + let mut columns = Columns::new(self.rows); + for (((key, data), valid), child) in self + .keys + .iter() + .zip(&self.data) + .zip(&self.valid) + .zip(children) + { + let values = match data { + OwnedValues::I64(v) => Values::I64(v), + OwnedValues::Dec(v) => Values::Dec(v), + OwnedValues::Bool(bits) => Values::Bool { bits, offset: 0 }, + OwnedValues::Str(i) => Values::Strs(&texts[*i]), + OwnedValues::Utf8(offsets, data) => Values::Utf8 { offsets, data }, + OwnedValues::Dict(keys, _) => Values::Dict { + keys, + values: child.into(), + }, + OwnedValues::List(offsets, _) => Values::List { + offsets, + child: child.into(), + }, + OwnedValues::Any(v) => Values::Any(v), + }; + columns = columns.column(key, Column::with_validity(values, valid, 0)); + } + columns + } +} + +#[test] +fn lane_matches_stack_vm_standard_csv() { + let mut d = Differential::new(ExpressionKind::Standard); + d.file(include_str!("data/standard.csv")); + d.assert(); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_matches_stack_vm_date_csv() { + let mut d = Differential::new(ExpressionKind::Standard); + d.file(include_str!("data/date.csv")); + d.assert(); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_matches_stack_vm_unary_csv() { + let mut d = Differential::new(ExpressionKind::Unary); + d.file(include_str!("data/unary.csv")); + d.assert(); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_struct_outputs_stay_typed() { + let inputs = vec![ + json!({"a": 1, "s": "x"}), + json!({"a": 2.5, "s": "yy"}), + json!({"a": "bad", "s": null}), + ]; + let owned = Owned::build(&inputs); + let texts: Vec> = owned + .texts + .iter() + .map(|t| t.iter().map(String::as_str).collect()) + .collect(); + let children = owned.children(&texts); + let columns = owned.columns(&texts, &children); + let program = LaneProgram::compile("{n: a * 2, t: s, p: [a, a + 1]}", ExpressionKind::Standard) + .expect("compile") + .specialize_columns(&columns) + .expect("specialize"); + let mut runner = LaneRunner::new(); + let mut out = Output::new(); + runner.evaluate_columns_into(&program, &columns, &mut out); + let fields = out.fields(); + assert_eq!( + fields.iter().map(|(k, _)| k.as_ref()).collect::>(), + ["n", "t", "p"] + ); + assert_eq!(fields[0].1.kind(), zen_expression::lane::Kind::Num); + assert_eq!(fields[1].1.kind(), zen_expression::lane::Kind::Str); + assert_eq!(fields[0].1.mantissas()[..2], [2, 50]); + assert_eq!(fields[0].1.scales()[..2], [0, 1]); + assert_eq!(fields[1].1.text(1), Some("yy")); + let list = fields[2].1.child().expect("list"); + assert_eq!(list.kind(), zen_expression::lane::Kind::Num); + assert_eq!(fields[2].1.offsets()[..3], [0, 2, 4]); + assert_eq!(list.mantissas()[..4], [1, 2, 25, 35]); + assert_eq!(list.scales()[..4], [0, 0, 1, 1]); + assert!(out.failed()[0] >> 2 & 1 == 1); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_matches_stack_vm_special_cases() { + let mut d = Differential::new(ExpressionKind::Standard); + let inputs = vec![ + json!({}), + json!({"a": 1, "b": [1, 2, 3], "s": "abc", "o": {"x": 1}}), + json!({"a": "x", "b": null, "s": 5}), + Value::Null, + json!({"s": "abc", "i": 18446744073709551615u64}), + ]; + let expressions = [ + "r = map([1,2,3] as x, (y = x * 2; y + 1)); r", + "r = flatMap([[1],[2,3]] as x, (y = x; y)); r", + "r = map([1,2] as x, map([10,20] as z, (y = x * z; y))); r", + "a = map([1] as x, (y = x; y)); b = a[0] + 1; b", + "d('2020-01-01').add(10000000000000000, 's').isValid()", + "s[i]", + "79228162514264337593543950335 + 1", + "sum([79228162514264337593543950335, 79228162514264337593543950335])", + "1 / 0", + "1 % 0", + "#", + "map(b, # + a)", + "map(b, map(b as y, # + y))", + "filter(b, # > 1)", + "some(b, # == 'x')", + "all(b, # > 0)", + "none(b, #)", + "one(b, # == 2)", + "count(b, # > 1)", + "a and b", + "a or b", + "a ?? b ?? 3", + "a ? 1 : 2", + "$root", + "$root.a", + "x = 1; y = x + a; {x, y}", + "o.x", + "o['x']", + "b[1]", + "b[1:2]", + "s[1:]", + "`${a} and ${s}`", + "{a: 1, [s]: 2}", + "{x: a, y: s, z: {w: a + 1, v: [a, a * 2]}}", + "{x: a, x: s}", + "{x: 1 / 0, y: a}", + "{x: a.y.z, y: len(b)}", + "[a, s, o]", + "[a, a, a + 1]", + "[s, s]", + "[]", + "{}", + "[{x: a}, {x: s}]", + "{items: map(b, # * 2), n: count(b, # > 1), d: d('2024-01-01')}", + "{c: s == 'abc', t: [true, a == 1]}", + "{x: 'lit', y: 'lit', z: 1}", + "[1, 1, 'q']", + "max([a, 2])", + "min([a, 2, -1.5])", + "max([1, 1.0, 1.00])", + "min([1.00, 1.0, 1])", + "max([a, s])", + "min([a])", + "max([a * 2, a + 1, 0.5])", + "sum(b)", + "avg(b)", + "min(b)", + "max(b)", + "sum(map(b, # * 1.5))", + "avg(map(b, # / 3))", + "max(map(b, # * -1))", + "min(filter(b, # > 1))", + "sum(filter(b, # > 5))", + "sum(map(b, # * 0.5 - 1))", + "sum(map(b, 0.5 - # * 0.5))", + "sum(map(b, # * 0.10))", + "max(map(b, # * 0.5))", + "min(map(b, # * 1.0 - 2))", + "map(filter(b, # > 1), # * 0.5)", + "max(filter(b, # > 99))", + "min(filter(b, # > 99))", + "max(map(b, 'x' + string(#)))", + "min(map(b, d('2024-01-01').add(#, 'd')))", + "max(map(b, # > 1))", + "max(map(b, # * 0.5)) + 1", + "len(map(b, #))", + "{x: map(b, # * 2), y: filter(b, # > 1), z: count(b, # > 1)}", + "map(b, [#, # * 2])", + "map(b, {v: #})", + "filter(b, # > 1) == [2, 3]", + "a in [1, 2]", + "a not in [1, 2]", + "a in [0..5]", + "not a", + "-a", + "a ^ 2", + "a == b", + "a != b", + "len(b)", + "some(b, # == 2) and all(b, # > 0)", + "map(1..3, # * 2)", + "map(b, x = #; x)", + "a * 7.40 + a * 7.4", + "(a ? 1.50 : 1.5) + 0.0", + "[1.0, 1.00, 1] == [1, 1, 1]", + "a in [2.0, 2.00]", + "map([1, 2, 3] as y, map([{x: 1}], o[#.x] in [y, #]))", + "v = a; w = all(['x', 'y'], # == 'y' and v = #; true); v", + "a in [1..10]", + "a in (1..10)", + "a in ]1..10[", + "a in [1..10)", + "a not in [2..3]", + "s in [1..10]", + "zz in [1..10]", + "b in [10..1]", + "date(s) in [1..2]", + "map(b, # in [1.5..2.50])", + "a == 1 or a == 2 or a == 3", + "s == 'abc' or (s == 'x' or s == null)", + "b == 1 or b == 2", + "zz == null or zz == 1", + "a == 1 or s == 'abc'", + "map(b, # == 2 or # == 3)", + "a == 1.0 or a == 2.00", + "a * 1.5 + a > 10", + "(a - 2) * 3 / 4", + "a / (a - a) + 1", + "a % (a - a) * 2", + "zz * 2 + 1", + "s * 2 + 1", + "a * 2 + s > 1", + "2 * 3 + a", + "(2 * 3) + (4 / 8) < a", + "a * 79228162514264337593543950335 + 1", + "a - 79228162514264337593543950335 * 2 > 0", + "a + (a * 1 + (a * 2 + (a * 3 + (a * 4 + (a * 5 + (a * 6 + (a * 7 + (a * 8 + (a * 9 + (a * 10 + (a * 11 + (a * 12 + (a * 13 + (a * 14 + (a * 15 + (a * 16 + (a * 17 + (a * 18 + (a * 19)))))))))))))))))))", + "map(b, # * 2 + 1 > 3)", + "a * 1.10 + 0.90", + "a / 3 * 3 == a", + "a == 1 and b > 2", + "a == 1 and s == 'abc' and 5 < a", + "a != 1 or s == 'abc' or b >= 3", + "(a == 1 and (s == 'abc' and zz == null))", + "s > 1 and a == 1", + "a == 1 and s > 1", + "a == 2 or s > 1", + "s > 1 or a == 2", + "map(b, # > 1 and # < 3)", + "a == 1 and b > 2 or s == 'x'", + "a * 1.5 + a - 0.25", + "a * 0 + 0.000 - a", + "(a - a) + (a - a) * 1.00", + "0.000 - (a - a)", + "a * 3.10 - a * 3.1 > 0", + "a * 1.25 + a * 2 >= 7.5", + "a * 922337203685477580 + a * 922337203685477580", + "a * 0.0000000000000000000001 * 0.00000001 + 1", + "a - 9223372036854775807 - 9223372036854775807 < 0", + "zz * 2 + 1", + "s * 2 + a", + "a + zz * 2 > 1", + "x = 3; x * a + 1", + "(0 - (a - a) * 1.00) * 2 + a * 0.50", + "(-0.00) * a + a - 0.5 * a", + "len(s)", + "contains(s, 'b')", + "contains(s, 1)", + "startsWith(s, 'a')", + "endsWith(s, 'c')", + "upper(s) + lower(s) + trim(s)", + "len(zz)", + "lower(a)", + "sum(b)", + "avg(b)", + "min(b)", + "max(b)", + "len(b)", + "contains(b, 2)", + "contains(b, 'x')", + "sum(zz)", + "date(s)", + "v = a; w = some(['x', 'y'], # == 'x' or v = #; false); v", + ]; + for e in expressions { + d.columns(e, &inputs); + d.check(e, &inputs); + for input in &inputs { + d.check(e, std::slice::from_ref(input)); + } + } + d.assert(); + conformance::Spec::no_fallbacks(); +} + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + + fn chance(&mut self, pct: usize) -> bool { + self.below(100) < pct + } + + fn pick<'a>(&mut self, items: &[&'a str]) -> &'a str { + items[self.below(items.len())] + } +} + +struct Generator<'r> { + rng: &'r mut Rng, + closures: usize, + aliases: Vec<&'static str>, +} + +impl Generator<'_> { + const FIELDS: [&'static str; 14] = [ + "a", "b", "c", "s", "t", "flag", "items", "tags", "o", "o.x", "o.y.z", "missing", "n", + "list", + ]; + const FUNCTIONS: [(&'static str, usize); 22] = [ + ("len", 1), + ("abs", 1), + ("round", 1), + ("floor", 1), + ("ceil", 1), + ("sum", 1), + ("min", 1), + ("max", 1), + ("avg", 1), + ("median", 1), + ("contains", 2), + ("upper", 1), + ("lower", 1), + ("trim", 1), + ("startsWith", 2), + ("endsWith", 2), + ("string", 1), + ("number", 1), + ("keys", 1), + ("values", 1), + ("isNumeric", 1), + ("flatten", 1), + ]; + + fn leaf(&mut self) -> String { + match self.rng.below(12) { + 0 => format!("{}", self.rng.below(20) as i64 - 5), + 1 => format!("{}.{}", self.rng.below(100), self.rng.below(100)), + 2 => format!( + "'{}'", + self.rng.pick(&["x", "gold", "abc", "", "1", "Hello"]) + ), + 3 => self.rng.pick(&["true", "false", "null"]).to_string(), + 4 if self.closures > 0 => "#".to_string(), + 5 if !self.aliases.is_empty() => { + let i = self.rng.below(self.aliases.len()); + self.aliases[i].to_string() + } + 6 if self.closures > 0 => format!("#.{}", self.rng.pick(&["x", "v", "name"])), + _ => self.rng.pick(&Self::FIELDS).to_string(), + } + } + + fn list(&mut self, depth: usize) -> String { + match self.rng.below(6) { + 0 => "[1, 2, 3]".to_string(), + 1 => "tags".to_string(), + 2 => "list".to_string(), + 3 => "1..4".to_string(), + 4 => self.expr(depth), + _ => "items".to_string(), + } + } + + fn expr(&mut self, depth: usize) -> String { + if depth == 0 || self.rng.chance(20) { + return self.leaf(); + } + let d = depth - 1; + match self.rng.below(20) { + 0..=3 => { + let op = self.rng.pick(&[ + "+", "-", "*", "/", "%", "^", "==", "!=", "<", "<=", ">", ">=", "and", "or", + "??", + ]); + format!("{} {op} {}", self.expr(d), self.expr(d)) + } + 4 => format!("({} ? {} : {})", self.expr(d), self.expr(d), self.expr(d)), + 5 => format!("{}{}", self.rng.pick(&["-", "not ", "+"]), self.expr(d)), + 6 => { + let (name, arity) = Self::FUNCTIONS[self.rng.below(Self::FUNCTIONS.len())]; + let args: Vec = (0..arity).map(|_| self.expr(d)).collect(); + format!("{name}({})", args.join(", ")) + } + 7 | 8 => { + let kind = self.rng.pick(&[ + "map", "filter", "some", "all", "none", "one", "count", "flatMap", + ]); + let list = self.list(d); + self.closures += 1; + let alias = self.rng.chance(20).then(|| self.rng.pick(&["x", "y"])); + let body = match alias { + Some(a) => { + self.aliases.push(a); + let b = self.expr(d); + self.aliases.pop(); + format!("{list} as {a}, {b}") + } + None => format!("{list}, {}", self.expr(d)), + }; + self.closures -= 1; + format!("{kind}({body})") + } + 9 => format!("[{}, {}]", self.expr(d), self.expr(d)), + 10 => format!("{{k: {}, 'm': {}}}", self.expr(d), self.expr(d)), + 11 => format!("{} in [{}, {}]", self.expr(d), self.leaf(), self.leaf()), + 12 => format!( + "{} in [{}..{}]", + self.expr(d), + self.rng.below(5), + 5 + self.rng.below(5) + ), + 13 => format!("`${{{}}}-${{{}}}`", self.expr(d), self.expr(d)), + 14 => format!( + "{}[{}]", + self.rng.pick(&["items", "tags", "s", "o", "list"]), + self.expr(d) + ), + 15 => format!( + "{}[{}:{}]", + self.rng.pick(&["items", "s", "tags"]), + self.rng.below(3), + self.rng.below(4) + ), + 16 => format!( + "v = {}; w = {}; {}", + self.expr(d), + self.expr(d), + self.rng.pick(&["v", "w", "v + w", "{v, w}"]) + ), + 17 => format!("{} not in [{}]", self.expr(d), self.leaf()), + 18 => format!("o.{}", self.rng.pick(&["x", "y", "y.z", "missing"])), + _ => self.leaf(), + } + } + + fn value(rng: &mut Rng) -> Value { + match rng.below(9) { + 0 => json!(rng.below(20) as i64 - 5), + 1 => json!(format!("{}.{}", rng.below(50), rng.below(100)) + .parse::() + .unwrap_or(0.0)), + 2 => json!(["x", "gold", "abc", "1", ""][rng.below(5)]), + 3 => json!(rng.chance(50)), + 4 => Value::Null, + 5 => json!([1, 2, 3]), + 6 => json!({"x": rng.below(5), "v": "a"}), + _ => json!(rng.below(100)), + } + } + + fn input(rng: &mut Rng) -> Value { + let mut o = serde_json::Map::new(); + let typed = rng.chance(60); + let num = |rng: &mut Rng| { + if typed { + json!(rng.below(30) as i64 - 10) + } else { + Self::value(rng) + } + }; + for k in ["a", "b", "c", "n"] { + if !rng.chance(10) { + o.insert(k.into(), num(rng)); + } + } + for k in ["s", "t"] { + if !rng.chance(10) { + let v = if typed { + json!(["x", "gold", "abc", "Hello"][rng.below(4)]) + } else { + Self::value(rng) + }; + o.insert(k.into(), v); + } + } + if !rng.chance(10) { + let v = if typed { + json!(rng.chance(50)) + } else { + Self::value(rng) + }; + o.insert("flag".into(), v); + } + let len = rng.below(6); + let items: Vec = (0..len) + .map(|_| { + if typed { + json!(rng.below(10)) + } else { + Self::value(rng) + } + }) + .collect(); + o.insert("items".into(), Value::Array(items)); + let tags: Vec = (0..rng.below(4)) + .map(|_| json!(["x", "gold", "abc"][rng.below(3)])) + .collect(); + o.insert("tags".into(), Value::Array(tags)); + let list: Vec = (0..rng.below(4)) + .map(|_| { + let v = ["a", "b"][rng.below(2)]; + json!({"x": rng.below(10), "v": v, "name": "n"}) + }) + .collect(); + o.insert("list".into(), Value::Array(list)); + if !rng.chance(15) { + o.insert( + "o".into(), + json!({"x": rng.below(10), "y": {"z": rng.below(10)}}), + ); + } + Value::Object(o) + } +} + +#[test] +fn lane_fuzz_matches_stack_vm() { + let iterations: u64 = std::env::var("LANE_FUZZ_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(300); + let seed: u64 = std::env::var("LANE_FUZZ_SEED") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0x5EED); + let mut d = Differential::new(ExpressionKind::Standard); + for i in 0..iterations { + let mut rng = Rng(seed + .wrapping_mul(6364136223846793005) + .wrapping_add(i.wrapping_mul(2654435761).wrapping_add(1))); + let expression = Generator { + rng: &mut rng, + closures: 0, + aliases: Vec::new(), + } + .expr(4); + let inputs: Vec = (0..48).map(|_| Generator::input(&mut rng)).collect(); + let before = d.failures.len(); + d.check(&expression, &inputs); + d.columns(&expression, &inputs); + if d.failures.len() > before { + eprintln!("fuzz case {i} (seed {seed}) failed: {expression}"); + } + } + d.assert(); + conformance::Spec::no_fallbacks(); +} + +struct Typed<'r> { + rng: &'r mut Rng, + closure: bool, +} + +impl Typed<'_> { + fn num(&mut self, depth: usize) -> String { + if depth == 0 || self.rng.chance(25) { + return match self.rng.below(6) { + 0 => format!("{}", self.rng.below(50) as i64 - 10), + 1 => format!("{}.{}", self.rng.below(20), self.rng.below(100)), + 2 if self.closure => "#".to_string(), + 3 if self.closure => "#.x".to_string(), + _ => self + .rng + .pick(&["a", "b", "c", "n", "o.x", "o.y.z"]) + .to_string(), + }; + } + let d = depth - 1; + match self.rng.below(9) { + 0..=3 => { + let op = self.rng.pick(&["+", "-", "*", "/", "%"]); + format!("({} {op} {})", self.num(d), self.num(d)) + } + 4 => format!("({} ? {} : {})", self.bool(d), self.num(d), self.num(d)), + 5 => format!( + "{}({})", + self.rng.pick(&["abs", "round", "floor", "ceil"]), + self.num(d) + ), + 6 if !self.closure => { + self.closure = true; + let body = self.num(d); + self.closure = false; + let list = self.rng.pick(&["items", "list"]); + format!( + "{}(map({list}, {body}))", + self.rng.pick(&["sum", "max", "min", "avg"]) + ) + } + 7 => format!("({} ?? {})", self.num(d), self.num(d)), + _ => format!("-{}", self.num(d)), + } + } + + fn bool(&mut self, depth: usize) -> String { + if depth == 0 || self.rng.chance(20) { + return match self.rng.below(3) { + 0 => "flag".to_string(), + 1 => self.rng.pick(&["true", "false"]).to_string(), + _ => format!("s == '{}'", self.rng.pick(&["gold", "x", "abc"])), + }; + } + let d = depth - 1; + match self.rng.below(9) { + 0..=2 => { + let op = self.rng.pick(&["<", "<=", ">", ">=", "==", "!="]); + format!("{} {op} {}", self.num(d), self.num(d)) + } + 3 => format!("({} and {})", self.bool(d), self.bool(d)), + 4 => format!("({} or {})", self.bool(d), self.bool(d)), + 5 => format!("not {}", self.bool(d)), + 6 if !self.closure => { + self.closure = true; + let body = self.bool(d); + self.closure = false; + let kind = self.rng.pick(&["some", "all", "none", "one"]); + format!("{kind}(items, {body})") + } + 7 => format!( + "{} in [{}..{}]", + self.num(d), + self.rng.below(10), + 10 + self.rng.below(20) + ), + _ => format!("s {} ['gold', 'x']", self.rng.pick(&["in", "not in"])), + } + } + + fn string(&mut self, depth: usize) -> String { + match self.rng.below(4) { + 0 => format!("`${{{}}}:${{s}}`", self.num(depth)), + 1 => format!("({} ? s : t)", self.bool(depth)), + 2 => "upper(s ?? 'z')".to_string(), + _ => "s + '-' + t".to_string(), + } + } + + fn input(rng: &mut Rng) -> Value { + let mut o = serde_json::Map::new(); + let noise = |rng: &mut Rng, v: Value| match rng.below(100) { + 0..=2 => Value::Null, + 3 => json!("oops"), + _ => v, + }; + for k in ["a", "b", "c", "n"] { + let v = json!(format!("{}.{}", rng.below(40) as i64 - 10, rng.below(10)) + .parse::() + .unwrap_or(0.0)); + let v = noise(rng, v); + if !rng.chance(3) { + o.insert(k.into(), v); + } + } + let s = json!(["gold", "x", "abc", "silver"][rng.below(4)]); + o.insert("s".into(), noise(rng, s)); + o.insert("t".into(), json!(["t1", "t2"][rng.below(2)])); + let flag = json!(rng.chance(50)); + o.insert("flag".into(), noise(rng, flag)); + let items: Vec = (0..rng.below(7)).map(|_| json!(rng.below(20))).collect(); + o.insert("items".into(), Value::Array(items)); + let list: Vec = (0..rng.below(5)) + .map(|_| json!({"x": rng.below(10)})) + .collect(); + o.insert("list".into(), Value::Array(list)); + o.insert( + "o".into(), + json!({"x": rng.below(10), "y": {"z": rng.below(10)}}), + ); + Value::Object(o) + } +} + +#[test] +fn lane_fuzz_typed_matches_stack_vm() { + let iterations: u64 = std::env::var("LANE_FUZZ_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(300); + let seed: u64 = std::env::var("LANE_FUZZ_SEED") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0x7EED); + let mut d = Differential::new(ExpressionKind::Standard); + for i in 0..iterations { + let mut rng = Rng(seed + .wrapping_mul(0x9E3779B97F4A7C15) + .wrapping_add(i.wrapping_mul(1442695040888963407).wrapping_add(7))); + let mut g = Typed { + rng: &mut rng, + closure: false, + }; + let expression = match g.rng.below(3) { + 0 => g.num(4), + 1 => g.bool(4), + _ => g.string(3), + }; + let inputs: Vec = (0..64).map(|_| Typed::input(&mut rng)).collect(); + let before = d.failures.len(); + d.check(&expression, &inputs); + d.columns(&expression, &inputs); + if d.failures.len() > before { + eprintln!("typed fuzz case {i} (seed {seed}) failed: {expression}"); + } + } + d.assert(); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_cell_sets_match_unary_evaluation() { + let iterations: u64 = std::env::var("LANE_FUZZ_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(60); + let mut runner = LaneRunner::new(); + let mut compared = 0usize; + let mut failures: Vec = Vec::new(); + for i in 0..iterations { + let mut rng = Rng(0xCE11u64.wrapping_mul(i.wrapping_add(1)).wrapping_add(17)); + let rules = [3usize, 40, 200][rng.below(3)]; + let cells: Vec = (0..rules) + .map(|_| match rng.below(12) { + 0 | 1 => String::new(), + 2 => format!("'{}'", ["GB", "US", "DE", "x"][rng.below(4)]), + 3 => format!( + "'{}', '{}'", + ["GB", "US"][rng.below(2)], + ["DE", "FR"][rng.below(2)] + ), + 4 => format!("{}", rng.below(10)), + 5 => format!( + "{} {}", + ["<", "<=", ">", ">="][rng.below(4)], + rng.below(20) as i64 - 5 + ), + 6 => format!("[{}..{}]", rng.below(10), 10 + rng.below(10)), + 7 => format!("({}..{}]", rng.below(10), 10 + rng.below(10)), + 8 => "$ > limit".to_string(), + 9 => "startsWith($, 'G')".to_string(), + 10 => "true, false".to_string(), + _ => format!("> {}.5", rng.below(9)), + }) + .collect(); + let refs: Vec> = cells.iter().map(|c| Some(c.as_str())).collect(); + let set = zen_expression::lane::CellSet::compile(&refs).expect("compile cells"); + let values: Vec = (0..70) + .map(|_| match rng.below(8) { + 0 => json!(["GB", "US", "DE", "FR", "x"][rng.below(5)]).into(), + 1 => json!(rng.below(25) as i64 - 5).into(), + 2 => json!(format!("{}.{}", rng.below(20), rng.below(10)) + .parse::() + .unwrap_or(0.0)) + .into(), + 3 => json!(rng.chance(50)).into(), + 4 => Variable::Null, + 5 => json!([1, 2]).into(), + 6 => json!(rng.below(25)).into(), + _ => json!("Gx").into(), + }) + .collect(); + let envs: Vec = (0..values.len()) + .map(|_| Scope::new(json!({"limit": rng.below(15)}).into())) + .collect(); + let mut out = Vec::new(); + set.evaluate(&mut runner, &values, &envs, &mut out); + let words = set.words(); + for (row, value) in values.iter().enumerate() { + let mut isolate = Isolate::new(); + for (rule, cell) in cells.iter().enumerate() { + let expected = match cell.trim() { + "" => true, + c => { + isolate.set_environment(envs[row].base().clone()); + let _ = isolate.set_reference_value(value.clone()); + isolate.run_unary(c).unwrap_or(false) + } + }; + let got = out[row * words + rule / 64] >> (rule % 64) & 1 == 1; + compared += 1; + if got != expected { + failures.push(format!( + "cell {cell:?} value {value} got {got} expected {expected}" + )); + } + } + } + } + eprintln!("cell sets compared {compared}"); + assert!( + failures.is_empty(), + "{} of {compared} differ:\n{}", + failures.len(), + failures + .iter() + .take(20) + .cloned() + .collect::>() + .join("\n") + ); + conformance::Spec::no_fallbacks(); +} + +type ManyResult = Result, (usize, String)>; + +#[test] +fn lane_many_matches_expression_node_semantics() { + let iterations: u64 = std::env::var("LANE_FUZZ_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(200); + let mut runner = LaneRunner::new(); + let mut compared = 0usize; + let mut failures: Vec = Vec::new(); + for i in 0..iterations { + let mut rng = Rng(0xA11u64.wrapping_mul(i.wrapping_add(3)).wrapping_add(99)); + let count = 2 + rng.below(4); + let mut entries: Vec<(String, String)> = Vec::new(); + for k in 0..count { + let source = match (k, rng.below(7)) { + (k, 5 | 6) if k > 0 => { + let r = rng.below(k); + match rng.below(14) { + 0 => format!("$.k{r} < 5"), + 1 => format!("$.k{r} >= 2 ? 'hi' : 'lo'"), + 2 => format!("$.k{r} == 'a'"), + 3 => format!("$.k{r} == 1"), + 4 => format!("$.k{r} != null"), + 5 => format!("$.k{r} in [1, 2, 'a']"), + 6 => format!("$.k{r} not in [true, 3]"), + 7 => format!("$.k{r} and a"), + 8 => format!("not $.k{r}"), + 9 => format!("$.k{r}.inner == 2"), + 10 => format!("$.k{r}.inner > 1"), + 11 => format!("len($.k{r} ?? [])"), + 12 => format!("5 > $.k{r}"), + _ => format!("$.k{r} * 2 >= b"), + } + } + (0, _) | (_, 0 | 1 | 5 | 6) => { + let typed = rng.chance(50); + let mut g = Typed { + rng: &mut rng, + closure: false, + }; + match typed { + true => g.num(3), + false => g.bool(2), + } + } + (_, 2) => format!("$.k{} + 1", rng.below(k)), + (_, 3) => format!("$.k{} ?? a", rng.below(k)), + _ => Generator { + rng: &mut rng, + closures: 0, + aliases: Vec::new(), + } + .expr(2), + }; + let key = if rng.chance(15) { + format!("k{k}.inner") + } else { + format!("k{k}") + }; + entries.push((key, source)); + } + let inputs: Vec = (0..70).map(|_| Typed::input(&mut rng)).collect(); + let mask: Vec = (0..inputs.len()).map(|_| !rng.chance(10)).collect(); + let refs: Vec<(&str, &str)> = entries + .iter() + .map(|(k, s)| (k.as_str(), s.as_str())) + .collect(); + let program = match LaneProgram::compile_many(&refs, true) { + Ok(p) => p, + Err(_) => continue, + }; + let scopes: Vec = inputs + .iter() + .map(|v| Scope::new(v.clone().into())) + .collect(); + let program = match rng.chance(50) { + true => program.specialize(&scopes).expect("specialize"), + false => program, + }; + let mut got: Vec> = vec![None; inputs.len()]; + runner.evaluate_many(&program, &scopes, Some(&mask), |row, r| { + got[row] = r.map(|r| { + r.map(|v| v.into_iter().map(|x| x.to_value()).collect()) + .map_err(|(s, e)| (s, conformance::Spec::describe(&e))) + }); + }); + for (row, input) in inputs.iter().enumerate() { + compared += 1; + if !mask[row] { + if got[row].is_some() { + failures.push(format!("masked row {row} produced a result")); + } + continue; + } + let mut isolate = Isolate::with_environment(input.clone().into()); + let mut outputs = Vec::new(); + let mut expected: Result, (usize, String)> = Ok(Vec::new()); + for (index, (key, source)) in entries.iter().enumerate() { + match isolate.run_standard(source) { + Ok(v) => { + outputs.push(v.to_value()); + isolate.insert_dollar(key, v); + } + Err(e) => { + expected = Err((index, conformance::Spec::describe(&e))); + break; + } + } + } + if expected.is_ok() { + expected = Ok(outputs); + } + if got[row].as_ref() != Some(&expected) { + failures.push(format!( + "{entries:?} | input {input} | lane {:?} vs stack {expected:?}", + got[row] + )); + } + } + } + eprintln!("many compared {compared}"); + assert!( + failures.is_empty(), + "{} of {compared} differ:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_builtins_match_stack_vm() { + let mut d = Differential::new(ExpressionKind::Standard); + let inputs = vec![ + json!({"a": 12.5, "s": "Hello World", "b": [3, 1, 2], "t": ["x", "yy", "x"], "o": {"k": 1, "z": [1]}, "e": "a1b2", "text": "Hello World"}), + json!({"a": -3, "s": " 42 ", "b": [], "t": [], "o": {}, "e": "(a)(b)", "text": " 42 "}), + json!({"a": 0, "s": "1e3", "b": [1.5, 2.5, 1.5], "t": ["b", "a"], "o": {"a": {"x": 1}, "b": [2]}, "e": "[", "text": "ÄbC ünï ẞ"}), + json!({"a": null, "s": null, "b": null, "t": null, "o": null, "e": null, "text": "MiXeD"}), + json!({"a": "7", "s": 5, "b": [1, "x"], "t": [true], "o": [1], "e": 3, "text": ""}), + json!({"a": 1000000, "s": "true", "b": [[1, 2], [3]], "t": [{"a": 1}, {"b": 2}], "o": {"k": "v"}, "e": ".*", "text": "true"}), + ]; + let pool = [ + "a", + "s", + "b", + "t", + "o", + "e", + "text", + "null", + "true", + "false", + "0", + "2", + "-1.5", + "3.14159", + "'abc'", + "' x '", + "'12.50'", + "'1e3'", + "''", + "[1, 2, 3]", + "['a', 'b']", + "[]", + "[1, 'a', null]", + "[[1], [2, 3]]", + "[{'a': 1}, {'b': 2}]", + "{'a': 1}", + "d('2025-01-02')", + "[d('2025-01-02'), d('2024-01-01')]", + "'^[a-z]+$'", + "'(l+)'", + "'Europe/Berlin'", + "'Mars/Olympus'", + ]; + let functions = [ + "len", + "contains", + "upper", + "lower", + "trim", + "startsWith", + "endsWith", + "matches", + "extract", + "fuzzyMatch", + "split", + "abs", + "sum", + "avg", + "min", + "max", + "median", + "mode", + "floor", + "ceil", + "round", + "trunc", + "flatten", + "merge", + "mergeDeep", + "keys", + "values", + "isNumeric", + "string", + "number", + "bool", + "type", + "d", + ]; + let mut checked = 0usize; + for function in functions { + for x in pool { + let one = format!("{function}({x})"); + d.check(&one, &inputs); + d.columns(&one, &inputs); + checked += 1; + for y in pool { + let two = format!("{function}({x}, {y})"); + d.check(&two, &inputs); + d.columns(&two, &inputs); + checked += 1; + } + } + } + eprintln!("builtin calls {checked}"); + d.assert(); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_date_builtins_match_stack_vm() { + let mut d = Differential::new(ExpressionKind::Standard); + let inputs = vec![ + json!({"a": 1700000000, "s": "2025-03-15 10:30:00", "t": "2024-02-29", "u": "day"}), + json!({"a": -86400, "s": "2025-03-15T10:30:00Z", "t": "bogus", "u": "month"}), + json!({"a": null, "s": null, "t": "2023-12-31", "u": null}), + json!({"a": "5", "s": 12, "t": "10:30:00", "u": 7}), + ]; + let pool = [ + "a", + "s", + "t", + "u", + "null", + "0", + "1", + "-2", + "1.5", + "1700000000", + "'2025-01-02'", + "'2025-01-02 03:04:05'", + "'2025-01-02T03:04:05Z'", + "'10:30'", + "'10:30:15'", + "'bogus'", + "'1d'", + "'2h 30m'", + "'day'", + "'week'", + "'month'", + "'year'", + "'hour'", + "'quarter'", + "'minute'", + "'second'", + "'decade'", + "'%Y-%m-%d %H:%M'", + "'Europe/Berlin'", + "'UTC'", + "'Nope/Zone'", + "d('2024-12-31')", + "true", + "[1]", + ]; + let legacy = [ + "date", + "time", + "duration", + "year", + "dayOfWeek", + "dayOfMonth", + "dayOfYear", + "weekOfYear", + "monthOfYear", + "monthString", + "dateString", + "weekdayString", + "startOf", + "endOf", + ]; + let methods = [ + "add", + "sub", + "set", + "format", + "startOf", + "endOf", + "diff", + "tz", + "isSame", + "isBefore", + "isAfter", + "isSameOrBefore", + "isSameOrAfter", + "second", + "minute", + "hour", + "day", + "dayOfYear", + "week", + "weekday", + "month", + "quarter", + "year", + "timestamp", + "offsetName", + "isValid", + "isYesterday", + "isToday", + "isTomorrow", + "isLeapYear", + ]; + let subjects = [ + "d('2025-03-15T10:30:00Z')", + "d('2024-02-29')", + "d(s)", + "d('bogus')", + "d(a)", + "d(t, 'Europe/Berlin')", + ]; + let mut checked = 0usize; + let mut run = |expression: String, d: &mut Differential| { + d.check(&expression, &inputs); + d.columns(&expression, &inputs); + checked += 1; + }; + for function in legacy { + for x in pool { + run(format!("{function}({x})"), &mut d); + for y in pool { + run(format!("{function}({x}, {y})"), &mut d); + } + } + } + for method in methods { + for subject in subjects { + run(format!("{subject}.{method}()"), &mut d); + for x in pool { + run(format!("{subject}.{method}({x})"), &mut d); + for y in ["'day'", "1", "'bogus'", "a", "null"] { + run(format!("{subject}.{method}({x}, {y})"), &mut d); + } + } + } + } + let flows = [ + "d(s).add(1, 'day').year()", + "d(s).startOf('month').add(2, 'day').isAfter(d(t))", + "d(s) > d(t)", + "d(s) == d(t)", + "d(s) == d(s).add(0, 'day')", + "a > 0 ? d(s) : d(t)", + "a > 0 ? d(s).year() : d(t)", + "[d(s), d(t).add(1, 'day')]", + "max([d(s), d(t)])", + "d(s) ?? d(t)", + "string(d(s))", + "type(d(s).add(1, 'day'))", + "bool(d(s))", + "{x: d(s), y: d(t).tz('UTC')}", + "map([s, t], d(#).year())", + "map([s, t], d(#).add(1, 'day'))", + "filter([s, t], d(#).isValid())", + "d(d(s).add(1, 'day')).diff(d(s), 'hour')", + "d(s).diff(d(t).startOf('year'))", + "d(s).add(1, 'day').format('%Y')", + "len(d(s))", + "d(s) + 1", + "d(s) in [d(t), d(s)]", + "d(s).isBefore(d(t)) and d(t).isValid()", + "not d(s).isLeapYear()", + ]; + for flow in flows { + run(flow.to_string(), &mut d); + } + eprintln!("date calls {checked}"); + d.assert(); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_wide_blocks_match_stack_vm() { + let mut rng = Rng(0xA5A5_5A5A_1234_5678); + let words = ["gold", "silver", "Bronze", " pad ", "ÄbC", ""]; + let inputs: Vec = (0..2500) + .map(|i| { + let n = rng.below(40) as i64 - 20; + let items: Vec = (0..rng.below(9)) + .map(|_| rng.below(12) as i64 - 3) + .collect(); + let a = match rng.below(10) { + 0 => json!(null), + 1 => json!("x"), + 2 => json!(n as f64 / 4.0), + _ => json!(n), + }; + json!({ + "a": a, + "b": rng.below(100) as i64 - 50, + "s": words[rng.below(words.len())], + "flag": rng.chance(50), + "items": items, + "d": format!("2024-0{}-1{} 10:00:00", 1 + rng.below(9), rng.below(10)), + "row": i, + "c": format!("{}{}.{}", ["", "-"][rng.below(2)], rng.below(12), 1 + rng.below(9)).parse::().unwrap_or(0.5), + "e": format!("{}{}.{}{}", ["", "-"][rng.below(2)], rng.below(3), rng.below(10), 1 + rng.below(9)).parse::().unwrap_or(0.25), + }) + }) + .collect(); + let expressions = [ + "a", + "a + b", + "a * 1.5 + b", + "a / 3", + "b > 0 ? a : b", + "a > 3 and b < 10", + "flag or a > 0", + "a ?? b", + "a in [1, 5, 9]", + "b in [-10..10)", + "s == 'gold'", + "lower(s) + '-' + upper(s)", + "trim(s)", + "len(s)", + "`${s}:${b}`", + "round(b * 1.07, 1)", + "abs(b) - 25", + "count(items, # > 2)", + "map(items, # * 2)", + "filter(items, # > 0)", + "some(items, # == 1)", + "all(items, # > -2)", + "sum(items)", + "max(items)", + "d(d).year()", + "d(d).isBefore(d('2024-05-01'))", + "{x: a, y: s, z: [b, b * 2]}", + "row % 7 == 0 ? a + 'x' : b", + "string(b)", + "number(string(b)) == b", + "max([a, b, 1.5])", + "min([b, b * 1.00])", + "a ?? 'none'", + "missing ?? 'none'", + "missing ?? 0", + "[none(items, contains(s, 'o')), map(items, len(s))]", + "[map(items, upper(s)), map(items, lower(s)), count(items, s == 'gold')]", + "[map(items, lower(s)), map(items, lower(d))]", + "b > 3.25", + "b >= 3.25", + "b < -3.25", + "b <= -3.25", + "b == 3.25", + "b == 3.0", + "b != 3.25", + "3.25 < b", + "-2.5 >= b", + "b > 3", + "c > 3", + "c >= 4.25", + "c < 3.25", + "c == 3.5", + "c == 3.50", + "c <= -2.75", + "c > 3.55", + "4 > c", + "c != -1.5", + "e > 1.005", + "e <= -0.125", + "e == 0.25", + "e < 0", + "e >= -1", + "c > 99999999999999999.5", + "-a", + "-b", + "-c", + "-e * 2", + "-(b - b)", + "string(-(b - b))", + "string(-(c - c))", + "-(-b)", + "b in [-10..0]", + "b in (-2.5..2.5]", + "c in [-1.5..1.5)", + "e not in [-0.5..0.5]", + "b not in [-3..3]", + "a in [-10..-1]", + "{x: filter(items, len(d) > len(s)), y: map(items, trim(s)), z: some(items, startsWith(d, '2024-01'))}", + ]; + let mut d = Differential::new(ExpressionKind::Standard); + for expression in expressions { + d.check(expression, &inputs); + d.columns(expression, &inputs); + } + d.assert(); + conformance::Spec::no_fallbacks(); +} + +struct Columnar<'r> { + rng: &'r mut Rng, + closure: Option<&'static str>, +} + +impl Columnar<'_> { + const ZONES: [&'static str; 7] = [ + "UTC", + "Etc/UTC", + "Europe/Berlin", + "America/New_York", + "Asia/Kolkata", + "Etc/GMT+5", + "Australia/Lord_Howe", + ]; + const UNITS: [&'static str; 9] = [ + "second", "minute", "hour", "day", "week", "month", "quarter", "year", "d", + ]; + const WORDS: [&'static str; 10] = [ + "gold", + "Silver", + " pad ", + "ÄbC", + "ünï ẞ", + "", + "a-b-c", + "GOLD", + "x", + "Hello World", + ]; + + fn decimal(rng: &mut Rng) -> String { + let sign = if rng.chance(30) { "-" } else { "" }; + match rng.below(10) { + 0 => format!("{sign}{}", rng.below(1000)), + 1 => format!("{sign}{}.{}", rng.below(100), rng.below(10)), + 2 => format!("{sign}{}.{:02}", rng.below(100), rng.below(100)), + 3 => format!("{sign}0.{:06}", rng.below(1_000_000)), + 4 => format!("{sign}{}.{}0", rng.below(50), rng.below(10)), + 5 => format!("{sign}92233720368547758{:02}", rng.below(8)), + 6 => format!( + "{sign}{}.{:09}", + rng.below(1_000_000_000), + rng.below(1_000_000_000) + ), + 7 => format!( + "{sign}0.{}", + ["5", "25", "125", "1", "10", "100"][rng.below(6)] + ), + 8 => format!("{sign}{}", rng.below(5)), + _ => format!("{sign}{}.5", rng.below(20)), + } + } + + fn num(&mut self, depth: usize) -> String { + if depth == 0 || self.rng.chance(25) { + return match self.rng.below(9) { + 0 => Self::decimal(self.rng), + 1 | 2 if self.closure.is_some() => { + self.closure.map_or("#".to_string(), str::to_string) + } + 3 => self.rng.pick(&["i", "j"]).to_string(), + 4 => "big".to_string(), + 5 => "mixed".to_string(), + _ => self.rng.pick(&["a", "b", "c"]).to_string(), + }; + } + let d = depth - 1; + match self.rng.below(16) { + 0..=4 => { + let op = self.rng.pick(&["+", "-", "*", "*", "/", "%", "+", "-"]); + format!("({} {op} {})", self.num(d), self.num(d)) + } + 5 => format!("({} ? {} : {})", self.bool(d), self.num(d), self.num(d)), + 6 => format!( + "{}({})", + self.rng.pick(&["abs", "round", "floor", "ceil", "trunc"]), + self.num(d) + ), + 7 => format!( + "{}({}, {})", + self.rng.pick(&["round", "trunc"]), + self.num(d), + self.rng.below(4) + ), + 8 if self.closure.is_none() => { + let list = self.list(d); + format!( + "{}({list})", + self.rng + .pick(&["sum", "max", "min", "avg", "sum", "median"]) + ) + } + 9 => format!("({} ?? {})", self.num(d), self.num(d)), + 10 => format!( + "{}([{}, {}, {}])", + self.rng.pick(&["max", "min"]), + self.num(d), + self.num(d), + self.num(d) + ), + 11 if self.closure.is_none() => format!("len({})", self.list(d)), + 12 if self.closure.is_none() => { + let list = self.list(d); + let body = self.scoped(|g| g.bool(d)); + Self::aliased("count", &list, body) + } + 13 => format!("len({})", self.string(d)), + 14 => format!( + "{}.{}()", + self.date(d), + self.rng.pick(&[ + "year", + "month", + "day", + "hour", + "weekday", + "dayOfYear", + "quarter", + "week" + ]) + ), + _ => format!("-{}", self.num(d)), + } + } + + fn scoped(&mut self, body: impl FnOnce(&mut Self) -> String) -> String { + let alias = self.rng.chance(20).then_some("x"); + self.closure = Some(alias.unwrap_or("#")); + let out = body(self); + self.closure = None; + match alias { + Some(a) => format!("{a}, {out}"), + None => out, + } + } + + fn list(&mut self, depth: usize) -> String { + match self.rng.below(9) { + 0 | 1 => self.rng.pick(&["ints", "decs", "items"]).to_string(), + 2 if depth > 0 && self.closure.is_none() => { + let list = self.rng.pick(&["ints", "decs", "items"]); + let body = self.scoped(|g| g.num(depth - 1)); + Self::aliased("map", list, body) + } + 3 if depth > 0 && self.closure.is_none() => { + let list = self.rng.pick(&["ints", "decs", "items"]); + let body = self.scoped(|g| g.bool(depth - 1)); + Self::aliased("filter", list, body) + } + 4 => format!("[{}, {}]", Self::decimal(self.rng), Self::decimal(self.rng)), + 5 => "[]".to_string(), + 6 => format!( + "{}[{}:{}]", + self.rng.pick(&["ints", "decs"]), + self.rng.below(3), + 1 + self.rng.below(4) + ), + _ => self.rng.pick(&["ints", "decs"]).to_string(), + } + } + + fn aliased(kind: &str, list: &str, body: String) -> String { + match body.strip_prefix("x, ") { + Some(rest) => format!("{kind}({list} as x, {rest})"), + None => format!("{kind}({list}, {body})"), + } + } + + fn strings(&mut self, depth: usize) -> String { + match self.rng.below(4) { + 0 if depth > 0 && self.closure.is_none() => { + let body = self.scoped(|g| g.string(depth - 1)); + Self::aliased("map", "tags", body) + } + 1 if depth > 0 && self.closure.is_none() => { + let body = self.scoped(|g| g.bool(depth - 1)); + Self::aliased("filter", "tags", body) + } + _ => "tags".to_string(), + } + } + + fn string(&mut self, depth: usize) -> String { + if depth == 0 || self.rng.chance(25) { + return match self.rng.below(7) { + 0 => format!("'{}'", Self::WORDS[self.rng.below(Self::WORDS.len())]), + 1 if self.closure.is_some() => self.closure.map_or("#".to_string(), str::to_string), + 2 => "tex".to_string(), + 3 => "st".to_string(), + _ => "s".to_string(), + }; + } + let d = depth - 1; + match self.rng.below(9) { + 0 => format!( + "{}({})", + self.rng.pick(&["lower", "upper", "trim"]), + self.string(d) + ), + 1 => format!("{} + {}", self.string(d), self.string(d)), + 2 => format!("`${{{}}}|${{{}}}`", self.string(d), self.num(d)), + 3 => format!( + "({} ? {} : {})", + self.bool(d), + self.string(d), + self.string(d) + ), + 4 => format!("string({})", self.num(d)), + 5 => format!("({} ?? {})", self.string(d), self.string(d)), + 6 => format!( + "{}.format('{}')", + self.date(d), + self.rng + .pick(&["%Y-%m-%d", "%H:%M", "%Y-%m-%dT%H:%M:%S%z", "%A"]) + ), + 7 => format!( + "{}[{}:{}]", + self.string(d), + self.rng.below(3), + 2 + self.rng.below(4) + ), + _ => format!("string({})", self.date(d)), + } + } + + fn date(&mut self, depth: usize) -> String { + let base = match self.rng.below(5) { + 0 => format!("d({})", self.rng.pick(&["d1", "d2", "dt"])), + 1 | 2 => format!( + "d({}, '{}')", + self.rng.pick(&["d1", "d2", "dt"]), + Self::ZONES[self.rng.below(Self::ZONES.len())] + ), + 3 => format!( + "d('{}')", + self.rng.pick(&[ + "2024-03-31 01:30:00", + "2024-10-27 02:30:00", + "2024-02-29", + "2023-11-05T05:30:00Z" + ]) + ), + _ => format!( + "d(d1).tz('{}')", + Self::ZONES[self.rng.below(Self::ZONES.len())] + ), + }; + let mut out = base; + for _ in 0..self.rng.below(depth.min(3) + 1) { + let unit = Self::UNITS[self.rng.below(Self::UNITS.len())]; + out = match self.rng.below(5) { + 0 => format!("{out}.add({}, '{unit}')", self.rng.below(40) as i64 - 10), + 1 => format!("{out}.sub({}, '{unit}')", self.rng.below(40)), + 2 => format!("{out}.startOf('{unit}')"), + 3 => format!("{out}.endOf('{unit}')"), + _ => format!( + "{out}.add('{}')", + self.rng.pick(&["1d", "2h 30m", "1w", "36h", "90m"]) + ), + }; + } + out + } + + fn bool(&mut self, depth: usize) -> String { + if depth == 0 || self.rng.chance(20) { + return match self.rng.below(4) { + 0 => "flag".to_string(), + 1 => self.rng.pick(&["true", "false"]).to_string(), + 2 => format!("{} > {}", self.num(0), self.num(0)), + _ => format!("s == '{}'", Self::WORDS[self.rng.below(Self::WORDS.len())]), + }; + } + let d = depth - 1; + match self.rng.below(14) { + 0..=2 => { + let op = self.rng.pick(&["<", "<=", ">", ">=", "==", "!="]); + format!("{} {op} {}", self.num(d), self.num(d)) + } + 3 => format!("({} and {})", self.bool(d), self.bool(d)), + 4 => format!("({} or {})", self.bool(d), self.bool(d)), + 5 => format!("not {}", self.bool(d)), + 6 if self.closure.is_none() => { + let list = self.list(d); + let body = self.scoped(|g| g.bool(d)); + Self::aliased(self.rng.pick(&["some", "all", "none", "one"]), &list, body) + } + 7 => format!( + "{} in [{}..{}]", + self.num(d), + self.rng.below(10), + 10 + self.rng.below(20) + ), + 8 => format!( + "{}({}, '{}')", + self.rng.pick(&["contains", "startsWith", "endsWith"]), + self.string(d), + self.rng.pick(&["g", "G", "ü", "a-", " ", "old", ""]) + ), + 9 => format!( + "{}.{}({})", + self.date(d), + self.rng + .pick(&["isBefore", "isAfter", "isSame", "isSameOrBefore"]), + self.date(d) + ), + 10 => format!("{} == {}", self.date(d), self.date(d)), + 11 => format!( + "{} {} [{}, {}]", + self.string(d), + self.rng.pick(&["in", "not in"]), + self.string(0), + self.string(0) + ), + 12 => format!("{} == {}", self.string(d), self.string(d)), + _ => format!( + "{} {} ['gold', 'x']", + self.string(d), + self.rng.pick(&["in", "not in"]) + ), + } + } + + fn top(&mut self) -> String { + match self.rng.below(12) { + 0..=2 => self.num(4), + 3 | 4 => self.bool(4), + 5 => self.string(3), + 6 => self.date(3), + 7 => self.list(3), + 8 => self.strings(3), + 9 => format!( + "{{x: {}, y: {}, z: {}}}", + self.num(2), + self.list(2), + self.string(2) + ), + 10 => format!("[{}, {}]", self.num(3), self.num(3)), + _ => format!( + "{}.diff({}, '{}')", + self.date(2), + self.date(2), + Self::UNITS[self.rng.below(Self::UNITS.len())] + ), + } + } + + fn day(rng: &mut Rng) -> String { + let (y, m, dd) = match rng.below(6) { + 0 => (2024, 3, 31), + 1 => (2024, 10, 27), + 2 => (2023, 11, 5), + 3 => (2024, 2, 29), + _ => (2000 + rng.below(40), 1 + rng.below(12), 1 + rng.below(28)), + }; + format!("{y:04}-{m:02}-{dd:02}") + } + + fn input(rng: &mut Rng, noisy: bool) -> Value { + let mut o = serde_json::Map::new(); + let num = |rng: &mut Rng| -> Value { + serde_json::from_str(&Self::decimal(rng)).unwrap_or(Value::Null) + }; + for k in ["a", "b", "c"] { + match rng.below(100) { + 0..=4 => {} + 5..=7 => { + o.insert(k.into(), Value::Null); + } + 8 if noisy => { + o.insert(k.into(), json!("oops")); + } + _ => { + o.insert(k.into(), num(rng)); + } + } + } + for k in ["i", "j"] { + if !rng.chance(4) { + o.insert(k.into(), json!(rng.below(2000) as i64 - 1000)); + } + } + let big = match rng.below(3) { + 0 => i64::MAX - rng.below(10) as i64, + 1 => i64::MIN + rng.below(10) as i64, + _ => rng.below(1 << 40) as i64 * 4096, + }; + o.insert("big".into(), json!(big)); + let mixed = match rng.below(5) { + 0 => json!("12.5"), + 1 => json!(true), + 2 => Value::Null, + _ => num(rng), + }; + o.insert("mixed".into(), mixed); + o.insert("s".into(), json!(Self::WORDS[rng.below(Self::WORDS.len())])); + o.insert( + "st".into(), + json!(Self::WORDS[rng.below(Self::WORDS.len())]), + ); + if !rng.chance(5) { + o.insert( + "tex".into(), + json!(Self::WORDS[rng.below(Self::WORDS.len())]), + ); + } + o.insert("flag".into(), json!(rng.chance(50))); + let hour = rng.below(24); + let d1 = match rng.below(12) { + 0 => json!("bogus"), + 1 => Value::Null, + 2 => json!(format!("{}T{hour:02}:30:00+02:00", Self::day(rng))), + 3 => json!(format!("{} {hour:02}:15:00", Self::day(rng))), + _ => json!(format!("{}T{hour:02}:30:00Z", Self::day(rng))), + }; + o.insert("d1".into(), d1); + o.insert("d2".into(), json!(Self::day(rng))); + o.insert( + "dt".into(), + json!(format!( + "{} {:02}:{:02}:{:02}", + Self::day(rng), + rng.below(24), + rng.below(60), + rng.below(60) + )), + ); + let ints: Vec = (0..rng.below(9)) + .map(|_| json!(rng.below(40) as i64 - 10)) + .collect(); + o.insert("ints".into(), Value::Array(ints)); + let decs: Vec = match rng.below(4) { + 0 => { + let v = num(rng); + let neg: Value = + serde_json::from_str(&format!("-{v}").replace("--", "")).unwrap_or(Value::Null); + vec![v, neg] + } + _ => (0..rng.below(7)).map(|_| num(rng)).collect(), + }; + o.insert("decs".into(), Value::Array(decs)); + let items: Vec = (0..rng.below(6)) + .map(|_| match (noisy, rng.below(10)) { + (true, 0) => json!("z"), + (true, 1) => Value::Null, + _ => json!(rng.below(20)), + }) + .collect(); + o.insert("items".into(), Value::Array(items)); + let tags: Vec = (0..rng.below(5)) + .map(|_| json!(Self::WORDS[rng.below(Self::WORDS.len())])) + .collect(); + o.insert("tags".into(), Value::Array(tags)); + Value::Object(o) + } +} + +#[test] +fn lane_fuzz_columnar_matches_stack_vm() { + let iterations: u64 = std::env::var("LANE_FUZZ_ITERS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(150); + let seed: u64 = std::env::var("LANE_FUZZ_SEED") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0xC0105); + let max_rows: usize = std::env::var("LANE_FUZZ_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1100); + let mut d = Differential::new(ExpressionKind::Standard); + for i in 0..iterations { + let mut rng = Rng(seed + .wrapping_mul(0xD1B54A32D192ED03) + .wrapping_add(i.wrapping_mul(0x9E3779B97F4A7C15).wrapping_add(11))); + let generated = Columnar { + rng: &mut rng, + closure: None, + } + .top(); + if std::env::var("LANE_FUZZ_CASE").is_ok_and(|c| c != i.to_string()) { + continue; + } + let expression = std::env::var("LANE_FUZZ_EXPR").unwrap_or(generated); + let rows = + [1, 3, 63, 64, 65, 130, 1023, 1024, 1025, 2500][rng.below(10)].min(max_rows.max(1)); + let noisy = rng.chance(30); + let inputs: Vec = (0..rows) + .map(|_| Columnar::input(&mut rng, noisy)) + .collect(); + let before = d.failures.len(); + d.check(&expression, &inputs); + d.columns(&expression, &inputs); + if std::env::var("LANE_FUZZ_SHOW").is_ok() { + eprintln!("{rows}\t{expression}"); + } + if d.failures.len() > before { + eprintln!("columnar fuzz case {i} (seed {seed}, rows {rows}) failed: {expression}"); + } + } + d.assert(); + conformance::Spec::no_fallbacks(); +} + +struct SpecLane { + runner: LaneRunner, + failures: Vec, + compared: usize, + unstable: usize, + kernels: usize, + compiled: usize, + rows: usize, + hits: usize, +} + +impl SpecLane { + fn scope(case: &conformance::SpecCase) -> Scope { + match &case.input { + Some(v) => Scope::new(v.depth_clone(64)), + None => Scope::default(), + } + } + + fn normalize( + kind: &ExpressionKind, + got: Result, + ) -> Result { + match (kind, got) { + (ExpressionKind::Unary, Ok(v)) => v.as_bool().map(Variable::Bool).ok_or_else(|| { + conformance::Spec::describe(&zen_expression::IsolateError::ValueCastError) + }), + (_, r) => r.map_err(|e| conformance::Spec::describe(&e)), + } + } + + fn same(a: &Result, b: &Result) -> bool { + match (a, b) { + (Ok(x), Ok(y)) => conformance::Spec::same(x, y) && conformance::Spec::same(y, x), + (Err(x), Err(y)) => x == y, + _ => false, + } + } + + fn compare( + &mut self, + label: &str, + case: &conformance::SpecCase, + want: &Result, + got: Result, + ) { + self.compared += 1; + if !Self::same(want, &got) { + let show = |r: &Result| match r { + Ok(v) => conformance::Spec::render(v), + Err(e) => format!("!error ({e})"), + }; + self.failures.push(format!( + "{} | {} | input {} | {label} | lane {} vs stack {}", + case.location(), + case.expression, + case.input_text, + show(&got), + show(want) + )); + } + } + + fn guarded(&mut self, f: impl FnOnce(&mut LaneRunner) -> T) -> Option { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&mut self.runner))); + if result.is_err() { + self.runner = LaneRunner::new(); + } + result.ok() + } + + fn panicked(n: usize) -> Vec> { + (0..n) + .map(|_| Err(zen_expression::IsolateError::ValueCastError)) + .collect() + } + + fn group(&mut self, cases: &[&conformance::SpecCase]) -> bool { + let Some(first) = cases.first() else { + return true; + }; + let (kind, expression) = (first.kind.clone(), first.expression.as_str()); + let want: Vec> = cases.iter().map(|c| c.exact()).collect(); + let again: Vec> = cases.iter().map(|c| c.exact()).collect(); + if want.iter().zip(&again).any(|(a, b)| !Self::same(a, b)) { + self.unstable += cases.len(); + return false; + } + let program = match LaneProgram::compile(expression, kind.clone()) { + Ok(p) => p, + Err(e) => { + for (case, want) in cases.iter().zip(&want) { + self.compare("compile", case, want, Err(conformance::Spec::describe(&e))); + } + return true; + } + }; + let scopes = || cases.iter().map(|c| Self::scope(c)).collect::>(); + let plain = program.without_kernel(); + self.compiled += 1; + match program.has_kernel() { + true => self.kernels += 1, + false => self + .failures + .push(format!("{expression} | compiled without a kernel")), + } + for case in cases.iter() { + self.rows += 1; + if self + .guarded(|_| program.try_kernel(&Self::scope(case))) + .flatten() + .is_some() + { + self.hits += 1; + } + } + for (case, want) in cases.iter().zip(&want) { + let got = match self.guarded(|r| { + r.evaluate_one(&plain, &Self::scope(case)) + .map(conformance::Spec::settle) + }) { + Some(got) => Self::normalize(&kind, got), + None => Err(format!("{}: lane", conformance::Spec::PANIC)), + }; + let got = match (want, got) { + (Err(w), Err(g)) + if w.starts_with(conformance::Spec::PANIC) + && g.starts_with(conformance::Spec::PANIC) => + { + Err(w.clone()) + } + (_, got) => got, + }; + self.compare("width 1 without kernel", case, want, got); + } + for (case, want) in cases.iter().zip(&want) { + let got = match self.guarded(|r| { + r.evaluate_one(&program, &Self::scope(case)) + .map(conformance::Spec::settle) + }) { + Some(got) => Self::normalize(&kind, got), + None => Err(format!("{}: lane", conformance::Spec::PANIC)), + }; + let got = match (want, got) { + (Err(w), Err(g)) + if w.starts_with(conformance::Spec::PANIC) + && g.starts_with(conformance::Spec::PANIC) => + { + Err(w.clone()) + } + (_, got) => got, + }; + self.compare("width 1", case, want, got); + } + if want.iter().any(|w| { + w.as_ref() + .is_err_and(|e| e.starts_with(conformance::Spec::PANIC)) + }) { + return false; + } + let n = cases.len(); + let batch = self + .guarded(|r| r.evaluate(&program, &scopes())) + .unwrap_or_else(|| Self::panicked(n)); + for ((case, want), got) in cases.iter().zip(&want).zip(batch) { + self.compare("batch", case, want, Self::normalize(&kind, got)); + } + let batch = self + .guarded(|r| r.evaluate(&plain, &scopes())) + .unwrap_or_else(|| Self::panicked(n)); + for ((case, want), got) in cases.iter().zip(&want).zip(batch) { + self.compare( + "batch without kernel", + case, + want, + Self::normalize(&kind, got), + ); + } + if let Ok(specialized) = program.specialize(&scopes()) { + for (case, want) in cases.iter().zip(&want) { + let got = match self.guarded(|r| { + r.evaluate_one(&specialized, &Self::scope(case)) + .map(conformance::Spec::settle) + }) { + Some(got) => Self::normalize(&kind, got), + None => Err(format!("{}: lane", conformance::Spec::PANIC)), + }; + self.compare("specialized", case, want, got); + } + let batch = self + .guarded(|r| r.evaluate(&specialized, &scopes())) + .unwrap_or_else(|| Self::panicked(n)); + for ((case, want), got) in cases.iter().zip(&want).zip(batch) { + self.compare("specialized batch", case, want, Self::normalize(&kind, got)); + } + } + let shape = first.input.as_ref().map_or(Value::Null, |v| v.to_value()); + if let Ok(typed) = + LaneProgram::compile_typed(expression, kind.clone(), &VariableType::from(&shape)) + { + let batch = self + .guarded(|r| r.evaluate(&typed, &scopes())) + .unwrap_or_else(|| Self::panicked(n)); + for ((case, want), got) in cases.iter().zip(&want).zip(batch) { + self.compare("typed", case, want, Self::normalize(&kind, got)); + } + } + true + } +} + +#[test] +fn lane_matches_spec() { + conformance::Spec::prepare(); + let (cases, problems) = conformance::Spec::cases(); + assert!( + problems.is_empty(), + "malformed spec:\n{}", + problems.join("\n") + ); + let mut groups: BTreeMap<(bool, String), Vec<&conformance::SpecCase>> = BTreeMap::new(); + for case in &cases { + let unary = matches!(case.kind, ExpressionKind::Unary); + groups + .entry((unary, case.expression.clone())) + .or_default() + .push(case); + } + let mut lane = SpecLane { + runner: LaneRunner::new(), + failures: Vec::new(), + compared: 0, + unstable: 0, + kernels: 0, + compiled: 0, + rows: 0, + hits: 0, + }; + let mut standard = Differential::new(ExpressionKind::Standard); + let mut unary = Differential::new(ExpressionKind::Unary); + conformance::Spec::prepare(); + for ((is_unary, expression), group) in &groups { + if !lane.group(group) { + continue; + } + let inputs: Vec = group + .iter() + .map(|c| c.input.as_ref().map_or(Value::Null, |v| v.to_value())) + .collect(); + match is_unary { + true => unary.columns(expression, &inputs), + false => standard.columns(expression, &inputs), + } + } + eprintln!( + "spec cases {} | lane row comparisons {} | skipped {} cases whose stack result is nondeterministic | kernels for {} of {} compiled groups, {}/{} rows settled in the kernel", + cases.len(), + lane.compared, + lane.unstable, + lane.kernels, + lane.compiled, + lane.hits, + lane.rows + ); + let shown: Vec = lane.failures.iter().take(60).cloned().collect(); + assert!( + lane.failures.is_empty(), + "{} lane/stack differences:\n{}", + lane.failures.len(), + shown.join("\n") + ); + for d in [standard, unary] { + if d.compared > 0 { + d.assert(); + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_cloned_programs_keep_object_keys() { + let src = "{a: {x: 1, y: 2}, b: {p: 3, q: 4}}"; + let scope = Scope::new(Variable::from(json!({}))); + let expected = Isolate::new() + .run_standard(src) + .expect("old vm") + .to_value() + .to_string(); + for _ in 0..40 { + let mut runner = LaneRunner::new(); + let first = LaneProgram::standard(src).expect("compile"); + let _ = runner.evaluate_one(&first, &scope); + let second = first.clone(); + drop(first); + let mut current = second.clone(); + for _ in 0..50 { + let got = runner + .evaluate_one(¤t, &scope) + .expect("lane") + .to_value() + .to_string(); + assert_eq!(got, expected); + let next = current.clone(); + drop(current); + current = next; + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_many_entries_do_not_share_assignments() { + let cases: [(&[(&str, &str)], Value); 3] = [ + (&[("k0", "x = a; x"), ("k1", "x")], json!({"a": 1})), + (&[("k0", "a.b = 1; 5"), ("k2", "a")], json!({})), + ( + &[("k1", "map(l, (t = #; t))"), ("k2", "t"), ("k3", "$.k1")], + json!({"l": [1, 2]}), + ), + ]; + let mut runner = LaneRunner::new(); + for (entries, input) in cases { + let mut isolate = Isolate::with_environment(input.clone().into()); + let mut expected = Vec::new(); + for (key, source) in entries.iter() { + let v = isolate.run_standard(source).expect("old vm"); + expected.push(v.to_value()); + isolate.insert_dollar(key, v); + } + let program = LaneProgram::compile_many(entries, true).expect("compile"); + let mut got = None; + runner.evaluate_many( + &program, + &[Scope::new(input.clone().into())], + None, + |_, r| { + got = r.map(|r| { + r.map(|v| v.into_iter().map(|x| x.to_value()).collect::>()) + .ok() + }) + }, + ); + assert_eq!(got.flatten(), Some(expected), "{entries:?}"); + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_empty_many_program_does_not_panic() { + let program = LaneProgram::compile_many(&[], true).expect("compile"); + let mut runner = LaneRunner::new(); + let scope = Scope::new(Variable::from(json!({"a": 1}))); + let _ = runner.evaluate_one(&program, &scope); + runner.evaluate_many(&program, std::slice::from_ref(&scope), None, |_, _| {}); + let columns = Columns::new(3); + let mut out = Output::new(); + runner.evaluate_columns_into(&program, &columns, &mut out); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_dates_cross_between_engines() { + std::env::set_var("TZ", "UTC"); + let expressions = [ + "d(x).year()", + "x.year()", + "d(x)", + "d(x) > d('2024-01-01')", + "x.diff(d('2024-03-15 10:00:00'))", + "[x, 1]", + ]; + let mut runner = LaneRunner::new(); + let old_date = Isolate::new() + .run_standard("d('2024-03-15 10:00:00')") + .expect("old vm"); + let lane_date = runner + .evaluate_one( + &LaneProgram::standard("d('2024-03-15 10:00:00')").expect("compile"), + &Scope::default(), + ) + .expect("lane"); + for date in [old_date, lane_date] { + let input = Variable::from(json!({"x": null})); + input.dot_insert("x", date); + for e in expressions { + let want = Isolate::with_environment(input.depth_clone(64)) + .run_standard(e) + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)); + let program = LaneProgram::standard(e).expect("compile"); + let got = runner + .evaluate_one(&program, &Scope::new(input.depth_clone(64))) + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)); + assert_eq!(got, want, "{e}"); + let again = runner + .evaluate_one(&program, &Scope::new(input.depth_clone(64))) + .expect("lane"); + let back = Variable::from(json!({"y": null})); + back.dot_insert("y", again); + let reread = Isolate::with_environment(back) + .run_standard("y") + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)); + assert_eq!(reread, want, "old vm re-reading lane output of {e}"); + } + } + conformance::Spec::no_fallbacks(); +} + +struct Rows; + +impl Rows { + fn check(columns: &Columns, expressions: &[&str]) { + let mut runner = LaneRunner::new(); + for e in expressions { + let program = LaneProgram::standard(e).expect("compile"); + for program in [ + program.clone(), + program.specialize_columns(columns).expect("specialize"), + ] { + let mut out = Output::new(); + runner.evaluate_columns_into(&program, columns, &mut out); + for r in 0..columns.rows { + let want = Isolate::with_environment(columns.row(r)) + .run_standard(e) + .map(|v| v.to_value()) + .ok(); + let got = out.variable(r).and_then(|x| x.ok()).map(|v| v.to_value()); + assert_eq!(got, want, "{e} row {r}"); + } + } + } + } +} + +#[test] +fn lane_regression_list_of_any_aggregates() { + let child = [ + Variable::Number(Decimal::ONE), + Variable::Number(Decimal::new(25, 1)), + Variable::Null, + Variable::Number(Decimal::new(-5, 1)), + ]; + let offsets = [0i32, 2, 4]; + let child = Column::new(Values::Any(&child)); + let columns = Columns::new(2).column( + "l", + Column::new(Values::List { + offsets: &offsets, + child: (&child).into(), + }), + ); + Rows::check( + &columns, + &[ + "sum(l)", + "avg(l)", + "median(l)", + "mode(l)", + "max(l)", + "len(l)", + ], + ); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_row_rebuild_does_not_mutate_input() { + let shared = Variable::from(json!({"k": 0})); + let objects = [shared.clone(), shared.clone()]; + let ys = [1i64, 2]; + let columns = Columns::new(2) + .column("o", Column::new(Values::Any(&objects))) + .column("o.y", Column::new(Values::I64(&ys))); + Rows::check(&columns, &["o.y", "o.k", "o"]); + assert_eq!(shared.to_value(), json!({"k": 0})); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_rand_is_not_memoized() { + let keys = vec![0i32; 1000]; + let values = [Decimal::from(1_000_000_000)]; + let dictionary = Column::new(Values::Dec(&values)); + let columns = Columns::new(1000).column( + "a", + Column::new(Values::Dict { + keys: &keys, + values: (&dictionary).into(), + }), + ); + let mut out = Output::new(); + LaneRunner::new().evaluate_columns_into( + &LaneProgram::standard("rand(a)").expect("compile"), + &columns, + &mut out, + ); + let distinct: std::collections::BTreeSet = (0..1000) + .filter_map(|r| out.variable(r)) + .filter_map(|v| v.ok()) + .map(|v| v.to_value().to_string()) + .collect(); + assert!(distinct.len() > 100, "{}", distinct.len()); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_cells_near_decimal_max() { + let max = "79228162514264337593543950335"; + let cells = [ + format!("> {max}"), + format!("< -{max}"), + "> 79228162514264337593543950330".to_string(), + "< 79228162514264337593543950000".to_string(), + ]; + let refs: Vec> = cells.iter().map(|c| Some(c.as_str())).collect(); + let set = zen_expression::lane::CellSet::compile(&refs).expect("compile"); + let values: Vec = [ + json!(5), + json!(max.parse::().unwrap_or(0.0)), + json!(-1), + ] + .into_iter() + .map(Variable::from) + .collect(); + let envs: Vec = values.iter().map(|_| Scope::default()).collect(); + let mut out = Vec::new(); + set.evaluate(&mut LaneRunner::new(), &values, &envs, &mut out); + for (row, value) in values.iter().enumerate() { + for (rule, cell) in cells.iter().enumerate() { + let mut isolate = Isolate::new(); + let _ = isolate.set_reference_value(value.clone()); + let expected = isolate.run_unary(cell).unwrap_or(false); + let got = out[row * set.words() + rule / 64] >> (rule % 64) & 1 == 1; + assert_eq!(got, expected, "{cell} {value}"); + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_malformed_offsets() { + let data = "aé".as_bytes(); + let split = [0i32, 1, 2, 3]; + let columns = Columns::new(3).column( + "s", + Column::new(Values::Utf8 { + offsets: &split, + data, + }), + ); + Rows::check(&columns, &["s", "s == null", "s ?? 'n'", "s + 'x'"]); + let items = [1i64, 2, 3, 4]; + let child = Column::new(Values::I64(&items)); + for offsets in [[3i32, 1, 4], [-2, 1, 4]] { + let columns = Columns::new(2).column( + "l", + Column::new(Values::List { + offsets: &offsets, + child: (&child).into(), + }), + ); + Rows::check( + &columns, + &["len(l)", "count(l, true)", "sum(l)", "map(l, # * 2)"], + ); + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_duplicate_column_names() { + let first = [1i64, 2]; + let second = [10i64, 20]; + let columns = Columns::new(2) + .column("a", Column::new(Values::I64(&first))) + .column("a", Column::new(Values::I64(&second))); + Rows::check(&columns, &["a", "a + 1"]); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_chained_dollar_matches_isolate() { + let cases: [(&[(&str, &str)], Value); 14] = [ + (&[("k0", "[1, 2]"), ("k1", "$.k0[1]")], json!({})), + (&[("k0", "{l: [5]}"), ("k1", "$.k0.l[0] + 1")], json!({})), + ( + &[("k0", "items"), ("k1", "$.k0[1]"), ("k2", "{ok: $.k0[0]}")], + json!({"items": [10, 20], "$": {"k0": [7, 8]}}), + ), + (&[("k0", "s"), ("k1", "$.k0[0]")], json!({"s": "gold"})), + ( + &[("k0", "1"), ("k1", "a.b = 7; 2"), ("k2", "$.k0")], + json!({"a": {"b": 1}}), + ), + ( + &[("k0", "1"), ("k1", "$ = 3; 2"), ("k2", "$.k0")], + json!({"a": {"b": 1}}), + ), + ( + &[("k0", "{p: 1}"), ("k1", "$.k0.p = 5; 2"), ("k2", "$.k0.p")], + json!({}), + ), + ( + &[("k0", "1"), ("k1", "$root.$.k0"), ("k2", "keys($root.$)")], + json!({}), + ), + (&[("k0", "$ == null"), ("k1", "type($)")], json!({"a": 1})), + (&[("k0", "keys($root)"), ("k1.x", "1")], json!({"a": 1})), + (&[("k0", "$")], json!({})), + (&[("k0", "$.x")], json!({"$": {"x": 5}})), + ( + &[("k0", "$.k0 ?? 0"), ("k0", "$.k0 + 1")], + json!({"$": {"k0": 7}}), + ), + (&[("k0.a", "1"), ("k1", "$.k0.a + $root.$.k0.a")], json!({})), + ]; + let mut runner = LaneRunner::new(); + for (entries, input) in cases { + let mut isolate = Isolate::with_environment(input.clone().into()); + let mut expected = Vec::new(); + for (key, source) in entries.iter() { + let v = isolate.run_standard(source).map(|v| v.to_value()).ok(); + expected.push(v.clone()); + isolate.insert_dollar(key, v.map(Variable::from).unwrap_or(Variable::Null)); + } + let program = LaneProgram::compile_many(entries, true).expect("compile"); + let scope = Scope::new(input.clone().into()); + for program in [ + program.clone(), + program + .specialize(std::slice::from_ref(&scope)) + .expect("specialize"), + ] { + let mut got = None; + runner.evaluate_many(&program, std::slice::from_ref(&scope), None, |_, r| { + got = r.and_then(|r| r.ok()).map(|v| { + v.into_iter() + .map(|x| Some(x.to_value())) + .collect::>() + }) + }); + assert_eq!(got, Some(expected.clone()), "{entries:?}"); + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_cells_survive_invalid_neighbours() { + let cells = [ + Some("$ > limit"), + Some("@"), + Some("startsWith($, 'a')"), + Some("-"), + Some("!= 2"), + ]; + let refs: Vec> = cells.to_vec(); + let set = zen_expression::lane::CellSet::compile(&refs).expect("compile"); + let values: Vec = [json!(10), json!("abc"), json!(2)] + .into_iter() + .map(Variable::from) + .collect(); + let envs: Vec = values + .iter() + .map(|_| Scope::new(json!({"limit": 2}).into())) + .collect(); + let mut out = Vec::new(); + set.evaluate(&mut LaneRunner::new(), &values, &envs, &mut out); + for (row, value) in values.iter().enumerate() { + for (rule, cell) in cells.iter().enumerate() { + let mut isolate = Isolate::with_environment(json!({"limit": 2}).into()); + let _ = isolate.set_reference_value(value.clone()); + let expected = cell + .and_then(|c| isolate.run_unary(c).ok()) + .unwrap_or(false); + let got = out[row * set.words() + rule / 64] >> (rule % 64) & 1 == 1; + assert_eq!(got, expected, "{cell:?} {value}"); + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_cells_probe_between_close_bounds() { + let cells = [ + "< 7.9228162514264337593543950335", + "[7.9228162514264337593543950333..7.9228162514264337593543950335)", + ]; + let refs: Vec> = cells.iter().map(|c| Some(*c)).collect(); + let set = zen_expression::lane::CellSet::compile(&refs).expect("compile"); + let values: Vec = [ + "7.9228162514264337593543950334", + "7.9228162514264337593543950333", + "7.9228162514264337593543950335", + ] + .iter() + .filter_map(|s| s.parse::().ok()) + .map(Variable::Number) + .collect(); + let envs: Vec = values.iter().map(|_| Scope::default()).collect(); + let mut out = Vec::new(); + set.evaluate(&mut LaneRunner::new(), &values, &envs, &mut out); + for (row, value) in values.iter().enumerate() { + for (rule, cell) in cells.iter().enumerate() { + let mut isolate = Isolate::new(); + let _ = isolate.set_reference_value(value.clone()); + let expected = isolate.run_unary(cell).unwrap_or(false); + let got = out[row * set.words() + rule / 64] >> (rule % 64) & 1 == 1; + assert_eq!(got, expected, "{cell} {value}"); + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_malformed_offsets_on_fast_paths() { + let data = "aébc".as_bytes(); + for offsets in [[3i32, 1, 3], [0, 3, 1], [1, i32::MIN, 3]] { + let columns = Columns::new(2).column( + "s", + Column::new(Values::Utf8 { + offsets: &offsets, + data, + }), + ); + Rows::check( + &columns, + &[ + "s", + "s == 'é'", + "s == 'aé'", + "upper(s)", + "len(s)", + "s in ['é', 'aé']", + "s == 'é' ? 1 : (s == 'aé' ? 2 : 3)", + ], + ); + let large: Vec = offsets.iter().map(|o| *o as i64).collect(); + let columns = Columns::new(2).column( + "s", + Column::new(Values::LargeUtf8 { + offsets: &large, + data, + }), + ); + Rows::check(&columns, &["s == 'é'", "s == 'aé'"]); + } + let items = [5i64, 6]; + let child = Column::new(Values::I64(&items)); + for offsets in [&[0i32, 1][..], &[0, 1, 4, 4][..]] { + let columns = Columns::new(3).column( + "a", + Column::new(Values::List { + offsets, + child: (&child).into(), + }), + ); + Rows::check( + &columns, + &[ + "len(a)", + "sum(a)", + "filter(a, # != null)", + "filter(a, # > 5)", + "count(a, # == null)", + ], + ); + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_date_inputs_keep_their_text() { + std::env::set_var("TZ", "UTC"); + let texts = [ + "2024-03-15", + "2024-03-15T10:30:00+02:00", + "2024-03-15 10:30", + "20240315", + ]; + let dates: Vec = texts + .iter() + .filter_map(|t| zen_expression::DateValue::from_text(t)) + .collect(); + let values: Vec = dates + .iter() + .cloned() + .chain([Variable::String("2024-03-15".into()), Variable::Null]) + .collect(); + let expressions = [ + "x", + "string(x)", + "x + ''", + "`${x}`", + "len(x)", + "upper(x)", + "x[0:3]", + "bool(x)", + "x == '2024-03-15'", + "x > '2024-03-01'", + "x in ['2024-03-15']", + "contains([x], '2024-03-15')", + "d(x)", + "d(x, 'Europe/Berlin')", + "x.year()", + "x.format(x)", + "year(x)", + "time(x)", + "fuzzyMatch(x, '2024')", + "[x, x]", + "{v: x}", + ]; + let scopes: Vec = values + .iter() + .map(|v| { + let input = Variable::from(json!({"x": null})); + input.dot_insert("x", v.clone()); + Scope::new(input) + }) + .collect(); + let want = |e: &str, s: &Scope| { + Isolate::with_environment(s.base().clone()) + .run_standard(e) + .map(|v| v.to_value()) + .ok() + }; + let date_type = VariableType::Object(std::rc::Rc::new(std::cell::RefCell::new( + [(std::rc::Rc::::from("x"), VariableType::Date)] + .into_iter() + .collect(), + ))); + let mut runner = LaneRunner::new(); + for e in expressions { + let plain = LaneProgram::standard(e).expect("compile"); + let programs = [ + plain.clone(), + plain.specialize(&scopes).expect("specialize"), + LaneProgram::compile_typed(e, ExpressionKind::Standard, &date_type).expect("typed"), + ]; + for program in &programs { + let got: Vec<_> = runner + .evaluate(program, &scopes) + .into_iter() + .map(|r| r.map(|v| v.to_value()).ok()) + .collect(); + let expected: Vec<_> = scopes.iter().map(|s| want(e, s)).collect(); + assert_eq!(got, expected, "{e}"); + } + let columns = Columns::new(values.len()).column("x", Column::new(Values::Any(&values))); + let mut out = Output::new(); + runner.evaluate_columns_into(&plain, &columns, &mut out); + for (r, s) in scopes.iter().enumerate() { + assert_eq!( + out.variable(r).and_then(|x| x.ok()).map(|v| v.to_value()), + want(e, s), + "{e} column row {r}" + ); + } + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_constant_folding_keeps_runtime_semantics() { + std::env::set_var("TZ", "UTC"); + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + let cases = [ + "1 + 2 * 3", + "(1 / 0) ?? 5", + "1.50 + 1.00", + "-0", + "0 * -1", + "string(1.500)", + "d('2024-01-01')", + "d('2024-01-01', 'Europe/Berlin')", + "d('2024-01-01T10:00:00+02:00') > d('2024-01-01')", + "d('2024-01-01').add(1, 'd').format('%Y-%m-%d')", + "d('now').isValid()", + "d().year() > 2000", + "d('2024-01-01').isToday()", + "d('UTC').isValid()", + "x ? d('2023-10-05').format('%Q') : 1", + "x > d('2024-01-01')", + "len([1, 2, 3]) + x", + "upper('abc') + x", + "({a: 1}).a + 1", + "[1, 2][0]", + "1 + {}", + "len('héllo')", + "`a${1 + 1}b`", + "5 in [1..10]", + "'a' in ['a', 'b']", + ]; + let mut runner = LaneRunner::new(); + let scope = Scope::new(Variable::from(json!({"x": false}))); + for e in cases { + let want = Isolate::with_environment(Variable::from(json!({"x": false}))) + .run_standard(e) + .map(|v| v.to_value()) + .ok(); + let program = LaneProgram::standard(e).expect("compile"); + for _ in 0..2 { + let got = runner + .evaluate_one(&program, &scope) + .map(|v| v.to_value()) + .ok(); + assert_eq!(got, want, "{e}"); + } + } + let rand = LaneProgram::standard("rand(1000000)").expect("compile"); + let values: std::collections::BTreeSet = (0..20) + .filter_map(|_| runner.evaluate_one(&rand, &scope).ok()) + .map(|v| v.to_value().to_string()) + .collect(); + assert!(values.len() > 1); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_long_strings_and_list_membership() { + let long = "x".repeat(1000); + let other = format!("{long}y"); + let rows: Vec = [ + json!({"s": long, "t": long}), + json!({"s": long, "t": other}), + json!({"s": "a", "t": "a"}), + json!({"s": null, "t": long}), + ] + .into_iter() + .map(|v| Scope::new(v.into())) + .collect(); + let mut runner = LaneRunner::new(); + for e in [ + "s == t", + "len(s)", + "s + 'z'", + "upper(s) == upper(t)", + "contains(s, 'xy')", + "s[0:2]", + ] { + let program = LaneProgram::standard(e).expect("compile"); + for program in [ + program.clone(), + program.specialize(&rows).expect("specialize"), + ] { + let got: Vec<_> = runner + .evaluate(&program, &rows) + .into_iter() + .map(|r| r.map(|v| v.to_value()).ok()) + .collect(); + let want: Vec<_> = rows + .iter() + .map(|s| { + Isolate::with_environment(s.base().clone()) + .run_standard(e) + .map(|v| v.to_value()) + .ok() + }) + .collect(); + assert_eq!(got, want, "{e}"); + } + } + let words = ["a", "b", "c", "d"]; + let child = Column::new(Values::Strs(&words)); + let offsets = [0i32, 2, 2, 4, 4]; + let nums = [1i64, 2, 3, 4]; + let num_child = Column::new(Values::I64(&nums)); + let valid = [0b1011u64]; + let texts = ["a", "c", "z", "b"]; + let columns = Columns::new(4) + .column( + "ws", + Column::with_validity( + Values::List { + offsets: &offsets, + child: (&child).into(), + }, + &valid, + 0, + ), + ) + .column( + "ns", + Column::new(Values::List { + offsets: &offsets, + child: (&num_child).into(), + }), + ) + .column("x", Column::new(Values::Strs(&texts))); + Rows::check( + &columns, + &[ + "x in ws", + "x not in ws", + "'a' in ws", + "null in ws", + "3 in ns", + "x in ns", + "1.0 in ns", + ], + ); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_regression_chained_dotted_keys_resolve() { + let cases: [(&[(&str, &str)], Value); 6] = [ + ( + &[ + ("fee.base", "1"), + ("fee.total", "$.fee.base + 1"), + ("net", "$.fee.total * 2"), + ], + json!({}), + ), + (&[("fee.base", "1"), ("all", "$.fee")], json!({})), + ( + &[("a.b", "{x: 1}"), ("c", "$.a.b.x"), ("d", "$.a.b.y ?? 5")], + json!({}), + ), + (&[("a.b", "1"), ("a.c", "$.a.b"), ("d", "$.a")], json!({})), + ( + &[("p", "1"), ("q.r", "$.p + $.missing.x ?? 0")], + json!({"$": {"missing": {"x": 3}}}), + ), + ( + &[("x.y", "2"), ("x.y", "$.x.y + 1"), ("z", "$.x.y")], + json!({}), + ), + ]; + let mut runner = LaneRunner::new(); + for (entries, input) in cases { + let mut isolate = Isolate::with_environment(input.clone().into()); + let mut expected = Vec::new(); + for (key, source) in entries.iter() { + let v = isolate.run_standard(source).map(|v| v.to_value()).ok(); + expected.push(v.clone()); + isolate.insert_dollar(key, v.map(Variable::from).unwrap_or(Variable::Null)); + } + let program = LaneProgram::compile_many(entries, true).expect("compile"); + let scope = Scope::new(input.clone().into()); + let mut got = None; + runner.evaluate_many(&program, std::slice::from_ref(&scope), None, |_, r| { + got = r.and_then(|r| r.ok()).map(|v| { + v.into_iter() + .map(|x| Some(x.to_value())) + .collect::>() + }) + }); + assert_eq!(got, Some(expected), "{entries:?}"); + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_builtin_failures_keep_messages() { + let input = json!({"n": 5, "s": "text", "b": true, "l": [1, 2], "o": {"a": 1}}); + let expressions = [ + "contains(n, 'a')", + "contains(s, 5)", + "upper(n)", + "len(b)", + "startsWith(n, 'x')", + "sum(s)", + "number(o)", + "contains(l, o)", + "trim(n)", + ]; + let scope = Scope::new(Variable::from(input.clone())); + let mut runner = LaneRunner::new(); + let mut mismatches = Vec::new(); + for expression in expressions { + let mut isolate = Isolate::with_environment(Variable::from(input.clone())); + let stack = isolate + .run_standard(expression) + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)); + let Ok(program) = LaneProgram::standard(expression) else { + continue; + }; + let lane = runner + .evaluate(&program, std::slice::from_ref(&scope)) + .remove(0) + .map(|v| v.to_value()) + .map_err(|e| conformance::Spec::describe(&e)); + if lane != stack { + mismatches.push(format!("{expression}\n stack {stack:?}\n lane {lane:?}")); + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_isolated_cells_keep_evaluating_after_a_fault() { + let program = LaneProgram::compile_cells(&[ + ("> 1", Some("a")), + ("x * 2 > 3", None), + ("< 10", Some("a")), + ("$ == b", Some("a")), + ]) + .expect("compile"); + let mant = [0i64, 5, 20, 7]; + let scale = [0u8; 4]; + let xs = [ + Variable::Null, + Variable::from(json!(4)), + Variable::from(json!("text")), + Variable::from(json!(1)), + ]; + let bs = [ + Variable::from(json!(0)), + Variable::from(json!(5)), + Variable::Null, + Variable::from(json!(8)), + ]; + let columns = Columns::new(4) + .column( + "a", + Column::new(Values::Scaled { + mant: &mant, + scale: &scale, + }), + ) + .column("x", Column::new(Values::Any(&xs))) + .column("b", Column::new(Values::Any(&bs))); + let bind = |key: &str| match columns.find(key) { + Some(index) => zen_expression::lane::Binding::Column(index), + None => zen_expression::lane::Binding::Absent, + }; + let scopes: Vec = (0..4).map(|_| Scope::new(Variable::Null)).collect(); + let mut runner = LaneRunner::new(); + let mut outs = Vec::new(); + let mut failures = Vec::new(); + runner.evaluate_bound_into( + &program, + &scopes, + &columns, + &bind, + None, + &mut outs, + |row, stage, _| failures.push((row, stage)), + ); + failures.sort_unstable(); + assert_eq!(failures, vec![(0, 1), (2, 1)]); + let truth = |cell: usize, row: usize| { + failures.iter().all(|f| *f != (row, cell)) + && matches!(outs[cell].variable(row), Some(Ok(Variable::Bool(true)))) + }; + let table: Vec> = (0..4) + .map(|cell| (0..4).map(|row| truth(cell, row)).collect()) + .collect(); + assert_eq!(table[0], vec![false, true, true, true]); + assert_eq!(table[1], vec![false, true, false, false]); + assert_eq!(table[2], vec![true, true, false, true]); + assert_eq!(table[3], vec![true, true, false, false]); + conformance::Spec::no_fallbacks(); +} + +enum FieldBuf { + Scaled(Vec, Vec), + Utf8(Vec, Vec), + Bool(Vec), + Any(Vec), + Struct(Vec<(String, FieldBuf, Vec)>), +} + +struct StructLists { + rows: usize, + offsets: Vec, + valid: Vec, + fields: Vec<(String, FieldBuf, Vec)>, + items: usize, + present: Vec, + scalars: Vec<(String, Vec, Vec)>, +} + +impl FieldBuf { + fn of(cells: &[Option]) -> (FieldBuf, Vec) { + let mut valid = vec![0u64; cells.len().div_ceil(64).max(1)]; + cells + .iter() + .enumerate() + .filter(|(_, c)| c.is_some()) + .for_each(|(i, _)| valid[i / 64] |= 1 << (i % 64)); + let present: Vec<&Value> = cells.iter().flatten().collect(); + let buf = if !present.is_empty() && present.iter().all(|v| v.is_object()) { + let mut names: Vec = Vec::new(); + for v in &present { + for k in v.as_object().into_iter().flat_map(|m| m.keys()) { + if !names.contains(k) { + names.push(k.clone()); + } + } + } + FieldBuf::Struct( + names + .into_iter() + .map(|n| { + let sub: Vec> = cells + .iter() + .map(|c| { + c.as_ref() + .and_then(|v| v.get(&n)) + .filter(|v| !v.is_null()) + .cloned() + }) + .collect(); + let (buf, valid) = FieldBuf::of(&sub); + (n, buf, valid) + }) + .collect(), + ) + } else if !present.is_empty() && present.iter().all(|v| v.is_number()) { + let parts: Vec<(i64, u8)> = cells + .iter() + .map(|c| match c { + Some(v) => { + let d: Decimal = v.to_string().parse().unwrap_or_default(); + (i64::try_from(d.mantissa()).unwrap_or(0), d.scale() as u8) + } + None => (0, 0), + }) + .collect(); + FieldBuf::Scaled( + parts.iter().map(|p| p.0).collect(), + parts.iter().map(|p| p.1).collect(), + ) + } else if !present.is_empty() && present.iter().all(|v| v.is_string()) { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for c in cells { + if let Some(Value::String(s)) = c { + data.extend_from_slice(s.as_bytes()); + } + offsets.push(data.len() as i32); + } + FieldBuf::Utf8(offsets, data) + } else if !present.is_empty() && present.iter().all(|v| v.is_boolean()) { + let mut bits = vec![0u64; cells.len().div_ceil(64).max(1)]; + cells + .iter() + .enumerate() + .filter(|(_, c)| matches!(c, Some(Value::Bool(true)))) + .for_each(|(i, _)| bits[i / 64] |= 1 << (i % 64)); + FieldBuf::Bool(bits) + } else { + FieldBuf::Any( + cells + .iter() + .map(|c| c.clone().map_or(Variable::Null, Variable::from)) + .collect(), + ) + }; + (buf, valid) + } + + fn values<'a>( + &'a self, + structs: &'a [Vec<(&'a str, Column<'a>)>], + next: &mut usize, + ) -> Values<'a> { + match self { + FieldBuf::Scaled(mant, scale) => Values::Scaled { mant, scale }, + FieldBuf::Utf8(offsets, data) => Values::Utf8 { offsets, data }, + FieldBuf::Bool(bits) => Values::Bool { bits, offset: 0 }, + FieldBuf::Any(values) => Values::Any(values), + FieldBuf::Struct(_) => { + let fields = &structs[*next]; + *next += 1; + Values::Struct { + fields, + len: fields.first().map_or(0, |(_, c)| c.len()), + } + } + } + } + + fn nested<'a>(&'a self, out: &mut Vec<&'a [(String, FieldBuf, Vec)]>) { + if let FieldBuf::Struct(fields) = self { + for (_, buf, _) in fields { + buf.nested(out); + } + out.push(fields); + } + } +} + +impl StructLists { + fn new(rows: &[Value]) -> Self { + let mut offsets = vec![0i32]; + let mut valid = vec![0u64; rows.len().div_ceil(64)]; + let mut items: Vec> = Vec::new(); + for (i, row) in rows.iter().enumerate() { + if let Some(Value::Array(list)) = row.get("accounts") { + valid[i / 64] |= 1 << (i % 64); + items.extend( + list.iter() + .map(|v| Some(v.clone()).filter(|v| !v.is_null())), + ); + } + offsets.push(items.len() as i32); + } + let (FieldBuf::Struct(fields), present) = FieldBuf::of(&items) else { + panic!("accounts must hold objects"); + }; + let scalars = ["cap"] + .iter() + .map(|k| { + let parts: Vec<(i64, u8)> = rows + .iter() + .map(|r| { + let d: Decimal = r + .get(*k) + .map(|v| v.to_string()) + .unwrap_or_default() + .parse() + .unwrap_or_default(); + (i64::try_from(d.mantissa()).unwrap_or(0), d.scale() as u8) + }) + .collect(); + ( + k.to_string(), + parts.iter().map(|p| p.0).collect(), + parts.iter().map(|p| p.1).collect(), + ) + }) + .collect(); + Self { + rows: rows.len(), + offsets, + valid, + fields, + items: items.len(), + present, + scalars, + } + } + + fn check(&self, expressions: &[&str]) { + let mut order: Vec<&[(String, FieldBuf, Vec)]> = Vec::new(); + for (_, buf, _) in &self.fields { + buf.nested(&mut order); + } + let built: Vec> = order + .iter() + .map(|fields| { + let mut next = 0usize; + fields + .iter() + .map(|(name, buf, valid)| { + ( + name.as_str(), + Column::with_validity(buf.values(&[], &mut next), valid, 0), + ) + }) + .collect() + }) + .collect(); + let mut next = 0usize; + let top: Vec<(&str, Column)> = self + .fields + .iter() + .map(|(name, buf, valid)| { + ( + name.as_str(), + Column::with_validity(buf.values(&built, &mut next), valid, 0), + ) + }) + .collect(); + let account = Column::with_validity( + Values::Struct { + fields: &top, + len: self.items, + }, + &self.present, + 0, + ); + let mut columns = Columns::new(self.rows).column( + "accounts", + Column::with_validity( + Values::List { + offsets: &self.offsets, + child: (&account).into(), + }, + &self.valid, + 0, + ), + ); + for (name, mant, scale) in &self.scalars { + columns = columns.column(name, Column::new(Values::Scaled { mant, scale })); + } + let mut runner = LaneRunner::new(); + let mut failures = Vec::new(); + for e in expressions { + let program = LaneProgram::standard(e).expect("compile"); + for program in [ + program.clone(), + program.specialize_columns(&columns).expect("specialize"), + ] { + let mut out = Output::new(); + runner.evaluate_columns_into(&program, &columns, &mut out); + let mut values = Vec::new(); + runner.evaluate_columns(&program, &columns, |_, r| { + values.push(r.map(|v| v.to_value()).ok()) + }); + for r in 0..columns.rows { + let want = Isolate::with_environment(columns.row(r)) + .run_standard(e) + .map(|v| v.to_value()) + .ok(); + let got = out.variable(r).and_then(|x| x.ok()).map(|v| v.to_value()); + if got != want || values.get(r) != Some(&want) { + failures.push(format!( + "{e} row {r}\n want {want:?}\n typed {got:?}\n value {:?}", + values.get(r) + )); + break; + } + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + + fn rows(count: usize) -> Vec { + let mut state = 0x2545_f491_4f6c_dd1du64; + let mut n = |m: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % m + }; + (0..count) + .map(|i| { + let accounts: Vec = (0..n(6)) + .map(|k| { + let mut a = serde_json::Map::new(); + match n(7) { + 0 => {} + 1 => { + a.insert("balance".into(), Value::Null); + } + 2 => { + a.insert( + "balance".into(), + json!(Decimal::new(n(100000) as i64, 2)), + ); + } + _ => { + a.insert("balance".into(), json!(n(5000))); + } + } + let kind = ["savings", "checking", "loan"][n(3) as usize]; + a.insert("kind".into(), json!(kind)); + if n(5) != 0 { + a.insert("active".into(), json!(n(3) != 0)); + } + a.insert( + "x".into(), + match n(3) { + 0 => json!(k), + 1 => json!("t"), + _ => Value::Null, + }, + ); + if n(4) != 0 { + let (score, tag) = (n(100), ["a", "b"][n(2) as usize]); + a.insert("meta".into(), json!({"score": score, "tag": tag})); + } + Value::Object(a) + }) + .collect(); + match i % 11 { + 7 => json!({"cap": n(50)}), + 9 => json!({"cap": n(50), "accounts": null}), + _ => json!({"cap": n(50), "accounts": accounts}), + } + }) + .collect() + } +} + +#[test] +fn lane_struct_lists_match_the_stack_vm() { + let rows = StructLists::rows(150); + StructLists::new(&rows).check(&[ + "len(accounts)", + "sum(map(accounts, #.balance ?? 0))", + "sum(map(filter(accounts, #.active), #.balance ?? 0))", + "sum(map(filter(accounts, #.active), #.balance))", + "avg(map(accounts, #.balance))", + "min(map(filter(accounts, #.active), #.balance))", + "max(map(accounts, #.balance))", + "avg(map(filter(accounts, #.active), #.balance))", + "sum(map(accounts, #.kind))", + "sum(map(filter(accounts, #.x), #.balance))", + "sum(map(filter(accounts, #.kind), #.balance))", + "sum(map(accounts, #.missing))", + "cap > 10 ? sum(map(accounts, #.balance)) : sum(map(filter(accounts, #.active), #.balance))", + "count(accounts, #.kind == 'loan')", + "count(accounts, #.active)", + "some(accounts, (#.balance ?? 0) > 1000)", + "all(accounts, #.active)", + "none(accounts, #.kind == 'loan')", + "one(accounts, #.kind == 'savings')", + "map(accounts, #.kind)", + "map(accounts, upper(#.kind))", + "map(accounts, (#.balance ?? 0) * 2)", + "map(accounts, #.balance)", + "map(accounts, #.active)", + "filter(accounts, (#.balance ?? 0) > 100)", + "map(accounts, #)", + "accounts[0].balance", + "map(accounts, #.meta.score)", + "sum(map(accounts, #.meta.score ?? 0))", + "map(accounts, #.meta)", + "map(accounts, #.x)", + "map(accounts, #.missing)", + "map(accounts, {k: #.kind, b: #.balance})", + "flatMap(accounts, [#.kind, #.kind])", + "sum(map(accounts, (#.balance ?? 0) * count(accounts, #.active)))", + "count(accounts, (#.balance ?? 0) > cap * 10)", + "map(filter(accounts, #.kind != 'loan'), #.kind)", + "max(map(accounts, #.balance ?? 0))", + "sum(map(accounts, #.balance))", + "len(filter(accounts, #.active))", + "len(filter(accounts, (#.balance ?? 0) > 1000 and #.active))", + "count(filter(accounts, #.active), #.kind == 'loan')", + "map(filter(accounts, #.active), #.balance ?? 0)", + "some(filter(accounts, #.active), #.kind == 'loan')", + "all(filter(accounts, #.active), (#.balance ?? 0) >= 0)", + "filter(filter(accounts, #.active), #.kind == 'loan')", + "sum(map(filter(filter(accounts, #.active), #.kind != 'loan'), #.balance ?? 0))", + "len(filter(accounts, #.active)) + count(accounts, #.active)", + "map(filter(accounts, #.active), #)", + "map(filter(accounts, #.active), #.meta.tag)", + "count(accounts, #.meta.tag == 'a')", + "sum(map(filter(accounts, (#.meta.score ?? 0) > 50), #.meta.score))", + "map(accounts, #.meta.missing)", + "map(accounts, (#.meta.score ?? 0) + (#.balance ?? 0))", + "map(accounts, #.meta == null)", + "map(accounts, #.meta.score > 10 and #.active)", + "accounts[1].kind", + "accounts[0].meta.score", + "accounts[5].balance", + "accounts[0]", + "accounts[0].missing", + "accounts[0].meta", + "(accounts[0].balance ?? 0) + (accounts[1].balance ?? 0)", + ]); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_struct_lists_with_null_items() { + let rows: Vec = (0..90) + .map(|i| match i % 5 { + 0 => json!({"cap": i, "accounts": [{"balance": i, "kind": "loan", "active": true}, null, {"balance": 3, "kind": "savings"}]}), + 1 => json!({"cap": i, "accounts": [null]}), + 2 => json!({"cap": i, "accounts": []}), + 3 => json!({"cap": i}), + _ => json!({"cap": i, "accounts": [{"balance": 1.5, "kind": "checking", "active": false}]}), + }) + .collect(); + StructLists::new(&rows).check(&[ + "map(accounts, #.balance)", + "sum(map(accounts, #.balance ?? 0))", + "count(accounts, #.kind == 'loan')", + "map(accounts, #)", + "len(filter(accounts, #.active))", + "map(filter(accounts, #.kind != 'loan'), #.kind)", + "some(accounts, # == null)", + ]); + conformance::Spec::no_fallbacks(); +} + +struct Fused; + +impl Fused { + fn rows(count: usize) -> Vec { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut n = |m: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % m + }; + (0..count) + .map(|_| { + let mut row = serde_json::Map::new(); + for key in ["x", "y"] { + match n(9) { + 0 => {} + 1 => { + row.insert(key.into(), Value::Null); + } + 2 => { + row.insert( + key.into(), + serde_json::from_str( + &Decimal::new(n(100_000) as i64 - 50_000, 3).to_string(), + ) + .unwrap_or_default(), + ); + } + _ => { + row.insert(key.into(), json!(n(40) as i64 - 10)); + } + } + } + if n(6) != 0 { + row.insert( + "s".into(), + json!(["gold", "silver", "bronze", "", "goldfish"][n(5) as usize]), + ); + } + Value::Object(row) + }) + .collect() + } + + fn columns<'a>( + rows: &[Value], + numbers: &'a mut Vec<(Vec, Vec, Vec)>, + text: &'a mut (Vec, Vec, Vec), + ) -> Columns<'a> { + for key in ["x", "y"] { + let mut column = (Vec::new(), Vec::new(), vec![0u64; rows.len().div_ceil(64)]); + for (r, row) in rows.iter().enumerate() { + let d: Option = row + .get(key) + .filter(|v| v.is_number()) + .and_then(|v| v.to_string().parse().ok()); + let (m, s) = d.map_or((0, 0), |d| { + (i64::try_from(d.mantissa()).unwrap_or(0), d.scale() as u8) + }); + column.0.push(m); + column.1.push(s); + if d.is_some() { + column.2[r / 64] |= 1 << (r % 64); + } + } + numbers.push(column); + } + text.0.push(0); + text.2.resize(rows.len().div_ceil(64), 0); + for (r, row) in rows.iter().enumerate() { + if let Some(Value::String(v)) = row.get("s") { + text.1.extend_from_slice(v.as_bytes()); + text.2[r / 64] |= 1 << (r % 64); + } + text.0.push(text.1.len() as i32); + } + let mut columns = Columns::new(rows.len()); + for (key, (mant, scale, valid)) in ["x", "y"].iter().zip(numbers.iter()) { + columns = columns.column( + key, + Column::with_validity(Values::Scaled { mant, scale }, valid, 0), + ); + } + columns.column( + "s", + Column::with_validity( + Values::Utf8 { + offsets: &text.0, + data: &text.1, + }, + &text.2, + 0, + ), + ) + } + + fn expected(env: Variable, entries: &[Fusion]) -> Option> { + let mut outputs = Vec::new(); + for entry in entries { + let mut isolate = Isolate::with_environment(env.depth_clone(usize::MAX)); + let (key, value) = match entry { + Fusion::Output { key, source } | Fusion::Hidden { key, source } => { + (key, isolate.run_standard(source).ok()?) + } + Fusion::Rules { key, rules } => { + let mut chosen = Variable::Null; + for (cells, value) in rules { + let mut matched = true; + for (field, cell) in cells { + let reference = isolate.run_standard(field).ok()?; + isolate.set_reference_value(reference).ok()?; + if !isolate.run_unary(cell).ok()? { + matched = false; + break; + } + } + if matched { + chosen = isolate.run_standard(value).ok()?; + break; + } + } + (key, chosen) + } + }; + if !key.is_empty() { + env.dot_insert(key, value.clone()); + } + if !matches!(entry, Fusion::Hidden { .. }) { + outputs.push(value.to_value()); + } + } + Some(outputs) + } + + fn check(rows: &[Value], entries: &[Fusion]) { + let (mut numbers, mut text) = (Vec::new(), (Vec::new(), Vec::new(), Vec::new())); + let columns = Self::columns(rows, &mut numbers, &mut text); + let generic = LaneProgram::compile_fused(entries).expect("fused program"); + let mut runner = LaneRunner::new(); + for program in [ + generic.clone(), + generic.specialize_columns(&columns).expect("specialize"), + ] { + let mut outs: Vec = Vec::new(); + let mut failed = vec![false; rows.len()]; + runner.evaluate_columns_many(&program, &columns, &mut outs, |row, _, _| { + failed[row] = true + }); + for (r, row) in rows.iter().enumerate() { + let want = Self::expected(columns.row(r), entries); + let got = match failed[r] { + true => None, + false => outs + .iter() + .map(|o| o.variable(r).and_then(|v| v.ok()).map(|v| v.to_value())) + .collect::>>(), + }; + assert_eq!(got, want, "row {r} {row}"); + } + } + } + + fn output(key: &str, source: &str) -> Fusion { + Fusion::Output { + key: key.to_string(), + source: source.to_string(), + } + } +} + +#[test] +fn lane_fused_programs_match_sequential_evaluation() { + let rows = Fused::rows(700); + Fused::check( + &rows, + &[ + Fused::output("a.total", "(x ?? 0) + (y ?? 0)"), + Fused::output("a.flag", "a.total > 10"), + Fused::output("", "a.total * 2"), + Fused::output( + "a.label", + "a.flag ? 'big' : (a.total > 0 ? 'mid' : 'small')", + ), + Fused::output("a.net", "a.total - (y ?? 1) - (x ?? 2)"), + Fused::output("a.n", "a.label == 'big' ? a.net : -1"), + Fused::output("a.total", "a.total * 3"), + Fused::output("b", "a.total + a.n.missing"), + Fused::output("c", "s == 'gold' and a.flag"), + Fused::output( + "d", + "s == 'gold' ? 1 : (s == 'silver' ? 2.5 : (s == '' ? -1 : 0))", + ), + Fused::output( + "e", + "((s == 'goldfish') == true) ? 'F' : (((s == 'bronze') == true) ? 'B' : null)", + ), + Fused::output("f", "s == 'gold' ? true : (s == 'bronze' ? false : true)"), + Fused::output( + "g", + "a.label == 'big' ? 'B' : (a.label == 'mid' ? 'M' : 'S')", + ), + Fused::output("", "x / y"), + ], + ); + Fused::check( + &rows, + &[ + Fused::output( + "a.risk", + "(x ?? 0) > 5 ? 'high' : ((x ?? 0) > 0 ? 'mid' : 'low')", + ), + Fusion::Hidden { + key: "__fuse0".to_string(), + source: "upper(s ?? '')".to_string(), + }, + Fusion::Rules { + key: "a.discount".to_string(), + rules: vec![ + ( + vec![ + ("s".to_string(), "'gold'".to_string()), + ("a.risk".to_string(), "'low'".to_string()), + ], + "0.15".to_string(), + ), + ( + vec![ + ("s".to_string(), "'gold'".to_string()), + ("a.risk".to_string(), "'mid'".to_string()), + ], + "0.1".to_string(), + ), + ( + vec![("__fuse0".to_string(), "'SILVER'".to_string())], + "x".to_string(), + ), + ( + vec![ + ("a.risk".to_string(), "'low', 'mid'".to_string()), + ("y".to_string(), "> 3".to_string()), + ], + "y * 2".to_string(), + ), + (vec![], "0".to_string()), + ], + }, + Fused::output("a.net", "(x ?? 0) - a.discount"), + Fused::output("a.eligible", "a.risk != 'high' and a.discount > 0"), + ], + ); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_fused_programs_reject_unresolvable_reads() { + for entries in [ + vec![Fused::output("a.total", "x + 1"), Fused::output("b", "a")], + vec![ + Fused::output("a.total", "x + 1"), + Fused::output("b", "map([1, 2], a.total + #)"), + ], + vec![ + Fused::output("a.total", "x + 1"), + Fused::output("b", "$root"), + ], + vec![Fused::output("a.total", "x + 1"), Fused::output("a", "2")], + vec![Fused::output("a", "x + 1"), Fused::output("a.total", "2")], + ] { + assert!(LaneProgram::compile_fused(&entries).is_err()); + } + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_switches_over_coded_and_plain_strings() { + let texts = ["gold", "silver", "", "goldfish", "a-much-longer-tier-name"]; + let offsets: Vec = std::iter::once(0) + .chain(texts.iter().scan(0i32, |at, t| { + *at += t.len() as i32; + Some(*at) + })) + .collect(); + let data: String = texts.concat(); + let dictionary = Column::new(Values::Text { + offsets: &offsets, + data: &data, + }); + let keys: Vec = (0..300).map(|i| (i * 7 % 6) as i32 - 1).collect(); + let valid: Vec = vec![ + u64::MAX ^ 0b1001, + u64::MAX, + u64::MAX ^ (1 << 40), + u64::MAX, + u64::MAX, + ]; + let mut plain_offsets = vec![0i32]; + let mut plain = Vec::new(); + for (i, key) in keys.iter().enumerate() { + if let Some(text) = usize::try_from(*key).ok().and_then(|k| texts.get(k)) { + if i % 5 != 3 { + plain.extend_from_slice(text.as_bytes()); + } + } + plain_offsets.push(plain.len() as i32); + } + let columns = Columns::new(300) + .column( + "t", + Column::with_validity( + Values::Dict { + keys: &keys, + values: (&dictionary).into(), + }, + &valid, + 0, + ), + ) + .column( + "u", + Column::with_validity( + Values::Utf8 { + offsets: &plain_offsets, + data: &plain, + }, + &valid, + 0, + ), + ); + let expressions = [ + "t == 'gold' ? 1 : (t == 'silver' ? 2 : 3)", + "t == 'goldfish' ? 'F' : (t == '' ? 'E' : (t == 'a-much-longer-tier-name' ? 'L' : 'O'))", + "t == 'gold' ? true : (t == 'gold' ? false : null)", + "u == 'gold' ? 1 : (u == 'silver' ? 2 : 3)", + "u == 'goldfish' ? 'F' : (u == '' ? 'E' : (u == 'a-much-longer-tier-name' ? 'L' : 'O'))", + "(u == 'gold' ? 1 : (u == 'silver' ? 2 : 3)) + (t == 'gold' ? 10 : (t == 'silver' ? 20 : 30))", + ]; + for expression in expressions.iter().take(5) { + let program = LaneProgram::standard(expression).expect("compile"); + let switched = program + .program() + .steps + .iter() + .any(|step| matches!(step.op, zen_expression::lane::Op::Switch(_))); + assert!(switched, "{expression}"); + } + Rows::check(&columns, &expressions); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn lane_clock_reads_are_not_timeless() { + let timeless = |source: &str| { + LaneProgram::compile(source, ExpressionKind::Standard) + .unwrap() + .program() + .timeless() + }; + let clocked = [ + "year('now')", + "dayOfWeek('now')", + "dayOfMonth('now')", + "dayOfYear('now')", + "weekOfYear('now')", + "monthOfYear('now')", + "monthString('now')", + "weekdayString('now')", + "startOf('now', 'day')", + "endOf('now', 'day')", + "date('now')", + "d()", + "d('Europe/Berlin')", + "d('2024-01-01').isToday()", + "rand(10)", + ]; + let frozen: Vec<&str> = clocked + .into_iter() + .filter(|source| timeless(source)) + .collect(); + assert!( + frozen.is_empty(), + "timeless although they read the clock: {frozen:?}" + ); + assert!( + timeless("duration('1h') + 1"), + "duration does not read the clock" + ); + let folded = [ + "d('now')", + "d('nope').isValid()", + "year('2024-03-05')", + "monthString(1700000000)", + ]; + let unfolded: Vec<&str> = folded + .into_iter() + .filter(|source| !timeless(source)) + .collect(); + assert!( + unfolded.is_empty(), + "constant date calls not folded: {unfolded:?}" + ); +} + +#[test] +fn lane_date_folds_match_the_stack_vm() { + let mut d = Differential::new(ExpressionKind::Standard); + let inputs = vec![json!({"a": 1})]; + let expressions = [ + "d('now')", + "d('nope')", + "d('nope').isValid()", + "string(d('nope'))", + "d(null)", + "d(true).isValid()", + "d(1700000000000).year()", + "d('2024-03-05', 'Europe/Berlin').hour()", + "year('2024-03-05') + a", + "monthString('2024-03-05')", + "weekdayString(1700000000)", + "startOf('2024-03-05 10:20', 'day')", + "endOf('2024-03-05', 'month')", + "date('2024-01-01') + time('10:30')", + "dayOfYear('garbage')", + "dateString(1700000000)", + ]; + for e in expressions { + d.check(e, &inputs); + } + d.assert(); +} + +#[test] +#[cfg_attr(miri, ignore)] +fn lane_handles_deep_and_wide_expressions() { + std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(deep_and_wide_on_this_thread) + .expect("spawn") + .join() + .expect("deep and wide expressions"); +} + +fn deep_and_wide_on_this_thread() { + let n = 5_000; + let values = 100; + let nest = |open: &str, middle: &str, close: &str| { + format!("{}{middle}{}", open.repeat(n), close.repeat(n)) + }; + let standard = [ + nest("1 + ", "1", ""), + nest("(", "1", ")"), + nest("true ? ", "1", " : 0"), + format!("len({}1{})", "[".repeat(values), "]".repeat(values)), + format!( + "len(keys({}1{}))", + "{a: ".repeat(values), + "}".repeat(values) + ), + format!("a{}", ".b".repeat(n)), + format!("a{}", "[0]".repeat(n)), + nest("x and ", "x", ""), + nest("y ?? ", "1", ""), + nest("abs(", "-1", ")"), + nest("sum(map([1], ", "#", "))"), + nest("'a' + ", "'a'", ""), + nest("s = 1; ", "s", ""), + format!( + "len([{}])", + (0..n) + .map(|i| format!("'s{i}'")) + .collect::>() + .join(", ") + ), + format!( + "len(keys({{{}}}))", + (0..n) + .map(|i| format!("k{i}: {i}")) + .collect::>() + .join(", ") + ), + ]; + let input = serde_json::json!({"a": {"b": null}, "x": true, "y": null}); + let mut d = Differential::new(ExpressionKind::Standard); + for expression in &standard { + d.check(expression, &[input.clone(), serde_json::json!({"x": true})]); + d.columns(expression, std::slice::from_ref(&input)); + } + d.assert(); + let unary = [nest("> 0 and ", "< 5", ""), format!("{}2", "1, ".repeat(n))]; + let mut d = Differential::new(ExpressionKind::Unary); + for expression in &unary { + d.check( + expression, + &[serde_json::json!({"$": 2}), serde_json::json!({"$": 7})], + ); + } + d.assert(); + conformance::Spec::no_fallbacks(); +} diff --git a/core/expression/tests/lane_config.rs b/core/expression/tests/lane_config.rs new file mode 100644 index 00000000..2bced529 --- /dev/null +++ b/core/expression/tests/lane_config.rs @@ -0,0 +1,35 @@ +mod conformance; + +use conformance::Spec; +use std::sync::atomic::Ordering; +use zen_expression::ZEN_EXPRESSION_CONFIG; + +#[test] +fn isolate_matches_on_both_engines_when_lane_is_enabled() { + Spec::prepare(); + let (cases, problems) = Spec::cases(); + assert!( + problems.is_empty(), + "malformed spec:\n{}", + problems.join("\n") + ); + let run = || -> Vec { + cases + .iter() + .map(|case| case.verdict(&case.exact()).is_none()) + .collect() + }; + let stack = run(); + ZEN_EXPRESSION_CONFIG.lane.store(true, Ordering::Relaxed); + let lane = run(); + ZEN_EXPRESSION_CONFIG.lane.store(false, Ordering::Relaxed); + let failures: Vec = cases + .iter() + .zip(stack.iter().zip(&lane)) + .filter(|(_, (a, b))| a != b) + .take(40) + .map(|(case, (a, b))| format!("{} | stack passes {a} | lane passes {b}", case.location())) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); + Spec::no_fallbacks(); +} diff --git a/core/expression/tests/session.rs b/core/expression/tests/session.rs new file mode 100644 index 00000000..23a19297 --- /dev/null +++ b/core/expression/tests/session.rs @@ -0,0 +1,864 @@ +mod conformance; + +use serde_json::json; +use std::collections::{BTreeMap, HashMap}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{LaneProgram, Programs, Session}; +use zen_expression::variable::Symbol; +use zen_expression::{ExpressionKind, Isolate, IsolateError, Variable}; + +struct Identity { + known: HashMap, +} + +impl Identity { + fn of(isolate: &zen_expression::Scope) -> Self { + let mut identity = Self { + known: HashMap::new(), + }; + identity.index(isolate.base(), "env".to_string()); + for (name, value) in isolate.locals() { + identity.index(value, format!("local:{name}")); + } + identity + } + + fn address(value: &Variable) -> Option { + match value { + Variable::Array(a) => Some(Rc::as_ptr(a) as *const () as usize), + Variable::Object(o) => Some(Rc::as_ptr(o) as *const () as usize), + _ => None, + } + } + + fn index(&mut self, value: &Variable, path: String) { + let Some(address) = Self::address(value) else { + return; + }; + if self.known.contains_key(&address) { + return; + } + self.known.insert(address, path.clone()); + match value { + Variable::Array(a) => { + for (i, item) in a.borrow().iter().enumerate() { + self.index(item, format!("{path}[{i}]")); + } + } + Variable::Object(o) => { + for (k, item) in o.borrow().iter() { + self.index(item, format!("{path}.{k}")); + } + } + _ => {} + } + } + + fn print(&self, value: &Variable) -> String { + let mut fresh = HashMap::new(); + let mut out = String::new(); + self.walk(value, &mut fresh, &mut out); + out + } + + fn walk(&self, value: &Variable, fresh: &mut HashMap, out: &mut String) { + let Some(address) = Self::address(value) else { + out.push('_'); + return; + }; + if let Some(path) = self.known.get(&address) { + out.push('@'); + out.push_str(path); + return; + } + if let Some(n) = fresh.get(&address) { + out.push_str(&format!("#{n}")); + return; + } + let n = fresh.len(); + fresh.insert(address, n); + match value { + Variable::Array(a) => { + out.push('['); + for item in a.borrow().iter() { + self.walk(item, fresh, out); + out.push(','); + } + out.push(']'); + } + Variable::Object(o) => { + let o = o.borrow(); + let mut keys: Vec<_> = o.keys().map(|k| k.to_string()).collect(); + keys.sort(); + out.push('{'); + for key in keys { + out.push_str(&key); + out.push(':'); + if let Some(item) = o.get_str(&key) { + self.walk(item, fresh, out); + } + out.push(','); + } + out.push('}'); + } + _ => {} + } + } +} + +struct Strict; + +impl Strict { + fn same(a: &Variable, b: &Variable) -> bool { + match (a, b) { + (Variable::Number(x), Variable::Number(y)) => x.to_string() == y.to_string(), + (Variable::Array(x), Variable::Array(y)) => { + let (x, y) = (x.borrow(), y.borrow()); + x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| Self::same(p, q)) + } + (Variable::Object(x), Variable::Object(y)) => { + let (x, y) = (x.borrow(), y.borrow()); + x.len() == y.len() + && x.iter() + .all(|(k, p)| y.get(k).is_some_and(|q| Self::same(p, q))) + } + (x, y) => conformance::Spec::same(x, y) && conformance::Spec::same(y, x), + } + } + + fn render(result: &Result) -> String { + match result { + Ok(value) => format!("{value:?}"), + Err(e) => format!("!{}", conformance::Spec::describe(e)), + } + } +} + +#[derive(Default)] +struct Report { + compared: usize, + failures: Vec, + shared: usize, + unshared: Vec, +} + +impl Report { + fn assert(&self, what: &str) { + eprintln!( + "{what}: compared {} | identity checked {} | identity differences {}", + self.compared, + self.shared, + self.unshared.len() + ); + let shown: Vec<&String> = self.failures.iter().take(40).collect(); + assert!( + self.failures.is_empty(), + "{what}: {} of {} comparisons differ:\n{}", + self.failures.len(), + self.compared, + shown + .iter() + .map(|s| s.as_str()) + .collect::>() + .join("\n") + ); + conformance::Spec::no_fallbacks(); + } + + fn assert_identity(&self, what: &str) { + let shown: Vec<&String> = self.unshared.iter().take(40).collect(); + assert!( + self.unshared.is_empty(), + "{what}: {} Rc identity differences:\n{}", + self.unshared.len(), + shown + .iter() + .map(|s| s.as_str()) + .collect::>() + .join("\n") + ); + } +} + +struct Pair<'r> { + isolate: Isolate, + session: Session, + report: &'r mut Report, + label: String, +} + +impl<'r> Pair<'r> { + fn new(report: &'r mut Report, label: &str, programs: Option>) -> Self { + Self { + isolate: Isolate::new(), + session: Session::new().with_programs(programs), + report, + label: label.to_string(), + } + } + + fn fail(&mut self, step: &str, want: String, got: String) { + self.report.failures.push(format!( + "{} | {step} | session {got} vs isolate {want}", + self.label + )); + } + + fn state(&mut self, step: &str) { + self.report.compared += 1; + let (a, b) = (self.isolate.scope(), self.session.scope()); + let same_base = Strict::same(a.base(), b.base()); + let same_locals = a.locals().len() == b.locals().len() + && a.locals() + .iter() + .zip(b.locals()) + .all(|((ka, va), (kb, vb))| ka.as_str() == kb.as_str() && Strict::same(va, vb)); + if !same_base || !same_locals { + let want = format!("{:?} {:?}", a.base(), a.locals()); + let got = format!("{:?} {:?}", b.base(), b.locals()); + self.fail(&format!("{step} state"), want, got); + } + } + + fn compare( + &mut self, + step: &str, + want: Result, + got: Result, + ) { + self.report.compared += 1; + let same = match (&want, &got) { + (Ok(a), Ok(b)) => Strict::same(a, b), + (Err(a), Err(b)) => { + format!("{a:?}") == format!("{b:?}") && a.to_string() == b.to_string() + } + _ => false, + }; + if !same { + self.fail(step, Strict::render(&want), Strict::render(&got)); + return; + } + if let (Ok(a), Ok(b)) = (&want, &got) { + self.report.shared += 1; + let (left, right) = ( + Identity::of(self.isolate.scope()).print(a), + Identity::of(self.session.scope()).print(b), + ); + if left != right { + self.report.unshared.push(format!( + "{} | {step} | session {right} vs isolate {left}", + self.label + )); + } + } + self.state(step); + } + + fn environment(&mut self, env: &Variable) { + self.isolate.set_environment(env.deep_clone()); + self.session.set_environment(env.deep_clone()); + self.state("set_environment"); + } + + fn local(&mut self, name: &str, value: &Variable) { + self.isolate + .set_local(Symbol::from(name), value.deep_clone()); + self.session + .set_local(Symbol::from(name), value.deep_clone()); + self.state(&format!("set_local {name}")); + } + + fn standard(&mut self, source: &str) -> Option { + let want = self.isolate.run_standard(source); + let got = self.session.run_standard(source); + let result = want.as_ref().ok().cloned(); + self.compare(&format!("run_standard {source}"), want, got); + result + } + + fn unary(&mut self, source: &str) -> bool { + let want = self.isolate.run_unary(source); + let got = self.session.run_unary(source); + let result = want.as_ref().is_ok_and(|b| *b); + self.compare( + &format!("run_unary {source}"), + want.map(Variable::Bool), + got.map(Variable::Bool), + ); + result + } + + fn dollar(&mut self, path: &str, value: &Variable) { + self.isolate.insert_dollar(path, value.deep_clone()); + self.session.insert_dollar(path, value.deep_clone()); + self.state(&format!("insert_dollar {path}")); + } + + fn produced_dollar(&mut self, path: &str, source: &str) { + let want = self.isolate.run_standard(source); + let got = self.session.run_standard(source); + let (a, b) = match (&want, &got) { + (Ok(a), Ok(b)) => (a.clone(), b.clone()), + _ => (Variable::Null, Variable::Null), + }; + self.compare(&format!("run_standard {source}"), want, got); + let (a, b) = match source.contains('$') { + true => (a.deep_clone(), b.deep_clone()), + false => (a, b), + }; + self.isolate.insert_dollar(path, a); + self.session.insert_dollar(path, b); + self.state(&format!("insert_dollar {path}")); + } + + fn reference(&mut self, field: &str) -> bool { + let want = self.isolate.set_reference(field); + let got = self.session.set_reference(field); + let ok = want.is_ok(); + self.compare( + &format!("set_reference {field}"), + want.map(|_| Variable::Null), + got.map(|_| Variable::Null), + ); + self.get_reference(field); + ok + } + + fn get_reference(&mut self, field: &str) { + let want = self.isolate.get_reference(field); + let got = self.session.get_reference(field); + self.report.compared += 1; + let same = match (&want, &got) { + (Some(a), Some(b)) => Strict::same(a, b), + (None, None) => true, + _ => false, + }; + if !same { + self.fail( + &format!("get_reference {field}"), + format!("{want:?}"), + format!("{got:?}"), + ); + } + } + + fn reference_value(&mut self, value: &Variable) { + let want = self.isolate.set_reference_value(value.deep_clone()); + let got = self.session.set_reference_value(value.deep_clone()); + self.compare( + "set_reference_value", + want.map(|_| Variable::Null), + got.map(|_| Variable::Null), + ); + } + + fn reference_from(&mut self, field: &str) -> bool { + let want = self.isolate.run_standard(field); + let got = self.session.run_standard(field); + let values = match (&want, &got) { + (Ok(a), Ok(b)) => Some((a.clone(), b.clone())), + _ => None, + }; + self.compare(&format!("run_standard {field}"), want, got); + let Some((a, b)) = values else { + return false; + }; + let _ = self.isolate.set_reference_value(a); + let _ = self.session.set_reference_value(b); + self.state("set_reference_value"); + true + } +} + +struct Scenarios; + +impl Scenarios { + fn env() -> Variable { + Variable::from(json!({ + "customer": {"age": 34, "name": "Ann", "tier": "gold", "tags": ["a", "b"], "score": 1.50, "address": {"city": "Split"}}, + "order": {"total": 120.25, "items": [{"sku": "x", "qty": 2, "price": 10.5}, {"sku": "y", "qty": 1, "price": 99.25}]}, + "flags": [true, false], + "matrix": [[1, 2], [3, 4]], + "empty": {}, + "none": null, + "text": "hello", + "when": "2024-03-15T10:00:00Z", + "$": {"stale": true} + })) + } + + fn nodes() -> Variable { + Variable::from(json!({"input": {"a": 1, "nested": {"b": [1, 2]}}, "calc": {"total": 10}})) + } + + const EXPRESSIONS: &'static [(&'static str, &'static str)] = &[ + ("age", "customer.age"), + ("adult", "$.age >= 18"), + ("customer", "customer"), + ("address", "customer.address"), + ("copy", "$.customer"), + ("whole", "$"), + ("nested.value", "$.address.city + '!'"), + ("nested.other", "$.nested"), + ("items", "order.items"), + ("first", "order.items[0]"), + ("mapped", "map(order.items, #.qty * #.price)"), + ("filtered", "filter(order.items, #.qty > 1)"), + ("node", "$nodes.input.nested"), + ("nodeArr", "$nodes.input.nested.b"), + ("obj", "{ c: customer, n: 1, a: customer.address }"), + ("arr", "[customer, customer.address, order.items[1]]"), + ("cond", "customer.age > 30 ? customer.address : order"), + ("coalesce", "none ?? customer"), + ("missing", "customer.unknown.deeper"), + ("bad", "customer.age + 'x'"), + ("after", "$.bad"), + ("assigned", "x = customer; y = x.address; y"), + ("date", "d(when)"), + ("dateBad", "d('not a date')"), + ("text", "upper(text) + string($.age)"), + ("keysOf", "keys(customer)"), + ("slice", "customer.tags[0:1]"), + ("matrix", "matrix[1]"), + ("flat", "flatten(matrix)"), + ("sum", "sum(map(order.items, #.price))"), + ("call", "abs()"), + ("unknown", "nofn(1)"), + ("lexer", "'unterminated"), + ("parser", "customer.age +"), + ("closureDollar", "map(order.items, $.age + #.qty)"), + ("dollarSelf", "$.dollarSelf"), + ]; + + const FIELDS: &'static [&'static str] = &[ + "customer.age", + "customer", + "customer.tags", + "order.items", + "order.items[0]", + "none", + "text", + "customer.age + 'x'", + "customer.age +", + "$", + "$.stale", + "$nodes.calc.total", + "when", + ]; + + const CELLS: &'static [&'static str] = &[ + "> 18", + "< 18", + "[18..40]", + "'Ann'", + "'gold', 'silver'", + "contains($, 'a')", + "$.address.city == 'Split'", + "len($) > 1", + "$ == null", + "$", + "$ + 1", + "", + "'x' + 1", + "> 'a'", + "== customer.age", + "startsWith($, 'h')", + "d($) > d('2020-01-01')", + "some($, # == 'a')", + "$ in [1, 2]", + "> ", + "abs()", + ]; + + const STANDALONE: &'static [&'static str] = &[ + "customer.age > 18", + "customer.age", + "text", + "$ == null", + "none", + "1 +", + "customer.age > 'x'", + ]; + + fn expression_node(pair: &mut Pair) { + pair.environment(&Self::env()); + pair.local("$nodes", &Self::nodes()); + for (key, source) in Self::EXPRESSIONS { + pair.produced_dollar(key, source); + } + pair.standard("$"); + pair.standard("$.nested"); + pair.standard("$nodes"); + } + + fn graph_table(pair: &mut Pair) { + pair.environment(&Self::env()); + pair.local("$nodes", &Self::nodes()); + for field in Self::FIELDS { + for cell in Self::CELLS { + if pair.reference(field) { + pair.unary(cell); + } + } + pair.get_reference(field); + } + for cell in Self::STANDALONE { + pair.standard(cell); + } + for field in Self::FIELDS { + pair.get_reference(field); + pair.standard(field); + } + } + + fn policy_table(pair: &mut Pair) { + pair.environment(&Self::env()); + for field in Self::FIELDS { + if pair.reference_from(field) { + for cell in Self::CELLS { + pair.unary(cell); + } + } + } + pair.reference_value(&Variable::from(json!({"k": [1, 2, 3]}))); + pair.unary("len($.k) == 3"); + pair.standard("$"); + } + + fn switching(pair: &mut Pair) { + pair.environment(&Self::env()); + pair.reference("customer.age"); + pair.dollar("x.y", &Variable::from(json!({"z": 1}))); + pair.standard("$"); + pair.environment(&Variable::from(json!({"customer": {"age": 7}}))); + pair.get_reference("customer.age"); + pair.standard("$"); + pair.unary("> 5"); + pair.reference("customer.age"); + pair.unary("> 5"); + pair.environment(&Variable::Null); + pair.standard("customer.age"); + pair.standard("$"); + pair.unary("$ == null"); + pair.dollar("a", &Variable::from(json!(1))); + pair.standard("$.a"); + pair.environment(&Variable::from(json!([1, 2, 3]))); + pair.standard("$"); + pair.standard("len($root)"); + pair.environment(&Variable::from(json!("text"))); + pair.standard("upper($root)"); + pair.reference_value(&Variable::from(json!(5))); + pair.dollar("a.b", &Variable::from(json!(2))); + pair.standard("$"); + pair.reference_value(&Variable::from(json!({"q": 1}))); + pair.dollar("w", &Variable::from(json!(2))); + pair.standard("$"); + pair.local("$", &Variable::from(json!("local"))); + pair.standard("$"); + pair.unary("'local'"); + pair.unary("1 + 1"); + pair.unary("'x'"); + } + + fn policy_driver(pair: &mut Pair) { + let env = Self::env(); + for round in 0..3 { + pair.environment(&env); + pair.standard("customer.age >= 18 and customer.tier != 'none'"); + pair.standard("order.total * 2"); + pair.standard("customer.age / 0"); + pair.standard("customer.name > 3"); + pair.standard("sum(map(order.items, #.qty))"); + pair.standard(match round { + 0 => "$", + 1 => "$.stale", + _ => "$root", + }); + pair.reference_from("customer.age"); + pair.unary("> 18"); + pair.standard("$"); + } + } + + fn all(report: &mut Report, programs: Option>, label: &str) { + for name in [ + "expression node", + "graph table", + "policy table", + "switching", + "policy driver", + ] { + for _ in 0..2 { + let mut pair = Pair::new(report, &format!("{label}: {name}"), programs.clone()); + for _ in 0..2 { + match name { + "expression node" => Self::expression_node(&mut pair), + "graph table" => Self::graph_table(&mut pair), + "policy table" => Self::policy_table(&mut pair), + "switching" => Self::switching(&mut pair), + _ => Self::policy_driver(&mut pair), + } + } + } + } + } + + fn sources() -> Vec<(&'static str, ExpressionKind)> { + let mut sources = Vec::new(); + for (_, source) in Self::EXPRESSIONS { + sources.push((*source, ExpressionKind::Standard)); + } + for field in Self::FIELDS.iter().chain(Self::STANDALONE) { + sources.push((*field, ExpressionKind::Standard)); + } + for cell in Self::CELLS { + sources.push((*cell, ExpressionKind::Unary)); + } + sources + } +} + +struct Checks; + +impl Checks { + fn sendable() {} +} + +#[test] +fn session_matches_isolate_in_executor_sequences() { + conformance::Spec::prepare(); + let mut report = Report::default(); + Scenarios::all(&mut report, None, "fallback"); + let programs = Arc::new(Programs::compile(Scenarios::sources())); + Scenarios::all(&mut report, Some(programs.clone()), "precompiled"); + Scenarios::all(&mut report, Some(Arc::new(Programs::new())), "empty"); + report.assert("session scenarios"); + report.assert_identity("session scenarios"); +} + +#[test] +fn session_programs_are_shared_across_threads() { + Checks::sendable::(); + Checks::sendable::>(); + let programs = Arc::new(Programs::compile([ + ("a + 1", ExpressionKind::Standard), + ("> 1", ExpressionKind::Unary), + ])); + let handles: Vec<_> = (0..3) + .map(|i| { + let programs = programs.clone(); + std::thread::spawn(move || { + let mut session = Session::with_environment(Variable::from(json!({"a": i}))) + .with_programs(Some(programs)); + let value = session.run_standard("a + 1").map(|v| v.to_value()); + let _ = session.set_reference_value(Variable::from(json!(i))); + let unary = session.run_unary("> 1"); + (value.ok(), unary.ok()) + }) + }) + .collect(); + let got: Vec<_> = handles + .into_iter() + .map(|h| h.join().expect("thread")) + .collect(); + assert_eq!( + got, + vec![ + (Some(json!(1)), Some(false)), + (Some(json!(2)), Some(false)), + (Some(json!(3)), Some(true)) + ] + ); + assert_eq!(programs.len(), 2); +} + +#[test] +fn session_compile_errors_match_isolate_exactly() { + let sources: &[(&str, ExpressionKind)] = &[ + ("'abc", ExpressionKind::Standard), + ("a +", ExpressionKind::Standard), + ("abs()", ExpressionKind::Standard), + ("unknownFn(1)", ExpressionKind::Standard), + ("a.b(", ExpressionKind::Standard), + ("x = ; 1", ExpressionKind::Standard), + ("[1, 2", ExpressionKind::Standard), + ("> ", ExpressionKind::Unary), + ("'a', ", ExpressionKind::Unary), + ("abs()", ExpressionKind::Unary), + ("$.a.method()", ExpressionKind::Standard), + ("len(1, 2)", ExpressionKind::Standard), + ("`${a`", ExpressionKind::Standard), + ("#", ExpressionKind::Standard), + ("1 ?? ", ExpressionKind::Standard), + ]; + let mut failures = Vec::new(); + for (source, kind) in sources { + let mut isolate = Isolate::new(); + let want = match kind { + ExpressionKind::Standard => isolate.compile_standard(source).map(|_| ()), + ExpressionKind::Unary => isolate.compile_unary(source).map(|_| ()), + }; + let got = LaneProgram::compile(source, kind.clone()).map(|_| ()); + let (want, got) = (format!("{want:?}"), format!("{got:?}")); + if want != got { + failures.push(format!("{source} | lane {got} vs vm {want}")); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + conformance::Spec::no_fallbacks(); +} + +#[test] +fn session_matches_isolate_over_the_spec() { + conformance::Spec::prepare(); + let (cases, problems) = conformance::Spec::cases(); + assert!( + problems.is_empty(), + "malformed spec:\n{}", + problems.join("\n") + ); + let mut report = Report::default(); + let mut groups: BTreeMap<(bool, String), Vec<&conformance::SpecCase>> = BTreeMap::new(); + for case in &cases { + let unary = matches!(case.kind, ExpressionKind::Unary); + groups + .entry((unary, case.expression.clone())) + .or_default() + .push(case); + } + let sources: Vec<(&str, ExpressionKind)> = groups + .keys() + .map(|(unary, source)| { + let kind = match unary { + true => ExpressionKind::Unary, + false => ExpressionKind::Standard, + }; + (source.as_str(), kind) + }) + .collect(); + let programs = Arc::new(Programs::compile(sources)); + let mut skipped = 0usize; + for ((unary, source), group) in &groups { + let unstable = group.iter().any(|c| { + let (a, b) = (c.exact(), c.exact()); + match (&a, &b) { + (Ok(x), Ok(y)) => !Strict::same(x, y), + (Err(x), Err(y)) => x != y || x.starts_with(conformance::Spec::PANIC), + _ => true, + } + }); + if unstable { + skipped += group.len(); + continue; + } + let mut pair = Pair::new(&mut report, source, Some(programs.clone())); + for case in group { + pair.environment(&case.environment()); + match unary { + true => { + pair.unary(source); + if let Some(input) = &case.input { + pair.reference_value(input); + pair.unary(source); + } + } + false => { + pair.standard(source); + pair.dollar("prev", &Variable::from(json!({"v": 1}))); + pair.standard(source); + } + } + } + } + eprintln!( + "spec groups {} | skipped {skipped} nondeterministic cases", + groups.len() + ); + report.assert("session spec"); + let shown: Vec<&String> = report.unshared.iter().take(60).collect(); + eprintln!( + "identity differences {}:\n{}", + report.unshared.len(), + shown + .iter() + .map(|s| s.as_str()) + .collect::>() + .join("\n") + ); + report.assert_identity("session spec"); +} + +#[test] +fn session_shares_rc_like_isolate() { + let env = Variable::from(json!({ + "customer": {"address": {"city": "Split"}, "tags": ["a"]}, + "items": [{"a": 1}, {"a": 2}] + })); + let nodes = Variable::from(json!({"input": {"x": {"y": 1}}})); + let cases: &[(&str, &str)] = &[ + ("member object", "customer"), + ("nested member", "customer.address"), + ("member array", "customer.tags"), + ("index", "items[0]"), + ("dollar passthrough", "$"), + ("dollar member", "$.address"), + ("nodes member", "$nodes.input.x"), + ("inserted dollar", "$.inserted"), + ("conditional", "true ? customer : null"), + ("coalesce", "null ?? customer"), + ("object literal", "{ c: customer }"), + ("array literal", "[customer]"), + ("root", "$root"), + ("filter", "filter(items, true)"), + ("map identity", "map(items, #)"), + ("slice", "items[0:1]"), + ]; + let mut rows = Vec::new(); + let mut differences = Vec::new(); + for (name, source) in cases { + let mut isolate = Isolate::with_environment(env.deep_clone()); + let mut session = Session::with_environment(env.deep_clone()); + isolate.set_local(Variable::nodes_key(), nodes.deep_clone()); + session.set_local(Variable::nodes_key(), nodes.deep_clone()); + isolate + .set_reference("customer") + .expect("isolate reference"); + session + .set_reference("customer") + .expect("session reference"); + let inserted = Variable::from(json!({"k": [1]})); + isolate.insert_dollar("inserted", inserted.deep_clone()); + session.insert_dollar("inserted", inserted.deep_clone()); + let (Ok(want), Ok(got)) = (isolate.run_standard(source), session.run_standard(source)) + else { + differences.push(format!("{name}: {source} failed")); + continue; + }; + let left = Identity::of(isolate.scope()).print(&want); + let right = Identity::of(session.scope()).print(&got); + rows.push(format!( + "{name:<20} {source:<24} isolate {left} | session {right}" + )); + if left != right { + differences.push(format!("{name}: {source} isolate {left} session {right}")); + } + let reference = ( + isolate.get_reference("customer"), + session.get_reference("customer"), + ); + if let (Some(Variable::Object(a)), Some(Variable::Object(b))) = reference { + let base_a = isolate.scope().base().dot("customer"); + let base_b = session.scope().base().dot("customer"); + let shared_a = matches!(base_a, Some(Variable::Object(o)) if Rc::ptr_eq(&o, &a)); + let shared_b = matches!(base_b, Some(Variable::Object(o)) if Rc::ptr_eq(&o, &b)); + if shared_a != shared_b { + differences.push(format!( + "{name}: reference sharing isolate {shared_a} session {shared_b}" + )); + } + } + } + eprintln!("{}", rows.join("\n")); + assert!(differences.is_empty(), "{}", differences.join("\n")); +} diff --git a/core/expression/tests/spec.rs b/core/expression/tests/spec.rs new file mode 100644 index 00000000..d889d24e --- /dev/null +++ b/core/expression/tests/spec.rs @@ -0,0 +1,81 @@ +mod conformance; + +use conformance::{Note, Spec}; +use std::collections::BTreeMap; + +#[derive(Default)] +struct Tally { + total: usize, + failed: usize, + bugs: usize, + questions: usize, +} + +#[test] +#[cfg_attr( + feature = "regex-lite", + ignore = "the spec assumes the full regex engine (Unicode classes and case folding)" +)] +fn spec_matches_stack_vm() { + Spec::prepare(); + let (cases, problems) = Spec::cases(); + let mut failures = Vec::new(); + let mut bugs = Vec::new(); + let mut files: BTreeMap = BTreeMap::new(); + for case in &cases { + let tally = files.entry(case.file.clone()).or_default(); + tally.total += 1; + let verdict = case.verdict(&case.stack()); + match (&case.note, verdict) { + (Note::Bug(note), Some(failure)) => { + tally.bugs += 1; + bugs.push(format!("{failure} | bug: {note}")); + } + (Note::Bug(note), None) => { + tally.failed += 1; + failures.push(format!( + "{} | {} | passes now, drop the bug note ({note})", + case.location(), + case.expression + )); + } + (note, Some(failure)) => { + tally.failed += 1; + tally.questions += matches!(note, Note::Question(_)) as usize; + failures.push(failure); + } + (note, None) => tally.questions += matches!(note, Note::Question(_)) as usize, + } + } + for (file, t) in &files { + eprintln!( + "{file}: {} cases, {} failed, {} known bugs, {} questions", + t.total, t.failed, t.bugs, t.questions + ); + } + eprintln!( + "spec: {} cases, {} failed, {} known bugs, {} malformed", + cases.len(), + failures.len(), + bugs.len(), + problems.len() + ); + if std::env::var("SPEC_BUGS").is_ok() { + eprintln!("known bugs:\n{}", bugs.join("\n")); + } + let limit: usize = std::env::var("SPEC_SHOW") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(60); + assert!( + problems.is_empty() && failures.is_empty(), + "malformed:\n{}\nfailures:\n{}", + problems.join("\n"), + failures + .iter() + .take(limit) + .cloned() + .collect::>() + .join("\n") + ); +} diff --git a/core/expression/tests/spec/README.md b/core/expression/tests/spec/README.md new file mode 100644 index 00000000..785be880 --- /dev/null +++ b/core/expression/tests/spec/README.md @@ -0,0 +1,47 @@ +# ZEN expression conformance suite + +Executable specification of the ZEN expression language, in the spirit of test262. +Each case states what the language is meant to produce, not only what the current VM +does. Known deviations are recorded in place. + +## Layout + +- `standard/NN-chapter.csv`: standard expressions (`Isolate::run_standard`) +- `unary/NN-chapter.csv`: unary expressions (`Isolate::run_unary`, reference in `$`) + +## Row format + +`expression;input;output;note`, `;`-separated CSV. Fields containing `;` or `"` are +wrapped in double quotes with inner `"` doubled. Lines starting with `#` are section +comments. + +- **expression**: source text. It cannot start with `#`. +- **input**: the environment as a JSON5-like literal, or empty for none. Numbers are read + as exact decimals, so `0.1000000000000000000000000001` is kept. `date('...')` is a date + input that keeps its source text, as the engine produces for schema date fields + (`DateValue::from_text`). +- **output**: the expected value as a literal, or `!error` (any error). Numbers are + compared by exact decimal value (`1.10 == 1.1`); scale is observed through `string()` + or templates. Dates are written as their string form + (`'2024-01-01T00:00:00Z'`). +- **note** (optional): + - `bug: `: the output column holds the intended result and the current VM + differs. + - `question: `: the output column holds current behaviour whose intent is + unclear. + +## Runners + +- `cargo test -p zen-expression --test spec`: the stack VM against the spec. A `bug:` + case that starts passing fails the run, so the note gets removed. +- `cargo test -p zen-expression --test lane lane_matches_spec`: every lane path (row, + batch, specialized, typed, columns) against the stack VM's actual result, bugs + included. + +Environment knobs: +- `SPEC_FILE=`: run only matching files. +- `SPEC_SHOW=`: how many failures to print. +- `SPEC_BUGS=1`: list known bugs. +- `SPEC_TZ=`: local time zone (default UTC). + +Evaluation time is fixed at `2025-03-20T10:15:30Z`. diff --git a/core/expression/tests/spec/standard/00-harness.csv b/core/expression/tests/spec/standard/00-harness.csv new file mode 100644 index 00000000..cf0dd84d --- /dev/null +++ b/core/expression/tests/spec/standard/00-harness.csv @@ -0,0 +1,14 @@ +expression (string);input (json 5);output (json 5);note +# Harness self-checks: exact decimals, errors, notes, panics +0.1 + 0.2;;0.3 +1 / 3;;0.3333333333333333333333333333 +string(1.10 + 1);;'2.10' +a + b;{a: 0.1000000000000000000000000001, b: 1};1.1000000000000000000000000001 +[1, 'a', {x: null}];;[1, "a", {x: null}] +keys({'': 1});;[''] +{'': 1};;{'': 1} +1 + {};;!error +"x = 1; x + 1";{};2 +"x = 1; x + 1";;!error;question: assignments need an object environment; with no input they fail +d('2024-01-01');;'2024-01-01T00:00:00Z' +rand(-1);;!error;bug: panics inside fastrand (empty range) instead of returning an error diff --git a/core/expression/tests/spec/standard/01-collections.csv b/core/expression/tests/spec/standard/01-collections.csv new file mode 100644 index 00000000..cb775b0f --- /dev/null +++ b/core/expression/tests/spec/standard/01-collections.csv @@ -0,0 +1,252 @@ +expression (string);input (json 5);output (json 5);note +# Array literals +[];;[] +[ ];;[] +type([]);;'array' +[1];;[1] +[1, 2, 3];;[1, 2, 3] +[1,2,3];;[1, 2, 3] +[ 1 , 2 , 3 ];;[1, 2, 3] +[1, 'a', true, null];;[1, 'a', true, null] +[{}, [], null, '', 0, false];;[{}, [], null, '', 0, false] +[1.50, -0.5, 1e2];;[1.5, -0.5, 100] +[1 + 1, 2 * 3];;[2, 6] +['a' + 'b'];;['ab'] +[(1)];;[1] +len([1, 2, 3]);;3 +len([]);;0 +# Nested arrays +[[]];;[[]] +[[[]]];;[[[]]] +[[1, 2], [3]];;[[1, 2], [3]] +[[1, [2, [3, [4]]]]];;[[1, [2, [3, [4]]]]] +[[], [[]], [[], []]];;[[], [[]], [[], []]] +# Trailing commas and holes +[1,];;[1] +[1, 2,];;[1, 2] +[[1,],];;[[1]] +[,];;!error +[,1];;!error +[1,,2];;!error +[1,,];;!error +# Missing separators and brackets +[1 2];;!error +['a' 'b'];;!error +[;;!error +[1;;!error +[1,;;!error +];;!error +[1]];;!error +[[1];;!error +# Indexing an array literal +[1, 2, 3][0];;1 +[1, 2, 3][2];;3 +[1, 2, 3][3];;null +[[1, 2], [3]][0][1];;2 +[{a: 1}][0].a;;1 +# Arrays built from the input +[x];{x: 1};[1] +[x];{x: null};[null] +[x];{};[null] +[x];{x: [1]};[[1]] +[x];{x: {a: 1}};[{a: 1}] +[x, y];{x: 1, y: 'b'};[1, 'b'] +[x, y];{x: 1};[1, null] +[x, y];{};[null, null] +[x, y];{x: true, y: [2]};[true, [2]] +[x, y];{x: 0.10, y: -0};[0.1, 0] +len([x, x, x]);{x: 1};3 +len([x, x, x]);{x: null};3 +len([x, x, x]);{};3 +len([x, x, x]);{x: []};3 +# Object literals with bare keys +{};;{} +{ };;{} +type({});;'object' +{a: 1};;{a: 1} +{a:1};;{a: 1} +{ a : 1 };;{a: 1} +{a: 1, b: 2};;{a: 1, b: 2} +{a: 1, b: 'x', c: true, d: null, e: [], f: {}};;{a: 1, b: 'x', c: true, d: null, e: [], f: {}} +{a: 1 + 1};;{a: 2} +{a: [1, 2]};;{a: [1, 2]} +{_a: 1, $b: 2, c1: 3, d_e: 4};;{_a: 1, $b: 2, c1: 3, d_e: 4} +{camelCase: 1, snake_case: 2, PascalCase: 3};;{camelCase: 1, snake_case: 2, PascalCase: 3} +{$: 1};;{'$': 1} +{$root: 1};;{'$root': 1} +{_: 1};;{'_': 1} +# Quoted keys +{'a': 1};;{a: 1} +"{""a"": 1}";;{a: 1} +{'a b': 1};;{'a b': 1} +keys({'': 1});;[''] +{'a.b': 1};;{'a.b': 1} +{'1': 1};;{'1': 1} +{'é': 1};;{'é': 1} +{'😀': 'x'};;{'😀': 'x'} +{'a-b': 1, 'c:d': 2};;{'a-b': 1, 'c:d': 2} +{`a`: 1};;!error;question: template keys are rejected even without interpolation +# Keys that are literals of other kinds +{1: 2};;{'1': 2} +{0: 'a', 1: 'b'};;{'0': 'a', '1': 'b'} +{1.5: 1};;{'1.5': 1} +{1.50: 1};;{'1.50': 1} +{1e3: 1};;{'1e3': 1} +{1_000: 1};;{'1_000': 1};question: numeric keys keep their source text, separators included +{-1: 1};;!error +{true: 1};;{'true': 1} +{false: 1};;{'false': 1} +{null: 1};;{'null': 1} +{true: 1, false: 2, null: 3};;{'true': 1, 'false': 2, 'null': 3} +# Keywords that are operators cannot be bare keys +{and: 1};;!error;question: operator keywords are not allowed as bare keys while true/false/null are +{or: 1};;!error;question: operator keywords are not allowed as bare keys while true/false/null are +{in: 1};;!error;question: operator keywords are not allowed as bare keys while true/false/null are +{not: 1};;!error;question: operator keywords are not allowed as bare keys while true/false/null are +{'and': 1, 'or': 2, 'in': 3, 'not': 4};;{and: 1, or: 2, in: 3, not: 4} +# Computed keys +{['a']: 1};;{a: 1} +{['a' + 'b']: 1};;{ab: 1} +{[`k${1}`]: 1};;{k1: 1} +{[1 + 1]: 3};;{'2': 3} +{[1.50]: 1};;{'1.50': 1} +{[true]: 1};;{'true': 1} +{[null]: 1};;{'null': 1};question: a null computed key becomes the string 'null' +{[[1]]: 1};;!error +{[{}]: 1};;!error +{['a']: 1, ['b']: 2};;{a: 1, b: 2} +{[]: 1};;!error +{[1: 1};;!error +{[k]: 1};{k: 'z'};{z: 1} +keys({[k]: 1});{k: ''};[''] +{[k]: 1};{k: 5};{'5': 1} +{[k]: 1};{k: 0.50};{'0.50': 1} +{[k]: 1};{k: true};{'true': 1} +{[k]: 1};{k: null};{'null': 1};question: a null computed key becomes the string 'null' +{[k]: 1};{};{'null': 1};question: a missing computed key becomes the string 'null' +{[k]: 1};{k: [1]};!error +{[k]: 1};{k: {a: 1}};!error +{[k + 'x']: v};{k: 'a', v: 1};{ax: 1} +{[k + 'x']: v};{k: 'a'};{ax: null} +{[k + 'x']: v};{k: '', v: [1]};{x: [1]} +{[k + 'x']: v};{k: 1, v: 2};!error +{[k + 'x']: v};{};!error +# Nested objects +{a: {}};;{a: {}} +{a: {b: {c: {}}}};;{a: {b: {c: {}}}} +{a: {b: 1}, c: {d: [1, {e: 2}]}};;{a: {b: 1}, c: {d: [1, {e: 2}]}} +{a: [{b: [{c: 1}]}]};;{a: [{b: [{c: 1}]}]} +[{a: 1}, {a: 2}];;[{a: 1}, {a: 2}] +# Duplicate keys +{a: 1, a: 2};;{a: 1};question: duplicate keys keep the first value (JS/JSON5 keep the last) +{a: 1, b: 2, a: 3};;{a: 1, b: 2};question: duplicate keys keep the first value (JS/JSON5 keep the last) +{a: 1, 'a': 2};;{a: 1};question: duplicate keys keep the first value (JS/JSON5 keep the last) +{['a']: 1, a: 2};;{a: 1};question: duplicate keys keep the first value (JS/JSON5 keep the last) +{1: 'x', '1': 'y'};;{'1': 'x'};question: duplicate keys keep the first value (JS/JSON5 keep the last) +{[k]: 1, a: 2};{k: 'a'};{a: 1};question: duplicate keys keep the first value (JS/JSON5 keep the last) +{[k]: 1, a: 2};{k: 'b'};{a: 2, b: 1} +{[k]: 1, a: 2};{};{a: 2, 'null': 1} +# Trailing comma, shorthand and malformed objects +{a: 1,};;{a: 1};bug: objects reject a trailing comma while arrays accept it +{a: 1, b: 2,};;{a: 1, b: 2};bug: objects reject a trailing comma while arrays accept it +{,};;!error +{a: 1,, b: 2};;!error +{a};{a: 1};!error +{a, b};{a: 1, b: 2};!error +{a: 1 b: 2};;!error +{a 1};;!error +{:1};;!error +{a:};;!error +{a: 1;;!error +{a: 1}};;!error +{;;!error +};;!error +{a.b: 1};;!error +"{a: 1; b: 2}";;!error +# Member access on object literals +({a: 1}).a;;1 +({a: 1})['a'];;1 +({a: {b: 2}}).a.b;;2 +({a: 1}).b;;null +{a: 1}.a;;1;bug: postfix access works on a parenthesized object literal but not a bare one +{a: 1}['a'];;1;bug: postfix access works on a parenthesized object literal but not a bare one +{'a.b': 1}['a.b'];;1;bug: postfix access works on a parenthesized object literal but not a bare one +# Objects built from the input +{a: x};{x: 2};{a: 2} +{a: x};{x: null};{a: null} +{a: x};{};{a: null} +{a: x};{x: [1, {b: 2}]};{a: [1, {b: 2}]} +{a: x};{x: 'é'};{a: 'é'} +{a: x.y, b: x.z};{x: {y: 1, z: 2}};{a: 1, b: 2} +{a: x.y, b: x.z};{x: {y: 1}};{a: 1, b: null} +{a: x.y, b: x.z};{x: null};{a: null, b: null} +{a: x.y, b: x.z};{};{a: null, b: null} +{a: x.y, b: x.z};{x: 5};{a: null, b: null} +# Interval literals +[1..5];;'[1..5]' +(1..5);;'(1..5)' +[1..5);;'[1..5)' +(1..5];;'(1..5]' +]1..5[;;']1..5[' +]1..5];;']1..5]' +[1..5[;;'[1..5[' +type([1..5]);;'interval' +type((1..5));;'interval' +type(]1..5[);;'interval' +[1 .. 5];;'[1..5]' +[ 1..5 ];;'[1..5]' +[-5..-1];;'[-5..-1]' +[1.5..2.5];;'[1.5..2.5]' +[1e1..1e2];;'[10..100]' +[1_000..2_000];;'[1000..2000]' +[1 + 1..2 * 3];;'[2..6]' +[5..1];;'[5..1]' +[1..1];;'[1..1]' +[(1)..(5)];;'[1..5]' +[d('2024-01-01')..d('2024-02-01')];;'[2024-01-01T00:00:00Z..2024-02-01T00:00:00Z]' +[(1..2)];;['(1..2)'] +[[1..2]];;['[1..2]'] +{r: [1..2]};;{r: '[1..2]'} +[1..5] == [1..5];;false;question: two identical interval literals compare unequal +# Intervals in their main use: membership +3 in [1..5];;true +1 in (1..5);;false +5 in [1..5];;true +# Reversed brackets denote the complement of the interval +0 in ]1..5[;;true;question: reversed brackets mean the complement (outside) of the interval +1 in ]1..5[;;true;question: reversed brackets mean the complement (outside) of the interval +3 in ]1..5[;;false;question: reversed brackets mean the complement (outside) of the interval +5 in ]1..5[;;true;question: reversed brackets mean the complement (outside) of the interval +6 in ]1..5[;;true;question: reversed brackets mean the complement (outside) of the interval +1 in )1..5(;;false;question: reversed parentheses mean the complement (outside) of the interval +0 in )1..5(;;true;question: reversed parentheses mean the complement (outside) of the interval +3 in [1..5[;;false;question: a mixed [a..b[ interval means v >= a and v >= b +5 in [1..5[;;true;question: a mixed [a..b[ interval means v >= a and v >= b +# Malformed intervals +[1..];;!error +[..5];;!error +[..];;!error +(1..);;!error +[1...5];;!error +[1..5, 6];;!error +[1..2..3];;!error +{1..2};;!error;bug: curly brackets are accepted as interval brackets and display as {1..2}} +['a'..'z'];;!error +[null..1];;!error +[true..false];;!error +[[1]..[2]];;!error +[1..5] + 1;;!error +# Intervals built from the input +[x..y];{x: 1, y: 3};'[1..3]' +[x..y];{x: -1.5, y: 0};'[-1.5..0]' +[x..y];{x: null, y: 2};!error +[x..y];{x: 1};!error +[x..y];{};!error +[x..y];{x: 'a', y: 'b'};!error +[x..y];{x: [1], y: [2]};!error +v in [x..y];{v: 2, x: 1, y: 3};true +v in [x..y];{v: 3, x: 1, y: 3};true +v in [x..y];{v: 4, x: 1, y: 3};false +v in [x..y];{v: null, x: 1, y: 3};!error +v in [x..y];{v: 2, x: null, y: 3};!error +v in [x..y];{};!error diff --git a/core/expression/tests/spec/standard/01-numbers.csv b/core/expression/tests/spec/standard/01-numbers.csv new file mode 100644 index 00000000..d3b9d260 --- /dev/null +++ b/core/expression/tests/spec/standard/01-numbers.csv @@ -0,0 +1,218 @@ +expression (string);input (json 5);output (json 5);note +# Integers +0;;0 +1;;1 +42;;42 +123456789;;123456789 +-1;;-1 +-42;;-42 ++1;;1 ++1.5;;1.5 +-+1;;-1 +- 5;;-5 +--5;;5 +-(-5);;5 +type(0);;'number' +type(-1);;'number' +type(1.5);;'number' +type(1e3);;'number' +# Leading zeros are decimal, not octal +007;;7 +00;;0 +0010;;10 +string(007);;'7' +string(00);;'0' +01.50;;1.5 +string(01.50);;'1.50' +# Decimals and preserved scale +0.5;;0.5 +3.14;;3.14 +-3.14;;-3.14 +0.1;;0.1 +1.0;;1 +1.50;;1.5 +string(1.0);;'1.0' +string(1.50);;'1.50' +string(1.500);;'1.500' +string(0.0);;'0.0' +string(0.000);;'0.000' +string(100);;'100' +string(100.00);;'100.00' +string(-2.50);;'-2.50' +0.1 + 0.2 == 0.3;;true +1.0 == 1;;true +1.50 == 1.5;;true +0.0 == 0;;true +# A dot must be followed or preceded by digits +.5;;!error +-.5;;!error +1.;;1;question: a trailing dot is accepted as `1` +string(1.);;'1';question: a trailing dot is accepted and drops the dot +1.2.3;;!error +1..2;;!error +1. 5;;!error +# Negative zero +-0;;0 +-0 == 0;;true +-0.0 == 0;;true +string(-0);;'-0';question: unary minus on a zero literal keeps a negative sign in the string form +string(-0.0);;'-0.0';question: unary minus on a zero literal keeps a negative sign in the string form +string(0 * -1);;'0' +# Underscore digit separators +1_000;;1000 +1_000_000;;1000000 +string(1_000);;'1000' +1_000.5;;1000.5 +1_000.000_1;;1000.0001 +string(1_000.50);;'1000.50' +-1_000;;-1000 +1_0;;10 +1__0;;10;question: consecutive separators are accepted +1_;;1;question: a trailing separator is accepted +1_.5;;1.5;question: a separator before the dot is accepted +1._5;;1.5;question: a separator right after the dot is accepted +_1;{};null +_1;{_1: 7};7 +_1_000;{_1_000: 3};3 +1e1_0;;!error +1_0e1_0;;!error +1_0e2;;1000 +# Scientific notation +1e3;;1000 +1e0;;1 +1e1;;10 +1e+2;;100 +1e-0;;1 +1e+0;;1 +1e-1;;0.1 +1e-3;;0.001 +2.5e2;;250 +2.5e-3;;0.0025 +1.5e1;;15 +-1e2;;-100 +-1e-2;;-0.01 +0e5;;0 +0e-5;;0 +0.0e0;;0 +1e0005;;100000 +1e-0005;;0.00001 +1.e3;;1000;question: a trailing dot before the exponent is accepted +12.345e1;;123.45 +12.345e-1;;1.2345 +123e-2;;1.23 +string(1e3);;'1000' +string(1.5e1);;'15' +string(1e-3);;'0.001' +string(2.50e1);;'25.0' +string(1.0e0);;'1.0' +1e3 == 1000;;true +1e-3 == 0.001;;true +1e3 + 1;;1001 +2 * 1e2;;200 +[1e2, 2e-1];;[100, 0.2] +{a: 1e2};;{a: 100} +1E3;;!error;question: uppercase E exponent is rejected by the lexer +1E-3;;!error;question: uppercase E exponent is rejected by the lexer +1e;;!error +1e+;;!error +1e-;;!error +1e2e3;;!error +1e2.5;;!error +e3;{};null +e3;{e3: 4};4 +1 e3;;!error +1e 3;;!error +# Exponent extremes +1e27;;1000000000000000000000000000 +1e28;;10000000000000000000000000000 +-1e28;;-10000000000000000000000000000 +1e29;;!error +1e100;;!error +1e1000;;!error +1e-27;;0.000000000000000000000000001 +1e-28;;0.0000000000000000000000000001 +-1e-28;;-0.0000000000000000000000000001 +1e-29;;!error;question: a literal below the smallest Decimal step errors instead of rounding to 0 +1e-100;;!error;question: a literal below the smallest Decimal step errors instead of rounding to 0 +1.5e-28;;!error;question: a literal needing scale 29 errors instead of rounding +7.9228162514264337593543950335e28;;79228162514264337593543950335 +7.9228162514264337593543950336e28;;!error +# Decimal range (96-bit mantissa, max 79228162514264337593543950335) +79228162514264337593543950335;;79228162514264337593543950335 +-79228162514264337593543950335;;-79228162514264337593543950335 +79228162514264337593543950334 + 1;;79228162514264337593543950335 +string(79228162514264337593543950335);;'79228162514264337593543950335' +79228162514264337593543950336;;!error +-79228162514264337593543950336;;!error +100000000000000000000000000000;;!error +999999999999999999999999999999;;!error +1_000_000_000_000_000_000_000_000_000;;1000000000000000000000000000 +# Significant digits and scale limits (scale at most 28) +0.0000000000000000000000000001;;0.0000000000000000000000000001 +0.00000000000000000000000000001;;!error;question: a literal with scale 29 errors instead of rounding +0.1234567890123456789012345678;;0.1234567890123456789012345678 +string(0.1234567890123456789012345678);;'0.1234567890123456789012345678' +0.12345678901234567890123456789;;!error;question: 29 fractional digits error instead of rounding to 28 +1.0000000000000000000000000001;;1.0000000000000000000000000001 +string(1.0000000000000000000000000001);;'1.0000000000000000000000000001' +1.00000000000000000000000000001;;!error;question: 30 significant digits error instead of rounding +123456789012345678901234567.8;;123456789012345678901234567.8 +1234567890123456789012345678.9;;1234567890123456789012345678.9 +12345678901234567890123456789.1;;!error;question: an in-range integer part with a fraction beyond precision errors instead of rounding +7922816251426433759354395033.5;;7922816251426433759354395033.5 +3.1415926535897932384626433832;;3.1415926535897932384626433832 +string(3.1415926535897932384626433832);;'3.1415926535897932384626433832' +0.1000000000000000000000000000;;0.1 +string(0.1000000000000000000000000000);;'0.1000000000000000000000000000' +# i64 boundaries are ordinary decimals +9223372036854775807;;9223372036854775807 +9223372036854775808;;9223372036854775808 +-9223372036854775808;;-9223372036854775808 +-9223372036854775809;;-9223372036854775809 +18446744073709551615;;18446744073709551615 +18446744073709551616;;18446744073709551616 +9223372036854775807 + 1;;9223372036854775808 +string(9223372036854775808);;'9223372036854775808' +9007199254740993;;9007199254740993 +string(9007199254740993);;'9007199254740993' +# i128 boundaries exceed the Decimal range +170141183460469231731687303715884105727;;!error +-170141183460469231731687303715884105728;;!error +# Non-decimal bases and special names are not number syntax +0x10;;!error +0b1;;!error +0o7;;!error +1a;;!error +Infinity;{};null +NaN;{};null +Infinity;{Infinity: 1};1 +# Numbers read from the input +x;{x: 0};0 +x;{x: -0.5};-0.5 +x;{x: 1.50};1.5 +x;{x: 79228162514264337593543950335};79228162514264337593543950335 +x;{x: 0.0000000000000000000000000001};0.0000000000000000000000000001 +x;{x: null};null +x;{};null +string(x);{x: 1.50};'1.50' +string(x);{x: 100};'100' +string(x);{x: -0.001};'-0.001' +string(x);{x: 0.0000000000000000000000000001};'0.0000000000000000000000000001' +string(x);{x: 12345678901234567890};'12345678901234567890' +x + 1_000;{x: 1};1001 +x + 1_000;{x: 0.5};1000.5 +x + 1_000;{x: -1000};0 +x + 1_000;{x: null};!error +x + 1_000;{};!error +x + 1_000;{x: 'a'};!error +x * 1e2;{x: 1.5};150 +x * 1e2;{x: 0};0 +x * 1e2;{x: -0.01};-1 +x * 1e2;{x: null};!error +x * 1e2;{x: true};!error +x == 1e3;{x: 1000};true +x == 1e3;{x: 1000.0};true +x == 1e3;{x: 999};false +x == 1e3;{x: '1000'};false +x == 1e3;{x: null};false +x == 1e3;{};false diff --git a/core/expression/tests/spec/standard/01-strings.csv b/core/expression/tests/spec/standard/01-strings.csv new file mode 100644 index 00000000..2ce6a7a4 --- /dev/null +++ b/core/expression/tests/spec/standard/01-strings.csv @@ -0,0 +1,177 @@ +expression (string);input (json 5);output (json 5);note +# Single and double quotes +'hello';;'hello' +"""hello""";;'hello' +'hello world';;'hello world' +"""hello world""";;'hello world' +'';;'' +"""""";;'' +' ';;' ' +' ';;' ' +"'a' == ""a""";;true +type('');;'string' +type('a');;'string' +len('');;0 +len(' ');;1 +# The other quote kind is plain text inside a string +"'""'";;"'""'" +"'a""b'";;'a"b' +"""'""";;'\'' +"""it's""";;'it\'s' +"""a'b'c""";;'a\'b\'c' +# Numeric-looking and keyword-looking strings stay strings +'1';;'1' +'1' == 1;;false +type('1');;'string' +'1e3';;'1e3' +'-0';;'-0' +'0x10';;'0x10' +'true';;'true' +'true' == true;;false +'null';;'null' +'null' == null;;false +'and';;'and' +'not in';;'not in' +# Operator and punctuation characters inside strings +'a + b';;'a + b' +'a, b';;'a, b' +'[1..5]';;'[1..5]' +'{a: 1}';;'{a: 1}' +'a.b';;'a.b' +'?? ?:';;'?? ?:' +'#';;'#' +'$';;'$' +'${x}';;'${x}' +"'a;b'";;"'a;b'" +'`';;'`' +'a`b`c';;'a`b`c' +'//';;'//' +'/* */';;'/* */' +'%^&*=!<>';;'%^&*=!<>' +'@~|';;'@~|' +# No escape sequences: a backslash is an ordinary character +'a\nb';;'a\\nb';question: string literals have no escape sequences so \n stays two characters +len('a\nb');;4;question: string literals have no escape sequences so \n stays two characters +'\t';;'\\t';question: string literals have no escape sequences +'\u0041';;'\\u0041';question: string literals have no escape sequences +'\\';;'\\\\';question: string literals have no escape sequences so \\ stays two backslashes +'\';;'\\';question: a trailing backslash does not escape the closing quote +"'\'";;'\\' +'a\'b';;!error;question: \' does not escape the quote so the literal is unterminated +"""a\""b""";;!error;question: \"" does not escape the quote +'a''b';;!error;question: doubling the quote is not an escape either, so a quote cannot appear in a same-quoted string +'''';;!error +# Unicode +'é';;'é' +'ü';;'ü' +'日本語';;'日本語' +'Привет';;'Привет' +'مرحبا';;'مرحبا' +'😀';;'😀' +'👨‍👩‍👧';;'👨‍👩‍👧' +'a😀b';;'a😀b' +'é' == 'é';;true +'😀' + '😀';;'😀😀' +len('é');;1;bug: len counts UTF-8 bytes instead of characters +len('日本語');;3;bug: len counts UTF-8 bytes instead of characters +len('😀');;1;bug: len counts UTF-8 bytes instead of characters +['é', '😀'];;['é', '😀'] +# Multi-line strings keep the newline +"'a +b'";;'a\nb' +"""a +b""";;'a\nb' +"len('a +b')";;3 +"' +'";;'\n' +# Tabs inside strings are kept +'a b';;'a\tb' +# Unterminated strings +';;!error +'abc;;!error +"""abc";;!error +'abc"";;!error +"""abc'";;!error +'a' + 'b;;!error +['a];;!error +{a: 'b};;!error +# Adjacent strings do not concatenate +'a' 'b';;!error +'a''';;!error +'a' + 'b';;'ab' +# Strings from the input +s;{s: 'x'};'x' +s;{s: ''};'' +s;{s: 'é😀'};'é😀' +s;{s: 'a\nb'};'a\nb' +s;{s: null};null +s;{};null +s == 'x';{s: 'x'};true +s == 'x';{s: 'X'};false +s == 'x';{s: ''};false +s == 'x';{s: null};false +s == 'x';{s: 1};false +s == 'x';{};false +s == 'é😀';{s: 'é😀'};true +s == 'é😀';{s: 'e😀'};false +s == 'é😀';{s: null};false +s == 'é😀';{};false +s == 'a\nb';{s: 'a\\nb'};true;question: string literals have no escape sequences +s == 'a\nb';{s: 'a\nb'};false;question: string literals have no escape sequences +s == 'a\nb';{s: null};false +# Booleans +true;;true +false;;false +type(true);;'bool' +type(false);;'bool' +true == true;;true +true == false;;false +not true;;false +not false;;true +!true;;false +!false;;true +[true, false];;[true, false] +{t: true, f: false};;{t: true, f: false} +# Keywords are lower-case only; other spellings are identifiers +TRUE;{};null +True;{};null +FALSE;{};null +True;{True: 1};1 +trueish;{trueish: 2};2 +falsey;{falsey: 3};3 +true1;{true1: 4};4 +# Null +null;;null +type(null);;'null' +null == null;;true +null != null;;false +null == false;;false +null == 0;;false +null == '';;false +[null];;[null] +[null, null];;[null, null] +{a: null};;{a: null} +Null;{};null +NULL;{Null: 1, NULL: 2};2 +nulls;{nulls: 5};5 +nullable;{nullable: 6};6 +null_;{null_: 7};7 +# Literal values compared to input values +b;{b: true};true +b;{b: false};false +b;{b: null};null +b;{};null +b == true;{b: true};true +b == true;{b: false};false +b == true;{b: 'true'};false +b == true;{b: 1};false +b == true;{b: null};false +b == true;{};false +n == null;{n: null};true +n == null;{};true +n == null;{n: 0};false +n == null;{n: ''};false +n == null;{n: false};false +n == null;{n: []};false +n == null;{n: 'null'};false diff --git a/core/expression/tests/spec/standard/01-syntax.csv b/core/expression/tests/spec/standard/01-syntax.csv new file mode 100644 index 00000000..66ca37e6 --- /dev/null +++ b/core/expression/tests/spec/standard/01-syntax.csv @@ -0,0 +1,177 @@ +expression (string);input (json 5);output (json 5);note +# Identifiers: ASCII letters, digits, _ and $ +x;{x: 1};1 +_;{_: 2};2 +_a;{_a: 3};3 +a_b_1;{a_b_1: 4};4 +a1;{a1: 5};5 +abc123def;{abc123def: 6};6 +$$;{$$: 7};7 +a$b;{a$b: 8};8 +camelCase;{camelCase: 9};9 +UPPER;{UPPER: 10};10 +x;{X: 1};null +X;{x: 1};null +# Keyword prefixes are ordinary identifiers +android;{android: 1};1 +order;{order: 2};2 +index;{index: 3};3 +notx;{notx: 4};4 +nothing;{nothing: 5};5 +truex;{truex: 6};6 +inx;{inx: 7};7 +# Identifiers must not start with a digit or use non-ASCII letters +1a;{};!error +1_a;{};!error +é;{};!error;question: identifiers are ASCII-only +café;{};!error;question: identifiers are ASCII-only +日本;{};!error;question: identifiers are ASCII-only +# Unknown characters are lexer errors +@;;!error +a @ b;{a: 1, b: 2};!error +~1;;!error +1 & 2;;!error +1 | 2;;!error +a\b;{};!error +'a' ` ;;!error +# Missing and present identifiers +x;;null +x;{};null +x;{x: null};null +x;{x: 0};0 +x;{x: ''};'' +x;{x: false};false +x;{x: []};[] +x;{x: {}};{} +x;{x: [1, [2]]};[1, [2]] +x;{x: {a: {b: 1}}};{a: {b: 1}} +x.y;{x: {y: 2}};2 +x.y;{x: {}};null +x.y;{x: null};null +x.y;{};null +x.y;{x: 'str'};null +x.y;{x: 1};null +x['y'];{x: {y: 2}};2 +x['y'];{x: {}};null +x['y'];{x: null};null +x['y'];{};null +"x[""y""]";{x: {y: 2}};2 +x['a b'];{x: {'a b': 3}};3 +x['é'];{x: {'é': 4}};4 +x['😀'];{x: {'😀': 5}};5 +x.😀;{x: {'😀': 5}};!error +x.1;{x: {'1': 6}};!error +x[1];{x: [5, 6]};6 +x.and;{x: {and: 1}};1 +x.in;{x: {in: 2}};2 +x.true;{x: {true: 1}};1;bug: true/false cannot follow a dot although and/in/null can +x.null;{x: {null: 1}};1 +x['and'];{x: {and: 1}};1 +# Whitespace: spaces, tabs and newlines +1+2;;3 +1 + 2;;3 + 1 + 2 ;;3 +1 + 2;;3 + 1;;1 +"1 ++ +2";;3 +" +1 +";;1 +"[ +1, +2, +]";;[1, 2] +"{ +a: 1, +b: [ +2 +] +}";;{a: 1, b: [2]} +[1, 2];;[1, 2] +{a : 1};;{a: 1} +x . y;{x: {y: 2}};2 +x .y;{x: {y: 2}};2 +x. y;{x: {y: 2}};2 +x [ 'y' ];{x: {y: 2}};2 +"x +.y";{x: {y: 2}};2 +"x +.y";{x: null};null +"x +.y";{};null +"x +.y";{x: {y: [1]}};[1] +# Parentheses +(1);;1 +((1));;1 +((((((1))))));;1 +# nested parentheses around a closure call over an interval: parse time grows about 4x per level (10 levels take ~1 s, 11 take ~4 s) in the shared parser +((((((map([0..3], [])))))));;[[], [], [], []] +((((((((map([0..3], [])))))))));;[[], [], [], []] +((((((((flatMap([0..3], [#])))))))));;[0, 1, 2, 3] +((((((((map([0, 3], [])))))))));;[[], []] +( 1 );;1 +('a');;'a' +(true);;true +(null);;null +([1]);;[1] +({a: 1});;{a: 1} +([1..2]);;'[1..2]' +(`t`);;'t' +type((1));;'number' +(1 + 2) * 3;;9 +1 + (2 * 3);;7 +(x);{x: 1};1 +(x);{x: null};null +(x);{};null +(x);{x: 'a'};'a' +(x).y;{x: {y: 1}};1 +(x).y;{x: null};null +(x).y;{};null +(x).y;{x: 3};null +# Unbalanced and empty parentheses +();;!error +(;;!error +);;!error +(1;;!error +1);;!error +((1);;!error +(1));;!error +(1)(2);;!error +(1 2);;!error +( );;!error +# Dangling and misplaced operators +1 +;;!error +1 -;;!error +1 *;;!error +* 1;;!error +/ 1;;!error +1 * * 2;;!error +1 ==;;!error +== 1;;!error +1 and;;!error +and 1;;!error +1 ? 2;;!error +? 1 : 2;;!error +1 ? : 2;;!error +1 ??;;!error +.;;!error +..;;!error +x.;{x: {}};!error +.x;{x: 1};!error +x..y;{x: {y: 1}};!error +,;;!error +1, 2;;!error +:;;!error +1 = 2;{};!error +# Juxtaposed values +1 2;;!error +'a' 'b';;!error +x y;{x: 1, y: 2};!error +[1] [2];;null +[1, 2] [1];;2 +{} {};;!error +true false;;!error +null null;;!error diff --git a/core/expression/tests/spec/standard/01-templates.csv b/core/expression/tests/spec/standard/01-templates.csv new file mode 100644 index 00000000..3feb603e --- /dev/null +++ b/core/expression/tests/spec/standard/01-templates.csv @@ -0,0 +1,147 @@ +expression (string);input (json 5);output (json 5);note +# Plain template strings +``;;'' +`a`;;'a' +`hello world`;;'hello world' +` `;;' ' +type(`a`);;'string' +`a` == 'a';;true +`it's`;;'it\'s' +"`say ""hi""`";;"'say ""hi""'" +`1 + 1`;;'1 + 1' +`[1..5]`;;'[1..5]' +`é😀`;;'é😀' +`$`;;'$' +`$$`;;'$$' +`{`;;'{' +`}`;;'}' +`{}`;;'{}' +`$ {1}`;;'$ {1}' +`${`;;!error +# Interpolation of literals of every type +`${1}`;;'1' +`${0}`;;'0' +`${-1}`;;'-1' +`${1.50}`;;'1.50' +`${-0.5}`;;'-0.5' +`${1e3}`;;'1000' +`${1_000}`;;'1000' +`${0.1 + 0.2}`;;'0.3' +`${1 / 3}`;;'0.3333333333333333333333333333' +`${79228162514264337593543950335}`;;'79228162514264337593543950335' +`${0.0000000000000000000000000001}`;;'0.0000000000000000000000000001' +`${'x'}`;;'x' +`${''}`;;'' +"`${""x""}`";;'x' +`${'é😀'}`;;'é😀' +`${true}`;;'true' +`${false}`;;'false' +`${null}`;;'null' +`${[]}`;;!error +`${[1, 2]}`;;!error +`${ {} }`;;!error +`${[1..5]}`;;!error +`${d('2024-01-01')}`;;'2024-01-01T00:00:00Z' +`${d('2024-01-01').format('%Y-%m-%d')}`;;'2024-01-01' +`${string(1)}`;;'1' +`${len('abc')}`;;'3' +`${[1, 2][0]}`;;'1' +`${1 > 0}`;;'true' +`${1 == 2}`;;'false' +`${null ?? 'd'}`;;'d' +`${true ? 'y' : 'n'}`;;'y' +# Surrounding text and multiple interpolations +`a${1}`;;'a1' +`${1}a`;;'1a' +`a${1}b`;;'a1b' +`${1}${2}`;;'12' +`${1}${2}${3}`;;'123' +`a${1}b${'x'}c${true}d`;;'a1bxctrued' +`${1} ${2}`;;'1 2' +` ${1} `;;' 1 ' +`$${1}`;;'$1' +`${1}$`;;'1$' +`${1}}`;;'1}' +`{${1}}`;;'{1}' +`é${1}ü`;;'é1ü' +`😀${'😀'}😀`;;'😀😀😀' +# Whitespace inside interpolations +`${ 1 }`;;'1' +`${ 1 }`;;'1' +` ${ 1 + 1 } `;;' 2 ' +"`${ +1 + 1 +}`";;'2' +"`a +${1} +b`";;'a\n1\nb' +# Quotes and braces as string values inside interpolations +`${'`'}`;;'`' +`${'}'}`;;'}' +`${'{'}`;;'{' +`a${'}'}b`;;'a}b' +`${'${'}`;;'${' +`${'${x}'}`;;'${x}' +# Nested braces and nested templates inside interpolations +`${keys({a: 1})[0]}`;;'a';bug: the first } inside an interpolation ends it, so object literals cannot be used +`${values({a: 1})[0]}`;;'1';bug: the first } inside an interpolation ends it, so object literals cannot be used +`${`in`}`;;'in';bug: a template nested in an interpolation fails to parse +`${`in${1}`}`;;'in1';bug: a template nested in an interpolation fails to parse +`${'a' + `b${'c'}`}`;;'abc';bug: a template nested in an interpolation fails to parse +# No escape sequences in templates +`\n`;;'\\n';question: template literals have no escape sequences +`\${1}`;;'\\1';question: there is no way to write a literal ${ in a template +`\``;;!error;question: a backtick cannot be escaped inside a template +# Malformed templates +`abc;;!error;bug: an unterminated template is accepted as if closed +`a${1}b;;!error;bug: an unterminated template is accepted as if closed +`${1`;;!error +`${1;;!error +`${}`;;!error +`${1 +}`;;!error +`${1 2}`;;!error +`a` `b`;;!error +`a` + `b`;;'ab' +`a` + 1;;!error +# Templates in literals +[`a`, `b${1}`];;['a', 'b1'] +{k: `v${1}`};;{k: 'v1'} +{[`k${1}`]: 1};;{k1: 1} +# Interpolating input values of every type +`${x}`;{x: 1};'1' +`${x}`;{x: 1.500};'1.500' +`${x}`;{x: -0.25};'-0.25' +`${x}`;{x: 0};'0' +`${x}`;{x: 'str'};'str' +`${x}`;{x: ''};'' +`${x}`;{x: 'é😀'};'é😀' +`${x}`;{x: true};'true' +`${x}`;{x: false};'false' +`${x}`;{x: null};'null' +`${x}`;{};'null' +`${x}`;{x: [1]};!error +`${x}`;{x: []};!error +`${x}`;{x: {a: 1}};!error +`${x}`;{x: {}};!error +`v=${x}!`;{x: 5};'v=5!' +`v=${x}!`;{x: 'a'};'v=a!' +`v=${x}!`;{x: null};'v=null!' +`v=${x}!`;{};'v=null!' +`v=${x}!`;{x: false};'v=false!' +`v=${x}!`;{x: 12345678901234567890.123};'v=12345678901234567890.123!' +`${a}-${b}`;{a: 1, b: 2};'1-2' +`${a}-${b}`;{a: 'x', b: null};'x-null' +`${a}-${b}`;{a: true};'true-null' +`${a}-${b}`;{};'null-null' +`${a}-${b}`;{a: 0.10, b: -0};'0.10-0' +`${u.name} is ${u.age}`;{u: {name: 'Ann', age: 30}};'Ann is 30' +`${u.name} is ${u.age}`;{u: {name: 'Bo'}};'Bo is null' +`${u.name} is ${u.age}`;{u: null};'null is null' +`${u.name} is ${u.age}`;{};'null is null' +`${u.name} is ${u.age}`;{u: {name: 1.0, age: '30'}};'1.0 is 30' +`${x + 1}`;{x: 1};'2' +`${x + 1}`;{x: 0.5};'1.5' +`${x + 1}`;{x: -1};'0' +`${x + 1}`;{x: null};!error +`${x + 1}`;{};!error +`${x + 1}`;{x: 'a'};!error diff --git a/core/expression/tests/spec/standard/02-inputs.csv b/core/expression/tests/spec/standard/02-inputs.csv new file mode 100644 index 00000000..f69a324b --- /dev/null +++ b/core/expression/tests/spec/standard/02-inputs.csv @@ -0,0 +1,204 @@ +expression (string);input (json 5);output (json 5);note +# Addition over input values +a + b;{a: 1, b: 2};3 +a + b;{a: -1, b: 1};0 +a + b;{a: 0.1, b: 0.2};0.3 +a + b;{a: 0.1000000000000000000000000001, b: 1};1.1000000000000000000000000001 +a + b;{a: 79228162514264337593543950335, b: 0};79228162514264337593543950335 +a + b;{a: 79228162514264337593543950335, b: 1};!error +a + b;{a: -79228162514264337593543950335, b: -1};!error +a + b;{a: 9223372036854775807, b: 1};9223372036854775808 +a + b;{a: 1.5, b: null};!error +a + b;{a: 1.5};!error +# Subtraction over input values +a - b;{a: 3, b: 5};-2 +a - b;{a: 0.3, b: 0.1};0.2 +a - b;{a: -0.5, b: -0.5};0 +a - b;{a: 1.0000000000000000000000000001, b: 1};0.0000000000000000000000000001 +a - b;{a: -79228162514264337593543950335, b: 1};!error +a - b;{a: 10, b: true};!error +a - b;{a: 10, b: '3'};!error +# Multiplication over input values +a * b;{a: 6, b: 7};42 +a * b;{a: 0.1, b: 0.1};0.01 +a * b;{a: -2.5, b: 4};-10 +a * b;{a: 0, b: -5};0 +a * b;{a: 4294967296, b: 4294967296};18446744073709551616 +a * b;{a: 79228162514264337593543950335, b: 2};!error +a * b;{a: 1e-28, b: 1e-28};0 +a * b;{a: null, b: 0};!error +# Division over input values +a / b;{a: 1, b: 3};0.3333333333333333333333333333 +a / b;{a: 10, b: 4};2.5 +a / b;{a: 1, b: 0};null +a / b;{a: 0, b: 0};null +a / b;{a: -1, b: 0.0};null +a / b;{a: 7, b: -2};-3.5 +a / b;{a: 0.3, b: 0.1};3 +a / b;{a: 79228162514264337593543950335, b: 0.5};!error;bug: division overflow returns null instead of an error +a / b;{a: 1, b: null};!error +a / b;{a: 1};!error +a / b;{a: 1, b: 'x'};!error +# Division by zero from input alongside non-zero divisors +(a / b) ?? -1;{a: 1, b: 2};0.5 +(a / b) ?? -1;{a: 1, b: 0};-1 +(a / b) ?? -1;{a: 5, b: 5};1 +(a / b) ?? -1;{a: 0, b: 0};-1 +a / b ?? -1;{a: 1, b: 0};null +a / b ?? -1;{a: 1, b: null};-1 +a / b ?? -1;{a: 1, b: 4};0.25 +# Modulo over input values +a % b;{a: 7, b: 3};1 +a % b;{a: -7, b: 3};-1 +a % b;{a: 7, b: -3};1 +a % b;{a: -7, b: -3};-1 +a % b;{a: 5.5, b: 2};1.5 +a % b;{a: 7, b: 0};null +a % b;{a: 0, b: 0};null +a % b;{a: 7, b: null};!error +a % b;{a: '7', b: 3};!error +a % b;{b: 3};!error +# Power over input values +a ^ b;{a: 2, b: 10};1024 +a ^ b;{a: 2, b: -1};0.5 +a ^ b;{a: 0, b: 0};1 +a ^ b;{a: -2, b: 3};-8 +a ^ b;{a: 1.5, b: 2};2.25 +a ^ b;{a: 10, b: 28};10000000000000000000000000000 +a ^ b;{a: 10, b: 29};!error +a ^ b;{a: 2, b: null};!error +a ^ b;{a: true, b: 2};!error +a ^ b;{a: 2};!error +# Unary minus over input values +-a;{a: 5};-5 +-a;{a: -5};5 +-a;{a: 0};0 +-a;{a: 1.5};-1.5 +-a;{a: 79228162514264337593543950335};-79228162514264337593543950335 +-a;{a: -79228162514264337593543950335};79228162514264337593543950335 +-a;{a: null};!error +-a;{};!error +-a;{a: '5'};!error +-a;{a: true};!error +-a;{a: [5]};!error +# Unary plus over input values ++a;{a: 5};5 ++a;{a: -1.5};-1.5 ++a;{a: 0};0 ++a;{a: null};null;question: unary plus passes non-numbers through unchanged, unlike unary minus ++a;{a: 'x'};'x';question: unary plus passes strings through unchanged ++a;{};null;question: unary plus on a missing key yields null instead of failing like unary minus +# Unary minus combined with binary operators +-a * b;{a: 2, b: 3};-6 +-a * b;{a: -2, b: 3};6 +-a * b;{a: 0.5, b: -4};2 +-a * b;{a: null, b: 3};!error +-a * b;{a: 2};!error +-a ^ 2;{a: 3};9;question: unary minus binds tighter than ^, (-a) ^ 2 +-a ^ 2;{a: -3};9 +-a ^ 2;{a: 0.5};0.25 +-a ^ 2;{a: null};!error +a - -b;{a: 1, b: 2};3 +a - -b;{a: 1, b: -2};-1 +a - -b;{a: 1.5, b: 0.5};2 +a - -b;{a: 1, b: null};!error +# Precedence over input values +a + b * c;{a: 1, b: 2, c: 3};7 +a + b * c;{a: 0.1, b: 0.2, c: 10};2.1 +a + b * c;{a: -1, b: -2, c: -3};5 +a + b * c;{a: 1, b: 2, c: null};!error +a + b * c;{a: null, b: 2, c: 3};!error +a + b * c;{a: 1, b: 2};!error +a - b - c;{a: 10, b: 2, c: 3};5 +a - b - c;{a: 0, b: 0, c: 0};0 +a - b - c;{a: 1.5, b: -1.5, c: 3};0 +a - b - c;{a: 10, b: 'x', c: 3};!error +a / b / c;{a: 100, b: 10, c: 5};2 +a / b / c;{a: 100, b: 0, c: 5};!error;question: 100 / 0 is null, then null / 5 fails; null does not propagate through arithmetic +a / b / c;{a: 1, b: 3, c: 3};0.1111111111111111111111111111 +a / b / c;{a: 1, b: 1, c: 0};null +a * b % c;{a: 2, b: 3, c: 4};2 +a * b % c;{a: 2.5, b: 3, c: 4};3.5 +a * b % c;{a: -2, b: 3, c: 4};-2 +a * b % c;{a: 2, b: 3, c: 0};null +a ^ b ^ c;{a: 2, b: 3, c: 2};512 +a ^ b ^ c;{a: 2, b: 2, c: 3};256 +a ^ b ^ c;{a: 10, b: 1, c: 0};10 +a ^ b ^ c;{a: 2, b: 3, c: null};!error +(a + b) * c;{a: 1, b: 2, c: 3};9 +(a + b) * c;{a: 0.1, b: 0.2, c: 3};0.9 +(a + b) * c;{a: 'x', b: 'y', c: 3};!error +(a + b) * c;{a: 1, b: 2, c: 0};0 +# Decimal exactness with input values +a * 3 == b;{a: 0.1, b: 0.3};true +a * 3 == b;{a: 1.1, b: 3.3};true +a * 3 == b;{a: 0.3333333333333333333333333333, b: 1};false +a * 3 == b;{a: 2, b: 6};true +a + b == c;{a: 0.1, b: 0.2, c: 0.3};true +a + b == c;{a: 0.7, b: 0.1, c: 0.8};true +a + b == c;{a: 1e-28, b: 1e-28, c: 2e-28};true +a + b == c;{a: 1, b: 2, c: 4};false +a / b * b;{a: 1, b: 3};0.9999999999999999999999999999 +a / b * b;{a: 2, b: 3};2.0000000000000000000000000001 +a / b * b;{a: 6, b: 3};6 +a / b * b;{a: 1, b: 7};1.0000000000000000000000000003 +# Scale of input values observed via string() +string(a + b);{a: 1.10, b: 1};'2.10' +string(a + b);{a: 1.5, b: 1.5};'3.0' +string(a + b);{a: 1, b: 2};'3' +string(a + b);{a: 0.1, b: 0.2};'0.3' +string(a * b);{a: 2.50, b: 2};'5.00' +string(a * b);{a: 1.5, b: 1.5};'2.25' +string(a * b);{a: 0.10, b: 10};'1.00' +string(a - b);{a: 2.50, b: 0.50};'2.00' +string(a - b);{a: 1, b: 1};'0' +string(a - b);{a: 0.1, b: 0.1};'0.0' +# Input values near the decimal range +a + 1;{a: 79228162514264337593543950334};79228162514264337593543950335 +a + 1;{a: 79228162514264337593543950335};!error +a + 1;{a: -79228162514264337593543950335};-79228162514264337593543950334 +a + 1;{a: 0.0000000000000000000000000001};1.0000000000000000000000000001 +a + 1;{a: -1};0 +a + 1;{a: null};!error +a * 2;{a: 39614081257132168796771975167};79228162514264337593543950334 +a * 2;{a: 39614081257132168796771975168};!error +a * 2;{a: 0.5};1 +a * 2;{a: -39614081257132168796771975167};-79228162514264337593543950334 +a * 2;{a: 'a'};!error +# Mixed literal and input operands +a * 1.1;{a: 100};110 +a * 1.1;{a: 0};0 +a * 1.1;{a: -10};-11 +a * 1.1;{a: 0.1};0.11 +a * 1.1;{a: null};!error +100 - a;{a: 99.99};0.01 +100 - a;{a: -0.01};100.01 +100 - a;{a: 100};0 +100 - a;{a: 100.0000000000000000000000001};-0.0000000000000000000000001 +100 - a;{a: false};!error +1 / a;{a: 3};0.3333333333333333333333333333 +1 / a;{a: 0};null +1 / a;{a: 0.0000000000000000000000000001};10000000000000000000000000000 +1 / a;{a: -8};-0.125 +1 / a;{a: '1'};!error +2 ^ a;{a: 10};1024 +2 ^ a;{a: -2};0.25 +2 ^ a;{a: 0};1 +2 ^ a;{a: 96};!error +2 ^ a;{a: []};!error +a % 2;{a: 7};1 +a % 2;{a: -7};-1 +a % 2;{a: 7.5};1.5 +a % 2;{a: 0};0 +a % 2;{a: null};!error +# Nested member operands +o.x + o.y;{o: {x: 1, y: 2}};3 +o.x + o.y;{o: {x: 0.1, y: 0.2}};0.3 +o.x + o.y;{o: {x: 1}};!error +o.x + o.y;{o: null};!error +o.x + o.y;{};!error +list[0] * list[1];{list: [3, 4]};12 +list[0] * list[1];{list: [0.5, 0.5]};0.25 +list[0] * list[1];{list: [3]};!error +list[0] * list[1];{list: []};!error +list[0] * list[1];{list: [3, 'x']};!error diff --git a/core/expression/tests/spec/standard/02-numbers.csv b/core/expression/tests/spec/standard/02-numbers.csv new file mode 100644 index 00000000..2736d603 --- /dev/null +++ b/core/expression/tests/spec/standard/02-numbers.csv @@ -0,0 +1,297 @@ +expression (string);input (json 5);output (json 5);note +# Basic arithmetic on integer literals +5 + 3;;8 +10 - 4;;6 +6 * 7;;42 +15 / 3;;5 +17 % 5;;2 +2 ^ 10;;1024 +0 + 0;;0 +1 - 1;;0 +3 - 5;;-2 +-3 - 5;;-8 +-3 + 5;;2 +-3 * 5;;-15 +-3 * -5;;15 +-15 / 3;;-5 +15 / -3;;-5 +-15 / -3;;5 +7 / 2;;3.5 +1 / 8;;0.125 +1 / 4;;0.25 +100 * 0;;0 +0 / 5;;0 +0 * -5;;0 +1000000 * 1000000;;1000000000000 +123456789 * 987654321;;121932631112635269 +# Decimal literals +1.5 + 2.5;;4 +1.5 + 2.25;;3.75 +0.5 - 0.25;;0.25 +0.25 - 0.5;;-0.25 +1.5 * 1.5;;2.25 +0.1 * 0.1;;0.01 +0.001 * 1000;;1 +2.5 / 0.5;;5 +0.3 / 0.1;;3 +1 / 0.1;;10 +1.2 - 1;;0.2 +-1.5 - -1.5;;0 +# Decimal exactness +0.1 + 0.2;;0.3 +0.1 + 0.2 == 0.3;;true +0.1 + 0.7;;0.8 +0.1 * 3;;0.3 +0.3 - 0.1;;0.2 +0.3 - 0.1 == 0.2;;true +1.1 * 1.1;;1.21 +3 * 1.1;;3.3 +1 - 0.9;;0.1 +100 * 1.1;;110 +4.35 * 100;;435 +1.005 * 1000;;1005 +0.07 * 100;;7 +1 / 3;;0.3333333333333333333333333333 +2 / 3;;0.6666666666666666666666666667 +-2 / 3;;-0.6666666666666666666666666667 +1 / 7;;0.1428571428571428571428571429 +22 / 7;;3.1428571428571428571428571429 +10 / 3;;3.3333333333333333333333333333 +100 / 3;;33.333333333333333333333333333 +1 / 3 * 3;;0.9999999999999999999999999999 +(1 / 3) * 3;;0.9999999999999999999999999999 +1 / 3 + 1 / 3 + 1 / 3;;0.9999999999999999999999999999 +3 * (1 / 3) == 1;;false +1 / 3 * 3 == 1;;false +2 / 3 * 3;;2.0000000000000000000000000001 +1 / 9;;0.1111111111111111111111111111 +1 / 11;;0.0909090909090909090909090909 +1 / 6;;0.1666666666666666666666666667 +1 / 1024;;0.0009765625 +1 / 3 - 0.3333333333333333333333333333;;0 +# 28-digit results and rounding beyond precision +1234567890123456789012345678 + 1;;1234567890123456789012345679 +0.1234567890123456789012345678 * 10;;1.234567890123456789012345678 +0.1234567890123456789012345678 + 1;;1.1234567890123456789012345678 +0.1234567890123456789012345678 + 10;;10.123456789012345678901234568 +1.0000000000000000000000000001 - 1;;0.0000000000000000000000000001 +0.0000000000000000000000000001 + 0.0000000000000000000000000001;;0.0000000000000000000000000002 +0.1234567890123456789012345678 * 0.1234567890123456789012345678;;0.0152415787532388367504953515 +0.3333333333333333333333333333 * 3;;0.9999999999999999999999999999 +1e-28;;0.0000000000000000000000000001 +1e-28 / 2;;0 +1e-28 * 0.5;;0 +1e-28 * 1e-28;;0 +1e-28 * 10;;0.000000000000000000000000001 +1e-28 + 1;;1.0000000000000000000000000001 +1e-28 + 10;;10.000000000000000000000000000 +1e-28 % 1;;0.0000000000000000000000000001 +# Scale of results observed via string() +string(1.10 + 1);;'2.10' +string(1 + 1.10);;'2.10' +string(1.10 - 0.10);;'1.00' +string(2.50 * 2);;'5.00' +string(1.0 / 2);;'0.5' +string(10 / 4);;'2.50';question: 10 / 4 yields scale 2 ('2.50') while 1.0 / 2 yields '0.5'; division result scale is not normalized +string(10 / 5);;'2' +string(10.0 / 5);;'2.0' +string(0 * 1.5);;'0';question: 0 * 1.5 drops the scale ('0') while 1.5 - 1.5 keeps it ('0.0') +string(1.5 - 1.5);;'0.0' +string(1.00 * 1.00);;'1.0000' +string(1.5 * 2);;'3.0' +string(0.1 + 0.2);;'0.3' +string(1.25 + 1.75);;'3.00' +string(100);;'100' +string(1e2);;'100' +string(1.5e1);;'15' +string(1 / 3);;'0.3333333333333333333333333333' +string(7 % 2.0);;'1.0' +string(7.5 % 2);;'1.5' +string(2.0 ^ 2);;'4.00' +string(1.5 ^ 2);;'2.25' +# Negative zero +-0;;0 +-0 == 0;;true +string(-0);;'0';bug: negative zero leaks into string conversion as '-0' +string(0 * -1);;'0' +string(-0.0);;'0.0';bug: negative zero leaks into string conversion as '-0.0' +-0 + 0;;0 +0 - 0;;0 +1 / -0;;null +-0 * 5;;0 +# Division by zero returns null +1 / 0;;null +0 / 0;;null +-1 / 0;;null +1.5 / 0.0;;null +1 / 0.0;;null +(1 / 0) == null;;true +1 / (1 - 1);;null +79228162514264337593543950335 / 0;;null +1e-28 / 0;;null +(1 / 0) ?? 5;;5 +# Modulo by zero returns null +1 % 0;;null +0 % 0;;null +-7 % 0;;null +1.5 % 0.0;;null +5 % (2 - 2);;null +# Modulo sign follows the dividend +7 % 3;;1 +-7 % 3;;-1 +7 % -3;;1 +-7 % -3;;-1 +3 % 7;;3 +-3 % 7;;-3 +0 % 5;;0 +6 % 3;;0 +-6 % 3;;0 +10 % 1;;0 +# Modulo with decimals +5.5 % 2;;1.5 +-5.5 % 2;;-1.5 +5.5 % -2;;1.5 +0.3 % 0.1;;0 +1 % 0.3;;0.1 +10 % 2.5;;0 +10 % 0.3;;0.1 +7.25 % 0.5;;0.25 +1.5 % 1;;0.5 +1 % 1e-28;;0 +79228162514264337593543950335 % 2;;1 +79228162514264337593543950335 % 10;;5 +79228162514264337593543950335 % 79228162514264337593543950335;;0 +1 / 3 % 0.1;;0.0333333333333333333333333333 +# Power with integer exponents +2 ^ 0;;1 +2 ^ 1;;2 +2 ^ 2;;4 +2 ^ 3;;8 +3 ^ 4;;81 +10 ^ 6;;1000000 +1 ^ 1000000;;1 +0 ^ 5;;0 +0 ^ 0;;1 +5 ^ 0;;1 +-2 ^ 0;;1 +(-2) ^ 2;;4 +(-2) ^ 3;;-8 +(-1) ^ 101;;-1 +(-1) ^ 100;;1 +1.5 ^ 2;;2.25 +1.1 ^ 2;;1.21 +0.1 ^ 3;;0.001 +0.5 ^ 10;;0.0009765625 +2 ^ 64;;18446744073709551616 +2 ^ 95;;39614081257132168796771975168 +10 ^ 28;;10000000000000000000000000000 +# Power with negative exponents +2 ^ -1;;0.5 +2 ^ -2;;0.25 +10 ^ -3;;0.001 +0.5 ^ -2;;4 +(-2) ^ -1;;-0.5 +(-2) ^ -2;;0.25 +4 ^ -0.5;;0.5;bug: fractional power is inexact (0.4999999999999999999999999999) +10 ^ -28;;0.0000000000000000000000000001 +3 ^ -1;;0.3333333333333333333333333333 +# Power with fractional exponents +4 ^ 0.5;;2;bug: fractional power is inexact (2.0000000000000000000000000003) +9 ^ 0.5;;3;bug: fractional power is inexact (3.0000000000000000000000000003) +16 ^ 0.25;;2;bug: fractional power is inexact (2.0000000000000000000000000001) +2 ^ 0.5;;1.4142135623730950488016887242;bug: last digits wrong, correctly rounded sqrt(2) ends in ...242, VM gives ...244 +100 ^ 0.5;;10;bug: fractional power is inexact (10.000000000000000000000000004) +0.25 ^ 0.5;;0.5 +8 ^ (1 / 3);;1.9999999999999999999999999999;bug: 8 ^ 0.3333333333333333333333333333 rounds to 1.9999999999999999999999999999, VM gives 2.0000000000000000000000000001 +0 ^ 0.5;;0 +1 ^ 0.5;;1 +# Power edge cases +0 ^ -1;;null;bug: 0 ^ -1 is 1 / 0 and must be null like division by zero, VM returns 0 +(-8) ^ (1 / 3);;-2.0000000000000000000000000001;question: negative base with a non-integer exponent returns a real odd root instead of failing +(-1) ^ 0.5;;!error;bug: square root of a negative number has no real result, VM returns -1 +(-4) ^ 0.5;;!error;bug: square root of a negative number has no real result, VM returns -2.0000000000000000000000000003 +10 ^ 29;;!error +2 ^ 96;;!error +2 ^ 1000;;!error +10 ^ 100;;!error +10 ^ -29;;0 +0.1 ^ 30;;0 +2 ^ 3 ^ 2;;512 +(2 ^ 3) ^ 2;;64 +2 ^ (3 ^ 2);;512 +2 ^ 2 ^ 3;;256 +2 ^ 1 ^ 5;;2 +# Decimal range boundaries +79228162514264337593543950335;;79228162514264337593543950335 +-79228162514264337593543950335;;-79228162514264337593543950335 +79228162514264337593543950335 - 1;;79228162514264337593543950334 +79228162514264337593543950335 + 0;;79228162514264337593543950335 +79228162514264337593543950335 * 1;;79228162514264337593543950335 +79228162514264337593543950335 / 1;;79228162514264337593543950335 +79228162514264337593543950335 * -1;;-79228162514264337593543950335 +79228162514264337593543950335 - 79228162514264337593543950335;;0 +79228162514264337593543950335 + -79228162514264337593543950335;;0 +79228162514264337593543950335 / 2;;39614081257132168796771975168 +79228162514264337593543950334 / 2;;39614081257132168796771975167 +-79228162514264337593543950335 + 1;;-79228162514264337593543950334 +# Overflow is an error +79228162514264337593543950335 + 1;;!error +-79228162514264337593543950335 - 1;;!error +79228162514264337593543950335 * 2;;!error +79228162514264337593543950335 - -1;;!error +79228162514264337593543950335 + 79228162514264337593543950335;;!error +-79228162514264337593543950335 * 2;;!error +79228162514264337593543950335 * 1.5;;!error +79228162514264337593543950335 / 0.5;;!error;bug: division overflow returns null instead of an error; docs say overflow is an error and null is reserved for division by zero +79228162514264337593543950335 / 0.1;;!error;bug: division overflow returns null instead of an error +1 / 1e-28 * 1e10;;!error +18446744073709551615 * 18446744073709551615;;!error +79228162514264337593543950336;;!error +79228162514264337593543950335 + 0.4;;79228162514264337593543950335 +79228162514264337593543950335 + 0.5;;!error +# Large integer literals beyond i64 are exact +9223372036854775807 + 1;;9223372036854775808 +-9223372036854775808 - 1;;-9223372036854775809 +9223372036854775807 * 2;;18446744073709551614 +18446744073709551615 + 1;;18446744073709551616 +4294967296 * 4294967296;;18446744073709551616 +170141183460469231731687303715884105727;;!error +1e28;;10000000000000000000000000000 +1e29;;!error +1e3 + 1;;1001 +1_000 + 1;;1001 +1_000_000 * 2;;2000000 +1.5e3 * 2;;3000 +2e-3 * 1000;;2 +# Unary minus and plus +-5;;-5 +- 5;;-5 +-(-5);;5 +-(5);;-5 +-(2 + 3);;-5 +- -5;;5 ++5;;5 ++-5;;-5 +-+5;;-5 ++(-5);;-5 +-1.5;;-1.5 +-0.0000000000000000000000000001;;-0.0000000000000000000000000001 +-79228162514264337593543950335;;-79228162514264337593543950335 +2 - -2;;4 +2 + -2;;0 +2 * -3;;-6 +-2 * -3;;6 +6 / -2;;-3 +2 ^ -2;;0.25 +-null;;!error +-true;;!error +-'1';;!error +-'a';;!error +-[1];;!error +-{a: 1};;!error +-d('2024-01-01');;!error ++null;;null;question: unary plus is a no-op for every type, unlike unary minus which rejects non-numbers ++true;;true;question: unary plus accepts booleans and returns them unchanged ++'1';;'1';question: unary plus returns strings unchanged instead of converting or rejecting them ++'a';;'a';question: unary plus returns non-numeric strings unchanged ++[1];;[1];question: unary plus returns arrays unchanged diff --git a/core/expression/tests/spec/standard/02-operand-types.csv b/core/expression/tests/spec/standard/02-operand-types.csv new file mode 100644 index 00000000..7d6812a3 --- /dev/null +++ b/core/expression/tests/spec/standard/02-operand-types.csv @@ -0,0 +1,241 @@ +expression (string);input (json 5);output (json 5);note +# Operand types: addition a + b +a + b;{a: 6, b: 3};9 +a + b;{a: null, b: 1};!error +a + b;{a: 1, b: null};!error +a + b;{a: null, b: null};!error +a + b;{b: 1};!error +a + b;{a: 1};!error +a + b;{};!error +a + b;{a: true, b: 1};!error +a + b;{a: 1, b: false};!error +a + b;{a: true, b: false};!error +a + b;{a: 'a', b: 1};!error +a + b;{a: 1, b: 'a'};!error +a + b;{a: '1', b: 1};!error +a + b;{a: 1, b: '1'};!error +a + b;{a: '6', b: '3'};'63' +a + b;{a: [1], b: 1};!error +a + b;{a: 1, b: [1]};!error +a + b;{a: [1], b: [2]};!error +a + b;{a: {x: 1}, b: 1};!error +a + b;{a: 1, b: {x: 1}};!error +a + b;{a: {}, b: {}};!error +a + b;{a: 0.5, b: 2};2.5 +# Operand types: subtraction a - b +a - b;{a: 6, b: 3};3 +a - b;{a: null, b: 1};!error +a - b;{a: 1, b: null};!error +a - b;{a: null, b: null};!error +a - b;{b: 1};!error +a - b;{a: 1};!error +a - b;{};!error +a - b;{a: true, b: 1};!error +a - b;{a: 1, b: false};!error +a - b;{a: true, b: false};!error +a - b;{a: 'a', b: 1};!error +a - b;{a: 1, b: 'a'};!error +a - b;{a: '1', b: 1};!error +a - b;{a: 1, b: '1'};!error +a - b;{a: '6', b: '3'};!error +a - b;{a: [1], b: 1};!error +a - b;{a: 1, b: [1]};!error +a - b;{a: [1], b: [2]};!error +a - b;{a: {x: 1}, b: 1};!error +a - b;{a: 1, b: {x: 1}};!error +a - b;{a: {}, b: {}};!error +a - b;{a: 0.5, b: 2};-1.5 +# Operand types: multiplication a * b +a * b;{a: 6, b: 3};18 +a * b;{a: null, b: 1};!error +a * b;{a: 1, b: null};!error +a * b;{a: null, b: null};!error +a * b;{b: 1};!error +a * b;{a: 1};!error +a * b;{};!error +a * b;{a: true, b: 1};!error +a * b;{a: 1, b: false};!error +a * b;{a: true, b: false};!error +a * b;{a: 'a', b: 1};!error +a * b;{a: 1, b: 'a'};!error +a * b;{a: '1', b: 1};!error +a * b;{a: 1, b: '1'};!error +a * b;{a: '6', b: '3'};!error +a * b;{a: [1], b: 1};!error +a * b;{a: 1, b: [1]};!error +a * b;{a: [1], b: [2]};!error +a * b;{a: {x: 1}, b: 1};!error +a * b;{a: 1, b: {x: 1}};!error +a * b;{a: {}, b: {}};!error +a * b;{a: 0.5, b: 2};1 +# Operand types: division a / b +a / b;{a: 6, b: 3};2 +a / b;{a: null, b: 1};!error +a / b;{a: 1, b: null};!error +a / b;{a: null, b: null};!error +a / b;{b: 1};!error +a / b;{a: 1};!error +a / b;{};!error +a / b;{a: true, b: 1};!error +a / b;{a: 1, b: false};!error +a / b;{a: true, b: false};!error +a / b;{a: 'a', b: 1};!error +a / b;{a: 1, b: 'a'};!error +a / b;{a: '1', b: 1};!error +a / b;{a: 1, b: '1'};!error +a / b;{a: '6', b: '3'};!error +a / b;{a: [1], b: 1};!error +a / b;{a: 1, b: [1]};!error +a / b;{a: [1], b: [2]};!error +a / b;{a: {x: 1}, b: 1};!error +a / b;{a: 1, b: {x: 1}};!error +a / b;{a: {}, b: {}};!error +a / b;{a: 0.5, b: 2};0.25 +# Operand types: modulo a % b +a % b;{a: 6, b: 3};0 +a % b;{a: null, b: 1};!error +a % b;{a: 1, b: null};!error +a % b;{a: null, b: null};!error +a % b;{b: 1};!error +a % b;{a: 1};!error +a % b;{};!error +a % b;{a: true, b: 1};!error +a % b;{a: 1, b: false};!error +a % b;{a: true, b: false};!error +a % b;{a: 'a', b: 1};!error +a % b;{a: 1, b: 'a'};!error +a % b;{a: '1', b: 1};!error +a % b;{a: 1, b: '1'};!error +a % b;{a: '6', b: '3'};!error +a % b;{a: [1], b: 1};!error +a % b;{a: 1, b: [1]};!error +a % b;{a: [1], b: [2]};!error +a % b;{a: {x: 1}, b: 1};!error +a % b;{a: 1, b: {x: 1}};!error +a % b;{a: {}, b: {}};!error +a % b;{a: 0.5, b: 2};0.5 +# Operand types: power a ^ b +a ^ b;{a: 6, b: 3};216 +a ^ b;{a: null, b: 1};!error +a ^ b;{a: 1, b: null};!error +a ^ b;{a: null, b: null};!error +a ^ b;{b: 1};!error +a ^ b;{a: 1};!error +a ^ b;{};!error +a ^ b;{a: true, b: 1};!error +a ^ b;{a: 1, b: false};!error +a ^ b;{a: true, b: false};!error +a ^ b;{a: 'a', b: 1};!error +a ^ b;{a: 1, b: 'a'};!error +a ^ b;{a: '1', b: 1};!error +a ^ b;{a: 1, b: '1'};!error +a ^ b;{a: '6', b: '3'};!error +a ^ b;{a: [1], b: 1};!error +a ^ b;{a: 1, b: [1]};!error +a ^ b;{a: [1], b: [2]};!error +a ^ b;{a: {x: 1}, b: 1};!error +a ^ b;{a: 1, b: {x: 1}};!error +a ^ b;{a: {}, b: {}};!error +a ^ b;{a: 0.5, b: 2};0.25 +# Operand types with literals: addition +2 + null;;!error +null + 2;;!error +2 + true;;!error +true + 2;;!error +2 + 'x';;!error +'x' + 2;;!error +2 + '2';;!error +'2' + 2;;!error +2 + [2];;!error +[2] + 2;;!error +2 + {x: 2};;!error +{x: 2} + 2;;!error +2 + d('2024-01-01');;!error +d('2024-01-01') + 2;;!error +2 + (1..3);;!error +(1..3) + 2;;!error +# Operand types with literals: subtraction +2 - null;;!error +null - 2;;!error +2 - true;;!error +true - 2;;!error +2 - 'x';;!error +'x' - 2;;!error +2 - '2';;!error +'2' - 2;;!error +2 - [2];;!error +[2] - 2;;!error +2 - {x: 2};;!error +{x: 2} - 2;;!error +2 - d('2024-01-01');;!error +d('2024-01-01') - 2;;!error +2 - (1..3);;!error +(1..3) - 2;;!error +# Operand types with literals: multiplication +2 * null;;!error +null * 2;;!error +2 * true;;!error +true * 2;;!error +2 * 'x';;!error +'x' * 2;;!error +2 * '2';;!error +'2' * 2;;!error +2 * [2];;!error +[2] * 2;;!error +2 * {x: 2};;!error +{x: 2} * 2;;!error +2 * d('2024-01-01');;!error +d('2024-01-01') * 2;;!error +2 * (1..3);;!error +(1..3) * 2;;!error +# Operand types with literals: division +2 / null;;!error +null / 2;;!error +2 / true;;!error +true / 2;;!error +2 / 'x';;!error +'x' / 2;;!error +2 / '2';;!error +'2' / 2;;!error +2 / [2];;!error +[2] / 2;;!error +2 / {x: 2};;!error +{x: 2} / 2;;!error +2 / d('2024-01-01');;!error +d('2024-01-01') / 2;;!error +2 / (1..3);;!error +(1..3) / 2;;!error +# Operand types with literals: modulo +2 % null;;!error +null % 2;;!error +2 % true;;!error +true % 2;;!error +2 % 'x';;!error +'x' % 2;;!error +2 % '2';;!error +'2' % 2;;!error +2 % [2];;!error +[2] % 2;;!error +2 % {x: 2};;!error +{x: 2} % 2;;!error +2 % d('2024-01-01');;!error +d('2024-01-01') % 2;;!error +2 % (1..3);;!error +(1..3) % 2;;!error +# Operand types with literals: power +2 ^ null;;!error +null ^ 2;;!error +2 ^ true;;!error +true ^ 2;;!error +2 ^ 'x';;!error +'x' ^ 2;;!error +2 ^ '2';;!error +'2' ^ 2;;!error +2 ^ [2];;!error +[2] ^ 2;;!error +2 ^ {x: 2};;!error +{x: 2} ^ 2;;!error +2 ^ d('2024-01-01');;!error +d('2024-01-01') ^ 2;;!error +2 ^ (1..3);;!error +(1..3) ^ 2;;!error diff --git a/core/expression/tests/spec/standard/02-precedence.csv b/core/expression/tests/spec/standard/02-precedence.csv new file mode 100644 index 00000000..ece6c4fd --- /dev/null +++ b/core/expression/tests/spec/standard/02-precedence.csv @@ -0,0 +1,93 @@ +expression (string);input (json 5);output (json 5);note +# Multiplicative binds tighter than additive +1 + 2 * 3;;7 +2 * 3 + 1;;7 +(1 + 2) * 3;;9 +10 - 6 / 2;;7 +(10 - 6) / 2;;2 +1 + 7 % 4;;4 +(1 + 7) % 4;;0 +10 - 3 * 2 - 1;;3 +5 ^ 2 + 3 * 4 - 6 / 2;;34 +4 ^ 3 - 2 * 5 + 7 / 2;;57.5 +# Power binds tighter than multiplicative +2 * 3 ^ 2;;18 +(2 * 3) ^ 2;;36 +3 ^ 2 * 2;;18 +18 / 3 ^ 2;;2 +10 % 3 ^ 2;;1 +2 ^ 3 % 5;;3 +1 + 2 ^ 3;;9 +2 ^ -1 * 4;;2 +# Additive operators are left-associative +10 - 2 - 3;;5 +10 - (2 - 3);;11 +1 - 2 + 3;;2 +1 - (2 + 3);;-4 +1 + 2 - 3 + 4 - 5;;-1 +0.1 + 0.2 - 0.3;;0 +# Multiplicative operators are left-associative +100 / 10 / 5;;2 +100 / (10 / 5);;50 +8 / 2 * 4;;16 +8 / (2 * 4);;1 +2 * 3 % 4;;2 +2 * (3 % 4);;6 +2 % 3 * 4;;8 +7 % 4 % 2;;1 +7 % (4 % 3);;0 +12 / 3 % 3;;1 +12 % 5 / 2;;1 +1 / 3 * 3;;0.9999999999999999999999999999 +3 * 1 / 3;;1 +# Power is right-associative +2 ^ 3 ^ 2;;512 +(2 ^ 3) ^ 2;;64 +2 ^ 2 ^ 3;;256 +4 ^ 3 ^ 0;;4 +(4 ^ 3) ^ 0;;1 +2 ^ -1 ^ 2;;2;question: unary minus binds tighter than ^, so this is 2 ^ ((-1) ^ 2) +# Unary minus with power +-2 ^ 2;;4;question: unary minus binds tighter than ^ (Excel-style (-2)^2 = 4); mathematical convention gives -(2^2) = -4 +-(2 ^ 2);;-4 +(-2) ^ 2;;4 +-3 ^ 2;;9;question: unary minus binds tighter than ^ (Excel-style); mathematical convention gives -9 +-2 ^ 3;;-8 +0 - 2 ^ 2;;-4 +1 - 2 ^ 2;;-3 +2 ^ -2;;0.25 +-2 ^ -2;;0.25 +# Unary minus with other operators +-2 * 3;;-6 +-2 * -3;;6 +-6 / 2;;-3 +-7 % 3;;-1 +-(7 % 3);;-1 +-1 + 2;;1 +-(1 + 2);;-3 +1 - -1;;2 +1 + -1;;0 +1 - - 1;;2 +- - 1;;1 +- - - 1;;-1 +-(-(-1));;-1 +3 * -(2 + 1);;-9 +# Arithmetic binds tighter than comparison +1 + 2 == 3;;true +2 * 3 > 5;;true +10 / 2 < 4;;false +2 ^ 3 == 8;;true +1 + 1 != 2;;false +1 + 2 * 3 == 7 and 2 ^ 2 == 4;;true +10 % 3 == 1 or false;;true +# Nullish coalescing binds tighter than arithmetic +null ?? 1 + 1;;2 +3 ?? 1 + 1;;4;question: ?? binds tighter than + so this is (3 ?? 1) + 1 = 4; JS/C# give 3 ?? (1 + 1) = 3 +2 * null ?? 5;;10 +(null ?? 1) + 1;;2 +# Grouping and nesting +((1 + 2) * (3 + 4)) ^ 2;;441 +(((((1)))));;1 +((2 + 3) * 4 - (6 / 3)) % 7;;4 +-((2 + 3) * 4);;-20 +(1 + 2) * (3 - 5) / (4 - 2);;-3 diff --git a/core/expression/tests/spec/standard/02-strings.csv b/core/expression/tests/spec/standard/02-strings.csv new file mode 100644 index 00000000..c0d2c87d --- /dev/null +++ b/core/expression/tests/spec/standard/02-strings.csv @@ -0,0 +1,61 @@ +expression (string);input (json 5);output (json 5);note +# String concatenation with + +'a' + 'b';;'ab' +'Hello' + ' ' + 'World';;'Hello World' +'' + '';;'' +'a' + '';;'a' +'' + 'a';;'a' +'1' + '2';;'12' +'1.5' + '0';;'1.50' +'á' + 'ü' + '😀';;'áü😀' +'a' + ('b' + 'c');;'abc' +('a' + 'b') + 'c';;'abc' +'x' + string(1);;'x1' +string(1.50) + 'x';;'1.50x' +string(1 + 2) + '!';;'3!' +'a' + 'b' == 'ab';;true +len('ab' + 'cd');;4 +# Concatenation does not coerce other types +'a' + 1;;!error +1 + 'a';;!error +'1' + 1;;!error +1 + '1';;!error +'a' + 1.5;;!error +'a' + null;;!error +null + 'a';;!error +'a' + true;;!error +true + 'a';;!error +'a' + [1];;!error +['a'] + 'b';;!error +'a' + {x: 1};;!error +'a' + d('2024-01-01');;'a2024-01-01T00:00:00Z' +'a' + 'b' + 1;;!error +1 + 2 + 'a';;!error +'a' + (1 + 2);;!error +# Other arithmetic operators reject strings +'a' - 'a';;!error +'ab' * 2;;!error +2 * 'ab';;!error +'6' / '3';;!error +'7' % '2';;!error +'2' ^ '3';;!error +'10' - 1;;!error +# String concatenation from input +a + b;{a: 'foo', b: 'bar'};'foobar' +a + b;{a: '', b: ''};'' +a + b;{a: 'foo', b: ''};'foo' +a + b;{a: 'foo', b: null};!error +a + b;{a: 'foo'};!error +a + b;{a: 'foo', b: 1};!error +a + b;{a: 1, b: 'foo'};!error +a + ' ' + b;{a: 'John', b: 'Doe'};'John Doe' +a + ' ' + b;{a: 'John', b: ''};'John ' +a + ' ' + b;{a: 'John', b: null};!error +a + ' ' + b;{a: 'John'};!error +a + ' ' + b;{a: 1, b: 2};!error +a + '!';{a: 'hi'};'hi!' +a + '!';{a: ''};'!' +a + '!';{a: null};!error +a + '!';{a: 5};!error +a + '!';{a: ['hi']};!error +a + '!';{};!error diff --git a/core/expression/tests/spec/standard/03-conditional.csv b/core/expression/tests/spec/standard/03-conditional.csv new file mode 100644 index 00000000..7c182316 --- /dev/null +++ b/core/expression/tests/spec/standard/03-conditional.csv @@ -0,0 +1,173 @@ +expression (string);input (json 5);output (json 5);note +# Nullish coalescing: only null and missing fall through +null ?? 1;;1 +1 ?? 2;;1 +0 ?? 1;;0 +false ?? 1;;false +true ?? 1;;true +'' ?? 'x';;'' +[] ?? 1;;[] +{} ?? 1;;{} +null ?? null;;null +null ?? false;;false +null ?? null ?? 3;;3 +null ?? 2 ?? 3;;2 +1 ?? null ?? 3;;1 +d('2024-01-01') ?? 1;;'2024-01-01T00:00:00Z' +# Nullish coalescing: the right side is evaluated only when needed +1 ?? (1 + {});;1 +0 ?? (1 + {});;0 +false ?? (1 + {});;false +null ?? (1 + {});;!error +# Nullish coalescing binds tighter than arithmetic and comparison +null ?? 1 + 2;;3 +2 ?? 1 + 2;;4 +null ?? 2 * 3;;6 +null ?? 2 ^ 3;;8 +2 ^ null ?? 3;;8 +null ?? 1 == 1;;true +null ?? 2 == 1;;false +null ?? false or true;;true +null ?? true and false;;false +null ?? 1 in [1];;true +1 + (null ?? 2);;3 +-(null ?? 5);;-5 +-null ?? 5;;!error +null ?? -5;;-5 +# Nullish coalescing: variable operands +x ?? 'default';{x: 'set'};'set' +x ?? 'default';{x: null};'default' +x ?? 'default';{};'default' +x ?? 'default';{x: ''};'' +x ?? 'default';{x: 0};0 +x ?? 'default';{x: false};false +x ?? 'default';{x: []};[] +x ?? 0;{x: 5};5 +x ?? 0;{x: null};0 +x ?? 0;{};0 +x ?? 0;{x: -0.5};-0.5 +x ?? 0;{x: '7'};'7' +a ?? b;{a: 1, b: 2};1 +a ?? b;{a: null, b: 2};2 +a ?? b;{b: 2};2 +a ?? b;{a: null};null +a ?? b;{};null +a ?? b;{a: false, b: true};false +a ?? b ?? c;{a: 1, b: 2, c: 3};1 +a ?? b ?? c;{b: 2, c: 3};2 +a ?? b ?? c;{c: 3};3 +a ?? b ?? c;{};null +a ?? b ?? c;{a: 0, c: 3};0 +x.y ?? 'd';{x: {y: 1}};1 +x.y ?? 'd';{x: {}};'d' +x.y ?? 'd';{x: null};'d' +x.y ?? 'd';{};'d' +x.y ?? 'd';{x: {y: false}};false +x.y.z ?? 'd';{};'d' +x.y.z ?? 'd';{x: {y: {z: 0}}};0 +x[0] ?? 'd';{x: []};'d' +x[0] ?? 'd';{x: [null]};'d' +x[0] ?? 'd';{x: [0]};0 +x ?? 1 + 1;{x: 5};6 +x ?? 1 + 1;{};2 +x ?? 1 + 1;{x: null};2 +x ?? 1 + 1;{x: 'a'};!error +x ?? 1 * 3;{x: 2};6 +x ?? 1 * 3;{};3 +x ?? 1 > 0;{x: 5};true +x ?? 1 > 0;{x: -5};false +x ?? 1 > 0;{};true +x ?? 1 > 0;{x: 'a'};!error +(x ?? 0) >= 18;{x: 21};true +(x ?? 0) >= 18;{};false +(x ?? 0) >= 18;{x: null};false +(x ?? 0) >= 18;{x: 18};true +x ?? false or y;{y: true};true +x ?? false or y;{x: true};true +x ?? false or y;{x: false, y: false};false +x ?? false or y;{x: 1, y: true};!error +# Ternary: condition must be a boolean +true ? 1 : 2;;1 +false ? 1 : 2;;2 +1 == 1 ? 'y' : 'n';;'y' +1 == 2 ? 'y' : 'n';;'n' +null ? 1 : 2;;!error +1 ? 1 : 2;;!error +0 ? 1 : 2;;!error +'' ? 1 : 2;;!error +'true' ? 1 : 2;;!error +[] ? 1 : 2;;!error +{} ? 1 : 2;;!error +# Ternary: only the chosen branch is evaluated +true ? 1 : (1 + {});;1 +false ? (1 + {}) : 2;;2 +true ? (1 + {}) : 2;;!error +false ? 1 : (1 + {});;!error +true ? null : 1;;null +false ? 1 : [1, 2];;[1, 2] +true ? {a: 1} : 0;;{a: 1} +# Ternary: nesting is right-associative +true ? 1 : false ? 2 : 3;;1 +false ? 1 : true ? 2 : 3;;2 +false ? 1 : false ? 2 : 3;;3 +true ? false ? 1 : 2 : 3;;2 +true ? true ? 1 : 2 : 3;;1 +false ? true ? 1 : 2 : 3;;3 +(true ? false : true) ? 1 : 2;;2 +true ? 1 : 2 ? 3 : 4;;1 +false ? 1 : (true ? 2 : 3);;2 +# Ternary: lowest precedence +true or false ? 'a' : 'b';;'a' +false and true ? 'a' : 'b';;'b' +1 + 1 == 2 ? 'a' : 'b';;'a' +true ? 1 : 2 + 10;;1 +false ? 1 : 2 + 10;;12 +null ?? true ? 'a' : 'b';;'a' +null ?? false ? 'a' : 'b';;'b' +(true ? 1 : 2) + 10;;11 +true ? 1 + 1 : 0;;2 +not true ? 'a' : 'b';;'b' +1 in [1] ? 'a' : 'b';;'a' +[true ? 1 : 2, false ? 1 : 2];;[1, 2] +{k: false ? 'a' : 'b'};;{k: 'b'} +# Ternary: variable operands +x ? 'yes' : 'no';{x: true};'yes' +x ? 'yes' : 'no';{x: false};'no' +x ? 'yes' : 'no';{x: null};!error +x ? 'yes' : 'no';{};!error +x ? 'yes' : 'no';{x: 1};!error +x ? 'yes' : 'no';{x: 'true'};!error +age >= 18 ? 'adult' : 'minor';{age: 18};'adult' +age >= 18 ? 'adult' : 'minor';{age: 17.9};'minor' +age >= 18 ? 'adult' : 'minor';{age: 99};'adult' +age >= 18 ? 'adult' : 'minor';{age: null};!error +age >= 18 ? 'adult' : 'minor';{};!error +score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';{score: 95};'A' +score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';{score: 90};'A' +score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';{score: 85};'B' +score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';{score: 70};'C' +score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';{score: 0};'F' +score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';{score: '95'};!error +x == null ? 'missing' : x;{};'missing' +x == null ? 'missing' : x;{x: null};'missing' +x == null ? 'missing' : x;{x: 0};0 +x == null ? 'missing' : x;{x: false};false +x == null ? 'missing' : x;{x: 'v'};'v' +c ? a : b;{c: true, a: 1, b: 2};1 +c ? a : b;{c: false, a: 1, b: 2};2 +c ? a : b;{c: true, b: 2};null +c ? a : b;{c: false, a: 1};null +c ? a : b;{c: true, a: 1, b: 'x'};1 +c ? a : b;{c: null, a: 1, b: 2};!error +c ? a + {} : b;{c: false, a: 1, b: 2};2 +c ? a + {} : b;{c: true, a: 1, b: 2};!error +x > 0 ? x : -x;{x: 5};5 +x > 0 ? x : -x;{x: -5};5 +x > 0 ? x : -x;{x: 0};0 +x > 0 ? x : -x;{x: -0.25};0.25 +x in [1..5] ? 'in' : 'out';{x: 3};'in' +x in [1..5] ? 'in' : 'out';{x: 6};'out' +x in [1..5] ? 'in' : 'out';{x: null};!error +(x ?? 0) > 0 ? 'pos' : 'non';{x: 1};'pos' +(x ?? 0) > 0 ? 'pos' : 'non';{};'non' +(x ?? 0) > 0 ? 'pos' : 'non';{x: -1};'non' diff --git a/core/expression/tests/spec/standard/03-equality.csv b/core/expression/tests/spec/standard/03-equality.csv new file mode 100644 index 00000000..cde3813d --- /dev/null +++ b/core/expression/tests/spec/standard/03-equality.csv @@ -0,0 +1,172 @@ +expression (string);input (json 5);output (json 5);note +# Equality: numbers compare by exact value, scale is ignored +1 == 1;;true +1 == 2;;false +1 == 1.0;;true +1.0 == 1.00;;true +1.10 == 1.1;;true +0 == -0;;true +-0 == 0.0;;true +0.1 + 0.2 == 0.3;;true +0.1 == 0.10000000000000000001;;false +1 / 3 == 0.3333333333333333333333333333;;true +1e3 == 1000;;true +1.5e1 == 15;;true +1_000 == 1000;;true +10000000000000000000000000000 == 10000000000000000000000000000;;true +79228162514264337593543950335 == 79228162514264337593543950335;;true +79228162514264337593543950335 == 79228162514264337593543950334;;false +-79228162514264337593543950335 == -79228162514264337593543950335;;true +0.0000000000000000000000000001 == 0;;false +0.0000000000000000000000000001 == 0.0000000000000000000000000001;;true +1 != 1;;false +1 != 2;;true +1 != 1.0;;false +0 != -0;;false +-1 == 1;;false +-1 != 1;;true +# Equality: booleans +true == true;;true +false == false;;true +true == false;;false +true != false;;true +false != false;;false +# Equality: null +null == null;;true +null != null;;false +null == false;;false +null == 0;;false +null == '';;false +null == [];;false +null == {};;false +false == null;;false +0 == null;;false +'' == null;;false +null != 0;;true +# Equality: strings are exact, case-sensitive, no normalization +'a' == 'a';;true +'a' == 'b';;false +'' == '';;true +'a' == 'A';;false +'abc' == 'abc ';;false +' abc' == 'abc';;false +'hello' == "hello";;true +'1' == '1.0';;false +'01' == '1';;false +'é' == 'é';;true +'é' == 'é';;false +'日本' == '日本';;true +'😀' == '😀';;true +'a' != 'A';;true +'' != ' ';;true +# Equality across types is false, never an error +1 == '1';;false +'1' == 1;;false +1 != '1';;true +0 == false;;false +1 == true;;false +'true' == true;;false +'' == false;;false +'null' == null;;false +[] == false;;false +[1] == 1;;false +1 == [1];;false +{} == false;;false +'a' == ['a'];;false +[] == {};;false +# Equality: arrays compare by value +[1, 2] == [1, 2];;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +[] == [];;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +[1, 2] == [2, 1];;false +[1, 2] != [1, 2];;false;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +[1, 2] != [2, 1];;true +[[1], [2]] == [[1], [2]];;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +[1, 'a', null] == [1, 'a', null];;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +[1] == [1, 1];;false +[1.0] == [1];;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +# Equality: objects compare by value +{a: 1} == {a: 1};;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +{} == {};;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +{a: 1, b: 2} == {b: 2, a: 1};;true;bug: == on objects is always false; deep equality with key order ignored is intended +{a: 1} == {a: 2};;false +{a: 1} == {b: 1};;false +{a: 1} != {a: 1};;false;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +{a: {b: [1]}} == {a: {b: [1]}};;true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +# Equality: a value read twice from the environment +a == a;{a: [1, 2]};true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +a == a;{a: {x: 1}};true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +a == b;{a: [1, 2], b: [1, 2]};true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +a == b;{a: [1, 2], b: [2, 1]};false +a == b;{a: [1, 2], b: null};false +a == b;{a: [], b: {}};false +a != b;{a: [1], b: [1]};false;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself implements deep equality) +a != b;{a: [1], b: [2]};true +a != b;{a: {x: 1}, b: {x: 2}};true +a == b;{a: {x: 1}, b: {x: 1}};true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +# Equality: dates +d('2024-01-01') == d('2024-01-01');;true +d('2024-01-01') == d('2024-01-02');;false +d('2024-01-01') != d('2024-01-02');;true +d('2024-01-01T00:00:00Z') == d('2024-01-01');;true +d('2024-01-01') == '2024-01-01';;true +'2024-01-01' == d('2024-01-01');;true +d('2024-01-01') == 1704067200;;false +d('2024-01-01') == null;;false +d('2024-01-01') != null;;true +d('2024-01-01').add('1d') == d('2024-01-02');;true +# Equality: intervals are not values that compare +[1..5] == [1..5];;false;question: two identical interval values compare unequal +# Equality: variable operands +a == b;{a: 1, b: 1};true +a == b;{a: 1, b: 1.00};true +a == b;{a: 1, b: 2};false +a == b;{a: 1, b: '1'};false +a == b;{a: null, b: null};true +a == b;{a: 1};false +a == b;{};true +a == b;{a: true, b: true};true +a == b;{a: 'x', b: 'x'};true +a == b;{a: 'x', b: 'X'};false +a != b;{a: 1, b: 1};false +a != b;{a: 1, b: 2};true +a != b;{a: 1, b: '1'};true +a != b;{a: null};false +a != b;{b: 0};true +a != b;{a: 'x', b: 'y'};true +x == 1;{x: 1};true +x == 1;{x: 1.000};true +x == 1;{x: '1'};false +x == 1;{x: null};false +x == 1;{};false +x == 1;{x: true};false +x == 'gold';{x: 'gold'};true +x == 'gold';{x: 'Gold'};false +x == 'gold';{x: null};false +x == 'gold';{};false +x == 'gold';{x: 1};false +x == 'gold';{x: ['gold']};false +x == null;{x: null};true +x == null;{};true +x == null;{x: 0};false +x == null;{x: false};false +x == null;{x: ''};false +x == null;{x: []};false +x != null;{x: null};false +x != null;{};false +x != null;{x: 0};true +x != null;{x: 'a'};true +x == true;{x: true};true +x == true;{x: 1};false +x == true;{x: 'true'};false +x == true;{};false +x.y == 1;{x: {y: 1}};true +x.y == 1;{x: {y: 2}};false +x.y == 1;{x: {}};false +x.y == 1;{x: null};false +x.y == 1;{};false +d(x) == d('2024-01-01');{x: '2024-01-01'};true +d(x) == d('2024-01-01');{x: '2024-01-01T00:00:00Z'};true +d(x) == d('2024-01-01');{x: '2024-01-02'};false +d(x) == d('2024-01-01');{x: 1704067200000};true +d(x) == d('2024-01-01');{x: 'garbage'};false +d(x) == d('2024-01-01');{x: 1704067200};false diff --git a/core/expression/tests/spec/standard/03-logic.csv b/core/expression/tests/spec/standard/03-logic.csv new file mode 100644 index 00000000..870f1cf8 --- /dev/null +++ b/core/expression/tests/spec/standard/03-logic.csv @@ -0,0 +1,153 @@ +expression (string);input (json 5);output (json 5);note +# Logic: truth tables +true and true;;true +true and false;;false +false and true;;false +false and false;;false +true or true;;true +true or false;;true +false or true;;true +false or false;;false +not true;;false +not false;;true +!true;;false +!false;;true +! true;;false +not not true;;true +!!true;;true +not !false;;false +!not true;;true +!(1 == 2);;true +not (1 == 1);;false +# Logic: `and` binds tighter than `or` +true or false and false;;true +(true or false) and false;;false +false and false or true;;true +false and (false or true);;false +false or false or true;;true +true and true and false;;false +true and true and true;;true +# Logic: `not` binds tighter than comparison and `and` +not true and false;;false +not false and true;;true +not false or false;;true +not (true and false);;true +not true == false;;true +not false == false;;false +not 1 == 2;;!error +not 2 * 3 == 6;;!error +not (2 * 3 == 6);;false +!1 == 2;;!error +# Logic: operands must be booleans +not 1;;!error +not 0;;!error +not null;;!error +not '';;!error +not 'true';;!error +not [];;!error +not {};;!error +!null;;!error +1 and true;;!error +0 and true;;!error +null and true;;!error +'' and true;;!error +[] and true;;!error +1 or true;;!error +0 or false;;!error +null or true;;!error +'x' or false;;!error +{} or true;;!error +true and 1;;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +true and null;;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +true and 'x';;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or 'x';;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or 0;;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or null;;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or [1];;!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +# Logic: short circuit leaves the right side unevaluated +false and (1 + {});;false +true or (1 + {});;true +false and 1 + {} == 1;;false +true or 1 + {} == 1;;true +false and not 1;;false +true or not 1;;true +false and 1;;false +true or 1;;true +false and null;;false +true or 'x';;true +true and (1 + {});;!error +false or (1 + {});;!error +false and false and (1 + {});;false +true and false and (1 + {});;false +false or true or (1 + {});;true +false and (1 + {}) or true;;true +true or (1 + {}) and true;;true +1 + {} and false;;!error +(1 + {}) or true;;!error +x and y;{x: false};false +x and y;{x: false, y: 1};false +x or y;{x: true};true +x or y;{x: true, y: 'z'};true +# Logic: variable operands +x and y;{x: true, y: true};true +x and y;{x: true, y: false};false +x and y;{x: false, y: true};false +x and y;{x: null, y: true};!error +x and y;{y: true};!error +x and y;{x: 1, y: true};!error +x and y;{x: 'true', y: true};!error +x and y;{x: true, y: null};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +x and y;{x: true};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +x or y;{x: false, y: false};false +x or y;{x: false, y: true};true +x or y;{x: true, y: false};true +x or y;{x: null, y: true};!error +x or y;{};!error +x or y;{x: 0, y: true};!error +x or y;{x: false, y: 'z'};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +x or y;{x: false, y: 0};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +not x;{x: true};false +not x;{x: false};true +not x;{x: null};!error +not x;{};!error +not x;{x: 0};!error +not x;{x: 'false'};!error +!x;{x: false};true +!x;{x: true};false +!x;{x: []};!error +!x;{};!error +x and not y;{x: true, y: false};true +x and not y;{x: true, y: true};false +x and not y;{x: false, y: 1};false +x and not y;{x: true, y: 1};!error +x or not y;{x: false, y: false};true +x or not y;{x: true, y: 'a'};true +x or not y;{x: false, y: null};!error +not x or y;{x: true, y: true};true +not x or y;{x: false, y: 1};true +not x or y;{x: true, y: false};false +not x or y;{x: 1, y: false};!error +x > 1 and x < 5;{x: 3};true +x > 1 and x < 5;{x: 5};false +x > 1 and x < 5;{x: 0};false +x > 1 and x < 5;{x: null};!error +x > 1 and x < 5;{x: '3'};!error +x == 1 or x == 2;{x: 1};true +x == 1 or x == 2;{x: 2};true +x == 1 or x == 2;{x: 3};false +x == 1 or x == 2;{x: null};false +x == 1 or x == 2;{};false +x != null and x > 10;{x: 20};true +x != null and x > 10;{x: 5};false +x != null and x > 10;{x: null};false +x != null and x > 10;{};false +x == null or x > 10;{};true +x == null or x > 10;{x: 11};true +x == null or x > 10;{x: 1};false +x == null or x > 10;{x: 'a'};!error +# Logic: equality of booleans produced by logic +(true and false) == false;;true +(true or false) != true;;false +true and false == false;;true +false or true == true;;true +true == false or true;;true diff --git a/core/expression/tests/spec/standard/03-membership.csv b/core/expression/tests/spec/standard/03-membership.csv new file mode 100644 index 00000000..afebfd3d --- /dev/null +++ b/core/expression/tests/spec/standard/03-membership.csv @@ -0,0 +1,246 @@ +expression (string);input (json 5);output (json 5);note +# Membership in arrays: numbers compare by value +1 in [1, 2, 3];;true +4 in [1, 2, 3];;false +1 in [1.0];;true +1.00 in [1];;true +0 in [-0];;true +-1 in [1];;false +0.1 + 0.2 in [0.3];;true +1 in [];;false +1 in ['1'];;false +1 in [true];;false +1 in [null];;false +1 in [[1]];;false +1 not in [1, 2];;false +3 not in [1, 2];;true +1 not in [];;true +1 not in ['1'];;true +# Membership in arrays: strings are exact +'a' in ['a', 'b'];;true +'c' in ['a', 'b'];;false +'A' in ['a'];;false +'' in [''];;true +'' in [];;false +'1' in [1];;false +'a' in ['a', 1, null];;true +'a ' in ['a'];;false +'日本' in ['日本'];;true +'US' not in ['US', 'CA'];;false +'GB' not in ['US', 'CA'];;true +# Membership in arrays: booleans and null +true in [true];;true +true in [false];;false +false in [false, true];;true +true in [1];;false +false in [0, null, ''];;false +null in [null];;true +null in [1, null];;true +null in [];;false +null in [0, false, ''];;false +null not in [null];;false +null not in [1];;true +# Membership in arrays: dates +d('2024-01-01') in [d('2024-01-01'), d('2024-02-01')];;true +d('2024-01-01') in [d('2024-01-02')];;false +d('2024-01-01') in ['2024-01-01'];;true +d('2024-01-01') in [];;false +d('2024-01-01T00:00:00Z') in [d('2024-01-01')];;true +# Membership in arrays: arrays and objects as the needle +[1] in [[1], [2]];;true;bug: membership of an array needle errors instead of using the deep equality `in` implies +[3] in [[1], [2]];;false;bug: membership of an array needle errors instead of returning false +[] in [];;false;bug: membership of an array needle errors instead of returning false +{a: 1} in [{a: 1}];;true;bug: membership of an object needle errors instead of using the deep equality `in` implies +{a: 1} in [{a: 2}];;false;bug: membership of an object needle errors instead of returning false +# Membership: intervals as haystack +1 in [1..5];;true +5 in [1..5];;true +3 in [1..5];;true +0 in [1..5];;false +6 in [1..5];;false +1 in (1..5);;false +5 in (1..5);;false +3 in (1..5);;true +1 in [1..5);;true +5 in [1..5);;false +1 in (1..5];;false +5 in (1..5];;true +2.5 in [1..5];;true +0.9999999999999999999999999999 in [1..5];;false +5.0000000000000000000000000001 in [1..5];;false +1.0000000000000000000000000001 in (1..5);;true +4.9999999999999999999999999999 in (1..5);;true +1.00 in (1..5];;false +3.2 in [1..3.5];;true +3.6 in [1..3.5];;false +0.5 in [0.1..0.9];;true +0.1 in (0.1..0.9);;false +-5 in [-10..-1];;true +-10 in (-10..-1];;false +-1 in [-10..-1);;false +-0.5 in (-1..0);;true +0 in (-1..0);;false +0 in [-0..0];;true +3 in [3..3];;true +3 in (3..3);;false +3 in [3..3);;false +3 in [5..1];;false +5 in [5..1];;false +3 not in [1..5];;false +0 not in [1..5];;true +5 not in [1..5);;true +# Membership: reversed brackets mean the outside of the range +3 in ]1..5[;;false;question: `]a..b[` is the exterior of [a..b] with endpoints included, not the ISO open interval (a..b) +1 in ]1..5[;;true;question: `]a..b[` is the exterior of [a..b] with endpoints included, not the ISO open interval (a..b) +5 in ]1..5[;;true;question: `]a..b[` is the exterior of [a..b] with endpoints included, not the ISO open interval (a..b) +0 in ]1..5[;;true +6 in ]1..5[;;true +1 in )1..5(;;false +5 in )1..5(;;false +0 in )1..5(;;true +3 in )1..5(;;false +x in ]1..5[;{x: 3};false;question: `]a..b[` is the exterior of [a..b] with endpoints included, not the ISO open interval (a..b) +x in ]1..5[;{x: 1};true;question: `]a..b[` is the exterior of [a..b] with endpoints included, not the ISO open interval (a..b) +x in ]1..5[;{x: 9};true +x in ]1..5[;{x: null};!error +x in ]a..5[;{x: 0, a: 1};true +x in ]1..b[;{x: 0, b: 5};true;bug: `b[` after `..` is parsed as an index access, so a non-literal right bound cannot close with `[` +x in )1..b(;{x: 0, b: 5};true;bug: `b(` after `..` is parsed as a call, so a non-literal right bound cannot close with `(` +d('2024-01-06') in ]d('2024-01-01')..d('2024-01-05')[;;true;bug: a call as the right bound followed by `[` is parsed as an index access +# Membership: mixed bracket forms +]1..5];;']1..5]' +[1..5[;;'[1..5[' +3 in ]1..5];;true;question: `]a..b]` accepts any v <= b (union of two half-lines), not the ISO half-open interval (a..b] +-100 in ]1..5];;true;question: `]a..b]` accepts any v <= b (union of two half-lines), not the ISO half-open interval (a..b] +3 in [1..5[;;false;question: `[a..b[` accepts only v >= b, not the ISO half-open interval [a..b) +7 in [1..5[;;true;question: `[a..b[` accepts only v >= b, not the ISO half-open interval [a..b) +# Membership: intervals are values +[1..5];;'[1..5]' +(1..5);;'(1..5)' +[1..5);;'[1..5)' +(0.5..2.5];;'(0.5..2.5]' +[-3..-1];;'[-3..-1]' +[5..1];;'[5..1]' +]1..5[;;']1..5[' +1..5;;!error +x in 1..5;{x: 2};!error +[1..'5'];;!error +['a'..'b'];;!error +[null..5];;!error +[1..d('2024-01-01')];;!error +[a..b];{a: 1, b: 3};'[1..3]' +# Membership: non-number needles in number intervals +null in [1..5];;!error +'3' in [1..5];;!error +true in [0..1];;!error +[3] in [1..5];;!error +d('2024-01-03') in [1..5];;!error;bug: a date against a number interval is false instead of the type error that `<` gives +d('2024-01-03') in ]1..5[;;!error;bug: a date against a number interval compares across types (true here) instead of erroring +3 in [d('2024-01-01')..d('2024-01-05')];;!error;bug: a number against a date interval is false instead of the type error that `<` gives +# Membership: date intervals +d('2024-01-03') in [d('2024-01-01')..d('2024-01-05')];;true +d('2024-01-01') in [d('2024-01-01')..d('2024-01-05')];;true +d('2024-01-01') in (d('2024-01-01')..d('2024-01-05')];;false +d('2024-01-05') in [d('2024-01-01')..d('2024-01-05'));;false +d('2024-01-06') in [d('2024-01-01')..d('2024-01-05')];;false +d('2024-01-03') not in [d('2024-01-01')..d('2024-01-05')];;false +# Membership: strings and objects as haystack +'a' in 'abc';;!error;question: `in` has no substring form; contains() is the supported way +1 in 'abc';;!error +'a' in {a: 1};;true +'b' in {a: 1};;false +'a' in {a: null};;true +'' in {};;false +'a' not in {a: 1};;false +'b' not in {a: 1};;true +1 in {a: 1};;!error +null in {a: 1};;!error +'A' in {a: 1};;false +# Membership: invalid haystacks +1 in null;;!error +null in null;;!error +1 in 1;;!error +'a' in 'a';;!error +1 in true;;!error +{} in {};;!error +# Membership: precedence +1 + 1 in [2];;true +2 * 2 in [1..4];;true +1 in [1] == true;;true +true == 1 in [1];;false +1 in [1] and 2 in [2];;true +1 in [2] or 2 in [2];;true +not 1 in [1];;!error +not (1 in [1]);;false +1 not in [2] and true;;true +(1 in [1]) in [true];;true +1 in [1, 2, 3][0:2];;true +2 in map([1, 2], # * 1);;true +x ?? 1 in [1];{};true +# Membership: variable needle and haystack +x in [1, 2, 3];{x: 2};true +x in [1, 2, 3];{x: 4};false +x in [1, 2, 3];{x: 2.0};true +x in [1, 2, 3];{x: '2'};false +x in [1, 2, 3];{x: null};false +x in [1, 2, 3];{};false +x in [1, 2, 3];{x: true};false +x in [1, 2, 3];{x: [2]};false;bug: membership of an array needle errors instead of returning false +x in list;{x: [1], list: [[1]]};true;bug: membership of an array needle errors instead of using deep equality +x in list;{x: {a: 1}, list: [{a: 1}]};true;bug: membership of an object needle errors instead of using deep equality +x in ['US', 'CA'];{x: 'US'};true +x in ['US', 'CA'];{x: 'us'};false +x in ['US', 'CA'];{x: ''};false +x in ['US', 'CA'];{x: null};false +x in ['US', 'CA'];{};false +x in ['US', 'CA'];{x: 1};false +x not in ['US', 'CA'];{x: 'US'};false +x not in ['US', 'CA'];{x: 'GB'};true +x not in ['US', 'CA'];{x: null};true +x not in ['US', 'CA'];{};true +x not in ['US', 'CA'];{x: 5};true +x in list;{x: 1, list: [1, 2]};true +x in list;{x: 3, list: [1, 2]};false +x in list;{x: 'a', list: ['a']};true +x in list;{x: 1, list: []};false +x in list;{x: null, list: [null]};true +x in list;{x: 1, list: null};!error +x in list;{x: 1};!error +x in list;{x: 'k', list: {k: 1}};true +x in list;{x: 'z', list: {k: 1}};false +x in [1..10];{x: 1};true +x in [1..10];{x: 10};true +x in [1..10];{x: 10.5};false +x in [1..10];{x: 0};false +x in [1..10];{x: null};!error +x in [1..10];{};!error +x in [1..10];{x: '5'};!error +x in (0..100);{x: 0};false +x in (0..100);{x: 0.01};true +x in (0..100);{x: 100};false +x in (0..100);{x: 99.99};true +x in (0..100);{x: -1};false +x in [0..100);{x: 0};true +x in [0..100);{x: 100};false +x in [0..100);{x: 50};true +x in (0..100];{x: 0};false +x in (0..100];{x: 100};true +x in (0..100];{x: 100.0000000000000000000000001};false +x in [a..b];{x: 3, a: 1, b: 5};true +x in [a..b];{x: 5, a: 1, b: 5};true +x in [a..b];{x: 6, a: 1, b: 5};false +x in [a..b];{x: 3, a: 5, b: 1};false +x in [a..b];{x: 3, a: 1};!error +x in [a..b];{x: 3, a: '1', b: 5};!error +x in (a..b);{x: 1, a: 1, b: 5};false +x in (a..b);{x: 2, a: 1, b: 5};true +x in (a..b);{x: 1.5, a: 1, b: 2};true +x in (a..b);{x: -3, a: -5, b: -1};true +x not in [1..5];{x: 3};false +x not in [1..5];{x: 7};true +x not in [1..5];{x: 5};false +x not in [1..5];{x: null};!error +d(x) in [d('2024-01-01')..d('2024-12-31')];{x: '2024-06-15'};true +d(x) in [d('2024-01-01')..d('2024-12-31')];{x: '2024-12-31'};true +d(x) in [d('2024-01-01')..d('2024-12-31')];{x: '2025-01-01'};false +d(x) in [d('2024-01-01')..d('2024-12-31')];{x: '2023-12-31T23:59:59Z'};false diff --git a/core/expression/tests/spec/standard/03-ordering.csv b/core/expression/tests/spec/standard/03-ordering.csv new file mode 100644 index 00000000..55ed0aad --- /dev/null +++ b/core/expression/tests/spec/standard/03-ordering.csv @@ -0,0 +1,141 @@ +expression (string);input (json 5);output (json 5);note +# Ordering: numbers by exact value +1 < 2;;true +2 < 1;;false +1 < 1;;false +1 <= 1;;true +1 > 1;;false +1 >= 1;;true +2 > 1;;true +1 >= 2;;false +1 < 1.0;;false +1 <= 1.00;;true +1.0 >= 1;;true +-0 < 0;;false +-0 <= 0;;true +0 >= -0;;true +-1 < 0;;true +-1 > -2;;true +-1.5 < -1.4;;true +0.1 + 0.2 <= 0.3;;true +0.1 + 0.2 >= 0.3;;true +0.3 < 0.3000000000000000000000000001;;true +0.0000000000000000000000000001 > 0;;true +-0.0000000000000000000000000001 < 0;;true +79228162514264337593543950335 > 79228162514264337593543950334;;true +-79228162514264337593543950335 < 79228162514264337593543950335;;true +1e3 > 999.999;;true +1 / 3 < 0.3333333333333333333333333334;;true +2 ^ 10 >= 1024;;true +10 % 3 < 2;;true +# Ordering: operands of other types are errors +'a' < 'b';;!error;question: strings have no ordering; is lexicographic comparison intended? +'b' > 'a';;!error;question: strings have no ordering; is lexicographic comparison intended? +'a' <= 'a';;!error;question: strings have no ordering even when equal +'' < 'a';;!error;question: strings have no ordering; is lexicographic comparison intended? +'10' < '9';;!error;question: numeric-looking strings have no ordering +'1' < 2;;!error +1 < '2';;!error +null < 1;;!error +1 < null;;!error +null <= null;;!error +null >= 0;;!error +true < false;;!error +false <= true;;!error +true > 0;;!error +[1] < [2];;!error +[] <= [];;!error +{} < {};;!error +{a: 1} >= {a: 1};;!error +1 < [2];;!error +# Ordering: comparisons do not chain +1 < 2 < 3;;!error +3 > 2 > 1;;!error +1 < 2 == true;;true +1 == 1 == true;;true +1 == 1 == 1;;false +(1 < 2) == (2 < 3);;true +1 < 2 and 2 < 3;;true +# Ordering: arithmetic binds tighter than comparison +1 + 2 > 2;;true +1 + 2 < 2 * 2;;true +10 - 5 >= 5;;true +2 * 3 <= 6;;true +2 ^ 3 > 7;;true +-1 < -1 + 1;;true +# Ordering: dates +d('2024-01-01') < d('2024-01-02');;true +d('2024-01-02') < d('2024-01-01');;false +d('2024-01-01') <= d('2024-01-01');;true +d('2024-01-01') < d('2024-01-01');;false +d('2024-01-01') >= d('2024-01-01T00:00:00Z');;true +d('2024-01-01T00:00:01Z') > d('2024-01-01');;true +d('2023-12-31T23:59:59Z') < d('2024-01-01');;true +d('1970-01-01') < d('2100-01-01');;true +d('2024-01-01') < '2024-01-02';;true +'2024-01-01' < d('2024-01-02');;true +d('2024-01-01') < 5;;!error +d('2024-01-01') > null;;!error +d('2024-01-01') < d('garbage');;false;question: an invalid date orders before every valid date instead of erroring +d('garbage') < d('2024-01-01');;true;question: an invalid date orders before every valid date instead of erroring +d('garbage') == d('garbage');;true;question: two invalid dates are equal to each other +# Ordering: variable operands +a < b;{a: 1, b: 2};true +a < b;{a: 2, b: 1};false +a < b;{a: 1, b: 1.0};false +a < b;{a: -0.5, b: 0};true +a < b;{a: 1};!error +a < b;{};!error +a < b;{a: 1, b: '2'};!error +a < b;{a: 'a', b: 'b'};!error;question: strings have no ordering; is lexicographic comparison intended? +a <= b;{a: 1, b: 1};true +a <= b;{a: 1.00, b: 1};true +a <= b;{a: 2, b: 1};false +a <= b;{a: null, b: 1};!error +a <= b;{a: true, b: true};!error +a > b;{a: 3, b: 2};true +a > b;{a: 2, b: 3};false +a > b;{a: 79228162514264337593543950335, b: 0};true +a > b;{a: 0.0000000000000000000000000001, b: 0};true +a > b;{b: 1};!error +a >= b;{a: 2, b: 2};true +a >= b;{a: 1, b: 2};false +a >= b;{a: -1, b: -1.0};true +a >= b;{a: [1], b: 1};!error +x > 18;{x: 21};true +x > 18;{x: 18};false +x > 18;{x: 18.0000000001};true +x > 18;{x: null};!error +x > 18;{};!error +x > 18;{x: '21'};!error +x >= 18;{x: 18};true +x >= 18;{x: 17.99};false +x >= 18;{x: -18};false +x >= 18;{x: false};!error +x < 0.5;{x: 0.49};true +x < 0.5;{x: 0.5};false +x < 0.5;{x: 0.50};false +x < 0.5;{x: -1};true +x < 0.5;{x: {}};!error +x <= 100;{x: 100};true +x <= 100;{x: 100.0000000000000000000000001};false +x <= 100;{x: -100};true +x <= 100;{x: []};!error +x.y > 1;{x: {y: 2}};true +x.y > 1;{x: {y: 1}};false +x.y > 1;{x: {}};!error +x.y > 1;{x: null};!error +x.y > 1;{};!error +d(x) < d('2024-06-01');{x: '2024-01-01'};true +d(x) < d('2024-06-01');{x: '2024-06-01'};false +d(x) < d('2024-06-01');{x: '2025-01-01'};false +d(x) < d('2024-06-01');{x: '2024-05-31T23:59:59Z'};true +d(x) < d(y);{x: '2024-01-01', y: '2024-01-02'};true +d(x) < d(y);{x: '2024-01-02', y: '2024-01-01'};false +d(x) >= d(y);{x: '2024-01-01', y: '2024-01-01'};true +d(x) >= d(y);{x: '2023-01-01', y: '2024-01-01'};false +x < y;{x: 1, y: 2};true +x < y;{x: 'a', y: 'b'};!error;question: strings have no ordering; is lexicographic comparison intended? +x < y;{x: 1, y: null};!error +x < y;{x: true, y: 1};!error +x < y;{x: 5, y: -5};false diff --git a/core/expression/tests/spec/standard/04-access.csv b/core/expression/tests/spec/standard/04-access.csv new file mode 100644 index 00000000..aa858840 --- /dev/null +++ b/core/expression/tests/spec/standard/04-access.csv @@ -0,0 +1,186 @@ +expression (string);input (json 5);output (json 5);note +# Dot access: present values of every kind +a;{a: 1};1 +a;{a: 'x'};'x' +a;{a: null};null +a;{a: true};true +a;{a: [1, 2]};[1, 2] +a;{a: {b: 1}};{b: 1} +a;{a: 1.50};1.5 +a;{};null +a;;null +a.b;{a: {b: 1}};1 +a.b;{a: {b: 'v'}};'v' +a.b;{a: {b: null}};null +a.b;{a: {b: [1]}};[1] +a.b;{a: {b: {c: 1}}};{c: 1} +a.b;{a: {c: 1}};null +a.b;{a: {}};null +a.b;{};null +a.b;;null +a.b.c;{a: {b: {c: 1}}};1 +a.b.c;{a: {b: {c: 'deep'}}};'deep' +a.b.c;{a: {b: {c: null}}};null +a.b.c;{a: {b: {}}};null +a.b.c;{a: {b: null}};null +a.b.c;{a: {}};null +a.b.c;{a: null};null +a.b.c;{};null +a.b.c;;null +a.b.c.d.e.f;{a: {b: {c: {d: {e: {f: 'deep'}}}}}};'deep' +a.b.c.d.e.f;{a: {b: {c: {d: {e: {}}}}}};null +a.b.c.d.e.f;{a: {b: {c: {d: 5}}}};null +a . b;{a: {b: 1}};1 +(a).b;{a: {b: 2}};2 +(a.b).c;{a: {b: {c: 3}}};3 +# Dot access on non-object values is null, not an error +a.b;{a: 5};null +a.b;{a: 'str'};null +a.b;{a: true};null +a.b;{a: false};null +a.b;{a: [1, 2]};null +a.b;{a: []};null +a.length;{a: 'abc'};null +a.length;{a: [1, 2, 3]};null +a.b.c;{a: {b: 5}};null +a.b.c;{a: {b: 'str'}};null +a.b.c;{a: {b: true}};null +a.b.c;{a: {b: [1]}};null +a.b.c;{a: 0};null +# Bracket access with string keys +a['b'];{a: {b: 1}};1 +a['b'];{a: {b: null}};null +a['b'];{a: {}};null +a['b'];{a: null};null +a['b'];{a: 5};null +a['b'];{};null +a['b']['c'];{a: {b: {c: 1}}};1 +a['b']['c'];{a: {b: 5}};null +a['b'].c;{a: {b: {c: 2}}};2 +a.b['c'];{a: {b: {c: 3}}};3 +a['my key'];{a: {'my key': 3}};3 +a['my key'];{a: {'my': 3}};null +a['ключ'];{a: {'ключ': 3}};3 +a['日本'];{a: {'日本': 'jp'}};'jp' +a['😀'];{a: {'😀': 1}};1 +a['1'];{a: {'1': 3}};3 +a['0'];{a: {'0': 'z'}};'z' +a['a.b'];{a: {'a.b': 1}};1 +a.a.b;{a: {'a.b': 1}};null +a['b c'].d;{a: {'b c': {d: 4}}};4 +a['B'];{a: {b: 1}};null +a['-'];{a: {'-': 'dash'}};'dash' +a['$'];{a: {'$': 1}};1 +# Number keys do not coerce to object string keys +a[1];{a: {'1': 3}};null +a[0];{a: {'0': 'z'}};null +a.1;{a: {'1': 3}};!error +# Dynamic keys +a[k];{a: {b: 1}, k: 'b'};1 +a[k];{a: {b: 1}, k: 'c'};null +a[k];{a: {b: 1}, k: 1};null +a[k];{a: {b: 1}, k: null};null +a[k];{a: {b: 1}};null +a[k];{a: {b: 1}, k: true};null +a[k];{a: {'1': 'one'}, k: '1'};'one' +a[k];{a: [5, 6], k: 1};6 +a[k];{a: [5, 6], k: 0};5 +a[k];{a: [5, 6], k: '1'};null +a[k];{a: [5, 6], k: null};null +a[k];{a: [5, 6]};null +a[k];{a: 'xyz', k: 1};'y' +a[k];{a: null, k: 'b'};null +a[k1][k2];{a: {x: {y: 7}}, k1: 'x', k2: 'y'};7 +a[k1][k2];{a: {x: {y: 7}}, k1: 'x', k2: 'z'};null +a[k1][k2];{a: {x: 5}, k1: 'x', k2: 'y'};null +a[k1][k2];{a: {x: {y: 7}}};null +a[k.p];{a: {x: 8}, k: {p: 'x'}};8 +a[k.p];{a: {x: 8}, k: {}};null +a[k.p];{a: {x: 8}, k: null};null +a[b[0]];{a: [10, 20], b: [1]};20 +a[b[0]];{a: [10, 20], b: []};null +a[b[0]];{a: {n: 1}, b: ['n']};1 +a['b' + 'c'];{a: {bc: 1}};1 +a[k + 'x'];{a: {yx: 2}, k: 'y'};2 +a[lower(k)];{a: {key: 3}, k: 'KEY'};3 +a[string(n)];{a: {'5': 'five'}, n: 5};'five' +a[k ?? 'd'];{a: {d: 'dflt', v: 'val'}, k: null};'dflt' +a[k ?? 'd'];{a: {d: 'dflt', v: 'val'}, k: 'v'};'val' +a[true ? 'x' : 'y'];{a: {x: 1, y: 2}};1 +# Unusual key types in brackets yield null +a[true];{a: [1]};null +a[null];{a: [1]};null +a[[0]];{a: [1]};null +a[{}];{a: [1]};null +a[true];{a: {'true': 1}};null +# Literal receivers +[1, 2, 3][0];;1 +[1, 2, 3][2];;3 +[1, 2, 3][3];;null +[[1, 2], [3]][1][0];;3 +[{a: 1}][0].a;;1 +{a: 1}.a;;!error;question: member access on an object literal is a parse error while array literals allow it +{a: 1}['a'];;!error;question: bracket access on an object literal is a parse error while array literals allow it +'abc'[1];;!error;question: indexing a string literal is a parse error while array literals allow it +true.x;;!error +null.x;;!error +null[0];;!error +a?.b;{a: {b: 1}};!error +# Access results feed expressions +a.b + 1;{a: {b: 1}};2 +a.b + a.c;{a: {b: 1, c: 2}};3 +a.b ?? 'none';{a: {b: 'v'}};'v' +a.b ?? 'none';{a: {}};'none' +a.b ?? 'none';{a: 5};'none' +a.b ?? 'none';{a: {b: false}};false +a.b == null;{a: {}};true +a.b == null;{a: {b: 0}};false +a.b.c ?? a.d;{a: {d: 'fallback'}};'fallback' +len(a.b);{a: {b: [1, 2, 3]}};3 +len(a.b);{a: {b: 'abcd'}};4 +upper(a.b);{a: {b: 'x'}};'X' +`${a.b}`;{a: {b: 'x'}};'x' +[a.b, a.c];{a: {b: 1}};[1, null] +{v: a.b};{a: {b: 1}};{v: 1} +# Root reference +$root;{a: 1};{a: 1} +$root;{};{} +$root;;null +$root;5;5 +$root;'s';'s' +$root;[1, 2];[1, 2] +$root.a;{a: 1};1 +$root.a;{};null +$root.a;;null +$root.a;5;null +$root.a.b;{a: {b: 2}};2 +$root.a.b;{a: 3};null +$root['a'];{a: 1};1 +$root['a b'];{'a b': 1};1 +$root[k];{a: 1, k: 'a'};1 +$root[k];{a: 1, k: 'zz'};null +$root[0];[1, 2];1 +$root[1];[1, 2];2 +$root.$root;{'$root': 1};1 +($root).a;{a: 4};4 +len($root);[1, 2, 3];3 +keys($root);{a: 1};['a'] +# $ is an ordinary identifier in standard mode +$;{'$': 5};5 +$;{a: 1};null +$.a;{'$': {a: 1}};1 +$.a;{a: 1};null +# Identifier lookup on a non-object environment +x;;null +x;{};null +x;{x: null};null +x;5;!error;question: an identifier on a non-object root errors while $root.x on the same root is null +x;'str';!error;question: an identifier on a non-object root errors while $root.x on the same root is null +x;[1, 2];!error;question: an identifier on a non-object root errors while $root.x on the same root is null +x;true;!error;question: an identifier on a non-object root errors while $root.x on the same root is null +# Identifiers are case sensitive and may contain $ and _ +X;{x: 1};null +_x;{_x: 1};1 +x1;{x1: 1};1 +$x;{'$x': 1};1 +a_b.c_d;{a_b: {c_d: 2}};2 diff --git a/core/expression/tests/spec/standard/04-assignment.csv b/core/expression/tests/spec/standard/04-assignment.csv new file mode 100644 index 00000000..1cc3fedf --- /dev/null +++ b/core/expression/tests/spec/standard/04-assignment.csv @@ -0,0 +1,219 @@ +expression (string);input (json 5);output (json 5);note +# A program of only assignments returns an object of the assigned keys (not the whole environment) +"x = 1";{};{x: 1} +"x = 1";{y: 2};{x: 1} +"x = 1";{x: 5};{x: 1} +"x = 1";{x: 2, y: 3};{x: 1} +"x = 1";{a: null};{x: 1} +"x = null";{x: 5};{x: null} +"x = 'a'";{};{x: 'a'} +"x = [1, 2]";{};{x: [1, 2]} +"x = {a: 1}";{};{x: {a: 1}} +"x = 1; y = 2";{};{x: 1, y: 2} +"x = 1; y = 2";{z: 3};{x: 1, y: 2} +"x = 1; y = x + 1";{};{x: 1, y: 2} +"x = 1; x = x + 1";{};{x: 2} +"x.y = 1; x = 2";{};{x: 2} +"a.b = 1";{};{a: {b: 1}} +"a.b = 1";{a: {c: 2}};{a: {b: 1}} +"a.b = 1";{a: {b: 0, c: 1}};{a: {b: 1}} +"a.b.c = 1";{};{a: {b: {c: 1}}} +"a.b.c = 1";{a: {b: 5}};{a: {b: {c: 1}}} +"a.b.c = 1; a.b.d = 2";{};{a: {b: {c: 1, d: 2}}} +"a.b = 1; a.c = 2";{a: {z: 0}};{a: {b: 1, c: 2}} +"x.y.z = 1";{x: {y: {w: 2}}};{x: {y: {z: 1}}} +# The assigned-keys object disagrees with the environment when a scalar is later extended +"a = 1; a.b = 2";{};{a: {b: 2}};bug: env holds a = {b: 2} (a reads back as {b: 2}) but the returned object keeps a = 1 +"a.b = 1; a.b.c = 2";{};{a: {b: {c: 2}}};bug: env holds a.b = {c: 2} but the returned object silently keeps a.b = 1 +"a = 1; a.b = 2; a";{};{b: 2} +"a.b = 1; a.b.c = 2; a";{};{b: {c: 2}} +# Trailing semicolon +"x = 1;";{};{x: 1} +"x = 1; y = 2;";{};{x: 1, y: 2} +"x = 1; x;";{};1;bug: a trailing ; is accepted after an assignment but rejected after the final expression +"x = 1; x + 1;";{};2;bug: a trailing ; is accepted after an assignment but rejected after the final expression +"x = 1;; x";{};!error +# Final expression is the result +"x = 1; x";{};1 +"a = 5; b = 10; a + b";{};15 +"x = 1; y = 2; x + y";{};3 +"x = 1 ; y = 2 ; x + y";{};3 +"x=1;y=x*2;y";{};2 +"x = 1; x = x + 1; x";{};2 +"x = 1; x = 'a'; x = [x]; x";{};['a'] +"x = 1; y = x; x = 2; y";{};1 +"x = 1; y = 2; [x, y, z]";{};[1, 2, null] +"x = 1; (x + 1)";{};2 +"x = 1; {a: x}";{};{a: 1} +"x = 1; [x]";{};[1] +"x = 1; `v${x}`";{};'v1' +"x = 1; -x";{};-1 +"x = 1; not true";{};false +"x = 1; 'str'";{};'str' +"x = 1; map([1], # + x)";{};[2] +"x = 'a'; y = x + 'b'; y";{};'ab' +"x = [1, 2]; x[0]";{};1 +"x = [1, 2, 3]; x[1:2]";{};[2, 3] +"x = 'ab'; x[0]";{};'a' +"x = {a: 1}; x.a";{};1 +"x = 1; y = x.z; y";{};null +"x = 1 == 1; x";{};true +"x = 1 ?? 2; x";{};1 +"x = true and false; x";{};false +"x = 1 > 0 ? 'a' : 'b'; x";{};'a' +"x = [1..5]; 3 in x";{};true +"user.name = 'Eve'; user.name";{};'Eve' +"config.debug = true; config.env = 'dev'; config";{};{debug: true, env: 'dev'} +"config.debug = true; config.env = 'dev'; $root";{};{config: {debug: true, env: 'dev'}} +# Assignments read the input +"x = x + 1; x";{x: 1};2 +"x = x + 1; x";{x: 1.5};2.5 +"x = x + 1; x";{x: null};!error +"x = x + 1; x";{};!error +"x = x + 1; x";{x: 'a'};!error +"x = x ?? 'd'; x";{x: null};'d' +"x = x ?? 'd'; x";{};'d' +"x = x ?? 'd'; x";{x: 'v'};'v' +"x = x ?? 'd'; x";{x: 0};0 +"x = x ?? 'd'; x";{x: false};false +"total = price * qty; total";{price: 2, qty: 3};6 +"total = price * qty; total";{price: 2.5, qty: 2};5 +"total = price * qty; total";{price: 0, qty: 2};0 +"total = price * qty; total";{price: null, qty: 2};!error +"total = price * qty; total";{qty: 2};!error +"total = price * qty; total";{price: '2', qty: 2};!error +"x = a[0]; x";{a: [7]};7 +"x = a[0]; x";{a: []};null +"x = a[0]; x";{a: null};null +"x = a[0]; x";{};null +"x = a.b; x";{a: {b: 'v'}};'v' +"x = a.b; x";{a: 5};null +"x = a.b; x";{};null +"u.name = upper(u.name); u";{u: {name: 'ann', age: 3}};{name: 'ANN', age: 3} +"u.name = upper(u.name); u";{u: {name: 'ann'}};{name: 'ANN'} +"u.name = upper(u.name); u";{u: {name: 'x', tags: [1]}};{name: 'X', tags: [1]} +"a.b = a.b + 1; a";{a: {b: 1, c: 2}};{b: 2, c: 2} +"a.b = a.b + 1";{a: {b: 1, c: 2}};{a: {b: 2}} +"a.b = a.b + 1; a.b";{a: null};!error +"a.b = (a.b ?? 0) + 1; a.b";{a: {b: 41}};42 +"a.b = (a.b ?? 0) + 1; a.b";{a: null};1 +"a.b = (a.b ?? 0) + 1; a.b";{a: 5};1 +"a.b = (a.b ?? 0) + 1; a.b";{};1 +"a.b = (a.b ?? 0) + 1; a.b";{a: {c: 1}};1 +# Dotted assignment merges into existing objects and replaces non-objects +"a.b = 1; a";{a: {c: 2}};{b: 1, c: 2} +"a.b = 1; a";{a: {}};{b: 1} +"a.b = 1; a";{a: 5};{b: 1} +"a.b = 1; a";{a: null};{b: 1} +"a.b = 1; a";{a: [1]};{b: 1} +"a.b = 1; a";{a: 'str'};{b: 1} +"a.b = 1; a";{};{b: 1} +"a.b.c = 1; a";{a: {b: 5}};{b: {c: 1}} +"x.y.z = 1; x";{x: {y: {w: 2}, v: 3}};{v: 3, y: {w: 2, z: 1}} +"x.y.z = 1; x.y";{x: {y: {w: 2}}};{w: 2, z: 1} +"x.y.z = 1; x.y.z";{};1 +"a.b = 1; $root";{a: {c: 2}};{a: {b: 1, c: 2}} +"a.b = 1; a.b";{};1 +"a.b = 1; a['b']";{};1 +"a.b = 1; a[k]";{k: 'b'};1 +"a.b = 1; a.b + a.c";{a: {c: 2}};3 +"a.b = 1; x = a.b + 1; x";{};2 +"a.b.c = 1; a.b.d = 2; a";{};{b: {c: 1, d: 2}} +"x.y = 1; x.y = 2; x";{};{y: 2} +"x = 1; x.y = 2; x";{};{y: 2} +"x.y = 1; x = 2; x";{};2 +"x = {a: 1}; x.a = 2; x";{};{a: 2} +"x = {a: 1}; x.b = 2; x";{};{a: 1, b: 2} +# $root sees assignments +"x = 1; $root";{};{x: 1} +"x = 1; $root";{x: 0};{x: 1} +"x = 1; $root";{y: 2};{x: 1, y: 2} +"x = x + 1; $root";{x: 1, y: 2};{x: 2, y: 2} +"x = 1; y = 2; $root";{x: 0, y: 0, z: 0};{x: 1, y: 2, z: 0} +"x = 1; y = $root; y";{a: 2};{a: 2, x: 1} +"x = 1; y = $root; y.x";{a: 2};1 +"x = 1; k = 'x'; $root[k]";{};1 +"x = 1; ($root).x";{x: 5};1 +"x = 1; $root.x";{};1;bug: $root.x compiles to a fast path that reads the original input while $root and ($root).x see the assignment +"x = 1; $root.x";{x: 5};1;bug: $root.x reads the original input (5) while ($root).x reads the assigned 1 +"x = 1; $root['x']";{};1;bug: $root['x'] compiles to a fast path that reads the original input +"x = 1; $root['x']";{x: 5};1;bug: $root['x'] reads the original input while $root[k] with k = 'x' sees the assignment +"a.b = 1; $root.a.b";{};1;bug: $root.a.b reads the original input instead of the assigned value +"a.b = 1; $root.a.b";{a: {b: 0}};1;bug: $root.a.b reads the original input instead of the assigned value +"x.y = 1; $root.x";{x: {z: 1}};{y: 1, z: 1};bug: $root.x reads the original input instead of the assigned value +"x.y = 1; $root.x.y";{x: {z: 1}};1;bug: $root.x.y reads the original input instead of the assigned value +# Assigning to $root and $-prefixed names +"$root = 1";{};{'$root': 1};question: $root is accepted as an assignment target and creates a literal '$root' key +"$root.x = 1";{};{'$root': {x: 1}};question: $root.x = 1 writes a nested '$root' key instead of assigning x at the root +"$root.x = 1; x";{};null;question: $root.x = 1 does not make x visible +"$root.x = 1; $root";{};{'$root': {x: 1}};question: $root.x = 1 writes a literal '$root' key into the environment +"$x = 1; $x";{};1 +"$ = 1; $";{};1 +"_x = 1; _x";{};1 +"x1 = 1; x1";{};1 +"len = 1; len";{};1 +"d = 1; d";{};1 +"x = 1; X";{};null +# Invalid assignment targets and malformed programs +"a['b'] = 1";{};!error +"a[0] = 1";{a: [0]};!error +"a[k] = 1";{k: 'b'};!error +"a.b[0] = 1";{};!error +"true = 1";{};!error +"null = 1";{};!error +"in = 1";{};!error +"x.true = 1; x";{};!error +"= 1";{};!error +"x =";{};!error +"x = ;";{};!error +"x = 1 = 2";{};!error +"x = 1, y = 2";{};!error +"x = 1 y = 2";{};!error +"x == 1; y = 2";{x: 1};!error +"x = 1; x + 1; 5";{};!error +"5; x = 1";{};!error +"1 + 1; 2";{};!error +"x = 3; filter(list, # > x); x";{list: [1, 5]};!error +# An assignment as the value of another assignment +"x = 1; y = x.w = 2";{};{x: 1, y: {x: {w: 2}}};question: y = x.w = 2 parses the right side as a nested assignment program whose value is its assigned-keys object and which also rebinds x +# Assignment values that error or produce null +"x = 1 + {}; 2";{};!error +"x = y; x";{};null +"x = null; x";{x: 5};null +"x = 1; x + y";{y: 2};3 +"x = y + 1; y = 5; x";{};!error +"x = y + 1; y = 5; x";{y: 1};2 +"x = y + 1; y = 5; [x, y]";{y: 1};[2, 5] +# Assignments need an object environment +"x = 1";;!error;question: assignments need an object environment - with no input they fail +"x = 1; x";;!error;question: assignments need an object environment - with no input they fail +"x = 1";5;!error +"x = 1";[1];!error +"x = 1";'s';!error +"x = 1";true;!error +# Values are copied on assignment - later writes do not reach other names or the input +"b = a; a = 5; b";{a: {x: 1}};{x: 1} +"b = a; a.c = 1; b";{a: {x: 1}};{x: 1} +"x.y = 1; z = x; x.w = 2; z";{};{y: 1} +"b = list; list = map(list, 0); b";{list: [1, 2]};[1, 2] +"f = map(list, #); list = [9]; f";{list: [1, 2]};[1, 2] +"b = a; b.c = 1; a";{a: {x: 1}};{x: 1};bug: b.c = 1 mutates the object shared with a (and the caller's input) in place +"b = a; b.c = 1; a";{a: {}};{};bug: b.c = 1 mutates the object shared with a (and the caller's input) in place +"b = a; b.x = 2; a.x";{a: {x: 1}};1;bug: b.x = 2 overwrites a.x through the shared reference +"b = a; b.c = 1; $root";{a: {x: 1}};{a: {x: 1}, b: {c: 1, x: 1}};bug: b.c = 1 leaks into a through the shared reference +"b = a; b.c = 1";{a: {x: 1}};{b: {c: 1, x: 1}} +"b = a.x; b.z = 2; a";{a: {x: {y: 1}}};{x: {y: 1}};bug: b.z = 2 mutates the nested input object a.x in place +"c = {v: 1}; d = c; d.v = 2; c.v";{};1;bug: d.v = 2 mutates c through the shared reference +"c = {v: 1}; d = c; c.v = 2; d.v";{};1;bug: c.v = 2 mutates d through the shared reference (the reverse direction on input a does not) +"x.y = 1; z = x; z.w = 2; x";{};{y: 1};bug: z.w = 2 mutates x through the shared reference while x.w = 2 does not reach z +"x.y = 1; z = x; z.w = 2; $root";{};{x: {y: 1}, z: {w: 2, y: 1}};bug: z.w = 2 leaks into x through the shared reference +# Parenthesized statement sequences +"(t = 1; t + 1)";{};2 +"(t = 1; t + 1) * 10";{};20 +"1 + (t = 1; t)";{};2 +"(a = 1; b = 2; a + b)";{};3 +"x = (y = 1; z = 2; y + z); x";{};3 +"x = 1; y = (z = 2; z + x)";{};{x: 1, y: 3} +"(t = 1)";{};!error +"x = (y = 1; z = 2); x";{};!error +"(t = 1; t + 1); t";{};!error;question: a program cannot begin with a parenthesized sequence followed by more statements diff --git a/core/expression/tests/spec/standard/04-index.csv b/core/expression/tests/spec/standard/04-index.csv new file mode 100644 index 00000000..51347c5b --- /dev/null +++ b/core/expression/tests/spec/standard/04-index.csv @@ -0,0 +1,104 @@ +expression (string);input (json 5);output (json 5);note +# Array indexing with literal indexes +a[0];{a: [1, 2, 3]};1 +a[0];{a: ['x']};'x' +a[0];{a: [null]};null +a[0];{a: [[9]]};[9] +a[0];{a: [{b: 1}]};{b: 1} +a[0];{a: []};null +a[0];{a: null};null +a[0];{};null +a[0];;null +a[1];{a: [1, 2, 3]};2 +a[2];{a: [1, 2, 3]};3 +a[3];{a: [1, 2, 3]};null +a[100];{a: [1, 2, 3]};null +# Indexing a non-array value is null +a[0];{a: 5};null +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: 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 +# Dynamic indexes +a[i];{a: [10, 20, 30], i: 0};10 +a[i];{a: [10, 20, 30], i: 2};30 +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: 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[b[0]];{a: [10, 20], b: [1]};20 +a[a[0]];{a: [2, 0, 9]};9 +# Decimal indexes are truncated +a[1.5];{a: [1, 2, 3]};2;question: a fractional index truncates to 1 instead of being null or an error +a[1.0];{a: [1, 2, 3]};2 +a[1.00];{a: [1, 2, 3]};2 +a[0.9];{a: [1, 2, 3]};1;question: a fractional index truncates to 0 instead of being null or an error +a[i];{a: [1, 2, 3], i: 1.5};2;question: a fractional index truncates to 1 instead of being null or an error +a[i];{a: [1, 2, 3], i: 2.999};3;question: a fractional index truncates to 2 instead of being null or an error +# Chained indexing and member access +a[0].x;{a: [{x: 1}]};1 +a[0].x;{a: [{y: 1}]};null +a[0].x;{a: []};null +a[0].x;{a: [5]};null +a[0].x;{a: null};null +a[0].x;{};null +a[1][0];{a: [[1], [2, 3]]};2 +a[1][1];{a: [[1], [2, 3]]};3 +a[1][5];{a: [[1], [2, 3]]};null +a[0][0][0];{a: [[[7]]]};7 +a.b[1].c;{a: {b: [{c: 1}, {c: 2}]}};2 +a.b[1].c;{a: {b: [{c: 1}]}};null +a.b[1].c;{a: {b: null}};null +a.b[1].c;{a: {b: 'xy'}};null +a.b[1].c;{a: null};null +a.b[0].c[1].d;{a: {b: [{c: [{d: 1}, {d: 2}]}]}};2 +a[0]['x'];{a: [{x: 'bx'}]};'bx' +a[0][k];{a: [{x: 'kx'}], k: 'x'};'kx' +a['0'];{a: [1, 2, 3]};null +a[0] + a[1];{a: [1, 2]};3 +a[0] ?? 'none';{a: []};'none' +a[0] ?? 'none';{a: [0]};0 +# String indexing selects one character +s[0];{s: 'hello'};'h' +s[1];{s: 'hello'};'e' +s[4];{s: 'hello'};'o' +s[5];{s: 'hello'};null +s[0];{s: ''};null +s[0];{s: 'a'};'a' +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.5];{s: 'hello'};'e';question: a fractional string index truncates +s['0'];{s: 'hello'};null +s.x;{s: 'hello'};null +# String indexing is by character, not by UTF-8 byte +s[0];{s: 'żółw'};'ż';bug: string indexing uses UTF-8 byte offsets so any multi-byte character reads as null +s[1];{s: 'żółw'};'ó';bug: string indexing uses UTF-8 byte offsets instead of characters +s[3];{s: 'żółw'};'w';bug: string indexing uses UTF-8 byte offsets instead of characters +s[i];{s: 'żółw', i: 0};'ż';bug: string indexing uses UTF-8 byte offsets instead of characters +s[i];{s: 'żółw', i: 2};'ł';bug: string indexing uses UTF-8 byte offsets instead of characters +s[0];{s: '😀x'};'😀';bug: string indexing uses UTF-8 byte offsets instead of characters +s[1];{s: '😀x'};'x';bug: string indexing uses UTF-8 byte offsets instead of characters +s[1];{s: '日本語'};'本';bug: string indexing uses UTF-8 byte offsets instead of characters +s[4];{s: 'żółw'};null +a[0][0];{a: ['xyz']};'x' +a.b[0];{a: {b: 'bc'}};'b' diff --git a/core/expression/tests/spec/standard/04-scoping.csv b/core/expression/tests/spec/standard/04-scoping.csv new file mode 100644 index 00000000..e828b44d --- /dev/null +++ b/core/expression/tests/spec/standard/04-scoping.csv @@ -0,0 +1,190 @@ +expression (string);input (json 5);output (json 5);note +# Intended model: one program-level environment (input + top-level assignments). A closure body runs once per element +# and assignments made inside it are local to that iteration: they shadow outer names, do not persist to the next +# iteration and are not visible after the closure returns. Top-level parenthesized sequences have no scope of their own. +# Closures read top-level assignments +"x = 10; y = filter(list, #.y > x); y";{list: [{y: 5}, {y: 15}, {y: 20}]};[{y: 15}, {y: 20}] +"x = 10; y = filter(list, #.y > x); y";{list: []};[] +"x = 10; y = filter(list, #.y > x); y";{list: [{y: 10}]};[] +"x = 10; y = filter(list, #.y > x); y";{list: [{}, {y: 11}]};!error +"x = 10; y = filter(list, #.y > x); y";{list: null};!error +"x = 10; y = filter(list, #.y > x); len(y)";{list: [{y: 5}, {y: 15}, {y: 20}]};2 +"x = 10; y = filter(list, #.y > x)";{list: [{y: 5}, {y: 15}, {y: 20}]};{x: 10, y: [{y: 15}, {y: 20}]} +"x = 10; y = filter(list, #.y > x); z = map(y, #.y + x); z";{list: [{y: 5}, {y: 15}, {y: 20}]};[25, 30] +"x = 10; y = filter(list, #.y > x); z = map(y, #.y + x); z";{list: [{y: 11}]};[21] +"x = 10; y = filter(list, #.y > x); z = map(y, #.y + x); z";{list: [{y: 1}]};[] +"x = 10; y = filter(list, #.y > x); z = map(y, #.y + x); [x, y, z]";{list: [{y: 12}], x: 0};[10, [{y: 12}], [22]] +"x = 5; map(list, # + x)";{list: [1, 2]};[6, 7] +"x = 5; map(list, # + x)";{list: []};[] +"x = 5; map(list, # + x)";{list: [0.5]};[5.5] +"x = 5; map(list, # + x)";{list: [1], x: 100};[6] +"x = 1; map(list, x)";{list: [1, 2]};[1, 1] +"x = 1; map(list, #.x)";{list: [{x: 5}, {x: 6}]};[5, 6] +"x = 1; map(list, #.x + x)";{list: [{x: 5}, {x: 6}]};[6, 7] +"x.y = 3; map(list, # * x.y)";{list: [1, 2]};[3, 6] +"limit = 2; cnt = count(list, # > limit); cnt";{list: [1, 5, 10], limit: 4};2 +"limit = 2; cnt = count(list, # > limit); cnt";{list: [1, 5, 10]};2 +"limit = 2; cnt = count(list, # > limit); cnt";{list: [], limit: 4};0 +"cnt = count(list, # > limit); cnt";{list: [1, 5, 10], limit: 4};2 +"cnt = count(list, # > limit); cnt";{list: [1, 5, 10], limit: 0};3 +"cnt = count(list, # > limit); cnt";{list: [1, 5, 10]};!error +"t = 3; [some(list, # > t), all(list, # > t), none(list, # > t), one(list, # > t), count(list, # > t)]";{list: [1, 5]};[true, false, false, true, 1] +"t = 3; [some(list, # > t), all(list, # > t), none(list, # > t), one(list, # > t), count(list, # > t)]";{list: [4, 5]};[true, true, false, false, 2] +"t = 3; [some(list, # > t), all(list, # > t), none(list, # > t), one(list, # > t), count(list, # > t)]";{list: []};[false, true, true, false, 0] +"t = 3; flatMap(list, [#, # * t])";{list: [1, 2]};[1, 3, 2, 6] +# Element fields versus variables of the same name +map(list, x);{list: [{x: 5}], x: 9};[9] +map(list, #.x);{list: [{x: 5}], x: 9};[5] +map(list, #.x + x);{list: [{x: 5}, {x: 1}], x: 9};[14, 10] +"x = 10; y = filter(list, #.x > x); y";{list: [{x: 5}, {x: 15}]};[{x: 15}] +"x = 10; y = filter(list, #.x > x); y";{list: [{x: 10}]};[] +"x = 10; y = filter(list, #.x > x); y";{list: [{x: 11}], x: 100};[{x: 11}] +# Closures capture the current value - reassignment between closures +"x = 5; a = map(list, # + x); x = 100; b = map(list, # + x); [a, b]";{list: [1, 2]};[[6, 7], [101, 102]] +"x = 5; a = map(list, # + x); x = 100; b = map(list, # + x); [a, b]";{list: []};[[], []] +"n = 2; r = map(list, # * n); n = 3; r2 = map(list, # * n); [r, r2]";{list: [1, 2]};[[2, 4], [3, 6]] +"y = 1; x = map(list, # + y); y = 2; x";{list: [1]};[2] +"a = 1; a = map(list, # + a); a";{list: [1, 2]};[2, 3] +"list = map(list, # * 2); list";{list: [1, 2]};[2, 4] +"list = map(list, # * 2); list";{list: []};[] +"list = map(list, # * 2)";{list: [1, 2]};{list: [2, 4]} +"list = filter(list, # > 1); list";{list: [1, 2]};[2] +"list = filter(list, # > 1); list = map(list, # * 10); list";{list: [1, 2, 3]};[20, 30] +# Aliases +"x = 10; y = filter(list as x, x.y > 10); x";{list: [{y: 5}, {y: 15}]};10 +"x = 10; y = filter(list as x, x.y > 10); y";{list: [{y: 5}, {y: 15}]};[{y: 15}] +"x = 10; y = map(list as x, x.y); y";{list: [{y: 5}, {y: 15}]};[5, 15] +"x = 10; y = map(list as x, x); y";{list: [{y: 5}, {y: 15}]};[{y: 5}, {y: 15}] +"x = 5; map(list as x, x + 1)";{list: [1, 2]};[2, 3] +"x.y = 3; map(list as x, x.y)";{list: [{y: 1}]};[1] +"x.y = 3; map(list as x, x.y)";{list: [{}]};[null] +map(list as x, x + 1);{list: [1, 2], x: 100};[2, 3] +map(list as x, x);{list: [], x: 100};[] +map(list as p, p.v);{list: [{v: 1}, {v: 2}], p: {v: 9}};[1, 2] +map(a as o, map(o.items as o, o + 1));{a: [{items: [1, 2]}, {items: [3]}]};[[2, 3], [4]] +map(a as o, map(o.items as i, i + len(o.items)));{a: [{items: [1, 2]}, {items: [3]}]};[[3, 4], [4]] +map(a as o, map(o.items, # + o.k));{a: [{k: 100, items: [1, 2]}, {k: 200, items: [3]}]};[[101, 102], [203]] +map(a as o, map(o.items, # + o.k));{a: []};[] +map(a as o, map(o.items, # + o.k));{a: [{k: 1, items: []}]};[[]] +map(a, map(#.items, # + 1));{a: [{items: [1, 2]}, {items: [3]}]};[[2, 3], [4]] +map(a as o, filter(o.items as i, i > o.min));{a: [{min: 1, items: [1, 2]}, {min: 0, items: [0, 5]}]};[[2], [5]] +map(a as o, map(o.items as i, map(i.v as j, j + i.k + o.k)));{a: [{k: 100, items: [{k: 10, v: [1, 2]}]}]};[[[111, 112]]] +# Nested closures and # +map(list, filter(list, # > 1));{list: [1, 2, 3]};[[2, 3], [2, 3], [2, 3]] +map(list as o, filter(list, # > o));{list: [1, 2, 3]};[[2, 3], [3], []] +map(list as o, count(list, # < o));{list: [3, 1, 2]};[2, 0, 1] +# Assignments inside closure bodies are local to the iteration +"map(list, (z = #; z * 2))";{list: [5, 6]};[10, 12] +"map(list, (z = #; z * 2))";{list: []};[] +"map(list, (z = #; z * 2))";{list: [0.5]};[1] +"map(list as p, (t = p.v; t * 2))";{list: [{v: 1}, {v: 2}]};[2, 4] +"map(list, (t = #; map(t.items, # + t.k)))";{list: [{k: 10, items: [1, 2]}]};[[11, 12]] +"map(list, (z = #; map([1, 2], z + #)))";{list: [10, 20]};[[11, 12], [21, 22]] +"map(list, (z = #; map([1, 2], (w = # * z; w))))";{list: [10, 20]};[[10, 20], [20, 40]] +"map(a as o, (t = o; map(o.items as i, (u = i; t.k + u))))";{a: [{k: 10, items: [1, 2]}, {k: 20, items: [3]}]};[[11, 12], [23]] +"map(list, (y = #.y * 2; #.y + y))";{list: [{y: 1}, {y: 2}]};[3, 6] +"y = 100; map(list, (y = #.y * 2; #.y + y))";{list: [{y: 1}, {y: 2}]};[3, 6] +"map(list, (i = #; filter(list, # > i)))";{list: [1, 2, 3]};[[2, 3], [3], []] +"map(list, (i = #; r = map(list, # * 10); [i, r]))";{list: [1, 2]};[[1, [10, 20]], [2, [10, 20]]] +"filter(list, (lim = 2; # > lim))";{list: [1, 2, 3]};[3] +"some(list, (t = #; t > 1))";{list: [1, 2, 3]};true +"all(list, (t = #; t > 0))";{list: [1, 2, 3]};true +"count(list, (t = #; t > 1))";{list: [1, 2, 3]};2 +"one(list, (t = #; t > 2))";{list: [1, 2, 3]};true +"none(list, (t = #; t > 5))";{list: [1, 2, 3]};true +"flatMap(list, (t = #; [t, t]))";{list: [1, 2]};[1, 1, 2, 2] +"x = map(list, (list = [9]; #)); x";{list: [1, 2]};[1, 2] +"list = map(list, (list = 0; #)); list";{list: [1, 2]};[1, 2] +"x = 10; y = map(list, (x = #.y; x)); y";{list: [{y: 1}, {y: 2}]};[1, 2] +"x = 10; y = map(list, (x = #.y; x))";{list: [{y: 1}, {y: 2}]};{x: 10, y: [1, 2]} +"y = map(list, (t = #.y; t))";{list: [{y: 1}, {y: 2}]};{y: [1, 2]} +# ... they must not leak out of the closure +"x = 10; y = map(list, (x = #.y; x)); x";{list: [{y: 1}, {y: 2}]};10;bug: an assignment inside the closure body overwrites the outer x (reads back the last element) +"x = 10; y = map(list, (x = #.y; x)); x";{list: [{y: 7}]};10;bug: an assignment inside the closure body overwrites the outer x +"x = 10; y = map(list, (x = #.y; x)); x";{list: []};10 +"x = 10; y = map(list, (x = #.y; x)); [x, y]";{list: [{y: 1}, {y: 2}]};[10, [1, 2]];bug: the returned object says x = 10 but reading x gives the closure's last value +"y = map(list, (t = #.y; t)); t";{list: [{y: 1}, {y: 2}]};null;bug: t assigned inside the closure leaks to the outer scope as the last element's value +"y = map(list, (t = #.y; t)); t";{list: [{y: 3}]};null;bug: t assigned inside the closure leaks to the outer scope +"y = map(list, (t = #.y; t)); t";{list: []};null +"y = map(list, (t = #.y; t)); $root";{list: [{y: 1}, {y: 2}]};{list: [{y: 1}, {y: 2}], y: [1, 2]};bug: $root contains t although the returned object does not +"y = map([], (t = 1; t)); t";{};null +"y = some([1, 2, 3], (t = #; # == 2)); t";{};null;bug: t leaks and its value depends on where some() short-circuits (2) +"y = all([1, 2, 3], (t = #; # < 2)); t";{};null;bug: t leaks and its value depends on where all() short-circuits (2) +"y = count([1, 2, 3], (t = #; # > 1)); t";{};null;bug: t leaks out of count() +"y = none([1, 2, 3], (t = #; # > 5)); t";{};null;bug: t leaks out of none() +"y = one([1, 2, 3], (t = #; # == 2)); t";{};null;bug: t leaks out of one() +"y = flatMap([[1], [2, 3]], (t = #; #)); t";{};null;bug: t leaks out of flatMap() +"y = filter(list, (lim = 2; # > lim)); lim";{list: [1, 2, 3]};null;bug: lim leaks out of filter() +"a = map(list, (t = #; t)); b = map(list2, (t = # * 10; t)); [a, b, t]";{list: [1, 2], list2: [3]};[[1, 2], [30], null];bug: t from the second closure leaks to the outer scope +"a = map(list, (t = #; t)); b = map(list2, t); [a, b]";{list: [1, 2], list2: [3]};[[1, 2], [null]];bug: t from the first closure is visible inside a later, unrelated closure +"sum(map(list, (t = # * 2; t))) + (t ?? 0)";{list: [1, 2]};6;bug: t leaks out of map() into the enclosing expression +"sum(map(list, (x = #; x))) + (x ?? 0)";{list: [1, 2]};3;bug: x leaks out of map() into the enclosing expression +# ... they must not persist from one iteration to the next +"y = map([1, 2, 3], (s = (s ?? 0) + #; s)); y";{};[1, 2, 3];bug: s carries over between iterations making map() a running sum +"y = map(list, (s = (s ?? 0) + #; s)); y";{list: [5, 5]};[5, 5];bug: s carries over between iterations +"y = map(list, (s = (s ?? 0) + #; s)); y";{list: [5, 5], s: 100};[105, 105];bug: s carries over between iterations instead of starting from the outer s +"x = 1; map(list, (x = x * 10; x))";{list: [1, 2]};[10, 10];bug: each iteration should start from the outer x = 1 but sees the previous iteration's x +"map(list, (x = x * 10; x))";{list: [1, 2], x: 1};[10, 10];bug: each iteration should start from the input x = 1 +"map(list, (x = x * 10; x))";{list: [1, 2, 3], x: 2};[20, 20, 20];bug: each iteration should start from the input x = 2 +"r = map(list, (x = x * 10; x)); x";{list: [1, 2], x: 1};1;bug: the closure overwrites input x (100) +"x = 1; y = map(list, (x = x * 10; x)); x";{list: [1, 2]};1;bug: the closure overwrites the outer x (100) +"x = 0; y = map(list, (x = x + #; x)); [x, y]";{list: [1, 2, 3]};[0, [1, 2, 3]];bug: x accumulates across iterations and leaks out +"x = 0; y = sum(map(list, (x = x + #; 0))); x";{list: [1, 2, 3]};0;bug: x accumulates across iterations and leaks out +"x = 3; r = filter(list, (x = x + 1; # > x)); [r, x]";{list: [1, 5, 9]};[[5, 9], 3];bug: x is incremented once per iteration and leaks out +"n = 0; r = some(list, (n = n + 1; # == 2)); n";{list: [1, 2, 3]};0;bug: a closure body counts iterations into the outer n +"n = 0; r = all(list, (n = n + 1; # < 2)); n";{list: [1, 2, 3]};0;bug: a closure body counts iterations into the outer n +"n = 0; r = count(list, (n = n + 1; true)); [r, n]";{list: [1, 2, 3]};[3, 0];bug: a closure body counts iterations into the outer n +# ... and an inner closure must not clobber an outer iteration's local +"map(list, (i = #; r = map(list, (i = # * 10; i)); i))";{list: [1, 2]};[1, 2];bug: the inner closure's i overwrites the outer iteration's i (gives [20, 20]) +"map(list, (i = #; r = map(list, (i = # * 10; i)); i))";{list: [3]};[3];bug: the inner closure's i overwrites the outer iteration's i +"map(list, (i = #; map(list, (i = # * 10; i))))";{list: [1, 2]};[[10, 20], [10, 20]] +"map(list, (i = #; count(list, (i = i; # > i))))";{list: [1, 2, 3]};[2, 1, 0] +"map(list, (i = #; r = map(list, (j = # * 10; j)); i + j))";{list: [1, 2]};!error;bug: j is local to the inner closure so i + j reads null (currently j leaks as 20 giving [21, 22]) +"map([1, 2], (x = #; map([10, 20], (x = x + #; x))))";{};[[11, 21], [12, 22]];bug: the inner closure's x persists across inner iterations +# Assigning to an alias name inside the closure body +"map(list as x, (x = 1; x))";{list: [5, 6]};[1, 1];bug: x = 1 then x in the same block reads the alias, so the assignment is silently ignored +"map(list as x, (x.y = 1; x))";{list: [{y: 5}]};[{y: 5}];question: a dotted assignment to an alias writes a same-named outer variable and the alias is unchanged +"map(list as x, (z = x; z))";{list: [5, 6]};[5, 6] +"map(list as x, (z = x; z)); z";{list: [5, 6]};!error;question: a program cannot begin with a closure call followed by more statements +# Assignments inside closures must not mutate elements of the input +"y = map(list, (t = #; t.k = 1; t)); y";{list: [{a: 1}, {a: 2}]};[{a: 1, k: 1}, {a: 2, k: 1}] +"y = map(list, (t = #; t.k = 1; t)); list";{list: [{a: 1}, {a: 2}]};[{a: 1}, {a: 2}];bug: t.k = 1 writes through t into the input element (the caller's input is mutated) +"y = map(list, (t = #; t.k = 1; t)); list";{list: [{a: 1}]};[{a: 1}];bug: t.k = 1 writes through t into the input element +"y = map(list, (t = #; t.k = 1; t)); list";{list: []};[] +"y = map(list, (t.k = #; t)); y";{list: [1, 2]};[{k: 1}, {k: 2}] +# Parenthesized sequences outside closures share the program environment +"(t = 1; t + 1) + t";{};3;question: a parenthesized sequence has no scope of its own so t stays visible after it +"[(t = 1; t), t]";{};[1, 1];question: a parenthesized sequence has no scope of its own +"{a: (t = 1; t), b: t}";{};{a: 1, b: 1};question: a parenthesized sequence has no scope of its own +"`${(t = 5; t)}-${t}`";{};'5-5';question: a parenthesized sequence inside a template has no scope of its own +"(a = 1; a) + (a = 2; a)";{};3 +"[(a = 1; a), (a = a + 1; a), a]";{};[1, 2, 2];question: sequences inside an array literal share one environment +"{x: (a = 1; a), y: (a = 2; a)}";{};{x: 1, y: 2} +"a = 1; b = (a = 5; a); [a, b]";{};[5, 5];question: a nested sequence rebinds the outer a +"x = ((y = 1; y) + (y = 2; y)); [x, y]";{};[3, 2];question: nested sequences rebind y in the program environment +"x = 1; y = (z = 2; z + x); [x, y, z]";{};[1, 3, 2];question: z from a nested sequence is visible at the top level +"x = 1; y = (z = 2; z + x)";{};{x: 1, y: 3} +"x = 1; y = (z = 2; z + x); $root";{};{x: 1, y: 3, z: 2};question: $root contains z although the returned object does not +# Assignments inside ternary branches +"true ? (t = 1; t) : (t = 2; t)";{};1 +"false ? (t = 1; t) : (t = 2; t)";{};2 +"c ? (t = 'yes'; t) : (t = 'no'; t)";{c: true};'yes' +"c ? (t = 'yes'; t) : (t = 'no'; t)";{c: false};'no' +"c ? (t = 'yes'; t) : (t = 'no'; t)";{c: null};!error +"c ? (t = 'yes'; t) : (t = 'no'; t)";{};!error +"r = c ? (t = 1; t) : 0; r";{c: true};1 +"r = c ? (t = 1; t) : 0; r";{c: false};0 +"r = c ? (t = 1; t) : 0; t";{c: false};null +"r = c ? (t = 1; t) : 0; t";{c: true};1;question: t assigned inside the taken branch is visible after the program-level ternary +# Assignments inside closures combined with ternaries, templates, objects +"map(list, # + (n = 1; n))";{list: [1, 2]};[2, 3] +"map(list, (n = #; n) + (n = 10; n))";{list: [1, 2]};[11, 12] +"map(list, `${(n = #; n)}`)";{list: [1, 2]};['1', '2'] +"map(list, {v: (n = #; n), w: n})";{list: [1, 2]};[{v: 1, w: 1}, {v: 2, w: 2}];question: a sequence inside an object literal leaks n to a sibling property in the same iteration +"map(list, # > 1 ? (n = 'big'; n) : (n = 'small'; n))";{list: [1, 2]};['small', 'big'] +"map(list, #.x ?? (n = 0; n))";{list: [{x: 1}, {}]};[1, 0] +# Reading a name before it is assigned +"x = y + 1; y = 5; x";{y: 1};2 +"x = y + 1; y = 5; [x, y]";{y: 1};[2, 5] +"x = y; y = 5; x";{};null +"x = y; y = 5; x";{y: 'in'};'in' diff --git a/core/expression/tests/spec/standard/04-slices.csv b/core/expression/tests/spec/standard/04-slices.csv new file mode 100644 index 00000000..7626b6ff --- /dev/null +++ b/core/expression/tests/spec/standard/04-slices.csv @@ -0,0 +1,97 @@ +expression (string);input (json 5);output (json 5);note +# Array slices: both bounds are inclusive in the VM and in the repo tests +a[1:3];{a: [0, 1, 2, 3, 4]};[1, 2, 3];question: docs (syntax page) describe string[0:5] as the first 5 characters (end exclusive) but the VM and repo tests treat the end as inclusive +a[:2];{a: [0, 1, 2, 3, 4]};[0, 1, 2];question: docs describe [:5] as the first 5 elements (end exclusive) but the VM includes index 2 +a[2:];{a: [0, 1, 2, 3, 4]};[2, 3, 4] +a[:];{a: [0, 1, 2, 3, 4]};[0, 1, 2, 3, 4] +a[0:0];{a: [0, 1, 2, 3, 4]};[0];question: with inclusive bounds [0:0] is one element, with exclusive bounds it would be empty +a[4:4];{a: [0, 1, 2, 3, 4]};[4] +a[0:4];{a: [0, 1, 2, 3, 4]};[0, 1, 2, 3, 4] +a[4:];{a: [0, 1, 2, 3, 4]};[4] +a[5:];{a: [0, 1, 2, 3, 4]};[] +a[1 : 2];{a: [5, 6, 7]};[6, 7] +a[1:3];{a: ['a', 'b', 'c', 'd']};['b', 'c', 'd'] +a[0:1];{a: [{x: 1}, {x: 2}, {x: 3}]};[{x: 1}, {x: 2}] +a[0:1];{a: [null, null]};[null, null] +# Reversed bounds give an empty slice +a[2:1];{a: [0, 1, 2, 3, 4]};[] +a[3:1];{a: [0, 1, 2, 3, 4]};[];bug: reversed bounds error when from exceeds to by more than one while [2:1] gives [] +a[4:0];{a: [0, 1, 2, 3, 4]};[];bug: reversed bounds error while [2:1] gives [] +# Out-of-range bounds +a[0:10];{a: [0, 1, 2, 3, 4]};!error;question: an end past the array errors while a start past the end ([5:]) yields [] - clamp or error? +a[0:5];{a: [0, 1, 2, 3, 4]};!error;question: an end equal to len errors under inclusive bounds - clamp or error? +a[6:];{a: [0, 1, 2, 3, 4]};!error;question: a start two past the end errors while [5:] yields [] +# Empty arrays +a[:];{a: []};[];bug: a full slice of an empty array errors because the implicit end len-1 is -1 +a[0:];{a: []};[];bug: an open-ended slice of an empty array errors because the implicit end len-1 is -1 +a[:0];{a: []};!error;question: under inclusive bounds [:0] names index 0 which does not exist - clamp or error? +# Negative bounds +a[-2:];{a: [0, 1, 2, 3, 4]};!error;question: negative indexing is documented for items[-1] but negative slice bounds fail to convert +a[:-2];{a: [0, 1, 2, 3, 4]};!error;question: negative indexing is documented for items[-1] but negative slice bounds fail to convert +a[-3:-2];{a: [0, 1, 2, 3, 4]};!error;question: negative indexing is documented for items[-1] but negative slice bounds fail to convert +a[:i];{a: [5, 6, 7], i: -1};!error;question: negative indexing is documented for items[-1] but negative slice bounds fail to convert +# Decimal bounds are truncated +a[1.5:3];{a: [0, 1, 2, 3, 4]};[1, 2, 3];question: fractional slice bounds truncate +a[0:1.9];{a: [0, 1, 2, 3, 4]};[0, 1];question: fractional slice bounds truncate +# Dynamic bounds +a[i:j];{a: [0, 1, 2, 3, 4], i: 1, j: 2};[1, 2] +a[i:j];{a: [0, 1, 2, 3, 4], i: 0, j: 0};[0] +a[i:j];{a: [0, 1, 2, 3, 4], i: 3, j: 4};[3, 4] +a[i:j];{a: [0, 1, 2, 3, 4], i: 2, j: 1};[] +a[i:j];{a: [0, 1, 2, 3, 4], i: null, j: 2};!error +a[i:j];{a: [0, 1, 2, 3, 4], i: '1', j: 2};!error +a[i:j];{a: [0, 1, 2, 3, 4], j: 2};!error +a[i:];{a: [5, 6, 7], i: 0};[5, 6, 7] +a[i:];{a: [5, 6, 7], i: 2};[7] +a[i:];{a: [5, 6, 7], i: 3};[] +a[:j];{a: [5, 6, 7], j: 0};[5] +a[:j];{a: [5, 6, 7], j: 1};[5, 6] +a[len(a)-2:];{a: [5, 6, 7]};[6, 7] +a[len(a)-2:];{a: [5, 6, 7, 8]};[7, 8] +a[1:len(a)-1];{a: [5, 6, 7, 8]};[6, 7, 8] +# Slicing non-sequence values +a[1:2];{a: null};!error;question: slicing null errors while indexing and member access on null yield null +a[1:2];{};!error;question: slicing a missing value errors while indexing a missing value yields null +a[1:2];{a: 5};!error +a[1:2];{a: true};!error +a[1:2];{a: {x: 1}};!error +a[:];{a: null};!error;question: slicing null errors while indexing null yields null +# Slices compose with other postfix operators +a[1:3][0];{a: [0, 1, 2, 3, 4]};1 +a[1:3][2];{a: [0, 1, 2, 3, 4]};3 +a[1:3][3];{a: [0, 1, 2, 3, 4]};null +a[1:3].x;{a: [0, 1, 2, 3, 4]};null +a.b[0:1];{a: {b: [5, 6, 7]}};[5, 6] +a[0:1][0:0];{a: [5, 6, 7]};[5] +a[1:][0].x;{a: [{x: 1}, {x: 2}]};2 +len(a[1:]);{a: [5, 6, 7]};2 +sum(a[0:1]);{a: [100, 200, 300]};300 +[1, 2, 3][0:1];;[1, 2] +[1, 2, 3][1:];;[2, 3] +'hello'[0:1];;!error;question: slicing a string literal is a parse error while array literals allow it +# String slices +s[0:2];{s: 'hello'};'hel' +s[1:];{s: 'hello'};'ello' +s[:1];{s: 'hello'};'he' +s[:];{s: 'hello'};'hello' +s[0:4];{s: 'hello'};'hello' +s[4:4];{s: 'hello'};'o' +s[5:];{s: 'hello'};'' +s[2:1];{s: 'hello'};'' +s[0:5];{s: 'hello'};!error;question: an end equal to the length errors - clamp or error? +s[0:5];{s: 'sample_string'};'sample' +s[7:12];{s: 'sample_string'};'string' +s[7:];{s: 'sample_string'};'string' +s[:5];{s: 'sample_string'};'sample' +s[:];{s: ''};'';bug: a full slice of an empty string errors because the implicit end len-1 is -1 +s[i:j];{s: 'hello', i: 1, j: 3};'ell' +s[i:j];{s: 'hello', i: null, j: 3};!error +s[1:2];{s: null};!error;question: slicing null errors while indexing null yields null +# String slices are by character, not by UTF-8 byte +s[0:1];{s: 'żółw'};'żó';bug: string slices use UTF-8 byte offsets - [0:1] happens to be the 2-byte 'ż' instead of two characters +s[1:];{s: 'żółw'};'ółw';bug: string slices use UTF-8 byte offsets so a start inside a multi-byte character errors +s[0:0];{s: 'żółw'};'ż';bug: string slices use UTF-8 byte offsets so an end inside a multi-byte character errors +s[1:2];{s: 'żółw'};'ół';bug: string slices use UTF-8 byte offsets instead of characters +s[:];{s: 'żółw'};'żółw' +s[2:3];{s: 'ab😀c'};'😀c';bug: string slices use UTF-8 byte offsets so a 4-byte emoji cannot be sliced by character +s[0:1];{s: '日本語'};'日本';bug: string slices use UTF-8 byte offsets instead of characters diff --git a/core/expression/tests/spec/standard/05-closures-basic.csv b/core/expression/tests/spec/standard/05-closures-basic.csv new file mode 100644 index 00000000..9886f84c --- /dev/null +++ b/core/expression/tests/spec/standard/05-closures-basic.csv @@ -0,0 +1,237 @@ +expression (string);input (json 5);output (json 5);note +# map: element transformation, one result per element, order preserved +map([1, 2, 3], # * 2);;[2, 4, 6] +map([], # * 2);;[] +map([7], # + 1);;[8] +map([1, 2, 3], #);;[1, 2, 3] +map([1, 2], 'x');;['x', 'x'] +map([1, 2], null);;[null, null] +map([1, 2], 5);;[5, 5] +map([1, 'a', true, null], #);;[1, 'a', true, null] +map([1, 'a', true, null, [1], {a: 1}], type(#));;['number', 'string', 'bool', 'null', 'array', 'object'] +map([1, null, 3], # ?? 0);;[1, 0, 3] +map([1, null, 3], # * 2);;!error +map([1, 2, 3], # > 1 ? 'big' : 'small');;['small', 'big', 'big'] +map([1, 2, 3], # == 2 ? 'x' : null);;[null, 'x', null] +map([0.1, 0.2], # + 0.1);;[0.2, 0.3] +map([1.5, 2.25, -0.10], # * 2);;[3, 4.5, -0.2] +map([1.5, 2.25, -0.10], string(# * 2));;['3.0', '4.50', '-0.20'] +map(['a', 'b', 'c'], # + '!');;['a!', 'b!', 'c!'] +map(['héllo', '日本', ''], upper(#));;['HÉLLO', '日本', ''] +map([true, false], not #);;[false, true] +map([[1, 2], [], [3]], len(#));;[2, 0, 1] +map([[1, 2], [3]], #);;[[1, 2], [3]] +map([{a: 1}, {a: 2}], #);;[{a: 1}, {a: 2}] +map([{a: 1}, {b: 2}], #.a);;[1, null] +map([{a: {b: 1}}, {a: null}, {}], #.a.b);;[1, null, null] +map([1, 2], [#, # * 10]);;[[1, 10], [2, 20]] +map([1, 2], {v: #});;[{v: 1}, {v: 2}] +map([1, 2], {v: #, [string(#)]: # * 2});;[{v: 1, '1': 2}, {v: 2, '2': 4}] +map([1, 2], `n${#}`);;['n1', 'n2'] +map([d('2024-01-01'), d('2024-01-02')], #.day());;[1, 2] +map([1, 0, 2], 1 / #);;[1, null, 0.5];question: division by zero inside a closure yields null (not an error); see operators chapter +map([1, 2, 3], # % 2 == 0);;[false, true, false] +# map: non-list first argument +map(null, #);;!error;question: a null list is an error rather than an empty list +map(5, #);;!error +map('abc', #);;!error +map(true, #);;!error +map({a: 1}, #);;!error +map(d('2024-01-01'), #);;!error +# map: parse errors +map([1, 2]);;!error +map();;!error +map([1, 2], #, 3);;!error +map([1, 2], # , );;!error +map([1, 2] as, #);;!error +map([1, 2] as 1, #);;!error +# map: element errors propagate +map([1, 'a', 3], # * 2);;!error +map([1, 2, 'a'], # * 2);;!error +map(['a', 1], upper(#));;!error +# filter: keeps elements whose predicate is true, preserves order and values +filter([1, 2, 3, 4, 5], # > 3);;[4, 5] +filter([], # > 3);;[] +filter([4], # > 3);;[4] +filter([1], # > 3);;[] +filter([1, 2, 3], true);;[1, 2, 3] +filter([1, 2, 3], false);;[] +filter([true, false, true], #);;[true, true] +filter([1, null, 3], # != null);;[1, 3] +filter([1, 'a', true, null], # == 'a');;['a'] +filter([1, 'a', true, null], type(#) == 'number');;[1] +filter([1.5, 2.25, -0.10], # < 2);;[1.5, -0.10] +filter(['a', 'b', 'c', 'd'], # in ['a', 'c']);;['a', 'c'] +filter(['héllo', 'abc', 'hé'], startsWith(#, 'h'));;['héllo', 'hé'] +filter([{a: 1}, {a: null}, {}], #.a != null);;[{a: 1}] +filter([{id: 1}, {id: 2}], #.id > 1);;[{id: 2}] +filter([[1, 2], [3]], len(#) > 1);;[[1, 2]] +filter([[1, 2], [3]], some(#, # > 2));;[[3]] +filter([1, 2, 3], not (# == 2));;[1, 3] +filter([1, 2, 3], !(# == 2));;[1, 3] +filter([d('2024-01-01'), d('2024-03-02')], #.month() > 1);;['2024-03-02T00:00:00Z'] +# filter: predicate must be boolean +filter([1, 2], 1);;!error +filter([1, 2], 'yes');;!error +filter([1, 2], null);;!error;question: a null predicate is an error, not treated as false +filter([1, null, 3], #);;!error +filter([1, 2], [#]);;!error +filter([], 1);;[] +# filter: non-list first argument and element errors +filter(null, true);;!error +filter(5, true);;!error +filter('abc', true);;!error +filter({a: 1}, true);;!error +filter([1, 'a', 3], # > 1);;!error +filter([1, 0, 2], 1 / # > 0);;!error +# some: true when any element matches, stops at the first match +some([1, 2, 3], # > 2);;true +some([1, 2, 3], # > 3);;false +some([], true);;false +some([], # > 0);;false +some([5], # > 3);;true +some([1], # > 3);;false +some(['a', 'b', 'c'], # == 'b');;true +some(['a', 'b', 'c'], # == 'd');;false +some([1, 'a', null], # == null);;true +some([{a: 1}, {}], #.a == null);;true +some([[1], [2, 3]], 3 in #);;true +some([false, false], #);;false +some([false, true], #);;true +some([2, 'a'], # > 1);;true +some(['a', 2], # > 1);;!error +some([5, null], # > 3);;true +some([1, null, 5], # > 3);;!error +some([1, 2], 'a');;!error +some([false, null], #);;!error;question: a null predicate result is an error, not falsy +some(null, true);;!error +some('abc', true);;!error +some({a: 1}, true);;!error +# all: true when every element matches, stops at the first failure +all([1, 2, 3], # > 0);;true +all([1, 2, 3], # > 1);;false +all([], false);;true +all([], # > 100);;true +all([1], # > 0);;true +all([0], # > 0);;false +all(['a', 'b', 'c'], # in ['a', 'b', 'c', 'd']);;true +all(['a', 'b', 'c'], # in ['a', 'b']);;false +all([true, true], #);;true +all([true, false], #);;false +all([1, 2], # > 0 and # < 3);;true +all([{a: 1}, {a: 2}], #.a > 0);;true +all([{a: 1}, {}], #.a != null);;false +all([0, 'a'], # > 0);;false +all(['a', 0], # > 0);;!error +all([1, 'a'], # > 0);;!error +all([true, null], #);;!error;question: a null predicate result is an error, not falsy +all([1, 2], 1);;!error +all(null, true);;!error +all(5, true);;!error +# none: true when no element matches, stops at the first match +none([1, 2, 3], # > 5);;true +none([1, 2, 3], # > 2);;false +none([], true);;true +none([], # > 0);;true +none([1], # == 1);;false +none([1], # == 2);;true +none(['a', 'b'], # == 'c');;true +none([false, false], #);;true +none([true, false], #);;false +none([{a: 1}, {a: 2}], #.a > 5);;true +none([5, 'a'], # > 1);;false +none(['a', 5], # > 1);;!error +none([1, 2], 'x');;!error +none(null, true);;!error +none({a: 1}, true);;!error +# one: true when exactly one element matches +one([1, 2, 3], # == 2);;true +one([1, 2, 3], # == 5);;false +one([1, 2, 3], # > 1);;false +one([1, 2, 3], # > 0);;false +one([], true);;false +one([1], true);;true +one([1], false);;false +one([1, 1], # == 1);;false +one(['a', 'b', 'c'], # == 'c');;true +one([true, false], #);;true +one([true, true], #);;false +one([{a: 1}, {a: 2}, {}], #.a == 2);;true +one([1, 1, 'a'], # == 1);;false +one([1, 2, 'a'], # > 0);;!error;question: one() keeps evaluating after a second match, so a later erroring element fails the whole call +one(['a', 1], # > 0);;!error +one([1, 2], 1);;!error +one(null, true);;!error +one('abc', true);;!error +# count: number of matching elements +count([1, 2, 3, 4, 5, 2], # == 2);;2 +count([1, 2, 3], # > 5);;0 +count([], true);;0 +count([], # > 0);;0 +count([1], true);;1 +count([1, 2, 3], true);;3 +count([1, 2, 3], false);;0 +count([true, false, true], #);;2 +count([1, 'a', null, true], type(#) == 'string');;1 +count([{a: 1}, {a: 2}, {}], #.a != null);;2 +count([[1], [], [2, 3]], len(#) > 0);;2 +count(['héllo', 'hé', 'x'], contains(#, 'é'));;2 +count([1..10], # % 3 == 0);;3 +count([1, 2], 1);;!error +count([1, 'a'], # > 0);;!error +count([1], #);;!error +count(null, true);;!error +count({a: 1}, true);;!error +# count agrees with len of filter and with len for an always-true predicate +count([1, 2, 3, 4], # % 2 == 0) == len(filter([1, 2, 3, 4], # % 2 == 0));;true +count([1, 2, 3], true) == len([1, 2, 3]);;true +count([[1, 2, 3]], true);;1 +len([[1, 2, 3]]);;1 +# flatMap: map then flatten one level +flatMap([[1, 2], [3, 4], [5, 6]], #);;[1, 2, 3, 4, 5, 6] +flatMap([], #);;[] +flatMap([[]], #);;[] +flatMap([[], [1]], #);;[1] +flatMap([1, 2], [#, # * 10]);;[1, 10, 2, 20] +flatMap([1, 2], [#]);;[1, 2] +flatMap([1, 2], #);;[1, 2] +flatMap([1, [2, [3]]], #);;[1, 2, [3]] +flatMap([[1], [2]], [#]);;[[1], [2]] +flatMap([[1], null], #);;[1, null] +flatMap([1, 2], []);;[] +flatMap(['a', 'b'], [#, upper(#)]);;['a', 'A', 'b', 'B'] +flatMap([{t: ['a', 'b']}, {t: []}, {}], #.t);;['a', 'b', null] +flatMap([{t: ['a', 'b']}, {t: []}, {}], #.t ?? []);;['a', 'b'] +flatMap([[1, 2], [3]], map(#, # + 1));;[2, 3, 4] +flatMap(null, #);;!error +flatMap('ab', #);;!error +flatMap([1, 'a'], # * 2);;!error +# intervals as closure sources +map([0..3], #);;[0, 1, 2, 3] +map((0..3], #);;[1, 2, 3] +map([0..3), #);;[0, 1, 2] +map((0..3), #);;[1, 2] +map([1..1], #);;[1] +map((1..1), #);;[] +map([3..1], #);;[] +map([-2..1], #);;[-2, -1, 0, 1] +map([1..5], # * 2);;[2, 4, 6, 8, 10] +filter([0..10], # % 2 == 0);;[0, 2, 4, 6, 8, 10] +some([1..3], # == 2);;true +all((0..5], # > 0);;true +none([1..3), # == 3);;true +one([1..3], # == 3);;true +count((1..5), true);;3 +flatMap([1..2], [#, #]);;[1, 1, 2, 2] +sum(map([1..4], #));;10 +map([a..b], #);{a: 1, b: 4};[1, 2, 3, 4] +map((a..b), #);{a: 1, b: 4};[2, 3] +map([a..b], #);{a: 'x', b: 4};!error +map([a..b], #);{a: null, b: 4};!error +map(['a'..'c'], #);;!error +map([1.5..3], #);;[2, 3];bug: iterating [1.5..3] yields 1, which lies outside the interval (bound truncated) +map([1..2.5), #);;[1, 2];bug: iterating [1..2.5) drops 2, which lies inside the interval (bound truncated before exclusion) +map((0.5..2], #);;[1, 2] +map([0..2], #) == [0, 1, 2];;false;question: array == compares by identity, so equal arrays are not equal (see equality chapter) +1..5;;!error +map(1..5, #);;!error diff --git a/core/expression/tests/spec/standard/05-closures-lists.csv b/core/expression/tests/spec/standard/05-closures-lists.csv new file mode 100644 index 00000000..832fe478 --- /dev/null +++ b/core/expression/tests/spec/standard/05-closures-lists.csv @@ -0,0 +1,284 @@ +expression (string);input (json 5);output (json 5);note +# closures over list inputs: integers, decimals, empty, nulls, missing, wrong type +map(xs, # * 2);{xs: [1, 2, 3, 4, 5]};[2, 4, 6, 8, 10] +map(xs, # * 2);{xs: [0.5, 1.25, -0.10, 2]};[1, 2.5, -0.2, 4] +map(xs, # * 2);{xs: []};[] +map(xs, # * 2);{xs: [-3, 0, 7]};[-6, 0, 14] +map(xs, # * 2);{xs: [1, null, 3]};!error +map(xs, # * 2);{xs: null};!error;question: a null list input is an error rather than an empty list +map(xs, # * 2);{};!error;question: a missing list input is an error rather than an empty list +map(xs, # * 2);{xs: 'abc'};!error +map(xs, # * 2);{xs: {a: 1}};!error +map(xs, # * 2);{xs: 5};!error +filter(xs, # > 1);{xs: [1, 2, 3, 4, 5]};[2, 3, 4, 5] +filter(xs, # > 1);{xs: [0.5, 1.25, -0.10, 2]};[1.25, 2] +filter(xs, # > 1);{xs: []};[] +filter(xs, # > 1);{xs: [-3, 0, 7]};[7] +filter(xs, # > 1);{xs: [1, null, 3]};!error +filter(xs, # > 1);{xs: null};!error +filter(xs, # > 1);{};!error +filter(xs, # > 1);{xs: 'abc'};!error +some(xs, # > 2);{xs: [1, 2, 3, 4, 5]};true +some(xs, # > 2);{xs: [0.5, 1.25, -0.10, 2]};false +some(xs, # > 2);{xs: []};false +some(xs, # > 2);{xs: [-3, 0, 7]};true +some(xs, # > 2);{xs: [5, null]};true +some(xs, # > 2);{xs: [1, null, 3]};!error +some(xs, # > 2);{xs: null};!error +some(xs, # > 2);{xs: 'abc'};!error +all(xs, # > 0);{xs: [1, 2, 3, 4, 5]};true +all(xs, # > 0);{xs: [0.5, 1.25, -0.10, 2]};false +all(xs, # > 0);{xs: []};true +all(xs, # > 0);{xs: [-3, 0, 7]};false +all(xs, # > 0);{xs: [1, null, 3]};!error +all(xs, # > 0);{xs: [-1, null]};false +all(xs, # > 0);{xs: null};!error +none(xs, # < 0);{xs: [1, 2, 3, 4, 5]};true +none(xs, # < 0);{xs: [0.5, 1.25, -0.10, 2]};false +none(xs, # < 0);{xs: []};true +none(xs, # < 0);{xs: [-3, 0, 7]};false +none(xs, # < 0);{xs: [-1, null]};false +none(xs, # < 0);{xs: [1, null]};!error +none(xs, # < 0);{};!error +one(xs, # < 0);{xs: [1, 2, 3, 4, 5]};false +one(xs, # < 0);{xs: [0.5, 1.25, -0.10, 2]};true +one(xs, # < 0);{xs: []};false +one(xs, # < 0);{xs: [-3, 0, 7]};true +one(xs, # < 0);{xs: [-3, -0.5]};false +one(xs, # < 0);{xs: [1, null]};!error +one(xs, # < 0);{xs: null};!error +count(xs, # >= 1);{xs: [1, 2, 3, 4, 5]};5 +count(xs, # >= 1);{xs: [0.5, 1.25, -0.10, 2]};2 +count(xs, # >= 1);{xs: []};0 +count(xs, # >= 1);{xs: [-3, 0, 7]};1 +count(xs, # >= 1);{xs: [1, null, 3]};!error +count(xs, # >= 1);{xs: null};!error +count(xs, # >= 1);{xs: 'abc'};!error +map(xs, # / 2);{xs: [1, 2, 3, 4, 5]};[0.5, 1, 1.5, 2, 2.5] +map(xs, # / 2);{xs: [0.5, 1.25, -0.10, 2]};[0.25, 0.625, -0.05, 1] +map(xs, # / 2);{xs: []};[] +map(xs, # / 2);{xs: [-3, 0, 7]};[-1.5, 0, 3.5] +map(xs, # + 0.1);{xs: [1, 2]};[1.1, 2.1] +map(xs, # + 0.1);{xs: [0.5, 1.25, -0.10]};[0.6, 1.35, 0] +map(xs, # - 1);{xs: [0.5, 1.25, -0.10]};[-0.5, 0.25, -1.1] +map(xs, # % 2);{xs: [0.5, 1.25, -0.10, 2, -3]};[0.5, 1.25, -0.10, 0, -1] +map(xs, # % 2 == 0);{xs: [1, 2, -3, -4]};[false, true, false, true] +map(xs, abs(#));{xs: [1, -2, -0.10]};[1, 2, 0.10] +map(xs, round(#));{xs: [0.5, 1.25, -0.10, 2]};[1, 1, 0, 2] +map(xs, floor(#));{xs: [0.5, 1.5, -0.5, 2.25]};[0, 1, -1, 2] +map(xs, string(#));{xs: [1, 2, 3]};['1', '2', '3'] +map(xs, string(#));{xs: [0.5, 1.25, -0.10, 2]};['0.5', '1.25', '-0.10', '2'] +map(xs, string(#));{xs: [1.0, 1.00, 1, 1e2]};['1.0', '1.00', '1', '100'] +map(xs, string(#));{xs: []};[] +map(xs, string(# * 2));{xs: [0.5, 1.25, -0.10]};['1.0', '2.50', '-0.20'] +map(xs, string(#) + 'x');{xs: [1, -2]};['1x', '-2x'] +map(xs, # > 1 ? 'hi' : 'lo');{xs: [1, 2, 3]};['lo', 'hi', 'hi'] +map(xs, # > 1 ? 'hi' : 'lo');{xs: [0.5, 1.25, -0.10]};['lo', 'hi', 'lo'] +map(xs, # > 1 ? 'hi' : 'lo');{xs: []};[] +map(xs, # ?? 0);{xs: [1, null, 3]};[1, 0, 3] +map(xs, # ?? 0);{xs: [0.5, null]};[0.5, 0] +map(xs, # ?? 0);{xs: [null, null]};[0, 0] +map(xs, # ?? 0);{xs: []};[] +filter(xs, # != null);{xs: [1, null, 3]};[1, 3] +filter(xs, # != null);{xs: [null]};[] +filter(xs, # != null);{xs: ['a', null, 0.5]};['a', 0.5] +filter(xs, # % 2 == 0);{xs: [1, 2, 3, 4, 5]};[2, 4] +filter(xs, # % 2 == 0);{xs: [0.5, 1.25, -0.10, 2]};[2] +filter(xs, # % 2 == 0);{xs: [-3, 0, 7]};[0] +count(xs, # == 1.25);{xs: [0.5, 1.25, -0.10, 2]};1 +count(xs, # == 1.25);{xs: [1.250, 1.25, 1.2500]};3 +count(xs, # == 1.25);{xs: [1, 2]};0 +filter(xs, # == 1);{xs: [1.0, 1.00, 1, 2]};[1.0, 1.00, 1] +map(xs, # * 79228162514264337593543950335);{xs: [1, 2]};!error +map(xs, # * 79228162514264337593543950335);{xs: [1]};[79228162514264337593543950335] +map(xs, # * 79228162514264337593543950335);{xs: []};[] +# aggregates over map and filter results (typed lists) +sum(map(xs, # * 2));{xs: [1, 2, 3, 4, 5]};30 +sum(map(xs, # * 2));{xs: [0.5, 1.25, -0.10, 2]};7.3 +sum(map(xs, # * 2));{xs: []};0 +sum(map(xs, # * 2));{xs: [-3, 0, 7]};8 +sum(map(xs, # * 2));{xs: [1, null]};!error +sum(map(xs, # * 2));{xs: null};!error +sum(filter(xs, # > 0));{xs: [1, 2, 3, 4, 5]};15 +sum(filter(xs, # > 0));{xs: [0.5, 1.25, -0.10, 2]};3.75 +sum(filter(xs, # > 0));{xs: []};0 +sum(filter(xs, # > 0));{xs: [-3, 0, 7]};7 +sum(filter(xs, # > 0));{xs: [-3, -1]};0 +string(sum(filter(xs, # > 0)));{xs: [0.5, 1.25, -0.10, 2]};'3.75' +string(sum(map(xs, #)));{xs: [0.5, 1.25, -0.10]};'1.65' +max(map(xs, # + 1));{xs: [1, 2, 3, 4, 5]};6 +max(map(xs, # + 1));{xs: [0.5, 1.25, -0.10, 2]};3 +max(map(xs, # + 1));{xs: []};!error +max(map(xs, # + 1));{xs: [-3, 0, 7]};8 +max(map(xs, # + 1));{xs: [-3, -5]};-2 +min(filter(xs, # > 0));{xs: [1, 2, 3, 4, 5]};1 +min(filter(xs, # > 0));{xs: [0.5, 1.25, -0.10, 2]};0.5 +min(filter(xs, # > 0));{xs: []};!error +min(filter(xs, # > 0));{xs: [-3, 0, 7]};7 +min(filter(xs, # > 0));{xs: [-3, -1]};!error +min(map(xs, # - 10));{xs: [1, 2, 3]};-9 +min(map(xs, #));{xs: [0.5, 1.25, -0.10]};-0.10 +string(min(filter(xs, # >= 0)));{xs: [0.5, 1.25, -0.10, 0.00]};'0.00' +avg(map(xs, #));{xs: [0.5, 1.25, -0.10, 2]};0.9125 +avg(map(xs, # * 2));{xs: [1, 2]};3 +avg(map(xs, #));{xs: []};!error +sum(map(xs, # / 3));{xs: [1, 2]};1 +sum(map(xs, # * 0.5));{xs: [1, 2, 3]};3 +sum(map(xs, 79228162514264337593543950335));{xs: [1, 2]};!error +sum(map(xs, 79228162514264337593543950335));{xs: [1]};79228162514264337593543950335 +len(filter(xs, # > 1));{xs: [1, 2, 3, 4, 5]};4 +len(filter(xs, # > 1));{xs: [0.5, 1.25, -0.10, 2]};2 +len(filter(xs, # > 1));{xs: []};0 +len(map(xs, #));{xs: [1, null, 'a']};3 +count(map(xs, # * 2), # > 2);{xs: [1, 2, 3]};2 +count(map(xs, # * 2), # > 2);{xs: [0.5, 1.25, 2]};2 +count(map(xs, # * 2), # > 2);{xs: []};0 +contains(map(xs, # * 2), 2.5);{xs: [0.5, 1.25, -0.10]};true +contains(map(xs, # * 2), 2.5);{xs: [1, 2]};false +contains(filter(xs, # > 0), 2);{xs: [2.00, -2]};true +# closures over string lists +map(xs, upper(#));{xs: ['a', 'héllo', '日本', '']};['A', 'HÉLLO', '日本', ''] +map(xs, upper(#));{xs: ['Ab', 'aB', 'b']};['AB', 'AB', 'B'] +map(xs, upper(#));{xs: []};[] +map(xs, upper(#));{xs: ['a', null]};!error +map(xs, upper(#));{xs: [1]};!error +map(xs, lower(#));{xs: ['ÉCOLE', 'ABC']};['école', 'abc'] +map(xs, # + '!');{xs: ['a', 'héllo', '日本', '']};['a!', 'héllo!', '日本!', '!'] +map(xs, # + '!');{xs: ['a', null]};!error +map(xs, len(#));{xs: ['a', 'bb', '']};[1, 2, 0] +map(xs, len(#));{xs: ['a', 'héllo', '日本', '']};[1, 5, 2, 0];bug: len counts UTF-8 bytes instead of characters +map(xs, len(#));{xs: []};[] +filter(xs, len(#) == 2);{xs: ['a', 'héllo', '日本', 'ab']};['日本', 'ab'];bug: len counts UTF-8 bytes instead of characters +filter(xs, len(#) == 2);{xs: ['ab', 'c']};['ab'] +map(xs, #[0]);{xs: ['ab', 'c']};['a', 'c'] +map(xs, #[0]);{xs: ['a', 'héllo', '日本', '']};['a', 'h', '日', null];bug: string indexing is byte-based, so a multi-byte first character yields null +filter(xs, startsWith(#, 'h'));{xs: ['a', 'héllo', '日本', '']};['héllo'] +filter(xs, startsWith(#, 'h'));{xs: ['Ab', 'aB', 'b']};[] +filter(xs, startsWith(#, 'h'));{xs: []};[] +filter(xs, startsWith(#, 'h'));{xs: ['h', null]};!error +filter(xs, contains(#, 'é'));{xs: ['héllo', 'abc', 'hé']};['héllo', 'hé'] +filter(xs, contains(#, 'é'));{xs: ['e', 'E']};[] +filter(xs, # != '');{xs: ['a', 'héllo', '日本', '']};['a', 'héllo', '日本'] +filter(xs, # != '');{xs: ['']};[] +some(xs, # == '日本');{xs: ['a', 'héllo', '日本', '']};true +some(xs, # == '日本');{xs: ['Ab', 'aB', 'b']};false +some(xs, # == '日本');{xs: []};false +some(xs, # == '日本');{xs: [1, '日本']};true +all(xs, len(#) > 0);{xs: ['a', 'bb']};true +all(xs, len(#) > 0);{xs: ['a', '']};false +all(xs, len(#) > 0);{xs: []};true +none(xs, # == 'x');{xs: ['a', 'b']};true +none(xs, # == 'x');{xs: ['x']};false +count(xs, lower(#) == 'ab');{xs: ['Ab', 'aB', 'b']};2 +count(xs, lower(#) == 'ab');{xs: ['a', 'héllo', '日本', '']};0 +one(xs, # == 'b');{xs: ['Ab', 'aB', 'b']};true +one(xs, # == 'b');{xs: ['b', 'b']};false +map(xs, # in ['a', 'b']);{xs: ['a', 'c', 'b']};[true, false, true] +map(xs, # in ['a', 'b']);{xs: []};[] +map(xs, # == 'hé');{xs: ['héllo', 'abc', 'hé']};[false, false, true] +map(xs, number(#));{xs: ['1', '2.50', '-0.10']};[1, 2.5, -0.1] +sum(map(xs, number(#)));{xs: ['1', '2.50', '-0.10']};3.4 +sum(map(xs, len(#)));{xs: ['a', 'bb', '']};3 +max(map(xs, len(#)));{xs: ['a', 'bb']};2 +flatMap(xs, [#, upper(#)]);{xs: ['a', 'é']};['a', 'A', 'é', 'É'] +# closures over boolean lists +filter(xs, #);{xs: [true, false, true]};[true, true] +filter(xs, #);{xs: []};[] +filter(xs, #);{xs: [true, null]};!error +map(xs, not #);{xs: [true, false]};[false, true] +all(xs, #);{xs: [true, true]};true +all(xs, #);{xs: [true, false]};false +count(xs, #);{xs: [true, false, true]};2 +count(xs, #);{xs: [1]};!error +# closures over object lists +map(xs, #.x);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};[1, 2.5, -0.10] +map(xs, #.x);{xs: [{x: 1}, {s: 'b'}, {x: null}]};[1, null, null] +map(xs, #.x);{xs: []};[] +map(xs, #.x);{xs: [1, 'a']};[null, null] +map(xs, #.x);{xs: null};!error +map(xs, #.x * 2);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};[2, 5, -0.2] +map(xs, #.x * 2);{xs: [{x: 1}, {s: 'b'}, {x: null}]};!error +map(xs, #.x * 2);{xs: []};[] +map(xs, #.s);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};['a', 'b', 'c'] +map(xs, #.s);{xs: [{x: 1}, {s: 'b'}, {x: null}]};[null, 'b', null] +filter(xs, #.x > 1);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};[{x: 2.5, s: 'b'}] +filter(xs, #.x > 1);{xs: [{x: 1}, {s: 'b'}, {x: null}]};!error +filter(xs, #.x > 1);{xs: []};[] +filter(xs, #.x != null);{xs: [{x: 1}, {s: 'b'}, {x: null}]};[{x: 1}] +filter(xs, #.s == 'b');{xs: [{x: 1}, {s: 'b'}, {x: null}]};[{s: 'b'}] +sum(map(xs, #.x));{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};3.4 +sum(map(xs, #.x));{xs: [{x: 1}, {s: 'b'}, {x: null}]};!error +sum(map(xs, #.x));{xs: []};0 +sum(map(xs, #.x ?? 0));{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};3.4 +sum(map(xs, #.x ?? 0));{xs: [{x: 1}, {s: 'b'}, {x: null}]};1 +max(map(xs, #.x));{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};2.5 +min(map(xs, #.x));{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};-0.10 +max(map(xs, #.x));{xs: []};!error +map(filter(xs, #.x > 0), #.s);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};['a', 'b'] +map(filter(xs, #.x > 0), #.s);{xs: []};[] +sum(map(filter(xs, #.x > 0), #.x));{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};3.5 +sum(map(filter(xs, #.x > 0), #.x));{xs: [{x: -1}]};0 +some(xs, #.s == 'b');{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};true +some(xs, #.s == 'b');{xs: [{x: 1}, {s: 'b'}, {x: null}]};true +some(xs, #.s == 'b');{xs: []};false +all(xs, #.x != null);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}, {x: -0.10, s: 'c'}]};true +all(xs, #.x != null);{xs: [{x: 1}, {s: 'b'}, {x: null}]};false +count(xs, #.x == null);{xs: [{x: 1, s: 'a'}, {x: 2.5, s: 'b'}]};0 +count(xs, #.x == null);{xs: [{x: 1}, {s: 'b'}, {x: null}]};2 +map(xs as o, o.x + 1);{xs: [{x: 1}, {x: 0.5}]};[2, 1.5] +map(xs as o, o.x + 1);{xs: []};[] +map(xs, {v: #.x, s: #.s});{xs: [{x: 1, s: 'a'}, {x: 2}]};[{v: 1, s: 'a'}, {v: 2, s: null}] +map(xs, #.a.b);{xs: [{a: {b: 1}}, {a: 5}, {a: 's'}]};[1, null, null] +filter(xs, 'p' in #.tags);{xs: [{x: 1, tags: ['p']}, {x: 2, tags: []}]};[{x: 1, tags: ['p']}] +filter(xs, 'p' in #.tags);{xs: [{x: 1, tags: ['p']}, {x: 2}]};!error +map(xs, len(#.tags ?? []));{xs: [{tags: ['a']}, {tags: []}, {}]};[1, 0, 0] +map(xs as o, o.tags[0]);{xs: [{tags: ['a']}, {tags: []}, {}]};['a', null, null] +flatMap(xs, #.tags);{xs: [{tags: ['a', 'b']}, {tags: []}]};['a', 'b'] +flatMap(xs, #.tags);{xs: []};[] +sum(map(xs, #.qty * #.price));{xs: [{qty: 2, price: 1.25}, {qty: 3, price: 0.10}]};2.8 +max(map(xs, #.qty * #.price));{xs: [{qty: 2, price: 10}, {qty: 1, price: 20}, {qty: 3, price: 15}]};45 +# nested list inputs +map(xs, map(#, # * 2));{xs: [[1, 2], [], [3]]};[[2, 4], [], [6]] +map(xs, map(#, # * 2));{xs: [[0.5], [1.25, -0.10]]};[[1], [2.5, -0.2]] +map(xs, map(#, # * 2));{xs: [[1], null]};!error +map(xs, sum(#));{xs: [[1, 2], [], [3]]};[3, 0, 3] +map(xs, len(#));{xs: [[1, 2], [], [3]]};[2, 0, 1] +flatMap(xs, map(#, # + 1));{xs: [[1, 2], [], [3]]};[2, 3, 4] +flatMap(xs, #);{xs: [[1, 2], [], [3]]};[1, 2, 3] +some(xs, 3 in #);{xs: [[1, 2], [], [3]]};true +sum(flatMap(xs, #));{xs: [[0.5, 1], [2.25]]};3.75 +# mixed lists +map(xs, #);{xs: [1, 'a', true]};[1, 'a', true] +filter(xs, # == 'a');{xs: [1, 'a', true]};['a'] +map(xs, type(#));{xs: [1, 'a', true, null, [1], {a: 1}]};['number', 'string', 'bool', 'null', 'array', 'object'] +filter(xs, type(#) == 'number');{xs: [1, 'a', 0.5, null]};[1, 0.5] +sum(filter(xs, type(#) == 'number'));{xs: [1, 'a', 0.5, null]};1.5 +# several closures reading the same inputs in one expression +[none(xs, contains(s, 'x')), map(ys, len(s))];{xs: [1, 2], ys: [0.5, 1.25], s: 'abc'};[true, [3, 3]] +[none(xs, contains(s, 'x')), map(ys, len(s))];{xs: [1, 2], ys: [0.5, 1.25], s: 'xyz'};[false, [3, 3]] +[none(xs, contains(s, 'x')), map(ys, len(s))];{xs: [], ys: [], s: 'xyz'};[true, []] +[none(xs, contains(s, 'x')), map(ys, len(s))];{xs: [1], ys: [1], s: null};!error +[some(xs, # > 1), map(xs, # * 2)];{xs: [1, 2, 3]};[true, [2, 4, 6]] +[some(xs, # > 1), map(xs, # * 2)];{xs: [0.5, 1.25, -0.10]};[true, [1, 2.5, -0.2]] +[some(xs, # > 1), map(xs, # * 2)];{xs: []};[false, []] +[some(xs, # > 1), map(xs, # * 2)];{xs: [2, null]};!error +[sum(map(xs, #)), sum(filter(xs, # > 0)), count(xs, # > 0)];{xs: [1, 2, 3]};[6, 6, 3] +[sum(map(xs, #)), sum(filter(xs, # > 0)), count(xs, # > 0)];{xs: [0.5, 1.25, -0.10]};[1.65, 1.75, 2] +[sum(map(xs, #)), sum(filter(xs, # > 0)), count(xs, # > 0)];{xs: []};[0, 0, 0] +[min(map(xs, #)), max(map(xs, #))];{xs: [3, 1, 2]};[1, 3] +[min(map(xs, #)), max(map(xs, #))];{xs: [0.5, 1.25, -0.10]};[-0.10, 1.25] +[min(map(xs, #)), max(map(xs, #))];{xs: []};!error +[map(xs, #.x), filter(xs, #.x > 1)];{xs: [{x: 1}, {x: 2.5}]};[[1, 2.5], [{x: 2.5}]] +[map(xs, #.x), filter(xs, #.x > 1)];{xs: []};[[], []] +[filter(xs, # > t), map(xs, # * t)];{t: 2, xs: [1, 2, 3]};[[3], [2, 4, 6]] +[filter(xs, # > t), map(xs, # * t)];{t: 0.5, xs: [0.25, 1.25]};[[1.25], [0.125, 0.625]] +[filter(xs, # > t), map(xs, # * t)];{t: null, xs: [1]};!error +[map(xs, upper(#)), count(xs, # == 'a'), some(xs, startsWith(#, 'é'))];{xs: ['a', 'é', 'a']};[['A', 'É', 'A'], 2, true] +[map(xs, upper(#)), count(xs, # == 'a'), some(xs, startsWith(#, 'é'))];{xs: []};[[], 0, false] +[map(xs, # * 2), map(ys, #.v), filter(zs, # != '')];{xs: [1, 0.5], ys: [{v: 'a'}], zs: ['', 'b']};[[2, 1], ['a'], ['b']] +[map(xs, # * 2), map(ys, #.v), filter(zs, # != '')];{xs: [], ys: [], zs: []};[[], [], []] +map(xs, count(ys, # == 1) + #);{xs: [10, 20], ys: [1, 1, 2]};[12, 22] +map(xs as x, count(ys, # < x));{xs: [1, 2.5], ys: [0.5, 1, 2]};[1, 3] +filter(xs as x, some(ys, # == x));{xs: [1, 2, 3], ys: [3, 1]};[1, 3] +filter(xs as x, none(ys, # == x));{xs: ['a', 'b', 'c'], ys: ['b']};['a', 'c'] +map(xs as x, filter(ys, #.k == x));{xs: ['a', 'b'], ys: [{k: 'a', v: 1}, {k: 'b', v: 2}, {k: 'a', v: 3}]};[[{k: 'a', v: 1}, {k: 'a', v: 3}], [{k: 'b', v: 2}]] diff --git a/core/expression/tests/spec/standard/05-closures-scoping.csv b/core/expression/tests/spec/standard/05-closures-scoping.csv new file mode 100644 index 00000000..6bbd8e9d --- /dev/null +++ b/core/expression/tests/spec/standard/05-closures-scoping.csv @@ -0,0 +1,119 @@ +expression (string);input (json 5);output (json 5);note +# pointer forms inside a closure +map([{a: {b: 1}}, {a: {b: 2}}], #.a.b);;[1, 2] +map([{a: 1}, {}], #['a']);;[1, null] +map([{a: [7]}, {a: []}], #.a[0]);;[7, null] +map([[1, 2], [], null], #[0]);;[1, null, null] +map(['ab', 'c'], #[0]);;['a', 'c'] +map([1, 2], #.a);;[null, null] +map([1, 2], #[0]);;[null, null] +map([1, 2], # in [2, 3]);;[false, true] +map([0, 1, 2.5, 3, 4], # in [1..3]);;[false, true, true, true, false] +map([1, 2, 3], # in (1..3));;[false, true, false] +map(['a', 'b'], # in 'abc');;!error +map([[1, 2], 'abc'], len(#));;[2, 3] +map([{a: 1, b: 2}], keys(#));;[['a', 'b']];bug: object literal keys come back in reverse insertion order +map([{k: 'a'}, {k: 'b'}], {[#.k]: true});;[{a: true}, {b: true}] +# pointer outside of any closure +len(#);;!error +1 + #;;!error +(#);;null;question: a bare # outside any closure evaluates to null instead of failing to compile +[#];;[null];question: a bare # outside any closure evaluates to null instead of failing to compile +# as alias +map([1, 2] as x, x * 2);;[2, 4] +filter([1, 2, 3] as x, x > 1);;[2, 3] +some([1, 2, 3] as x, x > 2);;true +all([1, 2, 3] as x, x > 0);;true +none([1, 2, 3] as x, x > 3);;true +one([1, 2, 3] as x, x == 2);;true +count([1, 2, 3] as x, x >= 2);;2 +flatMap([1, 2] as x, [x, x]);;[1, 1, 2, 2] +map(xs as p, p.price);{xs: [{price: 10}, {price: 2.5}]};[10, 2.5] +filter(xs as p, p.price > 5);{xs: [{price: 10}, {price: 2.5}]};[{price: 10}] +map([1, 2] as x, #);;[1, 2] +map([1, 2] as x, x + #);;[2, 4] +map([1, 2, 3] as x, [x, #]);;[[1, 1], [2, 2], [3, 3]] +map([{v: 1}] as item, item.v + 1);;[2] +map([] as x, x);;[] +map(null as x, x);;!error +# alias shadows an input field of the same name +map([1, 2] as x, x);{x: 5};[1, 2] +map(xs as item, item);{xs: [{v: 1}], item: 5};[{v: 1}] +map(xs as xs, xs * 2);{xs: [1, 2]};[2, 4] +map(xs as k, k + #);{k: 10, xs: [1, 2]};[2, 4] +[map([1] as x, x), x];{x: 5};[[1], 5] +# outer input fields next to the element +map(xs, # + x);{x: 5, xs: [1, 2]};[6, 7] +map(xs, #.x + x);{x: 5, xs: [{x: 1}]};[6] +map(xs, #.k + k);{k: 10, xs: [{k: 1}, {k: 2}]};[11, 12] +map(xs, #.k + k);{k: 10, xs: [{k: 1}, {}]};!error +map(xs, $root.k + #);{k: 10, xs: [1, 2]};[11, 12] +map(xs, k + #);{k: 10, xs: [1, 2]};[11, 12] +filter(xs, # > limit);{limit: 2, xs: [1, 2, 3, 4]};[3, 4] +filter(xs, #.tier == tier);{tier: 'gold', xs: [{tier: 'gold', n: 1}, {tier: 'silver', n: 2}]};[{tier: 'gold', n: 1}] +map(xs, #.price * rate);{rate: 1.5, xs: [{price: 10}, {price: 0.10}]};[15, 0.15] +some(xs, # == target);{target: 'b', xs: ['a', 'b']};true +count(xs, # >= min);{min: 2, xs: [1, 2, 3]};2 +map(xs, # + missing);{xs: [1]};!error +map(xs, missing ?? #);{xs: [1]};[1] +# nested closures: bare # binds to the innermost closure +map([[1, 2], [3]], map(#, # * 10));;[[10, 20], [30]] +map([[1, 2], [3, 4]], map(#, #));;[[1, 2], [3, 4]] +map([1, 2], map([10, 20], #));;[[10, 20], [10, 20]] +map([1, 2], filter([1, 2, 3], # > 1));;[[2, 3], [2, 3]] +map([[1, 2], [3]], sum(#));;[3, 3] +map([[1, 2], [], [3]], map(#, # * 2));;[[2, 4], [], [6]] +map([[1, 2], [], [3]], len(filter(#, # > 1)));;[1, 0, 1] +filter([[1, 2], [3]], all(#, # < 3));;[[1, 2]] +filter([[1, 2], [], [3]], none(#, # > 2));;[[1, 2], []] +count([[1, 2], [3]], one(#, # == 3));;1 +flatMap([[1, 2], [3]], filter(#, # != 2));;[1, 3] +some([[1, 2], [], [3]], 3 in #);;true +# nested closures: outer alias is visible in the inner closure +map([1, 2] as x, map([10, 20], x + #));;[[11, 21], [12, 22]] +map([1, 2] as x, map([10, 20] as y, x + y));;[[11, 21], [12, 22]] +map([1, 2] as x, filter([1, 2, 3], # > x));;[[2, 3], [3]] +map([1, 2] as x, filter([1, 2, 3] as y, y > x));;[[2, 3], [3]] +map([1, 2] as x, count([1, 2, 3], # >= x));;[3, 2] +map([1, 2] as x, some([2, 3], # == x));;[false, true] +filter([1, 2, 3] as x, all([1, 2] as y, x > y));;[3] +map([[1, 2], [3]] as row, map(row, # + len(row)));;[[3, 4], [4]] +map([[1, 2], [3]] as row, map(row as c, c * 10 + len(row)));;[[12, 22], [31]] +map([1, 2] as x, map([10, 20] as x, x));;[[10, 20], [10, 20]] +map([1, 2] as a, map([3] as b, map([5] as c, a + b + c)));;[[[9]], [[10]]] +map([1, 2] as a, map([3], map([5], a + #)));;[[[6]], [[7]]] +map([1, 2] as a, map([3] as b, map([5], a * 100 + b * 10 + #)));;[[[135]], [[235]]] +map(orders as o, map(o.items, #.qty * o.factor));{orders: [{factor: 2, items: [{qty: 1}, {qty: 3}]}, {factor: 0.5, items: []}]};[[2, 6], []] +map(orders as o, sum(map(o.items as i, i.qty * i.price)));{orders: [{items: [{qty: 2, price: 1.25}, {qty: 1, price: 0.10}]}, {items: []}]};[2.6, 0] +filter(users as u, some(u.roles, # == role));{role: 'admin', users: [{n: 1, roles: ['admin']}, {n: 2, roles: ['user']}, {n: 3, roles: []}]};[{n: 1, roles: ['admin']}] +map(groups as g, {name: g.name, total: sum(map(g.xs, #))});{groups: [{name: 'a', xs: [1, 2]}, {name: 'b', xs: [0.5]}]};[{name: 'a', total: 3}, {name: 'b', total: 0.5}] +# closures inside object, array and template literals +{a: map([1, 2], # * 2)};;{a: [2, 4]} +{a: map(xs, # * 2), b: filter(xs, # > 1)};{xs: [1, 2]};{a: [2, 4], b: [2]} +[map([1, 2], # * 2), filter([1, 2], # > 1)];;[[2, 4], [2]] +[some(xs, # > 1), count(xs, # > 1), filter(xs, # > 1), map(xs, # > 1)];{xs: [1, 2, 3]};[true, 2, [2, 3], [false, true, true]] +`v=${len(filter([1, 2, 3], # > 1))}`;;'v=2' +`${count(xs, # > 1)} of ${len(xs)}`;{xs: [1, 2, 3]};'2 of 3' +`v=${map([1, 2], # * 2)}`;;!error +`${some(xs, # == 'b') ? 'yes' : 'no'}`;{xs: ['a', 'b']};'yes' +map(xs, `${#.first} ${#.last}`);{xs: [{first: 'Ann', last: 'Lee'}, {first: 'Bo', last: 'Ng'}]};['Ann Lee', 'Bo Ng'] +map(items, {id: #.id, fullName: #.firstName + ' ' + #.lastName});{items: [{id: 1, firstName: 'John', lastName: 'Doe'}, {id: 2, firstName: 'Jane', lastName: 'Smith'}]};[{id: 1, fullName: 'John Doe'}, {id: 2, fullName: 'Jane Smith'}] +# closures in other expression positions +map(filter([1, 2, 3], # > 1), # * 2)[0];;4 +map([1, 2, 3], # * 2)[1];;4 +filter([{n: 'a'}, {n: 'b'}], #.n == 'b')[0].n;;'b' +filter([1, 2], # > 5)[0];;null +len(map([1, 2], # + 1));;2 +some(xs, # > 1) and all(xs, # < 5);{xs: [1, 2]};true +some(xs, # > 5) or none(xs, # > 5);{xs: [1, 2]};true +some(xs, # > 1) ? 'hit' : 'miss';{xs: [1, 2]};'hit' +count(xs, # > 1) > 0;{xs: [1, 2]};true +not some(xs, # > 1);{xs: [1, 2]};false +map(xs, # * 2) ?? [];{xs: [1]};[2] +map([1, 2] as x, x) + 1;;!error +3 in map([1, 2, 3], #);;true +'b' in filter(['a', 'b'], # != 'a');;true +# assignments using closures +"doubled = map(numbers, # * 2)";{numbers: [1, 2, 3]};{doubled: [2, 4, 6]} +"big = filter(xs, # > 1); n = len(big)";{xs: [1, 2, 3]};{big: [2, 3], n: 2} +"t = 2; r = map(xs, # * t)";{xs: [1, 2]};{t: 2, r: [2, 4]} diff --git a/core/expression/tests/spec/standard/05-collections.csv b/core/expression/tests/spec/standard/05-collections.csv new file mode 100644 index 00000000..ac98feb7 --- /dev/null +++ b/core/expression/tests/spec/standard/05-collections.csv @@ -0,0 +1,212 @@ +expression (string);input (json 5);output (json 5);note +# len: arrays and strings only +len([]);;0 +len([1, 2, 3]);;3 +len([null]);;1 +len([[1, 2]]);;1 +len([1, 'a', null, [1], {a: 1}]);;5 +len(xs);{xs: [1, 2]};2 +len(xs);{xs: []};0 +len(xs);{xs: [0.5, null]};2 +len(xs);{};!error +len(xs);{xs: null};!error +len('');;0 +len('abc');;3 +len('héllo');;5;bug: len counts UTF-8 bytes instead of characters +len('日本');;2;bug: len counts UTF-8 bytes instead of characters +len({a: 1});;!error +len({});;!error +len(null);;!error +len(5);;!error +len(true);;!error +len([1..3]);;!error +len(d('2024-01-01'));;20 +# contains on arrays: element equality for primitives +contains([1, 2, 3], 2);;true +contains([1, 2, 3], 4);;false +contains([], 1);;false +contains([], null);;false +contains([1, 'a', true], true);;true +contains([1, 'a', true], 'a');;true +contains([1, 2], '1');;false +contains(['1'], 1);;false +contains([true], 1);;false +contains([1, null], null);;true +contains([1], null);;false +contains([1.0, 2], 1.00);;true +contains(xs, 2);{xs: [1.0, 2.00]};true +contains(xs, 0.1);{xs: [0.10, 0.2]};true +contains(xs, 'é');{xs: ['e', 'é']};true +contains(xs, 'É');{xs: ['e', 'é']};false +contains(xs, 'b');{xs: []};false +contains(xs, x);{xs: [1, 2], x: 2};true +contains(xs, x);{xs: [1, 2]};false +contains([d('2024-01-01')], d('2024-01-01'));;true +contains([[1]], [1]);;false;question: contains uses no deep equality, so equal arrays never match +contains([{a: 1}], {a: 1});;false;question: contains uses no deep equality, so equal objects never match +contains('abc', 'b');;true +contains('abc', 'd');;false +contains(null, 1);;!error +contains(5, 5);;!error +contains({a: 1}, 'a');;!error +contains('abc', 1);;!error +contains(map([1, 2, 3], # * 2), 6);;true +contains(values({a: 1, b: 2, c: 3}), 2);;true +contains(keys({a: 1}), 'a');;true +contains(filter(xs, # > 1), 1);{xs: [1, 2]};false +# in versus contains on arrays +2 in [1, 2];;true +2 in xs;{xs: [1.0, 2.00]};true +null in [1, null];;true +d('2024-01-01') in [d('2024-01-01')];;true +contains([1, 2], 2) == (2 in [1, 2]);;true +# flatten: exactly one level +flatten([1, [2, [3]], []]);;[1, 2, [3]] +flatten([[1, 2], [3]]);;[1, 2, 3] +flatten([]);;[] +flatten([[]]);;[] +flatten([1, 2]);;[1, 2] +flatten([[[1]], [[2]]]);;[[1], [2]] +flatten(flatten([[[1]], [[2]]]));;[1, 2] +flatten([null, [null]]);;[null, null] +flatten([{a: [1]}, [{b: 2}]]);;[{a: [1]}, {b: 2}] +flatten(xs);{xs: [[0.5], [1.25, -0.10]]};[0.5, 1.25, -0.10] +flatten(xs);{xs: [['a'], 'b']};['a', 'b'] +flatten(map(xs, [#, # * 2]));{xs: [1, 2]};[1, 2, 2, 4] +flatten(map(xs, [#, # * 2])) == flatMap(xs, [#, # * 2]);{xs: [1, 2]};false;question: array == compares by identity, so equal arrays are not equal +len(flatten(map(xs, [#, # * 2])));{xs: [1, 2]};4 +flatten(null);;!error +flatten('ab');;!error +flatten({a: [1]});;!error +# keys: object keys in insertion order, array indices +keys({a: 1, b: 2});;['a', 'b'];bug: object literal keys come back in reverse insertion order +keys({b: 1, a: 2});;['b', 'a'];bug: object literal keys come back in reverse insertion order +keys({b: 1, a: 2, c: 3});;['b', 'a', 'c'];bug: object literal keys come back in reverse insertion order +keys(o);{o: {b: 1, a: 2}};['b', 'a'] +keys(o);{o: {}};[] +keys({});;[] +keys([]);;[] +keys([10, 11, 12]);;[0, 1, 2] +keys(xs);{xs: ['a', null]};[0, 1] +keys({[`dynamic-${'key'}`]: 123});;['dynamic-key'] +keys('ab');;!error +keys(null);;!error +keys(5);;!error +# values: object values in insertion order +values({a: 1});;[1] +values({b: 1, a: 2});;[1, 2];bug: object literal keys come back in reverse insertion order +values(o);{o: {b: 1, a: 2}};[1, 2] +values({});;[] +values({a: {b: 1}, c: [1]});;[{b: 1}, [1]];bug: object literal keys come back in reverse insertion order +values({a: null});;[null] +values([1, 2]);;!error +values(null);;!error +values('ab');;!error +sum(values({a: 1, b: 2, c: 3}));;6 +sum(values(o));{o: {a: 0.5, b: 1.25, c: -0.10}};1.65 +len(keys(o)) == len(values(o));{o: {a: 1, b: null}};true +map(keys(o), o[#]);{o: {a: 1, b: 2}};[1, 2] +map(keys(o) as k, k + '=' + string(o[k]));{o: {a: 1, b: 2}};['a=1', 'b=2'] +filter(keys(o), o[#] > 1);{o: {a: 1, b: 2}};['b'] +count(values(o), # == null);{o: {a: 1, b: null, c: null}};2 +map(values(o), #.n);{o: {x: {n: 1}, y: {n: 2}}};[1, 2] +# merge: arrays are concatenated, objects are shallow-merged, null entries skipped +merge([[1, 2], [3, 4], [5]]);;[1, 2, 3, 4, 5] +merge([[1, 2], [], [3]]);;[1, 2, 3] +merge([[]]);;[] +merge([[1], [[2]]]);;[1, [2]] +merge([null, [1, 2], [3]]);;[1, 2, 3] +merge([[1], null]);;[1] +merge([{a: 1}, {b: 2}, {c: 3}]);;{a: 1, b: 2, c: 3} +merge([{a: 1, b: 2}, {b: 3, c: 4}]);;{a: 1, b: 3, c: 4} +merge([{a: {x: 1}}, {a: {y: 2}}]);;{a: {y: 2}} +merge([{a: 1}, null, {a: 2}]);;{a: 2} +merge([{a: 1}, {a: null}]);;{a: null} +merge([{}]);;{} +merge([]);;{} +merge([null]);;{} +merge([null, null]);;{} +merge(xs);{xs: [{a: 1}, {b: 0.5}]};{a: 1, b: 0.5} +merge(xs);{xs: [[0.5], [1.25]]};[0.5, 1.25] +merge(xs);{xs: []};{} +keys(merge([{b: 1}, {a: 2}]));;['b', 'a'] +keys(merge([o, p]));{o: {b: 1}, p: {a: 2}};['b', 'a'] +merge([[1], {a: 1}]);;!error +merge([{a: 1}, [1]]);;!error +merge([1, 2]);;!error +merge([{a: 1}, 5]);;!error +merge([['a'], 'b']);;!error +merge({a: 1});;!error +merge(null);;!error +merge('ab');;!error +merge(map(xs, [#]));{xs: [1, 2]};[1, 2] +merge(map(xs, {[#.k]: #.v}));{xs: [{k: 'a', v: 1}, {k: 'b', v: 2}]};{a: 1, b: 2} +# mergeDeep: recursive object merge, arrays concatenated, scalars last-wins +mergeDeep([{a: 1}, {b: 2}]);;{a: 1, b: 2} +mergeDeep([{a: 1, b: 2}, {b: 3, c: 4}]);;{a: 1, b: 3, c: 4} +mergeDeep([{a: {x: 1}}, {a: {y: 2}}]);;{a: {x: 1, y: 2}} +mergeDeep([{a: [1, 2]}, {a: [3, 4]}]);;{a: [1, 2, 3, 4]} +mergeDeep([{a: {b: {c: 1}}}, {a: {b: {d: 2}}}]);;{a: {b: {c: 1, d: 2}}} +mergeDeep([{a: 1}, {a: 2}]);;{a: 2} +mergeDeep([{a: {x: 1}}, {a: 5}]);;{a: 5} +mergeDeep([{a: 1}, {a: {x: 1}}]);;{a: {x: 1}} +mergeDeep([{a: [1]}, {a: {x: 1}}]);;{a: {x: 1}} +mergeDeep([{a: {x: 1}}, {a: [1]}]);;{a: [1]} +mergeDeep([{a: {x: 1}}, {a: null}]);;{a: null} +mergeDeep([{a: null}, {a: {x: 1}}]);;{a: {x: 1}} +mergeDeep([{a: [1, {b: 1}]}, {a: [{b: 2}]}]);;{a: [1, {b: 1}, {b: 2}]} +mergeDeep([{a: {b: [1]}}, {a: {b: [2], c: 1}}, {a: {c: {d: 1}}}]);;{a: {b: [1, 2], c: {d: 1}}} +mergeDeep([null, {a: 1}]);;{a: 1} +mergeDeep([{a: 1}, null]);;{a: 1} +mergeDeep([{}]);;{} +mergeDeep([{a: 1}]);;{a: 1} +mergeDeep([]);;{} +mergeDeep([null]);;{} +mergeDeep(xs);{xs: [{a: {n: 0.5}}, {a: {m: 1.25}}]};{a: {n: 0.5, m: 1.25}} +mergeDeep(xs);{xs: [{t: ['a']}, {t: ['b']}, {t: []}]};{t: ['a', 'b']} +keys(mergeDeep([o, p]));{o: {b: 1, z: 1}, p: {a: 2, z: 2}};['b', 'z', 'a'] +mergeDeep([[1]]);;!error +mergeDeep([{a: 1}, 5]);;!error +mergeDeep([{a: 1}, [1]]);;!error +mergeDeep(null);;!error +mergeDeep({a: 1});;!error +mergeDeep(map(xs, {[#]: {v: #}}));{xs: ['a', 'b']};{a: {v: 'a'}, b: {v: 'b'}} +# array concatenation is not an operator +[1] + [2];;!error +[1] + 2;;!error +merge([[1], [2]]);;[1, 2] +# aggregates over closure results (briefly; see the aggregates chapter) +sum(map([1, 2], # * 1.5));;4.5 +sum(filter([1, 2, 3, 4, 5], # % 2 == 0));;6 +sum(map(filter([1, 2, 3, 4, 5], # > 3), # ^ 2));;41 +sum(filter([1, 2], # > 5));;0 +max(filter([1, 2], # > 5));;!error +min(map([3, 1, 2], #));;1 +avg(map([{p: 10}, {p: 20}, {p: 30}], #.p));;20 +sum(map([{x: 1}, {y: 2}], #.x));;!error +sum(map([{x: 1}, {y: 2}], #.x ?? 0));;1 +sum(map(filter([{id: 1, val: 10}, {id: 2, val: 20}, {id: 3, val: 30}], #.id > 1), #.val));;50 +# composition +map(filter([1, 2, 3, 4, 5], # > 2), # * 2);;[6, 8, 10] +filter(map([1, 2, 3, 4], # * 2), # > 5);;[6, 8] +len(filter(map([1, 2, 3, 4, 5], # * 2), # > 5));;3 +count(map([1, 2, 3], # * 2), # > 2);;2 +some(map([1, 2, 3], # * 2), # > 5);;true +all(map([1, 2, 3], # + 2), # > 2);;true +none(filter([1, 2, 3], # > 1), # == 1);;true +one(map([1, 2, 3], # % 2), # == 0);;true +map(map(map([1], # + 1), # * 10), string(#));;['20'] +filter(filter([1, 2, 3, 4], # > 1), # < 4);;[2, 3] +map(flatMap([[1], [2, 3]], #), # * 2);;[2, 4, 6] +flatMap(map([1, 2], [#]), #);;[1, 2] +len(flatMap([[1], [2, 3]], #)) == count(flatten([[1], [2, 3]]), true);;true +map(split('123,456,789', ','), number(#));;[123, 456, 789] +filter(split('a,,b', ','), # != '');;['a', 'b'] +sum(map(split('1.5,2.25', ','), number(#)));;3.75 +map(keys(merge([{a: 1}, {b: 2}])), upper(#));;['A', 'B'] +filter(values(mergeDeep([{a: 1}, {b: 2}, {a: 3}])), # > 1);;[3, 2] +map(orders, sum(map(#.lines, #.qty)));{orders: [{lines: [{qty: 1}, {qty: 2}]}, {lines: []}]};[3, 0] +filter(orders, sum(map(#.lines, #.qty)) > 1);{orders: [{id: 'a', lines: [{qty: 1}, {qty: 2}]}, {id: 'b', lines: []}]};[{id: 'a', lines: [{qty: 1}, {qty: 2}]}] +map(filter(orders, len(#.lines) > 0), #.id);{orders: [{id: 'a', lines: [{qty: 1}]}, {id: 'b', lines: []}]};['a'] +count(flatMap(orders, #.lines), #.qty > 1);{orders: [{lines: [{qty: 1}, {qty: 2}]}, {lines: [{qty: 3}]}]};2 +max(flatMap(orders, map(#.lines, #.qty)));{orders: [{lines: [{qty: 1}, {qty: 2.5}]}, {lines: [{qty: 0.5}]}]};2.5 diff --git a/core/expression/tests/spec/standard/06-aggregates.csv b/core/expression/tests/spec/standard/06-aggregates.csv new file mode 100644 index 00000000..6914a753 --- /dev/null +++ b/core/expression/tests/spec/standard/06-aggregates.csv @@ -0,0 +1,195 @@ +expression (string);input (json 5);output (json 5);note +# sum +sum([1, 2, 3, 4, 5]);;15 +sum([]);;0 +string(sum([]));;'0' +sum([7]);;7 +string(sum([7.50]));;'7.50' +sum([-1, -2, -3]);;-6 +sum([0.1, 0.2]);;0.3 +string(sum([0.1, 0.20]));;'0.30' +string(sum([1, 2.50]));;'3.50' +string(sum([0.5, -0.5]));;'0.0' +sum([0.5, -0.5]) == 0;;true +string(sum([1.25, -1.25, 0]));;'0.00';bug: adding an integer to a zero with scale drops the scale (0.00 + 0 prints '0') +string(sum([0, 1.25, -1.25]));;'0.00' +string(sum([0, 0.00]));;'0.00' +string(sum([0.00]));;'0.00' +string(sum([0.00, 1]));;'1.00';bug: a leading zero with scale is dropped from the running total (0.00 + 1 prints '1') +string(sum([1, 0.00]));;'1.00';bug: adding a zero with scale is an identity that drops its scale, unlike sum([1, 0.01, -0.01]) +string(sum([1, 0.01, -0.01]));;'1.00' +string(sum([0.00, 1.5]));;'1.50';bug: a leading zero with scale is dropped from the running total +string(sum([-0.0, 2]));;'2.0';bug: a leading zero with scale is dropped from the running total +string(sum([0.001, 1000]));;'1000.001' +sum([0.1000000000000000000000000001, 1]);;1.1000000000000000000000000001 +sum([9223372036854775807, 1]);;9223372036854775808 +sum([9223372036854775807, 9223372036854775807]);;18446744073709551614 +sum([-9223372036854775808, -1]);;-9223372036854775809 +sum([79228162514264337593543950335, 0]);;79228162514264337593543950335 +sum([79228162514264337593543950335, 1]);;!error +sum([79228162514264337593543950335, 1, -1]);;!error;question: overflow is detected in the running total even when the final sum is representable +sum([79228162514264337593543950335, -1, 1]);;79228162514264337593543950335 +sum([-79228162514264337593543950335, -1]);;!error +sum([1e3, 1e-3]);;1000.001 +sum([1, 2] + [3]);;!error +sum(1);;!error +sum(1, 2);;!error +sum();;!error +sum(null);;!error +sum('123');;!error +sum({a: 1});;!error +sum([1, null]);;!error +sum([null]);;!error +sum([1, '2']);;!error +sum([1, true]);;!error +sum([[1, 2]]);;!error +sum([1, [2]]);;!error +sum([{a: 1}]);;!error +sum([d('2024-01-01')]);;!error +sum(1..3);;!error +sum(map([1, 2, 3], # * 2));;12 +sum(map([0.1, 0.2, 0.3], # * 10));;6 +string(sum(map([1, 2], # * 1.5)));;'4.5' +sum(filter([1, -2, 3], # > 0));;4 +sum(filter([1, 2], # > 5));;0 +sum(map([1, 2, 3], #)) / len([1, 2, 3]);;2 +# avg +avg([10, 20, 30]);;20 +avg([1, 2]);;1.5 +avg([1, 1, 2]);;1.3333333333333333333333333333 +avg([2, 2, 2]);;2 +avg([5]);;5 +avg([-1, 1]);;0 +avg([0.1, 0.2]);;0.15 +avg([1, 2, 3, 4]);;2.5 +avg([2, 1]);;1.5 +avg([1, 2, 2]);;1.6666666666666666666666666667 +avg([-1, -2]);;-1.5 +avg([-1, -1, -2]);;-1.3333333333333333333333333333 +string(avg([1.5, 1.5]));;'1.5' +string(avg([1.50, 2.50]));;'2.00' +string(avg([10, 20, 30]));;'20' +string(avg([1, 2]));;'1.50';question: the mean's scale follows Decimal division (3 / 2 prints '1.50'), not the inputs' scale +string(avg([1, 1, 2]));;'1.3333333333333333333333333333' +avg([9223372036854775807, 9223372036854775807]);;9223372036854775807 +avg([9223372036854775807, 9223372036854775806]);;9223372036854775806.5 +avg([79228162514264337593543950335]);;79228162514264337593543950335 +avg([79228162514264337593543950335, 79228162514264337593543950335]);;79228162514264337593543950335;bug: the mean is representable but the intermediate sum overflows +avg([0.0000000000000000000000000001, 0]);;0.0000000000000000000000000000;question: the exact mean 0.00000000000000000000000000005 has too many digits and is rounded +avg([]);;!error;question: average of an empty list fails; could be null +avg(null);;!error +avg([1, null]);;!error +avg([1, '2']);;!error +avg([true]);;!error +avg([[1]]);;!error +avg([d('2024-01-01')]);;!error +avg(1);;!error +avg();;!error +avg(map([1, 2, 3], # * 0.5));;1 +avg(filter([1, 2, 3, 4], # % 2 == 0));;3 +# min and max +min([5, 2, 8, 1]);;1 +max([5, 2, 8, 1]);;8 +min([5]);;5 +max([5]);;5 +min([-1, -5, 0]);;-5 +max([-1, -5, 0]);;0 +min([-1, -5]);;-5 +max([-1, -5]);;-1 +min([0.1, 0.01, 0.001]);;0.001 +max([0.1, 0.01, 0.001]);;0.1 +min([9223372036854775807, 9223372036854775808]);;9223372036854775807 +max([9223372036854775807, 9223372036854775808]);;9223372036854775808 +min([-9223372036854775808, -9223372036854775809]);;-9223372036854775809 +max([79228162514264337593543950335, -79228162514264337593543950335]);;79228162514264337593543950335 +min([79228162514264337593543950335, -79228162514264337593543950335]);;-79228162514264337593543950335 +min([0.0000000000000000000000000001, 0]);;0 +max([0.0000000000000000000000000001, 0]);;0.0000000000000000000000000001 +min([1e3, 999.999]);;999.999 +string(max([1, 1.0, 1.00]));;'1.00';question: among equal values max returns the last one, so the result scale depends on order +string(min([1, 1.0, 1.00]));;'1';question: among equal values min returns the first one, so the result scale depends on order +string(max([1.00, 1.0, 1]));;'1';question: among equal values max returns the last one, so the result scale depends on order +string(min([1.00, 1.0, 1]));;'1.00';question: among equal values min returns the first one, so the result scale depends on order +string(max([2.50, 1, 2.5]));;'2.5';question: among equal values max returns the last one, so the result scale depends on order +string(min([0.10, 5, 0.1]));;'0.10' +string(max([1.50, -1]));;'1.50' +min([]);;!error;question: minimum of an empty list fails; could be null +max([]);;!error;question: maximum of an empty list fails; could be null +min(null);;!error +max(null);;!error +min(1);;!error +max(1, 2);;!error +min();;!error +min([1, null]);;!error +max([null, 1]);;!error +max([1, '2']);;!error +min(['a', 'b']);;!error +max([true, false]);;!error +max([[1], [2]]);;!error +max([1, [2]]);;!error +min([{a: 1}]);;!error +max(1..3);;!error +# min and max over dates +min([d('2024-01-01'), d('2023-06-15')]);;'2023-06-15T00:00:00Z' +max([d('2024-01-01'), d('2023-06-15')]);;'2024-01-01T00:00:00Z' +max([d('2024-01-01')]);;'2024-01-01T00:00:00Z' +min([d('2024-01-01T10:00:00Z'), d('2024-01-01T09:59:59Z'), d('2024-01-02')]);;'2024-01-01T09:59:59Z' +max([d('2024-01-01T10:00:00Z'), d('2024-01-01T09:59:59Z'), d('2024-01-02')]);;'2024-01-02T00:00:00Z' +max([d('2024-01-01'), 1]);;!error +max([1, d('2024-01-01')]);;!error +min([d('2024-01-01'), null]);;!error +min(['2024-01-01', '2023-01-01']);;!error;question: date strings are not accepted by min/max while d() values are +max(map([1, 2, 3], d('2024-01-01').add(#, 'd')));;'2024-01-04T00:00:00Z' +# median +median([1, 2, 3, 4, 5]);;3 +median([4, 2, 7, 5, 3]);;4 +median([5, 1]);;3 +median([1, 2]);;1.5 +median([1, 2, 3, 4]);;2.5 +median([4, 1, 3, 2]);;2.5 +median([7]);;7 +median([-3, -1, -2]);;-2 +median([-1, 2]);;0.5 +median([1, 1, 1, 100]);;1 +median([0.1, 0.2]);;0.15 +median([1, 2, 4, 3, 100, -50]);;2.5 +string(median([1.0, 2.0]));;'1.5' +string(median([1, 2]));;'1.50';question: the median's scale follows Decimal division (3 / 2 prints '1.50'), not the inputs' scale +string(median([1.50, 2.50]));;'2.00' +string(median([3, 1.00, 2]));;'2' +median([9223372036854775807, 9223372036854775806]);;9223372036854775806.5 +median([79228162514264337593543950335, 79228162514264337593543950335]);;79228162514264337593543950335;bug: the median is representable but the midpoint sum overflows +median([]);;!error;question: median of an empty list fails; could be null +median(null);;!error +median([1, null]);;!error +median([1, '2']);;!error +median([d('2024-01-01')]);;!error +median(1);;!error +median(map([3, 1, 2], # * 2));;4 +# mode +mode([1, 2, 2, 3, 3, 3]);;3 +mode([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]);;4 +mode([5]);;5 +mode([4, 4, 1]);;4 +mode([-1, -1, 2]);;-1 +mode([0.5, 0.5, 1]);;0.5 +mode([1, 2]);;2;question: ties resolve to the largest value +mode([2, 1]);;2;question: ties resolve to the largest value +mode([3, 3, 1, 1, 2]);;3;question: ties resolve to the largest value +mode([-5, -5, -7, -7]);;-5;question: ties resolve to the largest value +mode([1, 1.0, 2]);;1 +string(mode([1.0, 1, 2]));;'1.0';question: equal values with different scales count together and the first spelling wins +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(['a', 'a']);;!error +mode([true]);;!error +mode(1);;!error +# aggregates over literal arrays built from computed values +max([1 + 1, 2 * 2, 3]);;4 +min([abs(-3), round(2.5), floor(1.9)]);;1 +sum([round(1.25, 1), trunc(1.25, 1)]);;2.5 +avg([min([1, 2]), max([3, 4])]);;2.5 +median([sum([1, 2]), avg([4, 6]), 1]);;3 +max([len('abc'), 2]);;3 diff --git a/core/expression/tests/spec/standard/06-conversion.csv b/core/expression/tests/spec/standard/06-conversion.csv new file mode 100644 index 00000000..f414bb20 --- /dev/null +++ b/core/expression/tests/spec/standard/06-conversion.csv @@ -0,0 +1,120 @@ +expression (string);input (json 5);output (json 5);note +# number: numbers and booleans +number(123);;123 +number(-1.5);;-1.5 +string(number(1.50));;'1.50' +number(true);;1 +number(false);;0 +number(79228162514264337593543950335);;79228162514264337593543950335 +# number: strings +number('123');;123 +number('12.5');;12.5 +number('-12.5');;-12.5 +number('+12.5');;12.5 +string(number('1.50'));;'1.50' +string(number('0.000'));;'0.000' +number('0');;0 +number('-0');;0 +number(' 42 ');;42 +number(' -7 ');;-7 +number('1e3');;1000 +number('1E3');;1000 +number('1.5e1');;15 +number('1e-2');;0.01 +number('-2.5e2');;-250 +number('1e+3');;1000 +string(number('1e3'));;'1000' +number('.5');;0.5 +number('5.');;5 +number('007');;7 +number('9223372036854775807');;9223372036854775807 +number('9223372036854775808');;9223372036854775808 +number('-9223372036854775809');;-9223372036854775809 +number('79228162514264337593543950335');;79228162514264337593543950335 +number('79228162514264337593543950336');;!error +number('0.1000000000000000000000000001');;0.1000000000000000000000000001 +string(number('-0'));;'0' +string(number('-0.0'));;'0.0' +string(number('1.5e1'));;'15' +string(number('2.50e1'));;'25.0' +string(number('1e0'));;'1' +string(number('1e-2'));;'0.01' +number(' 1e3 ');;1000 +number('1e28');;10000000000000000000000000000 +number('1e29');;!error +number('1e-28');;0.0000000000000000000000000001 +number('1e-29');;!error;question: a value below the smallest representable step fails instead of rounding to 0 +number('0.12345678901234567890123456789');;!error;question: a string with more fractional digits than Decimal holds fails instead of rounding +number('123456789012345678901234567890.5');;!error +number('1_000');;1000 +number('0x10');;!error +number('0b10');;!error +number('');;!error +number(' ');;!error +number('abc');;!error +number('12abc');;!error +number('1,000');;!error +number('1 000');;!error +number('1.2.3');;!error +number('--1');;!error +number('Infinity');;!error +number('NaN');;!error +number('e3');;!error +number('1e');;!error +number('.');;!error +number('-');;!error +number(null);;!error;question: null does not convert; could be null or 0 +number([1]);;!error +number({});;!error +number(d('2024-01-01'));;!error +number();;!error +number('1', 2);;!error +number('1.5') + 1;;2.5 +number('10') * number('0.5');;5 +sum(map(['1', '2.5', '-0.5'], number(#)));;3 +# isNumeric +isNumeric(123);;true +isNumeric(-1.5);;true +isNumeric(0);;true +isNumeric('123');;true +isNumeric('12.5');;true +isNumeric('-12.5');;true +isNumeric('+12.5');;true +isNumeric(' 42 ');;true +isNumeric('1e3');;true +isNumeric('1E3');;true +isNumeric('1e-2');;true +isNumeric('.5');;true +isNumeric('5.');;true +isNumeric('-0');;true +isNumeric('79228162514264337593543950335');;true +isNumeric('79228162514264337593543950336');;false +isNumeric('hello');;false +isNumeric('');;false +isNumeric(' ');;false +isNumeric('1_000');;true +isNumeric('0x10');;false +isNumeric('1,000');;false +isNumeric('1.2.3');;false +isNumeric('Infinity');;false +isNumeric('NaN');;false +isNumeric('12abc');;false +isNumeric(true);;false;question: number(true) converts to 1 but isNumeric(true) is false +isNumeric(false);;false;question: number(false) converts to 0 but isNumeric(false) is false +isNumeric(null);;false +isNumeric([1]);;false +isNumeric({});;false +isNumeric(d('2024-01-01'));;false +isNumeric();;!error +# rand: only deterministic properties +rand(0);;0 +rand(0.4);;0 +rand(-0.4);;0 +"r = rand(10); r >= 0 and r <= 10 and r == trunc(r)";{};true +"r = rand(1); r == 0 or r == 1";{};true +"r = rand(9223372036854775807); r >= 0";{};true +type(rand(5));;'number' +rand(null);;!error +rand('5');;!error +rand();;!error +rand(79228162514264337593543950335);;!error diff --git a/core/expression/tests/spec/standard/06-inputs.csv b/core/expression/tests/spec/standard/06-inputs.csv new file mode 100644 index 00000000..338dc51b --- /dev/null +++ b/core/expression/tests/spec/standard/06-inputs.csv @@ -0,0 +1,287 @@ +expression (string);input (json 5);output (json 5);note +# round(a, 2) over mixed inputs +round(a, 2);{a: 0.5};0.5 +round(a, 2);{a: 1.25};1.25 +round(a, 2);{a: -0.10};-0.1 +round(a, 2);{a: 1234567.891};1234567.89 +round(a, 2);{a: 1.005};1.01 +round(a, 2);{a: -1.005};-1.01 +round(a, 2);{a: 2.675};2.68 +round(a, 2);{a: 9223372036854775807};9223372036854775807 +round(a, 2);{a: 922337203685477580.735};922337203685477580.74 +round(a, 2);{a: 92233720368547758.075};92233720368547758.08 +round(a, 2);{a: 0};0 +round(a, 2);{a: -0.004};0 +round(a, 2);{a: 79228162514264337593543950335};79228162514264337593543950335 +round(a, 2);{a: 0.0000000000000000000000000001};0 +round(a, 2);{a: null};!error +round(a, 2);{};!error +round(a, 2);{a: '1.5'};!error +round(a, 2);{a: true};!error +round(a, 2);{a: [1.5]};!error +# string(round(a, 2)) observes scale +string(round(a, 2));{a: 0.5};'0.5' +string(round(a, 2));{a: 1.25};'1.25' +string(round(a, 2));{a: -0.10};'-0.10' +string(round(a, 2));{a: 1234567.891};'1234567.89' +string(round(a, 2));{a: 1.995};'2.00' +string(round(a, 2));{a: -1.995};'-2.00' +string(round(a, 2));{a: 7};'7' +string(round(a, 2));{a: 1.2500};'1.25' +string(round(a, 2));{a: -0.004};'0.00' +string(round(a, 2));{a: 9223372036854775807};'9223372036854775807' +# round(a) ties away from zero +round(a);{a: 0.5};1 +round(a);{a: -0.5};-1 +round(a);{a: 2.5};3 +round(a);{a: -2.5};-3 +round(a);{a: 1.49};1 +round(a);{a: -1.25};-1 +round(a);{a: 1234567.891};1234568 +round(a);{a: 9223372036854775806.5};9223372036854775807 +round(a);{a: 9223372036854775807.5};9223372036854775808 +round(a);{a: -9223372036854775808.5};-9223372036854775809 +round(a);{a: 0};0 +round(a);{a: null};!error +string(round(a));{a: -0.4};'0' +string(round(a));{a: 2.50};'3' +string(round(a));{a: -0.10};'0' +# round(a, p) with input precision +round(a, p);{a: 3.14159, p: 0};3 +round(a, p);{a: 3.14159, p: 1};3.1 +round(a, p);{a: 3.14159, p: 4};3.1416 +round(a, p);{a: 3.14159, p: 10};3.14159 +round(a, p);{a: -3.14159, p: 3};-3.142 +round(a, p);{a: 3.14159, p: -1};!error;question: negative precision is rejected +round(a, p);{a: 3.14159, p: null};!error;question: null precision fails; could mean the default precision 0 +round(a, p);{a: 3.14159};!error +round(a, p);{a: 3.14159, p: '2'};!error +string(round(a, p));{a: 2.5, p: 3};'2.5' +string(round(a, p));{a: 2.5555, p: 3};'2.556' +# floor, ceil, trunc, abs over mixed inputs +floor(a);{a: 0.5};0 +floor(a);{a: 1.25};1 +floor(a);{a: -0.10};-1 +floor(a);{a: 1234567.891};1234567 +floor(a);{a: 9223372036854775807};9223372036854775807 +floor(a);{a: -9223372036854775807.5};-9223372036854775808 +floor(a);{a: -9223372036854775808.5};-9223372036854775809 +floor(a);{a: 0};0 +floor(a);{a: null};!error +floor(a);{};!error +ceil(a);{a: 0.5};1 +ceil(a);{a: 1.25};2 +ceil(a);{a: -0.10};0 +ceil(a);{a: 1234567.891};1234568 +ceil(a);{a: 9223372036854775806.1};9223372036854775807 +ceil(a);{a: 9223372036854775807.1};9223372036854775808 +ceil(a);{a: -9223372036854775808.9};-9223372036854775808 +ceil(a);{a: null};!error +ceil(a);{a: 'x'};!error +string(ceil(a));{a: -0.10};'0';bug: ceil of a negative fraction yields negative zero '-0' +string(ceil(a));{a: 1.00};'1' +string(floor(a));{a: -0.10};'-1' +string(floor(a));{a: 2.90};'2' +trunc(a);{a: 0.5};0 +trunc(a);{a: 1.25};1 +trunc(a);{a: -1.25};-1 +trunc(a);{a: 1234567.891};1234567 +trunc(a);{a: -9223372036854775808.9};-9223372036854775808 +trunc(a);{a: 9223372036854775807.9};9223372036854775807 +trunc(a);{a: null};!error +string(trunc(a));{a: -0.10};'0';bug: truncating a negative fraction yields negative zero '-0' +string(trunc(a, 1));{a: 1.25};'1.2' +string(trunc(a, 1));{a: -1.25};'-1.2' +string(trunc(a, 1));{a: 1234567.891};'1234567.8' +string(trunc(a, 1));{a: 5};'5.0';question: trunc pads the result to the requested scale while round(5, 1) keeps scale '5' +abs(a);{a: 0.5};0.5 +abs(a);{a: -1.25};1.25 +abs(a);{a: -0.10};0.1 +abs(a);{a: -9223372036854775808};9223372036854775808 +abs(a);{a: -79228162514264337593543950335};79228162514264337593543950335 +abs(a);{a: 0};0 +abs(a);{a: null};!error +abs(a);{a: '-1'};!error +string(abs(a));{a: -0.10};'0.10' +# sum(list) +sum(list);{list: []};0 +sum(list);{list: [0.5, 1.25, -0.10]};1.65 +sum(list);{list: [1234567.891, 0.109]};1234568 +sum(list);{list: [9223372036854775807, 1]};9223372036854775808 +sum(list);{list: [9223372036854775807, 9223372036854775807]};18446744073709551614 +sum(list);{list: [-9223372036854775808, -9223372036854775808]};-18446744073709551616 +sum(list);{list: [922337203685477580.7, 0.1]};922337203685477580.8 +sum(list);{list: [92233720368547758.07, 0.01]};92233720368547758.08 +sum(list);{list: [0.5, -0.5]};0 +sum(list);{list: [0.1000000000000000000000000001, 1]};1.1000000000000000000000000001 +sum(list);{list: [79228162514264337593543950335, 1]};!error +sum(list);{list: [1, null]};!error +sum(list);{list: ['1']};!error +sum(list);{list: [1, true]};!error +sum(list);{list: [[1]]};!error +sum(list);{list: null};!error +sum(list);{};!error +sum(list);{list: 5};!error +string(sum(list));{list: []};'0' +string(sum(list));{list: [0.5, 1.25, -0.10]};'1.65' +string(sum(list));{list: [1234567.891, 0.109]};'1234568.000' +string(sum(list));{list: [0.5, -0.5]};'0.0' +string(sum(list));{list: [0.1, 0.20]};'0.30' +string(sum(list));{list: [1, 2, 3]};'6' +string(sum(list));{list: [1.10, 2]};'3.10' +string(sum(list));{list: [-0.25, 0.25, -0.50]};'-0.50' +# sum over map and filter results +sum(map(list, # * 1.5));{list: []};0 +sum(map(list, # * 1.5));{list: [0.5, 1.25, -0.10]};2.475 +sum(map(list, # * 1.5));{list: [1234567.891]};1851851.8365 +sum(map(list, # * 1.5));{list: [9223372036854775807, 1]};13835058055282163712 +sum(map(list, # * 1.5));{list: [2, -2]};0 +sum(map(list, # * 1.5));{list: [1, null]};!error +sum(map(list, # * 1.5));{list: ['2']};!error +string(sum(map(list, # * 1.5)));{list: [2, 4]};'9.0' +string(sum(map(list, # * 1.5)));{list: [0.10, 0.30]};'0.600' +sum(map(list, #.price * #.qty));{list: [{price: 9.99, qty: 3}, {price: 0.01, qty: 1}]};29.98 +sum(map(list, #.price * #.qty));{list: [{price: 1.25, qty: -2}, {price: 0.5, qty: 5}]};0 +sum(map(list, #.price * #.qty));{list: []};0 +sum(map(list, #.price * #.qty));{list: [{price: 1}]};!error +string(sum(map(list, #.price * #.qty)));{list: [{price: 9.99, qty: 3}, {price: 0.01, qty: 1}]};'29.98' +sum(filter(list, # > 0));{list: [0.5, 1.25, -0.10]};1.75 +sum(filter(list, # > 0));{list: [-1, -2]};0 +sum(filter(list, # > 0));{list: [9223372036854775807, 9223372036854775807, -1]};18446744073709551614 +sum(filter(list, # > 0));{list: []};0 +string(sum(filter(list, # > 0)));{list: [1.50, -3, 2]};'3.50' +# max and min over filter results +max(filter(list, # > 0));{list: [0.5, 1.25, -0.10]};1.25 +max(filter(list, # > 0));{list: [1234567.891, 9223372036854775807, 1]};9223372036854775807 +max(filter(list, # > 0));{list: [0.0000000000000000000000000001, -1]};0.0000000000000000000000000001 +max(filter(list, # > 0));{list: [-1, -2]};!error +max(filter(list, # > 0));{list: []};!error +max(filter(list, # > 0));{list: [1, null]};!error +min(filter(list, # > 0));{list: [0.5, 1.25, -0.10]};0.5 +min(filter(list, # > 0));{list: [9223372036854775808, 9223372036854775807]};9223372036854775807 +min(filter(list, # > 0));{list: [-5]};!error +min(map(list, # - 1));{list: [0.5, 1.25, -0.10]};-1.1 +max(map(list, # * -1));{list: [0.5, 1.25, -0.10]};0.1 +string(max(filter(list, # > 0)));{list: [1.50, 1.5, -1]};'1.5';question: among equal values max returns the last one, so the result scale depends on order +string(min(filter(list, # > 0)));{list: [1.50, 1.5, -1]};'1.50';question: among equal values min returns the first one, so the result scale depends on order +# min and max over list inputs +max(list);{list: [0.5, 1.25, -0.10]};1.25 +max(list);{list: [-0.10, -0.5]};-0.1 +max(list);{list: [9223372036854775807, 9223372036854775808, 1234567.891]};9223372036854775808 +max(list);{list: [-79228162514264337593543950335, 79228162514264337593543950335]};79228162514264337593543950335 +max(list);{list: [0]};0 +max(list);{list: []};!error +max(list);{list: [1, '2']};!error +max(list);{list: null};!error +max(list);{};!error +min(list);{list: [0.5, 1.25, -0.10]};-0.1 +min(list);{list: [-9223372036854775808, -9223372036854775809]};-9223372036854775809 +min(list);{list: [1234567.891, 1234567.89]};1234567.89 +min(list);{list: [0.0000000000000000000000000001, 0.0000000000000000000000000002]};0.0000000000000000000000000001 +min(list);{list: []};!error +min(list);{list: [null]};!error +string(max(list));{list: [1, 1.0, 1.00]};'1.00';question: among equal values max returns the last one, so the result scale depends on order +string(min(list));{list: [1, 1.0, 1.00]};'1';question: among equal values min returns the first one, so the result scale depends on order +string(max(list));{list: [2.50, 1]};'2.50' +string(min(list));{list: [-0.10, 3]};'-0.10' +# max([a, b, c]) and min with literals +max([a, b, 1.5]);{a: 0.5, b: 1.25};1.5 +max([a, b, 1.5]);{a: 1234567.891, b: -0.10};1234567.891 +max([a, b, 1.5]);{a: -1, b: -2};1.5 +max([a, b, 1.5]);{a: 9223372036854775807, b: 0};9223372036854775807 +max([a, b, 1.5]);{a: 1.5, b: 1.50};1.5 +max([a, b, 1.5]);{a: null, b: 1};!error +max([a, b, 1.5]);{a: 1};!error +max([a, b, 1.5]);{a: '3', b: 1};!error +string(max([a, b, 1.5]));{a: 1.50, b: 0};'1.5';question: among equal values max returns the last one, so the result scale depends on order +string(max([a, b, 1.5]));{a: 1.25, b: 1.500};'1.5';question: among equal values max returns the last one, so the result scale depends on order +min([a, b, c]);{a: 0.5, b: 1.25, c: -0.10};-0.1 +min([a, b, c]);{a: 9223372036854775807, b: 9223372036854775806, c: 9223372036854775808};9223372036854775806 +min([a, b, c]);{a: 0, b: 0.0, c: -0};0 +min([a, b, c]);{a: -79228162514264337593543950335, b: 0, c: 1};-79228162514264337593543950335 +min([a, b, c]);{a: 1, b: 2};!error +min([a, b, c]);{a: 1, b: 2, c: false};!error +string(min([a, b, c]));{a: 2, b: 2.0, c: 2.00};'2';question: among equal values min returns the first one, so the result scale depends on order +string(min([a, b, c]));{a: 0.10, b: 0.1, c: 5};'0.10' +sum([a, b, c]);{a: 0.5, b: 1.25, c: -0.10};1.65 +sum([a, b, c]);{a: 9223372036854775807, b: 9223372036854775807, c: 2};18446744073709551616 +sum([a, b, c]);{a: 1, b: null, c: 2};!error +string(sum([a, b, c]));{a: 0.5, b: 0.25, c: -0.75};'0.00' +avg([a, b]);{a: 1, b: 2};1.5 +avg([a, b]);{a: 0.5, b: -0.10};0.2 +avg([a, b]);{a: 9223372036854775807, b: 9223372036854775807};9223372036854775807 +avg([a, b]);{a: 1};!error +# avg(list) +avg(list);{list: [1, 2]};1.5 +avg(list);{list: [1, 1, 2]};1.3333333333333333333333333333 +avg(list);{list: [0.5, 1.25, -0.10]};0.55 +avg(list);{list: [1234567.891, 0.109]};617284 +avg(list);{list: [9223372036854775807, 9223372036854775806]};9223372036854775806.5 +avg(list);{list: [-0.5, 0.5]};0 +avg(list);{list: [7]};7 +avg(list);{list: []};!error;question: average of an empty list fails; could be null +avg(list);{list: [1, null]};!error +avg(list);{list: null};!error +string(avg(list));{list: [1.50, 2.50]};'2.00' +string(avg(list));{list: [10, 20, 30]};'20' +avg(map(list, # * 2));{list: [0.5, 1.25, -0.10]};1.1 +avg(filter(list, # > 0));{list: [0.5, 1.25, -0.10]};0.875 +avg(filter(list, # > 0));{list: [-1]};!error +round(avg(list), 2);{list: [1, 1, 2]};1.33 +round(avg(list), 2);{list: [1, 2, 2]};1.67 +round(avg(list), 2);{list: [0.125, 0.125]};0.13 +string(round(avg(list), 2));{list: [1, 2]};'1.50';question: the mean's scale follows Decimal division (3 / 2 prints '1.50'), not the inputs' scale +string(avg(list));{list: [1, 2]};'1.50';question: the mean's scale follows Decimal division (3 / 2 prints '1.50'), not the inputs' scale +string(avg(list));{list: [1, 3]};'2' +round(sum(list), 1);{list: [0.25, 0.1]};0.4 +round(sum(list), 1);{list: [-0.25, -0.1]};-0.4 +string(round(sum(list), 1));{list: [0.04, -0.08]};'0.0' +# median and mode over list inputs +median(list);{list: [0.5, 1.25, -0.10]};0.5 +median(list);{list: [0.5, 1.25, -0.10, 1234567.891]};0.875 +median(list);{list: [9223372036854775807, 9223372036854775807]};9223372036854775807 +median(list);{list: [3]};3 +median(list);{list: [2, 1]};1.5 +median(list);{list: []};!error +median(list);{list: [1, 'a']};!error +mode(list);{list: [0.5, 1.25, 0.5]};0.5 +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 +# number and isNumeric over input strings +number(s);{s: '1.5'};1.5 +number(s);{s: ' 42 '};42 +number(s);{s: '1e3'};1000 +number(s);{s: '-0.10'};-0.1 +number(s);{s: '9223372036854775807'};9223372036854775807 +number(s);{s: ''};!error +number(s);{s: 'abc'};!error +number(s);{s: null};!error +number(s);{s: 12.50};12.5 +number(s);{s: true};1 +string(number(s));{s: '-0.10'};'-0.10' +string(number(s));{s: '1234567.891'};'1234567.891' +isNumeric(s);{s: '1.5'};true +isNumeric(s);{s: ' 42 '};true +isNumeric(s);{s: 'abc'};false +isNumeric(s);{s: ''};false +isNumeric(s);{s: null};false +isNumeric(s);{};false +isNumeric(s);{s: 3};true +isNumeric(s);{s: [1]};false +sum(map(list, number(#)));{list: ['0.5', '1.25', '-0.10']};1.65 +sum(map(filter(list, isNumeric(#)), number(#)));{list: ['1', 'x', '2.5', '']};3.5 +# aggregates in conditions +sum(list) > 100;{list: [50, 50.01]};true +sum(list) > 100;{list: [50, 50]};false +max(list) - min(list);{list: [0.5, 1.25, -0.10]};1.35 +max(list) - min(list);{list: [9223372036854775807, -9223372036854775808]};18446744073709551615 +avg(list) == median(list);{list: [1, 2, 3]};true +round(a * b, 2);{a: 19.99, b: 0.075};1.5 +round(a * b, 2);{a: 1234567.891, b: 1.5};1851851.84 +round(a * b, 2);{a: -0.10, b: 0.05};-0.01 +round(a / b, 4);{a: 1, b: 3};0.3333 +round(a / b, 4);{a: 2, b: 3};0.6667 +round(a / b, 4);{a: 1, b: 0};!error diff --git a/core/expression/tests/spec/standard/06-rounding.csv b/core/expression/tests/spec/standard/06-rounding.csv new file mode 100644 index 00000000..7eff944f --- /dev/null +++ b/core/expression/tests/spec/standard/06-rounding.csv @@ -0,0 +1,229 @@ +expression (string);input (json 5);output (json 5);note +# abs +abs(-5);;5 +abs(5);;5 +abs(0);;0 +abs(-0.5);;0.5 +string(abs(-1.50));;'1.50' +string(abs(1.50));;'1.50' +string(abs(-0.0));;'0.0' +string(abs(0));;'0' +abs(-79228162514264337593543950335);;79228162514264337593543950335 +abs(79228162514264337593543950335);;79228162514264337593543950335 +abs(-0.0000000000000000000000000001);;0.0000000000000000000000000001 +abs(-9223372036854775808);;9223372036854775808 +abs(-9223372036854775807);;9223372036854775807 +abs(-1e3);;1000 +abs(3 - 10);;7 +abs(-(2.5));;2.5 +abs(null);;!error +abs('5');;!error +abs('-5');;!error +abs(true);;!error +abs([1]);;!error +abs({});;!error +abs();;!error +abs(1, 2);;!error +abs(d('2024-01-01'));;!error +# round: no precision, ties away from zero +round(0);;0 +round(0.4);;0 +round(0.5);;1 +round(0.6);;1 +round(1.5);;2 +round(2.5);;3 +round(3.5);;4 +round(4.5);;5 +round(-0.4);;0 +round(-0.5);;-1 +round(-0.6);;-1 +round(-1.5);;-2 +round(-2.5);;-3 +round(-3.5);;-4 +round(7.49999999999999999999);;7 +round(7.50000000000000000001);;8 +round(-7.49999999999999999999);;-7 +round(0.4999999999999999999999999999);;0 +round(0.5000000000000000000000000000);;1 +round(123456789.5);;123456790 +round(1e3);;1000 +round(-1e-3);;0 +round(9223372036854775807);;9223372036854775807 +round(9223372036854775806.5);;9223372036854775807 +round(9223372036854775807.5);;9223372036854775808 +round(-9223372036854775808.5);;-9223372036854775809 +round(79228162514264337593543950335);;79228162514264337593543950335 +round(-79228162514264337593543950335);;-79228162514264337593543950335 +round(7922816251426433759354395033.5);;7922816251426433759354395034 +round(0.0000000000000000000000000001);;0 +# round: result scale +string(round(2.5));;'3' +string(round(2.4));;'2' +string(round(2));;'2' +string(round(2.00));;'2' +string(round(-0.4));;'0' +string(round(-0.5));;'-1' +string(round(-0.04, 1));;'0.0' +string(round(-0.0));;'0';bug: rounding negative zero keeps the sign and prints '-0' +string(round(1.005, 2));;'1.01' +string(round(1.004, 2));;'1.00' +string(round(1.10, 2));;'1.10' +string(round(1.1, 2));;'1.1' +string(round(1, 2));;'1' +string(round(1.23456, 3));;'1.235' +string(round(1.2, 0));;'1' +string(round(0.125, 2));;'0.13' +string(round(0.135, 2));;'0.14' +string(round(-0.125, 2));;'-0.13' +string(round(2.675, 2));;'2.68' +string(round(1.45, 1));;'1.5' +string(round(1.55, 1));;'1.6' +string(round(1.95, 1));;'2.0' +string(round(9.995, 2));;'10.00' +string(round(-9.995, 2));;'-10.00' +string(round(99.5));;'100' +# round: precision argument +round(7.444, 0);;7 +round(7.444, 1);;7.4 +round(7.444, 2);;7.44 +round(7.444, 3);;7.444 +round(7.444, 4);;7.444 +round(7.555, 1);;7.6 +round(7.555, 2);;7.56 +round(-7.555, 2);;-7.56 +round(-7.545, 2);;-7.55 +round(1.25, 1);;1.3 +round(1.35, 1);;1.4 +round(-1.25, 1);;-1.3 +round(-1.35, 1);;-1.4 +round(4.567, 2);;4.57 +round(0.0000000000000000000000000005, 27);;0.000000000000000000000000001 +round(0.0000000000000000000000000004, 27);;0 +round(1.5, 28);;1.5 +string(round(1.5, 28));;'1.5' +round(1.5, 29);;1.5 +round(1.5, 100);;1.5 +string(round(1.5, 100));;'1.5' +round(1.5, 4294967295);;1.5 +round(1.5, 4294967296);;!error;question: precision beyond u32 is rejected while 4294967295 is accepted +round(3.14159, 1 + 1);;3.14 +round(1.5, -1);;!error;question: negative precision (round to tens) is rejected; could mean round(15, -1) = 20 +round(15, -1);;!error;question: negative precision (round to tens) is rejected; could mean round(15, -1) = 20 +round(1.55, 1.5);;1.6;question: fractional precision is silently truncated to an integer instead of being rejected +round(1.55, 1.9);;1.6;question: fractional precision is silently truncated to an integer instead of being rejected +round(1.5, 0.5);;2;question: fractional precision is silently truncated to an integer instead of being rejected +round(1.5, null);;!error;question: null precision fails; could mean the default precision 0 +round(1.5, '1');;!error +round(1.5, true);;!error +round(null);;!error +round(null, 2);;!error +round('1.5');;!error +round('1.5', 1);;!error +round(true);;!error +round([1.5]);;!error +round({});;!error +round();;!error +round(1, 2, 3);;!error +round(d('2024-01-01'));;!error +# trunc +trunc(0);;0 +trunc(0.9);;0 +trunc(-0.9);;0 +trunc(4.9);;4 +trunc(-4.9);;-4 +trunc(7.999, 0);;7 +trunc(7.999, 1);;7.9 +trunc(7.999, 2);;7.99 +trunc(-7.999, 2);;-7.99 +trunc(7.999, 3);;7.999 +trunc(7.999, 10);;7.999 +trunc(7.999, 100);;7.999 +trunc(9223372036854775807.9);;9223372036854775807 +trunc(-9223372036854775808.9);;-9223372036854775808 +trunc(79228162514264337593543950335);;79228162514264337593543950335 +trunc(7922816251426433759354395033.3);;7922816251426433759354395033 +7922816251426433759354395033.9;;!error +trunc(0.0000000000000000000000000001, 28);;0.0000000000000000000000000001 +trunc(0.0000000000000000000000000001, 27);;0 +string(trunc(2.50));;'2' +string(trunc(2.59, 1));;'2.5' +string(trunc(2.50, 1));;'2.5' +string(trunc(2.500, 2));;'2.50' +string(trunc(2, 2));;'2.00';question: trunc pads the result to the requested scale while round(1, 2) keeps scale '1' +string(trunc(2.5, 2));;'2.50';question: trunc pads the result to the requested scale while round(1.1, 2) keeps '1.1' +string(trunc(-0.5));;'0';bug: truncating a negative fraction yields negative zero; round(-0.4) prints '0' +string(trunc(-0.05, 1));;'0.0';bug: truncating a negative fraction yields negative zero; round(-0.04, 1) prints '0.0' +string(trunc(-1.5));;'-1' +trunc(1.5, -1);;!error;question: negative precision is rejected like round +trunc(1.59, 1.5);;1.5;question: fractional precision is silently truncated to an integer instead of being rejected +trunc(1.5, null);;!error +trunc(null);;!error +trunc('1.5');;!error +trunc(true);;!error +trunc([1.5]);;!error +trunc();;!error +trunc(1, 2, 3);;!error +# floor +floor(4.9);;4 +floor(4.1);;4 +floor(4);;4 +floor(-4.1);;-5 +floor(-4.9);;-5 +floor(-4);;-4 +floor(0.5);;0 +floor(-0.5);;-1 +floor(-0.0000000000000000000000000001);;-1 +floor(0.9999999999999999999999999999);;0 +floor(9223372036854775807.5);;9223372036854775807 +floor(-9223372036854775808.5);;-9223372036854775809 +floor(79228162514264337593543950335);;79228162514264337593543950335 +floor(-79228162514264337593543950335);;-79228162514264337593543950335 +floor(-7922816251426433759354395033.5);;-7922816251426433759354395034 +string(floor(-0.5));;'-1' +string(floor(0.5));;'0' +string(floor(4.50));;'4' +string(floor(4.00));;'4' +string(floor(-4.00));;'-4' +floor(4.55, 1);;!error;question: floor accepts no precision argument unlike round and trunc +floor(null);;!error +floor('4.5');;!error +floor(true);;!error +floor([4.5]);;!error +floor();;!error +# ceil +ceil(4.1);;5 +ceil(4.9);;5 +ceil(4);;4 +ceil(-4.1);;-4 +ceil(-4.9);;-4 +ceil(0.5);;1 +ceil(-0.5);;0 +ceil(0.0000000000000000000000000001);;1 +ceil(-0.9999999999999999999999999999);;0 +ceil(9223372036854775806.5);;9223372036854775807 +ceil(9223372036854775807.5);;9223372036854775808 +ceil(79228162514264337593543950335);;79228162514264337593543950335 +ceil(7922816251426433759354395033.5);;7922816251426433759354395034 +string(ceil(4.1));;'5' +string(ceil(4.00));;'4' +string(ceil(-0.5));;'0';bug: ceil of a negative fraction yields negative zero '-0'; round(-0.4) prints '0' +string(ceil(-0.0000000000000000000000000001));;'0';bug: ceil of a negative fraction yields negative zero '-0' +ceil(-0.5) == 0;;true +ceil(4.11, 1);;!error;question: ceil accepts no precision argument unlike round and trunc +ceil(null);;!error +ceil('4.5');;!error +ceil(false);;!error +ceil([4.5]);;!error +ceil();;!error +# combinations +floor(-2.5) + ceil(-2.5);;-5 +round(2.5) - trunc(2.5);;1 +abs(floor(-2.5));;3 +round(10 / 3, 2);;3.33 +string(round(10 / 3, 2));;'3.33' +round(2 / 3, 5);;0.66667 +string(round(1 / 3 * 3, 2));;'1.00' +round(1 / 3 * 3);;1 +round(0.1 + 0.2, 1) == 0.3;;true +string(round(1.23 * 100) / 100);;'1.23' +round(abs(-2.5));;3 diff --git a/core/expression/tests/spec/standard/07-01-len-case-trim.csv b/core/expression/tests/spec/standard/07-01-len-case-trim.csv new file mode 100644 index 00000000..0d8c2027 --- /dev/null +++ b/core/expression/tests/spec/standard/07-01-len-case-trim.csv @@ -0,0 +1,182 @@ +expression (string);input (json 5);output (json 5);note +# len: string literals +len('');;0 +len('a');;1 +len('hello');;5 +len('Hello, World!');;13 +len(' ');;1 +len(' ');;3 +len('a b c');;5 +len('ä');;1;bug: len counts UTF-8 bytes (2), docs say length of a string (characters) +len('ß');;1;bug: len counts UTF-8 bytes (2), intended character count +len('日本語');;3;bug: len counts UTF-8 bytes (9), intended character count +len('😀');;1;bug: len counts UTF-8 bytes (4), intended character count +len('\d');;2 +# len: string input rows +len(s);{s: 'abc'};3 +len(s);{s: 'abc'};3 +len(s);{s: ''};0 +len(s);{s: ' \t\n'};3 +len(s);{s: '\r\n'};2 +len(s);{s: 'Hello'};5 +len(s);{s: 'ä'};1;bug: len counts UTF-8 bytes (2), intended character count +len(s);{s: 'straße'};6;bug: len counts UTF-8 bytes (7), intended character count +len(s);{s: 'e\u0301'};2;bug: len counts UTF-8 bytes (3), intended code points (combining mark counts separately) +len(s);{s: 'é'};1;bug: len counts UTF-8 bytes (2), intended character count +len(s);{s: '😀'};1;bug: len counts UTF-8 bytes (4), intended character count +len(s);{s: '👍🏽'};2;bug: len counts UTF-8 bytes (8), intended code points +len(s);{s: '\u00a0'};1;bug: len counts UTF-8 bytes (2), intended character count +len(s);{s: null};!error +len(s);{};!error +len(s);{s: 5};!error +len(s);{s: true};!error +len(s);{s: [1, 2]};2 +len(s);{s: []};0 +len(s);{s: {a: 1}};!error +# len: other argument kinds +len([]);;0 +len([1, [2, 3]]);;2 +len(['ä', 'ö']);;2 +len([null]);;1 +len(null);;!error +len(0);;!error +len(12345);;!error +len(false);;!error +len({});;!error +len({a: 1, b: 2});;!error +len(d('2024-01-01'));;20 +len();;!error +len('a', 'b');;!error +len(string(12345));;5 +len(`${1.50}`);;4 +# upper: literals +upper('hello');;'HELLO' +upper('');;'' +upper(' ');;' ' +upper('HeLLo 123 !?');;'HELLO 123 !?' +upper('HELLO');;'HELLO' +upper('ä');;'Ä' +upper('àéîõü');;'ÀÉÎÕÜ' +upper('ß');;'SS' +upper('straße');;'STRASSE' +upper('ẞ');;'ẞ' +upper('ı');;'I' +upper('i');;'I' +upper('σας');;'ΣΑΣ' +upper('fi');;'FI' +upper('😀');;'😀' +upper('日本');;'日本' +upper('dz');;'DZ' +upper('\d');;'\\D' +# upper: input rows +upper(s);{s: 'abc'};'ABC' +upper(s);{s: 'abc'};'ABC' +upper(s);{s: 'Mixed Case 42'};'MIXED CASE 42' +upper(s);{s: ''};'' +upper(s);{s: ' \t\n'};' \t\n' +upper(s);{s: 'straße'};'STRASSE' +upper(s);{s: 'çà va'};'ÇÀ VA' +upper(s);{s: 'e\u0301'};'E\u0301' +upper(s);{s: 'abc'};'ABC' +upper(s);{s: null};!error +upper(s);{};!error +upper(s);{s: 1};!error +upper(s);{s: true};!error +upper(s);{s: ['a']};!error +upper(s);{s: {a: 'a'}};!error +# upper: arguments +upper();;!error +upper('a', 'b');;!error +upper(null);;!error +upper(1);;!error +upper(1.5);;!error +upper(true);;!error +upper(['a']);;!error +upper(d('2024-01-01'));;'2024-01-01T00:00:00Z' +upper(upper('abc'));;'ABC' +upper(lower('ABC'));;'ABC' +# lower: literals +lower('HELLO');;'hello' +lower('');;'' +lower('HeLLo 123 !?');;'hello 123 !?' +lower('hello');;'hello' +lower('Ä');;'ä' +lower('ÀÉÎÕÜ');;'àéîõü' +lower('ẞ');;'ß' +lower('SS');;'ss' +lower('I');;'i' +lower('İ');;'i\u0307' +lower('Σ');;'σ' +lower('ΣΑΣ');;'σας' +lower('ΟΔΟΣ ΟΔΟΣ');;'οδος οδος' +lower('😀');;'😀' +lower('日本');;'日本' +lower('DZ');;'dz' +# lower: input rows +lower(s);{s: 'ABC'};'abc' +lower(s);{s: 'ABC'};'abc' +lower(s);{s: 'Hello World'};'hello world' +lower(s);{s: ''};'' +lower(s);{s: ' '};' ' +lower(s);{s: 'ÄÖÜ'};'äöü' +lower(s);{s: 'İstanbul'};'i\u0307stanbul' +lower(s);{s: 'ABC'};'abc' +lower(s);{s: '123'};'123' +lower(s);{s: null};!error +lower(s);{};!error +lower(s);{s: 123};!error +lower(s);{s: false};!error +lower(s);{s: ['A']};!error +# lower: arguments and composition +lower();;!error +lower('A', 'B');;!error +lower(null);;!error +lower(0);;!error +lower({});;!error +lower(upper('straße'));;'strasse' +lower(s) == lower(t);{s: 'Hello', t: 'HELLO'};true +lower(s) == lower(t);{s: 'Hello', t: 'hellO'};true +lower(s) == lower(t);{s: 'Hello', t: 'Hallo'};false +lower(s) == lower(t);{s: '', t: ''};true +lower(s) == lower(t);{s: 'ÄB', t: 'äb'};true +lower(s) == lower(t);{s: 'straße', t: 'STRASSE'};false +upper(s) == upper(t);{s: 'straße', t: 'STRASSE'};true +# trim: literals +trim('');;'' +trim(' ');;'' +trim('abc');;'abc' +trim(' hello ');;'hello' +trim(' a b ');;'a b' +trim('a b');;'a b' +trim(' HELLO, WORLD!');;'HELLO, WORLD!' +trim(' ä ');;'ä' +# trim: whitespace classes via input +trim(s);{s: ' abc '};'abc' +trim(s);{s: ' abc '};'abc' +trim(s);{s: '\t a \n'};'a' +trim(s);{s: '\r\n a \r\n'};'a' +trim(s);{s: '\u000ba\u000c'};'a' +trim(s);{s: '\u00a0a\u00a0'};'a' +trim(s);{s: '\u2003a\u3000'};'a' +trim(s);{s: '\u2028a\u2029'};'a' +trim(s);{s: '\u0085a\u0085'};'a' +trim(s);{s: '\u200ba\u200b'};'\u200ba\u200b' +trim(s);{s: '\ufeffa'};'\ufeffa';question: BOM is not Unicode White_Space so it is kept (JS trim removes it) +trim(s);{s: ''};'' +trim(s);{s: ' \t\n\r '};'' +trim(s);{s: 'a\tb'};'a\tb' +trim(s);{s: ' 日本 '};'日本' +trim(s);{s: null};!error +trim(s);{};!error +trim(s);{s: 1};!error +trim(s);{s: true};!error +trim(s);{s: [' a ']};!error +# trim: arguments and composition +trim();;!error +trim(' a ', 'a');;!error +trim(null);;!error +trim(1);;!error +len(trim(s));{s: ' ab '};2 +len(trim(s));{s: ' '};0 +upper(trim(s));{s: ' ab '};'AB' +trim(lower(s));{s: ' AB '};'ab' diff --git a/core/expression/tests/spec/standard/07-02-contains-prefix.csv b/core/expression/tests/spec/standard/07-02-contains-prefix.csv new file mode 100644 index 00000000..6c275d7a --- /dev/null +++ b/core/expression/tests/spec/standard/07-02-contains-prefix.csv @@ -0,0 +1,169 @@ +expression (string);input (json 5);output (json 5);note +# contains: string literals +contains('hello world', 'world');;true +contains('hello world', 'World');;false +contains('hello world', 'o w');;true +contains('hello world', 'hello world');;true +contains('hello', 'hello world');;false +contains('abc', '');;true +contains('', '');;true +contains('', 'a');;false +contains('a.b', '.');;true +contains('abc', '.');;false +contains('a*b', '*');;true +contains('abc', 'b*');;false +contains('äöü', 'ö');;true +contains('äöü', 'o');;false +contains('straße', 'ss');;false +contains('STRASSE', 'SS');;true +contains('日本語', '本');;true +contains('😀👍', '👍');;true +contains('ΣΑΣ', 'σ');;false +contains('abc', ' ');;false +contains('a b', ' ');;true +# contains: string and substring from input +contains(s, t);{s: 'hello', t: 'ell'};true +contains(s, t);{s: 'hello', t: 'ell'};true +contains(s, t);{s: 'hello', t: 'L'};false +contains(s, t);{s: 'hello', t: ''};true +contains(s, t);{s: '', t: ''};true +contains(s, t);{s: '', t: 'x'};false +contains(s, t);{s: '日本語', t: '本'};true +contains(s, t);{s: 'e\u0301', t: '\u0301'};true +contains(s, t);{s: 'a\tb', t: '\t'};true +contains(s, t);{s: null, t: 'a'};!error +contains(s, t);{s: 'a', t: null};!error +contains(s, t);{s: null, t: null};!error +contains(s, t);{t: 'a'};!error +contains(s, t);{s: 'a'};!error +contains(s, t);{s: 5, t: '5'};!error +contains(s, t);{s: '5', t: 5};!error +contains(s, t);{s: 'true', t: true};!error +contains(s, t);{s: ['a', 'b'], t: 'a'};true +contains(s, t);{s: ['ab'], t: 'a'};false +contains(s, t);{s: {a: 1}, t: 'a'};!error +# contains: single-byte needle over many rows +contains(s, 'e');{s: 'hello'};true +contains(s, 'e');{s: 'hello'};true +contains(s, 'e');{s: 'HELLO'};false +contains(s, 'e');{s: ''};false +contains(s, 'e');{s: 'é'};false +contains(s, 'e');{s: 'e\u0301'};true +contains(s, 'e');{s: 'eee'};true +contains(s, 'e');{s: ' '};false +contains(s, 'e');{s: null};!error +contains(s, 'e');{};!error +contains(s, 'e');{s: 1};!error +contains(s, 'e');{s: ['e']};true +# contains: multi-byte needle over many rows +contains(s, 'é');{s: 'café'};true +contains(s, 'é');{s: 'cafe'};false +contains(s, 'é');{s: 'CAFÉ'};false +contains(s, 'é');{s: 'cafe\u0301'};false +contains(s, 'é');{s: ''};false +contains(s, 'é');{s: 'café'};true +# contains: arrays +contains(['a', 'b'], 'a');;true +contains(['A'], 'a');;false +contains([1, 2], 2);;true +contains([1], '1');;false +contains(['1'], 1);;false +contains([true], true);;true +contains([true], 'true');;false +contains([null], null);;true +contains([], null);;false +contains([1.0], 1);;true +contains(['ä'], 'ä');;true +contains([[1]], [1]);;false;question: arrays inside arrays are never equal for contains +contains([{a: 1}], {a: 1});;false;question: objects inside arrays are never equal for contains +contains([d('2024-01-01')], d('2024-01-01'));;true +# contains: bad arguments +contains(1, 1);;!error +contains(null, 'a');;!error +contains('a', null);;!error +contains(true, 'true');;!error +contains({a: 1}, 'a');;!error +contains('abc');;!error +contains();;!error +contains('a', 'b', 'c');;!error +# startsWith: literals +startsWith('hello', 'he');;true +startsWith('hello', 'He');;false +startsWith('hello', 'hello');;true +startsWith('hello', 'hello!');;false +startsWith('hello', 'lo');;false +startsWith('hello', '');;true +startsWith('', '');;true +startsWith('', 'a');;false +startsWith(' abc', 'abc');;false +startsWith('äb', 'ä');;true +startsWith('äb', 'a');;false +startsWith('日本', '日');;true +startsWith('😀x', '😀');;true +startsWith('Straße', 'STRASSE');;false +startsWith('Hello, World!', 'World');;false +# startsWith: input rows +startsWith(s, 'ab');{s: 'abc'};true +startsWith(s, 'ab');{s: 'abc'};true +startsWith(s, 'ab');{s: 'ab'};true +startsWith(s, 'ab');{s: 'a'};false +startsWith(s, 'ab');{s: 'AB'};false +startsWith(s, 'ab');{s: ''};false +startsWith(s, 'ab');{s: ' ab'};false +startsWith(s, 'ab');{s: null};!error +startsWith(s, 'ab');{};!error +startsWith(s, 'ab');{s: 12};!error +startsWith(s, 'ab');{s: ['ab']};!error +startsWith(s, t);{s: 'prefix-x', t: 'prefix-'};true +startsWith(s, t);{s: 'prefix-x', t: ''};true +startsWith(s, t);{s: 'e\u0301', t: 'e'};true +startsWith(s, t);{s: '\u00e9', t: 'e'};false +startsWith(s, t);{s: 'x', t: null};!error +startsWith(s, t);{s: '1', t: 1};!error +# startsWith: bad arguments +startsWith(1, '1');;!error +startsWith(null, 'a');;!error +startsWith('a', null);;!error +startsWith(true, 't');;!error +startsWith(['a'], 'a');;!error +startsWith('a');;!error +startsWith('a', 'b', 'c');;!error +# endsWith: literals +endsWith('hello', 'lo');;true +endsWith('hello', 'LO');;false +endsWith('hello', 'hello');;true +endsWith('hello', 'ohello');;false +endsWith('hello', '');;true +endsWith('', '');;true +endsWith('', 'a');;false +endsWith('a', 'ba');;false +endsWith('abc ', 'abc');;false +endsWith('ß', 's');;false +endsWith('straße', 'ße');;true +endsWith('日本語', '語');;true +endsWith('x😀', '😀');;true +endsWith('file.CSV', '.csv');;false +# endsWith: input rows +endsWith(s, '.csv');{s: 'a.csv'};true +endsWith(s, '.csv');{s: 'a.csv'};true +endsWith(s, '.csv');{s: 'a.CSV'};false +endsWith(s, '.csv');{s: '.csv'};true +endsWith(s, '.csv');{s: 'csv'};false +endsWith(s, '.csv');{s: ''};false +endsWith(s, '.csv');{s: 'a.csv\n'};false +endsWith(s, '.csv');{s: null};!error +endsWith(s, '.csv');{};!error +endsWith(s, '.csv');{s: 1};!error +endsWith(s, '.csv');{s: false};!error +endsWith(s, t);{s: 'e\u0301', t: '\u0301'};true +endsWith(s, t);{s: 'e\u0301', t: 'é'};false +endsWith(s, t);{s: 'abc', t: ''};true +endsWith(s, t);{s: 'abc', t: null};!error +# endsWith: bad arguments +endsWith(1, '1');;!error +endsWith(10, 0);;!error +endsWith(null, '');;!error +endsWith('a');;!error +endsWith('a', 'b', 'c');;!error +startsWith(lower(s), 'ab') and endsWith(lower(s), 'yz');{s: 'ABxYZ'};true +startsWith(lower(s), 'ab') and endsWith(lower(s), 'yz');{s: 'abxy'};false diff --git a/core/expression/tests/spec/standard/07-03-regex.csv b/core/expression/tests/spec/standard/07-03-regex.csv new file mode 100644 index 00000000..a6c221b5 --- /dev/null +++ b/core/expression/tests/spec/standard/07-03-regex.csv @@ -0,0 +1,152 @@ +expression (string);input (json 5);output (json 5);note +# matches: search semantics and anchors +matches('hello123', '[a-z]+[0-9]+');;true +matches('Hello, World!', 'H[a-z]+, W[a-z]+!');;true +matches('Hello, World!', '[0-9]+');;false +matches('abc', 'b');;true +matches('abc', '^b');;false +matches('abc', 'b$');;false +matches('abc', '^abc$');;true +matches('abcd', '^abc$');;false +matches('xabc', '^abc');;false +matches('abc', '\Aabc\z');;true +matches('abc', '');;true +matches('', '');;true +matches('', '^$');;true +matches('a', '^$');;false +matches('', '.');;false +# matches: case sensitivity and flags +matches('ABC', 'abc');;false +matches('ABC', '(?i)abc');;true +matches('ÄBC', '(?i)äbc');;true +matches('ΣΑΣ', '(?i)σας');;true +# matches: escaping and special characters +matches('a.c', 'a\.c');;true +matches('abc', 'a\.c');;false +matches('abc', 'a.c');;true +matches('a+b', 'a\+b');;true +matches('aab', 'a+b');;true +matches('a|b', '^a\|b$');;true +matches('a b', 'a\sb');;true +matches('(x)', '^\(x\)$');;true +matches('$5', '^\$\d$');;true +matches('back\slash', '\\');;true +matches('tab', '\t');;false +matches('a/b', 'a/b');;true +# matches: unicode classes +matches('ä', '^.$');;true +matches('😀', '^.$');;true +matches('ä', '^\w$');;true +matches('日本', '^\p{Han}+$');;true +matches('abc', '\p{Lu}');;false +matches('aBc', '\p{Lu}');;true +matches('ß', '^\p{Ll}$');;true +matches('Ω', '^[α-ω]$');;false +matches('ω', '^[α-ω]$');;true +# matches: input rows with a fixed pattern +matches(s, '^[0-9]+$');{s: '123'};true +matches(s, '^[0-9]+$');{s: '123'};true +matches(s, '^[0-9]+$');{s: '12a'};false +matches(s, '^[0-9]+$');{s: ''};false +matches(s, '^[0-9]+$');{s: ' 123'};false +matches(s, '^[0-9]+$');{s: '١٢٣'};false +matches(s, '^[0-9]+$');{s: null};!error +matches(s, '^[0-9]+$');{};!error +matches(s, '^[0-9]+$');{s: 123};!error +matches(s, '^[0-9]+$');{s: ['1']};!error +matches(s, '^\d+$');{s: '123'};true +matches(s, '^\d+$');{s: '١٢٣'};true;question: \d is Unicode-aware (matches Arabic-Indic digits), unlike JS +matches(s, '^b$');{s: 'a\nb'};false +matches(s, '(?m)^b$');{s: 'a\nb'};true +matches(s, 'a.b');{s: 'a\nb'};false +matches(s, '(?s)a.b');{s: 'a\nb'};true +matches(s, '^\s+$');{s: ' \t\n'};true +matches(s, '^\s+$');{s: ' '};true +matches(s, '^\s+$');{s: ''};false +# matches: dynamic pattern rows +matches(s, p);{s: 'abc', p: 'b'};true +matches(s, p);{s: 'abc', p: '^b'};false +matches(s, p);{s: 'abc', p: 'b'};true +matches(s, p);{s: '', p: ''};true +matches(s, p);{s: 'abc', p: '('};!error +matches(s, p);{s: null, p: 'a'};!error +matches(s, p);{s: 'a', p: null};!error +matches(s, p);{s: 'a', p: 1};!error +matches(s, p);{s: 'a'};!error +# matches: invalid and unsupported patterns +matches('abc', '(');;!error +matches('abc', ')');;!error +matches('abc', '[');;!error +matches('abc', '[a-');;!error +matches('abc', '*');;!error +matches('abc', 'a**');;true +matches('abc', '\');;!error +matches('abc', '\p{Nope}');;!error +matches('aa', '(a)\1');;!error;question: regex flavour has no backreferences +matches('ab', 'a(?=b)');;!error;question: regex flavour has no lookaround +matches('abc', 'z{2}');;false +matches('abc', 'c{0}');;true +# matches: bad arguments +matches(1, '1');;!error +matches(null, 'a');;!error +matches('a', null);;!error +matches(true, 'true');;!error +matches(['a'], 'a');;!error +matches('a');;!error +matches('a', 'a', 'a');;!error +# extract: groups +extract('2022-09-18', '(\d{4})-(\d{2})-(\d{2})');;['2022-09-18', '2022', '09', '18'] +extract('abc', 'b');;['b'] +extract('abcabc', 'b');;['b'] +extract('abc', 'x');;[] +extract('', 'a');;[] +extract('abc', '');;[''] +extract('', '');;[''] +extract('abc', '(?:b)');;['b'] +extract('abc', '(?:b)(c)');;['bc', 'c'] +extract('key=val', '(?P\w+)=(?P\w+)');;['key=val', 'key', 'val'] +extract('a1b2', '\d');;['1'] +extract('a1b2', '[a-z](\d)$');;['b2', '2'] +extract('aaa', '(a)*');;['aaa', 'a'] +extract('x=', '(\w)=(\w*)');;['x=', 'x', ''] +# extract: greedy vs lazy +extract('aaa', 'a+');;['aaa'] +extract('aaa', 'a+?');;['a'] +extract('', '<.+>');;[''] +extract('', '<.+?>');;[''] +extract('', '<(.+?)>');;['', 'a'] +extract('aaa', 'a*?');;[''] +# extract: non-participating groups +extract('ab', '(a)|(b)');;['a', 'a', null];bug: non-participating groups are dropped, shifting group positions (got ['a', 'a']) +extract('b', '(a)|(b)');;['b', null, 'b'];bug: non-participating groups are dropped, group 2 lands at index 1 (got ['b', 'b']) +extract('ac', 'a(b)?c');;['ac', null];bug: optional group that did not participate is dropped (got ['ac']) +# extract: unicode +extract('Ä', '(?i)ä');;['Ä'] +extract('ÄÖ', '(\p{L})(\p{L})');;['ÄÖ', 'Ä', 'Ö'] +extract('日本語', '(.)(.)');;['日本', '日', '本'] +extract('😀x', '(.)x');;['😀x', '😀'] +extract('straße 12', '(\w+) (\d+)');;['straße 12', 'straße', '12'] +# extract: input rows +extract(s, '(\w+)@(\w+)\.com');{s: 'a@b.com'};['a@b.com', 'a', 'b'] +extract(s, '(\w+)@(\w+)\.com');{s: 'a@b.com'};['a@b.com', 'a', 'b'] +extract(s, '(\w+)@(\w+)\.com');{s: 'mail me: joe@site.com!'};['joe@site.com', 'joe', 'site'] +extract(s, '(\w+)@(\w+)\.com');{s: 'x'};[] +extract(s, '(\w+)@(\w+)\.com');{s: ''};[] +extract(s, '(\w+)@(\w+)\.com');{s: 'ü@ö.com'};['ü@ö.com', 'ü', 'ö'] +extract(s, '(\w+)@(\w+)\.com');{s: null};!error +extract(s, '(\w+)@(\w+)\.com');{};!error +extract(s, '(\w+)@(\w+)\.com');{s: 5};!error +extract(s, p);{s: 'abc', p: '(b)'};['b', 'b'] +extract(s, p);{s: 'abc', p: '['};!error +extract(s, p);{s: 'abc', p: null};!error +len(extract(s, '(\d+)'));{s: 'no digits'};0 +len(extract(s, '(\d+)'));{s: 'n=42'};2 +extract(s, '(\d+)')[1];{s: 'n=42'};'42' +# extract: bad arguments +extract('abc', '(');;!error +extract('abc', '[a-');;!error +extract(1, '1');;!error +extract(null, 'a');;!error +extract('a', null);;!error +extract('a');;!error +extract('a', 'a', 'a');;!error diff --git a/core/expression/tests/spec/standard/07-04-split-fuzzy.csv b/core/expression/tests/spec/standard/07-04-split-fuzzy.csv new file mode 100644 index 00000000..2c13efe6 --- /dev/null +++ b/core/expression/tests/spec/standard/07-04-split-fuzzy.csv @@ -0,0 +1,126 @@ +expression (string);input (json 5);output (json 5);note +# split: single-character separator +split('a,b,c', ',');;['a', 'b', 'c'] +split('hello1,hello2,hello3', ',');;['hello1', 'hello2', 'hello3'] +split('a', ',');;['a'] +split('', ',');;[''] +split(',', ',');;['', ''] +split(',a,', ',');;['', 'a', ''] +split('a,,b', ',');;['a', '', 'b'] +split(',,', ',');;['', '', ''] +split('a b c', ' ');;['a', 'b', '', 'c'] +split('abc', 'B');;['abc'] +split('aBc', 'B');;['a', 'c'] +# split: separators are literal, not regex +split('a.b', '.');;['a', 'b'] +split('a|b', '|');;['a', 'b'] +split('a*b', '*');;['a', 'b'] +split('a1b2c', '\d');;['a1b2c'] +split('a\db', '\d');;['a', 'b'] +# split: multi-character separator +split('a::b::c', '::');;['a', 'b', 'c'] +split('a:::b', '::');;['a', ':b'] +split('::a::', '::');;['', 'a', ''] +split('aaa', 'aa');;['', 'a'] +split('a, b, c', ', ');;['a', 'b', 'c'] +split('abc', 'abc');;['', ''] +split('ab', 'abc');;['ab'] +# split: empty separator +split('abc', '');;['a', 'b', 'c'];bug: empty separator yields leading and trailing empty strings (got ['', 'a', 'b', 'c', '']) +split('a,b', '');;['a', ',', 'b'];bug: empty separator yields leading and trailing empty strings +split('äö', '');;['ä', 'ö'];bug: empty separator yields leading and trailing empty strings +split('', '');;[];bug: splitting an empty string into characters yields ['', ''] +# split: unicode +split('ÄxÖ', 'x');;['Ä', 'Ö'] +split('日,本', ',');;['日', '本'] +split('a😀b', '😀');;['a', 'b'] +split('straße', 'ß');;['stra', 'e'] +split('STRASSE', 'ß');;['STRASSE'] +# split: input rows +split(s, ',');{s: 'a,b'};['a', 'b'] +split(s, ',');{s: 'a,b'};['a', 'b'] +split(s, ',');{s: ''};[''] +split(s, ',');{s: ','};['', ''] +split(s, ',');{s: 'x'};['x'] +split(s, ',');{s: 'ä,ö,ü'};['ä', 'ö', 'ü'] +split(s, ',');{s: ' a , b '};[' a ', ' b '] +split(s, ',');{s: null};!error +split(s, ',');{};!error +split(s, ',');{s: 5};!error +split(s, ',');{s: ['a,b']};!error +split(s, t);{s: 'a\tb', t: '\t'};['a', 'b'] +split(s, t);{s: 'l1\nl2\n', t: '\n'};['l1', 'l2', ''] +split(s, t);{s: 'l1\r\nl2', t: '\n'};['l1\r', 'l2'] +split(s, t);{s: 'a b', t: ' '};['a', 'b'] +split(s, t);{s: 'a\u00a0b', t: ' '};['a\u00a0b'] +split(s, t);{s: 'a,b', t: null};!error +split(s, t);{s: 'a1b', t: 1};!error +len(split(s, ','));{s: 'a,b,c'};3 +len(split(s, ','));{s: ''};1 +len(split(s, ','));{s: 'abc'};1 +map(split(s, ','), trim(#));{s: ' a , b ,c'};['a', 'b', 'c'] +map(split('123,456,789', ','), number(#));;[123, 456, 789] +split(s, ',')[1];{s: 'a,b'};'b' +split(s, ',')[5];{s: 'a,b'};null +# split: bad arguments +split('a');;!error +split('a', ',', 1);;!error +split();;!error +split(1, ',');;!error +split('a1b', 1);;!error +split(null, ',');;!error +split('a', null);;!error +split(true, 'r');;!error +# fuzzyMatch: strings +fuzzyMatch('hello', 'hello');;1 +fuzzyMatch('world', 'hello');;0.2 +fuzzyMatch('abc', 'abd');;0.666666666666667;question: score is an f64 rounded to 15 significant digits, not an exact decimal +fuzzyMatch('', '');;1 +fuzzyMatch('a', '');;0 +fuzzyMatch('', 'abc');;0 +fuzzyMatch('abc', 'ABC');;0 +fuzzyMatch('abc', 'xyz');;0 +fuzzyMatch('ab', 'ba');;0.5 +fuzzyMatch('abcd', 'abdc');;0.75 +fuzzyMatch('abcd', 'abc');;0.75 +fuzzyMatch('kitten', 'sitting');;0.571428571428571 +fuzzyMatch('ä', 'a');;0 +fuzzyMatch('äb', 'ab');;0.5 +fuzzyMatch('日本', '日本語');;0.666666666666667 +fuzzyMatch('straße', 'strasse');;0.714285714285714 +fuzzyMatch('hello', 'helo') > 0.7;;true +round(fuzzyMatch('abc', 'abd'), 2);;0.67 +string(fuzzyMatch('world', 'hello'));;'0.2' +string(fuzzyMatch('hello', 'hello'));;'1' +type(fuzzyMatch('a', 'b'));;'number' +# fuzzyMatch: arrays +fuzzyMatch(['hello', 'world'], 'hello');;[1, 0.2] +fuzzyMatch([], 'a');;[] +fuzzyMatch([''], '');;[1] +fuzzyMatch(['ab', 'ba', 'xy'], 'ab');;[1, 0.5, 0] +fuzzyMatch(['a', 1], 'a');;!error +fuzzyMatch(['a', null], 'a');;!error +fuzzyMatch([['a']], 'a');;!error +# fuzzyMatch: input rows +fuzzyMatch(s, 'kitten');{s: 'kitten'};1 +fuzzyMatch(s, 'kitten');{s: 'kitten'};1 +fuzzyMatch(s, 'kitten');{s: 'sitten'};0.833333333333333 +fuzzyMatch(s, 'kitten');{s: ''};0 +fuzzyMatch(s, 'kitten');{s: 'KITTEN'};0 +fuzzyMatch(s, 'kitten');{s: 'kittén'};0.833333333333333 +fuzzyMatch(s, 'kitten');{s: ['kitten', 'mitten']};[1, 0.833333333333333] +fuzzyMatch(s, 'kitten');{s: null};!error +fuzzyMatch(s, 'kitten');{};!error +fuzzyMatch(s, 'kitten');{s: 1};!error +fuzzyMatch(s, t);{s: 'abc', t: 'abc'};1 +fuzzyMatch(s, t);{s: 'abc', t: null};!error +fuzzyMatch(s, t);{s: 'abc', t: ['abc']};!error +# fuzzyMatch: bad arguments +fuzzyMatch('a');;!error +fuzzyMatch();;!error +fuzzyMatch('a', 'b', 'c');;!error +fuzzyMatch(1, 'a');;!error +fuzzyMatch(null, 'a');;!error +fuzzyMatch('a', null);;!error +fuzzyMatch('a', 1);;!error +fuzzyMatch({a: 'a'}, 'a');;!error diff --git a/core/expression/tests/spec/standard/07-05-conversions.csv b/core/expression/tests/spec/standard/07-05-conversions.csv new file mode 100644 index 00000000..4ba1e182 --- /dev/null +++ b/core/expression/tests/spec/standard/07-05-conversions.csv @@ -0,0 +1,208 @@ +expression (string);input (json 5);output (json 5);note +# string: numbers keep their scale +string(123);;'123' +string(123.123);;'123.123' +string(0);;'0' +string(-1.5);;'-1.5' +string(1.10);;'1.10' +string(1.0);;'1.0' +string(100);;'100' +string(0.5);;'0.5' +string(0.000001);;'0.000001' +string(1e3);;'1000' +string(1.5e3);;'1500' +string(2.5e2);;'250' +string(1.23e-3);;'0.00123' +string(1e-7);;'0.0000001' +string(1e28);;'10000000000000000000000000000' +string(79228162514264337593543950335);;'79228162514264337593543950335' +string(-79228162514264337593543950335);;'-79228162514264337593543950335' +string(-0);;'-0';question: negative zero keeps its sign in string form although -0 == 0 +string(-0.0);;'-0.0';question: negative zero keeps its sign in string form although -0 == 0 +string(0.1 + 0.2);;'0.3' +string(1.10 + 1);;'2.10' +string(2 * 1.50);;'3.00' +string(10 / 4);;'2.50';question: division result carries a trailing zero scale (2.50), unlike 1 / 3 or literal 2.5 +string(1 / 3);;'0.3333333333333333333333333333' +string(1_000);;'1000' +# string: other scalar types +string(true);;'true' +string(false);;'false' +string(null);;'null' +string(missing);;'null' +string('');;'' +string('already string');;'already string' +string('ä😀');;'ä😀' +string(' ');;' ' +string(string(1.50));;'1.50' +# string: composite values +string([1]);;!error;question: arrays have no string form (JSON would be a natural choice) +string([]);;!error;question: arrays have no string form +string({a: 1});;!error;question: objects have no string form +string({});;!error;question: objects have no string form +string(d('2024-01-01'));;'2024-01-01T00:00:00Z' +# string: input rows +string(n);{n: 1.10};'1.10' +string(n);{n: 1.10};'1.10' +string(n);{n: 0};'0' +string(n);{n: -2};'-2' +string(n);{n: 0.000001};'0.000001' +string(n);{n: 12345678901234567890};'12345678901234567890' +string(n);{n: true};'true' +string(n);{n: false};'false' +string(n);{n: null};'null' +string(n);{};'null' +string(n);{n: 'x'};'x' +string(n);{n: ''};'' +string(n);{n: [1]};!error +string(n);{n: {a: 1}};!error +# string: arguments +string();;!error +string(1, 2);;!error +# number: brief (parsing is covered by the math chapter) +number('12');;12 +number(' 12 ');;12 +number('-3.5');;-3.5 +string(number('1.50'));;'1.50' +number('1e3');;1000 +number('0.1');;0.1 +number(12);;12 +number(true);;1 +number(false);;0 +number('abc');;!error +number('');;!error +number(' ');;!error +number('1,000');;!error +number('0x10');;!error +number('١٢');;!error +number(null);;!error +number([1]);;!error +number({});;!error +number(d('2024-01-01'));;!error +number();;!error +number(s);{s: '42'};42 +number(s);{s: '42'};42 +number(s);{s: '\t7\n'};7 +number(s);{s: 'x'};!error +number(s);{s: null};!error +number(s);{};!error +number(s);{s: 3.25};3.25 +number(s);{s: false};0 +# bool: bools, numbers, null +bool(true);;true +bool(false);;false +bool(1);;true +bool(0);;false +bool(-1);;true +bool(0.0);;false +bool(0.001);;true +bool(-0);;false +bool(null);;false +bool(missing);;false +# bool: strings +bool('true');;true +bool('false');;false +bool(' true ');;true +bool(' false ');;false +bool('');;false;bug: empty string converts to true (non-true/false strings return s.is_empty(), inverted) +bool('yes');;true;bug: non-empty string converts to false (non-true/false strings return s.is_empty(), inverted) +bool('abc');;true;bug: non-empty string converts to false (inverted is_empty) +bool('1');;true;bug: non-empty string converts to false (inverted is_empty) +bool('TRUE');;false;question: only lowercase 'true'/'false' are recognized; with the non-empty rule this would be true +bool('True');;false;question: only lowercase 'true'/'false' are recognized +bool('FALSE');;false;question: uppercase 'FALSE' is not recognized as false +bool('0');;false;question: '0' is not recognized; a non-empty-is-true rule would give true +bool('no');;false;question: 'no' is not recognized; a non-empty-is-true rule would give true +bool(' ');;false;question: whitespace-only string is neither trimmed-empty nor truthy consistently +# bool: composite values +bool([]);;true +bool([0]);;true +bool({});;true +bool({a: false});;true +bool(d('2024-01-01'));;true +# bool: input rows +bool(v);{v: 'true'};true +bool(v);{v: 'true'};true +bool(v);{v: 'false'};false +bool(v);{v: '\ttrue\n'};true +bool(v);{v: 1};true +bool(v);{v: 0};false +bool(v);{v: true};true +bool(v);{v: null};false +bool(v);{};false +bool(v);{v: []};true +bool(v);{v: ''};false;bug: empty string converts to true (inverted is_empty) +bool(v);{v: 'x'};true;bug: non-empty string converts to false (inverted is_empty) +# bool: arguments +bool();;!error +bool(1, 2);;!error +# type: every value class +type('hello');;'string' +type('');;'string' +type(123);;'number' +type(1.5);;'number' +type(-0);;'number' +type(true);;'bool' +type(false);;'bool' +type(null);;'null' +type(missing);;'null' +type([1, 2, 3]);;'array' +type([]);;'array' +type({});;'object' +type({a: 1});;'object' +type(d('2024-01-01'));;'date' +type(1 == 1);;'bool' +type(`x`);;'string' +type(split('a', ','));;'array' +type(string(1));;'string' +type(number('1'));;'number' +type(type(1));;'string' +# type: input rows +type(v);{v: 'a'};'string' +type(v);{v: 'a'};'string' +type(v);{v: ''};'string' +type(v);{v: 1};'number' +type(v);{v: 1.10};'number' +type(v);{v: false};'bool' +type(v);{v: null};'null' +type(v);{};'null' +type(v);{v: []};'array' +type(v);{v: {}};'object' +type(v);{v: '2024-01-01'};'string' +type(v.x);{v: {x: 1}};'number' +type(v.x);{v: {}};'null' +# type: arguments +type();;!error +type(1, 2);;!error +# isNumeric: brief +isNumeric(123);;true +isNumeric(1.5);;true +isNumeric('123');;true +isNumeric('1.5');;true +isNumeric('-1.5');;true +isNumeric(' 1 ');;true +isNumeric('1e3');;true +isNumeric('');;false +isNumeric(' ');;false +isNumeric('abc');;false +isNumeric('12a');;false +isNumeric('1,5');;false +isNumeric('0x1');;false +isNumeric('NaN');;false +isNumeric('Infinity');;false +isNumeric('١');;false +isNumeric(null);;false +isNumeric(true);;false +isNumeric([1]);;false +isNumeric({});;false +isNumeric(d('2024-01-01'));;false +isNumeric();;!error +isNumeric(s);{s: '10'};true +isNumeric(s);{s: '10'};true +isNumeric(s);{s: '\t10\n'};true +isNumeric(s);{s: 'ten'};false +isNumeric(s);{s: ''};false +isNumeric(s);{s: 10};true +isNumeric(s);{s: null};false +isNumeric(s);{};false +isNumeric(s) == (type(s) == 'number' or s == '10');{s: '10'};true diff --git a/core/expression/tests/spec/standard/07-06-templates-concat.csv b/core/expression/tests/spec/standard/07-06-templates-concat.csv new file mode 100644 index 00000000..504122dc --- /dev/null +++ b/core/expression/tests/spec/standard/07-06-templates-concat.csv @@ -0,0 +1,128 @@ +expression (string);input (json 5);output (json 5);note +# templates: literal parts +`hello`;;'hello' +``;;'' +` `;;' ' +`a b c`;;'a b c' +`ä😀`;;'ä😀' +# templates: scalar interpolation +`${1}`;;'1' +`${1.10}`;;'1.10' +`${1.0}`;;'1.0' +`${1e3}`;;'1000' +`${0.000001}`;;'0.000001' +`${-0}`;;'-0';question: negative zero keeps its sign in string form +`${0.1 + 0.2}`;;'0.3' +`${2 * 1.50}`;;'3.00' +`${true}`;;'true' +`${false}`;;'false' +`${null}`;;'null' +`${missing}`;;'null' +`${''}`;;'' +`${'a'}${'b'}`;;'ab' +`a${1}b${2}c`;;'a1b2c' +`${1}${1}`;;'11' +`${ 1 + 1 }`;;'2' +`${'x' + 'y'}`;;'xy' +`${upper('x')}`;;'X' +`uppercase inner ${upper('string')}`;;'uppercase inner STRING' +`${len('abc')}`;;'3' +`${1 == 1}`;;'true' +`${1 > 2 ? 'yes' : 'no'}`;;'no' +`${string(1.50)}`;;'1.50' +`${type([])}`;;'array' +# templates: composite interpolation +`${[1]}`;;!error;question: arrays cannot be interpolated (no string form) +`${[]}`;;!error;question: arrays cannot be interpolated (no string form) +`${ {a: 1} }`;;!error;question: objects cannot be interpolated (no string form) +`${d('2024-01-01')}`;;'2024-01-01T00:00:00Z' +`${d('2024-01-01').format('%Y-%m-%d')}`;;'2024-01-01' +# templates: input rows +`${s}|${n}`;{s: 'a', n: 1};'a|1' +`${s}|${n}`;{s: 'a', n: 1};'a|1' +`${s}|${n}`;{s: 'ä', n: 1.50};'ä|1.50' +`${s}|${n}`;{s: '', n: 0};'|0' +`${s}|${n}`;{s: ' ', n: -2};' |-2' +`${s}|${n}`;{s: 'a\tb', n: 1e2};'a\tb|100' +`${s}|${n}`;{s: null, n: null};'null|null' +`${s}|${n}`;{};'null|null' +`${s}|${n}`;{s: true, n: false};'true|false' +`${s}|${n}`;{s: '1', n: '2'};'1|2' +`${s}|${n}`;{s: [1], n: 1};!error +`${s}|${n}`;{s: 'a', n: {x: 1}};!error +`${s}|${n}`;{s: 'a', n: 1};'a|1' +`Hello ${upper(s)}!`;{s: 'world'};'Hello WORLD!' +`Hello ${upper(s)}!`;{s: 'straße'};'Hello STRASSE!' +`Hello ${upper(s)}!`;{s: ''};'Hello !' +`Hello ${upper(s)}!`;{s: null};!error +`Hello ${upper(s)}!`;{s: 'world'};'Hello WORLD!' +`${n * 2}`;{n: 1.5};'3.0' +`${n * 2}`;{n: 1.25};'2.50' +`${n * 2}`;{n: 0};'0' +`${n * 2}`;{n: null};!error +`${n * 2}`;{n: '1'};!error +`${a.b}-${a.c}`;{a: {b: 'x', c: 2}};'x-2' +`${a.b}-${a.c}`;{a: {b: 'x'}};'x-null' +`${a.b}-${a.c}`;{a: null};'null-null' +len(`${s}`);{s: 'abc'};3 +len(`${s}`);{s: 12.50};5 +type(`${n}`);{n: 1};'string' +`${s}` == s;{s: 'abc'};true +`${n}` == string(n);{n: 1.10};true +# concatenation: literals +'a' + 'b';;'ab' +'' + '';;'' +'a' + '';;'a' +'' + 'a';;'a' +'1' + '2';;'12' +'ä' + 'ö';;'äö' +'😀' + '👍';;'😀👍' +'a' + ' ' + 'b';;'a b' +'a' + string(1);;'a1' +'a' + string(1.50);;'a1.50' +'a' + string(null);;'anull' +'x' + `${1}`;;'x1' +upper('a' + 'b');;'AB' +len('ab' + 'cd');;4 +# concatenation: every non-string operand is rejected +'a' + 1;;!error +1 + 'a';;!error +'a' + 1.5;;!error +'a' + null;;!error +null + 'a';;!error +'a' + true;;!error +false + 'a';;!error +'a' + [1];;!error +['a'] + 'b';;!error +'a' + {};;!error +'a' + d('2024-01-01');;'a2024-01-01T00:00:00Z' +'a' + missing;;!error +# concatenation: input rows +s + '-' + t;{s: 'a', t: 'b'};'a-b' +s + '-' + t;{s: 'a', t: 'b'};'a-b' +s + '-' + t;{s: '', t: ''};'-' +s + '-' + t;{s: 'ä', t: '😀'};'ä-😀' +s + '-' + t;{s: 'a\nb', t: 'c'};'a\nb-c' +s + '-' + t;{s: ' ', t: ' '};' - ' +s + '-' + t;{s: 'a', t: null};!error +s + '-' + t;{s: null, t: 'b'};!error +s + '-' + t;{s: 1, t: 'b'};!error +s + '-' + t;{s: 'a', t: true};!error +s + '-' + t;{s: 'a', t: ['b']};!error +s + '-' + t;{};!error +s + '-' + t;{s: 'a', t: 'b'};'a-b' +s + s;{s: 'ab'};'abab' +s + s;{s: ''};'' +s + s;{s: 'é'};'éé' +s + s;{s: 2};4 +upper(s + t);{s: 'ab', t: 'ß'};'ABSS' +upper(s + t);{s: 'x', t: ''};'X' +len(s + t);{s: 'ab', t: 'cd'};4 +len(s + t);{s: 'ä', t: 'ö'};2;bug: len counts UTF-8 bytes (4), intended character count +s + string(n);{s: 'n=', n: 1.10};'n=1.10' +s + string(n);{s: 'n=', n: null};'n=null' +s + string(n);{s: 'n=', n: true};'n=true' +s + string(n);{s: 'n=', n: [1]};!error +(s + t) == 'ab';{s: 'a', t: 'b'};true +(s + t) == 'ab';{s: 'ab', t: ''};true +(s + t) == 'ab';{s: 'A', t: 'b'};false diff --git a/core/expression/tests/spec/standard/08-arithmetic.csv b/core/expression/tests/spec/standard/08-arithmetic.csv new file mode 100644 index 00000000..2ba9af43 --- /dev/null +++ b/core/expression/tests/spec/standard/08-arithmetic.csv @@ -0,0 +1,211 @@ +expression (string);input (json 5);output (json 5);note +# add(n, unit): every unit and alias +d('2023-10-15').add(1, 'seconds');;'2023-10-15T00:00:01Z' +d('2023-10-15').add(1, 'second');;'2023-10-15T00:00:01Z' +d('2023-10-15').add(1, 'secs');;'2023-10-15T00:00:01Z' +d('2023-10-15').add(1, 'sec');;'2023-10-15T00:00:01Z' +d('2023-10-15').add(1, 's');;'2023-10-15T00:00:01Z' +d('2023-10-15').add(1, 'minutes');;'2023-10-15T00:01:00Z' +d('2023-10-15').add(1, 'minute');;'2023-10-15T00:01:00Z' +d('2023-10-15').add(1, 'min');;'2023-10-15T00:01:00Z' +d('2023-10-15').add(1, 'mins');;'2023-10-15T00:01:00Z' +d('2023-10-15').add(1, 'm');;'2023-10-15T00:01:00Z' +d('2023-10-15').add(1, 'hours');;'2023-10-15T01:00:00Z' +d('2023-10-15').add(1, 'hour');;'2023-10-15T01:00:00Z' +d('2023-10-15').add(1, 'hr');;'2023-10-15T01:00:00Z' +d('2023-10-15').add(1, 'hrs');;'2023-10-15T01:00:00Z' +d('2023-10-15').add(1, 'h');;'2023-10-15T01:00:00Z' +d('2023-10-15').add(1, 'days');;'2023-10-16T00:00:00Z' +d('2023-10-15').add(1, 'day');;'2023-10-16T00:00:00Z' +d('2023-10-15').add(1, 'd');;'2023-10-16T00:00:00Z' +d('2023-10-15').add(1, 'weeks');;'2023-10-22T00:00:00Z' +d('2023-10-15').add(1, 'week');;'2023-10-22T00:00:00Z' +d('2023-10-15').add(1, 'w');;'2023-10-22T00:00:00Z' +d('2023-10-15').add(1, 'months');;'2023-11-15T00:00:00Z' +d('2023-10-15').add(1, 'month');;'2023-11-15T00:00:00Z' +d('2023-10-15').add(1, 'mo');;'2023-11-15T00:00:00Z' +d('2023-10-15').add(1, 'M');;'2023-11-15T00:00:00Z' +d('2023-10-15').add(1, 'quarters');;'2024-01-15T00:00:00Z' +d('2023-10-15').add(1, 'quarter');;'2024-01-15T00:00:00Z' +d('2023-10-15').add(1, 'qtr');;'2024-01-15T00:00:00Z' +d('2023-10-15').add(1, 'q');;'2024-01-15T00:00:00Z' +d('2023-10-15').add(1, 'years');;'2024-10-15T00:00:00Z' +d('2023-10-15').add(1, 'year');;'2024-10-15T00:00:00Z' +d('2023-10-15').add(1, 'y');;'2024-10-15T00:00:00Z' +# add(n, unit): unknown units and case sensitivity +d('2023-10-15').add(1, 'ms');;!error +d('2023-10-15').add(1, 'millisecond');;!error +d('2023-10-15').add(1, 'D');;!error +d('2023-10-15').add(1, 'Y');;!error +d('2023-10-15').add(1, 'H');;!error +d('2023-10-15').add(1, 'W');;!error +d('2023-10-15').add(1, 'S');;!error +d('2023-10-15').add(1, 'Day');;!error +d('2023-10-15').add(1, 'fortnight');;!error +d('2023-10-15').add(1, '');;!error +d('2023-10-15').add(1);;!error +d('2023-10-15').add(null);;!error +d('2023-10-15').add(true, 'd');;!error +d('2023-10-15').add(1, null);;!error +# add(n, unit): zero, negative, fractional and large amounts +d('2023-10-15').add(0, 'd');;'2023-10-15T00:00:00Z' +d('2023-10-15').add(-1, 'd');;'2023-10-14T00:00:00Z' +d('2023-10-15').add(-1, 'M');;'2023-09-15T00:00:00Z' +d('2023-10-15').add(-1, 'y');;'2022-10-15T00:00:00Z' +d('2023-10-15').add(-2, 'q');;'2023-04-15T00:00:00Z' +d('2023-10-15').add(1.5, 'h');;'2023-10-15T01:30:00Z' +d('2023-10-15').add(1.5, 'd');;'2023-10-16T12:00:00Z' +d('2023-10-15').add(0.5, 'm');;'2023-10-15T00:00:30Z' +d('2023-10-15').add(0.5, 'w');;'2023-10-18T12:00:00Z' +d('2023-10-15').add(0.5, 's').timestamp();;1697328000000;question: sub-second amounts are truncated to whole seconds +d('2023-10-15').add(1.5, 'M');;'2023-11-15T00:00:00Z';question: fractional calendar amounts are truncated to whole months +d('2023-10-15').add(1.9, 'y');;'2024-10-15T00:00:00Z';question: fractional calendar amounts are truncated to whole years +d('2023-10-15').add(-1.5, 'M');;'2023-09-15T00:00:00Z';question: fractional calendar amounts are truncated toward zero +d('2023-10-15').add(1000, 'y');;'3023-10-15T00:00:00Z' +d('2023-10-15').add(10000, 'd');;'2051-03-02T00:00:00Z' +d('2023-10-15').add(1000000, 'y');;'Invalid date' +d('2023-10-15').add(1e30, 's');;!error +# sub(n, unit) +d('2023-10-15').sub(1, 's');;'2023-10-14T23:59:59Z' +d('2023-10-15').sub(1, 'm');;'2023-10-14T23:59:00Z' +d('2023-10-15').sub(1, 'h');;'2023-10-14T23:00:00Z' +d('2023-10-15').sub(1, 'd');;'2023-10-14T00:00:00Z' +d('2023-10-15').sub(1, 'w');;'2023-10-08T00:00:00Z' +d('2023-10-15').sub(1, 'M');;'2023-09-15T00:00:00Z' +d('2023-10-15').sub(1, 'q');;'2023-07-15T00:00:00Z' +d('2023-10-15').sub(1, 'y');;'2022-10-15T00:00:00Z' +d('2023-10-15').sub(-1, 'd');;'2023-10-16T00:00:00Z' +d('2023-10-15').sub(13, 'M');;'2022-09-15T00:00:00Z' +d('2023-01-01').sub(1, 's');;'2022-12-31T23:59:59Z' +d('2023-10-15').sub(1, 'ms');;!error +# duration strings +d('2023-10-15').add('1d');;'2023-10-16T00:00:00Z' +d('2023-10-15').add('1day');;'2023-10-16T00:00:00Z' +d('2023-10-15').add('2days');;'2023-10-17T00:00:00Z' +d('2023-10-15').add('1 d');;'2023-10-16T00:00:00Z' +d('2023-10-15').add(' 1d ');;'2023-10-16T00:00:00Z' +d('2023-10-15').add('2h 30m');;'2023-10-15T02:30:00Z' +d('2023-10-15').add('2h30m');;'2023-10-15T02:30:00Z' +d('2023-10-15').add('1w');;'2023-10-22T00:00:00Z' +d('2023-10-15').add('36h');;'2023-10-16T12:00:00Z' +d('2023-10-15').add('90m');;'2023-10-15T01:30:00Z' +d('2023-10-15').add('45s');;'2023-10-15T00:00:45Z' +d('2023-10-15').add('1M');;'2023-11-15T00:00:00Z' +d('2023-10-15').add('1m');;'2023-10-15T00:01:00Z' +d('2023-10-15').add('1mo');;'2023-11-15T00:00:00Z' +d('2023-10-15').add('1q');;'2024-01-15T00:00:00Z' +d('2023-10-15').add('1y');;'2024-10-15T00:00:00Z' +d('2023-10-15').add('1y 2M 3d 4h 5m 6s');;'2024-12-18T04:05:06Z' +d('2023-10-15').add('1d 5h');;'2023-10-16T05:00:00Z' +d('2023-10-15').add('1d 1d');;'2023-10-17T00:00:00Z' +d('2023-10-15').add('1M 1M');;'2023-12-15T00:00:00Z';bug: repeated month components overwrite instead of accumulating (hours and days do accumulate) +d('2023-10-15').add('1y 1y');;'2025-10-15T00:00:00Z';bug: repeated year components overwrite instead of accumulating +d('2023-10-15').add('1q 1M');;'2024-02-15T00:00:00Z';bug: a month component overwrites the preceding quarter instead of adding to it +d('2023-10-15').add('0d');;'2023-10-15T00:00:00Z' +d('2023-10-15').add('100000d');;'2297-07-30T00:00:00Z' +d('2023-10-15').sub('1d');;'2023-10-14T00:00:00Z' +d('2023-10-15').sub('2h 30m');;'2023-10-14T21:30:00Z' +d('2023-10-15').sub('1y 1M');;'2022-09-15T00:00:00Z' +d('2023-10-15').add('');;!error +d('2023-10-15').add(' ');;!error +d('2023-10-15').add('d');;!error +d('2023-10-15').add('10');;!error +d('2023-10-15').add('1x');;!error +d('2023-10-15').add('1D');;!error +d('2023-10-15').add('1ms');;!error +d('2023-10-15').add('-1d');;!error +d('2023-10-15').add('1.5h');;!error +d('2023-10-15').add('1d,2h');;!error +d('2023-10-15').add('P1D');;!error +d('2023-10-15').add('99999999999999999999d');;!error +# month-end clamping +d('2023-01-31').add(1, 'M');;'2023-02-28T00:00:00Z' +d('2024-01-31').add(1, 'M');;'2024-02-29T00:00:00Z' +d('2023-01-31').add(2, 'M');;'2023-03-31T00:00:00Z' +d('2023-03-31').add(1, 'M');;'2023-04-30T00:00:00Z' +d('2023-03-31').sub(1, 'M');;'2023-02-28T00:00:00Z' +d('2024-03-31').sub(1, 'M');;'2024-02-29T00:00:00Z' +d('2023-05-31').add(1, 'q');;'2023-08-31T00:00:00Z' +d('2023-11-30').add(1, 'q');;'2024-02-29T00:00:00Z' +d('2023-01-31').add(1, 'M').add(1, 'M');;'2023-03-28T00:00:00Z' +d('2023-12-31').add(1, 'M');;'2024-01-31T00:00:00Z' +d('2023-12-31').add(2, 'M');;'2024-02-29T00:00:00Z' +d('1900-01-31').add(1, 'M');;'1900-02-28T00:00:00Z' +d('2000-01-31').add(1, 'M');;'2000-02-29T00:00:00Z' +d('2024-02-29').add(12, 'M');;'2025-02-28T00:00:00Z' +d('2024-02-29').add(48, 'M');;'2028-02-29T00:00:00Z' +d('2024-02-29').add(4, 'y');;'2028-02-29T00:00:00Z' +d('2024-02-29').add(1, 'y');;'2025-02-28T00:00:00Z';bug: adding a year to Feb 29 gives an invalid date instead of clamping to Feb 28 like months do +d('2024-02-29').sub(1, 'y');;'2023-02-28T00:00:00Z';bug: subtracting a year from Feb 29 gives an invalid date instead of clamping +d('2024-02-29').add('1y');;'2025-02-28T00:00:00Z';bug: adding a year to Feb 29 gives an invalid date instead of clamping +d('2024-02-29').add(100, 'y');;'2124-02-29T00:00:00Z' +d('2000-02-29').add(100, 'y');;'2100-02-28T00:00:00Z';bug: 2100 is not a leap year, the result should clamp to Feb 28 instead of being invalid +d('2024-02-29').add(1, 'q');;'2024-05-29T00:00:00Z' +# duration components apply from the smallest unit up (seconds, then months, then years) +d('2023-01-30').add('1M 1d');;'2023-02-28T00:00:00Z';question: seconds/days apply before months; applying the largest unit first (Temporal, moment) would give 2023-03-01 +d('2024-02-28').add('1y 1d');;'Invalid date';question: the day is applied first (Feb 29) and the year then fails; largest-first would give 2025-03-01 +# date arithmetic through operators is not defined +d('2023-10-15') + '1d';;'2023-10-15T00:00:00Z1d' +d('2023-10-15') - d('2023-10-14');;!error +d('2023-10-15') + 86400000;;!error +# add/sub on an invalid date stays invalid +d('foo').add(1, 'd');;'Invalid date' +d('foo').sub('1d');;'Invalid date' +d(null).add(1, 'M').isValid();;false +# add/sub on rows: repeated dates, month ends, leap days, invalid, missing +d(s).add(1, 'month');{s: '2023-01-31'};'2023-02-28T00:00:00Z' +d(s).add(1, 'month');{s: '2023-01-31'};'2023-02-28T00:00:00Z' +d(s).add(1, 'month');{s: '2024-01-31'};'2024-02-29T00:00:00Z' +d(s).add(1, 'month');{s: '2023-12-15 13:45'};'2024-01-15T13:45:00Z' +d(s).add(1, 'month');{s: '2024-02-29'};'2024-03-29T00:00:00Z' +d(s).add(1, 'month');{s: 'garbage'};'Invalid date' +d(s).add(1, 'month');{s: null};'Invalid date' +d(s).add(1, 'month');{};'Invalid date' +d(s).add(1, 'month');{s: 0};'1970-02-01T00:00:00Z' +d(s).add(1, 'y');{s: '2023-06-15'};'2024-06-15T00:00:00Z' +d(s).add(1, 'y');{s: '2023-06-15'};'2024-06-15T00:00:00Z' +d(s).add(1, 'y');{s: '2024-02-29'};'2025-02-28T00:00:00Z';bug: adding a year to Feb 29 gives an invalid date instead of clamping +d(s).add(1, 'y');{s: '2023-02-28'};'2024-02-28T00:00:00Z' +d(s).add(1, 'y');{s: '1999-12-31 23:59:59'};'2000-12-31T23:59:59Z' +d(s).add(1, 'y');{s: 'x'};'Invalid date' +d(s).sub(1, 'd');{s: '2024-03-01'};'2024-02-29T00:00:00Z' +d(s).sub(1, 'd');{s: '2023-03-01'};'2023-02-28T00:00:00Z' +d(s).sub(1, 'd');{s: '2023-01-01'};'2022-12-31T00:00:00Z' +d(s).sub(1, 'd');{s: '2023-01-01'};'2022-12-31T00:00:00Z' +d(s).sub(1, 'd');{s: '1970-01-01'};'1969-12-31T00:00:00Z' +d(s).sub(1, 'd');{s: ''};'Invalid date' +d(s).add(n, u);{s: '2023-10-15', n: 1, u: 'd'};'2023-10-16T00:00:00Z' +d(s).add(n, u);{s: '2023-10-15', n: 2, u: 'M'};'2023-12-15T00:00:00Z' +d(s).add(n, u);{s: '2023-10-15', n: 2, u: 'm'};'2023-10-15T00:02:00Z' +d(s).add(n, u);{s: '2023-10-15', n: -3, u: 'q'};'2023-01-15T00:00:00Z' +d(s).add(n, u);{s: '2023-10-15', n: 1.5, u: 'h'};'2023-10-15T01:30:00Z' +d(s).add(n, u);{s: '2023-10-15', n: 1, u: 'x'};!error +d(s).add(n, u);{s: '2023-10-15', n: null, u: 'd'};!error +d(s).add(n, u);{s: 'x', n: 1, u: 'd'};'Invalid date' +d(s).add(dur);{s: '2023-10-15', dur: '1d'};'2023-10-16T00:00:00Z' +d(s).add(dur);{s: '2023-10-15', dur: '2h 30m'};'2023-10-15T02:30:00Z' +d(s).add(dur);{s: '2023-10-15', dur: '1M'};'2023-11-15T00:00:00Z' +d(s).add(dur);{s: '2023-01-31', dur: '1M'};'2023-02-28T00:00:00Z' +d(s).add(dur);{s: '2023-10-15', dur: 'soon'};!error +d(s).add(dur);{s: '2023-10-15', dur: null};!error +d(s, 'UTC').add(1, 'M');{s: '2023-01-31'};'2023-02-28T00:00:00Z' +d(s, 'UTC').add(1, 'M');{s: '2023-01-31'};'2023-02-28T00:00:00Z' +d(s, 'UTC').add(1, 'M');{s: '2024-01-30'};'2024-02-29T00:00:00Z' +d(s, 'UTC').add(1, 'M');{s: '2023-10-15T23:59:59Z'};'2023-11-15T23:59:59Z' +d(s, 'UTC').add(1, 'M');{s: 'bad'};'Invalid date' +d(s, 'UTC').add(1, 'M');{};'Invalid date' +d(s, 'Etc/GMT+5').add(1, 'd');{s: '2023-10-15'};'2023-10-16T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'd');{s: '2023-12-31 22:00'};'2024-01-01T22:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'd');{s: '2024-02-28'};'2024-02-29T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'd');{s: 'nope'};'Invalid date' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2023-03-31'};'2023-02-28T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2024-03-31'};'2024-02-29T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2023-01-15 12:00'};'2022-12-15T12:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2023-01-15 12:00'};'2022-12-15T12:00:00+05:30' +d(s, 'Asia/Kathmandu').add(1, 'q');{s: '2023-11-30'};'2024-02-29T00:00:00+05:45' +d(s, 'Asia/Kathmandu').add(1, 'q');{s: '2023-08-31'};'2023-11-30T00:00:00+05:45' +d(s, 'Asia/Kathmandu').add(1, 'q');{s: null};'Invalid date' +d(s).add(1, 'h').hour();{s: '2023-10-15 23:30'};0 +d(s).add(1, 'h').hour();{s: '2023-10-15 10:30'};11 +d(s).add(1, 'h').hour();{s: 'x'};null +d(s).add(1, 'h').hour();{};null diff --git a/core/expression/tests/spec/standard/08-boundaries.csv b/core/expression/tests/spec/standard/08-boundaries.csv new file mode 100644 index 00000000..9697fbad --- /dev/null +++ b/core/expression/tests/spec/standard/08-boundaries.csv @@ -0,0 +1,171 @@ +expression (string);input (json 5);output (json 5);note +# startOf for every unit (from Wednesday 2023-08-16 14:37:52.250) +d('2023-08-16T14:37:52.250Z').startOf('second');;'2023-08-16T14:37:52Z' +d('2023-08-16T14:37:52.250Z').startOf('second').timestamp();;1692196672000 +d('2023-08-16T14:37:52.250Z').startOf('s');;'2023-08-16T14:37:52Z' +d('2023-08-16T14:37:52.250Z').startOf('minute');;'2023-08-16T14:37:00Z' +d('2023-08-16T14:37:52.250Z').startOf('m');;'2023-08-16T14:37:00Z' +d('2023-08-16T14:37:52.250Z').startOf('hour');;'2023-08-16T14:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('h');;'2023-08-16T14:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('day');;'2023-08-16T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('d');;'2023-08-16T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('days');;'2023-08-16T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('week');;'2023-08-14T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('w');;'2023-08-14T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('month');;'2023-08-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('M');;'2023-08-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('mo');;'2023-08-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('quarter');;'2023-07-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('q');;'2023-07-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('year');;'2023-01-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('y');;'2023-01-01T00:00:00Z' +d('2023-08-16T14:37:52.250Z').startOf('year').timestamp();;1672531200000 +d('2023-08-16').startOf('ms');;!error +d('2023-08-16').startOf('D');;!error +d('2023-08-16').startOf('decade');;!error +d('2023-08-16').startOf('');;!error +d('2023-08-16').startOf(null);;!error +# endOf for every unit: the last representable instant, shown to the second +d('2023-08-16T14:37:52.250Z').endOf('second');;'2023-08-16T14:37:52Z' +d('2023-08-16T14:37:52.250Z').endOf('second').timestamp();;1692196672999 +d('2023-08-16T14:37:52.250Z').endOf('minute');;'2023-08-16T14:37:59Z' +d('2023-08-16T14:37:52.250Z').endOf('hour');;'2023-08-16T14:59:59Z' +d('2023-08-16T14:37:52.250Z').endOf('day');;'2023-08-16T23:59:59Z' +d('2023-08-16T14:37:52.250Z').endOf('day').timestamp();;1692230399999 +d('2023-08-16T14:37:52.250Z').endOf('week');;'2023-08-20T23:59:59Z' +d('2023-08-16T14:37:52.250Z').endOf('month');;'2023-08-31T23:59:59Z' +d('2023-08-16T14:37:52.250Z').endOf('quarter');;'2023-09-30T23:59:59Z' +d('2023-08-16T14:37:52.250Z').endOf('year');;'2023-12-31T23:59:59Z' +d('2023-08-16T14:37:52.250Z').endOf('year').timestamp();;1704067199999 +d('2023-08-16').endOf('ms');;!error +d('2023-08-16').endOf('Y');;!error +d('2023-08-16').endOf('day').add(1, 'ms');;!error +d('2023-08-16').endOf('day').add(1, 's');;'2023-08-17T00:00:00Z' +d('2023-08-16').endOf('day').add(1, 's').timestamp();;1692230400999;question: endOf keeps .999 of the last second, so adding one second lands at 00:00:00.999 rather than the next midnight +d('2023-08-16').endOf('day') < d('2023-08-17');;true +d('2023-08-16').endOf('day') == d('2023-08-16 23:59:59');;false +# weeks start on Monday and end on Sunday +d('2024-01-15').startOf('week');;'2024-01-15T00:00:00Z' +d('2024-01-16').startOf('week');;'2024-01-15T00:00:00Z' +d('2024-01-20').startOf('week');;'2024-01-15T00:00:00Z' +d('2024-01-21 23:59:59').startOf('week');;'2024-01-15T00:00:00Z' +d('2024-01-22').startOf('week');;'2024-01-22T00:00:00Z' +d('2024-01-15').endOf('week');;'2024-01-21T23:59:59Z' +d('2024-01-21').endOf('week');;'2024-01-21T23:59:59Z' +d('2024-01-22').endOf('week');;'2024-01-28T23:59:59Z' +d('2024-01-03').startOf('week');;'2024-01-01T00:00:00Z' +d('2023-01-01').startOf('week');;'2022-12-26T00:00:00Z' +d('2024-12-31').endOf('week');;'2025-01-05T23:59:59Z' +d('2024-03-01').startOf('week');;'2024-02-26T00:00:00Z' +d('2024-02-27').endOf('week');;'2024-03-03T23:59:59Z' +# months, quarters, years, leap years +d('2024-02-10').endOf('month');;'2024-02-29T23:59:59Z' +d('2023-02-10').endOf('month');;'2023-02-28T23:59:59Z' +d('1900-02-10').endOf('month');;'1900-02-28T23:59:59Z' +d('2000-02-10').endOf('month');;'2000-02-29T23:59:59Z' +d('2023-04-30 23:59:59').endOf('month');;'2023-04-30T23:59:59Z' +d('2023-12-01').endOf('month');;'2023-12-31T23:59:59Z' +d('2023-01-31').startOf('month');;'2023-01-01T00:00:00Z' +d('2023-01-01').startOf('quarter');;'2023-01-01T00:00:00Z' +d('2023-02-15').startOf('quarter');;'2023-01-01T00:00:00Z' +d('2023-03-31').startOf('quarter');;'2023-01-01T00:00:00Z' +d('2023-04-01').startOf('quarter');;'2023-04-01T00:00:00Z' +d('2023-05-31').startOf('quarter');;'2023-04-01T00:00:00Z';bug: the month is moved to April before the day is reset, April 31 does not exist so the result is invalid +d('2023-08-31').startOf('quarter');;'2023-07-01T00:00:00Z' +d('2023-12-31').startOf('quarter');;'2023-10-01T00:00:00Z' +d('2023-01-31').endOf('quarter');;'2023-03-31T23:59:59Z' +d('2024-02-29').endOf('quarter');;'2024-03-31T23:59:59Z' +d('2023-04-01').endOf('quarter');;'2023-06-30T23:59:59Z' +d('2023-05-31').endOf('quarter');;'2023-06-30T23:59:59Z';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d('2023-07-31').endOf('quarter');;'2023-09-30T23:59:59Z';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d('2023-08-31').endOf('quarter');;'2023-09-30T23:59:59Z';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d('2023-10-31').endOf('quarter');;'2023-12-31T23:59:59Z' +d('2023-11-30').endOf('quarter');;'2023-12-31T23:59:59Z' +d('2024-02-29').startOf('year');;'2024-01-01T00:00:00Z' +d('2024-02-29').endOf('year');;'2024-12-31T23:59:59Z' +d('2024-06-30').endOf('year');;'2024-12-31T23:59:59Z' +d('2023-01-01').startOf('year').sub(1, 's');;'2022-12-31T23:59:59Z' +# startOf/endOf are idempotent +d('2023-08-16 10:00').startOf('month').startOf('month');;'2023-08-01T00:00:00Z' +d('2023-08-16 10:00').endOf('month').endOf('month');;'2023-08-31T23:59:59Z' +d('2023-08-16 10:00').startOf('week').endOf('week');;'2023-08-20T23:59:59Z' +d('2023-08-16 10:00').endOf('year').startOf('day');;'2023-12-31T00:00:00Z' +# invalid dates stay invalid +d('foo').startOf('day');;'Invalid date' +d('foo').endOf('month');;'Invalid date' +d(null).startOf('week').isValid();;false +# other zones: boundaries are local to the date's zone +d('2023-08-16 14:37', 'Europe/Berlin').startOf('day');;'2023-08-16T00:00:00+02:00' +d('2023-08-16 14:37', 'Europe/Berlin').startOf('day').timestamp();;1692136800000 +d('2023-08-16 14:37', 'Europe/Berlin').endOf('month');;'2023-08-31T23:59:59+02:00' +d('2023-08-16 14:37', 'America/New_York').startOf('week');;'2023-08-14T00:00:00-04:00' +d('2023-08-16 14:37', 'Asia/Kolkata').startOf('hour');;'2023-08-16T14:00:00+05:30' +d('2023-08-16 14:37', 'Asia/Kathmandu').startOf('year');;'2023-01-01T00:00:00+05:45' +d('2023-08-16 14:37', 'Asia/Kathmandu').endOf('quarter');;'2023-09-30T23:59:59+05:45' +d('2023-08-16 14:37', 'Australia/Lord_Howe').startOf('month');;'2023-08-01T00:00:00+10:30' +d('2023-10-16 14:37', 'Australia/Lord_Howe').startOf('month');;'2023-10-01T00:00:00+10:30' +d('2023-10-16 14:37', 'Australia/Lord_Howe').startOf('year');;'2023-01-01T00:00:00+11:00' +d('2023-10-15T02:00:00Z').tz('America/New_York').startOf('day');;'2023-10-14T00:00:00-04:00' +d('2023-10-15T02:00:00Z').tz('Asia/Tokyo').endOf('day');;'2023-10-15T23:59:59+09:00' +d('2023-10-15', 'Etc/GMT+5').startOf('quarter');;'2023-10-01T00:00:00-05:00' +# startOf/endOf on rows +d(s).startOf('day');{s: '2023-10-15 13:45:10'};'2023-10-15T00:00:00Z' +d(s).startOf('day');{s: '2023-10-15 13:45:10'};'2023-10-15T00:00:00Z' +d(s).startOf('day');{s: '2024-02-29 23:59:59'};'2024-02-29T00:00:00Z' +d(s).startOf('day');{s: 'x'};'Invalid date' +d(s).startOf('day');{};'Invalid date' +d(s).startOf('day');{s: 1697380245123};'2023-10-15T00:00:00Z' +d(s, 'UTC').startOf('week');{s: '2023-10-15'};'2023-10-09T00:00:00Z' +d(s, 'UTC').startOf('week');{s: '2023-10-16'};'2023-10-16T00:00:00Z' +d(s, 'UTC').startOf('week');{s: '2023-10-16'};'2023-10-16T00:00:00Z' +d(s, 'UTC').startOf('week');{s: '2023-01-01'};'2022-12-26T00:00:00Z' +d(s, 'UTC').startOf('week');{s: '2024-03-02 23:00'};'2024-02-26T00:00:00Z' +d(s, 'UTC').startOf('week');{s: '2023-02-30'};'Invalid date' +d(s, 'UTC').startOf('week');{s: null};'Invalid date' +d(s, 'UTC').endOf('week');{s: '2023-10-15'};'2023-10-15T23:59:59Z' +d(s, 'UTC').endOf('week');{s: '2023-10-16'};'2023-10-22T23:59:59Z' +d(s, 'UTC').endOf('week');{s: '2024-12-30'};'2025-01-05T23:59:59Z' +d(s, 'UTC').endOf('week');{s: '2024-02-26'};'2024-03-03T23:59:59Z' +d(s).endOf('month');{s: '2024-02-01'};'2024-02-29T23:59:59Z' +d(s).endOf('month');{s: '2023-02-01'};'2023-02-28T23:59:59Z' +d(s).endOf('month');{s: '2023-02-01'};'2023-02-28T23:59:59Z' +d(s).endOf('month');{s: '2100-02-15'};'2100-02-28T23:59:59Z' +d(s).endOf('month');{s: '2023-09-30 23:59:59'};'2023-09-30T23:59:59Z' +d(s).endOf('month');{s: '2023-12-31'};'2023-12-31T23:59:59Z' +d(s).endOf('month');{s: ''};'Invalid date' +d(s).endOf('month').timestamp();{s: '2023-02-01'};1677628799999 +d(s).endOf('month').timestamp();{s: '2023-02-01'};1677628799999 +d(s).endOf('month').timestamp();{s: 'nope'};null +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: 'minute'};'2023-08-16T14:37:00Z' +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: 'hour'};'2023-08-16T14:00:00Z' +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: 'week'};'2023-08-14T00:00:00Z' +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: 'quarter'};'2023-07-01T00:00:00Z' +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: 'year'};'2023-01-01T00:00:00Z' +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: 'bogus'};!error +d(s).startOf(u);{s: '2023-08-16 14:37:52', u: null};!error +d(s).endOf(u);{s: '2023-11-16 14:37:52', u: 'quarter'};'2023-12-31T23:59:59Z' +d(s).endOf(u);{s: '2023-11-16 14:37:52', u: 'q'};'2023-12-31T23:59:59Z' +d(s).endOf(u);{s: '2023-11-16 14:37:52', u: 's'};'2023-11-16T14:37:52Z' +d(s).endOf(u);{s: '2023-11-16 14:37:52', u: 'M'};'2023-11-30T23:59:59Z' +d(s).endOf(u);{s: '2023-11-16 14:37:52', u: 'm'};'2023-11-16T14:37:59Z' +d(s, 'Etc/GMT-3').endOf('quarter');{s: '2024-02-10'};'2024-03-31T23:59:59+03:00' +d(s, 'Etc/GMT-3').endOf('quarter');{s: '2024-05-10'};'2024-06-30T23:59:59+03:00' +d(s, 'Etc/GMT-3').endOf('quarter');{s: '2024-05-10'};'2024-06-30T23:59:59+03:00' +d(s, 'Etc/GMT-3').endOf('quarter');{s: '2024-12-31 23:59:59'};'2024-12-31T23:59:59+03:00' +d(s, 'Etc/GMT-3').endOf('quarter');{s: 'invalid'};'Invalid date' +d(s, 'Asia/Kathmandu').startOf('month');{s: '2024-02-29 03:00'};'2024-02-01T00:00:00+05:45' +d(s, 'Asia/Kathmandu').startOf('month');{s: '2024-03-01'};'2024-03-01T00:00:00+05:45' +d(s, 'Asia/Kathmandu').startOf('month');{s: 1709251200000};'2024-03-01T00:00:00+05:45' +d(s).startOf('quarter');{s: '2023-05-31'};'2023-04-01T00:00:00Z';bug: the month is moved before the day is reset, April 31 does not exist +d(s).startOf('quarter');{s: '2023-05-30'};'2023-04-01T00:00:00Z' +d(s).startOf('quarter');{s: '2023-05-30'};'2023-04-01T00:00:00Z' +d(s).startOf('quarter');{s: '2023-12-31 23:00'};'2023-10-01T00:00:00Z' +d(s).startOf('quarter');{s: '2024-03-31'};'2024-01-01T00:00:00Z' +d(s).startOf('quarter');{s: null};'Invalid date' +d(s).endOf('quarter');{s: '2023-08-31'};'2023-09-30T23:59:59Z';bug: the month is moved to September before the day is set, September 31 does not exist +d(s).endOf('quarter');{s: '2023-08-30'};'2023-09-30T23:59:59Z' +d(s).endOf('quarter');{s: '2023-08-30'};'2023-09-30T23:59:59Z' +d(s).endOf('quarter');{s: '2023-01-31'};'2023-03-31T23:59:59Z' +d(s).endOf('quarter');{s: '2023-10-31'};'2023-12-31T23:59:59Z' +d(s).endOf('quarter');{s: '2023-05-31'};'2023-06-30T23:59:59Z';bug: the month is moved to June before the day is set, June 31 does not exist +d(s).endOf('quarter');{};'Invalid date' diff --git a/core/expression/tests/spec/standard/08-compare.csv b/core/expression/tests/spec/standard/08-compare.csv new file mode 100644 index 00000000..415dce80 --- /dev/null +++ b/core/expression/tests/spec/standard/08-compare.csv @@ -0,0 +1,184 @@ +expression (string);input (json 5);output (json 5);note +# isSame / isBefore / isAfter without a unit compare instants +d('2023-10-15').isSame(d('2023-10-15'));;true +d('2023-10-15').isSame(d('2023-10-15T00:00:00.001Z'));;false +d('2023-10-15 02:00', 'Europe/Berlin').isSame(d('2023-10-15T00:00:00Z'));;true +d('2023-10-15', 'Asia/Kathmandu').isSame(d('2023-10-14 18:15'));;true +d('2023-10-15').isBefore(d('2023-10-15T00:00:00.001Z'));;true +d('2023-10-15').isAfter(d('2023-10-14T23:59:59.999Z'));;true +d('2023-10-15').isBefore(d('2023-10-15'));;false +d('2023-10-15').isAfter(d('2023-10-15'));;false +d('2023-10-15').isSameOrBefore(d('2023-10-15'));;true +d('2023-10-15').isSameOrAfter(d('2023-10-15'));;true +d('2023-10-15').isSameOrBefore(d('2023-10-14'));;false +d('2023-10-15').isSameOrAfter(d('2023-10-16'));;false +d('2023-10-15', 'Asia/Tokyo').isBefore(d('2023-10-15'));;true +d('2023-10-15', 'America/New_York').isAfter(d('2023-10-15'));;true +# comparison methods accept strings and timestamps for the other date +d('2023-10-15').isBefore('2023-10-16');;true +d('2023-10-15').isSame('2023-10-15');;true +d('2023-10-15').isSame(1697328000000);;true +d('2023-10-15').isAfter('2023-10-14 23:59:59');;true +d('2023-10-15').isSame('2023-10-15 18:00', 'day');;true +# invalid dates never compare true +d('2023-10-15').isSame(d('foo'));;false +d('2023-10-15').isBefore(d('foo'));;false +d('2023-10-15').isAfter(d('foo'));;false +d('2023-10-15').isSameOrBefore('foo');;false +d('2023-10-15').isSameOrAfter(null);;false +d('foo').isSame(d('foo'));;false +d('foo').isBefore(d('2023-10-15'));;false +d('foo').isSameOrAfter(d('2023-10-15'), 'day');;false +# units: the other date is checked against this date's period +d('2023-10-15 00:00').isSame(d('2023-10-15 23:59:59'), 'day');;true +d('2023-10-15 00:00').isSame(d('2023-10-16'), 'day');;false +d('2023-10-15 10:30:15').isSame(d('2023-10-15 10:30:59'), 'minute');;true +d('2023-10-15 10:30:15').isSame(d('2023-10-15 10:31:00'), 'minute');;false +d('2023-10-15 10:30:15').isSame(d('2023-10-15 10:59:59'), 'hour');;true +d('2023-10-15 10:30:15').isSame(d('2023-10-15 11:00'), 'hour');;false +d('2023-10-15T10:30:15.100Z').isSame(d('2023-10-15T10:30:15.900Z'), 'second');;true +d('2023-10-15T10:30:15.100Z').isSame(d('2023-10-15T10:30:15.900Z'));;false +d('2023-10-16').isSame(d('2023-10-22 23:59'), 'week');;true +d('2023-10-16').isSame(d('2023-10-15'), 'week');;false +d('2023-10-15').isSame(d('2023-10-09'), 'week');;true +d('2023-10-15').isSame(d('2023-10-31'), 'month');;true +d('2023-10-15').isSame(d('2023-11-01'), 'month');;false +d('2023-10-15').isSame(d('2023-12-31 23:59:59'), 'quarter');;true +d('2023-10-15').isSame(d('2023-09-30'), 'quarter');;false +d('2023-10-15').isSame(d('2023-01-01'), 'year');;true +d('2023-10-15').isSame(d('2024-01-01'), 'y');;false +d('2023-10-15').isBefore(d('2023-10-16'), 'day');;true +d('2023-10-15 00:00').isBefore(d('2023-10-15 23:00'), 'day');;false +d('2023-10-15').isBefore(d('2023-10-22'), 'week');;true +d('2023-10-15').isBefore(d('2023-10-16'), 'week');;true +d('2023-10-14').isBefore(d('2023-10-15'), 'week');;false +d('2023-10-15').isAfter(d('2023-10-14'), 'day');;true +d('2023-10-15 23:59').isAfter(d('2023-10-15 00:00'), 'day');;false +d('2023-10-16').isAfter(d('2023-10-15'), 'week');;true +d('2023-10-15').isAfter(d('2023-10-09'), 'week');;false +d('2023-10-15').isSameOrBefore(d('2023-10-15 00:00:01'), 'day');;true +d('2023-10-15').isSameOrBefore(d('2023-10-14 23:59:59'), 'day');;false +d('2023-10-15 23:00').isSameOrAfter(d('2023-10-15 01:00'), 'day');;true +d('2023-10-15').isSameOrAfter(d('2023-10-16'), 'day');;false +d('2023-10-15').isSameOrBefore(d('2024-02-01'), 'year');;true +d('2023-10-15').isSameOrAfter(d('2023-01-01'), 'q');;true +d('2023-10-15').isSame(d('2023-10-15'), 'ms');;!error +d('2023-10-15').isBefore(d('2023-10-16'), 'D');;!error +# units across zones use this date's zone +d('2023-10-15', 'Europe/Berlin').isSame(d('2023-10-14 22:30'), 'day');;true +d('2023-10-15', 'Europe/Berlin').isSame(d('2023-10-15 22:30'), 'day');;false +d('2023-10-15T00:00:00Z').isSame(d('2023-10-14 23:00', 'America/New_York'), 'day');;true +d('2023-10-14 23:00', 'America/New_York').isSame(d('2023-10-15T00:00:00Z'), 'day');;true +d('2023-10-14 19:00', 'America/New_York').isSame(d('2023-10-15T04:00:00Z'), 'day');;false +d('2023-10-15', 'Asia/Kathmandu').isSame(d('2023-10-15 18:14'), 'day');;true +d('2023-10-15', 'Asia/Kathmandu').isSame(d('2023-10-15 18:15'), 'day');;false +# operators on dates +d('2023-10-15') == d('2023-10-15');;true +d('2023-10-15') == d('2023-10-15 00:00:00');;true +d('2023-10-15') == d(1697328000000);;true +d('2023-10-15') == d('2023-10-16');;false +d('2023-10-15') != d('2023-10-16');;true +d('2023-10-15 02:00', 'Europe/Berlin') == d('2023-10-15');;true +d('2023-10-15 02:00', 'Europe/Berlin') != d('2023-10-15');;false +d('2023-10-15', 'Asia/Kolkata') == d('2023-10-14 18:30');;true +d('2023-10-15T00:00:00.001Z') == d('2023-10-15');;false +d('2023-10-15') < d('2023-10-15T00:00:00.001Z');;true +d('2023-10-15', 'Asia/Tokyo') < d('2023-10-15');;true +d('2023-10-15', 'America/New_York') > d('2023-10-15');;true +d('2023-10-15') <= d('2023-10-15', 'UTC');;true +d('2023-10-15') >= d('2023-10-15 02:00', 'Europe/Berlin');;true +d('2023-10-15').endOf('day') > d('2023-10-15 23:59:59');;true +d('2023-10-15') == '2023-10-15';;true +d('2023-10-15') == null;;false +d('2023-10-15') != null;;true +d('2023-10-15') == 1697328000000;;false +d('2023-10-15') < '2023-10-16';;true +d('2023-10-15') < 1697328000001;;!error +d('2023-10-15') < null;;!error +# operators with invalid dates +d('foo') == d('foo');;false;bug: two invalid dates compare equal with == although isSame reports false +d('foo') == d('bar');;false;bug: two different invalid inputs compare equal +d('foo') != d('bar');;true;bug: two invalid dates are reported equal +d('foo') == d('2023-10-15');;false +d('foo') == null;;false +d('foo') < d('2023-10-15');;true;question: an invalid date orders before every valid date instead of failing or comparing false +d('foo') > d('2023-10-15');;false +d('2023-10-15') > d('foo');;true;question: every valid date orders after an invalid date +# in / not in with lists of dates +d('2023-10-15') in [d('2023-10-14'), d('2023-10-15')];;true +d('2023-10-15') in [d('2023-10-14'), d('2023-10-16')];;false +d('2023-10-15') in [d('2023-10-15 02:00', 'Europe/Berlin')];;true +d('2023-10-15') in ['2023-10-15'];;true +d('2023-10-15') in [];;false +d('2023-10-15') not in [d('2023-10-14'), d('2023-10-16')];;true +d('2023-10-15') not in [d('2023-10-15')];;false +d('foo') in [d('bar')];;false +d('2023-10-15') in [d('2023-10-14')..d('2023-10-16')];;true +d('2023-10-15') in (d('2023-10-15')..d('2023-10-16')];;false +d('2023-10-15') in [d('2023-10-15 02:00', 'Europe/Berlin')..d('2023-10-15')];;true +d('2023-10-15') in [d('2023-10-15')..d('2023-10-15')];;true +d('2023-10-15') in [d('2023-10-16')..d('2023-10-14')];;false +d('2023-10-15') in [1..2];;false;question: a date tested against a number range is false rather than a type error (a string range is an error) +d('2023-10-15') in ['a'..'b'];;!error +# min / max of dates +max([d('2023-10-15'), d('2023-10-15 02:00', 'Europe/Berlin'), d('2023-10-14')]);;'2023-10-15T02:00:00+02:00';question: on a tie between equal instants in different zones max returns the last one, so the rendered zone depends on list order +min([d('2023-10-15'), d('2023-10-15 02:00', 'Europe/Berlin')]);;'2023-10-15T00:00:00Z' +min([d('2023-10-15', 'Asia/Tokyo'), d('2023-10-15')]);;'2023-10-15T00:00:00+09:00' +max([d('2023-10-15', 'Asia/Tokyo'), d('2023-10-15')]);;'2023-10-15T00:00:00Z' +max([d('2023-10-15', 'America/New_York'), d('2023-10-15')]);;'2023-10-15T00:00:00-04:00' +min([d('2023-10-15T00:00:00.001Z'), d('2023-10-15')]).timestamp();;1697328000000 +max([d('foo'), d('2023-10-15')]);;'2023-10-15T00:00:00Z' +min([d('foo'), d('2023-10-15')]);;'Invalid date';question: min returns the invalid date because invalid dates order first +max([]);;!error +min([d('2023-10-15'), 1]);;!error +min([d('2023-10-15'), '2023-10-01']);;!error +# comparisons on rows +d(a) == d(b);{a: '2023-10-15', b: '2023-10-15'};true +d(a) == d(b);{a: '2023-10-15', b: '2023-10-15'};true +d(a) == d(b);{a: '2023-10-15', b: '2023-10-15 00:00:00'};true +d(a) == d(b);{a: '2023-10-15', b: '2023-10-16'};false +d(a) == d(b);{a: '2023-10-15', b: 1697328000000};true +d(a) == d(b);{a: '2023-10-15', b: 'x'};false +d(a) == d(b);{a: 'x', b: 'y'};false;bug: two invalid dates compare equal +d(a) == d(b);{a: '2023-10-15'};false +d(a) < d(b);{a: '2023-10-15', b: '2023-10-16'};true +d(a) < d(b);{a: '2023-10-16', b: '2023-10-15'};false +d(a) < d(b);{a: '2023-10-15', b: '2023-10-15'};false +d(a) < d(b);{a: '2023-10-15', b: '2023-10-15'};false +d(a) < d(b);{a: '2024-02-29 23:59:59', b: '2024-03-01'};true +d(a) <= d(b);{a: '2023-10-15', b: '2023-10-15'};true +d(a) >= d(b);{a: '2023-10-14', b: '2023-10-15'};false +d(a) > d(b);{a: 1697328000001, b: '2023-10-15'};true +d(a).isBefore(d(b), 'day');{a: '2023-10-15 23:59', b: '2023-10-16 00:00'};true +d(a).isBefore(d(b), 'day');{a: '2023-10-15 00:00', b: '2023-10-15 23:59'};false +d(a).isBefore(d(b), 'day');{a: '2023-10-15 00:00', b: '2023-10-15 23:59'};false +d(a).isBefore(d(b), 'day');{a: 'x', b: '2023-10-16'};false +d(a).isBefore(d(b), 'day');{a: '2023-10-15'};false +d(a).isSame(d(b), 'month');{a: '2024-02-01', b: '2024-02-29 23:59:59'};true +d(a).isSame(d(b), 'month');{a: '2024-02-01', b: '2024-03-01'};false +d(a).isSame(d(b), 'month');{a: '2024-02-01', b: '2024-03-01'};false +d(a).isSame(d(b), 'month');{a: '2023-12-31', b: '2023-12-01'};true +d(a).isSame(d(b), 'month');{a: null, b: null};false +d(a).isSameOrAfter(d(b), 'week');{a: '2023-10-15', b: '2023-10-09'};true +d(a).isSameOrAfter(d(b), 'week');{a: '2023-10-15', b: '2023-10-16'};false +d(a).isSameOrAfter(d(b), 'week');{a: '2023-10-16', b: '2023-10-15'};true +d(a).isSameOrAfter(d(b), 'week');{a: '2023-10-16', b: '2023-10-15'};true +d(a).isSameOrAfter(d(b), 'week');{a: '2023-10-16', b: 'no'};false +d(s) in [d('2023-10-01')..d('2023-10-31')];{s: '2023-10-15'};true +d(s) in [d('2023-10-01')..d('2023-10-31')];{s: '2023-10-15'};true +d(s) in [d('2023-10-01')..d('2023-10-31')];{s: '2023-10-31'};true +d(s) in [d('2023-10-01')..d('2023-10-31')];{s: '2023-10-31 00:00:01'};false +d(s) in [d('2023-10-01')..d('2023-10-31')];{s: '2023-09-30 23:59:59'};false +d(s) in [d('2023-10-01')..d('2023-10-31')];{s: 'bad'};false;question: an invalid date is simply outside every range rather than an error +d(s) in [d('2023-10-01')..d('2023-10-31')];{};false +d(s, 'UTC') > d('2025-03-20');{s: '2025-03-20T10:15:30Z'};true +d(s, 'UTC') > d('2025-03-20');{s: '2025-03-19'};false +d(s, 'UTC') > d('2025-03-20');{s: '2025-03-19'};false +d(s, 'UTC') > d('2025-03-20');{s: '2025-03-20'};false +d(s, 'UTC') > d('2025-03-20');{s: 1742428800001};true +max(map(xs, d(#)));{xs: ['2023-01-15', '2023-03-20', '2023-02-10']};'2023-03-20T00:00:00Z' +min(map(xs, d(#)));{xs: ['2023-01-15', '2023-03-20', '2023-02-10']};'2023-01-15T00:00:00Z' +min(map(xs, d(#)));{xs: ['2024-02-29', '2024-02-29']};'2024-02-29T00:00:00Z' +min(map(xs, d(#)));{xs: []};!error +count(xs, d(#) < d('2023-06-01'));{xs: ['2023-01-15', '2023-07-20', '2023-02-10']};2 +filter(xs, d(#).isSame(d('2023-10-01'), 'month'));{xs: ['2023-10-15', '2023-11-01', '2023-10-31 23:59']};['2023-10-15', '2023-10-31 23:59'] diff --git a/core/expression/tests/spec/standard/08-diff.csv b/core/expression/tests/spec/standard/08-diff.csv new file mode 100644 index 00000000..1752769f --- /dev/null +++ b/core/expression/tests/spec/standard/08-diff.csv @@ -0,0 +1,113 @@ +expression (string);input (json 5);output (json 5);note +# diff without a unit is milliseconds, first minus second +d('2023-10-15').diff(d('2023-10-14'));;86400000 +d('2023-10-14').diff(d('2023-10-15'));;-86400000 +d('2023-10-15T00:00:00.500Z').diff(d('2023-10-15'));;500 +d('2023-10-15').diff(d('2023-10-15'));;0 +d('2023-10-15').diff(d('2023-10-15', 'Asia/Tokyo'));;32400000 +# diff with a unit truncates toward zero +d('2023-10-15 12:00').diff(d('2023-10-15 10:30'), 'hour');;1 +d('2023-10-15 10:30').diff(d('2023-10-15 12:00'), 'hour');;-1 +d('2023-10-15 12:00').diff(d('2023-10-15 10:30'), 'minute');;90 +d('2023-10-15 12:00').diff(d('2023-10-15 10:30'), 'second');;5400 +d('2023-10-15T00:00:00.999Z').diff(d('2023-10-15'), 'second');;0 +d('2023-10-15').diff(d('2023-10-15T00:00:00.999Z'), 'second');;0 +d('2023-10-15T00:00:01.999Z').diff(d('2023-10-15'), 's');;1 +d('2023-10-15 00:00:59').diff(d('2023-10-15'), 'm');;0 +d('2023-10-16 11:59').diff(d('2023-10-15 12:00'), 'day');;0 +d('2023-10-16 12:00').diff(d('2023-10-15 12:00'), 'day');;1 +d('2023-10-15 12:00').diff(d('2023-10-16 11:59'), 'day');;0 +d('2023-10-14 12:00').diff(d('2023-10-16 11:59'), 'day');;-1 +d('2023-10-28').diff(d('2023-10-15'), 'week');;1 +d('2023-10-29').diff(d('2023-10-15'), 'w');;2 +d('2023-10-15').diff(d('2023-10-28'), 'w');;-1 +# diff in all unit spellings +d('2024-10-15').diff(d('2023-10-15'), 'seconds');;31622400 +d('2024-10-15').diff(d('2023-10-15'), 'mins');;527040 +d('2024-10-15').diff(d('2023-10-15'), 'hrs');;8784 +d('2024-10-15').diff(d('2023-10-15'), 'days');;366 +d('2024-10-15').diff(d('2023-10-15'), 'weeks');;52 +d('2024-10-15').diff(d('2023-10-15'), 'months');;12 +d('2024-10-15').diff(d('2023-10-15'), 'mo');;12 +d('2024-10-15').diff(d('2023-10-15'), 'M');;12 +d('2024-10-15').diff(d('2023-10-15'), 'm');;527040 +d('2024-10-15').diff(d('2023-10-15'), 'qtr');;4 +d('2024-10-15').diff(d('2023-10-15'), 'quarters');;4 +d('2024-10-15').diff(d('2023-10-15'), 'years');;1 +d('2024-10-15').diff(d('2023-10-15'), 'y');;1 +d('2024-10-15').diff(d('2023-10-15'), 'ms');;!error +d('2024-10-15').diff(d('2023-10-15'), 'D');;!error +d('2024-10-15').diff(d('2023-10-15'), '');;!error +# calendar units: whole months, month ends count as a whole month +d('2023-02-15').diff(d('2023-01-31'), 'month');;0 +d('2023-02-28').diff(d('2023-01-31'), 'month');;1 +d('2023-03-30').diff(d('2023-01-31'), 'month');;1 +d('2023-03-31').diff(d('2023-01-31'), 'month');;2 +d('2024-03-31').diff(d('2024-02-29'), 'month');;1 +d('2024-01-31').diff(d('2024-02-29'), 'month');;-1 +d('2023-01-31').diff(d('2023-03-30'), 'month');;-1 +d('2023-11-14').diff(d('2023-10-15'), 'month');;0 +d('2023-11-15').diff(d('2023-10-15'), 'month');;1 +d('2023-11-15').diff(d('2023-10-15 00:00:01'), 'month');;0 +d('2023-10-15').diff(d('2023-11-15'), 'month');;-1 +d('2023-10-15').diff(d('2023-11-14'), 'month');;0 +d('2024-01-15').diff(d('2023-10-15'), 'quarter');;1 +d('2024-01-14').diff(d('2023-10-15'), 'quarter');;0 +d('2023-10-15').diff(d('2024-01-15'), 'q');;-1 +d('2024-10-14').diff(d('2023-10-15'), 'year');;0 +d('2024-10-15').diff(d('2023-10-15'), 'year');;1 +d('2025-02-28').diff(d('2024-02-29'), 'year');;1 +d('2024-02-29').diff(d('2025-02-28'), 'year');;-1 +d('2028-02-29').diff(d('2024-02-29'), 'year');;4 +d('2023-10-15').diff(d('2013-10-16'), 'year');;9 +d('1900-03-01').diff(d('2000-03-01'), 'y');;-100 +# diff accepts strings and dates, invalid values give null +d('2023-10-15').diff('2023-10-10', 'day');;5 +d('2023-10-15').diff('2023-10-10 12:00', 'hour');;108 +d('2023-10-15').diff(1697241600000, 'day');;1 +d('2023-10-15').diff('garbage', 'day');;null +d('2023-10-15').diff(null, 'day');;null +d('foo').diff(d('2023-10-15'), 'day');;null +d('foo').diff(d('foo'));;null +# diff across zones and DST +d('2025-03-31', 'Europe/Berlin').diff(d('2025-03-30', 'Europe/Berlin'), 'hour');;23 +d('2025-03-31', 'Europe/Berlin').diff(d('2025-03-30', 'Europe/Berlin'), 'day');;1 +d('2025-10-27', 'Europe/Berlin').diff(d('2025-10-26', 'Europe/Berlin'), 'hour');;25 +d('2025-10-27', 'Europe/Berlin').diff(d('2025-10-26', 'Europe/Berlin'), 'day');;1 +d('2025-04-06', 'Europe/Berlin').diff(d('2025-03-30', 'Europe/Berlin'), 'week');;1 +d('2025-03-10', 'America/New_York').diff(d('2025-03-09', 'America/New_York'), 'h');;23 +d('2025-11-03', 'America/New_York').diff(d('2025-11-02', 'America/New_York'), 'h');;25 +d('2025-11-03', 'America/New_York').diff(d('2025-11-02', 'America/New_York'), 'd');;1 +d('2025-10-06', 'Australia/Lord_Howe').diff(d('2025-10-05', 'Australia/Lord_Howe'), 'm');;1410 +d('2023-10-15', 'Asia/Tokyo').diff(d('2023-10-15'), 'hour');;-9 +d('2023-10-15', 'Asia/Tokyo').diff(d('2023-10-15'), 'day');;0;question: day and week diffs subtract the offset difference, so two local midnights in different zones are 0 days apart though 9 hours apart +d('2023-10-16', 'Asia/Tokyo').diff(d('2023-10-15 20:00'), 'day');;0;question: day diffs compare wall clocks across zones (wall clocks +4h apart, instants -5h apart) +# diff on rows +d(a).diff(d(b), 'day');{a: '2023-10-15', b: '2023-10-10'};5 +d(a).diff(d(b), 'day');{a: '2023-10-15', b: '2023-10-10'};5 +d(a).diff(d(b), 'day');{a: '2024-03-01', b: '2024-02-28'};2 +d(a).diff(d(b), 'day');{a: '2023-03-01', b: '2023-02-28'};1 +d(a).diff(d(b), 'day');{a: '2023-10-10', b: '2023-10-15 12:00'};-5 +d(a).diff(d(b), 'day');{a: 'x', b: '2023-10-15'};null +d(a).diff(d(b), 'day');{a: '2023-10-15'};null +d(a).diff(d(b), 'day');{};null +d(a).diff(d(b), 'month');{a: '2023-02-28', b: '2023-01-31'};1 +d(a).diff(d(b), 'month');{a: '2023-02-27', b: '2023-01-31'};0 +d(a).diff(d(b), 'month');{a: '2024-02-29', b: '2023-02-28'};12 +d(a).diff(d(b), 'month');{a: '2024-02-29', b: '2023-02-28'};12 +d(a).diff(d(b), 'month');{a: '2023-01-01', b: '2023-12-31'};-11 +d(a).diff(d(b), 'year');{a: '2024-02-29', b: '2023-02-28'};1 +d(a).diff(d(b), 'year');{a: '2023-02-28', b: '2024-02-29'};-1 +d(a).diff(d(b), 'year');{a: '2000-01-01', b: '1900-01-01'};100 +d(a).diff(d(b));{a: '2023-10-15', b: '2023-10-15'};0 +d(a).diff(d(b));{a: '2023-10-15 00:00:01', b: '2023-10-15'};1000 +d(a).diff(d(b));{a: 0, b: 1000};-1000 +d(a).diff(d(b), u);{a: '2023-10-15 12:00', b: '2023-10-15', u: 'h'};12 +d(a).diff(d(b), u);{a: '2023-10-15 12:00', b: '2023-10-15', u: 'm'};720 +d(a).diff(d(b), u);{a: '2023-10-15 12:00', b: '2023-10-15', u: 'd'};0 +d(a).diff(d(b), u);{a: '2023-10-15 12:00', b: '2023-10-15', u: 'x'};!error +d(a, 'Europe/Berlin').diff(d(b, 'Europe/Berlin'), 'h');{a: '2025-03-31', b: '2025-03-30'};23 +d(a, 'Europe/Berlin').diff(d(b, 'Europe/Berlin'), 'h');{a: '2025-10-27', b: '2025-10-26'};25 +d(a, 'Europe/Berlin').diff(d(b, 'Europe/Berlin'), 'h');{a: '2025-06-02', b: '2025-06-01'};24 +d(a, 'Europe/Berlin').diff(d(b, 'Europe/Berlin'), 'h');{a: '2025-06-02', b: '2025-06-01'};24 +d(a, 'Europe/Berlin').diff(d(b, 'Europe/Berlin'), 'h');{a: '2025-03-30 02:30', b: '2025-03-30'};2 diff --git a/core/expression/tests/spec/standard/08-dst.csv b/core/expression/tests/spec/standard/08-dst.csv new file mode 100644 index 00000000..515b4ff5 --- /dev/null +++ b/core/expression/tests/spec/standard/08-dst.csv @@ -0,0 +1,111 @@ +expression (string);input (json 5);output (json 5);note +# instants around the transitions +d('2025-03-30T00:59:59Z').tz('Europe/Berlin');;'2025-03-30T01:59:59+01:00' +d('2025-03-30T01:00:00Z').tz('Europe/Berlin');;'2025-03-30T03:00:00+02:00' +d('2025-10-26T00:30:00Z').tz('Europe/Berlin');;'2025-10-26T02:30:00+02:00' +d('2025-10-26T01:30:00Z').tz('Europe/Berlin');;'2025-10-26T02:30:00+01:00' +d('2025-03-09T07:00:00Z').tz('America/New_York');;'2025-03-09T03:00:00-04:00' +d('2025-11-02T05:30:00Z').tz('America/New_York');;'2025-11-02T01:30:00-04:00' +d('2025-11-02T06:30:00Z').tz('America/New_York');;'2025-11-02T01:30:00-05:00' +d('2025-10-04T15:30:00Z').tz('Australia/Lord_Howe');;'2025-10-05T02:30:00+11:00' +d('2025-10-04T15:29:59Z').tz('Australia/Lord_Howe');;'2025-10-05T01:59:59+10:30' +# exact units (seconds to hours) are elapsed time +d('2025-03-30 01:30', 'Europe/Berlin').add(1, 'h');;'2025-03-30T03:30:00+02:00' +d('2025-03-30 03:30', 'Europe/Berlin').sub(1, 'h');;'2025-03-30T01:30:00+01:00' +d('2025-10-26 02:30', 'Europe/Berlin').add(1, 'h');;'2025-10-26T02:30:00+01:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d('2025-10-26 01:30', 'Europe/Berlin').add(2, 'h');;'2025-10-26T02:30:00+01:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d('2025-03-29 12:00', 'Europe/Berlin').add(24, 'h');;'2025-03-30T13:00:00+02:00' +d('2025-03-09 01:59', 'America/New_York').add(1, 'm');;'2025-03-09T03:00:00-04:00' +d('2025-11-02 01:30', 'America/New_York').add(1, 'h');;'2025-11-02T01:30:00-05:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d('2025-11-02 01:30', 'America/New_York').add('90m');;'2025-11-02T02:00:00-05:00' +d('2025-10-26 02:30', 'Europe/Berlin').add(0, 'h');;'2025-10-26T02:30:00+02:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(1761442200000, 'Europe/Berlin').sub(0, 's');;'2025-10-26T02:30:00+01:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d('2025-10-26 03:30', 'Europe/Berlin').sub(1, 'h');;'2025-10-26T02:30:00+01:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d('2025-10-26 02:30', 'Europe/Berlin').add(1, 'M');;'2025-11-26T02:30:00+01:00' +d('2025-10-26 02:30', 'Europe/Berlin').add(1, 'h').isValid();;true;bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d('2025-10-05 01:45', 'Australia/Lord_Howe').add(15, 'm');;'2025-10-05T02:30:00+11:00' +# days and weeks across a transition +d('2025-03-29 12:00', 'Europe/Berlin').add(1, 'd');;'2025-03-30T13:00:00+02:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-03-31 00:00', 'Europe/Berlin').sub(1, 'd');;'2025-03-29T23:00:00+01:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-10-25 12:00', 'Europe/Berlin').add(1, 'd');;'2025-10-26T11:00:00+01:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-03-27 12:00', 'Europe/Berlin').add(1, 'w');;'2025-04-03T13:00:00+02:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-03-08 12:00', 'America/New_York').add(1, 'd');;'2025-03-09T13:00:00-04:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-11-01 12:00', 'America/New_York').add('1d');;'2025-11-02T11:00:00-05:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-10-04 12:00', 'Australia/Lord_Howe').add(1, 'd');;'2025-10-05T12:30:00+11:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d('2025-06-01 12:00', 'Europe/Berlin').add(1, 'd');;'2025-06-02T12:00:00+02:00' +# months and years keep the wall clock +d('2025-03-15 12:00', 'Europe/Berlin').add(1, 'M');;'2025-04-15T12:00:00+02:00' +d('2025-10-15 12:00', 'Europe/Berlin').add(1, 'M');;'2025-11-15T12:00:00+01:00' +d('2025-11-15 12:00', 'America/New_York').sub(1, 'M');;'2025-10-15T12:00:00-04:00' +d('2024-03-30 12:00', 'Europe/Berlin').add(1, 'y');;'2025-03-30T12:00:00+02:00' +d('2025-01-30 02:30', 'Europe/Berlin').add(2, 'M');;'2025-03-30T03:30:00+02:00';bug: a month step landing in the spring-forward gap gives an invalid date +d('2025-02-09 02:30', 'America/New_York').add(1, 'M');;'2025-03-09T03:30:00-04:00';bug: a month step landing in the spring-forward gap gives an invalid date +d('2025-09-26 02:30', 'Europe/Berlin').add(1, 'M');;'2025-10-26T02:30:00+02:00';bug: a month step landing in the fall-back overlap gives an invalid date instead of the earlier offset that d() picks +d('2024-11-02 01:30', 'America/New_York').add(1, 'y');;'2025-11-02T01:30:00-04:00';bug: a year step landing in the fall-back overlap gives an invalid date +d('2025-09-05 02:15', 'Australia/Lord_Howe').add(1, 'M');;'2025-10-05T02:45:00+11:00';bug: a month step landing in the 30-minute gap gives an invalid date +# startOf / endOf on transition days +d('2025-03-30 12:00', 'Europe/Berlin').startOf('day');;'2025-03-30T00:00:00+01:00' +d('2025-03-30 12:00', 'Europe/Berlin').endOf('day');;'2025-03-30T23:59:59+02:00' +d('2025-10-26 12:00', 'Europe/Berlin').startOf('day');;'2025-10-26T00:00:00+02:00' +d('2025-10-26 12:00', 'Europe/Berlin').endOf('day');;'2025-10-26T23:59:59+01:00' +d('2025-03-30 12:00', 'Europe/Berlin').endOf('day').diff(d('2025-03-30 12:00', 'Europe/Berlin').startOf('day'), 'h');;22 +d('2025-03-09 12:00', 'America/New_York').startOf('day');;'2025-03-09T00:00:00-05:00' +d('2025-11-02 12:00', 'America/New_York').startOf('day');;'2025-11-02T00:00:00-04:00' +d('2025-11-02 12:00', 'America/New_York').endOf('day');;'2025-11-02T23:59:59-05:00' +d('2025-03-30 03:30', 'Europe/Berlin').startOf('hour');;'2025-03-30T03:00:00+02:00' +d('2025-03-31', 'Europe/Berlin').startOf('month');;'2025-03-01T00:00:00+01:00' +d('2025-03-01', 'Europe/Berlin').endOf('month');;'2025-03-31T23:59:59+02:00' +d('2025-10-01', 'Europe/Berlin').endOf('month');;'2025-10-31T23:59:59+01:00' +d('2025-03-27', 'Europe/Berlin').endOf('week');;'2025-03-30T23:59:59+02:00' +d('2025-04-06 01:45', 'Australia/Lord_Howe').startOf('hour');;'2025-04-06T01:00:00+11:00' +d('2025-10-26 02:30', 'Europe/Berlin').startOf('hour');;'2025-10-26T02:00:00+02:00';bug: startOf on an ambiguous wall time gives an invalid date +d(1761442200000, 'Europe/Berlin').startOf('hour');;'2025-10-26T02:00:00+01:00';bug: startOf on the second 02:30 of the fall-back night gives an invalid date +d('2025-10-26 02:30', 'Europe/Berlin').startOf('second');;'2025-10-26T02:30:00+02:00';bug: startOf('second') on an ambiguous wall time gives an invalid date +d('2025-10-26 02:30', 'Europe/Berlin').startOf('day');;'2025-10-26T00:00:00+02:00' +d('2025-10-26 02:30', 'Europe/Berlin').endOf('day');;'2025-10-26T23:59:59+01:00';bug: endOf from an ambiguous wall time gives an invalid date +d('2025-11-02 01:30', 'America/New_York').endOf('day');;'2025-11-02T23:59:59-05:00';bug: endOf from an ambiguous wall time gives an invalid date +d('2025-11-02 01:30', 'America/New_York').endOf('month');;'2025-11-30T23:59:59-05:00';bug: endOf from an ambiguous wall time gives an invalid date +d('2025-04-06 01:45', 'Australia/Lord_Howe').startOf('minute');;'2025-04-06T01:45:00+11:00';bug: startOf on an ambiguous wall time gives an invalid date +d('2025-03-05 02:30', 'America/New_York').endOf('week');;'2025-03-09T23:59:59-04:00';bug: endOf('week') steps through the gap day at 02:30 and gives an invalid date +d('2025-03-09 12:00', 'America/Havana').startOf('day');;'2025-03-09T01:00:00-04:00';bug: midnight does not exist in Havana that day, the start of the day is 01:00, not an invalid date +d('2025-10-26 02:30', 'Europe/Berlin').isSame(d('2025-10-26 12:00', 'Europe/Berlin'), 'day');;true;bug: isSame with a unit is false for an ambiguous wall time because startOf fails +d('2025-10-26 02:30', 'Europe/Berlin').isBefore(d('2025-10-27', 'Europe/Berlin'), 'day');;true;bug: isBefore with a unit is false for an ambiguous wall time because endOf fails +d('2025-10-26 02:30', 'Europe/Berlin').isToday();;false +# rows: add a day, read the hour +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-03-15 12:00'};12 +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-03-15 12:00'};12 +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-03-29 12:00'};13;question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-03-30 01:30'};2;question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-10-25 12:00'};11;question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-10-26 02:30'};1;question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: '2025-03-30 02:30'};3 +d(s, 'Europe/Berlin').add(1, 'day').hour();{s: 'x'};null +d(s, 'Europe/Berlin').add(1, 'day').hour();{};null +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-02-28 12:00'};'2025-03-28T12:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-03-28 12:00'};'2025-04-28T12:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-03-31 23:00'};'2025-04-30T23:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-03-31 23:00'};'2025-04-30T23:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-02-28 02:30'};'2025-03-28T02:30:00+01:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-02-30 02:30'};'Invalid date' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-09-26 02:30'};'2025-10-26T02:30:00+02:00';bug: a month step landing in the fall-back overlap gives an invalid date +d(s, 'Europe/Berlin').startOf('day');{s: '2025-03-30 12:00'};'2025-03-30T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('day');{s: '2025-03-30 12:00'};'2025-03-30T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('day');{s: '2025-03-30 03:00'};'2025-03-30T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('day');{s: '2025-10-26 23:59'};'2025-10-26T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('day');{s: '2025-06-15 10:00'};'2025-06-15T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('day');{s: null};'Invalid date' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-03-30 00:30'};'2025-03-30T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-10-26 00:30'};'2025-10-26T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-10-26 02:30'};'2025-10-26T23:59:59+01:00';bug: endOf from an ambiguous wall time gives an invalid date +d(s, 'Europe/Berlin').endOf('day');{s: '2025-12-31 12:00'};'2025-12-31T23:59:59+01:00' +d(s, 'America/New_York').add(n, 'h');{s: '2025-03-09 00:30', n: 2};'2025-03-09T03:30:00-04:00' +d(s, 'America/New_York').add(n, 'h');{s: '2025-03-09 00:30', n: 2};'2025-03-09T03:30:00-04:00' +d(s, 'America/New_York').add(n, 'h');{s: '2025-11-02 00:30', n: 1};'2025-11-02T01:30:00-04:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'America/New_York').add(n, 'h');{s: '2025-11-02 00:30', n: 2};'2025-11-02T01:30:00-05:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'America/New_York').add(n, 'h');{s: '2025-11-02 00:30', n: 3};'2025-11-02T02:30:00-05:00' +d(s, 'America/New_York').add(n, 'h');{s: '2025-11-02 00:30', n: -1};'2025-11-01T23:30:00-04:00' +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-10-25 02:30'};'2025-10-26T02:30:00+02:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-10-25 02:30'};'2025-10-26T02:30:00+02:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-10-25 03:30'};'2025-10-26T02:30:00+01:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-10-25 04:30'};'2025-10-26T03:30:00+01:00';question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-10-24 02:30'};'2025-10-25T02:30:00+02:00' diff --git a/core/expression/tests/spec/standard/08-format.csv b/core/expression/tests/spec/standard/08-format.csv new file mode 100644 index 00000000..fe9298cf --- /dev/null +++ b/core/expression/tests/spec/standard/08-format.csv @@ -0,0 +1,170 @@ +expression (string);input (json 5);output (json 5);note +# format: strftime-style specifiers (Thursday 2023-10-05 04:05:06.007 UTC) +d('2023-10-05T04:05:06.007Z').format('%Y-%m-%d');;'2023-10-05' +d('2023-10-05T04:05:06.007Z').format('%Y');;'2023' +d('2023-10-05T04:05:06.007Z').format('%y');;'23' +d('2023-10-05T04:05:06.007Z').format('%C');;'20' +d('2023-10-05T04:05:06.007Z').format('%m');;'10' +d('2023-10-05T04:05:06.007Z').format('%-m');;'10' +d('2023-10-05T04:05:06.007Z').format('%d');;'05' +d('2023-10-05T04:05:06.007Z').format('%-d');;'5' +d('2023-10-05T04:05:06.007Z').format('%e');;' 5' +d('2023-10-05T04:05:06.007Z').format('%H');;'04' +d('2023-10-05T04:05:06.007Z').format('%-H');;'4' +d('2023-10-05T04:05:06.007Z').format('%k');;' 4' +d('2023-10-05T04:05:06.007Z').format('%I');;'04' +d('2023-10-05T04:05:06.007Z').format('%l');;' 4' +d('2023-10-05T04:05:06.007Z').format('%p');;'AM' +d('2023-10-05T04:05:06.007Z').format('%P');;'am' +d('2023-10-05T04:05:06.007Z').format('%M');;'05' +d('2023-10-05T04:05:06.007Z').format('%S');;'06' +d('2023-10-05T04:05:06.007Z').format('%f');;'007000000' +d('2023-10-05T04:05:06.007Z').format('%.f');;'.007' +d('2023-10-05T04:05:06.007Z').format('%.3f');;'.007' +d('2023-10-05T04:05:06.007Z').format('%.6f');;'.007000' +d('2023-10-05T04:05:06.007Z').format('%3f');;'007' +d('2023-10-05T04:05:06.007Z').format('%6f');;'007000' +d('2023-10-05T04:05:06.007Z').format('%a');;'Thu' +d('2023-10-05T04:05:06.007Z').format('%A');;'Thursday' +d('2023-10-05T04:05:06.007Z').format('%b');;'Oct' +d('2023-10-05T04:05:06.007Z').format('%h');;'Oct' +d('2023-10-05T04:05:06.007Z').format('%B');;'October' +d('2023-10-05T04:05:06.007Z').format('%j');;'278' +d('2023-10-05T04:05:06.007Z').format('%u');;'4' +d('2023-10-05T04:05:06.007Z').format('%w');;'4' +d('2023-10-05T04:05:06.007Z').format('%U');;'40' +d('2023-10-05T04:05:06.007Z').format('%W');;'40' +d('2023-10-05T04:05:06.007Z').format('%V');;'40' +d('2023-10-05T04:05:06.007Z').format('%G');;'2023' +d('2023-10-05T04:05:06.007Z').format('%g');;'23' +d('2023-10-05T04:05:06.007Z').format('%s');;'1696478706' +d('2023-10-05T04:05:06.007Z').format('%z');;'+0000' +d('2023-10-05T04:05:06.007Z').format('%:z');;'+00:00' +d('2023-10-05T04:05:06.007Z').format('%D');;'10/05/23' +d('2023-10-05T04:05:06.007Z').format('%x');;'10/05/23' +d('2023-10-05T04:05:06.007Z').format('%F');;'2023-10-05' +d('2023-10-05T04:05:06.007Z').format('%T');;'04:05:06' +d('2023-10-05T04:05:06.007Z').format('%X');;'04:05:06' +d('2023-10-05T04:05:06.007Z').format('%R');;'04:05' +d('2023-10-05T04:05:06.007Z').format('%r');;'04:05:06 AM' +d('2023-10-05T04:05:06.007Z').format('%c');;'Thu Oct 5 04:05:06 2023' +d('2023-10-05T04:05:06.007Z').format('%v');;' 5-Oct-2023' +d('2023-10-05T04:05:06.007Z').format('%+');;'2023-10-05T04:05:06.007+00:00' +d('2023-10-05T04:05:06.007Z').format('%%');;'%' +d('2023-10-05T04:05:06.007Z').format('100%% at %H');;'100% at 04' +d('2023-10-05T04:05:06.007Z').format('');;'' +d('2023-10-05T04:05:06.007Z').format('plain text');;'plain text' +d('2023-10-05T04:05:06.007Z').format('Day %j of %Y, week %V');;'Day 278 of 2023, week 40' +# afternoon, Sunday, week-number edge cases +d('2023-10-15T14:30:45Z').format('%A, %B %d %Y, %H:%M:%S');;'Sunday, October 15 2023, 14:30:45' +d('2023-10-15T14:30:45Z').format('%I:%M %p');;'02:30 PM' +d('2023-10-15T12:00:00Z').format('%I %p');;'12 PM' +d('2023-10-15T00:00:00Z').format('%I %p');;'12 AM' +d('2023-10-15T14:30:45Z').format('%u %w');;'7 0' +d('2023-01-01').format('%U %W %V %G');;'01 00 52 2022' +d('2023-01-02').format('%U %W %V %G');;'01 01 01 2023' +d('2024-12-31').format('%U %W %V %G %j');;'52 53 01 2025 366' +d('2021-01-03').format('%U %W %V %G');;'01 00 53 2020' +d('0987-06-05').format('%Y %y %C');;'0987 87 09' +d('1969-12-31 23:59:59').format('%s');;'-1' +# invalid specifiers are evaluation errors, not panics +d('2023-10-05').format('%Q');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%E');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%#z');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%-');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%^A');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%#Z');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format('%a%');;!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d('2023-10-05').format(null);;!error +d('2023-10-05').format(1);;!error +# format with zones +d('2023-10-05', 'UTC').format();;'2023-10-05 00:00:00 UTC' +d('2023-10-05', 'Europe/Berlin').format();;'2023-10-05 00:00:00 CEST' +d('2023-01-05', 'Europe/Berlin').format();;'2023-01-05 00:00:00 CET' +d('2023-10-05', 'UTC').format('%z %Z');;'+0000 UTC' +d('2023-10-05', 'Europe/Berlin').format('%z %Z %:z');;'+0200 CEST +02:00' +d('2023-10-05', 'America/New_York').format('%z %Z');;'-0400 EDT' +d('2023-01-05', 'America/New_York').format('%z %Z');;'-0500 EST' +d('2023-10-05', 'Asia/Kolkata').format('%z %Z');;'+0530 IST' +d('2023-10-05', 'Asia/Kathmandu').format('%z %:z');;'+0545 +05:45' +d('2023-10-05', 'Australia/Lord_Howe').format('%z');;'+1100' +d('2023-06-05', 'Australia/Lord_Howe').format('%z');;'+1030' +d('2023-10-05', 'Etc/GMT+5').format('%z');;'-0500' +d('2023-10-05', 'Etc/GMT+5').format('%Y-%m-%d %H:%M');;'2023-10-05 00:00' +d('2023-10-05T04:05:06Z').tz('Asia/Tokyo').format('%Y-%m-%d %H:%M %z');;'2023-10-05 13:05 +0900' +d('2023-10-05T22:05:06Z').tz('Asia/Tokyo').format('%A %d');;'Friday 06' +d('2023-10-05T22:05:06Z').tz('Asia/Kathmandu').format('%F %T');;'2023-10-06 03:50:06' +d('2023-10-05T22:05:06Z').tz('America/St_Johns').format('%F %T %z');;'2023-10-05 19:35:06 -0230' +# format on invalid dates +d('foo').format('%Y');;'Invalid date' +d('foo').format();;'Invalid date' +d(null).format('%Y-%m-%d');;'Invalid date' +# format on rows +d(s).format('%Y-%m-%d');{s: '2023-10-15 13:45'};'2023-10-15' +d(s).format('%Y-%m-%d');{s: '2023-10-15 13:45'};'2023-10-15' +d(s).format('%Y-%m-%d');{s: '2024-02-29'};'2024-02-29' +d(s).format('%Y-%m-%d');{s: 1697328000000};'2023-10-15' +d(s).format('%Y-%m-%d');{s: 'x'};'Invalid date' +d(s).format('%Y-%m-%d');{};'Invalid date' +d(s).format(f);{s: '2023-10-15 13:45', f: '%H:%M'};'13:45' +d(s).format(f);{s: '2023-10-15 13:45', f: '%d/%m/%Y'};'15/10/2023' +d(s).format(f);{s: '2023-10-15 13:45', f: '%A'};'Sunday' +d(s).format(f);{s: '2023-10-15 13:45', f: '%Q'};!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d(s).format(f);{s: '2023-10-15 13:45', f: '%'};!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d(s).format(f);{s: '2023-10-15 13:45', f: '%-'};!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d(s).format(f);{s: '2023-10-15 13:45', f: '%a%'};!error;bug: an unknown format specifier panics inside chrono instead of raising an evaluation error +d(s).format(f);{s: '2023-10-15 13:45', f: null};!error +d(s, 'Europe/Berlin').format('%H:%M %z');{s: '2025-03-30 01:59'};'01:59 +0100' +d(s, 'Europe/Berlin').format('%H:%M %z');{s: '2025-03-30 03:00'};'03:00 +0200' +d(s, 'Europe/Berlin').format('%H:%M %z');{s: '2025-10-26 02:30'};'02:30 +0200' +d(s, 'Europe/Berlin').format('%H:%M %z');{s: 1761442200000};'02:30 +0100' +d(s, 'Europe/Berlin').format('%H:%M %z');{s: 1761442200000};'02:30 +0100' +# the string form: RFC 3339 to the second, Z for a zero offset +d('2023-10-05T04:05:06.007Z');;'2023-10-05T04:05:06Z' +d('2023-10-05', 'Europe/London');;'2023-10-05T00:00:00+01:00' +d('2023-01-05', 'Europe/London');;'2023-01-05T00:00:00Z' +d('2023-01-05', 'Etc/GMT-14');;'2023-01-05T00:00:00+14:00' +d('2023-01-05', 'America/St_Johns');;'2023-01-05T00:00:00-03:30' +[d('2023-06-05'), d('2023-06-05', 'Asia/Kolkata')];;['2023-06-05T00:00:00Z', '2023-06-05T00:00:00+05:30'] +{at: d('2023-06-05')};;{at: '2023-06-05T00:00:00Z'} +type(d('2023-06-05'));;'date' +type(d('foo'));;'date' +string(d('2023-10-05'));;'2023-10-05T00:00:00Z' +string(d('2023-10-05', 'Europe/Berlin'));;'2023-10-05T00:00:00+02:00' +string(d('foo'));;'Invalid date' +`${d('2023-10-05')}`;;'2023-10-05T00:00:00Z' +`due ${d('2023-10-05').add(1, 'd').format('%Y-%m-%d')}`;;'due 2023-10-06' +`at ${d(s).format('%H:%M')}`;{s: '2023-10-05 09:30'};'at 09:30' +`at ${d(s).format('%H:%M')}`;{s: '2023-10-05 23:59'};'at 23:59' +`at ${d(s).format('%H:%M')}`;{s: 'bad'};'at Invalid date' +d('2023-10-05') + '';;'2023-10-05T00:00:00Z' +'x' + d('2023-10-05');;'x2023-10-05T00:00:00Z' +# tz() converts the zone and keeps the instant +d('2023-10-15T00:00:00Z').tz('Asia/Kolkata');;'2023-10-15T05:30:00+05:30' +d('2023-10-15T00:00:00Z').tz('Asia/Kathmandu');;'2023-10-15T05:45:00+05:45' +d('2023-10-15T00:00:00Z').tz('Australia/Lord_Howe');;'2023-10-15T11:00:00+11:00' +d('2023-06-15T00:00:00Z').tz('Australia/Lord_Howe');;'2023-06-15T10:30:00+10:30' +d('2023-10-15T00:00:00Z').tz('Etc/GMT+5');;'2023-10-14T19:00:00-05:00' +d('2023-10-15T00:00:00Z').tz('Etc/UTC');;'2023-10-15T00:00:00Z' +d('2023-10-15', 'Europe/Berlin').tz('UTC');;'2023-10-14T22:00:00Z' +d('2023-10-15', 'Europe/Berlin').tz('America/New_York');;'2023-10-14T18:00:00-04:00' +d('2023-10-15', 'Europe/Berlin').tz('America/New_York').tz('Europe/Berlin');;'2023-10-15T00:00:00+02:00' +d('2023-10-15', 'Europe/Berlin').tz('Asia/Tokyo') == d('2023-10-15', 'Europe/Berlin');;true +d('2023-10-15', 'Europe/Berlin').tz('Asia/Tokyo').timestamp();;1697320800000 +d('2023-10-15').tz('Nope/Zone');;!error +d('2023-10-15').tz('utc');;!error +d('2023-10-15').tz(null);;!error +d('2023-10-15').tz('');;!error +d('foo').tz('UTC');;'Invalid date' +d(s).tz('Asia/Kolkata');{s: '2023-10-15T00:00:00Z'};'2023-10-15T05:30:00+05:30' +d(s).tz('Asia/Kolkata');{s: '2023-10-15T00:00:00Z'};'2023-10-15T05:30:00+05:30' +d(s).tz('Asia/Kolkata');{s: '2023-12-31 20:00'};'2024-01-01T01:30:00+05:30' +d(s).tz('Asia/Kolkata');{s: 0};'1970-01-01T05:30:00+05:30' +d(s).tz('Asia/Kolkata');{s: 'x'};'Invalid date' +d(s).tz('Asia/Kolkata');{};'Invalid date' +d(s).tz(z).hour();{s: '2023-10-15 12:00', z: 'Asia/Kathmandu'};17 +d(s).tz(z).hour();{s: '2023-10-15 12:00', z: 'America/New_York'};8 +d(s).tz(z).hour();{s: '2023-10-15 12:00', z: 'Australia/Lord_Howe'};23 +d(s).tz(z).hour();{s: '2023-10-15 12:00', z: 'Etc/GMT+12'};0 +d(s).tz(z).hour();{s: '2023-10-15 12:00', z: 'Bad/Zone'};!error diff --git a/core/expression/tests/spec/standard/08-legacy.csv b/core/expression/tests/spec/standard/08-legacy.csv new file mode 100644 index 00000000..ded4c6d1 --- /dev/null +++ b/core/expression/tests/spec/standard/08-legacy.csv @@ -0,0 +1,137 @@ +expression (string);input (json 5);output (json 5);note +# date(): deprecated, unix seconds +date('2023-10-15');;1697328000 +date('2023-10-15 10:30:45');;1697365845 +date('2023-10-15T10:30:45Z');;1697365845 +date('2023-10-15T12:30:45+02:00');;1697365845 +date('1970-01-01');;0 +date('1969-12-31 23:59:59');;-1 +date('now');;1742465730 +date(1697328000);;1697328000 +date(1.5);;1 +date('2023-10-15 10:30');;!error;question: the legacy parser rejects 'YYYY-MM-DD HH:MM' which d() accepts +date('2023-02-29');;!error +date('garbage');;!error +date('');;!error +date(null);;!error +date(true);;!error +# time(): deprecated, seconds since midnight +time('10:30');;37800 +time('10:30:15');;37815 +time('10');;36000;bug: the legacy parser has an hour-only pattern but chrono cannot build a time from an hour alone, so it fails +time('00:00');;0 +time('23:59:59');;86399 +time('2023-10-15 10:30:00');;37800 +time('2023-10-15T10:30:00Z');;37800 +time('2023-10-15T10:30:00+02:00');;30600 +time('now');;36930 +time(3600);;3600 +time(-1);;!error +time('24:00');;!error +time('10:60');;!error +time('noon');;!error +time(null);;!error +# duration(): deprecated, seconds +duration('1h');;3600 +duration('1h 30m');;5400 +duration('90min');;5400 +duration('1d');;86400 +duration('2 days');;172800 +duration('1w');;604800 +duration('45s');;45 +duration('1m');;60 +duration('1ms');;0 +duration('0s');;0 +duration(3600);;3600 +duration(1.5);;1 +duration('');;!error +duration('abc');;!error +duration('1x');;!error +duration(-1);;!error +duration(null);;!error +# part extraction on strings and unix seconds +year('2023-10-15');;2023 +year(1697328000);;2023 +year('2023-12-31T23:00:00-05:00');;2024 +year('bad');;!error +year(null);;!error +dayOfWeek('2023-10-15');;7 +dayOfWeek('2023-10-16');;1 +dayOfWeek(0);;4 +dayOfMonth('2023-10-15');;15 +dayOfMonth('2024-02-29 12:00:00');;29 +dayOfYear('2023-10-15');;288 +dayOfYear('2024-12-31');;366 +weekOfYear('2023-10-15');;41 +weekOfYear('2021-01-03');;53 +weekOfYear('2024-12-30');;1 +monthOfYear('2023-10-15');;10 +monthOfYear(0);;1 +monthString('2023-10-15');;'Oct' +monthString('2023-01-01');;'Jan' +weekdayString('2023-10-15');;'Sun' +weekdayString('2023-10-18');;'Wed' +dateString('2023-10-15');;'2023-10-15 00:00:00' +dateString('2023-10-15T10:30:45+02:00');;'2023-10-15 08:30:45' +dateString(0);;'1970-01-01 00:00:00' +dateString(-1);;'1969-12-31 23:59:59' +dateString(date('2023-10-15 10:30:45'));;'2023-10-15 10:30:45' +# startOf / endOf: deprecated, unix seconds +startOf('2023-10-15 10:30:45', 's');;1697365845 +startOf('2023-10-15 10:30:45', 'm');;1697365800 +startOf('2023-10-15 10:30:45', 'minute');;1697365800 +startOf('2023-10-15 10:30:45', 'h');;1697364000 +startOf('2023-10-15 10:30:45', 'd');;1697328000 +startOf('2023-10-15 10:30:45', 'day');;1697328000 +startOf('2023-10-15 10:30:45', 'w');;1696809600 +startOf('2023-10-15 10:30:45', 'M');;1696118400 +startOf('2023-10-15 10:30:45', 'month');;1696118400 +startOf('2023-10-15 10:30:45', 'y');;1672531200 +startOf('2024-03-01', 'week');;1708905600 +startOf(1697365845, 'd');;1697328000 +startOf('2023-10-15', 'q');;!error +startOf('2023-10-15', 'mo');;!error +startOf('2023-10-15', 'D');;!error +startOf('bad', 'd');;!error +endOf('2023-10-15 10:30:45', 's');;1697365845 +endOf('2023-10-15 10:30:45', 'm');;1697365859 +endOf('2023-10-15 10:30:45', 'h');;1697367599 +endOf('2023-10-15 10:30:45', 'd');;1697414399 +endOf('2023-10-15 10:30:45', 'w');;1697414399 +endOf('2024-02-26', 'w');;1709510399 +endOf('2023-10-15 10:30:45', 'M');;1698796799 +endOf('2024-02-10', 'M');;1709251199 +endOf('2023-02-10', 'month');;1677628799 +endOf('2023-10-15 10:30:45', 'y');;1704067199 +endOf('2024-01-15', 'year');;1735689599 +endOf('2023-02-15', 'y');;1704067199;bug: legacy endOf year keeps the current month's day count, so February gives Dec 28 +endOf('2023-04-15', 'y');;1704067199;bug: legacy endOf year keeps the current month's day count, so April gives Dec 30 +endOf('2023-10-15', 'q');;!error +# legacy functions agree with d() +date('2023-10-15 10:30:45') * 1000 == d('2023-10-15 10:30:45').timestamp();;true +startOf('2023-10-15 10:30:45', 'w') * 1000 == d('2023-10-15 10:30:45').startOf('w').timestamp();;true +weekOfYear('2027-01-01') == d('2027-01-01').week();;true +# legacy functions on rows +year(s);{s: '2023-10-15'};2023 +year(s);{s: '2023-10-15'};2023 +year(s);{s: 1697328000};2023 +year(s);{s: '1999-12-31 23:59:59'};1999 +year(s);{s: 'bad'};!error +year(s);{};!error +endOf(s, 'y');{s: '2023-01-15'};1704067199 +endOf(s, 'y');{s: '2023-03-15'};1704067199 +endOf(s, 'y');{s: '2023-06-15'};1704067199;bug: legacy endOf year keeps June's 30-day count and gives Dec 30 +endOf(s, 'y');{s: '2023-06-15'};1704067199;bug: legacy endOf year keeps June's 30-day count and gives Dec 30 +endOf(s, 'y');{s: '2024-02-29'};1735689599;bug: legacy endOf year keeps February's day count and gives Dec 29 +endOf(s, 'M');{s: '2024-02-01'};1709251199 +endOf(s, 'M');{s: '2023-02-01'};1677628799 +date(s);{s: '2023-10-15'};1697328000 +date(s);{s: '2023-10-15T12:30:45+02:00'};1697365845 +date(s);{s: 1697328000};1697328000 +date(s);{s: null};!error +time(s);{s: '10:30'};37800 +time(s);{s: '23:59:59'};86399 +time(s);{s: '10:30'};37800 +duration(s);{s: '2h'};7200 +duration(s);{s: '1d 12h'};129600 +duration(s);{s: 'forever'};!error diff --git a/core/expression/tests/spec/standard/08-parsing.csv b/core/expression/tests/spec/standard/08-parsing.csv new file mode 100644 index 00000000..a04c8547 --- /dev/null +++ b/core/expression/tests/spec/standard/08-parsing.csv @@ -0,0 +1,186 @@ +expression (string);input (json 5);output (json 5);note +# d(): date-only strings are midnight in the local zone (UTC for this suite) +d('2023-10-15');;'2023-10-15T00:00:00Z' +d('2024-02-29');;'2024-02-29T00:00:00Z' +d('2000-01-01');;'2000-01-01T00:00:00Z' +d('1970-01-01');;'1970-01-01T00:00:00Z' +d('1900-03-01');;'1900-03-01T00:00:00Z' +d('0001-01-01');;'0001-01-01T00:00:00Z' +d('9999-12-31');;'9999-12-31T00:00:00Z' +d('1969-07-20');;'1969-07-20T00:00:00Z' +# d(): 'YYYY-MM-DD HH:MM' and 'YYYY-MM-DD HH:MM:SS' +d('2023-10-15 14:30');;'2023-10-15T14:30:00Z' +d('2023-10-15 14:30:45');;'2023-10-15T14:30:45Z' +d('2023-10-15 00:00');;'2023-10-15T00:00:00Z' +d('2023-10-15 23:59:59');;'2023-10-15T23:59:59Z' +d('2023-10-15 24:00');;'Invalid date' +d('2023-10-15 12:60');;'Invalid date' +d('2023-10-15 12:30:61');;'Invalid date' +# d(): RFC 3339 with Z +d('2023-10-15T14:30:45Z');;'2023-10-15T14:30:45Z' +d('2023-10-15T14:30:45.123Z');;'2023-10-15T14:30:45Z' +d('2023-10-15T14:30:45.123Z').timestamp();;1697380245123 +d('2023-10-15T14:30:45.999999999Z').timestamp();;1697380245999 +d('2023-10-15t14:30:45z');;'2023-10-15T14:30:45Z' +d('2023-10-15 14:30:45Z');;'2023-10-15T14:30:45Z' +d('2023-10-15T00:00:00+00:00');;'2023-10-15T00:00:00Z' +d('2023-10-15T00:00:00-00:00');;'2023-10-15T00:00:00Z' +# d(): an explicit offset names an instant; it is shown in the local zone +d('2023-10-15T12:00:00+02:00');;'2023-10-15T10:00:00Z' +d('2023-10-15T12:00:00-05:30');;'2023-10-15T17:30:00Z' +d('2023-10-15T01:00:00+05:45');;'2023-10-14T19:15:00Z' +d('2023-10-15T12:00:00+02:00').timestamp();;1697364000000 +d('2023-10-15T12:00:00+02:00') == d('2023-10-15T10:00:00Z');;true +d('2023-10-15T12:00:00+02:00', 'Etc/GMT-2');;'2023-10-15T12:00:00+02:00' +d('2023-10-15T12:00:00+02:00', 'Europe/Berlin');;'2023-10-15T12:00:00+02:00' +d('2023-10-15T12:00:00Z', 'Europe/Berlin');;'2023-10-15T14:00:00+02:00' +d('2023-10-15T12:00:00Z', 'America/New_York');;'2023-10-15T08:00:00-04:00' +d('2023-10-15T12:00:00Z', 'UTC');;'2023-10-15T12:00:00Z' +# d(): strings that are not accepted give an invalid date, not an error +d('2023-10-15T14:30:00');;'2023-10-15T14:30:00Z' +d('2023-10-15T14:30');;'2023-10-15T14:30:00Z' +d('10:30');;'Invalid date';question: a bare time of day is not accepted by d() +d('10:30:00');;'Invalid date';question: a bare time of day is not accepted by d() +d('foo');;'Invalid date' +d('');;'Invalid date' +d(' ');;'Invalid date' +d('2023-13-01');;'Invalid date' +d('2023-02-30');;'Invalid date' +d('2023-02-29');;'Invalid date' +d('2023-00-10');;'Invalid date' +d('2023-10-00');;'Invalid date' +d('2023/10/15');;'2023-10-15T00:00:00Z' +d('15-10-2023');;'Invalid date' +d('20231015');;'2023-10-15T00:00:00Z' +d('2023-10');;'2023-10-01T00:00:00Z' +d('2023');;'2023-01-01T00:00:00Z' +d('Oct 15 2023');;'Invalid date' +d('2023-10-15T25:00:00Z');;'Invalid date' +d('2023-10-15T12:00:00+25:00');;'Invalid date' +d('now');;'Invalid date' +d('today');;'Invalid date' +d('2023-10-15').isValid();;true +d('foo').isValid();;false +d('2023-02-29').isValid();;false +d('2024-02-29').isValid();;true +d('1900-02-29').isValid();;false +d('2000-02-29').isValid();;true +# d(): unix timestamps in milliseconds +d(0);;'1970-01-01T00:00:00Z' +d(1697328000000);;'2023-10-15T00:00:00Z' +d(1697380245123);;'2023-10-15T14:30:45Z' +d(1697380245123).timestamp();;1697380245123 +d(-86400000);;'1969-12-31T00:00:00Z' +d(-1);;'1969-12-31T23:59:59Z' +d(-1).timestamp();;-1 +d(1000);;'1970-01-01T00:00:01Z' +d(1.5).timestamp();;1 +d(1.9).timestamp();;1 +d(-1.5).timestamp();;-1 +d(951782400000);;'2000-02-29T00:00:00Z' +d(253402300799000);;'9999-12-31T23:59:59Z' +d(1e20);;'Invalid date' +d(1697328000000, 'Europe/Berlin');;'2023-10-15T02:00:00+02:00' +d(1697328000000, 'America/New_York');;'2023-10-14T20:00:00-04:00' +d(0, 'Asia/Kolkata');;'1970-01-01T05:30:00+05:30' +# d(): non-string, non-number arguments +d(null);;'Invalid date' +d(null).isValid();;false +d(true);;'Invalid date' +d(false).isValid();;false +d([]);;'Invalid date' +d({}).isValid();;false +d(['2023-10-15']).isValid();;false +# d(): a date argument is passed through +d(d('2023-10-15'));;'2023-10-15T00:00:00Z' +d(d('2023-10-15', 'Europe/Berlin'));;'2023-10-15T00:00:00+02:00' +d(d('2023-10-15', 'Europe/Berlin'), 'UTC');;'2023-10-14T22:00:00Z' +d(d('foo')).isValid();;false +# d(): no argument is the evaluation time; a zone name alone is now in that zone +d();;'2025-03-20T10:15:30Z' +d().timestamp();;1742465730000 +d().isValid();;true +d('UTC');;'2025-03-20T10:15:30Z' +d('Europe/Berlin');;'2025-03-20T11:15:30+01:00' +d('America/New_York');;'2025-03-20T06:15:30-04:00' +d('Asia/Kathmandu');;'2025-03-20T16:00:30+05:45' +d('Europe/Berlin').timestamp();;1742465730000 +d('Europe/Berlin') == d();;true +d('Europe/Berlin').isToday();;true +d('Nowhere/City').isValid();;false +# d(): second argument time zone +d('2023-10-15', 'UTC');;'2023-10-15T00:00:00Z' +d('2023-10-15', 'Etc/UTC');;'2023-10-15T00:00:00Z' +d('2023-10-15', 'Europe/Berlin');;'2023-10-15T00:00:00+02:00' +d('2023-01-15', 'Europe/Berlin');;'2023-01-15T00:00:00+01:00' +d('2023-10-15', 'America/New_York');;'2023-10-15T00:00:00-04:00' +d('2023-01-15', 'America/New_York');;'2023-01-15T00:00:00-05:00' +d('2023-10-15', 'America/Los_Angeles');;'2023-10-15T00:00:00-07:00' +d('2023-10-15', 'Europe/London');;'2023-10-15T00:00:00+01:00' +d('2023-01-15', 'Europe/London');;'2023-01-15T00:00:00Z' +d('2023-10-15', 'Etc/GMT+5');;'2023-10-15T00:00:00-05:00' +d('2023-10-15', 'Etc/GMT-14');;'2023-10-15T00:00:00+14:00' +d('2023-10-15', 'Asia/Kolkata');;'2023-10-15T00:00:00+05:30' +d('2023-10-15', 'Asia/Kathmandu');;'2023-10-15T00:00:00+05:45' +d('2023-10-15', 'Australia/Lord_Howe');;'2023-10-15T00:00:00+11:00' +d('2023-06-15', 'Australia/Lord_Howe');;'2023-06-15T00:00:00+10:30' +d('2023-10-15', 'Asia/Tokyo');;'2023-10-15T00:00:00+09:00' +d('2023-10-15', 'Pacific/Chatham');;'2023-10-15T00:00:00+13:45' +d('2023-10-15', 'America/St_Johns');;'2023-10-15T00:00:00-02:30' +d('2023-10-15 14:30', 'Asia/Kolkata');;'2023-10-15T14:30:00+05:30' +d('2023-10-15 14:30', 'Asia/Kolkata').timestamp();;1697360400000 +d('2023-10-15', 'Asia/Kathmandu').timestamp();;1697307300000 +d('2023-10-15', 'Nope/Zone');;!error +d('2023-10-15', 'utc');;!error;question: time zone names are case-sensitive, so 'utc' is an error while 'UTC' works +d('2023-10-15', 'europe/berlin');;!error;question: time zone names are case-sensitive +d('2023-10-15', '');;!error +d('2023-10-15', '+02:00');;!error;question: fixed offsets are only accepted as Etc/GMT names +d('2023-10-15', 'CET');;'2023-10-15T00:00:00+02:00' +d('2023-10-15', 'EST');;'2023-10-15T00:00:00-05:00' +d('foo', 'Europe/Berlin').isValid();;false +d(null, 'Europe/Berlin').isValid();;false +# d(s): parsing rows from the environment +d(s);{s: '2023-10-15'};'2023-10-15T00:00:00Z' +d(s);{s: '2023-10-15'};'2023-10-15T00:00:00Z' +d(s);{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59Z' +d(s);{s: '2023-10-15T14:30:45Z'};'2023-10-15T14:30:45Z' +d(s);{s: '2023-02-29'};'Invalid date' +d(s);{s: 'garbage'};'Invalid date' +d(s);{s: null};'Invalid date' +d(s);{};'Invalid date' +d(s);{s: 1697328000000};'2023-10-15T00:00:00Z' +d(s);{s: -86400000};'1969-12-31T00:00:00Z' +d(s);{s: 'Europe/Berlin'};'2025-03-20T11:15:30+01:00' +d(s).isValid();{s: '2023-10-15'};true +d(s).isValid();{s: '2023-10-15'};true +d(s).isValid();{s: '2023-10-32'};false +d(s).isValid();{s: ''};false +d(s).isValid();{s: null};false +d(s).isValid();{};false +d(s).isValid();{s: 0};true +d(s).isValid();{s: true};false +d(s, 'Europe/Berlin');{s: '2025-03-30'};'2025-03-30T00:00:00+01:00' +d(s, 'Europe/Berlin');{s: '2025-03-30 01:59:59'};'2025-03-30T01:59:59+01:00' +d(s, 'Europe/Berlin');{s: '2025-03-30 03:00'};'2025-03-30T03:00:00+02:00' +d(s, 'Europe/Berlin');{s: '2025-10-26 02:30'};'2025-10-26T02:30:00+02:00' +d(s, 'Europe/Berlin');{s: '2025-10-26 03:00'};'2025-10-26T03:00:00+01:00' +d(s, 'Europe/Berlin');{s: '2025-10-26 03:00'};'2025-10-26T03:00:00+01:00' +d(s, 'Europe/Berlin');{s: 'nope'};'Invalid date' +d(s, 'Europe/Berlin');{s: 1742465730000};'2025-03-20T11:15:30+01:00' +d(s, z);{s: '2023-10-15', z: 'Asia/Kolkata'};'2023-10-15T00:00:00+05:30' +d(s, z);{s: '2023-10-15', z: 'Asia/Kathmandu'};'2023-10-15T00:00:00+05:45' +d(s, z);{s: '2023-10-15', z: 'Australia/Lord_Howe'};'2023-10-15T00:00:00+11:00' +d(s, z);{s: '2023-10-15', z: 'UTC'};'2023-10-15T00:00:00Z' +d(s, z);{s: '2023-10-15', z: 'Etc/GMT+5'};'2023-10-15T00:00:00-05:00' +d(s, z);{s: '2023-10-15', z: 'Mars/Olympus'};!error +d(s, z);{s: '2023-10-15', z: null};!error;question: a null zone is an error rather than falling back to the local zone like the one-argument form +d(s, z);{s: '2023-10-15'};!error +# d(): times inside a DST gap and overlap +d('2025-03-30 02:30', 'Europe/Berlin');;'2025-03-30T03:30:00+02:00' +d('2025-03-09 02:30', 'America/New_York');;'2025-03-09T03:30:00-04:00' +d('2025-03-09', 'America/Havana');;'2025-03-09T01:00:00-04:00' +d('2025-10-26 02:30', 'Europe/Berlin');;'2025-10-26T02:30:00+02:00' +d('2025-11-02 01:30', 'America/New_York');;'2025-11-02T01:30:00-04:00' +d('2025-11-02 01:30', 'America/New_York').timestamp();;1762061400000 +d('2025-10-05 02:15', 'Australia/Lord_Howe');;'2025-10-05T02:45:00+11:00' +d('2025-04-06 01:45', 'Australia/Lord_Howe');;'2025-04-06T01:45:00+11:00' diff --git a/core/expression/tests/spec/standard/08-parts.csv b/core/expression/tests/spec/standard/08-parts.csv new file mode 100644 index 00000000..594b4c62 --- /dev/null +++ b/core/expression/tests/spec/standard/08-parts.csv @@ -0,0 +1,239 @@ +expression (string);input (json 5);output (json 5);note +# getters on a UTC date-time (Sunday 2023-10-15 14:30:45.123) +d('2023-10-15T14:30:45.123Z').year();;2023 +d('2023-10-15T14:30:45.123Z').quarter();;4 +d('2023-10-15T14:30:45.123Z').month();;10 +d('2023-10-15T14:30:45.123Z').week();;41 +d('2023-10-15T14:30:45.123Z').day();;15 +d('2023-10-15T14:30:45.123Z').weekday();;7 +d('2023-10-15T14:30:45.123Z').dayOfYear();;288 +d('2023-10-15T14:30:45.123Z').hour();;14 +d('2023-10-15T14:30:45.123Z').minute();;30 +d('2023-10-15T14:30:45.123Z').second();;45 +d('2023-10-15T14:30:45.123Z').timestamp();;1697380245123 +d('2023-10-15T14:30:45.123Z').isValid();;true +d('2023-10-15T14:30:45.123Z').isLeapYear();;false +# weekday: Monday is 1, Sunday is 7 +d('2023-10-16').weekday();;1 +d('2023-10-17').weekday();;2 +d('2023-10-18').weekday();;3 +d('2023-10-19').weekday();;4 +d('2023-10-20').weekday();;5 +d('2023-10-21').weekday();;6 +d('2023-10-22').weekday();;7 +d('1970-01-01').weekday();;4 +d('2000-01-01').weekday();;6 +# week: ISO 8601 week number +d('2021-01-01').week();;53 +d('2021-01-03').week();;53 +d('2021-01-04').week();;1 +d('2024-12-29').week();;52 +d('2024-12-30').week();;1 +d('2024-12-31').week();;1 +d('2020-12-31').week();;53 +d('2015-12-31').week();;53 +d('2026-01-01').week();;1 +d('2027-01-01').week();;53 +d('2025-03-20').week();;12 +# dayOfYear +d('2023-01-01').dayOfYear();;1 +d('2023-12-31').dayOfYear();;365 +d('2024-12-31').dayOfYear();;366 +d('2024-02-29').dayOfYear();;60 +d('2024-03-01').dayOfYear();;61 +d('2023-03-01').dayOfYear();;60 +d('1900-12-31').dayOfYear();;365 +d('2000-12-31').dayOfYear();;366 +# quarter +d('2023-01-01').quarter();;1 +d('2023-03-31 23:59:59').quarter();;1 +d('2023-04-01').quarter();;2 +d('2023-06-30').quarter();;2 +d('2023-07-01').quarter();;3 +d('2023-09-30').quarter();;3 +d('2023-10-01').quarter();;4 +d('2023-12-31').quarter();;4 +# isLeapYear: divisible by 4, except centuries unless divisible by 400 +d('2024-06-01').isLeapYear();;true +d('2023-06-01').isLeapYear();;false +d('2000-06-01').isLeapYear();;true +d('1900-06-01').isLeapYear();;false +d('2100-06-01').isLeapYear();;false +d('2400-06-01').isLeapYear();;true +d('1996-01-01').isLeapYear();;true +# getters on invalid dates return null +d('foo').year();;null +d('foo').month();;null +d('foo').day();;null +d('foo').weekday();;null +d('foo').week();;null +d('foo').hour();;null +d('foo').timestamp();;null +d('foo').offsetName();;null +d('foo').isLeapYear();;null +d('foo').isToday();;null +d(null).quarter();;null +# getters are read in the date's own zone +d('2023-10-15T23:30:00Z').tz('Asia/Tokyo').day();;16 +d('2023-10-15T23:30:00Z').tz('Asia/Tokyo').hour();;8 +d('2023-10-15T23:30:00Z').tz('Asia/Tokyo').weekday();;1 +d('2023-10-15T23:30:00Z').tz('Asia/Tokyo').timestamp();;1697412600000 +d('2023-12-31T23:30:00Z').tz('Asia/Tokyo').year();;2024 +d('2023-12-31T23:30:00Z').tz('Asia/Tokyo').dayOfYear();;1 +d('2024-01-01T01:00:00Z').tz('America/New_York').year();;2023 +d('2024-01-01T01:00:00Z').tz('America/New_York').quarter();;4 +d('2024-01-01T01:00:00Z').tz('America/New_York').week();;52 +d('2023-10-15T00:00:00Z').tz('Asia/Kathmandu').minute();;45 +d('2023-10-15T00:00:00Z').tz('Asia/Kathmandu').hour();;5 +d('2023-10-15T00:00:00Z').tz('Asia/Kolkata').minute();;30 +d('2023-10-15T00:00:00Z').tz('Australia/Lord_Howe').hour();;11 +d('2023-06-15T00:00:00Z').tz('Australia/Lord_Howe').minute();;30 +d('2023-10-15 00:30', 'Etc/GMT+5').day();;15 +d('2023-10-15 00:30', 'Etc/GMT+5').timestamp();;1697347800000 +# offsetName is the zone name +d('2023-10-15', 'UTC').offsetName();;'UTC' +d('2023-10-15', 'Europe/Berlin').offsetName();;'Europe/Berlin' +d('2023-10-15', 'Etc/GMT+5').offsetName();;'Etc/GMT+5' +d('2023-10-15').tz('Asia/Kolkata').offsetName();;'Asia/Kolkata' +d('2023-10-15').tz('Australia/Lord_Howe').offsetName();;'Australia/Lord_Howe' +# isToday / isYesterday / isTomorrow (evaluation time 2025-03-20T10:15:30Z) +d('2025-03-20').isToday();;true +d('2025-03-20 23:59:59').isToday();;true +d('2025-03-19 23:59:59').isToday();;false +d('2025-03-21').isToday();;false +d('2025-03-19').isYesterday();;true +d('2025-03-19 23:59:59').isYesterday();;true +d('2025-03-18').isYesterday();;false +d('2025-03-20').isYesterday();;false +d('2025-03-21').isTomorrow();;true +d('2025-03-21 23:59:59').isTomorrow();;true +d('2025-03-22').isTomorrow();;false +d('2025-03-20').isTomorrow();;false +d('2024-03-20').isToday();;false +d().isToday();;true +d().add(1, 'd').isTomorrow();;true +d().sub(1, 'd').isYesterday();;true +d().add(1, 'y').isToday();;false +d('2025-03-20 23:30', 'America/New_York').isToday();;true +d('2025-03-21 01:00', 'Asia/Tokyo').isToday();;false +d('2025-03-21 01:00', 'Asia/Tokyo').isTomorrow();;true +d('2025-03-20 18:00', 'Asia/Tokyo').isToday();;true +d('2025-03-19 22:00', 'America/Los_Angeles').isYesterday();;true +d(s).isToday();{s: '2025-03-20'};true +d(s).isToday();{s: '2025-03-20'};true +d(s).isToday();{s: '2025-03-20 00:00:00'};true +d(s).isToday();{s: '2025-03-19'};false +d(s).isToday();{s: '2025-03-20T10:15:30Z'};true +d(s).isToday();{s: 'x'};null +d(s).isToday();{};null +d(s).isToday();{s: 1742465730000};true +# getters on rows +d(s).year();{s: '2023-10-15'};2023 +d(s).year();{s: '2023-10-15'};2023 +d(s).year();{s: '1999-12-31 23:59:59'};1999 +d(s).year();{s: '2024-02-29'};2024 +d(s).year();{s: 'bad'};null +d(s).year();{s: null};null +d(s).year();{};null +d(s).year();{s: 0};1970 +d(s).month();{s: '2023-01-31'};1 +d(s).month();{s: '2023-12-01'};12 +d(s).month();{s: '2023-12-01'};12 +d(s).month();{s: '2023-13-01'};null +d(s).day();{s: '2024-02-29'};29 +d(s).day();{s: '2023-10-01'};1 +d(s).day();{s: '2023-10-31 23:59'};31 +d(s).day();{s: ''};null +d(s).weekday();{s: '2023-10-15'};7 +d(s).weekday();{s: '2023-10-16'};1 +d(s).weekday();{s: '2023-10-16'};1 +d(s).weekday();{s: '2024-02-29'};4 +d(s).weekday();{};null +d(s).week();{s: '2021-01-03'};53 +d(s).week();{s: '2021-01-04'};1 +d(s).week();{s: '2024-12-30'};1 +d(s).week();{s: 'x'};null +d(s).dayOfYear();{s: '2024-12-31'};366 +d(s).dayOfYear();{s: '2023-12-31'};365 +d(s).dayOfYear();{s: '2023-12-31'};365 +d(s).dayOfYear();{s: null};null +d(s).quarter();{s: '2023-03-31'};1 +d(s).quarter();{s: '2023-04-01'};2 +d(s).quarter();{s: '2023-09-30'};3 +d(s).quarter();{s: '2023-10-01'};4 +d(s).hour() * 60 + d(s).minute();{s: '2023-10-15 14:30'};870 +d(s).hour() * 60 + d(s).minute();{s: '2023-10-15 00:01'};1 +d(s).hour() * 60 + d(s).minute();{s: 'x'};!error +d(s).second();{s: '2023-10-15 14:30:59'};59 +d(s).second();{s: '2023-10-15T14:30:59.999Z'};59 +d(s).timestamp();{s: '2023-10-15'};1697328000000 +d(s).timestamp();{s: '2023-10-15'};1697328000000 +d(s).timestamp();{s: '1969-12-31 23:59:59'};-1000 +d(s).timestamp();{s: 1697328000000};1697328000000 +d(s).timestamp();{s: 'nope'};null +d(s).isLeapYear();{s: '2024-01-01'};true +d(s).isLeapYear();{s: '1900-01-01'};false +d(s).isLeapYear();{s: '2000-01-01'};true +d(s).isLeapYear();{s: '2023-01-01'};false +d(s).isLeapYear();{s: null};null +d(s).isValid();{s: '2024-02-29'};true +d(s).isValid();{s: '2023-02-29'};false +d(s, 'Europe/Berlin').hour();{s: '2025-03-30 01:30'};1 +d(s, 'Europe/Berlin').hour();{s: '2025-03-30 03:30'};3 +d(s, 'Europe/Berlin').hour();{s: '2025-10-26 02:30'};2 +d(s, 'Europe/Berlin').hour();{s: '2025-10-26 02:30'};2 +d(s, 'Europe/Berlin').hour();{s: 1761438600000};2 +d(s, 'Europe/Berlin').hour();{s: 1761442200000};2 +d(s, 'Europe/Berlin').hour();{s: 'x'};null +# set(unit, value) +d('2023-10-15T10:30:45Z').set('year', 2024);;'2024-10-15T10:30:45Z' +d('2023-10-15T10:30:45Z').set('y', 1999);;'1999-10-15T10:30:45Z' +d('2023-10-15T10:30:45Z').set('month', 1);;'2023-01-15T10:30:45Z' +d('2023-10-15T10:30:45Z').set('M', 12);;'2023-12-15T10:30:45Z' +d('2023-10-15T10:30:45Z').set('day', 1);;'2023-10-01T10:30:45Z' +d('2023-10-15T10:30:45Z').set('d', 31);;'2023-10-31T10:30:45Z' +d('2023-10-15T10:30:45Z').set('hour', 0);;'2023-10-15T00:30:45Z' +d('2023-10-15T10:30:45Z').set('h', 23);;'2023-10-15T23:30:45Z' +d('2023-10-15T10:30:45Z').set('minute', 0);;'2023-10-15T10:00:45Z' +d('2023-10-15T10:30:45Z').set('m', 59);;'2023-10-15T10:59:45Z' +d('2023-10-15T10:30:45Z').set('second', 0);;'2023-10-15T10:30:00Z' +d('2023-10-15T10:30:45Z').set('s', 59);;'2023-10-15T10:30:59Z' +d('2023-10-15T10:30:45.500Z').set('second', 0).timestamp();;1697365800500 +d('2023-10-15').set('year', 0);;'0000-10-15T00:00:00Z' +d('2023-10-15').set('month', 1.9);;'2023-01-15T00:00:00Z';question: a fractional value is truncated rather than rejected +d('2023-10-15').set('year', -1);;!error;question: negative years are rejected with an error while year 0 is accepted +d('2023-10-15').set('day', -1);;!error +d('2023-10-15').set('month', 13);;'Invalid date';question: an out-of-range value gives an invalid date rather than an error or rollover +d('2023-10-15').set('month', 0);;'Invalid date' +d('2023-10-15').set('day', 0);;'Invalid date' +d('2023-10-15').set('day', 32);;'Invalid date' +d('2023-10-15').set('hour', 24);;'Invalid date' +d('2023-10-15').set('minute', 60);;'Invalid date' +d('2023-10-15').set('second', 60);;'Invalid date' +d('2023-09-15').set('day', 31);;'Invalid date';question: setting a day past the end of the month gives an invalid date instead of clamping like add(1, 'M') does +d('2023-01-31').set('month', 2);;'Invalid date';question: moving Jan 31 to February gives an invalid date instead of clamping to Feb 28 +d('2024-02-29').set('year', 2023);;'Invalid date';question: moving Feb 29 to a non-leap year gives an invalid date instead of clamping +d('2024-02-29').set('year', 2028);;'2028-02-29T00:00:00Z' +d('2023-10-15').set('week', 3);;'2023-10-15T00:00:00Z';question: setting the week is silently ignored instead of moving to that week or failing +d('2023-10-15').set('quarter', 1);;'2023-10-15T00:00:00Z';question: setting the quarter is silently ignored instead of moving to that quarter or failing +d('2023-10-15').set('ms', 1);;!error +d('2023-10-15').set('D', 1);;!error +d('2023-10-15').set('day', '1');;!error +d('2023-10-15').set('day', null);;!error +d('foo').set('day', 1);;'Invalid date' +d('2023-10-15', 'Europe/Berlin').set('month', 1);;'2023-01-15T00:00:00+01:00' +d('2023-10-15', 'Asia/Kathmandu').set('hour', 5).timestamp();;1697325300000 +d('2025-10-26 12:00', 'Europe/Berlin').set('hour', 2);;'2025-10-26T02:00:00+02:00';bug: a wall time in the fall-back overlap becomes invalid, while d() resolves the same wall time to the earlier offset +d('2025-03-30 12:00', 'Europe/Berlin').set('hour', 2);;'Invalid date';question: a wall time inside the spring-forward gap is invalid, consistent with d() +d(s).set('day', 31);{s: '2023-01-15'};'2023-01-31T00:00:00Z' +d(s).set('day', 31);{s: '2023-01-15'};'2023-01-31T00:00:00Z' +d(s).set('day', 31);{s: '2023-04-15'};'Invalid date' +d(s).set('day', 31);{s: 'x'};'Invalid date' +d(s).set('day', 31);{};'Invalid date' +d(s).set('month', 2);{s: '2024-01-29'};'2024-02-29T00:00:00Z' +d(s).set('month', 2);{s: '2023-01-29'};'Invalid date' +d(s).set('month', 2);{s: '2023-01-28 12:00'};'2023-02-28T12:00:00Z' +d(s).set(u, v);{s: '2023-10-15', u: 'year', v: 2020};'2020-10-15T00:00:00Z' +d(s).set(u, v);{s: '2023-10-15', u: 'hour', v: 7};'2023-10-15T07:00:00Z' +d(s).set(u, v);{s: '2023-10-15', u: 'nope', v: 7};!error +d(s).set(u, v);{s: '2023-10-15', u: 'day', v: null};!error diff --git a/core/expression/tests/spec/standard/10-01-collections.csv b/core/expression/tests/spec/standard/10-01-collections.csv new file mode 100644 index 00000000..3ce0fd1a --- /dev/null +++ b/core/expression/tests/spec/standard/10-01-collections.csv @@ -0,0 +1,398 @@ +expression (string);input (json 5);output (json 5);note +# len: argument 1 is string | array +# len (literal) +len(null);;!error +len(true);;!error +len(false);;!error +len(0);;!error +len(-1);;!error +len(1.5);;!error +len(79228162514264337593543950335);;!error +len('');;0 +len('abc');;3 +len('12.5');;4 +len('żółw');;4;bug: len counts UTF-8 bytes instead of characters +len([]);;0 +len([1, 2]);;2 +len(['a']);;1 +len([[1]]);;1 +len({});;!error +len({a: 1});;!error +len(d('2024-01-01'));;20 +len([1..3]);;!error +# len (input) +len(x);{x: null};!error +len(x);{x: true};!error +len(x);{x: false};!error +len(x);{x: 0};!error +len(x);{x: -1};!error +len(x);{x: 1.5};!error +len(x);{x: 79228162514264337593543950335};!error +len(x);{x: ''};0 +len(x);{x: 'abc'};3 +len(x);{x: '12.5'};4 +len(x);{x: 'żółw'};4;bug: len counts UTF-8 bytes instead of characters +len(x);{x: []};0 +len(x);{x: [1, 2]};2 +len(x);{x: ['a']};1 +len(x);{x: [[1]]};1 +len(x);{x: {}};!error +len(x);{x: {a: 1}};!error +len(x);{};!error +# contains: argument 1 is string | array (needle fixed to a string) +# contains arg 1 (literal) +contains(null, 'a');;!error +contains(true, 'a');;!error +contains(false, 'a');;!error +contains(0, 'a');;!error +contains(-1, 'a');;!error +contains(1.5, 'a');;!error +contains(79228162514264337593543950335, 'a');;!error +contains('', 'a');;false +contains('abc', 'a');;true +contains('12.5', 'a');;false +contains('żółw', 'a');;false +contains([], 'a');;false +contains([1, 2], 'a');;false +contains(['a'], 'a');;true +contains([[1]], 'a');;false +contains({}, 'a');;!error +contains({a: 1}, 'a');;!error +contains(d('2024-01-01'), 'a');;false +contains([1..3], 'a');;!error +# contains arg 1 (input) +contains(x, 'a');{x: null};!error +contains(x, 'a');{x: true};!error +contains(x, 'a');{x: false};!error +contains(x, 'a');{x: 0};!error +contains(x, 'a');{x: -1};!error +contains(x, 'a');{x: 1.5};!error +contains(x, 'a');{x: 79228162514264337593543950335};!error +contains(x, 'a');{x: ''};false +contains(x, 'a');{x: 'abc'};true +contains(x, 'a');{x: '12.5'};false +contains(x, 'a');{x: 'żółw'};false +contains(x, 'a');{x: []};false +contains(x, 'a');{x: [1, 2]};false +contains(x, 'a');{x: ['a']};true +contains(x, 'a');{x: [[1]]};false +contains(x, 'a');{x: {}};!error +contains(x, 'a');{x: {a: 1}};!error +contains(x, 'a');{};!error +# contains: argument 2 against an array haystack is any value +# contains arg 2 array (literal) +contains([0, 'abc', true, null], null);;true +contains([0, 'abc', true, null], true);;true +contains([0, 'abc', true, null], false);;false +contains([0, 'abc', true, null], 0);;true +contains([0, 'abc', true, null], -1);;false +contains([0, 'abc', true, null], 1.5);;false +contains([0, 'abc', true, null], 79228162514264337593543950335);;false +contains([0, 'abc', true, null], '');;false +contains([0, 'abc', true, null], 'abc');;true +contains([0, 'abc', true, null], '12.5');;false +contains([0, 'abc', true, null], 'żółw');;false +contains([0, 'abc', true, null], []);;false +contains([0, 'abc', true, null], [1, 2]);;false +contains([0, 'abc', true, null], ['a']);;false +contains([0, 'abc', true, null], [[1]]);;false +contains([0, 'abc', true, null], {});;false +contains([0, 'abc', true, null], {a: 1});;false +contains([0, 'abc', true, null], d('2024-01-01'));;false +contains([0, 'abc', true, null], [1..3]);;false +# contains arg 2 array (input) +contains([0, 'abc', true, null], x);{x: null};true +contains([0, 'abc', true, null], x);{x: true};true +contains([0, 'abc', true, null], x);{x: false};false +contains([0, 'abc', true, null], x);{x: 0};true +contains([0, 'abc', true, null], x);{x: -1};false +contains([0, 'abc', true, null], x);{x: 1.5};false +contains([0, 'abc', true, null], x);{x: 79228162514264337593543950335};false +contains([0, 'abc', true, null], x);{x: ''};false +contains([0, 'abc', true, null], x);{x: 'abc'};true +contains([0, 'abc', true, null], x);{x: '12.5'};false +contains([0, 'abc', true, null], x);{x: 'żółw'};false +contains([0, 'abc', true, null], x);{x: []};false +contains([0, 'abc', true, null], x);{x: [1, 2]};false +contains([0, 'abc', true, null], x);{x: ['a']};false +contains([0, 'abc', true, null], x);{x: [[1]]};false +contains([0, 'abc', true, null], x);{x: {}};false +contains([0, 'abc', true, null], x);{x: {a: 1}};false +contains([0, 'abc', true, null], x);{};true +# contains: argument 2 against a string haystack must be a string +# contains arg 2 string (literal) +contains('abc', null);;!error +contains('abc', true);;!error +contains('abc', false);;!error +contains('abc', 0);;!error +contains('abc', -1);;!error +contains('abc', 1.5);;!error +contains('abc', 79228162514264337593543950335);;!error +contains('abc', '');;true +contains('abc', 'abc');;true +contains('abc', '12.5');;false +contains('abc', 'żółw');;false +contains('abc', []);;!error +contains('abc', [1, 2]);;!error +contains('abc', ['a']);;!error +contains('abc', [[1]]);;!error +contains('abc', {});;!error +contains('abc', {a: 1});;!error +contains('abc', d('2024-01-01'));;false +contains('abc', [1..3]);;!error +# contains arg 2 string (input) +contains('abc', x);{x: null};!error +contains('abc', x);{x: true};!error +contains('abc', x);{x: false};!error +contains('abc', x);{x: 0};!error +contains('abc', x);{x: -1};!error +contains('abc', x);{x: 1.5};!error +contains('abc', x);{x: 79228162514264337593543950335};!error +contains('abc', x);{x: ''};true +contains('abc', x);{x: 'abc'};true +contains('abc', x);{x: '12.5'};false +contains('abc', x);{x: 'żółw'};false +contains('abc', x);{x: []};!error +contains('abc', x);{x: [1, 2]};!error +contains('abc', x);{x: ['a']};!error +contains('abc', x);{x: [[1]]};!error +contains('abc', x);{x: {}};!error +contains('abc', x);{x: {a: 1}};!error +contains('abc', x);{};!error +# contains: haystack and needle both from input +contains(x, y);{x: 'abc', y: 'b'};true +contains(x, y);{x: ['b'], y: 'b'};true +contains(x, y);{x: [1, 2], y: 2};true +contains(x, y);{x: 'abc', y: 2};!error +contains(x, y);{x: 2, y: 2};!error +contains(x, y);{x: null, y: null};!error +contains(x, y);{x: [null]};true +contains(x, y);{x: [], y: []};false +contains(x, y);{y: 'a'};!error +# flatten: argument 1 is array +# flatten (literal) +flatten(null);;!error +flatten(true);;!error +flatten(false);;!error +flatten(0);;!error +flatten(-1);;!error +flatten(1.5);;!error +flatten(79228162514264337593543950335);;!error +flatten('');;!error +flatten('abc');;!error +flatten('12.5');;!error +flatten('żółw');;!error +flatten([]);;[] +flatten([1, 2]);;[1, 2] +flatten(['a']);;['a'] +flatten([[1]]);;[1] +flatten({});;!error +flatten({a: 1});;!error +flatten(d('2024-01-01'));;!error +flatten([1..3]);;!error +# flatten (input) +flatten(x);{x: null};!error +flatten(x);{x: true};!error +flatten(x);{x: false};!error +flatten(x);{x: 0};!error +flatten(x);{x: -1};!error +flatten(x);{x: 1.5};!error +flatten(x);{x: 79228162514264337593543950335};!error +flatten(x);{x: ''};!error +flatten(x);{x: 'abc'};!error +flatten(x);{x: '12.5'};!error +flatten(x);{x: 'żółw'};!error +flatten(x);{x: []};[] +flatten(x);{x: [1, 2]};[1, 2] +flatten(x);{x: ['a']};['a'] +flatten(x);{x: [[1]]};[1] +flatten(x);{x: {}};!error +flatten(x);{x: {a: 1}};!error +flatten(x);{};!error +# flatten: element types +flatten(x);{x: [null, [null]]};[null, null] +flatten(x);{x: [{a: 1}, [{}]]};[{a: 1}, {}] +flatten(x);{x: [[[1]], 'a']};[[1], 'a'] +flatten(x);{x: [[], [], []]};[] +flatten(x);{x: [1, [2, [3]]]};[1, 2, [3]] +# merge: argument 1 is array of arrays | array of objects +# merge (literal) +merge(null);;!error +merge(true);;!error +merge(false);;!error +merge(0);;!error +merge(-1);;!error +merge(1.5);;!error +merge(79228162514264337593543950335);;!error +merge('');;!error +merge('abc');;!error +merge('12.5');;!error +merge('żółw');;!error +merge([]);;{};question: merge of an empty list gives an empty object although the array overload returns an array +merge([1, 2]);;!error +merge(['a']);;!error +merge([[1]]);;[1] +merge({});;!error +merge({a: 1});;!error +merge(d('2024-01-01'));;!error +merge([1..3]);;!error +# merge (input) +merge(x);{x: null};!error +merge(x);{x: true};!error +merge(x);{x: false};!error +merge(x);{x: 0};!error +merge(x);{x: -1};!error +merge(x);{x: 1.5};!error +merge(x);{x: 79228162514264337593543950335};!error +merge(x);{x: ''};!error +merge(x);{x: 'abc'};!error +merge(x);{x: '12.5'};!error +merge(x);{x: 'żółw'};!error +merge(x);{x: []};{};question: merge of an empty list gives an empty object although the array overload returns an array +merge(x);{x: [1, 2]};!error +merge(x);{x: ['a']};!error +merge(x);{x: [[1]]};[1] +merge(x);{x: {}};!error +merge(x);{x: {a: 1}};!error +merge(x);{};!error +# merge: element types +merge(x);{x: [{a: 1}, {b: 2}]};{a: 1, b: 2} +merge(x);{x: [[1], [2, 3]]};[1, 2, 3] +merge(x);{x: [null, {a: 1}]};{a: 1} +merge(x);{x: [null, [1]]};[1] +merge(x);{x: [null]};{} +merge(x);{x: [{a: 1}, [1]]};!error +merge(x);{x: [[1], {a: 1}]};!error +merge(x);{x: [{a: 1}, 'x']};!error +merge(x);{x: [1, [1]]};!error +merge(x);{x: [true]};!error +merge(x);{x: [[1], null, [2]]};[1, 2] +# mergeDeep: argument 1 is array of objects +# mergeDeep (literal) +mergeDeep(null);;!error +mergeDeep(true);;!error +mergeDeep(false);;!error +mergeDeep(0);;!error +mergeDeep(-1);;!error +mergeDeep(1.5);;!error +mergeDeep(79228162514264337593543950335);;!error +mergeDeep('');;!error +mergeDeep('abc');;!error +mergeDeep('12.5');;!error +mergeDeep('żółw');;!error +mergeDeep([]);;{} +mergeDeep([1, 2]);;!error +mergeDeep(['a']);;!error +mergeDeep([[1]]);;!error +mergeDeep({});;!error +mergeDeep({a: 1});;!error +mergeDeep(d('2024-01-01'));;!error +mergeDeep([1..3]);;!error +# mergeDeep (input) +mergeDeep(x);{x: null};!error +mergeDeep(x);{x: true};!error +mergeDeep(x);{x: false};!error +mergeDeep(x);{x: 0};!error +mergeDeep(x);{x: -1};!error +mergeDeep(x);{x: 1.5};!error +mergeDeep(x);{x: 79228162514264337593543950335};!error +mergeDeep(x);{x: ''};!error +mergeDeep(x);{x: 'abc'};!error +mergeDeep(x);{x: '12.5'};!error +mergeDeep(x);{x: 'żółw'};!error +mergeDeep(x);{x: []};{} +mergeDeep(x);{x: [1, 2]};!error +mergeDeep(x);{x: ['a']};!error +mergeDeep(x);{x: [[1]]};!error +mergeDeep(x);{x: {}};!error +mergeDeep(x);{x: {a: 1}};!error +mergeDeep(x);{};!error +# mergeDeep: element types +mergeDeep(x);{x: [{a: {b: 1}}, {a: {c: 2}}]};{a: {b: 1, c: 2}} +mergeDeep(x);{x: [null, {a: 1}]};{a: 1} +mergeDeep(x);{x: [null]};{} +mergeDeep(x);{x: [[1]]};!error +mergeDeep(x);{x: [{a: 1}, 1]};!error +mergeDeep(x);{x: ['a']};!error +mergeDeep(x);{x: [{a: [1]}, {a: [2]}]};{a: [1, 2]} +mergeDeep(x);{x: [{a: 1}, {a: null}]};{a: null} +# keys: argument 1 is object | array +# keys (literal) +keys(null);;!error +keys(true);;!error +keys(false);;!error +keys(0);;!error +keys(-1);;!error +keys(1.5);;!error +keys(79228162514264337593543950335);;!error +keys('');;!error +keys('abc');;!error +keys('12.5');;!error +keys('żółw');;!error +keys([]);;[] +keys([1, 2]);;[0, 1] +keys(['a']);;[0] +keys([[1]]);;[0] +keys({});;[] +keys({a: 1});;['a'] +keys(d('2024-01-01'));;!error +keys([1..3]);;!error +# keys (input) +keys(x);{x: null};!error +keys(x);{x: true};!error +keys(x);{x: false};!error +keys(x);{x: 0};!error +keys(x);{x: -1};!error +keys(x);{x: 1.5};!error +keys(x);{x: 79228162514264337593543950335};!error +keys(x);{x: ''};!error +keys(x);{x: 'abc'};!error +keys(x);{x: '12.5'};!error +keys(x);{x: 'żółw'};!error +keys(x);{x: []};[] +keys(x);{x: [1, 2]};[0, 1] +keys(x);{x: ['a']};[0] +keys(x);{x: [[1]]};[0] +keys(x);{x: {}};[] +keys(x);{x: {a: 1}};['a'] +keys(x);{};!error +# values: argument 1 is object +# values (literal) +values(null);;!error +values(true);;!error +values(false);;!error +values(0);;!error +values(-1);;!error +values(1.5);;!error +values(79228162514264337593543950335);;!error +values('');;!error +values('abc');;!error +values('12.5');;!error +values('żółw');;!error +values([]);;!error;question: keys() accepts arrays but values() rejects them +values([1, 2]);;!error;question: keys() accepts arrays but values() rejects them +values(['a']);;!error;question: keys() accepts arrays but values() rejects them +values([[1]]);;!error;question: keys() accepts arrays but values() rejects them +values({});;[] +values({a: 1});;[1] +values(d('2024-01-01'));;!error +values([1..3]);;!error +# values (input) +values(x);{x: null};!error +values(x);{x: true};!error +values(x);{x: false};!error +values(x);{x: 0};!error +values(x);{x: -1};!error +values(x);{x: 1.5};!error +values(x);{x: 79228162514264337593543950335};!error +values(x);{x: ''};!error +values(x);{x: 'abc'};!error +values(x);{x: '12.5'};!error +values(x);{x: 'żółw'};!error +values(x);{x: []};!error;question: keys() accepts arrays but values() rejects them +values(x);{x: [1, 2]};!error;question: keys() accepts arrays but values() rejects them +values(x);{x: ['a']};!error;question: keys() accepts arrays but values() rejects them +values(x);{x: [[1]]};!error;question: keys() accepts arrays but values() rejects them +values(x);{x: {}};[] +values(x);{x: {a: 1}};[1] +values(x);{};!error diff --git a/core/expression/tests/spec/standard/10-02-strings.csv b/core/expression/tests/spec/standard/10-02-strings.csv new file mode 100644 index 00000000..10a00a27 --- /dev/null +++ b/core/expression/tests/spec/standard/10-02-strings.csv @@ -0,0 +1,656 @@ +expression (string);input (json 5);output (json 5);note +# upper: argument 1 is string +# upper (literal) +upper(null);;!error +upper(true);;!error +upper(false);;!error +upper(0);;!error +upper(-1);;!error +upper(1.5);;!error +upper(79228162514264337593543950335);;!error +upper('');;'' +upper('abc');;'ABC' +upper('12.5');;'12.5' +upper('żółw');;'ŻÓŁW' +upper([]);;!error +upper([1, 2]);;!error +upper(['a']);;!error +upper([[1]]);;!error +upper({});;!error +upper({a: 1});;!error +upper(d('2024-01-01'));;'2024-01-01T00:00:00Z' +upper([1..3]);;!error +# upper (input) +upper(x);{x: null};!error +upper(x);{x: true};!error +upper(x);{x: false};!error +upper(x);{x: 0};!error +upper(x);{x: -1};!error +upper(x);{x: 1.5};!error +upper(x);{x: 79228162514264337593543950335};!error +upper(x);{x: ''};'' +upper(x);{x: 'abc'};'ABC' +upper(x);{x: '12.5'};'12.5' +upper(x);{x: 'żółw'};'ŻÓŁW' +upper(x);{x: []};!error +upper(x);{x: [1, 2]};!error +upper(x);{x: ['a']};!error +upper(x);{x: [[1]]};!error +upper(x);{x: {}};!error +upper(x);{x: {a: 1}};!error +upper(x);{};!error +# lower: argument 1 is string +# lower (literal) +lower(null);;!error +lower(true);;!error +lower(false);;!error +lower(0);;!error +lower(-1);;!error +lower(1.5);;!error +lower(79228162514264337593543950335);;!error +lower('');;'' +lower('abc');;'abc' +lower('12.5');;'12.5' +lower('żółw');;'żółw' +lower([]);;!error +lower([1, 2]);;!error +lower(['a']);;!error +lower([[1]]);;!error +lower({});;!error +lower({a: 1});;!error +lower(d('2024-01-01'));;'2024-01-01t00:00:00z' +lower([1..3]);;!error +# lower (input) +lower(x);{x: null};!error +lower(x);{x: true};!error +lower(x);{x: false};!error +lower(x);{x: 0};!error +lower(x);{x: -1};!error +lower(x);{x: 1.5};!error +lower(x);{x: 79228162514264337593543950335};!error +lower(x);{x: ''};'' +lower(x);{x: 'abc'};'abc' +lower(x);{x: '12.5'};'12.5' +lower(x);{x: 'żółw'};'żółw' +lower(x);{x: []};!error +lower(x);{x: [1, 2]};!error +lower(x);{x: ['a']};!error +lower(x);{x: [[1]]};!error +lower(x);{x: {}};!error +lower(x);{x: {a: 1}};!error +lower(x);{};!error +# trim: argument 1 is string +# trim (literal) +trim(null);;!error +trim(true);;!error +trim(false);;!error +trim(0);;!error +trim(-1);;!error +trim(1.5);;!error +trim(79228162514264337593543950335);;!error +trim('');;'' +trim('abc');;'abc' +trim('12.5');;'12.5' +trim('żółw');;'żółw' +trim([]);;!error +trim([1, 2]);;!error +trim(['a']);;!error +trim([[1]]);;!error +trim({});;!error +trim({a: 1});;!error +trim(d('2024-01-01'));;'2024-01-01T00:00:00Z' +trim([1..3]);;!error +# trim (input) +trim(x);{x: null};!error +trim(x);{x: true};!error +trim(x);{x: false};!error +trim(x);{x: 0};!error +trim(x);{x: -1};!error +trim(x);{x: 1.5};!error +trim(x);{x: 79228162514264337593543950335};!error +trim(x);{x: ''};'' +trim(x);{x: 'abc'};'abc' +trim(x);{x: '12.5'};'12.5' +trim(x);{x: 'żółw'};'żółw' +trim(x);{x: []};!error +trim(x);{x: [1, 2]};!error +trim(x);{x: ['a']};!error +trim(x);{x: [[1]]};!error +trim(x);{x: {}};!error +trim(x);{x: {a: 1}};!error +trim(x);{};!error +# startsWith: argument 1 +# startsWith arg 1 (literal) +startsWith(null, 'a');;!error +startsWith(true, 'a');;!error +startsWith(false, 'a');;!error +startsWith(0, 'a');;!error +startsWith(-1, 'a');;!error +startsWith(1.5, 'a');;!error +startsWith(79228162514264337593543950335, 'a');;!error +startsWith('', 'a');;false +startsWith('abc', 'a');;true +startsWith('12.5', 'a');;false +startsWith('żółw', 'a');;false +startsWith([], 'a');;!error +startsWith([1, 2], 'a');;!error +startsWith(['a'], 'a');;!error +startsWith([[1]], 'a');;!error +startsWith({}, 'a');;!error +startsWith({a: 1}, 'a');;!error +startsWith(d('2024-01-01'), 'a');;false +startsWith([1..3], 'a');;!error +# startsWith arg 1 (input) +startsWith(x, 'a');{x: null};!error +startsWith(x, 'a');{x: true};!error +startsWith(x, 'a');{x: false};!error +startsWith(x, 'a');{x: 0};!error +startsWith(x, 'a');{x: -1};!error +startsWith(x, 'a');{x: 1.5};!error +startsWith(x, 'a');{x: 79228162514264337593543950335};!error +startsWith(x, 'a');{x: ''};false +startsWith(x, 'a');{x: 'abc'};true +startsWith(x, 'a');{x: '12.5'};false +startsWith(x, 'a');{x: 'żółw'};false +startsWith(x, 'a');{x: []};!error +startsWith(x, 'a');{x: [1, 2]};!error +startsWith(x, 'a');{x: ['a']};!error +startsWith(x, 'a');{x: [[1]]};!error +startsWith(x, 'a');{x: {}};!error +startsWith(x, 'a');{x: {a: 1}};!error +startsWith(x, 'a');{};!error +# startsWith: argument 2 +# startsWith arg 2 (literal) +startsWith('abc', null);;!error +startsWith('abc', true);;!error +startsWith('abc', false);;!error +startsWith('abc', 0);;!error +startsWith('abc', -1);;!error +startsWith('abc', 1.5);;!error +startsWith('abc', 79228162514264337593543950335);;!error +startsWith('abc', '');;true +startsWith('abc', 'abc');;true +startsWith('abc', '12.5');;false +startsWith('abc', 'żółw');;false +startsWith('abc', []);;!error +startsWith('abc', [1, 2]);;!error +startsWith('abc', ['a']);;!error +startsWith('abc', [[1]]);;!error +startsWith('abc', {});;!error +startsWith('abc', {a: 1});;!error +startsWith('abc', d('2024-01-01'));;false +startsWith('abc', [1..3]);;!error +# startsWith arg 2 (input) +startsWith('abc', x);{x: null};!error +startsWith('abc', x);{x: true};!error +startsWith('abc', x);{x: false};!error +startsWith('abc', x);{x: 0};!error +startsWith('abc', x);{x: -1};!error +startsWith('abc', x);{x: 1.5};!error +startsWith('abc', x);{x: 79228162514264337593543950335};!error +startsWith('abc', x);{x: ''};true +startsWith('abc', x);{x: 'abc'};true +startsWith('abc', x);{x: '12.5'};false +startsWith('abc', x);{x: 'żółw'};false +startsWith('abc', x);{x: []};!error +startsWith('abc', x);{x: [1, 2]};!error +startsWith('abc', x);{x: ['a']};!error +startsWith('abc', x);{x: [[1]]};!error +startsWith('abc', x);{x: {}};!error +startsWith('abc', x);{x: {a: 1}};!error +startsWith('abc', x);{};!error +# startsWith: both arguments from input +startsWith(x, y);{x: 'abc', y: 'ab'};true +startsWith(x, y);{x: 'abc', y: 'b'};false +startsWith(x, y);{x: 1, y: '1'};!error +startsWith(x, y);{x: '1', y: 1};!error +startsWith(x, y);{x: null, y: null};!error +startsWith(x, y);{};!error +startsWith(x, y);{x: 'żółw', y: 'ż'};true +# endsWith: argument 1 +# endsWith arg 1 (literal) +endsWith(null, 'c');;!error +endsWith(true, 'c');;!error +endsWith(false, 'c');;!error +endsWith(0, 'c');;!error +endsWith(-1, 'c');;!error +endsWith(1.5, 'c');;!error +endsWith(79228162514264337593543950335, 'c');;!error +endsWith('', 'c');;false +endsWith('abc', 'c');;true +endsWith('12.5', 'c');;false +endsWith('żółw', 'c');;false +endsWith([], 'c');;!error +endsWith([1, 2], 'c');;!error +endsWith(['a'], 'c');;!error +endsWith([[1]], 'c');;!error +endsWith({}, 'c');;!error +endsWith({a: 1}, 'c');;!error +endsWith(d('2024-01-01'), 'c');;false +endsWith([1..3], 'c');;!error +# endsWith arg 1 (input) +endsWith(x, 'c');{x: null};!error +endsWith(x, 'c');{x: true};!error +endsWith(x, 'c');{x: false};!error +endsWith(x, 'c');{x: 0};!error +endsWith(x, 'c');{x: -1};!error +endsWith(x, 'c');{x: 1.5};!error +endsWith(x, 'c');{x: 79228162514264337593543950335};!error +endsWith(x, 'c');{x: ''};false +endsWith(x, 'c');{x: 'abc'};true +endsWith(x, 'c');{x: '12.5'};false +endsWith(x, 'c');{x: 'żółw'};false +endsWith(x, 'c');{x: []};!error +endsWith(x, 'c');{x: [1, 2]};!error +endsWith(x, 'c');{x: ['a']};!error +endsWith(x, 'c');{x: [[1]]};!error +endsWith(x, 'c');{x: {}};!error +endsWith(x, 'c');{x: {a: 1}};!error +endsWith(x, 'c');{};!error +# endsWith: argument 2 +# endsWith arg 2 (literal) +endsWith('abc', null);;!error +endsWith('abc', true);;!error +endsWith('abc', false);;!error +endsWith('abc', 0);;!error +endsWith('abc', -1);;!error +endsWith('abc', 1.5);;!error +endsWith('abc', 79228162514264337593543950335);;!error +endsWith('abc', '');;true +endsWith('abc', 'abc');;true +endsWith('abc', '12.5');;false +endsWith('abc', 'żółw');;false +endsWith('abc', []);;!error +endsWith('abc', [1, 2]);;!error +endsWith('abc', ['a']);;!error +endsWith('abc', [[1]]);;!error +endsWith('abc', {});;!error +endsWith('abc', {a: 1});;!error +endsWith('abc', d('2024-01-01'));;false +endsWith('abc', [1..3]);;!error +# endsWith arg 2 (input) +endsWith('abc', x);{x: null};!error +endsWith('abc', x);{x: true};!error +endsWith('abc', x);{x: false};!error +endsWith('abc', x);{x: 0};!error +endsWith('abc', x);{x: -1};!error +endsWith('abc', x);{x: 1.5};!error +endsWith('abc', x);{x: 79228162514264337593543950335};!error +endsWith('abc', x);{x: ''};true +endsWith('abc', x);{x: 'abc'};true +endsWith('abc', x);{x: '12.5'};false +endsWith('abc', x);{x: 'żółw'};false +endsWith('abc', x);{x: []};!error +endsWith('abc', x);{x: [1, 2]};!error +endsWith('abc', x);{x: ['a']};!error +endsWith('abc', x);{x: [[1]]};!error +endsWith('abc', x);{x: {}};!error +endsWith('abc', x);{x: {a: 1}};!error +endsWith('abc', x);{};!error +# endsWith: both arguments from input +endsWith(x, y);{x: 'abc', y: 'bc'};true +endsWith(x, y);{x: 'abc', y: 'b'};false +endsWith(x, y);{x: 1, y: '1'};!error +endsWith(x, y);{x: '1', y: 1};!error +endsWith(x, y);{x: null, y: null};!error +endsWith(x, y);{};!error +endsWith(x, y);{x: 'żółw', y: 'w'};true +# matches: argument 1 +# matches arg 1 (literal) +matches(null, '^a');;!error +matches(true, '^a');;!error +matches(false, '^a');;!error +matches(0, '^a');;!error +matches(-1, '^a');;!error +matches(1.5, '^a');;!error +matches(79228162514264337593543950335, '^a');;!error +matches('', '^a');;false +matches('abc', '^a');;true +matches('12.5', '^a');;false +matches('żółw', '^a');;false +matches([], '^a');;!error +matches([1, 2], '^a');;!error +matches(['a'], '^a');;!error +matches([[1]], '^a');;!error +matches({}, '^a');;!error +matches({a: 1}, '^a');;!error +matches(d('2024-01-01'), '^a');;false +matches([1..3], '^a');;!error +# matches arg 1 (input) +matches(x, '^a');{x: null};!error +matches(x, '^a');{x: true};!error +matches(x, '^a');{x: false};!error +matches(x, '^a');{x: 0};!error +matches(x, '^a');{x: -1};!error +matches(x, '^a');{x: 1.5};!error +matches(x, '^a');{x: 79228162514264337593543950335};!error +matches(x, '^a');{x: ''};false +matches(x, '^a');{x: 'abc'};true +matches(x, '^a');{x: '12.5'};false +matches(x, '^a');{x: 'żółw'};false +matches(x, '^a');{x: []};!error +matches(x, '^a');{x: [1, 2]};!error +matches(x, '^a');{x: ['a']};!error +matches(x, '^a');{x: [[1]]};!error +matches(x, '^a');{x: {}};!error +matches(x, '^a');{x: {a: 1}};!error +matches(x, '^a');{};!error +# matches: argument 2 +# matches arg 2 (literal) +matches('abc', null);;!error +matches('abc', true);;!error +matches('abc', false);;!error +matches('abc', 0);;!error +matches('abc', -1);;!error +matches('abc', 1.5);;!error +matches('abc', 79228162514264337593543950335);;!error +matches('abc', '');;true +matches('abc', 'abc');;true +matches('abc', '12.5');;false +matches('abc', 'żółw');;false +matches('abc', []);;!error +matches('abc', [1, 2]);;!error +matches('abc', ['a']);;!error +matches('abc', [[1]]);;!error +matches('abc', {});;!error +matches('abc', {a: 1});;!error +matches('abc', d('2024-01-01'));;false +matches('abc', [1..3]);;!error +# matches arg 2 (input) +matches('abc', x);{x: null};!error +matches('abc', x);{x: true};!error +matches('abc', x);{x: false};!error +matches('abc', x);{x: 0};!error +matches('abc', x);{x: -1};!error +matches('abc', x);{x: 1.5};!error +matches('abc', x);{x: 79228162514264337593543950335};!error +matches('abc', x);{x: ''};true +matches('abc', x);{x: 'abc'};true +matches('abc', x);{x: '12.5'};false +matches('abc', x);{x: 'żółw'};false +matches('abc', x);{x: []};!error +matches('abc', x);{x: [1, 2]};!error +matches('abc', x);{x: ['a']};!error +matches('abc', x);{x: [[1]]};!error +matches('abc', x);{x: {}};!error +matches('abc', x);{x: {a: 1}};!error +matches('abc', x);{};!error +# matches: both arguments from input +matches(x, y);{x: 'abc', y: 'b'};true +matches(x, y);{x: 'abc', y: '^b'};false +matches(x, y);{x: 1, y: '1'};!error +matches(x, y);{x: '1', y: 1};!error +matches(x, y);{x: null, y: null};!error +matches(x, y);{};!error +matches(x, y);{x: 'abc', y: '('};!error +# extract: argument 1 +# extract arg 1 (literal) +extract(null, '(b)');;!error +extract(true, '(b)');;!error +extract(false, '(b)');;!error +extract(0, '(b)');;!error +extract(-1, '(b)');;!error +extract(1.5, '(b)');;!error +extract(79228162514264337593543950335, '(b)');;!error +extract('', '(b)');;[] +extract('abc', '(b)');;['b', 'b'] +extract('12.5', '(b)');;[] +extract('żółw', '(b)');;[] +extract([], '(b)');;!error +extract([1, 2], '(b)');;!error +extract(['a'], '(b)');;!error +extract([[1]], '(b)');;!error +extract({}, '(b)');;!error +extract({a: 1}, '(b)');;!error +extract(d('2024-01-01'), '(b)');;[] +extract([1..3], '(b)');;!error +# extract arg 1 (input) +extract(x, '(b)');{x: null};!error +extract(x, '(b)');{x: true};!error +extract(x, '(b)');{x: false};!error +extract(x, '(b)');{x: 0};!error +extract(x, '(b)');{x: -1};!error +extract(x, '(b)');{x: 1.5};!error +extract(x, '(b)');{x: 79228162514264337593543950335};!error +extract(x, '(b)');{x: ''};[] +extract(x, '(b)');{x: 'abc'};['b', 'b'] +extract(x, '(b)');{x: '12.5'};[] +extract(x, '(b)');{x: 'żółw'};[] +extract(x, '(b)');{x: []};!error +extract(x, '(b)');{x: [1, 2]};!error +extract(x, '(b)');{x: ['a']};!error +extract(x, '(b)');{x: [[1]]};!error +extract(x, '(b)');{x: {}};!error +extract(x, '(b)');{x: {a: 1}};!error +extract(x, '(b)');{};!error +# extract: argument 2 +# extract arg 2 (literal) +extract('abc', null);;!error +extract('abc', true);;!error +extract('abc', false);;!error +extract('abc', 0);;!error +extract('abc', -1);;!error +extract('abc', 1.5);;!error +extract('abc', 79228162514264337593543950335);;!error +extract('abc', '');;[''] +extract('abc', 'abc');;['abc'] +extract('abc', '12.5');;[] +extract('abc', 'żółw');;[] +extract('abc', []);;!error +extract('abc', [1, 2]);;!error +extract('abc', ['a']);;!error +extract('abc', [[1]]);;!error +extract('abc', {});;!error +extract('abc', {a: 1});;!error +extract('abc', d('2024-01-01'));;[] +extract('abc', [1..3]);;!error +# extract arg 2 (input) +extract('abc', x);{x: null};!error +extract('abc', x);{x: true};!error +extract('abc', x);{x: false};!error +extract('abc', x);{x: 0};!error +extract('abc', x);{x: -1};!error +extract('abc', x);{x: 1.5};!error +extract('abc', x);{x: 79228162514264337593543950335};!error +extract('abc', x);{x: ''};[''] +extract('abc', x);{x: 'abc'};['abc'] +extract('abc', x);{x: '12.5'};[] +extract('abc', x);{x: 'żółw'};[] +extract('abc', x);{x: []};!error +extract('abc', x);{x: [1, 2]};!error +extract('abc', x);{x: ['a']};!error +extract('abc', x);{x: [[1]]};!error +extract('abc', x);{x: {}};!error +extract('abc', x);{x: {a: 1}};!error +extract('abc', x);{};!error +# extract: both arguments from input +extract(x, y);{x: 'abc', y: 'b'};['b'] +extract(x, y);{x: 'abc', y: 'z'};[] +extract(x, y);{x: 1, y: '1'};!error +extract(x, y);{x: '1', y: 1};!error +extract(x, y);{x: null, y: null};!error +extract(x, y);{};!error +extract(x, y);{x: 'abc', y: '['};!error +# split: argument 1 +# split arg 1 (literal) +split(null, ',');;!error +split(true, ',');;!error +split(false, ',');;!error +split(0, ',');;!error +split(-1, ',');;!error +split(1.5, ',');;!error +split(79228162514264337593543950335, ',');;!error +split('', ',');;[''] +split('abc', ',');;['abc'] +split('12.5', ',');;['12.5'] +split('żółw', ',');;['żółw'] +split([], ',');;!error +split([1, 2], ',');;!error +split(['a'], ',');;!error +split([[1]], ',');;!error +split({}, ',');;!error +split({a: 1}, ',');;!error +split(d('2024-01-01'), ',');;['2024-01-01T00:00:00Z'] +split([1..3], ',');;!error +# split arg 1 (input) +split(x, ',');{x: null};!error +split(x, ',');{x: true};!error +split(x, ',');{x: false};!error +split(x, ',');{x: 0};!error +split(x, ',');{x: -1};!error +split(x, ',');{x: 1.5};!error +split(x, ',');{x: 79228162514264337593543950335};!error +split(x, ',');{x: ''};[''] +split(x, ',');{x: 'abc'};['abc'] +split(x, ',');{x: '12.5'};['12.5'] +split(x, ',');{x: 'żółw'};['żółw'] +split(x, ',');{x: []};!error +split(x, ',');{x: [1, 2]};!error +split(x, ',');{x: ['a']};!error +split(x, ',');{x: [[1]]};!error +split(x, ',');{x: {}};!error +split(x, ',');{x: {a: 1}};!error +split(x, ',');{};!error +# split: argument 2 +# split arg 2 (literal) +split('a,b', null);;!error +split('a,b', true);;!error +split('a,b', false);;!error +split('a,b', 0);;!error +split('a,b', -1);;!error +split('a,b', 1.5);;!error +split('a,b', 79228162514264337593543950335);;!error +split('a,b', '');;['a', ',', 'b'];bug: empty separator yields leading and trailing empty strings +split('a,b', 'abc');;['a,b'] +split('a,b', '12.5');;['a,b'] +split('a,b', 'żółw');;['a,b'] +split('a,b', []);;!error +split('a,b', [1, 2]);;!error +split('a,b', ['a']);;!error +split('a,b', [[1]]);;!error +split('a,b', {});;!error +split('a,b', {a: 1});;!error +split('a,b', d('2024-01-01'));;['a,b'] +split('a,b', [1..3]);;!error +# split arg 2 (input) +split('a,b', x);{x: null};!error +split('a,b', x);{x: true};!error +split('a,b', x);{x: false};!error +split('a,b', x);{x: 0};!error +split('a,b', x);{x: -1};!error +split('a,b', x);{x: 1.5};!error +split('a,b', x);{x: 79228162514264337593543950335};!error +split('a,b', x);{x: ''};['a', ',', 'b'];bug: empty separator yields leading and trailing empty strings +split('a,b', x);{x: 'abc'};['a,b'] +split('a,b', x);{x: '12.5'};['a,b'] +split('a,b', x);{x: 'żółw'};['a,b'] +split('a,b', x);{x: []};!error +split('a,b', x);{x: [1, 2]};!error +split('a,b', x);{x: ['a']};!error +split('a,b', x);{x: [[1]]};!error +split('a,b', x);{x: {}};!error +split('a,b', x);{x: {a: 1}};!error +split('a,b', x);{};!error +# split: both arguments from input +split(x, y);{x: 'a b', y: ' '};['a', 'b'] +split(x, y);{x: 'ab', y: ','};['ab'] +split(x, y);{x: 1, y: '1'};!error +split(x, y);{x: '1', y: 1};!error +split(x, y);{x: null, y: null};!error +split(x, y);{};!error +split(x, y);{x: ['a,b'], y: ','};!error +# fuzzyMatch: argument 1 +# fuzzyMatch arg 1 (literal) +fuzzyMatch(null, 'abc');;!error +fuzzyMatch(true, 'abc');;!error +fuzzyMatch(false, 'abc');;!error +fuzzyMatch(0, 'abc');;!error +fuzzyMatch(-1, 'abc');;!error +fuzzyMatch(1.5, 'abc');;!error +fuzzyMatch(79228162514264337593543950335, 'abc');;!error +fuzzyMatch('', 'abc');;0 +fuzzyMatch('abc', 'abc');;1 +fuzzyMatch('12.5', 'abc');;0 +fuzzyMatch('żółw', 'abc');;0 +fuzzyMatch([], 'abc');;[] +fuzzyMatch([1, 2], 'abc');;!error +fuzzyMatch(['a'], 'abc');;[0.3333333333333334] +fuzzyMatch([[1]], 'abc');;!error +fuzzyMatch({}, 'abc');;!error +fuzzyMatch({a: 1}, 'abc');;!error +fuzzyMatch(d('2024-01-01'), 'abc');;0 +fuzzyMatch([1..3], 'abc');;!error +# fuzzyMatch arg 1 (input) +fuzzyMatch(x, 'abc');{x: null};!error +fuzzyMatch(x, 'abc');{x: true};!error +fuzzyMatch(x, 'abc');{x: false};!error +fuzzyMatch(x, 'abc');{x: 0};!error +fuzzyMatch(x, 'abc');{x: -1};!error +fuzzyMatch(x, 'abc');{x: 1.5};!error +fuzzyMatch(x, 'abc');{x: 79228162514264337593543950335};!error +fuzzyMatch(x, 'abc');{x: ''};0 +fuzzyMatch(x, 'abc');{x: 'abc'};1 +fuzzyMatch(x, 'abc');{x: '12.5'};0 +fuzzyMatch(x, 'abc');{x: 'żółw'};0 +fuzzyMatch(x, 'abc');{x: []};[] +fuzzyMatch(x, 'abc');{x: [1, 2]};!error +fuzzyMatch(x, 'abc');{x: ['a']};[0.3333333333333334] +fuzzyMatch(x, 'abc');{x: [[1]]};!error +fuzzyMatch(x, 'abc');{x: {}};!error +fuzzyMatch(x, 'abc');{x: {a: 1}};!error +fuzzyMatch(x, 'abc');{};!error +# fuzzyMatch: argument 2 +# fuzzyMatch arg 2 (literal) +fuzzyMatch('abc', null);;!error +fuzzyMatch('abc', true);;!error +fuzzyMatch('abc', false);;!error +fuzzyMatch('abc', 0);;!error +fuzzyMatch('abc', -1);;!error +fuzzyMatch('abc', 1.5);;!error +fuzzyMatch('abc', 79228162514264337593543950335);;!error +fuzzyMatch('abc', '');;0 +fuzzyMatch('abc', 'abc');;1 +fuzzyMatch('abc', '12.5');;0 +fuzzyMatch('abc', 'żółw');;0 +fuzzyMatch('abc', []);;!error +fuzzyMatch('abc', [1, 2]);;!error +fuzzyMatch('abc', ['a']);;!error +fuzzyMatch('abc', [[1]]);;!error +fuzzyMatch('abc', {});;!error +fuzzyMatch('abc', {a: 1});;!error +fuzzyMatch('abc', d('2024-01-01'));;0 +fuzzyMatch('abc', [1..3]);;!error +# fuzzyMatch arg 2 (input) +fuzzyMatch('abc', x);{x: null};!error +fuzzyMatch('abc', x);{x: true};!error +fuzzyMatch('abc', x);{x: false};!error +fuzzyMatch('abc', x);{x: 0};!error +fuzzyMatch('abc', x);{x: -1};!error +fuzzyMatch('abc', x);{x: 1.5};!error +fuzzyMatch('abc', x);{x: 79228162514264337593543950335};!error +fuzzyMatch('abc', x);{x: ''};0 +fuzzyMatch('abc', x);{x: 'abc'};1 +fuzzyMatch('abc', x);{x: '12.5'};0 +fuzzyMatch('abc', x);{x: 'żółw'};0 +fuzzyMatch('abc', x);{x: []};!error +fuzzyMatch('abc', x);{x: [1, 2]};!error +fuzzyMatch('abc', x);{x: ['a']};!error +fuzzyMatch('abc', x);{x: [[1]]};!error +fuzzyMatch('abc', x);{x: {}};!error +fuzzyMatch('abc', x);{x: {a: 1}};!error +fuzzyMatch('abc', x);{};!error +# fuzzyMatch: both arguments from input +fuzzyMatch(x, y);{x: 'abc', y: 'abc'};1 +fuzzyMatch(x, y);{x: ['abc'], y: 'abc'};[1] +fuzzyMatch(x, y);{x: 1, y: '1'};!error +fuzzyMatch(x, y);{x: 'abc', y: ['abc']};!error +fuzzyMatch(x, y);{x: null, y: null};!error +fuzzyMatch(x, y);{};!error +fuzzyMatch(x, y);{x: [], y: 'x'};[] +# fuzzyMatch: array elements must be strings +fuzzyMatch(x, 'abc');{x: ['abc', 'abc']};[1, 1] +fuzzyMatch(x, 'abc');{x: ['abc', null]};!error +fuzzyMatch(x, 'abc');{x: ['abc', 1]};!error +fuzzyMatch(x, 'abc');{x: [['abc']]};!error +fuzzyMatch(x, 'abc');{x: [null]};!error +fuzzyMatch(x, 'abc');{x: ['', 'abc']};[0, 1] diff --git a/core/expression/tests/spec/standard/10-03-math.csv b/core/expression/tests/spec/standard/10-03-math.csv new file mode 100644 index 00000000..9b512d37 --- /dev/null +++ b/core/expression/tests/spec/standard/10-03-math.csv @@ -0,0 +1,703 @@ +expression (string);input (json 5);output (json 5);note +# abs: argument 1 is number +# abs (literal) +abs(null);;!error +abs(true);;!error +abs(false);;!error +abs(0);;0 +abs(-1);;1 +abs(1.5);;1.5 +abs(79228162514264337593543950335);;79228162514264337593543950335 +abs('');;!error +abs('abc');;!error +abs('12.5');;!error +abs('żółw');;!error +abs([]);;!error +abs([1, 2]);;!error +abs(['a']);;!error +abs([[1]]);;!error +abs({});;!error +abs({a: 1});;!error +abs(d('2024-01-01'));;!error +abs([1..3]);;!error +# abs (input) +abs(x);{x: null};!error +abs(x);{x: true};!error +abs(x);{x: false};!error +abs(x);{x: 0};0 +abs(x);{x: -1};1 +abs(x);{x: 1.5};1.5 +abs(x);{x: 79228162514264337593543950335};79228162514264337593543950335 +abs(x);{x: ''};!error +abs(x);{x: 'abc'};!error +abs(x);{x: '12.5'};!error +abs(x);{x: 'żółw'};!error +abs(x);{x: []};!error +abs(x);{x: [1, 2]};!error +abs(x);{x: ['a']};!error +abs(x);{x: [[1]]};!error +abs(x);{x: {}};!error +abs(x);{x: {a: 1}};!error +abs(x);{};!error +# floor: argument 1 is number +# floor (literal) +floor(null);;!error +floor(true);;!error +floor(false);;!error +floor(0);;0 +floor(-1);;-1 +floor(1.5);;1 +floor(79228162514264337593543950335);;79228162514264337593543950335 +floor('');;!error +floor('abc');;!error +floor('12.5');;!error +floor('żółw');;!error +floor([]);;!error +floor([1, 2]);;!error +floor(['a']);;!error +floor([[1]]);;!error +floor({});;!error +floor({a: 1});;!error +floor(d('2024-01-01'));;!error +floor([1..3]);;!error +# floor (input) +floor(x);{x: null};!error +floor(x);{x: true};!error +floor(x);{x: false};!error +floor(x);{x: 0};0 +floor(x);{x: -1};-1 +floor(x);{x: 1.5};1 +floor(x);{x: 79228162514264337593543950335};79228162514264337593543950335 +floor(x);{x: ''};!error +floor(x);{x: 'abc'};!error +floor(x);{x: '12.5'};!error +floor(x);{x: 'żółw'};!error +floor(x);{x: []};!error +floor(x);{x: [1, 2]};!error +floor(x);{x: ['a']};!error +floor(x);{x: [[1]]};!error +floor(x);{x: {}};!error +floor(x);{x: {a: 1}};!error +floor(x);{};!error +# ceil: argument 1 is number +# ceil (literal) +ceil(null);;!error +ceil(true);;!error +ceil(false);;!error +ceil(0);;0 +ceil(-1);;-1 +ceil(1.5);;2 +ceil(79228162514264337593543950335);;79228162514264337593543950335 +ceil('');;!error +ceil('abc');;!error +ceil('12.5');;!error +ceil('żółw');;!error +ceil([]);;!error +ceil([1, 2]);;!error +ceil(['a']);;!error +ceil([[1]]);;!error +ceil({});;!error +ceil({a: 1});;!error +ceil(d('2024-01-01'));;!error +ceil([1..3]);;!error +# ceil (input) +ceil(x);{x: null};!error +ceil(x);{x: true};!error +ceil(x);{x: false};!error +ceil(x);{x: 0};0 +ceil(x);{x: -1};-1 +ceil(x);{x: 1.5};2 +ceil(x);{x: 79228162514264337593543950335};79228162514264337593543950335 +ceil(x);{x: ''};!error +ceil(x);{x: 'abc'};!error +ceil(x);{x: '12.5'};!error +ceil(x);{x: 'żółw'};!error +ceil(x);{x: []};!error +ceil(x);{x: [1, 2]};!error +ceil(x);{x: ['a']};!error +ceil(x);{x: [[1]]};!error +ceil(x);{x: {}};!error +ceil(x);{x: {a: 1}};!error +ceil(x);{};!error +# round: argument 1 is number +# round (literal) +round(null);;!error +round(true);;!error +round(false);;!error +round(0);;0 +round(-1);;-1 +round(1.5);;2 +round(79228162514264337593543950335);;79228162514264337593543950335 +round('');;!error +round('abc');;!error +round('12.5');;!error +round('żółw');;!error +round([]);;!error +round([1, 2]);;!error +round(['a']);;!error +round([[1]]);;!error +round({});;!error +round({a: 1});;!error +round(d('2024-01-01'));;!error +round([1..3]);;!error +# round (input) +round(x);{x: null};!error +round(x);{x: true};!error +round(x);{x: false};!error +round(x);{x: 0};0 +round(x);{x: -1};-1 +round(x);{x: 1.5};2 +round(x);{x: 79228162514264337593543950335};79228162514264337593543950335 +round(x);{x: ''};!error +round(x);{x: 'abc'};!error +round(x);{x: '12.5'};!error +round(x);{x: 'żółw'};!error +round(x);{x: []};!error +round(x);{x: [1, 2]};!error +round(x);{x: ['a']};!error +round(x);{x: [[1]]};!error +round(x);{x: {}};!error +round(x);{x: {a: 1}};!error +round(x);{};!error +# trunc: argument 1 is number +# trunc (literal) +trunc(null);;!error +trunc(true);;!error +trunc(false);;!error +trunc(0);;0 +trunc(-1);;-1 +trunc(1.5);;1 +trunc(79228162514264337593543950335);;79228162514264337593543950335 +trunc('');;!error +trunc('abc');;!error +trunc('12.5');;!error +trunc('żółw');;!error +trunc([]);;!error +trunc([1, 2]);;!error +trunc(['a']);;!error +trunc([[1]]);;!error +trunc({});;!error +trunc({a: 1});;!error +trunc(d('2024-01-01'));;!error +trunc([1..3]);;!error +# trunc (input) +trunc(x);{x: null};!error +trunc(x);{x: true};!error +trunc(x);{x: false};!error +trunc(x);{x: 0};0 +trunc(x);{x: -1};-1 +trunc(x);{x: 1.5};1 +trunc(x);{x: 79228162514264337593543950335};79228162514264337593543950335 +trunc(x);{x: ''};!error +trunc(x);{x: 'abc'};!error +trunc(x);{x: '12.5'};!error +trunc(x);{x: 'żółw'};!error +trunc(x);{x: []};!error +trunc(x);{x: [1, 2]};!error +trunc(x);{x: ['a']};!error +trunc(x);{x: [[1]]};!error +trunc(x);{x: {}};!error +trunc(x);{x: {a: 1}};!error +trunc(x);{};!error +# round: argument 1 with a precision +# round arg 1 (literal) +round(null, 1);;!error +round(true, 1);;!error +round(false, 1);;!error +round(0, 1);;0 +round(-1, 1);;-1 +round(1.5, 1);;1.5 +round(79228162514264337593543950335, 1);;79228162514264337593543950335 +round('', 1);;!error +round('abc', 1);;!error +round('12.5', 1);;!error +round('żółw', 1);;!error +round([], 1);;!error +round([1, 2], 1);;!error +round(['a'], 1);;!error +round([[1]], 1);;!error +round({}, 1);;!error +round({a: 1}, 1);;!error +round(d('2024-01-01'), 1);;!error +round([1..3], 1);;!error +# round arg 1 (input) +round(x, 1);{x: null};!error +round(x, 1);{x: true};!error +round(x, 1);{x: false};!error +round(x, 1);{x: 0};0 +round(x, 1);{x: -1};-1 +round(x, 1);{x: 1.5};1.5 +round(x, 1);{x: 79228162514264337593543950335};79228162514264337593543950335 +round(x, 1);{x: ''};!error +round(x, 1);{x: 'abc'};!error +round(x, 1);{x: '12.5'};!error +round(x, 1);{x: 'żółw'};!error +round(x, 1);{x: []};!error +round(x, 1);{x: [1, 2]};!error +round(x, 1);{x: ['a']};!error +round(x, 1);{x: [[1]]};!error +round(x, 1);{x: {}};!error +round(x, 1);{x: {a: 1}};!error +round(x, 1);{};!error +# round: argument 2 is a non-negative integer number +# round arg 2 (literal) +round(1.25, null);;!error;"question: null precision fails; could mean the default precision 0" +round(1.25, true);;!error +round(1.25, false);;!error +round(1.25, 0);;1 +round(1.25, -1);;!error;"question: negative precision (round to tens) is rejected; could mean rounding left of the point" +round(1.25, 1.5);;1.3;question: fractional precision is silently truncated to an integer instead of being rejected +round(1.25, 79228162514264337593543950335);;!error +round(1.25, '');;!error +round(1.25, 'abc');;!error +round(1.25, '12.5');;!error +round(1.25, 'żółw');;!error +round(1.25, []);;!error +round(1.25, [1, 2]);;!error +round(1.25, ['a']);;!error +round(1.25, [[1]]);;!error +round(1.25, {});;!error +round(1.25, {a: 1});;!error +round(1.25, d('2024-01-01'));;!error +round(1.25, [1..3]);;!error +# round arg 2 (input) +round(1.25, x);{x: null};!error;"question: null precision fails; could mean the default precision 0" +round(1.25, x);{x: true};!error +round(1.25, x);{x: false};!error +round(1.25, x);{x: 0};1 +round(1.25, x);{x: -1};!error;"question: negative precision (round to tens) is rejected; could mean rounding left of the point" +round(1.25, x);{x: 1.5};1.3;question: fractional precision is silently truncated to an integer instead of being rejected +round(1.25, x);{x: 79228162514264337593543950335};!error +round(1.25, x);{x: ''};!error +round(1.25, x);{x: 'abc'};!error +round(1.25, x);{x: '12.5'};!error +round(1.25, x);{x: 'żółw'};!error +round(1.25, x);{x: []};!error +round(1.25, x);{x: [1, 2]};!error +round(1.25, x);{x: ['a']};!error +round(1.25, x);{x: [[1]]};!error +round(1.25, x);{x: {}};!error +round(1.25, x);{x: {a: 1}};!error +round(1.25, x);{};!error;"question: null precision fails; could mean the default precision 0" +# trunc: argument 1 with a precision +# trunc arg 1 (literal) +trunc(null, 1);;!error +trunc(true, 1);;!error +trunc(false, 1);;!error +trunc(0, 1);;0 +trunc(-1, 1);;-1 +trunc(1.5, 1);;1.5 +trunc(79228162514264337593543950335, 1);;79228162514264337593543950335 +trunc('', 1);;!error +trunc('abc', 1);;!error +trunc('12.5', 1);;!error +trunc('żółw', 1);;!error +trunc([], 1);;!error +trunc([1, 2], 1);;!error +trunc(['a'], 1);;!error +trunc([[1]], 1);;!error +trunc({}, 1);;!error +trunc({a: 1}, 1);;!error +trunc(d('2024-01-01'), 1);;!error +trunc([1..3], 1);;!error +# trunc arg 1 (input) +trunc(x, 1);{x: null};!error +trunc(x, 1);{x: true};!error +trunc(x, 1);{x: false};!error +trunc(x, 1);{x: 0};0 +trunc(x, 1);{x: -1};-1 +trunc(x, 1);{x: 1.5};1.5 +trunc(x, 1);{x: 79228162514264337593543950335};79228162514264337593543950335 +trunc(x, 1);{x: ''};!error +trunc(x, 1);{x: 'abc'};!error +trunc(x, 1);{x: '12.5'};!error +trunc(x, 1);{x: 'żółw'};!error +trunc(x, 1);{x: []};!error +trunc(x, 1);{x: [1, 2]};!error +trunc(x, 1);{x: ['a']};!error +trunc(x, 1);{x: [[1]]};!error +trunc(x, 1);{x: {}};!error +trunc(x, 1);{x: {a: 1}};!error +trunc(x, 1);{};!error +# trunc: argument 2 is a non-negative integer number +# trunc arg 2 (literal) +trunc(1.25, null);;!error;"question: null precision fails; could mean the default precision 0" +trunc(1.25, true);;!error +trunc(1.25, false);;!error +trunc(1.25, 0);;1 +trunc(1.25, -1);;!error;"question: negative precision (round to tens) is rejected; could mean rounding left of the point" +trunc(1.25, 1.5);;1.2;question: fractional precision is silently truncated to an integer instead of being rejected +trunc(1.25, 79228162514264337593543950335);;!error +trunc(1.25, '');;!error +trunc(1.25, 'abc');;!error +trunc(1.25, '12.5');;!error +trunc(1.25, 'żółw');;!error +trunc(1.25, []);;!error +trunc(1.25, [1, 2]);;!error +trunc(1.25, ['a']);;!error +trunc(1.25, [[1]]);;!error +trunc(1.25, {});;!error +trunc(1.25, {a: 1});;!error +trunc(1.25, d('2024-01-01'));;!error +trunc(1.25, [1..3]);;!error +# trunc arg 2 (input) +trunc(1.25, x);{x: null};!error;"question: null precision fails; could mean the default precision 0" +trunc(1.25, x);{x: true};!error +trunc(1.25, x);{x: false};!error +trunc(1.25, x);{x: 0};1 +trunc(1.25, x);{x: -1};!error;"question: negative precision (round to tens) is rejected; could mean rounding left of the point" +trunc(1.25, x);{x: 1.5};1.2;question: fractional precision is silently truncated to an integer instead of being rejected +trunc(1.25, x);{x: 79228162514264337593543950335};!error +trunc(1.25, x);{x: ''};!error +trunc(1.25, x);{x: 'abc'};!error +trunc(1.25, x);{x: '12.5'};!error +trunc(1.25, x);{x: 'żółw'};!error +trunc(1.25, x);{x: []};!error +trunc(1.25, x);{x: [1, 2]};!error +trunc(1.25, x);{x: ['a']};!error +trunc(1.25, x);{x: [[1]]};!error +trunc(1.25, x);{x: {}};!error +trunc(1.25, x);{x: {a: 1}};!error +trunc(1.25, x);{};!error;"question: null precision fails; could mean the default precision 0" +# rand: argument 1 is number (upper bound, inclusive) +# rand (literal) +type(rand(null));;!error +type(rand(true));;!error +type(rand(false));;!error +type(rand(0));;'number' +type(rand(-1));;!error;bug: panics (empty range in fastrand) on a negative upper bound instead of raising an error +type(rand(1.5));;'number' +type(rand(79228162514264337593543950335));;!error;question: an upper bound beyond i64 is rejected +type(rand(''));;!error +type(rand('abc'));;!error +type(rand('12.5'));;!error +type(rand('żółw'));;!error +type(rand([]));;!error +type(rand([1, 2]));;!error +type(rand(['a']));;!error +type(rand([[1]]));;!error +type(rand({}));;!error +type(rand({a: 1}));;!error +type(rand(d('2024-01-01')));;!error +type(rand([1..3]));;!error +# rand (input) +type(rand(x));{x: null};!error +type(rand(x));{x: true};!error +type(rand(x));{x: false};!error +type(rand(x));{x: 0};'number' +type(rand(x));{x: -1};!error;bug: panics (empty range in fastrand) on a negative upper bound instead of raising an error +type(rand(x));{x: 1.5};'number' +type(rand(x));{x: 79228162514264337593543950335};!error;question: an upper bound beyond i64 is rejected +type(rand(x));{x: ''};!error +type(rand(x));{x: 'abc'};!error +type(rand(x));{x: '12.5'};!error +type(rand(x));{x: 'żółw'};!error +type(rand(x));{x: []};!error +type(rand(x));{x: [1, 2]};!error +type(rand(x));{x: ['a']};!error +type(rand(x));{x: [[1]]};!error +type(rand(x));{x: {}};!error +type(rand(x));{x: {a: 1}};!error +type(rand(x));{};!error +rand(x);{x: 0};0 +rand(x);{x: 0.4};0 +rand(x);{x: -0.4};0 +# sum: argument 1 is number array +# sum (literal) +sum(null);;!error +sum(true);;!error +sum(false);;!error +sum(0);;!error +sum(-1);;!error +sum(1.5);;!error +sum(79228162514264337593543950335);;!error +sum('');;!error +sum('abc');;!error +sum('12.5');;!error +sum('żółw');;!error +sum([]);;0 +sum([1, 2]);;3 +sum(['a']);;!error +sum([[1]]);;!error +sum({});;!error +sum({a: 1});;!error +sum(d('2024-01-01'));;!error +sum([1..3]);;!error +# sum (input) +sum(x);{x: null};!error +sum(x);{x: true};!error +sum(x);{x: false};!error +sum(x);{x: 0};!error +sum(x);{x: -1};!error +sum(x);{x: 1.5};!error +sum(x);{x: 79228162514264337593543950335};!error +sum(x);{x: ''};!error +sum(x);{x: 'abc'};!error +sum(x);{x: '12.5'};!error +sum(x);{x: 'żółw'};!error +sum(x);{x: []};0 +sum(x);{x: [1, 2]};3 +sum(x);{x: ['a']};!error +sum(x);{x: [[1]]};!error +sum(x);{x: {}};!error +sum(x);{x: {a: 1}};!error +sum(x);{};!error +# sum: element types +sum(x);{x: [1, null]};!error +sum(x);{x: [1, '2']};!error +sum(x);{x: [true]};!error +sum(x);{x: [[1], 2]};!error +sum(x);{x: [0.1, 0.2]};0.3 +sum(x);{x: [-1, 1.5]};0.5 +# avg: argument 1 is number array +# avg (literal) +avg(null);;!error +avg(true);;!error +avg(false);;!error +avg(0);;!error +avg(-1);;!error +avg(1.5);;!error +avg(79228162514264337593543950335);;!error +avg('');;!error +avg('abc');;!error +avg('12.5');;!error +avg('żółw');;!error +avg([]);;!error;"question: average of an empty list fails; could be null" +avg([1, 2]);;1.5 +avg(['a']);;!error +avg([[1]]);;!error +avg({});;!error +avg({a: 1});;!error +avg(d('2024-01-01'));;!error +avg([1..3]);;!error +# avg (input) +avg(x);{x: null};!error +avg(x);{x: true};!error +avg(x);{x: false};!error +avg(x);{x: 0};!error +avg(x);{x: -1};!error +avg(x);{x: 1.5};!error +avg(x);{x: 79228162514264337593543950335};!error +avg(x);{x: ''};!error +avg(x);{x: 'abc'};!error +avg(x);{x: '12.5'};!error +avg(x);{x: 'żółw'};!error +avg(x);{x: []};!error;"question: average of an empty list fails; could be null" +avg(x);{x: [1, 2]};1.5 +avg(x);{x: ['a']};!error +avg(x);{x: [[1]]};!error +avg(x);{x: {}};!error +avg(x);{x: {a: 1}};!error +avg(x);{};!error +# avg: element types +avg(x);{x: [1, null]};!error +avg(x);{x: [1, '2']};!error +avg(x);{x: [true]};!error +avg(x);{x: [[1], 2]};!error +avg(x);{x: [1, 2, 3]};2 +avg(x);{x: [-1, 1.5]};0.25 +# median: argument 1 is number array +# median (literal) +median(null);;!error +median(true);;!error +median(false);;!error +median(0);;!error +median(-1);;!error +median(1.5);;!error +median(79228162514264337593543950335);;!error +median('');;!error +median('abc');;!error +median('12.5');;!error +median('żółw');;!error +median([]);;!error;"question: median of an empty list fails; could be null" +median([1, 2]);;1.5 +median(['a']);;!error +median([[1]]);;!error +median({});;!error +median({a: 1});;!error +median(d('2024-01-01'));;!error +median([1..3]);;!error +# median (input) +median(x);{x: null};!error +median(x);{x: true};!error +median(x);{x: false};!error +median(x);{x: 0};!error +median(x);{x: -1};!error +median(x);{x: 1.5};!error +median(x);{x: 79228162514264337593543950335};!error +median(x);{x: ''};!error +median(x);{x: 'abc'};!error +median(x);{x: '12.5'};!error +median(x);{x: 'żółw'};!error +median(x);{x: []};!error;"question: median of an empty list fails; could be null" +median(x);{x: [1, 2]};1.5 +median(x);{x: ['a']};!error +median(x);{x: [[1]]};!error +median(x);{x: {}};!error +median(x);{x: {a: 1}};!error +median(x);{};!error +# median: element types +median(x);{x: [1, null]};!error +median(x);{x: [1, '2']};!error +median(x);{x: [true]};!error +median(x);{x: [[1], 2]};!error +median(x);{x: [3, 1, 2]};2 +median(x);{x: [-1, 1.5]};0.25 +# mode: argument 1 is number array +# mode (literal) +mode(null);;!error +mode(true);;!error +mode(false);;!error +mode(0);;!error +mode(-1);;!error +mode(1.5);;!error +mode(79228162514264337593543950335);;!error +mode('');;!error +mode('abc');;!error +mode('12.5');;!error +mode('żółw');;!error +mode([]);;!error;"question: mode of an empty list fails; could be null" +mode([1, 2]);;2;question: ties resolve to the largest value +mode(['a']);;!error +mode([[1]]);;!error +mode({});;!error +mode({a: 1});;!error +mode(d('2024-01-01'));;!error +mode([1..3]);;!error +# mode (input) +mode(x);{x: null};!error +mode(x);{x: true};!error +mode(x);{x: false};!error +mode(x);{x: 0};!error +mode(x);{x: -1};!error +mode(x);{x: 1.5};!error +mode(x);{x: 79228162514264337593543950335};!error +mode(x);{x: ''};!error +mode(x);{x: 'abc'};!error +mode(x);{x: '12.5'};!error +mode(x);{x: 'żółw'};!error +mode(x);{x: []};!error;"question: mode of an empty list fails; could be null" +mode(x);{x: [1, 2]};2;question: ties resolve to the largest value +mode(x);{x: ['a']};!error +mode(x);{x: [[1]]};!error +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, '2']};!error +mode(x);{x: [true]};!error +mode(x);{x: [[1], 2]};!error +mode(x);{x: [3, 1, 3]};3 +mode(x);{x: [-1]};-1 +# min: argument 1 is number array | date array +# min (literal) +min(null);;!error +min(true);;!error +min(false);;!error +min(0);;!error +min(-1);;!error +min(1.5);;!error +min(79228162514264337593543950335);;!error +min('');;!error +min('abc');;!error +min('12.5');;!error +min('żółw');;!error +min([]);;!error;"question: minimum of an empty list fails; could be null" +min([1, 2]);;1 +min(['a']);;!error +min([[1]]);;!error +min({});;!error +min({a: 1});;!error +min(d('2024-01-01'));;!error +min([1..3]);;!error +# min (input) +min(x);{x: null};!error +min(x);{x: true};!error +min(x);{x: false};!error +min(x);{x: 0};!error +min(x);{x: -1};!error +min(x);{x: 1.5};!error +min(x);{x: 79228162514264337593543950335};!error +min(x);{x: ''};!error +min(x);{x: 'abc'};!error +min(x);{x: '12.5'};!error +min(x);{x: 'żółw'};!error +min(x);{x: []};!error;"question: minimum of an empty list fails; could be null" +min(x);{x: [1, 2]};1 +min(x);{x: ['a']};!error +min(x);{x: [[1]]};!error +min(x);{x: {}};!error +min(x);{x: {a: 1}};!error +min(x);{};!error +# min: element types +min(x);{x: [1, null]};!error +min(x);{x: [1, '2']};!error +min(x);{x: [true]};!error +min(x);{x: [[1], 2]};!error +min(x);{x: [3, 1, 2]};1 +min(x);{x: [-1, 1.5]};-1 +min(x);{x: [null]};!error +min(x);{x: ['a', 'b']};!error +# max: argument 1 is number array | date array +# max (literal) +max(null);;!error +max(true);;!error +max(false);;!error +max(0);;!error +max(-1);;!error +max(1.5);;!error +max(79228162514264337593543950335);;!error +max('');;!error +max('abc');;!error +max('12.5');;!error +max('żółw');;!error +max([]);;!error;"question: maximum of an empty list fails; could be null" +max([1, 2]);;2 +max(['a']);;!error +max([[1]]);;!error +max({});;!error +max({a: 1});;!error +max(d('2024-01-01'));;!error +max([1..3]);;!error +# max (input) +max(x);{x: null};!error +max(x);{x: true};!error +max(x);{x: false};!error +max(x);{x: 0};!error +max(x);{x: -1};!error +max(x);{x: 1.5};!error +max(x);{x: 79228162514264337593543950335};!error +max(x);{x: ''};!error +max(x);{x: 'abc'};!error +max(x);{x: '12.5'};!error +max(x);{x: 'żółw'};!error +max(x);{x: []};!error;"question: maximum of an empty list fails; could be null" +max(x);{x: [1, 2]};2 +max(x);{x: ['a']};!error +max(x);{x: [[1]]};!error +max(x);{x: {}};!error +max(x);{x: {a: 1}};!error +max(x);{};!error +# max: element types +max(x);{x: [1, null]};!error +max(x);{x: [1, '2']};!error +max(x);{x: [true]};!error +max(x);{x: [[1], 2]};!error +max(x);{x: [3, 1, 2]};3 +max(x);{x: [-1, 1.5]};1.5 +max(x);{x: [null]};!error +max(x);{x: ['a', 'b']};!error +# min/max: date arrays +min([d('2024-01-02'), d('2024-01-01')]);;'2024-01-01T00:00:00Z' +max([d('2024-01-02'), d('2024-01-01')]);;'2024-01-02T00:00:00Z' +min([d('2024-01-01'), 1]);;!error +max([d('2024-01-01'), 1]);;!error +min([1, d('2024-01-01')]);;!error +max([1, d('2024-01-01')]);;!error +min([d('2024-01-01'), '2024-01-02']);;!error +max([d('2024-01-01'), null]);;!error +sum([d('2024-01-01')]);;!error +avg([d('2024-01-01')]);;!error +median([d('2024-01-01')]);;!error +mode([d('2024-01-01')]);;!error diff --git a/core/expression/tests/spec/standard/10-04-types.csv b/core/expression/tests/spec/standard/10-04-types.csv new file mode 100644 index 00000000..12f08705 --- /dev/null +++ b/core/expression/tests/spec/standard/10-04-types.csv @@ -0,0 +1,201 @@ +expression (string);input (json 5);output (json 5);note +# type: argument 1 is any +# type (literal) +type(null);;'null' +type(true);;'bool' +type(false);;'bool' +type(0);;'number' +type(-1);;'number' +type(1.5);;'number' +type(79228162514264337593543950335);;'number' +type('');;'string' +type('abc');;'string' +type('12.5');;'string' +type('żółw');;'string' +type([]);;'array' +type([1, 2]);;'array' +type(['a']);;'array' +type([[1]]);;'array' +type({});;'object' +type({a: 1});;'object' +type(d('2024-01-01'));;'date' +type([1..3]);;'interval' +# type (input) +type(x);{x: null};'null' +type(x);{x: true};'bool' +type(x);{x: false};'bool' +type(x);{x: 0};'number' +type(x);{x: -1};'number' +type(x);{x: 1.5};'number' +type(x);{x: 79228162514264337593543950335};'number' +type(x);{x: ''};'string' +type(x);{x: 'abc'};'string' +type(x);{x: '12.5'};'string' +type(x);{x: 'żółw'};'string' +type(x);{x: []};'array' +type(x);{x: [1, 2]};'array' +type(x);{x: ['a']};'array' +type(x);{x: [[1]]};'array' +type(x);{x: {}};'object' +type(x);{x: {a: 1}};'object' +type(x);{};'null' +# string: argument 1 is any +# string (literal) +string(null);;'null' +string(true);;'true' +string(false);;'false' +string(0);;'0' +string(-1);;'-1' +string(1.5);;'1.5' +string(79228162514264337593543950335);;'79228162514264337593543950335' +string('');;'' +string('abc');;'abc' +string('12.5');;'12.5' +string('żółw');;'żółw' +string([]);;!error;question: arrays have no string form +string([1, 2]);;!error;question: arrays have no string form +string(['a']);;!error;question: arrays have no string form +string([[1]]);;!error;question: arrays have no string form +string({});;!error;question: objects have no string form +string({a: 1});;!error;question: objects have no string form +string(d('2024-01-01'));;'2024-01-01T00:00:00Z' +string([1..3]);;!error;question: intervals have a string form as output values but string() rejects them +# string (input) +string(x);{x: null};'null' +string(x);{x: true};'true' +string(x);{x: false};'false' +string(x);{x: 0};'0' +string(x);{x: -1};'-1' +string(x);{x: 1.5};'1.5' +string(x);{x: 79228162514264337593543950335};'79228162514264337593543950335' +string(x);{x: ''};'' +string(x);{x: 'abc'};'abc' +string(x);{x: '12.5'};'12.5' +string(x);{x: 'żółw'};'żółw' +string(x);{x: []};!error;question: arrays have no string form +string(x);{x: [1, 2]};!error;question: arrays have no string form +string(x);{x: ['a']};!error;question: arrays have no string form +string(x);{x: [[1]]};!error;question: arrays have no string form +string(x);{x: {}};!error;question: objects have no string form +string(x);{x: {a: 1}};!error;question: objects have no string form +string(x);{};'null' +# bool: argument 1 is any +# bool (literal) +bool(null);;false +bool(true);;true +bool(false);;false +bool(0);;false +bool(-1);;true +bool(1.5);;true +bool(79228162514264337593543950335);;true +bool('');;false;bug: empty string converts to true (non-true/false strings return s.is_empty(), inverted) +bool('abc');;true;bug: non-empty string converts to false (inverted is_empty) +bool('12.5');;true;bug: non-empty string converts to false (inverted is_empty) +bool('żółw');;true;bug: non-empty string converts to false (inverted is_empty) +bool([]);;true +bool([1, 2]);;true +bool(['a']);;true +bool([[1]]);;true +bool({});;true +bool({a: 1});;true +bool(d('2024-01-01'));;true +bool([1..3]);;true +# bool (input) +bool(x);{x: null};false +bool(x);{x: true};true +bool(x);{x: false};false +bool(x);{x: 0};false +bool(x);{x: -1};true +bool(x);{x: 1.5};true +bool(x);{x: 79228162514264337593543950335};true +bool(x);{x: ''};false;bug: empty string converts to true (non-true/false strings return s.is_empty(), inverted) +bool(x);{x: 'abc'};true;bug: non-empty string converts to false (inverted is_empty) +bool(x);{x: '12.5'};true;bug: non-empty string converts to false (inverted is_empty) +bool(x);{x: 'żółw'};true;bug: non-empty string converts to false (inverted is_empty) +bool(x);{x: []};true +bool(x);{x: [1, 2]};true +bool(x);{x: ['a']};true +bool(x);{x: [[1]]};true +bool(x);{x: {}};true +bool(x);{x: {a: 1}};true +bool(x);{};false +# isNumeric: argument 1 is any +# isNumeric (literal) +isNumeric(null);;false +isNumeric(true);;false;question: number(true) converts to 1 but isNumeric(true) is false +isNumeric(false);;false;question: number(false) converts to 0 but isNumeric(false) is false +isNumeric(0);;true +isNumeric(-1);;true +isNumeric(1.5);;true +isNumeric(79228162514264337593543950335);;true +isNumeric('');;false +isNumeric('abc');;false +isNumeric('12.5');;true +isNumeric('żółw');;false +isNumeric([]);;false +isNumeric([1, 2]);;false +isNumeric(['a']);;false +isNumeric([[1]]);;false +isNumeric({});;false +isNumeric({a: 1});;false +isNumeric(d('2024-01-01'));;false +isNumeric([1..3]);;false +# isNumeric (input) +isNumeric(x);{x: null};false +isNumeric(x);{x: true};false;question: number(true) converts to 1 but isNumeric(true) is false +isNumeric(x);{x: false};false;question: number(false) converts to 0 but isNumeric(false) is false +isNumeric(x);{x: 0};true +isNumeric(x);{x: -1};true +isNumeric(x);{x: 1.5};true +isNumeric(x);{x: 79228162514264337593543950335};true +isNumeric(x);{x: ''};false +isNumeric(x);{x: 'abc'};false +isNumeric(x);{x: '12.5'};true +isNumeric(x);{x: 'żółw'};false +isNumeric(x);{x: []};false +isNumeric(x);{x: [1, 2]};false +isNumeric(x);{x: ['a']};false +isNumeric(x);{x: [[1]]};false +isNumeric(x);{x: {}};false +isNumeric(x);{x: {a: 1}};false +isNumeric(x);{};false +# number: argument 1 is any +# number (literal) +number(null);;!error;"question: null does not convert; could be null or 0" +number(true);;1 +number(false);;0 +number(0);;0 +number(-1);;-1 +number(1.5);;1.5 +number(79228162514264337593543950335);;79228162514264337593543950335 +number('');;!error +number('abc');;!error +number('12.5');;12.5 +number('żółw');;!error +number([]);;!error +number([1, 2]);;!error +number(['a']);;!error +number([[1]]);;!error +number({});;!error +number({a: 1});;!error +number(d('2024-01-01'));;!error +number([1..3]);;!error +# number (input) +number(x);{x: null};!error;"question: null does not convert; could be null or 0" +number(x);{x: true};1 +number(x);{x: false};0 +number(x);{x: 0};0 +number(x);{x: -1};-1 +number(x);{x: 1.5};1.5 +number(x);{x: 79228162514264337593543950335};79228162514264337593543950335 +number(x);{x: ''};!error +number(x);{x: 'abc'};!error +number(x);{x: '12.5'};12.5 +number(x);{x: 'żółw'};!error +number(x);{x: []};!error +number(x);{x: [1, 2]};!error +number(x);{x: ['a']};!error +number(x);{x: [[1]]};!error +number(x);{x: {}};!error +number(x);{x: {a: 1}};!error +number(x);{};!error;"question: null does not convert; could be null or 0" diff --git a/core/expression/tests/spec/standard/10-05-dates.csv b/core/expression/tests/spec/standard/10-05-dates.csv new file mode 100644 index 00000000..0148ca57 --- /dev/null +++ b/core/expression/tests/spec/standard/10-05-dates.csv @@ -0,0 +1,178 @@ +expression (string);input (json 5);output (json 5);note +# d: argument 1 is any +# d arg 1 (literal) +d(null);;'Invalid date' +d(true);;'Invalid date' +d(false);;'Invalid date' +d(0);;'1970-01-01T00:00:00Z' +d(-1);;'1969-12-31T23:59:59Z' +d(1.5);;'1970-01-01T00:00:00Z' +d(79228162514264337593543950335);;'Invalid date' +d('');;'Invalid date' +d('abc');;'Invalid date' +d('12.5');;'Invalid date' +d('żółw');;'Invalid date' +d([]);;'Invalid date' +d([1, 2]);;'Invalid date' +d(['a']);;'Invalid date' +d([[1]]);;'Invalid date' +d({});;'Invalid date' +d({a: 1});;'Invalid date' +d(d('2024-01-01'));;'2024-01-01T00:00:00Z' +d([1..3]);;'Invalid date' +# d arg 1 (input) +d(x);{x: null};'Invalid date' +d(x);{x: true};'Invalid date' +d(x);{x: false};'Invalid date' +d(x);{x: 0};'1970-01-01T00:00:00Z' +d(x);{x: -1};'1969-12-31T23:59:59Z' +d(x);{x: 1.5};'1970-01-01T00:00:00Z' +d(x);{x: 79228162514264337593543950335};'Invalid date' +d(x);{x: ''};'Invalid date' +d(x);{x: 'abc'};'Invalid date' +d(x);{x: '12.5'};'Invalid date' +d(x);{x: 'żółw'};'Invalid date' +d(x);{x: []};'Invalid date' +d(x);{x: [1, 2]};'Invalid date' +d(x);{x: ['a']};'Invalid date' +d(x);{x: [[1]]};'Invalid date' +d(x);{x: {}};'Invalid date' +d(x);{x: {a: 1}};'Invalid date' +d(x);{};'Invalid date' +# d: argument 1 with an explicit zone +# d arg 1 zoned (literal) +d(null, 'UTC');;'Invalid date' +d(true, 'UTC');;'Invalid date' +d(false, 'UTC');;'Invalid date' +d(0, 'UTC');;'1970-01-01T00:00:00Z' +d(-1, 'UTC');;'1969-12-31T23:59:59Z' +d(1.5, 'UTC');;'1970-01-01T00:00:00Z' +d(79228162514264337593543950335, 'UTC');;'Invalid date' +d('', 'UTC');;'Invalid date' +d('abc', 'UTC');;'Invalid date' +d('12.5', 'UTC');;'Invalid date' +d('żółw', 'UTC');;'Invalid date' +d([], 'UTC');;'Invalid date' +d([1, 2], 'UTC');;'Invalid date' +d(['a'], 'UTC');;'Invalid date' +d([[1]], 'UTC');;'Invalid date' +d({}, 'UTC');;'Invalid date' +d({a: 1}, 'UTC');;'Invalid date' +d(d('2024-01-01'), 'UTC');;'2024-01-01T00:00:00Z' +d([1..3], 'UTC');;'Invalid date' +# d arg 1 zoned (input) +d(x, 'UTC');{x: null};'Invalid date' +d(x, 'UTC');{x: true};'Invalid date' +d(x, 'UTC');{x: false};'Invalid date' +d(x, 'UTC');{x: 0};'1970-01-01T00:00:00Z' +d(x, 'UTC');{x: -1};'1969-12-31T23:59:59Z' +d(x, 'UTC');{x: 1.5};'1970-01-01T00:00:00Z' +d(x, 'UTC');{x: 79228162514264337593543950335};'Invalid date' +d(x, 'UTC');{x: ''};'Invalid date' +d(x, 'UTC');{x: 'abc'};'Invalid date' +d(x, 'UTC');{x: '12.5'};'Invalid date' +d(x, 'UTC');{x: 'żółw'};'Invalid date' +d(x, 'UTC');{x: []};'Invalid date' +d(x, 'UTC');{x: [1, 2]};'Invalid date' +d(x, 'UTC');{x: ['a']};'Invalid date' +d(x, 'UTC');{x: [[1]]};'Invalid date' +d(x, 'UTC');{x: {}};'Invalid date' +d(x, 'UTC');{x: {a: 1}};'Invalid date' +d(x, 'UTC');{};'Invalid date' +# d: argument 2 is a time zone name string +# d arg 2 (literal) +d('2024-01-01', null);;!error +d('2024-01-01', true);;!error +d('2024-01-01', false);;!error +d('2024-01-01', 0);;!error +d('2024-01-01', -1);;!error +d('2024-01-01', 1.5);;!error +d('2024-01-01', 79228162514264337593543950335);;!error +d('2024-01-01', '');;!error +d('2024-01-01', 'abc');;!error +d('2024-01-01', '12.5');;!error +d('2024-01-01', 'żółw');;!error +d('2024-01-01', []);;!error +d('2024-01-01', [1, 2]);;!error +d('2024-01-01', ['a']);;!error +d('2024-01-01', [[1]]);;!error +d('2024-01-01', {});;!error +d('2024-01-01', {a: 1});;!error +d('2024-01-01', d('2024-01-01'));;!error +d('2024-01-01', [1..3]);;!error +# d arg 2 (input) +d('2024-01-01', x);{x: null};!error +d('2024-01-01', x);{x: true};!error +d('2024-01-01', x);{x: false};!error +d('2024-01-01', x);{x: 0};!error +d('2024-01-01', x);{x: -1};!error +d('2024-01-01', x);{x: 1.5};!error +d('2024-01-01', x);{x: 79228162514264337593543950335};!error +d('2024-01-01', x);{x: ''};!error +d('2024-01-01', x);{x: 'abc'};!error +d('2024-01-01', x);{x: '12.5'};!error +d('2024-01-01', x);{x: 'żółw'};!error +d('2024-01-01', x);{x: []};!error +d('2024-01-01', x);{x: [1, 2]};!error +d('2024-01-01', x);{x: ['a']};!error +d('2024-01-01', x);{x: [[1]]};!error +d('2024-01-01', x);{x: {}};!error +d('2024-01-01', x);{x: {a: 1}};!error +d('2024-01-01', x);{};!error +# d: both arguments from input +d(x, y);{x: '2024-01-01', y: 'UTC'};'2024-01-01T00:00:00Z' +d(x, y);{x: '2024-01-01', y: 'Europe/Berlin'};'2024-01-01T00:00:00+01:00' +d(x, y);{x: '2024-01-01', y: 'Mars/Base'};!error +d(x, y);{x: '2024-01-01', y: 1};!error +d(x, y);{x: '2024-01-01', y: null};!error +d(x, y);{x: '2024-01-01'};!error +d(x, y);{x: null, y: 'UTC'};'Invalid date' +d(x, y);{x: 0, y: 'UTC'};'1970-01-01T00:00:00Z' +# d: validity for every argument class +# d isValid (literal) +d(null).isValid();;false +d(true).isValid();;false +d(false).isValid();;false +d(0).isValid();;true +d(-1).isValid();;true +d(1.5).isValid();;true +d(79228162514264337593543950335).isValid();;false +d('').isValid();;false +d('abc').isValid();;false +d('12.5').isValid();;false +d('żółw').isValid();;false +d([]).isValid();;false +d([1, 2]).isValid();;false +d(['a']).isValid();;false +d([[1]]).isValid();;false +d({}).isValid();;false +d({a: 1}).isValid();;false +d(d('2024-01-01')).isValid();;true +d([1..3]).isValid();;false +# d isValid (input) +d(x).isValid();{x: null};false +d(x).isValid();{x: true};false +d(x).isValid();{x: false};false +d(x).isValid();{x: 0};true +d(x).isValid();{x: -1};true +d(x).isValid();{x: 1.5};true +d(x).isValid();{x: 79228162514264337593543950335};false +d(x).isValid();{x: ''};false +d(x).isValid();{x: 'abc'};false +d(x).isValid();{x: '12.5'};false +d(x).isValid();{x: 'żółw'};false +d(x).isValid();{x: []};false +d(x).isValid();{x: [1, 2]};false +d(x).isValid();{x: ['a']};false +d(x).isValid();{x: [[1]]};false +d(x).isValid();{x: {}};false +d(x).isValid();{x: {a: 1}};false +d(x).isValid();{};false +# conversion to a zone past chrono's range +d('-262143-01-01').tz('Pacific/Kiritimati');;!error;bug: the date is valid but converting it to its string form panics in chrono (local time out of range) +d(s).tz('Pacific/Kiritimati');{s: '-262143-01-01'};!error;bug: the date is valid but converting it to its string form panics in chrono (local time out of range) +d(s).tz('Pacific/Kiritimati').isValid();{s: '-262143-01-01'};true +d(s).tz('Pacific/Kiritimati').isValid();{s: '2024-01-01'};true +d(n, 'Pacific/Kiritimati');{n: -8334601228800000};!error;bug: the date is valid but converting it to its string form panics in chrono (local time out of range) +d(n, 'Pacific/Kiritimati').year();{n: -8334601228800000};-262144 +d(n, 'Pacific/Kiritimati').year();{n: 0};1969 diff --git a/core/expression/tests/spec/standard/10-06-closures.csv b/core/expression/tests/spec/standard/10-06-closures.csv new file mode 100644 index 00000000..5f8b1c0e --- /dev/null +++ b/core/expression/tests/spec/standard/10-06-closures.csv @@ -0,0 +1,301 @@ +expression (string);input (json 5);output (json 5);note +# map: argument 1 is array | interval +map([1..3], #);;[1, 2, 3] +map(d('2024-01-01'), #);;!error +map(x, #);{x: null};!error;question: a null list is an error rather than an empty list +map(x, #);{x: true};!error +map(x, #);{x: false};!error +map(x, #);{x: 0};!error +map(x, #);{x: -1};!error +map(x, #);{x: 1.5};!error +map(x, #);{x: 79228162514264337593543950335};!error +map(x, #);{x: ''};!error +map(x, #);{x: 'abc'};!error +map(x, #);{x: '12.5'};!error +map(x, #);{x: 'żółw'};!error +map(x, #);{x: []};[] +map(x, #);{x: [1, 2]};[1, 2] +map(x, #);{x: ['a']};['a'] +map(x, #);{x: [[1]]};[[1]] +map(x, #);{x: {}};!error +map(x, #);{x: {a: 1}};!error +map(x, #);{};!error;question: a null list is an error rather than an empty list +# filter: argument 1 is array | interval +filter([1..3], true);;[1, 2, 3] +filter(d('2024-01-01'), true);;!error +filter(x, true);{x: null};!error +filter(x, true);{x: true};!error +filter(x, true);{x: false};!error +filter(x, true);{x: 0};!error +filter(x, true);{x: -1};!error +filter(x, true);{x: 1.5};!error +filter(x, true);{x: 79228162514264337593543950335};!error +filter(x, true);{x: ''};!error +filter(x, true);{x: 'abc'};!error +filter(x, true);{x: '12.5'};!error +filter(x, true);{x: 'żółw'};!error +filter(x, true);{x: []};[] +filter(x, true);{x: [1, 2]};[1, 2] +filter(x, true);{x: ['a']};['a'] +filter(x, true);{x: [[1]]};[[1]] +filter(x, true);{x: {}};!error +filter(x, true);{x: {a: 1}};!error +filter(x, true);{};!error +# flatMap: argument 1 is array | interval +flatMap([1..3], #);;[1, 2, 3] +flatMap(d('2024-01-01'), #);;!error +flatMap(x, #);{x: null};!error +flatMap(x, #);{x: true};!error +flatMap(x, #);{x: false};!error +flatMap(x, #);{x: 0};!error +flatMap(x, #);{x: -1};!error +flatMap(x, #);{x: 1.5};!error +flatMap(x, #);{x: 79228162514264337593543950335};!error +flatMap(x, #);{x: ''};!error +flatMap(x, #);{x: 'abc'};!error +flatMap(x, #);{x: '12.5'};!error +flatMap(x, #);{x: 'żółw'};!error +flatMap(x, #);{x: []};[] +flatMap(x, #);{x: [1, 2]};[1, 2] +flatMap(x, #);{x: ['a']};['a'] +flatMap(x, #);{x: [[1]]};[1] +flatMap(x, #);{x: {}};!error +flatMap(x, #);{x: {a: 1}};!error +flatMap(x, #);{};!error +# all: argument 1 is array | interval +all([1..3], true);;true +all(d('2024-01-01'), true);;!error +all(x, true);{x: null};!error +all(x, true);{x: true};!error +all(x, true);{x: false};!error +all(x, true);{x: 0};!error +all(x, true);{x: -1};!error +all(x, true);{x: 1.5};!error +all(x, true);{x: 79228162514264337593543950335};!error +all(x, true);{x: ''};!error +all(x, true);{x: 'abc'};!error +all(x, true);{x: '12.5'};!error +all(x, true);{x: 'żółw'};!error +all(x, true);{x: []};true +all(x, true);{x: [1, 2]};true +all(x, true);{x: ['a']};true +all(x, true);{x: [[1]]};true +all(x, true);{x: {}};!error +all(x, true);{x: {a: 1}};!error +all(x, true);{};!error +# some: argument 1 is array | interval +some([1..3], true);;true +some(d('2024-01-01'), true);;!error +some(x, true);{x: null};!error +some(x, true);{x: true};!error +some(x, true);{x: false};!error +some(x, true);{x: 0};!error +some(x, true);{x: -1};!error +some(x, true);{x: 1.5};!error +some(x, true);{x: 79228162514264337593543950335};!error +some(x, true);{x: ''};!error +some(x, true);{x: 'abc'};!error +some(x, true);{x: '12.5'};!error +some(x, true);{x: 'żółw'};!error +some(x, true);{x: []};false +some(x, true);{x: [1, 2]};true +some(x, true);{x: ['a']};true +some(x, true);{x: [[1]]};true +some(x, true);{x: {}};!error +some(x, true);{x: {a: 1}};!error +some(x, true);{};!error +# none: argument 1 is array | interval +none([1..3], true);;false +none(d('2024-01-01'), true);;!error +none(x, true);{x: null};!error +none(x, true);{x: true};!error +none(x, true);{x: false};!error +none(x, true);{x: 0};!error +none(x, true);{x: -1};!error +none(x, true);{x: 1.5};!error +none(x, true);{x: 79228162514264337593543950335};!error +none(x, true);{x: ''};!error +none(x, true);{x: 'abc'};!error +none(x, true);{x: '12.5'};!error +none(x, true);{x: 'żółw'};!error +none(x, true);{x: []};true +none(x, true);{x: [1, 2]};false +none(x, true);{x: ['a']};false +none(x, true);{x: [[1]]};false +none(x, true);{x: {}};!error +none(x, true);{x: {a: 1}};!error +none(x, true);{};!error +# one: argument 1 is array | interval +one([1..3], true);;false +one(d('2024-01-01'), true);;!error +one(x, true);{x: null};!error +one(x, true);{x: true};!error +one(x, true);{x: false};!error +one(x, true);{x: 0};!error +one(x, true);{x: -1};!error +one(x, true);{x: 1.5};!error +one(x, true);{x: 79228162514264337593543950335};!error +one(x, true);{x: ''};!error +one(x, true);{x: 'abc'};!error +one(x, true);{x: '12.5'};!error +one(x, true);{x: 'żółw'};!error +one(x, true);{x: []};false +one(x, true);{x: [1, 2]};false +one(x, true);{x: ['a']};true +one(x, true);{x: [[1]]};true +one(x, true);{x: {}};!error +one(x, true);{x: {a: 1}};!error +one(x, true);{};!error +# count: argument 1 is array | interval +count([1..3], true);;3 +count(d('2024-01-01'), true);;!error +count(x, true);{x: null};!error +count(x, true);{x: true};!error +count(x, true);{x: false};!error +count(x, true);{x: 0};!error +count(x, true);{x: -1};!error +count(x, true);{x: 1.5};!error +count(x, true);{x: 79228162514264337593543950335};!error +count(x, true);{x: ''};!error +count(x, true);{x: 'abc'};!error +count(x, true);{x: '12.5'};!error +count(x, true);{x: 'żółw'};!error +count(x, true);{x: []};0 +count(x, true);{x: [1, 2]};2 +count(x, true);{x: ['a']};1 +count(x, true);{x: [[1]]};1 +count(x, true);{x: {}};!error +count(x, true);{x: {a: 1}};!error +count(x, true);{};!error +# filter: predicate result must be bool +filter([1, 2], p);{p: null};!error;question: a null predicate result is an error, not falsy +filter([1, 2], p);{p: true};[1, 2] +filter([1, 2], p);{p: false};[] +filter([1, 2], p);{p: 0};!error +filter([1, 2], p);{p: -1};!error +filter([1, 2], p);{p: 1.5};!error +filter([1, 2], p);{p: 79228162514264337593543950335};!error +filter([1, 2], p);{p: ''};!error +filter([1, 2], p);{p: 'abc'};!error +filter([1, 2], p);{p: '12.5'};!error +filter([1, 2], p);{p: 'żółw'};!error +filter([1, 2], p);{p: []};!error +filter([1, 2], p);{p: [1, 2]};!error +filter([1, 2], p);{p: ['a']};!error +filter([1, 2], p);{p: [[1]]};!error +filter([1, 2], p);{p: {}};!error +filter([1, 2], p);{p: {a: 1}};!error +filter([1, 2], d('2024-01-01'));;!error +# all: predicate result must be bool +all([1, 2], p);{p: null};!error;question: a null predicate result is an error, not falsy +all([1, 2], p);{p: true};true +all([1, 2], p);{p: false};false +all([1, 2], p);{p: 0};!error +all([1, 2], p);{p: -1};!error +all([1, 2], p);{p: 1.5};!error +all([1, 2], p);{p: 79228162514264337593543950335};!error +all([1, 2], p);{p: ''};!error +all([1, 2], p);{p: 'abc'};!error +all([1, 2], p);{p: '12.5'};!error +all([1, 2], p);{p: 'żółw'};!error +all([1, 2], p);{p: []};!error +all([1, 2], p);{p: [1, 2]};!error +all([1, 2], p);{p: ['a']};!error +all([1, 2], p);{p: [[1]]};!error +all([1, 2], p);{p: {}};!error +all([1, 2], p);{p: {a: 1}};!error +all([1, 2], d('2024-01-01'));;!error +# some: predicate result must be bool +some([1, 2], p);{p: null};!error;question: a null predicate result is an error, not falsy +some([1, 2], p);{p: true};true +some([1, 2], p);{p: false};false +some([1, 2], p);{p: 0};!error +some([1, 2], p);{p: -1};!error +some([1, 2], p);{p: 1.5};!error +some([1, 2], p);{p: 79228162514264337593543950335};!error +some([1, 2], p);{p: ''};!error +some([1, 2], p);{p: 'abc'};!error +some([1, 2], p);{p: '12.5'};!error +some([1, 2], p);{p: 'żółw'};!error +some([1, 2], p);{p: []};!error +some([1, 2], p);{p: [1, 2]};!error +some([1, 2], p);{p: ['a']};!error +some([1, 2], p);{p: [[1]]};!error +some([1, 2], p);{p: {}};!error +some([1, 2], p);{p: {a: 1}};!error +some([1, 2], d('2024-01-01'));;!error +# none: predicate result must be bool +none([1, 2], p);{p: null};!error;question: a null predicate result is an error, not falsy +none([1, 2], p);{p: true};false +none([1, 2], p);{p: false};true +none([1, 2], p);{p: 0};!error +none([1, 2], p);{p: -1};!error +none([1, 2], p);{p: 1.5};!error +none([1, 2], p);{p: 79228162514264337593543950335};!error +none([1, 2], p);{p: ''};!error +none([1, 2], p);{p: 'abc'};!error +none([1, 2], p);{p: '12.5'};!error +none([1, 2], p);{p: 'żółw'};!error +none([1, 2], p);{p: []};!error +none([1, 2], p);{p: [1, 2]};!error +none([1, 2], p);{p: ['a']};!error +none([1, 2], p);{p: [[1]]};!error +none([1, 2], p);{p: {}};!error +none([1, 2], p);{p: {a: 1}};!error +none([1, 2], d('2024-01-01'));;!error +# one: predicate result must be bool +one([1, 2], p);{p: null};!error;question: a null predicate result is an error, not falsy +one([1, 2], p);{p: true};false +one([1, 2], p);{p: false};false +one([1, 2], p);{p: 0};!error +one([1, 2], p);{p: -1};!error +one([1, 2], p);{p: 1.5};!error +one([1, 2], p);{p: 79228162514264337593543950335};!error +one([1, 2], p);{p: ''};!error +one([1, 2], p);{p: 'abc'};!error +one([1, 2], p);{p: '12.5'};!error +one([1, 2], p);{p: 'żółw'};!error +one([1, 2], p);{p: []};!error +one([1, 2], p);{p: [1, 2]};!error +one([1, 2], p);{p: ['a']};!error +one([1, 2], p);{p: [[1]]};!error +one([1, 2], p);{p: {}};!error +one([1, 2], p);{p: {a: 1}};!error +one([1, 2], d('2024-01-01'));;!error +# count: predicate result must be bool +count([1, 2], p);{p: null};!error;question: a null predicate result is an error, not falsy +count([1, 2], p);{p: true};2 +count([1, 2], p);{p: false};0 +count([1, 2], p);{p: 0};!error +count([1, 2], p);{p: -1};!error +count([1, 2], p);{p: 1.5};!error +count([1, 2], p);{p: 79228162514264337593543950335};!error +count([1, 2], p);{p: ''};!error +count([1, 2], p);{p: 'abc'};!error +count([1, 2], p);{p: '12.5'};!error +count([1, 2], p);{p: 'żółw'};!error +count([1, 2], p);{p: []};!error +count([1, 2], p);{p: [1, 2]};!error +count([1, 2], p);{p: ['a']};!error +count([1, 2], p);{p: [[1]]};!error +count([1, 2], p);{p: {}};!error +count([1, 2], p);{p: {a: 1}};!error +count([1, 2], d('2024-01-01'));;!error +# map and flatMap: body result is any +map([1, 2], p);{p: null};[null, null] +map([1, 2], p);{p: true};[true, true] +map([1, 2], p);{p: false};[false, false] +map([1, 2], p);{p: 0};[0, 0] +map([1, 2], p);{p: -1};[-1, -1] +map([1, 2], p);{p: 1.5};[1.5, 1.5] +map([1, 2], p);{p: 79228162514264337593543950335};[79228162514264337593543950335, 79228162514264337593543950335] +map([1, 2], p);{p: ''};['', ''] +map([1, 2], p);{p: 'abc'};['abc', 'abc'] +map([1, 2], p);{p: '12.5'};['12.5', '12.5'] +map([1, 2], p);{p: 'żółw'};['żółw', 'żółw'] +map([1, 2], p);{p: []};[[], []] +map([1, 2], p);{p: [1, 2]};[[1, 2], [1, 2]] +map([1, 2], p);{p: ['a']};[['a'], ['a']] +map([1, 2], p);{p: [[1]]};[[[1]], [[1]]] +map([1, 2], p);{p: {}};[{}, {}] +map([1, 2], p);{p: {a: 1}};[{a: 1}, {a: 1}] diff --git a/core/expression/tests/spec/standard/10-07-arity.csv b/core/expression/tests/spec/standard/10-07-arity.csv new file mode 100644 index 00000000..a53412d1 --- /dev/null +++ b/core/expression/tests/spec/standard/10-07-arity.csv @@ -0,0 +1,495 @@ +expression (string);input (json 5);output (json 5);note +# len: arity +len('ab');;2 +len();;!error +len('ab', 1);;!error +len('ab', 1, 1);;!error +true ? 1 : len('ab', 1);;!error +true ? 1 : len();;!error +true ? 1 : len(5);;1 +len(5);;!error +len(x, x);{x: 1};!error +len(x, x);{x: 'a'};!error +len(x, x);{x: [1]};!error +len(x, x);{};!error +# contains: arity +contains('ab', 'a');;true +contains();;!error +contains('ab');;!error +contains('ab', 'a', 1);;!error +contains('ab', 'a', 1, 1);;!error +true ? 1 : contains('ab', 'a', 1);;!error +true ? 1 : contains();;!error +true ? 1 : contains(5, 5);;1 +contains(5, 5);;!error +contains(x, x, x);{x: 1};!error +contains(x, x, x);{x: 'a'};!error +contains(x, x, x);{x: [1]};!error +contains(x, x, x);{};!error +# flatten: arity +flatten([[1]]);;[1] +flatten();;!error +flatten([[1]], 1);;!error +flatten([[1]], 1, 1);;!error +true ? 1 : flatten([[1]], 1);;!error +true ? 1 : flatten();;!error +true ? 1 : flatten(5);;1 +flatten(5);;!error +flatten(x, x);{x: 1};!error +flatten(x, x);{x: 'a'};!error +flatten(x, x);{x: [1]};!error +flatten(x, x);{};!error +# merge: arity +merge([[1]]);;[1] +merge();;!error +merge([[1]], 1);;!error +merge([[1]], 1, 1);;!error +true ? 1 : merge([[1]], 1);;!error +true ? 1 : merge();;!error +true ? 1 : merge(5);;1 +merge(5);;!error +merge(x, x);{x: 1};!error +merge(x, x);{x: 'a'};!error +merge(x, x);{x: [1]};!error +merge(x, x);{};!error +# mergeDeep: arity +mergeDeep([{a: 1}]);;{a: 1} +mergeDeep();;!error +mergeDeep([{a: 1}], 1);;!error +mergeDeep([{a: 1}], 1, 1);;!error +true ? 1 : mergeDeep([{a: 1}], 1);;!error +true ? 1 : mergeDeep();;!error +true ? 1 : mergeDeep(5);;1 +mergeDeep(5);;!error +mergeDeep(x, x);{x: 1};!error +mergeDeep(x, x);{x: 'a'};!error +mergeDeep(x, x);{x: [1]};!error +mergeDeep(x, x);{};!error +# upper: arity +upper('ab');;'AB' +upper();;!error +upper('ab', 1);;!error +upper('ab', 1, 1);;!error +true ? 1 : upper('ab', 1);;!error +true ? 1 : upper();;!error +true ? 1 : upper(5);;1 +upper(5);;!error +upper(x, x);{x: 1};!error +upper(x, x);{x: 'a'};!error +upper(x, x);{x: [1]};!error +upper(x, x);{};!error +# lower: arity +lower('AB');;'ab' +lower();;!error +lower('AB', 1);;!error +lower('AB', 1, 1);;!error +true ? 1 : lower('AB', 1);;!error +true ? 1 : lower();;!error +true ? 1 : lower(5);;1 +lower(5);;!error +lower(x, x);{x: 1};!error +lower(x, x);{x: 'a'};!error +lower(x, x);{x: [1]};!error +lower(x, x);{};!error +# trim: arity +trim(' a ');;'a' +trim();;!error +trim(' a ', 1);;!error +trim(' a ', 1, 1);;!error +true ? 1 : trim(' a ', 1);;!error +true ? 1 : trim();;!error +true ? 1 : trim(5);;1 +trim(5);;!error +trim(x, x);{x: 1};!error +trim(x, x);{x: 'a'};!error +trim(x, x);{x: [1]};!error +trim(x, x);{};!error +# startsWith: arity +startsWith('ab', 'a');;true +startsWith();;!error +startsWith('ab');;!error +startsWith('ab', 'a', 1);;!error +startsWith('ab', 'a', 1, 1);;!error +true ? 1 : startsWith('ab', 'a', 1);;!error +true ? 1 : startsWith();;!error +true ? 1 : startsWith(5, 5);;1 +startsWith(5, 5);;!error +startsWith(x, x, x);{x: 1};!error +startsWith(x, x, x);{x: 'a'};!error +startsWith(x, x, x);{x: [1]};!error +startsWith(x, x, x);{};!error +# endsWith: arity +endsWith('ab', 'b');;true +endsWith();;!error +endsWith('ab');;!error +endsWith('ab', 'b', 1);;!error +endsWith('ab', 'b', 1, 1);;!error +true ? 1 : endsWith('ab', 'b', 1);;!error +true ? 1 : endsWith();;!error +true ? 1 : endsWith(5, 5);;1 +endsWith(5, 5);;!error +endsWith(x, x, x);{x: 1};!error +endsWith(x, x, x);{x: 'a'};!error +endsWith(x, x, x);{x: [1]};!error +endsWith(x, x, x);{};!error +# matches: arity +matches('ab', 'a');;true +matches();;!error +matches('ab');;!error +matches('ab', 'a', 1);;!error +matches('ab', 'a', 1, 1);;!error +true ? 1 : matches('ab', 'a', 1);;!error +true ? 1 : matches();;!error +true ? 1 : matches(5, 5);;1 +matches(5, 5);;!error +matches(x, x, x);{x: 1};!error +matches(x, x, x);{x: 'a'};!error +matches(x, x, x);{x: [1]};!error +matches(x, x, x);{};!error +# extract: arity +extract('ab', 'a');;['a'] +extract();;!error +extract('ab');;!error +extract('ab', 'a', 1);;!error +extract('ab', 'a', 1, 1);;!error +true ? 1 : extract('ab', 'a', 1);;!error +true ? 1 : extract();;!error +true ? 1 : extract(5, 5);;1 +extract(5, 5);;!error +extract(x, x, x);{x: 1};!error +extract(x, x, x);{x: 'a'};!error +extract(x, x, x);{x: [1]};!error +extract(x, x, x);{};!error +# split: arity +split('a,b', ',');;['a', 'b'] +split();;!error +split('a,b');;!error +split('a,b', ',', 1);;!error +split('a,b', ',', 1, 1);;!error +true ? 1 : split('a,b', ',', 1);;!error +true ? 1 : split();;!error +true ? 1 : split(5, 5);;1 +split(5, 5);;!error +split(x, x, x);{x: 1};!error +split(x, x, x);{x: 'a'};!error +split(x, x, x);{x: [1]};!error +split(x, x, x);{};!error +# fuzzyMatch: arity +fuzzyMatch('ab', 'ab');;1 +fuzzyMatch();;!error +fuzzyMatch('ab');;!error +fuzzyMatch('ab', 'ab', 1);;!error +fuzzyMatch('ab', 'ab', 1, 1);;!error +true ? 1 : fuzzyMatch('ab', 'ab', 1);;!error +true ? 1 : fuzzyMatch();;!error +true ? 1 : fuzzyMatch(5, 5);;1 +fuzzyMatch(5, 5);;!error +fuzzyMatch(x, x, x);{x: 1};!error +fuzzyMatch(x, x, x);{x: 'a'};!error +fuzzyMatch(x, x, x);{x: [1]};!error +fuzzyMatch(x, x, x);{};!error +# abs: arity +abs(-1);;1 +abs();;!error +abs(-1, 1);;!error +abs(-1, 1, 1);;!error +true ? 1 : abs(-1, 1);;!error +true ? 1 : abs();;!error +true ? 1 : abs('a');;1 +abs('a');;!error +abs(x, x);{x: 1};!error +abs(x, x);{x: 'a'};!error +abs(x, x);{x: [1]};!error +abs(x, x);{};!error +# floor: arity +floor(1.5);;1 +floor();;!error +floor(1.5, 1);;!error +floor(1.5, 1, 1);;!error +true ? 1 : floor(1.5, 1);;!error +true ? 1 : floor();;!error +true ? 1 : floor('a');;1 +floor('a');;!error +floor(x, x);{x: 1};!error +floor(x, x);{x: 'a'};!error +floor(x, x);{x: [1]};!error +floor(x, x);{};!error +# ceil: arity +ceil(1.5);;2 +ceil();;!error +ceil(1.5, 1);;!error +ceil(1.5, 1, 1);;!error +true ? 1 : ceil(1.5, 1);;!error +true ? 1 : ceil();;!error +true ? 1 : ceil('a');;1 +ceil('a');;!error +ceil(x, x);{x: 1};!error +ceil(x, x);{x: 'a'};!error +ceil(x, x);{x: [1]};!error +ceil(x, x);{};!error +# round: arity +round(1.25);;1 +round(1.25, 1);;1.3 +round();;!error +round(1.25, 1, 1);;!error +round(1.25, 1, 1, 1);;!error +true ? 1 : round(1.25, 1, 1);;!error +true ? 1 : round();;!error +true ? 1 : round('a');;1 +round('a');;!error +round(x, x, x);{x: 1};!error +round(x, x, x);{x: 'a'};!error +round(x, x, x);{x: [1]};!error +round(x, x, x);{};!error +# trunc: arity +trunc(1.25);;1 +trunc(1.25, 1);;1.2 +trunc();;!error +trunc(1.25, 1, 1);;!error +trunc(1.25, 1, 1, 1);;!error +true ? 1 : trunc(1.25, 1, 1);;!error +true ? 1 : trunc();;!error +true ? 1 : trunc('a');;1 +trunc('a');;!error +trunc(x, x, x);{x: 1};!error +trunc(x, x, x);{x: 'a'};!error +trunc(x, x, x);{x: [1]};!error +trunc(x, x, x);{};!error +# rand: arity +rand(0);;0 +rand();;!error +rand(0, 1);;!error +rand(0, 1, 1);;!error +true ? 1 : rand(0, 1);;!error +true ? 1 : rand();;!error +true ? 1 : rand('a');;1 +rand('a');;!error +rand(x, x);{x: 1};!error +rand(x, x);{x: 'a'};!error +rand(x, x);{x: [1]};!error +rand(x, x);{};!error +# sum: arity +sum([1, 2]);;3 +sum();;!error +sum([1, 2], 1);;!error +sum([1, 2], 1, 1);;!error +true ? 1 : sum([1, 2], 1);;!error +true ? 1 : sum();;!error +true ? 1 : sum('a');;1 +sum('a');;!error +sum(x, x);{x: 1};!error +sum(x, x);{x: 'a'};!error +sum(x, x);{x: [1]};!error +sum(x, x);{};!error +# avg: arity +avg([1, 2]);;1.5 +avg();;!error +avg([1, 2], 1);;!error +avg([1, 2], 1, 1);;!error +true ? 1 : avg([1, 2], 1);;!error +true ? 1 : avg();;!error +true ? 1 : avg('a');;1 +avg('a');;!error +avg(x, x);{x: 1};!error +avg(x, x);{x: 'a'};!error +avg(x, x);{x: [1]};!error +avg(x, x);{};!error +# min: arity +min([1, 2]);;1 +min();;!error +min([1, 2], 1);;!error +min([1, 2], 1, 1);;!error +true ? 1 : min([1, 2], 1);;!error +true ? 1 : min();;!error +true ? 1 : min('a');;1 +min('a');;!error +min(x, x);{x: 1};!error +min(x, x);{x: 'a'};!error +min(x, x);{x: [1]};!error +min(x, x);{};!error +# max: arity +max([1, 2]);;2 +max();;!error +max([1, 2], 1);;!error +max([1, 2], 1, 1);;!error +true ? 1 : max([1, 2], 1);;!error +true ? 1 : max();;!error +true ? 1 : max('a');;1 +max('a');;!error +max(x, x);{x: 1};!error +max(x, x);{x: 'a'};!error +max(x, x);{x: [1]};!error +max(x, x);{};!error +# median: arity +median([1, 2]);;1.5 +median();;!error +median([1, 2], 1);;!error +median([1, 2], 1, 1);;!error +true ? 1 : median([1, 2], 1);;!error +true ? 1 : median();;!error +true ? 1 : median('a');;1 +median('a');;!error +median(x, x);{x: 1};!error +median(x, x);{x: 'a'};!error +median(x, x);{x: [1]};!error +median(x, x);{};!error +# mode: arity +mode([1, 1, 2]);;1 +mode();;!error +mode([1, 1, 2], 1);;!error +mode([1, 1, 2], 1, 1);;!error +true ? 1 : mode([1, 1, 2], 1);;!error +true ? 1 : mode();;!error +true ? 1 : mode('a');;1 +mode('a');;!error +mode(x, x);{x: 1};!error +mode(x, x);{x: 'a'};!error +mode(x, x);{x: [1]};!error +mode(x, x);{};!error +# type: arity +type(1);;'number' +type();;!error +type(1, 1);;!error +type(1, 1, 1);;!error +true ? 1 : type(1, 1);;!error +true ? 1 : type();;!error +type(x, x);{x: 1};!error +type(x, x);{x: 'a'};!error +type(x, x);{x: [1]};!error +type(x, x);{};!error +# string: arity +string(1);;'1' +string();;!error +string(1, 1);;!error +string(1, 1, 1);;!error +true ? 1 : string(1, 1);;!error +true ? 1 : string();;!error +true ? 1 : string([]);;1 +string([]);;!error +string(x, x);{x: 1};!error +string(x, x);{x: 'a'};!error +string(x, x);{x: [1]};!error +string(x, x);{};!error +# bool: arity +bool(1);;true +bool();;!error +bool(1, 1);;!error +bool(1, 1, 1);;!error +true ? 1 : bool(1, 1);;!error +true ? 1 : bool();;!error +bool(x, x);{x: 1};!error +bool(x, x);{x: 'a'};!error +bool(x, x);{x: [1]};!error +bool(x, x);{};!error +# isNumeric: arity +isNumeric(1);;true +isNumeric();;!error +isNumeric(1, 1);;!error +isNumeric(1, 1, 1);;!error +true ? 1 : isNumeric(1, 1);;!error +true ? 1 : isNumeric();;!error +isNumeric(x, x);{x: 1};!error +isNumeric(x, x);{x: 'a'};!error +isNumeric(x, x);{x: [1]};!error +isNumeric(x, x);{};!error +# number: arity +number('1');;1 +number();;!error +number('1', 1);;!error +number('1', 1, 1);;!error +true ? 1 : number('1', 1);;!error +true ? 1 : number();;!error +true ? 1 : number('a');;1 +number('a');;!error +number(x, x);{x: 1};!error +number(x, x);{x: 'a'};!error +number(x, x);{x: [1]};!error +number(x, x);{};!error +# keys: arity +keys({a: 1});;['a'] +keys();;!error +keys({a: 1}, 1);;!error +keys({a: 1}, 1, 1);;!error +true ? 1 : keys({a: 1}, 1);;!error +true ? 1 : keys();;!error +true ? 1 : keys(5);;1 +keys(5);;!error +keys(x, x);{x: 1};!error +keys(x, x);{x: 'a'};!error +keys(x, x);{x: [1]};!error +keys(x, x);{};!error +# values: arity +values({a: 1});;[1] +values();;!error +values({a: 1}, 1);;!error +values({a: 1}, 1, 1);;!error +true ? 1 : values({a: 1}, 1);;!error +true ? 1 : values();;!error +true ? 1 : values(5);;1 +values(5);;!error +values(x, x);{x: 1};!error +values(x, x);{x: 'a'};!error +values(x, x);{x: [1]};!error +values(x, x);{};!error +# d: arity +d();;'2025-03-20T10:15:30Z' +d('2024-01-01');;'2024-01-01T00:00:00Z' +d('2024-01-01', 'UTC');;'2024-01-01T00:00:00Z' +d('2024-01-01', 'UTC', 1);;!error +d('2024-01-01', 'UTC', 1, 1);;!error +true ? 1 : d('2024-01-01', 'UTC', 1);;!error +true ? 1 : d('2024-01-01', 5);;1 +d('2024-01-01', 5);;!error +d(x, x, x);{x: 1};!error +d(x, x, x);{x: 'a'};!error +d(x, x, x);{x: [1]};!error +d(x, x, x);{};!error +# closures: arity +map();;!error +map([1]);;!error +map([1], true, 1);;!error +true ? 1 : map([1]);;!error +true ? 1 : map(5, true);;1 +filter();;!error +filter([1]);;!error +filter([1], true, 1);;!error +true ? 1 : filter([1]);;!error +true ? 1 : filter(5, true);;1 +flatMap();;!error +flatMap([1]);;!error +flatMap([1], true, 1);;!error +true ? 1 : flatMap([1]);;!error +true ? 1 : flatMap(5, true);;1 +all();;!error +all([1]);;!error +all([1], true, 1);;!error +true ? 1 : all([1]);;!error +true ? 1 : all(5, true);;1 +some();;!error +some([1]);;!error +some([1], true, 1);;!error +true ? 1 : some([1]);;!error +true ? 1 : some(5, true);;1 +none();;!error +none([1]);;!error +none([1], true, 1);;!error +true ? 1 : none([1]);;!error +true ? 1 : none(5, true);;1 +one();;!error +one([1]);;!error +one([1], true, 1);;!error +true ? 1 : one([1]);;!error +true ? 1 : one(5, true);;1 +count();;!error +count([1]);;!error +count([1], true, 1);;!error +true ? 1 : count([1]);;!error +true ? 1 : count(5, true);;1 +# unknown functions are compile errors +foo(1);;!error +true ? 1 : foo(1);;!error +Upper(1);;!error +LEN([]);;!error +date2(1);;!error +x(1);;!error +x(1);{x: 1};!error diff --git a/core/expression/tests/spec/standard/11-01-null-operators.csv b/core/expression/tests/spec/standard/11-01-null-operators.csv new file mode 100644 index 00000000..a6d0c50a --- /dev/null +++ b/core/expression/tests/spec/standard/11-01-null-operators.csv @@ -0,0 +1,486 @@ +expression (string);input (json 5);output (json 5);note +# A nested path that is null, missing or crosses a non-object reads as null, and null is an arithmetic error +o.a.b + 1;{o: {a: {b: 3}}};4 +o.a.b + 1;{o: {a: {b: 0.5}}};1.5 +o.a.b + 1;{o: {a: {b: null}}};!error +o.a.b + 1;{o: {a: {}}};!error +o.a.b + 1;{o: {a: null}};!error +o.a.b + 1;{o: {a: 5}};!error +o.a.b + 1;{o: null};!error +o.a.b + 1;{};!error +o.a.b + 1;{o: {a: {b: '7'}}};!error +o.a.b * 2;{o: {a: {b: 3}}};6 +o.a.b * 2;{o: {a: {b: 0.5}}};1.0 +o.a.b * 2;{o: {a: {b: null}}};!error +o.a.b * 2;{o: {a: {}}};!error +o.a.b * 2;{o: {a: null}};!error +o.a.b * 2;{o: {a: 5}};!error +o.a.b * 2;{o: null};!error +o.a.b * 2;{};!error +o.a.b * 2;{o: {a: {b: '7'}}};!error +6 / o.a.b;{o: {a: {b: 3}}};2 +6 / o.a.b;{o: {a: {b: 0.5}}};12 +6 / o.a.b;{o: {a: {b: null}}};!error +6 / o.a.b;{o: {a: {}}};!error +6 / o.a.b;{o: {a: null}};!error +6 / o.a.b;{o: {a: 5}};!error +6 / o.a.b;{o: null};!error +6 / o.a.b;{};!error +6 / o.a.b;{o: {a: {b: '7'}}};!error +# Ordering against a null or missing path is an error, equality is not +o.a.b > 1;{o: {a: {b: 3}}};true +o.a.b > 1;{o: {a: {b: 0.5}}};false +o.a.b > 1;{o: {a: {b: null}}};!error +o.a.b > 1;{o: {a: {}}};!error +o.a.b > 1;{o: {a: null}};!error +o.a.b > 1;{o: {a: 5}};!error +o.a.b > 1;{o: null};!error +o.a.b > 1;{};!error +o.a.b > 1;{o: {a: {b: '7'}}};!error +o.a.b == 3;{o: {a: {b: 3}}};true +o.a.b == 3;{o: {a: {b: 0.5}}};false +o.a.b == 3;{o: {a: {b: null}}};false +o.a.b == 3;{o: {a: {}}};false +o.a.b == 3;{o: {a: null}};false +o.a.b == 3;{o: {a: 5}};false +o.a.b == 3;{o: null};false +o.a.b == 3;{};false +o.a.b == 3;{o: {a: {b: '7'}}};false +o.a.b != null;{o: {a: {b: 3}}};true +o.a.b != null;{o: {a: {b: 0.5}}};true +o.a.b != null;{o: {a: {b: null}}};false +o.a.b != null;{o: {a: {}}};false +o.a.b != null;{o: {a: null}};false +o.a.b != null;{o: {a: 5}};false +o.a.b != null;{o: null};false +o.a.b != null;{};false +o.a.b != null;{o: {a: {b: '7'}}};true +# Coalescing a nested path +o.a.b ?? 0;{o: {a: {b: 3}}};3 +o.a.b ?? 0;{o: {a: {b: 0.5}}};0.5 +o.a.b ?? 0;{o: {a: {b: null}}};0 +o.a.b ?? 0;{o: {a: {}}};0 +o.a.b ?? 0;{o: {a: null}};0 +o.a.b ?? 0;{o: {a: 5}};0 +o.a.b ?? 0;{o: null};0 +o.a.b ?? 0;{};0 +o.a.b ?? 0;{o: {a: {b: '7'}}};'7' +(o.a.b ?? 0) + 1;{o: {a: {b: 3}}};4 +(o.a.b ?? 0) + 1;{o: {a: {b: 0.5}}};1.5 +(o.a.b ?? 0) + 1;{o: {a: {b: null}}};1 +(o.a.b ?? 0) + 1;{o: {a: {}}};1 +(o.a.b ?? 0) + 1;{o: {a: null}};1 +(o.a.b ?? 0) + 1;{o: {a: 5}};1 +(o.a.b ?? 0) + 1;{o: null};1 +(o.a.b ?? 0) + 1;{};1 +(o.a.b ?? 0) + 1;{o: {a: {b: '7'}}};!error +o.a.b ?? o.a ?? o ?? 'root';{o: {a: {b: 3}}};3 +o.a.b ?? o.a ?? o ?? 'root';{o: {a: {b: 0.5}}};0.5 +o.a.b ?? o.a ?? o ?? 'root';{o: {a: {b: null}}};{b: null} +o.a.b ?? o.a ?? o ?? 'root';{o: {a: {}}};{} +o.a.b ?? o.a ?? o ?? 'root';{o: {a: null}};{a: null} +o.a.b ?? o.a ?? o ?? 'root';{o: {a: 5}};5 +o.a.b ?? o.a ?? o ?? 'root';{o: null};'root' +o.a.b ?? o.a ?? o ?? 'root';{};'root' +o.a.b ?? o.a ?? o ?? 'root';{o: {a: {b: '7'}}};'7' +# Guarding a nested path +o.a.b == null ? 0 : o.a.b * 2;{o: {a: {b: 3}}};6 +o.a.b == null ? 0 : o.a.b * 2;{o: {a: {b: 0.5}}};1.0 +o.a.b == null ? 0 : o.a.b * 2;{o: {a: {b: null}}};0 +o.a.b == null ? 0 : o.a.b * 2;{o: {a: {}}};0 +o.a.b == null ? 0 : o.a.b * 2;{o: {a: null}};0 +o.a.b == null ? 0 : o.a.b * 2;{o: {a: 5}};0 +o.a.b == null ? 0 : o.a.b * 2;{o: null};0 +o.a.b == null ? 0 : o.a.b * 2;{};0 +o.a.b == null ? 0 : o.a.b * 2;{o: {a: {b: '7'}}};!error +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: {b: 3}}};true +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: {b: 0.5}}};false +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: {b: null}}};false +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: {}}};false +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: null}};false +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: 5}};false +type(o.a.b) == 'number' and o.a.b > 1;{o: null};false +type(o.a.b) == 'number' and o.a.b > 1;{};false +type(o.a.b) == 'number' and o.a.b > 1;{o: {a: {b: '7'}}};false +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: {b: 3}}};true +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: {b: 0.5}}};false +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: {b: null}}};true +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: {}}};true +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: null}};true +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: 5}};true +type(o.a.b) != 'number' or o.a.b > 1;{o: null};true +type(o.a.b) != 'number' or o.a.b > 1;{};true +type(o.a.b) != 'number' or o.a.b > 1;{o: {a: {b: '7'}}};true +o.a.b != null and o.a.b > 1;{o: {a: {b: 3}}};true +o.a.b != null and o.a.b > 1;{o: {a: {b: 0.5}}};false +o.a.b != null and o.a.b > 1;{o: {a: {b: null}}};false +o.a.b != null and o.a.b > 1;{o: {a: {}}};false +o.a.b != null and o.a.b > 1;{o: {a: null}};false +o.a.b != null and o.a.b > 1;{o: {a: 5}};false +o.a.b != null and o.a.b > 1;{o: null};false +o.a.b != null and o.a.b > 1;{};false +o.a.b != null and o.a.b > 1;{o: {a: {b: '7'}}};!error +# Nested path inside values that do not compute +type(o.a.b);{o: {a: {b: 3}}};'number' +type(o.a.b);{o: {a: {b: 0.5}}};'number' +type(o.a.b);{o: {a: {b: null}}};'null' +type(o.a.b);{o: {a: {}}};'null' +type(o.a.b);{o: {a: null}};'null' +type(o.a.b);{o: {a: 5}};'null' +type(o.a.b);{o: null};'null' +type(o.a.b);{};'null' +type(o.a.b);{o: {a: {b: '7'}}};'string' +[o.a.b, o.a];{o: {a: {b: 3}}};[3, {b: 3}] +[o.a.b, o.a];{o: {a: {b: 0.5}}};[0.5, {b: 0.5}] +[o.a.b, o.a];{o: {a: {b: null}}};[null, {b: null}] +[o.a.b, o.a];{o: {a: {}}};[null, {}] +[o.a.b, o.a];{o: {a: null}};[null, null] +[o.a.b, o.a];{o: {a: 5}};[null, 5] +[o.a.b, o.a];{o: null};[null, null] +{v: o.a.b};{o: {a: {b: 3}}};{v: 3} +{v: o.a.b};{o: {a: {b: 0.5}}};{v: 0.5} +{v: o.a.b};{o: {a: {b: null}}};{v: null} +{v: o.a.b};{o: {a: {}}};{v: null} +{v: o.a.b};{o: {a: null}};{v: null} +{v: o.a.b};{o: {a: 5}};{v: null} +{v: o.a.b};{o: null};{v: null} +o.a.b in [3, null];{o: {a: {b: 3}}};true +o.a.b in [3, null];{o: {a: {b: 0.5}}};false +o.a.b in [3, null];{o: {a: {b: null}}};true +o.a.b in [3, null];{o: {a: {}}};true +o.a.b in [3, null];{o: {a: null}};true +o.a.b in [3, null];{o: {a: 5}};true +o.a.b in [3, null];{o: null};true +o.a.b in [3, null];{};true +o.a.b in [3, null];{o: {a: {b: '7'}}};false +`v=${o.a.b}`;{o: {a: {b: 3}}};'v=3' +`v=${o.a.b}`;{o: {a: {b: 0.5}}};'v=0.5' +`v=${o.a.b}`;{o: {a: {b: null}}};'v=null' +`v=${o.a.b}`;{o: {a: {}}};'v=null' +`v=${o.a.b}`;{o: {a: null}};'v=null' +`v=${o.a.b}`;{o: {a: 5}};'v=null' +`v=${o.a.b}`;{o: null};'v=null' +`v=${o.a.b}`;{};'v=null' +`v=${o.a.b}`;{o: {a: {b: '7'}}};'v=7' +# Out-of-range and non-numeric indexes read as null and flow onward +o.list[i] + 1;{o: {list: [10, 20]}, i: 0};11 +o.list[i] + 1;{o: {list: [10, 20]}, i: 1};21 +o.list[i] + 1;{o: {list: [10, 20]}, i: 2};!error +o.list[i] + 1;{o: {list: [10, 20]}, i: null};!error +o.list[i] + 1;{o: {list: [10, 20]}};!error +o.list[i] + 1;{o: {list: [10, 20]}, i: '1'};!error +o.list[i] + 1;{o: {list: [null, 20]}, i: 0};!error +o.list[i] + 1;{o: {list: null}, i: 0};!error +o.list[i] + 1;{o: {}, i: 0};!error +o.list[i] + 1;{o: {list: 'ab'}, i: 1};!error +o.list[i] + 1;{i: 0};!error +o.list[i] ?? -1;{o: {list: [10, 20]}, i: 0};10 +o.list[i] ?? -1;{o: {list: [10, 20]}, i: 1};20 +o.list[i] ?? -1;{o: {list: [10, 20]}, i: 2};-1 +o.list[i] ?? -1;{o: {list: [10, 20]}, i: null};-1 +o.list[i] ?? -1;{o: {list: [10, 20]}};-1 +o.list[i] ?? -1;{o: {list: [10, 20]}, i: '1'};-1 +o.list[i] ?? -1;{o: {list: [null, 20]}, i: 0};-1 +o.list[i] ?? -1;{o: {list: null}, i: 0};-1 +o.list[i] ?? -1;{o: {}, i: 0};-1 +o.list[i] ?? -1;{o: {list: 'ab'}, i: 1};'b' +o.list[i] ?? -1;{i: 0};-1 +(o.list[i] ?? 0) * 2;{o: {list: [10, 20]}, i: 0};20 +(o.list[i] ?? 0) * 2;{o: {list: [10, 20]}, i: 1};40 +(o.list[i] ?? 0) * 2;{o: {list: [10, 20]}, i: 2};0 +(o.list[i] ?? 0) * 2;{o: {list: [10, 20]}, i: null};0 +(o.list[i] ?? 0) * 2;{o: {list: [10, 20]}};0 +(o.list[i] ?? 0) * 2;{o: {list: [10, 20]}, i: '1'};0 +(o.list[i] ?? 0) * 2;{o: {list: [null, 20]}, i: 0};0 +(o.list[i] ?? 0) * 2;{o: {list: null}, i: 0};0 +(o.list[i] ?? 0) * 2;{o: {}, i: 0};0 +(o.list[i] ?? 0) * 2;{o: {list: 'ab'}, i: 1};!error +(o.list[i] ?? 0) * 2;{i: 0};0 +o.list[i] == null;{o: {list: [10, 20]}, i: 0};false +o.list[i] == null;{o: {list: [10, 20]}, i: 1};false +o.list[i] == null;{o: {list: [10, 20]}, i: 2};true +o.list[i] == null;{o: {list: [10, 20]}, i: null};true +o.list[i] == null;{o: {list: [10, 20]}};true +o.list[i] == null;{o: {list: [10, 20]}, i: '1'};true +o.list[i] == null;{o: {list: [null, 20]}, i: 0};true +o.list[i] == null;{o: {list: null}, i: 0};true +o.list[i] == null;{o: {}, i: 0};true +o.list[i] == null;{o: {list: 'ab'}, i: 1};false +o.list[i] == null;{i: 0};true +`${o.list[i]}`;{o: {list: [10, 20]}, i: 0};'10' +`${o.list[i]}`;{o: {list: [10, 20]}, i: 1};'20' +`${o.list[i]}`;{o: {list: [10, 20]}, i: 2};'null' +`${o.list[i]}`;{o: {list: [10, 20]}, i: null};'null' +`${o.list[i]}`;{o: {list: [10, 20]}};'null' +`${o.list[i]}`;{o: {list: [10, 20]}, i: '1'};'null' +`${o.list[i]}`;{o: {list: [null, 20]}, i: 0};'null' +`${o.list[i]}`;{o: {list: null}, i: 0};'null' +`${o.list[i]}`;{o: {}, i: 0};'null' +`${o.list[i]}`;{o: {list: 'ab'}, i: 1};'b' +`${o.list[i]}`;{i: 0};'null' +o.list[i] > 15 ? 'big' : 'small';{o: {list: [10, 20]}, i: 0};'small' +o.list[i] > 15 ? 'big' : 'small';{o: {list: [10, 20]}, i: 1};'big' +o.list[i] > 15 ? 'big' : 'small';{o: {list: [10, 20]}, i: 2};!error +o.list[i] > 15 ? 'big' : 'small';{o: {list: [10, 20]}, i: null};!error +o.list[i] > 15 ? 'big' : 'small';{o: {list: [10, 20]}};!error +o.list[i] > 15 ? 'big' : 'small';{o: {list: [10, 20]}, i: '1'};!error +o.list[i] > 15 ? 'big' : 'small';{o: {list: [null, 20]}, i: 0};!error +o.list[i] > 15 ? 'big' : 'small';{o: {list: null}, i: 0};!error +o.list[i] > 15 ? 'big' : 'small';{o: {}, i: 0};!error +o.list[i] > 15 ? 'big' : 'small';{o: {list: 'ab'}, i: 1};!error +o.list[i] > 15 ? 'big' : 'small';{i: 0};!error +# Division by zero yields null, which then fails in arithmetic but coalesces, compares for equality and interpolates +a / b + 1;{a: 6, b: 3};3 +a / b + 1;{a: 1, b: 4};1.25 +a / b + 1;{a: 1, b: 0};!error +a / b + 1;{a: 0, b: 0};!error +a / b + 1;{a: -5, b: 0.0};!error +a / b + 1;{a: 1, b: null};!error +a / b + 1;{a: 1};!error +a / b + 1;{a: null, b: 2};!error +a / b + 1;{a: 1, b: '2'};!error +-(a / b);{a: 6, b: 3};-2 +-(a / b);{a: 1, b: 4};-0.25 +-(a / b);{a: 1, b: 0};!error +-(a / b);{a: 0, b: 0};!error +-(a / b);{a: -5, b: 0.0};!error +-(a / b);{a: 1, b: null};!error +-(a / b);{a: 1};!error +-(a / b);{a: null, b: 2};!error +-(a / b);{a: 1, b: '2'};!error +(a / b) > 1;{a: 6, b: 3};true +(a / b) > 1;{a: 1, b: 4};false +(a / b) > 1;{a: 1, b: 0};!error +(a / b) > 1;{a: 0, b: 0};!error +(a / b) > 1;{a: -5, b: 0.0};!error +(a / b) > 1;{a: 1, b: null};!error +(a / b) > 1;{a: 1};!error +(a / b) > 1;{a: null, b: 2};!error +(a / b) > 1;{a: 1, b: '2'};!error +(a / b) == null;{a: 6, b: 3};false +(a / b) == null;{a: 1, b: 4};false +(a / b) == null;{a: 1, b: 0};true +(a / b) == null;{a: 0, b: 0};true +(a / b) == null;{a: -5, b: 0.0};true +(a / b) == null;{a: 1, b: null};!error +(a / b) == null;{a: 1};!error +(a / b) == null;{a: null, b: 2};!error +(a / b) == null;{a: 1, b: '2'};!error +(a / b) ?? 0;{a: 6, b: 3};2 +(a / b) ?? 0;{a: 1, b: 4};0.25 +(a / b) ?? 0;{a: 1, b: 0};0 +(a / b) ?? 0;{a: 0, b: 0};0 +(a / b) ?? 0;{a: -5, b: 0.0};0 +(a / b) ?? 0;{a: 1, b: null};!error +(a / b) ?? 0;{a: 1};!error +(a / b) ?? 0;{a: null, b: 2};!error +(a / b) ?? 0;{a: 1, b: '2'};!error +((a / b) ?? 0) + 1;{a: 6, b: 3};3 +((a / b) ?? 0) + 1;{a: 1, b: 4};1.25 +((a / b) ?? 0) + 1;{a: 1, b: 0};1 +((a / b) ?? 0) + 1;{a: 0, b: 0};1 +((a / b) ?? 0) + 1;{a: -5, b: 0.0};1 +((a / b) ?? 0) + 1;{a: 1, b: null};!error +((a / b) ?? 0) + 1;{a: 1};!error +((a / b) ?? 0) + 1;{a: null, b: 2};!error +((a / b) ?? 0) + 1;{a: 1, b: '2'};!error +type(a / b);{a: 6, b: 3};'number' +type(a / b);{a: 1, b: 4};'number' +type(a / b);{a: 1, b: 0};'null' +type(a / b);{a: 0, b: 0};'null' +type(a / b);{a: -5, b: 0.0};'null' +type(a / b);{a: 1, b: null};!error +type(a / b);{a: 1};!error +type(a / b);{a: null, b: 2};!error +type(a / b);{a: 1, b: '2'};!error +string(a / b);{a: 6, b: 3};'2' +string(a / b);{a: 1, b: 4};'0.25' +string(a / b);{a: 1, b: 0};'null' +string(a / b);{a: 0, b: 0};'null' +string(a / b);{a: -5, b: 0.0};'null' +`r=${a / b}`;{a: 6, b: 3};'r=2' +`r=${a / b}`;{a: 1, b: 4};'r=0.25' +`r=${a / b}`;{a: 1, b: 0};'r=null' +`r=${a / b}`;{a: 0, b: 0};'r=null' +`r=${a / b}`;{a: -5, b: 0.0};'r=null' +{r: a / b};{a: 6, b: 3};{r: 2} +{r: a / b};{a: 1, b: 4};{r: 0.25} +{r: a / b};{a: 1, b: 0};{r: null} +{r: a / b};{a: 0, b: 0};{r: null} +{r: a / b};{a: -5, b: 0.0};{r: null} +{r: a / b};{a: 1, b: null};!error +{r: a / b};{a: 1};!error +{r: a / b};{a: null, b: 2};!error +{r: a / b};{a: 1, b: '2'};!error +round(a / b);{a: 6, b: 3};2 +round(a / b);{a: 1, b: 4};0 +round(a / b);{a: 1, b: 0};!error +round(a / b);{a: 0, b: 0};!error +round(a / b);{a: -5, b: 0.0};!error +round(a / b);{a: 1, b: null};!error +round(a / b);{a: 1};!error +round(a / b);{a: null, b: 2};!error +round(a / b);{a: 1, b: '2'};!error +(a / b) == null ? 'undefined' : a / b;{a: 6, b: 3};2 +(a / b) == null ? 'undefined' : a / b;{a: 1, b: 4};0.25 +(a / b) == null ? 'undefined' : a / b;{a: 1, b: 0};'undefined' +(a / b) == null ? 'undefined' : a / b;{a: 0, b: 0};'undefined' +(a / b) == null ? 'undefined' : a / b;{a: -5, b: 0.0};'undefined' +(a / b) == null ? 'undefined' : a / b;{a: 1, b: null};!error +(a / b) == null ? 'undefined' : a / b;{a: 1};!error +(a / b) == null ? 'undefined' : a / b;{a: null, b: 2};!error +(a / b) == null ? 'undefined' : a / b;{a: 1, b: '2'};!error +# Modulo by zero yields null too +a % b + 1;{a: 6, b: 3};1 +a % b + 1;{a: 1, b: 4};2 +a % b + 1;{a: 1, b: 0};!error +a % b + 1;{a: 0, b: 0};!error +a % b + 1;{a: -5, b: 0.0};!error +a % b + 1;{a: 1, b: null};!error +a % b + 1;{a: 1};!error +a % b + 1;{a: null, b: 2};!error +a % b + 1;{a: 1, b: '2'};!error +(a % b) ?? -1;{a: 6, b: 3};0 +(a % b) ?? -1;{a: 1, b: 4};1 +(a % b) ?? -1;{a: 1, b: 0};-1 +(a % b) ?? -1;{a: 0, b: 0};-1 +(a % b) ?? -1;{a: -5, b: 0.0};-1 +(a % b) ?? -1;{a: 1, b: null};!error +(a % b) ?? -1;{a: 1};!error +(a % b) ?? -1;{a: null, b: 2};!error +(a % b) ?? -1;{a: 1, b: '2'};!error +a % b == 0;{a: 6, b: 3};true +a % b == 0;{a: 1, b: 4};false +a % b == 0;{a: 1, b: 0};false +a % b == 0;{a: 0, b: 0};false +a % b == 0;{a: -5, b: 0.0};false +a % b == 0;{a: 1, b: null};!error +a % b == 0;{a: 1};!error +a % b == 0;{a: null, b: 2};!error +a % b == 0;{a: 1, b: '2'};!error +# Null and error are distinct: null is a value, a type error aborts +v + 1;{v: null};!error +v + 1;{};!error +v + 1;{v: {}};!error +v + 1;{v: []};!error +v + 1;{v: ''};!error +v + 1;{v: 0};1 +v + 1;{v: false};!error +v + 1;{v: 'x'};!error +v + 1;{v: [null]};!error +v + 1;{v: {a: null}};!error +v ?? 1;{v: null};1 +v ?? 1;{};1 +v ?? 1;{v: {}};{} +v ?? 1;{v: []};[] +v ?? 1;{v: ''};'' +v ?? 1;{v: 0};0 +v ?? 1;{v: false};false +v ?? 1;{v: 'x'};'x' +v ?? 1;{v: [null]};[null] +v ?? 1;{v: {a: null}};{a: null} +v == null;{v: null};true +v == null;{};true +v == null;{v: {}};false +v == null;{v: []};false +v == null;{v: ''};false +v == null;{v: 0};false +v == null;{v: false};false +v == null;{v: 'x'};false +v == null;{v: [null]};false +v == null;{v: {a: null}};false +type(v);{v: null};'null' +type(v);{};'null' +type(v);{v: {}};'object' +type(v);{v: []};'array' +type(v);{v: ''};'string' +type(v);{v: 0};'number' +type(v);{v: false};'bool' +type(v);{v: 'x'};'string' +type(v);{v: [null]};'array' +type(v);{v: {a: null}};'object' +v != null ? 'set' : 'unset';{v: null};'unset' +v != null ? 'set' : 'unset';{};'unset' +v != null ? 'set' : 'unset';{v: {}};'set' +v != null ? 'set' : 'unset';{v: []};'set' +v != null ? 'set' : 'unset';{v: ''};'set' +v != null ? 'set' : 'unset';{v: 0};'set' +v != null ? 'set' : 'unset';{v: false};'set' +v != null ? 'set' : 'unset';{v: 'x'};'set' +v != null ? 'set' : 'unset';{v: [null]};'set' +v != null ? 'set' : 'unset';{v: {a: null}};'set' +v.a;{v: null};null +v.a;{};null +v.a;{v: {}};null +v.a;{v: []};null +v.a;{v: ''};null +v.a;{v: 0};null +v.a;{v: false};null +v.a;{v: 'x'};null +v.a;{v: [null]};null +v.a;{v: {a: null}};null +v[0];{v: null};null +v[0];{};null +v[0];{v: {}};null +v[0];{v: []};null +v[0];{v: ''};null +v[0];{v: 0};null +v[0];{v: false};null +v[0];{v: 'x'};'x' +v[0];{v: [null]};null +v[0];{v: {a: null}};null +# Literal null in operators +null + null;;!error +null - 0;;!error +0 * null;;!error +null / 1;;!error +1 / null;;!error +null % 2;;!error +null ^ 2;;!error +2 ^ null;;!error +null + 'a';;!error +null + [];;!error +-null;;!error +null < null;;!error +null >= 0;;!error +0 > null;;!error +null == null;;true +null != null;;false +null == 0;;false +null == 'null';;false +null == false;;false +null == [];;false +null == {};;false +[] == null;;false +null != false;;true +null ?? null;;null +(null);;null +[null][0];;null +[null][0] ?? 1;;1 +({a: null}).a ?? 2;;2 +({a: null}).a.b;;null +({}).a;;null +({}).a.b.c ?? 3;;3 +[][0];;null +[][0] + 1;;!error +[1, 2][5] ?? 0;;0 +('abc')[9] ?? '-';;'-' +# An error anywhere in an evaluated operand aborts the whole expression +1 + {} + 1;;!error +(1 + {}) ?? 1;;!error +(1 + {}) == null;;!error +[1 + {}] ?? [];;!error +type(1 + {});;!error +string(1 + {});;!error +-(1 + {});;!error +(1 / 0) + (1 + {});;!error +(1 + {}) / 0;;!error +(1 / 0) ?? 7;;7 +(1 / 0) ?? (2 / 0) ?? 9;;9 +(2 / 0) ?? (1 / 0);;null +(1 / 0) == (2 / 0);;true +(1 / 0) != 0;;true +[1 / 0, 0 / 0, 1 % 0];;[null, null, null] +{x: 1 / 0};;{x: null} +`${1 / 0}|${0 % 0}`;;'null|null' +1 / 0 ?? (1 + {});;null;question: ?? binds tighter than / so this is 1 / (0 ?? (1 + {})); JS/C# would evaluate (1 / 0) ?? (1 + {}) and fail diff --git a/core/expression/tests/spec/standard/11-02-null-control-flow.csv b/core/expression/tests/spec/standard/11-02-null-control-flow.csv new file mode 100644 index 00000000..e16d01fa --- /dev/null +++ b/core/expression/tests/spec/standard/11-02-null-control-flow.csv @@ -0,0 +1,481 @@ +expression (string);input (json 5);output (json 5);note +# The right operand of and/or is not evaluated when the left decides, so its errors are skipped +x != null and x > 10;{x: 20};true +x != null and x > 10;{x: 5};false +x != null and x > 10;{x: 0};false +x != null and x > 10;{x: null};false +x != null and x > 10;{};false +x != null and x > 10;{x: 'abc'};!error +x != null and x > 10;{x: true};!error +x == null or x > 10;{x: 20};true +x == null or x > 10;{x: 5};false +x == null or x > 10;{x: 0};false +x == null or x > 10;{x: null};true +x == null or x > 10;{};true +x == null or x > 10;{x: 'abc'};!error +x == null or x > 10;{x: true};!error +type(x) == 'number' and x > 10;{x: 20};true +type(x) == 'number' and x > 10;{x: 5};false +type(x) == 'number' and x > 10;{x: 0};false +type(x) == 'number' and x > 10;{x: null};false +type(x) == 'number' and x > 10;{};false +type(x) == 'number' and x > 10;{x: 'abc'};false +type(x) == 'number' and x > 10;{x: true};false +type(x) == 'string' and len(x) > 2;{x: 20};false +type(x) == 'string' and len(x) > 2;{x: 5};false +type(x) == 'string' and len(x) > 2;{x: 0};false +type(x) == 'string' and len(x) > 2;{x: null};false +type(x) == 'string' and len(x) > 2;{};false +type(x) == 'string' and len(x) > 2;{x: 'abc'};true +type(x) == 'string' and len(x) > 2;{x: true};false +type(x) != 'string' or upper(x) == 'ABC';{x: 20};true +type(x) != 'string' or upper(x) == 'ABC';{x: 5};true +type(x) != 'string' or upper(x) == 'ABC';{x: 0};true +type(x) != 'string' or upper(x) == 'ABC';{x: null};true +type(x) != 'string' or upper(x) == 'ABC';{};true +type(x) != 'string' or upper(x) == 'ABC';{x: 'abc'};true +type(x) != 'string' or upper(x) == 'ABC';{x: true};true +x == 0 or 10 / x > 1;{x: 20};false +x == 0 or 10 / x > 1;{x: 5};true +x == 0 or 10 / x > 1;{x: 0};true +x == 0 or 10 / x > 1;{x: null};!error +x == 0 or 10 / x > 1;{};!error +x == 0 or 10 / x > 1;{x: 'abc'};!error +x == 0 or 10 / x > 1;{x: true};!error +x > 10 or x + {} > 0;{x: 20};true +x > 10 or x + {} > 0;{x: 5};!error +x > 10 or x + {} > 0;{x: 0};!error +x > 10 or x + {} > 0;{x: null};!error +x > 10 or x + {} > 0;{};!error +x > 10 or x + {} > 0;{x: 'abc'};!error +x > 10 or x + {} > 0;{x: true};!error +x < 10 and x + {} > 0;{x: 20};false +x < 10 and x + {} > 0;{x: 5};!error +x < 10 and x + {} > 0;{x: 0};!error +x < 10 and x + {} > 0;{x: null};!error +x < 10 and x + {} > 0;{};!error +x < 10 and x + {} > 0;{x: 'abc'};!error +x < 10 and x + {} > 0;{x: true};!error +x != null and x != 0 and 100 / x < 10;{x: 20};true +x != null and x != 0 and 100 / x < 10;{x: 5};false +x != null and x != 0 and 100 / x < 10;{x: 0};false +x != null and x != 0 and 100 / x < 10;{x: null};false +x != null and x != 0 and 100 / x < 10;{};false +x != null and x != 0 and 100 / x < 10;{x: 'abc'};!error +x != null and x != 0 and 100 / x < 10;{x: true};!error +# The left operand of and/or must be a boolean even when it is null +x and true;{x: 20};!error +x and true;{x: 5};!error +x and true;{x: 0};!error +x and true;{x: null};!error +x and true;{};!error +x and true;{x: 'abc'};!error +x and true;{x: true};true +x or false;{x: 20};!error +x or false;{x: 5};!error +x or false;{x: 0};!error +x or false;{x: null};!error +x or false;{};!error +x or false;{x: 'abc'};!error +x or false;{x: true};true +# A null right operand of and/or +true and b;{b: true};true +true and b;{b: false};false +true and b;{b: null};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +true and b;{};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +true and b;{b: 1};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +true and b;{b: 'true'};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false and b;{b: true};false +false and b;{b: false};false +false and b;{b: null};false +false and b;{};false +false and b;{b: 1};false +false and b;{b: 'true'};false +true or b;{b: true};true +true or b;{b: false};true +true or b;{b: null};true +true or b;{};true +true or b;{b: 1};true +true or b;{b: 'true'};true +false or b;{b: true};true +false or b;{b: false};false +false or b;{b: null};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or b;{};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or b;{b: 1};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or b;{b: 'true'};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or (b ?? false);{b: true};true +false or (b ?? false);{b: false};false +false or (b ?? false);{b: null};false +false or (b ?? false);{};false +false or (b ?? false);{b: 1};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +false or (b ?? false);{b: 'true'};!error;bug: a non-boolean right operand is returned as is, while the same value on the left is an error +not b;{b: true};false +not b;{b: false};true +not b;{b: null};!error +not b;{};!error +not b;{b: 1};!error +not b;{b: 'true'};!error +not (b ?? false);{b: true};false +not (b ?? false);{b: false};true +not (b ?? false);{b: null};true +not (b ?? false);{};true +not (b ?? false);{b: 1};!error +not (b ?? false);{b: 'true'};!error +b == true ? 'yes' : 'no';{b: true};'yes' +b == true ? 'yes' : 'no';{b: false};'no' +b == true ? 'yes' : 'no';{b: null};'no' +b == true ? 'yes' : 'no';{};'no' +b == true ? 'yes' : 'no';{b: 1};'no' +b == true ? 'yes' : 'no';{b: 'true'};'no' +b ? 'yes' : 'no';{b: true};'yes' +b ? 'yes' : 'no';{b: false};'no' +b ? 'yes' : 'no';{b: null};!error +b ? 'yes' : 'no';{};!error +b ? 'yes' : 'no';{b: 1};!error +b ? 'yes' : 'no';{b: 'true'};!error +b != false ? 'on' : 'off';{b: true};'on' +b != false ? 'on' : 'off';{b: false};'off' +b != false ? 'on' : 'off';{b: null};'on' +b != false ? 'on' : 'off';{};'on' +b != false ? 'on' : 'off';{b: 1};'on' +b != false ? 'on' : 'off';{b: 'true'};'on' +# Literal errors on the skipped side of and/or +false and (1 + {});;false +true or (1 + {});;true +false and upper(1);;false +true or len(5) > 0;;true +false and null > 1;;false +true or null < 1;;true +false and null;;false +true or null;;true +false and x.y.z > 1;;false +(false and 1 + {}) or true;;true +false and (1 + {}) or false;;false +true or (1 + {}) and false;;true +not (false and 1 + {});;true +true and (false or (true or 1 + {}));;true +true and (1 + {});;!error +false or (1 + {});;!error +true and null > 1;;!error +false or null < 1;;!error +# Ternary evaluates only the chosen branch +x == null ? 'none' : x * 2;{x: 20};40 +x == null ? 'none' : x * 2;{x: 5};10 +x == null ? 'none' : x * 2;{x: 0};0 +x == null ? 'none' : x * 2;{x: null};'none' +x == null ? 'none' : x * 2;{};'none' +x == null ? 'none' : x * 2;{x: 'abc'};!error +x == null ? 'none' : x * 2;{x: true};!error +type(x) == 'string' ? upper(x) : x;{x: 20};20 +type(x) == 'string' ? upper(x) : x;{x: 5};5 +type(x) == 'string' ? upper(x) : x;{x: 0};0 +type(x) == 'string' ? upper(x) : x;{x: null};null +type(x) == 'string' ? upper(x) : x;{};null +type(x) == 'string' ? upper(x) : x;{x: 'abc'};'ABC' +type(x) == 'string' ? upper(x) : x;{x: true};true +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{x: 20};20 +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{x: 5};5 +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{x: 0};0 +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{x: null};-1 +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{};-1 +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{x: 'abc'};3 +type(x) == 'array' ? x[0] : type(x) == 'string' ? len(x) : x ?? -1;{x: true};true +(x ?? 0) > 10 ? 'big' : 'small';{x: 20};'big' +(x ?? 0) > 10 ? 'big' : 'small';{x: 5};'small' +(x ?? 0) > 10 ? 'big' : 'small';{x: 0};'small' +(x ?? 0) > 10 ? 'big' : 'small';{x: null};'small' +(x ?? 0) > 10 ? 'big' : 'small';{};'small' +(x ?? 0) > 10 ? 'big' : 'small';{x: 'abc'};!error +(x ?? 0) > 10 ? 'big' : 'small';{x: true};!error +x == null ? null : x == 0 ? 0 : 100 / x;{x: 20};5 +x == null ? null : x == 0 ? 0 : 100 / x;{x: 5};20 +x == null ? null : x == 0 ? 0 : 100 / x;{x: 0};0 +x == null ? null : x == 0 ? 0 : 100 / x;{x: null};null +x == null ? null : x == 0 ? 0 : 100 / x;{};null +x == null ? null : x == 0 ? 0 : 100 / x;{x: 'abc'};!error +x == null ? null : x == 0 ? 0 : 100 / x;{x: true};!error +x ? 'yes' : 'no';{x: 20};!error +x ? 'yes' : 'no';{x: 5};!error +x ? 'yes' : 'no';{x: 0};!error +x ? 'yes' : 'no';{x: null};!error +x ? 'yes' : 'no';{};!error +x ? 'yes' : 'no';{x: 'abc'};!error +x ? 'yes' : 'no';{x: true};'yes' +x == 5 ? 1 + {} : 'safe';{x: 20};'safe' +x == 5 ? 1 + {} : 'safe';{x: 5};!error +x == 5 ? 1 + {} : 'safe';{x: 0};'safe' +x == 5 ? 1 + {} : 'safe';{x: null};'safe' +x == 5 ? 1 + {} : 'safe';{};'safe' +x == 5 ? 1 + {} : 'safe';{x: 'abc'};'safe' +x == 5 ? 1 + {} : 'safe';{x: true};'safe' +x != 5 ? 'safe' : 1 + {};{x: 20};'safe' +x != 5 ? 'safe' : 1 + {};{x: 5};!error +x != 5 ? 'safe' : 1 + {};{x: 0};'safe' +x != 5 ? 'safe' : 1 + {};{x: null};'safe' +x != 5 ? 'safe' : 1 + {};{};'safe' +x != 5 ? 'safe' : 1 + {};{x: 'abc'};'safe' +x != 5 ? 'safe' : 1 + {};{x: true};'safe' +(x == null ? 0 : x) + 1;{x: 20};21 +(x == null ? 0 : x) + 1;{x: 5};6 +(x == null ? 0 : x) + 1;{x: 0};1 +(x == null ? 0 : x) + 1;{x: null};1 +(x == null ? 0 : x) + 1;{};1 +(x == null ? 0 : x) + 1;{x: 'abc'};!error +(x == null ? 0 : x) + 1;{x: true};!error +# Literal errors on the skipped branch of a ternary +true ? 1 : 1 + {};;1 +false ? 1 + {} : 2;;2 +true ? null : 1 + {};;null +false ? upper(1) : 'ok';;'ok' +true ? 'ok' : len(null);;'ok' +1 == 1 ? 'a' : null > 1;;'a' +null == null ? 'a' : 1 + {};;'a' +true ? (false ? 1 + {} : 'in') : 1 + {};;'in' +false ? 1 : 1 + {};;!error +true ? 1 + {} : 2;;!error +null ? 1 : 2;;!error +(1 / 0) ? 1 : 2;;!error +(1 / 0) == null ? 'div0' : 'ok';;'div0' +[] ? 1 : 2;;!error +'' ? 1 : 2;;!error +0 ? 1 : 2;;!error +# ?? falls through only on null and missing, never on false, 0, empty string, empty array or empty object +a ?? b;{a: 1, b: 2};1 +a ?? b;{a: null, b: 2};2 +a ?? b;{b: 2};2 +a ?? b;{a: false, b: 2};false +a ?? b;{a: 0, b: 2};0 +a ?? b;{a: '', b: 2};'' +a ?? b;{a: [], b: 2};[] +a ?? b;{a: {}, b: 2};{} +a ?? b;{a: null, b: null};null +a ?? b;{};null +a ?? b ?? 3;{a: 1, b: 2};1 +a ?? b ?? 3;{a: null, b: 2};2 +a ?? b ?? 3;{b: 2};2 +a ?? b ?? 3;{a: false, b: 2};false +a ?? b ?? 3;{a: 0, b: 2};0 +a ?? b ?? 3;{a: '', b: 2};'' +a ?? b ?? 3;{a: [], b: 2};[] +a ?? b ?? 3;{a: {}, b: 2};{} +a ?? b ?? 3;{a: null, b: null};3 +a ?? b ?? 3;{};3 +a ?? (1 + {});{a: 1, b: 2};1 +a ?? (1 + {});{a: null, b: 2};!error +a ?? (1 + {});{b: 2};!error +a ?? (1 + {});{a: false, b: 2};false +a ?? (1 + {});{a: 0, b: 2};0 +a ?? (1 + {});{a: '', b: 2};'' +a ?? (1 + {});{a: [], b: 2};[] +a ?? (1 + {});{a: {}, b: 2};{} +a ?? (1 + {});{a: null, b: null};!error +a ?? (1 + {});{};!error +type(a ?? b);{a: 1, b: 2};'number' +type(a ?? b);{a: null, b: 2};'number' +type(a ?? b);{b: 2};'number' +type(a ?? b);{a: false, b: 2};'bool' +type(a ?? b);{a: 0, b: 2};'number' +type(a ?? b);{a: '', b: 2};'string' +type(a ?? b);{a: [], b: 2};'array' +type(a ?? b);{a: {}, b: 2};'object' +type(a ?? b);{a: null, b: null};'null' +type(a ?? b);{};'null' +(a ?? 0) + (b ?? 0);{a: 1, b: 2};3 +(a ?? 0) + (b ?? 0);{a: null, b: 2};2 +(a ?? 0) + (b ?? 0);{b: 2};2 +(a ?? 0) + (b ?? 0);{a: false, b: 2};!error +(a ?? 0) + (b ?? 0);{a: 0, b: 2};2 +(a ?? 0) + (b ?? 0);{a: '', b: 2};!error +(a ?? 0) + (b ?? 0);{a: [], b: 2};!error +(a ?? 0) + (b ?? 0);{a: {}, b: 2};!error +(a ?? 0) + (b ?? 0);{a: null, b: null};0 +(a ?? 0) + (b ?? 0);{};0 +[a ?? 0, b ?? 0];{a: 1, b: 2};[1, 2] +[a ?? 0, b ?? 0];{a: null, b: 2};[0, 2] +[a ?? 0, b ?? 0];{b: 2};[0, 2] +[a ?? 0, b ?? 0];{a: false, b: 2};[false, 2] +[a ?? 0, b ?? 0];{a: 0, b: 2};[0, 2] +[a ?? 0, b ?? 0];{a: '', b: 2};['', 2] +[a ?? 0, b ?? 0];{a: [], b: 2};[[], 2] +[a ?? 0, b ?? 0];{a: {}, b: 2};[{}, 2] +[a ?? 0, b ?? 0];{a: null, b: null};[0, 0] +[a ?? 0, b ?? 0];{};[0, 0] +# ?? binds tighter than arithmetic and comparison +a ?? 10 + b;{a: 1, b: 2};3;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 + b;{a: null, b: 2};12;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 + b;{b: 2};12;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 + b;{a: null, b: null};!error;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 + b;{};!error;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 * 3;{a: 1, b: 2};3;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 * 3;{a: null, b: 2};30;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 * 3;{b: 2};30;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 > 5;{a: 1, b: 2};false;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 > 5;{a: null, b: 2};true;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +a ?? 10 > 5;{b: 2};true;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +b / a ?? 1;{a: 1, b: 2};2;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +b / a ?? 1;{a: null, b: 2};2;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +b / a ?? 1;{b: 2};2;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +b / a ?? 1;{a: 0, b: 2};null;question: ?? binds tighter than arithmetic and comparison (JS/C# bind it lowest), see the precedence chapter +-a ?? 4;{a: 1, b: 2};-1 +-a ?? 4;{a: null, b: 2};!error +-a ?? 4;{b: 2};!error +# ?? with a container fallback feeds member access, functions and closures +len(xs ?? []);{xs: [1, 2, 3]};3 +len(xs ?? []);{xs: []};0 +len(xs ?? []);{xs: null};0 +len(xs ?? []);{};0 +len(xs ?? []);{xs: 'ab'};2 +sum(xs ?? []);{xs: [1, 2, 3]};6 +sum(xs ?? []);{xs: []};0 +sum(xs ?? []);{xs: null};0 +sum(xs ?? []);{};0 +sum(xs ?? []);{xs: 'ab'};!error +(xs ?? [0])[0];{xs: [1, 2, 3]};1 +(xs ?? [0])[0];{xs: []};null +(xs ?? [0])[0];{xs: null};0 +(xs ?? [0])[0];{};0 +(xs ?? [0])[0];{xs: 'ab'};'a' +map(xs ?? [], # * 2);{xs: [1, 2, 3]};[2, 4, 6] +map(xs ?? [], # * 2);{xs: []};[] +map(xs ?? [], # * 2);{xs: null};[] +map(xs ?? [], # * 2);{};[] +map(xs ?? [], # * 2);{xs: 'ab'};!error +(u ?? {}).name ?? 'anon';{u: {name: 'Al'}};'Al' +(u ?? {}).name ?? 'anon';{u: {}};'anon' +(u ?? {}).name ?? 'anon';{u: null};'anon' +(u ?? {}).name ?? 'anon';{};'anon' +(u ?? {}).name ?? 'anon';{u: 'x'};'anon' +(u ?? {}).name ?? 'anon';{u: {name: null}};'anon' +upper(s ?? '');{s: 'ab'};'AB' +upper(s ?? '');{s: null};'' +upper(s ?? '');{};'' +upper(s ?? '');{s: 1};!error +# ?? inside chains that already contain null reads +u.addr.city ?? d;{u: {addr: {city: 'Oslo'}}, d: 'X'};'Oslo' +u.addr.city ?? d;{u: {addr: {}}, d: 'X'};'X' +u.addr.city ?? d;{u: {addr: null}, d: 'X'};'X' +u.addr.city ?? d;{u: {}, d: 'X'};'X' +u.addr.city ?? d;{u: null, d: 'X'};'X' +u.addr.city ?? d;{d: 'X'};'X' +u.addr.city ?? d;{d: null};null +u.addr.city ?? d;{};null +u.addr.city ?? d ?? 'none';{u: {addr: {city: 'Oslo'}}, d: 'X'};'Oslo' +u.addr.city ?? d ?? 'none';{u: {addr: {}}, d: 'X'};'X' +u.addr.city ?? d ?? 'none';{u: {addr: null}, d: 'X'};'X' +u.addr.city ?? d ?? 'none';{u: {}, d: 'X'};'X' +u.addr.city ?? d ?? 'none';{u: null, d: 'X'};'X' +u.addr.city ?? d ?? 'none';{d: 'X'};'X' +u.addr.city ?? d ?? 'none';{d: null};'none' +u.addr.city ?? d ?? 'none';{};'none' +(u.addr ?? {}).city ?? 'none';{u: {addr: {city: 'Oslo'}}, d: 'X'};'Oslo' +(u.addr ?? {}).city ?? 'none';{u: {addr: {}}, d: 'X'};'none' +(u.addr ?? {}).city ?? 'none';{u: {addr: null}, d: 'X'};'none' +(u.addr ?? {}).city ?? 'none';{u: {}, d: 'X'};'none' +(u.addr ?? {}).city ?? 'none';{u: null, d: 'X'};'none' +(u.addr ?? {}).city ?? 'none';{d: 'X'};'none' +(u.addr ?? {}).city ?? 'none';{d: null};'none' +(u.addr ?? {}).city ?? 'none';{};'none' +u.addr.city + '!';{u: {addr: {city: 'Oslo'}}, d: 'X'};'Oslo!' +u.addr.city + '!';{u: {addr: {}}, d: 'X'};!error +u.addr.city + '!';{u: {addr: null}, d: 'X'};!error +u.addr.city + '!';{u: {}, d: 'X'};!error +u.addr.city + '!';{u: null, d: 'X'};!error +u.addr.city + '!';{d: 'X'};!error +u.addr.city + '!';{d: null};!error +u.addr.city + '!';{};!error +(u.addr.city ?? '?') + '!';{u: {addr: {city: 'Oslo'}}, d: 'X'};'Oslo!' +(u.addr.city ?? '?') + '!';{u: {addr: {}}, d: 'X'};'?!' +(u.addr.city ?? '?') + '!';{u: {addr: null}, d: 'X'};'?!' +(u.addr.city ?? '?') + '!';{u: {}, d: 'X'};'?!' +(u.addr.city ?? '?') + '!';{u: null, d: 'X'};'?!' +(u.addr.city ?? '?') + '!';{d: 'X'};'?!' +(u.addr.city ?? '?') + '!';{d: null};'?!' +(u.addr.city ?? '?') + '!';{};'?!' +u.addr.city == null ? d : u.addr.city;{u: {addr: {city: 'Oslo'}}, d: 'X'};'Oslo' +u.addr.city == null ? d : u.addr.city;{u: {addr: {}}, d: 'X'};'X' +u.addr.city == null ? d : u.addr.city;{u: {addr: null}, d: 'X'};'X' +u.addr.city == null ? d : u.addr.city;{u: {}, d: 'X'};'X' +u.addr.city == null ? d : u.addr.city;{u: null, d: 'X'};'X' +u.addr.city == null ? d : u.addr.city;{d: 'X'};'X' +u.addr.city == null ? d : u.addr.city;{d: null};null +u.addr.city == null ? d : u.addr.city;{};null +# Membership with null needles and null list elements +x in [1, 2, null];{x: 1};true +x in [1, 2, null];{x: 3};false +x in [1, 2, null];{x: null};true +x in [1, 2, null];{};true +x in [1, 2, null];{x: '1'};false +x in [1, 2, null];{x: true};false +x in [1, 2];{x: 1};true +x in [1, 2];{x: 3};false +x in [1, 2];{x: null};false +x in [1, 2];{};false +x in [1, 2];{x: '1'};false +x in [1, 2];{x: true};false +x not in [1, 2, null];{x: 1};false +x not in [1, 2, null];{x: 3};true +x not in [1, 2, null];{x: null};false +x not in [1, 2, null];{};false +x not in [1, 2, null];{x: '1'};true +x not in [1, 2, null];{x: true};true +x in [1..5];{x: 1};true +x in [1..5];{x: 3};true +x in [1..5];{x: null};!error +x in [1..5];{};!error +x in [1..5];{x: '1'};!error +x in [1..5];{x: true};!error +(x ?? 0) in [1..5];{x: 1};true +(x ?? 0) in [1..5];{x: 3};true +(x ?? 0) in [1..5];{x: null};false +(x ?? 0) in [1..5];{};false +(x ?? 0) in [1..5];{x: '1'};!error +(x ?? 0) in [1..5];{x: true};!error +x in ['1', true];{x: 1};false +x in ['1', true];{x: 3};false +x in ['1', true];{x: null};false +x in ['1', true];{};false +x in ['1', true];{x: '1'};true +x in ['1', true];{x: true};true +# Membership in a list that is null, missing or not a list +x in list;{x: 1, list: [1, 2]};true +x in list;{x: 1, list: []};false +x in list;{x: null, list: [null]};true +x in list;{x: 1, list: null};!error +x in list;{x: 1};!error +x in list;{x: 1, list: 'abc'};!error +x in list;{x: 1, list: {a: 1}};!error +x in list;{x: null, list: [1]};false +x in (list ?? []);{x: 1, list: [1, 2]};true +x in (list ?? []);{x: 1, list: []};false +x in (list ?? []);{x: null, list: [null]};true +x in (list ?? []);{x: 1, list: null};false +x in (list ?? []);{x: 1};false +x in (list ?? []);{x: 1, list: 'abc'};!error +x in (list ?? []);{x: 1, list: {a: 1}};!error +x in (list ?? []);{x: null, list: [1]};false +list != null and x in list;{x: 1, list: [1, 2]};true +list != null and x in list;{x: 1, list: []};false +list != null and x in list;{x: null, list: [null]};true +list != null and x in list;{x: 1, list: null};false +list != null and x in list;{x: 1};false +list != null and x in list;{x: 1, list: 'abc'};!error +list != null and x in list;{x: 1, list: {a: 1}};!error +list != null and x in list;{x: null, list: [1]};false +x in [a, b];{x: 1, a: 1};true +x in [a, b];{x: null};true +x in [a, b];{x: null, a: 1, b: 2};false +x in [a, b];{x: 2, b: 2};true +x in [a, b];{x: 3, a: null};false +# Intervals with null or missing bounds are errors +x in [lo..hi];{x: 3, lo: 1, hi: 5};true +x in [lo..hi];{x: 3, lo: null, hi: 5};!error +x in [lo..hi];{x: 3, hi: 5};!error +x in [lo..hi];{x: 3, lo: 1};!error +x in [lo..hi];{x: null, lo: 1, hi: 5};!error +x in [lo..hi];{x: 3, lo: '1', hi: 5};!error +x in [lo..hi];{x: 9, lo: 1, hi: 5};false +x in [(lo ?? 0)..(hi ?? 100)];{x: 3, lo: 1, hi: 5};true +x in [(lo ?? 0)..(hi ?? 100)];{x: 3, lo: null, hi: 5};true +x in [(lo ?? 0)..(hi ?? 100)];{x: 50};true +x in [(lo ?? 0)..(hi ?? 100)];{x: 101};false +x in [(lo ?? 0)..(hi ?? 100)];{x: null};!error diff --git a/core/expression/tests/spec/standard/11-03-null-functions.csv b/core/expression/tests/spec/standard/11-03-null-functions.csv new file mode 100644 index 00000000..763569cc --- /dev/null +++ b/core/expression/tests/spec/standard/11-03-null-functions.csv @@ -0,0 +1,411 @@ +expression (string);input (json 5);output (json 5);note +# String functions reject null and missing arguments +upper(s);{s: ' Ab '};' AB ' +upper(s);{s: ''};'' +upper(s);{s: null};!error +upper(s);{};!error +upper(s);{s: 5};!error +upper(s);{s: ['a']};!error +lower(s);{s: ' Ab '};' ab ' +lower(s);{s: ''};'' +lower(s);{s: null};!error +lower(s);{};!error +lower(s);{s: 5};!error +lower(s);{s: ['a']};!error +trim(s);{s: ' Ab '};'Ab' +trim(s);{s: ''};'' +trim(s);{s: null};!error +trim(s);{};!error +trim(s);{s: 5};!error +trim(s);{s: ['a']};!error +startsWith(s, ' A');{s: ' Ab '};true +startsWith(s, ' A');{s: ''};false +startsWith(s, ' A');{s: null};!error +startsWith(s, ' A');{};!error +startsWith(s, ' A');{s: 5};!error +startsWith(s, ' A');{s: ['a']};!error +endsWith(s, ' ');{s: ' Ab '};true +endsWith(s, ' ');{s: ''};false +endsWith(s, ' ');{s: null};!error +endsWith(s, ' ');{};!error +endsWith(s, ' ');{s: 5};!error +endsWith(s, ' ');{s: ['a']};!error +contains(s, 'b');{s: ' Ab '};true +contains(s, 'b');{s: ''};false +contains(s, 'b');{s: null};!error +contains(s, 'b');{};!error +contains(s, 'b');{s: 5};!error +contains(s, 'b');{s: ['a']};false +split(s, 'b');{s: ' Ab '};[' A', ' '] +split(s, 'b');{s: ''};[''] +split(s, 'b');{s: null};!error +split(s, 'b');{};!error +split(s, 'b');{s: 5};!error +split(s, 'b');{s: ['a']};!error +matches(s, 'A');{s: ' Ab '};true +matches(s, 'A');{s: ''};false +matches(s, 'A');{s: null};!error +matches(s, 'A');{};!error +matches(s, 'A');{s: 5};!error +matches(s, 'A');{s: ['a']};!error +# Defaulting a string argument with ?? before the call +upper(s ?? '');{s: ' Ab '};' AB ' +upper(s ?? '');{s: ''};'' +upper(s ?? '');{s: null};'' +upper(s ?? '');{};'' +upper(s ?? '');{s: 5};!error +upper(s ?? '');{s: ['a']};!error +trim(s ?? 'none');{s: ' Ab '};'Ab' +trim(s ?? 'none');{s: ''};'' +trim(s ?? 'none');{s: null};'none' +trim(s ?? 'none');{};'none' +trim(s ?? 'none');{s: 5};!error +trim(s ?? 'none');{s: ['a']};!error +len(s ?? '');{s: ' Ab '};4 +len(s ?? '');{s: ''};0 +len(s ?? '');{s: null};0 +len(s ?? '');{};0 +len(s ?? '');{s: 5};!error +len(s ?? '');{s: ['a']};1 +s != null and startsWith(s, ' ');{s: ' Ab '};true +s != null and startsWith(s, ' ');{s: ''};false +s != null and startsWith(s, ' ');{s: null};false +s != null and startsWith(s, ' ');{};false +s != null and startsWith(s, ' ');{s: 5};!error +s != null and startsWith(s, ' ');{s: ['a']};!error +type(s) == 'string' ? lower(s) : 'n/a';{s: ' Ab '};' ab ' +type(s) == 'string' ? lower(s) : 'n/a';{s: ''};'' +type(s) == 'string' ? lower(s) : 'n/a';{s: null};'n/a' +type(s) == 'string' ? lower(s) : 'n/a';{};'n/a' +type(s) == 'string' ? lower(s) : 'n/a';{s: 5};'n/a' +type(s) == 'string' ? lower(s) : 'n/a';{s: ['a']};'n/a' +# Null in the second argument of string functions +startsWith('abc', p);{p: 'b'};false +startsWith('abc', p);{p: null};!error +startsWith('abc', p);{};!error +startsWith('abc', p);{p: 1};!error +endsWith('abc', p);{p: 'b'};false +endsWith('abc', p);{p: null};!error +endsWith('abc', p);{};!error +endsWith('abc', p);{p: 1};!error +contains('abc', p);{p: 'b'};true +contains('abc', p);{p: null};!error +contains('abc', p);{};!error +contains('abc', p);{p: 1};!error +split('a,b', p);{p: 'b'};['a,', ''] +split('a,b', p);{p: null};!error +split('a,b', p);{};!error +split('a,b', p);{p: 1};!error +matches('abc', p);{p: 'b'};true +matches('abc', p);{p: null};!error +matches('abc', p);{};!error +matches('abc', p);{p: 1};!error +contains(['a', 'b', null], p);{p: 'b'};true +contains(['a', 'b', null], p);{p: null};true +contains(['a', 'b', null], p);{};true +contains(['a', 'b', null], p);{p: 1};false +contains(['a', 'b'], p);{p: 'b'};true +contains(['a', 'b'], p);{p: null};false +contains(['a', 'b'], p);{};false +contains(['a', 'b'], p);{p: 1};false +# Number functions reject null and missing arguments +abs(n);{n: -2.5};2.5 +abs(n);{n: 0};0 +abs(n);{n: null};!error +abs(n);{};!error +abs(n);{n: '3'};!error +abs(n);{n: true};!error +floor(n);{n: -2.5};-3 +floor(n);{n: 0};0 +floor(n);{n: null};!error +floor(n);{};!error +floor(n);{n: '3'};!error +floor(n);{n: true};!error +ceil(n);{n: -2.5};-2 +ceil(n);{n: 0};0 +ceil(n);{n: null};!error +ceil(n);{};!error +ceil(n);{n: '3'};!error +ceil(n);{n: true};!error +round(n);{n: -2.5};-3 +round(n);{n: 0};0 +round(n);{n: null};!error +round(n);{};!error +round(n);{n: '3'};!error +round(n);{n: true};!error +trunc(n);{n: -2.5};-2 +trunc(n);{n: 0};0 +trunc(n);{n: null};!error +trunc(n);{};!error +trunc(n);{n: '3'};!error +trunc(n);{n: true};!error +round(n, 1);{n: -2.5};-2.5 +round(n, 1);{n: 0};0.0 +round(n, 1);{n: null};!error +round(n, 1);{};!error +round(n, 1);{n: '3'};!error +round(n, 1);{n: true};!error +abs(n ?? 0);{n: -2.5};2.5 +abs(n ?? 0);{n: 0};0 +abs(n ?? 0);{n: null};0 +abs(n ?? 0);{};0 +abs(n ?? 0);{n: '3'};!error +abs(n ?? 0);{n: true};!error +round(n ?? 0) + 1;{n: -2.5};-2 +round(n ?? 0) + 1;{n: 0};1 +round(n ?? 0) + 1;{n: null};1 +round(n ?? 0) + 1;{};1 +round(n ?? 0) + 1;{n: '3'};!error +round(n ?? 0) + 1;{n: true};!error +isNumeric(n) ? number(n) * 2 : null;{n: -2.5};-5.0 +isNumeric(n) ? number(n) * 2 : null;{n: 0};0 +isNumeric(n) ? number(n) * 2 : null;{n: null};null +isNumeric(n) ? number(n) * 2 : null;{};null +isNumeric(n) ? number(n) * 2 : null;{n: '3'};6 +isNumeric(n) ? number(n) * 2 : null;{n: true};null +# Null in the precision argument +round(1.25, p);{p: 1};1.3 +round(1.25, p);{p: null};!error +round(1.25, p);{};!error +round(1.25, p);{p: '1'};!error +trunc(1.25, p);{p: 1};1.2 +trunc(1.25, p);{p: null};!error +trunc(1.25, p);{};!error +trunc(1.25, p);{p: '1'};!error +# Conversion functions give null a meaning of its own +string(n);{n: -2.5};'-2.5' +string(n);{n: 0};'0' +string(n);{n: null};'null' +string(n);{};'null' +string(n);{n: '3'};'3' +string(n);{n: true};'true' +type(n);{n: -2.5};'number' +type(n);{n: 0};'number' +type(n);{n: null};'null' +type(n);{};'null' +type(n);{n: '3'};'string' +type(n);{n: true};'bool' +number(n);{n: -2.5};-2.5 +number(n);{n: 0};0 +number(n);{n: null};!error +number(n);{};!error +number(n);{n: '3'};3 +number(n);{n: true};1 +isNumeric(n);{n: -2.5};true +isNumeric(n);{n: 0};true +isNumeric(n);{n: null};false +isNumeric(n);{};false +isNumeric(n);{n: '3'};true +isNumeric(n);{n: true};false +bool(n);{n: -2.5};true +bool(n);{n: 0};false +bool(n);{n: null};false +bool(n);{};false +bool(n);{n: '3'};true;bug: non-empty string converts to false (inverted is_empty) +bool(n);{n: true};true +string(n) == 'null';{n: -2.5};false +string(n) == 'null';{n: 0};false +string(n) == 'null';{n: null};true +string(n) == 'null';{};true +string(n) == 'null';{n: '3'};false +string(n) == 'null';{n: true};false +number(n ?? '0');{n: -2.5};-2.5 +number(n ?? '0');{n: 0};0 +number(n ?? '0');{n: null};0 +number(n ?? '0');{};0 +number(n ?? '0');{n: '3'};3 +number(n ?? '0');{n: true};1 +# Aggregates reject null lists and null elements; empty lists differ per function +sum(xs);{xs: [1, 2, 3]};6 +sum(xs);{xs: [1, null, 3]};!error +sum(xs);{xs: [null]};!error +sum(xs);{xs: []};0 +sum(xs);{xs: null};!error +sum(xs);{};!error +sum(xs);{xs: [1, '2']};!error +sum(xs);{xs: 5};!error +max(xs);{xs: [1, 2, 3]};3 +max(xs);{xs: [1, null, 3]};!error +max(xs);{xs: [null]};!error +max(xs);{xs: []};!error +max(xs);{xs: null};!error +max(xs);{};!error +max(xs);{xs: [1, '2']};!error +max(xs);{xs: 5};!error +min(xs);{xs: [1, 2, 3]};1 +min(xs);{xs: [1, null, 3]};!error +min(xs);{xs: [null]};!error +min(xs);{xs: []};!error +min(xs);{xs: null};!error +min(xs);{};!error +min(xs);{xs: [1, '2']};!error +min(xs);{xs: 5};!error +avg(xs);{xs: [1, 2, 3]};2 +avg(xs);{xs: [1, null, 3]};!error +avg(xs);{xs: [null]};!error +avg(xs);{xs: []};!error +avg(xs);{xs: null};!error +avg(xs);{};!error +avg(xs);{xs: [1, '2']};!error +avg(xs);{xs: 5};!error +len(xs);{xs: [1, 2, 3]};3 +len(xs);{xs: [1, null, 3]};3 +len(xs);{xs: [null]};1 +len(xs);{xs: []};0 +len(xs);{xs: null};!error +len(xs);{};!error +len(xs);{xs: [1, '2']};2 +len(xs);{xs: 5};!error +sum(xs ?? []);{xs: [1, 2, 3]};6 +sum(xs ?? []);{xs: [1, null, 3]};!error +sum(xs ?? []);{xs: [null]};!error +sum(xs ?? []);{xs: []};0 +sum(xs ?? []);{xs: null};0 +sum(xs ?? []);{};0 +sum(xs ?? []);{xs: [1, '2']};!error +sum(xs ?? []);{xs: 5};!error +sum(filter(xs, # != null));{xs: [1, 2, 3]};6 +sum(filter(xs, # != null));{xs: [1, null, 3]};4 +sum(filter(xs, # != null));{xs: [null]};0 +sum(filter(xs, # != null));{xs: []};0 +sum(filter(xs, # != null));{xs: null};!error +sum(filter(xs, # != null));{};!error +sum(filter(xs, # != null));{xs: [1, '2']};!error +sum(filter(xs, # != null));{xs: 5};!error +sum(map(xs, # ?? 0));{xs: [1, 2, 3]};6 +sum(map(xs, # ?? 0));{xs: [1, null, 3]};4 +sum(map(xs, # ?? 0));{xs: [null]};0 +sum(map(xs, # ?? 0));{xs: []};0 +sum(map(xs, # ?? 0));{xs: null};!error +sum(map(xs, # ?? 0));{};!error +sum(map(xs, # ?? 0));{xs: [1, '2']};!error +sum(map(xs, # ?? 0));{xs: 5};!error +len(xs) > 0 ? max(xs) : null;{xs: [1, 2, 3]};3 +len(xs) > 0 ? max(xs) : null;{xs: [1, null, 3]};!error +len(xs) > 0 ? max(xs) : null;{xs: [null]};!error +len(xs) > 0 ? max(xs) : null;{xs: []};null +len(xs) > 0 ? max(xs) : null;{xs: null};!error +len(xs) > 0 ? max(xs) : null;{};!error +len(xs) > 0 ? max(xs) : null;{xs: [1, '2']};!error +len(xs) > 0 ? max(xs) : null;{xs: 5};!error +contains(xs, null);{xs: [1, 2, 3]};false +contains(xs, null);{xs: [1, null, 3]};true +contains(xs, null);{xs: [null]};true +contains(xs, null);{xs: []};false +contains(xs, null);{xs: null};!error +contains(xs, null);{};!error +contains(xs, null);{xs: [1, '2']};false +contains(xs, null);{xs: 5};!error +null in xs;{xs: [1, 2, 3]};false +null in xs;{xs: [1, null, 3]};true +null in xs;{xs: [null]};true +null in xs;{xs: []};false +null in xs;{xs: null};!error +null in xs;{};!error +null in xs;{xs: [1, '2']};false +null in xs;{xs: 5};!error +flatten([xs]);{xs: [1, 2, 3]};[1, 2, 3] +flatten([xs]);{xs: [1, null, 3]};[1, null, 3] +flatten([xs]);{xs: [null]};[null] +flatten([xs]);{xs: []};[] +flatten([xs]);{xs: null};[null] +flatten([xs]);{};[null] +flatten([xs]);{xs: [1, '2']};[1, '2'] +flatten([xs]);{xs: 5};[5] +# keys and values of null +keys(o);{o: {a: 1, b: null}};['a', 'b'] +keys(o);{o: {}};[] +keys(o);{o: null};!error +keys(o);{};!error +keys(o);{o: [5, null]};[0, 1] +keys(o);{o: 'ab'};!error +values(o);{o: {a: 1, b: null}};[1, null] +values(o);{o: {}};[] +values(o);{o: null};!error +values(o);{};!error +values(o);{o: [5, null]};!error +values(o);{o: 'ab'};!error +keys(o ?? {});{o: {a: 1, b: null}};['a', 'b'] +keys(o ?? {});{o: {}};[] +keys(o ?? {});{o: null};[] +keys(o ?? {});{};[] +keys(o ?? {});{o: [5, null]};[0, 1] +keys(o ?? {});{o: 'ab'};!error +len(o ?? []);{o: {a: 1, b: null}};!error +len(o ?? []);{o: {}};!error +len(o ?? []);{o: null};0 +len(o ?? []);{};0 +len(o ?? []);{o: [5, null]};2 +len(o ?? []);{o: 'ab'};2 +# Dates from null or missing input are invalid dates, not errors +d(t).isValid();{t: '2024-05-06'};true +d(t).isValid();{t: null};false +d(t).isValid();{};false +d(t).isValid();{t: 'garbage'};false +d(t).year();{t: '2024-05-06'};2024 +d(t).year();{t: null};null +d(t).year();{};null +d(t).year();{t: 'garbage'};null +d(t).year() ?? 0;{t: '2024-05-06'};2024 +d(t).year() ?? 0;{t: null};0 +d(t).year() ?? 0;{};0 +d(t).year() ?? 0;{t: 'garbage'};0 +d(t).year() + 1;{t: '2024-05-06'};2025 +d(t).year() + 1;{t: null};!error +d(t).year() + 1;{};!error +d(t).year() + 1;{t: 'garbage'};!error +d(t).format('%Y');{t: '2024-05-06'};'2024' +d(t).format('%Y');{t: null};'Invalid date' +d(t).format('%Y');{};'Invalid date' +d(t).format('%Y');{t: 'garbage'};'Invalid date' +d(t).add(1, 'd').isValid();{t: '2024-05-06'};true +d(t).add(1, 'd').isValid();{t: null};false +d(t).add(1, 'd').isValid();{};false +d(t).add(1, 'd').isValid();{t: 'garbage'};false +t == null ? 'no date' : d(t).format('%d.%m.');{t: '2024-05-06'};'06.05.' +t == null ? 'no date' : d(t).format('%d.%m.');{t: null};'no date' +t == null ? 'no date' : d(t).format('%d.%m.');{};'no date' +t == null ? 'no date' : d(t).format('%d.%m.');{t: 'garbage'};'Invalid date' +d(t ?? '2000-01-01').year();{t: '2024-05-06'};2024 +d(t ?? '2000-01-01').year();{t: null};2000 +d(t ?? '2000-01-01').year();{};2000 +d(t ?? '2000-01-01').year();{t: 'garbage'};null +d(t).isValid() and d(t).year() > 2020;{t: '2024-05-06'};true +d(t).isValid() and d(t).year() > 2020;{t: null};false +d(t).isValid() and d(t).year() > 2020;{};false +d(t).isValid() and d(t).year() > 2020;{t: 'garbage'};false +date(t);{t: '2024-05-06'};1714953600 +date(t);{t: null};!error +date(t);{};!error +date(t);{t: 'garbage'};!error +t.year();{t: '2024-05-06'};!error +t.year();{t: null};!error +t.year();{};!error +t.year();{t: 'garbage'};!error +# Function calls that are skipped by ?? , and/or and ternaries do not raise +'x' ?? upper(1);;'x' +false and len(null) > 0;;false +true or sum(null) > 0;;true +true ? 1 : abs('a');;1 +s ?? upper(s);{s: 'a'};'a' +s ?? upper(s);{s: null};!error +s ?? upper(s);{};!error +xs ?? max(xs);{xs: [1]};[1] +xs ?? max(xs);{};!error +# Nested function calls propagate a null argument error outward +len(upper(s));{s: 'ab'};2 +len(upper(s));{s: null};!error +len(upper(s));{};!error +abs(round(n));{n: -1.6};2 +abs(round(n));{n: null};!error +string(len(xs));{xs: [1]};'1' +string(len(xs));{xs: null};!error +type(sum(xs));{xs: [1]};'number' +type(sum(xs));{xs: [null]};!error +upper(string(n));{n: null};'NULL' +upper(string(n));{};'NULL' +upper(string(n));{n: 1.5};'1.5' +len(string(n));{n: null};4 +len(split(s, ','));{s: null};!error +len(split(s ?? '', ','));{s: null};1 +len(split(s ?? '', ','));{s: 'a,b'};2 diff --git a/core/expression/tests/spec/standard/11-04-null-closures.csv b/core/expression/tests/spec/standard/11-04-null-closures.csv new file mode 100644 index 00000000..51548415 --- /dev/null +++ b/core/expression/tests/spec/standard/11-04-null-closures.csv @@ -0,0 +1,398 @@ +expression (string);input (json 5);output (json 5);note +# A null list is an error for every closure; an empty list never evaluates the body +map(xs, # * 2);{xs: [1, 5, 10]};[2, 10, 20] +map(xs, # * 2);{xs: [5, null, 10]};!error +map(xs, # * 2);{xs: []};[] +map(xs, # * 2);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, # * 2);{};!error;question: a null list is an error rather than an empty list +map(xs, # * 2);{xs: [1, 'a']};!error +map(xs, # * 2);{xs: ['a', 20]};!error +map(xs, # * 2);{xs: 'abc'};!error +filter(xs, # > 4);{xs: [1, 5, 10]};[5, 10] +filter(xs, # > 4);{xs: [5, null, 10]};!error +filter(xs, # > 4);{xs: []};[] +filter(xs, # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +filter(xs, # > 4);{};!error;question: a null list is an error rather than an empty list +filter(xs, # > 4);{xs: [1, 'a']};!error +filter(xs, # > 4);{xs: ['a', 20]};!error +filter(xs, # > 4);{xs: 'abc'};!error +some(xs, # > 4);{xs: [1, 5, 10]};true +some(xs, # > 4);{xs: [5, null, 10]};true +some(xs, # > 4);{xs: []};false +some(xs, # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +some(xs, # > 4);{};!error;question: a null list is an error rather than an empty list +some(xs, # > 4);{xs: [1, 'a']};!error +some(xs, # > 4);{xs: ['a', 20]};!error +some(xs, # > 4);{xs: 'abc'};!error +all(xs, # > 4);{xs: [1, 5, 10]};false +all(xs, # > 4);{xs: [5, null, 10]};!error +all(xs, # > 4);{xs: []};true +all(xs, # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +all(xs, # > 4);{};!error;question: a null list is an error rather than an empty list +all(xs, # > 4);{xs: [1, 'a']};false +all(xs, # > 4);{xs: ['a', 20]};!error +all(xs, # > 4);{xs: 'abc'};!error +none(xs, # > 4);{xs: [1, 5, 10]};false +none(xs, # > 4);{xs: [5, null, 10]};false +none(xs, # > 4);{xs: []};true +none(xs, # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +none(xs, # > 4);{};!error;question: a null list is an error rather than an empty list +none(xs, # > 4);{xs: [1, 'a']};!error +none(xs, # > 4);{xs: ['a', 20]};!error +none(xs, # > 4);{xs: 'abc'};!error +count(xs, # > 4);{xs: [1, 5, 10]};2 +count(xs, # > 4);{xs: [5, null, 10]};!error +count(xs, # > 4);{xs: []};0 +count(xs, # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +count(xs, # > 4);{};!error;question: a null list is an error rather than an empty list +count(xs, # > 4);{xs: [1, 'a']};!error +count(xs, # > 4);{xs: ['a', 20]};!error +count(xs, # > 4);{xs: 'abc'};!error +one(xs, # > 4);{xs: [1, 5, 10]};false +one(xs, # > 4);{xs: [5, null, 10]};!error +one(xs, # > 4);{xs: []};false +one(xs, # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +one(xs, # > 4);{};!error;question: a null list is an error rather than an empty list +one(xs, # > 4);{xs: [1, 'a']};!error +one(xs, # > 4);{xs: ['a', 20]};!error +one(xs, # > 4);{xs: 'abc'};!error +map(xs ?? [], # * 2);{xs: [1, 5, 10]};[2, 10, 20] +map(xs ?? [], # * 2);{xs: [5, null, 10]};!error +map(xs ?? [], # * 2);{xs: []};[] +map(xs ?? [], # * 2);{xs: null};[] +map(xs ?? [], # * 2);{};[] +map(xs ?? [], # * 2);{xs: [1, 'a']};!error +map(xs ?? [], # * 2);{xs: ['a', 20]};!error +map(xs ?? [], # * 2);{xs: 'abc'};!error +count(xs ?? [], true);{xs: [1, 5, 10]};3 +count(xs ?? [], true);{xs: [5, null, 10]};3 +count(xs ?? [], true);{xs: []};0 +count(xs ?? [], true);{xs: null};0 +count(xs ?? [], true);{};0 +count(xs ?? [], true);{xs: [1, 'a']};2 +count(xs ?? [], true);{xs: ['a', 20]};2 +count(xs ?? [], true);{xs: 'abc'};!error +# Guarding each element inside the body +map(xs, # ?? 0);{xs: [1, 5, 10]};[1, 5, 10] +map(xs, # ?? 0);{xs: [5, null, 10]};[5, 0, 10] +map(xs, # ?? 0);{xs: []};[] +map(xs, # ?? 0);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, # ?? 0);{};!error;question: a null list is an error rather than an empty list +map(xs, # ?? 0);{xs: [1, 'a']};[1, 'a'] +map(xs, # ?? 0);{xs: ['a', 20]};['a', 20] +map(xs, # ?? 0);{xs: 'abc'};!error +map(xs, (# ?? 0) * 2);{xs: [1, 5, 10]};[2, 10, 20] +map(xs, (# ?? 0) * 2);{xs: [5, null, 10]};[10, 0, 20] +map(xs, (# ?? 0) * 2);{xs: []};[] +map(xs, (# ?? 0) * 2);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, (# ?? 0) * 2);{};!error;question: a null list is an error rather than an empty list +map(xs, (# ?? 0) * 2);{xs: [1, 'a']};!error +map(xs, (# ?? 0) * 2);{xs: ['a', 20]};!error +map(xs, (# ?? 0) * 2);{xs: 'abc'};!error +map(xs, # == null ? -1 : # * 2);{xs: [1, 5, 10]};[2, 10, 20] +map(xs, # == null ? -1 : # * 2);{xs: [5, null, 10]};[10, -1, 20] +map(xs, # == null ? -1 : # * 2);{xs: []};[] +map(xs, # == null ? -1 : # * 2);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, # == null ? -1 : # * 2);{};!error;question: a null list is an error rather than an empty list +map(xs, # == null ? -1 : # * 2);{xs: [1, 'a']};!error +map(xs, # == null ? -1 : # * 2);{xs: ['a', 20]};!error +map(xs, # == null ? -1 : # * 2);{xs: 'abc'};!error +map(xs, type(#) == 'number' ? # * 2 : #);{xs: [1, 5, 10]};[2, 10, 20] +map(xs, type(#) == 'number' ? # * 2 : #);{xs: [5, null, 10]};[10, null, 20] +map(xs, type(#) == 'number' ? # * 2 : #);{xs: []};[] +map(xs, type(#) == 'number' ? # * 2 : #);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, type(#) == 'number' ? # * 2 : #);{};!error;question: a null list is an error rather than an empty list +map(xs, type(#) == 'number' ? # * 2 : #);{xs: [1, 'a']};[2, 'a'] +map(xs, type(#) == 'number' ? # * 2 : #);{xs: ['a', 20]};['a', 40] +map(xs, type(#) == 'number' ? # * 2 : #);{xs: 'abc'};!error +filter(xs, # != null and # > 4);{xs: [1, 5, 10]};[5, 10] +filter(xs, # != null and # > 4);{xs: [5, null, 10]};[5, 10] +filter(xs, # != null and # > 4);{xs: []};[] +filter(xs, # != null and # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +filter(xs, # != null and # > 4);{};!error;question: a null list is an error rather than an empty list +filter(xs, # != null and # > 4);{xs: [1, 'a']};!error +filter(xs, # != null and # > 4);{xs: ['a', 20]};!error +filter(xs, # != null and # > 4);{xs: 'abc'};!error +filter(xs, type(#) == 'number' and # > 4);{xs: [1, 5, 10]};[5, 10] +filter(xs, type(#) == 'number' and # > 4);{xs: [5, null, 10]};[5, 10] +filter(xs, type(#) == 'number' and # > 4);{xs: []};[] +filter(xs, type(#) == 'number' and # > 4);{xs: null};!error;question: a null list is an error rather than an empty list +filter(xs, type(#) == 'number' and # > 4);{};!error;question: a null list is an error rather than an empty list +filter(xs, type(#) == 'number' and # > 4);{xs: [1, 'a']};[] +filter(xs, type(#) == 'number' and # > 4);{xs: ['a', 20]};[20] +filter(xs, type(#) == 'number' and # > 4);{xs: 'abc'};!error +count(xs, # == null);{xs: [1, 5, 10]};0 +count(xs, # == null);{xs: [5, null, 10]};1 +count(xs, # == null);{xs: []};0 +count(xs, # == null);{xs: null};!error;question: a null list is an error rather than an empty list +count(xs, # == null);{};!error;question: a null list is an error rather than an empty list +count(xs, # == null);{xs: [1, 'a']};0 +count(xs, # == null);{xs: ['a', 20]};0 +count(xs, # == null);{xs: 'abc'};!error +some(xs, # == null);{xs: [1, 5, 10]};false +some(xs, # == null);{xs: [5, null, 10]};true +some(xs, # == null);{xs: []};false +some(xs, # == null);{xs: null};!error;question: a null list is an error rather than an empty list +some(xs, # == null);{};!error;question: a null list is an error rather than an empty list +some(xs, # == null);{xs: [1, 'a']};false +some(xs, # == null);{xs: ['a', 20]};false +some(xs, # == null);{xs: 'abc'};!error +all(xs, # != null);{xs: [1, 5, 10]};true +all(xs, # != null);{xs: [5, null, 10]};false +all(xs, # != null);{xs: []};true +all(xs, # != null);{xs: null};!error;question: a null list is an error rather than an empty list +all(xs, # != null);{};!error;question: a null list is an error rather than an empty list +all(xs, # != null);{xs: [1, 'a']};true +all(xs, # != null);{xs: ['a', 20]};true +all(xs, # != null);{xs: 'abc'};!error +map(xs, `${#}`);{xs: [1, 5, 10]};['1', '5', '10'] +map(xs, `${#}`);{xs: [5, null, 10]};['5', 'null', '10'] +map(xs, `${#}`);{xs: []};[] +map(xs, `${#}`);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, `${#}`);{};!error;question: a null list is an error rather than an empty list +map(xs, `${#}`);{xs: [1, 'a']};['1', 'a'] +map(xs, `${#}`);{xs: ['a', 20]};['a', '20'] +map(xs, `${#}`);{xs: 'abc'};!error +map(xs, [#]);{xs: [1, 5, 10]};[[1], [5], [10]] +map(xs, [#]);{xs: [5, null, 10]};[[5], [null], [10]] +map(xs, [#]);{xs: []};[] +map(xs, [#]);{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, [#]);{};!error;question: a null list is an error rather than an empty list +map(xs, [#]);{xs: [1, 'a']};[[1], ['a']] +map(xs, [#]);{xs: ['a', 20]};[['a'], [20]] +map(xs, [#]);{xs: 'abc'};!error +map(xs, 10 / (# ?? 0));{xs: [1, 5, 10]};[10, 2, 1] +map(xs, 10 / (# ?? 0));{xs: [5, null, 10]};[2, null, 1] +map(xs, 10 / (# ?? 0));{xs: []};[] +map(xs, 10 / (# ?? 0));{xs: null};!error;question: a null list is an error rather than an empty list +map(xs, 10 / (# ?? 0));{};!error;question: a null list is an error rather than an empty list +map(xs, 10 / (# ?? 0));{xs: [1, 'a']};!error +map(xs, 10 / (# ?? 0));{xs: ['a', 20]};!error +map(xs, 10 / (# ?? 0));{xs: 'abc'};!error +# some/all/none stop at the deciding element, so a bad element after it is never evaluated +some(xs, # > 3);{xs: [5, null]};true +some(xs, # > 3);{xs: [null, 5]};!error +some(xs, # > 3);{xs: [5, 'a', {}]};true +some(xs, # > 3);{xs: [1, 'a']};!error +all(xs, # > 3);{xs: [1, null]};false +all(xs, # > 3);{xs: [null, 1]};!error +all(xs, # > 3);{xs: [5, 6, null]};!error +none(xs, # > 3);{xs: [5, null]};false +none(xs, # > 3);{xs: [1, null]};!error +some(xs, #.a > 1);{xs: [{a: 2}, {}]};true +some(xs, #.a > 1);{xs: [{}, {a: 2}]};!error +all(xs, #.a > 1);{xs: [{a: 0}, {b: 1}]};false +all(xs, #.a > 1);{xs: [{a: 3}, {b: 1}]};!error +some(xs, # == 1 or # + {} > 0);{xs: [1, 2]};true +some(xs, # == 2 or # + {} > 0);{xs: [1, 2]};!error +# count, one, map and filter visit every element, so one bad element is an error +count(xs, # > 3);{xs: [5, null]};!error +count(xs, # > 3);{xs: [5, 6]};2 +one(xs, # > 3);{xs: [5, 1, null]};!error +one(xs, # > 3);{xs: [5, 6, null]};!error;question: one() keeps evaluating after a second match already decided false +map(xs, # * 2);{xs: [1, 2, null]};!error +map(xs, # * 2);{xs: [null, 1, 2]};!error +filter(xs, # > 1);{xs: [2, 3, null]};!error +flatMap(xs, [# * 2]);{xs: [1, null]};!error +flatMap(xs, [# ?? 0]);{xs: [1, null]};[1, 0] +# Filtering before mapping removes the elements that would fail +map(filter(xs, type(#) == 'number'), # * 2);{xs: [1, null, 'a', 3]};[2, 6] +map(filter(xs, type(#) == 'number'), # * 2);{xs: [null, null]};[] +map(filter(xs, type(#) == 'number'), # * 2);{xs: []};[] +map(filter(xs, type(#) == 'number'), # * 2);{xs: [0.5, true]};[1.0] +sum(filter(xs, type(#) == 'number'));{xs: [1, null, 'a', 3]};4 +sum(filter(xs, type(#) == 'number'));{xs: [null, null]};0 +sum(filter(xs, type(#) == 'number'));{xs: []};0 +sum(filter(xs, type(#) == 'number'));{xs: [0.5, true]};0.5 +map(xs, # * 2);{xs: [1, null, 'a', 3]};!error +map(xs, # * 2);{xs: [null, null]};!error +map(xs, # * 2);{xs: []};[] +map(xs, # * 2);{xs: [0.5, true]};!error +filter(map(xs, # ?? 0), # != 0);{xs: [1, null, 'a', 3]};[1, 'a', 3] +filter(map(xs, # ?? 0), # != 0);{xs: [null, null]};[] +filter(map(xs, # ?? 0), # != 0);{xs: []};[] +filter(map(xs, # ?? 0), # != 0);{xs: [0.5, true]};[0.5, true] +# Null predicate results are errors, not false +filter(xs, #.ok);{xs: [{ok: true}, {ok: false}]};[{ok: true}] +filter(xs, #.ok);{xs: [{ok: true}, {ok: null}]};!error;question: a null predicate result is an error, not falsy +filter(xs, #.ok);{xs: [{ok: true}, {}]};!error;question: a null predicate result is an error, not falsy +filter(xs, #.ok);{xs: [{ok: 'yes'}]};!error +filter(xs, #.ok);{xs: [{ok: false}, {ok: null}]};!error;question: a null predicate result is an error, not falsy +filter(xs, #.ok ?? false);{xs: [{ok: true}, {ok: false}]};[{ok: true}] +filter(xs, #.ok ?? false);{xs: [{ok: true}, {ok: null}]};[{ok: true}] +filter(xs, #.ok ?? false);{xs: [{ok: true}, {}]};[{ok: true}] +filter(xs, #.ok ?? false);{xs: [{ok: 'yes'}]};!error +filter(xs, #.ok ?? false);{xs: [{ok: false}, {ok: null}]};[] +filter(xs, #.ok == true);{xs: [{ok: true}, {ok: false}]};[{ok: true}] +filter(xs, #.ok == true);{xs: [{ok: true}, {ok: null}]};[{ok: true}] +filter(xs, #.ok == true);{xs: [{ok: true}, {}]};[{ok: true}] +filter(xs, #.ok == true);{xs: [{ok: 'yes'}]};[] +filter(xs, #.ok == true);{xs: [{ok: false}, {ok: null}]};[] +some(xs, #.ok);{xs: [{ok: true}, {ok: false}]};true +some(xs, #.ok);{xs: [{ok: true}, {ok: null}]};true +some(xs, #.ok);{xs: [{ok: true}, {}]};true +some(xs, #.ok);{xs: [{ok: 'yes'}]};!error +some(xs, #.ok);{xs: [{ok: false}, {ok: null}]};!error;question: a null predicate result is an error, not falsy +all(xs, #.ok);{xs: [{ok: true}, {ok: false}]};false +all(xs, #.ok);{xs: [{ok: true}, {ok: null}]};!error;question: a null predicate result is an error, not falsy +all(xs, #.ok);{xs: [{ok: true}, {}]};!error;question: a null predicate result is an error, not falsy +all(xs, #.ok);{xs: [{ok: 'yes'}]};!error +all(xs, #.ok);{xs: [{ok: false}, {ok: null}]};false +count(xs, #.ok);{xs: [{ok: true}, {ok: false}]};1 +count(xs, #.ok);{xs: [{ok: true}, {ok: null}]};!error;question: a null predicate result is an error, not falsy +count(xs, #.ok);{xs: [{ok: true}, {}]};!error;question: a null predicate result is an error, not falsy +count(xs, #.ok);{xs: [{ok: 'yes'}]};!error +count(xs, #.ok);{xs: [{ok: false}, {ok: null}]};!error;question: a null predicate result is an error, not falsy +count(xs, #.ok ?? false);{xs: [{ok: true}, {ok: false}]};1 +count(xs, #.ok ?? false);{xs: [{ok: true}, {ok: null}]};1 +count(xs, #.ok ?? false);{xs: [{ok: true}, {}]};1 +count(xs, #.ok ?? false);{xs: [{ok: 'yes'}]};!error +count(xs, #.ok ?? false);{xs: [{ok: false}, {ok: null}]};0 +# Null fields in #.x +map(xs, #.p);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[10, 5] +map(xs, #.p);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};[10, null] +map(xs, #.p);{xs: [{p: 10, q: 2}, {q: 1}]};[10, null] +map(xs, #.p);{xs: [{p: 10, q: 2}, null]};[10, null] +map(xs, #.p);{xs: [{p: 10, q: 2}, 7]};[10, null] +map(xs, #.p);{xs: [{p: 10, q: 0}]};[10] +map(xs, #.p);{xs: [{p: 10}]};[10] +map(xs, #.p * #.q);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[20, 5] +map(xs, #.p * #.q);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};!error +map(xs, #.p * #.q);{xs: [{p: 10, q: 2}, {q: 1}]};!error +map(xs, #.p * #.q);{xs: [{p: 10, q: 2}, null]};!error +map(xs, #.p * #.q);{xs: [{p: 10, q: 2}, 7]};!error +map(xs, #.p * #.q);{xs: [{p: 10, q: 0}]};[0] +map(xs, #.p * #.q);{xs: [{p: 10}]};!error +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[20, 5] +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10, q: 2}, {p: null, q: 1}]};[20, 0] +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10, q: 2}, {q: 1}]};[20, 0] +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10, q: 2}, null]};[20, 0] +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10, q: 2}, 7]};[20, 0] +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10, q: 0}]};[0] +map(xs, (#.p ?? 0) * (#.q ?? 1));{xs: [{p: 10}]};[10] +map(xs, #.p / #.q);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[5, 5] +map(xs, #.p / #.q);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};!error +map(xs, #.p / #.q);{xs: [{p: 10, q: 2}, {q: 1}]};!error +map(xs, #.p / #.q);{xs: [{p: 10, q: 2}, null]};!error +map(xs, #.p / #.q);{xs: [{p: 10, q: 2}, 7]};!error +map(xs, #.p / #.q);{xs: [{p: 10, q: 0}]};[null] +map(xs, #.p / #.q);{xs: [{p: 10}]};!error +sum(map(xs, #.p ?? 0));{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};15 +sum(map(xs, #.p ?? 0));{xs: [{p: 10, q: 2}, {p: null, q: 1}]};10 +sum(map(xs, #.p ?? 0));{xs: [{p: 10, q: 2}, {q: 1}]};10 +sum(map(xs, #.p ?? 0));{xs: [{p: 10, q: 2}, null]};10 +sum(map(xs, #.p ?? 0));{xs: [{p: 10, q: 2}, 7]};10 +sum(map(xs, #.p ?? 0));{xs: [{p: 10, q: 0}]};10 +sum(map(xs, #.p ?? 0));{xs: [{p: 10}]};10 +sum(map(xs, #.p));{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};15 +sum(map(xs, #.p));{xs: [{p: 10, q: 2}, {p: null, q: 1}]};!error +sum(map(xs, #.p));{xs: [{p: 10, q: 2}, {q: 1}]};!error +sum(map(xs, #.p));{xs: [{p: 10, q: 2}, null]};!error +sum(map(xs, #.p));{xs: [{p: 10, q: 2}, 7]};!error +sum(map(xs, #.p));{xs: [{p: 10, q: 0}]};10 +sum(map(xs, #.p));{xs: [{p: 10}]};10 +filter(xs, #.p > 6);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[{p: 10, q: 2}] +filter(xs, #.p > 6);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};!error +filter(xs, #.p > 6);{xs: [{p: 10, q: 2}, {q: 1}]};!error +filter(xs, #.p > 6);{xs: [{p: 10, q: 2}, null]};!error +filter(xs, #.p > 6);{xs: [{p: 10, q: 2}, 7]};!error +filter(xs, #.p > 6);{xs: [{p: 10, q: 0}]};[{p: 10, q: 0}] +filter(xs, #.p > 6);{xs: [{p: 10}]};[{p: 10}] +count(xs, #.p == null);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};0 +count(xs, #.p == null);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};1 +count(xs, #.p == null);{xs: [{p: 10, q: 2}, {q: 1}]};1 +count(xs, #.p == null);{xs: [{p: 10, q: 2}, null]};1 +count(xs, #.p == null);{xs: [{p: 10, q: 2}, 7]};1 +count(xs, #.p == null);{xs: [{p: 10, q: 0}]};0 +count(xs, #.p == null);{xs: [{p: 10}]};0 +map(xs, {p: #.p, q: #.q});{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[{p: 10, q: 2}, {p: 5, q: 1}] +map(xs, {p: #.p, q: #.q});{xs: [{p: 10, q: 2}, {p: null, q: 1}]};[{p: 10, q: 2}, {p: null, q: 1}] +map(xs, {p: #.p, q: #.q});{xs: [{p: 10, q: 2}, {q: 1}]};[{p: 10, q: 2}, {p: null, q: 1}] +map(xs, {p: #.p, q: #.q});{xs: [{p: 10, q: 2}, null]};[{p: 10, q: 2}, {p: null, q: null}] +map(xs, {p: #.p, q: #.q});{xs: [{p: 10, q: 2}, 7]};[{p: 10, q: 2}, {p: null, q: null}] +map(xs, {p: #.p, q: #.q});{xs: [{p: 10, q: 0}]};[{p: 10, q: 0}] +map(xs, {p: #.p, q: #.q});{xs: [{p: 10}]};[{p: 10, q: null}] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};['10/2', '5/1'] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};['10/2', 'null/1'] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10, q: 2}, {q: 1}]};['10/2', 'null/1'] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10, q: 2}, null]};['10/2', 'null/null'] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10, q: 2}, 7]};['10/2', 'null/null'] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10, q: 0}]};['10/0'] +map(xs, `${#.p}/${#.q}`);{xs: [{p: 10}]};['10/null'] +# Nested closures over null inner lists +map(xs, len(#.t ?? []));{xs: [{t: [1, 2]}, {t: [3]}]};[2, 1] +map(xs, len(#.t ?? []));{xs: [{t: [1, 2]}, {t: []}]};[2, 0] +map(xs, len(#.t ?? []));{xs: [{t: [1, 2]}, {t: null}]};[2, 0] +map(xs, len(#.t ?? []));{xs: [{t: [1, 2]}, {}]};[2, 0] +map(xs, len(#.t ?? []));{xs: [{t: [1, null]}]};[2] +map(xs, sum(#.t ?? []));{xs: [{t: [1, 2]}, {t: [3]}]};[3, 3] +map(xs, sum(#.t ?? []));{xs: [{t: [1, 2]}, {t: []}]};[3, 0] +map(xs, sum(#.t ?? []));{xs: [{t: [1, 2]}, {t: null}]};[3, 0] +map(xs, sum(#.t ?? []));{xs: [{t: [1, 2]}, {}]};[3, 0] +map(xs, sum(#.t ?? []));{xs: [{t: [1, null]}]};!error +map(xs, map(#.t, # * 10));{xs: [{t: [1, 2]}, {t: [3]}]};[[10, 20], [30]] +map(xs, map(#.t, # * 10));{xs: [{t: [1, 2]}, {t: []}]};[[10, 20], []] +map(xs, map(#.t, # * 10));{xs: [{t: [1, 2]}, {t: null}]};!error +map(xs, map(#.t, # * 10));{xs: [{t: [1, 2]}, {}]};!error +map(xs, map(#.t, # * 10));{xs: [{t: [1, null]}]};!error +map(xs, map(#.t ?? [], (# ?? 0) * 10));{xs: [{t: [1, 2]}, {t: [3]}]};[[10, 20], [30]] +map(xs, map(#.t ?? [], (# ?? 0) * 10));{xs: [{t: [1, 2]}, {t: []}]};[[10, 20], []] +map(xs, map(#.t ?? [], (# ?? 0) * 10));{xs: [{t: [1, 2]}, {t: null}]};[[10, 20], []] +map(xs, map(#.t ?? [], (# ?? 0) * 10));{xs: [{t: [1, 2]}, {}]};[[10, 20], []] +map(xs, map(#.t ?? [], (# ?? 0) * 10));{xs: [{t: [1, null]}]};[[10, 0]] +flatMap(xs, #.t ?? []);{xs: [{t: [1, 2]}, {t: [3]}]};[1, 2, 3] +flatMap(xs, #.t ?? []);{xs: [{t: [1, 2]}, {t: []}]};[1, 2] +flatMap(xs, #.t ?? []);{xs: [{t: [1, 2]}, {t: null}]};[1, 2] +flatMap(xs, #.t ?? []);{xs: [{t: [1, 2]}, {}]};[1, 2] +flatMap(xs, #.t ?? []);{xs: [{t: [1, null]}]};[1, null] +some(xs, some(#.t ?? [], # == null));{xs: [{t: [1, 2]}, {t: [3]}]};false +some(xs, some(#.t ?? [], # == null));{xs: [{t: [1, 2]}, {t: []}]};false +some(xs, some(#.t ?? [], # == null));{xs: [{t: [1, 2]}, {t: null}]};false +some(xs, some(#.t ?? [], # == null));{xs: [{t: [1, 2]}, {}]};false +some(xs, some(#.t ?? [], # == null));{xs: [{t: [1, null]}]};true +filter(xs, #.t != null and len(#.t) > 1);{xs: [{t: [1, 2]}, {t: [3]}]};[{t: [1, 2]}] +filter(xs, #.t != null and len(#.t) > 1);{xs: [{t: [1, 2]}, {t: []}]};[{t: [1, 2]}] +filter(xs, #.t != null and len(#.t) > 1);{xs: [{t: [1, 2]}, {t: null}]};[{t: [1, 2]}] +filter(xs, #.t != null and len(#.t) > 1);{xs: [{t: [1, 2]}, {}]};[{t: [1, 2]}] +filter(xs, #.t != null and len(#.t) > 1);{xs: [{t: [1, null]}]};[{t: [1, null]}] +# Named closure variables behave like # +map(xs as x, x ?? 0);{xs: [1, 5, 10]};[1, 5, 10] +map(xs as x, x ?? 0);{xs: [5, null, 10]};[5, 0, 10] +map(xs as x, x ?? 0);{xs: []};[] +map(xs as x, x ?? 0);{xs: null};!error +map(xs as x, x ?? 0);{};!error +map(xs as x, x ?? 0);{xs: [1, 'a']};[1, 'a'] +filter(xs as x, x != null);{xs: [1, 5, 10]};[1, 5, 10] +filter(xs as x, x != null);{xs: [5, null, 10]};[5, 10] +filter(xs as x, x != null);{xs: []};[] +filter(xs as x, x != null);{xs: null};!error +filter(xs as x, x != null);{};!error +filter(xs as x, x != null);{xs: [1, 'a']};[1, 'a'] +map(xs as x, x.p ?? x);{xs: [{p: 10, q: 2}, {p: 5, q: 1}]};[10, 5] +map(xs as x, x.p ?? x);{xs: [{p: 10, q: 2}, {p: null, q: 1}]};[10, {p: null, q: 1}] +map(xs as x, x.p ?? x);{xs: [{p: 10, q: 2}, {q: 1}]};[10, {q: 1}] +map(xs as x, x.p ?? x);{xs: [{p: 10, q: 2}, null]};[10, null] +map(xs as x, x.p ?? x);{xs: [{p: 10, q: 2}, 7]};[10, 7] +map(xs as x, x.p ?? x);{xs: [{p: 10, q: 0}]};[10] +map(xs as x, x.p ?? x);{xs: [{p: 10}]};[10] +# Outer inputs that are null inside a closure body +map(xs, # * k);{xs: [1, 2], k: 10};[10, 20] +map(xs, # * k);{xs: [1, 2], k: null};!error +map(xs, # * k);{xs: [1, 2]};!error +map(xs, # * k);{xs: [], k: null};[] +map(xs, # * k);{xs: [1, 2], k: 'a'};!error +map(xs, # * (k ?? 1));{xs: [1, 2], k: 10};[10, 20] +map(xs, # * (k ?? 1));{xs: [1, 2], k: null};[1, 2] +map(xs, # * (k ?? 1));{xs: [1, 2]};[1, 2] +map(xs, # * (k ?? 1));{xs: [], k: null};[] +map(xs, # * (k ?? 1));{xs: [1, 2], k: 'a'};!error +filter(xs, # < k);{xs: [1, 2], k: 10};[1, 2] +filter(xs, # < k);{xs: [1, 2], k: null};!error +filter(xs, # < k);{xs: [1, 2]};!error +filter(xs, # < k);{xs: [], k: null};[] +filter(xs, # < k);{xs: [1, 2], k: 'a'};!error +map(xs, k == null ? # : # + k);{xs: [1, 2], k: 10};[11, 12] +map(xs, k == null ? # : # + k);{xs: [1, 2], k: null};[1, 2] +map(xs, k == null ? # : # + k);{xs: [1, 2]};[1, 2] +map(xs, k == null ? # : # + k);{xs: [], k: null};[] +map(xs, k == null ? # : # + k);{xs: [1, 2], k: 'a'};!error diff --git a/core/expression/tests/spec/standard/11-05-null-programs.csv b/core/expression/tests/spec/standard/11-05-null-programs.csv new file mode 100644 index 00000000..4d2ca9c0 --- /dev/null +++ b/core/expression/tests/spec/standard/11-05-null-programs.csv @@ -0,0 +1,314 @@ +expression (string);input (json 5);output (json 5);note +# An assignment of null keeps the key, and later reads see null +"y = x.a; y";{};null +"y = x.a; y";{x: {a: 3}};3 +"y = x.a; y";{x: 5};null +y = x.a;{};{y: null} +"y = x.a; y ?? 'none'";{};'none' +"y = x.a; y ?? 'none'";{x: {a: false}};false +"y = x.a; y + 1";{};!error +"y = x.a; y + 1";{x: {a: 1}};2 +"y = x.a; y == null";{x: {}};true +"y = x.a; y.b.c";{x: {a: 1}};null +"y = null; $root";{y: 1};{y: null} +"y = x ?? 0; y + 1";{x: null};1 +"y = x ?? 0; y + 1";{x: 4};5 +"y = x ?? 0; y + 1";{x: 'a'};!error +"y = x / 0; y";{x: 1};null +"y = x / 0; y ?? 'div0'";{x: 1};'div0' +"y = x / 0; y + 1";{x: 1};!error +"y = x / z; y ?? 0";{x: 1, z: 0};0 +"y = x / z; y ?? 0";{x: 1, z: 4};0.25 +"y = x / z; y ?? 0";{x: 1};!error +"y = [x, x.a]; y";{};[null, null] +"y = {v: x}; y.v ?? 'd'";{};'d' +"y = {v: x}; y";{};{v: null} +# An error after assignments aborts the whole program +"x = 1; 1 + {}";{};!error +"x = 1; y = x + {}; x";{};!error +"x = 1 + {}; 2";{};!error +"x = 1; y = null; y + 1";{};!error +"x = 1; y = null; y ?? x";{};1 +"x = 1; y = 2; upper(y)";{};!error +"x = a; x.b = 1; x";{a: null};{b: 1} +"x = a * 2; x";{a: null};!error +"x = a * 2; x";{a: 3};6 +"x = a * 2; x";{};!error +"x = a ?? 1; y = x * 2; y";{};2 +"x = a ?? 1; y = x * 2; y";{a: 5};10 +"x = a ?? 1; y = x * 2; y";{a: 'q'};!error +"x = true ? 1 : 1 + {}; x";{};1 +"x = false and 1 + {}; x";{};false +"x = null ?? 3; x";{};3 +"x = [1 + {}]; 1";{};!error +"x = map([1, 2], # / 0); x";{};[null, null] +"x = map([1, 2], # / 0); x[0] ?? 'z'";{};'z' +# Dotted assignment into null, missing and non-object values +"a.b = 1; a";{a: null};{b: 1} +"a.b = 1; a";{};{b: 1} +"a.b = 1; a";{a: 5};{b: 1} +"a.b = 1; a";{a: {c: null}};{c: null, b: 1} +"a.b = 1; a";{a: {b: null}};{b: 1} +"x = a.b; a.b = 7; x";{a: null};null +"x = a.b; a.b = 7; x";{};null +"x = a.b; a.b = 7; x";{a: {b: null}};null +"x = a.b; a.b = 7; x";{a: {b: 2}};2 +"a.n = (a.n ?? 0) + 1; a.n";{a: null};1 +"a.n = (a.n ?? 0) + 1; a.n";{};1 +"a.n = (a.n ?? 0) + 1; a.n";{a: {n: null}};1 +"a.n = (a.n ?? 0) + 1; a.n";{a: {n: 4}};5 +"a.n = (a.n ?? 0) + 1; a.n";{a: {n: 'x'}};!error +"a.n = a.n + 1; a.n";{a: null};!error +"a.n = a.n + 1; a.n";{a: {n: 4}};5 +"a.n = a.n + 1; a.n";{};!error +# A null inside array and object literals is kept, an error is not +[a, b.c, a ?? 0];{a: 1, b: {c: 2}};[1, 2, 1] +[a, b.c, a ?? 0];{a: null, b: null};[null, null, 0] +[a, b.c, a ?? 0];{};[null, null, 0] +[a, b.c, a ?? 0];{a: 'x', b: 5};['x', null, 'x'] +{a: a, c: b.c};{a: 1, b: {c: 2}};{a: 1, c: 2} +{a: a, c: b.c};{a: null, b: null};{a: null, c: null} +{a: a, c: b.c};{};{a: null, c: null} +{a: a, c: b.c};{a: 'x', b: 5};{a: 'x', c: null} +[a, b.c + 1];{a: 1, b: {c: 2}};[1, 3] +[a, b.c + 1];{a: null, b: null};!error +[a, b.c + 1];{};!error +[a, b.c + 1];{a: 'x', b: 5};!error +{x: a, y: a * 2};{a: 1, b: {c: 2}};{x: 1, y: 2} +{x: a, y: a * 2};{a: null, b: null};!error +{x: a, y: a * 2};{};!error +{x: a, y: a * 2};{a: 'x', b: 5};!error +len([a, b, c]);{a: 1, b: {c: 2}};3 +len([a, b, c]);{a: null, b: null};3 +len([a, b, c]);{};3 +len([a, b, c]);{a: 'x', b: 5};3 +[a, b][1].c;{a: 1, b: {c: 2}};2 +[a, b][1].c;{a: null, b: null};null +[a, b][1].c;{};null +[a, b][1].c;{a: 'x', b: 5};null +{k: a}.k ?? 9;{a: 1, b: {c: 2}};1;bug: postfix access works on a parenthesized object literal but not a bare one +{k: a}.k ?? 9;{a: null, b: null};9;bug: postfix access works on a parenthesized object literal but not a bare one +{k: a}.k ?? 9;{};9;bug: postfix access works on a parenthesized object literal but not a bare one +{k: a}.k ?? 9;{a: 'x', b: 5};'x';bug: postfix access works on a parenthesized object literal but not a bare one +({k: a}).k ?? 9;{a: 1, b: {c: 2}};1 +({k: a}).k ?? 9;{a: null, b: null};9 +({k: a}).k ?? 9;{};9 +({k: a}).k ?? 9;{a: 'x', b: 5};'x' +[[a]][0][0] ?? 9;{a: 1, b: {c: 2}};1 +[[a]][0][0] ?? 9;{a: null, b: null};9 +[[a]][0][0] ?? 9;{};9 +[[a]][0][0] ?? 9;{a: 'x', b: 5};'x' +{[a]: 1};{a: 'k'};{k: 1} +{[a]: 1};{a: null};{null: 1};question: a null computed key becomes the string 'null' +{[a]: 1};{};{null: 1};question: a null computed key becomes the string 'null' +{[a]: 1};{a: 2};{'2': 1} +# Templates interpolate null as the text null and fail on errors inside an interpolation +`${n} (${age})`;{n: 'Ann', age: 30};'Ann (30)' +`${n} (${age})`;{n: 'Ann', age: null};'Ann (null)' +`${n} (${age})`;{n: 'Ann'};'Ann (null)' +`${n} (${age})`;{};'null (null)' +`${n} (${age})`;{n: ['A'], age: 1};!error +`${n} (${age})`;{n: 'Ann', age: 2.50};'Ann (2.50)' +`${n ?? '?'} (${age ?? '-'})`;{n: 'Ann', age: 30};'Ann (30)' +`${n ?? '?'} (${age ?? '-'})`;{n: 'Ann', age: null};'Ann (-)' +`${n ?? '?'} (${age ?? '-'})`;{n: 'Ann'};'Ann (-)' +`${n ?? '?'} (${age ?? '-'})`;{};'? (-)' +`${n ?? '?'} (${age ?? '-'})`;{n: ['A'], age: 1};!error +`${n ?? '?'} (${age ?? '-'})`;{n: 'Ann', age: 2.50};'Ann (2.50)' +`${n} is ${age + 1}`;{n: 'Ann', age: 30};'Ann is 31' +`${n} is ${age + 1}`;{n: 'Ann', age: null};!error +`${n} is ${age + 1}`;{n: 'Ann'};!error +`${n} is ${age + 1}`;{};!error +`${n} is ${age + 1}`;{n: ['A'], age: 1};!error +`${n} is ${age + 1}`;{n: 'Ann', age: 2.50};'Ann is 3.50' +`${age == null ? 'unknown' : age}`;{n: 'Ann', age: 30};'30' +`${age == null ? 'unknown' : age}`;{n: 'Ann', age: null};'unknown' +`${age == null ? 'unknown' : age}`;{n: 'Ann'};'unknown' +`${age == null ? 'unknown' : age}`;{};'unknown' +`${age == null ? 'unknown' : age}`;{n: ['A'], age: 1};'1' +`${age == null ? 'unknown' : age}`;{n: 'Ann', age: 2.50};'2.50' +`${upper(n)}`;{n: 'Ann', age: 30};'ANN' +`${upper(n)}`;{n: 'Ann', age: null};'ANN' +`${upper(n)}`;{n: 'Ann'};'ANN' +`${upper(n)}`;{};!error +`${upper(n)}`;{n: ['A'], age: 1};!error +`${upper(n)}`;{n: 'Ann', age: 2.50};'ANN' +`${type(age)}`;{n: 'Ann', age: 30};'number' +`${type(age)}`;{n: 'Ann', age: null};'null' +`${type(age)}`;{n: 'Ann'};'null' +`${type(age)}`;{};'null' +`${type(age)}`;{n: ['A'], age: 1};'number' +`${type(age)}`;{n: 'Ann', age: 2.50};'number' +`${age / 0}`;{n: 'Ann', age: 30};'null' +`${age / 0}`;{n: 'Ann', age: null};!error +`${age / 0}`;{n: 'Ann'};!error +`${age / 0}`;{};!error +`${age / 0}`;{n: ['A'], age: 1};'null' +`${age / 0}`;{n: 'Ann', age: 2.50};'null' +`${n}` == 'null';{n: 'Ann', age: 30};false +`${n}` == 'null';{n: 'Ann', age: null};false +`${n}` == 'null';{n: 'Ann'};false +`${n}` == 'null';{};true +`${n}` == 'null';{n: ['A'], age: 1};!error +`${n}` == 'null';{n: 'Ann', age: 2.50};false +# String concatenation with null is an error; string() and templates are the null-safe forms +s + t;{s: 'a', t: 'b'};'ab' +s + t;{s: 'a', t: null};!error +s + t;{s: 'a'};!error +s + t;{t: 'b'};!error +s + t;{s: 'a', t: 1};!error +s + (t ?? '');{s: 'a', t: 'b'};'ab' +s + (t ?? '');{s: 'a', t: null};'a' +s + (t ?? '');{s: 'a'};'a' +s + (t ?? '');{t: 'b'};!error +s + (t ?? '');{s: 'a', t: 1};!error +(s ?? '') + (t ?? '');{s: 'a', t: 'b'};'ab' +(s ?? '') + (t ?? '');{s: 'a', t: null};'a' +(s ?? '') + (t ?? '');{s: 'a'};'a' +(s ?? '') + (t ?? '');{t: 'b'};'b' +(s ?? '') + (t ?? '');{s: 'a', t: 1};!error +s + string(t);{s: 'a', t: 'b'};'ab' +s + string(t);{s: 'a', t: null};'anull' +s + string(t);{s: 'a'};'anull' +s + string(t);{t: 'b'};!error +s + string(t);{s: 'a', t: 1};'a1' +`${s}${t}`;{s: 'a', t: 'b'};'ab' +`${s}${t}`;{s: 'a', t: null};'anull' +`${s}${t}`;{s: 'a'};'anull' +`${s}${t}`;{t: 'b'};'nullb' +`${s}${t}`;{s: 'a', t: 1};'a1' +t == null ? s : s + t;{s: 'a', t: 'b'};'ab' +t == null ? s : s + t;{s: 'a', t: null};'a' +t == null ? s : s + t;{s: 'a'};'a' +t == null ? s : s + t;{t: 'b'};!error +t == null ? s : s + t;{s: 'a', t: 1};!error +# Member access chains mixing computed keys, indexes and nulls +m[k][i].v;{m: {x: [{v: 1}]}, k: 'x', i: 0};1 +m[k][i].v;{m: {x: [{v: 1}]}, k: 'y', i: 0};null +m[k][i].v;{m: {x: [{v: 1}]}, k: null, i: 0};null +m[k][i].v;{m: {x: [{v: 1}]}, k: 'x', i: 1};null +m[k][i].v;{m: {x: [{v: 1}]}, k: 'x'};null +m[k][i].v;{m: {x: [null]}, k: 'x', i: 0};null +m[k][i].v;{m: null, k: 'x', i: 0};null +m[k][i].v;{};null +m[k][i].v ?? -1;{m: {x: [{v: 1}]}, k: 'x', i: 0};1 +m[k][i].v ?? -1;{m: {x: [{v: 1}]}, k: 'y', i: 0};-1 +m[k][i].v ?? -1;{m: {x: [{v: 1}]}, k: null, i: 0};-1 +m[k][i].v ?? -1;{m: {x: [{v: 1}]}, k: 'x', i: 1};-1 +m[k][i].v ?? -1;{m: {x: [{v: 1}]}, k: 'x'};-1 +m[k][i].v ?? -1;{m: {x: [null]}, k: 'x', i: 0};-1 +m[k][i].v ?? -1;{m: null, k: 'x', i: 0};-1 +m[k][i].v ?? -1;{};-1 +m[k][i].v + 1;{m: {x: [{v: 1}]}, k: 'x', i: 0};2 +m[k][i].v + 1;{m: {x: [{v: 1}]}, k: 'y', i: 0};!error +m[k][i].v + 1;{m: {x: [{v: 1}]}, k: null, i: 0};!error +m[k][i].v + 1;{m: {x: [{v: 1}]}, k: 'x', i: 1};!error +m[k][i].v + 1;{m: {x: [{v: 1}]}, k: 'x'};!error +m[k][i].v + 1;{m: {x: [null]}, k: 'x', i: 0};!error +m[k][i].v + 1;{m: null, k: 'x', i: 0};!error +m[k][i].v + 1;{};!error +m[k ?? 'x'][i ?? 0].v;{m: {x: [{v: 1}]}, k: 'x', i: 0};1 +m[k ?? 'x'][i ?? 0].v;{m: {x: [{v: 1}]}, k: 'y', i: 0};null +m[k ?? 'x'][i ?? 0].v;{m: {x: [{v: 1}]}, k: null, i: 0};1 +m[k ?? 'x'][i ?? 0].v;{m: {x: [{v: 1}]}, k: 'x', i: 1};null +m[k ?? 'x'][i ?? 0].v;{m: {x: [{v: 1}]}, k: 'x'};1 +m[k ?? 'x'][i ?? 0].v;{m: {x: [null]}, k: 'x', i: 0};null +m[k ?? 'x'][i ?? 0].v;{m: null, k: 'x', i: 0};null +m[k ?? 'x'][i ?? 0].v;{};null +m[k][i];{m: {x: [{v: 1}]}, k: 'x', i: 0};{v: 1} +m[k][i];{m: {x: [{v: 1}]}, k: 'y', i: 0};null +m[k][i];{m: {x: [{v: 1}]}, k: null, i: 0};null +m[k][i];{m: {x: [{v: 1}]}, k: 'x', i: 1};null +m[k][i];{m: {x: [{v: 1}]}, k: 'x'};null +m[k][i];{m: {x: [null]}, k: 'x', i: 0};null +m[k][i];{m: null, k: 'x', i: 0};null +m[k][i];{};null +# Slices of null are errors while indexes of null are null +xs[0];{xs: [1, 2, 3]};1 +xs[0];{xs: null};null +xs[0];{};null +xs[0];{xs: 'abc'};'a' +xs[0:1];{xs: [1, 2, 3]};[1, 2] +xs[0:1];{xs: null};!error;question: slicing null errors while indexing null yields null +xs[0:1];{};!error;question: slicing null errors while indexing null yields null +xs[0:1];{xs: 'abc'};'ab' +(xs ?? [0, 0])[0:1];{xs: [1, 2, 3]};[1, 2] +(xs ?? [0, 0])[0:1];{xs: null};[0, 0] +(xs ?? [0, 0])[0:1];{};[0, 0] +(xs ?? [0, 0])[0:1];{xs: 'abc'};'ab' +xs[0:1] ?? [];{xs: [1, 2, 3]};[1, 2] +xs[0:1] ?? [];{xs: null};!error;question: slicing null errors while indexing null yields null +xs[0:1] ?? [];{};!error;question: slicing null errors while indexing null yields null +xs[0:1] ?? [];{xs: 'abc'};'ab' +# A division-by-zero null reaching other operators and functions +(x / y) ^ 2;{x: 1, y: 0};!error +2 ^ (x / y);{x: 1, y: 0};!error +(x / y) % 2;{x: 1, y: 0};!error +abs(x / y);{x: 1, y: 0};!error +abs(x / y);{x: -1, y: 2};0.5 +len([x / y]);{x: 1, y: 0};1 +[x / y] == [null];{x: 1, y: 0};true;bug: == on arrays/objects is always false, even for a value compared with itself (Variable itself itself implements deep equality) +(x / y) in [null, 0];{x: 1, y: 0};true +(x / y) in [null, 0];{x: 0, y: 1};true +(x / y) in [null, 0];{x: 1, y: 1};false +count([1 / 0, 2 / 0, 1 / 1], # == null);;2 +filter([1, 0, 2], 1 / # > 0);;!error +filter([1, 0, 2], (1 / #) != null);;[1, 2] +map([1, 0, 2], (1 / #) ?? 'inf');;[1, 'inf', 0.5] +some([0, 1], 1 / # > 0);;!error +some([1, 0], 1 / # > 0);;true +max(map([1, 0, 4], (8 / #) ?? 0));;8 +# Coalesced defaults feeding functions +max([x ?? 0, y ?? 0]);{y: 3};3 +max([x ?? 0, y ?? 0]);{x: -1, y: null};0 +max([x ?? 0, y ?? 0]);{x: 'a'};!error +min(map(xs, # ?? 99));{xs: [null, 5]};5 +min(map(xs, # ?? 99));{xs: [null]};99 +min(map(xs, # ?? 99));{xs: []};!error +median(map(xs, # ?? 0));{xs: [null, 5, 1]};1 +mode(xs ?? [1]);{};1 +avg(xs ?? [1, 2]);{};1.5 +avg(xs ?? [1, 2]);{xs: null};1.5 +avg(xs ?? [1, 2]);{xs: [4]};4 +fuzzyMatch(s ?? '', 'a');{};0 +extract(s ?? '', '(a)');{};[] +extract(s ?? '', '(a)');{s: 'xa'};['a', 'a'] +d(x ?? 0).year();{};1970 +string(x ?? null);{};'null' +bool(x ?? 'true');{};true +bool(x ?? 'true');{x: false};false +(x ?? 1) ^ (y ?? 2);{};1 +(x ?? 1) ^ (y ?? 2);{x: 3};9 +not (x ?? true);{};false +not (x ?? true);{x: false};true +-(x ?? 1);{};-1 +-(x ?? 1);{x: null};-1 +-(x ?? 1);{x: 2};-2 +`${(x ?? [])[0]}`;{};'null' +`${len(x ?? '')}`;{};'0' +`${len(x ?? '')}`;{x: 'abc'};'3' +# Reassigning null and extending null in a program +"x = null; x.y.z";{};null +"x = null; x[0]";{};null +"x = null; x[0:1]";{};!error +"x = {}; x.a.b = 1; x";{};{a: {b: 1}} +"x.a = null; x.a.b = 1; x";{};{a: {b: 1}} +"x.a = 1; x.a = null; x";{};{a: null} +"x.a = 1; x.a = null; x.a ?? 'gone'";{};'gone' +"x = 1; x = null; x ?? 2";{};2 +"x = 1; x = x / 0; x";{};null +"x = [1, null]; x[1] ?? x[0]";{};1 +"x = m[k]; x ?? 'nokey'";{m: {a: 1}, k: 'a'};1 +"x = m[k]; x ?? 'nokey'";{m: {a: 1}, k: 'b'};'nokey' +"x = m[k]; x ?? 'nokey'";{m: {a: 1}};'nokey' +"x = m[k]; x ?? 'nokey'";{k: 'a'};'nokey' +# $root reads follow the same null rules +$root.a.b ?? 1;{a: null};1 +$root.a.b ?? 1;{a: {b: 0}};0 +$root.a.b + 1;{};!error +$root[k] ?? 'd';{};'d' +$root[k] ?? 'd';{k: null};'d' +$root[k] ?? 'd';{k: 'k'};'k' +$root.xs[0].a ?? -1;{xs: [{a: 3}]};3 +$root.xs[0].a ?? -1;{xs: []};-1 +$root.xs[0].a ?? -1;{xs: null};-1 diff --git a/core/expression/tests/spec/standard/12-billing.csv b/core/expression/tests/spec/standard/12-billing.csv new file mode 100644 index 00000000..7f85bd18 --- /dev/null +++ b/core/expression/tests/spec/standard/12-billing.csv @@ -0,0 +1,122 @@ +expression (string);input (json 5);output (json 5);note +# Mid-cycle proration by days +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 29, newPrice: 99, periodStart: '2025-03-01', periodEnd: '2025-04-01', changeDate: '2025-03-16'};36.13 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 29, newPrice: 99, periodStart: '2025-02-01', periodEnd: '2025-03-01', changeDate: '2025-02-15'};35 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 29, newPrice: 99, periodStart: '2024-02-01', periodEnd: '2024-03-01', changeDate: '2024-02-15'};36.21 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 99, newPrice: 29, periodStart: '2025-03-01', periodEnd: '2025-04-01', changeDate: '2025-03-31'};-2.26 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 10, newPrice: 20, periodStart: '2025-03-01', periodEnd: '2025-04-01', changeDate: '2025-03-01'};10 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 10, newPrice: 20, periodStart: '2025-03-01', periodEnd: '2025-04-01', changeDate: '2025-04-01'};0 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 10, newPrice: 20, periodStart: '2025-03-01', periodEnd: '2025-03-01', changeDate: '2025-03-01'};!error +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 12.99, newPrice: 24.99, periodStart: '2024-12-15', periodEnd: '2025-01-15', changeDate: '2024-12-31'};5.81 +"total = d(periodEnd).diff(d(periodStart), 'day'); left = d(periodEnd).diff(d(changeDate), 'day'); round((newPrice - oldPrice) * left / total, 2)";{oldPrice: 10, newPrice: 20, periodStart: '2025-03-01', periodEnd: '2025-04-01'};!error +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 30, start: '2025-04-01'};30 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 30, start: '2025-04-30'};1 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 31, start: '2025-03-17'};15 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 28, start: '2025-02-15'};14 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 29, start: '2024-02-15'};15 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 49.99, start: '2025-01-31'};1.61 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 49.99, start: '2025-12-01'};49.99 +round(price * (d(start).endOf('month').day() - d(start).day() + 1) / d(start).endOf('month').day(), 2);{price: 49.99, start: 'soon'};!error +# Next renewal dates +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-01-31', cycles: 1, interval: 'month'};'2025-02-28' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-01-31', cycles: 2, interval: 'month'};'2025-03-31' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-01-31', cycles: 3, interval: 'month'};'2025-04-30' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2024-01-31', cycles: 1, interval: 'month'};'2024-02-29' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-01-31', cycles: 1, interval: 'quarter'};'2025-04-30' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2024-02-29', cycles: 4, interval: 'quarter'};'2025-02-28' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-08-31', cycles: 6, interval: 'month'};'2026-02-28' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-03-20', cycles: 0, interval: 'year'};'2025-03-20' +d(anchor).add(cycles * (interval == 'year' ? 12 : interval == 'quarter' ? 3 : 1), 'month').format('%Y-%m-%d');{anchor: '2025-03-20', cycles: null, interval: 'month'};!error +map([1, 2, 3, 4, 5, 6], d(anchor).add(#, 'month').day());{anchor: '2025-01-31'};[28, 31, 30, 31, 30, 31] +map([1, 2, 3, 4, 5, 6], d(anchor).add(#, 'month').day());{anchor: '2025-01-30'};[28, 30, 30, 30, 30, 30] +map([1, 2, 3, 4, 5, 6], d(anchor).add(#, 'month').day());{anchor: '2025-01-29'};[28, 29, 29, 29, 29, 29] +map([1, 2, 3, 4, 5, 6], d(anchor).add(#, 'month').day());{anchor: '2024-08-31'};[30, 31, 30, 31, 31, 28] +map([1, 2, 3, 4, 5, 6], d(anchor).add(#, 'month').day());{anchor: '2025-03-15'};[15, 15, 15, 15, 15, 15] +map([1, 2, 3, 4, 5, 6], d(anchor).add(#, 'month').day());{anchor: 'x'};[null, null, null, null, null, null] +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-03-10'};'trialing' +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-03-06'};'past_due' +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-03-06', paymentMethod: 'card'};'active' +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-02-18', trialDays: 30};'past_due' +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-02-17', trialDays: 30, paymentMethod: 'sepa'};'active' +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-03-20 10:15:31', trialDays: 0};'trialing' +d(trialStart).add(trialDays ?? 14, 'day').isAfter(d()) ? 'trialing' : paymentMethod != null ? 'active' : 'past_due';{trialStart: '2025-03-20 10:15:30', trialDays: 0};'past_due' +# Usage-based metered billing with tiers +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 0};0.0000 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 1000};0.0000 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 1001};0.0020 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 10000};18.0000 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 10001};18.0015 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 2500000};3753.0000 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: 1234.5};0.4690 +max([0, min([units, 10000]) - 1000]) * 0.002 + max([0, units - 10000]) * 0.0015;{units: null};!error +round(sum(map(usage, #.qty)) * (sum(map(usage, #.qty)) > 100000 ? 0.0008 : 0.001) + base, 2);{base: 20, usage: [{qty: 50000}, {qty: 50000}]};120.00 +round(sum(map(usage, #.qty)) * (sum(map(usage, #.qty)) > 100000 ? 0.0008 : 0.001) + base, 2);{base: 20, usage: [{qty: 50000}, {qty: 50001}]};100.00 +round(sum(map(usage, #.qty)) * (sum(map(usage, #.qty)) > 100000 ? 0.0008 : 0.001) + base, 2);{base: 0, usage: []};0.00 +round(sum(map(usage, #.qty)) * (sum(map(usage, #.qty)) > 100000 ? 0.0008 : 0.001) + base, 2);{base: 20, usage: [{qty: 1}]};20.00 +round(sum(map(usage, #.qty)) * (sum(map(usage, #.qty)) > 100000 ? 0.0008 : 0.001) + base, 2);{base: 20, usage: [{qty: 1000}, {qty: 1997}, {qty: 2994}, {qty: 3991}, {qty: 4988}, {qty: 5985}, {qty: 6982}, {qty: 7979}, {qty: 8976}, {qty: 9973}, {qty: 10970}, {qty: 11967}, {qty: 12964}, {qty: 13961}, {qty: 14958}, {qty: 15955}, {qty: 16952}, {qty: 17949}, {qty: 18946}, {qty: 19943}, {qty: 20940}, {qty: 21937}, {qty: 22934}, {qty: 23931}, {qty: 24928}, {qty: 25925}, {qty: 26922}, {qty: 27919}, {qty: 28916}, {qty: 29913}, {qty: 30910}, {qty: 31907}, {qty: 32904}, {qty: 33901}, {qty: 34898}, {qty: 35895}, {qty: 36892}, {qty: 37889}, {qty: 38886}, {qty: 39883}, {qty: 40880}, {qty: 41877}, {qty: 42874}, {qty: 43871}, {qty: 44868}, {qty: 45865}, {qty: 46862}, {qty: 47859}]};958.09 +round(sum(map(usage, #.qty)) * (sum(map(usage, #.qty)) > 100000 ? 0.0008 : 0.001) + base, 2);{base: 20, usage: [{qty: '5'}]};!error +map(usage, {day: d(#.at).format('%Y-%m-%d'), cost: round(#.qty * price, 4)});{price: 0.00015, usage: [{at: '2025-03-01 23:59:59', qty: 1234}, {at: '2025-03-02 00:00:00', qty: 1}]};[{day: '2025-03-01', cost: 0.1851}, {day: '2025-03-02', cost: 0.0002}] +map(usage, {day: d(#.at).format('%Y-%m-%d'), cost: round(#.qty * price, 4)});{price: 0.5, usage: []};[] +map(usage, {day: d(#.at).format('%Y-%m-%d'), cost: round(#.qty * price, 4)});{price: 0.00003, usage: [{at: '2024-12-31 12:00', qty: 99999}]};[{day: '2024-12-31', cost: 3.0000}] +map(usage, {day: d(#.at).format('%Y-%m-%d'), cost: round(#.qty * price, 4)});{price: 0.1, usage: [{at: 'bad', qty: 1}]};[{day: 'Invalid date', cost: 0.1}] +# Seat-based pricing and add-ons +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 5, seatPrice: 12, annual: false, addons: [{price: 99}]};0 +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 6, seatPrice: 12, annual: false, addons: []};12 +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 25, seatPrice: 8.5, annual: true, addons: [{price: 49}, {price: 19.99}]};1768.99 +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 0, seatPrice: 12, annual: true, addons: []};0 +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 100, seatPrice: 7.333, annual: false, addons: []};696.64 +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 10, seatPrice: 12, addons: []};!error +seats <= 5 ? 0 : round((seats - 5) * seatPrice * (annual ? 10 : 1), 2) + sum(map(addons, #.price));{seats: 10, seatPrice: 12, annual: false, addons: null};!error +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{plan: 'starter'};0 +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{plan: 'pro'};49 +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{plan: 'business'};199 +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{plan: 'enterprise'};'contact-sales' +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{plan: 'Pro'};'contact-sales' +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{plan: null};'contact-sales' +({starter: 0, pro: 49, business: 199, enterprise: null})[plan] ?? 'contact-sales';{};'contact-sales' +# Invoices: discounts, credits, tax and balance +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [{unit: 49, qty: 1}, {unit: 12.5, qty: 4}], discountPct: 10, taxRate: 0.08, credit: 20};{subtotal: 99.0, discount: 9.90, tax: 7.13, total: 96.23, due: 76.23} +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [{unit: 49, qty: 1}], taxRate: 0.2};{subtotal: 49, discount: 0, tax: 9.8, total: 58.8, due: 58.8} +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [], taxRate: 0.2, credit: 50};{subtotal: 0, discount: 0, tax: 0.0, total: 0.0, due: 0.0} +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [{unit: 10, qty: 1}], taxRate: 0.1, credit: 500};{subtotal: 10, discount: 0, tax: 1.0, total: 11.0, due: 0.0} +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [{unit: 19.99, qty: 3}], discountPct: 15, taxRate: 0.0725};{subtotal: 59.97, discount: 9.00, tax: 3.70, total: 54.67, due: 54.67} +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [{unit: 0.333, qty: 3}], discountPct: 33.33, taxRate: 0.19, credit: 0.5};{subtotal: 0.999, discount: 0.33, tax: 0.13, total: 0.799, due: 0.299} +"sub = sum(map(lines, #.unit * #.qty)); disc = round(sub * (discountPct ?? 0) / 100, 2); tax = round((sub - disc) * taxRate, 2); total = sub - disc + tax; {subtotal: sub, discount: disc, tax: tax, total: total, due: total - min([credit ?? 0, total])}";{lines: [{unit: 10, qty: 1}], taxRate: null};!error +string(round(sum(map(lines, #.unit * #.qty)) * (1 + taxRate), 2));{lines: [{unit: 10, qty: 1}], taxRate: 0.2};'12.0' +string(round(sum(map(lines, #.unit * #.qty)) * (1 + taxRate), 2));{lines: [{unit: 10.00, qty: 1}], taxRate: 0.20};'12.00' +string(round(sum(map(lines, #.unit * #.qty)) * (1 + taxRate), 2));{lines: [{unit: 9.99, qty: 1}], taxRate: 0.21};'12.09' +string(round(sum(map(lines, #.unit * #.qty)) * (1 + taxRate), 2));{lines: [{unit: 100, qty: 3}], taxRate: 0};'300' +string(round(sum(map(lines, #.unit * #.qty)) * (1 + taxRate), 2));{lines: [{unit: 0.5, qty: 1}], taxRate: 0.1};'0.55' +string(round(sum(map(lines, #.unit * #.qty)) * (1 + taxRate), 2));{lines: [], taxRate: 0.19};'0';question: 0 * 1.19 drops the scale ('0') while other products keep it +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2025-03-20', terms: 'net30'};'19 Apr 2025' +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2025-12-15', terms: 'net30'};'14 Jan 2026' +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2025-01-31', terms: 'net30'};'02 Mar 2025' +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2024-02-14', terms: 'net15'};'29 Feb 2024' +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2025-11-02', terms: 'net60'};'01 Jan 2026' +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2025-03-20', terms: 'due-on-receipt'};'20 Mar 2025' +d(issued).add(({net15: 15, net30: 30, net60: 60})[terms] ?? 0, 'day').format('%d %b %Y');{issued: '2025-03-20'};'20 Mar 2025' +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 1000, dueDate: '2025-03-20'};0 +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 1000, dueDate: '2025-03-19'};15.00 +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 1000, dueDate: '2025-02-18'};15.00 +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 1000, dueDate: '2025-02-17'};30.00 +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 2499.99, dueDate: '2024-12-01'};150.00 +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 1000, dueDate: '2025-04-01'};0 +d().diff(d(dueDate), 'day') > 0 ? round(balance * 0.015 * ceil(d().diff(d(dueDate), 'day') / 30), 2) : 0;{balance: 0, dueDate: '2020-01-01'};0.00 +# Dunning and churn signals +"failures = count(payments, #.status == 'failed'); failures == 0 ? 'none' : failures < 3 ? 'retry' : d().diff(d(payments[len(payments) - 1].at), 'day') > 14 ? 'cancel' : 'final-notice'";{payments: [{status: 'paid', at: '2025-01-01'}]};'none' +"failures = count(payments, #.status == 'failed'); failures == 0 ? 'none' : failures < 3 ? 'retry' : d().diff(d(payments[len(payments) - 1].at), 'day') > 14 ? 'cancel' : 'final-notice'";{payments: [{status: 'failed', at: '2025-03-01'}, {status: 'failed', at: '2025-03-05'}]};'retry' +"failures = count(payments, #.status == 'failed'); failures == 0 ? 'none' : failures < 3 ? 'retry' : d().diff(d(payments[len(payments) - 1].at), 'day') > 14 ? 'cancel' : 'final-notice'";{payments: [{status: 'failed', at: '2025-02-01'}, {status: 'failed', at: '2025-02-10'}, {status: 'failed', at: '2025-03-05'}]};'cancel' +"failures = count(payments, #.status == 'failed'); failures == 0 ? 'none' : failures < 3 ? 'retry' : d().diff(d(payments[len(payments) - 1].at), 'day') > 14 ? 'cancel' : 'final-notice'";{payments: [{status: 'failed', at: '2025-02-01'}, {status: 'failed', at: '2025-02-10'}, {status: 'failed', at: '2025-03-06'}]};'final-notice' +"failures = count(payments, #.status == 'failed'); failures == 0 ? 'none' : failures < 3 ? 'retry' : d().diff(d(payments[len(payments) - 1].at), 'day') > 14 ? 'cancel' : 'final-notice'";{payments: [{status: 'failed', at: '2025-02-01'}, {status: 'failed', at: '2025-02-10'}, {status: 'failed', at: '2025-02-20'}, {status: 'paid', at: '2025-03-19'}]};'final-notice' +"failures = count(payments, #.status == 'failed'); failures == 0 ? 'none' : failures < 3 ? 'retry' : d().diff(d(payments[len(payments) - 1].at), 'day') > 14 ? 'cancel' : 'final-notice'";{payments: []};'none' +"mrr = sum(map(filter(subs, #.status == 'active'), #.interval == 'year' ? #.amount / 12 : #.amount)); round(mrr, 2)";{subs: [{status: 'active', interval: 'month', amount: 49}, {status: 'active', interval: 'year', amount: 490}, {status: 'canceled', interval: 'month', amount: 99}]};89.83 +"mrr = sum(map(filter(subs, #.status == 'active'), #.interval == 'year' ? #.amount / 12 : #.amount)); round(mrr, 2)";{subs: []};0 +"mrr = sum(map(filter(subs, #.status == 'active'), #.interval == 'year' ? #.amount / 12 : #.amount)); round(mrr, 2)";{subs: [{status: 'active', interval: 'year', amount: 1000}]};83.33 +"mrr = sum(map(filter(subs, #.status == 'active'), #.interval == 'year' ? #.amount / 12 : #.amount)); round(mrr, 2)";{subs: [{status: 'active', interval: 'year', amount: 100}, {status: 'active', interval: 'year', amount: 100}, {status: 'active', interval: 'year', amount: 100}]};25.00 +"mrr = sum(map(filter(subs, #.status == 'active'), #.interval == 'year' ? #.amount / 12 : #.amount)); round(mrr, 2)";{subs: [{status: 'active', interval: 'month', amount: 9.99}, {status: 'active', interval: 'year', amount: 99.90}, {status: 'trialing', interval: 'month', amount: 19}, {status: 'active', interval: 'year', amount: 0}, {status: 'active', interval: 'month', amount: 9.99}, {status: 'trialing', interval: 'year', amount: 99.90}, {status: 'active', interval: 'month', amount: 19}, {status: 'active', interval: 'year', amount: 0}, {status: 'trialing', interval: 'month', amount: 9.99}, {status: 'active', interval: 'year', amount: 99.90}, {status: 'active', interval: 'month', amount: 19}, {status: 'trialing', interval: 'year', amount: 0}, {status: 'active', interval: 'month', amount: 9.99}, {status: 'active', interval: 'year', amount: 99.90}, {status: 'trialing', interval: 'month', amount: 19}, {status: 'active', interval: 'year', amount: 0}, {status: 'active', interval: 'month', amount: 9.99}, {status: 'trialing', interval: 'year', amount: 99.90}, {status: 'active', interval: 'month', amount: 19}, {status: 'active', interval: 'year', amount: 0}, {status: 'trialing', interval: 'month', amount: 9.99}, {status: 'active', interval: 'year', amount: 99.90}, {status: 'active', interval: 'month', amount: 19}, {status: 'trialing', interval: 'year', amount: 0}, {status: 'active', interval: 'month', amount: 9.99}, {status: 'active', interval: 'year', amount: 99.90}, {status: 'trialing', interval: 'month', amount: 19}, {status: 'active', interval: 'year', amount: 0}, {status: 'active', interval: 'month', amount: 9.99}, {status: 'trialing', interval: 'year', amount: 99.90}, {status: 'active', interval: 'month', amount: 19}, {status: 'active', interval: 'year', amount: 0}, {status: 'trialing', interval: 'month', amount: 9.99}, {status: 'active', interval: 'year', amount: 99.90}, {status: 'active', interval: 'month', amount: 19}]};223.89 +# Receipt lines +map(lines, `${#.qty} x ${#.name} @ ${string(#.unit)} = ${string(#.unit * #.qty)}`);{lines: [{qty: 2, name: 'Pro seat', unit: 12.50}, {qty: 1, name: 'Add-on: SSO', unit: 99}]};['2 x Pro seat @ 12.50 = 25.00', '1 x Add-on: SSO @ 99 = 99'] +map(lines, `${#.qty} x ${#.name} @ ${string(#.unit)} = ${string(#.unit * #.qty)}`);{lines: []};[] +map(lines, `${#.qty} x ${#.name} @ ${string(#.unit)} = ${string(#.unit * #.qty)}`);{lines: [{qty: 3, name: 'Café crème', unit: 3.10}]};['3 x Café crème @ 3.10 = 9.30'] +map(lines, `${#.qty} x ${#.name} @ ${string(#.unit)} = ${string(#.unit * #.qty)}`);{lines: [{qty: 1.5, name: 'GB', unit: 0.25}]};['1.5 x GB @ 0.25 = 0.375'] +map(lines, `${#.qty} x ${#.name} @ ${string(#.unit)} = ${string(#.unit * #.qty)}`);{lines: [{qty: 1, name: 'x', unit: null}]};!error diff --git a/core/expression/tests/spec/standard/12-commissions.csv b/core/expression/tests/spec/standard/12-commissions.csv new file mode 100644 index 00000000..8861e89d --- /dev/null +++ b/core/expression/tests/spec/standard/12-commissions.csv @@ -0,0 +1,112 @@ +expression (string);input (json 5);output (json 5);note +# Graduated tiers (marginal rates) +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 0};0.00 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 49999.99};2499.9995 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 50000};2500.00 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 50000.01};2500.0008 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 100000};6500.00 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 100000.01};6500.0012 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 250000};24500.00 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: 123456.78};9314.8136 +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: null};!error +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: '100000'};!error +min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12;{sales: -500};-25.00 +round(min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12, 2);{sales: 33333.33};1666.67 +round(min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12, 2);{sales: 77777.77};4722.22 +round(min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12, 2);{sales: 100000.05};6500.01 +round(min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12, 2);{sales: 99999.999};6500.00 +round(min([sales, 50000]) * 0.05 + max([0, min([sales, 100000]) - 50000]) * 0.08 + max([0, sales - 100000]) * 0.12, 2);{sales: 0.01};0.00 +# Retroactive tiers (one rate for the whole amount) +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: 49999.99};2499.9995 +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: 50000};4000.00 +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: 99999.99};7999.9992 +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: 100000};12000.00 +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: 0};0.00 +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: 1234567.89};148148.1468 +sales * (sales >= 100000 ? 0.12 : sales >= 50000 ? 0.08 : 0.05);{sales: null};!error +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: 49999.99};2499.9995 +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: 50000};4000.00 +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: 99999.99};7999.9992 +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: 100000};12000.00 +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: 0};0.00 +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: -1};-0.12 +sales * (sales in [0..50000) ? 0.05 : sales in [50000..100000) ? 0.08 : 0.12);{sales: '5'};!error +# Quota attainment and accelerators +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 80000, quota: 100000, rate: 0.1};8000.0 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 100000, quota: 100000, rate: 0.1};10000.0 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 120000, quota: 100000, rate: 0.1};13000.00 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 150000, quota: 100000, rate: 0.1};17500.00 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 150000.01, quota: 100000, rate: 0.1};20000.00 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 300000, quota: 100000, rate: 0.085};42500.00 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 0, quota: 100000, rate: 0.1};0.0 +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 50000, quota: 0, rate: 0.1};!error +"att = booked / quota; round(att <= 1 ? booked * rate : quota * rate + (booked - quota) * rate * (att > 1.5 ? 2 : 1.5), 2)";{booked: 50000, rate: 0.1};!error +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 120000, quota: 100000};{attainment: 120.0, band: 'club'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 119999, quota: 100000};{attainment: 120.0, band: 'target'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 100000, quota: 100000};{attainment: 100, band: 'target'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 80000, quota: 100000};{attainment: 80.0, band: 'threshold'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 79999.99, quota: 100000};{attainment: 80.0, band: 'below'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 1, quota: 3};{attainment: 33.3, band: 'below'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 2, quota: 3};{attainment: 66.7, band: 'below'} +{attainment: round(booked / quota * 100, 1), band: booked / quota >= 1.2 ? 'club' : booked / quota >= 1 ? 'target' : booked / quota >= 0.8 ? 'threshold' : 'below'};{booked: 0, quota: 250000};{attainment: 0, band: 'below'} +# Commission per deal type over deal lists +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}]};7643.98 +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};64191.90 +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: []};0 +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: [{amount: 1000, type: 'churn'}]};0 +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: [{amount: 1000}]};0 +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: [{amount: 999.99, type: 'new'}, {amount: 0.01, type: 'renewal'}]};100.00 +round(sum(map(deals, #.amount * (({new: 0.10, renewal: 0.03, upsell: 0.07})[#.type] ?? 0))), 2);{deals: [{amount: null, type: 'new'}]};!error +map(filter(deals, #.type == 'new' and #.amount >= 20000), #.id);{deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};['D03', 'D09', 'D15', 'D18', 'D24', 'D30', 'D33', 'D39'] +map(filter(deals, #.type == 'new' and #.amount >= 20000), #.id);{deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 24257.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 8014.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 31771.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 15528.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 39285.65, type: 'upsell', closedOn: '2025-06-26'}]};['D03'] +map(filter(deals, #.type == 'new' and #.amount >= 20000), #.id);{deals: []};[] +map(filter(deals, #.type == 'new' and #.amount >= 20000), #.id);{deals: [{id: 'X', type: 'new', amount: 20000}]};['X'] +sum(map(filter(deals, d(#.closedOn).quarter() == q and d(#.closedOn).year() == 2025), #.amount));{q: 1, deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};211537.64 +sum(map(filter(deals, d(#.closedOn).quarter() == q and d(#.closedOn).year() == 2025), #.amount));{q: 2, deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};296621.32 +sum(map(filter(deals, d(#.closedOn).quarter() == q and d(#.closedOn).year() == 2025), #.amount));{q: 4, deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};212466.74 +sum(map(filter(deals, d(#.closedOn).quarter() == q and d(#.closedOn).year() == 2025), #.amount));{q: 5, deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};0 +sum(map(filter(deals, d(#.closedOn).quarter() == q and d(#.closedOn).year() == 2025), #.amount));{q: 1, deals: [{closedOn: '2025-03-31', amount: 10}, {closedOn: '2025-04-01', amount: 20}, {closedOn: '2024-03-31', amount: 40}]};10 +sum(map(filter(deals, d(#.closedOn).quarter() == q and d(#.closedOn).year() == 2025), #.amount));{q: 1, deals: []};0 +# Split credit across reps +map(splits, {rep: #.rep, credit: round(amount * #.pct / 100, 2)});{amount: 10000, splits: [{rep: 'ana', pct: 60}, {rep: 'bo', pct: 40}]};[{rep: 'ana', credit: 6000}, {rep: 'bo', credit: 4000}] +map(splits, {rep: #.rep, credit: round(amount * #.pct / 100, 2)});{amount: 100, splits: [{rep: 'a', pct: 33.33}, {rep: 'b', pct: 33.33}, {rep: 'c', pct: 33.34}]};[{rep: 'a', credit: 33.33}, {rep: 'b', credit: 33.33}, {rep: 'c', credit: 33.34}] +map(splits, {rep: #.rep, credit: round(amount * #.pct / 100, 2)});{amount: 0.05, splits: [{rep: 'a', pct: 50}, {rep: 'b', pct: 50}]};[{rep: 'a', credit: 0.03}, {rep: 'b', credit: 0.03}] +map(splits, {rep: #.rep, credit: round(amount * #.pct / 100, 2)});{amount: 1000, splits: []};[] +map(splits, {rep: #.rep, credit: round(amount * #.pct / 100, 2)});{amount: 1000, splits: [{rep: 'a'}]};!error +sum(map(splits, #.pct)) == 100 ? 'ok' : 'invalid-split';{splits: [{pct: 60}, {pct: 40}]};'ok' +sum(map(splits, #.pct)) == 100 ? 'ok' : 'invalid-split';{splits: [{pct: 33.33}, {pct: 33.33}, {pct: 33.34}]};'ok' +sum(map(splits, #.pct)) == 100 ? 'ok' : 'invalid-split';{splits: [{pct: 33.33}, {pct: 33.33}, {pct: 33.33}]};'invalid-split' +sum(map(splits, #.pct)) == 100 ? 'ok' : 'invalid-split';{splits: [{pct: 100.00}]};'ok' +sum(map(splits, #.pct)) == 100 ? 'ok' : 'invalid-split';{splits: []};'invalid-split' +sum(map(splits, #.pct)) == 100 ? 'ok' : 'invalid-split';{splits: [{pct: 50}, {pct: '50'}]};!error +# Team rollups with nested closures +map(teams as t, {team: t.name, total: sum(map(t.reps as r, sum(map(r.deals, #.amount)))), topRep: max(map(t.reps as r, sum(map(r.deals, #.amount))))});{teams: [{name: 'East', reps: [{deals: [{amount: 100}, {amount: 250.5}]}, {deals: [{amount: 400}]}]}, {name: 'West', reps: [{deals: []}]}]};[{team: 'East', total: 750.5, topRep: 400}, {team: 'West', total: 0, topRep: 0}] +map(teams as t, {team: t.name, total: sum(map(t.reps as r, sum(map(r.deals, #.amount)))), topRep: max(map(t.reps as r, sum(map(r.deals, #.amount))))});{teams: []};[] +map(teams as t, {team: t.name, total: sum(map(t.reps as r, sum(map(r.deals, #.amount)))), topRep: max(map(t.reps as r, sum(map(r.deals, #.amount))))});{teams: [{name: 'Solo', reps: []}]};!error +map(teams as t, {team: t.name, total: sum(map(t.reps as r, sum(map(r.deals, #.amount)))), topRep: max(map(t.reps as r, sum(map(r.deals, #.amount))))});{teams: [{name: 'X', reps: [{deals: [{amount: 1}]}, {deals: [{amount: null}]}]}]};!error +count(reps, sum(map(#.deals, #.amount)) >= quota);{quota: 300, reps: [{deals: [{amount: 100}, {amount: 200}]}, {deals: [{amount: 299.99}]}, {deals: []}]};1 +count(reps, sum(map(#.deals, #.amount)) >= quota);{quota: 0, reps: [{deals: []}]};1 +count(reps, sum(map(#.deals, #.amount)) >= quota);{quota: 100, reps: []};0 +count(reps, sum(map(#.deals, #.amount)) >= quota);{quota: 100, reps: [{deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}]}, {deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}]}]};2 +# Caps, floors, draws and clawbacks +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: 4200, draw: 3000, cap: 10000};4200 +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: 2500, draw: 3000, cap: 10000};3000 +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: 12000, draw: 3000, cap: 10000};10000 +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: 12000};12000 +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: -500, draw: null};0 +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: 3000, draw: 3000, cap: 3000};3000 +min([cap ?? 1000000, max([draw ?? 0, earned])]);{earned: null, draw: 3000};!error +sum(map(filter(deals, #.cancelledOn != null and d(#.cancelledOn).diff(d(#.closedOn), 'day') <= 90), -#.commission));{deals: [{closedOn: '2025-01-01', cancelledOn: '2025-04-01', commission: 500}, {closedOn: '2025-01-01', cancelledOn: '2025-04-02', commission: 700}, {closedOn: '2025-01-01', commission: 900}]};-500 +sum(map(filter(deals, #.cancelledOn != null and d(#.cancelledOn).diff(d(#.closedOn), 'day') <= 90), -#.commission));{deals: []};0 +sum(map(filter(deals, #.cancelledOn != null and d(#.cancelledOn).diff(d(#.closedOn), 'day') <= 90), -#.commission));{deals: [{closedOn: '2024-12-15', cancelledOn: '2025-03-15', commission: 123.45}]};-123.45 +sum(map(filter(deals, #.cancelledOn != null and d(#.cancelledOn).diff(d(#.closedOn), 'day') <= 90), -#.commission));{deals: [{closedOn: '2024-12-15', cancelledOn: '2025-03-16', commission: 123.45}]};0 +sum(map(filter(deals, #.cancelledOn != null and d(#.cancelledOn).diff(d(#.closedOn), 'day') <= 90), -#.commission));{deals: [{closedOn: '2025-01-01', cancelledOn: '2025-01-02'}]};!error +"spiff = count(deals, #.type == 'new' and #.amount >= 25000) * 250; round(sum(map(deals, #.amount)) * rate + spiff, 2)";{rate: 0.04, deals: [{id: 'D00', amount: 500.00, type: 'new', closedOn: '2025-01-01'}, {id: 'D01', amount: 8419.13, type: 'renewal', closedOn: '2025-02-06'}, {id: 'D02', amount: 16338.26, type: 'upsell', closedOn: '2025-03-11'}, {id: 'D03', amount: 24257.39, type: 'new', closedOn: '2025-04-16'}, {id: 'D04', amount: 32176.52, type: 'renewal', closedOn: '2025-05-21'}, {id: 'D05', amount: 40095.65, type: 'upsell', closedOn: '2025-06-26'}, {id: 'D06', amount: 8014.78, type: 'new', closedOn: '2025-07-03'}, {id: 'D07', amount: 15933.91, type: 'renewal', closedOn: '2025-08-08'}, {id: 'D08', amount: 23852.04, type: 'upsell', closedOn: '2025-09-13'}, {id: 'D09', amount: 31771.17, type: 'new', closedOn: '2025-10-18'}, {id: 'D10', amount: 39690.30, type: 'renewal', closedOn: '2025-11-23'}, {id: 'D11', amount: 7609.43, type: 'upsell', closedOn: '2025-12-28'}, {id: 'D12', amount: 15528.56, type: 'new', closedOn: '2025-01-05'}, {id: 'D13', amount: 23447.69, type: 'renewal', closedOn: '2025-02-10'}, {id: 'D14', amount: 31366.82, type: 'upsell', closedOn: '2025-03-15'}, {id: 'D15', amount: 39285.95, type: 'new', closedOn: '2025-04-20'}, {id: 'D16', amount: 7204.08, type: 'renewal', closedOn: '2025-05-25'}, {id: 'D17', amount: 15123.21, type: 'upsell', closedOn: '2025-06-02'}, {id: 'D18', amount: 23042.34, type: 'new', closedOn: '2025-07-07'}, {id: 'D19', amount: 30961.47, type: 'renewal', closedOn: '2025-08-12'}, {id: 'D20', amount: 38880.60, type: 'upsell', closedOn: '2025-09-17'}, {id: 'D21', amount: 6799.73, type: 'new', closedOn: '2025-10-22'}, {id: 'D22', amount: 14718.86, type: 'renewal', closedOn: '2025-11-27'}, {id: 'D23', amount: 22637.99, type: 'upsell', closedOn: '2025-12-04'}, {id: 'D24', amount: 30556.12, type: 'new', closedOn: '2025-01-09'}, {id: 'D25', amount: 38475.25, type: 'renewal', closedOn: '2025-02-14'}, {id: 'D26', amount: 6394.38, type: 'upsell', closedOn: '2025-03-19'}, {id: 'D27', amount: 14313.51, type: 'new', closedOn: '2025-04-24'}, {id: 'D28', amount: 22232.64, type: 'renewal', closedOn: '2025-05-01'}, {id: 'D29', amount: 30151.77, type: 'upsell', closedOn: '2025-06-06'}, {id: 'D30', amount: 38070.90, type: 'new', closedOn: '2025-07-11'}, {id: 'D31', amount: 5989.03, type: 'renewal', closedOn: '2025-08-16'}, {id: 'D32', amount: 13908.16, type: 'upsell', closedOn: '2025-09-21'}, {id: 'D33', amount: 21827.29, type: 'new', closedOn: '2025-10-26'}, {id: 'D34', amount: 29746.42, type: 'renewal', closedOn: '2025-11-03'}, {id: 'D35', amount: 37665.55, type: 'upsell', closedOn: '2025-12-08'}, {id: 'D36', amount: 5584.68, type: 'new', closedOn: '2025-01-13'}, {id: 'D37', amount: 13503.81, type: 'renewal', closedOn: '2025-02-18'}, {id: 'D38', amount: 21422.94, type: 'upsell', closedOn: '2025-03-23'}, {id: 'D39', amount: 29341.07, type: 'new', closedOn: '2025-04-28'}, {id: 'D40', amount: 37260.20, type: 'renewal', closedOn: '2025-05-05'}, {id: 'D41', amount: 5179.33, type: 'upsell', closedOn: '2025-06-10'}, {id: 'D42', amount: 13098.46, type: 'new', closedOn: '2025-07-15'}, {id: 'D43', amount: 21017.59, type: 'renewal', closedOn: '2025-08-20'}, {id: 'D44', amount: 28936.72, type: 'upsell', closedOn: '2025-09-25'}]};40543.27 +"spiff = count(deals, #.type == 'new' and #.amount >= 25000) * 250; round(sum(map(deals, #.amount)) * rate + spiff, 2)";{rate: 0.04, deals: []};0.00 +"spiff = count(deals, #.type == 'new' and #.amount >= 25000) * 250; round(sum(map(deals, #.amount)) * rate + spiff, 2)";{rate: 0.04, deals: [{type: 'new', amount: 25000}, {type: 'new', amount: 24999.99}]};2250.00 +"spiff = count(deals, #.type == 'new' and #.amount >= 25000) * 250; round(sum(map(deals, #.amount)) * rate + spiff, 2)";{rate: null, deals: [{type: 'new', amount: 1}]};!error +# Statements +`${rep}: ${count(deals, true)} deals, ${string(round(sum(map(deals, #.amount)) * rate, 2))} earned (${string(round(sum(map(deals, #.amount)) / quota * 100, 1))}% of quota)`;{rep: 'Siobhán', rate: 0.1, quota: 50000, deals: [{amount: 12000}, {amount: 8000.50}]};'Siobhán: 2 deals, 2000.05 earned (40.0% of quota)' +`${rep}: ${count(deals, true)} deals, ${string(round(sum(map(deals, #.amount)) * rate, 2))} earned (${string(round(sum(map(deals, #.amount)) / quota * 100, 1))}% of quota)`;{rep: 'Kai', rate: 0.05, quota: 30000, deals: [{amount: 30000}]};'Kai: 1 deals, 1500.00 earned (100% of quota)' +`${rep}: ${count(deals, true)} deals, ${string(round(sum(map(deals, #.amount)) * rate, 2))} earned (${string(round(sum(map(deals, #.amount)) / quota * 100, 1))}% of quota)`;{rep: 'Ren', rate: 0.08, quota: 90000, deals: [{amount: 10000}, {amount: 20000}]};'Ren: 2 deals, 2400.00 earned (33.3% of quota)' +`${rep}: ${count(deals, true)} deals, ${string(round(sum(map(deals, #.amount)) * rate, 2))} earned (${string(round(sum(map(deals, #.amount)) / quota * 100, 1))}% of quota)`;{rep: 'Ida', rate: 0.1, quota: 0, deals: [{amount: 1}]};!error diff --git a/core/expression/tests/spec/standard/12-currency.csv b/core/expression/tests/spec/standard/12-currency.csv new file mode 100644 index 00000000..cfdd30b4 --- /dev/null +++ b/core/expression/tests/spec/standard/12-currency.csv @@ -0,0 +1,153 @@ +expression (string);input (json 5);output (json 5);note +# Minor units per currency +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 1234.5678, currency: 'USD'};1234.57 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 1234.5678, currency: 'JPY'};1235 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 1234.5678, currency: 'KWD'};1234.568 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 1234.5, currency: 'JPY'};1235 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 1233.5, currency: 'JPY'};1234 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 0.0005, currency: 'KWD'};0.001 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 0.0049, currency: 'EUR'};0.00 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: -2.675, currency: 'GBP'};-2.68 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 10, currency: 'XYZ'};10 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: 10.999, currency: null};11.00 +round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3, CHF: 2, GBP: 2})[currency] ?? 2);{amount: null, currency: 'USD'};!error +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 1234.5678, currency: 'USD'};'1234.57' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 1234.5678, currency: 'JPY'};'1235' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 1234.5678, currency: 'KWD'};'1234.568' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 1234.5, currency: 'USD'};'1234.5' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 1234, currency: 'USD'};'1234' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 1234.50, currency: 'EUR'};'1234.50' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 99.995, currency: 'USD'};'100.00' +string(round(amount, ({USD: 2, EUR: 2, JPY: 0, KWD: 3})[currency] ?? 2));{amount: 0.1, currency: 'KWD'};'0.1' +# Conversion through a USD pivot +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 100, from: 'USD', to: 'EUR', rates: {USD: 1, EUR: 0.9215, JPY: 149.37}, decimals: {JPY: 0}};92.15 +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 100, from: 'EUR', to: 'USD', rates: {USD: 1, EUR: 0.9215, JPY: 149.37}, decimals: {JPY: 0}};108.52 +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 100, from: 'EUR', to: 'JPY', rates: {USD: 1, EUR: 0.9215, JPY: 149.37}, decimals: {JPY: 0}};16209 +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 15000, from: 'JPY', to: 'EUR', rates: {USD: 1, EUR: 0.9215, JPY: 149.37}, decimals: {JPY: 0}};92.54 +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 0.01, from: 'USD', to: 'JPY', rates: {USD: 1, EUR: 0.9215, JPY: 149.37}, decimals: {JPY: 0}};1 +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 100, from: 'USD', to: 'GBP', rates: {USD: 1, EUR: 0.9215}, decimals: {}};!error +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 100, from: 'USD', to: 'EUR', rates: {USD: 0, EUR: 0.9215}, decimals: {}};!error +round(amount / rates[from] * rates[to], decimals[to] ?? 2);{amount: 100, from: 'USD', to: 'USD', rates: {USD: 1}, decimals: {}};100 +map(amounts, round(# * rate, 2));{rate: 0.9215, amounts: [1, 10, 100, 0.05, 0.06, 1234.56]};[0.92, 9.22, 92.15, 0.05, 0.06, 1137.65] +map(amounts, round(# * rate, 2));{rate: 1.0852, amounts: []};[] +map(amounts, round(# * rate, 2));{rate: 149.37, amounts: [0.01, 0.02, 0.03]};[1.49, 2.99, 4.48] +map(amounts, round(# * rate, 2));{rate: null, amounts: [1]};!error +map(amounts, round(# * rate, 2));{rate: 1.1, amounts: [1, null]};!error +map(amounts, round(# * rate, 2));{rate: 0.7893, amounts: [0.00, 17.29, 34.58, 51.87, 68.16, 85.45, 102.74, 119.03, 136.32, 153.61, 170.90, 187.19, 204.48, 221.77, 238.06, 255.35, 272.64, 289.93, 306.22, 323.51, 340.80, 357.09, 374.38, 391.67, 408.96, 425.25, 442.54, 459.83, 476.12, 493.41, 10.70, 27.99, 44.28, 61.57, 78.86, 95.15, 112.44, 129.73, 146.02, 163.31, 180.60, 197.89, 214.18, 231.47, 248.76, 265.05, 282.34, 299.63, 316.92, 333.21]};[0.00, 13.65, 27.29, 40.94, 53.80, 67.45, 81.09, 93.95, 107.60, 121.24, 134.89, 147.75, 161.40, 175.04, 187.90, 201.55, 215.19, 228.84, 241.70, 255.35, 268.99, 281.85, 295.50, 309.15, 322.79, 335.65, 349.30, 362.94, 375.80, 389.45, 8.45, 22.09, 34.95, 48.60, 62.24, 75.10, 88.75, 102.40, 115.25, 128.90, 142.55, 156.19, 169.05, 182.70, 196.35, 209.20, 222.85, 236.50, 250.14, 263.00] +sum(map(amounts, round(# * rate, 2))) - round(sum(amounts) * rate, 2);{rate: 0.9215, amounts: [0.05, 0.05, 0.05, 0.05]};0.02 +sum(map(amounts, round(# * rate, 2))) - round(sum(amounts) * rate, 2);{rate: 1.5, amounts: [0.01, 0.01, 0.01]};0.01 +sum(map(amounts, round(# * rate, 2))) - round(sum(amounts) * rate, 2);{rate: 0.3333, amounts: [1, 1, 1]};-0.01 +sum(map(amounts, round(# * rate, 2))) - round(sum(amounts) * rate, 2);{rate: 2, amounts: [1.11, 2.22]};0.00 +sum(map(amounts, round(# * rate, 2))) - round(sum(amounts) * rate, 2);{rate: 0.7893, amounts: [0.00, 17.29, 34.58, 51.87, 68.16, 85.45, 102.74, 119.03, 136.32, 153.61, 170.90, 187.19, 204.48, 221.77, 238.06, 255.35, 272.64, 289.93, 306.22, 323.51, 340.80, 357.09, 374.38, 391.67, 408.96, 425.25, 442.54, 459.83, 476.12, 493.41, 10.70, 27.99, 44.28, 61.57, 78.86, 95.15, 112.44, 129.73, 146.02, 163.31, 180.60, 197.89, 214.18, 231.47, 248.76, 265.05, 282.34, 299.63, 316.92, 333.21]};-0.01 +sum(map(amounts, round(# * rate, 2))) - round(sum(amounts) * rate, 2);{rate: 1, amounts: []};0 +# Cash rounding to 0.05 and to whole units +round(amount * 20) / 20;{amount: 10.02};10 +round(amount * 20) / 20;{amount: 10.024};10 +round(amount * 20) / 20;{amount: 10.025};10.05 +round(amount * 20) / 20;{amount: 10.03};10.05 +round(amount * 20) / 20;{amount: 10.07};10.05 +round(amount * 20) / 20;{amount: 10.075};10.1 +round(amount * 20) / 20;{amount: 10.974};10.95 +round(amount * 20) / 20;{amount: 10.975};11 +round(amount * 20) / 20;{amount: 0};0 +round(amount * 20) / 20;{amount: -10.025};-10.05 +round(amount * 20) / 20;{amount: '10'};!error +string(round(amount * 20) / 20);{amount: 10.02};'10' +string(round(amount * 20) / 20);{amount: 10.03};'10.05' +string(round(amount * 20) / 20);{amount: 10.08};'10.10';"question: 202 / 20 yields scale 2 (10.10) while 201 / 20 gives 10.05 and 200 / 20 gives 10; division result scale is not normalized" +string(round(amount * 20) / 20);{amount: 9.99};'10' +string(round(amount * 20) / 20);{amount: 10};'10' +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: 2.5};3 +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: 2.49};2 +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: -2.5};-2 +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: -2.51};-3 +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: 0};0 +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: 100};100 +floor(amount) + (amount - floor(amount) >= 0.5 ? 1 : 0);{amount: 1234567.4999};1234567 +ceil(amount * 100) / 100;{amount: 1.001};1.01 +ceil(amount * 100) / 100;{amount: 1.01};1.01 +ceil(amount * 100) / 100;{amount: 1.0100001};1.02 +ceil(amount * 100) / 100;{amount: -1.009};-1 +ceil(amount * 100) / 100;{amount: 0.001};0.01 +ceil(amount * 100) / 100;{amount: 999999.999};1000000 +trunc(amount * 100) / 100;{amount: 1.019};1.01 +trunc(amount * 100) / 100;{amount: -1.019};-1.01 +trunc(amount * 100) / 100;{amount: 0.009};0 +trunc(amount * 100) / 100;{amount: 12.3456};12.34 +trunc(amount * 100) / 100;{amount: 5};5 +# Penny allocation (largest remainder) +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 100, n: 3};[33.34, 33.33, 33.33] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 10, n: 4};[2.5, 2.5, 2.5, 2.5] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 0.05, n: 3};[0.02, 0.02, 0.01] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 1000.01, n: 7};[142.86, 142.86, 142.86, 142.86, 142.86, 142.86, 142.85] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 0.02, n: 5};[0.01, 0.01, 0, 0, 0] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 99.99, n: 1};[99.99] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); map([0..n), base + (# < rem ? 0.01 : 0))";{total: 1, n: 3};[0.34, 0.33, 0.33] +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); sum(map([0..n), base + (# < rem ? 0.01 : 0))) == total";{total: 100, n: 3};true +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); sum(map([0..n), base + (# < rem ? 0.01 : 0))) == total";{total: 10, n: 4};true +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); sum(map([0..n), base + (# < rem ? 0.01 : 0))) == total";{total: 0.05, n: 3};true +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); sum(map([0..n), base + (# < rem ? 0.01 : 0))) == total";{total: 1000.01, n: 7};true +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); sum(map([0..n), base + (# < rem ? 0.01 : 0))) == total";{total: 123456.78, n: 9};true +"base = floor(total * 100 / n) / 100; rem = round((total - base * n) * 100); sum(map([0..n), base + (# < rem ? 0.01 : 0))) == total";{total: 1, n: 3};true +map(weights, round(total * # / sum(weights), 2));{total: 100, weights: [1, 1, 1]};[33.33, 33.33, 33.33] +map(weights, round(total * # / sum(weights), 2));{total: 100, weights: [50, 30, 20]};[50, 30, 20] +map(weights, round(total * # / sum(weights), 2));{total: 0.03, weights: [1, 1]};[0.02, 0.02] +map(weights, round(total * # / sum(weights), 2));{total: 250, weights: [0.2, 0.3, 0.5]};[50, 75, 125] +map(weights, round(total * # / sum(weights), 2));{total: 100, weights: []};[] +map(weights, round(total * # / sum(weights), 2));{total: 100, weights: [0, 0]};!error +map(weights, round(total * # / sum(weights), 2));{total: 100, weights: [1, '1']};!error +# Price display strings +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 19.999, currency: 'USD'};'$20.00' +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 19.5, currency: 'EUR'};'€19.5' +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 19.50, currency: 'GBP'};'£19.50' +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 1999.5, currency: 'JPY'};'¥2000' +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 0.004, currency: 'USD'};'$0.00' +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 10, currency: 'CHF'};!error +({USD: '$', EUR: '€', GBP: '£', JPY: '¥'})[currency] + string(round(amount, currency == 'JPY' ? 0 : 2));{amount: 10, currency: null};!error +`${code} ${string(round(amount, 2) * 1.00)}`;{code: 'USD', amount: 10};'USD 10.00' +`${code} ${string(round(amount, 2) * 1.00)}`;{code: 'USD', amount: 10.5};'USD 10.500' +`${code} ${string(round(amount, 2) * 1.00)}`;{code: 'EUR', amount: 10.555};'EUR 10.5600' +`${code} ${string(round(amount, 2) * 1.00)}`;{code: 'EUR', amount: 10.554};'EUR 10.5500' +`${code} ${string(round(amount, 2) * 1.00)}`;{code: 'GBP', amount: 0.1};'GBP 0.100' +amount < 0 ? '(' + string(abs(round(amount, 2))) + ')' : string(round(amount, 2));{amount: -12.345};'(12.35)' +amount < 0 ? '(' + string(abs(round(amount, 2))) + ')' : string(round(amount, 2));{amount: 12.345};'12.35' +amount < 0 ? '(' + string(abs(round(amount, 2))) + ')' : string(round(amount, 2));{amount: -0.001};'(0.00)' +amount < 0 ? '(' + string(abs(round(amount, 2))) + ')' : string(round(amount, 2));{amount: 0};'0' +amount < 0 ? '(' + string(abs(round(amount, 2))) + ')' : string(round(amount, 2));{amount: -1000000.10};'(1000000.10)' +amount < 0 ? '(' + string(abs(round(amount, 2))) + ')' : string(round(amount, 2));{amount: null};!error +# Interest and fee math on money +round(principal * rate / 100 * days / (basis == 'ACT/360' ? 360 : 365), 2);{principal: 1000000, rate: 5.25, days: 30, basis: 'ACT/360'};4375.00 +round(principal * rate / 100 * days / (basis == 'ACT/360' ? 360 : 365), 2);{principal: 1000000, rate: 5.25, days: 30, basis: 'ACT/365'};4315.07 +round(principal * rate / 100 * days / (basis == 'ACT/360' ? 360 : 365), 2);{principal: 250000, rate: 4.125, days: 91, basis: 'ACT/360'};2606.77 +round(principal * rate / 100 * days / (basis == 'ACT/360' ? 360 : 365), 2);{principal: 250000, rate: 4.125, days: 91};2571.06 +round(principal * rate / 100 * days / (basis == 'ACT/360' ? 360 : 365), 2);{principal: 1, rate: 0.01, days: 1, basis: 'ACT/360'};0.00 +round(principal * rate / 100 * days / (basis == 'ACT/360' ? 360 : 365), 2);{principal: 1000, rate: 10, days: 0, basis: 'ACT/360'};0 +round(amount * pct / 100 + fixed, 2) > (maxFee ?? 999999) ? maxFee : max([minFee ?? 0, round(amount * pct / 100 + fixed, 2)]);{amount: 100, pct: 2.9, fixed: 0.30};3.20 +round(amount * pct / 100 + fixed, 2) > (maxFee ?? 999999) ? maxFee : max([minFee ?? 0, round(amount * pct / 100 + fixed, 2)]);{amount: 10000, pct: 2.9, fixed: 0.30, maxFee: 250};250 +round(amount * pct / 100 + fixed, 2) > (maxFee ?? 999999) ? maxFee : max([minFee ?? 0, round(amount * pct / 100 + fixed, 2)]);{amount: 5, pct: 2.9, fixed: 0.30, minFee: 0.50};0.50 +round(amount * pct / 100 + fixed, 2) > (maxFee ?? 999999) ? maxFee : max([minFee ?? 0, round(amount * pct / 100 + fixed, 2)]);{amount: 12.34, pct: 1.4, fixed: 0.25, minFee: 0.1};0.42 +round(amount * pct / 100 + fixed, 2) > (maxFee ?? 999999) ? maxFee : max([minFee ?? 0, round(amount * pct / 100 + fixed, 2)]);{amount: 0, pct: 2.9, fixed: 0};0 +round(amount * pct / 100 + fixed, 2) > (maxFee ?? 999999) ? maxFee : max([minFee ?? 0, round(amount * pct / 100 + fixed, 2)]);{amount: 1000, pct: 2.9, fixed: 0.30, maxFee: null};29.30 +sum(map(txns, #.currency == base ? #.amount : round(#.amount * (fx[#.currency] ?? 0), 2)));{base: 'EUR', fx: {USD: 0.9215, GBP: 1.1674}, txns: [{currency: 'EUR', amount: 10}, {currency: 'USD', amount: 10}, {currency: 'GBP', amount: 10}]};30.89 +sum(map(txns, #.currency == base ? #.amount : round(#.amount * (fx[#.currency] ?? 0), 2)));{base: 'EUR', fx: {}, txns: [{currency: 'JPY', amount: 1000}]};0 +sum(map(txns, #.currency == base ? #.amount : round(#.amount * (fx[#.currency] ?? 0), 2)));{base: 'EUR', fx: {USD: 0.9215}, txns: []};0 +sum(map(txns, #.currency == base ? #.amount : round(#.amount * (fx[#.currency] ?? 0), 2)));{base: 'EUR', fx: {USD: 0.9215}, txns: [{currency: 'USD', amount: 0.005}, {currency: 'USD', amount: 0.006}]};0.01 +sum(map(txns, #.currency == base ? #.amount : round(#.amount * (fx[#.currency] ?? 0), 2)));{base: 'USD', fx: {EUR: 1.0852}, txns: [{currency: 'USD', amount: 0.00}, {currency: 'EUR', amount: 31.11}, {currency: 'USD', amount: 62.22}, {currency: 'EUR', amount: 93.33}, {currency: 'USD', amount: 124.44}, {currency: 'EUR', amount: 155.55}, {currency: 'USD', amount: 186.66}, {currency: 'EUR', amount: 217.77}, {currency: 'USD', amount: 248.88}, {currency: 'EUR', amount: 279.99}, {currency: 'USD', amount: 310.10}, {currency: 'EUR', amount: 341.21}, {currency: 'USD', amount: 372.32}, {currency: 'EUR', amount: 403.43}, {currency: 'USD', amount: 434.54}, {currency: 'EUR', amount: 465.65}, {currency: 'USD', amount: 496.76}, {currency: 'EUR', amount: 527.87}, {currency: 'USD', amount: 558.98}, {currency: 'EUR', amount: 589.09}, {currency: 'USD', amount: 620.20}, {currency: 'EUR', amount: 651.31}, {currency: 'USD', amount: 682.42}, {currency: 'EUR', amount: 713.53}, {currency: 'USD', amount: 744.64}, {currency: 'EUR', amount: 775.75}, {currency: 'USD', amount: 806.86}, {currency: 'EUR', amount: 837.97}, {currency: 'USD', amount: 868.08}, {currency: 'EUR', amount: 899.19}, {currency: 'USD', amount: 30.30}, {currency: 'EUR', amount: 61.41}, {currency: 'USD', amount: 92.52}, {currency: 'EUR', amount: 123.63}, {currency: 'USD', amount: 154.74}, {currency: 'EUR', amount: 185.85}, {currency: 'USD', amount: 216.96}, {currency: 'EUR', amount: 247.07}, {currency: 'USD', amount: 278.18}, {currency: 'EUR', amount: 309.29}]};15873.70 +# Exactness of money sums +sum(amounts) == expected;{amounts: [0.1, 0.2], expected: 0.3};true +sum(amounts) == expected;{amounts: [0.1, 0.1, 0.1], expected: 0.3};true +sum(amounts) == expected;{amounts: [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], expected: 1};true +sum(amounts) == expected;{amounts: [0.010, 0.99], expected: 1.00};true +sum(amounts) == expected;{amounts: [19.99, 0.01], expected: 20};true +sum(amounts) == expected;{amounts: [], expected: 0};true +sum(amounts) == expected;{amounts: [79228162514264337593543950335, -79228162514264337593543950335], expected: 0};true +string(sum(amounts));{amounts: [0.10, 0.20]};'0.30' +string(sum(amounts));{amounts: [1.5, 1.50]};'3.00' +string(sum(amounts));{amounts: [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]};'1.00' +string(sum(amounts));{amounts: [19.99, 0.01]};'20.00' +string(sum(amounts));{amounts: [0.001, 0.009]};'0.010' +round(sum(map(lines, #.qty * #.unit)) * 1.0825, 2) == round(sum(map(lines, round(#.qty * #.unit * 1.0825, 2))), 2);{lines: [{qty: 1, unit: 10}]};true +round(sum(map(lines, #.qty * #.unit)) * 1.0825, 2) == round(sum(map(lines, round(#.qty * #.unit * 1.0825, 2))), 2);{lines: [{qty: 1, unit: 0.99}, {qty: 1, unit: 0.99}, {qty: 1, unit: 0.99}]};false +round(sum(map(lines, #.qty * #.unit)) * 1.0825, 2) == round(sum(map(lines, round(#.qty * #.unit * 1.0825, 2))), 2);{lines: [{qty: 3, unit: 1.11}, {qty: 7, unit: 0.13}]};true +round(sum(map(lines, #.qty * #.unit)) * 1.0825, 2) == round(sum(map(lines, round(#.qty * #.unit * 1.0825, 2))), 2);{lines: []};true +round(sum(map(lines, #.qty * #.unit)) * 1.0825, 2) == round(sum(map(lines, round(#.qty * #.unit * 1.0825, 2))), 2);{lines: [{qty: 2, unit: 0.05}, {qty: 2, unit: 0.06}]};true diff --git a/core/expression/tests/spec/standard/12-ecommerce.csv b/core/expression/tests/spec/standard/12-ecommerce.csv new file mode 100644 index 00000000..a40989b5 --- /dev/null +++ b/core/expression/tests/spec/standard/12-ecommerce.csv @@ -0,0 +1,166 @@ +expression (string);input (json 5);output (json 5);note +# Cart subtotal over line items +sum(map(items, #.price * #.qty));{items: [{price: 19.99, qty: 2}, {price: 5.01, qty: 1}]};44.99 +sum(map(items, #.price * #.qty));{items: []};0 +sum(map(items, #.price * #.qty));{items: [{price: 0.1, qty: 3}]};0.3 +sum(map(items, #.price * #.qty));{items: [{price: 9.999, qty: 3}]};29.997 +sum(map(items, #.price * #.qty));{items: [{price: 19.99, qty: 0}]};0.00 +sum(map(items, #.price * #.qty));{items: [{price: 19.99}]};!error +sum(map(items, #.price * #.qty));{items: [{price: '19.99', qty: 1}]};!error +sum(map(items, #.price * #.qty));{items: null};!error +sum(map(items, #.price * #.qty));{items: [{sku: 'SKU-000', price: 1.00, qty: 1, category: 'books'}, {sku: 'SKU-001', price: 8.37, qty: 2, category: 'toys'}, {sku: 'SKU-002', price: 15.74, qty: 3, category: 'food'}, {sku: 'SKU-003', price: 22.11, qty: 4, category: 'electronics'}, {sku: 'SKU-004', price: 29.48, qty: 1, category: 'books'}, {sku: 'SKU-005', price: 36.85, qty: 2, category: 'toys'}, {sku: 'SKU-006', price: 43.22, qty: 3, category: 'food'}, {sku: 'SKU-007', price: 50.59, qty: 4, category: 'electronics'}, {sku: 'SKU-008', price: 7.96, qty: 1, category: 'books'}, {sku: 'SKU-009', price: 14.33, qty: 2, category: 'toys'}, {sku: 'SKU-010', price: 21.70, qty: 3, category: 'food'}, {sku: 'SKU-011', price: 28.07, qty: 4, category: 'electronics'}, {sku: 'SKU-012', price: 35.44, qty: 1, category: 'books'}, {sku: 'SKU-013', price: 42.81, qty: 2, category: 'toys'}, {sku: 'SKU-014', price: 49.18, qty: 3, category: 'food'}, {sku: 'SKU-015', price: 6.55, qty: 4, category: 'electronics'}, {sku: 'SKU-016', price: 13.92, qty: 1, category: 'books'}, {sku: 'SKU-017', price: 20.29, qty: 2, category: 'toys'}, {sku: 'SKU-018', price: 27.66, qty: 3, category: 'food'}, {sku: 'SKU-019', price: 34.03, qty: 4, category: 'electronics'}, {sku: 'SKU-020', price: 41.40, qty: 1, category: 'books'}, {sku: 'SKU-021', price: 48.77, qty: 2, category: 'toys'}, {sku: 'SKU-022', price: 5.14, qty: 3, category: 'food'}, {sku: 'SKU-023', price: 12.51, qty: 4, category: 'electronics'}, {sku: 'SKU-024', price: 19.88, qty: 1, category: 'books'}, {sku: 'SKU-025', price: 26.25, qty: 2, category: 'toys'}, {sku: 'SKU-026', price: 33.62, qty: 3, category: 'food'}, {sku: 'SKU-027', price: 40.99, qty: 4, category: 'electronics'}, {sku: 'SKU-028', price: 47.36, qty: 1, category: 'books'}, {sku: 'SKU-029', price: 4.73, qty: 2, category: 'toys'}, {sku: 'SKU-030', price: 11.10, qty: 3, category: 'food'}, {sku: 'SKU-031', price: 18.47, qty: 4, category: 'electronics'}, {sku: 'SKU-032', price: 25.84, qty: 1, category: 'books'}, {sku: 'SKU-033', price: 32.21, qty: 2, category: 'toys'}, {sku: 'SKU-034', price: 39.58, qty: 3, category: 'food'}, {sku: 'SKU-035', price: 46.95, qty: 4, category: 'electronics'}, {sku: 'SKU-036', price: 3.32, qty: 1, category: 'books'}, {sku: 'SKU-037', price: 10.69, qty: 2, category: 'toys'}, {sku: 'SKU-038', price: 17.06, qty: 3, category: 'food'}, {sku: 'SKU-039', price: 24.43, qty: 4, category: 'electronics'}]};2647.00 +sum(map(items, #.price * #.qty));{items: [{sku: 'X0', price: 0.10, qty: 3, category: 'food'}, {sku: 'X1', price: 0.10, qty: 3, category: 'food'}, {sku: 'X2', price: 0.10, qty: 3, category: 'food'}, {sku: 'X3', price: 0.10, qty: 3, category: 'food'}, {sku: 'X4', price: 0.10, qty: 3, category: 'food'}, {sku: 'X5', price: 0.10, qty: 3, category: 'food'}, {sku: 'X6', price: 0.10, qty: 3, category: 'food'}, {sku: 'X7', price: 0.10, qty: 3, category: 'food'}, {sku: 'X8', price: 0.10, qty: 3, category: 'food'}, {sku: 'X9', price: 0.10, qty: 3, category: 'food'}, {sku: 'X10', price: 0.10, qty: 3, category: 'food'}, {sku: 'X11', price: 0.10, qty: 3, category: 'food'}, {sku: 'X12', price: 0.10, qty: 3, category: 'food'}, {sku: 'X13', price: 0.10, qty: 3, category: 'food'}, {sku: 'X14', price: 0.10, qty: 3, category: 'food'}, {sku: 'X15', price: 0.10, qty: 3, category: 'food'}, {sku: 'X16', price: 0.10, qty: 3, category: 'food'}, {sku: 'X17', price: 0.10, qty: 3, category: 'food'}, {sku: 'X18', price: 0.10, qty: 3, category: 'food'}, {sku: 'X19', price: 0.10, qty: 3, category: 'food'}, {sku: 'X20', price: 0.10, qty: 3, category: 'food'}, {sku: 'X21', price: 0.10, qty: 3, category: 'food'}, {sku: 'X22', price: 0.10, qty: 3, category: 'food'}, {sku: 'X23', price: 0.10, qty: 3, category: 'food'}, {sku: 'X24', price: 0.10, qty: 3, category: 'food'}, {sku: 'X25', price: 0.10, qty: 3, category: 'food'}, {sku: 'X26', price: 0.10, qty: 3, category: 'food'}, {sku: 'X27', price: 0.10, qty: 3, category: 'food'}, {sku: 'X28', price: 0.10, qty: 3, category: 'food'}, {sku: 'X29', price: 0.10, qty: 3, category: 'food'}, {sku: 'X30', price: 0.10, qty: 3, category: 'food'}, {sku: 'X31', price: 0.10, qty: 3, category: 'food'}, {sku: 'X32', price: 0.10, qty: 3, category: 'food'}, {sku: 'X33', price: 0.10, qty: 3, category: 'food'}, {sku: 'X34', price: 0.10, qty: 3, category: 'food'}, {sku: 'X35', price: 0.10, qty: 3, category: 'food'}, {sku: 'X36', price: 0.10, qty: 3, category: 'food'}, {sku: 'X37', price: 0.10, qty: 3, category: 'food'}, {sku: 'X38', price: 0.10, qty: 3, category: 'food'}, {sku: 'X39', price: 0.10, qty: 3, category: 'food'}, {sku: 'X40', price: 0.10, qty: 3, category: 'food'}, {sku: 'X41', price: 0.10, qty: 3, category: 'food'}, {sku: 'X42', price: 0.10, qty: 3, category: 'food'}, {sku: 'X43', price: 0.10, qty: 3, category: 'food'}, {sku: 'X44', price: 0.10, qty: 3, category: 'food'}, {sku: 'X45', price: 0.10, qty: 3, category: 'food'}, {sku: 'X46', price: 0.10, qty: 3, category: 'food'}, {sku: 'X47', price: 0.10, qty: 3, category: 'food'}, {sku: 'X48', price: 0.10, qty: 3, category: 'food'}, {sku: 'X49', price: 0.10, qty: 3, category: 'food'}, {sku: 'X50', price: 0.10, qty: 3, category: 'food'}, {sku: 'X51', price: 0.10, qty: 3, category: 'food'}, {sku: 'X52', price: 0.10, qty: 3, category: 'food'}, {sku: 'X53', price: 0.10, qty: 3, category: 'food'}, {sku: 'X54', price: 0.10, qty: 3, category: 'food'}, {sku: 'X55', price: 0.10, qty: 3, category: 'food'}, {sku: 'X56', price: 0.10, qty: 3, category: 'food'}, {sku: 'X57', price: 0.10, qty: 3, category: 'food'}, {sku: 'X58', price: 0.10, qty: 3, category: 'food'}, {sku: 'X59', price: 0.10, qty: 3, category: 'food'}]};18.00 +string(sum(map(items, #.price * #.qty)));{items: [{price: 19.99, qty: 2}, {price: 5.01, qty: 1}]};'44.99' +string(sum(map(items, #.price * #.qty)));{items: [{price: 0.10, qty: 3}]};'0.30' +string(sum(map(items, #.price * #.qty)));{items: [{price: 1.5, qty: 2}]};'3.0' +string(sum(map(items, #.price * #.qty)));{items: []};'0' +string(sum(map(items, #.price * #.qty)));{items: [{price: 2.50, qty: 4}, {price: 0.005, qty: 2}]};'10.010' +string(sum(map(items, #.price * #.qty)));{items: [{sku: 'X0', price: 0.10, qty: 3, category: 'food'}, {sku: 'X1', price: 0.10, qty: 3, category: 'food'}, {sku: 'X2', price: 0.10, qty: 3, category: 'food'}, {sku: 'X3', price: 0.10, qty: 3, category: 'food'}, {sku: 'X4', price: 0.10, qty: 3, category: 'food'}, {sku: 'X5', price: 0.10, qty: 3, category: 'food'}, {sku: 'X6', price: 0.10, qty: 3, category: 'food'}, {sku: 'X7', price: 0.10, qty: 3, category: 'food'}, {sku: 'X8', price: 0.10, qty: 3, category: 'food'}, {sku: 'X9', price: 0.10, qty: 3, category: 'food'}, {sku: 'X10', price: 0.10, qty: 3, category: 'food'}, {sku: 'X11', price: 0.10, qty: 3, category: 'food'}, {sku: 'X12', price: 0.10, qty: 3, category: 'food'}, {sku: 'X13', price: 0.10, qty: 3, category: 'food'}, {sku: 'X14', price: 0.10, qty: 3, category: 'food'}, {sku: 'X15', price: 0.10, qty: 3, category: 'food'}, {sku: 'X16', price: 0.10, qty: 3, category: 'food'}, {sku: 'X17', price: 0.10, qty: 3, category: 'food'}, {sku: 'X18', price: 0.10, qty: 3, category: 'food'}, {sku: 'X19', price: 0.10, qty: 3, category: 'food'}, {sku: 'X20', price: 0.10, qty: 3, category: 'food'}, {sku: 'X21', price: 0.10, qty: 3, category: 'food'}, {sku: 'X22', price: 0.10, qty: 3, category: 'food'}, {sku: 'X23', price: 0.10, qty: 3, category: 'food'}, {sku: 'X24', price: 0.10, qty: 3, category: 'food'}, {sku: 'X25', price: 0.10, qty: 3, category: 'food'}, {sku: 'X26', price: 0.10, qty: 3, category: 'food'}, {sku: 'X27', price: 0.10, qty: 3, category: 'food'}, {sku: 'X28', price: 0.10, qty: 3, category: 'food'}, {sku: 'X29', price: 0.10, qty: 3, category: 'food'}, {sku: 'X30', price: 0.10, qty: 3, category: 'food'}, {sku: 'X31', price: 0.10, qty: 3, category: 'food'}, {sku: 'X32', price: 0.10, qty: 3, category: 'food'}, {sku: 'X33', price: 0.10, qty: 3, category: 'food'}, {sku: 'X34', price: 0.10, qty: 3, category: 'food'}, {sku: 'X35', price: 0.10, qty: 3, category: 'food'}, {sku: 'X36', price: 0.10, qty: 3, category: 'food'}, {sku: 'X37', price: 0.10, qty: 3, category: 'food'}, {sku: 'X38', price: 0.10, qty: 3, category: 'food'}, {sku: 'X39', price: 0.10, qty: 3, category: 'food'}, {sku: 'X40', price: 0.10, qty: 3, category: 'food'}, {sku: 'X41', price: 0.10, qty: 3, category: 'food'}, {sku: 'X42', price: 0.10, qty: 3, category: 'food'}, {sku: 'X43', price: 0.10, qty: 3, category: 'food'}, {sku: 'X44', price: 0.10, qty: 3, category: 'food'}, {sku: 'X45', price: 0.10, qty: 3, category: 'food'}, {sku: 'X46', price: 0.10, qty: 3, category: 'food'}, {sku: 'X47', price: 0.10, qty: 3, category: 'food'}, {sku: 'X48', price: 0.10, qty: 3, category: 'food'}, {sku: 'X49', price: 0.10, qty: 3, category: 'food'}, {sku: 'X50', price: 0.10, qty: 3, category: 'food'}, {sku: 'X51', price: 0.10, qty: 3, category: 'food'}, {sku: 'X52', price: 0.10, qty: 3, category: 'food'}, {sku: 'X53', price: 0.10, qty: 3, category: 'food'}, {sku: 'X54', price: 0.10, qty: 3, category: 'food'}, {sku: 'X55', price: 0.10, qty: 3, category: 'food'}, {sku: 'X56', price: 0.10, qty: 3, category: 'food'}, {sku: 'X57', price: 0.10, qty: 3, category: 'food'}, {sku: 'X58', price: 0.10, qty: 3, category: 'food'}, {sku: 'X59', price: 0.10, qty: 3, category: 'food'}]};'18.00' +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: [{price: 100, qty: 1, discountPct: 15}, {price: 40, qty: 2}]};165.00 +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: [{price: 19.99, qty: 3, discountPct: 33}]};40.18 +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: [{price: 19.99, qty: 3, discountPct: 100}]};0.00 +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: [{price: 10, qty: 1, discountPct: null}]};10 +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: []};0 +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: [{price: 10, qty: 1, discountPct: '10'}]};!error +round(sum(map(items, #.price * #.qty * (1 - (#.discountPct ?? 0) / 100))), 2);{items: [{price: 0.99, qty: 7, discountPct: 12.5}, {price: 1.01, qty: 3, discountPct: 0}]};9.09 +# Coupon codes +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 'save10', subtotal: 84.95};8.50 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: ' SAVE10 ', subtotal: 84.95};8.50 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 'FLAT5', subtotal: 3.49};3.49 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 'flat5', subtotal: 120};5 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 'vip-gold', subtotal: 250.25};50.05 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 'VIP', subtotal: 0.03};0.01 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: '', subtotal: 50};0 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{subtotal: 50};0 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: null, subtotal: 50};0 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 'SAVE 10', subtotal: 50};0 +"code = upper(trim(code ?? '')); code == 'SAVE10' ? round(subtotal * 0.1, 2) : code == 'FLAT5' ? min([5, subtotal]) : startsWith(code, 'VIP') ? round(subtotal * 0.2, 2) : 0";{code: 10, subtotal: 50};!error +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{code: 'SPRG-2025', redeemed: []};true +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{code: 'SPRG-2025', redeemed: ['SPRG-2025']};false +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{code: 'sprg-2025', redeemed: []};false +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{code: 'SPRG-20250', redeemed: []};false +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{redeemed: []};false +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{code: 'SUMR-0001', redeemed: ['SPRG-2025', 'WNTR-9999']};true +matches(code ?? '', '^[A-Z]{4}-[0-9]{4}$') and not (code in redeemed);{code: 'SPRG-2025', redeemed: null};!error +# Shipping: free threshold, weight bands, express +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 50, items: [{weightKg: 10, qty: 1}]};0 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 49.99, items: [{weightKg: 0.5, qty: 2}]};4.99 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 49.99, items: [{weightKg: 0.5, qty: 3}]};8.99 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 20, items: [{weightKg: 2.5, qty: 2}]};8.99 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 20, items: [{weightKg: 2.5, qty: 2}, {weightKg: 0.01, qty: 1}]};10.49 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 20, items: [{weightKg: 7.2, qty: 1}], express: true};25.49 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 80, items: [], express: true};12.00 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 20, items: [], express: 'yes'};4.99 +"w = sum(map(items, #.weightKg * #.qty)); (subtotal >= 50 ? 0 : w <= 1 ? 4.99 : w <= 5 ? 8.99 : 8.99 + ceil(w - 5) * 1.5) + (express == true ? 12.00 : 0)";{subtotal: 20, items: [{weightKg: null, qty: 1}]};!error +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'US', state: 'CA'};7.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'US', state: 'HI'};19.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'US'};7.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'CA'};14.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'NL'};24.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'JP'};39.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: 'us', state: 'AK'};39.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{country: null};39.95 +country == 'US' ? (state in ['AK', 'HI'] ? 19.95 : 7.95) : country in ['CA', 'MX'] ? 14.95 : contains(['DE', 'FR', 'NL', 'ES', 'IT'], country) ? 24.95 : 39.95;{};39.95 +# Sales tax by jurisdiction +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'CA', items: [{price: 100, qty: 1}, {price: 20, qty: 2, taxExempt: true}]};7.25 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'NY', items: [{price: 19.99, qty: 3}]};2.40 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'TX', items: [{price: 8, qty: 1}]};0.50 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'OR', items: [{price: 999.99, qty: 1}]};0.00 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'WA', items: [{price: 10, qty: 1}]};0.50 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{items: [{price: 10, qty: 1}]};0.50 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'CA', items: []};0.00 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'CA', items: [{price: 0.14, qty: 1}]};0.01 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'CA', items: [{price: 0.06, qty: 1}]};0.00 +round(sum(map(filter(items, not (#.taxExempt ?? false)), #.price * #.qty)) * (({CA: 0.0725, NY: 0.04, TX: 0.0625, OR: 0})[state] ?? 0.05), 2);{state: 'CA', items: [{sku: 'SKU-000', price: 1.00, qty: 1, category: 'books'}, {sku: 'SKU-001', price: 8.37, qty: 2, category: 'toys'}, {sku: 'SKU-002', price: 15.74, qty: 3, category: 'food'}, {sku: 'SKU-003', price: 22.11, qty: 4, category: 'electronics'}, {sku: 'SKU-004', price: 29.48, qty: 1, category: 'books'}, {sku: 'SKU-005', price: 36.85, qty: 2, category: 'toys'}, {sku: 'SKU-006', price: 43.22, qty: 3, category: 'food'}, {sku: 'SKU-007', price: 50.59, qty: 4, category: 'electronics'}, {sku: 'SKU-008', price: 7.96, qty: 1, category: 'books'}, {sku: 'SKU-009', price: 14.33, qty: 2, category: 'toys'}, {sku: 'SKU-010', price: 21.70, qty: 3, category: 'food'}, {sku: 'SKU-011', price: 28.07, qty: 4, category: 'electronics'}, {sku: 'SKU-012', price: 35.44, qty: 1, category: 'books'}, {sku: 'SKU-013', price: 42.81, qty: 2, category: 'toys'}, {sku: 'SKU-014', price: 49.18, qty: 3, category: 'food'}, {sku: 'SKU-015', price: 6.55, qty: 4, category: 'electronics'}, {sku: 'SKU-016', price: 13.92, qty: 1, category: 'books'}, {sku: 'SKU-017', price: 20.29, qty: 2, category: 'toys'}, {sku: 'SKU-018', price: 27.66, qty: 3, category: 'food'}, {sku: 'SKU-019', price: 34.03, qty: 4, category: 'electronics'}, {sku: 'SKU-020', price: 41.40, qty: 1, category: 'books'}, {sku: 'SKU-021', price: 48.77, qty: 2, category: 'toys'}, {sku: 'SKU-022', price: 5.14, qty: 3, category: 'food'}, {sku: 'SKU-023', price: 12.51, qty: 4, category: 'electronics'}, {sku: 'SKU-024', price: 19.88, qty: 1, category: 'books'}, {sku: 'SKU-025', price: 26.25, qty: 2, category: 'toys'}, {sku: 'SKU-026', price: 33.62, qty: 3, category: 'food'}, {sku: 'SKU-027', price: 40.99, qty: 4, category: 'electronics'}, {sku: 'SKU-028', price: 47.36, qty: 1, category: 'books'}, {sku: 'SKU-029', price: 4.73, qty: 2, category: 'toys'}, {sku: 'SKU-030', price: 11.10, qty: 3, category: 'food'}, {sku: 'SKU-031', price: 18.47, qty: 4, category: 'electronics'}, {sku: 'SKU-032', price: 25.84, qty: 1, category: 'books'}, {sku: 'SKU-033', price: 32.21, qty: 2, category: 'toys'}, {sku: 'SKU-034', price: 39.58, qty: 3, category: 'food'}, {sku: 'SKU-035', price: 46.95, qty: 4, category: 'electronics'}, {sku: 'SKU-036', price: 3.32, qty: 1, category: 'books'}, {sku: 'SKU-037', price: 10.69, qty: 2, category: 'toys'}, {sku: 'SKU-038', price: 17.06, qty: 3, category: 'food'}, {sku: 'SKU-039', price: 24.43, qty: 4, category: 'electronics'}]};191.91 +map(items, {sku: #.sku, tax: round(#.price * #.qty * rate, 2)});{rate: 0.0825, items: [{sku: 'A', price: 10, qty: 1}, {sku: 'B', price: 3.33, qty: 3}]};[{sku: 'A', tax: 0.83}, {sku: 'B', tax: 0.82}] +map(items, {sku: #.sku, tax: round(#.price * #.qty * rate, 2)});{rate: 0.2, items: []};[] +map(items, {sku: #.sku, tax: round(#.price * #.qty * rate, 2)});{rate: 0.19, items: [{sku: 'Ü-1', price: 0.05, qty: 1}, {sku: 'Ü-2', price: 0.03, qty: 1}]};[{sku: 'Ü-1', tax: 0.01}, {sku: 'Ü-2', tax: 0.01}] +map(items, {sku: #.sku, tax: round(#.price * #.qty * rate, 2)});{rate: null, items: [{sku: 'A', price: 1, qty: 1}]};!error +map(items, {sku: #.sku, tax: round(#.price * #.qty * rate, 2)});{rate: 0.07, items: [{sku: null, price: 12.5, qty: 2}]};[{sku: null, tax: 1.75}] +# VAT-inclusive pricing +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 119, vatRate: 0.19};{net: 100, vat: 19} +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 100, vatRate: 0.19};{net: 84.03, vat: 15.97} +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 9.99, vatRate: 0.2};{net: 8.33, vat: 1.66} +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 0.01, vatRate: 0.21};{net: 0.01, vat: 0.00} +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 1234.56, vatRate: 0.07};{net: 1153.79, vat: 80.77} +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 50, vatRate: 0};{net: 50, vat: 0} +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 50, vatRate: -1};!error +"net = round(gross / (1 + vatRate), 2); {net: net, vat: gross - net}";{gross: 50};!error +string(round(gross / (1 + vatRate), 2));{gross: 119, vatRate: 0.19};'100' +string(round(gross / (1 + vatRate), 2));{gross: 120, vatRate: 0.2};'100' +string(round(gross / (1 + vatRate), 2));{gross: 12.10, vatRate: 0.21};'10' +string(round(gross / (1 + vatRate), 2));{gross: 100, vatRate: 0.19};'84.03' +# Tiered volume discounts and buy-x-get-y +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 9};22.41 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 10};23.66 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 49};115.91 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 50};112.05 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 99};221.86 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 100};211.65 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 1000};2116.50 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: 0};0.00 +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49};!error +round(unitPrice * qty * (1 - (qty >= 100 ? 0.15 : qty >= 50 ? 0.10 : qty >= 10 ? 0.05 : 0)), 2);{unitPrice: 2.49, qty: '10'};!error +price * (qty - floor(qty / (buy + get)) * get);{price: 3.50, qty: 3, buy: 2, get: 1};7.00 +price * (qty - floor(qty / (buy + get)) * get);{price: 3.50, qty: 5, buy: 2, get: 1};14.00 +price * (qty - floor(qty / (buy + get)) * get);{price: 3.50, qty: 6, buy: 2, get: 1};14.00 +price * (qty - floor(qty / (buy + get)) * get);{price: 3.50, qty: 1, buy: 2, get: 1};3.50 +price * (qty - floor(qty / (buy + get)) * get);{price: 9.99, qty: 7, buy: 3, get: 2};49.95 +price * (qty - floor(qty / (buy + get)) * get);{price: 1, qty: 10, buy: 0, get: 0};!error +price * (qty - floor(qty / (buy + get)) * get);{price: 1, qty: 0, buy: 1, get: 1};0 +sum(map(items, #.category == 'books' ? #.price * #.qty * 0.95 : #.category == 'electronics' and #.price > 30 ? #.price * #.qty - 5 : #.price * #.qty));{items: [{category: 'books', price: 20, qty: 2}, {category: 'electronics', price: 30, qty: 1}, {category: 'electronics', price: 30.01, qty: 2}]};123.02 +sum(map(items, #.category == 'books' ? #.price * #.qty * 0.95 : #.category == 'electronics' and #.price > 30 ? #.price * #.qty - 5 : #.price * #.qty));{items: [{sku: 'SKU-000', price: 1.00, qty: 1, category: 'books'}, {sku: 'SKU-001', price: 8.37, qty: 2, category: 'toys'}, {sku: 'SKU-002', price: 15.74, qty: 3, category: 'food'}, {sku: 'SKU-003', price: 22.11, qty: 4, category: 'electronics'}, {sku: 'SKU-004', price: 29.48, qty: 1, category: 'books'}, {sku: 'SKU-005', price: 36.85, qty: 2, category: 'toys'}, {sku: 'SKU-006', price: 43.22, qty: 3, category: 'food'}, {sku: 'SKU-007', price: 50.59, qty: 4, category: 'electronics'}, {sku: 'SKU-008', price: 7.96, qty: 1, category: 'books'}, {sku: 'SKU-009', price: 14.33, qty: 2, category: 'toys'}, {sku: 'SKU-010', price: 21.70, qty: 3, category: 'food'}, {sku: 'SKU-011', price: 28.07, qty: 4, category: 'electronics'}, {sku: 'SKU-012', price: 35.44, qty: 1, category: 'books'}, {sku: 'SKU-013', price: 42.81, qty: 2, category: 'toys'}, {sku: 'SKU-014', price: 49.18, qty: 3, category: 'food'}, {sku: 'SKU-015', price: 6.55, qty: 4, category: 'electronics'}, {sku: 'SKU-016', price: 13.92, qty: 1, category: 'books'}, {sku: 'SKU-017', price: 20.29, qty: 2, category: 'toys'}, {sku: 'SKU-018', price: 27.66, qty: 3, category: 'food'}, {sku: 'SKU-019', price: 34.03, qty: 4, category: 'electronics'}, {sku: 'SKU-020', price: 41.40, qty: 1, category: 'books'}, {sku: 'SKU-021', price: 48.77, qty: 2, category: 'toys'}, {sku: 'SKU-022', price: 5.14, qty: 3, category: 'food'}, {sku: 'SKU-023', price: 12.51, qty: 4, category: 'electronics'}, {sku: 'SKU-024', price: 19.88, qty: 1, category: 'books'}, {sku: 'SKU-025', price: 26.25, qty: 2, category: 'toys'}, {sku: 'SKU-026', price: 33.62, qty: 3, category: 'food'}, {sku: 'SKU-027', price: 40.99, qty: 4, category: 'electronics'}, {sku: 'SKU-028', price: 47.36, qty: 1, category: 'books'}, {sku: 'SKU-029', price: 4.73, qty: 2, category: 'toys'}, {sku: 'SKU-030', price: 11.10, qty: 3, category: 'food'}, {sku: 'SKU-031', price: 18.47, qty: 4, category: 'electronics'}, {sku: 'SKU-032', price: 25.84, qty: 1, category: 'books'}, {sku: 'SKU-033', price: 32.21, qty: 2, category: 'toys'}, {sku: 'SKU-034', price: 39.58, qty: 3, category: 'food'}, {sku: 'SKU-035', price: 46.95, qty: 4, category: 'electronics'}, {sku: 'SKU-036', price: 3.32, qty: 1, category: 'books'}, {sku: 'SKU-037', price: 10.69, qty: 2, category: 'toys'}, {sku: 'SKU-038', price: 17.06, qty: 3, category: 'food'}, {sku: 'SKU-039', price: 24.43, qty: 4, category: 'electronics'}]};2615.7200 +sum(map(items, #.category == 'books' ? #.price * #.qty * 0.95 : #.category == 'electronics' and #.price > 30 ? #.price * #.qty - 5 : #.price * #.qty));{items: []};0 +sum(map(items, #.category == 'books' ? #.price * #.qty * 0.95 : #.category == 'electronics' and #.price > 30 ? #.price * #.qty - 5 : #.price * #.qty));{items: [{category: null, price: 5, qty: 1}]};5 +sum(map(items, #.category == 'books' ? #.price * #.qty * 0.95 : #.category == 'electronics' and #.price > 30 ? #.price * #.qty - 5 : #.price * #.qty));{items: [{category: 'electronics', qty: 1}]};!error +# Cart checks: stock, limits, mixed carts +some(items, #.qty > (stock[#.sku] ?? 0));{stock: {A: 5, B: 0}, items: [{sku: 'A', qty: 5}]};false +some(items, #.qty > (stock[#.sku] ?? 0));{stock: {A: 5, B: 0}, items: [{sku: 'A', qty: 6}]};true +some(items, #.qty > (stock[#.sku] ?? 0));{stock: {A: 5, B: 0}, items: [{sku: 'B', qty: 1}]};true +some(items, #.qty > (stock[#.sku] ?? 0));{stock: {A: 5}, items: [{sku: 'Z', qty: 1}]};true +some(items, #.qty > (stock[#.sku] ?? 0));{stock: {}, items: []};false +some(items, #.qty > (stock[#.sku] ?? 0));{stock: null, items: [{sku: 'A', qty: 1}]};true +some(items, #.qty > (stock[#.sku] ?? 0));{stock: {A: 5}, items: [{sku: 'A', qty: 0}]};false +map(filter(items, #.qty > (stock[#.sku] ?? 0)), #.sku);{stock: {A: 5, B: 0, 'C-1': 2}, items: [{sku: 'A', qty: 6}, {sku: 'B', qty: 1}, {sku: 'C-1', qty: 2}]};['A', 'B'] +map(filter(items, #.qty > (stock[#.sku] ?? 0)), #.sku);{stock: {}, items: [{sku: 'Ω', qty: 1}]};['Ω'] +map(filter(items, #.qty > (stock[#.sku] ?? 0)), #.sku);{stock: {A: 1}, items: []};[] +map(filter(items, #.qty > (stock[#.sku] ?? 0)), #.sku);{stock: {A: 1}, items: [{sku: 'A', qty: 1}]};[] +len(items) > 50 or sum(map(items, #.qty)) > 200 ? 'bulk-review' : count(items, #.category == 'electronics') > 3 ? 'fraud-check' : 'auto';{items: [{sku: 'SKU-000', price: 1.00, qty: 1, category: 'books'}, {sku: 'SKU-001', price: 8.37, qty: 2, category: 'toys'}, {sku: 'SKU-002', price: 15.74, qty: 3, category: 'food'}, {sku: 'SKU-003', price: 22.11, qty: 4, category: 'electronics'}, {sku: 'SKU-004', price: 29.48, qty: 1, category: 'books'}, {sku: 'SKU-005', price: 36.85, qty: 2, category: 'toys'}, {sku: 'SKU-006', price: 43.22, qty: 3, category: 'food'}, {sku: 'SKU-007', price: 50.59, qty: 4, category: 'electronics'}, {sku: 'SKU-008', price: 7.96, qty: 1, category: 'books'}, {sku: 'SKU-009', price: 14.33, qty: 2, category: 'toys'}, {sku: 'SKU-010', price: 21.70, qty: 3, category: 'food'}, {sku: 'SKU-011', price: 28.07, qty: 4, category: 'electronics'}, {sku: 'SKU-012', price: 35.44, qty: 1, category: 'books'}, {sku: 'SKU-013', price: 42.81, qty: 2, category: 'toys'}, {sku: 'SKU-014', price: 49.18, qty: 3, category: 'food'}, {sku: 'SKU-015', price: 6.55, qty: 4, category: 'electronics'}, {sku: 'SKU-016', price: 13.92, qty: 1, category: 'books'}, {sku: 'SKU-017', price: 20.29, qty: 2, category: 'toys'}, {sku: 'SKU-018', price: 27.66, qty: 3, category: 'food'}, {sku: 'SKU-019', price: 34.03, qty: 4, category: 'electronics'}, {sku: 'SKU-020', price: 41.40, qty: 1, category: 'books'}, {sku: 'SKU-021', price: 48.77, qty: 2, category: 'toys'}, {sku: 'SKU-022', price: 5.14, qty: 3, category: 'food'}, {sku: 'SKU-023', price: 12.51, qty: 4, category: 'electronics'}, {sku: 'SKU-024', price: 19.88, qty: 1, category: 'books'}, {sku: 'SKU-025', price: 26.25, qty: 2, category: 'toys'}, {sku: 'SKU-026', price: 33.62, qty: 3, category: 'food'}, {sku: 'SKU-027', price: 40.99, qty: 4, category: 'electronics'}, {sku: 'SKU-028', price: 47.36, qty: 1, category: 'books'}, {sku: 'SKU-029', price: 4.73, qty: 2, category: 'toys'}, {sku: 'SKU-030', price: 11.10, qty: 3, category: 'food'}, {sku: 'SKU-031', price: 18.47, qty: 4, category: 'electronics'}, {sku: 'SKU-032', price: 25.84, qty: 1, category: 'books'}, {sku: 'SKU-033', price: 32.21, qty: 2, category: 'toys'}, {sku: 'SKU-034', price: 39.58, qty: 3, category: 'food'}, {sku: 'SKU-035', price: 46.95, qty: 4, category: 'electronics'}, {sku: 'SKU-036', price: 3.32, qty: 1, category: 'books'}, {sku: 'SKU-037', price: 10.69, qty: 2, category: 'toys'}, {sku: 'SKU-038', price: 17.06, qty: 3, category: 'food'}, {sku: 'SKU-039', price: 24.43, qty: 4, category: 'electronics'}]};'fraud-check' +len(items) > 50 or sum(map(items, #.qty)) > 200 ? 'bulk-review' : count(items, #.category == 'electronics') > 3 ? 'fraud-check' : 'auto';{items: [{sku: 'X0', price: 0.10, qty: 3, category: 'food'}, {sku: 'X1', price: 0.10, qty: 3, category: 'food'}, {sku: 'X2', price: 0.10, qty: 3, category: 'food'}, {sku: 'X3', price: 0.10, qty: 3, category: 'food'}, {sku: 'X4', price: 0.10, qty: 3, category: 'food'}, {sku: 'X5', price: 0.10, qty: 3, category: 'food'}, {sku: 'X6', price: 0.10, qty: 3, category: 'food'}, {sku: 'X7', price: 0.10, qty: 3, category: 'food'}, {sku: 'X8', price: 0.10, qty: 3, category: 'food'}, {sku: 'X9', price: 0.10, qty: 3, category: 'food'}, {sku: 'X10', price: 0.10, qty: 3, category: 'food'}, {sku: 'X11', price: 0.10, qty: 3, category: 'food'}, {sku: 'X12', price: 0.10, qty: 3, category: 'food'}, {sku: 'X13', price: 0.10, qty: 3, category: 'food'}, {sku: 'X14', price: 0.10, qty: 3, category: 'food'}, {sku: 'X15', price: 0.10, qty: 3, category: 'food'}, {sku: 'X16', price: 0.10, qty: 3, category: 'food'}, {sku: 'X17', price: 0.10, qty: 3, category: 'food'}, {sku: 'X18', price: 0.10, qty: 3, category: 'food'}, {sku: 'X19', price: 0.10, qty: 3, category: 'food'}, {sku: 'X20', price: 0.10, qty: 3, category: 'food'}, {sku: 'X21', price: 0.10, qty: 3, category: 'food'}, {sku: 'X22', price: 0.10, qty: 3, category: 'food'}, {sku: 'X23', price: 0.10, qty: 3, category: 'food'}, {sku: 'X24', price: 0.10, qty: 3, category: 'food'}, {sku: 'X25', price: 0.10, qty: 3, category: 'food'}, {sku: 'X26', price: 0.10, qty: 3, category: 'food'}, {sku: 'X27', price: 0.10, qty: 3, category: 'food'}, {sku: 'X28', price: 0.10, qty: 3, category: 'food'}, {sku: 'X29', price: 0.10, qty: 3, category: 'food'}, {sku: 'X30', price: 0.10, qty: 3, category: 'food'}, {sku: 'X31', price: 0.10, qty: 3, category: 'food'}, {sku: 'X32', price: 0.10, qty: 3, category: 'food'}, {sku: 'X33', price: 0.10, qty: 3, category: 'food'}, {sku: 'X34', price: 0.10, qty: 3, category: 'food'}, {sku: 'X35', price: 0.10, qty: 3, category: 'food'}, {sku: 'X36', price: 0.10, qty: 3, category: 'food'}, {sku: 'X37', price: 0.10, qty: 3, category: 'food'}, {sku: 'X38', price: 0.10, qty: 3, category: 'food'}, {sku: 'X39', price: 0.10, qty: 3, category: 'food'}, {sku: 'X40', price: 0.10, qty: 3, category: 'food'}, {sku: 'X41', price: 0.10, qty: 3, category: 'food'}, {sku: 'X42', price: 0.10, qty: 3, category: 'food'}, {sku: 'X43', price: 0.10, qty: 3, category: 'food'}, {sku: 'X44', price: 0.10, qty: 3, category: 'food'}, {sku: 'X45', price: 0.10, qty: 3, category: 'food'}, {sku: 'X46', price: 0.10, qty: 3, category: 'food'}, {sku: 'X47', price: 0.10, qty: 3, category: 'food'}, {sku: 'X48', price: 0.10, qty: 3, category: 'food'}, {sku: 'X49', price: 0.10, qty: 3, category: 'food'}, {sku: 'X50', price: 0.10, qty: 3, category: 'food'}, {sku: 'X51', price: 0.10, qty: 3, category: 'food'}, {sku: 'X52', price: 0.10, qty: 3, category: 'food'}, {sku: 'X53', price: 0.10, qty: 3, category: 'food'}, {sku: 'X54', price: 0.10, qty: 3, category: 'food'}, {sku: 'X55', price: 0.10, qty: 3, category: 'food'}, {sku: 'X56', price: 0.10, qty: 3, category: 'food'}, {sku: 'X57', price: 0.10, qty: 3, category: 'food'}, {sku: 'X58', price: 0.10, qty: 3, category: 'food'}, {sku: 'X59', price: 0.10, qty: 3, category: 'food'}]};'bulk-review' +len(items) > 50 or sum(map(items, #.qty)) > 200 ? 'bulk-review' : count(items, #.category == 'electronics') > 3 ? 'fraud-check' : 'auto';{items: []};'auto' +len(items) > 50 or sum(map(items, #.qty)) > 200 ? 'bulk-review' : count(items, #.category == 'electronics') > 3 ? 'fraud-check' : 'auto';{items: [{qty: 201, category: 'food'}]};'bulk-review' +len(items) > 50 or sum(map(items, #.qty)) > 200 ? 'bulk-review' : count(items, #.category == 'electronics') > 3 ? 'fraud-check' : 'auto';{items: [{qty: 1, category: 'electronics'}, {qty: 1, category: 'electronics'}, {qty: 1, category: 'electronics'}]};'auto' +len(items) > 50 or sum(map(items, #.qty)) > 200 ? 'bulk-review' : count(items, #.category == 'electronics') > 3 ? 'fraud-check' : 'auto';{items: [{qty: 1, category: 'electronics'}, {qty: 1, category: 'electronics'}, {qty: 1, category: 'electronics'}, {qty: 1, category: 'electronics'}]};'fraud-check' +# Delivery date promises +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-03-17 09:00'};'2025-03-18' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-03-17 13:59'};'2025-03-18' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-03-17 14:00'};'2025-03-19' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-03-21 10:00'};'2025-03-24' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-03-22 10:00'};'2025-03-24' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-03-23 23:59'};'2025-03-25' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2024-12-31 15:00'};'2025-01-02' +"o = d(orderedAt); wd = o.weekday(); o.add((o.hour() >= 14 ? 1 : 0) + (wd == 5 ? 3 : wd == 6 ? 2 : 1), 'day').format('%Y-%m-%d')";{orderedAt: '2025-02-28 08:00'};'2025-03-03' +d(deliveredAt).diff(d(orderedAt), 'day') > (promisedDays ?? 5) ? round(total * 0.1, 2) : 0;{orderedAt: '2025-03-01', deliveredAt: '2025-03-06', total: 89.95};0 +d(deliveredAt).diff(d(orderedAt), 'day') > (promisedDays ?? 5) ? round(total * 0.1, 2) : 0;{orderedAt: '2025-03-01', deliveredAt: '2025-03-07', total: 89.95};9.00 +d(deliveredAt).diff(d(orderedAt), 'day') > (promisedDays ?? 5) ? round(total * 0.1, 2) : 0;{orderedAt: '2025-02-26', deliveredAt: '2025-03-02', total: 45.55, promisedDays: 3};4.56 +d(deliveredAt).diff(d(orderedAt), 'day') > (promisedDays ?? 5) ? round(total * 0.1, 2) : 0;{orderedAt: '2024-02-26', deliveredAt: '2024-03-02', total: 45.55, promisedDays: 3};4.56 +d(deliveredAt).diff(d(orderedAt), 'day') > (promisedDays ?? 5) ? round(total * 0.1, 2) : 0;{orderedAt: '2025-03-01 18:00', deliveredAt: '2025-03-07 09:00', total: 10};0 +d(deliveredAt).diff(d(orderedAt), 'day') > (promisedDays ?? 5) ? round(total * 0.1, 2) : 0;{orderedAt: '2025-03-01', deliveredAt: null, total: 10};!error +# Return windows +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: '2025-03-05', category: 'electronics'};true +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: '2025-03-04', category: 'electronics'};false +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: '2025-02-18', category: 'apparel'};true +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: '2025-02-17', category: 'apparel'};false +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: '2025-03-19', category: 'apparel', finalSale: true};false +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: '2025-03-25', category: 'apparel'};true +d().diff(d(purchasedOn), 'day') <= (category == 'electronics' ? 15 : 30) and not (finalSale ?? false);{purchasedOn: 'yesterday', category: 'apparel'};!error +# Order confirmation text +`Hi ${trim(customer.firstName ?? 'there')}, your order #${orderId} of ${len(items)} item(s) totals ${currency} ${string(round(sum(map(items, #.price * #.qty)), 2))}.`;{customer: {firstName: ' Chloé '}, orderId: 1001, currency: 'EUR', items: [{price: 12.5, qty: 2}]};'Hi Chloé, your order #1001 of 1 item(s) totals EUR 25.0.' +`Hi ${trim(customer.firstName ?? 'there')}, your order #${orderId} of ${len(items)} item(s) totals ${currency} ${string(round(sum(map(items, #.price * #.qty)), 2))}.`;{customer: {}, orderId: 'A-7', currency: 'USD', items: [{price: 0.333, qty: 3}]};'Hi there, your order #A-7 of 1 item(s) totals USD 1.00.' +`Hi ${trim(customer.firstName ?? 'there')}, your order #${orderId} of ${len(items)} item(s) totals ${currency} ${string(round(sum(map(items, #.price * #.qty)), 2))}.`;{customer: null, orderId: 9, currency: 'GBP', items: []};'Hi there, your order #9 of 0 item(s) totals GBP 0.' +`Hi ${trim(customer.firstName ?? 'there')}, your order #${orderId} of ${len(items)} item(s) totals ${currency} ${string(round(sum(map(items, #.price * #.qty)), 2))}.`;{customer: {firstName: '山田'}, orderId: 12, currency: 'JPY', items: [{price: 1200, qty: 1}]};'Hi 山田, your order #12 of 1 item(s) totals JPY 1200.' +`Hi ${trim(customer.firstName ?? 'there')}, your order #${orderId} of ${len(items)} item(s) totals ${currency} ${string(round(sum(map(items, #.price * #.qty)), 2))}.`;{customer: {firstName: 5}, orderId: 1, currency: 'USD', items: []};!error +{subtotal: sum(map(items, #.price * #.qty)), itemCount: sum(map(items, #.qty)), skus: map(items, upper(#.sku)), heaviest: max(map(items, #.weightKg ?? 0))};{items: [{sku: 'ab-1', price: 3.25, qty: 4, weightKg: 0.2}, {sku: 'cd-2', price: 10, qty: 1}]};{subtotal: 23.00, itemCount: 5, skus: ['AB-1', 'CD-2'], heaviest: 0.2} +{subtotal: sum(map(items, #.price * #.qty)), itemCount: sum(map(items, #.qty)), skus: map(items, upper(#.sku)), heaviest: max(map(items, #.weightKg ?? 0))};{items: []};!error +{subtotal: sum(map(items, #.price * #.qty)), itemCount: sum(map(items, #.qty)), skus: map(items, upper(#.sku)), heaviest: max(map(items, #.weightKg ?? 0))};{items: [{sku: 'straße', price: 1, qty: 1, weightKg: 1.5}]};{subtotal: 1, itemCount: 1, skus: ['STRASSE'], heaviest: 1.5} +{subtotal: sum(map(items, #.price * #.qty)), itemCount: sum(map(items, #.qty)), skus: map(items, upper(#.sku)), heaviest: max(map(items, #.weightKg ?? 0))};{items: [{sku: 7, price: 1, qty: 1}]};!error diff --git a/core/expression/tests/spec/standard/12-fraud-risk.csv b/core/expression/tests/spec/standard/12-fraud-risk.csv new file mode 100644 index 00000000..df2a9adc --- /dev/null +++ b/core/expression/tests/spec/standard/12-fraud-risk.csv @@ -0,0 +1,114 @@ +expression (string);input (json 5);output (json 5);note +# Additive risk scores +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 50, country: 'US', billingCountry: 'US', accountAgeDays: 400, emailVerified: true};0 +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 1000, country: 'US', billingCountry: 'US', accountAgeDays: 30, emailVerified: true};0 +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 1000.01, country: 'US', billingCountry: 'US', accountAgeDays: 29, emailVerified: true};40 +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 2500, country: 'NG', billingCountry: 'US', accountAgeDays: 2, emailVerified: false};120 +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 10, country: 'GB', billingCountry: 'GB'};25 +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 10, country: null, billingCountry: 'GB', accountAgeDays: 100, emailVerified: true};30 +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: null, country: 'US', billingCountry: 'US'};!error +(amount > 1000 ? 25 : 0) + (country != billingCountry ? 30 : 0) + (country in ['NG', 'RU', 'KP'] ? 40 : 0) + ((accountAgeDays ?? 0) < 30 ? 15 : 0) + ((emailVerified ?? false) ? 0 : 10);{amount: 10, country: 'RU', billingCountry: 'RU', accountAgeDays: 5000, emailVerified: 'yes'};!error +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 10, signals: [{weight: 5}, {weight: 4.5}]};{score: 19.5, action: 'allow'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 10, signals: [{weight: 10}]};{score: 20, action: 'step-up'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 0, signals: [{weight: 49.99}]};{score: 49.99, action: 'step-up'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 0, signals: [{weight: 50}]};{score: 50, action: 'review'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 30, signals: [{weight: 25}, {weight: 25}]};{score: 80, action: 'block'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 70, signals: [{weight: 45}]};{score: 100, action: 'block'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 0, signals: [{weight: -30}]};{score: 0, action: 'allow'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 5, signals: []};{score: 5, action: 'allow'} +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 5, signals: [{weight: null}]};!error +"s = min([100, max([0, base + sum(map(signals, #.weight))])]); {score: s, action: s >= 80 ? 'block' : s >= 50 ? 'review' : s >= 20 ? 'step-up' : 'allow'}";{base: 5, signals: [{}, {weight: 1}]};!error +# Velocity checks over transaction history +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};false +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 9999.99, country: 'US', at: '2025-03-19 02:00'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:01'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:02'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:03'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:04'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:05'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:06'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:07'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:08'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:09'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:10'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:11'}]};true +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: []};false +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 501}, {amount: 501}, {amount: 500}]};false +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 501}, {amount: 501}, {amount: 501}]};true +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 2500}, {amount: 2500}]};false +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 2500}, {amount: 2500.01}]};true +count(txns, #.amount > 500) >= 3 or sum(map(txns, #.amount)) > 5000;{txns: [{amount: 100}, {amount: null}]};!error +len(filter(txns, d(#.at) >= d(now).add(-1, 'hour'))) > 5;{now: '2025-03-19 12:00', txns: [{at: '2025-03-19 11:00'}, {at: '2025-03-19 11:10'}, {at: '2025-03-19 11:20'}, {at: '2025-03-19 11:30'}, {at: '2025-03-19 11:40'}, {at: '2025-03-19 11:59'}]};true +len(filter(txns, d(#.at) >= d(now).add(-1, 'hour'))) > 5;{now: '2025-03-19 12:00', txns: [{at: '2025-03-19 10:59'}, {at: '2025-03-19 11:10'}, {at: '2025-03-19 11:20'}, {at: '2025-03-19 11:30'}, {at: '2025-03-19 11:40'}, {at: '2025-03-19 11:59'}]};false +len(filter(txns, d(#.at) >= d(now).add(-1, 'hour'))) > 5;{now: '2025-03-19 00:30', txns: [{at: '2025-03-18 23:30'}, {at: '2025-03-18 23:31'}, {at: '2025-03-18 23:59'}, {at: '2025-03-19 00:00'}, {at: '2025-03-19 00:10'}, {at: '2025-03-19 00:29'}]};true +len(filter(txns, d(#.at) >= d(now).add(-1, 'hour'))) > 5;{now: '2025-03-19 12:00', txns: []};false +len(filter(txns, d(#.at) >= d(now).add(-1, 'hour'))) > 5;{now: '2025-03-19 12:00', txns: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};true +map(txns, d(#.at).hour());{txns: [{amount: 9999.99, country: 'US', at: '2025-03-19 02:00'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:01'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:02'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:03'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:04'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:05'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:06'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:07'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:08'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:09'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:10'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:11'}]};[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] +map(txns, d(#.at).hour());{txns: []};[] +map(txns, d(#.at).hour());{txns: [{at: '2025-12-31 23:59:59'}, {at: '2026-01-01 00:00'}]};[23, 0] +map(txns, d(#.at).hour());{txns: [{at: 'garbage'}]};[null] +count(txns, d(#.at).hour() < 6) / len(txns) >= 0.5;{txns: [{amount: 9999.99, country: 'US', at: '2025-03-19 02:00'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:01'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:02'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:03'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:04'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:05'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:06'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:07'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:08'}, {amount: 9999.99, country: 'US', at: '2025-03-19 02:09'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:10'}, {amount: 0.99, country: 'US', at: '2025-03-19 02:11'}]};true +count(txns, d(#.at).hour() < 6) / len(txns) >= 0.5;{txns: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};false +count(txns, d(#.at).hour() < 6) / len(txns) >= 0.5;{txns: [{at: '2025-03-19 05:59'}, {at: '2025-03-19 06:00'}]};true +count(txns, d(#.at).hour() < 6) / len(txns) >= 0.5;{txns: [{at: '2025-03-19 06:00'}, {at: '2025-03-19 06:01'}, {at: '2025-03-19 01:00'}]};false +count(txns, d(#.at).hour() < 6) / len(txns) >= 0.5;{txns: []};!error +len(filter(map(txns, #.country), # != homeCountry)) > 0 and none(txns, #.country == homeCountry);{homeCountry: 'US', txns: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};false +len(filter(map(txns, #.country), # != homeCountry)) > 0 and none(txns, #.country == homeCountry);{homeCountry: 'FR', txns: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};true +len(filter(map(txns, #.country), # != homeCountry)) > 0 and none(txns, #.country == homeCountry);{homeCountry: 'US', txns: []};false +len(filter(map(txns, #.country), # != homeCountry)) > 0 and none(txns, #.country == homeCountry);{homeCountry: null, txns: [{country: null}]};false +len(filter(map(txns, #.country), # != homeCountry)) > 0 and none(txns, #.country == homeCountry);{homeCountry: 'US', txns: [{country: 'US'}, {}]};false +len(filter(map(txns, #.country), # != homeCountry)) > 0 and none(txns, #.country == homeCountry);{homeCountry: 'US', txns: [{}]};true +# Amount anomaly versus history +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 900, history: [{amount: 100}, {amount: 200}, {amount: 300}]};true +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 1200.01, history: [{amount: 100}, {amount: 200}, {amount: 300}, {amount: 1000}]};true +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 1200, history: [{amount: 100}, {amount: 200}, {amount: 300}, {amount: 1000}]};false +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 150, history: [{amount: 1}]};false +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 300, history: [{amount: 33.33}, {amount: 33.33}, {amount: 33.34}]};true +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 900, history: []};!error +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 900, history: [{amount: '100'}]};!error +amount > avg(map(history, #.amount)) * 3 and amount > 200;{amount: 999, history: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};true +round(abs(amount - median(map(history, #.amount))) / median(map(history, #.amount)), 4);{amount: 150, history: [{amount: 100}, {amount: 90}, {amount: 110}]};0.5 +round(abs(amount - median(map(history, #.amount))) / median(map(history, #.amount)), 4);{amount: 50, history: [{amount: 100}, {amount: 200}]};0.6667 +round(abs(amount - median(map(history, #.amount))) / median(map(history, #.amount)), 4);{amount: 0, history: [{amount: 10}, {amount: 20}, {amount: 30}, {amount: 40}]};1 +round(abs(amount - median(map(history, #.amount))) / median(map(history, #.amount)), 4);{amount: 100, history: [{amount: 0}, {amount: 0}, {amount: 5}]};!error +round(abs(amount - median(map(history, #.amount))) / median(map(history, #.amount)), 4);{amount: 100, history: []};!error +round(abs(amount - median(map(history, #.amount))) / median(map(history, #.amount)), 4);{amount: 77.77, history: [{amount: 10.00, country: 'US', at: '2025-03-19 00:00'}, {amount: 23.07, country: 'US', at: '2025-03-19 01:01'}, {amount: 36.14, country: 'GB', at: '2025-03-19 02:02'}, {amount: 49.21, country: 'NG', at: '2025-03-19 03:03'}, {amount: 62.28, country: 'US', at: '2025-03-19 04:04'}, {amount: 75.35, country: 'US', at: '2025-03-19 05:05'}, {amount: 88.42, country: 'US', at: '2025-03-19 06:06'}, {amount: 101.49, country: 'GB', at: '2025-03-19 07:07'}, {amount: 114.56, country: 'NG', at: '2025-03-19 08:08'}, {amount: 127.63, country: 'US', at: '2025-03-19 09:09'}, {amount: 140.70, country: 'US', at: '2025-03-19 10:10'}, {amount: 153.77, country: 'US', at: '2025-03-19 11:11'}, {amount: 166.84, country: 'GB', at: '2025-03-19 12:12'}, {amount: 179.91, country: 'NG', at: '2025-03-19 13:13'}, {amount: 192.98, country: 'US', at: '2025-03-19 14:14'}, {amount: 205.05, country: 'US', at: '2025-03-19 15:15'}, {amount: 18.12, country: 'US', at: '2025-03-19 16:16'}, {amount: 31.19, country: 'GB', at: '2025-03-19 17:17'}, {amount: 44.26, country: 'NG', at: '2025-03-19 18:18'}, {amount: 57.33, country: 'US', at: '2025-03-19 19:19'}, {amount: 70.40, country: 'US', at: '2025-03-19 20:20'}, {amount: 83.47, country: 'US', at: '2025-03-19 21:21'}, {amount: 96.54, country: 'GB', at: '2025-03-19 22:22'}, {amount: 109.61, country: 'NG', at: '2025-03-19 23:23'}, {amount: 122.68, country: 'US', at: '2025-03-19 00:24'}, {amount: 135.75, country: 'US', at: '2025-03-19 01:25'}, {amount: 148.82, country: 'US', at: '2025-03-19 02:26'}, {amount: 161.89, country: 'GB', at: '2025-03-19 03:27'}, {amount: 174.96, country: 'NG', at: '2025-03-19 04:28'}, {amount: 187.03, country: 'US', at: '2025-03-19 05:29'}]};0.2632 +# Device and identity signals +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '203.0.113.9', blockedIps: ['203.0.113.9'], userAgent: 'Mozilla/5.0'};true +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '10.1.2.3', blockedIps: [], userAgent: 'Mozilla/5.0'};true +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '110.1.2.3', blockedIps: [], userAgent: 'Mozilla/5.0'};false +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '198.51.100.1', blockedIps: [], userAgent: 'Googlebot/2.1'};true +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '198.51.100.1', blockedIps: [], userAgent: 'CURL/8.0'};true +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '198.51.100.1', blockedIps: [], userAgent: 'Python-Requests/2.31'};true +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: null, blockedIps: [], userAgent: null};false +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{blockedIps: []};false +(ip in blockedIps) or startsWith(ip ?? '', '10.') or matches(userAgent ?? '', '(?i)(bot|curl|python-requests)');{ip: '198.51.100.1', blockedIps: null, userAgent: 'x'};!error +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: 'a@mailinator.com', disposableDomains: ['mailinator.com', 'tempmail.io']};30 +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: 'a@MAILINATOR.COM', disposableDomains: ['mailinator.com']};30 +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: 'ivan@yandex.RU', disposableDomains: ['mailinator.com']};10 +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: 'bob@example.com', disposableDomains: ['mailinator.com']};0 +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: 'no-at-sign', disposableDomains: ['mailinator.com']};0 +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: 'x@tempmail.io', disposableDomains: []};0 +lower(split(email, '@')[1] ?? '') in disposableDomains ? 30 : endsWith(lower(email), '.ru') ? 10 : 0;{email: null, disposableDomains: []};!error +len(distinctCards ?? []) > 3 or count(attempts, #.declined) >= 3;{distinctCards: ['a', 'b', 'c', 'd'], attempts: []};true +len(distinctCards ?? []) > 3 or count(attempts, #.declined) >= 3;{distinctCards: ['a', 'b', 'c'], attempts: [{declined: true}, {declined: true}]};false +len(distinctCards ?? []) > 3 or count(attempts, #.declined) >= 3;{attempts: [{declined: true}, {declined: false}, {declined: true}, {declined: true}]};true +len(distinctCards ?? []) > 3 or count(attempts, #.declined) >= 3;{distinctCards: null, attempts: []};false +len(distinctCards ?? []) > 3 or count(attempts, #.declined) >= 3;{distinctCards: [], attempts: [{declined: null}]};!error +len(distinctCards ?? []) > 3 or count(attempts, #.declined) >= 3;{distinctCards: 'abcd', attempts: []};true +# Chargeback ratio monitoring +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 10, transactions: 1000};'excessive' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 9, transactions: 1000};'early-warning' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 65, transactions: 10000};'early-warning' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 64, transactions: 10000};'normal' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 0, transactions: 0};'normal' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 1, transactions: 0};'excessive' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: 3, transactions: 450};'early-warning' +"ratio = chargebacks / max([1, transactions]) * 100; ratio >= 1 ? 'excessive' : ratio >= 0.65 ? 'early-warning' : 'normal'";{chargebacks: null, transactions: 100};!error +# Rule hits collected into a reasons list +filter(['high-amount', 'geo-mismatch', 'new-account'], # == 'high-amount' ? amount > 5000 : # == 'geo-mismatch' ? ipCountry != cardCountry : accountAgeDays < 7);{amount: 6000, ipCountry: 'US', cardCountry: 'CA', accountAgeDays: 1};['high-amount', 'geo-mismatch', 'new-account'] +filter(['high-amount', 'geo-mismatch', 'new-account'], # == 'high-amount' ? amount > 5000 : # == 'geo-mismatch' ? ipCountry != cardCountry : accountAgeDays < 7);{amount: 5000, ipCountry: 'US', cardCountry: 'US', accountAgeDays: 7};[] +filter(['high-amount', 'geo-mismatch', 'new-account'], # == 'high-amount' ? amount > 5000 : # == 'geo-mismatch' ? ipCountry != cardCountry : accountAgeDays < 7);{amount: 10, ipCountry: 'BR', cardCountry: 'US', accountAgeDays: 100};['geo-mismatch'] +filter(['high-amount', 'geo-mismatch', 'new-account'], # == 'high-amount' ? amount > 5000 : # == 'geo-mismatch' ? ipCountry != cardCountry : accountAgeDays < 7);{amount: 10, ipCountry: null, cardCountry: null, accountAgeDays: 6};['new-account'] +filter(['high-amount', 'geo-mismatch', 'new-account'], # == 'high-amount' ? amount > 5000 : # == 'geo-mismatch' ? ipCountry != cardCountry : accountAgeDays < 7);{amount: 10, ipCountry: 'US', cardCountry: 'US', accountAgeDays: null};!error +`risk=${score} reasons=${len(reasons)} first=${reasons[0] ?? 'none'}`;{score: 72.5, reasons: ['geo', 'velocity']};'risk=72.5 reasons=2 first=geo' +`risk=${score} reasons=${len(reasons)} first=${reasons[0] ?? 'none'}`;{score: 0, reasons: []};'risk=0 reasons=0 first=none' +`risk=${score} reasons=${len(reasons)} first=${reasons[0] ?? 'none'}`;{score: null, reasons: ['x']};'risk=null reasons=1 first=x' +`risk=${score} reasons=${len(reasons)} first=${reasons[0] ?? 'none'}`;{score: 10, reasons: null};!error +# Sanctions screening by normalized name +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: 'John Doe', watchlist: ['JOHN DOE ', 'Jane Roe']};true +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: ' jane roe', watchlist: ['JOHN DOE', 'Jane Roe']};true +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: 'Jon Doe', watchlist: ['John Doe']};false +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: 'ÉLODIE DURAND', watchlist: ['élodie durand']};true +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: 'x', watchlist: []};false +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: null, watchlist: ['a']};!error +some(watchlist, lower(trim(#)) == lower(trim(name)));{name: 'a', watchlist: ['a', null]};true diff --git a/core/expression/tests/spec/standard/12-healthcare.csv b/core/expression/tests/spec/standard/12-healthcare.csv new file mode 100644 index 00000000..f4e4a659 --- /dev/null +++ b/core/expression/tests/spec/standard/12-healthcare.csv @@ -0,0 +1,124 @@ +expression (string);input (json 5);output (json 5);note +# Age-based program eligibility +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '2007-03-20', serviceDate: '2025-03-19', income: 0, fpl: 15650};'CHIP' +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '2006-03-20', serviceDate: '2025-03-20', income: 0, fpl: 15650};'Medicaid' +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '1960-03-21', serviceDate: '2025-03-20', income: 90000, fpl: 15650};'Marketplace' +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '1960-03-20', serviceDate: '2025-03-20', income: 90000, fpl: 15650};'Medicare' +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '1985-01-01', serviceDate: '2025-03-20', income: 21597, fpl: 15650};'Medicaid' +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '1985-01-01', serviceDate: '2025-03-20', income: 21597.01, fpl: 15650};'Marketplace' +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: '1985-01-01', serviceDate: '2025-03-20', income: null, fpl: 15650};!error +"age = d(serviceDate).diff(d(dob), 'year'); age < 19 ? 'CHIP' : age >= 65 ? 'Medicare' : income <= fpl * 1.38 ? 'Medicaid' : 'Marketplace'";{dob: 'unknown', serviceDate: '2025-03-20', income: 0, fpl: 15650};!error +round(income / (fpl + (householdSize - 1) * perPerson) * 100, 1);{income: 32000, fpl: 15650, householdSize: 1, perPerson: 5500};204.5 +round(income / (fpl + (householdSize - 1) * perPerson) * 100, 1);{income: 32000, fpl: 15650, householdSize: 4, perPerson: 5500};99.5 +round(income / (fpl + (householdSize - 1) * perPerson) * 100, 1);{income: 0, fpl: 15650, householdSize: 2, perPerson: 5500};0 +round(income / (fpl + (householdSize - 1) * perPerson) * 100, 1);{income: 45000.50, fpl: 15650, householdSize: 3, perPerson: 5500};168.9 +round(income / (fpl + (householdSize - 1) * perPerson) * 100, 1);{income: 32000, fpl: 0, householdSize: 1, perPerson: 5500};!error +round(income / (fpl + (householdSize - 1) * perPerson) * 100, 1);{income: 32000, fpl: 15650, perPerson: 5500};!error +# Cost sharing: deductible, coinsurance, out-of-pocket max +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: 0, coinsurance: 0.2, oopMax: 6000, oopYtd: 0};1000.0 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: 1200, coinsurance: 0.2, oopMax: 6000, oopYtd: 1200};440.0 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: 1500, coinsurance: 0.2, oopMax: 6000, oopYtd: 3000};200.0 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: 1500, coinsurance: 0.2, oopMax: 6000, oopYtd: 5900};100 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: 1500, coinsurance: 0.2, oopMax: 6000, oopYtd: 6000};0 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: 1600, coinsurance: 0.2, oopMax: 6000, oopYtd: 6100};0 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 0, deductible: 1500, metYtd: 0, coinsurance: 0.3, oopMax: 6000, oopYtd: 0};0.0 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 437.63, deductible: 250, metYtd: 100, coinsurance: 0.15, oopMax: 3000, oopYtd: 100};193.1445 +"remaining = max([0, deductible - metYtd]); ded = min([billed, remaining]); min([ded + (billed - ded) * coinsurance, max([0, oopMax - oopYtd])])";{billed: 1000, deductible: 1500, metYtd: null, coinsurance: 0.2, oopMax: 6000, oopYtd: 0};!error +sum(map(claims, #.billed * (#.inNetwork ? 0.8 : 0.5)));{claims: [{billed: 200, inNetwork: true}, {billed: 300, inNetwork: false}]};310.0 +sum(map(claims, #.billed * (#.inNetwork ? 0.8 : 0.5)));{claims: []};0 +sum(map(claims, #.billed * (#.inNetwork ? 0.8 : 0.5)));{claims: [{billed: 125.25, inNetwork: true}]};100.200 +sum(map(claims, #.billed * (#.inNetwork ? 0.8 : 0.5)));{claims: [{billed: 100}]};!error +sum(map(claims, #.billed * (#.inNetwork ? 0.8 : 0.5)));{claims: [{billed: 100, inNetwork: 'Y'}]};!error +sum(map(claims, #.billed * (#.inNetwork ? 0.8 : 0.5)));{claims: [{billed: 50.00, inNetwork: false}, {billed: 61.03, inNetwork: true}, {billed: 72.06, inNetwork: true}, {billed: 83.09, inNetwork: false}, {billed: 94.12, inNetwork: true}, {billed: 105.15, inNetwork: true}, {billed: 116.18, inNetwork: false}, {billed: 127.21, inNetwork: true}, {billed: 138.24, inNetwork: true}, {billed: 149.27, inNetwork: false}, {billed: 160.30, inNetwork: true}, {billed: 171.33, inNetwork: true}, {billed: 182.36, inNetwork: false}, {billed: 193.39, inNetwork: true}, {billed: 204.42, inNetwork: true}, {billed: 215.45, inNetwork: false}, {billed: 226.48, inNetwork: true}, {billed: 237.51, inNetwork: true}, {billed: 248.54, inNetwork: false}, {billed: 259.57, inNetwork: true}, {billed: 270.60, inNetwork: true}, {billed: 281.63, inNetwork: false}, {billed: 292.66, inNetwork: true}, {billed: 303.69, inNetwork: true}, {billed: 314.72, inNetwork: false}]};3154.828 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'primary', admitted: false};25 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'specialist'};50 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'er', admitted: false};250 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'er', admitted: true};0 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'telehealth', admitted: false};0 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: null};0 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'ER', admitted: true};0 +"copay = ({primary: 25, specialist: 50, urgent: 75, er: 250})[visitType] ?? 0; visitType == 'er' and admitted ? 0 : copay";{visitType: 'er'};!error +# Clinical thresholds +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 118, diastolic: 76};'normal' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 120, diastolic: 79};'elevated' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 129, diastolic: 80};'stage1' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 130, diastolic: 70};'stage1' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 139, diastolic: 89};'stage1' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 140, diastolic: 60};'stage2' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 150, diastolic: 120};'crisis' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 180, diastolic: 80};'crisis' +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: 110, diastolic: null};!error +systolic >= 180 or diastolic >= 120 ? 'crisis' : systolic >= 140 or diastolic >= 90 ? 'stage2' : systolic >= 130 or diastolic >= 80 ? 'stage1' : systolic >= 120 ? 'elevated' : 'normal';{systolic: null, diastolic: 130};!error +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 70, sex: 'M', age: 60, creatinine: 1.0};77.8 +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 70, sex: 'F', age: 60, creatinine: 1.0};66.1 +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 82.5, sex: 'M', age: 45, creatinine: 1.3};83.7 +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 55, sex: 'F', age: 85, creatinine: 0.7};51.0 +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 70, sex: 'M', age: 60, creatinine: 0};!error +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 70, sex: 'X', age: 140, creatinine: 1};0 +round(weightKg * (sex == 'F' ? 0.85 : 1) * (140 - age) / (72 * creatinine), 1);{weightKg: 70, age: 30, creatinine: 1.1};97.2 +map(readings, #.value >= 70 and #.value <= 180 ? 'in-range' : #.value < 70 ? 'low' : 'high');{readings: [{value: 69}, {value: 70}, {value: 180}, {value: 181}, {value: 120.5}]};['low', 'in-range', 'in-range', 'high', 'in-range'] +map(readings, #.value >= 70 and #.value <= 180 ? 'in-range' : #.value < 70 ? 'low' : 'high');{readings: []};[] +map(readings, #.value >= 70 and #.value <= 180 ? 'in-range' : #.value < 70 ? 'low' : 'high');{readings: [{value: 40}]};['low'] +map(readings, #.value >= 70 and #.value <= 180 ? 'in-range' : #.value < 70 ? 'low' : 'high');{readings: [{value: null}]};!error +round(count(readings, #.value >= 70 and #.value <= 180) / len(readings) * 100, 1);{readings: [{value: 69}, {value: 70}, {value: 180}, {value: 181}, {value: 120.5}]};60.0 +round(count(readings, #.value >= 70 and #.value <= 180) / len(readings) * 100, 1);{readings: [{value: 100}, {value: 100}, {value: 250}]};66.7 +round(count(readings, #.value >= 70 and #.value <= 180) / len(readings) * 100, 1);{readings: []};!error +round(count(readings, #.value >= 70 and #.value <= 180) / len(readings) * 100, 1);{readings: [{value: 50}, {value: 57}, {value: 64}, {value: 71}, {value: 78}, {value: 85}, {value: 92}, {value: 99}, {value: 106}, {value: 113}, {value: 120}, {value: 127}, {value: 134}, {value: 141}, {value: 148}, {value: 155}, {value: 162}, {value: 169}, {value: 176}, {value: 183}, {value: 190}, {value: 197}, {value: 204}, {value: 211}, {value: 218}, {value: 225}, {value: 232}, {value: 239}, {value: 246}, {value: 253}]};53.3 +# Prior authorization and formulary +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 4, specialty: false}, quantity: 30};'prior-auth' +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 2, specialty: true}, quantity: 30};'prior-auth' +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 2, specialty: false}, quantity: 30};'auto-approve' +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 2, specialty: false}, quantity: 31};'prior-auth' +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 1, specialty: false, maxQty: 90}, quantity: 90};'auto-approve' +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 1, specialty: false}};'auto-approve' +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: {tier: 1}, quantity: 10};!error +drug.tier >= 4 or drug.specialty or (quantity ?? 0) > (drug.maxQty ?? 30) ? 'prior-auth' : 'auto-approve';{drug: null, quantity: 10};!error +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: ['E11.9', 'I10'], meds: ['Lisinopril']};'care-gap' +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: ['E11.65'], meds: ['METFORMIN']};'ok' +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: ['E10.9'], meds: []};'ok' +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: [], meds: []};'ok' +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: ['I10', 'E11'], meds: ['Metformin ER']};'care-gap' +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: ['E11.9'], meds: null};!error +some(diagnoses, startsWith(#, 'E11')) and not some(meds, lower(#) == 'metformin') ? 'care-gap' : 'ok';{diagnoses: [11], meds: []};!error +filter(map(codes, trim(upper(#))), matches(#, '^[A-TV-Z][0-9][0-9AB](\.[0-9A-TV-Z]{1,4})?$'));{codes: ['e11.9', ' I10 ', 'U07.1', 'XYZ', 'J45.909', 'Z00.00000']};['E11.9', 'I10', 'J45.909'] +filter(map(codes, trim(upper(#))), matches(#, '^[A-TV-Z][0-9][0-9AB](\.[0-9A-TV-Z]{1,4})?$'));{codes: []};[] +filter(map(codes, trim(upper(#))), matches(#, '^[A-TV-Z][0-9][0-9AB](\.[0-9A-TV-Z]{1,4})?$'));{codes: ['a01']};['A01'] +filter(map(codes, trim(upper(#))), matches(#, '^[A-TV-Z][0-9][0-9AB](\.[0-9A-TV-Z]{1,4})?$'));{codes: [null]};!error +# Coverage periods and waiting periods +d(serviceDate) >= d(coverageStart) and d(serviceDate) <= d(coverageEnd ?? '9999-12-31');{serviceDate: '2025-01-01', coverageStart: '2025-01-01', coverageEnd: '2025-12-31'};true +d(serviceDate) >= d(coverageStart) and d(serviceDate) <= d(coverageEnd ?? '9999-12-31');{serviceDate: '2024-12-31', coverageStart: '2025-01-01', coverageEnd: '2025-12-31'};false +d(serviceDate) >= d(coverageStart) and d(serviceDate) <= d(coverageEnd ?? '9999-12-31');{serviceDate: '2025-12-31', coverageStart: '2025-01-01', coverageEnd: '2025-12-31'};true +d(serviceDate) >= d(coverageStart) and d(serviceDate) <= d(coverageEnd ?? '9999-12-31');{serviceDate: '2025-12-31 12:00', coverageStart: '2025-01-01', coverageEnd: '2025-12-31'};false +d(serviceDate) >= d(coverageStart) and d(serviceDate) <= d(coverageEnd ?? '9999-12-31');{serviceDate: '2031-06-01', coverageStart: '2025-01-01'};true +d(serviceDate) >= d(coverageStart) and d(serviceDate) <= d(coverageEnd ?? '9999-12-31');{serviceDate: '2025-06-01', coverageStart: '2025-01-01', coverageEnd: null};true +d(serviceDate) >= d(serviceDate).startOf('month') and d(coverageStart).add(waitingMonths, 'month') <= d(serviceDate);{coverageStart: '2024-08-31', waitingMonths: 6, serviceDate: '2025-02-28'};true +d(serviceDate) >= d(serviceDate).startOf('month') and d(coverageStart).add(waitingMonths, 'month') <= d(serviceDate);{coverageStart: '2024-08-31', waitingMonths: 6, serviceDate: '2025-02-27'};false +d(serviceDate) >= d(serviceDate).startOf('month') and d(coverageStart).add(waitingMonths, 'month') <= d(serviceDate);{coverageStart: '2024-01-15', waitingMonths: 12, serviceDate: '2025-01-15'};true +d(serviceDate) >= d(serviceDate).startOf('month') and d(coverageStart).add(waitingMonths, 'month') <= d(serviceDate);{coverageStart: '2024-01-15', waitingMonths: 12, serviceDate: '2025-01-14'};false +d(serviceDate) >= d(serviceDate).startOf('month') and d(coverageStart).add(waitingMonths, 'month') <= d(serviceDate);{coverageStart: '2024-01-15', waitingMonths: 0, serviceDate: '2024-01-15'};true +d(serviceDate) >= d(serviceDate).startOf('month') and d(coverageStart).add(waitingMonths, 'month') <= d(serviceDate);{coverageStart: '2024-01-15', serviceDate: '2025-01-15'};!error +d(dischargedAt).diff(d(admittedAt), 'day') < 30 and previousDiagnosis == diagnosis ? 'readmission' : 'new-episode';{admittedAt: '2025-02-01', dischargedAt: '2025-03-02', previousDiagnosis: 'I50.9', diagnosis: 'I50.9'};'readmission' +d(dischargedAt).diff(d(admittedAt), 'day') < 30 and previousDiagnosis == diagnosis ? 'readmission' : 'new-episode';{admittedAt: '2025-02-01', dischargedAt: '2025-03-03', previousDiagnosis: 'I50.9', diagnosis: 'I50.9'};'new-episode' +d(dischargedAt).diff(d(admittedAt), 'day') < 30 and previousDiagnosis == diagnosis ? 'readmission' : 'new-episode';{admittedAt: '2024-02-01', dischargedAt: '2024-03-02', previousDiagnosis: 'I50.9', diagnosis: 'I50.9'};'new-episode' +d(dischargedAt).diff(d(admittedAt), 'day') < 30 and previousDiagnosis == diagnosis ? 'readmission' : 'new-episode';{admittedAt: '2025-02-01', dischargedAt: '2025-02-05', previousDiagnosis: 'J18.9', diagnosis: 'I50.9'};'new-episode' +d(dischargedAt).diff(d(admittedAt), 'day') < 30 and previousDiagnosis == diagnosis ? 'readmission' : 'new-episode';{admittedAt: '2025-02-01', dischargedAt: '2025-02-05', diagnosis: 'I50.9'};'new-episode' +d(dischargedAt).diff(d(admittedAt), 'day') < 30 and previousDiagnosis == diagnosis ? 'readmission' : 'new-episode';{admittedAt: '2025-02-01', previousDiagnosis: 'x', diagnosis: 'x'};!error +d(lastVisit).add(intervalMonths ?? 12, 'month').isBefore(d()) ? 'overdue' : 'up-to-date';{lastVisit: '2024-03-20'};'overdue' +d(lastVisit).add(intervalMonths ?? 12, 'month').isBefore(d()) ? 'overdue' : 'up-to-date';{lastVisit: '2024-03-21'};'up-to-date' +d(lastVisit).add(intervalMonths ?? 12, 'month').isBefore(d()) ? 'overdue' : 'up-to-date';{lastVisit: '2024-03-19', intervalMonths: 12};'overdue' +d(lastVisit).add(intervalMonths ?? 12, 'month').isBefore(d()) ? 'overdue' : 'up-to-date';{lastVisit: '2024-09-20', intervalMonths: 6};'overdue' +d(lastVisit).add(intervalMonths ?? 12, 'month').isBefore(d()) ? 'overdue' : 'up-to-date';{lastVisit: '2024-09-21', intervalMonths: 6};'up-to-date' +d(lastVisit).add(intervalMonths ?? 12, 'month').isBefore(d()) ? 'overdue' : 'up-to-date';{lastVisit: '2023-01-01', intervalMonths: 24};'overdue' +# Dosage by weight +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 20, mgPerKg: 15, dosesPerDay: 4, maxDose: 1000};75 +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 18.5, mgPerKg: 10, dosesPerDay: 3, maxDose: 500};62 +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 90, mgPerKg: 15, dosesPerDay: 1, maxDose: 1000};1000 +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 25, mgPerKg: 10, dosesPerDay: 2, maxDose: 125};125 +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 25, mgPerKg: 10, maxDose: 1000};250 +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 25, mgPerKg: 10, dosesPerDay: 0, maxDose: 1000};!error +min([maxDose, round(weightKg * mgPerKg / (dosesPerDay ?? 1), 0)]);{weightKg: 4.2, mgPerKg: 12.5, dosesPerDay: 3, maxDose: 1000};18 +# Member summaries +`${upper(member.last)}, ${member.first} (${member.id}) - ${len(filter(claims, #.status == 'denied'))} denied, $${string(sum(map(claims, #.paid ?? 0)))} paid`;{member: {first: 'Ana', last: 'Pérez', id: 'M001'}, claims: [{status: 'paid', paid: 120.50}, {status: 'denied'}]};'PÉREZ, Ana (M001) - 1 denied, $120.50 paid' +`${upper(member.last)}, ${member.first} (${member.id}) - ${len(filter(claims, #.status == 'denied'))} denied, $${string(sum(map(claims, #.paid ?? 0)))} paid`;{member: {first: 'Øyvind', last: 'Å', id: 42}, claims: []};'Å, Øyvind (42) - 0 denied, $0 paid' +`${upper(member.last)}, ${member.first} (${member.id}) - ${len(filter(claims, #.status == 'denied'))} denied, $${string(sum(map(claims, #.paid ?? 0)))} paid`;{member: {first: 'x', last: null, id: 1}, claims: []};!error +`${upper(member.last)}, ${member.first} (${member.id}) - ${len(filter(claims, #.status == 'denied'))} denied, $${string(sum(map(claims, #.paid ?? 0)))} paid`;{member: {first: 'Kim', last: 'Lee', id: 'M9'}, claims: [{status: 'paid', paid: 10.10}, {status: 'paid', paid: 0.90}]};'LEE, Kim (M9) - 0 denied, $11.00 paid' diff --git a/core/expression/tests/spec/standard/12-insurance.csv b/core/expression/tests/spec/standard/12-insurance.csv new file mode 100644 index 00000000..d9c78377 --- /dev/null +++ b/core/expression/tests/spec/standard/12-insurance.csv @@ -0,0 +1,209 @@ +expression (string);input (json 5);output (json 5);note +# Motor: age-banded base premium +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: 18};1177.98 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: 24};1177.98 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: 25};812.40 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: 64};812.40 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: 65};1056.12 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 1234.57, age: 99};1604.94 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 0, age: 30};0.0 +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: null};!error +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40};!error +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: 812.40, age: '30'};!error +round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2);{basePremium: null, age: 30};!error +string(round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2));{basePremium: 812.40, age: 18};'1177.98' +string(round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2));{basePremium: 812.40, age: 40};'812.40' +string(round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2));{basePremium: 812.4, age: 40};'812.40' +string(round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2));{basePremium: 999.99, age: 70};'1299.99' +string(round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2));{basePremium: 100, age: 70};'130.0' +string(round(basePremium * (age < 25 ? 1.45 : age < 65 ? 1.0 : 1.3), 2));{basePremium: 0.01, age: 20};'0.01' +# Motor: claims loading and multi-policy discount +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, claims: 0, multiPolicy: false};600.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, claims: 1, multiPolicy: false};690.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, claims: 2, multiPolicy: true};702.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, multiPolicy: true};540.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600};600.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 733.33, claims: 3, multiPolicy: true};957.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, claims: null, multiPolicy: null};600.00 +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, claims: '1'};!error +round(base * (1 + 0.15 * (claims ?? 0)) * (1 - (multiPolicy ?? false ? 0.1 : 0)), 2);{base: 600, claims: 1, multiPolicy: 'yes'};!error +# Motor: deductible by vehicle class +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'SUV', value: 20000}};1000 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'Truck'}};1000 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'Sedan', value: 50000}};500 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'Sedan', value: 50000.01}};750 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'suv', value: 10}};500 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'Coupe'}};500 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: null};500 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{};500 +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: {type: 'Sedan', value: '90000'}};!error +vehicle.type in ['SUV', 'Truck'] ? 1000 : (vehicle.value ?? 0) > 50000 ? 750 : 500;{vehicle: 'SUV'};500 +# Underwriting decision objects +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 780, claims: 0};{decision: 'approve', loading: 0} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 700, claims: 0};{decision: 'approve', loading: 0} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 700, claims: 1};{decision: 'refer', loading: 0} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 699, claims: 0};{decision: 'refer', loading: 0} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 650, claims: 2};{decision: 'refer', loading: 0} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 649, claims: 0};{decision: 'refer', loading: 0.25} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 600, claims: 0};{decision: 'refer', loading: 0.25} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 599.99, claims: 0};{decision: 'decline', loading: 0.25} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: 720};{decision: 'refer', loading: 0} +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{score: null, claims: 0};!error +{decision: score >= 700 and claims == 0 ? 'approve' : score >= 600 ? 'refer' : 'decline', loading: score < 650 ? 0.25 : 0};{claims: 0};!error +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 750, claims: 0, hasDui: false};'standard' +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 750};'standard' +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 750, hasDui: true};'declined' +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 640, hasDui: false};'substandard' +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 640, claims: 0};!error +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 750, claims: 1, hasDui: false};'substandard' +score >= 700 and (claims ?? 0) == 0 and not (hasDui ?? false) ? 'standard' : hasDui ? 'declined' : 'substandard';{score: 750, claims: 0, hasDui: 'no'};!error +# Homeowners: rate per thousand with flood zone surcharge +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 350000, rate: 3.25, floodZone: 'X', hasPool: false};1137.50 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 350000, rate: 3.25, floodZone: 'AE', hasPool: true};2122.50 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 412500, rate: 2.875, floodZone: 'V', hasPool: false};2134.69 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 412500, rate: 2.875, floodZone: 'VE', hasPool: true};2209.69 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 0, rate: 3, floodZone: 'A', hasPool: true};75.0 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 250000, rate: 3.1, floodZone: null, hasPool: false};775.0 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 250000, rate: 3.1, floodZone: 'ae', hasPool: false};775.0 +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 250000, rate: 3.1, floodZone: 'X'};!error +round(dwelling * rate / 1000 * (floodZone in ['A', 'AE', 'V', 'VE'] ? 1.8 : 1) + (hasPool ? 75 : 0), 2);{dwelling: 1234567, rate: 1.111, floodZone: 'X', hasPool: false};1371.60 +# Life: BMI and build class +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 80, heightCm: 175};26.1 +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 50, heightCm: 160};19.5 +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 100, heightCm: 200};25 +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 72.5, heightCm: 180};22.4 +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 120, heightCm: 165};44.1 +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 80, heightCm: 0};!error +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: 80};!error +round(weightKg / (heightCm / 100) ^ 2, 1);{weightKg: '80', heightCm: 175};!error +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 22};'normal' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 18.5};'normal' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 18.49};'under' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 25};'over' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 24.99};'normal' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 29.9};'over' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 30};'obese' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 45.2};'obese' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: 0};'under' +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: null};!error +bmi in [18.5..25) ? 'normal' : bmi < 18.5 ? 'under' : bmi in [25..30) ? 'over' : 'obese';{bmi: '22'};!error +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 30, smoker: false, faceAmount: 500000};60.00 +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 45, smoker: true, faceAmount: 250000};66.000 +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 46, smoker: false, faceAmount: 250000};48.000 +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 60, smoker: true, faceAmount: 100000};42.2400 +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 61, smoker: false, faceAmount: 100000};34.800 +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 17, smoker: false, faceAmount: 100000};34.800 +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 30, smoker: null, faceAmount: 100000};!error +(age in [18..45] ? 1 : age in (45..60] ? 1.6 : 2.9) * (smoker ? 2.2 : 1) * faceAmount / 1000 * 0.12;{age: 30, smoker: false};!error +# Claims: loss ratio over paid claims +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 1200, claims: [{status: 'paid', amount: 300}, {status: 'denied', amount: 5000}, {status: 'paid', amount: 150.50}]};37.54 +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 1200, claims: []};0 +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 999.99, claims: [{status: 'paid', amount: 333.33}]};33.33 +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 0, claims: [{status: 'paid', amount: 1}]};!error +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 800, claims: [{status: 'PAID', amount: 100}, {status: 'open', amount: 50}]};0 +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 800, claims: [{status: 'paid', amount: null}]};!error +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 800, claims: null};!error +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 800};!error +round(sum(map(filter(claims, #.status == 'paid'), #.amount)) / premium * 100, 2);{premium: 3000, claims: [{status: 'paid', amount: 1000}, {status: 'paid', amount: 1000}, {status: 'paid', amount: 1000}, {status: 'paid', amount: 0.01}]};100.00 +{paid: count(claims, #.status == 'paid'), open: count(claims, #.status == 'open'), reserve: sum(map(filter(claims, #.status == 'open'), #.reserve ?? 0))};{claims: [{status: 'open', reserve: 1500}, {status: 'paid'}, {status: 'open'}, {status: 'open', reserve: 250.25}]};{paid: 1, open: 3, reserve: 1750.25} +{paid: count(claims, #.status == 'paid'), open: count(claims, #.status == 'open'), reserve: sum(map(filter(claims, #.status == 'open'), #.reserve ?? 0))};{claims: []};{paid: 0, open: 0, reserve: 0} +{paid: count(claims, #.status == 'paid'), open: count(claims, #.status == 'open'), reserve: sum(map(filter(claims, #.status == 'open'), #.reserve ?? 0))};{claims: [{status: 'paid'}, {status: 'paid'}]};{paid: 2, open: 0, reserve: 0} +{paid: count(claims, #.status == 'paid'), open: count(claims, #.status == 'open'), reserve: sum(map(filter(claims, #.status == 'open'), #.reserve ?? 0))};{claims: [{status: 'open', reserve: '100'}]};!error +{paid: count(claims, #.status == 'paid'), open: count(claims, #.status == 'open'), reserve: sum(map(filter(claims, #.status == 'open'), #.reserve ?? 0))};{claims: [{}, {status: null}]};{paid: 0, open: 0, reserve: 0} +{paid: count(claims, #.status == 'paid'), open: count(claims, #.status == 'open'), reserve: sum(map(filter(claims, #.status == 'open'), #.reserve ?? 0))};{claims: {status: 'open'}};!error +map(claims, max([0, #.amount - deductible]));{deductible: 500, claims: [{amount: 1200}, {amount: 499.99}, {amount: 500}, {amount: 500.01}]};[700, 0, 0, 0.01] +map(claims, max([0, #.amount - deductible]));{deductible: 0, claims: [{amount: 10}]};[10] +map(claims, max([0, #.amount - deductible]));{deductible: 250, claims: []};[] +map(claims, max([0, #.amount - deductible]));{deductible: null, claims: [{amount: 10}]};!error +map(claims, max([0, #.amount - deductible]));{deductible: 100, claims: [{amount: 50}, {}]};!error +map(claims, max([0, #.amount - deductible]));{deductible: 1000, claims: [{amount: 2500.75}, {amount: 1000}, {amount: 0}]};[1500.75, 0, 0] +sum(map(claims, min([#.amount, perClaimLimit]))) > aggregateLimit ? aggregateLimit : sum(map(claims, min([#.amount, perClaimLimit])));{perClaimLimit: 10000, aggregateLimit: 25000, claims: [{amount: 12000}, {amount: 8000}, {amount: 3000}]};21000 +sum(map(claims, min([#.amount, perClaimLimit]))) > aggregateLimit ? aggregateLimit : sum(map(claims, min([#.amount, perClaimLimit])));{perClaimLimit: 10000, aggregateLimit: 25000, claims: [{amount: 12000}, {amount: 12000}, {amount: 12000}]};25000 +sum(map(claims, min([#.amount, perClaimLimit]))) > aggregateLimit ? aggregateLimit : sum(map(claims, min([#.amount, perClaimLimit])));{perClaimLimit: 10000, aggregateLimit: 25000, claims: [{amount: 10000}, {amount: 10000}, {amount: 5000}]};25000 +sum(map(claims, min([#.amount, perClaimLimit]))) > aggregateLimit ? aggregateLimit : sum(map(claims, min([#.amount, perClaimLimit])));{perClaimLimit: 10000, aggregateLimit: 25000, claims: []};0 +sum(map(claims, min([#.amount, perClaimLimit]))) > aggregateLimit ? aggregateLimit : sum(map(claims, min([#.amount, perClaimLimit])));{perClaimLimit: 5000.50, aggregateLimit: 9999.99, claims: [{amount: 5000.49}, {amount: 5000.51}]};9999.99 +sum(map(claims, min([#.amount, perClaimLimit]))) > aggregateLimit ? aggregateLimit : sum(map(claims, min([#.amount, perClaimLimit])));{perClaimLimit: 10000, aggregateLimit: 25000, claims: [{amount: null}]};!error +# No-claims discount and installment plans +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: 0};950.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: 1};855.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: 4};570.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: 5};475.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: 12};475.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950};950.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: null};950.0 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 777.77, ncdYears: 3};544.44 +round(base * (1 - min([ncdYears ?? 0, 5]) * 0.1), 2);{base: 950, ncdYears: 'five'};!error +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 1200, plan: 'monthly'};102.5 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 1000, plan: 'monthly'};85.83 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 1000, plan: 'quarterly'};250 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 1000, plan: 'annual'};1000 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 1000};1000 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 999.99, plan: 'monthly'};85.83 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: 0.10, plan: 'quarterly'};0.03 +round(annual / (plan == 'monthly' ? 12 : plan == 'quarterly' ? 4 : 1) + (plan == 'monthly' ? 2.5 : 0), 2);{annual: null, plan: 'monthly'};!error +# Policy dates: age at inception, renewal and pro-rata refunds +d(effective).diff(d(birthDate), 'year');{effective: '2025-01-01', birthDate: '1990-06-15'};34 +d(effective).diff(d(birthDate), 'year');{effective: '2025-06-15', birthDate: '1990-06-15'};35 +d(effective).diff(d(birthDate), 'year');{effective: '2025-06-14', birthDate: '1990-06-15'};34 +d(effective).diff(d(birthDate), 'year');{effective: '2024-02-29', birthDate: '2000-02-29'};24 +d(effective).diff(d(birthDate), 'year');{effective: '2025-02-28', birthDate: '2000-02-29'};25 +d(effective).diff(d(birthDate), 'year');{effective: '2025-03-01', birthDate: '2000-02-29'};25 +d(effective).diff(d(birthDate), 'year');{effective: '2025-01-01', birthDate: 'unknown'};null +d(effective).diff(d(birthDate), 'year');{effective: '2025-01-01'};null +d(effective).diff(d(birthDate), 'year');{effective: '2000-01-01', birthDate: '2010-01-01'};-10 +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{dob: '2000-03-20'};'standard' +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{dob: '2000-03-21'};'young-driver' +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{dob: '1970-12-31'};'standard' +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{dob: '2007-01-01'};'young-driver' +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{dob: '2000-02-29'};'standard' +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{dob: 'n/a'};!error +d().diff(d(dob), 'year') >= 25 ? 'standard' : 'young-driver';{};!error +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2025-01-01'};'2025-12-31' +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2025-03-20'};'2026-03-19' +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2024-12-31'};'2025-12-30' +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2023-03-01'};'2024-02-29' +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2024-03-01'};'2025-02-28' +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2024-02-29'};'2025-02-27';bug: adding a year to Feb 29 gives an invalid date instead of clamping +d(start).add(1, 'year').add(-1, 'day').format('%Y-%m-%d');{start: '2025-13-01'};'Invalid date' +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 1200, start: '2025-01-01', end: '2026-01-01', cancel: '2025-07-02'};601.64 +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 1200, start: '2024-01-01', end: '2025-01-01', cancel: '2024-07-02'};600 +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 1000, start: '2025-01-01', end: '2026-01-01', cancel: '2025-01-01'};1000 +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 1000, start: '2025-01-01', end: '2026-01-01', cancel: '2026-01-01'};0 +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 365, start: '2025-01-01', end: '2026-01-01', cancel: '2025-12-31'};1 +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 500, start: '2025-01-01', end: '2025-01-01', cancel: '2025-01-01'};!error +round(premium * d(end).diff(d(cancel), 'day') / d(end).diff(d(start), 'day'), 2);{premium: 1000, start: '2025-01-01', end: '2026-01-01', cancel: 'never'};!error +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-04-01'};'send-reminder' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-04-19'};'send-reminder' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-04-20'};'send-reminder' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-04-19 10:15:30'};'send-reminder' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-04-19 10:15:31'};'send-reminder' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-03-20'};'wait' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2025-03-21'};'send-reminder' +d(renewal).diff(d(), 'day') <= 30 and d(renewal) > d() ? 'send-reminder' : 'wait';{renewal: '2024-12-31'};'wait' +# Quote summaries as templates +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: 'P-1001', name: 'Ana Silva', premium: 812.4, currency: 'EUR'};'Policy P-1001 for ANA SILVA: 812.4 EUR' +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: 'P-1002', name: 'Jürgen Groß', premium: 1000, currency: 'EUR'};'Policy P-1002 for JÜRGEN GROSS: 1000 EUR' +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: 'P-1003', name: 'li wei', premium: 99.999};'Policy P-1003 for LI WEI: 100.00 USD' +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: 1004, name: 'o\'brien', premium: 12.345, currency: null};'Policy 1004 for O\'BRIEN: 12.35 USD' +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: null, name: 'x', premium: 0.005};'Policy null for X: 0.01 USD' +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: 'P-1', name: null, premium: 1};!error +`Policy ${policyNo} for ${upper(name)}: ${string(round(premium, 2))} ${currency ?? 'USD'}`;{policyNo: 'P-1', name: 'x'};!error +`${count(drivers, #.age < 25)} young of ${len(drivers)} drivers, oldest ${max(map(drivers, #.age))}`;{drivers: [{age: 19}, {age: 45}, {age: 24}]};'2 young of 3 drivers, oldest 45' +`${count(drivers, #.age < 25)} young of ${len(drivers)} drivers, oldest ${max(map(drivers, #.age))}`;{drivers: [{age: 25}]};'0 young of 1 drivers, oldest 25' +`${count(drivers, #.age < 25)} young of ${len(drivers)} drivers, oldest ${max(map(drivers, #.age))}`;{drivers: []};!error +`${count(drivers, #.age < 25)} young of ${len(drivers)} drivers, oldest ${max(map(drivers, #.age))}`;{drivers: [{age: 30}, {age: null}]};!error +`${count(drivers, #.age < 25)} young of ${len(drivers)} drivers, oldest ${max(map(drivers, #.age))}`;{drivers: [{age: 70}, {age: 71}, {age: 22}, {age: 23}, {age: 18}]};'3 young of 5 drivers, oldest 71' +# Fleet eligibility over driver lists +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: [{age: 30, licenseYears: 10, points: 0}, {age: 21, licenseYears: 2, points: 6}]};true +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: [{age: 20, licenseYears: 3, points: 0}]};false +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: [{age: 40, licenseYears: 1, points: 0}]};false +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: [{age: 40, licenseYears: 20, points: 7}]};false +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: []};true +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: [{age: 40, licenseYears: 20}]};!error +all(drivers, #.age >= 21 and #.licenseYears >= 2) and none(drivers, #.points > 6);{drivers: [{age: 18, licenseYears: 0, points: 12}, {age: 50}]};false +round(sum(map(vehicles, #.value * (#.age > 10 ? 0.02 : 0.035))) * (len(vehicles) >= 5 ? 0.9 : 1), 2);{vehicles: [{value: 20000, age: 3}, {value: 8000, age: 12}]};860.00 +round(sum(map(vehicles, #.value * (#.age > 10 ? 0.02 : 0.035))) * (len(vehicles) >= 5 ? 0.9 : 1), 2);{vehicles: [{value: 20000, age: 10}, {value: 20000, age: 11}, {value: 15000, age: 1}, {value: 15000, age: 2}, {value: 33333.33, age: 0}]};2985.00 +round(sum(map(vehicles, #.value * (#.age > 10 ? 0.02 : 0.035))) * (len(vehicles) >= 5 ? 0.9 : 1), 2);{vehicles: []};0 +round(sum(map(vehicles, #.value * (#.age > 10 ? 0.02 : 0.035))) * (len(vehicles) >= 5 ? 0.9 : 1), 2);{vehicles: [{value: 10000}]};!error +round(sum(map(vehicles, #.value * (#.age > 10 ? 0.02 : 0.035))) * (len(vehicles) >= 5 ? 0.9 : 1), 2);{vehicles: [{value: null, age: 1}]};!error +round(sum(map(vehicles, #.value * (#.age > 10 ? 0.02 : 0.035))) * (len(vehicles) >= 5 ? 0.9 : 1), 2);{vehicles: [{value: 12345.67, age: 4}, {value: 7654.32, age: 15}, {value: 1, age: 1}, {value: 2, age: 2}]};585.29 diff --git a/core/expression/tests/spec/standard/12-kyc.csv b/core/expression/tests/spec/standard/12-kyc.csv new file mode 100644 index 00000000..64f84a2d --- /dev/null +++ b/core/expression/tests/spec/standard/12-kyc.csv @@ -0,0 +1,138 @@ +expression (string);input (json 5);output (json 5);note +# Name validation +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: 'Ana'};true +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: ' Zoë Ødegaard '};true +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: 'Jean-Luc Picard'};true +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: 'R2D2'};false +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: 'J. R. R. Tolkien'};true +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: 'Ö'};false;bug: len counts UTF-8 bytes instead of characters +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: '山田太郎'};true +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: 'Anna_Maria'};false +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: ''};false +len(trim(name)) >= 2 and matches(trim(name), '^[\p{L} .-]+$');{name: null};!error +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'Ana'};true +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: ' Li '};true +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'X'};false +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'Ö'};false;bug: len counts UTF-8 bytes instead of characters +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'O\'Brien-Smith'};true +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'R2D2'};false +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'user_1'};false +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: ' '};false +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 'Nguyễn Văn A'};true +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: null};!error +len(trim(name)) >= 2 and not matches(name, '[0-9_@#$%]');{name: 42};!error +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: 'Jo'};'too-short' +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: 'Joe'};'ok' +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'};'ok' +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'};'too-long' +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: '李明'};'too-short';bug: len counts UTF-8 bytes instead of characters +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: 'éééééééééééééééééééééééééééééééééééééééé'};'ok';bug: len counts UTF-8 bytes instead of characters +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: ''};'too-short' +len(fullName) > 70 ? 'too-long' : len(fullName) < 3 ? 'too-short' : 'ok';{fullName: null};!error +map(split(trim(fullName), ' '), upper(#[0]));{fullName: 'mary jane watson'};['M', 'J', 'W'] +map(split(trim(fullName), ' '), upper(#[0]));{fullName: ' Ada Lovelace '};['A', 'L'] +map(split(trim(fullName), ' '), upper(#[0]));{fullName: 'Prince'};['P'] +map(split(trim(fullName), ' '), upper(#[0]));{fullName: 'élodie durand'};['É', 'D'];bug: string indexing uses UTF-8 byte offsets instead of characters +map(split(trim(fullName), ' '), upper(#[0]));{fullName: 'a b'};!error +map(split(trim(fullName), ' '), upper(#[0]));{fullName: ''};!error +# Email and phone formats +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: 'jane.doe@example.com'};true +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: ' JANE@EXAMPLE.CO.UK '};true +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: 'jane@localhost'};false +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: 'jane@@example.com'};false +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: 'a+tag@sub.example.io'};true +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: 'jane doe@example.com'};false +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: '@example.com'};false +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: 'x@y.z'};false +matches(lower(trim(email)), '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$');{email: null};!error +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '+14155552671'};'e164' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '+4915112345678'};'e164' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '+0123456789'};'needs-normalizing' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '(415) 555-2671'};'needs-normalizing' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '555-2671'};'needs-normalizing' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '555-26'};'invalid' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '+1 415 555 2671'};'needs-normalizing' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: 'call me'};'invalid' +matches(phone, '^\+[1-9][0-9]{7,14}$') ? 'e164' : matches(phone, '^[0-9 ()+-]{7,20}$') ? 'needs-normalizing' : 'invalid';{phone: '+1234567890123456'};'needs-normalizing' +# Age and document validity +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: '2007-03-20', country: 'DE'};true +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: '2007-03-21', country: 'DE'};false +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: '2004-03-20', country: 'US'};true +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: '2004-03-21', country: 'US'};false +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: '2007-02-28', country: 'GB'};true +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: '1950-01-01'};true +d().diff(d(dob), 'year') >= (country == 'US' ? 21 : 18);{dob: 'n/a', country: 'DE'};!error +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2030-01-01'};'valid' +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2025-06-20 10:15:31'};'valid' +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2025-06-20 10:15:30'};'expiring-soon' +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2025-06-20'};'expiring-soon' +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2025-03-20 10:15:31'};'expiring-soon' +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2025-03-20'};'expired' +d(expiresOn) > d().add(3, 'month') ? 'valid' : d(expiresOn) > d() ? 'expiring-soon' : 'expired';{expiresOn: '2020-12-31'};'expired' +{age: d(asOf).diff(d(dob), 'year'), adult: d(asOf).diff(d(dob), 'year') >= 18, birthday: d(dob).format('%d.%m.')};{dob: '2000-02-29', asOf: '2018-02-28'};{age: 18, adult: true, birthday: '29.02.'} +{age: d(asOf).diff(d(dob), 'year'), adult: d(asOf).diff(d(dob), 'year') >= 18, birthday: d(dob).format('%d.%m.')};{dob: '2000-02-29', asOf: '2018-03-01'};{age: 18, adult: true, birthday: '29.02.'} +{age: d(asOf).diff(d(dob), 'year'), adult: d(asOf).diff(d(dob), 'year') >= 18, birthday: d(dob).format('%d.%m.')};{dob: '1999-12-31', asOf: '2017-12-31'};{age: 18, adult: true, birthday: '31.12.'} +{age: d(asOf).diff(d(dob), 'year'), adult: d(asOf).diff(d(dob), 'year') >= 18, birthday: d(dob).format('%d.%m.')};{dob: '1999-12-31', asOf: '2017-12-30'};{age: 17, adult: false, birthday: '31.12.'} +{age: d(asOf).diff(d(dob), 'year'), adult: d(asOf).diff(d(dob), 'year') >= 18, birthday: d(dob).format('%d.%m.')};{dob: '2010-06-15', asOf: '2025-03-20'};{age: 14, adult: false, birthday: '15.06.'} +# Masking identifiers +'***-**-' + ssn[len(ssn) - 4:];{ssn: '123-45-6789'};'***-**-6789' +'***-**-' + ssn[len(ssn) - 4:];{ssn: '123456789'};'***-**-6789' +'***-**-' + ssn[len(ssn) - 4:];{ssn: '6789'};'***-**-6789' +'***-**-' + ssn[len(ssn) - 4:];{ssn: null};!error +'**** **** **** ' + card[len(card) - 4:];{card: '4111111111111111'};'**** **** **** 1111' +'**** **** **** ' + card[len(card) - 4:];{card: '378282246310005'};'**** **** **** 0005' +'**** **** **** ' + card[len(card) - 4:];{card: '5555555555554444'};'**** **** **** 4444' +'**** **** **** ' + card[len(card) - 4:];{card: '1234'};'**** **** **** 1234' +`${upper(email[0])}***@${split(email, '@')[1]}`;{email: 'jane.doe@example.com'};'J***@example.com' +`${upper(email[0])}***@${split(email, '@')[1]}`;{email: 'x@y.io'};'X***@y.io' +`${upper(email[0])}***@${split(email, '@')[1]}`;{email: 'no-at'};'N***@null' +`${upper(email[0])}***@${split(email, '@')[1]}`;{email: 'élise@exemple.fr'};'É***@exemple.fr';bug: string indexing uses UTF-8 byte offsets instead of characters +# Luhn checksum over card numbers +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '4111111111111111'};true +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '4111111111111112'};false +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '79927398713'};true +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '79927398710'};false +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '378282246310005'};true +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '6011111111111117'};true +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '0'};true +sum(map([0..len(s)), # % 2 == 1 ? (number(s[len(s) - 1 - #]) * 2 > 9 ? number(s[len(s) - 1 - #]) * 2 - 9 : number(s[len(s) - 1 - #]) * 2) : number(s[len(s) - 1 - #]))) % 10 == 0;{s: '4111-1111'};!error +# IBAN shape checks +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: 'DE89370400440532013000'};true +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: ' de89370400440532013000 '};true +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: 'DE8937040044053201300'};false +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: 'NL91ABNA0417164300'};true +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: 'GB29NWBK60161331926819'};true +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: 'XX29NWBK60161331926819'};false +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: 'DE89 3704 0044 0532 0130 00'};false +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: ''};false +"s = upper(trim(iban)); parts = extract(s, '^([A-Z]{2})[0-9]{2}[A-Z0-9]+$'); len(parts) == 2 and len(s) == ({DE: 22, FR: 27, GB: 22, NL: 18, ES: 24})[parts[1]]";{iban: null};!error +# Address completeness with dynamic keys +filter(['line1', 'city', 'postcode', 'country'], trim(address[#] ?? '') == '');{address: {line1: '1 Main St', city: 'Springfield', postcode: '12345', country: 'US'}};[] +filter(['line1', 'city', 'postcode', 'country'], trim(address[#] ?? '') == '');{address: {line1: '1 Main St', city: ' ', country: 'US'}};['city', 'postcode'] +filter(['line1', 'city', 'postcode', 'country'], trim(address[#] ?? '') == '');{address: {}};['line1', 'city', 'postcode', 'country'] +filter(['line1', 'city', 'postcode', 'country'], trim(address[#] ?? '') == '');{address: null};['line1', 'city', 'postcode', 'country'] +filter(['line1', 'city', 'postcode', 'country'], trim(address[#] ?? '') == '');{address: {line1: 'x', city: 'y', postcode: 12345, country: 'US'}};!error +all(['line1', 'city', 'country'], (address[#] ?? '') != '') and (country in ['US', 'CA'] ? matches(address.postcode ?? '', '^[0-9A-Z -]{5,7}$') : true);{country: 'US', address: {line1: 'a', city: 'b', country: 'US', postcode: '94105'}};true +all(['line1', 'city', 'country'], (address[#] ?? '') != '') and (country in ['US', 'CA'] ? matches(address.postcode ?? '', '^[0-9A-Z -]{5,7}$') : true);{country: 'US', address: {line1: 'a', city: 'b', country: 'US'}};false +all(['line1', 'city', 'country'], (address[#] ?? '') != '') and (country in ['US', 'CA'] ? matches(address.postcode ?? '', '^[0-9A-Z -]{5,7}$') : true);{country: 'CA', address: {line1: 'a', city: 'b', country: 'CA', postcode: 'K1A 0B1'}};true +all(['line1', 'city', 'country'], (address[#] ?? '') != '') and (country in ['US', 'CA'] ? matches(address.postcode ?? '', '^[0-9A-Z -]{5,7}$') : true);{country: 'FR', address: {line1: 'a', city: 'b', country: 'FR'}};true +all(['line1', 'city', 'country'], (address[#] ?? '') != '') and (country in ['US', 'CA'] ? matches(address.postcode ?? '', '^[0-9A-Z -]{5,7}$') : true);{country: 'FR', address: {line1: 'a', country: 'FR'}};false +all(['line1', 'city', 'country'], (address[#] ?? '') != '') and (country in ['US', 'CA'] ? matches(address.postcode ?? '', '^[0-9A-Z -]{5,7}$') : true);{country: 'US', address: {line1: 'a', city: 'b', country: 'US', postcode: '9410'}};false +# Screening outcome objects +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: 'DE'};{status: 'clear', hits: []} +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: 'DE', pep: true};{status: 'enhanced-due-diligence', hits: ['pep']} +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: 'IR'};{status: 'enhanced-due-diligence', hits: ['country']} +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: 'US', sanctionsHit: true, pep: true};{status: 'reject', hits: ['sanctions', 'pep']} +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: 'KP', sanctionsHit: false, pep: false};{status: 'enhanced-due-diligence', hits: ['country']} +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: null, pep: null};{status: 'clear', hits: []} +"hits = filter(['sanctions', 'pep', 'country'], # == 'sanctions' ? sanctionsHit ?? false : # == 'pep' ? pep ?? false : country in ['IR', 'KP', 'SY', 'CU']); {status: len(hits) == 0 ? 'clear' : contains(hits, 'sanctions') ? 'reject' : 'enhanced-due-diligence', hits: hits}";{country: 'DE', pep: 'yes'};!error +`KYC ${upper(level)}: ${first} ${upper(last)}, born ${d(dob).format('%Y-%m-%d')}, ${len(docs)} document(s)`;{level: 'basic', first: 'Sam', last: 'Hill', dob: '1990-01-02', docs: ['passport']};'KYC BASIC: Sam HILL, born 1990-01-02, 1 document(s)' +`KYC ${upper(level)}: ${first} ${upper(last)}, born ${d(dob).format('%Y-%m-%d')}, ${len(docs)} document(s)`;{level: 'full', first: 'Łucja', last: 'Wąs', dob: '1985-12-31', docs: []};'KYC FULL: Łucja WĄS, born 1985-12-31, 0 document(s)' +`KYC ${upper(level)}: ${first} ${upper(last)}, born ${d(dob).format('%Y-%m-%d')}, ${len(docs)} document(s)`;{level: 'full', first: 'A', last: 'B', dob: 'x', docs: []};'KYC FULL: A B, born Invalid date, 0 document(s)' +`KYC ${upper(level)}: ${first} ${upper(last)}, born ${d(dob).format('%Y-%m-%d')}, ${len(docs)} document(s)`;{level: null, first: 'A', last: 'B', dob: '1990-01-01', docs: []};!error +lower(trim(a.first)) == lower(trim(b.first)) and lower(trim(a.last)) == lower(trim(b.last)) and a.dob == b.dob;{a: {first: 'John', last: 'Smith', dob: '1980-01-01'}, b: {first: 'JOHN ', last: 'smith', dob: '1980-01-01'}};true +lower(trim(a.first)) == lower(trim(b.first)) and lower(trim(a.last)) == lower(trim(b.last)) and a.dob == b.dob;{a: {first: 'John', last: 'Smith', dob: '1980-01-01'}, b: {first: 'Jon', last: 'Smith', dob: '1980-01-01'}};false +lower(trim(a.first)) == lower(trim(b.first)) and lower(trim(a.last)) == lower(trim(b.last)) and a.dob == b.dob;{a: {first: 'John', last: 'Smith', dob: '1980-01-01'}, b: {first: 'John', last: 'Smith', dob: '1980-01-02'}};false +lower(trim(a.first)) == lower(trim(b.first)) and lower(trim(a.last)) == lower(trim(b.last)) and a.dob == b.dob;{a: {first: 'ÉMILE', last: 'ZOLA', dob: '1840-04-02'}, b: {first: 'émile', last: 'zola', dob: '1840-04-02'}};true +lower(trim(a.first)) == lower(trim(b.first)) and lower(trim(a.last)) == lower(trim(b.last)) and a.dob == b.dob;{a: {first: 'x', last: 'y'}, b: {first: 'x', last: 'y'}};true +lower(trim(a.first)) == lower(trim(b.first)) and lower(trim(a.last)) == lower(trim(b.last)) and a.dob == b.dob;{a: {first: 'x', last: null}, b: {first: 'x', last: 'y'}};!error diff --git a/core/expression/tests/spec/standard/12-lending.csv b/core/expression/tests/spec/standard/12-lending.csv new file mode 100644 index 00000000..2510e7ba --- /dev/null +++ b/core/expression/tests/spec/standard/12-lending.csv @@ -0,0 +1,149 @@ +expression (string);input (json 5);output (json 5);note +# Debt-to-income ratio +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 1800, annualIncome: 96000, debts: [{monthly: 350}, {monthly: 120.50}]};28.38 +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 0, annualIncome: 60000, debts: []};0 +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 2150.75, annualIncome: 120000, debts: [{monthly: 499.25}]};26.50 +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 1500, annualIncome: 0, debts: []};!error +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 1500, annualIncome: 72000, debts: [{monthly: null}]};!error +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 1500, annualIncome: 72000, debts: null};!error +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: null, annualIncome: 72000, debts: []};!error +round((mortgage + sum(map(debts, #.monthly))) / (annualIncome / 12) * 100, 2);{mortgage: 1000, annualIncome: 36000, debts: [{monthly: 100}, {monthly: 100}, {monthly: 100}, {monthly: 100}, {monthly: 100}, {monthly: 100}, {monthly: 100}, {monthly: 100}]};60.0 +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 120000, housing: 2500, debts: [{monthly: 800}]};{eligible: true, dti: 0.33} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 120000, housing: 3000, debts: [{monthly: 1300}]};{eligible: true, dti: 0.43} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 120000, housing: 3000, debts: [{monthly: 1300.01}]};{eligible: false, dti: 0.4300} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 0, housing: 1000, debts: []};{eligible: false, dti: null} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 50000, debts: [{monthly: 400}, {}]};{eligible: true, dti: 0.0960} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 85000, housing: 1999.99, debts: [{monthly: 250}, {monthly: 75.5}]};{eligible: true, dti: 0.3283} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: 85000, housing: 0, debts: []};{eligible: true, dti: 0} +"income = annualIncome / 12; debt = (housing ?? 0) + sum(map(debts, #.monthly ?? 0)); dti = debt / income; dti == null ? {eligible: false, dti: null} : {eligible: dti <= 0.43, dti: round(dti, 4)}";{annualIncome: null, housing: 0, debts: []};!error +# Credit tier and pricing +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 850};'A+' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 760};'A+' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 759};'A' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 700};'A' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 699};'B' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 640};'B' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 580};'C' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 579};'D' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: 300};'D' +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: null};!error +fico >= 760 ? 'A+' : fico >= 700 ? 'A' : fico >= 640 ? 'B' : fico >= 580 ? 'C' : 'D';{fico: '720'};!error +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'A+', ltv: 60, term: 360};5.99 +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'A', ltv: 80, term: 360};6.49 +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'A', ltv: 80.01, term: 360};6.99 +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'B', ltv: 95, term: 480};8.74 +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'D', ltv: 50, term: 120};14.99 +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'E', ltv: 50, term: 120};!error +({'A+': 5.99, A: 6.49, B: 7.99, C: 10.49, D: 14.99})[tier] + (ltv > 80 ? 0.5 : 0) + (term > 360 ? 0.25 : 0);{tier: 'C', ltv: 90, term: 361};11.24 +# Amortized monthly payment with integer powers +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 200000, rate: 6, months: 360};1199.10 +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 10000, rate: 12, months: 12};888.49 +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 25000, rate: 7.2, months: 60};497.39 +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 1000, rate: 24, months: 1};1020.00 +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 350000, rate: 4.5, months: 180};2677.48 +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 5000, rate: 0, months: 12};!error +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: 5000, rate: 12, months: null};!error +"r = rate / 100 / 12; f = (1 + r) ^ months; round(principal * r * f / (f - 1), 2)";{principal: '5000', rate: 12, months: 12};!error +"r = rate / 100 / 12; rate == 0 ? round(principal / months, 2) : round(principal * r * (1 + r) ^ months / ((1 + r) ^ months - 1), 2)";{principal: 5000, rate: 0, months: 12};416.67 +"r = rate / 100 / 12; rate == 0 ? round(principal / months, 2) : round(principal * r * (1 + r) ^ months / ((1 + r) ^ months - 1), 2)";{principal: 1200, rate: 0, months: 12};100 +"r = rate / 100 / 12; rate == 0 ? round(principal / months, 2) : round(principal * r * (1 + r) ^ months / ((1 + r) ^ months - 1), 2)";{principal: 10000, rate: 12, months: 12};888.49 +"r = rate / 100 / 12; rate == 0 ? round(principal / months, 2) : round(principal * r * (1 + r) ^ months / ((1 + r) ^ months - 1), 2)";{principal: 18500, rate: 3.9, months: 72};288.59 +"r = rate / 100 / 12; rate == 0 ? round(principal / months, 2) : round(principal * r * (1 + r) ^ months / ((1 + r) ^ months - 1), 2)";{principal: 1000, rate: 0, months: 0};!error +"r = rate / 100 / 12; rate == 0 ? round(principal / months, 2) : round(principal * r * (1 + r) ^ months / ((1 + r) ^ months - 1), 2)";{principal: 100, rate: 6, months: 3};33.67 +round(principal * (1 + rate / 100 / 12) ^ months, 2);{principal: 1000, rate: 12, months: 1};1010.00 +round(principal * (1 + rate / 100 / 12) ^ months, 2);{principal: 1000, rate: 12, months: 2};1020.10 +round(principal * (1 + rate / 100 / 12) ^ months, 2);{principal: 1000, rate: 12, months: 12};1126.83 +round(principal * (1 + rate / 100 / 12) ^ months, 2);{principal: 1000, rate: 6, months: 0};1000 +round(principal * (1 + rate / 100 / 12) ^ months, 2);{principal: 2500.50, rate: 4.8, months: 24};2751.92 +round(principal * (1 + rate / 100 / 12) ^ months, 2);{principal: 1000, rate: 12, months: 'x'};!error +# Loan-to-value and PMI +"ltv = loan / min([appraised, price]) * 100; {ltv: round(ltv, 2), pmi: ltv > 80 ? round(loan * 0.0055 / 12, 2) : 0}";{loan: 320000, appraised: 400000, price: 410000};{ltv: 80.0, pmi: 0} +"ltv = loan / min([appraised, price]) * 100; {ltv: round(ltv, 2), pmi: ltv > 80 ? round(loan * 0.0055 / 12, 2) : 0}";{loan: 320001, appraised: 400000, price: 400000};{ltv: 80.00, pmi: 146.67} +"ltv = loan / min([appraised, price]) * 100; {ltv: round(ltv, 2), pmi: ltv > 80 ? round(loan * 0.0055 / 12, 2) : 0}";{loan: 380000, appraised: 400000, price: 395000};{ltv: 96.20, pmi: 174.17} +"ltv = loan / min([appraised, price]) * 100; {ltv: round(ltv, 2), pmi: ltv > 80 ? round(loan * 0.0055 / 12, 2) : 0}";{loan: 100000, appraised: 0, price: 150000};!error +"ltv = loan / min([appraised, price]) * 100; {ltv: round(ltv, 2), pmi: ltv > 80 ? round(loan * 0.0055 / 12, 2) : 0}";{loan: 250000, appraised: null, price: 300000};!error +"ltv = loan / min([appraised, price]) * 100; {ltv: round(ltv, 2), pmi: ltv > 80 ? round(loan * 0.0055 / 12, 2) : 0}";{loan: 0, appraised: 300000, price: 300000};{ltv: 0, pmi: 0} +# Eligibility gates over applicant lists +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 34, income: 55000}, {age: 33, income: 0}]};true +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 17, income: 10000}]};false +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 75, income: 1, bankrupt: false}]};true +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 76, income: 1}]};false +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 40, income: 0}, {age: 41, income: 0}]};false +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 40, income: 90000, bankrupt: true}]};false +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: []};false +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: 40, income: 1000, bankrupt: null}]};true +all(applicants, #.age >= 18 and #.age <= 75) and some(applicants, #.income > 0) and none(applicants, #.bankrupt ?? false);{applicants: [{age: '40', income: 1000}]};!error +sum(map(applicants, #.income ?? 0)) >= loanAmount / 4 and max(map(applicants, #.fico)) >= 620;{loanAmount: 200000, applicants: [{income: 30000, fico: 600}, {income: 20000, fico: 620}]};true +sum(map(applicants, #.income ?? 0)) >= loanAmount / 4 and max(map(applicants, #.fico)) >= 620;{loanAmount: 200000, applicants: [{income: 49999.99, fico: 800}]};false +sum(map(applicants, #.income ?? 0)) >= loanAmount / 4 and max(map(applicants, #.fico)) >= 620;{loanAmount: 200000, applicants: [{fico: 800}, {income: 50000, fico: 500}]};true +sum(map(applicants, #.income ?? 0)) >= loanAmount / 4 and max(map(applicants, #.fico)) >= 620;{loanAmount: 0, applicants: []};!error +sum(map(applicants, #.income ?? 0)) >= loanAmount / 4 and max(map(applicants, #.fico)) >= 620;{loanAmount: 100000, applicants: []};false +sum(map(applicants, #.income ?? 0)) >= loanAmount / 4 and max(map(applicants, #.fico)) >= 620;{loanAmount: 100000, applicants: [{income: 25000, fico: null}]};!error +# Employment and residency checks with dates +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2023-03-20'};true +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2023-03-21'};false +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2024-09-01', priorEmploymentMonths: 18};true +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2024-09-01', priorEmploymentMonths: 17};false +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2025-03-01'};false +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2010-01-31'};true +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: 'last year'};!error +d().diff(d(employedSince), 'month') >= 24 or (priorEmploymentMonths ?? 0) + d().diff(d(employedSince), 'month') >= 24;{employedSince: '2024-09-01', priorEmploymentMonths: '18'};!error +d(maturity).diff(d(origination), 'month');{origination: '2025-01-31', maturity: '2025-02-28'};1 +d(maturity).diff(d(origination), 'month');{origination: '2025-01-31', maturity: '2025-03-30'};1 +d(maturity).diff(d(origination), 'month');{origination: '2025-01-31', maturity: '2025-03-31'};2 +d(maturity).diff(d(origination), 'month');{origination: '2024-02-29', maturity: '2054-02-28'};360 +d(maturity).diff(d(origination), 'month');{origination: '2025-03-20', maturity: '2030-03-19'};59 +d(maturity).diff(d(origination), 'month');{origination: '2025-03-20', maturity: '2030-03-20'};60 +d(maturity).diff(d(origination), 'month');{origination: '2025-03-20', maturity: '2025-03-20'};0 +d(maturity).diff(d(origination), 'month');{origination: '2025-03-20', maturity: null};null +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2025-01-31', n: 1};'2025-01-31' +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2025-01-31', n: 2};'2025-02-28' +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2025-01-31', n: 14};'2026-02-28' +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2024-01-31', n: 2};'2024-02-29' +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2025-03-15', n: 360};'2055-02-15' +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2025-12-31', n: 3};'2026-02-28' +d(firstPayment).add(n - 1, 'month').format('%Y-%m-%d');{firstPayment: '2025-01-31', n: null};!error +# Late fees and delinquency buckets +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 1250, dueOn: '2025-03-01', paidOn: '2025-03-01'};0 +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 1250, dueOn: '2025-03-01', paidOn: '2025-03-16'};0 +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 1250, dueOn: '2025-03-01', paidOn: '2025-03-17'};62.50 +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 199.99, dueOn: '2025-03-01', paidOn: '2025-04-01'};15 +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 1250, dueOn: '2025-02-28', paidOn: '2025-02-01'};0 +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 2345.67, dueOn: '2024-12-20', paidOn: '2025-01-10'};117.28 +"days = d(paidOn).diff(d(dueOn), 'day'); days <= 15 ? 0 : round(max([15, installment * 0.05]), 2)";{installment: 1250, dueOn: '2025-03-01'};!error +map(loans, #.dpd <= 0 ? 'current' : #.dpd <= 30 ? '1-30' : #.dpd <= 60 ? '31-60' : #.dpd <= 90 ? '61-90' : 'default');{loans: [{dpd: 0}, {dpd: 1}, {dpd: 30}, {dpd: 31}, {dpd: 60}, {dpd: 61}, {dpd: 90}, {dpd: 91}, {dpd: -5}]};['current', '1-30', '1-30', '31-60', '31-60', '61-90', '61-90', 'default', 'current'] +map(loans, #.dpd <= 0 ? 'current' : #.dpd <= 30 ? '1-30' : #.dpd <= 60 ? '31-60' : #.dpd <= 90 ? '61-90' : 'default');{loans: []};[] +map(loans, #.dpd <= 0 ? 'current' : #.dpd <= 30 ? '1-30' : #.dpd <= 60 ? '31-60' : #.dpd <= 90 ? '61-90' : 'default');{loans: [{dpd: 400}]};['default'] +map(loans, #.dpd <= 0 ? 'current' : #.dpd <= 30 ? '1-30' : #.dpd <= 60 ? '31-60' : #.dpd <= 90 ? '61-90' : 'default');{loans: [{dpd: 15}, {}]};!error +map(loans, #.dpd <= 0 ? 'current' : #.dpd <= 30 ? '1-30' : #.dpd <= 60 ? '31-60' : #.dpd <= 90 ? '61-90' : 'default');{loans: 'none'};!error +count(loans, #.dpd > 90) / len(loans) > 0.05 ? 'watchlist' : 'ok';{loans: [{dpd: 91}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}]};'watchlist' +count(loans, #.dpd > 90) / len(loans) > 0.05 ? 'watchlist' : 'ok';{loans: [{dpd: 91}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}, {dpd: 0}]};'ok' +count(loans, #.dpd > 90) / len(loans) > 0.05 ? 'watchlist' : 'ok';{loans: [{dpd: 91}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}, {dpd: 5}]};'ok' +count(loans, #.dpd > 90) / len(loans) > 0.05 ? 'watchlist' : 'ok';{loans: []};!error +count(loans, #.dpd > 90) / len(loans) > 0.05 ? 'watchlist' : 'ok';{loans: [{dpd: 100}]};'watchlist' +# Credit card minimum payment and interest +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 5000, interest: 82.19, fees: 0};132.19 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 5000, interest: 82.19, fees: 39};171.19 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 1000, interest: 5};25 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 20, interest: 0.3};20 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 0, interest: 0};0 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: -15.50, interest: 0};0 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 2500, interest: 41.095};66.10 +balance <= 0 ? 0 : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2) > balance ? balance : round(max([25, balance * 0.01 + interest + (fees ?? 0)]), 2);{balance: 2500, interest: null};!error +round(balance * apr / 100 / 365 * d(statementEnd).diff(d(statementStart), 'day'), 2);{balance: 3650, apr: 20, statementStart: '2025-01-15', statementEnd: '2025-02-14'};60 +round(balance * apr / 100 / 365 * d(statementEnd).diff(d(statementStart), 'day'), 2);{balance: 1000, apr: 24.99, statementStart: '2025-02-01', statementEnd: '2025-03-01'};19.17 +round(balance * apr / 100 / 365 * d(statementEnd).diff(d(statementStart), 'day'), 2);{balance: 1000, apr: 24.99, statementStart: '2024-02-01', statementEnd: '2024-03-01'};19.86 +round(balance * apr / 100 / 365 * d(statementEnd).diff(d(statementStart), 'day'), 2);{balance: 0, apr: 29.99, statementStart: '2025-01-01', statementEnd: '2025-01-31'};0.00 +round(balance * apr / 100 / 365 * d(statementEnd).diff(d(statementStart), 'day'), 2);{balance: 1000, apr: 18, statementStart: '2025-01-31', statementEnd: '2025-01-01'};-14.79 +round(balance * apr / 100 / 365 * d(statementEnd).diff(d(statementStart), 'day'), 2);{balance: 1000, apr: 18, statementStart: '2025-01-01'};!error +# Decision summaries as templates and objects +`${applicant.lastName}, ${applicant.firstName}: ${fico >= 640 ? 'approved' : 'declined'} at ${string(rate)}% APR`;{applicant: {firstName: 'María', lastName: 'Núñez'}, fico: 700, rate: 6.490};'Núñez, María: approved at 6.490% APR' +`${applicant.lastName}, ${applicant.firstName}: ${fico >= 640 ? 'approved' : 'declined'} at ${string(rate)}% APR`;{applicant: {firstName: 'Bo', lastName: 'Li'}, fico: 639, rate: 14.99};'Li, Bo: declined at 14.99% APR' +`${applicant.lastName}, ${applicant.firstName}: ${fico >= 640 ? 'approved' : 'declined'} at ${string(rate)}% APR`;{applicant: {firstName: 'Zoë'}, fico: 640, rate: 7};'null, Zoë: approved at 7% APR' +`${applicant.lastName}, ${applicant.firstName}: ${fico >= 640 ? 'approved' : 'declined'} at ${string(rate)}% APR`;{applicant: null, fico: 800, rate: 5.25};'null, null: approved at 5.25% APR' +`${applicant.lastName}, ${applicant.firstName}: ${fico >= 640 ? 'approved' : 'declined'} at ${string(rate)}% APR`;{applicant: {firstName: 'A', lastName: 'B'}, fico: null, rate: 5};!error +{approved: fico >= 620 and dti <= 0.45, maxLoan: floor(min([income * 4.5, (collateral ?? 0) * 0.8]) / 1000) * 1000, reasons: filter(['fico', 'dti'], # == 'fico' ? fico < 620 : dti > 0.45)};{fico: 700, dti: 0.30, income: 80000, collateral: 500000};{approved: true, maxLoan: 360000, reasons: []} +{approved: fico >= 620 and dti <= 0.45, maxLoan: floor(min([income * 4.5, (collateral ?? 0) * 0.8]) / 1000) * 1000, reasons: filter(['fico', 'dti'], # == 'fico' ? fico < 620 : dti > 0.45)};{fico: 610, dti: 0.46, income: 80000, collateral: 300000};{approved: false, maxLoan: 240000, reasons: ['fico', 'dti']} +{approved: fico >= 620 and dti <= 0.45, maxLoan: floor(min([income * 4.5, (collateral ?? 0) * 0.8]) / 1000) * 1000, reasons: filter(['fico', 'dti'], # == 'fico' ? fico < 620 : dti > 0.45)};{fico: 620, dti: 0.45, income: 55555, collateral: 1000000};{approved: true, maxLoan: 249000, reasons: []} +{approved: fico >= 620 and dti <= 0.45, maxLoan: floor(min([income * 4.5, (collateral ?? 0) * 0.8]) / 1000) * 1000, reasons: filter(['fico', 'dti'], # == 'fico' ? fico < 620 : dti > 0.45)};{fico: 700, dti: 0.2, income: 80000};{approved: true, maxLoan: 0, reasons: []} +{approved: fico >= 620 and dti <= 0.45, maxLoan: floor(min([income * 4.5, (collateral ?? 0) * 0.8]) / 1000) * 1000, reasons: filter(['fico', 'dti'], # == 'fico' ? fico < 620 : dti > 0.45)};{fico: 700, dti: 0.2, income: 123456.78, collateral: 400000};{approved: true, maxLoan: 320000, reasons: []} diff --git a/core/expression/tests/spec/standard/12-logistics.csv b/core/expression/tests/spec/standard/12-logistics.csv new file mode 100644 index 00000000..3f264728 --- /dev/null +++ b/core/expression/tests/spec/standard/12-logistics.csv @@ -0,0 +1,129 @@ +expression (string);input (json 5);output (json 5);note +# Billable weight: actual versus dimensional +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 40, w: 30, h: 20, kg: 3};5 +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 40, w: 30, h: 20, kg: 5};5 +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 40, w: 30, h: 21, kg: 1};5.5 +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 10, w: 10, h: 10, kg: 0.1};0.5 +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 120, w: 80, h: 100, kg: 150};192 +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 60.5, w: 40.2, h: 33.3, kg: 12};16.5 +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 40, w: 30, h: null, kg: 3};!error +max([kg, ceil(l * w * h / 5000 * 2) / 2]);{l: 40, w: 30, h: 20};!error +sum(map(parcels, max([#.kg, #.l * #.w * #.h / 5000])));{parcels: [{id: 'P000', l: 10, w: 10, h: 5, kg: 0.5}, {id: 'P001', l: 15, w: 14, h: 15, kg: 1.25}, {id: 'P002', l: 20, w: 18, h: 25, kg: 3}, {id: 'P003', l: 25, w: 22, h: 5, kg: 12.8}, {id: 'P004', l: 30, w: 26, h: 15, kg: 22}, {id: 'P005', l: 35, w: 10, h: 25, kg: 0.5}, {id: 'P006', l: 40, w: 14, h: 5, kg: 1.25}, {id: 'P007', l: 10, w: 18, h: 15, kg: 3}]};45.55 +sum(map(parcels, max([#.kg, #.l * #.w * #.h / 5000])));{parcels: [{id: 'P000', l: 10, w: 10, h: 5, kg: 0.5}, {id: 'P001', l: 15, w: 14, h: 15, kg: 1.25}, {id: 'P002', l: 20, w: 18, h: 25, kg: 3}, {id: 'P003', l: 25, w: 22, h: 5, kg: 12.8}, {id: 'P004', l: 30, w: 26, h: 15, kg: 22}, {id: 'P005', l: 35, w: 10, h: 25, kg: 0.5}, {id: 'P006', l: 40, w: 14, h: 5, kg: 1.25}, {id: 'P007', l: 10, w: 18, h: 15, kg: 3}, {id: 'P008', l: 15, w: 22, h: 25, kg: 12.8}, {id: 'P009', l: 20, w: 26, h: 5, kg: 22}, {id: 'P010', l: 25, w: 10, h: 15, kg: 0.5}, {id: 'P011', l: 30, w: 14, h: 25, kg: 1.25}, {id: 'P012', l: 35, w: 18, h: 5, kg: 3}, {id: 'P013', l: 40, w: 22, h: 15, kg: 12.8}, {id: 'P014', l: 10, w: 26, h: 25, kg: 22}, {id: 'P015', l: 15, w: 10, h: 5, kg: 0.5}, {id: 'P016', l: 20, w: 14, h: 15, kg: 1.25}, {id: 'P017', l: 25, w: 18, h: 25, kg: 3}, {id: 'P018', l: 30, w: 22, h: 5, kg: 12.8}, {id: 'P019', l: 35, w: 26, h: 15, kg: 22}, {id: 'P020', l: 40, w: 10, h: 25, kg: 0.5}, {id: 'P021', l: 10, w: 14, h: 5, kg: 1.25}, {id: 'P022', l: 15, w: 18, h: 15, kg: 3}, {id: 'P023', l: 20, w: 22, h: 25, kg: 12.8}, {id: 'P024', l: 25, w: 26, h: 5, kg: 22}, {id: 'P025', l: 30, w: 10, h: 15, kg: 0.5}, {id: 'P026', l: 35, w: 14, h: 25, kg: 1.25}, {id: 'P027', l: 40, w: 18, h: 5, kg: 3}, {id: 'P028', l: 10, w: 22, h: 15, kg: 12.8}, {id: 'P029', l: 15, w: 26, h: 25, kg: 22}, {id: 'P030', l: 20, w: 10, h: 5, kg: 0.5}, {id: 'P031', l: 25, w: 14, h: 15, kg: 1.25}, {id: 'P032', l: 30, w: 18, h: 25, kg: 3}, {id: 'P033', l: 35, w: 22, h: 5, kg: 12.8}, {id: 'P034', l: 40, w: 26, h: 15, kg: 22}, {id: 'P035', l: 10, w: 10, h: 25, kg: 0.5}, {id: 'P036', l: 15, w: 14, h: 5, kg: 1.25}, {id: 'P037', l: 20, w: 18, h: 15, kg: 3}, {id: 'P038', l: 25, w: 22, h: 25, kg: 12.8}, {id: 'P039', l: 30, w: 26, h: 5, kg: 22}]};321.85 +sum(map(parcels, max([#.kg, #.l * #.w * #.h / 5000])));{parcels: []};0 +sum(map(parcels, max([#.kg, #.l * #.w * #.h / 5000])));{parcels: [{l: 50, w: 50, h: 50, kg: 20}]};25 +sum(map(parcels, max([#.kg, #.l * #.w * #.h / 5000])));{parcels: [{l: 50, w: 50, h: 50}]};!error +map(filter(parcels, #.kg > 20 or max([#.l, #.w, #.h]) > 120), #.id);{parcels: [{id: 'P000', l: 10, w: 10, h: 5, kg: 0.5}, {id: 'P001', l: 15, w: 14, h: 15, kg: 1.25}, {id: 'P002', l: 20, w: 18, h: 25, kg: 3}, {id: 'P003', l: 25, w: 22, h: 5, kg: 12.8}, {id: 'P004', l: 30, w: 26, h: 15, kg: 22}, {id: 'P005', l: 35, w: 10, h: 25, kg: 0.5}, {id: 'P006', l: 40, w: 14, h: 5, kg: 1.25}, {id: 'P007', l: 10, w: 18, h: 15, kg: 3}, {id: 'P008', l: 15, w: 22, h: 25, kg: 12.8}, {id: 'P009', l: 20, w: 26, h: 5, kg: 22}, {id: 'P010', l: 25, w: 10, h: 15, kg: 0.5}, {id: 'P011', l: 30, w: 14, h: 25, kg: 1.25}]};['P004', 'P009'] +map(filter(parcels, #.kg > 20 or max([#.l, #.w, #.h]) > 120), #.id);{parcels: [{id: 'X', l: 121, w: 1, h: 1, kg: 1}, {id: 'Y', l: 120, w: 120, h: 120, kg: 20}]};['X'] +map(filter(parcels, #.kg > 20 or max([#.l, #.w, #.h]) > 120), #.id);{parcels: []};[] +# Zone rating tables +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 1, kg: 0.4};5.10 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 1, kg: 1};5.10 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 1, kg: 1.01};6.25 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 3, kg: 7.5};15.85 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 4, kg: 30};42.80 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 8, kg: 2};13.15 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 2, kg: 0};6.35 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: null, kg: 1};12.00 +round((({'1': 5.10, '2': 6.35, '3': 7.80, '4': 9.45})[string(zone)] ?? 12.00) + max([0, ceil(kg) - 1]) * 1.15, 2);{zone: 2, kg: null};!error +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: '94105'};'west' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: '02139'};'east' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: '10001'};'east' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: '60601'};'central' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: '2'};'central' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: 'SW1A 1AA'};'unknown' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: ''};'unknown' +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: 94105};!error +startsWith(zip, '9') ? 'west' : startsWith(zip, '0') or startsWith(zip, '1') ? 'east' : matches(zip, '^[2-8]') ? 'central' : 'unknown';{zip: null};!error +# Delivery SLA with calendar days +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: '2025-03-19 09:59'};'on-time' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: '2025-03-19 10:00'};'on-time' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: '2025-03-19 10:01'};'late' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: '2025-03-20 10:00'};'late' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: '2025-03-20 10:59'};'late' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: '2025-03-20 11:00'};'breach' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2024-12-30 16:00', slaDays: 3, deliveredAt: '2025-01-02 15:00'};'on-time' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2024-02-27 12:00', slaDays: 2, deliveredAt: '2024-02-29 12:00'};'on-time' +"promise = d(shippedAt).add(slaDays, 'day'); d(deliveredAt) <= promise ? 'on-time' : d(deliveredAt).diff(promise, 'hour') <= 24 ? 'late' : 'breach'";{shippedAt: '2025-03-17 10:00', slaDays: 2, deliveredAt: null};'on-time';question: an invalid date orders before every valid date, so a missing delivery date counts as on time +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-17', n: 1};'2025-03-18 Tue' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-17', n: 4};'2025-03-21 Fri' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-17', n: 5};'2025-03-24 Mon' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-20', n: 1};'2025-03-21 Fri' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-20', n: 2};'2025-03-24 Mon' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-21', n: 1};'2025-03-24 Mon' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-21', n: 10};'2025-04-04 Fri' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-12-29', n: 3};'2026-01-01 Thu' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-02-26', n: 3};'2025-03-03 Mon' +"wd = d(start).weekday(); d(start).add(floor(n / 5) * 7 + n % 5 + (wd - 1 + n % 5 > 4 ? 2 : 0), 'day').format('%Y-%m-%d %a')";{start: '2025-03-17', n: 0};'2025-03-17 Mon' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: '2025-03-21'};'2025-03-21' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: '2025-03-22'};'2025-03-24' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: '2025-03-23'};'2025-03-24' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: '2025-05-31'};'2025-06-02' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: '2025-12-27'};'2025-12-29' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: '2026-02-28'};'2026-03-02' +d(eta).weekday() >= 6 ? d(eta).add(8 - d(eta).weekday(), 'day').format('%Y-%m-%d') : d(eta).format('%Y-%m-%d');{eta: 'tbd'};!error +# Cut-off times in the warehouse time zone +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-03-19T17:59:00Z', tz: 'America/New_York', cutoffHour: 14};'same-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-03-19T18:00:00Z', tz: 'America/New_York', cutoffHour: 14};'next-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-01-15T18:59:00Z', tz: 'America/New_York', cutoffHour: 14};'same-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-01-15T19:00:00Z', tz: 'America/New_York', cutoffHour: 14};'next-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-03-19T02:00:00Z', tz: 'Asia/Tokyo', cutoffHour: 12};'same-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-03-19T03:00:00Z', tz: 'Asia/Tokyo', cutoffHour: 12};'next-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-03-19T13:30:00Z', tz: 'Europe/London', cutoffHour: 14};'same-day' +d(orderedAt).tz(tz).hour() < cutoffHour ? 'same-day' : 'next-day';{orderedAt: '2025-06-19T13:30:00Z', tz: 'Europe/London', cutoffHour: 14};'next-day' +d(pickupAt).tz(tz).format('%Y-%m-%d %H:%M');{pickupAt: '2025-03-19T23:30:00Z', tz: 'Asia/Kolkata'};'2025-03-20 05:00' +d(pickupAt).tz(tz).format('%Y-%m-%d %H:%M');{pickupAt: '2025-12-31T23:30:00Z', tz: 'Europe/Berlin'};'2026-01-01 00:30' +d(pickupAt).tz(tz).format('%Y-%m-%d %H:%M');{pickupAt: '2025-01-01T03:00:00Z', tz: 'America/Los_Angeles'};'2024-12-31 19:00' +d(pickupAt).tz(tz).format('%Y-%m-%d %H:%M');{pickupAt: '2025-07-01T03:00:00Z', tz: 'America/Los_Angeles'};'2025-06-30 20:00' +d(pickupAt).tz(tz).format('%Y-%m-%d %H:%M');{pickupAt: '2024-02-29T20:00:00Z', tz: 'Pacific/Auckland'};'2024-03-01 09:00' +# Transit time and dwell statistics +map(legs, d(#.arrived).diff(d(#.departed), 'hour'));{legs: [{departed: '2025-03-01 08:00', arrived: '2025-03-01 17:30'}, {departed: '2025-03-01 20:00', arrived: '2025-03-03 06:00'}]};[9, 34] +map(legs, d(#.arrived).diff(d(#.departed), 'hour'));{legs: []};[] +map(legs, d(#.arrived).diff(d(#.departed), 'hour'));{legs: [{departed: '2024-12-31 22:00', arrived: '2025-01-01 01:59'}]};[3] +map(legs, d(#.arrived).diff(d(#.departed), 'hour'));{legs: [{departed: '2025-03-01 08:00', arrived: '2025-03-01 07:00'}]};[-1] +map(legs, d(#.arrived).diff(d(#.departed), 'hour'));{legs: [{departed: '2025-03-01 08:00'}]};[null] +sum(map(legs, d(#.arrived).diff(d(#.departed), 'minute'))) / 60;{legs: [{departed: '2025-03-01 08:00', arrived: '2025-03-01 17:30'}, {departed: '2025-03-01 20:00', arrived: '2025-03-03 06:15'}]};43.75 +sum(map(legs, d(#.arrived).diff(d(#.departed), 'minute'))) / 60;{legs: []};0 +sum(map(legs, d(#.arrived).diff(d(#.departed), 'minute'))) / 60;{legs: [{departed: '2025-03-01 08:00', arrived: '2025-03-01 08:45'}]};0.75 +sum(map(legs, d(#.arrived).diff(d(#.departed), 'minute'))) / 60;{legs: [{departed: '2025-03-01 08:00', arrived: 'x'}]};!error +"scans = map(events, d(#.at)); max(map(events, d(#.at).timestamp())) - min(map(events, d(#.at).timestamp())) > 72 * 3600000 ? 'stuck' : 'moving'";{events: [{at: '2025-03-01 00:00'}, {at: '2025-03-04 00:00'}]};'moving' +"scans = map(events, d(#.at)); max(map(events, d(#.at).timestamp())) - min(map(events, d(#.at).timestamp())) > 72 * 3600000 ? 'stuck' : 'moving'";{events: [{at: '2025-03-01 00:00'}, {at: '2025-03-04 00:00:01'}]};'stuck' +"scans = map(events, d(#.at)); max(map(events, d(#.at).timestamp())) - min(map(events, d(#.at).timestamp())) > 72 * 3600000 ? 'stuck' : 'moving'";{events: [{at: '2025-03-04 00:00'}, {at: '2025-03-01 00:00'}, {at: '2025-03-05 12:00'}]};'stuck' +"scans = map(events, d(#.at)); max(map(events, d(#.at).timestamp())) - min(map(events, d(#.at).timestamp())) > 72 * 3600000 ? 'stuck' : 'moving'";{events: [{at: '2025-03-01 00:00'}]};'moving' +"scans = map(events, d(#.at)); max(map(events, d(#.at).timestamp())) - min(map(events, d(#.at).timestamp())) > 72 * 3600000 ? 'stuck' : 'moving'";{events: []};!error +# Fuel surcharge and accessorials +round(base * (1 + max([0, dieselPrice - 3.00]) * 0.05) + (residential ? 5.25 : 0) + (liftgate ?? false ? 85 : 0), 2);{base: 100, dieselPrice: 3.00, residential: false};100.00 +round(base * (1 + max([0, dieselPrice - 3.00]) * 0.05) + (residential ? 5.25 : 0) + (liftgate ?? false ? 85 : 0), 2);{base: 100, dieselPrice: 3.859, residential: true};109.55 +round(base * (1 + max([0, dieselPrice - 3.00]) * 0.05) + (residential ? 5.25 : 0) + (liftgate ?? false ? 85 : 0), 2);{base: 250.50, dieselPrice: 4.25, residential: false, liftgate: true};351.16 +round(base * (1 + max([0, dieselPrice - 3.00]) * 0.05) + (residential ? 5.25 : 0) + (liftgate ?? false ? 85 : 0), 2);{base: 100, dieselPrice: 2.5, residential: true, liftgate: false};105.25 +round(base * (1 + max([0, dieselPrice - 3.00]) * 0.05) + (residential ? 5.25 : 0) + (liftgate ?? false ? 85 : 0), 2);{base: 100, dieselPrice: 3.01, residential: null};!error +round(base * (1 + max([0, dieselPrice - 3.00]) * 0.05) + (residential ? 5.25 : 0) + (liftgate ?? false ? 85 : 0), 2);{base: 100, dieselPrice: null, residential: false};!error +# Route planning over stops +{stops: len(stops), km: sum(map(stops, #.km)), late: map(filter(stops, #.eta > #.windowEnd), #.name), avgKm: round(avg(map(stops, #.km)), 1)};{stops: [{name: 'A', km: 12.4, eta: 9.5, windowEnd: 10}, {name: 'B', km: 7.1, eta: 11, windowEnd: 10.5}, {name: 'Zürich HB', km: 30, eta: 12, windowEnd: 12}]};{stops: 3, km: 49.5, late: ['B'], avgKm: 16.5} +{stops: len(stops), km: sum(map(stops, #.km)), late: map(filter(stops, #.eta > #.windowEnd), #.name), avgKm: round(avg(map(stops, #.km)), 1)};{stops: [{name: 'solo', km: 5, eta: 1, windowEnd: 0}]};{stops: 1, km: 5, late: ['solo'], avgKm: 5} +{stops: len(stops), km: sum(map(stops, #.km)), late: map(filter(stops, #.eta > #.windowEnd), #.name), avgKm: round(avg(map(stops, #.km)), 1)};{stops: []};!error +{stops: len(stops), km: sum(map(stops, #.km)), late: map(filter(stops, #.eta > #.windowEnd), #.name), avgKm: round(avg(map(stops, #.km)), 1)};{stops: [{name: 'x', km: 1, eta: null, windowEnd: 2}]};!error +map(stops as s, `${s.seq}. ${upper(s.city)} (${s.windowStart}-${s.windowEnd})`);{stops: [{seq: 1, city: 'Kraków', windowStart: '08:00', windowEnd: '10:00'}, {seq: 2, city: 'Łódź', windowStart: '13:00', windowEnd: '15:30'}]};['1. KRAKÓW (08:00-10:00)', '2. ŁÓDŹ (13:00-15:30)'] +map(stops as s, `${s.seq}. ${upper(s.city)} (${s.windowStart}-${s.windowEnd})`);{stops: []};[] +map(stops as s, `${s.seq}. ${upper(s.city)} (${s.windowStart}-${s.windowEnd})`);{stops: [{seq: 1, city: 'x'}]};['1. X (null-null)'] +map(stops as s, `${s.seq}. ${upper(s.city)} (${s.windowStart}-${s.windowEnd})`);{stops: [{seq: 1, city: null}]};!error +all(stops, #.palletCount <= 26) and sum(map(stops, #.palletCount)) <= truckCapacity and sum(map(stops, #.kg)) <= maxKg;{truckCapacity: 26, maxKg: 20000, stops: [{palletCount: 10, kg: 8000}, {palletCount: 16, kg: 12000}]};true +all(stops, #.palletCount <= 26) and sum(map(stops, #.palletCount)) <= truckCapacity and sum(map(stops, #.kg)) <= maxKg;{truckCapacity: 26, maxKg: 20000, stops: [{palletCount: 10, kg: 8000}, {palletCount: 17, kg: 1}]};false +all(stops, #.palletCount <= 26) and sum(map(stops, #.palletCount)) <= truckCapacity and sum(map(stops, #.kg)) <= maxKg;{truckCapacity: 26, maxKg: 20000, stops: [{palletCount: 10, kg: 8000}, {palletCount: 16, kg: 12000.01}]};false +all(stops, #.palletCount <= 26) and sum(map(stops, #.palletCount)) <= truckCapacity and sum(map(stops, #.kg)) <= maxKg;{truckCapacity: 52, maxKg: 40000, stops: [{palletCount: 27, kg: 1}]};false +all(stops, #.palletCount <= 26) and sum(map(stops, #.palletCount)) <= truckCapacity and sum(map(stops, #.kg)) <= maxKg;{truckCapacity: 26, maxKg: 20000, stops: []};true +all(stops, #.palletCount <= 26) and sum(map(stops, #.palletCount)) <= truckCapacity and sum(map(stops, #.kg)) <= maxKg;{truckCapacity: 26, maxKg: 20000, stops: [{palletCount: 10}]};!error +# Tracking numbers +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: '1Z999AA10123456784'};'UPS' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: '1z999aa10123456784'};'unknown' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: '123456789012'};'FedEx' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: '123456789012345'};'FedEx' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: '1234567890123'};'unknown' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: '9400111899223856927581'};'USPS' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: ''};'unknown' +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: 123456789012};!error +matches(tracking, '^1Z[0-9A-Z]{16}$') ? 'UPS' : matches(tracking, '^[0-9]{12}$') or matches(tracking, '^[0-9]{15}$') ? 'FedEx' : matches(tracking, '^9[0-9]{21}$') ? 'USPS' : 'unknown';{tracking: null};!error +upper(trim(carrier)) + '-' + extract(tracking, '([0-9]{4})$')[1];{carrier: ' dhl ', tracking: 'JD014600003828'};'DHL-3828' +upper(trim(carrier)) + '-' + extract(tracking, '([0-9]{4})$')[1];{carrier: 'ups', tracking: '1Z999AA10123456784'};'UPS-6784' +upper(trim(carrier)) + '-' + extract(tracking, '([0-9]{4})$')[1];{carrier: 'fedex', tracking: 'ABC'};!error +upper(trim(carrier)) + '-' + extract(tracking, '([0-9]{4})$')[1];{carrier: null, tracking: '1234'};!error diff --git a/core/expression/tests/spec/standard/12-payroll.csv b/core/expression/tests/spec/standard/12-payroll.csv new file mode 100644 index 00000000..4b5838f6 --- /dev/null +++ b/core/expression/tests/spec/standard/12-payroll.csv @@ -0,0 +1,135 @@ +expression (string);input (json 5);output (json 5);note +# Overtime pay +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 38, rate: 22.50};855.00 +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 40, rate: 22.50};900.00 +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 40.25, rate: 22.50};908.44 +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 52.5, rate: 18.75};1101.56 +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 0, rate: 30};0.0 +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 80, rate: 15.333};1533.30 +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: null, rate: 20};!error +round(min([hours, 40]) * rate + max([0, hours - 40]) * rate * 1.5, 2);{hours: 45, rate: '20'};!error +round(sum(map(shifts, min([#.hours, 8]) + max([0, #.hours - 8]) * 1.5)) * rate, 2);{rate: 20, shifts: [{date: '2025-03-01', hours: 8, night: true}, {date: '2025-03-02', hours: 9.5, night: false}, {date: '2025-03-03', hours: 10, night: false}, {date: '2025-03-04', hours: 7.25, night: false}, {date: '2025-03-05', hours: 12, night: true}]};1010.00 +round(sum(map(shifts, min([#.hours, 8]) + max([0, #.hours - 8]) * 1.5)) * rate, 2);{rate: 17.35, shifts: [{date: '2025-03-01', hours: 8, night: true}, {date: '2025-03-02', hours: 9.5, night: false}, {date: '2025-03-03', hours: 10, night: false}, {date: '2025-03-04', hours: 7.25, night: false}, {date: '2025-03-05', hours: 12, night: true}, {date: '2025-03-06', hours: 8, night: false}, {date: '2025-03-07', hours: 9.5, night: false}, {date: '2025-03-08', hours: 10, night: false}, {date: '2025-03-09', hours: 7.25, night: true}, {date: '2025-03-10', hours: 12, night: false}, {date: '2025-03-11', hours: 8, night: false}, {date: '2025-03-12', hours: 9.5, night: false}, {date: '2025-03-13', hours: 10, night: true}, {date: '2025-03-14', hours: 7.25, night: false}, {date: '2025-03-15', hours: 12, night: false}, {date: '2025-03-16', hours: 8, night: false}, {date: '2025-03-17', hours: 9.5, night: true}, {date: '2025-03-18', hours: 10, night: false}, {date: '2025-03-19', hours: 7.25, night: false}, {date: '2025-03-20', hours: 12, night: false}, {date: '2025-03-21', hours: 8, night: true}, {date: '2025-03-22', hours: 9.5, night: false}]};3821.34 +round(sum(map(shifts, min([#.hours, 8]) + max([0, #.hours - 8]) * 1.5)) * rate, 2);{rate: 20, shifts: []};0 +round(sum(map(shifts, min([#.hours, 8]) + max([0, #.hours - 8]) * 1.5)) * rate, 2);{rate: 20, shifts: [{hours: 8}, {hours: 8.01}]};320.30 +round(sum(map(shifts, min([#.hours, 8]) + max([0, #.hours - 8]) * 1.5)) * rate, 2);{rate: 20, shifts: [{hours: null}]};!error +sum(map(filter(shifts, #.night), #.hours)) * nightPremium;{nightPremium: 2.25, shifts: [{date: '2025-03-01', hours: 8, night: true}, {date: '2025-03-02', hours: 9.5, night: false}, {date: '2025-03-03', hours: 10, night: false}, {date: '2025-03-04', hours: 7.25, night: false}, {date: '2025-03-05', hours: 12, night: true}, {date: '2025-03-06', hours: 8, night: false}, {date: '2025-03-07', hours: 9.5, night: false}, {date: '2025-03-08', hours: 10, night: false}, {date: '2025-03-09', hours: 7.25, night: true}, {date: '2025-03-10', hours: 12, night: false}, {date: '2025-03-11', hours: 8, night: false}, {date: '2025-03-12', hours: 9.5, night: false}, {date: '2025-03-13', hours: 10, night: true}, {date: '2025-03-14', hours: 7.25, night: false}, {date: '2025-03-15', hours: 12, night: false}, {date: '2025-03-16', hours: 8, night: false}, {date: '2025-03-17', hours: 9.5, night: true}, {date: '2025-03-18', hours: 10, night: false}, {date: '2025-03-19', hours: 7.25, night: false}, {date: '2025-03-20', hours: 12, night: false}, {date: '2025-03-21', hours: 8, night: true}, {date: '2025-03-22', hours: 9.5, night: false}]};123.1875 +sum(map(filter(shifts, #.night), #.hours)) * nightPremium;{nightPremium: 1, shifts: []};0 +sum(map(filter(shifts, #.night), #.hours)) * nightPremium;{nightPremium: 3, shifts: [{hours: 8, night: false}]};0 +sum(map(filter(shifts, #.night), #.hours)) * nightPremium;{nightPremium: 3, shifts: [{hours: 8}]};!error +sum(map(filter(shifts, #.night), #.hours)) * nightPremium;{nightPremium: null, shifts: [{hours: 8, night: true}]};!error +# Progressive income tax brackets +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 0};0.00 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 11600};1160.00 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 11601};1160.12 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 47150};5426.00 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 75000};11553.00 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 100525};17168.50 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 250000};53042.50 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: 58432.17};7908.08 +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: null};!error +round(min([income, 11600]) * 0.10 + max([0, min([income, 47150]) - 11600]) * 0.12 + max([0, min([income, 100525]) - 47150]) * 0.22 + max([0, income - 100525]) * 0.24, 2);{income: '50000'};!error +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 64600};6000.00 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 64601};11000.22 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 114600, deductions: 14600};22000.00 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 114601};24000.24 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 10000};0.00 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 80000, deductions: 29200, credits: 2000};9176.00 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 80000, deductions: null, credits: null};14388.00 +"taxable = max([0, gross - (deductions ?? 14600)]); round(taxable * (taxable > 100000 ? 0.24 : taxable > 50000 ? 0.22 : 0.12) - (credits ?? 0), 2)";{gross: 12345.67, deductions: 0};1481.48 +# Payroll deductions with caps +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 5000, ytd: 0};{ss: 310.00, medicare: 72.50} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 5000, ytd: 174000};{ss: 130.20, medicare: 72.50} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 5000, ytd: 176100};{ss: 0.00, medicare: 72.50} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 10000, ytd: 195000};{ss: 0.00, medicare: 190.00} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 10000, ytd: 250000};{ss: 0.00, medicare: 685.00} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 3846.15, ytd: 50000};{ss: 238.46, medicare: 55.77} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 0, ytd: 0};{ss: 0.00, medicare: 0.00} +{ss: round(min([gross, max([0, 176100 - ytd])]) * 0.062, 2), medicare: round(gross * 0.0145 + max([0, ytd + gross - 200000]) * 0.009, 2)};{gross: 5000};!error +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 4, matchEligible: true};240.0 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 6, matchEligible: true};360.0 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 10, matchEligible: true};520.00 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 10, matchEligible: false};400 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 0, matchEligible: true};0.0 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 3333.33, contributionPct: 7.5, matchEligible: true};350.00 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 150, matchEligible: false};4000 +round(gross * min([contributionPct, 100]) / 100 + (matchEligible ? min([gross * contributionPct / 100, gross * 0.06]) * 0.5 : 0), 2);{gross: 4000, contributionPct: 5};!error +# Net pay statement +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: [{amount: 3000}, {amount: 250.50}], deductions: [{type: 'pct', value: 5}, {type: 'flat', value: 125}]};{gross: 3250.50, deductions: 287.53, net: 2962.97} +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: [], deductions: []};{gross: 0, deductions: 0, net: 0} +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: [{amount: 100}], deductions: [{type: 'flat', value: 150}]};{gross: 100, deductions: 150, net: 0} +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: [{amount: 1234.56}], deductions: [{type: 'pct', value: 12.5}, {type: 'pct', value: 1.45}, {type: 'flat', value: 0}]};{gross: 1234.56, deductions: 172.22, net: 1062.34} +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: [{amount: 1000}], deductions: [{type: 'PCT', value: 5}]};{gross: 1000, deductions: 5, net: 995} +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: [{amount: 1000}], deductions: [{type: 'pct'}]};!error +"gross = sum(map(earnings, #.amount)); ded = sum(map(deductions, #.type == 'pct' ? round(gross * #.value / 100, 2) : #.value)); {gross: gross, deductions: ded, net: max([0, gross - ded])}";{earnings: null, deductions: []};!error +# Tenure, leave accrual and anniversaries +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2024-03-21', asOf: '2025-03-20'};10 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2024-03-20', asOf: '2025-03-20'};15 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2020-03-21', asOf: '2025-03-20'};15 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2020-03-20', asOf: '2025-03-20'};20 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2015-03-20', asOf: '2025-03-20'};25 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2016-02-29', asOf: '2025-02-28'};20 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '2030-01-01', asOf: '2025-03-20'};10 +"years = d(asOf).diff(d(hireDate), 'year'); years < 1 ? 10 : years < 5 ? 15 : years < 10 ? 20 : 25";{hireDate: '', asOf: '2025-03-20'};!error +round(min([maxBalance, balance + hoursWorked / 40 * accrualPerWeek]), 2);{balance: 40, hoursWorked: 80, accrualPerWeek: 3.08, maxBalance: 240};46.16 +round(min([maxBalance, balance + hoursWorked / 40 * accrualPerWeek]), 2);{balance: 238, hoursWorked: 80, accrualPerWeek: 3.08, maxBalance: 240};240 +round(min([maxBalance, balance + hoursWorked / 40 * accrualPerWeek]), 2);{balance: 0, hoursWorked: 37.5, accrualPerWeek: 3.08, maxBalance: 240};2.89 +round(min([maxBalance, balance + hoursWorked / 40 * accrualPerWeek]), 2);{balance: 0, hoursWorked: 0, accrualPerWeek: 3.08, maxBalance: 240};0.00 +round(min([maxBalance, balance + hoursWorked / 40 * accrualPerWeek]), 2);{balance: 100, hoursWorked: 13, accrualPerWeek: 4.615, maxBalance: 120};101.50 +round(min([maxBalance, balance + hoursWorked / 40 * accrualPerWeek]), 2);{balance: 10, hoursWorked: 40, maxBalance: 240};!error +d(hireDate).set('year', d(asOf).year()).isSameOrAfter(d(asOf)) ? d(hireDate).set('year', d(asOf).year()).format('%Y-%m-%d') : d(hireDate).set('year', d(asOf).year() + 1).format('%Y-%m-%d');{hireDate: '2019-06-01', asOf: '2025-03-20'};'2025-06-01' +d(hireDate).set('year', d(asOf).year()).isSameOrAfter(d(asOf)) ? d(hireDate).set('year', d(asOf).year()).format('%Y-%m-%d') : d(hireDate).set('year', d(asOf).year() + 1).format('%Y-%m-%d');{hireDate: '2019-03-20', asOf: '2025-03-20'};'2025-03-20' +d(hireDate).set('year', d(asOf).year()).isSameOrAfter(d(asOf)) ? d(hireDate).set('year', d(asOf).year()).format('%Y-%m-%d') : d(hireDate).set('year', d(asOf).year() + 1).format('%Y-%m-%d');{hireDate: '2019-03-19', asOf: '2025-03-20'};'2026-03-19' +d(hireDate).set('year', d(asOf).year()).isSameOrAfter(d(asOf)) ? d(hireDate).set('year', d(asOf).year()).format('%Y-%m-%d') : d(hireDate).set('year', d(asOf).year() + 1).format('%Y-%m-%d');{hireDate: '2019-12-31', asOf: '2025-12-31'};'2025-12-31' +d(hireDate).set('year', d(asOf).year()).isSameOrAfter(d(asOf)) ? d(hireDate).set('year', d(asOf).year()).format('%Y-%m-%d') : d(hireDate).set('year', d(asOf).year() + 1).format('%Y-%m-%d');{hireDate: '2019-01-01', asOf: '2025-12-31'};'2026-01-01' +d(hireDate).set('year', d(asOf).year()).isSameOrAfter(d(asOf)) ? d(hireDate).set('year', d(asOf).year()).format('%Y-%m-%d') : d(hireDate).set('year', d(asOf).year() + 1).format('%Y-%m-%d');{hireDate: '2020-02-29', asOf: '2025-03-20'};'Invalid date';question: moving Feb 29 to a non-leap year gives an invalid date instead of clamping +map(employees, {name: #.name, anniversary: d(#.hireDate).month() == d(asOf).month()});{asOf: '2025-03-20', employees: [{name: 'Ann', hireDate: '2019-03-01'}, {name: 'Bob', hireDate: '2021-04-01'}, {name: 'Çağla', hireDate: '2024-03-31'}]};[{name: 'Ann', anniversary: true}, {name: 'Bob', anniversary: false}, {name: 'Çağla', anniversary: true}] +map(employees, {name: #.name, anniversary: d(#.hireDate).month() == d(asOf).month()});{asOf: '2025-12-31', employees: []};[] +map(employees, {name: #.name, anniversary: d(#.hireDate).month() == d(asOf).month()});{asOf: '2025-01-01', employees: [{name: 'X', hireDate: '2020-12-31'}]};[{name: 'X', anniversary: false}] +map(employees, {name: #.name, anniversary: d(#.hireDate).month() == d(asOf).month()});{asOf: '2025-03-20', employees: [{name: 'Y', hireDate: null}]};[{name: 'Y', anniversary: false}] +# Pay periods and pay dates +frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : frequency == 'monthly' ? 12 : null;{frequency: 'weekly'};52 +frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : frequency == 'monthly' ? 12 : null;{frequency: 'biweekly'};26 +frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : frequency == 'monthly' ? 12 : null;{frequency: 'semimonthly'};24 +frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : frequency == 'monthly' ? 12 : null;{frequency: 'monthly'};12 +frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : frequency == 'monthly' ? 12 : null;{frequency: 'daily'};null +frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : frequency == 'monthly' ? 12 : null;{};null +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 78000, frequency: 'weekly'};1500 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 78000, frequency: 'biweekly'};3000 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 78000, frequency: 'semimonthly'};3250 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 78000, frequency: 'monthly'};6500 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 100000, frequency: 'biweekly'};3846.15 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 55555.55, frequency: 'weekly'};1068.38 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: 78000};6500 +round(salary / (frequency == 'weekly' ? 52 : frequency == 'biweekly' ? 26 : frequency == 'semimonthly' ? 24 : 12), 2);{salary: null, frequency: 'monthly'};!error +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: '2025-03-31'};'2025-03-31' +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: '2025-05-31'};'2025-05-30' +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: '2025-08-31'};'2025-08-29' +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: '2025-03-01'};'2025-02-28' +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: '2025-02-28'};'2025-02-28' +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: '2026-01-31'};'2026-01-30' +"p = d(periodEnd); p.add(p.weekday() == 6 ? -1 : p.weekday() == 7 ? -2 : 0, 'day').format('%Y-%m-%d')";{periodEnd: 'eom'};'Invalid date' +d(month + '-01').endOf('month').day();{month: '2025-02'};28 +d(month + '-01').endOf('month').day();{month: '2024-02'};29 +d(month + '-01').endOf('month').day();{month: '2025-04'};30 +d(month + '-01').endOf('month').day();{month: '2025-12'};31 +d(month + '-01').endOf('month').day();{month: '1900-02'};28 +d(month + '-01').endOf('month').day();{month: '2000-02'};29 +d(month + '-01').endOf('month').day();{month: 202502};!error +round(salary / 12 * (d(termDate).day() / d(termDate).endOf('month').day()), 2);{salary: 60000, termDate: '2025-03-15'};2419.35 +round(salary / 12 * (d(termDate).day() / d(termDate).endOf('month').day()), 2);{salary: 60000, termDate: '2025-02-14'};2500.0 +round(salary / 12 * (d(termDate).day() / d(termDate).endOf('month').day()), 2);{salary: 60000, termDate: '2024-02-14'};2413.79 +round(salary / 12 * (d(termDate).day() / d(termDate).endOf('month').day()), 2);{salary: 60000, termDate: '2025-04-30'};5000 +round(salary / 12 * (d(termDate).day() / d(termDate).endOf('month').day()), 2);{salary: 72500, termDate: '2025-06-01'};201.39 +round(salary / 12 * (d(termDate).day() / d(termDate).endOf('month').day()), 2);{salary: 60000, termDate: null};!error +# Commission-style bonus and headcount +{eligible: count(employees, #.rating >= 4), pool: round(sum(map(filter(employees, #.rating >= 4), #.salary * (#.rating == 5 ? 0.1 : 0.05))), 2)};{employees: [{salary: 80000, rating: 5}, {salary: 60000, rating: 4}, {salary: 90000, rating: 3}]};{eligible: 2, pool: 11000.00} +{eligible: count(employees, #.rating >= 4), pool: round(sum(map(filter(employees, #.rating >= 4), #.salary * (#.rating == 5 ? 0.1 : 0.05))), 2)};{employees: []};{eligible: 0, pool: 0} +{eligible: count(employees, #.rating >= 4), pool: round(sum(map(filter(employees, #.rating >= 4), #.salary * (#.rating == 5 ? 0.1 : 0.05))), 2)};{employees: [{salary: 55555.55, rating: 4.5}]};{eligible: 1, pool: 2777.78} +{eligible: count(employees, #.rating >= 4), pool: round(sum(map(filter(employees, #.rating >= 4), #.salary * (#.rating == 5 ? 0.1 : 0.05))), 2)};{employees: [{salary: 50000, rating: null}]};!error +{eligible: count(employees, #.rating >= 4), pool: round(sum(map(filter(employees, #.rating >= 4), #.salary * (#.rating == 5 ? 0.1 : 0.05))), 2)};{employees: [{salary: 40000, rating: 1}, {salary: 41250, rating: 2}, {salary: 42500, rating: 3}, {salary: 43750, rating: 4}, {salary: 45000, rating: 5}, {salary: 46250, rating: 1}, {salary: 47500, rating: 2}, {salary: 48750, rating: 3}, {salary: 50000, rating: 4}, {salary: 51250, rating: 5}, {salary: 52500, rating: 1}, {salary: 53750, rating: 2}, {salary: 55000, rating: 3}, {salary: 56250, rating: 4}, {salary: 57500, rating: 5}, {salary: 58750, rating: 1}, {salary: 60000, rating: 2}, {salary: 61250, rating: 3}, {salary: 62500, rating: 4}, {salary: 63750, rating: 5}, {salary: 65000, rating: 1}, {salary: 66250, rating: 2}, {salary: 67500, rating: 3}, {salary: 68750, rating: 4}, {salary: 70000, rating: 5}, {salary: 71250, rating: 1}, {salary: 72500, rating: 2}, {salary: 73750, rating: 3}, {salary: 75000, rating: 4}, {salary: 76250, rating: 5}]};{eligible: 12, pool: 54187.50} +`${lastName}, ${firstName} - ${department ?? 'Unassigned'} - ${string(round(salary / 12, 2))}/mo`;{firstName: 'José', lastName: 'García', department: 'Finance', salary: 60000};'García, José - Finance - 5000/mo' +`${lastName}, ${firstName} - ${department ?? 'Unassigned'} - ${string(round(salary / 12, 2))}/mo`;{firstName: 'Mia', lastName: 'Ng', salary: 50000};'Ng, Mia - Unassigned - 4166.67/mo' +`${lastName}, ${firstName} - ${department ?? 'Unassigned'} - ${string(round(salary / 12, 2))}/mo`;{firstName: 'Lee', lastName: 'Park', department: null, salary: 100000.10};'Park, Lee - Unassigned - 8333.34/mo' +`${lastName}, ${firstName} - ${department ?? 'Unassigned'} - ${string(round(salary / 12, 2))}/mo`;{firstName: 'A', lastName: 'B', department: 'Ops', salary: 12};'B, A - Ops - 1/mo' +`${lastName}, ${firstName} - ${department ?? 'Unassigned'} - ${string(round(salary / 12, 2))}/mo`;{firstName: 'A', lastName: 'B', department: 'Ops'};!error diff --git a/core/expression/tests/spec/standard/12-pricing.csv b/core/expression/tests/spec/standard/12-pricing.csv new file mode 100644 index 00000000..ed162b73 --- /dev/null +++ b/core/expression/tests/spec/standard/12-pricing.csv @@ -0,0 +1,95 @@ +expression (string);input (json 5);output (json 5);note +# Margin and markdown over a large catalog +map(products, round((#.list - #.cost) / #.list * 100, 2));{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}]};[61.51, 56.58, 52.30, 48.56, 45.25, 42.31, 39.67] +map(products, round((#.list - #.cost) / #.list * 100, 2));{products: []};[] +map(products, round((#.list - #.cost) / #.list * 100, 2));{products: [{list: 0, cost: 1}]};!error +map(products, round((#.list - #.cost) / #.list * 100, 2));{products: [{list: 10, cost: 12.5}]};[-25.00] +map(products, round((#.list - #.cost) / #.list * 100, 2));{products: [{list: '10', cost: 1}]};!error +count(products, (#.list - #.cost) / #.list < 0.3);{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}, {sku: 'C0007', cost: 12.49, list: 19.92, stock: 9, launched: '2021-08-08', tags: []}, {sku: 'C0008', cost: 13.56, list: 20.91, stock: 46, launched: '2022-09-09', tags: []}, {sku: 'C0009', cost: 14.63, list: 21.90, stock: 83, launched: '2023-10-10', tags: []}, {sku: 'C0010', cost: 15.70, list: 22.89, stock: 120, launched: '2024-11-11', tags: ['seasonal']}, {sku: 'C0011', cost: 16.77, list: 23.88, stock: 157, launched: '2025-12-12', tags: ['clearance']}, {sku: 'C0012', cost: 17.84, list: 24.87, stock: 194, launched: '2020-01-13', tags: []}, {sku: 'C0013', cost: 18.91, list: 25.86, stock: 231, launched: '2021-02-14', tags: []}, {sku: 'C0014', cost: 19.98, list: 26.85, stock: 18, launched: '2022-03-15', tags: []}, {sku: 'C0015', cost: 20.05, list: 27.84, stock: 55, launched: '2023-04-16', tags: ['seasonal']}, {sku: 'C0016', cost: 21.12, list: 28.83, stock: 92, launched: '2024-05-17', tags: []}, {sku: 'C0017', cost: 22.19, list: 29.82, stock: 129, launched: '2025-06-18', tags: []}, {sku: 'C0018', cost: 23.26, list: 30.81, stock: 166, launched: '2020-07-19', tags: []}, {sku: 'C0019', cost: 24.33, list: 31.80, stock: 203, launched: '2021-08-20', tags: []}, {sku: 'C0020', cost: 25.40, list: 32.79, stock: 240, launched: '2022-09-21', tags: ['seasonal']}, {sku: 'C0021', cost: 26.47, list: 33.78, stock: 27, launched: '2023-10-22', tags: []}, {sku: 'C0022', cost: 27.54, list: 34.77, stock: 64, launched: '2024-11-23', tags: ['clearance']}, {sku: 'C0023', cost: 28.61, list: 35.76, stock: 101, launched: '2025-12-24', tags: []}, {sku: 'C0024', cost: 29.68, list: 36.75, stock: 138, launched: '2020-01-25', tags: []}, {sku: 'C0025', cost: 30.75, list: 37.74, stock: 175, launched: '2021-02-26', tags: ['seasonal']}, {sku: 'C0026', cost: 31.82, list: 38.73, stock: 212, launched: '2022-03-27', tags: []}, {sku: 'C0027', cost: 32.89, list: 39.72, stock: 249, launched: '2023-04-28', tags: []}, {sku: 'C0028', cost: 33.96, list: 40.71, stock: 36, launched: '2024-05-01', tags: []}, {sku: 'C0029', cost: 34.03, list: 41.70, stock: 73, launched: '2025-06-02', tags: []}, {sku: 'C0030', cost: 35.10, list: 42.69, stock: 110, launched: '2020-07-03', tags: ['seasonal']}, {sku: 'C0031', cost: 36.17, list: 43.68, stock: 147, launched: '2021-08-04', tags: []}, {sku: 'C0032', cost: 37.24, list: 44.67, stock: 184, launched: '2022-09-05', tags: []}, {sku: 'C0033', cost: 38.31, list: 45.66, stock: 221, launched: '2023-10-06', tags: ['clearance']}, {sku: 'C0034', cost: 39.38, list: 46.65, stock: 8, launched: '2024-11-07', tags: []}, {sku: 'C0035', cost: 40.45, list: 47.64, stock: 45, launched: '2025-12-08', tags: ['seasonal']}, {sku: 'C0036', cost: 41.52, list: 48.63, stock: 82, launched: '2020-01-09', tags: []}, {sku: 'C0037', cost: 42.59, list: 49.62, stock: 119, launched: '2021-02-10', tags: []}, {sku: 'C0038', cost: 43.66, list: 50.61, stock: 156, launched: '2022-03-11', tags: []}, {sku: 'C0039', cost: 44.73, list: 51.60, stock: 193, launched: '2023-04-12', tags: []}, {sku: 'C0040', cost: 45.80, list: 52.59, stock: 230, launched: '2024-05-13', tags: ['seasonal']}, {sku: 'C0041', cost: 46.87, list: 53.58, stock: 17, launched: '2025-06-14', tags: []}, {sku: 'C0042', cost: 47.94, list: 54.57, stock: 54, launched: '2020-07-15', tags: []}, {sku: 'C0043', cost: 48.01, list: 55.56, stock: 91, launched: '2021-08-16', tags: []}, {sku: 'C0044', cost: 49.08, list: 56.55, stock: 128, launched: '2022-09-17', tags: ['clearance']}, {sku: 'C0045', cost: 50.15, list: 57.54, stock: 165, launched: '2023-10-18', tags: ['seasonal']}, {sku: 'C0046', cost: 51.22, list: 58.53, stock: 202, launched: '2024-11-19', tags: []}, {sku: 'C0047', cost: 52.29, list: 59.52, stock: 239, launched: '2025-12-20', tags: []}, {sku: 'C0048', cost: 53.36, list: 60.51, stock: 26, launched: '2020-01-21', tags: []}, {sku: 'C0049', cost: 54.43, list: 61.50, stock: 63, launched: '2021-02-22', tags: []}, {sku: 'C0050', cost: 55.50, list: 62.49, stock: 100, launched: '2022-03-23', tags: ['seasonal']}, {sku: 'C0051', cost: 56.57, list: 63.48, stock: 137, launched: '2023-04-24', tags: []}, {sku: 'C0052', cost: 57.64, list: 64.47, stock: 174, launched: '2024-05-25', tags: []}, {sku: 'C0053', cost: 58.71, list: 65.46, stock: 211, launched: '2025-06-26', tags: []}, {sku: 'C0054', cost: 59.78, list: 66.45, stock: 248, launched: '2020-07-27', tags: []}, {sku: 'C0055', cost: 60.85, list: 67.44, stock: 35, launched: '2021-08-28', tags: ['clearance', 'seasonal']}, {sku: 'C0056', cost: 61.92, list: 68.43, stock: 72, launched: '2022-09-01', tags: []}, {sku: 'C0057', cost: 62.99, list: 69.42, stock: 109, launched: '2023-10-02', tags: []}, {sku: 'C0058', cost: 63.06, list: 70.41, stock: 146, launched: '2024-11-03', tags: []}, {sku: 'C0059', cost: 64.13, list: 71.40, stock: 183, launched: '2025-12-04', tags: []}, {sku: 'C0060', cost: 65.20, list: 72.39, stock: 220, launched: '2020-01-05', tags: ['seasonal']}, {sku: 'C0061', cost: 66.27, list: 73.38, stock: 7, launched: '2021-02-06', tags: []}, {sku: 'C0062', cost: 67.34, list: 74.37, stock: 44, launched: '2022-03-07', tags: []}, {sku: 'C0063', cost: 68.41, list: 75.36, stock: 81, launched: '2023-04-08', tags: []}, {sku: 'C0064', cost: 69.48, list: 76.35, stock: 118, launched: '2024-05-09', tags: []}, {sku: 'C0065', cost: 70.55, list: 77.34, stock: 155, launched: '2025-06-10', tags: ['seasonal']}, {sku: 'C0066', cost: 71.62, list: 78.33, stock: 192, launched: '2020-07-11', tags: ['clearance']}, {sku: 'C0067', cost: 72.69, list: 79.32, stock: 229, launched: '2021-08-12', tags: []}, {sku: 'C0068', cost: 73.76, list: 80.31, stock: 16, launched: '2022-09-13', tags: []}, {sku: 'C0069', cost: 74.83, list: 81.30, stock: 53, launched: '2023-10-14', tags: []}, {sku: 'C0070', cost: 75.90, list: 82.29, stock: 90, launched: '2024-11-15', tags: ['seasonal']}, {sku: 'C0071', cost: 76.97, list: 83.28, stock: 127, launched: '2025-12-16', tags: []}, {sku: 'C0072', cost: 77.04, list: 84.27, stock: 164, launched: '2020-01-17', tags: []}, {sku: 'C0073', cost: 78.11, list: 85.26, stock: 201, launched: '2021-02-18', tags: []}, {sku: 'C0074', cost: 79.18, list: 86.25, stock: 238, launched: '2022-03-19', tags: []}, {sku: 'C0075', cost: 80.25, list: 87.24, stock: 25, launched: '2023-04-20', tags: ['seasonal']}, {sku: 'C0076', cost: 81.32, list: 88.23, stock: 62, launched: '2024-05-21', tags: []}, {sku: 'C0077', cost: 82.39, list: 89.22, stock: 99, launched: '2025-06-22', tags: ['clearance']}, {sku: 'C0078', cost: 83.46, list: 90.21, stock: 136, launched: '2020-07-23', tags: []}, {sku: 'C0079', cost: 84.53, list: 91.20, stock: 173, launched: '2021-08-24', tags: []}, {sku: 'C0080', cost: 85.60, list: 92.19, stock: 210, launched: '2022-09-25', tags: ['seasonal']}, {sku: 'C0081', cost: 86.67, list: 93.18, stock: 247, launched: '2023-10-26', tags: []}, {sku: 'C0082', cost: 87.74, list: 94.17, stock: 34, launched: '2024-11-27', tags: []}, {sku: 'C0083', cost: 88.81, list: 95.16, stock: 71, launched: '2025-12-28', tags: []}, {sku: 'C0084', cost: 89.88, list: 96.15, stock: 108, launched: '2020-01-01', tags: []}, {sku: 'C0085', cost: 90.95, list: 97.14, stock: 145, launched: '2021-02-02', tags: ['seasonal']}, {sku: 'C0086', cost: 91.02, list: 98.13, stock: 182, launched: '2022-03-03', tags: []}, {sku: 'C0087', cost: 92.09, list: 99.12, stock: 219, launched: '2023-04-04', tags: []}, {sku: 'C0088', cost: 93.16, list: 100.11, stock: 6, launched: '2024-05-05', tags: ['clearance']}, {sku: 'C0089', cost: 94.23, list: 101.10, stock: 43, launched: '2025-06-06', tags: []}, {sku: 'C0090', cost: 5.30, list: 102.09, stock: 80, launched: '2020-07-07', tags: ['seasonal']}, {sku: 'C0091', cost: 6.37, list: 103.08, stock: 117, launched: '2021-08-08', tags: []}, {sku: 'C0092', cost: 7.44, list: 104.07, stock: 154, launched: '2022-09-09', tags: []}, {sku: 'C0093', cost: 8.51, list: 105.06, stock: 191, launched: '2023-10-10', tags: []}, {sku: 'C0094', cost: 9.58, list: 106.05, stock: 228, launched: '2024-11-11', tags: []}, {sku: 'C0095', cost: 10.65, list: 107.04, stock: 15, launched: '2025-12-12', tags: ['seasonal']}, {sku: 'C0096', cost: 11.72, list: 108.03, stock: 52, launched: '2020-01-13', tags: []}, {sku: 'C0097', cost: 12.79, list: 109.02, stock: 89, launched: '2021-02-14', tags: []}, {sku: 'C0098', cost: 13.86, list: 110.01, stock: 126, launched: '2022-03-15', tags: []}, {sku: 'C0099', cost: 14.93, list: 111.00, stock: 163, launched: '2023-04-16', tags: ['clearance']}, {sku: 'C0100', cost: 15.00, list: 112.99, stock: 200, launched: '2024-05-17', tags: ['seasonal']}, {sku: 'C0101', cost: 16.07, list: 113.98, stock: 237, launched: '2025-06-18', tags: []}, {sku: 'C0102', cost: 17.14, list: 114.97, stock: 24, launched: '2020-07-19', tags: []}, {sku: 'C0103', cost: 18.21, list: 115.96, stock: 61, launched: '2021-08-20', tags: []}, {sku: 'C0104', cost: 19.28, list: 116.95, stock: 98, launched: '2022-09-21', tags: []}, {sku: 'C0105', cost: 20.35, list: 117.94, stock: 135, launched: '2023-10-22', tags: ['seasonal']}, {sku: 'C0106', cost: 21.42, list: 118.93, stock: 172, launched: '2024-11-23', tags: []}, {sku: 'C0107', cost: 22.49, list: 119.92, stock: 209, launched: '2025-12-24', tags: []}, {sku: 'C0108', cost: 23.56, list: 120.91, stock: 246, launched: '2020-01-25', tags: []}, {sku: 'C0109', cost: 24.63, list: 121.90, stock: 33, launched: '2021-02-26', tags: []}, {sku: 'C0110', cost: 25.70, list: 122.89, stock: 70, launched: '2022-03-27', tags: ['clearance', 'seasonal']}, {sku: 'C0111', cost: 26.77, list: 123.88, stock: 107, launched: '2023-04-28', tags: []}, {sku: 'C0112', cost: 27.84, list: 124.87, stock: 144, launched: '2024-05-01', tags: []}, {sku: 'C0113', cost: 28.91, list: 125.86, stock: 181, launched: '2025-06-02', tags: []}, {sku: 'C0114', cost: 29.98, list: 126.85, stock: 218, launched: '2020-07-03', tags: []}, {sku: 'C0115', cost: 30.05, list: 127.84, stock: 5, launched: '2021-08-04', tags: ['seasonal']}, {sku: 'C0116', cost: 31.12, list: 128.83, stock: 42, launched: '2022-09-05', tags: []}, {sku: 'C0117', cost: 32.19, list: 129.82, stock: 79, launched: '2023-10-06', tags: []}, {sku: 'C0118', cost: 33.26, list: 130.81, stock: 116, launched: '2024-11-07', tags: []}, {sku: 'C0119', cost: 34.33, list: 131.80, stock: 153, launched: '2025-12-08', tags: []}, {sku: 'C0120', cost: 35.40, list: 132.79, stock: 190, launched: '2020-01-09', tags: ['seasonal']}, {sku: 'C0121', cost: 36.47, list: 133.78, stock: 227, launched: '2021-02-10', tags: ['clearance']}, {sku: 'C0122', cost: 37.54, list: 134.77, stock: 14, launched: '2022-03-11', tags: []}, {sku: 'C0123', cost: 38.61, list: 135.76, stock: 51, launched: '2023-04-12', tags: []}, {sku: 'C0124', cost: 39.68, list: 136.75, stock: 88, launched: '2024-05-13', tags: []}, {sku: 'C0125', cost: 40.75, list: 137.74, stock: 125, launched: '2025-06-14', tags: ['seasonal']}, {sku: 'C0126', cost: 41.82, list: 138.73, stock: 162, launched: '2020-07-15', tags: []}, {sku: 'C0127', cost: 42.89, list: 139.72, stock: 199, launched: '2021-08-16', tags: []}, {sku: 'C0128', cost: 43.96, list: 140.71, stock: 236, launched: '2022-09-17', tags: []}, {sku: 'C0129', cost: 44.03, list: 141.70, stock: 23, launched: '2023-10-18', tags: []}, {sku: 'C0130', cost: 45.10, list: 142.69, stock: 60, launched: '2024-11-19', tags: ['seasonal']}, {sku: 'C0131', cost: 46.17, list: 143.68, stock: 97, launched: '2025-12-20', tags: []}, {sku: 'C0132', cost: 47.24, list: 144.67, stock: 134, launched: '2020-01-21', tags: ['clearance']}, {sku: 'C0133', cost: 48.31, list: 145.66, stock: 171, launched: '2021-02-22', tags: []}, {sku: 'C0134', cost: 49.38, list: 146.65, stock: 208, launched: '2022-03-23', tags: []}, {sku: 'C0135', cost: 50.45, list: 147.64, stock: 245, launched: '2023-04-24', tags: ['seasonal']}, {sku: 'C0136', cost: 51.52, list: 148.63, stock: 32, launched: '2024-05-25', tags: []}, {sku: 'C0137', cost: 52.59, list: 149.62, stock: 69, launched: '2025-06-26', tags: []}, {sku: 'C0138', cost: 53.66, list: 150.61, stock: 106, launched: '2020-07-27', tags: []}, {sku: 'C0139', cost: 54.73, list: 151.60, stock: 143, launched: '2021-08-28', tags: []}, {sku: 'C0140', cost: 55.80, list: 152.59, stock: 180, launched: '2022-09-01', tags: ['seasonal']}, {sku: 'C0141', cost: 56.87, list: 153.58, stock: 217, launched: '2023-10-02', tags: []}, {sku: 'C0142', cost: 57.94, list: 154.57, stock: 4, launched: '2024-11-03', tags: []}, {sku: 'C0143', cost: 58.01, list: 155.56, stock: 41, launched: '2025-12-04', tags: ['clearance']}, {sku: 'C0144', cost: 59.08, list: 156.55, stock: 78, launched: '2020-01-05', tags: []}, {sku: 'C0145', cost: 60.15, list: 157.54, stock: 115, launched: '2021-02-06', tags: ['seasonal']}, {sku: 'C0146', cost: 61.22, list: 158.53, stock: 152, launched: '2022-03-07', tags: []}, {sku: 'C0147', cost: 62.29, list: 159.52, stock: 189, launched: '2023-04-08', tags: []}, {sku: 'C0148', cost: 63.36, list: 160.51, stock: 226, launched: '2024-05-09', tags: []}, {sku: 'C0149', cost: 64.43, list: 161.50, stock: 13, launched: '2025-06-10', tags: []}, {sku: 'C0150', cost: 65.50, list: 12.49, stock: 50, launched: '2020-07-11', tags: ['seasonal']}, {sku: 'C0151', cost: 66.57, list: 13.48, stock: 87, launched: '2021-08-12', tags: []}, {sku: 'C0152', cost: 67.64, list: 14.47, stock: 124, launched: '2022-09-13', tags: []}, {sku: 'C0153', cost: 68.71, list: 15.46, stock: 161, launched: '2023-10-14', tags: []}, {sku: 'C0154', cost: 69.78, list: 16.45, stock: 198, launched: '2024-11-15', tags: ['clearance']}, {sku: 'C0155', cost: 70.85, list: 17.44, stock: 235, launched: '2025-12-16', tags: ['seasonal']}, {sku: 'C0156', cost: 71.92, list: 18.43, stock: 22, launched: '2020-01-17', tags: []}, {sku: 'C0157', cost: 72.99, list: 19.42, stock: 59, launched: '2021-02-18', tags: []}, {sku: 'C0158', cost: 73.06, list: 20.41, stock: 96, launched: '2022-03-19', tags: []}, {sku: 'C0159', cost: 74.13, list: 21.40, stock: 133, launched: '2023-04-20', tags: []}, {sku: 'C0160', cost: 75.20, list: 22.39, stock: 170, launched: '2024-05-21', tags: ['seasonal']}, {sku: 'C0161', cost: 76.27, list: 23.38, stock: 207, launched: '2025-06-22', tags: []}, {sku: 'C0162', cost: 77.34, list: 24.37, stock: 244, launched: '2020-07-23', tags: []}, {sku: 'C0163', cost: 78.41, list: 25.36, stock: 31, launched: '2021-08-24', tags: []}, {sku: 'C0164', cost: 79.48, list: 26.35, stock: 68, launched: '2022-09-25', tags: []}, {sku: 'C0165', cost: 80.55, list: 27.34, stock: 105, launched: '2023-10-26', tags: ['clearance', 'seasonal']}, {sku: 'C0166', cost: 81.62, list: 28.33, stock: 142, launched: '2024-11-27', tags: []}, {sku: 'C0167', cost: 82.69, list: 29.32, stock: 179, launched: '2025-12-28', tags: []}, {sku: 'C0168', cost: 83.76, list: 30.31, stock: 216, launched: '2020-01-01', tags: []}, {sku: 'C0169', cost: 84.83, list: 31.30, stock: 3, launched: '2021-02-02', tags: []}, {sku: 'C0170', cost: 85.90, list: 32.29, stock: 40, launched: '2022-03-03', tags: ['seasonal']}, {sku: 'C0171', cost: 86.97, list: 33.28, stock: 77, launched: '2023-04-04', tags: []}, {sku: 'C0172', cost: 87.04, list: 34.27, stock: 114, launched: '2024-05-05', tags: []}, {sku: 'C0173', cost: 88.11, list: 35.26, stock: 151, launched: '2025-06-06', tags: []}, {sku: 'C0174', cost: 89.18, list: 36.25, stock: 188, launched: '2020-07-07', tags: []}, {sku: 'C0175', cost: 90.25, list: 37.24, stock: 225, launched: '2021-08-08', tags: ['seasonal']}, {sku: 'C0176', cost: 91.32, list: 38.23, stock: 12, launched: '2022-09-09', tags: ['clearance']}, {sku: 'C0177', cost: 92.39, list: 39.22, stock: 49, launched: '2023-10-10', tags: []}, {sku: 'C0178', cost: 93.46, list: 40.21, stock: 86, launched: '2024-11-11', tags: []}, {sku: 'C0179', cost: 94.53, list: 41.20, stock: 123, launched: '2025-12-12', tags: []}, {sku: 'C0180', cost: 5.60, list: 42.19, stock: 160, launched: '2020-01-13', tags: ['seasonal']}, {sku: 'C0181', cost: 6.67, list: 43.18, stock: 197, launched: '2021-02-14', tags: []}, {sku: 'C0182', cost: 7.74, list: 44.17, stock: 234, launched: '2022-03-15', tags: []}, {sku: 'C0183', cost: 8.81, list: 45.16, stock: 21, launched: '2023-04-16', tags: []}, {sku: 'C0184', cost: 9.88, list: 46.15, stock: 58, launched: '2024-05-17', tags: []}, {sku: 'C0185', cost: 10.95, list: 47.14, stock: 95, launched: '2025-06-18', tags: ['seasonal']}, {sku: 'C0186', cost: 11.02, list: 48.13, stock: 132, launched: '2020-07-19', tags: []}, {sku: 'C0187', cost: 12.09, list: 49.12, stock: 169, launched: '2021-08-20', tags: ['clearance']}, {sku: 'C0188', cost: 13.16, list: 50.11, stock: 206, launched: '2022-09-21', tags: []}, {sku: 'C0189', cost: 14.23, list: 51.10, stock: 243, launched: '2023-10-22', tags: []}, {sku: 'C0190', cost: 15.30, list: 52.09, stock: 30, launched: '2024-11-23', tags: ['seasonal']}, {sku: 'C0191', cost: 16.37, list: 53.08, stock: 67, launched: '2025-12-24', tags: []}, {sku: 'C0192', cost: 17.44, list: 54.07, stock: 104, launched: '2020-01-25', tags: []}, {sku: 'C0193', cost: 18.51, list: 55.06, stock: 141, launched: '2021-02-26', tags: []}, {sku: 'C0194', cost: 19.58, list: 56.05, stock: 178, launched: '2022-03-27', tags: []}, {sku: 'C0195', cost: 20.65, list: 57.04, stock: 215, launched: '2023-04-28', tags: ['seasonal']}, {sku: 'C0196', cost: 21.72, list: 58.03, stock: 2, launched: '2024-05-01', tags: []}, {sku: 'C0197', cost: 22.79, list: 59.02, stock: 39, launched: '2025-06-02', tags: []}, {sku: 'C0198', cost: 23.86, list: 60.01, stock: 76, launched: '2020-07-03', tags: ['clearance']}, {sku: 'C0199', cost: 24.93, list: 61.00, stock: 113, launched: '2021-08-04', tags: []}]};109 +count(products, (#.list - #.cost) / #.list < 0.3);{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}]};0 +count(products, (#.list - #.cost) / #.list < 0.3);{products: []};0 +count(products, (#.list - #.cost) / #.list < 0.3);{products: [{list: 10, cost: 7}, {list: 10, cost: 7.01}]};1 +sum(map(filter(products, 'clearance' in #.tags), #.stock * #.cost));{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}, {sku: 'C0007', cost: 12.49, list: 19.92, stock: 9, launched: '2021-08-08', tags: []}, {sku: 'C0008', cost: 13.56, list: 20.91, stock: 46, launched: '2022-09-09', tags: []}, {sku: 'C0009', cost: 14.63, list: 21.90, stock: 83, launched: '2023-10-10', tags: []}, {sku: 'C0010', cost: 15.70, list: 22.89, stock: 120, launched: '2024-11-11', tags: ['seasonal']}, {sku: 'C0011', cost: 16.77, list: 23.88, stock: 157, launched: '2025-12-12', tags: ['clearance']}, {sku: 'C0012', cost: 17.84, list: 24.87, stock: 194, launched: '2020-01-13', tags: []}, {sku: 'C0013', cost: 18.91, list: 25.86, stock: 231, launched: '2021-02-14', tags: []}, {sku: 'C0014', cost: 19.98, list: 26.85, stock: 18, launched: '2022-03-15', tags: []}, {sku: 'C0015', cost: 20.05, list: 27.84, stock: 55, launched: '2023-04-16', tags: ['seasonal']}, {sku: 'C0016', cost: 21.12, list: 28.83, stock: 92, launched: '2024-05-17', tags: []}, {sku: 'C0017', cost: 22.19, list: 29.82, stock: 129, launched: '2025-06-18', tags: []}, {sku: 'C0018', cost: 23.26, list: 30.81, stock: 166, launched: '2020-07-19', tags: []}, {sku: 'C0019', cost: 24.33, list: 31.80, stock: 203, launched: '2021-08-20', tags: []}, {sku: 'C0020', cost: 25.40, list: 32.79, stock: 240, launched: '2022-09-21', tags: ['seasonal']}, {sku: 'C0021', cost: 26.47, list: 33.78, stock: 27, launched: '2023-10-22', tags: []}, {sku: 'C0022', cost: 27.54, list: 34.77, stock: 64, launched: '2024-11-23', tags: ['clearance']}, {sku: 'C0023', cost: 28.61, list: 35.76, stock: 101, launched: '2025-12-24', tags: []}, {sku: 'C0024', cost: 29.68, list: 36.75, stock: 138, launched: '2020-01-25', tags: []}, {sku: 'C0025', cost: 30.75, list: 37.74, stock: 175, launched: '2021-02-26', tags: ['seasonal']}, {sku: 'C0026', cost: 31.82, list: 38.73, stock: 212, launched: '2022-03-27', tags: []}, {sku: 'C0027', cost: 32.89, list: 39.72, stock: 249, launched: '2023-04-28', tags: []}, {sku: 'C0028', cost: 33.96, list: 40.71, stock: 36, launched: '2024-05-01', tags: []}, {sku: 'C0029', cost: 34.03, list: 41.70, stock: 73, launched: '2025-06-02', tags: []}, {sku: 'C0030', cost: 35.10, list: 42.69, stock: 110, launched: '2020-07-03', tags: ['seasonal']}, {sku: 'C0031', cost: 36.17, list: 43.68, stock: 147, launched: '2021-08-04', tags: []}, {sku: 'C0032', cost: 37.24, list: 44.67, stock: 184, launched: '2022-09-05', tags: []}, {sku: 'C0033', cost: 38.31, list: 45.66, stock: 221, launched: '2023-10-06', tags: ['clearance']}, {sku: 'C0034', cost: 39.38, list: 46.65, stock: 8, launched: '2024-11-07', tags: []}, {sku: 'C0035', cost: 40.45, list: 47.64, stock: 45, launched: '2025-12-08', tags: ['seasonal']}, {sku: 'C0036', cost: 41.52, list: 48.63, stock: 82, launched: '2020-01-09', tags: []}, {sku: 'C0037', cost: 42.59, list: 49.62, stock: 119, launched: '2021-02-10', tags: []}, {sku: 'C0038', cost: 43.66, list: 50.61, stock: 156, launched: '2022-03-11', tags: []}, {sku: 'C0039', cost: 44.73, list: 51.60, stock: 193, launched: '2023-04-12', tags: []}, {sku: 'C0040', cost: 45.80, list: 52.59, stock: 230, launched: '2024-05-13', tags: ['seasonal']}, {sku: 'C0041', cost: 46.87, list: 53.58, stock: 17, launched: '2025-06-14', tags: []}, {sku: 'C0042', cost: 47.94, list: 54.57, stock: 54, launched: '2020-07-15', tags: []}, {sku: 'C0043', cost: 48.01, list: 55.56, stock: 91, launched: '2021-08-16', tags: []}, {sku: 'C0044', cost: 49.08, list: 56.55, stock: 128, launched: '2022-09-17', tags: ['clearance']}, {sku: 'C0045', cost: 50.15, list: 57.54, stock: 165, launched: '2023-10-18', tags: ['seasonal']}, {sku: 'C0046', cost: 51.22, list: 58.53, stock: 202, launched: '2024-11-19', tags: []}, {sku: 'C0047', cost: 52.29, list: 59.52, stock: 239, launched: '2025-12-20', tags: []}, {sku: 'C0048', cost: 53.36, list: 60.51, stock: 26, launched: '2020-01-21', tags: []}, {sku: 'C0049', cost: 54.43, list: 61.50, stock: 63, launched: '2021-02-22', tags: []}, {sku: 'C0050', cost: 55.50, list: 62.49, stock: 100, launched: '2022-03-23', tags: ['seasonal']}, {sku: 'C0051', cost: 56.57, list: 63.48, stock: 137, launched: '2023-04-24', tags: []}, {sku: 'C0052', cost: 57.64, list: 64.47, stock: 174, launched: '2024-05-25', tags: []}, {sku: 'C0053', cost: 58.71, list: 65.46, stock: 211, launched: '2025-06-26', tags: []}, {sku: 'C0054', cost: 59.78, list: 66.45, stock: 248, launched: '2020-07-27', tags: []}, {sku: 'C0055', cost: 60.85, list: 67.44, stock: 35, launched: '2021-08-28', tags: ['clearance', 'seasonal']}, {sku: 'C0056', cost: 61.92, list: 68.43, stock: 72, launched: '2022-09-01', tags: []}, {sku: 'C0057', cost: 62.99, list: 69.42, stock: 109, launched: '2023-10-02', tags: []}, {sku: 'C0058', cost: 63.06, list: 70.41, stock: 146, launched: '2024-11-03', tags: []}, {sku: 'C0059', cost: 64.13, list: 71.40, stock: 183, launched: '2025-12-04', tags: []}, {sku: 'C0060', cost: 65.20, list: 72.39, stock: 220, launched: '2020-01-05', tags: ['seasonal']}, {sku: 'C0061', cost: 66.27, list: 73.38, stock: 7, launched: '2021-02-06', tags: []}, {sku: 'C0062', cost: 67.34, list: 74.37, stock: 44, launched: '2022-03-07', tags: []}, {sku: 'C0063', cost: 68.41, list: 75.36, stock: 81, launched: '2023-04-08', tags: []}, {sku: 'C0064', cost: 69.48, list: 76.35, stock: 118, launched: '2024-05-09', tags: []}, {sku: 'C0065', cost: 70.55, list: 77.34, stock: 155, launched: '2025-06-10', tags: ['seasonal']}, {sku: 'C0066', cost: 71.62, list: 78.33, stock: 192, launched: '2020-07-11', tags: ['clearance']}, {sku: 'C0067', cost: 72.69, list: 79.32, stock: 229, launched: '2021-08-12', tags: []}, {sku: 'C0068', cost: 73.76, list: 80.31, stock: 16, launched: '2022-09-13', tags: []}, {sku: 'C0069', cost: 74.83, list: 81.30, stock: 53, launched: '2023-10-14', tags: []}, {sku: 'C0070', cost: 75.90, list: 82.29, stock: 90, launched: '2024-11-15', tags: ['seasonal']}, {sku: 'C0071', cost: 76.97, list: 83.28, stock: 127, launched: '2025-12-16', tags: []}, {sku: 'C0072', cost: 77.04, list: 84.27, stock: 164, launched: '2020-01-17', tags: []}, {sku: 'C0073', cost: 78.11, list: 85.26, stock: 201, launched: '2021-02-18', tags: []}, {sku: 'C0074', cost: 79.18, list: 86.25, stock: 238, launched: '2022-03-19', tags: []}, {sku: 'C0075', cost: 80.25, list: 87.24, stock: 25, launched: '2023-04-20', tags: ['seasonal']}, {sku: 'C0076', cost: 81.32, list: 88.23, stock: 62, launched: '2024-05-21', tags: []}, {sku: 'C0077', cost: 82.39, list: 89.22, stock: 99, launched: '2025-06-22', tags: ['clearance']}, {sku: 'C0078', cost: 83.46, list: 90.21, stock: 136, launched: '2020-07-23', tags: []}, {sku: 'C0079', cost: 84.53, list: 91.20, stock: 173, launched: '2021-08-24', tags: []}, {sku: 'C0080', cost: 85.60, list: 92.19, stock: 210, launched: '2022-09-25', tags: ['seasonal']}, {sku: 'C0081', cost: 86.67, list: 93.18, stock: 247, launched: '2023-10-26', tags: []}, {sku: 'C0082', cost: 87.74, list: 94.17, stock: 34, launched: '2024-11-27', tags: []}, {sku: 'C0083', cost: 88.81, list: 95.16, stock: 71, launched: '2025-12-28', tags: []}, {sku: 'C0084', cost: 89.88, list: 96.15, stock: 108, launched: '2020-01-01', tags: []}, {sku: 'C0085', cost: 90.95, list: 97.14, stock: 145, launched: '2021-02-02', tags: ['seasonal']}, {sku: 'C0086', cost: 91.02, list: 98.13, stock: 182, launched: '2022-03-03', tags: []}, {sku: 'C0087', cost: 92.09, list: 99.12, stock: 219, launched: '2023-04-04', tags: []}, {sku: 'C0088', cost: 93.16, list: 100.11, stock: 6, launched: '2024-05-05', tags: ['clearance']}, {sku: 'C0089', cost: 94.23, list: 101.10, stock: 43, launched: '2025-06-06', tags: []}, {sku: 'C0090', cost: 5.30, list: 102.09, stock: 80, launched: '2020-07-07', tags: ['seasonal']}, {sku: 'C0091', cost: 6.37, list: 103.08, stock: 117, launched: '2021-08-08', tags: []}, {sku: 'C0092', cost: 7.44, list: 104.07, stock: 154, launched: '2022-09-09', tags: []}, {sku: 'C0093', cost: 8.51, list: 105.06, stock: 191, launched: '2023-10-10', tags: []}, {sku: 'C0094', cost: 9.58, list: 106.05, stock: 228, launched: '2024-11-11', tags: []}, {sku: 'C0095', cost: 10.65, list: 107.04, stock: 15, launched: '2025-12-12', tags: ['seasonal']}, {sku: 'C0096', cost: 11.72, list: 108.03, stock: 52, launched: '2020-01-13', tags: []}, {sku: 'C0097', cost: 12.79, list: 109.02, stock: 89, launched: '2021-02-14', tags: []}, {sku: 'C0098', cost: 13.86, list: 110.01, stock: 126, launched: '2022-03-15', tags: []}, {sku: 'C0099', cost: 14.93, list: 111.00, stock: 163, launched: '2023-04-16', tags: ['clearance']}, {sku: 'C0100', cost: 15.00, list: 112.99, stock: 200, launched: '2024-05-17', tags: ['seasonal']}, {sku: 'C0101', cost: 16.07, list: 113.98, stock: 237, launched: '2025-06-18', tags: []}, {sku: 'C0102', cost: 17.14, list: 114.97, stock: 24, launched: '2020-07-19', tags: []}, {sku: 'C0103', cost: 18.21, list: 115.96, stock: 61, launched: '2021-08-20', tags: []}, {sku: 'C0104', cost: 19.28, list: 116.95, stock: 98, launched: '2022-09-21', tags: []}, {sku: 'C0105', cost: 20.35, list: 117.94, stock: 135, launched: '2023-10-22', tags: ['seasonal']}, {sku: 'C0106', cost: 21.42, list: 118.93, stock: 172, launched: '2024-11-23', tags: []}, {sku: 'C0107', cost: 22.49, list: 119.92, stock: 209, launched: '2025-12-24', tags: []}, {sku: 'C0108', cost: 23.56, list: 120.91, stock: 246, launched: '2020-01-25', tags: []}, {sku: 'C0109', cost: 24.63, list: 121.90, stock: 33, launched: '2021-02-26', tags: []}, {sku: 'C0110', cost: 25.70, list: 122.89, stock: 70, launched: '2022-03-27', tags: ['clearance', 'seasonal']}, {sku: 'C0111', cost: 26.77, list: 123.88, stock: 107, launched: '2023-04-28', tags: []}, {sku: 'C0112', cost: 27.84, list: 124.87, stock: 144, launched: '2024-05-01', tags: []}, {sku: 'C0113', cost: 28.91, list: 125.86, stock: 181, launched: '2025-06-02', tags: []}, {sku: 'C0114', cost: 29.98, list: 126.85, stock: 218, launched: '2020-07-03', tags: []}, {sku: 'C0115', cost: 30.05, list: 127.84, stock: 5, launched: '2021-08-04', tags: ['seasonal']}, {sku: 'C0116', cost: 31.12, list: 128.83, stock: 42, launched: '2022-09-05', tags: []}, {sku: 'C0117', cost: 32.19, list: 129.82, stock: 79, launched: '2023-10-06', tags: []}, {sku: 'C0118', cost: 33.26, list: 130.81, stock: 116, launched: '2024-11-07', tags: []}, {sku: 'C0119', cost: 34.33, list: 131.80, stock: 153, launched: '2025-12-08', tags: []}, {sku: 'C0120', cost: 35.40, list: 132.79, stock: 190, launched: '2020-01-09', tags: ['seasonal']}, {sku: 'C0121', cost: 36.47, list: 133.78, stock: 227, launched: '2021-02-10', tags: ['clearance']}, {sku: 'C0122', cost: 37.54, list: 134.77, stock: 14, launched: '2022-03-11', tags: []}, {sku: 'C0123', cost: 38.61, list: 135.76, stock: 51, launched: '2023-04-12', tags: []}, {sku: 'C0124', cost: 39.68, list: 136.75, stock: 88, launched: '2024-05-13', tags: []}, {sku: 'C0125', cost: 40.75, list: 137.74, stock: 125, launched: '2025-06-14', tags: ['seasonal']}, {sku: 'C0126', cost: 41.82, list: 138.73, stock: 162, launched: '2020-07-15', tags: []}, {sku: 'C0127', cost: 42.89, list: 139.72, stock: 199, launched: '2021-08-16', tags: []}, {sku: 'C0128', cost: 43.96, list: 140.71, stock: 236, launched: '2022-09-17', tags: []}, {sku: 'C0129', cost: 44.03, list: 141.70, stock: 23, launched: '2023-10-18', tags: []}, {sku: 'C0130', cost: 45.10, list: 142.69, stock: 60, launched: '2024-11-19', tags: ['seasonal']}, {sku: 'C0131', cost: 46.17, list: 143.68, stock: 97, launched: '2025-12-20', tags: []}, {sku: 'C0132', cost: 47.24, list: 144.67, stock: 134, launched: '2020-01-21', tags: ['clearance']}, {sku: 'C0133', cost: 48.31, list: 145.66, stock: 171, launched: '2021-02-22', tags: []}, {sku: 'C0134', cost: 49.38, list: 146.65, stock: 208, launched: '2022-03-23', tags: []}, {sku: 'C0135', cost: 50.45, list: 147.64, stock: 245, launched: '2023-04-24', tags: ['seasonal']}, {sku: 'C0136', cost: 51.52, list: 148.63, stock: 32, launched: '2024-05-25', tags: []}, {sku: 'C0137', cost: 52.59, list: 149.62, stock: 69, launched: '2025-06-26', tags: []}, {sku: 'C0138', cost: 53.66, list: 150.61, stock: 106, launched: '2020-07-27', tags: []}, {sku: 'C0139', cost: 54.73, list: 151.60, stock: 143, launched: '2021-08-28', tags: []}, {sku: 'C0140', cost: 55.80, list: 152.59, stock: 180, launched: '2022-09-01', tags: ['seasonal']}, {sku: 'C0141', cost: 56.87, list: 153.58, stock: 217, launched: '2023-10-02', tags: []}, {sku: 'C0142', cost: 57.94, list: 154.57, stock: 4, launched: '2024-11-03', tags: []}, {sku: 'C0143', cost: 58.01, list: 155.56, stock: 41, launched: '2025-12-04', tags: ['clearance']}, {sku: 'C0144', cost: 59.08, list: 156.55, stock: 78, launched: '2020-01-05', tags: []}, {sku: 'C0145', cost: 60.15, list: 157.54, stock: 115, launched: '2021-02-06', tags: ['seasonal']}, {sku: 'C0146', cost: 61.22, list: 158.53, stock: 152, launched: '2022-03-07', tags: []}, {sku: 'C0147', cost: 62.29, list: 159.52, stock: 189, launched: '2023-04-08', tags: []}, {sku: 'C0148', cost: 63.36, list: 160.51, stock: 226, launched: '2024-05-09', tags: []}, {sku: 'C0149', cost: 64.43, list: 161.50, stock: 13, launched: '2025-06-10', tags: []}, {sku: 'C0150', cost: 65.50, list: 12.49, stock: 50, launched: '2020-07-11', tags: ['seasonal']}, {sku: 'C0151', cost: 66.57, list: 13.48, stock: 87, launched: '2021-08-12', tags: []}, {sku: 'C0152', cost: 67.64, list: 14.47, stock: 124, launched: '2022-09-13', tags: []}, {sku: 'C0153', cost: 68.71, list: 15.46, stock: 161, launched: '2023-10-14', tags: []}, {sku: 'C0154', cost: 69.78, list: 16.45, stock: 198, launched: '2024-11-15', tags: ['clearance']}, {sku: 'C0155', cost: 70.85, list: 17.44, stock: 235, launched: '2025-12-16', tags: ['seasonal']}, {sku: 'C0156', cost: 71.92, list: 18.43, stock: 22, launched: '2020-01-17', tags: []}, {sku: 'C0157', cost: 72.99, list: 19.42, stock: 59, launched: '2021-02-18', tags: []}, {sku: 'C0158', cost: 73.06, list: 20.41, stock: 96, launched: '2022-03-19', tags: []}, {sku: 'C0159', cost: 74.13, list: 21.40, stock: 133, launched: '2023-04-20', tags: []}, {sku: 'C0160', cost: 75.20, list: 22.39, stock: 170, launched: '2024-05-21', tags: ['seasonal']}, {sku: 'C0161', cost: 76.27, list: 23.38, stock: 207, launched: '2025-06-22', tags: []}, {sku: 'C0162', cost: 77.34, list: 24.37, stock: 244, launched: '2020-07-23', tags: []}, {sku: 'C0163', cost: 78.41, list: 25.36, stock: 31, launched: '2021-08-24', tags: []}, {sku: 'C0164', cost: 79.48, list: 26.35, stock: 68, launched: '2022-09-25', tags: []}, {sku: 'C0165', cost: 80.55, list: 27.34, stock: 105, launched: '2023-10-26', tags: ['clearance', 'seasonal']}, {sku: 'C0166', cost: 81.62, list: 28.33, stock: 142, launched: '2024-11-27', tags: []}, {sku: 'C0167', cost: 82.69, list: 29.32, stock: 179, launched: '2025-12-28', tags: []}, {sku: 'C0168', cost: 83.76, list: 30.31, stock: 216, launched: '2020-01-01', tags: []}, {sku: 'C0169', cost: 84.83, list: 31.30, stock: 3, launched: '2021-02-02', tags: []}, {sku: 'C0170', cost: 85.90, list: 32.29, stock: 40, launched: '2022-03-03', tags: ['seasonal']}, {sku: 'C0171', cost: 86.97, list: 33.28, stock: 77, launched: '2023-04-04', tags: []}, {sku: 'C0172', cost: 87.04, list: 34.27, stock: 114, launched: '2024-05-05', tags: []}, {sku: 'C0173', cost: 88.11, list: 35.26, stock: 151, launched: '2025-06-06', tags: []}, {sku: 'C0174', cost: 89.18, list: 36.25, stock: 188, launched: '2020-07-07', tags: []}, {sku: 'C0175', cost: 90.25, list: 37.24, stock: 225, launched: '2021-08-08', tags: ['seasonal']}, {sku: 'C0176', cost: 91.32, list: 38.23, stock: 12, launched: '2022-09-09', tags: ['clearance']}, {sku: 'C0177', cost: 92.39, list: 39.22, stock: 49, launched: '2023-10-10', tags: []}, {sku: 'C0178', cost: 93.46, list: 40.21, stock: 86, launched: '2024-11-11', tags: []}, {sku: 'C0179', cost: 94.53, list: 41.20, stock: 123, launched: '2025-12-12', tags: []}, {sku: 'C0180', cost: 5.60, list: 42.19, stock: 160, launched: '2020-01-13', tags: ['seasonal']}, {sku: 'C0181', cost: 6.67, list: 43.18, stock: 197, launched: '2021-02-14', tags: []}, {sku: 'C0182', cost: 7.74, list: 44.17, stock: 234, launched: '2022-03-15', tags: []}, {sku: 'C0183', cost: 8.81, list: 45.16, stock: 21, launched: '2023-04-16', tags: []}, {sku: 'C0184', cost: 9.88, list: 46.15, stock: 58, launched: '2024-05-17', tags: []}, {sku: 'C0185', cost: 10.95, list: 47.14, stock: 95, launched: '2025-06-18', tags: ['seasonal']}, {sku: 'C0186', cost: 11.02, list: 48.13, stock: 132, launched: '2020-07-19', tags: []}, {sku: 'C0187', cost: 12.09, list: 49.12, stock: 169, launched: '2021-08-20', tags: ['clearance']}, {sku: 'C0188', cost: 13.16, list: 50.11, stock: 206, launched: '2022-09-21', tags: []}, {sku: 'C0189', cost: 14.23, list: 51.10, stock: 243, launched: '2023-10-22', tags: []}, {sku: 'C0190', cost: 15.30, list: 52.09, stock: 30, launched: '2024-11-23', tags: ['seasonal']}, {sku: 'C0191', cost: 16.37, list: 53.08, stock: 67, launched: '2025-12-24', tags: []}, {sku: 'C0192', cost: 17.44, list: 54.07, stock: 104, launched: '2020-01-25', tags: []}, {sku: 'C0193', cost: 18.51, list: 55.06, stock: 141, launched: '2021-02-26', tags: []}, {sku: 'C0194', cost: 19.58, list: 56.05, stock: 178, launched: '2022-03-27', tags: []}, {sku: 'C0195', cost: 20.65, list: 57.04, stock: 215, launched: '2023-04-28', tags: ['seasonal']}, {sku: 'C0196', cost: 21.72, list: 58.03, stock: 2, launched: '2024-05-01', tags: []}, {sku: 'C0197', cost: 22.79, list: 59.02, stock: 39, launched: '2025-06-02', tags: []}, {sku: 'C0198', cost: 23.86, list: 60.01, stock: 76, launched: '2020-07-03', tags: ['clearance']}, {sku: 'C0199', cost: 24.93, list: 61.00, stock: 113, launched: '2021-08-04', tags: []}]};92187.01 +sum(map(filter(products, 'clearance' in #.tags), #.stock * #.cost));{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}]};0.00 +sum(map(filter(products, 'clearance' in #.tags), #.stock * #.cost));{products: []};0 +sum(map(filter(products, 'clearance' in #.tags), #.stock * #.cost));{products: [{tags: ['clearance'], stock: 3, cost: 1.10}, {tags: ['CLEARANCE'], stock: 1, cost: 1}]};3.30 +map(products, max([#.cost, round(#.list * (1 - ('clearance' in #.tags ? 0.5 : d(today).diff(d(#.launched), 'month') >= 24 ? 0.3 : d(today).diff(d(#.launched), 'month') >= 12 ? 0.15 : 0)), 2)]));{today: '2025-03-20', products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}]};[6.50, 9.79, 10.48, 13.57, 16.95, 17.94, 13.25] +map(products, max([#.cost, round(#.list * (1 - ('clearance' in #.tags ? 0.5 : d(today).diff(d(#.launched), 'month') >= 24 ? 0.3 : d(today).diff(d(#.launched), 'month') >= 12 ? 0.15 : 0)), 2)]));{today: '2025-03-20', products: []};[] +map(products, max([#.cost, round(#.list * (1 - ('clearance' in #.tags ? 0.5 : d(today).diff(d(#.launched), 'month') >= 24 ? 0.3 : d(today).diff(d(#.launched), 'month') >= 12 ? 0.15 : 0)), 2)]));{today: '2025-03-20', products: [{cost: 5, list: 20, launched: '2024-03-20', tags: []}, {cost: 5, list: 20, launched: '2024-03-21', tags: []}]};[17.00, 20] +map(products, max([#.cost, round(#.list * (1 - ('clearance' in #.tags ? 0.5 : d(today).diff(d(#.launched), 'month') >= 24 ? 0.3 : d(today).diff(d(#.launched), 'month') >= 12 ? 0.15 : 0)), 2)]));{today: '2025-03-20', products: [{cost: 5, list: 20, launched: '2023-03-20', tags: []}, {cost: 15, list: 20, launched: '2025-01-01', tags: ['clearance']}]};[14.0, 15] +map(products, max([#.cost, round(#.list * (1 - ('clearance' in #.tags ? 0.5 : d(today).diff(d(#.launched), 'month') >= 24 ? 0.3 : d(today).diff(d(#.launched), 'month') >= 12 ? 0.15 : 0)), 2)]));{today: '2025-03-20', products: [{cost: 5, list: 20, launched: null, tags: []}]};!error +sum(map(products, #.stock));{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}, {sku: 'C0007', cost: 12.49, list: 19.92, stock: 9, launched: '2021-08-08', tags: []}, {sku: 'C0008', cost: 13.56, list: 20.91, stock: 46, launched: '2022-09-09', tags: []}, {sku: 'C0009', cost: 14.63, list: 21.90, stock: 83, launched: '2023-10-10', tags: []}, {sku: 'C0010', cost: 15.70, list: 22.89, stock: 120, launched: '2024-11-11', tags: ['seasonal']}, {sku: 'C0011', cost: 16.77, list: 23.88, stock: 157, launched: '2025-12-12', tags: ['clearance']}, {sku: 'C0012', cost: 17.84, list: 24.87, stock: 194, launched: '2020-01-13', tags: []}, {sku: 'C0013', cost: 18.91, list: 25.86, stock: 231, launched: '2021-02-14', tags: []}, {sku: 'C0014', cost: 19.98, list: 26.85, stock: 18, launched: '2022-03-15', tags: []}, {sku: 'C0015', cost: 20.05, list: 27.84, stock: 55, launched: '2023-04-16', tags: ['seasonal']}, {sku: 'C0016', cost: 21.12, list: 28.83, stock: 92, launched: '2024-05-17', tags: []}, {sku: 'C0017', cost: 22.19, list: 29.82, stock: 129, launched: '2025-06-18', tags: []}, {sku: 'C0018', cost: 23.26, list: 30.81, stock: 166, launched: '2020-07-19', tags: []}, {sku: 'C0019', cost: 24.33, list: 31.80, stock: 203, launched: '2021-08-20', tags: []}, {sku: 'C0020', cost: 25.40, list: 32.79, stock: 240, launched: '2022-09-21', tags: ['seasonal']}, {sku: 'C0021', cost: 26.47, list: 33.78, stock: 27, launched: '2023-10-22', tags: []}, {sku: 'C0022', cost: 27.54, list: 34.77, stock: 64, launched: '2024-11-23', tags: ['clearance']}, {sku: 'C0023', cost: 28.61, list: 35.76, stock: 101, launched: '2025-12-24', tags: []}, {sku: 'C0024', cost: 29.68, list: 36.75, stock: 138, launched: '2020-01-25', tags: []}, {sku: 'C0025', cost: 30.75, list: 37.74, stock: 175, launched: '2021-02-26', tags: ['seasonal']}, {sku: 'C0026', cost: 31.82, list: 38.73, stock: 212, launched: '2022-03-27', tags: []}, {sku: 'C0027', cost: 32.89, list: 39.72, stock: 249, launched: '2023-04-28', tags: []}, {sku: 'C0028', cost: 33.96, list: 40.71, stock: 36, launched: '2024-05-01', tags: []}, {sku: 'C0029', cost: 34.03, list: 41.70, stock: 73, launched: '2025-06-02', tags: []}, {sku: 'C0030', cost: 35.10, list: 42.69, stock: 110, launched: '2020-07-03', tags: ['seasonal']}, {sku: 'C0031', cost: 36.17, list: 43.68, stock: 147, launched: '2021-08-04', tags: []}, {sku: 'C0032', cost: 37.24, list: 44.67, stock: 184, launched: '2022-09-05', tags: []}, {sku: 'C0033', cost: 38.31, list: 45.66, stock: 221, launched: '2023-10-06', tags: ['clearance']}, {sku: 'C0034', cost: 39.38, list: 46.65, stock: 8, launched: '2024-11-07', tags: []}, {sku: 'C0035', cost: 40.45, list: 47.64, stock: 45, launched: '2025-12-08', tags: ['seasonal']}, {sku: 'C0036', cost: 41.52, list: 48.63, stock: 82, launched: '2020-01-09', tags: []}, {sku: 'C0037', cost: 42.59, list: 49.62, stock: 119, launched: '2021-02-10', tags: []}, {sku: 'C0038', cost: 43.66, list: 50.61, stock: 156, launched: '2022-03-11', tags: []}, {sku: 'C0039', cost: 44.73, list: 51.60, stock: 193, launched: '2023-04-12', tags: []}, {sku: 'C0040', cost: 45.80, list: 52.59, stock: 230, launched: '2024-05-13', tags: ['seasonal']}, {sku: 'C0041', cost: 46.87, list: 53.58, stock: 17, launched: '2025-06-14', tags: []}, {sku: 'C0042', cost: 47.94, list: 54.57, stock: 54, launched: '2020-07-15', tags: []}, {sku: 'C0043', cost: 48.01, list: 55.56, stock: 91, launched: '2021-08-16', tags: []}, {sku: 'C0044', cost: 49.08, list: 56.55, stock: 128, launched: '2022-09-17', tags: ['clearance']}, {sku: 'C0045', cost: 50.15, list: 57.54, stock: 165, launched: '2023-10-18', tags: ['seasonal']}, {sku: 'C0046', cost: 51.22, list: 58.53, stock: 202, launched: '2024-11-19', tags: []}, {sku: 'C0047', cost: 52.29, list: 59.52, stock: 239, launched: '2025-12-20', tags: []}, {sku: 'C0048', cost: 53.36, list: 60.51, stock: 26, launched: '2020-01-21', tags: []}, {sku: 'C0049', cost: 54.43, list: 61.50, stock: 63, launched: '2021-02-22', tags: []}, {sku: 'C0050', cost: 55.50, list: 62.49, stock: 100, launched: '2022-03-23', tags: ['seasonal']}, {sku: 'C0051', cost: 56.57, list: 63.48, stock: 137, launched: '2023-04-24', tags: []}, {sku: 'C0052', cost: 57.64, list: 64.47, stock: 174, launched: '2024-05-25', tags: []}, {sku: 'C0053', cost: 58.71, list: 65.46, stock: 211, launched: '2025-06-26', tags: []}, {sku: 'C0054', cost: 59.78, list: 66.45, stock: 248, launched: '2020-07-27', tags: []}, {sku: 'C0055', cost: 60.85, list: 67.44, stock: 35, launched: '2021-08-28', tags: ['clearance', 'seasonal']}, {sku: 'C0056', cost: 61.92, list: 68.43, stock: 72, launched: '2022-09-01', tags: []}, {sku: 'C0057', cost: 62.99, list: 69.42, stock: 109, launched: '2023-10-02', tags: []}, {sku: 'C0058', cost: 63.06, list: 70.41, stock: 146, launched: '2024-11-03', tags: []}, {sku: 'C0059', cost: 64.13, list: 71.40, stock: 183, launched: '2025-12-04', tags: []}, {sku: 'C0060', cost: 65.20, list: 72.39, stock: 220, launched: '2020-01-05', tags: ['seasonal']}, {sku: 'C0061', cost: 66.27, list: 73.38, stock: 7, launched: '2021-02-06', tags: []}, {sku: 'C0062', cost: 67.34, list: 74.37, stock: 44, launched: '2022-03-07', tags: []}, {sku: 'C0063', cost: 68.41, list: 75.36, stock: 81, launched: '2023-04-08', tags: []}, {sku: 'C0064', cost: 69.48, list: 76.35, stock: 118, launched: '2024-05-09', tags: []}, {sku: 'C0065', cost: 70.55, list: 77.34, stock: 155, launched: '2025-06-10', tags: ['seasonal']}, {sku: 'C0066', cost: 71.62, list: 78.33, stock: 192, launched: '2020-07-11', tags: ['clearance']}, {sku: 'C0067', cost: 72.69, list: 79.32, stock: 229, launched: '2021-08-12', tags: []}, {sku: 'C0068', cost: 73.76, list: 80.31, stock: 16, launched: '2022-09-13', tags: []}, {sku: 'C0069', cost: 74.83, list: 81.30, stock: 53, launched: '2023-10-14', tags: []}, {sku: 'C0070', cost: 75.90, list: 82.29, stock: 90, launched: '2024-11-15', tags: ['seasonal']}, {sku: 'C0071', cost: 76.97, list: 83.28, stock: 127, launched: '2025-12-16', tags: []}, {sku: 'C0072', cost: 77.04, list: 84.27, stock: 164, launched: '2020-01-17', tags: []}, {sku: 'C0073', cost: 78.11, list: 85.26, stock: 201, launched: '2021-02-18', tags: []}, {sku: 'C0074', cost: 79.18, list: 86.25, stock: 238, launched: '2022-03-19', tags: []}, {sku: 'C0075', cost: 80.25, list: 87.24, stock: 25, launched: '2023-04-20', tags: ['seasonal']}, {sku: 'C0076', cost: 81.32, list: 88.23, stock: 62, launched: '2024-05-21', tags: []}, {sku: 'C0077', cost: 82.39, list: 89.22, stock: 99, launched: '2025-06-22', tags: ['clearance']}, {sku: 'C0078', cost: 83.46, list: 90.21, stock: 136, launched: '2020-07-23', tags: []}, {sku: 'C0079', cost: 84.53, list: 91.20, stock: 173, launched: '2021-08-24', tags: []}, {sku: 'C0080', cost: 85.60, list: 92.19, stock: 210, launched: '2022-09-25', tags: ['seasonal']}, {sku: 'C0081', cost: 86.67, list: 93.18, stock: 247, launched: '2023-10-26', tags: []}, {sku: 'C0082', cost: 87.74, list: 94.17, stock: 34, launched: '2024-11-27', tags: []}, {sku: 'C0083', cost: 88.81, list: 95.16, stock: 71, launched: '2025-12-28', tags: []}, {sku: 'C0084', cost: 89.88, list: 96.15, stock: 108, launched: '2020-01-01', tags: []}, {sku: 'C0085', cost: 90.95, list: 97.14, stock: 145, launched: '2021-02-02', tags: ['seasonal']}, {sku: 'C0086', cost: 91.02, list: 98.13, stock: 182, launched: '2022-03-03', tags: []}, {sku: 'C0087', cost: 92.09, list: 99.12, stock: 219, launched: '2023-04-04', tags: []}, {sku: 'C0088', cost: 93.16, list: 100.11, stock: 6, launched: '2024-05-05', tags: ['clearance']}, {sku: 'C0089', cost: 94.23, list: 101.10, stock: 43, launched: '2025-06-06', tags: []}, {sku: 'C0090', cost: 5.30, list: 102.09, stock: 80, launched: '2020-07-07', tags: ['seasonal']}, {sku: 'C0091', cost: 6.37, list: 103.08, stock: 117, launched: '2021-08-08', tags: []}, {sku: 'C0092', cost: 7.44, list: 104.07, stock: 154, launched: '2022-09-09', tags: []}, {sku: 'C0093', cost: 8.51, list: 105.06, stock: 191, launched: '2023-10-10', tags: []}, {sku: 'C0094', cost: 9.58, list: 106.05, stock: 228, launched: '2024-11-11', tags: []}, {sku: 'C0095', cost: 10.65, list: 107.04, stock: 15, launched: '2025-12-12', tags: ['seasonal']}, {sku: 'C0096', cost: 11.72, list: 108.03, stock: 52, launched: '2020-01-13', tags: []}, {sku: 'C0097', cost: 12.79, list: 109.02, stock: 89, launched: '2021-02-14', tags: []}, {sku: 'C0098', cost: 13.86, list: 110.01, stock: 126, launched: '2022-03-15', tags: []}, {sku: 'C0099', cost: 14.93, list: 111.00, stock: 163, launched: '2023-04-16', tags: ['clearance']}, {sku: 'C0100', cost: 15.00, list: 112.99, stock: 200, launched: '2024-05-17', tags: ['seasonal']}, {sku: 'C0101', cost: 16.07, list: 113.98, stock: 237, launched: '2025-06-18', tags: []}, {sku: 'C0102', cost: 17.14, list: 114.97, stock: 24, launched: '2020-07-19', tags: []}, {sku: 'C0103', cost: 18.21, list: 115.96, stock: 61, launched: '2021-08-20', tags: []}, {sku: 'C0104', cost: 19.28, list: 116.95, stock: 98, launched: '2022-09-21', tags: []}, {sku: 'C0105', cost: 20.35, list: 117.94, stock: 135, launched: '2023-10-22', tags: ['seasonal']}, {sku: 'C0106', cost: 21.42, list: 118.93, stock: 172, launched: '2024-11-23', tags: []}, {sku: 'C0107', cost: 22.49, list: 119.92, stock: 209, launched: '2025-12-24', tags: []}, {sku: 'C0108', cost: 23.56, list: 120.91, stock: 246, launched: '2020-01-25', tags: []}, {sku: 'C0109', cost: 24.63, list: 121.90, stock: 33, launched: '2021-02-26', tags: []}, {sku: 'C0110', cost: 25.70, list: 122.89, stock: 70, launched: '2022-03-27', tags: ['clearance', 'seasonal']}, {sku: 'C0111', cost: 26.77, list: 123.88, stock: 107, launched: '2023-04-28', tags: []}, {sku: 'C0112', cost: 27.84, list: 124.87, stock: 144, launched: '2024-05-01', tags: []}, {sku: 'C0113', cost: 28.91, list: 125.86, stock: 181, launched: '2025-06-02', tags: []}, {sku: 'C0114', cost: 29.98, list: 126.85, stock: 218, launched: '2020-07-03', tags: []}, {sku: 'C0115', cost: 30.05, list: 127.84, stock: 5, launched: '2021-08-04', tags: ['seasonal']}, {sku: 'C0116', cost: 31.12, list: 128.83, stock: 42, launched: '2022-09-05', tags: []}, {sku: 'C0117', cost: 32.19, list: 129.82, stock: 79, launched: '2023-10-06', tags: []}, {sku: 'C0118', cost: 33.26, list: 130.81, stock: 116, launched: '2024-11-07', tags: []}, {sku: 'C0119', cost: 34.33, list: 131.80, stock: 153, launched: '2025-12-08', tags: []}, {sku: 'C0120', cost: 35.40, list: 132.79, stock: 190, launched: '2020-01-09', tags: ['seasonal']}, {sku: 'C0121', cost: 36.47, list: 133.78, stock: 227, launched: '2021-02-10', tags: ['clearance']}, {sku: 'C0122', cost: 37.54, list: 134.77, stock: 14, launched: '2022-03-11', tags: []}, {sku: 'C0123', cost: 38.61, list: 135.76, stock: 51, launched: '2023-04-12', tags: []}, {sku: 'C0124', cost: 39.68, list: 136.75, stock: 88, launched: '2024-05-13', tags: []}, {sku: 'C0125', cost: 40.75, list: 137.74, stock: 125, launched: '2025-06-14', tags: ['seasonal']}, {sku: 'C0126', cost: 41.82, list: 138.73, stock: 162, launched: '2020-07-15', tags: []}, {sku: 'C0127', cost: 42.89, list: 139.72, stock: 199, launched: '2021-08-16', tags: []}, {sku: 'C0128', cost: 43.96, list: 140.71, stock: 236, launched: '2022-09-17', tags: []}, {sku: 'C0129', cost: 44.03, list: 141.70, stock: 23, launched: '2023-10-18', tags: []}, {sku: 'C0130', cost: 45.10, list: 142.69, stock: 60, launched: '2024-11-19', tags: ['seasonal']}, {sku: 'C0131', cost: 46.17, list: 143.68, stock: 97, launched: '2025-12-20', tags: []}, {sku: 'C0132', cost: 47.24, list: 144.67, stock: 134, launched: '2020-01-21', tags: ['clearance']}, {sku: 'C0133', cost: 48.31, list: 145.66, stock: 171, launched: '2021-02-22', tags: []}, {sku: 'C0134', cost: 49.38, list: 146.65, stock: 208, launched: '2022-03-23', tags: []}, {sku: 'C0135', cost: 50.45, list: 147.64, stock: 245, launched: '2023-04-24', tags: ['seasonal']}, {sku: 'C0136', cost: 51.52, list: 148.63, stock: 32, launched: '2024-05-25', tags: []}, {sku: 'C0137', cost: 52.59, list: 149.62, stock: 69, launched: '2025-06-26', tags: []}, {sku: 'C0138', cost: 53.66, list: 150.61, stock: 106, launched: '2020-07-27', tags: []}, {sku: 'C0139', cost: 54.73, list: 151.60, stock: 143, launched: '2021-08-28', tags: []}, {sku: 'C0140', cost: 55.80, list: 152.59, stock: 180, launched: '2022-09-01', tags: ['seasonal']}, {sku: 'C0141', cost: 56.87, list: 153.58, stock: 217, launched: '2023-10-02', tags: []}, {sku: 'C0142', cost: 57.94, list: 154.57, stock: 4, launched: '2024-11-03', tags: []}, {sku: 'C0143', cost: 58.01, list: 155.56, stock: 41, launched: '2025-12-04', tags: ['clearance']}, {sku: 'C0144', cost: 59.08, list: 156.55, stock: 78, launched: '2020-01-05', tags: []}, {sku: 'C0145', cost: 60.15, list: 157.54, stock: 115, launched: '2021-02-06', tags: ['seasonal']}, {sku: 'C0146', cost: 61.22, list: 158.53, stock: 152, launched: '2022-03-07', tags: []}, {sku: 'C0147', cost: 62.29, list: 159.52, stock: 189, launched: '2023-04-08', tags: []}, {sku: 'C0148', cost: 63.36, list: 160.51, stock: 226, launched: '2024-05-09', tags: []}, {sku: 'C0149', cost: 64.43, list: 161.50, stock: 13, launched: '2025-06-10', tags: []}, {sku: 'C0150', cost: 65.50, list: 12.49, stock: 50, launched: '2020-07-11', tags: ['seasonal']}, {sku: 'C0151', cost: 66.57, list: 13.48, stock: 87, launched: '2021-08-12', tags: []}, {sku: 'C0152', cost: 67.64, list: 14.47, stock: 124, launched: '2022-09-13', tags: []}, {sku: 'C0153', cost: 68.71, list: 15.46, stock: 161, launched: '2023-10-14', tags: []}, {sku: 'C0154', cost: 69.78, list: 16.45, stock: 198, launched: '2024-11-15', tags: ['clearance']}, {sku: 'C0155', cost: 70.85, list: 17.44, stock: 235, launched: '2025-12-16', tags: ['seasonal']}, {sku: 'C0156', cost: 71.92, list: 18.43, stock: 22, launched: '2020-01-17', tags: []}, {sku: 'C0157', cost: 72.99, list: 19.42, stock: 59, launched: '2021-02-18', tags: []}, {sku: 'C0158', cost: 73.06, list: 20.41, stock: 96, launched: '2022-03-19', tags: []}, {sku: 'C0159', cost: 74.13, list: 21.40, stock: 133, launched: '2023-04-20', tags: []}, {sku: 'C0160', cost: 75.20, list: 22.39, stock: 170, launched: '2024-05-21', tags: ['seasonal']}, {sku: 'C0161', cost: 76.27, list: 23.38, stock: 207, launched: '2025-06-22', tags: []}, {sku: 'C0162', cost: 77.34, list: 24.37, stock: 244, launched: '2020-07-23', tags: []}, {sku: 'C0163', cost: 78.41, list: 25.36, stock: 31, launched: '2021-08-24', tags: []}, {sku: 'C0164', cost: 79.48, list: 26.35, stock: 68, launched: '2022-09-25', tags: []}, {sku: 'C0165', cost: 80.55, list: 27.34, stock: 105, launched: '2023-10-26', tags: ['clearance', 'seasonal']}, {sku: 'C0166', cost: 81.62, list: 28.33, stock: 142, launched: '2024-11-27', tags: []}, {sku: 'C0167', cost: 82.69, list: 29.32, stock: 179, launched: '2025-12-28', tags: []}, {sku: 'C0168', cost: 83.76, list: 30.31, stock: 216, launched: '2020-01-01', tags: []}, {sku: 'C0169', cost: 84.83, list: 31.30, stock: 3, launched: '2021-02-02', tags: []}, {sku: 'C0170', cost: 85.90, list: 32.29, stock: 40, launched: '2022-03-03', tags: ['seasonal']}, {sku: 'C0171', cost: 86.97, list: 33.28, stock: 77, launched: '2023-04-04', tags: []}, {sku: 'C0172', cost: 87.04, list: 34.27, stock: 114, launched: '2024-05-05', tags: []}, {sku: 'C0173', cost: 88.11, list: 35.26, stock: 151, launched: '2025-06-06', tags: []}, {sku: 'C0174', cost: 89.18, list: 36.25, stock: 188, launched: '2020-07-07', tags: []}, {sku: 'C0175', cost: 90.25, list: 37.24, stock: 225, launched: '2021-08-08', tags: ['seasonal']}, {sku: 'C0176', cost: 91.32, list: 38.23, stock: 12, launched: '2022-09-09', tags: ['clearance']}, {sku: 'C0177', cost: 92.39, list: 39.22, stock: 49, launched: '2023-10-10', tags: []}, {sku: 'C0178', cost: 93.46, list: 40.21, stock: 86, launched: '2024-11-11', tags: []}, {sku: 'C0179', cost: 94.53, list: 41.20, stock: 123, launched: '2025-12-12', tags: []}, {sku: 'C0180', cost: 5.60, list: 42.19, stock: 160, launched: '2020-01-13', tags: ['seasonal']}, {sku: 'C0181', cost: 6.67, list: 43.18, stock: 197, launched: '2021-02-14', tags: []}, {sku: 'C0182', cost: 7.74, list: 44.17, stock: 234, launched: '2022-03-15', tags: []}, {sku: 'C0183', cost: 8.81, list: 45.16, stock: 21, launched: '2023-04-16', tags: []}, {sku: 'C0184', cost: 9.88, list: 46.15, stock: 58, launched: '2024-05-17', tags: []}, {sku: 'C0185', cost: 10.95, list: 47.14, stock: 95, launched: '2025-06-18', tags: ['seasonal']}, {sku: 'C0186', cost: 11.02, list: 48.13, stock: 132, launched: '2020-07-19', tags: []}, {sku: 'C0187', cost: 12.09, list: 49.12, stock: 169, launched: '2021-08-20', tags: ['clearance']}, {sku: 'C0188', cost: 13.16, list: 50.11, stock: 206, launched: '2022-09-21', tags: []}, {sku: 'C0189', cost: 14.23, list: 51.10, stock: 243, launched: '2023-10-22', tags: []}, {sku: 'C0190', cost: 15.30, list: 52.09, stock: 30, launched: '2024-11-23', tags: ['seasonal']}, {sku: 'C0191', cost: 16.37, list: 53.08, stock: 67, launched: '2025-12-24', tags: []}, {sku: 'C0192', cost: 17.44, list: 54.07, stock: 104, launched: '2020-01-25', tags: []}, {sku: 'C0193', cost: 18.51, list: 55.06, stock: 141, launched: '2021-02-26', tags: []}, {sku: 'C0194', cost: 19.58, list: 56.05, stock: 178, launched: '2022-03-27', tags: []}, {sku: 'C0195', cost: 20.65, list: 57.04, stock: 215, launched: '2023-04-28', tags: ['seasonal']}, {sku: 'C0196', cost: 21.72, list: 58.03, stock: 2, launched: '2024-05-01', tags: []}, {sku: 'C0197', cost: 22.79, list: 59.02, stock: 39, launched: '2025-06-02', tags: []}, {sku: 'C0198', cost: 23.86, list: 60.01, stock: 76, launched: '2020-07-03', tags: ['clearance']}, {sku: 'C0199', cost: 24.93, list: 61.00, stock: 113, launched: '2021-08-04', tags: []}]};24800 +sum(map(products, #.stock));{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}]};777 +sum(map(products, #.stock));{products: []};0 +len(filter(products, #.stock == 0)) / len(products);{products: [{sku: 'C0000', cost: 5.00, list: 12.99, stock: 0, launched: '2020-01-01', tags: ['clearance', 'seasonal']}, {sku: 'C0001', cost: 6.07, list: 13.98, stock: 37, launched: '2021-02-02', tags: []}, {sku: 'C0002', cost: 7.14, list: 14.97, stock: 74, launched: '2022-03-03', tags: []}, {sku: 'C0003', cost: 8.21, list: 15.96, stock: 111, launched: '2023-04-04', tags: []}, {sku: 'C0004', cost: 9.28, list: 16.95, stock: 148, launched: '2024-05-05', tags: []}, {sku: 'C0005', cost: 10.35, list: 17.94, stock: 185, launched: '2025-06-06', tags: ['seasonal']}, {sku: 'C0006', cost: 11.42, list: 18.93, stock: 222, launched: '2020-07-07', tags: []}, {sku: 'C0007', cost: 12.49, list: 19.92, stock: 9, launched: '2021-08-08', tags: []}, {sku: 'C0008', cost: 13.56, list: 20.91, stock: 46, launched: '2022-09-09', tags: []}, {sku: 'C0009', cost: 14.63, list: 21.90, stock: 83, launched: '2023-10-10', tags: []}, {sku: 'C0010', cost: 15.70, list: 22.89, stock: 120, launched: '2024-11-11', tags: ['seasonal']}, {sku: 'C0011', cost: 16.77, list: 23.88, stock: 157, launched: '2025-12-12', tags: ['clearance']}, {sku: 'C0012', cost: 17.84, list: 24.87, stock: 194, launched: '2020-01-13', tags: []}, {sku: 'C0013', cost: 18.91, list: 25.86, stock: 231, launched: '2021-02-14', tags: []}, {sku: 'C0014', cost: 19.98, list: 26.85, stock: 18, launched: '2022-03-15', tags: []}, {sku: 'C0015', cost: 20.05, list: 27.84, stock: 55, launched: '2023-04-16', tags: ['seasonal']}, {sku: 'C0016', cost: 21.12, list: 28.83, stock: 92, launched: '2024-05-17', tags: []}, {sku: 'C0017', cost: 22.19, list: 29.82, stock: 129, launched: '2025-06-18', tags: []}, {sku: 'C0018', cost: 23.26, list: 30.81, stock: 166, launched: '2020-07-19', tags: []}, {sku: 'C0019', cost: 24.33, list: 31.80, stock: 203, launched: '2021-08-20', tags: []}, {sku: 'C0020', cost: 25.40, list: 32.79, stock: 240, launched: '2022-09-21', tags: ['seasonal']}, {sku: 'C0021', cost: 26.47, list: 33.78, stock: 27, launched: '2023-10-22', tags: []}, {sku: 'C0022', cost: 27.54, list: 34.77, stock: 64, launched: '2024-11-23', tags: ['clearance']}, {sku: 'C0023', cost: 28.61, list: 35.76, stock: 101, launched: '2025-12-24', tags: []}, {sku: 'C0024', cost: 29.68, list: 36.75, stock: 138, launched: '2020-01-25', tags: []}, {sku: 'C0025', cost: 30.75, list: 37.74, stock: 175, launched: '2021-02-26', tags: ['seasonal']}, {sku: 'C0026', cost: 31.82, list: 38.73, stock: 212, launched: '2022-03-27', tags: []}, {sku: 'C0027', cost: 32.89, list: 39.72, stock: 249, launched: '2023-04-28', tags: []}, {sku: 'C0028', cost: 33.96, list: 40.71, stock: 36, launched: '2024-05-01', tags: []}, {sku: 'C0029', cost: 34.03, list: 41.70, stock: 73, launched: '2025-06-02', tags: []}, {sku: 'C0030', cost: 35.10, list: 42.69, stock: 110, launched: '2020-07-03', tags: ['seasonal']}, {sku: 'C0031', cost: 36.17, list: 43.68, stock: 147, launched: '2021-08-04', tags: []}, {sku: 'C0032', cost: 37.24, list: 44.67, stock: 184, launched: '2022-09-05', tags: []}, {sku: 'C0033', cost: 38.31, list: 45.66, stock: 221, launched: '2023-10-06', tags: ['clearance']}, {sku: 'C0034', cost: 39.38, list: 46.65, stock: 8, launched: '2024-11-07', tags: []}, {sku: 'C0035', cost: 40.45, list: 47.64, stock: 45, launched: '2025-12-08', tags: ['seasonal']}, {sku: 'C0036', cost: 41.52, list: 48.63, stock: 82, launched: '2020-01-09', tags: []}, {sku: 'C0037', cost: 42.59, list: 49.62, stock: 119, launched: '2021-02-10', tags: []}, {sku: 'C0038', cost: 43.66, list: 50.61, stock: 156, launched: '2022-03-11', tags: []}, {sku: 'C0039', cost: 44.73, list: 51.60, stock: 193, launched: '2023-04-12', tags: []}, {sku: 'C0040', cost: 45.80, list: 52.59, stock: 230, launched: '2024-05-13', tags: ['seasonal']}, {sku: 'C0041', cost: 46.87, list: 53.58, stock: 17, launched: '2025-06-14', tags: []}, {sku: 'C0042', cost: 47.94, list: 54.57, stock: 54, launched: '2020-07-15', tags: []}, {sku: 'C0043', cost: 48.01, list: 55.56, stock: 91, launched: '2021-08-16', tags: []}, {sku: 'C0044', cost: 49.08, list: 56.55, stock: 128, launched: '2022-09-17', tags: ['clearance']}, {sku: 'C0045', cost: 50.15, list: 57.54, stock: 165, launched: '2023-10-18', tags: ['seasonal']}, {sku: 'C0046', cost: 51.22, list: 58.53, stock: 202, launched: '2024-11-19', tags: []}, {sku: 'C0047', cost: 52.29, list: 59.52, stock: 239, launched: '2025-12-20', tags: []}, {sku: 'C0048', cost: 53.36, list: 60.51, stock: 26, launched: '2020-01-21', tags: []}, {sku: 'C0049', cost: 54.43, list: 61.50, stock: 63, launched: '2021-02-22', tags: []}, {sku: 'C0050', cost: 55.50, list: 62.49, stock: 100, launched: '2022-03-23', tags: ['seasonal']}, {sku: 'C0051', cost: 56.57, list: 63.48, stock: 137, launched: '2023-04-24', tags: []}, {sku: 'C0052', cost: 57.64, list: 64.47, stock: 174, launched: '2024-05-25', tags: []}, {sku: 'C0053', cost: 58.71, list: 65.46, stock: 211, launched: '2025-06-26', tags: []}, {sku: 'C0054', cost: 59.78, list: 66.45, stock: 248, launched: '2020-07-27', tags: []}, {sku: 'C0055', cost: 60.85, list: 67.44, stock: 35, launched: '2021-08-28', tags: ['clearance', 'seasonal']}, {sku: 'C0056', cost: 61.92, list: 68.43, stock: 72, launched: '2022-09-01', tags: []}, {sku: 'C0057', cost: 62.99, list: 69.42, stock: 109, launched: '2023-10-02', tags: []}, {sku: 'C0058', cost: 63.06, list: 70.41, stock: 146, launched: '2024-11-03', tags: []}, {sku: 'C0059', cost: 64.13, list: 71.40, stock: 183, launched: '2025-12-04', tags: []}, {sku: 'C0060', cost: 65.20, list: 72.39, stock: 220, launched: '2020-01-05', tags: ['seasonal']}, {sku: 'C0061', cost: 66.27, list: 73.38, stock: 7, launched: '2021-02-06', tags: []}, {sku: 'C0062', cost: 67.34, list: 74.37, stock: 44, launched: '2022-03-07', tags: []}, {sku: 'C0063', cost: 68.41, list: 75.36, stock: 81, launched: '2023-04-08', tags: []}, {sku: 'C0064', cost: 69.48, list: 76.35, stock: 118, launched: '2024-05-09', tags: []}, {sku: 'C0065', cost: 70.55, list: 77.34, stock: 155, launched: '2025-06-10', tags: ['seasonal']}, {sku: 'C0066', cost: 71.62, list: 78.33, stock: 192, launched: '2020-07-11', tags: ['clearance']}, {sku: 'C0067', cost: 72.69, list: 79.32, stock: 229, launched: '2021-08-12', tags: []}, {sku: 'C0068', cost: 73.76, list: 80.31, stock: 16, launched: '2022-09-13', tags: []}, {sku: 'C0069', cost: 74.83, list: 81.30, stock: 53, launched: '2023-10-14', tags: []}, {sku: 'C0070', cost: 75.90, list: 82.29, stock: 90, launched: '2024-11-15', tags: ['seasonal']}, {sku: 'C0071', cost: 76.97, list: 83.28, stock: 127, launched: '2025-12-16', tags: []}, {sku: 'C0072', cost: 77.04, list: 84.27, stock: 164, launched: '2020-01-17', tags: []}, {sku: 'C0073', cost: 78.11, list: 85.26, stock: 201, launched: '2021-02-18', tags: []}, {sku: 'C0074', cost: 79.18, list: 86.25, stock: 238, launched: '2022-03-19', tags: []}, {sku: 'C0075', cost: 80.25, list: 87.24, stock: 25, launched: '2023-04-20', tags: ['seasonal']}, {sku: 'C0076', cost: 81.32, list: 88.23, stock: 62, launched: '2024-05-21', tags: []}, {sku: 'C0077', cost: 82.39, list: 89.22, stock: 99, launched: '2025-06-22', tags: ['clearance']}, {sku: 'C0078', cost: 83.46, list: 90.21, stock: 136, launched: '2020-07-23', tags: []}, {sku: 'C0079', cost: 84.53, list: 91.20, stock: 173, launched: '2021-08-24', tags: []}, {sku: 'C0080', cost: 85.60, list: 92.19, stock: 210, launched: '2022-09-25', tags: ['seasonal']}, {sku: 'C0081', cost: 86.67, list: 93.18, stock: 247, launched: '2023-10-26', tags: []}, {sku: 'C0082', cost: 87.74, list: 94.17, stock: 34, launched: '2024-11-27', tags: []}, {sku: 'C0083', cost: 88.81, list: 95.16, stock: 71, launched: '2025-12-28', tags: []}, {sku: 'C0084', cost: 89.88, list: 96.15, stock: 108, launched: '2020-01-01', tags: []}, {sku: 'C0085', cost: 90.95, list: 97.14, stock: 145, launched: '2021-02-02', tags: ['seasonal']}, {sku: 'C0086', cost: 91.02, list: 98.13, stock: 182, launched: '2022-03-03', tags: []}, {sku: 'C0087', cost: 92.09, list: 99.12, stock: 219, launched: '2023-04-04', tags: []}, {sku: 'C0088', cost: 93.16, list: 100.11, stock: 6, launched: '2024-05-05', tags: ['clearance']}, {sku: 'C0089', cost: 94.23, list: 101.10, stock: 43, launched: '2025-06-06', tags: []}, {sku: 'C0090', cost: 5.30, list: 102.09, stock: 80, launched: '2020-07-07', tags: ['seasonal']}, {sku: 'C0091', cost: 6.37, list: 103.08, stock: 117, launched: '2021-08-08', tags: []}, {sku: 'C0092', cost: 7.44, list: 104.07, stock: 154, launched: '2022-09-09', tags: []}, {sku: 'C0093', cost: 8.51, list: 105.06, stock: 191, launched: '2023-10-10', tags: []}, {sku: 'C0094', cost: 9.58, list: 106.05, stock: 228, launched: '2024-11-11', tags: []}, {sku: 'C0095', cost: 10.65, list: 107.04, stock: 15, launched: '2025-12-12', tags: ['seasonal']}, {sku: 'C0096', cost: 11.72, list: 108.03, stock: 52, launched: '2020-01-13', tags: []}, {sku: 'C0097', cost: 12.79, list: 109.02, stock: 89, launched: '2021-02-14', tags: []}, {sku: 'C0098', cost: 13.86, list: 110.01, stock: 126, launched: '2022-03-15', tags: []}, {sku: 'C0099', cost: 14.93, list: 111.00, stock: 163, launched: '2023-04-16', tags: ['clearance']}, {sku: 'C0100', cost: 15.00, list: 112.99, stock: 200, launched: '2024-05-17', tags: ['seasonal']}, {sku: 'C0101', cost: 16.07, list: 113.98, stock: 237, launched: '2025-06-18', tags: []}, {sku: 'C0102', cost: 17.14, list: 114.97, stock: 24, launched: '2020-07-19', tags: []}, {sku: 'C0103', cost: 18.21, list: 115.96, stock: 61, launched: '2021-08-20', tags: []}, {sku: 'C0104', cost: 19.28, list: 116.95, stock: 98, launched: '2022-09-21', tags: []}, {sku: 'C0105', cost: 20.35, list: 117.94, stock: 135, launched: '2023-10-22', tags: ['seasonal']}, {sku: 'C0106', cost: 21.42, list: 118.93, stock: 172, launched: '2024-11-23', tags: []}, {sku: 'C0107', cost: 22.49, list: 119.92, stock: 209, launched: '2025-12-24', tags: []}, {sku: 'C0108', cost: 23.56, list: 120.91, stock: 246, launched: '2020-01-25', tags: []}, {sku: 'C0109', cost: 24.63, list: 121.90, stock: 33, launched: '2021-02-26', tags: []}, {sku: 'C0110', cost: 25.70, list: 122.89, stock: 70, launched: '2022-03-27', tags: ['clearance', 'seasonal']}, {sku: 'C0111', cost: 26.77, list: 123.88, stock: 107, launched: '2023-04-28', tags: []}, {sku: 'C0112', cost: 27.84, list: 124.87, stock: 144, launched: '2024-05-01', tags: []}, {sku: 'C0113', cost: 28.91, list: 125.86, stock: 181, launched: '2025-06-02', tags: []}, {sku: 'C0114', cost: 29.98, list: 126.85, stock: 218, launched: '2020-07-03', tags: []}, {sku: 'C0115', cost: 30.05, list: 127.84, stock: 5, launched: '2021-08-04', tags: ['seasonal']}, {sku: 'C0116', cost: 31.12, list: 128.83, stock: 42, launched: '2022-09-05', tags: []}, {sku: 'C0117', cost: 32.19, list: 129.82, stock: 79, launched: '2023-10-06', tags: []}, {sku: 'C0118', cost: 33.26, list: 130.81, stock: 116, launched: '2024-11-07', tags: []}, {sku: 'C0119', cost: 34.33, list: 131.80, stock: 153, launched: '2025-12-08', tags: []}, {sku: 'C0120', cost: 35.40, list: 132.79, stock: 190, launched: '2020-01-09', tags: ['seasonal']}, {sku: 'C0121', cost: 36.47, list: 133.78, stock: 227, launched: '2021-02-10', tags: ['clearance']}, {sku: 'C0122', cost: 37.54, list: 134.77, stock: 14, launched: '2022-03-11', tags: []}, {sku: 'C0123', cost: 38.61, list: 135.76, stock: 51, launched: '2023-04-12', tags: []}, {sku: 'C0124', cost: 39.68, list: 136.75, stock: 88, launched: '2024-05-13', tags: []}, {sku: 'C0125', cost: 40.75, list: 137.74, stock: 125, launched: '2025-06-14', tags: ['seasonal']}, {sku: 'C0126', cost: 41.82, list: 138.73, stock: 162, launched: '2020-07-15', tags: []}, {sku: 'C0127', cost: 42.89, list: 139.72, stock: 199, launched: '2021-08-16', tags: []}, {sku: 'C0128', cost: 43.96, list: 140.71, stock: 236, launched: '2022-09-17', tags: []}, {sku: 'C0129', cost: 44.03, list: 141.70, stock: 23, launched: '2023-10-18', tags: []}, {sku: 'C0130', cost: 45.10, list: 142.69, stock: 60, launched: '2024-11-19', tags: ['seasonal']}, {sku: 'C0131', cost: 46.17, list: 143.68, stock: 97, launched: '2025-12-20', tags: []}, {sku: 'C0132', cost: 47.24, list: 144.67, stock: 134, launched: '2020-01-21', tags: ['clearance']}, {sku: 'C0133', cost: 48.31, list: 145.66, stock: 171, launched: '2021-02-22', tags: []}, {sku: 'C0134', cost: 49.38, list: 146.65, stock: 208, launched: '2022-03-23', tags: []}, {sku: 'C0135', cost: 50.45, list: 147.64, stock: 245, launched: '2023-04-24', tags: ['seasonal']}, {sku: 'C0136', cost: 51.52, list: 148.63, stock: 32, launched: '2024-05-25', tags: []}, {sku: 'C0137', cost: 52.59, list: 149.62, stock: 69, launched: '2025-06-26', tags: []}, {sku: 'C0138', cost: 53.66, list: 150.61, stock: 106, launched: '2020-07-27', tags: []}, {sku: 'C0139', cost: 54.73, list: 151.60, stock: 143, launched: '2021-08-28', tags: []}, {sku: 'C0140', cost: 55.80, list: 152.59, stock: 180, launched: '2022-09-01', tags: ['seasonal']}, {sku: 'C0141', cost: 56.87, list: 153.58, stock: 217, launched: '2023-10-02', tags: []}, {sku: 'C0142', cost: 57.94, list: 154.57, stock: 4, launched: '2024-11-03', tags: []}, {sku: 'C0143', cost: 58.01, list: 155.56, stock: 41, launched: '2025-12-04', tags: ['clearance']}, {sku: 'C0144', cost: 59.08, list: 156.55, stock: 78, launched: '2020-01-05', tags: []}, {sku: 'C0145', cost: 60.15, list: 157.54, stock: 115, launched: '2021-02-06', tags: ['seasonal']}, {sku: 'C0146', cost: 61.22, list: 158.53, stock: 152, launched: '2022-03-07', tags: []}, {sku: 'C0147', cost: 62.29, list: 159.52, stock: 189, launched: '2023-04-08', tags: []}, {sku: 'C0148', cost: 63.36, list: 160.51, stock: 226, launched: '2024-05-09', tags: []}, {sku: 'C0149', cost: 64.43, list: 161.50, stock: 13, launched: '2025-06-10', tags: []}, {sku: 'C0150', cost: 65.50, list: 12.49, stock: 50, launched: '2020-07-11', tags: ['seasonal']}, {sku: 'C0151', cost: 66.57, list: 13.48, stock: 87, launched: '2021-08-12', tags: []}, {sku: 'C0152', cost: 67.64, list: 14.47, stock: 124, launched: '2022-09-13', tags: []}, {sku: 'C0153', cost: 68.71, list: 15.46, stock: 161, launched: '2023-10-14', tags: []}, {sku: 'C0154', cost: 69.78, list: 16.45, stock: 198, launched: '2024-11-15', tags: ['clearance']}, {sku: 'C0155', cost: 70.85, list: 17.44, stock: 235, launched: '2025-12-16', tags: ['seasonal']}, {sku: 'C0156', cost: 71.92, list: 18.43, stock: 22, launched: '2020-01-17', tags: []}, {sku: 'C0157', cost: 72.99, list: 19.42, stock: 59, launched: '2021-02-18', tags: []}, {sku: 'C0158', cost: 73.06, list: 20.41, stock: 96, launched: '2022-03-19', tags: []}, {sku: 'C0159', cost: 74.13, list: 21.40, stock: 133, launched: '2023-04-20', tags: []}, {sku: 'C0160', cost: 75.20, list: 22.39, stock: 170, launched: '2024-05-21', tags: ['seasonal']}, {sku: 'C0161', cost: 76.27, list: 23.38, stock: 207, launched: '2025-06-22', tags: []}, {sku: 'C0162', cost: 77.34, list: 24.37, stock: 244, launched: '2020-07-23', tags: []}, {sku: 'C0163', cost: 78.41, list: 25.36, stock: 31, launched: '2021-08-24', tags: []}, {sku: 'C0164', cost: 79.48, list: 26.35, stock: 68, launched: '2022-09-25', tags: []}, {sku: 'C0165', cost: 80.55, list: 27.34, stock: 105, launched: '2023-10-26', tags: ['clearance', 'seasonal']}, {sku: 'C0166', cost: 81.62, list: 28.33, stock: 142, launched: '2024-11-27', tags: []}, {sku: 'C0167', cost: 82.69, list: 29.32, stock: 179, launched: '2025-12-28', tags: []}, {sku: 'C0168', cost: 83.76, list: 30.31, stock: 216, launched: '2020-01-01', tags: []}, {sku: 'C0169', cost: 84.83, list: 31.30, stock: 3, launched: '2021-02-02', tags: []}, {sku: 'C0170', cost: 85.90, list: 32.29, stock: 40, launched: '2022-03-03', tags: ['seasonal']}, {sku: 'C0171', cost: 86.97, list: 33.28, stock: 77, launched: '2023-04-04', tags: []}, {sku: 'C0172', cost: 87.04, list: 34.27, stock: 114, launched: '2024-05-05', tags: []}, {sku: 'C0173', cost: 88.11, list: 35.26, stock: 151, launched: '2025-06-06', tags: []}, {sku: 'C0174', cost: 89.18, list: 36.25, stock: 188, launched: '2020-07-07', tags: []}, {sku: 'C0175', cost: 90.25, list: 37.24, stock: 225, launched: '2021-08-08', tags: ['seasonal']}, {sku: 'C0176', cost: 91.32, list: 38.23, stock: 12, launched: '2022-09-09', tags: ['clearance']}, {sku: 'C0177', cost: 92.39, list: 39.22, stock: 49, launched: '2023-10-10', tags: []}, {sku: 'C0178', cost: 93.46, list: 40.21, stock: 86, launched: '2024-11-11', tags: []}, {sku: 'C0179', cost: 94.53, list: 41.20, stock: 123, launched: '2025-12-12', tags: []}, {sku: 'C0180', cost: 5.60, list: 42.19, stock: 160, launched: '2020-01-13', tags: ['seasonal']}, {sku: 'C0181', cost: 6.67, list: 43.18, stock: 197, launched: '2021-02-14', tags: []}, {sku: 'C0182', cost: 7.74, list: 44.17, stock: 234, launched: '2022-03-15', tags: []}, {sku: 'C0183', cost: 8.81, list: 45.16, stock: 21, launched: '2023-04-16', tags: []}, {sku: 'C0184', cost: 9.88, list: 46.15, stock: 58, launched: '2024-05-17', tags: []}, {sku: 'C0185', cost: 10.95, list: 47.14, stock: 95, launched: '2025-06-18', tags: ['seasonal']}, {sku: 'C0186', cost: 11.02, list: 48.13, stock: 132, launched: '2020-07-19', tags: []}, {sku: 'C0187', cost: 12.09, list: 49.12, stock: 169, launched: '2021-08-20', tags: ['clearance']}, {sku: 'C0188', cost: 13.16, list: 50.11, stock: 206, launched: '2022-09-21', tags: []}, {sku: 'C0189', cost: 14.23, list: 51.10, stock: 243, launched: '2023-10-22', tags: []}, {sku: 'C0190', cost: 15.30, list: 52.09, stock: 30, launched: '2024-11-23', tags: ['seasonal']}, {sku: 'C0191', cost: 16.37, list: 53.08, stock: 67, launched: '2025-12-24', tags: []}, {sku: 'C0192', cost: 17.44, list: 54.07, stock: 104, launched: '2020-01-25', tags: []}, {sku: 'C0193', cost: 18.51, list: 55.06, stock: 141, launched: '2021-02-26', tags: []}, {sku: 'C0194', cost: 19.58, list: 56.05, stock: 178, launched: '2022-03-27', tags: []}, {sku: 'C0195', cost: 20.65, list: 57.04, stock: 215, launched: '2023-04-28', tags: ['seasonal']}, {sku: 'C0196', cost: 21.72, list: 58.03, stock: 2, launched: '2024-05-01', tags: []}, {sku: 'C0197', cost: 22.79, list: 59.02, stock: 39, launched: '2025-06-02', tags: []}, {sku: 'C0198', cost: 23.86, list: 60.01, stock: 76, launched: '2020-07-03', tags: ['clearance']}, {sku: 'C0199', cost: 24.93, list: 61.00, stock: 113, launched: '2021-08-04', tags: []}]};0.005 +len(filter(products, #.stock == 0)) / len(products);{products: [{stock: 0}, {stock: 1}, {stock: 0}, {stock: 5}]};0.5 +len(filter(products, #.stock == 0)) / len(products);{products: []};null +len(filter(products, #.stock == 0)) / len(products);{products: [{stock: null}, {stock: 0}]};0.5 +# Competitive price matching +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: [{price: 45, inStock: true}, {price: 39, inStock: true}, {price: 30, inStock: false}]};44.99 +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: [{price: 40, inStock: true}]};40 +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: [{price: 40.01, inStock: true}]};40 +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: []};49.99 +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: [{price: 60, inStock: false}]};49.99 +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: [{price: 45, inStock: null}]};!error +"comp = map(filter(competitors, #.inStock and #.price >= floor), #.price); len(comp) == 0 ? price : max([floor, min(comp) - 0.01])";{price: 49.99, floor: 40, competitors: [{price: '45', inStock: true}]};!error +# Same expression, differently typed rows +(price ?? 0) * (qty ?? 1);{price: 9.99, qty: 3};29.97 +(price ?? 0) * (qty ?? 1);{price: 9.99};9.99 +(price ?? 0) * (qty ?? 1);{qty: 3};0 +(price ?? 0) * (qty ?? 1);{};0 +(price ?? 0) * (qty ?? 1);{price: '9.99', qty: 3};!error +(price ?? 0) * (qty ?? 1);{price: 9.99, qty: true};!error +(price ?? 0) * (qty ?? 1);{price: [9.99], qty: 1};!error +(price ?? 0) * (qty ?? 1);{price: {amount: 9.99}, qty: 1};!error +(price ?? 0) * (qty ?? 1);{price: 0.000000001, qty: 1000000000};1.000000000 +(price ?? 0) * (qty ?? 1);{price: -5, qty: -2};10 +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: 10};12.0 +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: '10'};12.0 +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: ' 12.345 '};14.81 +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: 'ten'};null +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: null};null +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: true};null +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: ''};null +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: '1e2'};120 +isNumeric(price) ? round(number(price) * 1.2, 2) : null;{price: [1]};null +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: 5};75 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: '15%'};68.00 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: ' 12.5 %'};70.00 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: '5'};80 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80};80 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: true};80 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: 'abc%'};!error +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 19.99, discount: '33%'};13.39 +type(discount) == 'number' ? price - discount : type(discount) == 'string' and endsWith(discount, '%') ? round(price * (1 - number(trim(split(discount, '%')[0])) / 100), 2) : price;{price: 80, discount: [5]};80 +sum(map(items, type(#) == 'number' ? # : type(#) == 'string' and isNumeric(#) ? number(#) : 0));{items: [1, '2', 'x', null, true, 3.5, ' 4 ']};10.5 +sum(map(items, type(#) == 'number' ? # : type(#) == 'string' and isNumeric(#) ? number(#) : 0));{items: []};0 +sum(map(items, type(#) == 'number' ? # : type(#) == 'string' and isNumeric(#) ? number(#) : 0));{items: ['1e1', '0.10', [1], {a: 1}]};10.10 +sum(map(items, type(#) == 'number' ? # : type(#) == 'string' and isNumeric(#) ? number(#) : 0));{items: [0.1, 0.2, '0.3']};0.6 +# Bundles and price books +"prices = map(skus, book[#] ?? 0); full = sum(prices); {full: full, bundle: round(full * (len(prices) >= 3 ? 0.85 : 1), 2), missing: filter(skus, book[#] == null)}";{book: {A: 10, B: 20.5, C: 5.25}, skus: ['A', 'B', 'C']};{full: 35.75, bundle: 30.39, missing: []} +"prices = map(skus, book[#] ?? 0); full = sum(prices); {full: full, bundle: round(full * (len(prices) >= 3 ? 0.85 : 1), 2), missing: filter(skus, book[#] == null)}";{book: {A: 10, B: 20.5}, skus: ['A', 'B']};{full: 30.5, bundle: 30.5, missing: []} +"prices = map(skus, book[#] ?? 0); full = sum(prices); {full: full, bundle: round(full * (len(prices) >= 3 ? 0.85 : 1), 2), missing: filter(skus, book[#] == null)}";{book: {A: 10}, skus: ['A', 'Z', 'Y']};{full: 10, bundle: 8.50, missing: ['Z', 'Y']} +"prices = map(skus, book[#] ?? 0); full = sum(prices); {full: full, bundle: round(full * (len(prices) >= 3 ? 0.85 : 1), 2), missing: filter(skus, book[#] == null)}";{book: {}, skus: []};{full: 0, bundle: 0, missing: []} +"prices = map(skus, book[#] ?? 0); full = sum(prices); {full: full, bundle: round(full * (len(prices) >= 3 ? 0.85 : 1), 2), missing: filter(skus, book[#] == null)}";{book: {'Ä': 3.33}, skus: ['Ä', 'Ä', 'Ä']};{full: 9.99, bundle: 8.49, missing: []} +"prices = map(skus, book[#] ?? 0); full = sum(prices); {full: full, bundle: round(full * (len(prices) >= 3 ? 0.85 : 1), 2), missing: filter(skus, book[#] == null)}";{book: null, skus: ['A']};{full: 0, bundle: 0, missing: ['A']} +map(tiers, {minQty: #.minQty, unit: round(base * (1 - #.pct / 100), 2), total: round(base * (1 - #.pct / 100), 2) * #.minQty});{base: 12.99, tiers: [{minQty: 1, pct: 0}, {minQty: 10, pct: 5}, {minQty: 100, pct: 12.5}]};[{minQty: 1, unit: 12.99, total: 12.99}, {minQty: 10, unit: 12.34, total: 123.40}, {minQty: 100, unit: 11.37, total: 1137.00}] +map(tiers, {minQty: #.minQty, unit: round(base * (1 - #.pct / 100), 2), total: round(base * (1 - #.pct / 100), 2) * #.minQty});{base: 1, tiers: []};[] +map(tiers, {minQty: #.minQty, unit: round(base * (1 - #.pct / 100), 2), total: round(base * (1 - #.pct / 100), 2) * #.minQty});{base: 0.99, tiers: [{minQty: 3, pct: 33.333}]};[{minQty: 3, unit: 0.66, total: 1.98}] +map(tiers, {minQty: #.minQty, unit: round(base * (1 - #.pct / 100), 2), total: round(base * (1 - #.pct / 100), 2) * #.minQty});{base: 5, tiers: [{minQty: 1}]};!error +keys(book);{book: {A: 1, B: 2, C: 3}};['A', 'B', 'C'] +keys(book);{book: {}};[] +keys(book);{book: {z: 1, a: 2}};['z', 'a'] +keys(book);{book: null};!error +sum(values(book));{book: {A: 1.25, B: 2.50, C: 3}};6.75 +sum(values(book));{book: {}};0 +sum(values(book));{book: {a: '1'}};!error +# Happy-hour and weekday pricing +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.50, at: '2025-03-19 15:59'};7.50 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.50, at: '2025-03-19 16:00'};3.75 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.50, at: '2025-03-19 17:59'};3.75 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.50, at: '2025-03-19 18:00'};7.50 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.50, at: '2025-03-22 16:30'};8.25 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.50, at: '2025-03-23 23:59'};8.25 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.45, at: '2025-03-21 17:00'};3.73 +"t = d(at); round(price * (t.weekday() <= 5 and t.hour() in [16..18) ? 0.5 : t.weekday() >= 6 ? 1.1 : 1), 2)";{price: 7.45, at: '2025-03-22 12:00'};8.20 diff --git a/core/expression/tests/spec/standard/13-01-nested-paths.csv b/core/expression/tests/spec/standard/13-01-nested-paths.csv new file mode 100644 index 00000000..26beaa7c --- /dev/null +++ b/core/expression/tests/spec/standard/13-01-nested-paths.csv @@ -0,0 +1,509 @@ +expression (string);input (json 5);output (json 5);note +# five-level paths: every level may be missing or null +a.b.c.d.e;{a: {b: {c: {d: {e: 1}}}}};1 +a.b.c.d.e;{a: {b: {c: {d: {e: 2.5}}}}};2.5 +a.b.c.d.e;{a: {b: {c: {d: {}}}}};null +a.b.c.d.e;{a: {b: {c: {}}}};null +a.b.c.d.e;{a: {b: null}};null +a.b.c.d.e;{a: {}};null +a.b.c.d.e;{};null +a.b.c.d.e;{a: {b: {c: {d: {e: 'x'}}}}};'x' +a.b.c.d.e ?? 0;{a: {b: {c: {d: {e: 1}}}}};1 +a.b.c.d.e ?? 0;{a: {b: {c: {d: {e: 2.5}}}}};2.5 +a.b.c.d.e ?? 0;{a: {b: {c: {d: {}}}}};0 +a.b.c.d.e ?? 0;{a: {b: {c: {}}}};0 +a.b.c.d.e ?? 0;{a: {b: null}};0 +a.b.c.d.e ?? 0;{a: {}};0 +a.b.c.d.e ?? 0;{};0 +a.b.c.d.e ?? 0;{a: {b: {c: {d: {e: 'x'}}}}};'x' +a['b'].c['d'].e;{a: {b: {c: {d: {e: 1}}}}};1 +a['b'].c['d'].e;{a: {b: {c: {d: {e: 2.5}}}}};2.5 +a['b'].c['d'].e;{a: {b: {c: {d: {}}}}};null +a['b'].c['d'].e;{a: {b: {c: {}}}};null +a.b.c.d.e + 1;{a: {b: {c: {d: {e: 1}}}}};2 +a.b.c.d.e + 1;{a: {b: {c: {d: {e: 2.5}}}}};3.5 +a.b.c.d.e + 1;{a: {b: {c: {d: {}}}}};!error +a.b.c.d.e + 1;{a: {b: {c: {}}}};!error +a.b.c.d.e + 1;{a: {b: null}};!error +a.b.c.d.e + 1;{a: {}};!error +a.b.c.d.e + 1;{};!error +a.b.c.d.e + 1;{a: {b: {c: {d: {e: 'x'}}}}};!error +a.b.c.d.e == null;{a: {b: {c: {d: {e: 1}}}}};false +a.b.c.d.e == null;{a: {b: {c: {d: {e: 2.5}}}}};false +a.b.c.d.e == null;{a: {b: {c: {d: {}}}}};true +a.b.c.d.e == null;{a: {b: {c: {}}}};true +a.b.c.d.e == null;{a: {b: null}};true +a.b.c.d.e == null;{a: {}};true +a.b.c.d.e == null;{};true +a.b.c.d.e == null;{a: {b: {c: {d: {e: 'x'}}}}};false +type(a.b.c.d);{a: {b: {c: {d: {e: 1}}}}};'object' +type(a.b.c.d);{a: {b: {c: {d: {e: 2.5}}}}};'object' +type(a.b.c.d);{a: {b: {c: {d: {}}}}};'object' +type(a.b.c.d);{a: {b: {c: {}}}};'null' +type(a.b.c.d);{a: {b: null}};'null' +type(a.b.c.d);{a: {}};'null' +type(a.b.c.d);{};'null' +a.b.c.d.e.f;{a: {b: {c: {d: {e: {f: 9}}}}}};9 +a.b.c.d.e.f;{a: {b: {c: {d: {e: {f: [1]}}}}}};[1] +# dynamic keys along a deep path +a[k1][k2];{k1: 'b', k2: 'c', a: {b: {c: 1}, x: {c: 2}}};1 +a[k1][k2];{k1: 'x', k2: 'c', a: {b: {c: 1}, x: {c: 2}}};2 +a[k1][k2];{k1: 'x', k2: 'z', a: {b: {c: 1}, x: {c: 2}}};null +a[k1][k2];{k1: 'q', k2: 'c', a: {b: {c: 1}}};null +a[k1][k2];{k1: 'b', a: {b: {c: 1}}};null +a[k1][k2];{k1: 1, k2: 'c', a: {b: {c: 1}}};null +a[k1][k2] ?? -1;{k1: 'b', k2: 'c', a: {b: {c: 1}, x: {c: 2}}};1 +a[k1][k2] ?? -1;{k1: 'x', k2: 'c', a: {b: {c: 1}, x: {c: 2}}};2 +a[k1][k2] ?? -1;{k1: 'x', k2: 'z', a: {b: {c: 1}, x: {c: 2}}};-1 +a[k1][k2] ?? -1;{k1: 'q', k2: 'c', a: {b: {c: 1}}};-1 +a[k1][k2] ?? -1;{k1: 'b', a: {b: {c: 1}}};-1 +a[k1][k2] ?? -1;{k1: 1, k2: 'c', a: {b: {c: 1}}};-1 +a[k1 + ''].c;{k1: 'b', k2: 'c', a: {b: {c: 1}, x: {c: 2}}};1 +a[k1 + ''].c;{k1: 'x', k2: 'c', a: {b: {c: 1}, x: {c: 2}}};2 +a[k1 + ''].c;{k1: 'x', k2: 'z', a: {b: {c: 1}, x: {c: 2}}};2 +a[k1 + ''].c;{k1: 'q', k2: 'c', a: {b: {c: 1}}};null +a[k1 + ''].c;{k1: 'b', a: {b: {c: 1}}};1 +a[k1 + ''].c;{k1: 1, k2: 'c', a: {b: {c: 1}}};!error +# arrays of arrays: index chains +m[1][2];{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};6 +m[1][2];{m: [[1], [], [7, 8]]};null +m[1][2];{m: [[], []]};null +m[1][2];{m: []};null +m[1][2];{m: [[[1, 2]], [[3]]]};null +m[1][2];{m: [null, [1]]};null +m[1][2];{m: null};null +m[0][0];{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};1 +m[0][0];{m: [[1], [], [7, 8]]};1 +m[0][0];{m: [[], []]};null +m[0][0];{m: []};null +m[0][0];{m: [[[1, 2]], [[3]]]};[1, 2] +m[0][0];{m: [null, [1]]};null +m[0][0];{m: null};null +m[2][1] ?? 0;{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};8 +m[2][1] ?? 0;{m: [[1], [], [7, 8]]};8 +m[2][1] ?? 0;{m: [[], []]};0 +m[2][1] ?? 0;{m: []};0 +m[2][1] ?? 0;{m: [[[1, 2]], [[3]]]};0 +m[2][1] ?? 0;{m: [null, [1]]};0 +m[2][1] ?? 0;{m: null};0 +map(m, #[0]);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[1, 4, 7] +map(m, #[0]);{m: [[1], [], [7, 8]]};[1, null, 7] +map(m, #[0]);{m: [[], []]};[null, null] +map(m, #[0]);{m: []};[] +map(m, #[0]);{m: [[[1, 2]], [[3]]]};[[1, 2], [3]] +map(m, #[0]);{m: [null, [1]]};[null, 1] +map(m, #[0]);{m: null};!error +map(m, len(#));{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[3, 3, 3] +map(m, len(#));{m: [[1], [], [7, 8]]};[1, 0, 2] +map(m, len(#));{m: [[], []]};[0, 0] +map(m, len(#));{m: []};[] +map(m, len(#));{m: [[[1, 2]], [[3]]]};[1, 1] +map(m, len(#));{m: [null, [1]]};!error +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 +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: [[], []]};[] +flatten(m);{m: []};[] +flatten(m);{m: [[[1, 2]], [[3]]]};[[1, 2], [3]] +flatten(m);{m: [null, [1]]};[null, 1] +flatten(m);{m: null};!error +len(flatten(m));{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};9 +len(flatten(m));{m: [[1], [], [7, 8]]};3 +len(flatten(m));{m: [[], []]};0 +len(flatten(m));{m: []};0 +len(flatten(m));{m: [[[1, 2]], [[3]]]};2 +len(flatten(m));{m: [null, [1]]};2 +len(flatten(m));{m: null};!error +flatten(flatten(m));{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[1, 2, 3, 4, 5, 6, 7, 8, 9] +flatten(flatten(m));{m: [[1], [], [7, 8]]};[1, 7, 8] +flatten(flatten(m));{m: [[], []]};[] +flatten(flatten(m));{m: []};[] +flatten(flatten(m));{m: [[[1, 2]], [[3]]]};[1, 2, 3] +sum(map(m, sum(#)));{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};45 +sum(map(m, sum(#)));{m: [[1], [], [7, 8]]};16 +sum(map(m, sum(#)));{m: [[], []]};0 +sum(map(m, sum(#)));{m: []};0 +sum(map(m, sum(#)));{m: [[[1, 2]], [[3]]]};!error +sum(map(m, sum(#)));{m: [null, [1]]};!error +sum(map(m, sum(#)));{m: null};!error +map(m, map(#, # * 10));{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[[10, 20, 30], [40, 50, 60], [70, 80, 90]] +map(m, map(#, # * 10));{m: [[1], [], [7, 8]]};[[10], [], [70, 80]] +map(m, map(#, # * 10));{m: [[], []]};[[], []] +map(m, map(#, # * 10));{m: []};[] +map(m, map(#, # * 10));{m: [[[1, 2]], [[3]]]};!error +map(m, map(#, # * 10));{m: [null, [1]]};!error +map(m, map(#, # * 10));{m: null};!error +map(m, filter(#, # % 2 == 1));{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[[1, 3], [5], [7, 9]] +map(m, filter(#, # % 2 == 1));{m: [[1], [], [7, 8]]};[[1], [], [7]] +map(m, filter(#, # % 2 == 1));{m: [[], []]};[[], []] +map(m, filter(#, # % 2 == 1));{m: []};[] +map(m, filter(#, # % 2 == 1));{m: [[[1, 2]], [[3]]]};!error +map(m, filter(#, # % 2 == 1));{m: [null, [1]]};!error +map(m, filter(#, # % 2 == 1));{m: null};!error +filter(m, len(#) > 1);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[[1, 2, 3], [4, 5, 6], [7, 8, 9]] +filter(m, len(#) > 1);{m: [[1], [], [7, 8]]};[[7, 8]] +filter(m, len(#) > 1);{m: [[], []]};[] +filter(m, len(#) > 1);{m: []};[] +filter(m, len(#) > 1);{m: [[[1, 2]], [[3]]]};[] +filter(m, len(#) > 1);{m: [null, [1]]};!error +filter(m, len(#) > 1);{m: null};!error +count(m, len(#) == 0);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};0 +count(m, len(#) == 0);{m: [[1], [], [7, 8]]};1 +count(m, len(#) == 0);{m: [[], []]};2 +count(m, len(#) == 0);{m: []};0 +count(m, len(#) == 0);{m: [[[1, 2]], [[3]]]};0 +count(m, len(#) == 0);{m: [null, [1]]};!error +count(m, len(#) == 0);{m: null};!error +some(m, 5 in #);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};true +some(m, 5 in #);{m: [[1], [], [7, 8]]};false +some(m, 5 in #);{m: [[], []]};false +some(m, 5 in #);{m: []};false +some(m, 5 in #);{m: [[[1, 2]], [[3]]]};false +some(m, 5 in #);{m: [null, [1]]};!error +some(m, 5 in #);{m: null};!error +map(m, 2 in #);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[true, false, false] +map(m, 2 in #);{m: [[1], [], [7, 8]]};[false, false, false] +map(m, 2 in #);{m: [[], []]};[false, false] +map(m, 2 in #);{m: []};[] +map(m, 2 in #);{m: [[[1, 2]], [[3]]]};[false, false] +map(m, 2 in #);{m: [null, [1]]};!error +map(m, 2 in #);{m: null};!error +# three-dimensional arrays +t[1][1][0];{t: [[[1, 2], [3]], [[4], [5, 6]]]};5 +t[1][1][0];{t: [[[1]], [], [[]]]};null +t[1][1][0];{t: [[[0.5, 0.25]], [[0.125]]]};null +t[1][1][0];{t: []};null +t[1][1][0];{t: [[[1, 'a']]]};null +map(t, map(#, sum(#)));{t: [[[1, 2], [3]], [[4], [5, 6]]]};[[3, 3], [4, 11]] +map(t, map(#, sum(#)));{t: [[[1]], [], [[]]]};[[1], [], [0]] +map(t, map(#, sum(#)));{t: [[[0.5, 0.25]], [[0.125]]]};[[0.75], [0.125]] +map(t, map(#, sum(#)));{t: []};[] +map(t, map(#, sum(#)));{t: [[[1, 'a']]]};!error +sum(map(t, sum(map(#, sum(#)))));{t: [[[1, 2], [3]], [[4], [5, 6]]]};21 +sum(map(t, sum(map(#, sum(#)))));{t: [[[1]], [], [[]]]};1 +sum(map(t, sum(map(#, sum(#)))));{t: [[[0.5, 0.25]], [[0.125]]]};0.875 +sum(map(t, sum(map(#, sum(#)))));{t: []};0 +sum(map(t, sum(map(#, sum(#)))));{t: [[[1, 'a']]]};!error +flatten(flatten(t));{t: [[[1, 2], [3]], [[4], [5, 6]]]};[1, 2, 3, 4, 5, 6] +flatten(flatten(t));{t: [[[1]], [], [[]]]};[1] +flatten(flatten(t));{t: [[[0.5, 0.25]], [[0.125]]]};[0.5, 0.25, 0.125] +flatten(flatten(t));{t: []};[] +flatten(flatten(t));{t: [[[1, 'a']]]};[1, 'a'] +flatMap(t, flatMap(#, #));{t: [[[1, 2], [3]], [[4], [5, 6]]]};[1, 2, 3, 4, 5, 6] +flatMap(t, flatMap(#, #));{t: [[[1]], [], [[]]]};[1] +flatMap(t, flatMap(#, #));{t: [[[0.5, 0.25]], [[0.125]]]};[0.5, 0.25, 0.125] +flatMap(t, flatMap(#, #));{t: []};[] +flatMap(t, flatMap(#, #));{t: [[[1, 'a']]]};[1, 'a'] +map(t, len(flatten(#)));{t: [[[1, 2], [3]], [[4], [5, 6]]]};[3, 3] +map(t, len(flatten(#)));{t: [[[1]], [], [[]]]};[1, 0, 0] +map(t, len(flatten(#)));{t: [[[0.5, 0.25]], [[0.125]]]};[2, 1] +map(t, len(flatten(#)));{t: []};[] +map(t, len(flatten(#)));{t: [[[1, 'a']]]};[2] +map(t, map(#, len(#)));{t: [[[1, 2], [3]], [[4], [5, 6]]]};[[2, 1], [1, 2]] +map(t, map(#, len(#)));{t: [[[1]], [], [[]]]};[[1], [], [0]] +map(t, map(#, len(#)));{t: [[[0.5, 0.25]], [[0.125]]]};[[2], [1]] +map(t, map(#, len(#)));{t: []};[] +map(t, map(#, len(#)));{t: [[[1, 'a']]]};[[2]] +count(flatten(flatten(t)), true);{t: [[[1, 2], [3]], [[4], [5, 6]]]};6 +count(flatten(flatten(t)), true);{t: [[[1]], [], [[]]]};1 +count(flatten(flatten(t)), true);{t: [[[0.5, 0.25]], [[0.125]]]};3 +count(flatten(flatten(t)), true);{t: []};0 +count(flatten(flatten(t)), true);{t: [[[1, 'a']]]};2 +# objects of arrays +map(keys(o), len(o[#]));{o: {a: [1, 2], b: [3], c: []}};[2, 1, 0] +map(keys(o), len(o[#]));{o: {x: [0.5, 0.5]}};[2] +map(keys(o), len(o[#]));{o: {}};[] +map(keys(o), len(o[#]));{o: {a: [1], b: null}};!error +map(keys(o), len(o[#]));{o: {a: [1], b: 'str'}};[1, 3] +map(keys(o), len(o[#]));{o: null};!error +map(values(o), len(#));{o: {a: [1, 2], b: [3], c: []}};[2, 1, 0] +map(values(o), len(#));{o: {x: [0.5, 0.5]}};[2] +map(values(o), len(#));{o: {}};[] +map(values(o), len(#));{o: {a: [1], b: null}};!error +map(values(o), len(#));{o: {a: [1], b: 'str'}};[1, 3] +map(values(o), len(#));{o: null};!error +sum(flatten(values(o)));{o: {a: [1, 2], b: [3], c: []}};6 +sum(flatten(values(o)));{o: {x: [0.5, 0.5]}};1.0 +sum(flatten(values(o)));{o: {}};0 +sum(flatten(values(o)));{o: {a: [1], b: null}};!error +sum(flatten(values(o)));{o: {a: [1], b: 'str'}};!error +sum(flatten(values(o)));{o: null};!error +merge(values(o));{o: {a: [1, 2], b: [3], c: []}};[1, 2, 3] +merge(values(o));{o: {x: [0.5, 0.5]}};[0.5, 0.5] +merge(values(o));{o: {}};{} +merge(values(o));{o: {a: [1], b: null}};[1] +merge(values(o));{o: {a: [1], b: 'str'}};!error +merge(values(o));{o: null};!error +filter(keys(o), len(o[#]) > 0);{o: {a: [1, 2], b: [3], c: []}};['a', 'b'] +filter(keys(o), len(o[#]) > 0);{o: {x: [0.5, 0.5]}};['x'] +filter(keys(o), len(o[#]) > 0);{o: {}};[] +filter(keys(o), len(o[#]) > 0);{o: {a: [1], b: null}};!error +filter(keys(o), len(o[#]) > 0);{o: {a: [1], b: 'str'}};['a', 'b'] +filter(keys(o), len(o[#]) > 0);{o: null};!error +map(keys(o) as k, {key: k, n: len(o[k])});{o: {a: [1, 2], b: [3], c: []}};[{key: 'a', n: 2}, {key: 'b', n: 1}, {key: 'c', n: 0}] +map(keys(o) as k, {key: k, n: len(o[k])});{o: {x: [0.5, 0.5]}};[{key: 'x', n: 2}] +map(keys(o) as k, {key: k, n: len(o[k])});{o: {}};[] +map(keys(o) as k, {key: k, n: len(o[k])});{o: {a: [1], b: null}};!error +map(keys(o) as k, {key: k, n: len(o[k])});{o: {a: [1], b: 'str'}};[{key: 'a', n: 1}, {key: 'b', n: 3}] +map(keys(o) as k, {key: k, n: len(o[k])});{o: null};!error +o.a[0] + (o.b[0] ?? 0);{o: {a: [1, 2], b: [3], c: []}};4 +o.a[0] + (o.b[0] ?? 0);{o: {x: [0.5, 0.5]}};!error +o.a[0] + (o.b[0] ?? 0);{o: {}};!error +o.a[0] + (o.b[0] ?? 0);{o: {a: [1], b: null}};1 +o.a[0] + (o.b[0] ?? 0);{o: {a: [1], b: 'str'}};!error +o.a[0] + (o.b[0] ?? 0);{o: null};!error +o['a'][1];{o: {a: [1, 2], b: [3], c: []}};2 +o['a'][1];{o: {x: [0.5, 0.5]}};null +o['a'][1];{o: {}};null +o['a'][1];{o: {a: [1], b: null}};null +o['a'][1];{o: {a: [1], b: 'str'}};null +o['a'][1];{o: null};null +len(o.a ?? []);{o: {a: [1, 2], b: [3], c: []}};2 +len(o.a ?? []);{o: {x: [0.5, 0.5]}};0 +len(o.a ?? []);{o: {}};0 +len(o.a ?? []);{o: {a: [1], b: null}};1 +len(o.a ?? []);{o: {a: [1], b: 'str'}};1 +len(o.a ?? []);{o: null};0 +# objects of objects of arrays +map(values(r), sum(flatten(values(#))));{r: {eu: {de: [10, 20], fr: [5]}, us: {ny: [1, 2, 3]}}};[35, 6] +map(values(r), sum(flatten(values(#))));{r: {eu: {}, us: {ny: []}}};[0, 0] +map(values(r), sum(flatten(values(#))));{r: {eu: {de: [0.1, 0.2]}}};[0.3] +map(values(r), sum(flatten(values(#))));{r: {}};[] +sum(flatMap(values(r), flatten(values(#))));{r: {eu: {de: [10, 20], fr: [5]}, us: {ny: [1, 2, 3]}}};41 +sum(flatMap(values(r), flatten(values(#))));{r: {eu: {}, us: {ny: []}}};0 +sum(flatMap(values(r), flatten(values(#))));{r: {eu: {de: [0.1, 0.2]}}};0.3 +sum(flatMap(values(r), flatten(values(#))));{r: {}};0 +flatMap(keys(r) as a, map(keys(r[a]), a + '/' + #));{r: {eu: {de: [10, 20], fr: [5]}, us: {ny: [1, 2, 3]}}};['eu/de', 'eu/fr', 'us/ny'] +flatMap(keys(r) as a, map(keys(r[a]), a + '/' + #));{r: {eu: {}, us: {ny: []}}};['us/ny'] +flatMap(keys(r) as a, map(keys(r[a]), a + '/' + #));{r: {eu: {de: [0.1, 0.2]}}};['eu/de'] +flatMap(keys(r) as a, map(keys(r[a]), a + '/' + #));{r: {}};[] +map(keys(r) as a, len(keys(r[a])));{r: {eu: {de: [10, 20], fr: [5]}, us: {ny: [1, 2, 3]}}};[2, 1] +map(keys(r) as a, len(keys(r[a])));{r: {eu: {}, us: {ny: []}}};[0, 1] +map(keys(r) as a, len(keys(r[a])));{r: {eu: {de: [0.1, 0.2]}}};[1] +map(keys(r) as a, len(keys(r[a])));{r: {}};[] +r.eu.de[1] ?? r.us.ny[0];{r: {eu: {de: [10, 20], fr: [5]}, us: {ny: [1, 2, 3]}}};20 +r.eu.de[1] ?? r.us.ny[0];{r: {eu: {}, us: {ny: []}}};null +r.eu.de[1] ?? r.us.ny[0];{r: {eu: {de: [0.1, 0.2]}}};0.2 +r.eu.de[1] ?? r.us.ny[0];{r: {}};null +len(r.us.ny ?? []);{r: {eu: {de: [10, 20], fr: [5]}, us: {ny: [1, 2, 3]}}};3 +len(r.us.ny ?? []);{r: {eu: {}, us: {ny: []}}};0 +len(r.us.ny ?? []);{r: {eu: {de: [0.1, 0.2]}}};0 +len(r.us.ny ?? []);{r: {}};0 +# arrays of objects with heterogeneous fields +map(xs, #.a);{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};[1, 3, null, null] +map(xs, #.a);{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};[1.5, null, 2.5] +map(xs, #.a);{xs: [{a: 'x'}, {a: 1}]};['x', 1] +map(xs, #.a);{xs: [{a: [1]}, {a: {n: 1}}]};[[1], {n: 1}] +map(xs, #.a);{xs: [null, {a: 1}]};[null, 1] +map(xs, #.a);{xs: [1, 'a', {a: 2}]};[null, null, 2] +map(xs, #.a);{xs: []};[] +map(xs, #.a ?? #.b ?? 0);{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};[1, 3, 4, 0] +map(xs, #.a ?? #.b ?? 0);{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};[1.5, 0, 2.5] +map(xs, #.a ?? #.b ?? 0);{xs: [{a: 'x'}, {a: 1}]};['x', 1] +map(xs, #.a ?? #.b ?? 0);{xs: [{a: [1]}, {a: {n: 1}}]};[[1], {n: 1}] +map(xs, #.a ?? #.b ?? 0);{xs: [null, {a: 1}]};[0, 1] +map(xs, #.a ?? #.b ?? 0);{xs: [1, 'a', {a: 2}]};[0, 0, 2] +map(xs, #.a ?? #.b ?? 0);{xs: []};[] +filter(xs, #.a != null);{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};[{a: 1, b: 2}, {a: 3}] +filter(xs, #.a != null);{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};[{a: 1.5}, {a: 2.5}] +filter(xs, #.a != null);{xs: [{a: 'x'}, {a: 1}]};[{a: 'x'}, {a: 1}] +filter(xs, #.a != null);{xs: [{a: [1]}, {a: {n: 1}}]};[{a: [1]}, {a: {n: 1}}] +filter(xs, #.a != null);{xs: [null, {a: 1}]};[{a: 1}] +filter(xs, #.a != null);{xs: [1, 'a', {a: 2}]};[{a: 2}] +filter(xs, #.a != null);{xs: []};[] +count(xs, #.a == null);{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};2 +count(xs, #.a == null);{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};1 +count(xs, #.a == null);{xs: [{a: 'x'}, {a: 1}]};0 +count(xs, #.a == null);{xs: [{a: [1]}, {a: {n: 1}}]};0 +count(xs, #.a == null);{xs: [null, {a: 1}]};1 +count(xs, #.a == null);{xs: [1, 'a', {a: 2}]};2 +count(xs, #.a == null);{xs: []};0 +map(xs, type(#.a));{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};['number', 'number', 'null', 'null'] +map(xs, type(#.a));{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};['number', 'null', 'number'] +map(xs, type(#.a));{xs: [{a: 'x'}, {a: 1}]};['string', 'number'] +map(xs, type(#.a));{xs: [{a: [1]}, {a: {n: 1}}]};['array', 'object'] +map(xs, type(#.a));{xs: [null, {a: 1}]};['null', 'number'] +map(xs, type(#.a));{xs: [1, 'a', {a: 2}]};['null', 'null', 'number'] +map(xs, type(#.a));{xs: []};[] +sum(map(xs, #.a ?? 0));{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};4 +sum(map(xs, #.a ?? 0));{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};4.0 +sum(map(xs, #.a ?? 0));{xs: [{a: 'x'}, {a: 1}]};!error +sum(map(xs, #.a ?? 0));{xs: [{a: [1]}, {a: {n: 1}}]};!error +sum(map(xs, #.a ?? 0));{xs: [null, {a: 1}]};1 +sum(map(xs, #.a ?? 0));{xs: [1, 'a', {a: 2}]};2 +sum(map(xs, #.a ?? 0));{xs: []};0 +sum(map(filter(xs, #.a != null), #.a));{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};4 +sum(map(filter(xs, #.a != null), #.a));{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};4.0 +sum(map(filter(xs, #.a != null), #.a));{xs: [{a: 'x'}, {a: 1}]};!error +sum(map(filter(xs, #.a != null), #.a));{xs: [{a: [1]}, {a: {n: 1}}]};!error +sum(map(filter(xs, #.a != null), #.a));{xs: [null, {a: 1}]};1 +sum(map(filter(xs, #.a != null), #.a));{xs: [1, 'a', {a: 2}]};2 +sum(map(filter(xs, #.a != null), #.a));{xs: []};0 +map(xs, #.a == null ? 'none' : 'some');{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};['some', 'some', 'none', 'none'] +map(xs, #.a == null ? 'none' : 'some');{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};['some', 'none', 'some'] +map(xs, #.a == null ? 'none' : 'some');{xs: [{a: 'x'}, {a: 1}]};['some', 'some'] +map(xs, #.a == null ? 'none' : 'some');{xs: [{a: [1]}, {a: {n: 1}}]};['some', 'some'] +map(xs, #.a == null ? 'none' : 'some');{xs: [null, {a: 1}]};['none', 'some'] +map(xs, #.a == null ? 'none' : 'some');{xs: [1, 'a', {a: 2}]};['none', 'none', 'some'] +map(xs, #.a == null ? 'none' : 'some');{xs: []};[] +filter(xs, isNumeric(#.a));{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};[{a: 1, b: 2}, {a: 3}] +filter(xs, isNumeric(#.a));{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};[{a: 1.5}, {a: 2.5}] +filter(xs, isNumeric(#.a));{xs: [{a: 'x'}, {a: 1}]};[{a: 1}] +filter(xs, isNumeric(#.a));{xs: [{a: [1]}, {a: {n: 1}}]};[] +filter(xs, isNumeric(#.a));{xs: [null, {a: 1}]};[{a: 1}] +filter(xs, isNumeric(#.a));{xs: [1, 'a', {a: 2}]};[{a: 2}] +filter(xs, isNumeric(#.a));{xs: []};[] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};[2, 6] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};[3.0, 5.0] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: [{a: 'x'}, {a: 1}]};[2] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: [{a: [1]}, {a: {n: 1}}]};[] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: [null, {a: 1}]};[2] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: [1, 'a', {a: 2}]};[4] +map(filter(xs, isNumeric(#.a)), #.a * 2);{xs: []};[] +map(xs, len(keys(#)));{xs: [{a: 1, b: 2}, {a: 3}, {b: 4}, {}]};[2, 1, 1, 0] +map(xs, len(keys(#)));{xs: [{a: 1.5}, {a: null}, {a: 2.5}]};[1, 1, 1] +map(xs, len(keys(#)));{xs: [{a: 'x'}, {a: 1}]};[1, 1] +map(xs, len(keys(#)));{xs: [{a: [1]}, {a: {n: 1}}]};[1, 1] +map(xs, len(keys(#)));{xs: [null, {a: 1}]};!error +map(xs, len(keys(#)));{xs: [1, 'a', {a: 2}]};!error +map(xs, len(keys(#)));{xs: []};[] +# mixed shapes per row: the same expression over differently typed inputs +len(v.items);{v: {items: [{n: 1}, {n: 2}]}};2 +len(v.items);{v: {items: []}};0 +len(v.items);{v: {items: null}};!error +len(v.items);{v: {}};!error +len(v.items);{v: null};!error +len(v.items);{v: {items: 'abc'}};3 +len(v.items);{v: {items: {n: 1}}};!error +len(v.items);{v: {items: [{n: '1'}]}};1 +len(v.items ?? []);{v: {items: [{n: 1}, {n: 2}]}};2 +len(v.items ?? []);{v: {items: []}};0 +len(v.items ?? []);{v: {items: null}};0 +len(v.items ?? []);{v: {}};0 +len(v.items ?? []);{v: null};0 +len(v.items ?? []);{v: {items: 'abc'}};3 +len(v.items ?? []);{v: {items: {n: 1}}};!error +len(v.items ?? []);{v: {items: [{n: '1'}]}};1 +map(v.items ?? [], #.n);{v: {items: [{n: 1}, {n: 2}]}};[1, 2] +map(v.items ?? [], #.n);{v: {items: []}};[] +map(v.items ?? [], #.n);{v: {items: null}};[] +map(v.items ?? [], #.n);{v: {}};[] +map(v.items ?? [], #.n);{v: null};[] +map(v.items ?? [], #.n);{v: {items: 'abc'}};!error +map(v.items ?? [], #.n);{v: {items: {n: 1}}};!error +map(v.items ?? [], #.n);{v: {items: [{n: '1'}]}};['1'] +sum(map(v.items ?? [], #.n));{v: {items: [{n: 1}, {n: 2}]}};3 +sum(map(v.items ?? [], #.n));{v: {items: []}};0 +sum(map(v.items ?? [], #.n));{v: {items: null}};0 +sum(map(v.items ?? [], #.n));{v: {}};0 +sum(map(v.items ?? [], #.n));{v: null};0 +sum(map(v.items ?? [], #.n));{v: {items: 'abc'}};!error +sum(map(v.items ?? [], #.n));{v: {items: {n: 1}}};!error +sum(map(v.items ?? [], #.n));{v: {items: [{n: '1'}]}};!error +v.items[0].n;{v: {items: [{n: 1}, {n: 2}]}};1 +v.items[0].n;{v: {items: []}};null +v.items[0].n;{v: {items: null}};null +v.items[0].n;{v: {}};null +v.items[0].n;{v: null};null +v.items[0].n;{v: {items: 'abc'}};null +v.items[0].n;{v: {items: {n: 1}}};null +v.items[0].n;{v: {items: [{n: '1'}]}};'1' +v.items.n;{v: {items: [{n: 1}, {n: 2}]}};null +v.items.n;{v: {items: []}};null +v.items.n;{v: {items: null}};null +v.items.n;{v: {}};null +v.items.n;{v: null};null +v.items.n;{v: {items: 'abc'}};null +v.items.n;{v: {items: {n: 1}}};1 +v.items.n;{v: {items: [{n: '1'}]}};null +type(v.items);{v: {items: [{n: 1}, {n: 2}]}};'array' +type(v.items);{v: {items: []}};'array' +type(v.items);{v: {items: null}};'null' +type(v.items);{v: {}};'null' +type(v.items);{v: null};'null' +type(v.items);{v: {items: 'abc'}};'string' +type(v.items);{v: {items: {n: 1}}};'object' +type(v.items);{v: {items: [{n: '1'}]}};'array' +# deep paths through closure results +map(orders, #.lines)[0][0].sku;{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'a' +map(orders, #.lines)[0][0].sku;{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};null +map(orders, #.lines)[0][0].sku;{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};'a' +map(orders, #.lines)[0][0].sku;{orders: []};null +map(orders, #.lines)[0][0].sku;{orders: [{id: 'o1'}]};null +map(orders, #.lines[0])[1].q;{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};5 +map(orders, #.lines[0])[1].q;{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};5 +map(orders, #.lines[0])[1].q;{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};null +map(orders, #.lines[0])[1].q;{orders: []};null +map(orders, #.lines[0])[1].q;{orders: [{id: 'o1'}]};null +filter(orders, len(#.lines ?? []) > 0)[0].id;{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o1' +filter(orders, len(#.lines ?? []) > 0)[0].id;{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o2' +filter(orders, len(#.lines ?? []) > 0)[0].id;{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};'o1' +filter(orders, len(#.lines ?? []) > 0)[0].id;{orders: []};null +filter(orders, len(#.lines ?? []) > 0)[0].id;{orders: [{id: 'o1'}]};null +flatMap(orders, #.lines ?? [])[1].sku;{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'b' +flatMap(orders, #.lines ?? [])[1].sku;{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};null +flatMap(orders, #.lines ?? [])[1].sku;{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};null +flatMap(orders, #.lines ?? [])[1].sku;{orders: []};null +flatMap(orders, #.lines ?? [])[1].sku;{orders: [{id: 'o1'}]};null +map(orders, {id: #.id, n: len(#.lines ?? [])})[0].n;{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};2 +map(orders, {id: #.id, n: len(#.lines ?? [])})[0].n;{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};0 +map(orders, {id: #.id, n: len(#.lines ?? [])})[0].n;{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};1 +map(orders, {id: #.id, n: len(#.lines ?? [])})[0].n;{orders: []};null +map(orders, {id: #.id, n: len(#.lines ?? [])})[0].n;{orders: [{id: 'o1'}]};0 +map(orders, {first: #.lines[0]})[0].first.sku;{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'a' +map(orders, {first: #.lines[0]})[0].first.sku;{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};null +map(orders, {first: #.lines[0]})[0].first.sku;{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};'a' +map(orders, {first: #.lines[0]})[0].first.sku;{orders: []};null +map(orders, {first: #.lines[0]})[0].first.sku;{orders: [{id: 'o1'}]};null +len(flatMap(orders, map(#.lines ?? [], #.sku)));{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};3 +len(flatMap(orders, map(#.lines ?? [], #.sku)));{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};1 +len(flatMap(orders, map(#.lines ?? [], #.sku)));{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};1 +len(flatMap(orders, map(#.lines ?? [], #.sku)));{orders: []};0 +len(flatMap(orders, map(#.lines ?? [], #.sku)));{orders: [{id: 'o1'}]};0 +map(orders, map(#.lines ?? [], #.q ?? 0));{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};[[2, 1], [5]] +map(orders, map(#.lines ?? [], #.q ?? 0));{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};[[], [5]] +map(orders, map(#.lines ?? [], #.q ?? 0));{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};[[0]] +map(orders, map(#.lines ?? [], #.q ?? 0));{orders: []};[] +map(orders, map(#.lines ?? [], #.q ?? 0));{orders: [{id: 'o1'}]};[[]] +map(orders, map(#.lines, #.q));{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};[[2, 1], [5]] +map(orders, map(#.lines, #.q));{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};[[], [5]] +map(orders, map(#.lines, #.q));{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};[[null]] +map(orders, map(#.lines, #.q));{orders: []};[] +map(orders, map(#.lines, #.q));{orders: [{id: 'o1'}]};!error +{r: map(orders, #.id)}.r[0];{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o1';bug: postfix access works on a parenthesized object literal but not a bare one +{r: map(orders, #.id)}.r[0];{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o1';bug: postfix access works on a parenthesized object literal but not a bare one +({r: map(orders, #.id)}).r[0];{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o1' +({r: map(orders, #.id)}).r[0];{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o1' +({r: map(orders, #.id)}).r[0];{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};'o1' +({r: map(orders, #.id)}).r[0];{orders: []};null +({r: map(orders, #.id)}).r[0];{orders: [{id: 'o1'}]};'o1' +[map(orders, #.id), 1][0][1];{orders: [{id: 'o1', lines: [{sku: 'a', q: 2}, {sku: 'b', q: 1}]}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o2' +[map(orders, #.id), 1][0][1];{orders: [{id: 'o1', lines: []}, {id: 'o2', lines: [{sku: 'c', q: 5}]}]};'o2' +[map(orders, #.id), 1][0][1];{orders: [{id: 'o1', lines: [{sku: 'a'}]}]};null +[map(orders, #.id), 1][0][1];{orders: []};null +[map(orders, #.id), 1][0][1];{orders: [{id: 'o1'}]};null +# $root inside nested closures +map(groups, map(#.xs, # * $root.rate));{rate: 2, groups: [{xs: [1, 2]}, {xs: [3]}]};[[2, 4], [6]] +map(groups, map(#.xs, # * $root.rate));{rate: 0.5, groups: [{xs: []}, {xs: [4]}]};[[], [2.0]] +map(groups, map(#.xs, # * $root.rate));{rate: null, groups: [{xs: [1]}]};!error +map(groups, map(#.xs, # * $root.rate));{rate: 1, groups: []};[] +map(groups, map(#.xs, # * rate));{rate: 2, groups: [{xs: [1, 2]}, {xs: [3]}]};[[2, 4], [6]] +map(groups, map(#.xs, # * rate));{rate: 0.5, groups: [{xs: []}, {xs: [4]}]};[[], [2.0]] +map(groups, map(#.xs, # * rate));{rate: null, groups: [{xs: [1]}]};!error +map(groups, map(#.xs, # * rate));{rate: 1, groups: []};[] +map(groups, len($root.groups));{rate: 2, groups: [{xs: [1, 2]}, {xs: [3]}]};[2, 2] +map(groups, len($root.groups));{rate: 0.5, groups: [{xs: []}, {xs: [4]}]};[2, 2] +map(groups, len($root.groups));{rate: null, groups: [{xs: [1]}]};[1] +map(groups, len($root.groups));{rate: 1, groups: []};[] +flatMap(groups, map(#.xs, # + len($root.groups)));{rate: 2, groups: [{xs: [1, 2]}, {xs: [3]}]};[3, 4, 5] +flatMap(groups, map(#.xs, # + len($root.groups)));{rate: 0.5, groups: [{xs: []}, {xs: [4]}]};[6] +flatMap(groups, map(#.xs, # + len($root.groups)));{rate: null, groups: [{xs: [1]}]};[2] +flatMap(groups, map(#.xs, # + len($root.groups)));{rate: 1, groups: []};[] +map(groups as g, map(g.xs, $root.groups[0].xs[0] ?? 0));{rate: 2, groups: [{xs: [1, 2]}, {xs: [3]}]};[[1, 1], [1]] +map(groups as g, map(g.xs, $root.groups[0].xs[0] ?? 0));{rate: 0.5, groups: [{xs: []}, {xs: [4]}]};[[], [0]] +map(groups as g, map(g.xs, $root.groups[0].xs[0] ?? 0));{rate: null, groups: [{xs: [1]}]};[[1]] +map(groups as g, map(g.xs, $root.groups[0].xs[0] ?? 0));{rate: 1, groups: []};[] diff --git a/core/expression/tests/spec/standard/13-02-nested-closures.csv b/core/expression/tests/spec/standard/13-02-nested-closures.csv new file mode 100644 index 00000000..2a67adab --- /dev/null +++ b/core/expression/tests/spec/standard/13-02-nested-closures.csv @@ -0,0 +1,302 @@ +expression (string);input (json 5);output (json 5);note +# three levels of aliases, each referencing the outer ones +map(gs as g, map(g.ys as y, map(y.zs as z, g.k + y.k + z)));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[[12, 13], []], [[28]]] +map(gs as g, map(g.ys as y, map(y.zs as z, g.k + y.k + z)));{gs: [{k: 1, ys: []}]};[[]] +map(gs as g, map(g.ys as y, map(y.zs as z, g.k + y.k + z)));{gs: []};[] +map(gs as g, map(g.ys as y, map(y.zs as z, g.k + y.k + z)));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[[0.875]]] +map(gs as g, map(g.ys as y, map(y.zs as z, g.k + y.k + z)));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};!error +map(gs as g, map(g.ys as y, map(y.zs as z, g.k + y.k + z)));{gs: [{k: 1, ys: [{k: 2}]}]};!error +flatMap(gs as g, flatMap(g.ys as y, map(y.zs ?? [] as z, g.k * 100 + y.k * 10 + z)));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[1011, 1012, 2035] +flatMap(gs as g, flatMap(g.ys as y, map(y.zs ?? [] as z, g.k * 100 + y.k * 10 + z)));{gs: [{k: 1, ys: []}]};[] +flatMap(gs as g, flatMap(g.ys as y, map(y.zs ?? [] as z, g.k * 100 + y.k * 10 + z)));{gs: []};[] +flatMap(gs as g, flatMap(g.ys as y, map(y.zs ?? [] as z, g.k * 100 + y.k * 10 + z)));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[52.625] +flatMap(gs as g, flatMap(g.ys as y, map(y.zs ?? [] as z, g.k * 100 + y.k * 10 + z)));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};!error +flatMap(gs as g, flatMap(g.ys as y, map(y.zs ?? [] as z, g.k * 100 + y.k * 10 + z)));{gs: [{k: 1, ys: [{k: 2}]}]};[] +map(gs as g, map(g.ys as y, len(y.zs ?? []) + len(g.ys)));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[4, 2], [2]] +map(gs as g, map(g.ys as y, len(y.zs ?? []) + len(g.ys)));{gs: [{k: 1, ys: []}]};[[]] +map(gs as g, map(g.ys as y, len(y.zs ?? []) + len(g.ys)));{gs: []};[] +map(gs as g, map(g.ys as y, len(y.zs ?? []) + len(g.ys)));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[2]] +map(gs as g, map(g.ys as y, len(y.zs ?? []) + len(g.ys)));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[2]] +map(gs as g, map(g.ys as y, len(y.zs ?? []) + len(g.ys)));{gs: [{k: 1, ys: [{k: 2}]}]};[[1]] +map(gs as g, count(g.ys as y, some(y.zs ?? [] as z, z > g.k / 10)));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[1, 1] +map(gs as g, count(g.ys as y, some(y.zs ?? [] as z, z > g.k / 10)));{gs: [{k: 1, ys: []}]};[0] +map(gs as g, count(g.ys as y, some(y.zs ?? [] as z, z > g.k / 10)));{gs: []};[] +map(gs as g, count(g.ys as y, some(y.zs ?? [] as z, z > g.k / 10)));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[1] +map(gs as g, count(g.ys as y, some(y.zs ?? [] as z, z > g.k / 10)));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[1] +map(gs as g, count(g.ys as y, some(y.zs ?? [] as z, z > g.k / 10)));{gs: [{k: 1, ys: [{k: 2}]}]};[0] +map(gs as g, sum(map(g.ys as y, sum(map(y.zs ?? [] as z, z * g.k)))));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[30, 100] +map(gs as g, sum(map(g.ys as y, sum(map(y.zs ?? [] as z, z * g.k)))));{gs: [{k: 1, ys: []}]};[0] +map(gs as g, sum(map(g.ys as y, sum(map(y.zs ?? [] as z, z * g.k)))));{gs: []};[] +map(gs as g, sum(map(g.ys as y, sum(map(y.zs ?? [] as z, z * g.k)))));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[0.0625] +map(gs as g, sum(map(g.ys as y, sum(map(y.zs ?? [] as z, z * g.k)))));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[1] +map(gs as g, sum(map(g.ys as y, sum(map(y.zs ?? [] as z, z * g.k)))));{gs: [{k: 1, ys: [{k: 2}]}]};[0] +filter(gs as g, all(g.ys as y, y.k < g.k));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}] +filter(gs as g, all(g.ys as y, y.k < g.k));{gs: [{k: 1, ys: []}]};[{k: 1, ys: []}] +filter(gs as g, all(g.ys as y, y.k < g.k));{gs: []};[] +filter(gs as g, all(g.ys as y, y.k < g.k));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}] +filter(gs as g, all(g.ys as y, y.k < g.k));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};!error +filter(gs as g, all(g.ys as y, y.k < g.k));{gs: [{k: 1, ys: [{k: 2}]}]};[] +map(gs as g, map(g.ys as y, {g: g.k, y: y.k, n: len(y.zs ?? [])}));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[{g: 10, y: 1, n: 2}, {g: 10, y: 2, n: 0}], [{g: 20, y: 3, n: 1}]] +map(gs as g, map(g.ys as y, {g: g.k, y: y.k, n: len(y.zs ?? [])}));{gs: [{k: 1, ys: []}]};[[]] +map(gs as g, map(g.ys as y, {g: g.k, y: y.k, n: len(y.zs ?? [])}));{gs: []};[] +map(gs as g, map(g.ys as y, {g: g.k, y: y.k, n: len(y.zs ?? [])}));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[{g: 0.5, y: 0.25, n: 1}]] +map(gs as g, map(g.ys as y, {g: g.k, y: y.k, n: len(y.zs ?? [])}));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[{g: 1, y: null, n: 1}]] +map(gs as g, map(g.ys as y, {g: g.k, y: y.k, n: len(y.zs ?? [])}));{gs: [{k: 1, ys: [{k: 2}]}]};[[{g: 1, y: 2, n: 0}]] +# bare # mixed with aliases: # is always the innermost element +map(gs as g, map(g.ys, #.k + g.k));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[11, 12], [23]] +map(gs as g, map(g.ys, #.k + g.k));{gs: [{k: 1, ys: []}]};[[]] +map(gs as g, map(g.ys, #.k + g.k));{gs: []};[] +map(gs as g, map(g.ys, #.k + g.k));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[0.75]] +map(gs as g, map(g.ys, #.k + g.k));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};!error +map(gs as g, map(g.ys, #.k + g.k));{gs: [{k: 1, ys: [{k: 2}]}]};[[3]] +map(gs as g, map(g.ys, map(#.zs ?? [], # + g.k)));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[[11, 12], []], [[25]]] +map(gs as g, map(g.ys, map(#.zs ?? [], # + g.k)));{gs: [{k: 1, ys: []}]};[[]] +map(gs as g, map(g.ys, map(#.zs ?? [], # + g.k)));{gs: []};[] +map(gs as g, map(g.ys, map(#.zs ?? [], # + g.k)));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[[0.625]]] +map(gs as g, map(g.ys, map(#.zs ?? [], # + g.k)));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[[2]]] +map(gs as g, map(g.ys, map(#.zs ?? [], # + g.k)));{gs: [{k: 1, ys: [{k: 2}]}]};[[[]]] +map(gs, map(#.ys as y, y.k + #.k));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[2, 4], [6]] +map(gs, map(#.ys as y, y.k + #.k));{gs: [{k: 1, ys: []}]};[[]] +map(gs, map(#.ys as y, y.k + #.k));{gs: []};[] +map(gs, map(#.ys as y, y.k + #.k));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[0.50]] +map(gs, map(#.ys as y, y.k + #.k));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};!error +map(gs, map(#.ys as y, y.k + #.k));{gs: [{k: 1, ys: [{k: 2}]}]};[[4]] +map(gs, map(#.ys, #.k));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[1, 2], [3]] +map(gs, map(#.ys, #.k));{gs: [{k: 1, ys: []}]};[[]] +map(gs, map(#.ys, #.k));{gs: []};[] +map(gs, map(#.ys, #.k));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[0.25]] +map(gs, map(#.ys, #.k));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[null]] +map(gs, map(#.ys, #.k));{gs: [{k: 1, ys: [{k: 2}]}]};[[2]] +map(gs, len(#.ys) + len(map(#.ys, #.zs)));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[4, 2] +map(gs, len(#.ys) + len(map(#.ys, #.zs)));{gs: [{k: 1, ys: []}]};[0] +map(gs, len(#.ys) + len(map(#.ys, #.zs)));{gs: []};[] +map(gs, len(#.ys) + len(map(#.ys, #.zs)));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[2] +map(gs, len(#.ys) + len(map(#.ys, #.zs)));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[2] +map(gs, len(#.ys) + len(map(#.ys, #.zs)));{gs: [{k: 1, ys: [{k: 2}]}]};[2] +map(gs, [#.k, map(#.ys, #.k), #.k]);{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[10, [1, 2], 10], [20, [3], 20]] +map(gs, [#.k, map(#.ys, #.k), #.k]);{gs: [{k: 1, ys: []}]};[[1, [], 1]] +map(gs, [#.k, map(#.ys, #.k), #.k]);{gs: []};[] +map(gs, [#.k, map(#.ys, #.k), #.k]);{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[0.5, [0.25], 0.5]] +map(gs, [#.k, map(#.ys, #.k), #.k]);{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[1, [null], 1]] +map(gs, [#.k, map(#.ys, #.k), #.k]);{gs: [{k: 1, ys: [{k: 2}]}]};[[1, [2], 1]] +map(gs, {before: #.k, inner: sum(map(#.ys, 1)), after: #.k});{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[{before: 10, inner: 2, after: 10}, {before: 20, inner: 1, after: 20}] +map(gs, {before: #.k, inner: sum(map(#.ys, 1)), after: #.k});{gs: [{k: 1, ys: []}]};[{before: 1, inner: 0, after: 1}] +map(gs, {before: #.k, inner: sum(map(#.ys, 1)), after: #.k});{gs: []};[] +map(gs, {before: #.k, inner: sum(map(#.ys, 1)), after: #.k});{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[{before: 0.5, inner: 1, after: 0.5}] +map(gs, {before: #.k, inner: sum(map(#.ys, 1)), after: #.k});{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[{before: 1, inner: 1, after: 1}] +map(gs, {before: #.k, inner: sum(map(#.ys, 1)), after: #.k});{gs: [{k: 1, ys: [{k: 2}]}]};[{before: 1, inner: 1, after: 1}] +map(gs as g, map(g.ys as g, g.k));{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[1, 2], [3]] +map(gs as g, map(g.ys as g, g.k));{gs: [{k: 1, ys: []}]};[[]] +map(gs as g, map(g.ys as g, g.k));{gs: []};[] +map(gs as g, map(g.ys as g, g.k));{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[0.25]] +map(gs as g, map(g.ys as g, g.k));{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[null]] +map(gs as g, map(g.ys as g, g.k));{gs: [{k: 1, ys: [{k: 2}]}]};[[2]] +map(gs as g, [map(g.ys as g, g.k), g.k]);{gs: [{k: 10, ys: [{k: 1, zs: [1, 2]}, {k: 2, zs: []}]}, {k: 20, ys: [{k: 3, zs: [5]}]}]};[[[1, 2], 10], [[3], 20]] +map(gs as g, [map(g.ys as g, g.k), g.k]);{gs: [{k: 1, ys: []}]};[[[], 1]] +map(gs as g, [map(g.ys as g, g.k), g.k]);{gs: []};[] +map(gs as g, [map(g.ys as g, g.k), g.k]);{gs: [{k: 0.5, ys: [{k: 0.25, zs: [0.125]}]}]};[[[0.25], 0.5]] +map(gs as g, [map(g.ys as g, g.k), g.k]);{gs: [{k: 1, ys: [{k: null, zs: [1]}]}]};[[[null], 1]] +map(gs as g, [map(g.ys as g, g.k), g.k]);{gs: [{k: 1, ys: [{k: 2}]}]};[[[2], 1]] +# # after an inner closure returns refers to the outer element again +map(xs, sum(map(#, # * 2)) + len(#));{xs: [[1, 2], [3], []]};[8, 7, 0] +map(xs, sum(map(#, # * 2)) + len(#));{xs: [[0.5], [0.25, 0.25]]};[2.0, 3.00] +map(xs, sum(map(#, # * 2)) + len(#));{xs: []};[] +map(xs, sum(map(#, # * 2)) + len(#));{xs: [[1, 'a']]};!error +map(xs, sum(map(#, # * 2)) + len(#));{xs: [null]};!error +map(xs, len(#) + sum(map(#, # * 2)));{xs: [[1, 2], [3], []]};[8, 7, 0] +map(xs, len(#) + sum(map(#, # * 2)));{xs: [[0.5], [0.25, 0.25]]};[2.0, 3.00] +map(xs, len(#) + sum(map(#, # * 2)));{xs: []};[] +map(xs, len(#) + sum(map(#, # * 2)));{xs: [[1, 'a']]};!error +map(xs, len(#) + sum(map(#, # * 2)));{xs: [null]};!error +map(xs, [len(#), count(#, true), len(#)]);{xs: [[1, 2], [3], []]};[[2, 2, 2], [1, 1, 1], [0, 0, 0]] +map(xs, [len(#), count(#, true), len(#)]);{xs: [[0.5], [0.25, 0.25]]};[[1, 1, 1], [2, 2, 2]] +map(xs, [len(#), count(#, true), len(#)]);{xs: []};[] +map(xs, [len(#), count(#, true), len(#)]);{xs: [[1, 'a']]};[[2, 2, 2]] +map(xs, [len(#), count(#, true), len(#)]);{xs: [null]};!error +filter(xs, some(#, # > 1) or len(#) == 0);{xs: [[1, 2], [3], []]};[[1, 2], [3], []] +filter(xs, some(#, # > 1) or len(#) == 0);{xs: [[0.5], [0.25, 0.25]]};[] +filter(xs, some(#, # > 1) or len(#) == 0);{xs: []};[] +filter(xs, some(#, # > 1) or len(#) == 0);{xs: [[1, 'a']]};!error +filter(xs, some(#, # > 1) or len(#) == 0);{xs: [null]};!error +map(xs, filter(#, # != len(#)));{xs: [['ab', 'c']]};[['ab', 'c']] +map(xs as r, filter(r, # != len(r)));{xs: [[1, 2], [3], []]};[[1], [3], []] +map(xs as r, filter(r, # != len(r)));{xs: [[0.5], [0.25, 0.25]]};[[0.5], [0.25, 0.25]] +map(xs as r, filter(r, # != len(r)));{xs: []};[] +map(xs as r, filter(r, # != len(r)));{xs: [[1, 'a']]};[[1, 'a']] +map(xs as r, filter(r, # != len(r)));{xs: [null]};!error +# dynamic keys inside closures +map(rows, #[col]);{col: 'price', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[1, 3, null] +map(rows, #[col]);{col: 'qty', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[2, 4, 5] +map(rows, #[col]);{col: 'none', rows: [{price: 1}]};[null] +map(rows, #[col]);{col: null, rows: [{price: 1}]};[null] +map(rows, #[col]);{col: 'price', rows: []};[] +map(rows, #[col]);{col: 0, rows: [{price: 1}]};[null] +map(rows, #[col] ?? 0);{col: 'price', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[1, 3, 0] +map(rows, #[col] ?? 0);{col: 'qty', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[2, 4, 5] +map(rows, #[col] ?? 0);{col: 'none', rows: [{price: 1}]};[0] +map(rows, #[col] ?? 0);{col: null, rows: [{price: 1}]};[0] +map(rows, #[col] ?? 0);{col: 'price', rows: []};[] +map(rows, #[col] ?? 0);{col: 0, rows: [{price: 1}]};[0] +sum(map(rows, #[col] ?? 0));{col: 'price', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};4 +sum(map(rows, #[col] ?? 0));{col: 'qty', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};11 +sum(map(rows, #[col] ?? 0));{col: 'none', rows: [{price: 1}]};0 +sum(map(rows, #[col] ?? 0));{col: null, rows: [{price: 1}]};0 +sum(map(rows, #[col] ?? 0));{col: 'price', rows: []};0 +sum(map(rows, #[col] ?? 0));{col: 0, rows: [{price: 1}]};0 +filter(rows, #[col] != null);{col: 'price', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[{price: 1, qty: 2}, {price: 3, qty: 4}] +filter(rows, #[col] != null);{col: 'qty', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}] +filter(rows, #[col] != null);{col: 'none', rows: [{price: 1}]};[] +filter(rows, #[col] != null);{col: null, rows: [{price: 1}]};[] +filter(rows, #[col] != null);{col: 'price', rows: []};[] +filter(rows, #[col] != null);{col: 0, rows: [{price: 1}]};[] +map(rows as r, r[col]);{col: 'price', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[1, 3, null] +map(rows as r, r[col]);{col: 'qty', rows: [{price: 1, qty: 2}, {price: 3, qty: 4}, {qty: 5}]};[2, 4, 5] +map(rows as r, r[col]);{col: 'none', rows: [{price: 1}]};[null] +map(rows as r, r[col]);{col: null, rows: [{price: 1}]};[null] +map(rows as r, r[col]);{col: 'price', rows: []};[] +map(rows as r, r[col]);{col: 0, rows: [{price: 1}]};[null] +map(cols as c, map(rows, #[c]));{cols: ['a', 'b'], rows: [{a: 1, b: 2}, {a: 3, b: 4}]};[[1, 3], [2, 4]] +map(cols as c, map(rows, #[c]));{cols: ['b'], rows: [{a: 1, b: 2}, {a: 3}]};[[2, null]] +map(cols as c, map(rows, #[c]));{cols: [], rows: [{a: 1}]};[] +map(cols as c, map(rows, #[c]));{cols: ['a', 'z'], rows: []};[[], []] +map(cols as c, map(rows, #[c]));{cols: ['a', 'a'], rows: [{a: 'x'}]};[['x'], ['x']] +map(rows as r, map(cols, r[#]));{cols: ['a', 'b'], rows: [{a: 1, b: 2}, {a: 3, b: 4}]};[[1, 2], [3, 4]] +map(rows as r, map(cols, r[#]));{cols: ['b'], rows: [{a: 1, b: 2}, {a: 3}]};[[2], [null]] +map(rows as r, map(cols, r[#]));{cols: [], rows: [{a: 1}]};[[]] +map(rows as r, map(cols, r[#]));{cols: ['a', 'z'], rows: []};[] +map(rows as r, map(cols, r[#]));{cols: ['a', 'a'], rows: [{a: 'x'}]};[['x', 'x']] +map(rows, map(cols as c, #[c]));{cols: ['a', 'b'], rows: [{a: 1, b: 2}, {a: 3, b: 4}]};[[null, null], [null, null]] +map(rows, map(cols as c, #[c]));{cols: ['b'], rows: [{a: 1, b: 2}, {a: 3}]};[[null], [null]] +map(rows, map(cols as c, #[c]));{cols: [], rows: [{a: 1}]};[[]] +map(rows, map(cols as c, #[c]));{cols: ['a', 'z'], rows: []};[] +map(rows, map(cols as c, #[c]));{cols: ['a', 'a'], rows: [{a: 'x'}]};[[null, null]] +map(cols as c, {name: c, filled: count(rows, #[c] != null)});{cols: ['a', 'b'], rows: [{a: 1, b: 2}, {a: 3, b: 4}]};[{name: 'a', filled: 2}, {name: 'b', filled: 2}] +map(cols as c, {name: c, filled: count(rows, #[c] != null)});{cols: ['b'], rows: [{a: 1, b: 2}, {a: 3}]};[{name: 'b', filled: 1}] +map(cols as c, {name: c, filled: count(rows, #[c] != null)});{cols: [], rows: [{a: 1}]};[] +map(cols as c, {name: c, filled: count(rows, #[c] != null)});{cols: ['a', 'z'], rows: []};[{name: 'a', filled: 0}, {name: 'z', filled: 0}] +map(cols as c, {name: c, filled: count(rows, #[c] != null)});{cols: ['a', 'a'], rows: [{a: 'x'}]};[{name: 'a', filled: 1}, {name: 'a', filled: 1}] +map(rows, merge(map(cols as c, {[c]: #[c]})));{cols: ['a', 'b'], rows: [{a: 1, b: 2}, {a: 3, b: 4}]};[{a: null, b: null}, {a: null, b: null}] +map(rows, merge(map(cols as c, {[c]: #[c]})));{cols: ['b'], rows: [{a: 1, b: 2}, {a: 3}]};[{b: null}, {b: null}] +map(rows, merge(map(cols as c, {[c]: #[c]})));{cols: [], rows: [{a: 1}]};[{}] +map(rows, merge(map(cols as c, {[c]: #[c]})));{cols: ['a', 'z'], rows: []};[] +map(rows, merge(map(cols as c, {[c]: #[c]})));{cols: ['a', 'a'], rows: [{a: 'x'}]};[{a: null}] +map(rows as r, merge(map(cols as c, {[c]: r[c]})));{cols: ['a', 'b'], rows: [{a: 1, b: 2}, {a: 3, b: 4}]};[{a: 1, b: 2}, {a: 3, b: 4}] +map(rows as r, merge(map(cols as c, {[c]: r[c]})));{cols: ['b'], rows: [{a: 1, b: 2}, {a: 3}]};[{b: 2}, {b: null}] +map(rows as r, merge(map(cols as c, {[c]: r[c]})));{cols: [], rows: [{a: 1}]};[{}] +map(rows as r, merge(map(cols as c, {[c]: r[c]})));{cols: ['a', 'z'], rows: []};[] +map(rows as r, merge(map(cols as c, {[c]: r[c]})));{cols: ['a', 'a'], rows: [{a: 'x'}]};[{a: 'x'}] +map(rows, #.a[i]);{i: 0, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[10, 30, null] +map(rows, #.a[i]);{i: 1, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[20, null, null] +map(rows, #.a[i]);{i: 5, rows: [{a: [10, 20]}]};[null] +map(rows, #.a[i]);{i: 1, rows: [{a: 'xyz'}, {}]};['y', null] +map(rows, #.a[i]);{i: null, rows: [{a: [1]}]};[null] +map(rows, #.a[i] ?? -1);{i: 0, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[10, 30, -1] +map(rows, #.a[i] ?? -1);{i: 1, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[20, -1, -1] +map(rows, #.a[i] ?? -1);{i: 5, rows: [{a: [10, 20]}]};[-1] +map(rows, #.a[i] ?? -1);{i: 1, rows: [{a: 'xyz'}, {}]};['y', -1] +map(rows, #.a[i] ?? -1);{i: null, rows: [{a: [1]}]};[-1] +map(rows as r, r.a[i]);{i: 0, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[10, 30, null] +map(rows as r, r.a[i]);{i: 1, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[20, null, null] +map(rows as r, r.a[i]);{i: 5, rows: [{a: [10, 20]}]};[null] +map(rows as r, r.a[i]);{i: 1, rows: [{a: 'xyz'}, {}]};['y', null] +map(rows as r, r.a[i]);{i: null, rows: [{a: [1]}]};[null] +map(rows, #['a'][i]);{i: 0, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[10, 30, null] +map(rows, #['a'][i]);{i: 1, rows: [{a: [10, 20]}, {a: [30]}, {a: []}]};[20, null, null] +map(rows, #['a'][i]);{i: 5, rows: [{a: [10, 20]}]};[null] +map(rows, #['a'][i]);{i: 1, rows: [{a: 'xyz'}, {}]};['y', null] +map(rows, #['a'][i]);{i: null, rows: [{a: [1]}]};[null] +# index-based zip and positional closures over intervals +map([0..len(xs) - 1], {x: xs[#], y: ys[#]});{xs: ['a', 'b', 'c'], ys: [1, 2, 3]};[{x: 'a', y: 1}, {x: 'b', y: 2}, {x: 'c', y: 3}] +map([0..len(xs) - 1], {x: xs[#], y: ys[#]});{xs: ['a', 'b'], ys: [1]};[{x: 'a', y: 1}, {x: 'b', y: null}] +map([0..len(xs) - 1], {x: xs[#], y: ys[#]});{xs: [], ys: [1]};[] +map([0..len(xs) - 1], {x: xs[#], y: ys[#]});{xs: ['x'], ys: []};[{x: 'x', y: null}] +map([0..len(xs) - 1] as i, xs[i] + string(ys[i] ?? 0));{xs: ['a', 'b', 'c'], ys: [1, 2, 3]};['a1', 'b2', 'c3'] +map([0..len(xs) - 1] as i, xs[i] + string(ys[i] ?? 0));{xs: ['a', 'b'], ys: [1]};['a1', 'b0'] +map([0..len(xs) - 1] as i, xs[i] + string(ys[i] ?? 0));{xs: [], ys: [1]};[] +map([0..len(xs) - 1] as i, xs[i] + string(ys[i] ?? 0));{xs: ['x'], ys: []};['x0'] +filter([0..len(ys) - 1], ys[#] > 1);{xs: ['a', 'b', 'c'], ys: [1, 2, 3]};[1, 2] +filter([0..len(ys) - 1], ys[#] > 1);{xs: ['a', 'b'], ys: [1]};[] +filter([0..len(ys) - 1], ys[#] > 1);{xs: [], ys: [1]};[] +filter([0..len(ys) - 1], ys[#] > 1);{xs: ['x'], ys: []};[] +map([0..len(xs)), xs[#]);{xs: ['a', 'b', 'c'], ys: [1, 2, 3]};['a', 'b', 'c'] +map([0..len(xs)), xs[#]);{xs: ['a', 'b'], ys: [1]};['a', 'b'] +map([0..len(xs)), xs[#]);{xs: [], ys: [1]};[] +map([0..len(xs)), xs[#]);{xs: ['x'], ys: []};['x'] +map([0..len(m[0]) - 1] as j, map(m, #[j]));{m: [[1, 2, 3], [4, 5, 6]]};[[1, 4], [2, 5], [3, 6]] +map([0..len(m[0]) - 1] as j, map(m, #[j]));{m: [[1], [2], [3]]};[[1, 2, 3]] +map([0..len(m[0]) - 1] as j, map(m, #[j]));{m: [[7, 8]]};[[7], [8]] +map([0..len(m[0]) - 1] as j, map(m, #[j]));{m: [[1, 2], [3]]};[[1, 3], [2, null]] +map(m as r, map([0..len(r) - 1] as j, r[j] * (j + 1)));{m: [[1, 2, 3], [4, 5, 6]]};[[1, 4, 9], [4, 10, 18]] +map(m as r, map([0..len(r) - 1] as j, r[j] * (j + 1)));{m: [[1], [2], [3]]};[[1], [2], [3]] +map(m as r, map([0..len(r) - 1] as j, r[j] * (j + 1)));{m: [[7, 8]]};[[7, 16]] +map(m as r, map([0..len(r) - 1] as j, r[j] * (j + 1)));{m: [[1, 2], [3]]};[[1, 4], [3]] +sum(map([0..len(m) - 1] as i, m[i][i] ?? 0));{m: [[1, 2, 3], [4, 5, 6]]};6 +sum(map([0..len(m) - 1] as i, m[i][i] ?? 0));{m: [[1], [2], [3]]};1 +sum(map([0..len(m) - 1] as i, m[i][i] ?? 0));{m: [[7, 8]]};7 +sum(map([0..len(m) - 1] as i, m[i][i] ?? 0));{m: [[1, 2], [3]]};1 +# outer input fields and aliases with colliding names +map(xs, map(#.ys, #.k + k));{k: 100, xs: [{k: 1, ys: [{k: 2}]}]};[[102]] +map(xs, map(#.ys, #.k + k));{k: 0, xs: [{k: 1, ys: []}, {ys: [{k: 3}]}]};[[], [3]] +map(xs, map(#.ys, #.k + k));{k: 5, xs: []};[] +map(xs as k, map(k.ys, #.k));{k: 100, xs: [{k: 1, ys: [{k: 2}]}]};[[2]] +map(xs as k, map(k.ys, #.k));{k: 0, xs: [{k: 1, ys: []}, {ys: [{k: 3}]}]};[[], [3]] +map(xs as k, map(k.ys, #.k));{k: 5, xs: []};[] +map(xs as x, map(x.ys as y, [k, x.k ?? 0, y.k]));{k: 100, xs: [{k: 1, ys: [{k: 2}]}]};[[[100, 1, 2]]] +map(xs as x, map(x.ys as y, [k, x.k ?? 0, y.k]));{k: 0, xs: [{k: 1, ys: []}, {ys: [{k: 3}]}]};[[], [[0, 0, 3]]] +map(xs as x, map(x.ys as y, [k, x.k ?? 0, y.k]));{k: 5, xs: []};[] +map(xs, $root.k + len(#.ys));{k: 100, xs: [{k: 1, ys: [{k: 2}]}]};[101] +map(xs, $root.k + len(#.ys));{k: 0, xs: [{k: 1, ys: []}, {ys: [{k: 3}]}]};[0, 1] +map(xs, $root.k + len(#.ys));{k: 5, xs: []};[] +map(xs as xs, len(xs.ys));{k: 100, xs: [{k: 1, ys: [{k: 2}]}]};[1] +map(xs as xs, len(xs.ys));{k: 0, xs: [{k: 1, ys: []}, {ys: [{k: 3}]}]};[0, 1] +map(xs as xs, len(xs.ys));{k: 5, xs: []};[] +# closures over results of other closures, nested three deep +map(map(map(xs, # + 1), # * 2), # - 1);{xs: [1, 2, 3, 4]};[3, 5, 7, 9] +map(map(map(xs, # + 1), # * 2), # - 1);{xs: [0.5, 1.5]};[2.0, 4.0] +map(map(map(xs, # + 1), # * 2), # - 1);{xs: []};[] +map(map(map(xs, # + 1), # * 2), # - 1);{xs: [-1, 0, 1]};[-1, 1, 3] +filter(map(filter(xs, # > 0), # * 10), # < 30);{xs: [1, 2, 3, 4]};[10, 20] +filter(map(filter(xs, # > 0), # * 10), # < 30);{xs: [0.5, 1.5]};[5.0, 15.0] +filter(map(filter(xs, # > 0), # * 10), # < 30);{xs: []};[] +filter(map(filter(xs, # > 0), # * 10), # < 30);{xs: [-1, 0, 1]};[10] +map(xs as a, map(xs as b, a * b));{xs: [1, 2, 3, 4]};[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]] +map(xs as a, map(xs as b, a * b));{xs: [0.5, 1.5]};[[0.25, 0.75], [0.75, 2.25]] +map(xs as a, map(xs as b, a * b));{xs: []};[] +map(xs as a, map(xs as b, a * b));{xs: [-1, 0, 1]};[[1, -0, -1], [-0, 0, 0], [-1, 0, 1]] +flatMap(xs as a, map(filter(xs, # > a), [a, #]));{xs: [1, 2, 3, 4]};[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] +flatMap(xs as a, map(filter(xs, # > a), [a, #]));{xs: [0.5, 1.5]};[[0.5, 1.5]] +flatMap(xs as a, map(filter(xs, # > a), [a, #]));{xs: []};[] +flatMap(xs as a, map(filter(xs, # > a), [a, #]));{xs: [-1, 0, 1]};[[-1, 0], [-1, 1], [0, 1]] +count(xs as a, some(xs as b, a + b == 0 and a != b));{xs: [1, 2, 3, 4]};0 +count(xs as a, some(xs as b, a + b == 0 and a != b));{xs: [0.5, 1.5]};0 +count(xs as a, some(xs as b, a + b == 0 and a != b));{xs: []};0 +count(xs as a, some(xs as b, a + b == 0 and a != b));{xs: [-1, 0, 1]};2 +map(xs as a, count(xs, # < a));{xs: [1, 2, 3, 4]};[0, 1, 2, 3] +map(xs as a, count(xs, # < a));{xs: [0.5, 1.5]};[0, 1] +map(xs as a, count(xs, # < a));{xs: []};[] +map(xs as a, count(xs, # < a));{xs: [-1, 0, 1]};[0, 1, 2] +sum(flatMap(xs as a, map(xs as b, a * b)));{xs: [1, 2, 3, 4]};100 +sum(flatMap(xs as a, map(xs as b, a * b)));{xs: [0.5, 1.5]};4.00 +sum(flatMap(xs as a, map(xs as b, a * b)));{xs: []};0 +sum(flatMap(xs as a, map(xs as b, a * b)));{xs: [-1, 0, 1]};0 +map(xs as a, map(xs as b, map(xs as c, a + b + c)))[0][0];{xs: [1, 2, 3, 4]};[3, 4, 5, 6] +map(xs as a, map(xs as b, map(xs as c, a + b + c)))[0][0];{xs: [0.5, 1.5]};[1.5, 2.5] +map(xs as a, map(xs as b, map(xs as c, a + b + c)))[0][0];{xs: []};null +map(xs as a, map(xs as b, map(xs as c, a + b + c)))[0][0];{xs: [-1, 0, 1]};[-3, -2, -1] +len(flatMap(xs as a, flatMap(xs as b, map(xs, 1))));{xs: [1, 2, 3, 4]};64 +len(flatMap(xs as a, flatMap(xs as b, map(xs, 1))));{xs: [0.5, 1.5]};8 +len(flatMap(xs as a, flatMap(xs as b, map(xs, 1))));{xs: []};0 +len(flatMap(xs as a, flatMap(xs as b, map(xs, 1))));{xs: [-1, 0, 1]};27 +# closures over strings split into nested lists +map(split(csv, ','), split(#, ':'));{csv: 'a:1,b:2,c:3'};[['a', '1'], ['b', '2'], ['c', '3']] +map(split(csv, ','), split(#, ':'));{csv: 'x:10'};[['x', '10']] +map(split(csv, ','), split(#, ':'));{csv: 'p:1,q:'};[['p', '1'], ['q', '']] +map(split(csv, ','), split(#, ':')[0]);{csv: 'a:1,b:2,c:3'};['a', 'b', 'c'] +map(split(csv, ','), split(#, ':')[0]);{csv: 'x:10'};['x'] +map(split(csv, ','), split(#, ':')[0]);{csv: 'p:1,q:'};['p', 'q'] +merge(map(split(csv, ','), {[split(#, ':')[0]]: split(#, ':')[1]}));{csv: 'a:1,b:2,c:3'};{a: '1', b: '2', c: '3'} +merge(map(split(csv, ','), {[split(#, ':')[0]]: split(#, ':')[1]}));{csv: 'x:10'};{x: '10'} +merge(map(split(csv, ','), {[split(#, ':')[0]]: split(#, ':')[1]}));{csv: 'p:1,q:'};{p: '1', q: ''} +filter(map(split(csv, ','), split(#, ':')), #[1] != '');{csv: 'a:1,b:2,c:3'};[['a', '1'], ['b', '2'], ['c', '3']] +filter(map(split(csv, ','), split(#, ':')), #[1] != '');{csv: 'x:10'};[['x', '10']] +filter(map(split(csv, ','), split(#, ':')), #[1] != '');{csv: 'p:1,q:'};[['p', '1']] diff --git a/core/expression/tests/spec/standard/13-03-reductions.csv b/core/expression/tests/spec/standard/13-03-reductions.csv new file mode 100644 index 00000000..563a6a02 --- /dev/null +++ b/core/expression/tests/spec/standard/13-03-reductions.csv @@ -0,0 +1,398 @@ +expression (string);input (json 5);output (json 5);note +# sums over nested line items +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};81.75 +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};990.715 +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};39.96 +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: []};0 +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};0.4 +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', items: [{sku: 'a', qty: 1}]}]};!error +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1'}]};!error +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: null};!error +sum(flatMap(orders, map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: '2', price: 1}]}]};!error +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};81.75 +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};990.715 +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};39.96 +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: []};0 +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};0.4 +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', items: [{sku: 'a', qty: 1}]}]};!error +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1'}]};!error +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: null};!error +sum(map(orders, sum(map(#.items, #.qty * #.price))));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: '2', price: 1}]}]};!error +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[5.40, 30, 46.35] +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[20.515, 6.25, 443.71, 520.24] +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[39.96, 0] +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'gold', items: []}]};[0] +map(orders, sum(map(#.items, #.qty * #.price)));{orders: []};[] +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[0.4] +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', items: [{sku: 'a', qty: 1}]}]};!error +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1'}]};!error +map(orders, sum(map(#.items, #.qty * #.price)));{orders: null};!error +map(orders, sum(map(#.items, #.qty * #.price)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: '2', price: 1}]}]};!error +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};24 +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};37 +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};4 +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +sum(flatMap(orders, map(#.items, #.qty)));{orders: []};0 +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};3 +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', items: [{sku: 'a', qty: 1}]}]};1 +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1'}]};!error +sum(flatMap(orders, map(#.items, #.qty)));{orders: null};!error +sum(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: '2', price: 1}]}]};!error +sum(flatMap(orders as o, map(o.items as i, i.qty * i.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};81.75 +sum(flatMap(orders as o, map(o.items as i, i.qty * i.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};990.715 +sum(flatMap(orders as o, map(o.items as i, i.qty * i.price)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};39.96 +sum(flatMap(orders as o, map(o.items as i, i.qty * i.price)));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +sum(flatMap(orders as o, map(o.items as i, i.qty * i.price)));{orders: []};0 +sum(flatMap(orders as o, map(o.items as i, i.qty * i.price)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};0.4 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};81.75 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};990.715 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};39.96 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: []};0 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};0.4 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', items: [{sku: 'a', qty: 1}]}]};0 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1'}]};0 +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: null};!error +sum(flatMap(orders, map(#.items ?? [], (#.qty ?? 0) * (#.price ?? 0))));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: '2', price: 1}]}]};!error +len(flatMap(orders, #.items));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};7 +len(flatMap(orders, #.items));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};11 +len(flatMap(orders, #.items));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};1 +len(flatMap(orders, #.items));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +len(flatMap(orders, #.items));{orders: []};0 +len(flatMap(orders, #.items));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};2 +len(flatMap(orders, #.items));{orders: [{id: 'o1', items: [{sku: 'a', qty: 1}]}]};1 +len(flatMap(orders, #.items));{orders: [{id: 'o1'}]};1 +len(flatMap(orders, #.items));{orders: null};!error +len(flatMap(orders, #.items));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: '2', price: 1}]}]};1 +count(flatMap(orders, #.items), #.qty >= 3);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};5 +count(flatMap(orders, #.items), #.qty >= 3);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};8 +count(flatMap(orders, #.items), #.qty >= 3);{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};1 +count(flatMap(orders, #.items), #.qty >= 3);{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +count(flatMap(orders, #.items), #.qty >= 3);{orders: []};0 +count(flatMap(orders, #.items), #.qty >= 3);{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};0 +max(flatMap(orders, map(#.items, #.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};10 +max(flatMap(orders, map(#.items, #.price)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};100 +max(flatMap(orders, map(#.items, #.price)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};9.99 +max(flatMap(orders, map(#.items, #.price)));{orders: [{id: 'o1', tier: 'gold', items: []}]};!error +max(flatMap(orders, map(#.items, #.price)));{orders: []};!error +max(flatMap(orders, map(#.items, #.price)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};0.2 +min(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};2 +min(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};1 +min(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};4 +min(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: []}]};!error +min(flatMap(orders, map(#.items, #.qty)));{orders: []};!error +min(flatMap(orders, map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};1 +max(map(orders, len(#.items)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};3 +max(map(orders, len(#.items)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};4 +max(map(orders, len(#.items)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};1 +max(map(orders, len(#.items)));{orders: [{id: 'o1', tier: 'gold', items: []}]};0 +max(map(orders, len(#.items)));{orders: []};!error +max(map(orders, len(#.items)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};2 +map(orders, max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[5, 3, 5] +map(orders, max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[5, 5, 4, 5] +map(orders, max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};!error +map(orders, max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: []}]};!error +map(orders, max(map(#.items, #.qty)));{orders: []};[] +map(orders, max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[2] +map(filter(orders, len(#.items) > 0), max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[5, 3, 5] +map(filter(orders, len(#.items) > 0), max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[5, 5, 4, 5] +map(filter(orders, len(#.items) > 0), max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[4] +map(filter(orders, len(#.items) > 0), max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: []}]};[] +map(filter(orders, len(#.items) > 0), max(map(#.items, #.qty)));{orders: []};[] +map(filter(orders, len(#.items) > 0), max(map(#.items, #.qty)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[2] +avg(map(filter(orders, len(#.items) > 0), len(#.items)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};2.33333333333333333333333333333333333333333333333333333333333 +avg(map(filter(orders, len(#.items) > 0), len(#.items)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};2.75 +avg(map(filter(orders, len(#.items) > 0), len(#.items)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};1 +avg(map(filter(orders, len(#.items) > 0), len(#.items)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};2 +# filtered reductions with outer parameters +sum(map(filter(flatMap(orders, #.items), #.sku == sku), #.qty));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};5 +sum(map(filter(flatMap(orders, #.items), #.sku == sku), #.qty));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};13 +sum(map(filter(flatMap(orders, #.items), #.sku == sku), #.qty));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};4 +sum(map(filter(flatMap(orders, #.items), #.sku == sku), #.qty));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};3 +sum(map(filter(flatMap(orders, #.items), #.sku == sku), #.qty));{orders: [], sku: 'a', min: 1};0 +sum(map(filter(flatMap(orders, #.items), #.sku == sku), #.qty));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};0 +count(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};2 +count(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};3 +count(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};1 +count(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};1 +count(orders, some(#.items, #.sku == sku));{orders: [], sku: 'a', min: 1};0 +count(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};0 +map(filter(orders, some(#.items, #.qty >= min)), #.id);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};['o1', 'o2', 'o3'] +map(filter(orders, some(#.items, #.qty >= min)), #.id);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};['o1', 'o2', 'o3', 'o4'] +map(filter(orders, some(#.items, #.qty >= min)), #.id);{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};['o1'] +map(filter(orders, some(#.items, #.qty >= min)), #.id);{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};['o1'] +map(filter(orders, some(#.items, #.qty >= min)), #.id);{orders: [], sku: 'a', min: 1};[] +map(filter(orders, some(#.items, #.qty >= min)), #.id);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};['o1', 'o2', 'o3', 'o4'] +filter(orders as o, all(o.items, #.qty >= min) and len(o.items) > 0);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};[{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}] +filter(orders as o, all(o.items, #.qty >= min) and len(o.items) > 0);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};[{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}] +filter(orders as o, all(o.items, #.qty >= min) and len(o.items) > 0);{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};[{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}] +filter(orders as o, all(o.items, #.qty >= min) and len(o.items) > 0);{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};[{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}] +filter(orders as o, all(o.items, #.qty >= min) and len(o.items) > 0);{orders: [], sku: 'a', min: 1};[] +filter(orders as o, all(o.items, #.qty >= min) and len(o.items) > 0);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};[{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}] +map(orders as o, count(o.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};[0, 1, 1] +map(orders as o, count(o.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};[1, 1, 0, 1] +map(orders as o, count(o.items, #.sku == sku));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};[1, 0] +map(orders as o, count(o.items, #.sku == sku));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};[2] +map(orders as o, count(o.items, #.sku == sku));{orders: [], sku: 'a', min: 1};[] +map(orders as o, count(o.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};[0, 0, 0, 0] +map(orders as o, sum(map(filter(o.items, #.qty >= min), #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};[10, 3, 11] +map(orders as o, sum(map(filter(o.items, #.qty >= min), #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};[9, 5, 11, 12] +map(orders as o, sum(map(filter(o.items, #.qty >= min), #.qty)));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};[4, 0] +map(orders as o, sum(map(filter(o.items, #.qty >= min), #.qty)));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};[3] +map(orders as o, sum(map(filter(o.items, #.qty >= min), #.qty)));{orders: [], sku: 'a', min: 1};[] +map(orders as o, sum(map(filter(o.items, #.qty >= min), #.qty)));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};[9, 5, 11, 12] +none(flatMap(orders, #.items), #.sku == sku);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};false +none(flatMap(orders, #.items), #.sku == sku);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};false +none(flatMap(orders, #.items), #.sku == sku);{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};false +none(flatMap(orders, #.items), #.sku == sku);{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};false +none(flatMap(orders, #.items), #.sku == sku);{orders: [], sku: 'a', min: 1};true +none(flatMap(orders, #.items), #.sku == sku);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};true +one(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};false +one(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};false +one(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};true +one(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};true +one(orders, some(#.items, #.sku == sku));{orders: [], sku: 'a', min: 1};false +one(orders, some(#.items, #.sku == sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};false +sku in flatMap(orders, map(#.items, #.sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};true +sku in flatMap(orders, map(#.items, #.sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};true +sku in flatMap(orders, map(#.items, #.sku));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};true +sku in flatMap(orders, map(#.items, #.sku));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};true +sku in flatMap(orders, map(#.items, #.sku));{orders: [], sku: 'a', min: 1};false +sku in flatMap(orders, map(#.items, #.sku));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};false +contains(flatMap(orders, map(#.items, #.sku)), sku);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}], sku: 'a', min: 2};true +contains(flatMap(orders, map(#.items, #.sku)), sku);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'b', min: 1};true +contains(flatMap(orders, map(#.items, #.sku)), sku);{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}], sku: 'c', min: 3};true +contains(flatMap(orders, map(#.items, #.sku)), sku);{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}], sku: 'a', min: 1};true +contains(flatMap(orders, map(#.items, #.sku)), sku);{orders: [], sku: 'a', min: 1};false +contains(flatMap(orders, map(#.items, #.sku)), sku);{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}], sku: 'z', min: 1};false +# group-by with mergeDeep: key to list of values +mergeDeep(map(orders, {[#.tier]: [#.id]}));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};{silver: ['o1', 'o2', 'o3']} +mergeDeep(map(orders, {[#.tier]: [#.id]}));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};{silver: ['o1'], bronze: ['o2', 'o3', 'o4']} +mergeDeep(map(orders, {[#.tier]: [#.id]}));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};{bronze: ['o1'], silver: ['o2']} +mergeDeep(map(orders, {[#.tier]: [#.id]}));{orders: [{id: 'o1', tier: 'gold', items: []}]};{gold: ['o1']} +mergeDeep(map(orders, {[#.tier]: [#.id]}));{orders: []};{} +mergeDeep(map(orders, {[#.tier]: [#.id]}));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};{gold: ['o1']} +mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};{b: [5, 5], c: [3, 2], a: [3, 2], d: [4]} +mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};{c: [1, 3, 1], b: [3, 5, 5], d: [5, 4, 5, 1], a: [4]} +mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};{c: [4]} +mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})));{orders: [{id: 'o1', tier: 'gold', items: []}]};{} +mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})));{orders: []};{} +mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};{a: [2, 1]} +mergeDeep(flatMap(orders as o, map(o.items, {[#.sku]: [o.id]})));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};{b: ['o1', 'o3'], c: ['o1', 'o1'], a: ['o2', 'o3'], d: ['o3']} +mergeDeep(flatMap(orders as o, map(o.items, {[#.sku]: [o.id]})));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};{c: ['o1', 'o3', 'o4'], b: ['o1', 'o2', 'o4'], d: ['o1', 'o3', 'o4', 'o4'], a: ['o3']} +mergeDeep(flatMap(orders as o, map(o.items, {[#.sku]: [o.id]})));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};{c: ['o1']} +mergeDeep(flatMap(orders as o, map(o.items, {[#.sku]: [o.id]})));{orders: [{id: 'o1', tier: 'gold', items: []}]};{} +mergeDeep(flatMap(orders as o, map(o.items, {[#.sku]: [o.id]})));{orders: []};{} +mergeDeep(flatMap(orders as o, map(o.items, {[#.sku]: [o.id]})));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};{a: ['o1', 'o1']} +mergeDeep(map(orders, {[#.tier]: {[#.id]: len(#.items)}}));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};{silver: {o1: 3, o2: 1, o3: 3}} +mergeDeep(map(orders, {[#.tier]: {[#.id]: len(#.items)}}));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};{silver: {o1: 3}, bronze: {o2: 1, o3: 3, o4: 4}} +mergeDeep(map(orders, {[#.tier]: {[#.id]: len(#.items)}}));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};{bronze: {o1: 1}, silver: {o2: 0}} +mergeDeep(map(orders, {[#.tier]: {[#.id]: len(#.items)}}));{orders: [{id: 'o1', tier: 'gold', items: []}]};{gold: {o1: 0}} +mergeDeep(map(orders, {[#.tier]: {[#.id]: len(#.items)}}));{orders: []};{} +mergeDeep(map(orders, {[#.tier]: {[#.id]: len(#.items)}}));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};{gold: {o1: 2}} +mergeDeep(map(orders, {[#.tier]: {n: [1]}}));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};{silver: {n: [1, 1, 1]}} +mergeDeep(map(orders, {[#.tier]: {n: [1]}}));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};{silver: {n: [1]}, bronze: {n: [1, 1, 1]}} +mergeDeep(map(orders, {[#.tier]: {n: [1]}}));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};{bronze: {n: [1]}, silver: {n: [1]}} +mergeDeep(map(orders, {[#.tier]: {n: [1]}}));{orders: [{id: 'o1', tier: 'gold', items: []}]};{gold: {n: [1]}} +mergeDeep(map(orders, {[#.tier]: {n: [1]}}));{orders: []};{} +mergeDeep(map(orders, {[#.tier]: {n: [1]}}));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};{gold: {n: [1]}} +map(values(mergeDeep(map(orders, {[#.tier]: [#.id]}))), len(#));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[3] +map(values(mergeDeep(map(orders, {[#.tier]: [#.id]}))), len(#));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[1, 3] +map(values(mergeDeep(map(orders, {[#.tier]: [#.id]}))), len(#));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[1, 1] +map(values(mergeDeep(map(orders, {[#.tier]: [#.id]}))), len(#));{orders: [{id: 'o1', tier: 'gold', items: []}]};[1] +map(values(mergeDeep(map(orders, {[#.tier]: [#.id]}))), len(#));{orders: []};[] +map(values(mergeDeep(map(orders, {[#.tier]: [#.id]}))), len(#));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[1] +keys(mergeDeep(map(orders, {[#.tier]: [#.id]})));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};['silver'] +keys(mergeDeep(map(orders, {[#.tier]: [#.id]})));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};['silver', 'bronze'] +keys(mergeDeep(map(orders, {[#.tier]: [#.id]})));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};['bronze', 'silver'] +keys(mergeDeep(map(orders, {[#.tier]: [#.id]})));{orders: [{id: 'o1', tier: 'gold', items: []}]};['gold'] +keys(mergeDeep(map(orders, {[#.tier]: [#.id]})));{orders: []};[] +keys(mergeDeep(map(orders, {[#.tier]: [#.id]})));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};['gold'] +map(values(mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})))), sum(#));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[10, 5, 5, 4] +map(values(mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})))), sum(#));{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[5, 13, 15, 4] +map(values(mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})))), sum(#));{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[4] +map(values(mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})))), sum(#));{orders: [{id: 'o1', tier: 'gold', items: []}]};[] +map(values(mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})))), sum(#));{orders: []};[] +map(values(mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty]})))), sum(#));{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[3] +"g = mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty * #.price]}))); map(keys(g), {sku: #, total: sum(g[#])})";{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[{sku: 'b', total: 6.50}, {sku: 'c', total: 5.15}, {sku: 'a', total: 30.10}, {sku: 'd', total: 40}] +"g = mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty * #.price]}))); map(keys(g), {sku: #, total: sum(g[#])})";{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[{sku: 'c', total: 13.85}, {sku: 'b', total: 10.25}, {sku: 'd', total: 566.615}, {sku: 'a', total: 400}] +"g = mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty * #.price]}))); map(keys(g), {sku: #, total: sum(g[#])})";{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[{sku: 'c', total: 39.96}] +"g = mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty * #.price]}))); map(keys(g), {sku: #, total: sum(g[#])})";{orders: [{id: 'o1', tier: 'gold', items: []}]};[] +"g = mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty * #.price]}))); map(keys(g), {sku: #, total: sum(g[#])})";{orders: []};[] +"g = mergeDeep(flatMap(orders, map(#.items, {[#.sku]: [#.qty * #.price]}))); map(keys(g), {sku: #, total: sum(g[#])})";{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[{sku: 'a', total: 0.4}] +"g = mergeDeep(map(orders, {[#.tier]: [#]})); map(keys(g) as t, {tier: t, orders: len(g[t]), lines: len(flatMap(g[t], #.items))})";{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};[{tier: 'silver', orders: 3, lines: 7}] +"g = mergeDeep(map(orders, {[#.tier]: [#]})); map(keys(g) as t, {tier: t, orders: len(g[t]), lines: len(flatMap(g[t], #.items))})";{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};[{tier: 'silver', orders: 1, lines: 3}, {tier: 'bronze', orders: 3, lines: 8}] +"g = mergeDeep(map(orders, {[#.tier]: [#]})); map(keys(g) as t, {tier: t, orders: len(g[t]), lines: len(flatMap(g[t], #.items))})";{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[{tier: 'bronze', orders: 1, lines: 1}, {tier: 'silver', orders: 1, lines: 0}] +"g = mergeDeep(map(orders, {[#.tier]: [#]})); map(keys(g) as t, {tier: t, orders: len(g[t]), lines: len(flatMap(g[t], #.items))})";{orders: [{id: 'o1', tier: 'gold', items: []}]};[{tier: 'gold', orders: 1, lines: 0}] +"g = mergeDeep(map(orders, {[#.tier]: [#]})); map(keys(g) as t, {tier: t, orders: len(g[t]), lines: len(flatMap(g[t], #.items))})";{orders: []};[] +"g = mergeDeep(map(orders, {[#.tier]: [#]})); map(keys(g) as t, {tier: t, orders: len(g[t]), lines: len(flatMap(g[t], #.items))})";{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[{tier: 'gold', orders: 1, lines: 2}] +"g = mergeDeep(map(orders, {[#.tier]: [#.id]})); filter(keys(g), len(g[#]) > 1)";{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'b', qty: 5, price: 0.05}, {sku: 'c', qty: 3, price: 0.05}, {sku: 'c', qty: 2, price: 2.50}]}, {id: 'o2', tier: 'silver', items: [{sku: 'a', qty: 3, price: 10}]}, {id: 'o3', tier: 'silver', items: [{sku: 'd', qty: 4, price: 10}, {sku: 'b', qty: 5, price: 1.25}, {sku: 'a', qty: 2, price: 0.05}]}]};['silver'] +"g = mergeDeep(map(orders, {[#.tier]: [#.id]})); filter(keys(g), len(g[#]) > 1)";{orders: [{id: 'o1', tier: 'silver', items: [{sku: 'c', qty: 1, price: 0.10}, {sku: 'b', qty: 3, price: 1.25}, {sku: 'd', qty: 5, price: 3.333}]}, {id: 'o2', tier: 'bronze', items: [{sku: 'b', qty: 5, price: 1.25}]}, {id: 'o3', tier: 'bronze', items: [{sku: 'c', qty: 3, price: 1.25}, {sku: 'a', qty: 4, price: 100}, {sku: 'd', qty: 4, price: 9.99}]}, {id: 'o4', tier: 'bronze', items: [{sku: 'c', qty: 1, price: 10}, {sku: 'd', qty: 5, price: 100}, {sku: 'd', qty: 1, price: 9.99}, {sku: 'b', qty: 5, price: 0.05}]}]};['bronze'] +"g = mergeDeep(map(orders, {[#.tier]: [#.id]})); filter(keys(g), len(g[#]) > 1)";{orders: [{id: 'o1', tier: 'bronze', items: [{sku: 'c', qty: 4, price: 9.99}]}, {id: 'o2', tier: 'silver', items: []}]};[] +"g = mergeDeep(map(orders, {[#.tier]: [#.id]})); filter(keys(g), len(g[#]) > 1)";{orders: [{id: 'o1', tier: 'gold', items: []}]};[] +"g = mergeDeep(map(orders, {[#.tier]: [#.id]})); filter(keys(g), len(g[#]) > 1)";{orders: []};[] +"g = mergeDeep(map(orders, {[#.tier]: [#.id]})); filter(keys(g), len(g[#]) > 1)";{orders: [{id: 'o1', tier: 'gold', items: [{sku: 'a', qty: 2, price: 0.1}, {sku: 'a', qty: 1, price: 0.2}]}]};[] +# pivot with merge: key to last value +merge(map(kv, {[#.k]: #.v}));{kv: [{k: 'a', v: 1}, {k: 'b', v: 2}, {k: 'a', v: 3}]};{a: 3, b: 2} +merge(map(kv, {[#.k]: #.v}));{kv: [{k: 'x', v: null}]};{x: null} +merge(map(kv, {[#.k]: #.v}));{kv: []};{} +merge(map(kv, {[#.k]: #.v}));{kv: [{k: 'n', v: [1, 2]}, {k: 'm', v: {z: 1}}]};{n: [1, 2], m: {z: 1}} +merge(map(kv, {[#.k]: #.v}));{kv: [{k: 1, v: 1}]};{'1': 1} +merge(map(kv, {[#.k]: #.v}));{kv: [{v: 1}]};{'null': 1};question: a null computed key becomes the string 'null' +merge(map(kv, {[#.k]: #.v})).a;{kv: [{k: 'a', v: 1}, {k: 'b', v: 2}, {k: 'a', v: 3}]};3 +merge(map(kv, {[#.k]: #.v})).a;{kv: [{k: 'x', v: null}]};null +merge(map(kv, {[#.k]: #.v})).a;{kv: []};null +merge(map(kv, {[#.k]: #.v})).a;{kv: [{k: 'n', v: [1, 2]}, {k: 'm', v: {z: 1}}]};null +len(keys(merge(map(kv, {[#.k]: #.v}))));{kv: [{k: 'a', v: 1}, {k: 'b', v: 2}, {k: 'a', v: 3}]};2 +len(keys(merge(map(kv, {[#.k]: #.v}))));{kv: [{k: 'x', v: null}]};1 +len(keys(merge(map(kv, {[#.k]: #.v}))));{kv: []};0 +len(keys(merge(map(kv, {[#.k]: #.v}))));{kv: [{k: 'n', v: [1, 2]}, {k: 'm', v: {z: 1}}]};2 +mergeDeep(map(kv, {[#.k]: [#.v]}));{kv: [{k: 'a', v: 1}, {k: 'b', v: 2}, {k: 'a', v: 3}]};{a: [1, 3], b: [2]} +mergeDeep(map(kv, {[#.k]: [#.v]}));{kv: [{k: 'x', v: null}]};{x: [null]} +mergeDeep(map(kv, {[#.k]: [#.v]}));{kv: []};{} +mergeDeep(map(kv, {[#.k]: [#.v]}));{kv: [{k: 'n', v: [1, 2]}, {k: 'm', v: {z: 1}}]};{n: [[1, 2]], m: [{z: 1}]} +map(kv, {[#.k + '_v']: #.v});{kv: [{k: 'a', v: 1}, {k: 'b', v: 2}, {k: 'a', v: 3}]};[{a_v: 1}, {b_v: 2}, {a_v: 3}] +map(kv, {[#.k + '_v']: #.v});{kv: [{k: 'x', v: null}]};[{x_v: null}] +map(kv, {[#.k + '_v']: #.v});{kv: []};[] +map(kv, {[#.k + '_v']: #.v});{kv: [{k: 'n', v: [1, 2]}, {k: 'm', v: {z: 1}}]};[{n_v: [1, 2]}, {m_v: {z: 1}}] +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}}));{cells: [{r: 'r1', c: 'x', v: 1}, {r: 'r1', c: 'y', v: 2}, {r: 'r2', c: 'x', v: 3}]};{r1: {x: 1, y: 2}, r2: {x: 3}} +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}}));{cells: [{r: 'a', c: 'b', v: 0.5}]};{a: {b: 0.5}} +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}}));{cells: []};{} +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}}));{cells: [{r: 'r', c: 'x', v: 1}, {r: 'r', c: 'x', v: 2}]};{r: {x: 2}} +mergeDeep(map(cells, {[#.c]: {[#.r]: #.v}}));{cells: [{r: 'r1', c: 'x', v: 1}, {r: 'r1', c: 'y', v: 2}, {r: 'r2', c: 'x', v: 3}]};{x: {r1: 1, r2: 3}, y: {r1: 2}} +mergeDeep(map(cells, {[#.c]: {[#.r]: #.v}}));{cells: [{r: 'a', c: 'b', v: 0.5}]};{b: {a: 0.5}} +mergeDeep(map(cells, {[#.c]: {[#.r]: #.v}}));{cells: []};{} +mergeDeep(map(cells, {[#.c]: {[#.r]: #.v}}));{cells: [{r: 'r', c: 'x', v: 1}, {r: 'r', c: 'x', v: 2}]};{x: {r: 2}} +mergeDeep(map(cells, {[#.r]: {[#.c]: [#.v]}}));{cells: [{r: 'r1', c: 'x', v: 1}, {r: 'r1', c: 'y', v: 2}, {r: 'r2', c: 'x', v: 3}]};{r1: {x: [1], y: [2]}, r2: {x: [3]}} +mergeDeep(map(cells, {[#.r]: {[#.c]: [#.v]}}));{cells: [{r: 'a', c: 'b', v: 0.5}]};{a: {b: [0.5]}} +mergeDeep(map(cells, {[#.r]: {[#.c]: [#.v]}}));{cells: []};{} +mergeDeep(map(cells, {[#.r]: {[#.c]: [#.v]}}));{cells: [{r: 'r', c: 'x', v: 1}, {r: 'r', c: 'x', v: 2}]};{r: {x: [1, 2]}} +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}})).r1.x;{cells: [{r: 'r1', c: 'x', v: 1}, {r: 'r1', c: 'y', v: 2}, {r: 'r2', c: 'x', v: 3}]};1 +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}})).r1.x;{cells: [{r: 'a', c: 'b', v: 0.5}]};null +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}})).r1.x;{cells: []};null +mergeDeep(map(cells, {[#.r]: {[#.c]: #.v}})).r1.x;{cells: [{r: 'r', c: 'x', v: 1}, {r: 'r', c: 'x', v: 2}]};null +# join-like lookups between two input lists +map(orders as o, filter(users, #.id == o.uid)[0].name);{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};['Ann', 'Bo', 'Ann', null] +map(orders as o, filter(users, #.id == o.uid)[0].name);{users: [{id: 1, name: 'Ann'}], orders: []};[] +map(orders as o, filter(users, #.id == o.uid)[0].name);{users: [], orders: [{uid: 1, t: 1}]};[null] +map(orders as o, filter(users, #.id == o.uid)[0].name);{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};['Ann'] +map(orders as o, filter(users, #.id == o.uid)[0].name);{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[null] +map(orders as o, filter(users, #.id == o.uid)[0].name ?? 'unknown');{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};['Ann', 'Bo', 'Ann', 'unknown'] +map(orders as o, filter(users, #.id == o.uid)[0].name ?? 'unknown');{users: [{id: 1, name: 'Ann'}], orders: []};[] +map(orders as o, filter(users, #.id == o.uid)[0].name ?? 'unknown');{users: [], orders: [{uid: 1, t: 1}]};['unknown'] +map(orders as o, filter(users, #.id == o.uid)[0].name ?? 'unknown');{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};['Ann'] +map(orders as o, filter(users, #.id == o.uid)[0].name ?? 'unknown');{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};['unknown'] +map(users as u, {name: u.name, total: sum(map(filter(orders, #.uid == u.id), #.t))});{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};[{name: 'Ann', total: 12.5}, {name: 'Bo', total: 5}] +map(users as u, {name: u.name, total: sum(map(filter(orders, #.uid == u.id), #.t))});{users: [{id: 1, name: 'Ann'}], orders: []};[{name: 'Ann', total: 0}] +map(users as u, {name: u.name, total: sum(map(filter(orders, #.uid == u.id), #.t))});{users: [], orders: [{uid: 1, t: 1}]};[] +map(users as u, {name: u.name, total: sum(map(filter(orders, #.uid == u.id), #.t))});{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};[{name: 'Ann', total: 1}, {name: 'Dup', total: 1}] +map(users as u, {name: u.name, total: sum(map(filter(orders, #.uid == u.id), #.t))});{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[{name: 'Str', total: 0}] +map(users as u, count(orders, #.uid == u.id));{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};[2, 1] +map(users as u, count(orders, #.uid == u.id));{users: [{id: 1, name: 'Ann'}], orders: []};[0] +map(users as u, count(orders, #.uid == u.id));{users: [], orders: [{uid: 1, t: 1}]};[] +map(users as u, count(orders, #.uid == u.id));{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};[1, 1] +map(users as u, count(orders, #.uid == u.id));{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[0] +filter(orders as o, none(users, #.id == o.uid));{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};[{uid: 3, t: 1}] +filter(orders as o, none(users, #.id == o.uid));{users: [{id: 1, name: 'Ann'}], orders: []};[] +filter(orders as o, none(users, #.id == o.uid));{users: [], orders: [{uid: 1, t: 1}]};[{uid: 1, t: 1}] +filter(orders as o, none(users, #.id == o.uid));{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};[] +filter(orders as o, none(users, #.id == o.uid));{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[{uid: 1, t: 1}] +filter(users as u, some(orders, #.uid == u.id));{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};[{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}] +filter(users as u, some(orders, #.uid == u.id));{users: [{id: 1, name: 'Ann'}], orders: []};[] +filter(users as u, some(orders, #.uid == u.id));{users: [], orders: [{uid: 1, t: 1}]};[] +filter(users as u, some(orders, #.uid == u.id));{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};[{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}] +filter(users as u, some(orders, #.uid == u.id));{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[] +map(filter(users as u, some(orders, #.uid == u.id)), #.name);{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};['Ann', 'Bo'] +map(filter(users as u, some(orders, #.uid == u.id)), #.name);{users: [{id: 1, name: 'Ann'}], orders: []};[] +map(filter(users as u, some(orders, #.uid == u.id)), #.name);{users: [], orders: [{uid: 1, t: 1}]};[] +map(filter(users as u, some(orders, #.uid == u.id)), #.name);{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};['Ann', 'Dup'] +map(filter(users as u, some(orders, #.uid == u.id)), #.name);{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[] +flatMap(users as u, map(filter(orders, #.uid == u.id), [u.name, #.t]));{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};[['Ann', 10], ['Ann', 2.5], ['Bo', 5]] +flatMap(users as u, map(filter(orders, #.uid == u.id), [u.name, #.t]));{users: [{id: 1, name: 'Ann'}], orders: []};[] +flatMap(users as u, map(filter(orders, #.uid == u.id), [u.name, #.t]));{users: [], orders: [{uid: 1, t: 1}]};[] +flatMap(users as u, map(filter(orders, #.uid == u.id), [u.name, #.t]));{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};[['Ann', 1], ['Dup', 1]] +flatMap(users as u, map(filter(orders, #.uid == u.id), [u.name, #.t]));{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[] +len(flatMap(users as u, filter(orders, #.uid == u.id)));{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};3 +len(flatMap(users as u, filter(orders, #.uid == u.id)));{users: [{id: 1, name: 'Ann'}], orders: []};0 +len(flatMap(users as u, filter(orders, #.uid == u.id)));{users: [], orders: [{uid: 1, t: 1}]};0 +len(flatMap(users as u, filter(orders, #.uid == u.id)));{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};2 +len(flatMap(users as u, filter(orders, #.uid == u.id)));{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};0 +map(orders, #.uid in map(users, #.id));{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};[true, true, true, false] +map(orders, #.uid in map(users, #.id));{users: [{id: 1, name: 'Ann'}], orders: []};[] +map(orders, #.uid in map(users, #.id));{users: [], orders: [{uid: 1, t: 1}]};[false] +map(orders, #.uid in map(users, #.id));{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};[true] +map(orders, #.uid in map(users, #.id));{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};[false] +"u = merge(map(users, {[string(#.id)]: #.name})); map(orders, u[string(#.uid)])";{users: [{id: 1, name: 'Ann'}, {id: 2, name: 'Bo'}], orders: [{uid: 1, t: 10}, {uid: 2, t: 5}, {uid: 1, t: 2.5}, {uid: 3, t: 1}]};['Ann', 'Bo', 'Ann', null] +"u = merge(map(users, {[string(#.id)]: #.name})); map(orders, u[string(#.uid)])";{users: [{id: 1, name: 'Ann'}], orders: []};[] +"u = merge(map(users, {[string(#.id)]: #.name})); map(orders, u[string(#.uid)])";{users: [], orders: [{uid: 1, t: 1}]};[null] +"u = merge(map(users, {[string(#.id)]: #.name})); map(orders, u[string(#.uid)])";{users: [{id: 1, name: 'Ann'}, {id: 1, name: 'Dup'}], orders: [{uid: 1, t: 1}]};['Dup'] +"u = merge(map(users, {[string(#.id)]: #.name})); map(orders, u[string(#.uid)])";{users: [{id: '1', name: 'Str'}], orders: [{uid: 1, t: 1}]};['Str'] +# reductions over objects of objects +sum(map(values(acc), #.bal));{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};10.5 +sum(map(values(acc), #.bal));{acc: {z: {bal: -1, tx: [5, 5, 5]}}};-1 +sum(map(values(acc), #.bal));{acc: {}};0 +sum(map(values(acc), #.bal));{acc: {a: {bal: 1}}};1 +sum(map(values(acc), #.bal + sum(#.tx ?? [])));{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};9.5 +sum(map(values(acc), #.bal + sum(#.tx ?? [])));{acc: {z: {bal: -1, tx: [5, 5, 5]}}};14 +sum(map(values(acc), #.bal + sum(#.tx ?? [])));{acc: {}};0 +sum(map(values(acc), #.bal + sum(#.tx ?? [])));{acc: {a: {bal: 1}}};1 +map(keys(acc), acc[#].bal + sum(acc[#].tx ?? []));{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};[9, 0.5] +map(keys(acc), acc[#].bal + sum(acc[#].tx ?? []));{acc: {z: {bal: -1, tx: [5, 5, 5]}}};[14] +map(keys(acc), acc[#].bal + sum(acc[#].tx ?? []));{acc: {}};[] +map(keys(acc), acc[#].bal + sum(acc[#].tx ?? []));{acc: {a: {bal: 1}}};[1] +filter(keys(acc), len(acc[#].tx ?? []) > 1);{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};['a'] +filter(keys(acc), len(acc[#].tx ?? []) > 1);{acc: {z: {bal: -1, tx: [5, 5, 5]}}};['z'] +filter(keys(acc), len(acc[#].tx ?? []) > 1);{acc: {}};[] +filter(keys(acc), len(acc[#].tx ?? []) > 1);{acc: {a: {bal: 1}}};[] +sum(flatMap(values(acc), #.tx));{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};-1 +sum(flatMap(values(acc), #.tx));{acc: {z: {bal: -1, tx: [5, 5, 5]}}};15 +sum(flatMap(values(acc), #.tx));{acc: {}};0 +sum(flatMap(values(acc), #.tx));{acc: {a: {bal: 1}}};!error +merge(map(keys(acc), {[#]: len(acc[#].tx ?? [])}));{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};{a: 2, b: 0} +merge(map(keys(acc), {[#]: len(acc[#].tx ?? [])}));{acc: {z: {bal: -1, tx: [5, 5, 5]}}};{z: 3} +merge(map(keys(acc), {[#]: len(acc[#].tx ?? [])}));{acc: {}};{} +merge(map(keys(acc), {[#]: len(acc[#].tx ?? [])}));{acc: {a: {bal: 1}}};{a: 0} +mergeDeep([acc, {a: {bal: 0}}]).a.bal;{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};0 +mergeDeep([acc, {a: {bal: 0}}]).a.bal;{acc: {z: {bal: -1, tx: [5, 5, 5]}}};0 +mergeDeep([acc, {a: {bal: 0}}]).a.bal;{acc: {}};0 +mergeDeep([acc, {a: {bal: 0}}]).a.bal;{acc: {a: {bal: 1}}};0 +mergeDeep([acc, {a: {tx: [9]}}]).a.tx;{acc: {a: {bal: 10, tx: [1, -2]}, b: {bal: 0.5, tx: []}}};[1, -2, 9] +mergeDeep([acc, {a: {tx: [9]}}]).a.tx;{acc: {z: {bal: -1, tx: [5, 5, 5]}}};[9] +mergeDeep([acc, {a: {tx: [9]}}]).a.tx;{acc: {}};[9] +mergeDeep([acc, {a: {tx: [9]}}]).a.tx;{acc: {a: {bal: 1}}};[9] +# running indicators computed per element against the whole list +map(xs as x, count(xs, # > x) + 1);{xs: [3, 1, 2]};[1, 3, 2] +map(xs as x, count(xs, # > x) + 1);{xs: [5]};[1] +map(xs as x, count(xs, # > x) + 1);{xs: [2, 2, 1]};[1, 1, 3] +map(xs as x, count(xs, # > x) + 1);{xs: [0.5, 1.5, 1]};[3, 1, 2] +map(xs as x, count(xs, # > x) + 1);{xs: []};[] +map(xs as x, x == max(xs));{xs: [3, 1, 2]};[true, false, false] +map(xs as x, x == max(xs));{xs: [5]};[true] +map(xs as x, x == max(xs));{xs: [2, 2, 1]};[true, true, false] +map(xs as x, x == max(xs));{xs: [0.5, 1.5, 1]};[false, true, false] +map(xs as x, x == max(xs));{xs: []};[] +filter(xs as x, x > avg(xs));{xs: [3, 1, 2]};[3] +filter(xs as x, x > avg(xs));{xs: [5]};[] +filter(xs as x, x > avg(xs));{xs: [2, 2, 1]};[2, 2] +filter(xs as x, x > avg(xs));{xs: [0.5, 1.5, 1]};[1.5] +map(xs as x, x - min(xs));{xs: [3, 1, 2]};[2, 0, 1] +map(xs as x, x - min(xs));{xs: [5]};[0] +map(xs as x, x - min(xs));{xs: [2, 2, 1]};[1, 1, 0] +map(xs as x, x - min(xs));{xs: [0.5, 1.5, 1]};[0.0, 1.0, 0.5] +map(xs as x, x - min(xs));{xs: []};[] +map(xs as x, x / sum(xs));{xs: [2, 1, 1]};[0.5, 0.25, 0.25] +map(xs as x, x / sum(xs));{xs: [5]};[1] +map(xs as x, x / sum(xs));{xs: [1, 3]};[0.25, 0.75] +map(xs as x, x / sum(xs));{xs: []};[] +map(xs as x, count(xs, # == x));{xs: [3, 1, 2]};[1, 1, 1] +map(xs as x, count(xs, # == x));{xs: [5]};[1] +map(xs as x, count(xs, # == x));{xs: [2, 2, 1]};[2, 2, 1] +map(xs as x, count(xs, # == x));{xs: [0.5, 1.5, 1]};[1, 1, 1] +map(xs as x, count(xs, # == x));{xs: []};[] +filter(xs as x, count(xs, # == x) == 1);{xs: [3, 1, 2]};[3, 1, 2] +filter(xs as x, count(xs, # == x) == 1);{xs: [5]};[5] +filter(xs as x, count(xs, # == x) == 1);{xs: [2, 2, 1]};[1] +filter(xs as x, count(xs, # == x) == 1);{xs: [0.5, 1.5, 1]};[0.5, 1.5, 1] +filter(xs as x, count(xs, # == x) == 1);{xs: []};[] diff --git a/core/expression/tests/spec/standard/13-04-empty-and-building.csv b/core/expression/tests/spec/standard/13-04-empty-and-building.csv new file mode 100644 index 00000000..3a433ce7 --- /dev/null +++ b/core/expression/tests/spec/standard/13-04-empty-and-building.csv @@ -0,0 +1,503 @@ +expression (string);input (json 5);output (json 5);note +# empty collections at every nesting level +len(a);{a: []};0 +len(a);{a: [[]]};1 +len(a);{a: [[], []]};2 +len(a);{a: [[[]]]};1 +len(a);{a: [{b: []}]};1 +len(a);{a: [{b: [{c: []}]}]};1 +len(a);{a: [{}]};1 +len(a);{a: [{b: [{}]}]};1 +flatten(a);{a: []};[] +flatten(a);{a: [[]]};[] +flatten(a);{a: [[], []]};[] +flatten(a);{a: [[[]]]};[[]] +flatten(a);{a: [{b: []}]};[{b: []}] +flatten(a);{a: [{b: [{c: []}]}]};[{b: [{c: []}]}] +flatten(a);{a: [{}]};[{}] +flatten(a);{a: [{b: [{}]}]};[{b: [{}]}] +len(flatten(a));{a: []};0 +len(flatten(a));{a: [[]]};0 +len(flatten(a));{a: [[], []]};0 +len(flatten(a));{a: [[[]]]};1 +len(flatten(a));{a: [{b: []}]};1 +len(flatten(a));{a: [{b: [{c: []}]}]};1 +len(flatten(a));{a: [{}]};1 +len(flatten(a));{a: [{b: [{}]}]};1 +map(a, len(#));{a: []};[] +map(a, len(#));{a: [[]]};[0] +map(a, len(#));{a: [[], []]};[0, 0] +map(a, len(#));{a: [[[]]]};[1] +map(a, len(#));{a: [{b: []}]};!error +map(a, len(#));{a: [{b: [{c: []}]}]};!error +map(a, len(#));{a: [{}]};!error +map(a, len(#));{a: [{b: [{}]}]};!error +map(a, #.b);{a: []};[] +map(a, #.b);{a: [[]]};[null] +map(a, #.b);{a: [[], []]};[null, null] +map(a, #.b);{a: [[[]]]};[null] +map(a, #.b);{a: [{b: []}]};[[]] +map(a, #.b);{a: [{b: [{c: []}]}]};[[{c: []}]] +map(a, #.b);{a: [{}]};[null] +map(a, #.b);{a: [{b: [{}]}]};[[{}]] +map(a, #.b ?? []);{a: []};[] +map(a, #.b ?? []);{a: [[]]};[[]] +map(a, #.b ?? []);{a: [[], []]};[[], []] +map(a, #.b ?? []);{a: [[[]]]};[[]] +map(a, #.b ?? []);{a: [{b: []}]};[[]] +map(a, #.b ?? []);{a: [{b: [{c: []}]}]};[[{c: []}]] +map(a, #.b ?? []);{a: [{}]};[[]] +map(a, #.b ?? []);{a: [{b: [{}]}]};[[{}]] +flatMap(a, #.b ?? []);{a: []};[] +flatMap(a, #.b ?? []);{a: [[]]};[] +flatMap(a, #.b ?? []);{a: [[], []]};[] +flatMap(a, #.b ?? []);{a: [[[]]]};[] +flatMap(a, #.b ?? []);{a: [{b: []}]};[] +flatMap(a, #.b ?? []);{a: [{b: [{c: []}]}]};[{c: []}] +flatMap(a, #.b ?? []);{a: [{}]};[] +flatMap(a, #.b ?? []);{a: [{b: [{}]}]};[{}] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: []};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [[]]};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [[], []]};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [[[]]]};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [{b: []}]};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [{b: [{c: []}]}]};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [{}]};[] +flatMap(a, flatMap(#.b ?? [], #.c ?? []));{a: [{b: [{}]}]};[] +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: []};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [[]]};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [[], []]};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [[[]]]};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [{b: []}]};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [{b: [{c: []}]}]};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [{}]};0 +sum(flatMap(a, map(#.b ?? [], len(#.c ?? []))));{a: [{b: [{}]}]};0 +some(a, true);{a: []};false +some(a, true);{a: [[]]};true +some(a, true);{a: [[], []]};true +some(a, true);{a: [[[]]]};true +some(a, true);{a: [{b: []}]};true +some(a, true);{a: [{b: [{c: []}]}]};true +some(a, true);{a: [{}]};true +some(a, true);{a: [{b: [{}]}]};true +all(a, false);{a: []};true +all(a, false);{a: [[]]};false +all(a, false);{a: [[], []]};false +all(a, false);{a: [[[]]]};false +all(a, false);{a: [{b: []}]};false +all(a, false);{a: [{b: [{c: []}]}]};false +all(a, false);{a: [{}]};false +all(a, false);{a: [{b: [{}]}]};false +none(a, true);{a: []};true +none(a, true);{a: [[]]};false +none(a, true);{a: [[], []]};false +none(a, true);{a: [[[]]]};false +none(a, true);{a: [{b: []}]};false +none(a, true);{a: [{b: [{c: []}]}]};false +none(a, true);{a: [{}]};false +none(a, true);{a: [{b: [{}]}]};false +count(a, true);{a: []};0 +count(a, true);{a: [[]]};1 +count(a, true);{a: [[], []]};2 +count(a, true);{a: [[[]]]};1 +count(a, true);{a: [{b: []}]};1 +count(a, true);{a: [{b: [{c: []}]}]};1 +count(a, true);{a: [{}]};1 +count(a, true);{a: [{b: [{}]}]};1 +one(a, true);{a: []};false +one(a, true);{a: [[]]};true +one(a, true);{a: [[], []]};false +one(a, true);{a: [[[]]]};true +one(a, true);{a: [{b: []}]};true +one(a, true);{a: [{b: [{c: []}]}]};true +one(a, true);{a: [{}]};true +one(a, true);{a: [{b: [{}]}]};true +a[0];{a: []};null +a[0];{a: [[]]};[] +a[0];{a: [[], []]};[] +a[0];{a: [[[]]]};[[]] +a[0];{a: [{b: []}]};{b: []} +a[0];{a: [{b: [{c: []}]}]};{b: [{c: []}]} +a[0];{a: [{}]};{} +a[0];{a: [{b: [{}]}]};{b: [{}]} +a[0][0];{a: []};null +a[0][0];{a: [[]]};null +a[0][0];{a: [[], []]};null +a[0][0];{a: [[[]]]};[] +a[0][0];{a: [{b: []}]};null +a[0][0];{a: [{b: [{c: []}]}]};null +a[0][0];{a: [{}]};null +a[0][0];{a: [{b: [{}]}]};null +a[0].b[0].c;{a: []};null +a[0].b[0].c;{a: [[]]};null +a[0].b[0].c;{a: [[], []]};null +a[0].b[0].c;{a: [[[]]]};null +a[0].b[0].c;{a: [{b: []}]};null +a[0].b[0].c;{a: [{b: [{c: []}]}]};[] +a[0].b[0].c;{a: [{}]};null +a[0].b[0].c;{a: [{b: [{}]}]};null +map(a, []);{a: []};[] +map(a, []);{a: [[]]};[[]] +map(a, []);{a: [[], []]};[[], []] +map(a, []);{a: [[[]]]};[[]] +map(a, []);{a: [{b: []}]};[[]] +map(a, []);{a: [{b: [{c: []}]}]};[[]] +map(a, []);{a: [{}]};[[]] +map(a, []);{a: [{b: [{}]}]};[[]] +flatMap(a, []);{a: []};[] +flatMap(a, []);{a: [[]]};[] +flatMap(a, []);{a: [[], []]};[] +flatMap(a, []);{a: [[[]]]};[] +flatMap(a, []);{a: [{b: []}]};[] +flatMap(a, []);{a: [{b: [{c: []}]}]};[] +flatMap(a, []);{a: [{}]};[] +flatMap(a, []);{a: [{b: [{}]}]};[] +map(a, {});{a: []};[] +map(a, {});{a: [[]]};[{}] +map(a, {});{a: [[], []]};[{}, {}] +map(a, {});{a: [[[]]]};[{}] +map(a, {});{a: [{b: []}]};[{}] +map(a, {});{a: [{b: [{c: []}]}]};[{}] +map(a, {});{a: [{}]};[{}] +map(a, {});{a: [{b: [{}]}]};[{}] +merge(map(a, {}));{a: []};{} +merge(map(a, {}));{a: [[]]};{} +merge(map(a, {}));{a: [[], []]};{} +merge(map(a, {}));{a: [[[]]]};{} +merge(map(a, {}));{a: [{b: []}]};{} +merge(map(a, {}));{a: [{b: [{c: []}]}]};{} +merge(map(a, {}));{a: [{}]};{} +merge(map(a, {}));{a: [{b: [{}]}]};{} +mergeDeep(map(a, {}));{a: []};{} +mergeDeep(map(a, {}));{a: [[]]};{} +mergeDeep(map(a, {}));{a: [[], []]};{} +mergeDeep(map(a, {}));{a: [[[]]]};{} +mergeDeep(map(a, {}));{a: [{b: []}]};{} +mergeDeep(map(a, {}));{a: [{b: [{c: []}]}]};{} +mergeDeep(map(a, {}));{a: [{}]};{} +mergeDeep(map(a, {}));{a: [{b: [{}]}]};{} +merge(map(a, []));{a: []};{} +merge(map(a, []));{a: [[]]};[] +merge(map(a, []));{a: [[], []]};[] +merge(map(a, []));{a: [[[]]]};[] +merge(map(a, []));{a: [{b: []}]};[] +merge(map(a, []));{a: [{b: [{c: []}]}]};[] +merge(map(a, []));{a: [{}]};[] +merge(map(a, []));{a: [{b: [{}]}]};[] +filter(a, len(#) == 0);{a: []};[] +filter(a, len(#) == 0);{a: [[]]};[[]] +filter(a, len(#) == 0);{a: [[], []]};[[], []] +filter(a, len(#) == 0);{a: [[[]]]};[] +filter(a, len(#) == 0);{a: [{b: []}]};!error +filter(a, len(#) == 0);{a: [[], [1], []]};[[], []] +map(a, keys(#));{a: []};[] +map(a, keys(#));{a: [[]]};[[]] +map(a, keys(#));{a: [[], []]};[[], []] +map(a, keys(#));{a: [[[]]]};[[0]] +map(a, keys(#));{a: [{b: []}]};[['b']] +map(a, keys(#));{a: [{b: [{c: []}]}]};[['b']] +map(a, keys(#));{a: [{}]};[[]] +map(a, keys(#));{a: [{b: [{}]}]};[['b']] +map(a, values(#));{a: []};[] +map(a, values(#));{a: [[]]};!error +map(a, values(#));{a: [[], []]};!error +map(a, values(#));{a: [[[]]]};!error +map(a, values(#));{a: [{b: []}]};[[[]]] +map(a, values(#));{a: [{b: [{c: []}]}]};[[[{c: []}]]] +map(a, values(#));{a: [{}]};[[]] +map(a, values(#));{a: [{b: [{}]}]};[[[{}]]] +sum(map(a, len(keys(#))));{a: []};0 +sum(map(a, len(keys(#))));{a: [[]]};0 +sum(map(a, len(keys(#))));{a: [[], []]};0 +sum(map(a, len(keys(#))));{a: [[[]]]};1 +sum(map(a, len(keys(#))));{a: [{b: []}]};1 +sum(map(a, len(keys(#))));{a: [{b: [{c: []}]}]};1 +sum(map(a, len(keys(#))));{a: [{}]};0 +sum(map(a, len(keys(#))));{a: [{b: [{}]}]};1 +[] in a;{a: []};false;bug: membership of an array needle errors instead of using the deep equality `in` implies +[] in a;{a: [[]]};true;bug: membership of an array needle errors instead of using the deep equality `in` implies +[] in a;{a: [[], []]};true;bug: membership of an array needle errors instead of using the deep equality `in` implies +sum(flatten(a));{a: []};0 +sum(flatten(a));{a: [[]]};0 +sum(flatten(a));{a: [[], []]};0 +sum(flatten(a));{a: [[[]]]};!error +sum(flatten(a));{a: [{b: []}]};!error +sum(flatten(a));{a: [{b: [{c: []}]}]};!error +sum(flatten(a));{a: [{}]};!error +sum(flatten(a));{a: [{b: [{}]}]};!error +max(flatten(a));{a: []};!error +max(flatten(a));{a: [[]]};!error +max(flatten(a));{a: [[], []]};!error +max(flatten(a));{a: [[[]]]};!error +avg(flatten(a));{a: []};!error +avg(flatten(a));{a: [[]]};!error +avg(flatten(a));{a: [[], []]};!error +map(a, map(#, #));{a: []};[] +map(a, map(#, #));{a: [[]]};[[]] +map(a, map(#, #));{a: [[], []]};[[], []] +map(a, map(#, #));{a: [[[]]]};[[[]]] +map(a, map(#, #));{a: [{b: []}]};!error +map(a, map(#, #));{a: [{b: [{c: []}]}]};!error +map(a, map(#, #));{a: [{}]};!error +map(a, map(#, #));{a: [{b: [{}]}]};!error +# empty objects at every nesting level +keys(o);{o: {}};[] +keys(o);{o: {x: {}}};['x'] +keys(o);{o: {x: {y: {}}}};['x'] +keys(o);{o: {x: []}};['x'] +keys(o);{o: {x: {y: []}}};['x'] +keys(o);{o: {x: null}};['x'] +values(o);{o: {}};[] +values(o);{o: {x: {}}};[{}] +values(o);{o: {x: {y: {}}}};[{y: {}}] +values(o);{o: {x: []}};[[]] +values(o);{o: {x: {y: []}}};[{y: []}] +values(o);{o: {x: null}};[null] +map(values(o), keys(#));{o: {}};[] +map(values(o), keys(#));{o: {x: {}}};[[]] +map(values(o), keys(#));{o: {x: {y: {}}}};[['y']] +map(values(o), keys(#));{o: {x: []}};[[]] +map(values(o), keys(#));{o: {x: {y: []}}};[['y']] +map(values(o), keys(#));{o: {x: null}};!error +mergeDeep([o, o]);{o: {}};{} +mergeDeep([o, o]);{o: {x: {}}};{x: {}} +mergeDeep([o, o]);{o: {x: {y: {}}}};{x: {y: {}}} +mergeDeep([o, o]);{o: {x: []}};{x: []} +mergeDeep([o, o]);{o: {x: {y: []}}};{x: {y: []}} +mergeDeep([o, o]);{o: {x: null}};{x: null} +merge([o, {}]);{o: {}};{} +merge([o, {}]);{o: {x: {}}};{x: {}} +merge([o, {}]);{o: {x: {y: {}}}};{x: {y: {}}} +merge([o, {}]);{o: {x: []}};{x: []} +merge([o, {}]);{o: {x: {y: []}}};{x: {y: []}} +merge([o, {}]);{o: {x: null}};{x: null} +mergeDeep([o, {x: {z: 1}}]);{o: {}};{x: {z: 1}} +mergeDeep([o, {x: {z: 1}}]);{o: {x: {}}};{x: {z: 1}} +mergeDeep([o, {x: {z: 1}}]);{o: {x: {y: {}}}};{x: {y: {}, z: 1}} +mergeDeep([o, {x: {z: 1}}]);{o: {x: []}};{x: {z: 1}} +mergeDeep([o, {x: {z: 1}}]);{o: {x: {y: []}}};{x: {y: [], z: 1}} +mergeDeep([o, {x: {z: 1}}]);{o: {x: null}};{x: {z: 1}} +o.x.y;{o: {}};null +o.x.y;{o: {x: {}}};null +o.x.y;{o: {x: {y: {}}}};{} +o.x.y;{o: {x: []}};null +o.x.y;{o: {x: {y: []}}};[] +o.x.y;{o: {x: null}};null +len(keys(o.x ?? {}));{o: {}};0 +len(keys(o.x ?? {}));{o: {x: {}}};0 +len(keys(o.x ?? {}));{o: {x: {y: {}}}};1 +len(keys(o.x ?? {}));{o: {x: []}};0 +len(keys(o.x ?? {}));{o: {x: {y: []}}};1 +len(keys(o.x ?? {}));{o: {x: null}};0 +flatten(values(o));{o: {}};[] +flatten(values(o));{o: {x: {}}};[{}] +flatten(values(o));{o: {x: {y: {}}}};[{y: {}}] +flatten(values(o));{o: {x: []}};[] +flatten(values(o));{o: {x: {y: []}}};[{y: []}] +flatten(values(o));{o: {x: null}};[null] +# building nested results from closures +map(xs, {v: #, sq: # * #, parts: [#, # + 1]});{xs: [1, 2, 3]};[{v: 1, sq: 1, parts: [1, 2]}, {v: 2, sq: 4, parts: [2, 3]}, {v: 3, sq: 9, parts: [3, 4]}] +map(xs, {v: #, sq: # * #, parts: [#, # + 1]});{xs: [0.5]};[{v: 0.5, sq: 0.25, parts: [0.5, 1.5]}] +map(xs, {v: #, sq: # * #, parts: [#, # + 1]});{xs: []};[] +map(xs, {v: #, sq: # * #, parts: [#, # + 1]});{xs: [-1, 10]};[{v: -1, sq: 1, parts: [-1, 0]}, {v: 10, sq: 100, parts: [10, 11]}] +map(xs, {v: #, sq: # * #, parts: [#, # + 1]})[0].parts[1];{xs: [1, 2, 3]};2 +map(xs, {v: #, sq: # * #, parts: [#, # + 1]})[0].parts[1];{xs: [0.5]};1.5 +map(xs, {v: #, sq: # * #, parts: [#, # + 1]})[0].parts[1];{xs: []};null +map(xs, {v: #, sq: # * #, parts: [#, # + 1]})[0].parts[1];{xs: [-1, 10]};0 +map(xs, [[#], [[#]]]);{xs: [1, 2, 3]};[[[1], [[1]]], [[2], [[2]]], [[3], [[3]]]] +map(xs, [[#], [[#]]]);{xs: [0.5]};[[[0.5], [[0.5]]]] +map(xs, [[#], [[#]]]);{xs: []};[] +map(xs, [[#], [[#]]]);{xs: [-1, 10]};[[[-1], [[-1]]], [[10], [[10]]]] +map(xs, {a: {b: {c: #}}});{xs: [1, 2, 3]};[{a: {b: {c: 1}}}, {a: {b: {c: 2}}}, {a: {b: {c: 3}}}] +map(xs, {a: {b: {c: #}}});{xs: [0.5]};[{a: {b: {c: 0.5}}}] +map(xs, {a: {b: {c: #}}});{xs: []};[] +map(xs, {a: {b: {c: #}}});{xs: [-1, 10]};[{a: {b: {c: -1}}}, {a: {b: {c: 10}}}] +map(map(xs, {a: {b: {c: #}}}), #.a.b.c * 2);{xs: [1, 2, 3]};[2, 4, 6] +map(map(xs, {a: {b: {c: #}}}), #.a.b.c * 2);{xs: [0.5]};[1.0] +map(map(xs, {a: {b: {c: #}}}), #.a.b.c * 2);{xs: []};[] +map(map(xs, {a: {b: {c: #}}}), #.a.b.c * 2);{xs: [-1, 10]};[-2, 20] +map(xs, {a: {b: {c: #}}})[1].a.b.c;{xs: [1, 2, 3]};2 +map(xs, {a: {b: {c: #}}})[1].a.b.c;{xs: [0.5]};null +map(xs, {a: {b: {c: #}}})[1].a.b.c;{xs: []};null +map(xs, {a: {b: {c: #}}})[1].a.b.c;{xs: [-1, 10]};10 +{total: sum(xs), items: map(xs, {v: #, pct: # * 100})};{xs: [1, 2, 3]};{total: 6, items: [{v: 1, pct: 100}, {v: 2, pct: 200}, {v: 3, pct: 300}]} +{total: sum(xs), items: map(xs, {v: #, pct: # * 100})};{xs: [0.5]};{total: 0.5, items: [{v: 0.5, pct: 50.0}]} +{total: sum(xs), items: map(xs, {v: #, pct: # * 100})};{xs: []};{total: 0, items: []} +{total: sum(xs), items: map(xs, {v: #, pct: # * 100})};{xs: [-1, 10]};{total: 9, items: [{v: -1, pct: -100}, {v: 10, pct: 1000}]} +{total: sum(xs), items: map(xs, {v: #})}.items[0].v;{xs: [1, 2, 3]};1;bug: postfix access works on a parenthesized object literal but not a bare one +{total: sum(xs), items: map(xs, {v: #})}.items[0].v;{xs: [0.5]};0.5;bug: postfix access works on a parenthesized object literal but not a bare one +{total: sum(xs), items: map(xs, {v: #})}.items[0].v;{xs: []};null;bug: postfix access works on a parenthesized object literal but not a bare one +{total: sum(xs), items: map(xs, {v: #})}.items[0].v;{xs: [-1, 10]};-1;bug: postfix access works on a parenthesized object literal but not a bare one +({total: sum(xs), items: map(xs, {v: #})}).items[0].v;{xs: [1, 2, 3]};1 +({total: sum(xs), items: map(xs, {v: #})}).items[0].v;{xs: [0.5]};0.5 +({total: sum(xs), items: map(xs, {v: #})}).items[0].v;{xs: []};null +({total: sum(xs), items: map(xs, {v: #})}).items[0].v;{xs: [-1, 10]};-1 +{pos: filter(xs, # > 0), neg: filter(xs, # < 0), n: len(xs)};{xs: [1, 2, 3]};{pos: [1, 2, 3], neg: [], n: 3} +{pos: filter(xs, # > 0), neg: filter(xs, # < 0), n: len(xs)};{xs: [0.5]};{pos: [0.5], neg: [], n: 1} +{pos: filter(xs, # > 0), neg: filter(xs, # < 0), n: len(xs)};{xs: []};{pos: [], neg: [], n: 0} +{pos: filter(xs, # > 0), neg: filter(xs, # < 0), n: len(xs)};{xs: [-1, 10]};{pos: [10], neg: [-1], n: 2} +[filter(xs, # > 0), filter(xs, # <= 0)];{xs: [1, 2, 3]};[[1, 2, 3], []] +[filter(xs, # > 0), filter(xs, # <= 0)];{xs: [0.5]};[[0.5], []] +[filter(xs, # > 0), filter(xs, # <= 0)];{xs: []};[[], []] +[filter(xs, # > 0), filter(xs, # <= 0)];{xs: [-1, 10]};[[10], [-1]] +map(xs, filter(xs, # != 0));{xs: [1, 2, 3]};[[1, 2, 3], [1, 2, 3], [1, 2, 3]] +map(xs, filter(xs, # != 0));{xs: [0.5]};[[0.5]] +map(xs, filter(xs, # != 0));{xs: []};[] +map(xs, filter(xs, # != 0));{xs: [-1, 10]};[[-1, 10], [-1, 10]] +map(xs as x, {x: x, others: filter(xs, # != x)});{xs: [1, 2, 3]};[{x: 1, others: [2, 3]}, {x: 2, others: [1, 3]}, {x: 3, others: [1, 2]}] +map(xs as x, {x: x, others: filter(xs, # != x)});{xs: [0.5]};[{x: 0.5, others: []}] +map(xs as x, {x: x, others: filter(xs, # != x)});{xs: []};[] +map(xs as x, {x: x, others: filter(xs, # != x)});{xs: [-1, 10]};[{x: -1, others: [10]}, {x: 10, others: [-1]}] +flatMap(xs, [{k: 'v', n: #}, {k: 'd', n: # * 2}]);{xs: [1, 2, 3]};[{k: 'v', n: 1}, {k: 'd', n: 2}, {k: 'v', n: 2}, {k: 'd', n: 4}, {k: 'v', n: 3}, {k: 'd', n: 6}] +flatMap(xs, [{k: 'v', n: #}, {k: 'd', n: # * 2}]);{xs: [0.5]};[{k: 'v', n: 0.5}, {k: 'd', n: 1.0}] +flatMap(xs, [{k: 'v', n: #}, {k: 'd', n: # * 2}]);{xs: []};[] +flatMap(xs, [{k: 'v', n: #}, {k: 'd', n: # * 2}]);{xs: [-1, 10]};[{k: 'v', n: -1}, {k: 'd', n: -2}, {k: 'v', n: 10}, {k: 'd', n: 20}] +flatMap(xs, [[#]]);{xs: [1, 2, 3]};[[1], [2], [3]] +flatMap(xs, [[#]]);{xs: [0.5]};[[0.5]] +flatMap(xs, [[#]]);{xs: []};[] +flatMap(xs, [[#]]);{xs: [-1, 10]};[[-1], [10]] +flatMap(xs, [[#, #]])[0];{xs: [1, 2, 3]};[1, 1] +flatMap(xs, [[#, #]])[0];{xs: [0.5]};[0.5, 0.5] +flatMap(xs, [[#, #]])[0];{xs: []};null +flatMap(xs, [[#, #]])[0];{xs: [-1, 10]};[-1, -1] +flatMap(xs, #);{xs: [1, 2, 3]};[1, 2, 3] +flatMap(xs, #);{xs: [0.5]};[0.5] +flatMap(xs, #);{xs: []};[] +flatMap(xs, #);{xs: [-1, 10]};[-1, 10] +map(xs, `${#}:${# * 2}`);{xs: [1, 2, 3]};['1:2', '2:4', '3:6'] +map(xs, `${#}:${# * 2}`);{xs: []};[] +map(xs, `${#}:${# * 2}`);{xs: [-1, 10]};['-1:-2', '10:20'] +map(xs, {[string(#)]: #});{xs: [1, 2, 3]};[{'1': 1}, {'2': 2}, {'3': 3}] +map(xs, {[string(#)]: #});{xs: [0.5]};[{'0.5': 0.5}] +map(xs, {[string(#)]: #});{xs: []};[] +map(xs, {[string(#)]: #});{xs: [-1, 10]};[{'-1': -1}, {'10': 10}] +merge(map(xs, {[string(#)]: # * 2}));{xs: [1, 2, 3]};{'1': 2, '2': 4, '3': 6} +merge(map(xs, {[string(#)]: # * 2}));{xs: [0.5]};{'0.5': 1.0} +merge(map(xs, {[string(#)]: # * 2}));{xs: []};{} +merge(map(xs, {[string(#)]: # * 2}));{xs: [-1, 10]};{'-1': -2, '10': 20} +keys(merge(map(xs, {[string(#)]: true})));{xs: [1, 2, 3]};['1', '2', '3'] +keys(merge(map(xs, {[string(#)]: true})));{xs: [0.5]};['0.5'] +keys(merge(map(xs, {[string(#)]: true})));{xs: []};[] +keys(merge(map(xs, {[string(#)]: true})));{xs: [-1, 10]};['-1', '10'] +mergeDeep(map(xs, {all: [#], last: #}));{xs: [1, 2, 3]};{all: [1, 2, 3], last: 3} +mergeDeep(map(xs, {all: [#], last: #}));{xs: [0.5]};{all: [0.5], last: 0.5} +mergeDeep(map(xs, {all: [#], last: #}));{xs: []};{} +mergeDeep(map(xs, {all: [#], last: #}));{xs: [-1, 10]};{all: [-1, 10], last: 10} +mergeDeep(map(xs, {s: {[string(#)]: [#]}}));{xs: [1, 2, 3]};{s: {'1': [1], '2': [2], '3': [3]}} +mergeDeep(map(xs, {s: {[string(#)]: [#]}}));{xs: [0.5]};{s: {'0.5': [0.5]}} +mergeDeep(map(xs, {s: {[string(#)]: [#]}}));{xs: []};{} +mergeDeep(map(xs, {s: {[string(#)]: [#]}}));{xs: [-1, 10]};{s: {'-1': [-1], '10': [10]}} +merge(map(xs, [#, #]));{xs: [1, 2, 3]};[1, 1, 2, 2, 3, 3] +merge(map(xs, [#, #]));{xs: [0.5]};[0.5, 0.5] +merge(map(xs, [#, #]));{xs: []};{} +merge(map(xs, [#, #]));{xs: [-1, 10]};[-1, -1, 10, 10] +merge(map(xs, [[#]]));{xs: [1, 2, 3]};[[1], [2], [3]] +merge(map(xs, [[#]]));{xs: [0.5]};[[0.5]] +merge(map(xs, [[#]]));{xs: []};{} +merge(map(xs, [[#]]));{xs: [-1, 10]};[[-1], [10]] +# building nested results then querying them +map(people, {n: #.n, ages: map(#.kids ?? [], #.age)});{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};[{n: 'a', ages: [3, 9]}, {n: 'b', ages: []}, {n: 'c', ages: [12]}] +map(people, {n: #.n, ages: map(#.kids ?? [], #.age)});{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[{n: 'x', ages: [1]}] +map(people, {n: #.n, ages: map(#.kids ?? [], #.age)});{people: []};[] +map(people, {n: #.n, ages: map(#.kids ?? [], #.age)});{people: [{n: 'y'}]};[{n: 'y', ages: []}] +filter(map(people, {n: #.n, ages: map(#.kids ?? [], #.age)}), len(#.ages) > 0);{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};[{n: 'a', ages: [3, 9]}, {n: 'c', ages: [12]}] +filter(map(people, {n: #.n, ages: map(#.kids ?? [], #.age)}), len(#.ages) > 0);{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[{n: 'x', ages: [1]}] +filter(map(people, {n: #.n, ages: map(#.kids ?? [], #.age)}), len(#.ages) > 0);{people: []};[] +filter(map(people, {n: #.n, ages: map(#.kids ?? [], #.age)}), len(#.ages) > 0);{people: [{n: 'y'}]};[] +map(filter(map(people, {n: #.n, k: len(#.kids ?? [])}), #.k > 0), #.n);{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};['a', 'c'] +map(filter(map(people, {n: #.n, k: len(#.kids ?? [])}), #.k > 0), #.n);{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};['x'] +map(filter(map(people, {n: #.n, k: len(#.kids ?? [])}), #.k > 0), #.n);{people: []};[] +map(filter(map(people, {n: #.n, k: len(#.kids ?? [])}), #.k > 0), #.n);{people: [{n: 'y'}]};[] +map(people, {n: #.n, older: filter(#.kids ?? [], #.age > 5)})[0].older;{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};[{n: 'a2', age: 9}] +map(people, {n: #.n, older: filter(#.kids ?? [], #.age > 5)})[0].older;{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[] +map(people, {n: #.n, older: filter(#.kids ?? [], #.age > 5)})[0].older;{people: []};null +map(people, {n: #.n, older: filter(#.kids ?? [], #.age > 5)})[0].older;{people: [{n: 'y'}]};[] +len(map(people, #.kids ?? [])[0]);{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};2 +len(map(people, #.kids ?? [])[0]);{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};1 +len(map(people, #.kids ?? [])[0]);{people: []};!error +len(map(people, #.kids ?? [])[0]);{people: [{n: 'y'}]};0 +'a1' in flatMap(people, map(#.kids ?? [], #.n));{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};true +'a1' in flatMap(people, map(#.kids ?? [], #.n));{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};false +'a1' in flatMap(people, map(#.kids ?? [], #.n));{people: []};false +'a1' in flatMap(people, map(#.kids ?? [], #.n));{people: [{n: 'y'}]};false +contains(map(people, #.n), 'b');{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};true +contains(map(people, #.n), 'b');{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};false +contains(map(people, #.n), 'b');{people: []};false +contains(map(people, #.n), 'b');{people: [{n: 'y'}]};false +some(people, 'x1' in map(#.kids ?? [], #.n));{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};false +some(people, 'x1' in map(#.kids ?? [], #.n));{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};true +some(people, 'x1' in map(#.kids ?? [], #.n));{people: []};false +some(people, 'x1' in map(#.kids ?? [], #.n));{people: [{n: 'y'}]};false +map(people, len(filter(#.kids ?? [], #.age >= 9)) > 0);{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};[true, false, true] +map(people, len(filter(#.kids ?? [], #.age >= 9)) > 0);{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[false] +map(people, len(filter(#.kids ?? [], #.age >= 9)) > 0);{people: []};[] +map(people, len(filter(#.kids ?? [], #.age >= 9)) > 0);{people: [{n: 'y'}]};[false] +flatMap(people as p, map(p.kids ?? [], p.n + '/' + #.n));{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};['a/a1', 'a/a2', 'c/c1'] +flatMap(people as p, map(p.kids ?? [], p.n + '/' + #.n));{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};['x/x1'] +flatMap(people as p, map(p.kids ?? [], p.n + '/' + #.n));{people: []};[] +flatMap(people as p, map(p.kids ?? [], p.n + '/' + #.n));{people: [{n: 'y'}]};[] +max(flatMap(people, map(#.kids ?? [], #.age)));{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};12 +max(flatMap(people, map(#.kids ?? [], #.age)));{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};1 +max(flatMap(people, map(#.kids ?? [], #.age)));{people: []};!error +max(flatMap(people, map(#.kids ?? [], #.age)));{people: [{n: 'y'}]};!error +map(people, max(map(#.kids ?? [], #.age)));{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};!error +map(people, max(map(#.kids ?? [], #.age)));{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[1] +map(people, max(map(#.kids ?? [], #.age)));{people: []};[] +map(people, max(map(#.kids ?? [], #.age)));{people: [{n: 'y'}]};!error +map(people, sum(map(#.kids ?? [], #.age)));{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};[12, 0, 12] +map(people, sum(map(#.kids ?? [], #.age)));{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[1] +map(people, sum(map(#.kids ?? [], #.age)));{people: []};[] +map(people, sum(map(#.kids ?? [], #.age)));{people: [{n: 'y'}]};[0] +map(people, #.kids[0].age ?? 0);{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};[3, 0, 12] +map(people, #.kids[0].age ?? 0);{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[1] +map(people, #.kids[0].age ?? 0);{people: []};[] +map(people, #.kids[0].age ?? 0);{people: [{n: 'y'}]};[0] +map(people, #.kids[1].n);{people: [{n: 'a', kids: [{n: 'a1', age: 3}, {n: 'a2', age: 9}]}, {n: 'b', kids: []}, {n: 'c', kids: [{n: 'c1', age: 12}]}]};['a2', null, null] +map(people, #.kids[1].n);{people: [{n: 'x', kids: [{n: 'x1', age: 1}]}]};[null] +map(people, #.kids[1].n);{people: []};[] +map(people, #.kids[1].n);{people: [{n: 'y'}]};[null] +# len, contains and in over nested results +len(filter(m, 2 in #));{m: [[1, 2], [2, 3], [4]]};2 +len(filter(m, 2 in #));{m: [['a'], ['b', 'a']]};0 +len(filter(m, 2 in #));{m: [[], [null]]};0 +len(filter(m, 2 in #));{m: []};0 +map(m, contains(#, 'a'));{m: [[1, 2], [2, 3], [4]]};[false, false, false] +map(m, contains(#, 'a'));{m: [['a'], ['b', 'a']]};[true, true] +map(m, contains(#, 'a'));{m: [[], [null]]};[false, false] +map(m, contains(#, 'a'));{m: []};[] +map(m, null in #);{m: [[1, 2], [2, 3], [4]]};[false, false, false] +map(m, null in #);{m: [['a'], ['b', 'a']]};[false, false] +map(m, null in #);{m: [[], [null]]};[false, true] +map(m, null in #);{m: []};[] +2 in flatten(m);{m: [[1, 2], [2, 3], [4]]};true +2 in flatten(m);{m: [['a'], ['b', 'a']]};false +2 in flatten(m);{m: [[], [null]]};false +2 in flatten(m);{m: []};false +len(flatten(m)) - len(m);{m: [[1, 2], [2, 3], [4]]};2 +len(flatten(m)) - len(m);{m: [['a'], ['b', 'a']]};1 +len(flatten(m)) - len(m);{m: [[], [null]]};-1 +len(flatten(m)) - len(m);{m: []};0 +map(m, len(#) in [1, 2]);{m: [[1, 2], [2, 3], [4]]};[true, true, true] +map(m, len(#) in [1, 2]);{m: [['a'], ['b', 'a']]};[true, true] +map(m, len(#) in [1, 2]);{m: [[], [null]]};[false, true] +map(m, len(#) in [1, 2]);{m: []};[] +map(m, len(#) in [1..2]);{m: [[1, 2], [2, 3], [4]]};[true, true, true] +map(m, len(#) in [1..2]);{m: [['a'], ['b', 'a']]};[true, true] +map(m, len(#) in [1..2]);{m: [[], [null]]};[false, true] +map(m, len(#) in [1..2]);{m: []};[] +filter(m, len(#) not in [0, 1]);{m: [[1, 2], [2, 3], [4]]};[[1, 2], [2, 3]] +filter(m, len(#) not in [0, 1]);{m: [['a'], ['b', 'a']]};[['b', 'a']] +filter(m, len(#) not in [0, 1]);{m: [[], [null]]};[] +filter(m, len(#) not in [0, 1]);{m: []};[] +map(m, # in [[1, 2]]);{m: [[1, 2], [2, 3], [4]]};[true, false, false];bug: membership of an array needle errors instead of using the deep equality `in` implies +map(m, # in [[1, 2]]);{m: [['a'], ['b', 'a']]};[false, false];bug: membership of an array needle errors instead of using the deep equality `in` implies +map(m, # in [[1, 2]]);{m: [[], [null]]};[false, false];bug: membership of an array needle errors instead of using the deep equality `in` implies +map(m, # in [[1, 2]]);{m: []};[] +[1, 2] in m;{m: [[1, 2], [2, 3], [4]]};true;bug: membership of an array needle errors instead of using the deep equality `in` implies +[1, 2] in m;{m: [['a'], ['b', 'a']]};false;bug: membership of an array needle errors instead of using the deep equality `in` implies +[1, 2] in m;{m: [[], [null]]};false;bug: membership of an array needle errors instead of using the deep equality `in` implies +[1, 2] in m;{m: []};false;bug: membership of an array needle errors instead of using the deep equality `in` implies +map(m, len(#))[0] in [1, 2];{m: [[1, 2], [2, 3], [4]]};true +map(m, len(#))[0] in [1, 2];{m: [['a'], ['b', 'a']]};true +map(m, len(#))[0] in [1, 2];{m: [[], [null]]};false +map(m, len(#))[0] in [1, 2];{m: []};false diff --git a/core/expression/tests/spec/standard/13-05-long-lists.csv b/core/expression/tests/spec/standard/13-05-long-lists.csv new file mode 100644 index 00000000..db20eca0 --- /dev/null +++ b/core/expression/tests/spec/standard/13-05-long-lists.csv @@ -0,0 +1,585 @@ +expression (string);input (json 5);output (json 5);note +# long number lists crossing 64-element boundaries +len(xs);{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};50 +len(xs);{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};63 +len(xs);{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};64 +len(xs);{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};65 +len(xs);{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};127 +len(xs);{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};128 +len(xs);{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};129 +len(xs);{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};200 +sum(xs);{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};716.54 +sum(xs);{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};1120.07 +sum(xs);{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};641.56 +sum(xs);{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};1177.30 +sum(xs);{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};1652.19 +sum(xs);{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};1574.37 +sum(xs);{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};1619.06 +sum(xs);{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};2430.97 +sum(map(xs, # * 2));{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};1433.08 +sum(map(xs, # * 2));{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};2240.14 +sum(map(xs, # * 2));{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};1283.12 +sum(map(xs, # * 2));{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};2354.60 +sum(map(xs, # * 2));{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};3304.38 +sum(map(xs, # * 2));{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};3148.74 +sum(map(xs, # * 2));{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};3238.12 +sum(map(xs, # * 2));{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};4861.94 +count(xs, # > 0);{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};34 +count(xs, # > 0);{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};42 +count(xs, # > 0);{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};39 +count(xs, # > 0);{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};45 +count(xs, # > 0);{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};89 +count(xs, # > 0);{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};86 +count(xs, # > 0);{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};86 +count(xs, # > 0);{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};130 +len(filter(xs, # < 0));{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};8 +len(filter(xs, # < 0));{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};16 +len(filter(xs, # < 0));{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};17 +len(filter(xs, # < 0));{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};16 +len(filter(xs, # < 0));{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};26 +len(filter(xs, # < 0));{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};33 +len(filter(xs, # < 0));{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};27 +len(filter(xs, # < 0));{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};49 +max(xs);{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};99 +max(xs);{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};99 +max(xs);{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};99 +max(xs);{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};99 +max(xs);{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};99 +max(xs);{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};99 +max(xs);{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};99 +max(xs);{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};99 +min(map(xs, # - 1));{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};-4 +min(map(xs, # - 1));{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};-4 +min(map(xs, # - 1));{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};-4 +min(map(xs, # - 1));{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};-4 +min(map(xs, # - 1));{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};-4 +min(map(xs, # - 1));{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};-4 +min(map(xs, # - 1));{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};-4 +min(map(xs, # - 1));{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};-4 +filter(xs, # == 99);{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};[99, 99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};[99, 99, 99, 99, 99, 99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};[99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};[99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};[99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};[99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};[99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99] +filter(xs, # == 99);{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};[99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99] +map(xs, # * 2)[63];{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};null +map(xs, # * 2)[63];{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};null +map(xs, # * 2)[63];{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};0.02 +map(xs, # * 2)[63];{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};5.0 +map(xs, # * 2)[63];{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};2 +map(xs, # * 2)[63];{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};-6 +map(xs, # * 2)[63];{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};5.0 +map(xs, # * 2)[63];{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};0 +map(xs, # + 1)[64];{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};null +map(xs, # + 1)[64];{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};null +map(xs, # + 1)[64];{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};null +map(xs, # + 1)[64];{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};1.01 +map(xs, # + 1)[64];{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};100 +map(xs, # + 1)[64];{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};100 +map(xs, # + 1)[64];{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};1 +map(xs, # + 1)[64];{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};0.5 +map(xs, # + 1)[128];{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};null +map(xs, # + 1)[128];{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};null +map(xs, # + 1)[128];{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};null +map(xs, # + 1)[128];{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};null +map(xs, # + 1)[128];{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};null +map(xs, # + 1)[128];{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};null +map(xs, # + 1)[128];{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};8 +map(xs, # + 1)[128];{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};1.01 +filter(xs, # > 0)[64];{xs: [7, 0.01, 10.25, 0, 0, 7, 10.25, 1, 99, 99, 7, 99, 2.5, 0.01, 10.25, 0.01, 2.5, 7, 7, 0, 7, 7, -0.5, -3, 0, -0.5, 0.01, -3, 99, 7, 7, 1, 1, -3, 7, 2.5, 0, 1, 7, 10.25, -3, 0, 7, 99, -0.5, 0, -3, 0, 99, 2.5]};null +filter(xs, # > 0)[64];{xs: [-0.5, 0.01, 99, -3, 2.5, -0.5, -0.5, 1, 7, 0.01, 10.25, -0.5, 1, 7, 0.01, 10.25, 1, 7, -0.5, 2.5, 0, 10.25, -3, 7, 99, -3, 0.01, 0.01, -3, 99, 7, 99, -3, 99, 1, 10.25, 7, 10.25, 99, 10.25, 10.25, 99, 0, 0.01, 99, -3, 7, 99, 0.01, 10.25, -3, 0, 99, -3, -3, 10.25, 10.25, 2.5, -3, 0, 0, 2.5, -3]};null +filter(xs, # > 0)[64];{xs: [-0.5, -0.5, 0, 0.01, 0, 0.01, 2.5, 2.5, -3, 10.25, 0, 7, 2.5, 99, 7, 2.5, 7, -0.5, -3, -3, 0, -0.5, 10.25, -0.5, 0, -0.5, 99, 7, 99, -3, 0, 10.25, -3, -0.5, -3, 0.01, 1, -0.5, 99, 2.5, 1, 2.5, 10.25, -3, 0, 10.25, 7, 99, 0, 10.25, -0.5, 7, 7, 1, -0.5, 10.25, 0.01, 7, 10.25, 7, 7, 2.5, 0.01, 0.01]};null +filter(xs, # > 0)[64];{xs: [0, 7, 99, 2.5, 1, 1, 99, 1, 1, 1, 1, 2.5, 7, 99, 2.5, 1, 7, -0.5, 0.01, 0, 0.01, -0.5, -0.5, 99, 0, 1, 10.25, 99, -0.5, 99, 2.5, 99, 7, 7, -3, -3, 0, 1, 7, -0.5, 99, 0.01, 7, -0.5, 10.25, 0.01, -3, 99, -0.5, -0.5, 2.5, -3, 99, -3, 99, -3, -0.5, 2.5, -3, 2.5, 10.25, 2.5, 2.5, 2.5, 0.01]};null +filter(xs, # > 0)[64];{xs: [0.01, 0, 2.5, 10.25, 0.01, 10.25, 0.01, 7, 0, 99, 0, 99, -0.5, -0.5, 2.5, 0.01, -0.5, 2.5, 10.25, 99, 0.01, 99, -3, 99, 2.5, 0, 0.01, 2.5, 0, 7, 10.25, 0.01, 0, 10.25, -0.5, 99, 7, -3, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 1, -3, -3, 1, 0.01, 7, 1, -3, 0, 0.01, 0.01, 0.01, 0, 99, 7, 0.01, -0.5, -0.5, 1, 1, 99, -3, 99, -3, 1, -3, 7, -3, 2.5, 0.01, 1, -3, 1, 0.01, 0, 0.01, -0.5, -0.5, -3, 2.5, 10.25, 10.25, 99, 1, 10.25, 99, -3, 99, 10.25, 10.25, 7, 7, 1, 2.5, 0.01, 7, 0, 0, 99, 1, 0.01, -3, 10.25, 10.25, 99, 2.5, 0.01, 10.25, -0.5, 0, 10.25, 7, 7, 7, 1, -0.5, -0.5, -3, 1, 1, 7, 1, 1]};7 +filter(xs, # > 0)[64];{xs: [10.25, -3, 10.25, -0.5, 2.5, 1, 10.25, 10.25, 1, 1, 99, 10.25, 0, 10.25, -0.5, 1, 2.5, 10.25, 10.25, 10.25, 2.5, -0.5, 7, 7, 1, 1, -0.5, 7, 10.25, 7, 2.5, 2.5, 0, 0, 10.25, -0.5, 2.5, 99, 2.5, -0.5, 1, 99, -3, 0.01, 99, 2.5, -0.5, 10.25, 7, -3, 0, -0.5, 10.25, 0.01, 7, -0.5, 99, 0.01, 10.25, -3, 10.25, 0, -3, -3, 99, 1, -3, 10.25, 2.5, 99, 1, -0.5, 0.01, 0.01, 2.5, -3, -3, 0, 10.25, 0.01, 1, 2.5, 2.5, 2.5, 2.5, 0.01, -3, 99, 0, -0.5, 0.01, 99, 10.25, 1, 0.01, -0.5, -3, 10.25, -3, 7, -0.5, 0, 0, 7, -0.5, -3, -0.5, 99, 1, -3, 7, 99, -0.5, 0.01, -3, 0.01, 10.25, 0.01, 7, 99, 2.5, 1, -3, 7, -0.5, 1, 99, 10.25]};10.25 +filter(xs, # > 0)[64];{xs: [7, -3, 10.25, 2.5, -0.5, 0, 1, 7, 0, 2.5, 2.5, 7, 1, -3, -3, 10.25, 0, -0.5, 0, 0.01, 2.5, 0, 10.25, 0, -0.5, 99, 99, 1, 10.25, -3, 0.01, 0.01, 0, 0, 99, -0.5, 0.01, -3, -0.5, 10.25, 1, 0, 2.5, 0.01, 10.25, 1, 1, 7, 0, 7, 0, 10.25, 0, 7, -3, -3, 7, 10.25, 7, 10.25, 10.25, -3, 1, 2.5, 0, 0, 10.25, 99, 99, 2.5, 7, 1, 99, 0, 99, 99, -3, 10.25, -3, -0.5, -0.5, -3, 2.5, -0.5, -3, 10.25, -3, 10.25, 1, 7, 10.25, 2.5, 7, 10.25, 99, -0.5, 2.5, 10.25, 99, 7, 7, 10.25, 2.5, -0.5, -0.5, 0, 99, 1, 1, 2.5, 10.25, 10.25, 99, 7, 1, -3, 1, 7, 7, 2.5, -3, -3, 1, 99, 7, 7, 1, 0.01, 7]};10.25 +filter(xs, # > 0)[64];{xs: [0, 1, 0.01, 7, 7, 1, 99, -0.5, 7, -0.5, -0.5, 99, 99, -3, -0.5, 0.01, -0.5, 99, 99, 99, 2.5, 10.25, 99, -3, -0.5, -0.5, 99, -3, 0, 2.5, 0, 0.01, 1, -0.5, 1, 2.5, 7, 2.5, 0.01, 7, 1, 0, 2.5, 0, -0.5, 0, 2.5, 99, -0.5, -0.5, 99, 0.01, 10.25, 7, 7, 0.01, 1, 99, 7, 1, 0, -0.5, 10.25, 0, -0.5, 0.01, 0, 10.25, 0, 1, 2.5, -3, 7, 10.25, 2.5, 0, 7, 10.25, -3, 0.01, -0.5, -3, 0, 2.5, 7, 0.01, 2.5, -3, -3, 99, 7, 2.5, 7, -0.5, -3, 0, -0.5, -0.5, 0, -3, 99, 0.01, -0.5, 0.01, -3, 10.25, 0.01, 99, 2.5, 99, 1, 1, -3, -3, 1, 2.5, 0.01, 10.25, -0.5, 7, 10.25, 7, 0.01, 0, -3, -0.5, 0.01, 99, 0.01, 7, -3, 7, 0.01, 99, 7, -3, 1, -0.5, 10.25, 7, 0, 99, 10.25, 10.25, 7, 1, 7, 2.5, 1, 7, 0, -3, 0, 1, 0.01, 0.01, -0.5, 99, 1, 1, 2.5, 2.5, -3, 99, -0.5, 7, 7, 7, 7, 0, 2.5, 10.25, -3, -3, -3, 0.01, 0.01, 1, -3, 7, 10.25, 1, 1, 10.25, -3, 2.5, 10.25, 10.25, -3, 1, 0, 0, 0.01, 99, 1, 2.5, 1, -0.5, -0.5, 2.5]};99 +sum(filter(xs, # > t));{xs: [-3, 99, 1, 0, 99, -0.5, 0.01, 7, -3, 1, 2.5, 0.01, 1, 7, 99, 10.25, -3, 0.01, 7, 0.01, 1, 99, 99, 0.01, 7, 7, -3, 2.5, 0.01, 1, -0.5, 99, 1, 2.5, 1, 0.01, 7, 1, 0, 1, -3, -0.5, 0.01, -3, 7, 0.01, -3, 99, 10.25, 1, 99, 2.5, 99, 0.01, 1, 1, -3, 1, 1, 7, 0, 7, 2.5], t: 2.5};974.50 +sum(filter(xs, # > t));{xs: [99, 10.25, 10.25, 10.25, 7, 10.25, -0.5, -0.5, -0.5, 0, -0.5, 0.01, 10.25, 0.01, 10.25, 1, 0.01, 99, 1, 0.01, 7, 7, -3, 1, -3, 7, 2.5, 1, -3, 1, 1, 7, 1, 2.5, 0.01, -0.5, 1, 1, 99, 1, -3, 1, 0, -3, 0.01, 99, -0.5, -3, -3, 10.25, 0.01, 10.25, 99, 1, 7, 2.5, 0.01, 0.01, 1, 99, 7, -3, 7, 10.25], t: 0};762.84 +sum(filter(xs, # > t));{xs: [-3, 1, -0.5, 2.5, 99, 7, 99, 2.5, -0.5, -3, 2.5, 2.5, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 10.25, 2.5, 10.25, 1, 10.25, 0, 0.01, 99, 7, 2.5, 99, 7, 10.25, 7, 0, 99, -3, 7, 0, 99, 0, 0.01, 99, 1, 10.25, 0, -0.5, 1, 7, -3, -3, 99, 1, 10.25, 0.01, 7, 99, 0.01, 0.01, 99, 10.25, 99, 2.5, -3, 2.5, 99, 1], t: 7};1300.75 +sum(filter(xs, # > t));{xs: [2.5, -0.5, 10.25, -0.5, 0.01, -0.5, 99, 0.01, 1, 1, 7, 0.01, 0.01, 2.5, -0.5, 10.25, 2.5, 99, 1, -3, 0, 99, -3, 0, -0.5, 0, -3, 99, 7, -3, 0, -3, 10.25, -0.5, 1, 0, 7, 0, 0, 1, 2.5, -0.5, 7, 99, 1, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 1, 10.25, 10.25, 10.25, 99, 10.25, -0.5, 10.25, 7, -0.5, -3, 2.5, 0, 0, 1, 0.01, 99, -0.5, -0.5, 0.01, 7, 0, 2.5, 10.25, 2.5, 0, 0.01, 99, 0, 0, 7, 10.25, -3, 7, 2.5, 10.25, 10.25, -0.5, 99, 0.01, 10.25, 10.25, 10.25, 0, 0.01, 0, 7, 0, 1, 0.01, 0.01, 1, 1, 0, -3, 0.01, 99, 10.25, 7, 99, 0.01, -3, 0, 99, 0, 99, -3, -0.5, 99, 99, 2.5, 0.01, -3, 1, 2.5, -3], t: 7};1768.50 +sum(filter(xs, # > t));{xs: [0, -0.5, 7, 7, -3, 0.01, 7, -0.5, 7, 0.01, -3, 0, 7, -0.5, 0, 7, -3, 2.5, 1, 99, 7, -0.5, 7, 7, 0, 7, -0.5, -0.5, 2.5, 10.25, 7, 2.5, 0.01, 99, 0, -0.5, 99, 7, -3, 0.01, -0.5, 0, 10.25, 0, 0, 1, 0.01, 7, 0, 99, 1, 1, 10.25, -3, 10.25, 99, 7, 2.5, 1, -0.5, 0.01, 99, 10.25, 0.01, 7, -0.5, 0, 1, 10.25, 10.25, 1, 2.5, 10.25, -3, 2.5, -3, 1, 0, 0, 10.25, 1, 2.5, 10.25, 2.5, 0.01, 2.5, 0, 0, -0.5, 10.25, -0.5, 1, 2.5, -0.5, 99, -3, -0.5, 0, 10.25, -0.5, 7, 0.01, 99, 99, 0.01, 0, 1, 2.5, 99, 99, 7, 99, 0.01, 1, -3, 2.5, 2.5, 0.01, -3, 99, 99, 7, 10.25, -0.5, 2.5, -3, -0.5, 1, 0.01, 99, 0.01, 10.25, -0.5, 10.25, 7, -3, 7, 99, -3, 7, -0.5, 0, 0, 99, -0.5, -3, 99, 99, 10.25, 7, 99, 10.25, -0.5, -0.5, 99, 7, 99, 10.25, 0.01, 0, 10.25, 99, 10.25, 10.25, -0.5, 7, 2.5, 1, 10.25, 10.25, 7, 0, -3, 99, -3, 7, -0.5, 1, 0.01, 0, 0, 0.01, 99, 0.01, 99, -0.5, 2.5, 0, 0, 2.5, 1, -0.5, -0.5, 0.01, 7, 0.01, 1, -3, 10.25, 0.01], t: 0};3068.71 +count(xs, # >= t);{xs: [-3, 99, 1, 0, 99, -0.5, 0.01, 7, -3, 1, 2.5, 0.01, 1, 7, 99, 10.25, -3, 0.01, 7, 0.01, 1, 99, 99, 0.01, 7, 7, -3, 2.5, 0.01, 1, -0.5, 99, 1, 2.5, 1, 0.01, 7, 1, 0, 1, -3, -0.5, 0.01, -3, 7, 0.01, -3, 99, 10.25, 1, 99, 2.5, 99, 0.01, 1, 1, -3, 1, 1, 7, 0, 7, 2.5], t: 2.5};25 +count(xs, # >= t);{xs: [99, 10.25, 10.25, 10.25, 7, 10.25, -0.5, -0.5, -0.5, 0, -0.5, 0.01, 10.25, 0.01, 10.25, 1, 0.01, 99, 1, 0.01, 7, 7, -3, 1, -3, 7, 2.5, 1, -3, 1, 1, 7, 1, 2.5, 0.01, -0.5, 1, 1, 99, 1, -3, 1, 0, -3, 0.01, 99, -0.5, -3, -3, 10.25, 0.01, 10.25, 99, 1, 7, 2.5, 0.01, 0.01, 1, 99, 7, -3, 7, 10.25], t: 0};50 +count(xs, # >= t);{xs: [-3, 1, -0.5, 2.5, 99, 7, 99, 2.5, -0.5, -3, 2.5, 2.5, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 10.25, 2.5, 10.25, 1, 10.25, 0, 0.01, 99, 7, 2.5, 99, 7, 10.25, 7, 0, 99, -3, 7, 0, 99, 0, 0.01, 99, 1, 10.25, 0, -0.5, 1, 7, -3, -3, 99, 1, 10.25, 0.01, 7, 99, 0.01, 0.01, 99, 10.25, 99, 2.5, -3, 2.5, 99, 1], t: 7};30 +count(xs, # >= t);{xs: [2.5, -0.5, 10.25, -0.5, 0.01, -0.5, 99, 0.01, 1, 1, 7, 0.01, 0.01, 2.5, -0.5, 10.25, 2.5, 99, 1, -3, 0, 99, -3, 0, -0.5, 0, -3, 99, 7, -3, 0, -3, 10.25, -0.5, 1, 0, 7, 0, 0, 1, 2.5, -0.5, 7, 99, 1, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 1, 10.25, 10.25, 10.25, 99, 10.25, -0.5, 10.25, 7, -0.5, -3, 2.5, 0, 0, 1, 0.01, 99, -0.5, -0.5, 0.01, 7, 0, 2.5, 10.25, 2.5, 0, 0.01, 99, 0, 0, 7, 10.25, -3, 7, 2.5, 10.25, 10.25, -0.5, 99, 0.01, 10.25, 10.25, 10.25, 0, 0.01, 0, 7, 0, 1, 0.01, 0.01, 1, 1, 0, -3, 0.01, 99, 10.25, 7, 99, 0.01, -3, 0, 99, 0, 99, -3, -0.5, 99, 99, 2.5, 0.01, -3, 1, 2.5, -3], t: 7};44 +count(xs, # >= t);{xs: [0, -0.5, 7, 7, -3, 0.01, 7, -0.5, 7, 0.01, -3, 0, 7, -0.5, 0, 7, -3, 2.5, 1, 99, 7, -0.5, 7, 7, 0, 7, -0.5, -0.5, 2.5, 10.25, 7, 2.5, 0.01, 99, 0, -0.5, 99, 7, -3, 0.01, -0.5, 0, 10.25, 0, 0, 1, 0.01, 7, 0, 99, 1, 1, 10.25, -3, 10.25, 99, 7, 2.5, 1, -0.5, 0.01, 99, 10.25, 0.01, 7, -0.5, 0, 1, 10.25, 10.25, 1, 2.5, 10.25, -3, 2.5, -3, 1, 0, 0, 10.25, 1, 2.5, 10.25, 2.5, 0.01, 2.5, 0, 0, -0.5, 10.25, -0.5, 1, 2.5, -0.5, 99, -3, -0.5, 0, 10.25, -0.5, 7, 0.01, 99, 99, 0.01, 0, 1, 2.5, 99, 99, 7, 99, 0.01, 1, -3, 2.5, 2.5, 0.01, -3, 99, 99, 7, 10.25, -0.5, 2.5, -3, -0.5, 1, 0.01, 99, 0.01, 10.25, -0.5, 10.25, 7, -3, 7, 99, -3, 7, -0.5, 0, 0, 99, -0.5, -3, 99, 99, 10.25, 7, 99, 10.25, -0.5, -0.5, 99, 7, 99, 10.25, 0.01, 0, 10.25, 99, 10.25, 10.25, -0.5, 7, 2.5, 1, 10.25, 10.25, 7, 0, -3, 99, -3, 7, -0.5, 1, 0.01, 0, 0, 0.01, 99, 0.01, 99, -0.5, 2.5, 0, 0, 2.5, 1, -0.5, -0.5, 0.01, 7, 0.01, 1, -3, 10.25, 0.01], t: 0};156 +map(xs, # > t ? 1 : 0);{xs: [-3, 99, 1, 0, 99, -0.5, 0.01, 7, -3, 1, 2.5, 0.01, 1, 7, 99, 10.25, -3, 0.01, 7, 0.01, 1, 99, 99, 0.01, 7, 7, -3, 2.5, 0.01, 1, -0.5, 99, 1, 2.5, 1, 0.01, 7, 1, 0, 1, -3, -0.5, 0.01, -3, 7, 0.01, -3, 99, 10.25, 1, 99, 2.5, 99, 0.01, 1, 1, -3, 1, 1, 7, 0, 7, 2.5], t: 2.5};[0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0] +map(xs, # > t ? 1 : 0);{xs: [99, 10.25, 10.25, 10.25, 7, 10.25, -0.5, -0.5, -0.5, 0, -0.5, 0.01, 10.25, 0.01, 10.25, 1, 0.01, 99, 1, 0.01, 7, 7, -3, 1, -3, 7, 2.5, 1, -3, 1, 1, 7, 1, 2.5, 0.01, -0.5, 1, 1, 99, 1, -3, 1, 0, -3, 0.01, 99, -0.5, -3, -3, 10.25, 0.01, 10.25, 99, 1, 7, 2.5, 0.01, 0.01, 1, 99, 7, -3, 7, 10.25], t: 0};[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1] +map(xs, # > t ? 1 : 0);{xs: [-3, 1, -0.5, 2.5, 99, 7, 99, 2.5, -0.5, -3, 2.5, 2.5, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 10.25, 2.5, 10.25, 1, 10.25, 0, 0.01, 99, 7, 2.5, 99, 7, 10.25, 7, 0, 99, -3, 7, 0, 99, 0, 0.01, 99, 1, 10.25, 0, -0.5, 1, 7, -3, -3, 99, 1, 10.25, 0.01, 7, 99, 0.01, 0.01, 99, 10.25, 99, 2.5, -3, 2.5, 99, 1], t: 7};[0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0] +sum(map(xs, # > t ? # : 0));{xs: [-3, 99, 1, 0, 99, -0.5, 0.01, 7, -3, 1, 2.5, 0.01, 1, 7, 99, 10.25, -3, 0.01, 7, 0.01, 1, 99, 99, 0.01, 7, 7, -3, 2.5, 0.01, 1, -0.5, 99, 1, 2.5, 1, 0.01, 7, 1, 0, 1, -3, -0.5, 0.01, -3, 7, 0.01, -3, 99, 10.25, 1, 99, 2.5, 99, 0.01, 1, 1, -3, 1, 1, 7, 0, 7, 2.5], t: 2.5};974.50 +sum(map(xs, # > t ? # : 0));{xs: [99, 10.25, 10.25, 10.25, 7, 10.25, -0.5, -0.5, -0.5, 0, -0.5, 0.01, 10.25, 0.01, 10.25, 1, 0.01, 99, 1, 0.01, 7, 7, -3, 1, -3, 7, 2.5, 1, -3, 1, 1, 7, 1, 2.5, 0.01, -0.5, 1, 1, 99, 1, -3, 1, 0, -3, 0.01, 99, -0.5, -3, -3, 10.25, 0.01, 10.25, 99, 1, 7, 2.5, 0.01, 0.01, 1, 99, 7, -3, 7, 10.25], t: 0};762.84 +sum(map(xs, # > t ? # : 0));{xs: [-3, 1, -0.5, 2.5, 99, 7, 99, 2.5, -0.5, -3, 2.5, 2.5, 10.25, 10.25, 10.25, 0.01, -0.5, 10.25, 10.25, 2.5, 10.25, 1, 10.25, 0, 0.01, 99, 7, 2.5, 99, 7, 10.25, 7, 0, 99, -3, 7, 0, 99, 0, 0.01, 99, 1, 10.25, 0, -0.5, 1, 7, -3, -3, 99, 1, 10.25, 0.01, 7, 99, 0.01, 0.01, 99, 10.25, 99, 2.5, -3, 2.5, 99, 1], t: 7};1300.75 +sum(map(xs, # > t ? # : 0));{xs: [2.5, -0.5, 10.25, -0.5, 0.01, -0.5, 99, 0.01, 1, 1, 7, 0.01, 0.01, 2.5, -0.5, 10.25, 2.5, 99, 1, -3, 0, 99, -3, 0, -0.5, 0, -3, 99, 7, -3, 0, -3, 10.25, -0.5, 1, 0, 7, 0, 0, 1, 2.5, -0.5, 7, 99, 1, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 1, 10.25, 10.25, 10.25, 99, 10.25, -0.5, 10.25, 7, -0.5, -3, 2.5, 0, 0, 1, 0.01, 99, -0.5, -0.5, 0.01, 7, 0, 2.5, 10.25, 2.5, 0, 0.01, 99, 0, 0, 7, 10.25, -3, 7, 2.5, 10.25, 10.25, -0.5, 99, 0.01, 10.25, 10.25, 10.25, 0, 0.01, 0, 7, 0, 1, 0.01, 0.01, 1, 1, 0, -3, 0.01, 99, 10.25, 7, 99, 0.01, -3, 0, 99, 0, 99, -3, -0.5, 99, 99, 2.5, 0.01, -3, 1, 2.5, -3], t: 7};1768.50 +sum(map(xs, # > t ? # : 0));{xs: [0, -0.5, 7, 7, -3, 0.01, 7, -0.5, 7, 0.01, -3, 0, 7, -0.5, 0, 7, -3, 2.5, 1, 99, 7, -0.5, 7, 7, 0, 7, -0.5, -0.5, 2.5, 10.25, 7, 2.5, 0.01, 99, 0, -0.5, 99, 7, -3, 0.01, -0.5, 0, 10.25, 0, 0, 1, 0.01, 7, 0, 99, 1, 1, 10.25, -3, 10.25, 99, 7, 2.5, 1, -0.5, 0.01, 99, 10.25, 0.01, 7, -0.5, 0, 1, 10.25, 10.25, 1, 2.5, 10.25, -3, 2.5, -3, 1, 0, 0, 10.25, 1, 2.5, 10.25, 2.5, 0.01, 2.5, 0, 0, -0.5, 10.25, -0.5, 1, 2.5, -0.5, 99, -3, -0.5, 0, 10.25, -0.5, 7, 0.01, 99, 99, 0.01, 0, 1, 2.5, 99, 99, 7, 99, 0.01, 1, -3, 2.5, 2.5, 0.01, -3, 99, 99, 7, 10.25, -0.5, 2.5, -3, -0.5, 1, 0.01, 99, 0.01, 10.25, -0.5, 10.25, 7, -3, 7, 99, -3, 7, -0.5, 0, 0, 99, -0.5, -3, 99, 99, 10.25, 7, 99, 10.25, -0.5, -0.5, 99, 7, 99, 10.25, 0.01, 0, 10.25, 99, 10.25, 10.25, -0.5, 7, 2.5, 1, 10.25, 10.25, 7, 0, -3, 99, -3, 7, -0.5, 1, 0.01, 0, 0, 0.01, 99, 0.01, 99, -0.5, 2.5, 0, 0, 2.5, 1, -0.5, -0.5, 0.01, 7, 0.01, 1, -3, 10.25, 0.01], t: 0};3068.71 +# long lists: the deciding element sits exactly at a boundary +some(xs, # == 1);{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[0];{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]};true +map(xs, # == 1)[62];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +map(xs, # == 1)[63];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +some(xs, # == 1);{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[0];{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]};true +map(xs, # == 1)[62];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]};true +map(xs, # == 1)[63];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +map(xs, # == 1)[64];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +some(xs, # == 1);{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[0];{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[62];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[63];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[64];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[65];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +map(xs, # == 1)[127];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +some(xs, # == 1);{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[0];{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[62];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[63];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[64];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[65];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]};true +map(xs, # == 1)[127];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +map(xs, # == 1)[128];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +some(xs, # == 1);{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[0];{xs: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[62];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[63];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[64];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[65];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[127];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +map(xs, # == 1)[128];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +some(xs, # == 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +map(xs, # == 1)[199];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]};true +all(xs, # == 1);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +none(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +one(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +count(xs, # == 1);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};63 +filter(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};63 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};63 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};[0] +all(xs, # == 1);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +none(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +one(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +count(xs, # == 1);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};64 +filter(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1]};64 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};64 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};64 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};[0] +all(xs, # == 1);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +none(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +one(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +count(xs, # == 1);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};128 +filter(xs, # == 0);{xs: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};128 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};128 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +none(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};true +count(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};128 +filter(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]};[0] +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +all(xs, # == 1);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};true +one(xs, # == 0);{xs: [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]};false +one(xs, # == 0);{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]};false +# long lists: short-circuit past a boundary before an erroring element +some(xs, # > 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};true +all(xs, # < 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};false +map(xs, # + 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};!error +count(xs, # > 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};!error +sum(xs);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};!error +map(xs, # ?? -1)[65];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};-1 +count(xs, # == null);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0]};1 +some(xs, # > 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};true +all(xs, # < 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};false +map(xs, # + 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};!error +count(xs, # > 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};!error +sum(xs);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};!error +map(xs, # ?? -1)[129];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};-1 +count(xs, # == null);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null]};1 +some(xs, # > 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};true +all(xs, # < 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};false +map(xs, # + 1);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};!error +count(xs, # > 3);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};!error +sum(xs);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};!error +map(xs, # ?? -1)[66];{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};-1 +count(xs, # == null);{xs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]};1 +# long lists of objects with missing and heterogeneous fields +len(rows);{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};50 +len(rows);{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};64 +len(rows);{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};65 +len(rows);{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};128 +len(rows);{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};129 +len(rows);{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};200 +count(rows, #.v == null);{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};10 +count(rows, #.v == null);{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};14 +count(rows, #.v == null);{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};13 +count(rows, #.v == null);{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};24 +count(rows, #.v == null);{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};24 +count(rows, #.v == null);{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};30 +sum(map(rows, #.v ?? 0));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};669.30 +sum(map(rows, #.v ?? 0));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};475.04 +sum(map(rows, #.v ?? 0));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};697.05 +sum(map(rows, #.v ?? 0));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};1314.87 +sum(map(rows, #.v ?? 0));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};1657.89 +sum(map(rows, #.v ?? 0));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};2234.20 +sum(map(filter(rows, #.v != null), #.v));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};669.30 +sum(map(filter(rows, #.v != null), #.v));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};475.04 +sum(map(filter(rows, #.v != null), #.v));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};697.05 +sum(map(filter(rows, #.v != null), #.v));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};1314.87 +sum(map(filter(rows, #.v != null), #.v));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};1657.89 +sum(map(filter(rows, #.v != null), #.v));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};2234.20 +sum(map(rows, #.v));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};!error +sum(map(rows, #.v));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};!error +sum(map(rows, #.v));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};!error +sum(map(rows, #.v));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};!error +sum(map(rows, #.v));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};!error +sum(map(rows, #.v));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};!error +len(flatMap(rows, #.tags ?? []));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};54 +len(flatMap(rows, #.tags ?? []));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};77 +len(flatMap(rows, #.tags ?? []));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};69 +len(flatMap(rows, #.tags ?? []));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};146 +len(flatMap(rows, #.tags ?? []));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};172 +len(flatMap(rows, #.tags ?? []));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};266 +count(flatMap(rows, #.tags ?? []), # == 'x');{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};14 +count(flatMap(rows, #.tags ?? []), # == 'x');{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};28 +count(flatMap(rows, #.tags ?? []), # == 'x');{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};20 +count(flatMap(rows, #.tags ?? []), # == 'x');{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};51 +count(flatMap(rows, #.tags ?? []), # == 'x');{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};60 +count(flatMap(rows, #.tags ?? []), # == 'x');{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};89 +map(rows, len(#.tags ?? []));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};[0, 0, 1, 0, 3, 0, 1, 0, 0, 2, 0, 3, 1, 0, 3, 1, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 3, 0, 0, 2, 2, 2, 3, 0, 0, 0, 2, 0, 0, 1, 0, 2, 1, 3, 2, 1, 3, 0, 1, 1] +map(rows, len(#.tags ?? []));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};[1, 0, 1, 0, 2, 2, 1, 3, 1, 1, 2, 1, 3, 0, 0, 0, 0, 2, 1, 3, 0, 0, 2, 3, 0, 3, 0, 1, 1, 3, 3, 0, 2, 1, 0, 1, 3, 0, 3, 0, 0, 0, 0, 3, 1, 3, 3, 0, 1, 0, 0, 3, 1, 0, 0, 3, 0, 2, 0, 1, 1, 2, 1, 2] +count(rows, 'y' in (#.tags ?? []));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};19 +count(rows, 'y' in (#.tags ?? []));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};16 +count(rows, 'y' in (#.tags ?? []));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};23 +count(rows, 'y' in (#.tags ?? []));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};36 +count(rows, 'y' in (#.tags ?? []));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};42 +count(rows, 'y' in (#.tags ?? []));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};67 +len(filter(rows, #.g == 'a'));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};13 +len(filter(rows, #.g == 'a'));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};20 +len(filter(rows, #.g == 'a'));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};17 +len(filter(rows, #.g == 'a'));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};45 +len(filter(rows, #.g == 'a'));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};30 +len(filter(rows, #.g == 'a'));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};70 +map(values(mergeDeep(map(filter(rows, #.g != null), {[#.g]: [1]}))), len(#));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};[13, 16, 14] +map(values(mergeDeep(map(filter(rows, #.g != null), {[#.g]: [1]}))), len(#));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};[18, 20, 19] +map(values(mergeDeep(map(filter(rows, #.g != null), {[#.g]: [1]}))), len(#));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};[18, 17, 21] +map(values(mergeDeep(map(filter(rows, #.g != null), {[#.g]: [1]}))), len(#));{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};[45, 41, 31] +map(values(mergeDeep(map(filter(rows, #.g != null), {[#.g]: [1]}))), len(#));{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};[34, 56, 30] +map(values(mergeDeep(map(filter(rows, #.g != null), {[#.g]: [1]}))), len(#));{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};[53, 70, 60] +mergeDeep(map(filter(rows, #.v != null), {[#.g]: [#.v]}));{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};{c: [-0.5, 99, 0, 7, 2.5, -3, 2.5, 0.01, 10.25, 7, 7, 7, 1, 99, 0, -0.5], a: [99, 0.01, -3, 0.01, 0, 0.01, -0.5, 99, 1, -0.5], b: [-0.5, 10.25, 99, 1, 0.01, 7, 1, -3, -3, 7, 7, 99, 1, 10.25]} +mergeDeep(map(filter(rows, #.v != null), {[#.g]: [#.v]}));{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};{b: [1, 10.25, 0, 0.01, 0, 7, -3, 99, -0.5, -3, 0, 1, -3, 10.25, -0.5], a: [0.01, 0, 1, 99, -3, -3, 10.25, 0, 10.25, 10.25, -3, 0.01, 2.5, 99, 99, 2.5], c: [1, 1, 7, -3, -3, 2.5, 7, 10.25, -3, -0.5, 1, 0, -3, 1, 7, 0, 7, 0.01, -0.5]} +mergeDeep(map(filter(rows, #.v != null), {[#.g]: [#.v]}));{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};{c: [1, 0.01, 99, 0.01, -3, 99, 99, -3, 0, 0, 7, -0.5, -0.5, 0.01, 7, 99, 2.5, 0], a: [1, 7, 10.25, 0, 7, 10.25, 7, 7, -3, 0.01, 7, -3, 0, 99], b: [-3, 10.25, 7, -0.5, 7, 10.25, 1, 0, -3, -3, -0.5, 0.01, -0.5, 99, -0.5, 10.25, 0, -3, 0, 10.25]} +map(rows, #.v ?? 0)[64];{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};null +map(rows, #.v ?? 0)[64];{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};null +map(rows, #.v ?? 0)[64];{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};99 +map(rows, #.v ?? 0)[64];{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};0 +map(rows, #.v ?? 0)[64];{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};0.01 +map(rows, #.v ?? 0)[64];{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};0 +filter(rows, #.v == null)[1];{rows: [{v: null, g: 'a'}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {}, {v: 0.01, g: 'a', tags: ['y', 'y', 'z']}, {v: null, g: 'a'}, {v: 99, g: 'c', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {}, {v: 10.25, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'c', tags: []}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 1, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: -3, g: 'a', tags: ['y', 'y']}, {}, {v: null, g: 'a'}, {v: -3, g: 'c', tags: []}, {v: 2.5, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'a', tags: ['y', 'y']}, {v: 0.01, g: 'c', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'x']}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: 7, g: 'c', tags: ['z', 'y']}, {v: 1, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: -3, g: 'b', tags: []}, {}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'c', tags: ['z', 'y']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['y', 'x']}, {v: 1, g: 'a', tags: ['x']}, {v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z']}, {v: 10.25, g: 'b', tags: ['x']}]};{} +filter(rows, #.v == null)[1];{rows: [{v: 1, g: 'b', tags: ['x']}, {v: null, g: 'b'}, {v: 10.25, g: 'b', tags: ['x']}, {v: 0.01, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['z']}, {v: 99, g: 'a', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 7, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 10.25, g: 'a', tags: []}, {v: 99, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'x', 'x']}, {v: 2.5, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 7, g: 'c', tags: ['z']}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['x', 'z', 'x']}, {}, {v: -0.5, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: null, g: 'a'}, {v: null, g: 'a'}, {v: 0, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'b', tags: ['x']}, {v: -3, g: 'c', tags: ['y', 'x', 'z']}, {v: 1, g: 'c', tags: ['y', 'y', 'z']}, {}, {v: 7, g: 'c', tags: ['y']}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 99, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {}, {v: 7, g: 'c', tags: ['y', 'z', 'z']}, {}, {v: 99, g: 'a', tags: ['x', 'y']}, {}, {v: 2.5, g: 'a', tags: ['x']}, {v: 0.01, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x', 'y']}]};{v: null, g: 'a'} +filter(rows, #.v == null)[1];{rows: [{}, {}, {v: 1, g: 'c', tags: ['z', 'y', 'y']}, {v: 1, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['y', 'x', 'y']}, {}, {v: 99, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'b', tags: ['z']}, {}, {}, {v: 7, g: 'b', tags: ['z']}, {v: -0.5, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['z']}, {}, {v: 7, g: 'b', tags: ['y']}, {v: 10.25, g: 'b', tags: []}, {v: 1, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: -3, g: 'b', tags: ['z']}, {v: -3, g: 'c', tags: ['y', 'z']}, {v: 99, g: 'c', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: -0.5, g: 'b', tags: ['y']}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: -3, g: 'c', tags: ['y']}, {v: 0, g: 'c', tags: ['z', 'y']}, {v: 0, g: 'c', tags: ['y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'c', tags: ['x', 'z', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 7, g: 'a', tags: []}, {v: -0.5, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['z', 'x']}, {v: null, g: 'a'}, {}, {v: null, g: 'b'}, {v: -0.5, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {}, {v: -3, g: 'a', tags: ['y', 'z']}, {v: 7, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'a', tags: ['x']}, {v: 99, g: 'c', tags: ['x']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['z']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: -3, g: 'b', tags: ['z', 'z']}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'a', tags: ['z']}, {}, {v: 10.25, g: 'b', tags: []}, {v: 0, g: 'c', tags: ['x', 'z']}, {v: 99, g: 'a', tags: ['x']}]};{} +filter(rows, #.v == null)[1];{rows: [{}, {v: 7, g: 'a', tags: []}, {}, {v: null, g: 'b'}, {v: 2.5, g: 'a', tags: ['x', 'z', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 10.25, g: 'b', tags: ['z', 'y']}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 0.01, g: 'a', tags: ['x', 'z']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x', 'y']}, {v: 2.5, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['z', 'z', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'a', tags: ['z', 'z']}, {}, {v: null, g: 'b'}, {}, {v: -0.5, g: 'c', tags: ['y']}, {v: 99, g: 'b', tags: ['z', 'y', 'x']}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: -0.5, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['x', 'z']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'y']}, {}, {v: 7, g: 'a', tags: []}, {v: 99, g: 'a', tags: ['x', 'x']}, {v: null, g: 'b'}, {v: null, g: 'a'}, {}, {v: -0.5, g: 'a', tags: ['x']}, {}, {v: 2.5, g: 'c', tags: ['z', 'y', 'y']}, {v: -3, g: 'b', tags: []}, {v: 7, g: 'b', tags: []}, {v: 7, g: 'a', tags: ['y']}, {v: 7, g: 'a', tags: []}, {v: 0, g: 'a', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'c', tags: ['x', 'x', 'z']}, {v: 7, g: 'c', tags: ['x', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 10.25, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y', 'x']}, {v: 0.01, g: 'a', tags: ['z']}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 1, g: 'c', tags: ['x', 'y', 'y']}, {v: 0, g: 'a', tags: ['x', 'y']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 1, g: 'a', tags: ['z']}, {v: 0, g: 'b', tags: ['y', 'z', 'y']}, {v: 1, g: 'c', tags: ['y', 'x']}, {v: 0.01, g: 'b', tags: []}, {v: 99, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 10.25, g: 'c', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'a', tags: ['x', 'y', 'x']}, {v: 0, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 0, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['z', 'z']}, {}, {v: 0, g: 'b', tags: ['x', 'y']}, {v: 99, g: 'c', tags: []}, {v: 1, g: 'a', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['z']}, {}, {v: 7, g: 'b', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'x', 'x']}, {v: 1, g: 'c', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: -0.5, g: 'c', tags: ['x']}, {v: -0.5, g: 'a', tags: ['y', 'z']}, {v: 0.01, g: 'c', tags: ['z', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'z', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 0.01, g: 'b', tags: ['y']}, {v: 0, g: 'c', tags: ['y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'a', tags: []}, {v: 7, g: 'b', tags: ['y', 'z', 'y']}, {v: 0.01, g: 'b', tags: []}, {v: 1, g: 'a', tags: ['y', 'z', 'x']}, {v: 99, g: 'b', tags: ['x', 'y', 'x']}, {v: 2.5, g: 'a', tags: ['z', 'z', 'z']}, {}, {v: 1, g: 'a', tags: ['z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 1, g: 'c', tags: ['z', 'y', 'z']}, {v: -0.5, g: 'a', tags: ['z', 'z']}, {v: 10.25, g: 'b', tags: ['z', 'x']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'c', tags: ['x']}, {v: 1, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: null, g: 'a'}, {v: 1, g: 'c', tags: ['x']}, {v: 99, g: 'c', tags: ['z', 'y']}, {v: -3, g: 'b', tags: ['y', 'x', 'x']}, {v: 10.25, g: 'b', tags: ['z']}]};{} +filter(rows, #.v == null)[1];{rows: [{v: -0.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -0.5, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['y']}, {v: 1, g: 'b', tags: ['y', 'x', 'x']}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: []}, {v: 0.01, g: 'b', tags: ['x', 'y']}, {v: 0, g: 'b', tags: ['x', 'x']}, {v: null, g: 'b'}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'x', 'x']}, {v: -0.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: 7, g: 'c', tags: ['y']}, {v: -3, g: 'b', tags: ['y', 'z']}, {v: 1, g: 'b', tags: ['z', 'x', 'y']}, {v: 7, g: 'c', tags: ['y', 'x', 'x']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: []}, {v: -3, g: 'a', tags: ['z', 'x']}, {v: 10.25, g: 'b', tags: []}, {v: 10.25, g: 'b', tags: ['x', 'x', 'y']}, {v: null, g: 'a'}, {v: 7, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: []}, {v: 10.25, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'x']}, {v: 2.5, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['y', 'y', 'x']}, {v: 99, g: 'a', tags: ['x']}, {v: 0, g: 'b', tags: ['z', 'z', 'x']}, {v: 10.25, g: 'b', tags: ['y', 'z']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 10.25, g: 'c', tags: ['z']}, {v: 7, g: 'c', tags: ['y']}, {v: 0.01, g: 'c', tags: ['z']}, {v: 99, g: 'b', tags: ['y']}, {v: 7, g: 'c', tags: ['x']}, {v: 7, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: ['z']}, {v: 99, g: 'c', tags: ['x', 'y']}, {v: 0.01, g: 'c', tags: []}, {}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['x', 'z', 'z']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'y', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z', 'y']}, {v: 1, g: 'b', tags: ['y', 'y']}, {v: null, g: 'a'}, {v: 2.5, g: 'a', tags: []}, {v: 1, g: 'b', tags: ['y', 'z', 'y']}, {v: null, g: 'b'}, {v: 99, g: 'b', tags: ['z', 'y', 'y']}, {v: 0.01, g: 'b', tags: ['x', 'x']}, {}, {v: -3, g: 'c', tags: []}, {v: 1, g: 'c', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'b', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'a', tags: ['x', 'x', 'x']}, {}, {}, {v: null, g: 'b'}, {v: 7, g: 'c', tags: ['y', 'z', 'y']}, {v: 10.25, g: 'b', tags: ['x', 'z']}, {v: 1, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: -3, g: 'b', tags: ['y', 'x', 'y']}, {v: 0, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: -3, g: 'c', tags: ['z', 'x', 'z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: null, g: 'b'}, {v: null, g: 'b'}, {v: 0, g: 'b', tags: []}, {v: null, g: 'b'}, {v: 0, g: 'c', tags: []}, {v: null, g: 'b'}, {v: 99, g: 'c', tags: ['x', 'x', 'x']}, {v: 1, g: 'b', tags: ['x', 'x']}, {v: 0, g: 'b', tags: ['x', 'z']}, {v: 99, g: 'c', tags: ['y', 'x']}, {v: 99, g: 'b', tags: ['y', 'z']}, {v: -3, g: 'a', tags: []}, {v: 99, g: 'b', tags: ['z', 'x', 'z']}, {v: 7, g: 'b', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'z']}, {}, {v: 99, g: 'c', tags: ['y', 'x', 'y']}, {v: 7, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 2.5, g: 'a', tags: ['z']}, {v: -3, g: 'b', tags: []}, {v: 99, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['z', 'x']}, {v: -0.5, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'z', 'z']}, {v: null, g: 'a'}, {}, {v: 0.01, g: 'b', tags: ['z']}, {v: -0.5, g: 'a', tags: ['z', 'z', 'y']}, {v: 7, g: 'c', tags: ['z']}, {v: 2.5, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'y']}, {v: 0.01, g: 'b', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z', 'z']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: 0.01, g: 'c', tags: ['z', 'y', 'x']}, {v: -0.5, g: 'c', tags: ['z']}, {v: null, g: 'b'}, {v: 99, g: 'a', tags: ['x']}, {}, {v: 10.25, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['z']}, {v: 0, g: 'b', tags: ['z', 'y', 'y']}, {}, {v: 99, g: 'a', tags: []}, {v: 1, g: 'a', tags: ['y']}]};{} +filter(rows, #.v == null)[1];{rows: [{v: 99, g: 'b', tags: ['y', 'x', 'z']}, {v: 0.01, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['y', 'y', 'x']}, {v: null, g: 'a'}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'a', tags: ['x', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: 7, g: 'a', tags: ['z', 'x', 'z']}, {v: 0, g: 'a', tags: ['y', 'y']}, {v: 99, g: 'c', tags: []}, {v: -0.5, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['z', 'z', 'y']}, {v: -3, g: 'b', tags: ['x', 'z', 'y']}, {v: 0, g: 'b', tags: ['y', 'z', 'x']}, {v: -0.5, g: 'b', tags: ['z', 'z']}, {v: 99, g: 'c', tags: ['y', 'z']}, {v: 10.25, g: 'c', tags: ['y']}, {v: -0.5, g: 'c', tags: ['z', 'z']}, {v: null, g: 'a'}, {v: 0.01, g: 'b', tags: []}, {v: 7, g: 'b', tags: ['y', 'y', 'x']}, {v: -0.5, g: 'b', tags: ['x']}, {v: -3, g: 'a', tags: []}, {v: 1, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y']}, {v: 99, g: 'b', tags: ['z']}, {v: -3, g: 'b', tags: ['y', 'x']}, {v: null, g: 'a'}, {v: 99, g: 'a', tags: ['y', 'y']}, {}, {}, {}, {v: null, g: 'a'}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'z']}, {v: 2.5, g: 'b', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: 1, g: 'c', tags: ['x', 'y', 'z']}, {v: -0.5, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}, {v: 1, g: 'a', tags: ['x']}, {v: 2.5, g: 'c', tags: ['y']}, {v: 0, g: 'a', tags: ['z', 'z', 'x']}, {}, {v: 99, g: 'b', tags: ['y', 'y', 'z']}, {v: 99, g: 'c', tags: ['x', 'x', 'y']}, {v: 10.25, g: 'b', tags: ['y', 'y']}, {}, {v: 2.5, g: 'c', tags: ['x', 'y', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: []}, {v: 2.5, g: 'c', tags: ['x']}, {v: 2.5, g: 'c', tags: ['x', 'z']}, {}, {v: 99, g: 'a', tags: ['z']}, {v: 1, g: 'c', tags: ['z', 'x']}, {v: 99, g: 'b', tags: []}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'b', tags: ['y', 'y']}, {v: 7, g: 'c', tags: ['z', 'x']}, {v: 0.01, g: 'c', tags: ['y']}, {v: 10.25, g: 'a', tags: []}, {v: 2.5, g: 'b', tags: ['z']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x']}, {v: 0.01, g: 'c', tags: []}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'a', tags: ['y', 'z', 'y']}, {v: 99, g: 'c', tags: ['z']}, {v: -0.5, g: 'b', tags: ['x']}, {v: 7, g: 'b', tags: ['y', 'x', 'y']}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 0, g: 'b', tags: []}, {v: 10.25, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 7, g: 'b', tags: ['y', 'x']}, {v: -0.5, g: 'c', tags: ['x', 'z']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {}, {v: -0.5, g: 'a', tags: []}, {v: 0.01, g: 'c', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['x', 'x', 'z']}, {v: 10.25, g: 'c', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'y']}, {v: null, g: 'b'}, {v: -0.5, g: 'a', tags: ['y', 'x']}, {}, {v: 7, g: 'a', tags: ['x']}, {v: -3, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['z']}, {v: 7, g: 'a', tags: ['x']}, {v: 7, g: 'a', tags: ['z', 'x', 'x']}, {v: 2.5, g: 'b', tags: ['x', 'x']}, {v: -3, g: 'a', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'x']}, {}, {v: -0.5, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0.01, g: 'c', tags: ['y', 'x']}, {v: 0, g: 'a', tags: []}, {v: -3, g: 'c', tags: ['y', 'x', 'x']}, {v: 7, g: 'b', tags: []}, {v: -3, g: 'b', tags: ['x']}, {v: 0, g: 'b', tags: []}, {v: 0, g: 'b', tags: ['z', 'x', 'x']}, {v: 7, g: 'b', tags: ['x', 'x']}, {v: 99, g: 'a', tags: ['z', 'x', 'y']}, {v: 1, g: 'b', tags: []}, {v: 0, g: 'a', tags: []}, {v: 1, g: 'c', tags: []}, {v: 0, g: 'b', tags: ['x', 'x', 'x']}, {v: 7, g: 'a', tags: ['z', 'z', 'y']}, {v: 0, g: 'c', tags: []}, {v: 1, g: 'b', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['z']}, {}, {v: -0.5, g: 'a', tags: ['z', 'y']}, {v: 10.25, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: []}, {v: -3, g: 'c', tags: ['x', 'z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 0, g: 'c', tags: ['z', 'z', 'z']}, {v: 0, g: 'b', tags: []}, {}, {v: 0, g: 'c', tags: ['z', 'x']}, {v: 2.5, g: 'c', tags: []}, {v: 0.01, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['x']}, {v: 7, g: 'c', tags: ['y', 'z', 'x']}, {v: 0, g: 'a', tags: ['x', 'y', 'x']}, {v: -3, g: 'b', tags: []}, {v: 1, g: 'a', tags: []}, {v: 10.25, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y']}, {v: -0.5, g: 'b', tags: []}, {v: 1, g: 'c', tags: []}, {v: 7, g: 'a', tags: []}, {v: 7, g: 'a', tags: ['x', 'y']}, {}, {v: -0.5, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'b', tags: ['z']}, {v: -3, g: 'a', tags: ['z', 'x', 'y']}, {v: 10.25, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: 2.5, g: 'a', tags: []}, {v: 0.01, g: 'b', tags: ['y']}, {v: 10.25, g: 'a', tags: ['z', 'y', 'z']}, {v: 0.01, g: 'a', tags: ['z', 'z']}, {v: 0.01, g: 'b', tags: []}, {v: 2.5, g: 'c', tags: ['y', 'y', 'x']}, {}, {v: 1, g: 'c', tags: ['y', 'x', 'z']}, {v: 99, g: 'b', tags: ['z', 'x']}, {v: 99, g: 'c', tags: []}, {v: 0, g: 'c', tags: []}, {v: -3, g: 'a', tags: ['y', 'z', 'y']}, {v: 2.5, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 10.25, g: 'a', tags: ['y', 'z', 'y']}, {}, {v: null, g: 'b'}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: -3, g: 'c', tags: ['z']}, {v: 0.01, g: 'b', tags: ['z']}, {v: 10.25, g: 'a', tags: ['x']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -3, g: 'a', tags: ['y', 'z', 'x']}, {v: 10.25, g: 'a', tags: []}, {v: 10.25, g: 'a', tags: ['x', 'y', 'z']}, {v: 1, g: 'c', tags: ['x', 'x']}, {v: 10.25, g: 'c', tags: []}, {v: 99, g: 'a', tags: ['y']}, {v: 2.5, g: 'a', tags: ['y', 'x']}, {}, {v: 1, g: 'c', tags: ['x', 'z']}, {v: 0, g: 'c', tags: ['y', 'z', 'y']}, {}, {v: -3, g: 'c', tags: ['x', 'y']}, {v: 2.5, g: 'a', tags: ['x']}, {v: -0.5, g: 'a', tags: []}, {v: 0, g: 'a', tags: ['z', 'x', 'z']}, {v: 0.01, g: 'c', tags: ['x', 'y', 'y']}, {v: 2.5, g: 'c', tags: ['y', 'z', 'x']}, {v: 0.01, g: 'b', tags: ['y', 'z']}, {v: 99, g: 'b', tags: ['y', 'y', 'y']}, {v: 10.25, g: 'a', tags: ['y', 'x', 'z']}, {v: -0.5, g: 'c', tags: ['z', 'z', 'x']}, {v: -0.5, g: 'c', tags: ['z', 'x']}, {v: null, g: 'a'}, {v: 1, g: 'b', tags: ['x']}, {v: 99, g: 'c', tags: []}, {v: 7, g: 'c', tags: []}, {v: null, g: 'a'}, {v: 99, g: 'b', tags: ['y', 'y']}, {v: 0.01, g: 'b', tags: ['z']}, {v: null, g: 'a'}, {v: 2.5, g: 'c', tags: ['y', 'y', 'y']}, {v: -3, g: 'a', tags: ['y', 'y', 'z']}]};{v: null, g: 'a'} +# long outer lists with short inner lists, and the reverse +sum(flatMap(gs, #.xs));{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};764.34 +sum(flatMap(gs, #.xs));{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};1373.08 +sum(flatMap(gs, #.xs));{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};2776.75 +sum(flatMap(gs, #.xs));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};2063.45 +sum(flatMap(gs, #.xs));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};641.58 +sum(flatMap(gs, #.xs));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};194 +len(flatMap(gs, #.xs));{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};77 +len(flatMap(gs, #.xs));{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};97 +len(flatMap(gs, #.xs));{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};213 +len(flatMap(gs, #.xs));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};147 +len(flatMap(gs, #.xs));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};87 +len(flatMap(gs, #.xs));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};129 +map(gs, len(#.xs));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};[23, 105, 19] +map(gs, len(#.xs));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};[18, 69] +map(gs, len(#.xs));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};[64, 65] +map(gs, sum(#.xs));{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};[0, 11, 0.01, 106, 0, 2.01, 0, 0, 1, 0, 14.01, 20.50, 0, 0, -3, -0.49, 2.5, 8.25, 1, 9.5, 11, -0.5, 99.01, 0, 0, 0, -2.99, 0, 0, 0, 0, 0.5, 0, 11.25, -0.5, 0.01, 109.25, 1, -3, 17.25, 0, 4, 8, 0, 3.5, 9.51, 0, 0, 1, 7, -0.5, 109.25, 101.5, 0, 0, 1, -0.5, 0, 2.0, 0, 5.0, 99.01, 0, 0] +map(gs, sum(#.xs));{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};[198, -1, 0, -0.5, 108.75, 1, 0.51, 0, 0, 7, 99.01, 99, 7, 7.25, 0, 0.01, 7.25, 96, 0, -3.5, 0.01, 0, 11, 0, 7.01, -0.5, 8, 0, 95.5, 0, 0.01, 99, 0.01, 10.26, 9.5, 0, 1, 3.5, 0, 0, 1, 99, 0, 2.5, 17.25, 21.50, 99, -0.5, 0, 0, 2.5, 0, 99, 10.25, 2.0, 13.75, -0.5, 9, -1.0, 3.5, 8, 7, 0.5, 99, 10.25] +map(gs, sum(#.xs));{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};[0, 10.26, -1.5, 14, 0, -0.5, 2.5, 2.5, 0, 0, 0, 8, 0.01, 0, 0.5, 2.51, 2.0, 99, 106, 1, 100, 0.02, -0.5, 11.26, 111.75, 1, 0, 0, 3.5, 0, 7, 4.25, 19.75, -6, 0, 4, 0.5, 2.5, 2.5, 99.5, 0, 10.5, 0, -0.5, -0.5, 0, 10.25, 10.26, 7.5, 0, 0, 0, 1.01, -0.49, 7.26, 17.25, 17.50, 107, -0.49, 0, 111.75, 0, 2.5, 99.5, 0.01, 2.5, 0, -1.99, 2.5, 0, 10.25, 0, 102.5, 2.5, 0, 0.01, 12.25, 2.5, 0.01, 4, 109.26, 98.5, 0.01, 1, 113, 0.01, 1, 0, 0, 1, 0, 20.00, 4.5, 99, 2.5, 0, 11.25, 0, 7, 0, 10.26, -6, -3, 2.01, 10.26, 0, 99, 198.01, 98.5, 98.51, 0, 103, 7.25, 198, 0, 101.51, 6.5, 0.01, 7.25, 0, 0, 0.5, 96, 7.5, 1, 7, 0, 109.25, 0.5, 11.25] +map(gs, sum(#.xs));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};[257.52, 1666.41, 139.52] +map(gs, sum(#.xs));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};[123.52, 518.06] +map(gs, sum(#.xs));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};[64, 130] +map(gs, count(#.xs, # > 0));{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};[0, 2, 1, 2, 0, 3, 0, 0, 1, 0, 3, 2, 0, 0, 0, 1, 1, 2, 1, 2, 2, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, 1, 2, 1, 0, 2, 0, 1, 2, 0, 2, 3, 0, 0, 1, 1, 0, 2, 2, 0, 0, 1, 1, 0, 1, 0, 2, 2, 0, 0] +map(gs, count(#.xs, # > 0));{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};[2, 2, 0, 0, 2, 1, 2, 0, 0, 1, 2, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 2, 0, 2, 0, 2, 0, 1, 0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 0, 1, 1, 0, 1, 2, 3, 1, 0, 0, 0, 1, 0, 1, 1, 1, 3, 1, 3, 0, 2, 2, 1, 1, 1, 1] +map(gs, count(#.xs, # > 0));{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};[0, 2, 0, 2, 0, 0, 1, 1, 0, 0, 0, 2, 1, 0, 1, 2, 1, 1, 2, 1, 2, 2, 0, 3, 3, 1, 0, 0, 2, 0, 1, 1, 3, 0, 0, 1, 1, 1, 1, 2, 0, 3, 0, 0, 0, 0, 1, 2, 2, 0, 0, 0, 2, 1, 2, 2, 2, 3, 2, 0, 3, 0, 1, 2, 1, 1, 0, 2, 1, 0, 1, 0, 3, 1, 0, 1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 0, 0, 1, 0, 2, 3, 1, 1, 0, 2, 0, 1, 0, 2, 0, 0, 2, 2, 0, 1, 3, 1, 2, 0, 2, 1, 2, 0, 3, 2, 1, 1, 0, 0, 2, 1, 3, 1, 1, 0, 2, 2, 2] +map(gs, count(#.xs, # > 0));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};[13, 78, 11] +map(gs, count(#.xs, # > 0));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};[10, 48] +map(gs, count(#.xs, # > 0));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};[64, 65] +count(gs, len(#.xs) == 0);{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};24 +count(gs, len(#.xs) == 0);{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};13 +count(gs, len(#.xs) == 0);{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};28 +count(gs, len(#.xs) == 0);{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};0 +count(gs, len(#.xs) == 0);{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};0 +count(gs, len(#.xs) == 0);{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};0 +map(filter(gs, some(#.xs, # == 99)), #.id);{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};[3, 22, 36, 51, 52, 61] +map(filter(gs, some(#.xs, # == 99)), #.id);{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};[0, 4, 10, 11, 17, 28, 31, 41, 46, 52, 63] +map(filter(gs, some(#.xs, # == 99)), #.id);{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};[17, 18, 20, 24, 39, 57, 60, 63, 72, 80, 81, 84, 93, 106, 107, 108, 109, 111, 113, 115, 122, 127] +map(filter(gs, some(#.xs, # == 99)), #.id);{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};[0, 1, 2] +map(filter(gs, some(#.xs, # == 99)), #.id);{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};[0, 1] +map(filter(gs, some(#.xs, # == 99)), #.id);{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};[] +sum(map(gs as g, sum(map(g.xs, # * g.id))));{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};27031.21 +sum(map(gs as g, sum(map(g.xs, # * g.id))));{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};37227.70 +sum(map(gs as g, sum(map(g.xs, # * g.id))));{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};218422.18 +sum(map(gs as g, sum(map(g.xs, # * g.id))));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};1945.45 +sum(map(gs as g, sum(map(g.xs, # * g.id))));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};518.06 +sum(map(gs as g, sum(map(g.xs, # * g.id))));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};130 +max(map(gs, len(#.xs)));{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};3 +max(map(gs, len(#.xs)));{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};3 +max(map(gs, len(#.xs)));{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};3 +max(map(gs, len(#.xs)));{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};105 +max(map(gs, len(#.xs)));{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};69 +max(map(gs, len(#.xs)));{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};65 +flatMap(gs, #.xs)[64];{gs: [{id: 0, xs: []}, {id: 1, xs: [-3, 7, 7]}, {id: 2, xs: [0.01]}, {id: 3, xs: [99, 7]}, {id: 4, xs: []}, {id: 5, xs: [0.01, 1, 1]}, {id: 6, xs: []}, {id: 7, xs: []}, {id: 8, xs: [1]}, {id: 9, xs: []}, {id: 10, xs: [7, 0.01, 7]}, {id: 11, xs: [10.25, 0, 10.25]}, {id: 12, xs: []}, {id: 13, xs: []}, {id: 14, xs: [-3]}, {id: 15, xs: [0.01, -0.5]}, {id: 16, xs: [2.5]}, {id: 17, xs: [-3, 1, 10.25]}, {id: 18, xs: [1]}, {id: 19, xs: [7, 0, 2.5]}, {id: 20, xs: [7, 7, -3]}, {id: 21, xs: [-0.5]}, {id: 22, xs: [0.01, 99]}, {id: 23, xs: []}, {id: 24, xs: []}, {id: 25, xs: []}, {id: 26, xs: [0.01, -3]}, {id: 27, xs: []}, {id: 28, xs: []}, {id: 29, xs: []}, {id: 30, xs: []}, {id: 31, xs: [-0.5, 1]}, {id: 32, xs: []}, {id: 33, xs: [1, 10.25, 0]}, {id: 34, xs: [-0.5]}, {id: 35, xs: [0.01, 0]}, {id: 36, xs: [99, 10.25]}, {id: 37, xs: [1]}, {id: 38, xs: [0, -3]}, {id: 39, xs: [7, 10.25]}, {id: 40, xs: []}, {id: 41, xs: [7, -3]}, {id: 42, xs: [7, 1]}, {id: 43, xs: []}, {id: 44, xs: [1, 2.5]}, {id: 45, xs: [7, 0.01, 2.5]}, {id: 46, xs: []}, {id: 47, xs: []}, {id: 48, xs: [1]}, {id: 49, xs: [7]}, {id: 50, xs: [-0.5]}, {id: 51, xs: [10.25, 99]}, {id: 52, xs: [99, 2.5]}, {id: 53, xs: []}, {id: 54, xs: []}, {id: 55, xs: [1, 0]}, {id: 56, xs: [-3, 2.5]}, {id: 57, xs: []}, {id: 58, xs: [-0.5, 2.5]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 2.5]}, {id: 61, xs: [99, 0.01]}, {id: 62, xs: [0]}, {id: 63, xs: []}]};99 +flatMap(gs, #.xs)[64];{gs: [{id: 0, xs: [99, 99]}, {id: 1, xs: [-3, 1, 1]}, {id: 2, xs: []}, {id: 3, xs: [-0.5]}, {id: 4, xs: [99, 10.25, -0.5]}, {id: 5, xs: [1]}, {id: 6, xs: [1, 0.01, -0.5]}, {id: 7, xs: []}, {id: 8, xs: []}, {id: 9, xs: [7]}, {id: 10, xs: [0.01, 99]}, {id: 11, xs: [99]}, {id: 12, xs: [7]}, {id: 13, xs: [10.25, -3]}, {id: 14, xs: []}, {id: 15, xs: [0.01]}, {id: 16, xs: [10.25, -3]}, {id: 17, xs: [-3, 99]}, {id: 18, xs: []}, {id: 19, xs: [-3, 2.5, -3]}, {id: 20, xs: [0.01]}, {id: 21, xs: [0]}, {id: 22, xs: [-3, 7, 7]}, {id: 23, xs: []}, {id: 24, xs: [7, 0.01]}, {id: 25, xs: [-0.5, 0]}, {id: 26, xs: [7, 1]}, {id: 27, xs: []}, {id: 28, xs: [-0.5, -3, 99]}, {id: 29, xs: []}, {id: 30, xs: [0.01, 0]}, {id: 31, xs: [99, 0]}, {id: 32, xs: [0.01]}, {id: 33, xs: [10.25, 0.01]}, {id: 34, xs: [0, 7, 2.5]}, {id: 35, xs: [0]}, {id: 36, xs: [1]}, {id: 37, xs: [0, 2.5, 1]}, {id: 38, xs: []}, {id: 39, xs: []}, {id: 40, xs: [0, 1]}, {id: 41, xs: [99]}, {id: 42, xs: []}, {id: 43, xs: [2.5, 0]}, {id: 44, xs: [10.25, 7]}, {id: 45, xs: [10.25, 10.25, 1]}, {id: 46, xs: [99]}, {id: 47, xs: [-0.5]}, {id: 48, xs: []}, {id: 49, xs: [0, 0]}, {id: 50, xs: [2.5]}, {id: 51, xs: []}, {id: 52, xs: [99]}, {id: 53, xs: [10.25]}, {id: 54, xs: [2.5, -0.5]}, {id: 55, xs: [2.5, 1, 10.25]}, {id: 56, xs: [2.5, -3]}, {id: 57, xs: [7, 1, 1]}, {id: 58, xs: [-0.5, -0.5]}, {id: 59, xs: [1, 0, 2.5]}, {id: 60, xs: [7, 1, 0]}, {id: 61, xs: [7]}, {id: 62, xs: [1, -0.5]}, {id: 63, xs: [99]}, {id: 64, xs: [10.25]}]};10.25 +flatMap(gs, #.xs)[64];{gs: [{id: 0, xs: []}, {id: 1, xs: [0.01, 10.25]}, {id: 2, xs: [-0.5, -0.5, -0.5]}, {id: 3, xs: [7, 7, 0]}, {id: 4, xs: []}, {id: 5, xs: [-0.5]}, {id: 6, xs: [2.5]}, {id: 7, xs: [2.5]}, {id: 8, xs: []}, {id: 9, xs: []}, {id: 10, xs: [0]}, {id: 11, xs: [1, 7]}, {id: 12, xs: [0.01]}, {id: 13, xs: []}, {id: 14, xs: [0, 1, -0.5]}, {id: 15, xs: [0, 2.5, 0.01]}, {id: 16, xs: [2.5, -0.5]}, {id: 17, xs: [99]}, {id: 18, xs: [99, 7]}, {id: 19, xs: [-3, 7, -3]}, {id: 20, xs: [99, 1]}, {id: 21, xs: [0.01, 0, 0.01]}, {id: 22, xs: [-0.5, 0, 0]}, {id: 23, xs: [10.25, 0.01, 1]}, {id: 24, xs: [99, 2.5, 10.25]}, {id: 25, xs: [1]}, {id: 26, xs: [0]}, {id: 27, xs: []}, {id: 28, xs: [2.5, 1]}, {id: 29, xs: [0]}, {id: 30, xs: [7]}, {id: 31, xs: [10.25, -3, -3]}, {id: 32, xs: [10.25, 2.5, 7]}, {id: 33, xs: [-3, -3]}, {id: 34, xs: []}, {id: 35, xs: [7, -3]}, {id: 36, xs: [1, -0.5]}, {id: 37, xs: [0, 2.5]}, {id: 38, xs: [2.5, 0]}, {id: 39, xs: [99, 1, -0.5]}, {id: 40, xs: []}, {id: 41, xs: [2.5, 7, 1]}, {id: 42, xs: [0]}, {id: 43, xs: [-0.5]}, {id: 44, xs: [-0.5]}, {id: 45, xs: []}, {id: 46, xs: [10.25]}, {id: 47, xs: [0.01, 10.25]}, {id: 48, xs: [1, -0.5, 7]}, {id: 49, xs: []}, {id: 50, xs: []}, {id: 51, xs: []}, {id: 52, xs: [1, 0.01]}, {id: 53, xs: [-0.5, 0.01]}, {id: 54, xs: [0.01, 10.25, -3]}, {id: 55, xs: [10.25, 7]}, {id: 56, xs: [-3, 10.25, 10.25]}, {id: 57, xs: [7, 1, 99]}, {id: 58, xs: [0.01, 2.5, -3]}, {id: 59, xs: []}, {id: 60, xs: [2.5, 10.25, 99]}, {id: 61, xs: []}, {id: 62, xs: [2.5]}, {id: 63, xs: [99, -0.5, 1]}, {id: 64, xs: [0.01]}, {id: 65, xs: [2.5, 0, 0]}, {id: 66, xs: []}, {id: 67, xs: [1, 0.01, -3]}, {id: 68, xs: [2.5, 0, 0]}, {id: 69, xs: [0]}, {id: 70, xs: [10.25, 0]}, {id: 71, xs: []}, {id: 72, xs: [2.5, 99, 1]}, {id: 73, xs: [2.5]}, {id: 74, xs: []}, {id: 75, xs: [0.01]}, {id: 76, xs: [1, 10.25, 1]}, {id: 77, xs: [2.5]}, {id: 78, xs: [0.01]}, {id: 79, xs: [7, 0, -3]}, {id: 80, xs: [99, 10.25, 0.01]}, {id: 81, xs: [99, -0.5]}, {id: 82, xs: [0.01]}, {id: 83, xs: [1]}, {id: 84, xs: [99, 7, 7]}, {id: 85, xs: [0, 0.01, 0]}, {id: 86, xs: [1]}, {id: 87, xs: []}, {id: 88, xs: []}, {id: 89, xs: [1]}, {id: 90, xs: [0]}, {id: 91, xs: [10.25, -0.5, 10.25]}, {id: 92, xs: [1, 2.5, 1]}, {id: 93, xs: [99]}, {id: 94, xs: [2.5]}, {id: 95, xs: []}, {id: 96, xs: [10.25, 1]}, {id: 97, xs: []}, {id: 98, xs: [7]}, {id: 99, xs: []}, {id: 100, xs: [10.25, 0.01]}, {id: 101, xs: [-3, -3]}, {id: 102, xs: [-3]}, {id: 103, xs: [-0.5, 0.01, 2.5]}, {id: 104, xs: [0.01, 10.25]}, {id: 105, xs: []}, {id: 106, xs: [99]}, {id: 107, xs: [99, 99, 0.01]}, {id: 108, xs: [0, 99, -0.5]}, {id: 109, xs: [-0.5, 0.01, 99]}, {id: 110, xs: []}, {id: 111, xs: [-3, 99, 7]}, {id: 112, xs: [0, -3, 10.25]}, {id: 113, xs: [99, 99]}, {id: 114, xs: []}, {id: 115, xs: [99, 2.5, 0.01]}, {id: 116, xs: [7, 2.5, -3]}, {id: 117, xs: [0.01]}, {id: 118, xs: [-3, 10.25]}, {id: 119, xs: []}, {id: 120, xs: []}, {id: 121, xs: [1, 2.5, -3]}, {id: 122, xs: [99, -3]}, {id: 123, xs: [2.5, 2.5, 2.5]}, {id: 124, xs: [1]}, {id: 125, xs: [0, 7]}, {id: 126, xs: []}, {id: 127, xs: [10.25, 99]}, {id: 128, xs: [1, -3, 2.5]}, {id: 129, xs: [1, 10.25]}]};0 +flatMap(gs, #.xs)[64];{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};-0.5 +flatMap(gs, #.xs)[64];{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};1 +flatMap(gs, #.xs)[64];{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};2 +map(gs, #.xs[64] ?? null);{gs: [{id: 0, xs: [99, 0, 10.25, -3, -0.5, 10.25, 7, 0, 7, 7, 0, -0.5, 0.01, 99, -3, 10.25, -3, 1, 0, 10.25, -0.5, 0.01, 7]}, {id: 1, xs: [1, 99, 1, -3, 7, 2.5, 0, -0.5, 1, 0.01, 2.5, 99, -3, 0, 0.01, 10.25, 0.01, 1, 0, 10.25, 99, 2.5, 2.5, 1, 0.01, 10.25, 1, 1, 99, 99, 7, 10.25, 10.25, 99, 99, -0.5, 1, 10.25, 0, 10.25, 0.01, -0.5, 10.25, 99, 1, 7, 1, 2.5, 1, 0.01, 7, 7, -0.5, -3, 99, 99, 10.25, 7, -3, 2.5, 7, -3, 0, -0.5, 7, 1, -3, 0, -0.5, 1, 2.5, 0.01, 0.01, 0.01, -0.5, -0.5, 0, 0.01, -3, 1, 99, 99, 0.01, 2.5, 1, 1, 0.01, 1, 0.01, 0.01, 0, 0.01, 99, 10.25, -0.5, 99, 0.01, 99, -0.5, 0, -3, 1, 2.5, 1, 10.25]}, {id: 2, xs: [7, 7, 0.01, 7, -0.5, 1, -0.5, 99, 2.5, 7, -0.5, 0, 0.01, 7, -0.5, -3, 7, 0, 0]}]};[null, 7, null] +map(gs, #.xs[64] ?? null);{gs: [{id: 0, xs: [0, -0.5, 0.01, 10.25, -3, 1, 0.01, 99, 7, -3, 7, 2.5, 2.5, -3, 10.25, -0.5, -3, -3]}, {id: 1, xs: [7, -0.5, 0, 0, 0, 10.25, 0, 2.5, 2.5, 7, 10.25, -3, 0.01, -3, -3, 10.25, 10.25, 0.01, 1, 99, 2.5, -0.5, 1, 7, 10.25, 7, 10.25, 1, 0, 10.25, 0.01, 1, -0.5, 0, 99, -0.5, 10.25, 0.01, 10.25, 7, 99, -0.5, -3, 0, 10.25, 2.5, 1, 7, 7, 0, -0.5, 1, -3, 2.5, 2.5, 1, 0.01, -3, 0.01, 10.25, -3, 10.25, 7, 7, 2.5, 7, 10.25, 7, 10.25]}]};[null, 2.5] +map(gs, #.xs[64] ?? null);{gs: [{id: 0, xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, {id: 1, xs: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]}]};[null, 2] +# long generated lists: closure sources from intervals +sum(map([1..n], #));{n: 63};2016 +sum(map([1..n], #));{n: 64};2080 +sum(map([1..n], #));{n: 65};2145 +sum(map([1..n], #));{n: 128};8256 +sum(map([1..n], #));{n: 200};20100 +count([1..n], # % 7 == 0);{n: 63};9 +count([1..n], # % 7 == 0);{n: 64};9 +count([1..n], # % 7 == 0);{n: 65};9 +count([1..n], # % 7 == 0);{n: 128};18 +count([1..n], # % 7 == 0);{n: 200};28 +len(filter([0..n), # % 2 == 0));{n: 63};32 +len(filter([0..n), # % 2 == 0));{n: 64};32 +len(filter([0..n), # % 2 == 0));{n: 65};33 +len(filter([0..n), # % 2 == 0));{n: 129};65 +map([0..n), # * #)[n - 1];{n: 64};3969 +map([0..n), # * #)[n - 1];{n: 65};4096 +map([0..n), # * #)[n - 1];{n: 128};16129 +map([0..n), # * #)[n - 1];{n: 129};16384 +len(flatMap([1..n], [#, -#]));{n: 32};64 +len(flatMap([1..n], [#, -#]));{n: 33};66 +len(flatMap([1..n], [#, -#]));{n: 64};128 +len(flatMap([1..n], [#, -#]));{n: 100};200 +sum(flatMap([1..n], [#, -#]));{n: 32};0 +sum(flatMap([1..n], [#, -#]));{n: 33};0 +sum(flatMap([1..n], [#, -#]));{n: 64};0 +sum(flatMap([1..n], [#, -#]));{n: 100};0 +len(flatMap([1..a], map([1..b], [#])));{a: 8, b: 8};64 +len(flatMap([1..a], map([1..b], [#])));{a: 9, b: 8};72 +len(flatMap([1..a], map([1..b], [#])));{a: 13, b: 10};130 +len(flatMap([1..a], map([1..b], [#])));{a: 1, b: 130};130 +sum(map([1..a] as i, sum(map([1..b], # * i))));{a: 8, b: 8};1296 +sum(map([1..a] as i, sum(map([1..b], # * i))));{a: 9, b: 8};1620 +sum(map([1..a] as i, sum(map([1..b], # * i))));{a: 13, b: 10};5005 +sum(map([1..a] as i, sum(map([1..b], # * i))));{a: 1, b: 130};8515 +map([1..n], # % 64 == 0)[63];{n: 64};true +map([1..n], # % 64 == 0)[63];{n: 65};true +map([1..n], # % 64 == 0)[63];{n: 200};true +filter([1..n], # % 64 == 0);{n: 63};[] +filter([1..n], # % 64 == 0);{n: 64};[64] +filter([1..n], # % 64 == 0);{n: 128};[64, 128] +filter([1..n], # % 64 == 0);{n: 200};[64, 128, 192] +# long string lists +count(ws, # == 'alpha');{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};3 +count(ws, # == 'alpha');{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};7 +count(ws, # == 'alpha');{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};15 +len(filter(ws, len(#) > 4));{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};17 +len(filter(ws, len(#) > 4));{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};23 +len(filter(ws, len(#) > 4));{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};42 +sum(map(ws, len(#)));{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};190 +sum(map(ws, len(#)));{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};224 +sum(map(ws, len(#)));{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};438 +keys(merge(map(ws, {[#]: true})));{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};['', 'delta', 'b', 'beta', 'eta', 'Alpha', 'zeta', 'eps', 'gamma', 'alpha'];bug: merging more than 32 objects loses key insertion order +keys(merge(map(ws, {[#]: true})));{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};['delta', 'beta', '', 'eta', 'eps', 'gamma', 'Alpha', 'alpha', 'zeta', 'b'];bug: merging more than 32 objects loses key insertion order +keys(merge(map(ws, {[#]: true})));{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};['Alpha', 'beta', 'alpha', 'gamma', '', 'zeta', 'b', 'eta', 'delta', 'eps'];bug: merging more than 32 objects loses key insertion order +len(keys(merge(map(ws, {[#]: true}))));{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};10 +len(keys(merge(map(ws, {[#]: true}))));{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};10 +len(keys(merge(map(ws, {[#]: true}))));{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};10 +map(ws, upper(#))[64];{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};null +map(ws, upper(#))[64];{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};'B' +map(ws, upper(#))[64];{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};'ALPHA' +'gamma' in ws;{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};true +'gamma' in ws;{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};true +'gamma' in ws;{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};true +map(ws, #[0] ?? '')[64];{ws: ['', 'delta', 'b', 'beta', 'eta', 'eta', 'delta', 'Alpha', 'delta', 'delta', 'eta', 'delta', '', 'delta', 'zeta', 'beta', 'delta', '', 'eps', 'b', 'zeta', 'beta', '', 'beta', 'delta', '', '', 'gamma', 'eps', 'b', '', 'b', 'b', 'b', 'alpha', '', 'beta', 'zeta', '', '', '', 'beta', 'eps', 'zeta', 'b', 'eta', 'eps', 'eta', 'Alpha', 'beta', 'b', 'alpha', 'zeta', 'eps', 'alpha', 'eps', 'eta', 'Alpha', 'beta', 'delta', 'eps', 'Alpha', 'eta', 'eps']};null +map(ws, #[0] ?? '')[64];{ws: ['delta', 'beta', '', 'eta', 'eta', 'eps', 'gamma', 'eps', 'Alpha', 'gamma', 'alpha', 'beta', '', 'eps', 'eta', 'zeta', '', 'eta', 'alpha', 'gamma', 'Alpha', 'beta', 'alpha', 'eps', '', 'Alpha', 'delta', 'zeta', 'gamma', 'alpha', 'zeta', 'beta', 'eta', 'zeta', 'gamma', 'gamma', 'beta', 'delta', 'b', 'eta', 'alpha', 'alpha', 'b', 'b', 'b', 'delta', 'Alpha', 'eps', 'zeta', 'eta', 'eta', 'beta', 'beta', 'gamma', 'eta', 'beta', 'beta', '', 'eta', 'delta', 'b', 'alpha', 'b', 'b', 'b']};'b' +map(ws, #[0] ?? '')[64];{ws: ['Alpha', 'beta', 'alpha', 'Alpha', 'gamma', '', 'zeta', '', 'b', '', 'eta', 'zeta', 'beta', 'Alpha', 'delta', 'Alpha', 'beta', 'gamma', 'alpha', 'gamma', 'alpha', 'beta', 'delta', 'eta', 'beta', 'delta', 'eps', '', 'eps', 'eta', '', 'beta', 'eps', 'eps', 'delta', 'beta', 'beta', 'b', 'eta', 'beta', 'zeta', 'zeta', 'Alpha', 'alpha', 'gamma', 'delta', 'eps', 'alpha', 'alpha', 'b', 'eps', 'beta', 'b', 'eps', 'delta', '', 'b', 'eps', 'eps', 'beta', 'eta', 'alpha', '', 'b', 'Alpha', 'eps', 'alpha', 'delta', 'gamma', 'alpha', 'beta', 'zeta', 'Alpha', 'zeta', 'zeta', 'eps', 'b', '', 'zeta', 'beta', 'beta', 'eps', '', 'b', 'beta', 'alpha', 'eps', 'eps', 'eta', 'beta', '', 'eps', 'beta', 'zeta', 'b', 'zeta', '', 'b', 'zeta', 'Alpha', 'alpha', 'zeta', 'delta', 'zeta', 'b', '', 'b', 'beta', 'Alpha', 'b', 'eps', 'b', 'eps', 'eta', 'eps', 'delta', 'gamma', 'alpha', 'delta', 'alpha', 'beta', 'alpha', 'eta', 'zeta', 'delta', 'eta', 'alpha', 'b', 'Alpha']};'A' +# wide objects: more than 32 keys keep insertion order +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};['k0', 'k7', 'k14', 'k21', 'k28', 'k4', 'k11', 'k18', 'k25', 'k1', 'k8', 'k15', 'k22', 'k29', 'k5', 'k12', 'k19', 'k26', 'k2', 'k9', 'k16', 'k23', 'k30', 'k6', 'k13', 'k20', 'k27', 'k3', 'k10', 'k17', 'k24'] +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};['k0', 'k7', 'k14', 'k21', 'k28', 'k3', 'k10', 'k17', 'k24', 'k31', 'k6', 'k13', 'k20', 'k27', 'k2', 'k9', 'k16', 'k23', 'k30', 'k5', 'k12', 'k19', 'k26', 'k1', 'k8', 'k15', 'k22', 'k29', 'k4', 'k11', 'k18', 'k25'] +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};['k0', 'k7', 'k14', 'k21', 'k28', 'k2', 'k9', 'k16', 'k23', 'k30', 'k4', 'k11', 'k18', 'k25', 'k32', 'k6', 'k13', 'k20', 'k27', 'k1', 'k8', 'k15', 'k22', 'k29', 'k3', 'k10', 'k17', 'k24', 'k31', 'k5', 'k12', 'k19', 'k26'];bug: an object with more than 32 keys loses key insertion order +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k6', 'k13', 'k20', 'k27', 'k34', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k5', 'k12', 'k19', 'k26', 'k33'];bug: an object with more than 32 keys loses key insertion order +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57'];bug: an object with more than 32 keys loses key insertion order +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58'];bug: an object with more than 32 keys loses key insertion order +keys(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k70', 'k77', 'k84', 'k91', 'k98', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k68', 'k75', 'k82', 'k89', 'k96', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k66', 'k73', 'k80', 'k87', 'k94', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k71', 'k78', 'k85', 'k92', 'k99', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k69', 'k76', 'k83', 'k90', 'k97', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k67', 'k74', 'k81', 'k88', 'k95', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k65', 'k72', 'k79', 'k86', 'k93'];bug: an object with more than 32 keys loses key insertion order +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32];bug: an object with more than 32 keys loses key insertion order +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39];bug: an object with more than 32 keys loses key insertion order +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63];bug: an object with more than 32 keys loses key insertion order +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64];bug: an object with more than 32 keys loses key insertion order +values(o);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99];bug: an object with more than 32 keys loses key insertion order +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32];bug: an object with more than 32 keys loses key insertion order +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39];bug: an object with more than 32 keys loses key insertion order +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63];bug: an object with more than 32 keys loses key insertion order +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64];bug: an object with more than 32 keys loses key insertion order +map(keys(o), o[#]);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99];bug: an object with more than 32 keys loses key insertion order +values(o)[len(o) - 1];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};!error +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};31 +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};32 +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};33 +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};40 +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};64 +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};65 +len(keys(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};100 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};465 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};496 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};528 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};780 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};2016 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};2080 +sum(values(o));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};4950 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};0 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};0 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};1 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};8 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};32 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};33 +count(keys(o), o[#] >= 32);{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};68 +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};'none' +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};'none' +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};14 +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};16 +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};32 +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};51 +o.k32 ?? 'none';{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};76 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};22 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};9 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};14 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};17 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};9 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};37 +o['k' + string(len(keys(o)) - 1)];{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};57 +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};['k0', 'k7', 'k14', 'k21', 'k28', 'k4', 'k11', 'k18', 'k25', 'k1', 'k8', 'k15', 'k22', 'k29', 'k5', 'k12', 'k19', 'k26', 'k2', 'k9', 'k16', 'k23', 'k30', 'k6', 'k13', 'k20', 'k27', 'k3', 'k10', 'k17', 'k24'] +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};['k0', 'k7', 'k14', 'k21', 'k28', 'k3', 'k10', 'k17', 'k24', 'k31', 'k6', 'k13', 'k20', 'k27', 'k2', 'k9', 'k16', 'k23', 'k30', 'k5', 'k12', 'k19', 'k26', 'k1', 'k8', 'k15', 'k22', 'k29', 'k4', 'k11', 'k18', 'k25'] +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};['k0', 'k7', 'k14', 'k21', 'k28', 'k2', 'k9', 'k16', 'k23', 'k30', 'k4', 'k11', 'k18', 'k25', 'k32', 'k6', 'k13', 'k20', 'k27', 'k1', 'k8', 'k15', 'k22', 'k29', 'k3', 'k10', 'k17', 'k24', 'k31', 'k5', 'k12', 'k19', 'k26'];bug: an object with more than 32 keys loses key insertion order +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k6', 'k13', 'k20', 'k27', 'k34', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k5', 'k12', 'k19', 'k26', 'k33'];bug: an object with more than 32 keys loses key insertion order +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57'];bug: an object with more than 32 keys loses key insertion order +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58'];bug: an object with more than 32 keys loses key insertion order +keys(merge([o]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k70', 'k77', 'k84', 'k91', 'k98', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k68', 'k75', 'k82', 'k89', 'k96', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k66', 'k73', 'k80', 'k87', 'k94', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k71', 'k78', 'k85', 'k92', 'k99', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k69', 'k76', 'k83', 'k90', 'k97', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k67', 'k74', 'k81', 'k88', 'k95', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k65', 'k72', 'k79', 'k86', 'k93'];bug: an object with more than 32 keys loses key insertion order +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};['k0', 'k7', 'k14', 'k21', 'k28', 'k4', 'k11', 'k18', 'k25', 'k1', 'k8', 'k15', 'k22', 'k29', 'k5', 'k12', 'k19', 'k26', 'k2', 'k9', 'k16', 'k23', 'k30', 'k6', 'k13', 'k20', 'k27', 'k3', 'k10', 'k17', 'k24'] +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};['k0', 'k7', 'k14', 'k21', 'k28', 'k3', 'k10', 'k17', 'k24', 'k31', 'k6', 'k13', 'k20', 'k27', 'k2', 'k9', 'k16', 'k23', 'k30', 'k5', 'k12', 'k19', 'k26', 'k1', 'k8', 'k15', 'k22', 'k29', 'k4', 'k11', 'k18', 'k25'] +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};['k0', 'k7', 'k14', 'k21', 'k28', 'k2', 'k9', 'k16', 'k23', 'k30', 'k4', 'k11', 'k18', 'k25', 'k32', 'k6', 'k13', 'k20', 'k27', 'k1', 'k8', 'k15', 'k22', 'k29', 'k3', 'k10', 'k17', 'k24', 'k31', 'k5', 'k12', 'k19', 'k26'];bug: an object with more than 32 keys loses key insertion order +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k6', 'k13', 'k20', 'k27', 'k34', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k5', 'k12', 'k19', 'k26', 'k33'];bug: an object with more than 32 keys loses key insertion order +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57'];bug: an object with more than 32 keys loses key insertion order +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58'];bug: an object with more than 32 keys loses key insertion order +keys(mergeDeep([o, {}]));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k70', 'k77', 'k84', 'k91', 'k98', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k68', 'k75', 'k82', 'k89', 'k96', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k66', 'k73', 'k80', 'k87', 'k94', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k71', 'k78', 'k85', 'k92', 'k99', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k69', 'k76', 'k83', 'k90', 'k97', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k67', 'k74', 'k81', 'k88', 'k95', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k65', 'k72', 'k79', 'k86', 'k93'];bug: an object with more than 32 keys loses key insertion order +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};28 +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};38 +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};58 +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};70 +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};38 +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};20 +merge(map(keys(o), {[#]: o[#] * 2})).k5;{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};30 +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k4: 5, k11: 6, k18: 7, k25: 8, k1: 9, k8: 10, k15: 11, k22: 12, k29: 13, k5: 14, k12: 15, k19: 16, k26: 17, k2: 18, k9: 19, k16: 20, k23: 21, k30: 22, k6: 23, k13: 24, k20: 25, k27: 26, k3: 27, k10: 28, k17: 29, k24: 30}};['k0', 'k7', 'k14', 'k21', 'k28', 'k4', 'k11', 'k18', 'k25', 'k1', 'k8', 'k15', 'k22', 'k29', 'k5', 'k12', 'k19', 'k26', 'k2', 'k9', 'k16', 'k23', 'k30', 'k6', 'k13', 'k20', 'k27', 'k3', 'k10', 'k17', 'k24'] +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k3: 5, k10: 6, k17: 7, k24: 8, k31: 9, k6: 10, k13: 11, k20: 12, k27: 13, k2: 14, k9: 15, k16: 16, k23: 17, k30: 18, k5: 19, k12: 20, k19: 21, k26: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k4: 28, k11: 29, k18: 30, k25: 31}};['k0', 'k7', 'k14', 'k21', 'k28', 'k3', 'k10', 'k17', 'k24', 'k31', 'k6', 'k13', 'k20', 'k27', 'k2', 'k9', 'k16', 'k23', 'k30', 'k5', 'k12', 'k19', 'k26', 'k1', 'k8', 'k15', 'k22', 'k29', 'k4', 'k11', 'k18', 'k25'] +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k2: 5, k9: 6, k16: 7, k23: 8, k30: 9, k4: 10, k11: 11, k18: 12, k25: 13, k32: 14, k6: 15, k13: 16, k20: 17, k27: 18, k1: 19, k8: 20, k15: 21, k22: 22, k29: 23, k3: 24, k10: 25, k17: 26, k24: 27, k31: 28, k5: 29, k12: 30, k19: 31, k26: 32}};['k0', 'k7', 'k14', 'k21', 'k28', 'k2', 'k9', 'k16', 'k23', 'k30', 'k4', 'k11', 'k18', 'k25', 'k32', 'k6', 'k13', 'k20', 'k27', 'k1', 'k8', 'k15', 'k22', 'k29', 'k3', 'k10', 'k17', 'k24', 'k31', 'k5', 'k12', 'k19', 'k26'];bug: an object with more than 32 keys loses key insertion order +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k2: 6, k9: 7, k16: 8, k23: 9, k30: 10, k37: 11, k4: 12, k11: 13, k18: 14, k25: 15, k32: 16, k39: 17, k6: 18, k13: 19, k20: 20, k27: 21, k34: 22, k1: 23, k8: 24, k15: 25, k22: 26, k29: 27, k36: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k5: 35, k12: 36, k19: 37, k26: 38, k33: 39}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k6', 'k13', 'k20', 'k27', 'k34', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k5', 'k12', 'k19', 'k26', 'k33'];bug: an object with more than 32 keys loses key insertion order +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k6: 10, k13: 11, k20: 12, k27: 13, k34: 14, k41: 15, k48: 16, k55: 17, k62: 18, k5: 19, k12: 20, k19: 21, k26: 22, k33: 23, k40: 24, k47: 25, k54: 26, k61: 27, k4: 28, k11: 29, k18: 30, k25: 31, k32: 32, k39: 33, k46: 34, k53: 35, k60: 36, k3: 37, k10: 38, k17: 39, k24: 40, k31: 41, k38: 42, k45: 43, k52: 44, k59: 45, k2: 46, k9: 47, k16: 48, k23: 49, k30: 50, k37: 51, k44: 52, k51: 53, k58: 54, k1: 55, k8: 56, k15: 57, k22: 58, k29: 59, k36: 60, k43: 61, k50: 62, k57: 63}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57'];bug: an object with more than 32 keys loses key insertion order +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k5: 10, k12: 11, k19: 12, k26: 13, k33: 14, k40: 15, k47: 16, k54: 17, k61: 18, k3: 19, k10: 20, k17: 21, k24: 22, k31: 23, k38: 24, k45: 25, k52: 26, k59: 27, k1: 28, k8: 29, k15: 30, k22: 31, k29: 32, k36: 33, k43: 34, k50: 35, k57: 36, k64: 37, k6: 38, k13: 39, k20: 40, k27: 41, k34: 42, k41: 43, k48: 44, k55: 45, k62: 46, k4: 47, k11: 48, k18: 49, k25: 50, k32: 51, k39: 52, k46: 53, k53: 54, k60: 55, k2: 56, k9: 57, k16: 58, k23: 59, k30: 60, k37: 61, k44: 62, k51: 63, k58: 64}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58'];bug: an object with more than 32 keys loses key insertion order +keys(merge(map(keys(o), {[#]: 1})));{o: {k0: 0, k7: 1, k14: 2, k21: 3, k28: 4, k35: 5, k42: 6, k49: 7, k56: 8, k63: 9, k70: 10, k77: 11, k84: 12, k91: 13, k98: 14, k5: 15, k12: 16, k19: 17, k26: 18, k33: 19, k40: 20, k47: 21, k54: 22, k61: 23, k68: 24, k75: 25, k82: 26, k89: 27, k96: 28, k3: 29, k10: 30, k17: 31, k24: 32, k31: 33, k38: 34, k45: 35, k52: 36, k59: 37, k66: 38, k73: 39, k80: 40, k87: 41, k94: 42, k1: 43, k8: 44, k15: 45, k22: 46, k29: 47, k36: 48, k43: 49, k50: 50, k57: 51, k64: 52, k71: 53, k78: 54, k85: 55, k92: 56, k99: 57, k6: 58, k13: 59, k20: 60, k27: 61, k34: 62, k41: 63, k48: 64, k55: 65, k62: 66, k69: 67, k76: 68, k83: 69, k90: 70, k97: 71, k4: 72, k11: 73, k18: 74, k25: 75, k32: 76, k39: 77, k46: 78, k53: 79, k60: 80, k67: 81, k74: 82, k81: 83, k88: 84, k95: 85, k2: 86, k9: 87, k16: 88, k23: 89, k30: 90, k37: 91, k44: 92, k51: 93, k58: 94, k65: 95, k72: 96, k79: 97, k86: 98, k93: 99}};['k0', 'k7', 'k14', 'k21', 'k28', 'k35', 'k42', 'k49', 'k56', 'k63', 'k70', 'k77', 'k84', 'k91', 'k98', 'k5', 'k12', 'k19', 'k26', 'k33', 'k40', 'k47', 'k54', 'k61', 'k68', 'k75', 'k82', 'k89', 'k96', 'k3', 'k10', 'k17', 'k24', 'k31', 'k38', 'k45', 'k52', 'k59', 'k66', 'k73', 'k80', 'k87', 'k94', 'k1', 'k8', 'k15', 'k22', 'k29', 'k36', 'k43', 'k50', 'k57', 'k64', 'k71', 'k78', 'k85', 'k92', 'k99', 'k6', 'k13', 'k20', 'k27', 'k34', 'k41', 'k48', 'k55', 'k62', 'k69', 'k76', 'k83', 'k90', 'k97', 'k4', 'k11', 'k18', 'k25', 'k32', 'k39', 'k46', 'k53', 'k60', 'k67', 'k74', 'k81', 'k88', 'k95', 'k2', 'k9', 'k16', 'k23', 'k30', 'k37', 'k44', 'k51', 'k58', 'k65', 'k72', 'k79', 'k86', 'k93'];bug: an object with more than 32 keys loses key insertion order +keys(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9'] +keys(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9'];bug: merging more than 32 objects loses key insertion order +keys(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k0: 12}, {k1: 13}, {k2: 14}, {k3: 15}, {k4: 16}, {k5: 17}, {k6: 18}, {k7: 19}, {k8: 20}, {k9: 21}, {k10: 22}, {k11: 23}, {k0: 24}, {k1: 25}, {k2: 26}, {k3: 27}, {k4: 28}, {k5: 29}, {k6: 30}, {k7: 31}, {k8: 32}, {k9: 33}, {k10: 34}, {k11: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9', 'k10', 'k11'];bug: merging more than 32 objects loses key insertion order +keys(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k12: 12}, {k13: 13}, {k14: 14}, {k15: 15}, {k16: 16}, {k17: 17}, {k18: 18}, {k19: 19}, {k20: 20}, {k21: 21}, {k22: 22}, {k23: 23}, {k24: 24}, {k25: 25}, {k26: 26}, {k27: 27}, {k28: 28}, {k29: 29}, {k30: 30}, {k31: 31}, {k32: 32}, {k33: 33}, {k34: 34}, {k35: 35}, {k36: 36}, {k37: 37}, {k38: 38}, {k39: 39}, {k40: 40}, {k41: 41}, {k42: 42}, {k43: 43}, {k44: 44}, {k45: 45}, {k46: 46}, {k47: 47}, {k48: 48}, {k49: 49}, {k50: 50}, {k51: 51}, {k52: 52}, {k53: 53}, {k54: 54}, {k55: 55}, {k56: 56}, {k57: 57}, {k58: 58}, {k59: 59}, {k60: 60}, {k61: 61}, {k62: 62}, {k63: 63}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9', 'k10', 'k11', 'k12', 'k13', 'k14', 'k15', 'k16', 'k17', 'k18', 'k19', 'k20', 'k21', 'k22', 'k23', 'k24', 'k25', 'k26', 'k27', 'k28', 'k29', 'k30', 'k31', 'k32', 'k33', 'k34', 'k35', 'k36', 'k37', 'k38', 'k39', 'k40', 'k41', 'k42', 'k43', 'k44', 'k45', 'k46', 'k47', 'k48', 'k49', 'k50', 'k51', 'k52', 'k53', 'k54', 'k55', 'k56', 'k57', 'k58', 'k59', 'k60', 'k61', 'k62', 'k63'];bug: merging more than 32 objects loses key insertion order +keys(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k0: 9}, {k1: 10}, {k2: 11}, {k3: 12}, {k4: 13}, {k5: 14}, {k6: 15}, {k7: 16}, {k8: 17}, {k0: 18}, {k1: 19}, {k2: 20}, {k3: 21}, {k4: 22}, {k5: 23}, {k6: 24}, {k7: 25}, {k8: 26}, {k0: 27}, {k1: 28}, {k2: 29}, {k3: 30}, {k4: 31}, {k5: 32}, {k6: 33}, {k7: 34}, {k8: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}, {k4: 40}, {k5: 41}, {k6: 42}, {k7: 43}, {k8: 44}, {k0: 45}, {k1: 46}, {k2: 47}, {k3: 48}, {k4: 49}, {k5: 50}, {k6: 51}, {k7: 52}, {k8: 53}, {k0: 54}, {k1: 55}, {k2: 56}, {k3: 57}, {k4: 58}, {k5: 59}, {k6: 60}, {k7: 61}, {k8: 62}, {k0: 63}, {k1: 64}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8'];bug: merging more than 32 objects loses key insertion order +keys(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}, {k3: 33}, {k4: 34}, {k5: 35}, {k6: 36}, {k7: 37}, {k8: 38}, {k9: 39}, {k0: 40}, {k1: 41}, {k2: 42}, {k3: 43}, {k4: 44}, {k5: 45}, {k6: 46}, {k7: 47}, {k8: 48}, {k9: 49}, {k0: 50}, {k1: 51}, {k2: 52}, {k3: 53}, {k4: 54}, {k5: 55}, {k6: 56}, {k7: 57}, {k8: 58}, {k9: 59}, {k0: 60}, {k1: 61}, {k2: 62}, {k3: 63}, {k4: 64}, {k5: 65}, {k6: 66}, {k7: 67}, {k8: 68}, {k9: 69}, {k0: 70}, {k1: 71}, {k2: 72}, {k3: 73}, {k4: 74}, {k5: 75}, {k6: 76}, {k7: 77}, {k8: 78}, {k9: 79}, {k0: 80}, {k1: 81}, {k2: 82}, {k3: 83}, {k4: 84}, {k5: 85}, {k6: 86}, {k7: 87}, {k8: 88}, {k9: 89}, {k0: 90}, {k1: 91}, {k2: 92}, {k3: 93}, {k4: 94}, {k5: 95}, {k6: 96}, {k7: 97}, {k8: 98}, {k9: 99}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9'];bug: merging more than 32 objects loses key insertion order +values(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}]};[30, 31, 22, 23, 24, 25, 26, 27, 28, 29] +values(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}]};[30, 31, 32, 23, 24, 25, 26, 27, 28, 29];bug: merging more than 32 objects loses key insertion order +values(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k0: 12}, {k1: 13}, {k2: 14}, {k3: 15}, {k4: 16}, {k5: 17}, {k6: 18}, {k7: 19}, {k8: 20}, {k9: 21}, {k10: 22}, {k11: 23}, {k0: 24}, {k1: 25}, {k2: 26}, {k3: 27}, {k4: 28}, {k5: 29}, {k6: 30}, {k7: 31}, {k8: 32}, {k9: 33}, {k10: 34}, {k11: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}]};[36, 37, 38, 39, 28, 29, 30, 31, 32, 33, 34, 35];bug: merging more than 32 objects loses key insertion order +values(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k12: 12}, {k13: 13}, {k14: 14}, {k15: 15}, {k16: 16}, {k17: 17}, {k18: 18}, {k19: 19}, {k20: 20}, {k21: 21}, {k22: 22}, {k23: 23}, {k24: 24}, {k25: 25}, {k26: 26}, {k27: 27}, {k28: 28}, {k29: 29}, {k30: 30}, {k31: 31}, {k32: 32}, {k33: 33}, {k34: 34}, {k35: 35}, {k36: 36}, {k37: 37}, {k38: 38}, {k39: 39}, {k40: 40}, {k41: 41}, {k42: 42}, {k43: 43}, {k44: 44}, {k45: 45}, {k46: 46}, {k47: 47}, {k48: 48}, {k49: 49}, {k50: 50}, {k51: 51}, {k52: 52}, {k53: 53}, {k54: 54}, {k55: 55}, {k56: 56}, {k57: 57}, {k58: 58}, {k59: 59}, {k60: 60}, {k61: 61}, {k62: 62}, {k63: 63}]};[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63];bug: merging more than 32 objects loses key insertion order +values(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k0: 9}, {k1: 10}, {k2: 11}, {k3: 12}, {k4: 13}, {k5: 14}, {k6: 15}, {k7: 16}, {k8: 17}, {k0: 18}, {k1: 19}, {k2: 20}, {k3: 21}, {k4: 22}, {k5: 23}, {k6: 24}, {k7: 25}, {k8: 26}, {k0: 27}, {k1: 28}, {k2: 29}, {k3: 30}, {k4: 31}, {k5: 32}, {k6: 33}, {k7: 34}, {k8: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}, {k4: 40}, {k5: 41}, {k6: 42}, {k7: 43}, {k8: 44}, {k0: 45}, {k1: 46}, {k2: 47}, {k3: 48}, {k4: 49}, {k5: 50}, {k6: 51}, {k7: 52}, {k8: 53}, {k0: 54}, {k1: 55}, {k2: 56}, {k3: 57}, {k4: 58}, {k5: 59}, {k6: 60}, {k7: 61}, {k8: 62}, {k0: 63}, {k1: 64}]};[63, 64, 56, 57, 58, 59, 60, 61, 62];bug: merging more than 32 objects loses key insertion order +values(merge(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}, {k3: 33}, {k4: 34}, {k5: 35}, {k6: 36}, {k7: 37}, {k8: 38}, {k9: 39}, {k0: 40}, {k1: 41}, {k2: 42}, {k3: 43}, {k4: 44}, {k5: 45}, {k6: 46}, {k7: 47}, {k8: 48}, {k9: 49}, {k0: 50}, {k1: 51}, {k2: 52}, {k3: 53}, {k4: 54}, {k5: 55}, {k6: 56}, {k7: 57}, {k8: 58}, {k9: 59}, {k0: 60}, {k1: 61}, {k2: 62}, {k3: 63}, {k4: 64}, {k5: 65}, {k6: 66}, {k7: 67}, {k8: 68}, {k9: 69}, {k0: 70}, {k1: 71}, {k2: 72}, {k3: 73}, {k4: 74}, {k5: 75}, {k6: 76}, {k7: 77}, {k8: 78}, {k9: 79}, {k0: 80}, {k1: 81}, {k2: 82}, {k3: 83}, {k4: 84}, {k5: 85}, {k6: 86}, {k7: 87}, {k8: 88}, {k9: 89}, {k0: 90}, {k1: 91}, {k2: 92}, {k3: 93}, {k4: 94}, {k5: 95}, {k6: 96}, {k7: 97}, {k8: 98}, {k9: 99}]};[90, 91, 92, 93, 94, 95, 96, 97, 98, 99];bug: merging more than 32 objects loses key insertion order +keys(mergeDeep(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9'] +keys(mergeDeep(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9'] +keys(mergeDeep(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k0: 12}, {k1: 13}, {k2: 14}, {k3: 15}, {k4: 16}, {k5: 17}, {k6: 18}, {k7: 19}, {k8: 20}, {k9: 21}, {k10: 22}, {k11: 23}, {k0: 24}, {k1: 25}, {k2: 26}, {k3: 27}, {k4: 28}, {k5: 29}, {k6: 30}, {k7: 31}, {k8: 32}, {k9: 33}, {k10: 34}, {k11: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9', 'k10', 'k11'] +keys(mergeDeep(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k12: 12}, {k13: 13}, {k14: 14}, {k15: 15}, {k16: 16}, {k17: 17}, {k18: 18}, {k19: 19}, {k20: 20}, {k21: 21}, {k22: 22}, {k23: 23}, {k24: 24}, {k25: 25}, {k26: 26}, {k27: 27}, {k28: 28}, {k29: 29}, {k30: 30}, {k31: 31}, {k32: 32}, {k33: 33}, {k34: 34}, {k35: 35}, {k36: 36}, {k37: 37}, {k38: 38}, {k39: 39}, {k40: 40}, {k41: 41}, {k42: 42}, {k43: 43}, {k44: 44}, {k45: 45}, {k46: 46}, {k47: 47}, {k48: 48}, {k49: 49}, {k50: 50}, {k51: 51}, {k52: 52}, {k53: 53}, {k54: 54}, {k55: 55}, {k56: 56}, {k57: 57}, {k58: 58}, {k59: 59}, {k60: 60}, {k61: 61}, {k62: 62}, {k63: 63}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9', 'k10', 'k11', 'k12', 'k13', 'k14', 'k15', 'k16', 'k17', 'k18', 'k19', 'k20', 'k21', 'k22', 'k23', 'k24', 'k25', 'k26', 'k27', 'k28', 'k29', 'k30', 'k31', 'k32', 'k33', 'k34', 'k35', 'k36', 'k37', 'k38', 'k39', 'k40', 'k41', 'k42', 'k43', 'k44', 'k45', 'k46', 'k47', 'k48', 'k49', 'k50', 'k51', 'k52', 'k53', 'k54', 'k55', 'k56', 'k57', 'k58', 'k59', 'k60', 'k61', 'k62', 'k63'];bug: an object with more than 32 keys loses key insertion order +keys(mergeDeep(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k0: 9}, {k1: 10}, {k2: 11}, {k3: 12}, {k4: 13}, {k5: 14}, {k6: 15}, {k7: 16}, {k8: 17}, {k0: 18}, {k1: 19}, {k2: 20}, {k3: 21}, {k4: 22}, {k5: 23}, {k6: 24}, {k7: 25}, {k8: 26}, {k0: 27}, {k1: 28}, {k2: 29}, {k3: 30}, {k4: 31}, {k5: 32}, {k6: 33}, {k7: 34}, {k8: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}, {k4: 40}, {k5: 41}, {k6: 42}, {k7: 43}, {k8: 44}, {k0: 45}, {k1: 46}, {k2: 47}, {k3: 48}, {k4: 49}, {k5: 50}, {k6: 51}, {k7: 52}, {k8: 53}, {k0: 54}, {k1: 55}, {k2: 56}, {k3: 57}, {k4: 58}, {k5: 59}, {k6: 60}, {k7: 61}, {k8: 62}, {k0: 63}, {k1: 64}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8'] +keys(mergeDeep(xs));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}, {k3: 33}, {k4: 34}, {k5: 35}, {k6: 36}, {k7: 37}, {k8: 38}, {k9: 39}, {k0: 40}, {k1: 41}, {k2: 42}, {k3: 43}, {k4: 44}, {k5: 45}, {k6: 46}, {k7: 47}, {k8: 48}, {k9: 49}, {k0: 50}, {k1: 51}, {k2: 52}, {k3: 53}, {k4: 54}, {k5: 55}, {k6: 56}, {k7: 57}, {k8: 58}, {k9: 59}, {k0: 60}, {k1: 61}, {k2: 62}, {k3: 63}, {k4: 64}, {k5: 65}, {k6: 66}, {k7: 67}, {k8: 68}, {k9: 69}, {k0: 70}, {k1: 71}, {k2: 72}, {k3: 73}, {k4: 74}, {k5: 75}, {k6: 76}, {k7: 77}, {k8: 78}, {k9: 79}, {k0: 80}, {k1: 81}, {k2: 82}, {k3: 83}, {k4: 84}, {k5: 85}, {k6: 86}, {k7: 87}, {k8: 88}, {k9: 89}, {k0: 90}, {k1: 91}, {k2: 92}, {k3: 93}, {k4: 94}, {k5: 95}, {k6: 96}, {k7: 97}, {k8: 98}, {k9: 99}]};['k0', 'k1', 'k2', 'k3', 'k4', 'k5', 'k6', 'k7', 'k8', 'k9'] +merge(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}]};{k0: 30, k1: 31, k2: 22, k3: 23, k4: 24, k5: 25, k6: 26, k7: 27, k8: 28, k9: 29} +merge(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}]};{k0: 30, k1: 31, k2: 32, k3: 23, k4: 24, k5: 25, k6: 26, k7: 27, k8: 28, k9: 29} +merge(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k0: 12}, {k1: 13}, {k2: 14}, {k3: 15}, {k4: 16}, {k5: 17}, {k6: 18}, {k7: 19}, {k8: 20}, {k9: 21}, {k10: 22}, {k11: 23}, {k0: 24}, {k1: 25}, {k2: 26}, {k3: 27}, {k4: 28}, {k5: 29}, {k6: 30}, {k7: 31}, {k8: 32}, {k9: 33}, {k10: 34}, {k11: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}]};{k0: 36, k1: 37, k2: 38, k3: 39, k4: 28, k5: 29, k6: 30, k7: 31, k8: 32, k9: 33, k10: 34, k11: 35} +merge(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k12: 12}, {k13: 13}, {k14: 14}, {k15: 15}, {k16: 16}, {k17: 17}, {k18: 18}, {k19: 19}, {k20: 20}, {k21: 21}, {k22: 22}, {k23: 23}, {k24: 24}, {k25: 25}, {k26: 26}, {k27: 27}, {k28: 28}, {k29: 29}, {k30: 30}, {k31: 31}, {k32: 32}, {k33: 33}, {k34: 34}, {k35: 35}, {k36: 36}, {k37: 37}, {k38: 38}, {k39: 39}, {k40: 40}, {k41: 41}, {k42: 42}, {k43: 43}, {k44: 44}, {k45: 45}, {k46: 46}, {k47: 47}, {k48: 48}, {k49: 49}, {k50: 50}, {k51: 51}, {k52: 52}, {k53: 53}, {k54: 54}, {k55: 55}, {k56: 56}, {k57: 57}, {k58: 58}, {k59: 59}, {k60: 60}, {k61: 61}, {k62: 62}, {k63: 63}]};{k0: 0, k1: 1, k2: 2, k3: 3, k4: 4, k5: 5, k6: 6, k7: 7, k8: 8, k9: 9, k10: 10, k11: 11, k12: 12, k13: 13, k14: 14, k15: 15, k16: 16, k17: 17, k18: 18, k19: 19, k20: 20, k21: 21, k22: 22, k23: 23, k24: 24, k25: 25, k26: 26, k27: 27, k28: 28, k29: 29, k30: 30, k31: 31, k32: 32, k33: 33, k34: 34, k35: 35, k36: 36, k37: 37, k38: 38, k39: 39, k40: 40, k41: 41, k42: 42, k43: 43, k44: 44, k45: 45, k46: 46, k47: 47, k48: 48, k49: 49, k50: 50, k51: 51, k52: 52, k53: 53, k54: 54, k55: 55, k56: 56, k57: 57, k58: 58, k59: 59, k60: 60, k61: 61, k62: 62, k63: 63} +merge(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k0: 9}, {k1: 10}, {k2: 11}, {k3: 12}, {k4: 13}, {k5: 14}, {k6: 15}, {k7: 16}, {k8: 17}, {k0: 18}, {k1: 19}, {k2: 20}, {k3: 21}, {k4: 22}, {k5: 23}, {k6: 24}, {k7: 25}, {k8: 26}, {k0: 27}, {k1: 28}, {k2: 29}, {k3: 30}, {k4: 31}, {k5: 32}, {k6: 33}, {k7: 34}, {k8: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}, {k4: 40}, {k5: 41}, {k6: 42}, {k7: 43}, {k8: 44}, {k0: 45}, {k1: 46}, {k2: 47}, {k3: 48}, {k4: 49}, {k5: 50}, {k6: 51}, {k7: 52}, {k8: 53}, {k0: 54}, {k1: 55}, {k2: 56}, {k3: 57}, {k4: 58}, {k5: 59}, {k6: 60}, {k7: 61}, {k8: 62}, {k0: 63}, {k1: 64}]};{k0: 63, k1: 64, k2: 56, k3: 57, k4: 58, k5: 59, k6: 60, k7: 61, k8: 62} +merge(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}, {k3: 33}, {k4: 34}, {k5: 35}, {k6: 36}, {k7: 37}, {k8: 38}, {k9: 39}, {k0: 40}, {k1: 41}, {k2: 42}, {k3: 43}, {k4: 44}, {k5: 45}, {k6: 46}, {k7: 47}, {k8: 48}, {k9: 49}, {k0: 50}, {k1: 51}, {k2: 52}, {k3: 53}, {k4: 54}, {k5: 55}, {k6: 56}, {k7: 57}, {k8: 58}, {k9: 59}, {k0: 60}, {k1: 61}, {k2: 62}, {k3: 63}, {k4: 64}, {k5: 65}, {k6: 66}, {k7: 67}, {k8: 68}, {k9: 69}, {k0: 70}, {k1: 71}, {k2: 72}, {k3: 73}, {k4: 74}, {k5: 75}, {k6: 76}, {k7: 77}, {k8: 78}, {k9: 79}, {k0: 80}, {k1: 81}, {k2: 82}, {k3: 83}, {k4: 84}, {k5: 85}, {k6: 86}, {k7: 87}, {k8: 88}, {k9: 89}, {k0: 90}, {k1: 91}, {k2: 92}, {k3: 93}, {k4: 94}, {k5: 95}, {k6: 96}, {k7: 97}, {k8: 98}, {k9: 99}]};{k0: 90, k1: 91, k2: 92, k3: 93, k4: 94, k5: 95, k6: 96, k7: 97, k8: 98, k9: 99} +mergeDeep(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}]};{k0: 30, k1: 31, k2: 22, k3: 23, k4: 24, k5: 25, k6: 26, k7: 27, k8: 28, k9: 29} +mergeDeep(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}]};{k0: 30, k1: 31, k2: 32, k3: 23, k4: 24, k5: 25, k6: 26, k7: 27, k8: 28, k9: 29} +mergeDeep(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k0: 12}, {k1: 13}, {k2: 14}, {k3: 15}, {k4: 16}, {k5: 17}, {k6: 18}, {k7: 19}, {k8: 20}, {k9: 21}, {k10: 22}, {k11: 23}, {k0: 24}, {k1: 25}, {k2: 26}, {k3: 27}, {k4: 28}, {k5: 29}, {k6: 30}, {k7: 31}, {k8: 32}, {k9: 33}, {k10: 34}, {k11: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}]};{k0: 36, k1: 37, k2: 38, k3: 39, k4: 28, k5: 29, k6: 30, k7: 31, k8: 32, k9: 33, k10: 34, k11: 35} +mergeDeep(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k12: 12}, {k13: 13}, {k14: 14}, {k15: 15}, {k16: 16}, {k17: 17}, {k18: 18}, {k19: 19}, {k20: 20}, {k21: 21}, {k22: 22}, {k23: 23}, {k24: 24}, {k25: 25}, {k26: 26}, {k27: 27}, {k28: 28}, {k29: 29}, {k30: 30}, {k31: 31}, {k32: 32}, {k33: 33}, {k34: 34}, {k35: 35}, {k36: 36}, {k37: 37}, {k38: 38}, {k39: 39}, {k40: 40}, {k41: 41}, {k42: 42}, {k43: 43}, {k44: 44}, {k45: 45}, {k46: 46}, {k47: 47}, {k48: 48}, {k49: 49}, {k50: 50}, {k51: 51}, {k52: 52}, {k53: 53}, {k54: 54}, {k55: 55}, {k56: 56}, {k57: 57}, {k58: 58}, {k59: 59}, {k60: 60}, {k61: 61}, {k62: 62}, {k63: 63}]};{k0: 0, k1: 1, k2: 2, k3: 3, k4: 4, k5: 5, k6: 6, k7: 7, k8: 8, k9: 9, k10: 10, k11: 11, k12: 12, k13: 13, k14: 14, k15: 15, k16: 16, k17: 17, k18: 18, k19: 19, k20: 20, k21: 21, k22: 22, k23: 23, k24: 24, k25: 25, k26: 26, k27: 27, k28: 28, k29: 29, k30: 30, k31: 31, k32: 32, k33: 33, k34: 34, k35: 35, k36: 36, k37: 37, k38: 38, k39: 39, k40: 40, k41: 41, k42: 42, k43: 43, k44: 44, k45: 45, k46: 46, k47: 47, k48: 48, k49: 49, k50: 50, k51: 51, k52: 52, k53: 53, k54: 54, k55: 55, k56: 56, k57: 57, k58: 58, k59: 59, k60: 60, k61: 61, k62: 62, k63: 63} +mergeDeep(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k0: 9}, {k1: 10}, {k2: 11}, {k3: 12}, {k4: 13}, {k5: 14}, {k6: 15}, {k7: 16}, {k8: 17}, {k0: 18}, {k1: 19}, {k2: 20}, {k3: 21}, {k4: 22}, {k5: 23}, {k6: 24}, {k7: 25}, {k8: 26}, {k0: 27}, {k1: 28}, {k2: 29}, {k3: 30}, {k4: 31}, {k5: 32}, {k6: 33}, {k7: 34}, {k8: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}, {k4: 40}, {k5: 41}, {k6: 42}, {k7: 43}, {k8: 44}, {k0: 45}, {k1: 46}, {k2: 47}, {k3: 48}, {k4: 49}, {k5: 50}, {k6: 51}, {k7: 52}, {k8: 53}, {k0: 54}, {k1: 55}, {k2: 56}, {k3: 57}, {k4: 58}, {k5: 59}, {k6: 60}, {k7: 61}, {k8: 62}, {k0: 63}, {k1: 64}]};{k0: 63, k1: 64, k2: 56, k3: 57, k4: 58, k5: 59, k6: 60, k7: 61, k8: 62} +mergeDeep(xs);{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}, {k3: 33}, {k4: 34}, {k5: 35}, {k6: 36}, {k7: 37}, {k8: 38}, {k9: 39}, {k0: 40}, {k1: 41}, {k2: 42}, {k3: 43}, {k4: 44}, {k5: 45}, {k6: 46}, {k7: 47}, {k8: 48}, {k9: 49}, {k0: 50}, {k1: 51}, {k2: 52}, {k3: 53}, {k4: 54}, {k5: 55}, {k6: 56}, {k7: 57}, {k8: 58}, {k9: 59}, {k0: 60}, {k1: 61}, {k2: 62}, {k3: 63}, {k4: 64}, {k5: 65}, {k6: 66}, {k7: 67}, {k8: 68}, {k9: 69}, {k0: 70}, {k1: 71}, {k2: 72}, {k3: 73}, {k4: 74}, {k5: 75}, {k6: 76}, {k7: 77}, {k8: 78}, {k9: 79}, {k0: 80}, {k1: 81}, {k2: 82}, {k3: 83}, {k4: 84}, {k5: 85}, {k6: 86}, {k7: 87}, {k8: 88}, {k9: 89}, {k0: 90}, {k1: 91}, {k2: 92}, {k3: 93}, {k4: 94}, {k5: 95}, {k6: 96}, {k7: 97}, {k8: 98}, {k9: 99}]};{k0: 90, k1: 91, k2: 92, k3: 93, k4: 94, k5: 95, k6: 96, k7: 97, k8: 98, k9: 99} +sum(values(merge(xs)));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}]};265 +sum(values(merge(xs)));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}]};275 +sum(values(merge(xs)));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k0: 12}, {k1: 13}, {k2: 14}, {k3: 15}, {k4: 16}, {k5: 17}, {k6: 18}, {k7: 19}, {k8: 20}, {k9: 21}, {k10: 22}, {k11: 23}, {k0: 24}, {k1: 25}, {k2: 26}, {k3: 27}, {k4: 28}, {k5: 29}, {k6: 30}, {k7: 31}, {k8: 32}, {k9: 33}, {k10: 34}, {k11: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}]};402 +sum(values(merge(xs)));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k10: 10}, {k11: 11}, {k12: 12}, {k13: 13}, {k14: 14}, {k15: 15}, {k16: 16}, {k17: 17}, {k18: 18}, {k19: 19}, {k20: 20}, {k21: 21}, {k22: 22}, {k23: 23}, {k24: 24}, {k25: 25}, {k26: 26}, {k27: 27}, {k28: 28}, {k29: 29}, {k30: 30}, {k31: 31}, {k32: 32}, {k33: 33}, {k34: 34}, {k35: 35}, {k36: 36}, {k37: 37}, {k38: 38}, {k39: 39}, {k40: 40}, {k41: 41}, {k42: 42}, {k43: 43}, {k44: 44}, {k45: 45}, {k46: 46}, {k47: 47}, {k48: 48}, {k49: 49}, {k50: 50}, {k51: 51}, {k52: 52}, {k53: 53}, {k54: 54}, {k55: 55}, {k56: 56}, {k57: 57}, {k58: 58}, {k59: 59}, {k60: 60}, {k61: 61}, {k62: 62}, {k63: 63}]};2016 +sum(values(merge(xs)));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k0: 9}, {k1: 10}, {k2: 11}, {k3: 12}, {k4: 13}, {k5: 14}, {k6: 15}, {k7: 16}, {k8: 17}, {k0: 18}, {k1: 19}, {k2: 20}, {k3: 21}, {k4: 22}, {k5: 23}, {k6: 24}, {k7: 25}, {k8: 26}, {k0: 27}, {k1: 28}, {k2: 29}, {k3: 30}, {k4: 31}, {k5: 32}, {k6: 33}, {k7: 34}, {k8: 35}, {k0: 36}, {k1: 37}, {k2: 38}, {k3: 39}, {k4: 40}, {k5: 41}, {k6: 42}, {k7: 43}, {k8: 44}, {k0: 45}, {k1: 46}, {k2: 47}, {k3: 48}, {k4: 49}, {k5: 50}, {k6: 51}, {k7: 52}, {k8: 53}, {k0: 54}, {k1: 55}, {k2: 56}, {k3: 57}, {k4: 58}, {k5: 59}, {k6: 60}, {k7: 61}, {k8: 62}, {k0: 63}, {k1: 64}]};540 +sum(values(merge(xs)));{xs: [{k0: 0}, {k1: 1}, {k2: 2}, {k3: 3}, {k4: 4}, {k5: 5}, {k6: 6}, {k7: 7}, {k8: 8}, {k9: 9}, {k0: 10}, {k1: 11}, {k2: 12}, {k3: 13}, {k4: 14}, {k5: 15}, {k6: 16}, {k7: 17}, {k8: 18}, {k9: 19}, {k0: 20}, {k1: 21}, {k2: 22}, {k3: 23}, {k4: 24}, {k5: 25}, {k6: 26}, {k7: 27}, {k8: 28}, {k9: 29}, {k0: 30}, {k1: 31}, {k2: 32}, {k3: 33}, {k4: 34}, {k5: 35}, {k6: 36}, {k7: 37}, {k8: 38}, {k9: 39}, {k0: 40}, {k1: 41}, {k2: 42}, {k3: 43}, {k4: 44}, {k5: 45}, {k6: 46}, {k7: 47}, {k8: 48}, {k9: 49}, {k0: 50}, {k1: 51}, {k2: 52}, {k3: 53}, {k4: 54}, {k5: 55}, {k6: 56}, {k7: 57}, {k8: 58}, {k9: 59}, {k0: 60}, {k1: 61}, {k2: 62}, {k3: 63}, {k4: 64}, {k5: 65}, {k6: 66}, {k7: 67}, {k8: 68}, {k9: 69}, {k0: 70}, {k1: 71}, {k2: 72}, {k3: 73}, {k4: 74}, {k5: 75}, {k6: 76}, {k7: 77}, {k8: 78}, {k9: 79}, {k0: 80}, {k1: 81}, {k2: 82}, {k3: 83}, {k4: 84}, {k5: 85}, {k6: 86}, {k7: 87}, {k8: 88}, {k9: 89}, {k0: 90}, {k1: 91}, {k2: 92}, {k3: 93}, {k4: 94}, {k5: 95}, {k6: 96}, {k7: 97}, {k8: 98}, {k9: 99}]};945 diff --git a/core/expression/tests/spec/standard/14-properties.csv b/core/expression/tests/spec/standard/14-properties.csv new file mode 100644 index 00000000..57714814 --- /dev/null +++ b/core/expression/tests/spec/standard/14-properties.csv @@ -0,0 +1,1719 @@ +expression (string);input (json 5);output (json 5);note +# Commutativity of + and * holds exactly, including at the 28-digit limit +a + b == b + a;{a: 0.1, b: 0.2};true +a + b == b + a;{a: 79228162514264337593543950335, b: -1};true +a + b == b + a;{a: 0.0000000000000000000000000001, b: 10};true +a + b == b + a;{a: 1.005, b: -3.14159};true +a + b == b + a;{a: 1.10, b: -0.0000000000000000000000000001};true +a + b == b + a;{a: 4294967295, b: 0.3333333333333333333333333333};true +a + b == b + a;{a: 12345678901234567890.12345678, b: 3};true +a + b == b + a;{a: 18446744073709551616, b: 9007199254740993};true +a + b == b + a;{a: 4294967295, b: 7};true +a + b == b + a;{a: 4294967295, b: 9007199254740992};true +a + b == b + a;{b: 0.5};!error +a * b == b * a;{a: 0.1, b: 0.1};true +a * b == b * a;{a: 0.3333333333333333333333333333, b: 3};true +a * b == b * a;{a: 0.0000000000000000000000000001, b: 0.5};true +a * b == b * a;{a: 79228162514264337593543950335, b: 2};!error +a * b == b * a;{a: 1.005, b: -3.14159};true +a * b == b * a;{a: 79228162514264337593543950335, b: 2147483647};!error +a * b == b * a;{a: 9007199254740993, b: 0.3};true +a * b == b * a;{a: 1.0000000000000000000000000001, b: 2147483647};true +a * b == b * a;{a: -79228162514264337593543950335, b: 1.0000000000000000000000000001};!error +a * b == b * a;{a: 12345678901234567890.12345678, b: 3.1415926535897932384626433833};true +a * b == b * a;{a: 0.01};!error +string(a + b) == string(b + a);{a: 1.10, b: 2};true +string(a + b) == string(b + a);{a: 2.000, b: 0.5};true +string(a + b) == string(b + a);{a: 0.0000000000000000000000000001, b: 10};true +string(a + b) == string(b + a);{a: -0.0000000000000000000000000001, b: 0.3333333333333333333333333333};true +string(a + b) == string(b + a);{a: -2147483649, b: 0};true +string(a + b) == string(b + a);{a: 4294967295, b: -79228162514264337593543950335};true +string(a + b) == string(b + a);{a: 0.5, b: 0.5};true +string(a + b) == string(b + a);{a: 1, b: -12.5};true +string(a + b) == string(b + a);{a: 1.10, b: 1.0000000000000000000000000001};true +string(a + b) == string(b + a);{a: 0.01, b: 18446744073709551616};true +string(a + b) == string(b + a);{a: 3};!error +string(a * b) == string(b * a);{a: 1.10, b: 2.000};true +string(a * b) == string(b * a);{a: 0.01, b: 0.01};true +string(a * b) == string(b * a);{a: 3.1415926535897932384626433833, b: 3.1415926535897932384626433833};true +string(a * b) == string(b * a);{a: -9007199254740993, b: 9007199254740993};!error +string(a * b) == string(b * a);{a: 2147483647, b: 0.3333333333333333333333333333};true +string(a * b) == string(b * a);{a: -2147483649, b: -9007199254740993};true +string(a * b) == string(b * a);{a: -79228162514264337593543950335, b: -9223372036854775808};!error +string(a * b) == string(b * a);{a: 0.5, b: -9223372036854775808};true +string(a * b) == string(b * a);{a: 1000000000000, b: 0.3};true +string(a * b) == string(b * a);{a: 9007199254740992, b: 100};true +string(a * b) == string(b * a);{a: true, b: -0.75};!error +min([a, b]) == min([b, a]);{a: 1, b: 1.0};true +min([a, b]) == min([b, a]);{a: -1, b: 1};true +min([a, b]) == min([b, a]);{a: 79228162514264337593543950335, b: 2.000};true +min([a, b]) == min([b, a]);{a: 2147483647, b: 9007199254740993};true +min([a, b]) == min([b, a]);{a: -1, b: -0.75};true +min([a, b]) == min([b, a]);{a: 1.10, b: -0.75};true +min([a, b]) == min([b, a]);{a: 0.3333333333333333333333333333, b: 2147483647};true +min([a, b]) == min([b, a]);{a: -1, b: 0.1};true +min([a, b]) == min([b, a]);{b: 1.10};!error +max([a, b]) == max([b, a]);{a: 2.5, b: 2.50};true +max([a, b]) == max([b, a]);{a: 79228162514264337593543950335, b: -79228162514264337593543950335};true +max([a, b]) == max([b, a]);{a: -2147483649, b: -1};true +max([a, b]) == max([b, a]);{a: 3.1415926535897932384626433833, b: 0.3333333333333333333333333333};true +max([a, b]) == max([b, a]);{a: 79228162514264337593543950335, b: 9223372036854775807};true +max([a, b]) == max([b, a]);{a: 0.0000000000000000000000000001, b: 39614081257132168796771975167};true +max([a, b]) == max([b, a]);{a: 3.1415926535897932384626433833, b: 0.01};true +max([a, b]) == max([b, a]);{a: 9007199254740993, b: 2.000};true +max([a, b]) == max([b, a]);{a: '5', b: 0.25};!error +# Identities +a + 0 == a;{a: 7};true +a + 0 == a;{a: -12.5};true +a + 0 == a;{a: 0.01};true +a + 0 == a;{a: 0.3};true +a + 0 == a;{a: 9007199254740992};true +a + 0 == a;{a: 2147483647};true +a + 0 == a;{a: 4294967295};true +a + 0 == a;{a: -79228162514264337593543950335};true +a + 0 == a;{a: 0.0000000000000000000000000001};true +a + 0 == a;{a: -0.0000000000000000000000000001};true +a + 0 == a;{a: null};!error +a + 0 == a;{a: '5'};!error +a - 0 == a;{a: 0.2};true +a - 0 == a;{a: -1};true +a - 0 == a;{a: 0.5};true +a - 0 == a;{a: 7};true +a - 0 == a;{a: -9007199254740993};true +a - 0 == a;{a: 2147483648};true +a - 0 == a;{a: 9223372036854775807};true +a - 0 == a;{a: 7922816251426433759354395033.5};true +a - 0 == a;{a: 79228162514264337593543950335};true +a - 0 == a;{a: -79228162514264337593543950335};true +a - 0 == a;{a: '5'};!error +a - 0 == a;{a: true};!error +a * 1 == a;{a: 100};true +a * 1 == a;{a: -12.5};true +a * 1 == a;{a: 1.10};true +a * 1 == a;{a: 1.005};true +a * 1 == a;{a: -9007199254740993};true +a * 1 == a;{a: -2147483649};true +a * 1 == a;{a: 2147483647};true +a * 1 == a;{a: 0.0000000000000000000000000001};true +a * 1 == a;{a: 12345678901234567890.12345678};true +a * 1 == a;{a: 1.0000000000000000000000000001};true +a * 1 == a;{a: null};!error +a * 1 == a;{a: '5'};!error +a / 1 == a;{a: 7};true +a / 1 == a;{a: 100};true +a / 1 == a;{a: 0.25};true +a / 1 == a;{a: -0.75};true +a / 1 == a;{a: 9007199254740993};true +a / 1 == a;{a: -9007199254740993};true +a / 1 == a;{a: 4294967295};true +a / 1 == a;{a: 0};true +a / 1 == a;{a: 3.1415926535897932384626433833};true +a / 1 == a;{a: -79228162514264337593543950335};true +a / 1 == a;{a: '5'};!error +a / 1 == a;{a: null};!error +a - a == 0;{a: 2.000};true +a - a == 0;{a: -3.14159};true +a - a == 0;{a: 1.005};true +a - a == 0;{a: -1};true +a - a == 0;{a: 2147483647};true +a - a == 0;{a: 123456789.123456789};true +a - a == 0;{a: 2147483648};true +a - a == 0;{a: -79228162514264337593543950335};true +a - a == 0;{a: 79228162514264337593543950335};true +a - a == 0;{a: 0.3333333333333333333333333333};true +a - a == 0;{a: null};!error +a - a == 0;{a: true};!error +a * 0 == 0;{a: 0.3};true +a * 0 == 0;{a: 0.2};true +a * 0 == 0;{a: 0.1};true +a * 0 == 0;{a: 3};true +a * 0 == 0;{a: -9007199254740993};true +a * 0 == 0;{a: 1000000000000};true +a * 0 == 0;{a: 18446744073709551616};true +a * 0 == 0;{a: 39614081257132168796771975167};true +a * 0 == 0;{a: 79228162514264337593543950335};true +a * 0 == 0;{a: 0.3333333333333333333333333333};true +a * 0 == 0;{a: null};!error +a * 0 == 0;{};!error +-(-a) == a;{a: 7};true +-(-a) == a;{a: -0.75};true +-(-a) == a;{a: 0.1};true +-(-a) == a;{a: 0.5};true +-(-a) == a;{a: -2147483649};true +-(-a) == a;{a: 123456789.123456789};true +-(-a) == a;{a: 9007199254740992};true +-(-a) == a;{a: -79228162514264337593543950335};true +-(-a) == a;{a: 12345678901234567890.12345678};true +-(-a) == a;{a: 7922816251426433759354395033.5};true +-(-a) == a;{a: true};!error +-(-a) == a;{};!error +a == a;{a: -0.75};true +a == a;{a: 100};true +a == a;{a: 2.5};true +a == a;{a: 0.1};true +a == a;{a: 4294967295};true +a == a;{a: 2147483648};true +a == a;{a: 1000000000000};true +a == a;{a: 1.0000000000000000000000000001};true +a == a;{a: 0.3333333333333333333333333333};true +a == a;{a: -0.0000000000000000000000000001};true +a == a;{a: true};true +a == a;{a: null};true +a == a;{a: '5'};true +a == a;{};true +a ^ 1 == a;{a: 2.5};true +a ^ 1 == a;{a: 0.3};true +a ^ 1 == a;{a: -12.5};true +a ^ 1 == a;{a: 0.2};true +a ^ 1 == a;{a: 18446744073709551616};true +a ^ 1 == a;{a: 9007199254740993};true +a ^ 1 == a;{a: -2147483649};true +a ^ 1 == a;{a: 79228162514264337593543950335};true +a ^ 1 == a;{a: 7922816251426433759354395033.5};true +a ^ 1 == a;{a: 0};true +a ^ 1 == a;{};!error +a ^ 1 == a;{a: true};!error +a ^ 0 == 1;{a: 1.10};true +a ^ 0 == 1;{a: -3.14159};true +a ^ 0 == 1;{a: 7};true +a ^ 0 == 1;{a: -12.5};true +a ^ 0 == 1;{a: -2147483649};true +a ^ 0 == 1;{a: 1000000000000};true +a ^ 0 == 1;{a: 4294967295};true +a ^ 0 == 1;{a: -79228162514264337593543950335};true +a ^ 0 == 1;{a: -0.0000000000000000000000000001};true +a ^ 0 == 1;{a: 12345678901234567890.12345678};true +a ^ 0 == 1;{a: true};!error +a ^ 0 == 1;{a: '5'};!error +string(a + 0) == string(a);{a: 2.000};true +string(a + 0) == string(a);{a: 1.10};true +string(a + 0) == string(a);{a: 0.25};true +string(a + 0) == string(a);{a: 0.1};true +string(a + 0) == string(a);{a: -3.14159};true +string(a + 0) == string(a);{a: 18446744073709551616};true +string(a + 0) == string(a);{a: 1000000000000};true +string(a + 0) == string(a);{a: -9223372036854775808};true +string(a + 0) == string(a);{a: 12345678901234567890.12345678};true +string(a + 0) == string(a);{a: 0.3333333333333333333333333333};true +string(a + 0) == string(a);{a: 7922816251426433759354395033.5};true +string(a + 0) == string(a);{a: true};!error +string(a + 0) == string(a);{a: null};!error +string(a * 1) == string(a);{a: 2.000};true +string(a * 1) == string(a);{a: 1.10};true +string(a * 1) == string(a);{a: 1.005};true +string(a * 1) == string(a);{a: 1};true +string(a * 1) == string(a);{a: 100};true +string(a * 1) == string(a);{a: 9007199254740992};true +string(a * 1) == string(a);{a: -9007199254740993};true +string(a * 1) == string(a);{a: -2147483649};true +string(a * 1) == string(a);{a: 7922816251426433759354395033.5};true +string(a * 1) == string(a);{a: -79228162514264337593543950335};true +string(a * 1) == string(a);{a: 3.1415926535897932384626433833};true +string(a * 1) == string(a);{a: true};!error +string(a * 1) == string(a);{a: null};!error +string(a - 0) == string(a);{a: 2.000};true +string(a - 0) == string(a);{a: 1.10};true +string(a - 0) == string(a);{a: 100};true +string(a - 0) == string(a);{a: 2.5};true +string(a - 0) == string(a);{a: 0.01};true +string(a - 0) == string(a);{a: 0.5};true +string(a - 0) == string(a);{a: 4294967295};true +string(a - 0) == string(a);{a: 123456789.123456789};true +string(a - 0) == string(a);{a: 2147483648};true +string(a - 0) == string(a);{a: 1.0000000000000000000000000001};true +string(a - 0) == string(a);{a: 0};true +string(a - 0) == string(a);{a: 0.0000000000000000000000000001};true +string(a - 0) == string(a);{a: '5'};!error +string(a - 0) == string(a);{};!error +sum([a]) == a;{a: -0.75};true +sum([a]) == a;{a: 0.25};true +sum([a]) == a;{a: 0.2};true +sum([a]) == a;{a: 0.1};true +sum([a]) == a;{a: 9223372036854775807};true +sum([a]) == a;{a: 123456789.123456789};true +sum([a]) == a;{a: 4294967295};true +sum([a]) == a;{a: 0};true +sum([a]) == a;{a: 3.1415926535897932384626433833};true +sum([a]) == a;{a: 0.3333333333333333333333333333};true +sum([a]) == a;{a: '5'};!error +sum([a]) == a;{a: true};!error +min([a]) == a and max([a]) == a;{a: 1};true +min([a]) == a and max([a]) == a;{a: 0.2};true +min([a]) == a and max([a]) == a;{a: 0.1};true +min([a]) == a and max([a]) == a;{a: -3.14159};true +min([a]) == a and max([a]) == a;{a: 9223372036854775807};true +min([a]) == a and max([a]) == a;{a: 2147483647};true +min([a]) == a and max([a]) == a;{a: 2147483648};true +min([a]) == a and max([a]) == a;{a: 1.0000000000000000000000000001};true +min([a]) == a and max([a]) == a;{a: -0.0000000000000000000000000001};true +min([a]) == a and max([a]) == a;{a: 0.3333333333333333333333333333};true +min([a]) == a and max([a]) == a;{a: true};!error +min([a]) == a and max([a]) == a;{a: '5'};!error +# Subtraction and negation relate as a - b == a + -b +a - b == a + -b;{a: 0.0000000000000000000000000001, b: -0.0000000000000000000000000001};true +a - b == a + -b;{a: 0.1, b: 0.3};true +a - b == a + -b;{a: 9007199254740992, b: 0.0000000000000000000000000001};true +a - b == a + -b;{a: 9223372036854775807, b: 100};true +a - b == a + -b;{a: 9007199254740993, b: -79228162514264337593543950335};!error +a - b == a + -b;{a: -0.75, b: 0.5};true +a - b == a + -b;{a: -1, b: -2147483649};true +a - b == a + -b;{a: 7, b: 7922816251426433759354395033.5};true +a - b == a + -b;{a: -9007199254740993, b: -79228162514264337593543950335};true +a - b == a + -b;{a: -9007199254740993, b: 1.005};true +a - b == a + -b;{b: 2.000};!error +a - b == -(b - a);{a: 1.005, b: 123456789.123456789};true +a - b == -(b - a);{a: 2.000, b: 1.0000000000000000000000000001};true +a - b == -(b - a);{a: 9223372036854775807, b: 1.005};true +a - b == -(b - a);{a: 0.01, b: 2147483647};true +a - b == -(b - a);{a: 1.005, b: 39614081257132168796771975167};true +a - b == -(b - a);{a: -0.0000000000000000000000000001, b: -3.14159};true +a - b == -(b - a);{a: 2.000, b: -9007199254740993};true +a - b == -(b - a);{a: 9223372036854775807, b: 2147483647};true +a - b == -(b - a);{a: 3.1415926535897932384626433833, b: -79228162514264337593543950335};!error +a - b == -(b - a);{a: 0.3333333333333333333333333333, b: 2147483648};true +a - b == -(b - a);{a: true, b: -3.14159};!error +a * 2 == a + a;{a: 39614081257132168796771975168};!error +a * 2 == a + a;{a: 100};true +a * 2 == a + a;{a: 0.25};true +a * 2 == a + a;{a: 3};true +a * 2 == a + a;{a: 1};true +a * 2 == a + a;{a: 123456789.123456789};true +a * 2 == a + a;{a: 1000000000000};true +a * 2 == a + a;{a: 9223372036854775807};true +a * 2 == a + a;{a: 7922816251426433759354395033.5};true +a * 2 == a + a;{a: -0.0000000000000000000000000001};true +a * 2 == a + a;{a: 1.0000000000000000000000000001};true +a * 2 == a + a;{a: null};!error +a * 2 == a + a;{};!error +-a * -b == a * b;{a: 0.0000000000000000000000000001, b: 0.3333333333333333333333333333};true +-a * -b == a * b;{a: 2147483648, b: 1.005};true +-a * -b == a * b;{a: 9007199254740992, b: 0};true +-a * -b == a * b;{a: -12.5, b: 0.0000000000000000000000000001};true +-a * -b == a * b;{a: 7922816251426433759354395033.5, b: 0.3333333333333333333333333333};true +-a * -b == a * b;{a: 0.3333333333333333333333333333, b: -1};true +-a * -b == a * b;{a: -3.14159, b: 0.3333333333333333333333333333};true +-a * -b == a * b;{a: 0.25, b: -0.0000000000000000000000000001};true +-a * -b == a * b;{a: 0.3, b: 0.5};true +-a * -b == a * b;{a: null, b: 0.1};!error +-a / -b == a / b;{a: 1, b: 3};true +-a / -b == a / b;{a: 2, b: 3};true +-a / -b == a / b;{a: 1, b: 0};true +-a / -b == a / b;{a: -0.75, b: 79228162514264337593543950335};true +-a / -b == a / b;{a: -2147483649, b: -0.0000000000000000000000000001};!error;bug: division overflow returns null instead of an error, so both sides are null or the comparison sees null +-a / -b == a / b;{a: -2147483649, b: 0.25};true +-a / -b == a / b;{a: 123456789.123456789, b: 2.000};true +-a / -b == a / b;{a: 9223372036854775807, b: 0.3333333333333333333333333333};true +-a / -b == a / b;{a: -2147483649, b: 1000000000000};true +-a / -b == a / b;{a: null, b: 0.2};!error +(a < b) == (b > a);{a: 0.0000000000000000000000000001, b: 0};true +(a < b) == (b > a);{a: 1.0, b: 1};true +(a < b) == (b > a);{a: 1000000000000, b: 0.5};true +(a < b) == (b > a);{a: -0.75, b: -79228162514264337593543950335};true +(a < b) == (b > a);{a: 9007199254740993, b: 79228162514264337593543950335};true +(a < b) == (b > a);{a: 9007199254740992, b: 7922816251426433759354395033.5};true +(a < b) == (b > a);{a: 9223372036854775807, b: 9007199254740992};true +(a < b) == (b > a);{a: 12345678901234567890.12345678, b: 0.1};true +(a < b) == (b > a);{a: -2147483649, b: 1};true +(a < b) == (b > a);{b: 3};!error +(a <= b) == not (a > b);{a: 2.50, b: 2.5};true +(a <= b) == not (a > b);{a: 9007199254740993, b: 7922816251426433759354395033.5};true +(a <= b) == not (a > b);{a: 7, b: 1000000000000};true +(a <= b) == not (a > b);{a: 1.005, b: 9223372036854775807};true +(a <= b) == not (a > b);{a: -0.0000000000000000000000000001, b: 12345678901234567890.12345678};true +(a <= b) == not (a > b);{a: 0, b: 7922816251426433759354395033.5};true +(a <= b) == not (a > b);{a: 3.1415926535897932384626433833, b: 9007199254740992};true +(a <= b) == not (a > b);{a: -9007199254740993, b: 0.3333333333333333333333333333};true +(a <= b) == not (a > b);{a: 9007199254740992, b: 2147483648};true +(a <= b) == not (a > b);{a: null, b: -0.75};!error +len(filter([a < b, a == b, a > b], #)) == 1;{a: 1.10, b: 1.1};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 79228162514264337593543950335, b: 79228162514264337593543950335};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: -0.0000000000000000000000000001, b: 0.0000000000000000000000000001};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 0.01, b: 18446744073709551616};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 0.01, b: 0.1};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: -12.5, b: 1};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 0.0000000000000000000000000001, b: 0.3};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: -0.75, b: 0.2};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 2.5, b: 2147483647};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 79228162514264337593543950335, b: -3.14159};true +len(filter([a < b, a == b, a > b], #)) == 1;{a: 0.1, b: null};!error +# Associativity of + holds while no intermediate result needs more than 28-29 significant digits +(a + b) + c == a + (b + c);{a: 0.1, b: 0.2, c: 0.3};true +(a + b) + c == a + (b + c);{a: 1.005, b: -3.14159, c: 123456789.123456789};true +(a + b) + c == a + (b + c);{a: 0.0000000000000000000000000001, b: 1, c: -1};true +(a + b) + c == a + (b + c);{a: 79228162514264337593543950335, b: 1, c: -1};!error +(a + b) + c == a + (b + c);{a: -1, b: 79228162514264337593543950335, c: 1};!error +(a + b) + c == a + (b + c);{a: 0.0000000000000000000000000001, b: 0.0000000000000000000000000001, c: 8};true +(a + b) + c == a + (b + c);{a: 0.5, b: 7922816251426433759354395033, c: 0.5};true +(a + b) + c == a + (b + c);{a: 2.000, b: 0.0000000000000000000000000001, c: 2.5};true +(a + b) + c == a + (b + c);{a: -9223372036854775808, b: 1.0000000000000000000000000001, c: 1.0000000000000000000000000001};true +(a + b) + c == a + (b + c);{a: 0.1, b: true, c: 0.1};!error +# Precision limit: rounding an intermediate sum to 28-29 digits loses low digits, so associativity fails and false is intended +(a + b) + c == a + (b + c);{a: 0.0000000000000000000000000001, b: 10, c: -10};false +# Associativity of * holds for exact products and fails once a product is rounded +(a * b) * c == a * (b * c);{a: 0.1, b: 0.2, c: 0.3};true +(a * b) * c == a * (b * c);{a: 1.005, b: -3.14159, c: 2.5};true +(a * b) * c == a * (b * c);{a: 0.3333333333333333333333333333, b: 3, c: 3};true +(a * b) * c == a * (b * c);{a: 2147483648, b: 2147483648, c: 2147483648};true +(a * b) * c == a * (b * c);{a: 0.1, b: -12.5, c: 0.1};true +(a * b) * c == a * (b * c);{a: -3.14159, b: 9007199254740992, c: 0.25};true +(a * b) * c == a * (b * c);{a: 3, b: 2147483648, c: -0.75};true +(a * b) * c == a * (b * c);{a: 0.5, b: true, c: -12.5};!error +# Precision limit: a product rounded (or underflowing) at 28 fractional digits changes the result of the second multiplication, so false is intended +(a * b) * c == a * (b * c);{a: 0.0000000000000000000000000001, b: 0.5, c: 2};false +(a * b) * c == a * (b * c);{a: 0.5, b: 0.0000000000000000000000000001, c: 2};false +(a * b) * c == a * (b * c);{a: 3.1415926535897932384626433833, b: 0.1, c: 10};false +# Property: a - b - c == a - (b + c) +a - b - c == a - (b + c);{a: -79228162514264337593543950335, b: 1, c: -1};!error +a - b - c == a - (b + c);{a: 0.01, b: 1.10, c: 0.01};true +a - b - c == a - (b + c);{a: 0.5, b: 0.0000000000000000000000000001, c: 1.005};true +a - b - c == a - (b + c);{a: 3.1415926535897932384626433833, b: 0.0000000000000000000000000001, c: 1.10};true +a - b - c == a - (b + c);{a: 3.1415926535897932384626433833, b: 9007199254740993, c: 123456789.123456789};true +a - b - c == a - (b + c);{a: 100, b: 2.000, c: 0.1};true +a - b - c == a - (b + c);{a: 0.25, b: 2147483647, c: 2.5};true +a - b - c == a - (b + c);{a: 7922816251426433759354395033.5, b: 1.0000000000000000000000000001, c: 2.5};true +a - b - c == a - (b + c);{a: 0.3, c: -3.14159};!error +# Precision limit: the two groupings round different intermediates, so false is intended +a - b - c == a - (b + c);{a: 0.0000000000000000000000000001, b: -10, c: 10};false +# Distributivity +a * (b + c) == a * b + a * c;{a: 2, b: 0.1, c: 0.2};true +a * (b + c) == a * b + a * c;{a: 1.005, b: 3, c: -3};true +a * (b + c) == a * b + a * c;{a: 0.3333333333333333333333333333, b: 1, c: 2};true +a * (b + c) == a * b + a * c;{a: 79228162514264337593543950335, b: 1, c: -1};true +a * (b + c) == a * b + a * c;{a: 3, b: 0.3333333333333333333333333333, c: 0.3333333333333333333333333333};true +a * (b + c) == a * b + a * c;{a: 2.000, b: 7922816251426433759354395033.5, c: -0.75};true +a * (b + c) == a * b + a * c;{a: 100, b: -0.75, c: 18446744073709551616};true +a * (b + c) == a * b + a * c;{a: -9007199254740993, b: 0.25, c: -79228162514264337593543950335};!error +a * (b + c) == a * b + a * c;{a: -79228162514264337593543950335, b: 7922816251426433759354395033.5, c: 2147483647};!error +a * (b + c) == a * b + a * c;{a: 2.5, b: null, c: -0.75};!error +# Precision limit: rounding the partial products (or overflow of one of them) breaks distributivity, so false is intended +a * (b + c) == a * b + a * c;{a: 0.5, b: 0.0000000000000000000000000001, c: 0.0000000000000000000000000001};false +# Property: (a + b) * c == a * c + b * c +(a + b) * c == a * c + b * c;{a: 0.1, b: 0.2, c: 3};true +(a + b) * c == a * c + b * c;{a: -0.75, b: -3.14159, c: -9007199254740993};true +(a + b) * c == a * c + b * c;{a: 79228162514264337593543950335, b: 9223372036854775807, c: 9223372036854775807};!error +(a + b) * c == a * c + b * c;{a: 9223372036854775807, b: 2.5, c: 4294967295};true +(a + b) * c == a * c + b * c;{a: -79228162514264337593543950335, b: 3, c: 0.3333333333333333333333333333};true +(a + b) * c == a * c + b * c;{a: -0.75, b: 0.3333333333333333333333333333, c: 1000000000000};true +(a + b) * c == a * c + b * c;{a: 0.2, b: 0.5, c: -1};true +(a + b) * c == a * c + b * c;{a: 1.0000000000000000000000000001, b: 2.000, c: 0.3333333333333333333333333333};true +(a + b) * c == a * c + b * c;{a: 0.3, b: true, c: 2.5};!error +# Precision limit: rounding the partial products breaks distributivity, so false is intended +(a + b) * c == a * c + b * c;{a: 0.0000000000000000000000000001, b: 0.0000000000000000000000000001, c: 0.5};false +# Property: (a + b) * (a - b) == a * a - b * b +(a + b) * (a - b) == a * a - b * b;{a: 3, b: 2};true +(a + b) * (a - b) == a * a - b * b;{a: 0.1, b: 0.2};true +(a + b) * (a - b) == a * a - b * b;{a: 9223372036854775807, b: 9223372036854775806};!error +(a + b) * (a - b) == a * a - b * b;{a: 2.000, b: 1.10};true +(a + b) * (a - b) == a * a - b * b;{a: 2147483647, b: -2147483649};true +(a + b) * (a - b) == a * a - b * b;{a: 9007199254740993, b: 3};!error +(a + b) * (a - b) == a * a - b * b;{a: 0.5, b: 3.1415926535897932384626433833};true +(a + b) * (a - b) == a * a - b * b;{a: 0.3333333333333333333333333333, b: 0};true +(a + b) * (a - b) == a * a - b * b;{a: 9007199254740993, b: 0.3333333333333333333333333333};!error +(a + b) * (a - b) == a * a - b * b;{a: '5', b: 0.3};!error +# Inverses: add then subtract, multiply then divide +(a + b) - b == a;{a: 0.0000000000000000000000000001, b: 7};true +(a + b) - b == a;{a: 1.005, b: -1.005};true +(a + b) - b == a;{a: -1, b: -9007199254740993};true +(a + b) - b == a;{a: 9007199254740993, b: 12345678901234567890.12345678};true +(a + b) - b == a;{a: 0, b: 0.3333333333333333333333333333};true +(a + b) - b == a;{a: 0.01, b: -0.75};true +(a + b) - b == a;{a: 1.10, b: 7};true +(a + b) - b == a;{a: 0.1, b: null};!error +# Precision limit: a + b is rounded to 28-29 digits so subtracting b does not restore a, false is intended +(a + b) - b == a;{a: 0.0000000000000000000000000001, b: 10};false +(a + b) - b == a;{a: 0.0000000000000000000000000001, b: 8};false +(a + b) - b == a;{a: 0.1, b: 79228162514264337593543950335};false +# Property: (a - b) + b == a +(a - b) + b == a;{a: 0.2, b: 0.1};true +(a - b) + b == a;{a: 1.0000000000000000000000000001, b: -3.14159};true +(a - b) + b == a;{a: -79228162514264337593543950335, b: 2.000};!error +(a - b) + b == a;{a: -1, b: -9223372036854775808};true +(a - b) + b == a;{a: -1, b: 79228162514264337593543950335};!error +(a - b) + b == a;{a: 2147483648, b: 123456789.123456789};true +(a - b) + b == a;{a: 7922816251426433759354395033.5, b: 0};true +(a - b) + b == a;{a: 0.0000000000000000000000000001, b: -3.14159};true +(a - b) + b == a;{a: 2147483648, b: -1};true +(a - b) + b == a;{a: '5', b: 2.5};!error +# Precision limit: a - b is rounded so adding b back does not restore a, false is intended +(a - b) + b == a;{a: -0.0000000000000000000000000001, b: 10};false +# Property: (a / b) * b == a +(a / b) * b == a;{a: 1, b: 8};true +(a / b) * b == a;{a: 10, b: 4};true +(a / b) * b == a;{a: 1, b: 0};!error +(a / b) * b == a;{a: 22, b: 7};true +(a / b) * b == a;{a: 1, b: 1024};true +(a / b) * b == a;{a: 100, b: 0.5};true +(a / b) * b == a;{a: 9223372036854775807, b: -2147483649};true +(a / b) * b == a;{a: 7, b: true};!error +# Precision limit: a / b is rounded to 28 digits so multiplying by b does not restore a, false is intended +(a / b) * b == a;{a: 1, b: 3};false +(a / b) * b == a;{a: 2, b: 3};false +(a / b) * b == a;{a: 1, b: 7};false +# Property: (a * b) / b == a +(a * b) / b == a;{a: 1.005, b: 3};true +(a * b) / b == a;{a: 79228162514264337593543950335, b: 0.5};!error;bug: division overflow returns null instead of an error, so both sides are null or the comparison sees null +(a * b) / b == a;{a: 9223372036854775807, b: 9223372036854775807};!error +(a * b) / b == a;{a: -79228162514264337593543950335, b: 79228162514264337593543950335};!error +(a * b) / b == a;{a: 0.3, b: -9223372036854775808};true +(a * b) / b == a;{a: -9223372036854775808, b: 0.1};true +(a * b) / b == a;{a: 79228162514264337593543950335, b: 12345678901234567890.12345678};!error +(a * b) / b == a;{a: 0, b: 18446744073709551616};true +(a * b) / b == a;{a: 7, b: true};!error +# Precision limit: a * b underflows or is rounded, so dividing by b does not restore a (and for b == 0 the division is null); false is intended +(a * b) / b == a;{a: 0.0000000000000000000000000001, b: 0.5};false +(a * b) / b == a;{a: 7, b: 0};false +# Property: a / b == 1 / (b / a) +a / b == 1 / (b / a);{a: 1, b: 3};true +a / b == 1 / (b / a);{a: 2, b: 4};true +a / b == 1 / (b / a);{a: 1, b: 7};true +a / b == 1 / (b / a);{a: 100, b: -12.5};true +a / b == 1 / (b / a);{a: 79228162514264337593543950335, b: 0.0000000000000000000000000001};!error;bug: division overflow returns null instead of an error, so both sides are null or the comparison sees null +a / b == 1 / (b / a);{a: 0.3, b: 0.25};true +a / b == 1 / (b / a);{a: null, b: 0.25};!error +# Precision limit: two roundings in 1 / (b / a) differ from one rounding in a / b, false is intended +a / b == 1 / (b / a);{a: 3, b: 1};false +a / b == 1 / (b / a);{a: 9007199254740993, b: 0.3333333333333333333333333333};false +a / b == 1 / (b / a);{a: 7922816251426433759354395033.5, b: 123456789.123456789};false +# Property: a / a == 1 +a / a == 1;{a: 2.000};true +a / a == 1;{a: 0.2};true +a / a == 1;{a: 0.25};true +a / a == 1;{a: -0.75};true +a / a == 1;{a: 4294967295};true +a / a == 1;{a: -9007199254740993};true +a / a == 1;{a: 2147483648};true +a / a == 1;{a: 0.3333333333333333333333333333};true +a / a == 1;{a: -79228162514264337593543950335};true +a / a == 1;{a: 0.0000000000000000000000000001};true +a / a == 1;{a: '5'};!error +a / a == 1;{a: true};!error +# Magnitude: abs +abs(a) >= 0;{a: -3.14159};true +abs(a) >= 0;{a: 2.5};true +abs(a) >= 0;{a: 7};true +abs(a) >= 0;{a: 3};true +abs(a) >= 0;{a: 4294967295};true +abs(a) >= 0;{a: 2147483647};true +abs(a) >= 0;{a: 2147483648};true +abs(a) >= 0;{a: 1.0000000000000000000000000001};true +abs(a) >= 0;{a: 7922816251426433759354395033.5};true +abs(a) >= 0;{a: 12345678901234567890.12345678};true +abs(a) >= 0;{a: true};!error +abs(a) >= 0;{a: null};!error +abs(a) == abs(-a);{a: -0.75};true +abs(a) == abs(-a);{a: 1.10};true +abs(a) == abs(-a);{a: -12.5};true +abs(a) == abs(-a);{a: 2.5};true +abs(a) == abs(-a);{a: 2147483647};true +abs(a) == abs(-a);{a: -9223372036854775808};true +abs(a) == abs(-a);{a: 9223372036854775807};true +abs(a) == abs(-a);{a: 0.3333333333333333333333333333};true +abs(a) == abs(-a);{a: -79228162514264337593543950335};true +abs(a) == abs(-a);{a: 79228162514264337593543950335};true +abs(a) == abs(-a);{};!error +abs(a) == abs(-a);{a: '5'};!error +abs(a) == max([a, -a]);{a: 2.5};true +abs(a) == max([a, -a]);{a: 0.25};true +abs(a) == max([a, -a]);{a: 3};true +abs(a) == max([a, -a]);{a: 1.10};true +abs(a) == max([a, -a]);{a: 1000000000000};true +abs(a) == max([a, -a]);{a: 9007199254740993};true +abs(a) == max([a, -a]);{a: 2147483647};true +abs(a) == max([a, -a]);{a: 39614081257132168796771975167};true +abs(a) == max([a, -a]);{a: 0.0000000000000000000000000001};true +abs(a) == max([a, -a]);{a: 1.0000000000000000000000000001};true +abs(a) == max([a, -a]);{a: true};!error +abs(a) == max([a, -a]);{a: null};!error +abs(a) == (a < 0 ? -a : a);{a: 1.005};true +abs(a) == (a < 0 ? -a : a);{a: 0.25};true +abs(a) == (a < 0 ? -a : a);{a: 7};true +abs(a) == (a < 0 ? -a : a);{a: 1};true +abs(a) == (a < 0 ? -a : a);{a: 9223372036854775807};true +abs(a) == (a < 0 ? -a : a);{a: -2147483649};true +abs(a) == (a < 0 ? -a : a);{a: 18446744073709551616};true +abs(a) == (a < 0 ? -a : a);{a: 0.0000000000000000000000000001};true +abs(a) == (a < 0 ? -a : a);{a: -79228162514264337593543950335};true +abs(a) == (a < 0 ? -a : a);{a: -0.0000000000000000000000000001};true +abs(a) == (a < 0 ? -a : a);{};!error +abs(a) == (a < 0 ? -a : a);{a: '5'};!error +string(abs(a)) == string(a < 0 ? -a : a);{a: -2.000};true +string(abs(a)) == string(a < 0 ? -a : a);{a: -1.10};true +string(abs(a)) == string(a < 0 ? -a : a);{a: -1};true +string(abs(a)) == string(a < 0 ? -a : a);{a: 1};true +string(abs(a)) == string(a < 0 ? -a : a);{a: 2.5};true +string(abs(a)) == string(a < 0 ? -a : a);{a: 0.2};true +string(abs(a)) == string(a < 0 ? -a : a);{a: -9223372036854775808};true +string(abs(a)) == string(a < 0 ? -a : a);{a: -9007199254740993};true +string(abs(a)) == string(a < 0 ? -a : a);{a: -2147483649};true +string(abs(a)) == string(a < 0 ? -a : a);{a: 1.0000000000000000000000000001};true +string(abs(a)) == string(a < 0 ? -a : a);{a: 0.0000000000000000000000000001};true +string(abs(a)) == string(a < 0 ? -a : a);{a: 79228162514264337593543950335};true +string(abs(a)) == string(a < 0 ? -a : a);{a: null};!error +string(abs(a)) == string(a < 0 ? -a : a);{a: '5'};!error +abs(a * b) == abs(a) * abs(b);{a: 9007199254740993, b: 0.5};true +abs(a * b) == abs(a) * abs(b);{a: -79228162514264337593543950335, b: 9007199254740993};!error +abs(a * b) == abs(a) * abs(b);{a: 9007199254740992, b: 123456789.123456789};true +abs(a * b) == abs(a) * abs(b);{a: 9223372036854775807, b: 0.25};true +abs(a * b) == abs(a) * abs(b);{a: 3.1415926535897932384626433833, b: 2.5};true +abs(a * b) == abs(a) * abs(b);{a: -1, b: 9223372036854775807};true +abs(a * b) == abs(a) * abs(b);{a: 9223372036854775807, b: 0.5};true +abs(a * b) == abs(a) * abs(b);{a: 0.25, b: -1};true +abs(a * b) == abs(a) * abs(b);{a: -3.14159, b: 1.10};true +abs(a * b) == abs(a) * abs(b);{b: 2.5};!error +abs(a + b) <= abs(a) + abs(b);{a: 79228162514264337593543950335, b: -1};!error +abs(a + b) <= abs(a) + abs(b);{a: -79228162514264337593543950335, b: 1};!error +abs(a + b) <= abs(a) + abs(b);{a: 3, b: -2147483649};true +abs(a + b) <= abs(a) + abs(b);{a: 18446744073709551616, b: -0.0000000000000000000000000001};true +abs(a + b) <= abs(a) + abs(b);{a: 1.0000000000000000000000000001, b: 0};true +abs(a + b) <= abs(a) + abs(b);{a: 0.01, b: 18446744073709551616};true +abs(a + b) <= abs(a) + abs(b);{a: 2.5, b: -3.14159};true +abs(a + b) <= abs(a) + abs(b);{a: 2.000, b: 0.1};true +abs(a + b) <= abs(a) + abs(b);{a: 0.1, b: 79228162514264337593543950335};true +abs(a + b) <= abs(a) + abs(b);{a: true, b: 1};!error +abs(a - b) == abs(b - a);{a: -9223372036854775808, b: 79228162514264337593543950335};!error +abs(a - b) == abs(b - a);{a: 2147483648, b: 7922816251426433759354395033.5};true +abs(a - b) == abs(b - a);{a: 1, b: -9007199254740993};true +abs(a - b) == abs(b - a);{a: 9223372036854775807, b: 4294967295};true +abs(a - b) == abs(b - a);{a: -79228162514264337593543950335, b: 0};true +abs(a - b) == abs(b - a);{a: 1.10, b: 3.1415926535897932384626433833};true +abs(a - b) == abs(b - a);{a: 1.0000000000000000000000000001, b: -1};true +abs(a - b) == abs(b - a);{a: 9223372036854775807, b: 3.1415926535897932384626433833};true +abs(a - b) == abs(b - a);{a: 7922816251426433759354395033.5, b: -9223372036854775808};true +abs(a - b) == abs(b - a);{a: 2.000};!error +a * a >= 0;{a: 2.5};true +a * a >= 0;{a: 3};true +a * a >= 0;{a: 0.1};true +a * a >= 0;{a: 0.2};true +a * a >= 0;{a: 1000000000000};true +a * a >= 0;{a: -9223372036854775808};!error +a * a >= 0;{a: 123456789.123456789};true +a * a >= 0;{a: 39614081257132168796771975167};!error +a * a >= 0;{a: -79228162514264337593543950335};!error +a * a >= 0;{a: 3.1415926535897932384626433833};true +a * a >= 0;{a: true};!error +a * a >= 0;{a: '5'};!error +# floor, ceil and trunc bracket the value +floor(a) <= a and a <= ceil(a);{a: -0.5};true +floor(a) <= a and a <= ceil(a);{a: 0.9999999999999999999999999999};true +floor(a) <= a and a <= ceil(a);{a: 2.000};true +floor(a) <= a and a <= ceil(a);{a: -3.14159};true +floor(a) <= a and a <= ceil(a);{a: 1.005};true +floor(a) <= a and a <= ceil(a);{a: 0.01};true +floor(a) <= a and a <= ceil(a);{a: 9223372036854775807};true +floor(a) <= a and a <= ceil(a);{a: 4294967295};true +floor(a) <= a and a <= ceil(a);{a: 2147483647};true +floor(a) <= a and a <= ceil(a);{a: 39614081257132168796771975167};true +floor(a) <= a and a <= ceil(a);{a: 0};true +floor(a) <= a and a <= ceil(a);{a: -79228162514264337593543950335};true +floor(a) <= a and a <= ceil(a);{a: null};!error +floor(a) <= a and a <= ceil(a);{a: true};!error +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 2.000};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: -0.0000000000000000000000000001};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 2.5};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 1};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 3};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 1.10};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: -9007199254740993};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: -2147483649};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 1000000000000};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 79228162514264337593543950335};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 7922816251426433759354395033.5};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: 39614081257132168796771975167};true +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{};!error +ceil(a) - floor(a) == (a == floor(a) ? 0 : 1);{a: '5'};!error +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: -0.5};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: -2.5};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: 0.2};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: 1};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: -0.75};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: 0.01};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: -9007199254740993};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: 2147483648};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: 9007199254740993};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: -0.0000000000000000000000000001};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: -79228162514264337593543950335};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: 0.0000000000000000000000000001};true +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: true};!error +trunc(a) == (a >= 0 ? floor(a) : ceil(a));{a: '5'};!error +floor(-a) == -ceil(a);{a: 0.01};true +floor(-a) == -ceil(a);{a: 0.3};true +floor(-a) == -ceil(a);{a: 0.5};true +floor(-a) == -ceil(a);{a: -3.14159};true +floor(-a) == -ceil(a);{a: -9007199254740993};true +floor(-a) == -ceil(a);{a: 9223372036854775807};true +floor(-a) == -ceil(a);{a: 2147483648};true +floor(-a) == -ceil(a);{a: 7922816251426433759354395033.5};true +floor(-a) == -ceil(a);{a: 0};true +floor(-a) == -ceil(a);{a: -0.0000000000000000000000000001};true +floor(-a) == -ceil(a);{a: '5'};!error +floor(-a) == -ceil(a);{a: true};!error +ceil(-a) == -floor(a);{a: 0.3};true +ceil(-a) == -floor(a);{a: 7};true +ceil(-a) == -floor(a);{a: 0.2};true +ceil(-a) == -floor(a);{a: 0.25};true +ceil(-a) == -floor(a);{a: -2147483649};true +ceil(-a) == -floor(a);{a: 9223372036854775807};true +ceil(-a) == -floor(a);{a: 9007199254740993};true +ceil(-a) == -floor(a);{a: 1.0000000000000000000000000001};true +ceil(-a) == -floor(a);{a: 0};true +ceil(-a) == -floor(a);{a: 0.0000000000000000000000000001};true +ceil(-a) == -floor(a);{a: null};!error +ceil(-a) == -floor(a);{a: true};!error +floor(a + 1) == floor(a) + 1;{a: -0.0000000000000000000000000001};true +floor(a + 1) == floor(a) + 1;{a: 0.9999999999999999999999999999};true +floor(a + 1) == floor(a) + 1;{a: 0.2};true +floor(a + 1) == floor(a) + 1;{a: 1.005};true +floor(a + 1) == floor(a) + 1;{a: -0.75};true +floor(a + 1) == floor(a) + 1;{a: 100};true +floor(a + 1) == floor(a) + 1;{a: -9223372036854775808};true +floor(a + 1) == floor(a) + 1;{a: 1000000000000};true +floor(a + 1) == floor(a) + 1;{a: -2147483649};true +floor(a + 1) == floor(a) + 1;{a: 12345678901234567890.12345678};true +floor(a + 1) == floor(a) + 1;{a: 3.1415926535897932384626433833};true +floor(a + 1) == floor(a) + 1;{a: 7922816251426433759354395033.5};true +floor(a + 1) == floor(a) + 1;{a: '5'};!error +floor(a + 1) == floor(a) + 1;{a: null};!error +abs(a - trunc(a)) < 1;{a: -1};true +abs(a - trunc(a)) < 1;{a: 1};true +abs(a - trunc(a)) < 1;{a: 3};true +abs(a - trunc(a)) < 1;{a: 0.3};true +abs(a - trunc(a)) < 1;{a: 2147483648};true +abs(a - trunc(a)) < 1;{a: 9007199254740993};true +abs(a - trunc(a)) < 1;{a: -2147483649};true +abs(a - trunc(a)) < 1;{a: 12345678901234567890.12345678};true +abs(a - trunc(a)) < 1;{a: 39614081257132168796771975167};true +abs(a - trunc(a)) < 1;{a: 0.0000000000000000000000000001};true +abs(a - trunc(a)) < 1;{a: true};!error +abs(a - trunc(a)) < 1;{};!error +trunc(a) + (a - trunc(a)) == a;{a: 0.01};true +trunc(a) + (a - trunc(a)) == a;{a: 1};true +trunc(a) + (a - trunc(a)) == a;{a: 0.5};true +trunc(a) + (a - trunc(a)) == a;{a: -12.5};true +trunc(a) + (a - trunc(a)) == a;{a: 18446744073709551616};true +trunc(a) + (a - trunc(a)) == a;{a: 2147483647};true +trunc(a) + (a - trunc(a)) == a;{a: -2147483649};true +trunc(a) + (a - trunc(a)) == a;{a: 7922816251426433759354395033.5};true +trunc(a) + (a - trunc(a)) == a;{a: 0.0000000000000000000000000001};true +trunc(a) + (a - trunc(a)) == a;{a: -79228162514264337593543950335};true +trunc(a) + (a - trunc(a)) == a;{a: '5'};!error +trunc(a) + (a - trunc(a)) == a;{};!error +a % 1 == a - trunc(a);{a: -2.5};true +a % 1 == a - trunc(a);{a: 0.3};true +a % 1 == a - trunc(a);{a: 1.005};true +a % 1 == a - trunc(a);{a: 1};true +a % 1 == a - trunc(a);{a: -0.75};true +a % 1 == a - trunc(a);{a: -9007199254740993};true +a % 1 == a - trunc(a);{a: 9223372036854775807};true +a % 1 == a - trunc(a);{a: 1000000000000};true +a % 1 == a - trunc(a);{a: 12345678901234567890.12345678};true +a % 1 == a - trunc(a);{a: 0.3333333333333333333333333333};true +a % 1 == a - trunc(a);{a: -79228162514264337593543950335};true +a % 1 == a - trunc(a);{a: null};!error +a % 1 == a - trunc(a);{a: true};!error +floor(a) == a - a % 1;{a: 2.5};true +floor(a) == a - a % 1;{a: 0.5};true +floor(a) == a - a % 1;{a: 0.2};true +floor(a) == a - a % 1;{a: 123456789.123456789};true +floor(a) == a - a % 1;{a: 4294967295};true +floor(a) == a - a % 1;{a: 2147483647};true +floor(a) == a - a % 1;{a: 0};true +floor(a) == a - a % 1;{a: 12345678901234567890.12345678};true +floor(a) == a - a % 1;{a: 1.0000000000000000000000000001};true +floor(a) == a - a % 1;{a: true};!error +floor(a) == a - a % 1;{a: '5'};!error +# Negative non-integers: % follows the dividend, so a - a % 1 is trunc(a), not floor(a); false is intended +floor(a) == a - a % 1;{a: -2.5};false +floor(a) == a - a % 1;{a: -0.75};false +floor(a) == a - a % 1;{a: -3.14159};false +# Property: floor(a) == ceil(a) == (a == trunc(a)) +floor(a) == ceil(a) == (a == trunc(a));{a: 5.000};true +floor(a) == ceil(a) == (a == trunc(a));{a: 2.000};true +floor(a) == ceil(a) == (a == trunc(a));{a: -1};true +floor(a) == ceil(a) == (a == trunc(a));{a: 0.1};true +floor(a) == ceil(a) == (a == trunc(a));{a: 2.5};true +floor(a) == ceil(a) == (a == trunc(a));{a: -9223372036854775808};true +floor(a) == ceil(a) == (a == trunc(a));{a: -2147483649};true +floor(a) == ceil(a) == (a == trunc(a));{a: 1000000000000};true +floor(a) == ceil(a) == (a == trunc(a));{a: -79228162514264337593543950335};true +floor(a) == ceil(a) == (a == trunc(a));{a: 0.3333333333333333333333333333};true +floor(a) == ceil(a) == (a == trunc(a));{a: 0.0000000000000000000000000001};true +floor(a) == ceil(a) == (a == trunc(a));{a: '5'};!error +floor(a) == ceil(a) == (a == trunc(a));{a: true};!error +# round: idempotence, symmetry and bounded error +round(round(a, n), n) == round(a, n);{a: 1.005, n: 2};true +round(round(a, n), n) == round(a, n);{a: -3.14159, n: 3};true +round(round(a, n), n) == round(a, n);{a: 123456789.123456789, n: 4};true +round(round(a, n), n) == round(a, n);{a: 2.5, n: 0};true +round(round(a, n), n) == round(a, n);{a: -2.5, n: 0};true +round(round(a, n), n) == round(a, n);{a: 0.0000000000000000000000000001, n: 27};true +round(round(a, n), n) == round(a, n);{a: 0.3333333333333333333333333333, n: 10};true +round(round(a, n), n) == round(a, n);{a: 79228162514264337593543950335, n: 5};true +round(round(a, n), n) == round(a, n);{a: 7922816251426433759354395033.5, n: 0};true +round(round(a, n), n) == round(a, n);{a: null, n: 2};!error +round(round(a, n), n) == round(a, n);{a: 1.005, n: null};!error;"question: null precision fails; could mean the default precision 0" +round(a) == round(a, 0);{a: 2.5};true +round(a) == round(a, 0);{a: -2.5};true +round(a) == round(a, 0);{a: 0.5};true +round(a) == round(a, 0);{a: 0.25};true +round(a) == round(a, 0);{a: 2.000};true +round(a) == round(a, 0);{a: 1.005};true +round(a) == round(a, 0);{a: 9007199254740992};true +round(a) == round(a, 0);{a: -9007199254740993};true +round(a) == round(a, 0);{a: -2147483649};true +round(a) == round(a, 0);{a: 12345678901234567890.12345678};true +round(a) == round(a, 0);{a: 0.3333333333333333333333333333};true +round(a) == round(a, 0);{a: 7922816251426433759354395033.5};true +round(a) == round(a, 0);{};!error +round(a) == round(a, 0);{a: '5'};!error +round(-a) == -round(a);{a: 2.5};true +round(-a) == -round(a);{a: -0.5};true +round(-a) == -round(a);{a: 1.5};true +round(-a) == -round(a);{a: 1};true +round(-a) == -round(a);{a: 0.2};true +round(-a) == -round(a);{a: -3.14159};true +round(-a) == -round(a);{a: 0.3};true +round(-a) == -round(a);{a: 9223372036854775807};true +round(-a) == -round(a);{a: 4294967295};true +round(-a) == -round(a);{a: 18446744073709551616};true +round(-a) == -round(a);{a: 39614081257132168796771975167};true +round(-a) == -round(a);{a: -0.0000000000000000000000000001};true +round(-a) == -round(a);{a: 1.0000000000000000000000000001};true +round(-a) == -round(a);{a: '5'};!error +round(-a) == -round(a);{a: null};!error +round(-a, 2) == -round(a, 2);{a: 1.005};true +round(-a, 2) == -round(a, 2);{a: -1.005};true +round(-a, 2) == -round(a, 2);{a: 0.125};true +round(-a, 2) == -round(a, 2);{a: 0.5};true +round(-a, 2) == -round(a, 2);{a: -1};true +round(-a, 2) == -round(a, 2);{a: 0.3};true +round(-a, 2) == -round(a, 2);{a: 0.2};true +round(-a, 2) == -round(a, 2);{a: 4294967295};true +round(-a, 2) == -round(a, 2);{a: 9007199254740993};true +round(-a, 2) == -round(a, 2);{a: -2147483649};true +round(-a, 2) == -round(a, 2);{a: 39614081257132168796771975167};true +round(-a, 2) == -round(a, 2);{a: 0.3333333333333333333333333333};true +round(-a, 2) == -round(a, 2);{a: 79228162514264337593543950335};true +round(-a, 2) == -round(a, 2);{a: '5'};!error +round(-a, 2) == -round(a, 2);{};!error +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 1.005, n: 2};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: -3.14159, n: 3};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 123456789.123456789, n: 4};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 2.5, n: 0};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 0.3333333333333333333333333333, n: 10};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 0.0000000000000000000000000001, n: 5};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 0.125, n: 2};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: -0.125, n: 2};true +abs(round(a, n) - a) <= 0.5 * 10 ^ -n;{a: 9007199254740993.5, n: 0};true +round(a, 28) == a;{a: 0.5};true +round(a, 28) == a;{a: 2.000};true +round(a, 28) == a;{a: -3.14159};true +round(a, 28) == a;{a: 3};true +round(a, 28) == a;{a: 18446744073709551616};true +round(a, 28) == a;{a: 9223372036854775807};true +round(a, 28) == a;{a: -9223372036854775808};true +round(a, 28) == a;{a: 0.3333333333333333333333333333};true +round(a, 28) == a;{a: 0.0000000000000000000000000001};true +round(a, 28) == a;{a: 12345678901234567890.12345678};true +round(a, 28) == a;{};!error +round(a, 28) == a;{a: true};!error +round(a, 1) == round(round(a, 2), 1);{a: 1.05};true +round(a, 1) == round(round(a, 2), 1);{a: 0.25};true +round(a, 1) == round(round(a, 2), 1);{a: 1.0449};true +round(a, 1) == round(round(a, 2), 1);{a: 7};true +round(a, 1) == round(round(a, 2), 1);{a: 123456789.123456789};true +round(a, 1) == round(round(a, 2), 1);{a: null};!error +# Double rounding: rounding to 2 places first can create a new tie (1.045 -> 1.05 -> 1.1 while round(1.045, 1) is 1.0), false is intended +round(a, 1) == round(round(a, 2), 1);{a: 1.045};false +round(a, 1) == round(round(a, 2), 1);{a: -1.045};false +round(a, 1) == round(round(a, 2), 1);{a: 0.149};false +round(a, 1) == round(round(a, 2), 1);{a: 2.449};false +round(a, 1) == round(round(a, 2), 1);{a: -2.449};false +# Property: a > b or round(a, 2) <= round(b, 2) +a > b or round(a, 2) <= round(b, 2);{a: 1.004, b: 1.005};true +a > b or round(a, 2) <= round(b, 2);{a: -1.005, b: -1.004};true +a > b or round(a, 2) <= round(b, 2);{a: 2.5, b: 2.5};true +a > b or round(a, 2) <= round(b, 2);{a: 0.001, b: 0.009};true +a > b or round(a, 2) <= round(b, 2);{a: 1.0000000000000000000000000001, b: 3};true +a > b or round(a, 2) <= round(b, 2);{a: 0.25, b: 3};true +a > b or round(a, 2) <= round(b, 2);{a: 9007199254740993, b: 9007199254740992};true +a > b or round(a, 2) <= round(b, 2);{a: 1.10, b: 9223372036854775807};true +a > b or round(a, 2) <= round(b, 2);{a: 1, b: 39614081257132168796771975167};true +a > b or round(a, 2) <= round(b, 2);{a: 100, b: 0};true +a > b or round(a, 2) <= round(b, 2);{a: 2.000, b: '5'};!error +a > b or floor(a) <= floor(b);{a: -0.5, b: 0};true +a > b or floor(a) <= floor(b);{a: 0.9, b: 1};true +a > b or floor(a) <= floor(b);{a: 0.1, b: 3.1415926535897932384626433833};true +a > b or floor(a) <= floor(b);{a: 0.2, b: 2.5};true +a > b or floor(a) <= floor(b);{a: 12345678901234567890.12345678, b: 2147483647};true +a > b or floor(a) <= floor(b);{a: 9007199254740993, b: 39614081257132168796771975167};true +a > b or floor(a) <= floor(b);{a: 9007199254740992, b: -9007199254740993};true +a > b or floor(a) <= floor(b);{a: -9007199254740993, b: -2147483649};true +a > b or floor(a) <= floor(b);{a: -2147483649, b: -9007199254740993};true +a > b or floor(a) <= floor(b);{a: 0.25, b: null};!error +a > b or ceil(a) <= ceil(b);{a: -0.5, b: 0};true +a > b or ceil(a) <= ceil(b);{a: 0.9, b: 1};true +a > b or ceil(a) <= ceil(b);{a: -9007199254740993, b: 0};true +a > b or ceil(a) <= ceil(b);{a: 0, b: 1.0000000000000000000000000001};true +a > b or ceil(a) <= ceil(b);{a: -9223372036854775808, b: -1};true +a > b or ceil(a) <= ceil(b);{a: 2147483647, b: 9007199254740993};true +a > b or ceil(a) <= ceil(b);{a: 0.3333333333333333333333333333, b: 79228162514264337593543950335};true +a > b or ceil(a) <= ceil(b);{a: 7922816251426433759354395033.5, b: 7922816251426433759354395033.5};true +a > b or ceil(a) <= ceil(b);{a: 1000000000000, b: -2147483649};true +a > b or ceil(a) <= ceil(b);{a: 0.25, b: '5'};!error +a > b or trunc(a) <= trunc(b);{a: -1.5, b: -0.5};true +a > b or trunc(a) <= trunc(b);{a: 7922816251426433759354395033.5, b: 79228162514264337593543950335};true +a > b or trunc(a) <= trunc(b);{a: 9223372036854775807, b: 9007199254740992};true +a > b or trunc(a) <= trunc(b);{a: 123456789.123456789, b: 0.01};true +a > b or trunc(a) <= trunc(b);{a: -0.75, b: 4294967295};true +a > b or trunc(a) <= trunc(b);{a: 9223372036854775807, b: -1};true +a > b or trunc(a) <= trunc(b);{a: 3.1415926535897932384626433833, b: 2.000};true +a > b or trunc(a) <= trunc(b);{a: 2147483647, b: 0.25};true +a > b or trunc(a) <= trunc(b);{a: 3.1415926535897932384626433833, b: -2147483649};true +a > b or trunc(a) <= trunc(b);{a: true, b: -1};!error +a > b or round(a) <= round(b);{a: -0.5, b: -0.4};true +a > b or round(a) <= round(b);{a: 0.4, b: 0.5};true +a > b or round(a) <= round(b);{a: -3.14159, b: 79228162514264337593543950335};true +a > b or round(a) <= round(b);{a: 9223372036854775807, b: -3.14159};true +a > b or round(a) <= round(b);{a: 0.1, b: 0.1};true +a > b or round(a) <= round(b);{a: 0.2, b: 2147483647};true +a > b or round(a) <= round(b);{a: 12345678901234567890.12345678, b: 1.10};true +a > b or round(a) <= round(b);{a: 0.2, b: 1.0000000000000000000000000001};true +a > b or round(a) <= round(b);{a: -1, b: -1};true +a > b or round(a) <= round(b);{a: true, b: 0.25};!error +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 1.999};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: -1.999};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 1.005};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 0.25};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 2.000};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: -3.14159};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 18446744073709551616};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 1000000000000};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 2147483648};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 12345678901234567890.12345678};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 0.3333333333333333333333333333};true +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: 79228162514264337593543950335};!error +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{};!error +trunc(a, 2) == (a >= 0 ? floor(a * 100) / 100 : ceil(a * 100) / 100);{a: true};!error +round(a, 2) == round(a * 100) / 100;{a: 1.005};true +round(a, 2) == round(a * 100) / 100;{a: -1.005};true +round(a, 2) == round(a * 100) / 100;{a: 2.675};true +round(a, 2) == round(a * 100) / 100;{a: -0.75};true +round(a, 2) == round(a * 100) / 100;{a: -3.14159};true +round(a, 2) == round(a * 100) / 100;{a: -12.5};true +round(a, 2) == round(a * 100) / 100;{a: 1000000000000};true +round(a, 2) == round(a * 100) / 100;{a: 9007199254740992};true +round(a, 2) == round(a * 100) / 100;{a: 9007199254740993};true +round(a, 2) == round(a * 100) / 100;{a: 0};true +round(a, 2) == round(a * 100) / 100;{a: 0.0000000000000000000000000001};true +round(a, 2) == round(a * 100) / 100;{a: 79228162514264337593543950335};!error +round(a, 2) == round(a * 100) / 100;{a: '5'};!error +round(a, 2) == round(a * 100) / 100;{};!error +# Remainder: range, sign and the division identity +abs(a % b) < abs(b);{a: 7, b: 3};true +abs(a % b) < abs(b);{a: -7, b: 3};true +abs(a % b) < abs(b);{a: 7, b: -3};true +abs(a % b) < abs(b);{a: 5.5, b: 2};true +abs(a % b) < abs(b);{a: 79228162514264337593543950335, b: 7};true +abs(a % b) < abs(b);{a: 1, b: 0.0000000000000000000000000001};true +abs(a % b) < abs(b);{a: 9007199254740992, b: 12345678901234567890.12345678};true +abs(a % b) < abs(b);{a: 3.1415926535897932384626433833, b: 1.0000000000000000000000000001};true +abs(a % b) < abs(b);{a: 9007199254740993, b: 1.10};true +abs(a % b) < abs(b);{a: 1.10, b: -2147483649};true +abs(a % b) < abs(b);{a: 2.5, b: '5'};!error +a % b == 0 or (a % b > 0) == (a > 0);{a: -7, b: 3};true +a % b == 0 or (a % b > 0) == (a > 0);{a: 7, b: -3};true +a % b == 0 or (a % b > 0) == (a > 0);{a: -7, b: -3};true +a % b == 0 or (a % b > 0) == (a > 0);{a: -5.5, b: 2};true +a % b == 0 or (a % b > 0) == (a > 0);{a: -79228162514264337593543950335, b: 10};true +a % b == 0 or (a % b > 0) == (a > 0);{a: 18446744073709551616, b: 79228162514264337593543950335};true +a % b == 0 or (a % b > 0) == (a > 0);{a: 9223372036854775807, b: -9223372036854775808};true +a % b == 0 or (a % b > 0) == (a > 0);{a: 9223372036854775807, b: 1.0000000000000000000000000001};true +a % b == 0 or (a % b > 0) == (a > 0);{a: 0.1, b: -3.14159};true +a % b == 0 or (a % b > 0) == (a > 0);{a: 0.01, b: 2147483648};true +a % b == 0 or (a % b > 0) == (a > 0);{a: '5', b: 0.2};!error +trunc(a / b) * b + a % b == a;{a: 7, b: 3};true +trunc(a / b) * b + a % b == a;{a: -7, b: 3};true +trunc(a / b) * b + a % b == a;{a: 7.25, b: 0.5};true +trunc(a / b) * b + a % b == a;{a: 10, b: 0.3};true +trunc(a / b) * b + a % b == a;{a: 1, b: 0.3333333333333333333333333333};true +trunc(a / b) * b + a % b == a;{a: 79228162514264337593543950335, b: 3};true +trunc(a / b) * b + a % b == a;{a: 1, b: 3};true +trunc(a / b) * b + a % b == a;{a: 0.25, b: 2147483648};true +trunc(a / b) * b + a % b == a;{a: 4294967295, b: 2.5};true +trunc(a / b) * b + a % b == a;{a: 0.3333333333333333333333333333, b: -0.0000000000000000000000000001};true +trunc(a / b) * b + a % b == a;{a: '5', b: 0.3};!error +(a + b) % b == a % b;{a: 1, b: 3};true +(a + b) % b == a % b;{a: 0.5, b: 1};true +(a + b) % b == a % b;{a: 79228162514264337593543950335, b: 0.25};true +(a + b) % b == a % b;{a: 4294967295, b: 1000000000000};true +(a + b) % b == a % b;{a: -1, b: 0};true +(a + b) % b == a % b;{a: -9007199254740993, b: 123456789.123456789};true +(a + b) % b == a % b;{a: 9223372036854775807, b: 2147483648};true +(a + b) % b == a % b;{a: 1.10, b: '5'};!error +# The remainder takes the dividend's sign, so shifting a across zero changes the result (or a + b is rounded at 28 digits); false is intended +(a + b) % b == a % b;{a: -1, b: 3};false +(a + b) % b == a % b;{a: 3.1415926535897932384626433833, b: 12345678901234567890.12345678};false +# Property: a % b == a % -b +a % b == a % -b;{a: 7, b: 3};true +a % b == a % -b;{a: -7, b: 3};true +a % b == a % -b;{a: 100, b: 0.25};true +a % b == a % -b;{a: 18446744073709551616, b: 0};true +a % b == a % -b;{a: 0.5, b: 18446744073709551616};true +a % b == a % -b;{a: 1.10, b: 2147483647};true +a % b == a % -b;{a: 79228162514264337593543950335, b: 123456789.123456789};true +a % b == a % -b;{a: 2147483647, b: 2.000};true +a % b == a % -b;{a: 100, b: 2.5};true +a % b == a % -b;{b: 0.3};!error +-a % b == -(a % b);{a: 7, b: 3};true +-a % b == -(a % b);{a: 5.5, b: 2};true +-a % b == -(a % b);{a: -79228162514264337593543950335, b: 9223372036854775807};true +-a % b == -(a % b);{a: 1.005, b: -79228162514264337593543950335};true +-a % b == -(a % b);{a: 3, b: 0.2};true +-a % b == -(a % b);{a: 12345678901234567890.12345678, b: -9007199254740993};true +-a % b == -(a % b);{a: -9007199254740993, b: 9223372036854775807};true +-a % b == -(a % b);{a: -0.0000000000000000000000000001, b: 2147483648};true +-a % b == -(a % b);{a: 2147483648, b: -2147483649};true +-a % b == -(a % b);{b: 0.3};!error +# min and max agree with the ordering operators +min([a, b]) <= max([a, b]);{a: 18446744073709551616, b: 3};true +min([a, b]) <= max([a, b]);{a: 1.005, b: -3.14159};true +min([a, b]) <= max([a, b]);{a: 0.3333333333333333333333333333, b: 3.1415926535897932384626433833};true +min([a, b]) <= max([a, b]);{a: 0.25, b: -79228162514264337593543950335};true +min([a, b]) <= max([a, b]);{a: 2147483647, b: 1000000000000};true +min([a, b]) <= max([a, b]);{a: 1.0000000000000000000000000001, b: 0.5};true +min([a, b]) <= max([a, b]);{a: -1, b: 9007199254740993};true +min([a, b]) <= max([a, b]);{a: 2147483648, b: 0.3333333333333333333333333333};true +min([a, b]) <= max([a, b]);{a: 0.3, b: 1000000000000};true +min([a, b]) <= max([a, b]);{a: '5', b: 1};!error +min([a, b]) == (a < b ? a : b);{a: 2147483647, b: 0.1};true +min([a, b]) == (a < b ? a : b);{a: 0.0000000000000000000000000001, b: 1};true +min([a, b]) == (a < b ? a : b);{a: 1.10, b: 7};true +min([a, b]) == (a < b ? a : b);{a: 3, b: 7};true +min([a, b]) == (a < b ? a : b);{a: 18446744073709551616, b: 2.000};true +min([a, b]) == (a < b ? a : b);{a: -2147483649, b: 1.0000000000000000000000000001};true +min([a, b]) == (a < b ? a : b);{a: 0, b: 9223372036854775807};true +min([a, b]) == (a < b ? a : b);{a: 0.3, b: -2147483649};true +min([a, b]) == (a < b ? a : b);{a: 1.005, b: -2147483649};true +min([a, b]) == (a < b ? a : b);{a: 0.25, b: null};!error +max([a, b]) == (a > b ? a : b);{a: -9007199254740993, b: 3.1415926535897932384626433833};true +max([a, b]) == (a > b ? a : b);{a: -9007199254740993, b: -12.5};true +max([a, b]) == (a > b ? a : b);{a: 79228162514264337593543950335, b: 0.01};true +max([a, b]) == (a > b ? a : b);{a: 0, b: 0};true +max([a, b]) == (a > b ? a : b);{a: -9007199254740993, b: 9007199254740993};true +max([a, b]) == (a > b ? a : b);{a: -0.75, b: -2147483649};true +max([a, b]) == (a > b ? a : b);{a: 1.005, b: 0.3333333333333333333333333333};true +max([a, b]) == (a > b ? a : b);{a: 0.1, b: -12.5};true +max([a, b]) == (a > b ? a : b);{a: 9223372036854775807, b: 9007199254740993};true +max([a, b]) == (a > b ? a : b);{a: 0.01, b: '5'};!error +min([a, b]) + max([a, b]) == a + b;{a: 79228162514264337593543950335, b: 1};!error +min([a, b]) + max([a, b]) == a + b;{a: 0.5, b: 12345678901234567890.12345678};true +min([a, b]) + max([a, b]) == a + b;{a: 2147483647, b: 9223372036854775807};true +min([a, b]) + max([a, b]) == a + b;{a: 1000000000000, b: 0.3333333333333333333333333333};true +min([a, b]) + max([a, b]) == a + b;{a: 2147483648, b: -2147483649};true +min([a, b]) + max([a, b]) == a + b;{a: 1.0000000000000000000000000001, b: 7922816251426433759354395033.5};true +min([a, b]) + max([a, b]) == a + b;{a: 0.3, b: 3};true +min([a, b]) + max([a, b]) == a + b;{a: 1000000000000, b: 0.5};true +min([a, b]) + max([a, b]) == a + b;{a: 2147483648, b: 0.01};true +min([a, b]) + max([a, b]) == a + b;{a: -1, b: null};!error +max([a, b]) - min([a, b]) == abs(a - b);{a: 79228162514264337593543950335, b: -1};!error +max([a, b]) - min([a, b]) == abs(a - b);{a: 0.5, b: 100};true +max([a, b]) - min([a, b]) == abs(a - b);{a: 1, b: 0.0000000000000000000000000001};true +max([a, b]) - min([a, b]) == abs(a - b);{a: 100, b: -3.14159};true +max([a, b]) - min([a, b]) == abs(a - b);{a: -12.5, b: 0};true +max([a, b]) - min([a, b]) == abs(a - b);{a: 1, b: 0.3333333333333333333333333333};true +max([a, b]) - min([a, b]) == abs(a - b);{a: 79228162514264337593543950335, b: 1.10};true +max([a, b]) - min([a, b]) == abs(a - b);{a: 2.000, b: 123456789.123456789};true +max([a, b]) - min([a, b]) == abs(a - b);{a: -2147483649, b: 79228162514264337593543950335};!error +max([a, b]) - min([a, b]) == abs(a - b);{a: 0.2};!error +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 123456789.123456789, b: 2147483647, c: 4294967295};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: -9007199254740993, b: -12.5, c: -3.14159};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 7, b: 123456789.123456789, c: 9223372036854775807};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 7, b: 0.3, c: 1.005};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: -0.75, b: 0.5, c: 7};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: -0.75, b: 0.1, c: 9007199254740992};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 0.3333333333333333333333333333, b: 1, c: 39614081257132168796771975167};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 2.000, b: 2.000, c: 0.0000000000000000000000000001};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 0.0000000000000000000000000001, b: 1, c: 2.5};true +max([a, b, c]) >= a and max([a, b, c]) >= b and max([a, b, c]) >= c;{a: 0.3, c: -3.14159};!error +min([a, b, c]) == min([min([a, b]), c]);{a: 1.0000000000000000000000000001, b: -79228162514264337593543950335, c: 4294967295};true +min([a, b, c]) == min([min([a, b]), c]);{a: 0.25, b: 7922816251426433759354395033.5, c: 100};true +min([a, b, c]) == min([min([a, b]), c]);{a: -12.5, b: 39614081257132168796771975167, c: 0.0000000000000000000000000001};true +min([a, b, c]) == min([min([a, b]), c]);{a: 18446744073709551616, b: 3, c: 9007199254740992};true +min([a, b, c]) == min([min([a, b]), c]);{a: 0.01, b: 0.25, c: 0.0000000000000000000000000001};true +min([a, b, c]) == min([min([a, b]), c]);{a: 0.25, b: -79228162514264337593543950335, c: 0.2};true +min([a, b, c]) == min([min([a, b]), c]);{a: 123456789.123456789, b: -0.0000000000000000000000000001, c: 0};true +min([a, b, c]) == min([min([a, b]), c]);{a: 0.2, b: 3, c: 3.1415926535897932384626433833};true +min([a, b, c]) == min([min([a, b]), c]);{a: 1.0000000000000000000000000001, b: -3.14159, c: 7922816251426433759354395033.5};true +min([a, b, c]) == min([min([a, b]), c]);{a: 100, b: true, c: -1};!error +max([a, b, c]) == -min([-a, -b, -c]);{a: -1, b: 7, c: -0.0000000000000000000000000001};true +max([a, b, c]) == -min([-a, -b, -c]);{a: 18446744073709551616, b: -3.14159, c: -79228162514264337593543950335};true +max([a, b, c]) == -min([-a, -b, -c]);{a: -12.5, b: -0.0000000000000000000000000001, c: -2147483649};true +max([a, b, c]) == -min([-a, -b, -c]);{a: 0.3333333333333333333333333333, b: -1, c: 9007199254740993};true +max([a, b, c]) == -min([-a, -b, -c]);{a: 0, b: 0.25, c: -0.0000000000000000000000000001};true +max([a, b, c]) == -min([-a, -b, -c]);{a: 0.5, b: 79228162514264337593543950335, c: 7922816251426433759354395033.5};true +max([a, b, c]) == -min([-a, -b, -c]);{a: 18446744073709551616, b: 0.5, c: 2.000};true +max([a, b, c]) == -min([-a, -b, -c]);{a: 1, b: 9223372036854775807, c: -12.5};true +max([a, b, c]) == -min([-a, -b, -c]);{a: -79228162514264337593543950335, b: 0.01, c: 2.000};true +max([a, b, c]) == -min([-a, -b, -c]);{a: -0.75, b: '5', c: 0.5};!error +# sum and avg against + chains +sum([a, b]) == a + b;{a: 79228162514264337593543950335, b: -1};true +sum([a, b]) == a + b;{a: 18446744073709551616, b: 79228162514264337593543950335};!error +sum([a, b]) == a + b;{a: 2147483648, b: 0.3333333333333333333333333333};true +sum([a, b]) == a + b;{a: 0.1, b: 7922816251426433759354395033.5};true +sum([a, b]) == a + b;{a: 9223372036854775807, b: 2.000};true +sum([a, b]) == a + b;{a: 0, b: 79228162514264337593543950335};true +sum([a, b]) == a + b;{a: 1.10, b: 1.0000000000000000000000000001};true +sum([a, b]) == a + b;{a: 9007199254740993, b: 9223372036854775807};true +sum([a, b]) == a + b;{a: 2.000, b: 7};true +sum([a, b]) == a + b;{a: null, b: 0.5};!error +sum([a, b, c]) == a + b + c;{a: 0.0000000000000000000000000001, b: 10, c: -10};true +sum([a, b, c]) == a + b + c;{a: -0.75, b: 0.0000000000000000000000000001, c: 0.5};true +sum([a, b, c]) == a + b + c;{a: 1.0000000000000000000000000001, b: 0.01, c: 0};true +sum([a, b, c]) == a + b + c;{a: 123456789.123456789, b: 0.2, c: -9007199254740993};true +sum([a, b, c]) == a + b + c;{a: 2147483648, b: -12.5, c: -9007199254740993};true +sum([a, b, c]) == a + b + c;{a: 0, b: -9007199254740993, c: 0.0000000000000000000000000001};true +sum([a, b, c]) == a + b + c;{a: 2147483648, b: 3.1415926535897932384626433833, c: -0.75};true +sum([a, b, c]) == a + b + c;{a: 0.25, b: 12345678901234567890.12345678, c: -0.75};true +sum([a, b, c]) == a + b + c;{a: 2.5, b: 0.1, c: 4294967295};true +sum([a, b, c]) == a + b + c;{a: 0.1, b: true, c: 3};!error +string(sum([a, b, c])) == string(a + b + c);{a: 1.10, b: 2.000, c: 3};true +string(sum([a, b, c])) == string(a + b + c);{a: 0.5, b: 0.5, c: 1};true +string(sum([a, b, c])) == string(a + b + c);{a: 2.5, b: -2147483649, c: 79228162514264337593543950335};true +string(sum([a, b, c])) == string(a + b + c);{a: -3.14159, b: 4294967295, c: 1.0000000000000000000000000001};true +string(sum([a, b, c])) == string(a + b + c);{a: 9007199254740993, b: -0.75, c: 1.0000000000000000000000000001};true +string(sum([a, b, c])) == string(a + b + c);{a: -12.5, b: 9223372036854775807, c: 39614081257132168796771975167};true +string(sum([a, b, c])) == string(a + b + c);{a: 0.3, b: -2147483649, c: 0.25};true +string(sum([a, b, c])) == string(a + b + c);{a: 2147483647, b: -1, c: 2.000};true +string(sum([a, b, c])) == string(a + b + c);{a: -9223372036854775808, b: 3.1415926535897932384626433833, c: 0.5};true +string(sum([a, b, c])) == string(a + b + c);{a: 2.5, c: 100};!error +sum([a, b, c]) == sum([c, b, a]);{a: 79228162514264337593543950335, b: 1, c: -1};!error +sum([a, b, c]) == sum([c, b, a]);{a: 0.3333333333333333333333333333, b: 39614081257132168796771975167, c: 3};true +sum([a, b, c]) == sum([c, b, a]);{a: 100, b: 0.25, c: 1};true +sum([a, b, c]) == sum([c, b, a]);{a: -1, b: -79228162514264337593543950335, c: -12.5};!error +sum([a, b, c]) == sum([c, b, a]);{a: 0.3, b: 1.10, c: -3.14159};true +sum([a, b, c]) == sum([c, b, a]);{a: 0.1, b: 0.0000000000000000000000000001, c: 3};true +sum([a, b, c]) == sum([c, b, a]);{a: -9007199254740993, b: 9007199254740992, c: 9007199254740992};true +sum([a, b, c]) == sum([c, b, a]);{a: 2147483648, b: -0.75, c: -3.14159};true +sum([a, b, c]) == sum([c, b, a]);{a: 1.005, c: -1};!error +# Precision limit or running-total overflow: summation order changes the rounding, false is intended +sum([a, b, c]) == sum([c, b, a]);{a: 0.0000000000000000000000000001, b: 10, c: -10};false +# Property: avg([a, b]) == (a + b) / 2 +avg([a, b]) == (a + b) / 2;{a: 1, b: 2};true +avg([a, b]) == (a + b) / 2;{a: 0.1, b: 0.2};true +avg([a, b]) == (a + b) / 2;{a: 1, b: -9223372036854775808};true +avg([a, b]) == (a + b) / 2;{a: 3.1415926535897932384626433833, b: 9223372036854775807};true +avg([a, b]) == (a + b) / 2;{a: 0.2, b: 7922816251426433759354395033.5};true +avg([a, b]) == (a + b) / 2;{a: 2.5, b: -9007199254740993};true +avg([a, b]) == (a + b) / 2;{a: 0.3333333333333333333333333333, b: 0.0000000000000000000000000001};true +avg([a, b]) == (a + b) / 2;{a: 0.0000000000000000000000000001, b: 0.0000000000000000000000000001};true +avg([a, b]) == (a + b) / 2;{a: -3.14159, b: 2.5};true +avg([a, b]) == (a + b) / 2;{a: 7};!error +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 1, b: 1, c: 2};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 123456789.123456789, b: -9223372036854775808, c: 3};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 7922816251426433759354395033.5, b: 18446744073709551616, c: 3};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 3.1415926535897932384626433833, b: -9223372036854775808, c: 1000000000000};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 123456789.123456789, b: 0.1, c: 12345678901234567890.12345678};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 2.5, b: -1, c: -9223372036854775808};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 7, b: 0.25, c: 7922816251426433759354395033.5};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 1, b: 123456789.123456789, c: 100};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 123456789.123456789, b: 0.0000000000000000000000000001, c: 2.5};true +avg([a, b, c]) == sum([a, b, c]) / 3;{a: 0.1, b: true, c: 1.10};!error +avg([a, a]) == a;{a: -3.14159};true +avg([a, a]) == a;{a: 0.3333333333333333333333333333};true +avg([a, a]) == a;{a: 79228162514264337593543950335};true;bug: the mean is representable but the intermediate sum overflows +avg([a, a]) == a;{a: -79228162514264337593543950335};true;bug: the mean is representable but the intermediate sum overflows +avg([a, a]) == a;{a: 2.000};true +avg([a, a]) == a;{a: 2.5};true +avg([a, a]) == a;{a: 0.01};true +avg([a, a]) == a;{a: 100};true +avg([a, a]) == a;{a: 9007199254740992};true +avg([a, a]) == a;{a: 2147483647};true +avg([a, a]) == a;{a: 9007199254740993};true +avg([a, a]) == a;{a: 12345678901234567890.12345678};true +avg([a, a]) == a;{a: 0.0000000000000000000000000001};true +avg([a, a]) == a;{a: true};!error +avg([a, a]) == a;{a: null};!error +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 0.0000000000000000000000000001, b: 0};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 1, b: 0.0000000000000000000000000003};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 0.0000000000000000000000000001, b: 7922816251426433759354395033.5};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 2.000, b: 1000000000000};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: -12.5, b: 0.25};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: -12.5, b: 2147483647};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 1.0000000000000000000000000001, b: 79228162514264337593543950335};!error +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 18446744073709551616, b: 123456789.123456789};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{a: 0.0000000000000000000000000001, b: 0.3333333333333333333333333333};true +min([a, b]) <= avg([a, b]) and avg([a, b]) <= max([a, b]);{b: 0.01};!error +# avg(xs) against sum(xs) / len(xs) over list inputs +avg(xs) == sum(xs) / len(xs);{xs: [1, 2, 3]};true +avg(xs) == sum(xs) / len(xs);{xs: [0.1, 0.2, 0.3]};true +avg(xs) == sum(xs) / len(xs);{xs: [1.005, -3.14159, 2.5]};true +avg(xs) == sum(xs) / len(xs);{xs: [1, 2]};true +avg(xs) == sum(xs) / len(xs);{xs: [7]};true +avg(xs) == sum(xs) / len(xs);{xs: [1, 1, 1, 2]};true +avg(xs) == sum(xs) / len(xs);{xs: [0.0000000000000000000000000001, 0]};true +avg(xs) == sum(xs) / len(xs);{xs: [9223372036854775807, 9223372036854775807]};true +avg(xs) == sum(xs) / len(xs);{xs: [123456789.123456789, 0.000000001]};true +avg(xs) == sum(xs) / len(xs);{xs: [-1, 1]};true +avg(xs) == sum(xs) / len(xs);{xs: []};!error +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [1, 2, 3]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [0.1, 0.2, 0.3]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [1.005, -3.14159, 2.5]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [1, 2]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [7]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [1, 1, 1, 2]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [0.0000000000000000000000000001, 0]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [9223372036854775807, 9223372036854775807]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [123456789.123456789, 0.000000001]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: [-1, 1]};true +sum(map(xs, # * 2)) == sum(xs) * 2;{xs: []};true +sum(map(xs, -#)) == -sum(xs);{xs: [1, 2, 3]};true +sum(map(xs, -#)) == -sum(xs);{xs: [0.1, 0.2, 0.3]};true +sum(map(xs, -#)) == -sum(xs);{xs: [1.005, -3.14159, 2.5]};true +sum(map(xs, -#)) == -sum(xs);{xs: [1, 2]};true +sum(map(xs, -#)) == -sum(xs);{xs: [7]};true +sum(map(xs, -#)) == -sum(xs);{xs: [1, 1, 1, 2]};true +sum(map(xs, -#)) == -sum(xs);{xs: [0.0000000000000000000000000001, 0]};true +sum(map(xs, -#)) == -sum(xs);{xs: [9223372036854775807, 9223372036854775807]};true +sum(map(xs, -#)) == -sum(xs);{xs: [123456789.123456789, 0.000000001]};true +sum(map(xs, -#)) == -sum(xs);{xs: [-1, 1]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [1, 2, 3]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [0.1, 0.2, 0.3]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [1.005, -3.14159, 2.5]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [1, 2]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [7]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [1, 1, 1, 2]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [0.0000000000000000000000000001, 0]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [9223372036854775807, 9223372036854775807]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [123456789.123456789, 0.000000001]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: [-1, 1]};true +min(xs) <= avg(xs) and avg(xs) <= max(xs);{xs: []};!error +# Round trips between numbers and strings +number(string(a)) == a;{a: 2.000};true +number(string(a)) == a;{a: -1.10};true +number(string(a)) == a;{a: 7};true +number(string(a)) == a;{a: -12.5};true +number(string(a)) == a;{a: -1};true +number(string(a)) == a;{a: 0.25};true +number(string(a)) == a;{a: -9007199254740993};true +number(string(a)) == a;{a: 9007199254740992};true +number(string(a)) == a;{a: 123456789.123456789};true +number(string(a)) == a;{a: 3.1415926535897932384626433833};true +number(string(a)) == a;{a: 12345678901234567890.12345678};true +number(string(a)) == a;{a: 0};true +number(string(a)) == a;{a: '5'};false +string(number(string(a))) == string(a);{a: 2.000};true +string(number(string(a))) == string(a);{a: -1.10};true +string(number(string(a))) == string(a);{a: 0.0000000000000000000000000001};true +string(number(string(a))) == string(a);{a: 1};true +string(number(string(a))) == string(a);{a: 3};true +string(number(string(a))) == string(a);{a: -1};true +string(number(string(a))) == string(a);{a: 1.10};true +string(number(string(a))) == string(a);{a: -9007199254740993};true +string(number(string(a))) == string(a);{a: 2147483648};true +string(number(string(a))) == string(a);{a: 18446744073709551616};true +string(number(string(a))) == string(a);{a: -0.0000000000000000000000000001};true +string(number(string(a))) == string(a);{a: -79228162514264337593543950335};true +string(number(string(a))) == string(a);{a: 79228162514264337593543950335};true +string(number(string(a))) == string(a);{a: null};!error +isNumeric(string(a));{a: 2.000};true +isNumeric(string(a));{a: 0.01};true +isNumeric(string(a));{a: 0.25};true +isNumeric(string(a));{a: 0.2};true +isNumeric(string(a));{a: 1};true +isNumeric(string(a));{a: 9007199254740992};true +isNumeric(string(a));{a: 2147483648};true +isNumeric(string(a));{a: 9007199254740993};true +isNumeric(string(a));{a: 39614081257132168796771975167};true +isNumeric(string(a));{a: -79228162514264337593543950335};true +isNumeric(string(a));{a: 1.0000000000000000000000000001};true +isNumeric(string(a));{a: '5'};true +isNumeric(string(a));{a: null};false +isNumeric(string(a));{};false +number(string(a) + '0') == a;{a: 1.5};true +number(string(a) + '0') == a;{a: 0.25};true +number(string(a) + '0') == a;{a: -3.14159};true +number(string(a) + '0') == a;{a: 1.10};true +number(string(a) + '0') == a;{a: 123456789.123456789};true +number(string(a) + '0') == a;{a: 0};true +number(string(a) + '0') == a;{a: null};!error +# Integers: appending '0' multiplies by ten, so false is intended +number(string(a) + '0') == a;{a: 7};false +number(string(a) + '0') == a;{a: 100};false +# Property: string(number(s)) == s +string(number(s)) == s;{s: '0.10'};true +string(number(s)) == s;{s: '1.500'};true +string(number(s)) == s;{s: '-2.25'};true +string(number(s)) == s;{s: '123456789.123456789'};true +string(number(s)) == s;{s: '79228162514264337593543950335'};true +string(number(s)) == s;{s: '0.0000000000000000000000000001'};true +string(number(s)) == s;{s: '2147483648'};true +string(number(s)) == s;{s: '-9223372036854775809'};true +string(number(s)) == s;{s: '0.0'};true +string(number(s)) == s;{s: '100'};true +string(number(s)) == s;{s: 'abc'};!error +# Non-canonical spellings (leading zeros, exponent) normalize, so false is intended +string(number(s)) == s;{s: '007'};false +string(number(s)) == s;{s: '1e3'};false +# Scale matrix: string(a + b) over fractional-digit counts 0 to 6 +# Scale matrix for string(a + b) +string(a + b);{a: 1, b: 1};'2' +string(a + b);{a: 1, b: 1.5};'2.5' +string(a + b);{a: 1, b: 1.25};'2.25' +string(a + b);{a: 1, b: 1.125};'2.125' +string(a + b);{a: 1, b: 1.0625};'2.0625' +string(a + b);{a: 1, b: 1.03125};'2.03125' +string(a + b);{a: 1, b: 1.015625};'2.015625' +string(a + b);{a: 1.5, b: 1};'2.5' +string(a + b);{a: 1.5, b: 1.5};'3.0' +string(a + b);{a: 1.5, b: 1.25};'2.75' +string(a + b);{a: 1.5, b: 1.125};'2.625' +string(a + b);{a: 1.5, b: 1.0625};'2.5625' +string(a + b);{a: 1.5, b: 1.03125};'2.53125' +string(a + b);{a: 1.5, b: 1.015625};'2.515625' +string(a + b);{a: 1.25, b: 1};'2.25' +string(a + b);{a: 1.25, b: 1.5};'2.75' +string(a + b);{a: 1.25, b: 1.25};'2.50' +string(a + b);{a: 1.25, b: 1.125};'2.375' +string(a + b);{a: 1.25, b: 1.0625};'2.3125' +string(a + b);{a: 1.25, b: 1.03125};'2.28125' +string(a + b);{a: 1.25, b: 1.015625};'2.265625' +string(a + b);{a: 1.125, b: 1};'2.125' +string(a + b);{a: 1.125, b: 1.5};'2.625' +string(a + b);{a: 1.125, b: 1.25};'2.375' +string(a + b);{a: 1.125, b: 1.125};'2.250' +string(a + b);{a: 1.125, b: 1.0625};'2.1875' +string(a + b);{a: 1.125, b: 1.03125};'2.15625' +string(a + b);{a: 1.125, b: 1.015625};'2.140625' +string(a + b);{a: 1.0625, b: 1};'2.0625' +string(a + b);{a: 1.0625, b: 1.5};'2.5625' +string(a + b);{a: 1.0625, b: 1.25};'2.3125' +string(a + b);{a: 1.0625, b: 1.125};'2.1875' +string(a + b);{a: 1.0625, b: 1.0625};'2.1250' +string(a + b);{a: 1.0625, b: 1.03125};'2.09375' +string(a + b);{a: 1.0625, b: 1.015625};'2.078125' +string(a + b);{a: 1.03125, b: 1};'2.03125' +string(a + b);{a: 1.03125, b: 1.5};'2.53125' +string(a + b);{a: 1.03125, b: 1.25};'2.28125' +string(a + b);{a: 1.03125, b: 1.125};'2.15625' +string(a + b);{a: 1.03125, b: 1.0625};'2.09375' +string(a + b);{a: 1.03125, b: 1.03125};'2.06250' +string(a + b);{a: 1.03125, b: 1.015625};'2.046875' +string(a + b);{a: 1.015625, b: 1};'2.015625' +string(a + b);{a: 1.015625, b: 1.5};'2.515625' +string(a + b);{a: 1.015625, b: 1.25};'2.265625' +string(a + b);{a: 1.015625, b: 1.125};'2.140625' +string(a + b);{a: 1.015625, b: 1.0625};'2.078125' +string(a + b);{a: 1.015625, b: 1.03125};'2.046875' +string(a + b);{a: 1.015625, b: 1.015625};'2.031250' +string(a + b);{a: 2, b: 2};'4' +string(a + b);{a: 2, b: 2.0};'4.0' +string(a + b);{a: 2, b: 2.00};'4.00' +string(a + b);{a: 2, b: 2.000};'4.000' +string(a + b);{a: 2, b: 0.5000};'2.5000' +string(a + b);{a: 2, b: 0.00001};'2.00001' +string(a + b);{a: 2, b: -0.000001};'1.999999' +string(a + b);{a: 2.0, b: 2};'4.0' +string(a + b);{a: 2.0, b: 2.0};'4.0' +string(a + b);{a: 2.0, b: 2.00};'4.00' +string(a + b);{a: 2.0, b: 2.000};'4.000' +string(a + b);{a: 2.0, b: 0.5000};'2.5000' +string(a + b);{a: 2.0, b: 0.00001};'2.00001' +string(a + b);{a: 2.0, b: -0.000001};'1.999999' +string(a + b);{a: 2.00, b: 2};'4.00' +string(a + b);{a: 2.00, b: 2.0};'4.00' +string(a + b);{a: 2.00, b: 2.00};'4.00' +string(a + b);{a: 2.00, b: 2.000};'4.000' +string(a + b);{a: 2.00, b: 0.5000};'2.5000' +string(a + b);{a: 2.00, b: 0.00001};'2.00001' +string(a + b);{a: 2.00, b: -0.000001};'1.999999' +string(a + b);{a: 2.000, b: 2};'4.000' +string(a + b);{a: 2.000, b: 2.0};'4.000' +string(a + b);{a: 2.000, b: 2.00};'4.000' +string(a + b);{a: 2.000, b: 2.000};'4.000' +string(a + b);{a: 2.000, b: 0.5000};'2.5000' +string(a + b);{a: 2.000, b: 0.00001};'2.00001' +string(a + b);{a: 2.000, b: -0.000001};'1.999999' +string(a + b);{a: 0.5000, b: 2};'2.5000' +string(a + b);{a: 0.5000, b: 2.0};'2.5000' +string(a + b);{a: 0.5000, b: 2.00};'2.5000' +string(a + b);{a: 0.5000, b: 2.000};'2.5000' +string(a + b);{a: 0.5000, b: 0.5000};'1.0000' +string(a + b);{a: 0.5000, b: 0.00001};'0.50001' +string(a + b);{a: 0.5000, b: -0.000001};'0.499999' +string(a + b);{a: 0.00001, b: 2};'2.00001' +string(a + b);{a: 0.00001, b: 2.0};'2.00001' +string(a + b);{a: 0.00001, b: 2.00};'2.00001' +string(a + b);{a: 0.00001, b: 2.000};'2.00001' +string(a + b);{a: 0.00001, b: 0.5000};'0.50001' +string(a + b);{a: 0.00001, b: 0.00001};'0.00002' +string(a + b);{a: 0.00001, b: -0.000001};'0.000009' +string(a + b);{a: -0.000001, b: 2};'1.999999' +string(a + b);{a: -0.000001, b: 2.0};'1.999999' +string(a + b);{a: -0.000001, b: 2.00};'1.999999' +string(a + b);{a: -0.000001, b: 2.000};'1.999999' +string(a + b);{a: -0.000001, b: 0.5000};'0.499999' +string(a + b);{a: -0.000001, b: 0.00001};'0.000009' +string(a + b);{a: -0.000001, b: -0.000001};'-0.000002' +# Scale matrix for string(a - b) +string(a - b);{a: 1, b: 2};'-1' +string(a - b);{a: 1, b: 2.0};'-1.0' +string(a - b);{a: 1, b: 2.00};'-1.00' +string(a - b);{a: 1, b: 2.000};'-1.000' +string(a - b);{a: 1, b: 0.5000};'0.5000' +string(a - b);{a: 1, b: 0.00001};'0.99999' +string(a - b);{a: 1, b: -0.000001};'1.000001' +string(a - b);{a: 1.5, b: 2};'-0.5' +string(a - b);{a: 1.5, b: 2.0};'-0.5' +string(a - b);{a: 1.5, b: 2.00};'-0.50' +string(a - b);{a: 1.5, b: 2.000};'-0.500' +string(a - b);{a: 1.5, b: 0.5000};'1.0000' +string(a - b);{a: 1.5, b: 0.00001};'1.49999' +string(a - b);{a: 1.5, b: -0.000001};'1.500001' +string(a - b);{a: 1.25, b: 2};'-0.75' +string(a - b);{a: 1.25, b: 2.0};'-0.75' +string(a - b);{a: 1.25, b: 2.00};'-0.75' +string(a - b);{a: 1.25, b: 2.000};'-0.750' +string(a - b);{a: 1.25, b: 0.5000};'0.7500' +string(a - b);{a: 1.25, b: 0.00001};'1.24999' +string(a - b);{a: 1.25, b: -0.000001};'1.250001' +string(a - b);{a: 1.125, b: 2};'-0.875' +string(a - b);{a: 1.125, b: 2.0};'-0.875' +string(a - b);{a: 1.125, b: 2.00};'-0.875' +string(a - b);{a: 1.125, b: 2.000};'-0.875' +string(a - b);{a: 1.125, b: 0.5000};'0.6250' +string(a - b);{a: 1.125, b: 0.00001};'1.12499' +string(a - b);{a: 1.125, b: -0.000001};'1.125001' +string(a - b);{a: 1.0625, b: 2};'-0.9375' +string(a - b);{a: 1.0625, b: 2.0};'-0.9375' +string(a - b);{a: 1.0625, b: 2.00};'-0.9375' +string(a - b);{a: 1.0625, b: 2.000};'-0.9375' +string(a - b);{a: 1.0625, b: 0.5000};'0.5625' +string(a - b);{a: 1.0625, b: 0.00001};'1.06249' +string(a - b);{a: 1.0625, b: -0.000001};'1.062501' +string(a - b);{a: 1.03125, b: 2};'-0.96875' +string(a - b);{a: 1.03125, b: 2.0};'-0.96875' +string(a - b);{a: 1.03125, b: 2.00};'-0.96875' +string(a - b);{a: 1.03125, b: 2.000};'-0.96875' +string(a - b);{a: 1.03125, b: 0.5000};'0.53125' +string(a - b);{a: 1.03125, b: 0.00001};'1.03124' +string(a - b);{a: 1.03125, b: -0.000001};'1.031251' +string(a - b);{a: 1.015625, b: 2};'-0.984375' +string(a - b);{a: 1.015625, b: 2.0};'-0.984375' +string(a - b);{a: 1.015625, b: 2.00};'-0.984375' +string(a - b);{a: 1.015625, b: 2.000};'-0.984375' +string(a - b);{a: 1.015625, b: 0.5000};'0.515625' +string(a - b);{a: 1.015625, b: 0.00001};'1.015615' +string(a - b);{a: 1.015625, b: -0.000001};'1.015626' +# Scale matrix for string(a * b) +string(a * b);{a: 1, b: 2};'2' +string(a * b);{a: 1, b: 2.0};'2.0' +string(a * b);{a: 1, b: 2.00};'2.00' +string(a * b);{a: 1, b: 2.000};'2.000' +string(a * b);{a: 1, b: 0.5000};'0.5000' +string(a * b);{a: 1, b: 0.00001};'0.00001' +string(a * b);{a: 1, b: -0.000001};'-0.000001' +string(a * b);{a: 1.5, b: 2};'3.0' +string(a * b);{a: 1.5, b: 2.0};'3.00' +string(a * b);{a: 1.5, b: 2.00};'3.000' +string(a * b);{a: 1.5, b: 2.000};'3.0000' +string(a * b);{a: 1.5, b: 0.5000};'0.75000' +string(a * b);{a: 1.5, b: 0.00001};'0.000015' +string(a * b);{a: 1.5, b: -0.000001};'-0.0000015' +string(a * b);{a: 1.25, b: 2};'2.50' +string(a * b);{a: 1.25, b: 2.0};'2.500' +string(a * b);{a: 1.25, b: 2.00};'2.5000' +string(a * b);{a: 1.25, b: 2.000};'2.50000' +string(a * b);{a: 1.25, b: 0.5000};'0.625000' +string(a * b);{a: 1.25, b: 0.00001};'0.0000125' +string(a * b);{a: 1.25, b: -0.000001};'-0.00000125' +string(a * b);{a: 1.125, b: 2};'2.250' +string(a * b);{a: 1.125, b: 2.0};'2.2500' +string(a * b);{a: 1.125, b: 2.00};'2.25000' +string(a * b);{a: 1.125, b: 2.000};'2.250000' +string(a * b);{a: 1.125, b: 0.5000};'0.5625000' +string(a * b);{a: 1.125, b: 0.00001};'0.00001125' +string(a * b);{a: 1.125, b: -0.000001};'-0.000001125' +string(a * b);{a: 1.0625, b: 2};'2.1250' +string(a * b);{a: 1.0625, b: 2.0};'2.12500' +string(a * b);{a: 1.0625, b: 2.00};'2.125000' +string(a * b);{a: 1.0625, b: 2.000};'2.1250000' +string(a * b);{a: 1.0625, b: 0.5000};'0.53125000' +string(a * b);{a: 1.0625, b: 0.00001};'0.000010625' +string(a * b);{a: 1.0625, b: -0.000001};'-0.0000010625' +string(a * b);{a: 1.03125, b: 2};'2.06250' +string(a * b);{a: 1.03125, b: 2.0};'2.062500' +string(a * b);{a: 1.03125, b: 2.00};'2.0625000' +string(a * b);{a: 1.03125, b: 2.000};'2.06250000' +string(a * b);{a: 1.03125, b: 0.5000};'0.515625000' +string(a * b);{a: 1.03125, b: 0.00001};'0.0000103125' +string(a * b);{a: 1.03125, b: -0.000001};'-0.00000103125' +string(a * b);{a: 1.015625, b: 2};'2.031250' +string(a * b);{a: 1.015625, b: 2.0};'2.0312500' +string(a * b);{a: 1.015625, b: 2.00};'2.03125000' +string(a * b);{a: 1.015625, b: 2.000};'2.031250000' +string(a * b);{a: 1.015625, b: 0.5000};'0.5078125000' +string(a * b);{a: 1.015625, b: 0.00001};'0.00001015625' +string(a * b);{a: 1.015625, b: -0.000001};'-0.000001015625' +# Scale matrix for string(a % b) +string(a % b);{a: 1, b: 2};'1' +string(a % b);{a: 1, b: 2.0};'1' +string(a % b);{a: 1, b: 2.00};'1' +string(a % b);{a: 1, b: 2.000};'1' +string(a % b);{a: 1, b: 0.5000};'0.0000' +string(a % b);{a: 1, b: 0.00001};'0.00000' +string(a % b);{a: 1, b: -0.000001};'0.000000' +string(a % b);{a: 1.5, b: 2};'1.5' +string(a % b);{a: 1.5, b: 2.0};'1.5' +string(a % b);{a: 1.5, b: 2.00};'1.5' +string(a % b);{a: 1.5, b: 2.000};'1.5' +string(a % b);{a: 1.5, b: 0.5000};'0.0000' +string(a % b);{a: 1.5, b: 0.00001};'0.00000' +string(a % b);{a: 1.5, b: -0.000001};'0.000000' +string(a % b);{a: 1.25, b: 2};'1.25' +string(a % b);{a: 1.25, b: 2.0};'1.25' +string(a % b);{a: 1.25, b: 2.00};'1.25' +string(a % b);{a: 1.25, b: 2.000};'1.25' +string(a % b);{a: 1.25, b: 0.5000};'0.2500' +string(a % b);{a: 1.25, b: 0.00001};'0.00000' +string(a % b);{a: 1.25, b: -0.000001};'0.000000' +string(a % b);{a: 1.125, b: 2};'1.125' +string(a % b);{a: 1.125, b: 2.0};'1.125' +string(a % b);{a: 1.125, b: 2.00};'1.125' +string(a % b);{a: 1.125, b: 2.000};'1.125' +string(a % b);{a: 1.125, b: 0.5000};'0.1250' +string(a % b);{a: 1.125, b: 0.00001};'0.00000' +string(a % b);{a: 1.125, b: -0.000001};'0.000000' +string(a % b);{a: 1.0625, b: 2};'1.0625' +string(a % b);{a: 1.0625, b: 2.0};'1.0625' +string(a % b);{a: 1.0625, b: 2.00};'1.0625' +string(a % b);{a: 1.0625, b: 2.000};'1.0625' +string(a % b);{a: 1.0625, b: 0.5000};'0.0625' +string(a % b);{a: 1.0625, b: 0.00001};'0.00000' +string(a % b);{a: 1.0625, b: -0.000001};'0.000000' +string(a % b);{a: 1.03125, b: 2};'1.03125' +string(a % b);{a: 1.03125, b: 2.0};'1.03125' +string(a % b);{a: 1.03125, b: 2.00};'1.03125' +string(a % b);{a: 1.03125, b: 2.000};'1.03125' +string(a % b);{a: 1.03125, b: 0.5000};'0.03125' +string(a % b);{a: 1.03125, b: 0.00001};'0.00000' +string(a % b);{a: 1.03125, b: -0.000001};'0.000000' +string(a % b);{a: 1.015625, b: 2};'1.015625' +string(a % b);{a: 1.015625, b: 2.0};'1.015625' +string(a % b);{a: 1.015625, b: 2.00};'1.015625' +string(a % b);{a: 1.015625, b: 2.000};'1.015625' +string(a % b);{a: 1.015625, b: 0.5000};'0.015625' +string(a % b);{a: 1.015625, b: 0.00001};'0.000005' +string(a % b);{a: 1.015625, b: -0.000001};'0.000000' +# Division values over a grid, compared by value +a / b;{a: 1, b: 3};0.3333333333333333333333333333 +a / b;{a: 1, b: 6};0.1666666666666666666666666667 +a / b;{a: 1, b: 7};0.1428571428571428571428571429 +a / b;{a: 1, b: 9};0.1111111111111111111111111111 +a / b;{a: 1, b: 11};0.0909090909090909090909090909 +a / b;{a: 1, b: 12};0.0833333333333333333333333333 +a / b;{a: 1, b: 13};0.0769230769230769230769230769 +a / b;{a: 1, b: 0.3};3.3333333333333333333333333333 +a / b;{a: 1, b: 0.7};1.4285714285714285714285714286 +a / b;{a: 1, b: -3};-0.3333333333333333333333333333 +a / b;{a: 1, b: 8};0.125 +a / b;{a: 1, b: 1024};0.0009765625 +a / b;{a: 1, b: 0.0003};3333.3333333333333333333333333 +a / b;{a: 1, b: 81};0.012345679012345679012345679 +a / b;{a: 100, b: 3};33.333333333333333333333333333 +a / b;{a: 100, b: 6};16.666666666666666666666666667 +a / b;{a: 100, b: 7};14.285714285714285714285714286 +a / b;{a: 100, b: 9};11.111111111111111111111111111 +a / b;{a: 100, b: 11};9.090909090909090909090909091 +a / b;{a: 100, b: 12};8.333333333333333333333333333 +a / b;{a: 100, b: 13};7.6923076923076923076923076923 +a / b;{a: 2, b: 3};0.6666666666666666666666666667 +a / b;{a: 2, b: 6};0.3333333333333333333333333333 +a / b;{a: 2, b: 7};0.2857142857142857142857142857 +a / b;{a: 2, b: 9};0.2222222222222222222222222222 +a / b;{a: 2, b: 11};0.1818181818181818181818181818 +a / b;{a: 2, b: 12};0.1666666666666666666666666667 +a / b;{a: 2, b: 13};0.1538461538461538461538461538 +a / b;{a: 123456789.123456789, b: 3};41152263.041152263 +a / b;{a: 9223372036854775807, b: 7};1317624576693539401 +a / b;{a: 79228162514264337593543950335, b: 3};26409387504754779197847983445 +a / b;{a: 79228162514264337593543950335, b: 7};11318308930609191084791992905 +a / b;{a: 0.0000000000000000000000000001, b: 3};0 +a / b;{a: 0.0000000000000000000000000003, b: 2};0.0000000000000000000000000002 +a / b;{a: 0.0000000000000000000000000005, b: 10};0;question: implicit rounding in arithmetic is half-even (ties go to the even digit) while round() rounds half away from zero +# Overflow approached step by step +a + 1;{a: 79228162514264337593543950331};79228162514264337593543950332 +a + 1;{a: 79228162514264337593543950332};79228162514264337593543950333 +a + 1;{a: 79228162514264337593543950333};79228162514264337593543950334 +a + 1;{a: 79228162514264337593543950334};79228162514264337593543950335 +a + 1;{a: 79228162514264337593543950335};!error +a + 1;{a: -79228162514264337593543950335};-79228162514264337593543950334 +a - 1;{a: -79228162514264337593543950332};-79228162514264337593543950333 +a - 1;{a: -79228162514264337593543950333};-79228162514264337593543950334 +a - 1;{a: -79228162514264337593543950334};-79228162514264337593543950335 +a - 1;{a: -79228162514264337593543950335};!error +a - 1;{a: 79228162514264337593543950335};79228162514264337593543950334 +a * 2;{a: 39614081257132168796771975166};79228162514264337593543950332 +a * 2;{a: 39614081257132168796771975167};79228162514264337593543950334 +a * 2;{a: 3961408125713216879677197516.7};7922816251426433759354395033.4 +a * 2;{a: 39614081257132168796771975168};!error +a * 2;{a: -39614081257132168796771975167};-79228162514264337593543950334 +a * 2;{a: -39614081257132168796771975168};!error +a * 10;{a: 7922816251426433759354395032};79228162514264337593543950320 +a * 10;{a: 7922816251426433759354395033};79228162514264337593543950330 +a * 10;{a: 7922816251426433759354395033.5};79228162514264337593543950335 +a * 10;{a: 7922816251426433759354395034};!error +a * 10;{a: -7922816251426433759354395033};-79228162514264337593543950330 +a + b;{a: 79228162514264337593543950335, b: 0.1};79228162514264337593543950335 +a + b;{a: 79228162514264337593543950335, b: 0.4};79228162514264337593543950335 +a + b;{a: 79228162514264337593543950335, b: 0.49};79228162514264337593543950335 +a + b;{a: 79228162514264337593543950335, b: 0.4999999999999999999999999999};79228162514264337593543950335 +a + b;{a: 79228162514264337593543950335, b: 0.5};!error +a + b;{a: 79228162514264337593543950335, b: 0.51};!error +a + b;{a: 79228162514264337593543950335, b: -0.5};79228162514264337593543950334 +a + b;{a: 79228162514264337593543950334, b: 0.5};79228162514264337593543950334;question: implicit rounding in arithmetic is half-even (ties go to the even digit) while round() rounds half away from zero +a + b;{a: 79228162514264337593543950334, b: 1.5};!error +a + b;{a: -79228162514264337593543950335, b: -0.4};-79228162514264337593543950335 +a + b;{a: -79228162514264337593543950335, b: -0.5};!error +2 ^ n;{n: 90};1237940039285380274899124224 +2 ^ n;{n: 91};2475880078570760549798248448 +2 ^ n;{n: 92};4951760157141521099596496896 +2 ^ n;{n: 93};9903520314283042199192993792 +2 ^ n;{n: 94};19807040628566084398385987584 +2 ^ n;{n: 95};39614081257132168796771975168 +2 ^ n;{n: 96};!error +2 ^ n;{n: 97};!error +10 ^ n;{n: 25};10000000000000000000000000 +10 ^ n;{n: 26};100000000000000000000000000 +10 ^ n;{n: 27};1000000000000000000000000000 +10 ^ n;{n: 28};10000000000000000000000000000 +10 ^ n;{n: 29};!error +10 ^ n;{n: 30};!error +10 ^ n;{n: -26};0.00000000000000000000000001 +10 ^ n;{n: -27};0.000000000000000000000000001 +10 ^ n;{n: -28};0.0000000000000000000000000001 +10 ^ n;{n: -29};0 +10 ^ n;{n: -30};0 +a * a;{a: 281474976710655};79228162514263774643590529025 +a * a;{a: 281474976710656};!error +a * a;{a: 281474976710657};!error +a * a;{a: 4294967296};18446744073709551616 +a * a;{a: 18446744073709551615};!error +a * a;{a: 281474976710656.5};!error +a * a;{a: 281474976710655.9};79228162514264281298548608205 +a * a;{a: -281474976710657};!error +a * b;{a: 79228162514264337593543950335, b: 0.1};7922816251426433759354395033.5 +a * b;{a: 79228162514264337593543950335, b: 0.5};39614081257132168796771975168 +a * b;{a: 79228162514264337593543950335, b: 0.9999999999999999999999999999};79228162514264337593543950327 +a * b;{a: 79228162514264337593543950335, b: 1.0000000000000000000000000001};!error +a * b;{a: -79228162514264337593543950335, b: 0.5};-39614081257132168796771975168 +a * b;{a: 9223372036854775807, b: 9223372036854775807};!error +a * b;{a: 4294967296, b: 18446744073709551616};!error +a * b;{a: 8589934592, b: 9223372036854775808};!error +a * b;{a: 8589934591, b: 9223372036854775808};79228162505040965556689174528 +# Precision limit approached step by step: adding 1e-28 to growing magnitudes +string(b + 0.0000000000000000000000000001);{b: 0};'0.0000000000000000000000000001' +string(b + 0.0000000000000000000000000001);{b: 1};'1.0000000000000000000000000001' +string(b + 0.0000000000000000000000000001);{b: 5};'5.0000000000000000000000000001' +string(b + 0.0000000000000000000000000001);{b: 7};'7.0000000000000000000000000001' +string(b + 0.0000000000000000000000000001);{b: 7.9};'7.9000000000000000000000000001' +string(b + 0.0000000000000000000000000001);{b: 7.92};'7.9200000000000000000000000001' +string(b + 0.0000000000000000000000000001);{b: 7.93};'7.930000000000000000000000000' +string(b + 0.0000000000000000000000000001);{b: 8};'8.000000000000000000000000000' +string(b + 0.0000000000000000000000000001);{b: 9};'9.000000000000000000000000000' +string(b + 0.0000000000000000000000000001);{b: 10};'10.000000000000000000000000000' +string(b + 0.0000000000000000000000000001);{b: 100};'100.00000000000000000000000000' +string(b + 0.0000000000000000000000000001);{b: 1000000};'1000000.0000000000000000000000' +string(b + 0.0000000000000000000000000001);{b: -7};'-6.9999999999999999999999999999' +string(b + 0.0000000000000000000000000001);{b: -8};'-8.000000000000000000000000000' +b + 0.0000000000000000000000000001 == b;{b: 8};true +b + 0.0000000000000000000000000001 == b;{b: 10};true +b + 0.0000000000000000000000000001 == b;{b: 100};true +b + 0.0000000000000000000000000001 == b;{b: 1000000};true +b + 0.0000000000000000000000000001 == b;{b: 9007199254740993};true +b + 0.0000000000000000000000000001 == b;{b: 79228162514264337593543950335};true +# Precision limit: the sum rounds away from b only while b has room for 28 fractional digits +b + 0.0000000000000000000000000001 == b;{b: 1};false +b + 0.0000000000000000000000000001 == b;{b: 7};false +# Property: string(1 + a) +string(1 + a);{a: 0.0000000000000000001};'1.0000000000000000001' +string(1 + a);{a: 0.00000000000000000001};'1.00000000000000000001' +string(1 + a);{a: 0.000000000000000000001};'1.000000000000000000001' +string(1 + a);{a: 0.0000000000000000000001};'1.0000000000000000000001' +string(1 + a);{a: 0.00000000000000000000001};'1.00000000000000000000001' +string(1 + a);{a: 0.000000000000000000000001};'1.000000000000000000000001' +string(1 + a);{a: 0.0000000000000000000000001};'1.0000000000000000000000001' +string(1 + a);{a: 0.00000000000000000000000001};'1.00000000000000000000000001' +string(1 + a);{a: 0.000000000000000000000000001};'1.000000000000000000000000001' +string(1 + a);{a: 0.0000000000000000000000000001};'1.0000000000000000000000000001' +string(a * 3);{a: 0.3333333333333333333333333333};'0.9999999999999999999999999999' +string(a * 3);{a: 3.3333333333333333333333333333};'10.000000000000000000000000000' +string(a * 3);{a: 33.333333333333333333333333333};'100.00000000000000000000000000' +string(a * 3);{a: 333.33333333333333333333333333};'1000.0000000000000000000000000' +string(a * 3);{a: 26409387504754779197847983445};'79228162514264337593543950335' +string(a * 3);{a: 26409387504754779197847983446};!error +string(a * b);{a: 1.1, b: 1.1};'1.21' +string(a * b);{a: 1.01, b: 1.01};'1.0201' +string(a * b);{a: 1.00000000000001, b: 1.00000000000001};'1.0000000000000200000000000001' +string(a * b);{a: 1.000000000000001, b: 1.000000000000001};'1.0000000000000020000000000000' +string(a * b);{a: 1.0000000000000000000000000001, b: 1.0000000000000000000000000001};'1.0000000000000000000000000002' +string(a * b);{a: 0.1234567890123456789012345678, b: 0.1234567890123456789012345678};'0.0152415787532388367504953515' +string(a * b);{a: 12345.678901234567890123, b: 12345.678901234567890123};'152415787.53238836750494223688' +string(a * b);{a: 1.5, b: 0.0000000000000000000000000001};'0.0000000000000000000000000002' +string(a * b);{a: 2.5, b: 0.0000000000000000000000000001};'0.0000000000000000000000000002';question: implicit rounding in arithmetic is half-even (ties go to the even digit) while round() rounds half away from zero +# Integers near 2^31, 2^53 and 2^63 stay exact +a + 1 - a == 1;{a: 2147483647};true +a + 1 - a == 1;{a: -2147483648};true +a + 1 - a == 1;{a: 4294967295};true +a + 1 - a == 1;{a: 9007199254740991};true +a + 1 - a == 1;{a: 9007199254740992};true +a + 1 - a == 1;{a: 9007199254740993};true +a + 1 - a == 1;{a: 9223372036854775807};true +a + 1 - a == 1;{a: -9223372036854775808};true +a + 1 - a == 1;{a: 18446744073709551615};true +a + 1 - a == 1;{a: null};!error +a + 1 - a == 1;{a: '1'};!error +a + 1 == a;{a: 9007199254740992};false +a + 1 == a;{a: 9007199254740993};false +a + 1 == a;{a: 9223372036854775807};false +a + 1 == a;{a: 18446744073709551616};false +a + 1 == a;{a: 79228162514264337593543950334};false +string(a + b);{a: 2147483647, b: 1};'2147483648' +string(a + b);{a: -2147483648, b: -1};'-2147483649' +string(a + b);{a: 9007199254740992, b: 1};'9007199254740993' +string(a + b);{a: 9007199254740993, b: 0.5};'9007199254740993.5' +string(a + b);{a: 9223372036854775807, b: 1};'9223372036854775808' +string(a + b);{a: 9223372036854775807, b: 9223372036854775807};'18446744073709551614' +string(a + b);{a: -9223372036854775808, b: -9223372036854775808};'-18446744073709551616' +string(a + b);{a: 18446744073709551615, b: 0.000000001};'18446744073709551615.000000001' +string(a + b);{a: 9007199254740993, b: 0.1};'9007199254740993.1' +a == b;{a: 9007199254740992, b: 9007199254740993};false +a == b;{a: 9223372036854775807, b: 9223372036854775808};false +a == b;{a: 9007199254740993, b: 9007199254740993.0};true +a == b;{a: 2147483648, b: 2147483648.000};true +a == b;{a: 79228162514264337593543950335, b: 79228162514264337593543950334};false +a < b;{a: 9007199254740992, b: 9007199254740993};true +a < b;{a: 9223372036854775807, b: 9223372036854775808};true +a < b;{a: -9223372036854775809, b: -9223372036854775808};true +a < b;{a: 0.0000000000000000000000000001, b: 0.0000000000000000000000000002};true +a < b;{a: 79228162514264337593543950334, b: 79228162514264337593543950335};true +a < b;{a: 1.0000000000000000000000000001, b: 1};false +a * b;{a: 2147483647, b: 2147483647};4611686014132420609 +a * b;{a: 2147483648, b: 2147483648};4611686018427387904 +a * b;{a: -2147483648, b: 2147483648};-4611686018427387904 +a * b;{a: 9007199254740993, b: 3};27021597764222979 +a * b;{a: 9223372036854775807, b: -1};-9223372036854775807 +a * b;{a: -9223372036854775808, b: -1};9223372036854775808 +a * b;{a: 4294967295, b: 4294967297};18446744073709551615 +a % b;{a: 9007199254740993, b: 2};1 +a % b;{a: 9223372036854775807, b: 10};7 +a % b;{a: -9223372036854775808, b: 10};-8 +a % b;{a: 18446744073709551615, b: 4294967296};4294967295 +a % b;{a: 79228162514264337593543950335, b: 18446744073709551616};18446744073709551615 +a % b;{a: 79228162514264337593543950335, b: 0.7};0 +a % b;{a: 2147483648, b: 2147483647};1 +trunc(a / b);{a: 9007199254740993, b: 2};4503599627370496 +trunc(a / b);{a: 9223372036854775807, b: 10};922337203685477580 +trunc(a / b);{a: -9223372036854775808, b: 10};-922337203685477580 +trunc(a / b);{a: 18446744073709551615, b: 4294967296};4294967295 +trunc(a / b);{a: 2147483648, b: 3};715827882 +trunc(a / b);{a: 79228162514264337593543950334, b: 79228162514264337593543950335};1 diff --git a/core/expression/tests/spec/standard/15-01-pipelines.csv b/core/expression/tests/spec/standard/15-01-pipelines.csv new file mode 100644 index 00000000..c4447e1b --- /dev/null +++ b/core/expression/tests/spec/standard/15-01-pipelines.csv @@ -0,0 +1,941 @@ +expression (string);input (json 5);output (json 5);note +# normalize then transform: case after trim +upper(trim(s));{s: ' gold '};'GOLD' +upper(trim(s));{s: 'Gold'};'GOLD' +upper(trim(s));{s: 'GOLD'};'GOLD' +upper(trim(s));{s: '\tsilver\n'};'SILVER' +upper(trim(s));{s: 'Bronze '};'BRONZE' +upper(trim(s));{s: ''};'' +upper(trim(s));{s: ' '};'' +upper(trim(s));{s: 'straße '};'STRASSE' +upper(trim(s));{s: '\u00a0vip\u3000'};'VIP' +upper(trim(s));{s: 'platinum'};'PLATINUM' +upper(trim(s));{s: null};!error +upper(trim(s));{s: 42};!error +upper(trim(s));{s: true};!error +upper(trim(s));{s: ['gold']};!error +upper(trim(s));{};!error +lower(trim(s));{s: ' gold '};'gold' +lower(trim(s));{s: 'Gold'};'gold' +lower(trim(s));{s: 'GOLD'};'gold' +lower(trim(s));{s: '\tsilver\n'};'silver' +lower(trim(s));{s: 'Bronze '};'bronze' +lower(trim(s));{s: ''};'' +lower(trim(s));{s: ' '};'' +lower(trim(s));{s: 'straße '};'straße' +lower(trim(s));{s: '\u00a0vip\u3000'};'vip' +lower(trim(s));{s: 'platinum'};'platinum' +lower(trim(s));{s: null};!error +lower(trim(s));{s: 42};!error +lower(trim(s));{s: true};!error +lower(trim(s));{s: ['gold']};!error +lower(trim(s));{};!error +trim(upper(s));{s: ' gold '};'GOLD' +trim(upper(s));{s: 'Gold'};'GOLD' +trim(upper(s));{s: 'GOLD'};'GOLD' +trim(upper(s));{s: '\tsilver\n'};'SILVER' +trim(upper(s));{s: 'Bronze '};'BRONZE' +trim(upper(s));{s: ''};'' +trim(upper(s));{s: ' '};'' +trim(upper(s));{s: 'straße '};'STRASSE' +trim(upper(s));{s: '\u00a0vip\u3000'};'VIP' +trim(upper(s));{};!error +upper(trim(s)) == trim(upper(s));{s: ' gold '};true +upper(trim(s)) == trim(upper(s));{s: 'Gold'};true +upper(trim(s)) == trim(upper(s));{s: 'GOLD'};true +upper(trim(s)) == trim(upper(s));{s: '\tsilver\n'};true +upper(trim(s)) == trim(upper(s));{s: 'Bronze '};true +upper(trim(s)) == trim(upper(s));{s: ''};true +upper(trim(s)) == trim(upper(s));{s: ' '};true +upper(trim(s)) == trim(upper(s));{s: 'straße '};true +upper(trim(s)) == trim(upper(s));{s: '\u00a0vip\u3000'};true +upper(trim(s)) == trim(upper(s));{s: 'platinum'};true +# normalize then compare +lower(trim(s)) == 'gold';{s: ' gold '};true +lower(trim(s)) == 'gold';{s: 'Gold'};true +lower(trim(s)) == 'gold';{s: 'GOLD'};true +lower(trim(s)) == 'gold';{s: '\tsilver\n'};false +lower(trim(s)) == 'gold';{s: 'Bronze '};false +lower(trim(s)) == 'gold';{s: ''};false +lower(trim(s)) == 'gold';{s: ' '};false +lower(trim(s)) == 'gold';{s: 'straße '};false +lower(trim(s)) == 'gold';{s: '\u00a0vip\u3000'};false +lower(trim(s)) == 'gold';{s: 'platinum'};false +lower(trim(s)) == 'gold';{s: null};!error +lower(trim(s)) == 'gold';{s: 42};!error +lower(trim(s)) == 'gold';{s: true};!error +lower(trim(s)) == 'gold';{s: ['gold']};!error +lower(trim(s)) == 'gold';{};!error +upper(trim(s)) == 'STRASSE';{s: 'straße'};true +upper(trim(s)) == 'STRASSE';{s: ' Straße '};true +upper(trim(s)) == 'STRASSE';{s: 'STRASSE'};true +upper(trim(s)) == 'STRASSE';{s: 'strasse'};true +upper(trim(s)) == 'STRASSE';{s: 'strase'};false +upper(trim(s)) == 'STRASSE';{s: 'STRAẞE'};false +lower(trim(s)) == lower(trim(t));{s: 'Gold', t: 'gold'};true +lower(trim(s)) == lower(trim(t));{s: ' gold', t: 'GOLD '};true +lower(trim(s)) == lower(trim(t));{s: 'Straße', t: 'STRASSE'};false +lower(trim(s)) == lower(trim(t));{s: 'ΣΑΣ', t: 'σας'};true +lower(trim(s)) == lower(trim(t));{s: 'İstanbul', t: 'istanbul'};false +lower(trim(s)) == lower(trim(t));{s: 'a b', t: 'a b'};false +lower(trim(s)) == lower(trim(t));{s: '', t: ' '};true +lower(trim(s)) == lower(trim(t));{s: 'x', t: null};!error +lower(trim(s)) == lower(trim(t));{s: null, t: null};!error +lower(trim(s)) == lower(trim(t));{s: 1, t: '1'};!error +upper(s) == upper(t);{s: 'Gold', t: 'gold'};true +upper(s) == upper(t);{s: ' gold', t: 'GOLD '};false +upper(s) == upper(t);{s: 'Straße', t: 'STRASSE'};true +upper(s) == upper(t);{s: 'ΣΑΣ', t: 'σας'};true +upper(s) == upper(t);{s: 'İstanbul', t: 'istanbul'};false +upper(s) == upper(t);{s: 'a b', t: 'a b'};false +upper(s) == upper(t);{s: '', t: ' '};false +upper(s) == upper(t);{s: 'x', t: null};!error +upper(s) == upper(t);{s: null, t: null};!error +upper(s) == upper(t);{s: 1, t: '1'};!error +upper(s) == upper(t) and s != t;{s: 'Gold', t: 'gold'};true +upper(s) == upper(t) and s != t;{s: ' gold', t: 'GOLD '};false +upper(s) == upper(t) and s != t;{s: 'Straße', t: 'STRASSE'};true +upper(s) == upper(t) and s != t;{s: 'ΣΑΣ', t: 'σας'};true +upper(s) == upper(t) and s != t;{s: 'İstanbul', t: 'istanbul'};false +upper(s) == upper(t) and s != t;{s: 'a b', t: 'a b'};false +upper(s) == upper(t) and s != t;{s: '', t: ' '};false +# membership after normalization +lower(s) in ['gold', 'silver', 'bronze'];{s: ' gold '};false +lower(s) in ['gold', 'silver', 'bronze'];{s: 'Gold'};true +lower(s) in ['gold', 'silver', 'bronze'];{s: 'GOLD'};true +lower(s) in ['gold', 'silver', 'bronze'];{s: '\tsilver\n'};false +lower(s) in ['gold', 'silver', 'bronze'];{s: 'Bronze '};false +lower(s) in ['gold', 'silver', 'bronze'];{s: ''};false +lower(s) in ['gold', 'silver', 'bronze'];{s: ' '};false +lower(s) in ['gold', 'silver', 'bronze'];{s: 'straße '};false +lower(s) in ['gold', 'silver', 'bronze'];{s: '\u00a0vip\u3000'};false +lower(s) in ['gold', 'silver', 'bronze'];{s: 'platinum'};false +lower(s) in ['gold', 'silver', 'bronze'];{s: null};!error +lower(s) in ['gold', 'silver', 'bronze'];{s: 42};!error +lower(s) in ['gold', 'silver', 'bronze'];{s: true};!error +lower(s) in ['gold', 'silver', 'bronze'];{s: ['gold']};!error +lower(s) in ['gold', 'silver', 'bronze'];{};!error +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: ' gold '};true +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: 'Gold'};true +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: 'GOLD'};true +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: '\tsilver\n'};true +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: 'Bronze '};true +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: ''};false +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: ' '};false +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: 'straße '};false +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: '\u00a0vip\u3000'};false +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: 'platinum'};false +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: null};!error +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: 42};!error +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: true};!error +lower(trim(s)) in ['gold', 'silver', 'bronze'];{s: ['gold']};!error +lower(trim(s)) in ['gold', 'silver', 'bronze'];{};!error +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: 'n/a'};false +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: ' None '};false +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: '-'};false +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: ''};false +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: ' '};false +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: 'value'};true +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: 'none of these'};true +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: null};!error +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{s: 0};!error +upper(trim(s)) not in ['N/A', 'NONE', '-', ''];{};!error +lower(s) in allowed;{s: 'US', allowed: ['us', 'ca']};true +lower(s) in allowed;{s: 'Ca', allowed: ['us', 'ca']};true +lower(s) in allowed;{s: 'MX', allowed: ['us', 'ca']};false +lower(s) in allowed;{s: 'US', allowed: []};false +lower(s) in allowed;{s: 'US', allowed: ['US']};false +lower(s) in allowed;{s: 'us', allowed: null};!error +lower(s) in allowed;{s: null, allowed: ['us']};!error +lower(s) in allowed;{s: 'us', allowed: 'us'};!error +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'us', zip: '94107'};true +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'CA', zip: '90210'};true +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'us', zip: '10001'};false +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'mx', zip: '94107'};false +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'mx', zip: null};false +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'us', zip: null};!error +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: null, zip: '9'};!error +upper(country) in ['US', 'CA'] and startsWith(zip, '9');{country: 'Us', zip: 94107};!error +# contains over normalized text +contains(lower(s), lower(t));{s: 'Hello World', t: 'world'};true +contains(lower(s), lower(t));{s: 'HELLO', t: 'ell'};true +contains(lower(s), lower(t));{s: 'Straße', t: 'SS'};false +contains(lower(s), lower(t));{s: 'Straße', t: 'ß'};true +contains(lower(s), lower(t));{s: 'abc', t: ''};true +contains(lower(s), lower(t));{s: '', t: ''};true +contains(lower(s), lower(t));{s: '', t: 'a'};false +contains(lower(s), lower(t));{s: 'Ünïcödé', t: 'ÏCÖ'};true +contains(lower(s), lower(t));{s: 'a b', t: 'A B'};false +contains(lower(s), lower(t));{s: 'x', t: null};!error +contains(lower(s), lower(t));{s: null, t: 'x'};!error +contains(lower(s), lower(t));{s: 12, t: '1'};!error +contains(upper(s), upper(t));{s: 'Hello World', t: 'world'};true +contains(upper(s), upper(t));{s: 'HELLO', t: 'ell'};true +contains(upper(s), upper(t));{s: 'Straße', t: 'SS'};true +contains(upper(s), upper(t));{s: 'Straße', t: 'ß'};true +contains(upper(s), upper(t));{s: 'abc', t: ''};true +contains(upper(s), upper(t));{s: '', t: ''};true +contains(upper(s), upper(t));{s: '', t: 'a'};false +contains(upper(s), upper(t));{s: 'Ünïcödé', t: 'ÏCÖ'};true +contains(upper(s), upper(t));{s: 'a b', t: 'A B'};false +contains(upper(s), upper(t));{s: 'x', t: null};!error +contains(upper(s), upper(t));{s: null, t: 'x'};!error +contains(upper(s), upper(t));{s: 12, t: '1'};!error +contains(s, t) or contains(lower(s), lower(t));{s: 'Hello World', t: 'world'};true +contains(s, t) or contains(lower(s), lower(t));{s: 'HELLO', t: 'ell'};true +contains(s, t) or contains(lower(s), lower(t));{s: 'Straße', t: 'SS'};false +contains(s, t) or contains(lower(s), lower(t));{s: 'Straße', t: 'ß'};true +contains(s, t) or contains(lower(s), lower(t));{s: 'abc', t: ''};true +contains(s, t) or contains(lower(s), lower(t));{s: '', t: ''};true +contains(s, t) or contains(lower(s), lower(t));{s: '', t: 'a'};false +contains(s, t) or contains(lower(s), lower(t));{s: 'Ünïcödé', t: 'ÏCÖ'};true +contains(s, t) or contains(lower(s), lower(t));{s: 'a b', t: 'A B'};false +contains(s, t) or contains(lower(s), lower(t));{s: 'x', t: null};!error +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: 'Customer requested REFUND'};true +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: 'chargeback filed'};true +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: 'Disputed charge'};false +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: 'normal purchase'};false +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: ''};false +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: 'refunded twice'};true +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: 'Charge-back'};false +contains(lower(d), 'refund') or contains(lower(d), 'chargeback');{d: null};!error +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: 'Customer requested REFUND'};true +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: 'chargeback filed'};false +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: 'Disputed charge'};false +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: 'normal purchase'};false +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: ''};false +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: 'refunded twice'};false +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: 'Charge-back'};false +contains(lower(d), 'refund') and not contains(lower(d), 'refunded');{d: null};!error +# prefix and suffix after normalization +startsWith(upper(trim(code)), 'SKU-');{code: ' sku-001 '};true +startsWith(upper(trim(code)), 'SKU-');{code: 'SKU-002'};true +startsWith(upper(trim(code)), 'SKU-');{code: 'Sku-3'};true +startsWith(upper(trim(code)), 'SKU-');{code: 'ski-004'};false +startsWith(upper(trim(code)), 'SKU-');{code: 'SKU'};false +startsWith(upper(trim(code)), 'SKU-');{code: ''};false +startsWith(upper(trim(code)), 'SKU-');{code: '\tsku-9\n'};true +startsWith(upper(trim(code)), 'SKU-');{code: null};!error +startsWith(upper(trim(code)), 'SKU-');{code: 7};!error +endsWith(lower(email), '@example.com');{email: 'Joe@Example.com'};true +endsWith(lower(email), '@example.com');{email: 'ann@example.COM'};true +endsWith(lower(email), '@example.com');{email: 'bob@example.co'};false +endsWith(lower(email), '@example.com');{email: 'x@sub.example.com'};false +endsWith(lower(email), '@example.com');{email: 'example.com'};false +endsWith(lower(email), '@example.com');{email: ''};false +endsWith(lower(email), '@example.com');{email: ' a@example.com '};false +endsWith(lower(email), '@example.com');{email: null};!error +endsWith(lower(trim(email)), 'example.com');{email: 'Joe@Example.com'};true +endsWith(lower(trim(email)), 'example.com');{email: 'ann@example.COM'};true +endsWith(lower(trim(email)), 'example.com');{email: 'bob@example.co'};false +endsWith(lower(trim(email)), 'example.com');{email: 'x@sub.example.com'};true +endsWith(lower(trim(email)), 'example.com');{email: 'example.com'};true +endsWith(lower(trim(email)), 'example.com');{email: ''};false +endsWith(lower(trim(email)), 'example.com');{email: ' a@example.com '};true +endsWith(lower(trim(email)), 'example.com');{email: null};!error +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: 'https://a.io'};true +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: 'HTTP://A.IO'};true +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: 'ftp://x'};false +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: 'httpx://'};false +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: 'Https://'};true +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: ''};false +startsWith(lower(url), 'https://') or startsWith(lower(url), 'http://');{url: null};!error +# split then map +split(s, ',');{s: 'a,b,c'};['a', 'b', 'c'] +split(s, ',');{s: ' a , b ,c '};[' a ', ' b ', 'c '] +split(s, ',');{s: 'a,,b'};['a', '', 'b'] +split(s, ',');{s: ','};['', ''] +split(s, ',');{s: ''};[''] +split(s, ',');{s: 'single'};['single'] +split(s, ',');{s: 'x, y, z, '};['x', ' y', ' z', ' '] +split(s, ',');{s: 'ä,ö,ü'};['ä', 'ö', 'ü'] +split(s, ',');{s: null};!error +split(s, ',');{s: 5};!error +split(s, ',');{};!error +map(split(s, ','), trim(#));{s: 'a,b,c'};['a', 'b', 'c'] +map(split(s, ','), trim(#));{s: ' a , b ,c '};['a', 'b', 'c'] +map(split(s, ','), trim(#));{s: 'a,,b'};['a', '', 'b'] +map(split(s, ','), trim(#));{s: ','};['', ''] +map(split(s, ','), trim(#));{s: ''};[''] +map(split(s, ','), trim(#));{s: 'single'};['single'] +map(split(s, ','), trim(#));{s: 'x, y, z, '};['x', 'y', 'z', ''] +map(split(s, ','), trim(#));{s: 'ä,ö,ü'};['ä', 'ö', 'ü'] +map(split(s, ','), trim(#));{s: null};!error +map(split(s, ','), trim(#));{s: 5};!error +map(split(s, ','), trim(#));{};!error +map(split(s, ','), upper(trim(#)));{s: 'a,b,c'};['A', 'B', 'C'] +map(split(s, ','), upper(trim(#)));{s: ' a , b ,c '};['A', 'B', 'C'] +map(split(s, ','), upper(trim(#)));{s: 'a,,b'};['A', '', 'B'] +map(split(s, ','), upper(trim(#)));{s: ','};['', ''] +map(split(s, ','), upper(trim(#)));{s: ''};[''] +map(split(s, ','), upper(trim(#)));{s: 'single'};['SINGLE'] +map(split(s, ','), upper(trim(#)));{s: 'x, y, z, '};['X', 'Y', 'Z', ''] +map(split(s, ','), upper(trim(#)));{s: 'ä,ö,ü'};['Ä', 'Ö', 'Ü'] +map(split(s, ','), upper(trim(#)));{s: null};!error +map(split(s, ','), upper(trim(#)));{s: 5};!error +map(split(s, ','), upper(trim(#)));{};!error +filter(map(split(s, ','), trim(#)), # != '');{s: 'a,b,c'};['a', 'b', 'c'] +filter(map(split(s, ','), trim(#)), # != '');{s: ' a , b ,c '};['a', 'b', 'c'] +filter(map(split(s, ','), trim(#)), # != '');{s: 'a,,b'};['a', 'b'] +filter(map(split(s, ','), trim(#)), # != '');{s: ','};[] +filter(map(split(s, ','), trim(#)), # != '');{s: ''};[] +filter(map(split(s, ','), trim(#)), # != '');{s: 'single'};['single'] +filter(map(split(s, ','), trim(#)), # != '');{s: 'x, y, z, '};['x', 'y', 'z'] +filter(map(split(s, ','), trim(#)), # != '');{s: 'ä,ö,ü'};['ä', 'ö', 'ü'] +filter(map(split(s, ','), trim(#)), # != '');{s: null};!error +filter(map(split(s, ','), trim(#)), # != '');{s: 5};!error +filter(map(split(s, ','), trim(#)), # != '');{};!error +len(split(s, ','));{s: 'a,b,c'};3 +len(split(s, ','));{s: ' a , b ,c '};3 +len(split(s, ','));{s: 'a,,b'};3 +len(split(s, ','));{s: ','};2 +len(split(s, ','));{s: ''};1 +len(split(s, ','));{s: 'single'};1 +len(split(s, ','));{s: 'x, y, z, '};4 +len(split(s, ','));{s: 'ä,ö,ü'};3 +len(split(s, ','));{s: null};!error +len(split(s, ','));{s: 5};!error +len(split(s, ','));{};!error +map(split(s, ','), len(#));{s: 'a,b,c'};[1, 1, 1] +map(split(s, ','), len(#));{s: ' a , b ,c '};[3, 3, 2] +map(split(s, ','), len(#));{s: 'a,,b'};[1, 0, 1] +map(split(s, ','), len(#));{s: ','};[0, 0] +map(split(s, ','), len(#));{s: ''};[0] +map(split(s, ','), len(#));{s: 'single'};[6] +map(split(s, ','), len(#));{s: 'x, y, z, '};[1, 2, 2, 1] +map(split(s, ','), len(#));{s: 'ä,ö,ü'};[1, 1, 1];bug: len counts UTF-8 bytes, intended character count +map(split(s, ','), len(#));{s: null};!error +map(split(s, ','), len(#));{s: 5};!error +map(split(s, ','), len(#));{};!error +map(split(s, ','), len(trim(#)));{s: 'a,b,c'};[1, 1, 1] +map(split(s, ','), len(trim(#)));{s: ' a , b ,c '};[1, 1, 1] +map(split(s, ','), len(trim(#)));{s: 'a,,b'};[1, 0, 1] +map(split(s, ','), len(trim(#)));{s: ','};[0, 0] +map(split(s, ','), len(trim(#)));{s: ''};[0] +map(split(s, ','), len(trim(#)));{s: 'single'};[6] +map(split(s, ','), len(trim(#)));{s: 'x, y, z, '};[1, 1, 1, 0] +map(split(s, ','), len(trim(#)));{s: 'ä,ö,ü'};[1, 1, 1];bug: len counts UTF-8 bytes, intended character count +map(split(s, ','), len(trim(#)));{s: null};!error +map(split(s, ','), len(trim(#)));{s: 5};!error +map(split(s, ','), len(trim(#)));{};!error +count(split(s, ','), trim(#) == '');{s: 'a,b,c'};0 +count(split(s, ','), trim(#) == '');{s: ' a , b ,c '};0 +count(split(s, ','), trim(#) == '');{s: 'a,,b'};1 +count(split(s, ','), trim(#) == '');{s: ','};2 +count(split(s, ','), trim(#) == '');{s: ''};1 +count(split(s, ','), trim(#) == '');{s: 'single'};0 +count(split(s, ','), trim(#) == '');{s: 'x, y, z, '};1 +count(split(s, ','), trim(#) == '');{s: 'ä,ö,ü'};0 +count(split(s, ','), trim(#) == '');{s: null};!error +count(split(s, ','), trim(#) == '');{s: 5};!error +count(split(s, ','), trim(#) == '');{};!error +split(s, ',')[0];{s: 'a,b,c'};'a' +split(s, ',')[0];{s: ' a , b ,c '};' a ' +split(s, ',')[0];{s: 'a,,b'};'a' +split(s, ',')[0];{s: ','};'' +split(s, ',')[0];{s: ''};'' +split(s, ',')[0];{s: 'single'};'single' +split(s, ',')[0];{s: 'x, y, z, '};'x' +split(s, ',')[0];{s: 'ä,ö,ü'};'ä' +split(s, ',')[0];{s: null};!error +split(s, ',')[0];{s: 5};!error +split(s, ',')[0];{};!error +trim(split(s, ',')[1] ?? '');{s: 'a,b,c'};'b' +trim(split(s, ',')[1] ?? '');{s: ' a , b ,c '};'b' +trim(split(s, ',')[1] ?? '');{s: 'a,,b'};'' +trim(split(s, ',')[1] ?? '');{s: ','};'' +trim(split(s, ',')[1] ?? '');{s: ''};'' +trim(split(s, ',')[1] ?? '');{s: 'single'};'' +trim(split(s, ',')[1] ?? '');{s: 'x, y, z, '};'y' +trim(split(s, ',')[1] ?? '');{s: 'ä,ö,ü'};'ö' +trim(split(s, ',')[1] ?? '');{s: null};!error +trim(split(s, ',')[1] ?? '');{s: 5};!error +trim(split(s, ',')[1] ?? '');{};!error +len(filter(split(s, ' '), # != ''));{s: 'the quick brown fox'};4 +len(filter(split(s, ' '), # != ''));{s: ' leading and trailing '};3 +len(filter(split(s, ' '), # != ''));{s: 'double space'};2 +len(filter(split(s, ' '), # != ''));{s: 'one'};1 +len(filter(split(s, ' '), # != ''));{s: ''};0 +len(filter(split(s, ' '), # != ''));{s: 'tab\tseparated words'};2 +len(filter(split(s, ' '), # != ''));{s: 'Ünïcödé wörds here'};3 +len(filter(split(s, ' '), # != ''));{s: null};!error +filter(split(trim(s), ' '), # != '');{s: 'the quick brown fox'};['the', 'quick', 'brown', 'fox'] +filter(split(trim(s), ' '), # != '');{s: ' leading and trailing '};['leading', 'and', 'trailing'] +filter(split(trim(s), ' '), # != '');{s: 'double space'};['double', 'space'] +filter(split(trim(s), ' '), # != '');{s: 'one'};['one'] +filter(split(trim(s), ' '), # != '');{s: ''};[] +filter(split(trim(s), ' '), # != '');{s: 'tab\tseparated words'};['tab\tseparated', 'words'] +filter(split(trim(s), ' '), # != '');{s: 'Ünïcödé wörds here'};['Ünïcödé', 'wörds', 'here'] +filter(split(trim(s), ' '), # != '');{s: null};!error +map(filter(split(s, ' '), # != ''), upper(#));{s: 'the quick brown fox'};['THE', 'QUICK', 'BROWN', 'FOX'] +map(filter(split(s, ' '), # != ''), upper(#));{s: ' leading and trailing '};['LEADING', 'AND', 'TRAILING'] +map(filter(split(s, ' '), # != ''), upper(#));{s: 'double space'};['DOUBLE', 'SPACE'] +map(filter(split(s, ' '), # != ''), upper(#));{s: 'one'};['ONE'] +map(filter(split(s, ' '), # != ''), upper(#));{s: ''};[] +map(filter(split(s, ' '), # != ''), upper(#));{s: 'tab\tseparated words'};['TAB\tSEPARATED', 'WORDS'] +map(filter(split(s, ' '), # != ''), upper(#));{s: 'Ünïcödé wörds here'};['ÜNÏCÖDÉ', 'WÖRDS', 'HERE'] +map(filter(split(s, ' '), # != ''), upper(#));{s: null};!error +max(map(filter(split(s, ' '), # != ''), len(#)));{s: 'the quick brown fox'};5 +max(map(filter(split(s, ' '), # != ''), len(#)));{s: ' leading and trailing '};8 +max(map(filter(split(s, ' '), # != ''), len(#)));{s: 'double space'};6 +max(map(filter(split(s, ' '), # != ''), len(#)));{s: 'one'};3 +max(map(filter(split(s, ' '), # != ''), len(#)));{s: ''};!error +max(map(filter(split(s, ' '), # != ''), len(#)));{s: 'aa bbb c'};3 +map(split(s, ','), number(#));{s: '1,2,3'};[1, 2, 3] +map(split(s, ','), number(#));{s: ' 10 , 20 '};[10, 20] +map(split(s, ','), number(#));{s: '1.50,2.25'};[1.50, 2.25] +map(split(s, ','), number(#));{s: '-1,1'};[-1, 1] +map(split(s, ','), number(#));{s: '7'};[7] +map(split(s, ','), number(#));{s: '1,x'};!error +map(split(s, ','), number(#));{s: ''};!error +map(split(s, ','), number(#));{s: null};!error +sum(map(split(s, ','), number(#)));{s: '1,2,3'};6 +sum(map(split(s, ','), number(#)));{s: ' 10 , 20 '};30 +sum(map(split(s, ','), number(#)));{s: '1.50,2.25'};3.75 +sum(map(split(s, ','), number(#)));{s: '-1,1'};0 +sum(map(split(s, ','), number(#)));{s: '7'};7 +sum(map(split(s, ','), number(#)));{s: '1,x'};!error +sum(map(split(s, ','), number(#)));{s: ''};!error +sum(map(split(s, ','), number(#)));{s: null};!error +sum(map(split(s, ','), number(trim(#)))) * 2;{s: '1,2,3'};12 +sum(map(split(s, ','), number(trim(#)))) * 2;{s: ' 10 , 20 '};60 +sum(map(split(s, ','), number(trim(#)))) * 2;{s: '1.50,2.25'};7.50 +sum(map(split(s, ','), number(trim(#)))) * 2;{s: '-1,1'};0 +sum(map(split(s, ','), number(trim(#)))) * 2;{s: '7'};14 +sum(map(split(s, ','), number(trim(#)))) * 2;{s: '1,x'};!error +sum(map(split(s, ','), number(trim(#)))) * 2;{s: ''};!error +sum(map(split(s, ','), number(trim(#)))) * 2;{s: null};!error +string(sum(map(split(s, ','), number(#))));{s: '1,2,3'};'6' +string(sum(map(split(s, ','), number(#))));{s: ' 10 , 20 '};'30' +string(sum(map(split(s, ','), number(#))));{s: '1.50,2.25'};'3.75' +string(sum(map(split(s, ','), number(#))));{s: '-1,1'};'0' +string(sum(map(split(s, ','), number(#))));{s: '7'};'7' +# split into parts: emails, paths, key-value pairs +split(email, '@')[1];{email: 'Joe.Doe@Example.COM'};'Example.COM' +split(email, '@')[1];{email: 'ann@mail.co.uk'};'mail.co.uk' +split(email, '@')[1];{email: 'no-at-sign'};null +split(email, '@')[1];{email: 'a@b@c'};'b' +split(email, '@')[1];{email: '@example.com'};'example.com' +split(email, '@')[1];{email: 'user@'};'' +split(email, '@')[1];{email: ''};null +split(email, '@')[1];{email: null};!error +lower(split(email, '@')[1] ?? '');{email: 'Joe.Doe@Example.COM'};'example.com' +lower(split(email, '@')[1] ?? '');{email: 'ann@mail.co.uk'};'mail.co.uk' +lower(split(email, '@')[1] ?? '');{email: 'no-at-sign'};'' +lower(split(email, '@')[1] ?? '');{email: 'a@b@c'};'b' +lower(split(email, '@')[1] ?? '');{email: '@example.com'};'example.com' +lower(split(email, '@')[1] ?? '');{email: 'user@'};'' +lower(split(email, '@')[1] ?? '');{email: ''};'' +lower(split(email, '@')[1] ?? '');{email: null};!error +lower(split(email, '@')[0]);{email: 'Joe.Doe@Example.COM'};'joe.doe' +lower(split(email, '@')[0]);{email: 'ann@mail.co.uk'};'ann' +lower(split(email, '@')[0]);{email: 'no-at-sign'};'no-at-sign' +lower(split(email, '@')[0]);{email: 'a@b@c'};'a' +lower(split(email, '@')[0]);{email: '@example.com'};'' +lower(split(email, '@')[0]);{email: 'user@'};'user' +lower(split(email, '@')[0]);{email: ''};'' +lower(split(email, '@')[0]);{email: null};!error +len(split(email, '@')) == 2;{email: 'Joe.Doe@Example.COM'};true +len(split(email, '@')) == 2;{email: 'ann@mail.co.uk'};true +len(split(email, '@')) == 2;{email: 'no-at-sign'};false +len(split(email, '@')) == 2;{email: 'a@b@c'};false +len(split(email, '@')) == 2;{email: '@example.com'};true +len(split(email, '@')) == 2;{email: 'user@'};true +len(split(email, '@')) == 2;{email: ''};false +len(split(email, '@')) == 2;{email: null};!error +split(lower(email), '@')[1] == 'example.com';{email: 'Joe.Doe@Example.COM'};true +split(lower(email), '@')[1] == 'example.com';{email: 'ann@mail.co.uk'};false +split(lower(email), '@')[1] == 'example.com';{email: 'no-at-sign'};false +split(lower(email), '@')[1] == 'example.com';{email: 'a@b@c'};false +split(lower(email), '@')[1] == 'example.com';{email: '@example.com'};true +split(lower(email), '@')[1] == 'example.com';{email: 'user@'};false +split(lower(email), '@')[1] == 'example.com';{email: ''};false +split(lower(email), '@')[1] == 'example.com';{email: null};!error +split(p, '/');{p: '/usr/local/bin'};['', 'usr', 'local', 'bin'] +split(p, '/');{p: 'a/b'};['a', 'b'] +split(p, '/');{p: '/'};['', ''] +split(p, '/');{p: ''};[''] +split(p, '/');{p: 'no-slash'};['no-slash'] +split(p, '/');{p: '/trailing/'};['', 'trailing', ''] +split(p, '/');{p: 'ä/ö'};['ä', 'ö'] +split(p, '/');{p: null};!error +filter(split(p, '/'), # != '');{p: '/usr/local/bin'};['usr', 'local', 'bin'] +filter(split(p, '/'), # != '');{p: 'a/b'};['a', 'b'] +filter(split(p, '/'), # != '');{p: '/'};[] +filter(split(p, '/'), # != '');{p: ''};[] +filter(split(p, '/'), # != '');{p: 'no-slash'};['no-slash'] +filter(split(p, '/'), # != '');{p: '/trailing/'};['trailing'] +filter(split(p, '/'), # != '');{p: 'ä/ö'};['ä', 'ö'] +filter(split(p, '/'), # != '');{p: null};!error +len(filter(split(p, '/'), # != ''));{p: '/usr/local/bin'};3 +len(filter(split(p, '/'), # != ''));{p: 'a/b'};2 +len(filter(split(p, '/'), # != ''));{p: '/'};0 +len(filter(split(p, '/'), # != ''));{p: ''};0 +len(filter(split(p, '/'), # != ''));{p: 'no-slash'};1 +len(filter(split(p, '/'), # != ''));{p: '/trailing/'};1 +len(filter(split(p, '/'), # != ''));{p: 'ä/ö'};2 +len(filter(split(p, '/'), # != ''));{p: null};!error +map(split(q, '&'), split(#, '='));{q: 'a=1&b=2'};[['a', '1'], ['b', '2']] +map(split(q, '&'), split(#, '='));{q: 'key=value'};[['key', 'value']] +map(split(q, '&'), split(#, '='));{q: 'x=&y=z'};[['x', ''], ['y', 'z']] +map(split(q, '&'), split(#, '='));{q: 'flag'};[['flag']] +map(split(q, '&'), split(#, '='));{q: ''};[['']] +map(split(q, '&'), split(#, '='));{q: 'a=1&a=2'};[['a', '1'], ['a', '2']] +map(split(q, '&'), split(#, '='));{q: 'k=v=w'};[['k', 'v', 'w']] +map(split(q, '&'), split(#, '='));{q: null};!error +map(split(q, '&'), split(#, '=')[0]);{q: 'a=1&b=2'};['a', 'b'] +map(split(q, '&'), split(#, '=')[0]);{q: 'key=value'};['key'] +map(split(q, '&'), split(#, '=')[0]);{q: 'x=&y=z'};['x', 'y'] +map(split(q, '&'), split(#, '=')[0]);{q: 'flag'};['flag'] +map(split(q, '&'), split(#, '=')[0]);{q: ''};[''] +map(split(q, '&'), split(#, '=')[0]);{q: 'a=1&a=2'};['a', 'a'] +map(split(q, '&'), split(#, '=')[0]);{q: 'k=v=w'};['k'] +map(split(q, '&'), split(#, '=')[0]);{q: null};!error +map(split(q, '&'), split(#, '=')[1] ?? '');{q: 'a=1&b=2'};['1', '2'] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: 'key=value'};['value'] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: 'x=&y=z'};['', 'z'] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: 'flag'};[''] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: ''};[''] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: 'a=1&a=2'};['1', '2'] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: 'k=v=w'};['v'] +map(split(q, '&'), split(#, '=')[1] ?? '');{q: null};!error +some(split(q, '&'), startsWith(#, 'a='));{q: 'a=1&b=2'};true +some(split(q, '&'), startsWith(#, 'a='));{q: 'key=value'};false +some(split(q, '&'), startsWith(#, 'a='));{q: 'x=&y=z'};false +some(split(q, '&'), startsWith(#, 'a='));{q: 'flag'};false +some(split(q, '&'), startsWith(#, 'a='));{q: ''};false +some(split(q, '&'), startsWith(#, 'a='));{q: 'a=1&a=2'};true +some(split(q, '&'), startsWith(#, 'a='));{q: 'k=v=w'};false +some(split(q, '&'), startsWith(#, 'a='));{q: null};!error +map(split(s, '|'), split(#, ','));{s: 'a,b|c,d'};[['a', 'b'], ['c', 'd']] +map(split(s, '|'), split(#, ','));{s: 'x|y'};[['x'], ['y']] +map(split(s, '|'), split(#, ','));{s: '|'};[[''], ['']] +map(split(s, '|'), split(#, ','));{s: 'one'};[['one']] +map(split(s, '|'), split(#, ','));{s: ''};[['']] +map(split(s, '|'), split(#, ','));{s: 'a,b,c|'};[['a', 'b', 'c'], ['']] +map(split(s, '|'), split(#, ','));{s: null};!error +split(split(s, '|')[0], ',');{s: 'a,b|c,d'};['a', 'b'] +split(split(s, '|')[0], ',');{s: 'x|y'};['x'] +split(split(s, '|')[0], ',');{s: '|'};[''] +split(split(s, '|')[0], ',');{s: 'one'};['one'] +split(split(s, '|')[0], ',');{s: ''};[''] +split(split(s, '|')[0], ',');{s: 'a,b,c|'};['a', 'b', 'c'] +split(split(s, '|')[0], ',');{s: null};!error +flatMap(split(s, '|'), split(#, ','));{s: 'a,b|c,d'};['a', 'b', 'c', 'd'] +flatMap(split(s, '|'), split(#, ','));{s: 'x|y'};['x', 'y'] +flatMap(split(s, '|'), split(#, ','));{s: '|'};['', ''] +flatMap(split(s, '|'), split(#, ','));{s: 'one'};['one'] +flatMap(split(s, '|'), split(#, ','));{s: ''};[''] +flatMap(split(s, '|'), split(#, ','));{s: 'a,b,c|'};['a', 'b', 'c', ''] +flatMap(split(s, '|'), split(#, ','));{s: null};!error +len(flatMap(split(s, '|'), split(#, ',')));{s: 'a,b|c,d'};4 +len(flatMap(split(s, '|'), split(#, ',')));{s: 'x|y'};2 +len(flatMap(split(s, '|'), split(#, ',')));{s: '|'};2 +len(flatMap(split(s, '|'), split(#, ',')));{s: 'one'};1 +len(flatMap(split(s, '|'), split(#, ',')));{s: ''};1 +len(flatMap(split(s, '|'), split(#, ',')));{s: 'a,b,c|'};4 +len(flatMap(split(s, '|'), split(#, ',')));{s: null};!error +# membership in split results +'vip' in split(s, ',');{s: 'vip,new'};true +'vip' in split(s, ',');{s: 'new'};false +'vip' in split(s, ',');{s: 'VIP'};false +'vip' in split(s, ',');{s: ' vip'};false +'vip' in split(s, ',');{s: 'vip'};true +'vip' in split(s, ',');{s: ''};false +'vip' in split(s, ',');{s: 'a,vip,b'};true +'vip' in split(s, ',');{s: null};!error +contains(split(s, ','), 'vip');{s: 'vip,new'};true +contains(split(s, ','), 'vip');{s: 'new'};false +contains(split(s, ','), 'vip');{s: 'VIP'};false +contains(split(s, ','), 'vip');{s: ' vip'};false +contains(split(s, ','), 'vip');{s: 'vip'};true +contains(split(s, ','), 'vip');{s: ''};false +contains(split(s, ','), 'vip');{s: 'a,vip,b'};true +contains(split(s, ','), 'vip');{s: null};!error +'vip' in map(split(s, ','), lower(trim(#)));{s: 'vip,new'};true +'vip' in map(split(s, ','), lower(trim(#)));{s: 'new'};false +'vip' in map(split(s, ','), lower(trim(#)));{s: 'VIP'};true +'vip' in map(split(s, ','), lower(trim(#)));{s: ' vip'};true +'vip' in map(split(s, ','), lower(trim(#)));{s: 'vip'};true +'vip' in map(split(s, ','), lower(trim(#)));{s: ''};false +'vip' in map(split(s, ','), lower(trim(#)));{s: 'a,vip,b'};true +'vip' in map(split(s, ','), lower(trim(#)));{s: null};!error +some(split(s, ','), lower(trim(#)) == 'vip');{s: 'vip,new'};true +some(split(s, ','), lower(trim(#)) == 'vip');{s: 'new'};false +some(split(s, ','), lower(trim(#)) == 'vip');{s: 'VIP'};true +some(split(s, ','), lower(trim(#)) == 'vip');{s: ' vip'};true +some(split(s, ','), lower(trim(#)) == 'vip');{s: 'vip'};true +some(split(s, ','), lower(trim(#)) == 'vip');{s: ''};false +some(split(s, ','), lower(trim(#)) == 'vip');{s: 'a,vip,b'};true +some(split(s, ','), lower(trim(#)) == 'vip');{s: null};!error +# string comparisons feeding decisions +s == 'GOLD' or lower(s) == 'gold';{s: 'GOLD'};true +s == 'GOLD' or lower(s) == 'gold';{s: 'gold'};true +s == 'GOLD' or lower(s) == 'gold';{s: 'Gold'};true +s == 'GOLD' or lower(s) == 'gold';{s: ' gold'};false +s == 'GOLD' or lower(s) == 'gold';{s: 'silver'};false +s == 'GOLD' or lower(s) == 'gold';{s: ''};false +s == 'GOLD' or lower(s) == 'gold';{s: null};!error +s == 'GOLD' or lower(s) == 'gold';{s: 1};!error +s == 'GOLD' or lower(s) == 'gold';{s: true};!error +s == 'GOLD' or lower(s) == 'gold';{};!error +s == 'GOLD' or s == 'gold';{s: 'GOLD'};true +s == 'GOLD' or s == 'gold';{s: 'gold'};true +s == 'GOLD' or s == 'gold';{s: 'Gold'};false +s == 'GOLD' or s == 'gold';{s: ' gold'};false +s == 'GOLD' or s == 'gold';{s: 'silver'};false +s == 'GOLD' or s == 'gold';{s: ''};false +s == 'GOLD' or s == 'gold';{s: null};false +s == 'GOLD' or s == 'gold';{s: 1};false +s == 'GOLD' or s == 'gold';{s: true};false +s == 'GOLD' or s == 'gold';{};false +lower(s) == 'gold' or s == 'GOLD';{s: 'GOLD'};true +lower(s) == 'gold' or s == 'GOLD';{s: 'gold'};true +lower(s) == 'gold' or s == 'GOLD';{s: 'Gold'};true +lower(s) == 'gold' or s == 'GOLD';{s: ' gold'};false +lower(s) == 'gold' or s == 'GOLD';{s: 'silver'};false +lower(s) == 'gold' or s == 'GOLD';{s: ''};false +lower(s) == 'gold' or s == 'GOLD';{s: null};!error +lower(s) == 'gold' or s == 'GOLD';{s: 1};!error +lower(s) == 'gold' or s == 'GOLD';{s: true};!error +lower(s) == 'gold' or s == 'GOLD';{};!error +s != null and lower(s) == 'gold';{s: 'GOLD'};true +s != null and lower(s) == 'gold';{s: 'gold'};true +s != null and lower(s) == 'gold';{s: 'Gold'};true +s != null and lower(s) == 'gold';{s: ' gold'};false +s != null and lower(s) == 'gold';{s: 'silver'};false +s != null and lower(s) == 'gold';{s: ''};false +s != null and lower(s) == 'gold';{s: null};false +s != null and lower(s) == 'gold';{s: 1};!error +s != null and lower(s) == 'gold';{s: true};!error +s != null and lower(s) == 'gold';{};false +type(s) == 'string' and lower(s) == 'gold';{s: 'GOLD'};true +type(s) == 'string' and lower(s) == 'gold';{s: 'gold'};true +type(s) == 'string' and lower(s) == 'gold';{s: 'Gold'};true +type(s) == 'string' and lower(s) == 'gold';{s: ' gold'};false +type(s) == 'string' and lower(s) == 'gold';{s: 'silver'};false +type(s) == 'string' and lower(s) == 'gold';{s: ''};false +type(s) == 'string' and lower(s) == 'gold';{s: null};false +type(s) == 'string' and lower(s) == 'gold';{s: 1};false +type(s) == 'string' and lower(s) == 'gold';{s: true};false +type(s) == 'string' and lower(s) == 'gold';{};false +lower(s ?? '') == 'gold';{s: 'GOLD'};true +lower(s ?? '') == 'gold';{s: 'gold'};true +lower(s ?? '') == 'gold';{s: 'Gold'};true +lower(s ?? '') == 'gold';{s: ' gold'};false +lower(s ?? '') == 'gold';{s: 'silver'};false +lower(s ?? '') == 'gold';{s: ''};false +lower(s ?? '') == 'gold';{s: null};false +lower(s ?? '') == 'gold';{s: 1};!error +lower(s ?? '') == 'gold';{s: true};!error +lower(s ?? '') == 'gold';{};false +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: 'GOLD'};0.2 +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: 'gold'};0.2 +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: 'Gold'};0.2 +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: ' gold'};0 +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: 'silver'};0.1 +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: ''};0 +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: null};!error +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: 1};!error +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{s: true};!error +lower(s) == 'gold' ? 0.2 : lower(s) == 'silver' ? 0.1 : 0;{};!error +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: 'GOLD'};'premium' +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: 'gold'};'premium' +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: 'Gold'};'premium' +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: ' gold'};'premium' +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: 'silver'};'standard' +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: ''};'standard' +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: null};!error +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: 1};!error +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{s: true};!error +upper(trim(s)) == 'GOLD' ? 'premium' : 'standard';{};!error +(s ?? '') == 'active';{s: 'active'};true +(s ?? '') == 'active';{s: 'Active'};false +(s ?? '') == 'active';{s: ''};false +(s ?? '') == 'active';{s: null};false +(s ?? '') == 'active';{};false +lower(s ?? 'unknown');{s: 'ACTIVE'};'active' +lower(s ?? 'unknown');{s: 'Pending'};'pending' +lower(s ?? 'unknown');{s: null};'unknown' +lower(s ?? 'unknown');{s: 5};!error +lower(s ?? 'unknown');{};'unknown' +trim(s) == '' ? 'blank' : trim(s);{s: ''};'blank' +trim(s) == '' ? 'blank' : trim(s);{s: ' '};'blank' +trim(s) == '' ? 'blank' : trim(s);{s: '\t\n'};'blank' +trim(s) == '' ? 'blank' : trim(s);{s: ' x '};'x' +trim(s) == '' ? 'blank' : trim(s);{s: 'y'};'y' +trim(s) == '' ? 'blank' : trim(s);{s: null};!error +trim(s) == '' ? 'blank' : trim(s);{};!error +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: 'abc'};true +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: ' '};false +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: '0123456789'};true +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: '01234567890'};false +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: ' 0123456789 '};true +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: ''};false +len(trim(s)) > 0 and len(trim(s)) <= 10;{s: null};!error +len(trim(s)) > 0 and len(trim(s)) <= 10;{};!error +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{s: 'URGENT: fix'};1 +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{s: 'High priority'};2 +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{s: 'low'};3 +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{s: 'highly urgent'};1 +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{s: ''};3 +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{s: null};!error +contains(lower(s), 'urgent') ? 1 : contains(lower(s), 'high') ? 2 : 3;{};!error +status == 'open' and (lower(owner) == 'me' or owner == null);{status: 'open', owner: 'ME'};true +status == 'open' and (lower(owner) == 'me' or owner == null);{status: 'open', owner: 'you'};false +status == 'open' and (lower(owner) == 'me' or owner == null);{status: 'closed', owner: 'me'};false +status == 'open' and (lower(owner) == 'me' or owner == null);{status: 'open'};!error +status == 'open' and (lower(owner) == 'me' or owner == null);{status: 'Open', owner: 'me'};false +startsWith(s, t) and endsWith(s, t);{s: 'abcab', t: 'ab'};true +startsWith(s, t) and endsWith(s, t);{s: 'aba', t: 'aba'};true +startsWith(s, t) and endsWith(s, t);{s: 'abc', t: 'a'};false +startsWith(s, t) and endsWith(s, t);{s: 'x', t: ''};true +startsWith(s, t) and endsWith(s, t);{s: '', t: ''};true +startsWith(s, t) and endsWith(s, t);{s: 'ab', t: 'abc'};false +startsWith(s, t) and endsWith(s, t);{s: 'ab', t: null};!error +# initials and capitalization with slices +upper(first[0:0]) + '. ' + upper(last[0:0]) + '.';{first: 'ada', last: 'lovelace'};'A. L.' +upper(first[0:0]) + '. ' + upper(last[0:0]) + '.';{first: 'Grace', last: 'Hopper'};'G. H.' +upper(first[0:0]) + '. ' + upper(last[0:0]) + '.';{first: 'x', last: 'y'};'X. Y.' +upper(first[0:0]) + '. ' + upper(last[0:0]) + '.';{first: 'élodie', last: 'dupont'};'É. D.';bug: string slices use UTF-8 byte offsets instead of characters +upper(first[0:0]) + '. ' + upper(last[0:0]) + '.';{first: 'ann', last: null};!error +upper(first[0:0]) + '. ' + upper(last[0:0]) + '.';{first: 'ann'};!error +upper(first[0]) + lower(first[1:]);{first: 'ada', last: 'lovelace'};'Ada' +upper(first[0]) + lower(first[1:]);{first: 'Grace', last: 'Hopper'};'Grace' +upper(first[0]) + lower(first[1:]);{first: 'x', last: 'y'};'X' +upper(first[0]) + lower(first[1:]);{first: 'élodie', last: 'dupont'};'Élodie';bug: string indexing uses UTF-8 byte offsets instead of characters +upper(first[0]) + lower(first[1:]);{first: 'ann', last: null};'Ann' +upper(first[0]) + lower(first[1:]);{first: 'ann'};'Ann' +upper(s[0:0]) + s[1:];{s: 'hello'};'Hello' +upper(s[0:0]) + s[1:];{s: 'h'};'H' +upper(s[0:0]) + s[1:];{s: 'hELLO'};'HELLO' +upper(s[0:0]) + s[1:];{s: 'élan'};'Élan';bug: string slices use UTF-8 byte offsets instead of characters +upper(s[0:0]) + s[1:];{s: ' space'};' space' +upper(s[0:0]) + s[1:];{s: null};!error +upper(s[0:0]) + s[1:];{};!error +lower(s[0:2]) == 'abc';{s: 'ABCDEF'};true +lower(s[0:2]) == 'abc';{s: 'abc'};true +lower(s[0:2]) == 'abc';{s: 'abx'};false +lower(s[0:2]) == 'abc';{s: 'ab'};!error +lower(s[0:2]) == 'abc';{s: 'AbC-1'};true +lower(s[0:2]) == 'abc';{};!error +upper(s[0:1]) == 'US';{s: 'us-east'};true +upper(s[0:1]) == 'US';{s: 'US'};true +upper(s[0:1]) == 'US';{s: 'uk'};false +upper(s[0:1]) == 'US';{s: 'u'};!error +upper(s[0:1]) == 'US';{s: 'Us1'};true +upper(s[0:1]) == 'US';{};!error +# number and string round trips +number(trim(s)) * 2;{s: ' 12 '};24 +number(trim(s)) * 2;{s: '1.25'};2.50 +number(trim(s)) * 2;{s: '-3'};-6 +number(trim(s)) * 2;{s: 'x'};!error +number(trim(s)) * 2;{s: ''};!error +number(trim(s)) * 2;{s: null};!error +number(trim(s)) * 2;{};!error +string(number(s)) == trim(s);{s: '12'};true +string(number(s)) == trim(s);{s: ' 12'};true +string(number(s)) == trim(s);{s: '1.50'};true +string(number(s)) == trim(s);{s: '007'};false +string(number(s)) == trim(s);{s: '-0.5'};true +string(number(s)) == trim(s);{s: 'x'};!error +string(number(s)) == trim(s);{};!error +string(n) + ' ' + upper(unit);{n: 12, unit: 'kg'};'12 KG' +string(n) + ' ' + upper(unit);{n: 1.50, unit: 'lb'};'1.50 LB' +string(n) + ' ' + upper(unit);{n: null, unit: 'g'};'null G' +string(n) + ' ' + upper(unit);{n: 1, unit: null};!error +string(n) + ' ' + upper(unit);{n: true, unit: 'x'};'true X' +string(n) + ' ' + upper(unit);{n: 'five', unit: 'm'};'five M' +len(string(n));{n: 100};3 +len(string(n));{n: 1.50};4 +len(string(n));{n: -0.001};6 +len(string(n));{n: null};4 +len(string(n));{n: true};4 +len(string(n));{n: 'abc'};3 +# properties over many strings +trim(trim(s)) == trim(s);{s: ''};true +trim(trim(s)) == trim(s);{s: 'a'};true +trim(trim(s)) == trim(s);{s: 'Hello'};true +trim(trim(s)) == trim(s);{s: ' padded '};true +trim(trim(s)) == trim(s);{s: 'MiXeD CaSe'};true +trim(trim(s)) == trim(s);{s: 'straße'};true +trim(trim(s)) == trim(s);{s: 'ΣΑΣ'};true +trim(trim(s)) == trim(s);{s: 'İ'};true +trim(trim(s)) == trim(s);{s: 'file'};true +trim(trim(s)) == trim(s);{s: 'Dž'};true +trim(trim(s)) == trim(s);{s: '日本語'};true +trim(trim(s)) == trim(s);{s: '😀 ok'};true +trim(trim(s)) == trim(s);{s: 'a\tb\nc'};true +trim(trim(s)) == trim(s);{s: '\u00a0x\u00a0'};true +trim(trim(s)) == trim(s);{s: 'ABC'};true +upper(upper(s)) == upper(s);{s: ''};true +upper(upper(s)) == upper(s);{s: 'a'};true +upper(upper(s)) == upper(s);{s: 'Hello'};true +upper(upper(s)) == upper(s);{s: ' padded '};true +upper(upper(s)) == upper(s);{s: 'MiXeD CaSe'};true +upper(upper(s)) == upper(s);{s: 'straße'};true +upper(upper(s)) == upper(s);{s: 'ΣΑΣ'};true +upper(upper(s)) == upper(s);{s: 'İ'};true +upper(upper(s)) == upper(s);{s: 'file'};true +upper(upper(s)) == upper(s);{s: 'Dž'};true +upper(upper(s)) == upper(s);{s: '日本語'};true +upper(upper(s)) == upper(s);{s: '😀 ok'};true +upper(upper(s)) == upper(s);{s: 'a\tb\nc'};true +upper(upper(s)) == upper(s);{s: '\u00a0x\u00a0'};true +upper(upper(s)) == upper(s);{s: 'ABC'};true +lower(lower(s)) == lower(s);{s: ''};true +lower(lower(s)) == lower(s);{s: 'a'};true +lower(lower(s)) == lower(s);{s: 'Hello'};true +lower(lower(s)) == lower(s);{s: ' padded '};true +lower(lower(s)) == lower(s);{s: 'MiXeD CaSe'};true +lower(lower(s)) == lower(s);{s: 'straße'};true +lower(lower(s)) == lower(s);{s: 'ΣΑΣ'};true +lower(lower(s)) == lower(s);{s: 'İ'};true +lower(lower(s)) == lower(s);{s: 'file'};true +lower(lower(s)) == lower(s);{s: 'Dž'};true +lower(lower(s)) == lower(s);{s: '日本語'};true +lower(lower(s)) == lower(s);{s: '😀 ok'};true +lower(lower(s)) == lower(s);{s: 'a\tb\nc'};true +lower(lower(s)) == lower(s);{s: '\u00a0x\u00a0'};true +lower(lower(s)) == lower(s);{s: 'ABC'};true +upper(lower(s)) == upper(s);{s: ''};true +upper(lower(s)) == upper(s);{s: 'a'};true +upper(lower(s)) == upper(s);{s: 'Hello'};true +upper(lower(s)) == upper(s);{s: ' padded '};true +upper(lower(s)) == upper(s);{s: 'MiXeD CaSe'};true +upper(lower(s)) == upper(s);{s: 'straße'};true +upper(lower(s)) == upper(s);{s: 'ΣΑΣ'};true +upper(lower(s)) == upper(s);{s: 'İ'};false +upper(lower(s)) == upper(s);{s: 'file'};true +upper(lower(s)) == upper(s);{s: 'Dž'};true +upper(lower(s)) == upper(s);{s: '日本語'};true +upper(lower(s)) == upper(s);{s: '😀 ok'};true +upper(lower(s)) == upper(s);{s: 'a\tb\nc'};true +upper(lower(s)) == upper(s);{s: '\u00a0x\u00a0'};true +upper(lower(s)) == upper(s);{s: 'ABC'};true +lower(upper(s)) == lower(s);{s: ''};true +lower(upper(s)) == lower(s);{s: 'a'};true +lower(upper(s)) == lower(s);{s: 'Hello'};true +lower(upper(s)) == lower(s);{s: ' padded '};true +lower(upper(s)) == lower(s);{s: 'MiXeD CaSe'};true +lower(upper(s)) == lower(s);{s: 'straße'};false +lower(upper(s)) == lower(s);{s: 'ΣΑΣ'};true +lower(upper(s)) == lower(s);{s: 'İ'};true +lower(upper(s)) == lower(s);{s: 'file'};false +lower(upper(s)) == lower(s);{s: 'Dž'};true +lower(upper(s)) == lower(s);{s: '日本語'};true +lower(upper(s)) == lower(s);{s: '😀 ok'};true +lower(upper(s)) == lower(s);{s: 'a\tb\nc'};true +lower(upper(s)) == lower(s);{s: '\u00a0x\u00a0'};true +lower(upper(s)) == lower(s);{s: 'ABC'};true +upper(s);{s: ''};'' +upper(s);{s: 'a'};'A' +upper(s);{s: 'Hello'};'HELLO' +upper(s);{s: ' padded '};' PADDED ' +upper(s);{s: 'MiXeD CaSe'};'MIXED CASE' +upper(s);{s: 'straße'};'STRASSE' +upper(s);{s: 'ΣΑΣ'};'ΣΑΣ' +upper(s);{s: 'İ'};'İ' +upper(s);{s: 'file'};'FILE' +upper(s);{s: 'Dž'};'DŽ' +upper(s);{s: '日本語'};'日本語' +upper(s);{s: '😀 ok'};'😀 OK' +upper(s);{s: 'a\tb\nc'};'A\tB\nC' +upper(s);{s: '\u00a0x\u00a0'};'\u00a0X\u00a0' +upper(s);{s: 'ABC'};'ABC' +lower(s);{s: ''};'' +lower(s);{s: 'a'};'a' +lower(s);{s: 'Hello'};'hello' +lower(s);{s: ' padded '};' padded ' +lower(s);{s: 'MiXeD CaSe'};'mixed case' +lower(s);{s: 'straße'};'straße' +lower(s);{s: 'ΣΑΣ'};'σας' +lower(s);{s: 'İ'};'i̇' +lower(s);{s: 'file'};'file' +lower(s);{s: 'Dž'};'dž' +lower(s);{s: '日本語'};'日本語' +lower(s);{s: '😀 ok'};'😀 ok' +lower(s);{s: 'a\tb\nc'};'a\tb\nc' +lower(s);{s: '\u00a0x\u00a0'};'\u00a0x\u00a0' +lower(s);{s: 'ABC'};'abc' +trim(s);{s: ''};'' +trim(s);{s: 'a'};'a' +trim(s);{s: 'Hello'};'Hello' +trim(s);{s: ' padded '};'padded' +trim(s);{s: 'MiXeD CaSe'};'MiXeD CaSe' +trim(s);{s: 'straße'};'straße' +trim(s);{s: 'ΣΑΣ'};'ΣΑΣ' +trim(s);{s: 'İ'};'İ' +trim(s);{s: 'file'};'file' +trim(s);{s: 'Dž'};'Dž' +trim(s);{s: '日本語'};'日本語' +trim(s);{s: '😀 ok'};'😀 ok' +trim(s);{s: 'a\tb\nc'};'a\tb\nc' +trim(s);{s: '\u00a0x\u00a0'};'x' +trim(s);{s: 'ABC'};'ABC' +contains(s, trim(s));{s: ''};true +contains(s, trim(s));{s: 'a'};true +contains(s, trim(s));{s: 'Hello'};true +contains(s, trim(s));{s: ' padded '};true +contains(s, trim(s));{s: 'MiXeD CaSe'};true +contains(s, trim(s));{s: 'straße'};true +contains(s, trim(s));{s: 'ΣΑΣ'};true +contains(s, trim(s));{s: 'İ'};true +contains(s, trim(s));{s: 'file'};true +contains(s, trim(s));{s: 'Dž'};true +contains(s, trim(s));{s: '日本語'};true +contains(s, trim(s));{s: '😀 ok'};true +contains(s, trim(s));{s: 'a\tb\nc'};true +contains(s, trim(s));{s: '\u00a0x\u00a0'};true +contains(s, trim(s));{s: 'ABC'};true +startsWith(s, s) and endsWith(s, s);{s: ''};true +startsWith(s, s) and endsWith(s, s);{s: 'a'};true +startsWith(s, s) and endsWith(s, s);{s: 'Hello'};true +startsWith(s, s) and endsWith(s, s);{s: ' padded '};true +startsWith(s, s) and endsWith(s, s);{s: 'MiXeD CaSe'};true +startsWith(s, s) and endsWith(s, s);{s: 'straße'};true +startsWith(s, s) and endsWith(s, s);{s: 'ΣΑΣ'};true +startsWith(s, s) and endsWith(s, s);{s: 'İ'};true +startsWith(s, s) and endsWith(s, s);{s: 'file'};true +startsWith(s, s) and endsWith(s, s);{s: 'Dž'};true +startsWith(s, s) and endsWith(s, s);{s: '日本語'};true +startsWith(s, s) and endsWith(s, s);{s: '😀 ok'};true +startsWith(s, s) and endsWith(s, s);{s: 'a\tb\nc'};true +startsWith(s, s) and endsWith(s, s);{s: '\u00a0x\u00a0'};true +startsWith(s, s) and endsWith(s, s);{s: 'ABC'};true +s + '' == s;{s: ''};true +s + '' == s;{s: 'a'};true +s + '' == s;{s: 'Hello'};true +s + '' == s;{s: ' padded '};true +s + '' == s;{s: 'MiXeD CaSe'};true +s + '' == s;{s: 'straße'};true +s + '' == s;{s: 'ΣΑΣ'};true +s + '' == s;{s: 'İ'};true +len(split(s, t)) - 1;{s: 'a,b,c', t: ','};2 +len(split(s, t)) - 1;{s: 'aaa', t: 'a'};3 +len(split(s, t)) - 1;{s: 'abcabc', t: 'bc'};2 +len(split(s, t)) - 1;{s: 'none', t: ','};0 +len(split(s, t)) - 1;{s: '', t: ','};0 +len(split(s, t)) - 1;{s: 'x--y--z', t: '--'};2 +len(split(s, t)) - 1;{s: 'ß,ß', t: ','};1 +contains(s, t) == (len(split(s, t)) > 1);{s: 'a,b,c', t: ','};true +contains(s, t) == (len(split(s, t)) > 1);{s: 'aaa', t: 'a'};true +contains(s, t) == (len(split(s, t)) > 1);{s: 'abcabc', t: 'bc'};true +contains(s, t) == (len(split(s, t)) > 1);{s: 'none', t: ','};true +contains(s, t) == (len(split(s, t)) > 1);{s: '', t: ','};true +contains(s, t) == (len(split(s, t)) > 1);{s: 'x--y--z', t: '--'};true +contains(s, t) == (len(split(s, t)) > 1);{s: 'ß,ß', t: ','};true +startsWith(s, t) == (split(s, t)[0] == '');{s: 'a,b,c', t: ','};true +startsWith(s, t) == (split(s, t)[0] == '');{s: 'aaa', t: 'a'};true +startsWith(s, t) == (split(s, t)[0] == '');{s: 'abcabc', t: 'bc'};true +startsWith(s, t) == (split(s, t)[0] == '');{s: 'none', t: ','};true +startsWith(s, t) == (split(s, t)[0] == '');{s: '', t: ','};false +startsWith(s, t) == (split(s, t)[0] == '');{s: 'x--y--z', t: '--'};true +startsWith(s, t) == (split(s, t)[0] == '');{s: 'ß,ß', t: ','};true +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: 'a,b,c', t: ','};true +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: 'aaa', t: 'a'};true +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: 'abcabc', t: 'bc'};true +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: 'none', t: ','};true +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: '', t: ','};false +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: 'x--y--z', t: '--'};true +endsWith(s, t) == (split(s, t)[len(split(s, t)) - 1] == '');{s: 'ß,ß', t: ','};true diff --git a/core/expression/tests/spec/standard/15-02-closures.csv b/core/expression/tests/spec/standard/15-02-closures.csv new file mode 100644 index 00000000..afaae2f6 --- /dev/null +++ b/core/expression/tests/spec/standard/15-02-closures.csv @@ -0,0 +1,393 @@ +expression (string);input (json 5);output (json 5);note +# string building inside closures +map(names, upper(#[0:0]) + #[1:]);{names: ['alice', 'bob']};['Alice', 'Bob'] +map(names, upper(#[0:0]) + #[1:]);{names: ['Ann', 'JOHN', 'mary']};['Ann', 'JOHN', 'Mary'] +map(names, upper(#[0:0]) + #[1:]);{names: ['x']};['X'] +map(names, upper(#[0:0]) + #[1:]);{names: []};[] +map(names, upper(#[0:0]) + #[1:]);{names: ['élan', 'zoë']};['Élan', 'Zoë'];bug: string slices use UTF-8 byte offsets instead of characters +map(names, upper(#[0:0]) + #[1:]);{names: ['alice', null]};!error +map(names, upper(#[0:0]) + #[1:]);{names: ['a', 5]};!error +map(names, upper(#[0:0]) + #[1:]);{names: 'alice'};!error +map(names, upper(#[0:0]) + #[1:]);{names: null};!error +map(names, upper(#[0:0]) + #[1:]);{};!error +map(names, upper(#[0]) + lower(#[1:]));{names: ['alice', 'bob']};['Alice', 'Bob'] +map(names, upper(#[0]) + lower(#[1:]));{names: ['Ann', 'JOHN', 'mary']};['Ann', 'John', 'Mary'] +map(names, upper(#[0]) + lower(#[1:]));{names: ['x']};['X'] +map(names, upper(#[0]) + lower(#[1:]));{names: []};[] +map(names, upper(#[0]) + lower(#[1:]));{names: ['élan', 'zoë']};['Élan', 'Zoë'];bug: string indexing uses UTF-8 byte offsets instead of characters +map(names, upper(#[0]) + lower(#[1:]));{names: ['alice', null]};!error +map(names, upper(#[0]) + lower(#[1:]));{names: ['a', 5]};!error +map(names, upper(#[0]) + lower(#[1:]));{names: 'alice'};!error +map(names, upper(#[0]) + lower(#[1:]));{names: null};!error +map(names, upper(#[0]) + lower(#[1:]));{};!error +map(names, upper(#));{names: ['alice', 'bob']};['ALICE', 'BOB'] +map(names, upper(#));{names: ['Ann', 'JOHN', 'mary']};['ANN', 'JOHN', 'MARY'] +map(names, upper(#));{names: ['x']};['X'] +map(names, upper(#));{names: []};[] +map(names, upper(#));{names: ['élan', 'zoë']};['ÉLAN', 'ZOË'] +map(names, upper(#));{names: ['alice', null]};!error +map(names, upper(#));{names: ['a', 5]};!error +map(names, upper(#));{names: 'alice'};!error +map(names, upper(#));{names: null};!error +map(names, upper(#));{};!error +map(names, trim(lower(#)));{names: ['alice', 'bob']};['alice', 'bob'] +map(names, trim(lower(#)));{names: ['Ann', 'JOHN', 'mary']};['ann', 'john', 'mary'] +map(names, trim(lower(#)));{names: ['x']};['x'] +map(names, trim(lower(#)));{names: []};[] +map(names, trim(lower(#)));{names: ['élan', 'zoë']};['élan', 'zoë'] +map(names, trim(lower(#)));{names: ['alice', null]};!error +map(names, trim(lower(#)));{names: ['a', 5]};!error +map(names, trim(lower(#)));{names: 'alice'};!error +map(names, trim(lower(#)));{names: null};!error +map(names, trim(lower(#)));{};!error +map(names, '<' + # + '>');{names: ['alice', 'bob']};['', ''] +map(names, '<' + # + '>');{names: ['Ann', 'JOHN', 'mary']};['', '', ''] +map(names, '<' + # + '>');{names: ['x']};[''] +map(names, '<' + # + '>');{names: []};[] +map(names, '<' + # + '>');{names: ['élan', 'zoë']};['<élan>', ''] +map(names, '<' + # + '>');{names: ['alice', null]};!error +map(names, '<' + # + '>');{names: ['a', 5]};!error +map(names, '<' + # + '>');{names: 'alice'};!error +map(names, '<' + # + '>');{names: null};!error +map(names, '<' + # + '>');{};!error +map(names, # + '!' + #);{names: ['alice', 'bob']};['alice!alice', 'bob!bob'] +map(names, # + '!' + #);{names: ['Ann', 'JOHN', 'mary']};['Ann!Ann', 'JOHN!JOHN', 'mary!mary'] +map(names, # + '!' + #);{names: ['x']};['x!x'] +map(names, # + '!' + #);{names: []};[] +map(names, # + '!' + #);{names: ['élan', 'zoë']};['élan!élan', 'zoë!zoë'] +map(names, # + '!' + #);{names: ['alice', null]};!error +map(names, # + '!' + #);{names: ['a', 5]};!error +map(names, # + '!' + #);{names: 'alice'};!error +map(names, # + '!' + #);{names: null};!error +map(names, # + '!' + #);{};!error +map(names, len(#));{names: ['alice', 'bob']};[5, 3] +map(names, len(#));{names: ['Ann', 'JOHN', 'mary']};[3, 4, 4] +map(names, len(#));{names: ['x']};[1] +map(names, len(#));{names: []};[] +map(names, len(#));{names: ['élan', 'zoë']};[4, 3];bug: len counts UTF-8 bytes, intended character count +map(names, len(#));{names: ['alice', null]};!error +map(names, len(#));{names: ['a', 5]};!error +map(names, len(#));{names: 'alice'};!error +map(names, len(#));{names: null};!error +map(names, len(#));{};!error +map(names, #[0] ?? '?');{names: ['alice', 'bob']};['a', 'b'] +map(names, #[0] ?? '?');{names: ['Ann', 'JOHN', 'mary']};['A', 'J', 'm'] +map(names, #[0] ?? '?');{names: ['x']};['x'] +map(names, #[0] ?? '?');{names: []};[] +map(names, #[0] ?? '?');{names: ['élan', 'zoë']};['é', 'z'];bug: string indexing uses UTF-8 byte offsets instead of characters +map(names, #[0] ?? '?');{names: ['', 'b']};['?', 'b'] +# title case of free text +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: 'hello world'};['Hello', 'World'] +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: 'the QUICK brown'};['The', 'Quick', 'Brown'] +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: 'a'};['A'] +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: 'x y z'};['X', 'Y', 'Z'] +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: 'jean luc picard'};['Jean', 'Luc', 'Picard'] +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: 'one two'};['One', 'Two'] +map(split(s, ' '), upper(#[0:0]) + lower(#[1:]));{s: null};!error +map(split(s, ' '), upper(#[0]) + #[1:]);{s: 'hello world'};['Hello', 'World'] +map(split(s, ' '), upper(#[0]) + #[1:]);{s: 'the QUICK brown'};['The', 'QUICK', 'Brown'] +map(split(s, ' '), upper(#[0]) + #[1:]);{s: 'a'};['A'] +map(split(s, ' '), upper(#[0]) + #[1:]);{s: 'x y z'};['X', 'Y', 'Z'] +map(split(s, ' '), upper(#[0]) + #[1:]);{s: 'jean luc picard'};['Jean', 'Luc', 'Picard'] +map(split(s, ' '), upper(#[0]) + #[1:]);{s: 'one two'};['One', 'Two'] +map(split(s, ' '), upper(#[0]) + #[1:]);{s: null};!error +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: 'hello world'};['Hello', 'World'] +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: 'the QUICK brown'};['the', 'Quick', 'Brown'] +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: 'a'};['a'] +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: 'x y z'};['x', 'y', 'z'] +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: 'jean luc picard'};['Jean', 'luc', 'Picard'] +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: 'one two'};['one', 'two'] +map(split(lower(s), ' '), len(#) > 3 ? upper(#[0:0]) + #[1:] : #);{s: null};!error +# predicates over string arrays +some(tags, lower(#) == 'vip');{tags: ['VIP', 'new']};true +some(tags, lower(#) == 'vip');{tags: ['vip']};true +some(tags, lower(#) == 'vip');{tags: [' Vip ']};false +some(tags, lower(#) == 'vip');{tags: ['regular']};false +some(tags, lower(#) == 'vip');{tags: []};false +some(tags, lower(#) == 'vip');{tags: ['a', 'b', 'VIP', 'vip']};true +some(tags, lower(#) == 'vip');{tags: ['x', null]};!error +some(tags, lower(#) == 'vip');{tags: null};!error +some(tags, lower(trim(#)) == 'vip');{tags: ['VIP', 'new']};true +some(tags, lower(trim(#)) == 'vip');{tags: ['vip']};true +some(tags, lower(trim(#)) == 'vip');{tags: [' Vip ']};true +some(tags, lower(trim(#)) == 'vip');{tags: ['regular']};false +some(tags, lower(trim(#)) == 'vip');{tags: []};false +some(tags, lower(trim(#)) == 'vip');{tags: ['a', 'b', 'VIP', 'vip']};true +some(tags, lower(trim(#)) == 'vip');{tags: ['x', null]};!error +some(tags, lower(trim(#)) == 'vip');{tags: null};!error +count(tags, lower(#) == 'vip');{tags: ['VIP', 'new']};1 +count(tags, lower(#) == 'vip');{tags: ['vip']};1 +count(tags, lower(#) == 'vip');{tags: [' Vip ']};0 +count(tags, lower(#) == 'vip');{tags: ['regular']};0 +count(tags, lower(#) == 'vip');{tags: []};0 +count(tags, lower(#) == 'vip');{tags: ['a', 'b', 'VIP', 'vip']};2 +count(tags, lower(#) == 'vip');{tags: ['x', null]};!error +count(tags, lower(#) == 'vip');{tags: null};!error +one(tags, upper(#) == 'VIP');{tags: ['VIP', 'new']};true +one(tags, upper(#) == 'VIP');{tags: ['vip']};true +one(tags, upper(#) == 'VIP');{tags: [' Vip ']};false +one(tags, upper(#) == 'VIP');{tags: ['regular']};false +one(tags, upper(#) == 'VIP');{tags: []};false +one(tags, upper(#) == 'VIP');{tags: ['a', 'b', 'VIP', 'vip']};false +one(tags, upper(#) == 'VIP');{tags: ['x', null]};!error +one(tags, upper(#) == 'VIP');{tags: null};!error +none(tags, contains(lower(#), 'vip'));{tags: ['VIP', 'new']};false +none(tags, contains(lower(#), 'vip'));{tags: ['vip']};false +none(tags, contains(lower(#), 'vip'));{tags: [' Vip ']};false +none(tags, contains(lower(#), 'vip'));{tags: ['regular']};true +none(tags, contains(lower(#), 'vip'));{tags: []};true +none(tags, contains(lower(#), 'vip'));{tags: ['a', 'b', 'VIP', 'vip']};false +none(tags, contains(lower(#), 'vip'));{tags: ['x', null]};!error +none(tags, contains(lower(#), 'vip'));{tags: null};!error +all(tags, upper(#) == #);{tags: ['VIP', 'new']};false +all(tags, upper(#) == #);{tags: ['vip']};false +all(tags, upper(#) == #);{tags: [' Vip ']};false +all(tags, upper(#) == #);{tags: ['regular']};false +all(tags, upper(#) == #);{tags: []};true +all(tags, upper(#) == #);{tags: ['a', 'b', 'VIP', 'vip']};false +all(tags, upper(#) == #);{tags: ['x', null]};false +all(tags, upper(#) == #);{tags: null};!error +filter(tags, lower(#) != 'vip');{tags: ['VIP', 'new']};['new'] +filter(tags, lower(#) != 'vip');{tags: ['vip']};[] +filter(tags, lower(#) != 'vip');{tags: [' Vip ']};[' Vip '] +filter(tags, lower(#) != 'vip');{tags: ['regular']};['regular'] +filter(tags, lower(#) != 'vip');{tags: []};[] +filter(tags, lower(#) != 'vip');{tags: ['a', 'b', 'VIP', 'vip']};['a', 'b'] +filter(tags, lower(#) != 'vip');{tags: ['x', null]};!error +filter(tags, lower(#) != 'vip');{tags: null};!error +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: ['VIP', 'new']};['vip', 'new'] +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: ['vip']};['vip'] +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: [' Vip ']};['vip'] +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: ['regular']};['regular'] +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: []};[] +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: ['a', 'b', 'VIP', 'vip']};['a', 'b', 'vip', 'vip'] +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: ['x', null]};!error +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: null};!error +map(filter(tags, len(trim(#)) > 0), lower(trim(#)));{tags: [' ', 'A ', '']};['a'] +all(codes, matches(#, '^[A-Z]{3}$'));{codes: ['USD', 'EUR', 'GBP']};true +all(codes, matches(#, '^[A-Z]{3}$'));{codes: ['usd', 'EUR']};false +all(codes, matches(#, '^[A-Z]{3}$'));{codes: ['US', 'EURO']};false +all(codes, matches(#, '^[A-Z]{3}$'));{codes: []};true +all(codes, matches(#, '^[A-Z]{3}$'));{codes: ['USD', '']};false +all(codes, matches(#, '^[A-Z]{3}$'));{codes: ['ÄÖÜ']};false +all(codes, matches(#, '^[A-Z]{3}$'));{codes: ['USD', 1]};!error +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: ['USD', 'EUR', 'GBP']};[] +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: ['usd', 'EUR']};['usd'] +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: ['US', 'EURO']};['US', 'EURO'] +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: []};[] +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: ['USD', '']};[''] +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: ['ÄÖÜ']};['ÄÖÜ'] +filter(codes, not matches(#, '^[A-Z]{3}$'));{codes: ['USD', 1]};!error +map(codes, upper(#) in ['USD', 'EUR']);{codes: ['USD', 'EUR', 'GBP']};[true, true, false] +map(codes, upper(#) in ['USD', 'EUR']);{codes: ['usd', 'EUR']};[true, true] +map(codes, upper(#) in ['USD', 'EUR']);{codes: ['US', 'EURO']};[false, false] +map(codes, upper(#) in ['USD', 'EUR']);{codes: []};[] +map(codes, upper(#) in ['USD', 'EUR']);{codes: ['USD', '']};[true, false] +map(codes, upper(#) in ['USD', 'EUR']);{codes: ['ÄÖÜ']};[false] +map(codes, upper(#) in ['USD', 'EUR']);{codes: ['USD', 1]};!error +none(emails, endsWith(lower(#), '.ru'));{emails: ['a@x.com', 'B@Y.ORG']};true +none(emails, endsWith(lower(#), '.ru'));{emails: ['bad', 'c@d.ru']};false +none(emails, endsWith(lower(#), '.ru'));{emails: ['x@spam.ru', 'y@mail.RU']};false +none(emails, endsWith(lower(#), '.ru'));{emails: []};true +none(emails, endsWith(lower(#), '.ru'));{emails: ['a@b']};true +none(emails, endsWith(lower(#), '.ru'));{emails: [null]};!error +map(emails, split(#, '@')[1] ?? '');{emails: ['a@x.com', 'B@Y.ORG']};['x.com', 'Y.ORG'] +map(emails, split(#, '@')[1] ?? '');{emails: ['bad', 'c@d.ru']};['', 'd.ru'] +map(emails, split(#, '@')[1] ?? '');{emails: ['x@spam.ru', 'y@mail.RU']};['spam.ru', 'mail.RU'] +map(emails, split(#, '@')[1] ?? '');{emails: []};[] +map(emails, split(#, '@')[1] ?? '');{emails: ['a@b']};['b'] +map(emails, split(#, '@')[1] ?? '');{emails: [null]};!error +map(emails, lower(split(#, '@')[0]));{emails: ['a@x.com', 'B@Y.ORG']};['a', 'b'] +map(emails, lower(split(#, '@')[0]));{emails: ['bad', 'c@d.ru']};['bad', 'c'] +map(emails, lower(split(#, '@')[0]));{emails: ['x@spam.ru', 'y@mail.RU']};['x', 'y'] +map(emails, lower(split(#, '@')[0]));{emails: []};[] +map(emails, lower(split(#, '@')[0]));{emails: ['a@b']};['a'] +map(emails, lower(split(#, '@')[0]));{emails: [null]};!error +filter(emails, matches(#, '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$'));{emails: ['a@x.com', 'B@Y.ORG']};['a@x.com', 'B@Y.ORG'] +filter(emails, matches(#, '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$'));{emails: ['bad', 'c@d.ru']};['c@d.ru'] +filter(emails, matches(#, '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$'));{emails: ['x@spam.ru', 'y@mail.RU']};['x@spam.ru', 'y@mail.RU'] +filter(emails, matches(#, '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$'));{emails: []};[] +filter(emails, matches(#, '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$'));{emails: ['a@b']};[] +filter(emails, matches(#, '^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$'));{emails: [null]};!error +# object arrays: concatenation and search +map(people, #.first + ' ' + #.last);{people: [{first: 'Ada', last: 'Lovelace'}, {first: 'Alan', last: 'Turing'}]};['Ada Lovelace', 'Alan Turing'] +map(people, #.first + ' ' + #.last);{people: [{first: ' grace ', last: 'HOPPER'}]};[' grace HOPPER'] +map(people, #.first + ' ' + #.last);{people: [{first: 'Ann', last: null}]};!error +map(people, #.first + ' ' + #.last);{people: [{first: 'Ann'}]};!error +map(people, #.first + ' ' + #.last);{people: []};[] +map(people, #.first + ' ' + #.last);{people: [{first: 'Zoë', last: 'Ñúñez'}]};['Zoë Ñúñez'] +map(people, #.first + ' ' + #.last);{people: null};!error +map(people, `${#.last}, ${#.first}`);{people: [{first: 'Ada', last: 'Lovelace'}, {first: 'Alan', last: 'Turing'}]};['Lovelace, Ada', 'Turing, Alan'] +map(people, `${#.last}, ${#.first}`);{people: [{first: ' grace ', last: 'HOPPER'}]};['HOPPER, grace '] +map(people, `${#.last}, ${#.first}`);{people: [{first: 'Ann', last: null}]};['null, Ann'] +map(people, `${#.last}, ${#.first}`);{people: [{first: 'Ann'}]};['null, Ann'] +map(people, `${#.last}, ${#.first}`);{people: []};[] +map(people, `${#.last}, ${#.first}`);{people: [{first: 'Zoë', last: 'Ñúñez'}]};['Ñúñez, Zoë'] +map(people, `${#.last}, ${#.first}`);{people: null};!error +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: [{first: 'Ada', last: 'Lovelace'}, {first: 'Alan', last: 'Turing'}]};['LOVELACE, Ada', 'TURING, Alan'] +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: [{first: ' grace ', last: 'HOPPER'}]};['HOPPER, grace'] +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: [{first: 'Ann', last: null}]};!error +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: [{first: 'Ann'}]};!error +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: []};[] +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: [{first: 'Zoë', last: 'Ñúñez'}]};['ÑÚÑEZ, Zoë'] +map(people as p, upper(p.last) + ', ' + trim(p.first));{people: null};!error +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: [{first: 'Ada', last: 'Lovelace'}, {first: 'Alan', last: 'Turing'}]};['Ada Lovelace', 'Alan Turing'] +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: [{first: ' grace ', last: 'HOPPER'}]};['grace HOPPER'] +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: [{first: 'Ann', last: null}]};['Ann -'] +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: [{first: 'Ann'}]};['Ann -'] +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: []};[] +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: [{first: 'Zoë', last: 'Ñúñez'}]};['Zoë Ñúñez'] +map(people, trim(#.first) + ' ' + (#.last ?? '-'));{people: null};!error +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: [{first: 'Ada', last: 'Lovelace'}, {first: 'Alan', last: 'Turing'}]};['AL', 'AT'] +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: [{first: ' grace ', last: 'HOPPER'}]};[' H'] +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: [{first: 'Ann', last: null}]};['A'] +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: [{first: 'Ann'}]};['A'] +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: []};[] +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: [{first: 'Zoë', last: 'Ñúñez'}]};['ZÑ'];bug: string indexing uses UTF-8 byte offsets instead of characters +map(people, upper(#.first[0]) + upper(#.last[0] ?? ''));{people: null};!error +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: [{first: 'Ada', last: 'Lovelace'}, {first: 'Alan', last: 'Turing'}]};[{name: 'ADA', initial: 'L'}, {name: 'ALAN', initial: 'T'}] +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: [{first: ' grace ', last: 'HOPPER'}]};[{name: ' GRACE ', initial: 'H'}] +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: [{first: 'Ann', last: null}]};[{name: 'ANN', initial: null}] +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: [{first: 'Ann'}]};[{name: 'ANN', initial: null}] +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: []};[] +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: [{first: 'Zoë', last: 'Ñúñez'}]};[{name: 'ZOË', initial: 'Ñ'}];bug: string indexing uses UTF-8 byte offsets instead of characters +map(people, {name: upper(#.first), initial: #.last[0] ?? null});{people: null};!error +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'blue'};[{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'EF-3', name: 'blue jeans', qty: 5}] +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'BLUE'};[{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'EF-3', name: 'blue jeans', qty: 5}] +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'hat'};[{sku: 'cd-2', name: 'Red Hat', qty: 0}] +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'x'};[] +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: ''};[{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}] +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: ' blue'};[{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}] +filter(items, contains(lower(#.name), lower(q)));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: null};!error +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'blue'};['AB-1', 'EF-3'] +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'BLUE'};['AB-1', 'EF-3'] +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'hat'};['CD-2'] +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'x'};[] +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: ''};['AB-1', 'CD-2', 'EF-3', 'GH-4'] +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: ' blue'};['AB-1', 'EF-3'] +map(filter(items, contains(lower(#.name), lower(trim(q)))), upper(#.sku));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: null};!error +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'blue'};2 +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'BLUE'};2 +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'hat'};0 +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: 'x'};0 +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: ''};3 +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: ' blue'};1 +count(items, contains(lower(#.name), lower(q)) and #.qty > 0);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}], q: null};!error +map(items, {sku: upper(#.sku), name: trim(#.name)});{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}]};[{sku: 'AB-1', name: 'Blue Shirt'}, {sku: 'CD-2', name: 'Red Hat'}, {sku: 'EF-3', name: 'blue jeans'}, {sku: 'GH-4', name: 'Green Scarf'}] +map(items, {sku: upper(#.sku), name: trim(#.name)});{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}]};[{sku: 'AB-1', name: 'Blue Shirt'}] +map(items, {sku: upper(#.sku), name: trim(#.name)});{items: []};[] +map(items, {sku: upper(#.sku), name: trim(#.name)});{items: [{sku: null, name: 'x', qty: 1}]};!error +map(items, {sku: upper(#.sku), name: trim(#.name)});{items: [{sku: 'a', name: 5, qty: 1}]};!error +map(filter(items, #.qty > 0), trim(#.name) + ' x' + string(#.qty));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}]};['Blue Shirt x2', 'blue jeans x5', 'Green Scarf x1'] +map(filter(items, #.qty > 0), trim(#.name) + ' x' + string(#.qty));{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}]};['Blue Shirt x2'] +map(filter(items, #.qty > 0), trim(#.name) + ' x' + string(#.qty));{items: []};[] +map(filter(items, #.qty > 0), trim(#.name) + ' x' + string(#.qty));{items: [{sku: null, name: 'x', qty: 1}]};['x x1'] +map(filter(items, #.qty > 0), trim(#.name) + ' x' + string(#.qty));{items: [{sku: 'a', name: 5, qty: 1}]};!error +map(items, `${upper(#.sku)}: ${trim(#.name)} (${#.qty})`);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}, {sku: 'cd-2', name: 'Red Hat', qty: 0}, {sku: 'EF-3', name: 'blue jeans', qty: 5}, {sku: 'gh-4', name: 'Green Scarf', qty: 1}]};['AB-1: Blue Shirt (2)', 'CD-2: Red Hat (0)', 'EF-3: blue jeans (5)', 'GH-4: Green Scarf (1)'] +map(items, `${upper(#.sku)}: ${trim(#.name)} (${#.qty})`);{items: [{sku: 'ab-1', name: ' Blue Shirt ', qty: 2}]};['AB-1: Blue Shirt (2)'] +map(items, `${upper(#.sku)}: ${trim(#.name)} (${#.qty})`);{items: []};[] +map(items, `${upper(#.sku)}: ${trim(#.name)} (${#.qty})`);{items: [{sku: null, name: 'x', qty: 1}]};!error +map(items, `${upper(#.sku)}: ${trim(#.name)} (${#.qty})`);{items: [{sku: 'a', name: 5, qty: 1}]};!error +# nested closures over strings +map(groups, map(#.members, upper(#)));{groups: [{name: 'a', members: ['x', 'Y']}, {name: 'b', members: []}]};[['X', 'Y'], []] +map(groups, map(#.members, upper(#)));{groups: [{name: 'Admins', members: ['root', 'ADMIN']}]};[['ROOT', 'ADMIN']] +map(groups, map(#.members, upper(#)));{groups: [{name: 'c', members: ['ä']}]};[['Ä']] +map(groups, map(#.members, upper(#)));{groups: []};[] +map(groups, map(#.members, upper(#)));{groups: [{name: 'd', members: null}]};!error +map(groups as g, map(g.members, g.name + ':' + lower(#)));{groups: [{name: 'a', members: ['x', 'Y']}, {name: 'b', members: []}]};[['a:x', 'a:y'], []] +map(groups as g, map(g.members, g.name + ':' + lower(#)));{groups: [{name: 'Admins', members: ['root', 'ADMIN']}]};[['Admins:root', 'Admins:admin']] +map(groups as g, map(g.members, g.name + ':' + lower(#)));{groups: [{name: 'c', members: ['ä']}]};[['c:ä']] +map(groups as g, map(g.members, g.name + ':' + lower(#)));{groups: []};[] +map(groups as g, map(g.members, g.name + ':' + lower(#)));{groups: [{name: 'd', members: null}]};!error +flatMap(groups as g, map(g.members, lower(g.name) + '/' + #));{groups: [{name: 'a', members: ['x', 'Y']}, {name: 'b', members: []}]};['a/x', 'a/Y'] +flatMap(groups as g, map(g.members, lower(g.name) + '/' + #));{groups: [{name: 'Admins', members: ['root', 'ADMIN']}]};['admins/root', 'admins/ADMIN'] +flatMap(groups as g, map(g.members, lower(g.name) + '/' + #));{groups: [{name: 'c', members: ['ä']}]};['c/ä'] +flatMap(groups as g, map(g.members, lower(g.name) + '/' + #));{groups: []};[] +flatMap(groups as g, map(g.members, lower(g.name) + '/' + #));{groups: [{name: 'd', members: null}]};!error +filter(groups, some(#.members, lower(#) == 'admin'));{groups: [{name: 'a', members: ['x', 'Y']}, {name: 'b', members: []}]};[] +filter(groups, some(#.members, lower(#) == 'admin'));{groups: [{name: 'Admins', members: ['root', 'ADMIN']}]};[{name: 'Admins', members: ['root', 'ADMIN']}] +filter(groups, some(#.members, lower(#) == 'admin'));{groups: [{name: 'c', members: ['ä']}]};[] +filter(groups, some(#.members, lower(#) == 'admin'));{groups: []};[] +filter(groups, some(#.members, lower(#) == 'admin'));{groups: [{name: 'd', members: null}]};!error +map(groups, len(#.members) == 0 ? #.name + ' (empty)' : #.name);{groups: [{name: 'a', members: ['x', 'Y']}, {name: 'b', members: []}]};['a', 'b (empty)'] +map(groups, len(#.members) == 0 ? #.name + ' (empty)' : #.name);{groups: [{name: 'Admins', members: ['root', 'ADMIN']}]};['Admins'] +map(groups, len(#.members) == 0 ? #.name + ' (empty)' : #.name);{groups: [{name: 'c', members: ['ä']}]};['c'] +map(groups, len(#.members) == 0 ? #.name + ' (empty)' : #.name);{groups: []};[] +map(groups, len(#.members) == 0 ? #.name + ' (empty)' : #.name);{groups: [{name: 'd', members: null}]};!error +flatMap(lines, split(#, ','));{lines: ['a,b', 'c']};['a', 'b', 'c'] +flatMap(lines, split(#, ','));{lines: ['x, y ,z']};['x', ' y ', 'z'] +flatMap(lines, split(#, ','));{lines: ['']};[''] +flatMap(lines, split(#, ','));{lines: []};[] +flatMap(lines, split(#, ','));{lines: [',,']};['', '', ''] +flatMap(lines, split(#, ','));{lines: ['ä,ö', 'ü']};['ä', 'ö', 'ü'] +flatMap(lines, split(#, ','));{lines: ['a', null]};!error +flatMap(lines, map(split(#, ','), trim(#)));{lines: ['a,b', 'c']};['a', 'b', 'c'] +flatMap(lines, map(split(#, ','), trim(#)));{lines: ['x, y ,z']};['x', 'y', 'z'] +flatMap(lines, map(split(#, ','), trim(#)));{lines: ['']};[''] +flatMap(lines, map(split(#, ','), trim(#)));{lines: []};[] +flatMap(lines, map(split(#, ','), trim(#)));{lines: [',,']};['', '', ''] +flatMap(lines, map(split(#, ','), trim(#)));{lines: ['ä,ö', 'ü']};['ä', 'ö', 'ü'] +flatMap(lines, map(split(#, ','), trim(#)));{lines: ['a', null]};!error +map(lines, len(split(#, ',')));{lines: ['a,b', 'c']};[2, 1] +map(lines, len(split(#, ',')));{lines: ['x, y ,z']};[3] +map(lines, len(split(#, ',')));{lines: ['']};[1] +map(lines, len(split(#, ',')));{lines: []};[] +map(lines, len(split(#, ',')));{lines: [',,']};[3] +map(lines, len(split(#, ',')));{lines: ['ä,ö', 'ü']};[2, 1] +map(lines, len(split(#, ',')));{lines: ['a', null]};!error +map(lines, map(split(#, ','), upper(trim(#))));{lines: ['a,b', 'c']};[['A', 'B'], ['C']] +map(lines, map(split(#, ','), upper(trim(#))));{lines: ['x, y ,z']};[['X', 'Y', 'Z']] +map(lines, map(split(#, ','), upper(trim(#))));{lines: ['']};[['']] +map(lines, map(split(#, ','), upper(trim(#))));{lines: []};[] +map(lines, map(split(#, ','), upper(trim(#))));{lines: [',,']};[['', '', '']] +map(lines, map(split(#, ','), upper(trim(#))));{lines: ['ä,ö', 'ü']};[['Ä', 'Ö'], ['Ü']] +map(lines, map(split(#, ','), upper(trim(#))));{lines: ['a', null]};!error +# decisions over string arrays +map(tiers, # == 'GOLD' or lower(#) == 'gold');{tiers: ['GOLD', 'gold', 'Gold', 'silver']};[true, true, true, false] +map(tiers, # == 'GOLD' or lower(#) == 'gold');{tiers: ['bronze', 'SILVER']};[false, false] +map(tiers, # == 'GOLD' or lower(#) == 'gold');{tiers: []};[] +map(tiers, # == 'GOLD' or lower(#) == 'gold');{tiers: ['gold', null]};!error +map(tiers, # == 'GOLD' or lower(#) == 'gold');{tiers: ['gold', 7]};!error +map(tiers, lower(#) == 'gold' ? 0.2 : lower(#) == 'silver' ? 0.1 : 0);{tiers: ['GOLD', 'gold', 'Gold', 'silver']};[0.2, 0.2, 0.2, 0.1] +map(tiers, lower(#) == 'gold' ? 0.2 : lower(#) == 'silver' ? 0.1 : 0);{tiers: ['bronze', 'SILVER']};[0, 0.1] +map(tiers, lower(#) == 'gold' ? 0.2 : lower(#) == 'silver' ? 0.1 : 0);{tiers: []};[] +map(tiers, lower(#) == 'gold' ? 0.2 : lower(#) == 'silver' ? 0.1 : 0);{tiers: ['gold', null]};!error +map(tiers, lower(#) == 'gold' ? 0.2 : lower(#) == 'silver' ? 0.1 : 0);{tiers: ['gold', 7]};!error +sum(map(tiers, lower(#) == 'gold' ? 10 : 1));{tiers: ['GOLD', 'gold', 'Gold', 'silver']};31 +sum(map(tiers, lower(#) == 'gold' ? 10 : 1));{tiers: ['bronze', 'SILVER']};2 +sum(map(tiers, lower(#) == 'gold' ? 10 : 1));{tiers: []};0 +sum(map(tiers, lower(#) == 'gold' ? 10 : 1));{tiers: ['gold', null]};!error +sum(map(tiers, lower(#) == 'gold' ? 10 : 1));{tiers: ['gold', 7]};!error +map(tiers, lower(#) in ['gold', 'silver'] ? upper(#) : 'OTHER');{tiers: ['GOLD', 'gold', 'Gold', 'silver']};['GOLD', 'GOLD', 'GOLD', 'SILVER'] +map(tiers, lower(#) in ['gold', 'silver'] ? upper(#) : 'OTHER');{tiers: ['bronze', 'SILVER']};['OTHER', 'SILVER'] +map(tiers, lower(#) in ['gold', 'silver'] ? upper(#) : 'OTHER');{tiers: []};[] +map(tiers, lower(#) in ['gold', 'silver'] ? upper(#) : 'OTHER');{tiers: ['gold', null]};!error +map(tiers, lower(#) in ['gold', 'silver'] ? upper(#) : 'OTHER');{tiers: ['gold', 7]};!error +# object keys as strings +map(keys(o), upper(#));{o: {a: 1, b: 'x'}};['A', 'B'] +map(keys(o), upper(#));{o: {'Content-Type': 'json', 'X-Id': '7'}};['CONTENT-TYPE', 'X-ID'] +map(keys(o), upper(#));{o: {}};[] +map(keys(o), upper(#));{o: {'ä': 'ö'}};['Ä'] +map(keys(o), lower(#) + '=' + string(o[#]));{o: {a: 1, b: 'x'}};['a=1', 'b=x'] +map(keys(o), lower(#) + '=' + string(o[#]));{o: {'Content-Type': 'json', 'X-Id': '7'}};['content-type=json', 'x-id=7'] +map(keys(o), lower(#) + '=' + string(o[#]));{o: {}};[] +map(keys(o), lower(#) + '=' + string(o[#]));{o: {'ä': 'ö'}};['ä=ö'] +filter(keys(o), startsWith(lower(#), 'x-'));{o: {a: 1, b: 'x'}};[] +filter(keys(o), startsWith(lower(#), 'x-'));{o: {'Content-Type': 'json', 'X-Id': '7'}};['X-Id'] +filter(keys(o), startsWith(lower(#), 'x-'));{o: {}};[] +filter(keys(o), startsWith(lower(#), 'x-'));{o: {'ä': 'ö'}};[] +some(keys(o), lower(#) == 'content-type');{o: {a: 1, b: 'x'}};false +some(keys(o), lower(#) == 'content-type');{o: {'Content-Type': 'json', 'X-Id': '7'}};true +some(keys(o), lower(#) == 'content-type');{o: {}};false +some(keys(o), lower(#) == 'content-type');{o: {'ä': 'ö'}};false +# capitalization edge: empty words +map(split(s, ' '), upper(#[0:0]) + #[1:]);{s: 'a b'};!error +map(split(s, ' '), upper(#[0:0]) + #[1:]);{s: ' a'};!error +map(split(s, ' '), upper(#[0:0]) + #[1:]);{s: ''};!error +map(filter(split(s, ' '), # != ''), upper(#[0:0]) + #[1:]);{s: 'a b'};['A', 'B'] +map(filter(split(s, ' '), # != ''), upper(#[0:0]) + #[1:]);{s: ' a'};['A'] +map(filter(split(s, ' '), # != ''), upper(#[0:0]) + #[1:]);{s: ''};[] +map(filter(split(s, ' '), # != ''), upper(#[0:0]) + #[1:]);{s: ' hello world '};['Hello', 'World'] +map(split(s, ' '), len(#) > 0 ? upper(#[0:0]) + #[1:] : #);{s: 'a b'};['A', '', 'B'] +map(split(s, ' '), len(#) > 0 ? upper(#[0:0]) + #[1:] : #);{s: ' a'};['', 'A'] +map(split(s, ' '), len(#) > 0 ? upper(#[0:0]) + #[1:] : #);{s: ''};[''] diff --git a/core/expression/tests/spec/standard/15-03-templates.csv b/core/expression/tests/spec/standard/15-03-templates.csv new file mode 100644 index 00000000..0f81aea5 --- /dev/null +++ b/core/expression/tests/spec/standard/15-03-templates.csv @@ -0,0 +1,363 @@ +expression (string);input (json 5);output (json 5);note +# templates: function calls and pipelines inside interpolation +`${upper(first)} ${lower(last)}`;{first: 'ada', last: 'LOVELACE'};'ADA lovelace' +`${upper(first)} ${lower(last)}`;{first: ' Grace ', last: 'hopper'};' GRACE hopper' +`${upper(first)} ${lower(last)}`;{first: 'Zoë', last: 'Ñúñez'};'ZOË ñúñez' +`${upper(first)} ${lower(last)}`;{first: '', last: ''};' ' +`${upper(first)} ${lower(last)}`;{first: 'x', last: null};!error +`${upper(first)} ${lower(last)}`;{};!error +`${upper(trim(first))}-${len(last ?? '')}`;{first: 'ada', last: 'LOVELACE'};'ADA-8' +`${upper(trim(first))}-${len(last ?? '')}`;{first: ' Grace ', last: 'hopper'};'GRACE-6' +`${upper(trim(first))}-${len(last ?? '')}`;{first: 'Zoë', last: 'Ñúñez'};'ZOË-5';bug: len counts UTF-8 bytes, intended character count +`${upper(trim(first))}-${len(last ?? '')}`;{first: '', last: ''};'-0' +`${upper(trim(first))}-${len(last ?? '')}`;{first: 'x', last: null};'X-0' +`${upper(trim(first))}-${len(last ?? '')}`;{};!error +`${trim(first)} ${last ?? '?'}`;{first: 'ada', last: 'LOVELACE'};'ada LOVELACE' +`${trim(first)} ${last ?? '?'}`;{first: ' Grace ', last: 'hopper'};'Grace hopper' +`${trim(first)} ${last ?? '?'}`;{first: 'Zoë', last: 'Ñúñez'};'Zoë Ñúñez' +`${trim(first)} ${last ?? '?'}`;{first: '', last: ''};' ' +`${trim(first)} ${last ?? '?'}`;{first: 'x', last: null};'x ?' +`${trim(first)} ${last ?? '?'}`;{};!error +`${first ?? 'anon'}`;{first: 'ada', last: 'LOVELACE'};'ada' +`${first ?? 'anon'}`;{first: ' Grace ', last: 'hopper'};' Grace ' +`${first ?? 'anon'}`;{first: 'Zoë', last: 'Ñúñez'};'Zoë' +`${first ?? 'anon'}`;{first: '', last: ''};'' +`${first ?? 'anon'}`;{first: 'x', last: null};'x' +`${first ?? 'anon'}`;{};'anon' +`Dear ${upper(first[0] ?? '?')}. ${last}`;{first: 'ada', last: 'LOVELACE'};'Dear A. LOVELACE' +`Dear ${upper(first[0] ?? '?')}. ${last}`;{first: ' Grace ', last: 'hopper'};'Dear . hopper' +`Dear ${upper(first[0] ?? '?')}. ${last}`;{first: 'Zoë', last: 'Ñúñez'};'Dear Z. Ñúñez' +`Dear ${upper(first[0] ?? '?')}. ${last}`;{first: '', last: ''};'Dear ?. ' +`Dear ${upper(first[0] ?? '?')}. ${last}`;{first: 'x', last: null};'Dear X. null' +`Dear ${upper(first[0] ?? '?')}. ${last}`;{};'Dear ?. null' +# templates: arithmetic with decimals +`${qty} x ${price} = ${qty * price}`;{qty: 3, price: 19.99};'3 x 19.99 = 59.97' +`${qty} x ${price} = ${qty * price}`;{qty: 1, price: 0.10};'1 x 0.10 = 0.10' +`${qty} x ${price} = ${qty * price}`;{qty: 0, price: 5};'0 x 5 = 0' +`${qty} x ${price} = ${qty * price}`;{qty: 2, price: 1.005};'2 x 1.005 = 2.010' +`${qty} x ${price} = ${qty * price}`;{qty: 1.5, price: 2.40};'1.5 x 2.40 = 3.600' +`${qty} x ${price} = ${qty * price}`;{qty: 2, price: null};!error +`${qty} x ${price} = ${qty * price}`;{qty: '2', price: 1};!error +`${qty} x ${price} = ${qty * price}`;{};!error +`Total: $${qty * price}`;{qty: 3, price: 19.99};'Total: $59.97' +`Total: $${qty * price}`;{qty: 1, price: 0.10};'Total: $0.10' +`Total: $${qty * price}`;{qty: 0, price: 5};'Total: $0' +`Total: $${qty * price}`;{qty: 2, price: 1.005};'Total: $2.010' +`Total: $${qty * price}`;{qty: 1.5, price: 2.40};'Total: $3.600' +`Total: $${qty * price}`;{qty: 2, price: null};!error +`Total: $${qty * price}`;{qty: '2', price: 1};!error +`Total: $${qty * price}`;{};!error +`${qty * price + 0.01}`;{qty: 3, price: 19.99};'59.98' +`${qty * price + 0.01}`;{qty: 1, price: 0.10};'0.11' +`${qty * price + 0.01}`;{qty: 0, price: 5};'0.01' +`${qty * price + 0.01}`;{qty: 2, price: 1.005};'2.020' +`${qty * price + 0.01}`;{qty: 1.5, price: 2.40};'3.610' +`${qty * price + 0.01}`;{qty: 2, price: null};!error +`${qty * price + 0.01}`;{qty: '2', price: 1};!error +`${qty * price + 0.01}`;{};!error +`${round(qty * price, 1)}`;{qty: 3, price: 19.99};'60.0' +`${round(qty * price, 1)}`;{qty: 1, price: 0.10};'0.1' +`${round(qty * price, 1)}`;{qty: 0, price: 5};'0' +`${round(qty * price, 1)}`;{qty: 2, price: 1.005};'2.0' +`${round(qty * price, 1)}`;{qty: 1.5, price: 2.40};'3.6' +`${round(qty * price, 1)}`;{qty: 2, price: null};!error +`${round(qty * price, 1)}`;{qty: '2', price: 1};!error +`${round(qty * price, 1)}`;{};!error +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: 3, price: 19.99};'big order' +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: 1, price: 0.10};'small order' +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: 0, price: 5};'small order' +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: 2, price: 1.005};'small order' +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: 1.5, price: 2.40};'small order' +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: 2, price: null};!error +`${qty * price > 10 ? 'big' : 'small'} order`;{qty: '2', price: 1};!error +`${qty * price > 10 ? 'big' : 'small'} order`;{};!error +`${(price ?? 0) * 100}%`;{qty: 3, price: 19.99};'1999.00%' +`${(price ?? 0) * 100}%`;{qty: 1, price: 0.10};'10.00%' +`${(price ?? 0) * 100}%`;{qty: 0, price: 5};'500%' +`${(price ?? 0) * 100}%`;{qty: 2, price: 1.005};'100.500%' +`${(price ?? 0) * 100}%`;{qty: 1.5, price: 2.40};'240.00%' +`${(price ?? 0) * 100}%`;{qty: 2, price: null};'0%' +`${(price ?? 0) * 100}%`;{qty: '2', price: 1};'100%' +`${(price ?? 0) * 100}%`;{};'0%' +`${price - 0.01}`;{qty: 3, price: 19.99};'19.98' +`${price - 0.01}`;{qty: 1, price: 0.10};'0.09' +`${price - 0.01}`;{qty: 0, price: 5};'4.99' +`${price - 0.01}`;{qty: 2, price: 1.005};'0.995' +`${price - 0.01}`;{qty: 1.5, price: 2.40};'2.39' +`${price - 0.01}`;{qty: 2, price: null};!error +`${price - 0.01}`;{qty: '2', price: 1};'0.99' +`${price - 0.01}`;{};!error +`${-price}`;{qty: 3, price: 19.99};'-19.99' +`${-price}`;{qty: 1, price: 0.10};'-0.10' +`${-price}`;{qty: 0, price: 5};'-5' +`${-price}`;{qty: 2, price: 1.005};'-1.005' +`${-price}`;{qty: 1.5, price: 2.40};'-2.40' +`${-price}`;{price: null};!error +# templates: ternaries and null coalescing +`${lower(tier ?? 'none')}:${pts ?? 0}`;{tier: 'gold', pts: 1200};'gold:1200' +`${lower(tier ?? 'none')}:${pts ?? 0}`;{tier: 'SILVER', pts: 50};'silver:50' +`${lower(tier ?? 'none')}:${pts ?? 0}`;{tier: null, pts: 0};'none:0' +`${lower(tier ?? 'none')}:${pts ?? 0}`;{pts: 10};'none:10' +`${lower(tier ?? 'none')}:${pts ?? 0}`;{tier: 'bronze'};'bronze:0' +`${lower(tier ?? 'none')}:${pts ?? 0}`;{tier: 1, pts: 1};!error +`${tier == null ? 'guest' : upper(tier)}`;{tier: 'gold', pts: 1200};'GOLD' +`${tier == null ? 'guest' : upper(tier)}`;{tier: 'SILVER', pts: 50};'SILVER' +`${tier == null ? 'guest' : upper(tier)}`;{tier: null, pts: 0};'guest' +`${tier == null ? 'guest' : upper(tier)}`;{pts: 10};'guest' +`${tier == null ? 'guest' : upper(tier)}`;{tier: 'bronze'};'BRONZE' +`${tier == null ? 'guest' : upper(tier)}`;{tier: 1, pts: 1};!error +`${(pts ?? 0) >= 1000 ? 'elite' : (pts ?? 0) >= 50 ? 'member' : 'new'}`;{tier: 'gold', pts: 1200};'elite' +`${(pts ?? 0) >= 1000 ? 'elite' : (pts ?? 0) >= 50 ? 'member' : 'new'}`;{tier: 'SILVER', pts: 50};'member' +`${(pts ?? 0) >= 1000 ? 'elite' : (pts ?? 0) >= 50 ? 'member' : 'new'}`;{tier: null, pts: 0};'new' +`${(pts ?? 0) >= 1000 ? 'elite' : (pts ?? 0) >= 50 ? 'member' : 'new'}`;{pts: 10};'new' +`${(pts ?? 0) >= 1000 ? 'elite' : (pts ?? 0) >= 50 ? 'member' : 'new'}`;{tier: 'bronze'};'new' +`${(pts ?? 0) >= 1000 ? 'elite' : (pts ?? 0) >= 50 ? 'member' : 'new'}`;{tier: 1, pts: 1};'new' +`${tier ?? 'none'} / ${pts ?? 'n/a'}`;{tier: 'gold', pts: 1200};'gold / 1200' +`${tier ?? 'none'} / ${pts ?? 'n/a'}`;{tier: 'SILVER', pts: 50};'SILVER / 50' +`${tier ?? 'none'} / ${pts ?? 'n/a'}`;{tier: null, pts: 0};'none / 0' +`${tier ?? 'none'} / ${pts ?? 'n/a'}`;{pts: 10};'none / 10' +`${tier ?? 'none'} / ${pts ?? 'n/a'}`;{tier: 'bronze'};'bronze / n/a' +`${tier ?? 'none'} / ${pts ?? 'n/a'}`;{tier: 1, pts: 1};'1 / 1' +`${lower(tier) in ['gold', 'silver']}`;{tier: 'gold', pts: 1200};'true' +`${lower(tier) in ['gold', 'silver']}`;{tier: 'SILVER', pts: 50};'true' +`${lower(tier) in ['gold', 'silver']}`;{tier: null, pts: 0};!error +`${lower(tier) in ['gold', 'silver']}`;{pts: 10};!error +`${lower(tier) in ['gold', 'silver']}`;{tier: 'bronze'};'false' +`${lower(tier) in ['gold', 'silver']}`;{tier: 1, pts: 1};!error +`${contains(lower(tier), 'old') ? 'has old' : 'no old'}`;{tier: 'gold', pts: 1200};'has old' +`${contains(lower(tier), 'old') ? 'has old' : 'no old'}`;{tier: 'SILVER', pts: 50};'no old' +`${contains(lower(tier), 'old') ? 'has old' : 'no old'}`;{tier: null, pts: 0};!error +`${contains(lower(tier), 'old') ? 'has old' : 'no old'}`;{pts: 10};!error +`${contains(lower(tier), 'old') ? 'has old' : 'no old'}`;{tier: 'bronze'};'no old' +`${contains(lower(tier), 'old') ? 'has old' : 'no old'}`;{tier: 1, pts: 1};!error +# templates: nested member access +`${user.name} lives in ${user.address.city}`;{user: {name: 'Ann', address: {city: 'Oslo', zip: '0150'}}};'Ann lives in Oslo' +`${user.name} lives in ${user.address.city}`;{user: {name: 'Bo', address: null}};'Bo lives in null' +`${user.name} lives in ${user.address.city}`;{user: {name: 'Cy'}};'Cy lives in null' +`${user.name} lives in ${user.address.city}`;{user: null};'null lives in null' +`${user.name} lives in ${user.address.city}`;{};'null lives in null' +`${user.name} lives in ${user.address.city}`;{user: {name: 'Dee', address: {city: 'São Paulo', zip: 1310}}};'Dee lives in São Paulo' +`${user.address.city ?? 'unknown'} (${user.address.zip ?? '-'})`;{user: {name: 'Ann', address: {city: 'Oslo', zip: '0150'}}};'Oslo (0150)' +`${user.address.city ?? 'unknown'} (${user.address.zip ?? '-'})`;{user: {name: 'Bo', address: null}};'unknown (-)' +`${user.address.city ?? 'unknown'} (${user.address.zip ?? '-'})`;{user: {name: 'Cy'}};'unknown (-)' +`${user.address.city ?? 'unknown'} (${user.address.zip ?? '-'})`;{user: null};'unknown (-)' +`${user.address.city ?? 'unknown'} (${user.address.zip ?? '-'})`;{};'unknown (-)' +`${user.address.city ?? 'unknown'} (${user.address.zip ?? '-'})`;{user: {name: 'Dee', address: {city: 'São Paulo', zip: 1310}}};'São Paulo (1310)' +`${upper(user.address.city ?? 'n/a')}`;{user: {name: 'Ann', address: {city: 'Oslo', zip: '0150'}}};'OSLO' +`${upper(user.address.city ?? 'n/a')}`;{user: {name: 'Bo', address: null}};'N/A' +`${upper(user.address.city ?? 'n/a')}`;{user: {name: 'Cy'}};'N/A' +`${upper(user.address.city ?? 'n/a')}`;{user: null};'N/A' +`${upper(user.address.city ?? 'n/a')}`;{};'N/A' +`${upper(user.address.city ?? 'n/a')}`;{user: {name: 'Dee', address: {city: 'São Paulo', zip: 1310}}};'SÃO PAULO' +`${user['name']}`;{user: {name: 'Ann', address: {city: 'Oslo', zip: '0150'}}};'Ann' +`${user['name']}`;{user: {name: 'Bo', address: null}};'Bo' +`${user['name']}`;{user: {name: 'Cy'}};'Cy' +`${user['name']}`;{user: null};'null' +`${user['name']}`;{};'null' +`${user['name']}`;{user: {name: 'Dee', address: {city: 'São Paulo', zip: 1310}}};'Dee' +`${orders[0].id}/${orders[0].lines[0].sku}`;{orders: [{id: 'A1', lines: [{sku: 'x', qty: 2}]}]};'A1/x' +`${orders[0].id}/${orders[0].lines[0].sku}`;{orders: [{id: 'B2', lines: []}]};'B2/null' +`${orders[0].id}/${orders[0].lines[0].sku}`;{orders: []};'null/null' +`${orders[0].id}/${orders[0].lines[0].sku}`;{orders: null};'null/null' +`${orders[0].id}/${orders[0].lines[0].sku}`;{};'null/null' +`first: ${orders[0].lines[0].qty ?? 0}`;{orders: [{id: 'A1', lines: [{sku: 'x', qty: 2}]}]};'first: 2' +`first: ${orders[0].lines[0].qty ?? 0}`;{orders: [{id: 'B2', lines: []}]};'first: 0' +`first: ${orders[0].lines[0].qty ?? 0}`;{orders: []};'first: 0' +`first: ${orders[0].lines[0].qty ?? 0}`;{orders: null};'first: 0' +`first: ${orders[0].lines[0].qty ?? 0}`;{};'first: 0' +`${o['key with space']}|${o['ä']}`;{o: {'key with space': 'v1', 'ä': 'umlaut'}};'v1|umlaut' +`${o['key with space']}|${o['ä']}`;{o: {}};'null|null' +`${o['key with space']}|${o['ä']}`;{o: null};'null|null' +# templates: closures and aggregates inside interpolation +`${len(xs)} items, total ${sum(xs)}`;{xs: [1, 2, 3]};'3 items, total 6' +`${len(xs)} items, total ${sum(xs)}`;{xs: [0.5, 0.25]};'2 items, total 0.75' +`${len(xs)} items, total ${sum(xs)}`;{xs: []};'0 items, total 0' +`${len(xs)} items, total ${sum(xs)}`;{xs: [10]};'1 items, total 10' +`${count(xs, # > 1)}/${len(xs)}`;{xs: [1, 2, 3]};'2/3' +`${count(xs, # > 1)}/${len(xs)}`;{xs: [0.5, 0.25]};'0/2' +`${count(xs, # > 1)}/${len(xs)}`;{xs: []};'0/0' +`${count(xs, # > 1)}/${len(xs)}`;{xs: [10]};'1/1' +`${sum(map(xs, # * 2))}`;{xs: [1, 2, 3]};'12' +`${sum(map(xs, # * 2))}`;{xs: [0.5, 0.25]};'1.50' +`${sum(map(xs, # * 2))}`;{xs: []};'0' +`${sum(map(xs, # * 2))}`;{xs: [10]};'20' +`${some(xs, # > 2) ? 'has big' : 'all small'}`;{xs: [1, 2, 3]};'has big' +`${some(xs, # > 2) ? 'has big' : 'all small'}`;{xs: [0.5, 0.25]};'all small' +`${some(xs, # > 2) ? 'has big' : 'all small'}`;{xs: []};'all small' +`${some(xs, # > 2) ? 'has big' : 'all small'}`;{xs: [10]};'has big' +`${len(filter(words, len(#) > 3))} long words`;{words: ['alpha', 'beta']};'2 long words' +`${len(filter(words, len(#) > 3))} long words`;{words: []};'0 long words' +`${len(filter(words, len(#) > 3))} long words`;{words: ['ONE']};'0 long words' +`${len(filter(words, len(#) > 3))} long words`;{words: ['a', 'b', 'c']};'0 long words' +`${upper(words[0] ?? 'none')} and ${len(words) - 1} more`;{words: ['alpha', 'beta']};'ALPHA and 1 more' +`${upper(words[0] ?? 'none')} and ${len(words) - 1} more`;{words: []};'NONE and -1 more' +`${upper(words[0] ?? 'none')} and ${len(words) - 1} more`;{words: ['ONE']};'ONE and 0 more' +`${upper(words[0] ?? 'none')} and ${len(words) - 1} more`;{words: ['a', 'b', 'c']};'A and 2 more' +# templates inside closures +map(xs, `#${#}`);{xs: [1, 2, 3]};['#1', '#2', '#3'] +map(xs, `#${#}`);{xs: [0.5, 0.25]};['#0.5', '#0.25'] +map(xs, `#${#}`);{xs: []};[] +map(xs, `#${#}`);{xs: [10]};['#10'] +map(xs, `#${#}`);{xs: ['a', null, true]};['#a', '#null', '#true'] +map(xs, `${#}:${# * 2}`);{xs: [1, 2, 3]};['1:2', '2:4', '3:6'] +map(xs, `${#}:${# * 2}`);{xs: [0.5, 0.25]};['0.5:1.0', '0.25:0.50'] +map(xs, `${#}:${# * 2}`);{xs: []};[] +map(xs, `${#}:${# * 2}`);{xs: [10]};['10:20'] +map(words, `<${upper(#)}>`);{words: ['alpha', 'beta']};['', ''] +map(words, `<${upper(#)}>`);{words: []};[] +map(words, `<${upper(#)}>`);{words: ['ONE']};[''] +map(words, `<${upper(#)}>`);{words: ['a', 'b', 'c']};['', '', ''] +map(words, `<${upper(#)}>`);{words: ['ß', 'fi']};['', ''] +map(words, `${#}${len(#) > 3 ? '!' : ''}`);{words: ['alpha', 'beta']};['alpha!', 'beta!'] +map(words, `${#}${len(#) > 3 ? '!' : ''}`);{words: []};[] +map(words, `${#}${len(#) > 3 ? '!' : ''}`);{words: ['ONE']};['ONE'] +map(words, `${#}${len(#) > 3 ? '!' : ''}`);{words: ['a', 'b', 'c']};['a', 'b', 'c'] +filter(map(words, `${lower(#)}`), # != 'one');{words: ['alpha', 'beta']};['alpha', 'beta'] +filter(map(words, `${lower(#)}`), # != 'one');{words: []};[] +filter(map(words, `${lower(#)}`), # != 'one');{words: ['ONE']};[] +filter(map(words, `${lower(#)}`), # != 'one');{words: ['a', 'b', 'c']};['a', 'b', 'c'] +map(rows, `${#.k}=${#.v}`);{rows: [{k: 'a', v: 1}, {k: 'b', v: 2.50}]};['a=1', 'b=2.50'] +map(rows, `${#.k}=${#.v}`);{rows: [{k: 'x'}]};['x=null'] +map(rows, `${#.k}=${#.v}`);{rows: []};[] +map(rows, `${#.k}=${#.v}`);{rows: [{k: null, v: null}]};['null=null'] +map(rows, `${upper(#.k ?? '?')}=${#.v ?? 0}`);{rows: [{k: 'a', v: 1}, {k: 'b', v: 2.50}]};['A=1', 'B=2.50'] +map(rows, `${upper(#.k ?? '?')}=${#.v ?? 0}`);{rows: [{k: 'x'}]};['X=0'] +map(rows, `${upper(#.k ?? '?')}=${#.v ?? 0}`);{rows: []};[] +map(rows, `${upper(#.k ?? '?')}=${#.v ?? 0}`);{rows: [{k: null, v: null}]};['?=0'] +map(rows as r, `${r.k}:${r.v * 10}`);{rows: [{k: 'a', v: 1}, {k: 'b', v: 2.50}]};['a:10', 'b:25.00'] +map(rows as r, `${r.k}:${r.v * 10}`);{rows: [{k: 'x'}]};!error +map(rows as r, `${r.k}:${r.v * 10}`);{rows: []};[] +map(rows as r, `${r.k}:${r.v * 10}`);{rows: [{k: null, v: null}]};!error +# templates inside objects and arrays +[`${a}`, `${b}`];{a: 'x', b: 1};['x', '1'] +[`${a}`, `${b}`];{a: 'Ä', b: 1.50};['Ä', '1.50'] +[`${a}`, `${b}`];{a: null, b: null};['null', 'null'] +[`${a}`, `${b}`];{};['null', 'null'] +[`${a}`, `${b}`];{a: '', b: true};['', 'true'] +{label: `${a}-${b}`, raw: a};{a: 'x', b: 1};{label: 'x-1', raw: 'x'} +{label: `${a}-${b}`, raw: a};{a: 'Ä', b: 1.50};{label: 'Ä-1.50', raw: 'Ä'} +{label: `${a}-${b}`, raw: a};{a: null, b: null};{label: 'null-null', raw: null} +{label: `${a}-${b}`, raw: a};{};{label: 'null-null', raw: null} +{label: `${a}-${b}`, raw: a};{a: '', b: true};{label: '-true', raw: ''} +map([1, 2], `${a}${#}`);{a: 'x', b: 1};['x1', 'x2'] +map([1, 2], `${a}${#}`);{a: 'Ä', b: 1.50};['Ä1', 'Ä2'] +map([1, 2], `${a}${#}`);{a: null, b: null};['null1', 'null2'] +map([1, 2], `${a}${#}`);{};['null1', 'null2'] +map([1, 2], `${a}${#}`);{a: '', b: true};['1', '2'] +({id: `${upper(a ?? 'n')}_${b ?? 0}`}).id;{a: 'x', b: 1};'X_1' +({id: `${upper(a ?? 'n')}_${b ?? 0}`}).id;{a: 'Ä', b: 1.50};'Ä_1.50' +({id: `${upper(a ?? 'n')}_${b ?? 0}`}).id;{a: null, b: null};'N_0' +({id: `${upper(a ?? 'n')}_${b ?? 0}`}).id;{};'N_0' +({id: `${upper(a ?? 'n')}_${b ?? 0}`}).id;{a: '', b: true};'_true' +[`${a}`, `${b}`][1];{a: 'x', b: 1};'1' +[`${a}`, `${b}`][1];{a: 'Ä', b: 1.50};'1.50' +[`${a}`, `${b}`][1];{a: null, b: null};'null' +[`${a}`, `${b}`][1];{};'null' +[`${a}`, `${b}`][1];{a: '', b: true};'true' +len([`${a}`, `${b}`, ``]);{a: 'x', b: 1};3 +len([`${a}`, `${b}`, ``]);{a: 'Ä', b: 1.50};3 +len([`${a}`, `${b}`, ``]);{a: null, b: null};3 +len([`${a}`, `${b}`, ``]);{};3 +len([`${a}`, `${b}`, ``]);{a: '', b: true};3 +# templates: type-dependent operators across rows +`${a + b}`;{a: 1, b: 2};'3' +`${a + b}`;{a: 'x', b: 'y'};'xy' +`${a + b}`;{a: 0.1, b: 0.2};'0.3' +`${a + b}`;{a: 'x', b: 1};!error +`${a + b}`;{a: null, b: 'y'};!error +`${a + b}`;{a: '', b: ''};'' +`${a}${b}`;{a: 1, b: 2};'12' +`${a}${b}`;{a: 'x', b: 'y'};'xy' +`${a}${b}`;{a: 0.1, b: 0.2};'0.10.2' +`${a}${b}`;{a: 'x', b: 1};'x1' +`${a}${b}`;{a: null, b: 'y'};'nully' +`${a}${b}`;{a: '', b: ''};'' +`${a}${b}` == string(a) + string(b);{a: 1, b: 2};true +`${a}${b}` == string(a) + string(b);{a: 'x', b: 'y'};true +`${a}${b}` == string(a) + string(b);{a: 0.1, b: 0.2};true +`${a}${b}` == string(a) + string(b);{a: 'x', b: 1};true +`${a}${b}` == string(a) + string(b);{a: null, b: 'y'};true +`${a}${b}` == string(a) + string(b);{a: '', b: ''};true +`${a == b}`;{a: 1, b: 2};'false' +`${a == b}`;{a: 'x', b: 'y'};'false' +`${a == b}`;{a: 0.1, b: 0.2};'false' +`${a == b}`;{a: 'x', b: 1};'false' +`${a == b}`;{a: null, b: 'y'};'false' +`${a == b}`;{a: '', b: ''};'true' +# templates: results fed into string functions +upper(`${a}-${b}`);{a: 'ab', b: 'CD'};'AB-CD' +upper(`${a}-${b}`);{a: ' x', b: 'y '};' X-Y ' +upper(`${a}-${b}`);{a: 'ß', b: 'ö'};'SS-Ö' +upper(`${a}-${b}`);{a: null, b: 'z'};'NULL-Z' +upper(`${a}-${b}`);{a: 1, b: 2.0};'1-2.0' +trim(`${a} ${b}`);{a: 'ab', b: 'CD'};'ab CD' +trim(`${a} ${b}`);{a: ' x', b: 'y '};'x y' +trim(`${a} ${b}`);{a: 'ß', b: 'ö'};'ß ö' +trim(`${a} ${b}`);{a: null, b: 'z'};'null z' +trim(`${a} ${b}`);{a: 1, b: 2.0};'1 2.0' +len(`${a}${b}`);{a: 'ab', b: 'CD'};4 +len(`${a}${b}`);{a: ' x', b: 'y '};4 +len(`${a}${b}`);{a: 'ß', b: 'ö'};2;bug: len counts UTF-8 bytes, intended character count +len(`${a}${b}`);{a: null, b: 'z'};5 +len(`${a}${b}`);{a: 1, b: 2.0};4 +split(`${a},${b}`, ',');{a: 'ab', b: 'CD'};['ab', 'CD'] +split(`${a},${b}`, ',');{a: ' x', b: 'y '};[' x', 'y '] +split(`${a},${b}`, ',');{a: 'ß', b: 'ö'};['ß', 'ö'] +split(`${a},${b}`, ',');{a: null, b: 'z'};['null', 'z'] +split(`${a},${b}`, ',');{a: 1, b: 2.0};['1', '2.0'] +contains(`${a}${b}`, 'null');{a: 'ab', b: 'CD'};false +contains(`${a}${b}`, 'null');{a: ' x', b: 'y '};false +contains(`${a}${b}`, 'null');{a: 'ß', b: 'ö'};false +contains(`${a}${b}`, 'null');{a: null, b: 'z'};true +contains(`${a}${b}`, 'null');{a: 1, b: 2.0};false +matches(`${a}${b}`, '^[a-z]+$');{a: 'ab', b: 'CD'};false +matches(`${a}${b}`, '^[a-z]+$');{a: ' x', b: 'y '};false +matches(`${a}${b}`, '^[a-z]+$');{a: 'ß', b: 'ö'};false +matches(`${a}${b}`, '^[a-z]+$');{a: null, b: 'z'};true +matches(`${a}${b}`, '^[a-z]+$');{a: 1, b: 2.0};false +`${a}` == a;{a: 'ab', b: 'CD'};true +`${a}` == a;{a: ' x', b: 'y '};true +`${a}` == a;{a: 'ß', b: 'ö'};true +`${a}` == a;{a: null, b: 'z'};false +`${a}` == a;{a: 1, b: 2.0};false +# templates: literal text around interpolations +`$${n}`;{n: 5};'$5' +`$${n}`;{n: 9.90};'$9.90' +`$${n}`;{n: null};'$null' +`$${n}`;{n: 'x'};'$x' +`${n}%`;{n: 5};'5%' +`${n}%`;{n: 12.50};'12.50%' +`${n}%`;{n: -0.5};'-0.5%' +`${n}%`;{};'null%' +`{${n}}`;{n: 1};'{1}' +`{${n}}`;{n: 'a'};'{a}' +`{${n}}`;{};'{null}' +`a ${n} b ${n} c`;{n: 1};'a 1 b 1 c' +`a ${n} b ${n} c`;{n: 'x'};'a x b x c' +`a ${n} b ${n} c`;{n: ''};'a b c' +`${s}` + '|' + `${t}`;{s: 'a', t: 'b'};'a|b' +`${s}` + '|' + `${t}`;{s: '', t: ''};'|' +`${s}` + '|' + `${t}`;{s: null};'null|null' +`${s}` + '|' + `${t}`;{s: 1, t: false};'1|false' +`${s}`;{s: ' spaced '};' spaced ' +`${s}`;{s: 'tab\there'};'tab\there' +`${s}`;{s: 'line\nbreak'};'line\nbreak' +`${s}`;{s: '日本語'};'日本語' +`${s}`;{s: '😀'};'😀' +`${s}`;{s: '\u00a0'};'\u00a0' +`${s}`;{s: 'é'};'é' +`${s}`;{s: 'O\'Brien'};'O\'Brien' +`${s}`;{s: 'back\\slash'};'back\\slash' +`${s}`;{s: '`tick`'};'`tick`' +`${s}`;{s: '${not}'};'${not}' +# templates: nested templates +`${`inner ${x}`}`;{x: 1};'inner 1';bug: a template nested in an interpolation fails to parse +`${`inner ${x}`}`;{x: 'a'};'inner a';bug: a template nested in an interpolation fails to parse +`${`inner ${x}`}`;{x: null};'inner null';bug: a template nested in an interpolation fails to parse +`${`inner ${x}`}`;{};'inner null';bug: a template nested in an interpolation fails to parse +`${x > 0 ? `+${x}` : `${x}`}`;{x: 5};'+5';bug: a template nested in an interpolation fails to parse +`${x > 0 ? `+${x}` : `${x}`}`;{x: 0};'0';bug: a template nested in an interpolation fails to parse +`${x > 0 ? `+${x}` : `${x}`}`;{x: -2.5};'-2.5';bug: a template nested in an interpolation fails to parse +`${x > 0 ? `+${x}` : `${x}`}`;{x: null};!error +map(xs, `${`[${#}]`}`);{xs: [1, 'a']};['[1]', '[a]'];bug: a template nested in an interpolation fails to parse +map(xs, `${`[${#}]`}`);{xs: []};[];bug: a template nested in an interpolation fails to parse diff --git a/core/expression/tests/spec/standard/15-04-regex.csv b/core/expression/tests/spec/standard/15-04-regex.csv new file mode 100644 index 00000000..4f9a36cd --- /dev/null +++ b/core/expression/tests/spec/standard/15-04-regex.csv @@ -0,0 +1,651 @@ +expression (string);input (json 5);output (json 5);note +# regex matrix: email addresses +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'john.doe@example.com'};true +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'a+tag@sub.domain.co.uk'};true +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'UPPER@EXAMPLE.ORG'};true +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'no-at-sign.com'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'two@@example.com'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'user@localhost'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'user@exa mple.com'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: ' lead@space.com'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'x@y.z'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'dots..ok@example.io'};true +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: 'ünï@example.com'};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: ''};false +matches(s, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');{s: null};!error +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'john.doe@example.com'};true +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'a+tag@sub.domain.co.uk'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'UPPER@EXAMPLE.ORG'};true +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'no-at-sign.com'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'two@@example.com'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'user@localhost'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'user@exa mple.com'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: ' lead@space.com'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'x@y.z'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'dots..ok@example.io'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: 'ünï@example.com'};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: ''};false +matches(s, '(?i)^[a-z0-9._%+-]+@example\.(com|org)$');{s: null};!error +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'john.doe@example.com'};['john.doe@example.com', 'john.doe', 'example.com'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'a+tag@sub.domain.co.uk'};['a+tag@sub.domain.co.uk', 'a+tag', 'sub.domain.co.uk'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'UPPER@EXAMPLE.ORG'};['UPPER@EXAMPLE.ORG', 'UPPER', 'EXAMPLE.ORG'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'no-at-sign.com'};[] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'two@@example.com'};[] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'user@localhost'};['user@localhost', 'user', 'localhost'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'user@exa mple.com'};['user@exa', 'user', 'exa'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: ' lead@space.com'};['lead@space.com', 'lead', 'space.com'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'x@y.z'};['x@y.z', 'x', 'y.z'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'dots..ok@example.io'};['dots..ok@example.io', 'dots..ok', 'example.io'] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'ünï@example.com'};[] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: ''};[] +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: null};!error +extract(s, '([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)');{s: 'contact: sales@acme.com, or support@acme.com'};['sales@acme.com', 'sales', 'acme.com'] +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'john.doe@example.com'};'example.com' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'a+tag@sub.domain.co.uk'};'sub.domain.co.uk' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'UPPER@EXAMPLE.ORG'};'example.org' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'no-at-sign.com'};'' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'two@@example.com'};'example.com' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'user@localhost'};'localhost' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'user@exa mple.com'};'' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: ' lead@space.com'};'space.com' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'x@y.z'};'y.z' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'dots..ok@example.io'};'example.io' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: 'ünï@example.com'};'example.com' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: ''};'' +lower(extract(s, '@([A-Za-z0-9.-]+)$')[1] ?? '');{s: null};!error +# regex matrix: phone numbers +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '555-123-4567'};true +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '(555) 123-4567'};true +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '+1 555 123 4567'};true +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '5551234567'};true +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '555.123.4567'};true +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '1-555-123-4567'};true +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '555-1234'};false +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '555-123-45678'};false +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: 'abc-def-ghij'};false +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: '+44 20 7946 0958'};false +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: ''};false +matches(s, '^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$');{s: null};!error +matches(s, '^\+[1-9]\d{6,14}$');{s: '+14155552671'};true +matches(s, '^\+[1-9]\d{6,14}$');{s: '+442079460958'};true +matches(s, '^\+[1-9]\d{6,14}$');{s: '+0123456789'};false +matches(s, '^\+[1-9]\d{6,14}$');{s: '14155552671'};false +matches(s, '^\+[1-9]\d{6,14}$');{s: '+1415555267123456'};false +matches(s, '^\+[1-9]\d{6,14}$');{s: '+123456'};false +matches(s, '^\+[1-9]\d{6,14}$');{s: '+1234567'};true +matches(s, '^\+[1-9]\d{6,14}$');{s: '+49 30 1234'};false +matches(s, '^\+[1-9]\d{6,14}$');{s: ''};false +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '555-123-4567'};['555-123-4567', null, '555', '123', '4567'];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '(555) 123-4567'};['(555) 123-4567', null, '555', '123', '4567'];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '+1 555 123 4567'};['+1 555 123 4567', '+1', '555', '123', '4567'] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '5551234567'};['5551234567', null, '555', '123', '4567'];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '555.123.4567'};['555.123.4567', null, '555', '123', '4567'];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '1-555-123-4567'};[] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '555-1234'};[] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '555-123-45678'};[] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: 'abc-def-ghij'};[] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: '+44 20 7946 0958'};[] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: ''};[] +extract(s, '^(\+\d{1,3})?\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})$');{s: null};!error +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: '555-123-4567'};[12, 3, 3, 4] +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: '(555) 123-4567'};[13, 3, 3, 4] +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: '+1 555 123 4567'};[12, 3, 3, 4] +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: '5551234567'};[10, 3, 3, 4] +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: '555.123.4567'};[12, 3, 3, 4] +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: '1-555-123-4567'};[12, 3, 3, 4] +map(extract(s, '(\d{3})\D*(\d{3})\D*(\d{4})'), len(#));{s: 'call 555 123 4567 now'};[12, 3, 3, 4] +# regex matrix: postcodes +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'SW1A 1AA'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'M1 1AE'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'B33 8TH'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'CR2 6XH'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'DN55 1PT'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'EC1A1BB'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'sw1a 1aa'};false +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'SW1A 1AA'};false +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: '12345'};false +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'W1A 0AX'};true +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'Q1 1QQQ'};false +matches(s, '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: ''};false +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'SW1A 1AA'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'M1 1AE'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'B33 8TH'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'CR2 6XH'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'DN55 1PT'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'EC1A1BB'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'sw1a 1aa'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'SW1A 1AA'};false +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: '12345'};false +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'W1A 0AX'};true +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'Q1 1QQQ'};false +matches(s, '(?i)^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: ''};false +matches(upper(trim(s)), '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: ' sw1a 1aa '};true +matches(upper(trim(s)), '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'm1 1ae'};true +matches(upper(trim(s)), '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'b338th'};true +matches(upper(trim(s)), '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: 'xx'};false +matches(upper(trim(s)), '^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$');{s: null};!error +matches(s, '^\d{5}(-\d{4})?$');{s: '12345'};true +matches(s, '^\d{5}(-\d{4})?$');{s: '12345-6789'};true +matches(s, '^\d{5}(-\d{4})?$');{s: '1234'};false +matches(s, '^\d{5}(-\d{4})?$');{s: '123456'};false +matches(s, '^\d{5}(-\d{4})?$');{s: '12345-678'};false +matches(s, '^\d{5}(-\d{4})?$');{s: '12345 6789'};false +matches(s, '^\d{5}(-\d{4})?$');{s: 'ABCDE'};false +matches(s, '^\d{5}(-\d{4})?$');{s: '02134'};true +matches(s, '^\d{5}(-\d{4})?$');{s: ''};false +matches(s, '^\d{5}(-\d{4})?$');{s: '94107'};true;question: \d is Unicode-aware (matches fullwidth digits), unlike JS +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '12345'};true +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '12345-6789'};true +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '1234'};false +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '123456'};false +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '12345-678'};false +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '12345 6789'};false +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: 'ABCDE'};false +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '02134'};true +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: ''};false +matches(s, '^[0-9]{5}(-[0-9]{4})?$');{s: '94107'};false +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '12345'};['12345', '12345', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '12345-6789'};['12345-6789', '12345', '6789'] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '1234'};[] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '123456'};[] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '12345-678'};[] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '12345 6789'};[] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: 'ABCDE'};[] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '02134'};['02134', '02134', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: ''};[] +extract(s, '^(\d{5})(?:-(\d{4}))?$');{s: '94107'};['94107', '94107', null];bug: non-participating groups are dropped, shifting group positions +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: 'K1A 0B1'};true +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: 'k1a0b1'};true +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: 'K1A-0B1'};true +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: 'K1A 0B1'};false +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: 'KIA 0B1'};false +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: '1A1 A1A'};false +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: 'H0H 0H0'};true +matches(s, '^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$');{s: ''};false +# regex matrix: IBAN-like account numbers +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'DE89370400440532013000'};true +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'GB82WEST12345698765432'};true +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'NL91ABNA0417164300'};true +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'de89370400440532013000'};false +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'DE89 3704 0044 0532 0130 00'};false +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'D89370400440532013000'};false +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'DE8937040044'};false +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'FR1420041010050500013M02606'};true +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'XX00'};false +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: ''};false +matches(s, '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: null};!error +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'DE89370400440532013000'};['DE893704', 'DE', '89', '3704'] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'GB82WEST12345698765432'};['GB82WEST', 'GB', '82', 'WEST'] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'NL91ABNA0417164300'};['NL91ABNA', 'NL', '91', 'ABNA'] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'de89370400440532013000'};[] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'DE89 3704 0044 0532 0130 00'};[] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'D89370400440532013000'};[] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'DE8937040044'};['DE893704', 'DE', '89', '3704'] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'FR1420041010050500013M02606'};['FR142004', 'FR', '14', '2004'] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: 'XX00'};[] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: ''};[] +extract(s, '^([A-Z]{2})(\d{2})([A-Z0-9]{4})');{s: null};!error +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'DE89370400440532013000'};true +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'GB82WEST12345698765432'};true +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'NL91ABNA0417164300'};true +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'de89370400440532013000'};true +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'DE89 3704 0044 0532 0130 00'};false +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'D89370400440532013000'};false +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'DE8937040044'};false +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'FR1420041010050500013M02606'};true +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: 'XX00'};false +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: ''};false +matches(upper(s), '^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$');{s: null};!error +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'DE89370400440532013000'};true +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'GB82WEST12345698765432'};false +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'NL91ABNA0417164300'};true +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'de89370400440532013000'};false +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'DE89 3704 0044 0532 0130 00'};true +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'D89370400440532013000'};false +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'DE8937040044'};true +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'FR1420041010050500013M02606'};true +extract(s, '^([A-Z]{2})')[1] in ['DE', 'NL', 'FR'];{s: 'XX00'};false +# regex matrix: SKUs and product codes +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234'};true +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234-XL'};true +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'abc-1234'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'AB-1234'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABCD-1234'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-123'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-12345'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234-X'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234-XLL'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC1234'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: ' ABC-1234'};false +matches(s, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: ''};false +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC-1234'};['ABC-1234', 'ABC', '1234', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC-1234-XL'};['ABC-1234-XL', 'ABC', '1234', 'XL'] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'abc-1234'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'AB-1234'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABCD-1234'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC-123'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC-12345'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC-1234-X'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC-1234-XLL'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: 'ABC1234'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: ' ABC-1234'};[] +extract(s, '^([A-Z]{3})-(\d{4})(?:-([A-Z]{2}))?$');{s: ''};[] +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC-1234'};'1234' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC-1234-XL'};'1234' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'abc-1234'};'none' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'AB-1234'};'none' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABCD-1234'};'none' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC-123'};'none' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC-12345'};'1234' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC-1234-X'};'1234' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC-1234-XLL'};'1234' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: 'ABC1234'};'none' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: ' ABC-1234'};'none' +extract(s, '^([A-Z]{3})-(\d{4})')[2] ?? 'none';{s: ''};'none' +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'ABC-1234'};1235 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'ABC-1234-XL'};1235 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'abc-1234'};1235 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'AB-1234'};1235 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'ABCD-1234'};1235 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'ABC-123'};1 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'ABC-12345'};1235 +number(extract(s, '-(\d{4})')[1] ?? '0') + 1;{s: 'ABC-1234-X'};1235 +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234'};true +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234-XL'};true +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'abc-1234'};true +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'AB-1234'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABCD-1234'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-123'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-12345'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234-X'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC-1234-XLL'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: 'ABC1234'};false +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: ' ABC-1234'};true +matches(upper(trim(s)), '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$');{s: ''};false +# regex matrix: dates +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-01-31'};true +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-12-01'};true +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-13-01'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-00-10'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-02-30'};true +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-1-5'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '24-01-01'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024/01/01'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-01-32'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: '2024-10-10T00:00'};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: ''};false +matches(s, '^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$');{s: null};!error +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-01-31'};['2024-01-31', '2024', '01', '31'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-12-01'};['2024-12-01', '2024', '12', '01'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-13-01'};['2024-13-01', '2024', '13', '01'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-00-10'};['2024-00-10', '2024', '00', '10'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-02-30'};['2024-02-30', '2024', '02', '30'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-1-5'};[] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '24-01-01'};[] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024/01/01'};[] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-01-32'};['2024-01-32', '2024', '01', '32'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: '2024-10-10T00:00'};['2024-10-10', '2024', '10', '10'] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: ''};[] +extract(s, '^(\d{4})-(\d{2})-(\d{2})');{s: null};!error +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: 'Invoice dated 2024-03-15, due 2024-04-15.'};true +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: 'no date here'};false +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: 'on 1999-12-31 at noon'};true +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: 'v2024-01-01x'};false +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: '20240101'};false +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: 'Date:2025-03-20'};true +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: ''};false +matches(s, '\b\d{4}-\d{2}-\d{2}\b');{s: 'range 2024-01-01..2024-02-01'};true +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: 'Invoice dated 2024-03-15, due 2024-04-15.'};['2024-03-15', '2024', '03', '15'] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: 'no date here'};[] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: 'on 1999-12-31 at noon'};['1999-12-31', '1999', '12', '31'] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: 'v2024-01-01x'};['2024-01-01', '2024', '01', '01'] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: '20240101'};[] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: 'Date:2025-03-20'};['2025-03-20', '2025', '03', '20'] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: ''};[] +extract(s, '(\d{4})-(\d{2})-(\d{2})');{s: 'range 2024-01-01..2024-02-01'};['2024-01-01', '2024', '01', '01'] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: 'Invoice dated 2024-03-15, due 2024-04-15.'};['due 2024-04-15', '2024-04-15'] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: 'no date here'};[] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: 'on 1999-12-31 at noon'};[] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: 'v2024-01-01x'};[] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: '20240101'};[] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: 'Date:2025-03-20'};[] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: ''};[] +extract(s, 'due (\d{4}-\d{2}-\d{2})');{s: 'range 2024-01-01..2024-02-01'};[] +d(extract(s, '\d{4}-\d{2}-\d{2}')[0]).format('%d/%m/%Y');{s: 'Invoice dated 2024-03-15, due 2024-04-15.'};'15/03/2024' +d(extract(s, '\d{4}-\d{2}-\d{2}')[0]).format('%d/%m/%Y');{s: 'on 1999-12-31 at noon'};'31/12/1999' +d(extract(s, '\d{4}-\d{2}-\d{2}')[0]).format('%d/%m/%Y');{s: 'Date:2025-03-20'};'20/03/2025' +extract(s, '(\d{1,2})/(\d{1,2})/(\d{4})');{s: 'Paid on 3/7/2024'};['3/7/2024', '3', '7', '2024'] +extract(s, '(\d{1,2})/(\d{1,2})/(\d{4})');{s: 'due 12/31/1999!'};['12/31/1999', '12', '31', '1999'] +extract(s, '(\d{1,2})/(\d{1,2})/(\d{4})');{s: '1/1/70'};[] +extract(s, '(\d{1,2})/(\d{1,2})/(\d{4})');{s: 'n/a'};[] +# regex matrix: times, colors, network +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '00:00'};true +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '23:59'};true +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '24:00'};false +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '12:60'};false +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '9:30'};false +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '09:30'};true +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '19:05:00'};false +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: ''};false +matches(s, '^([01]\d|2[0-3]):[0-5]\d$');{s: '7pm'};false +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '00:00'};['00:00', '00', '00', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '23:59'};['23:59', '23', '59', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '24:00'};['24:00', '24', '00', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '12:60'};['12:60', '12', '60', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '9:30'};['9:30', '9', '30', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '09:30'};['09:30', '09', '30', null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '19:05:00'};['19:05:00', '19', '05', '00'] +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: ''};[] +extract(s, '^(\d{1,2}):(\d{2})(?::(\d{2}))?$');{s: '7pm'};[] +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#fff'};true +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#FFFFFF'};true +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#a1b2c3'};true +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#abcd'};false +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#ggg'};false +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: 'fff'};false +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#12345'};false +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: '#1234567'};false +matches(s, '^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');{s: ''};false +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: '192.168.0.1'};true +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: '10.0.0.255'};true +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: '256.1.1.1'};true +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: '1.2.3'};false +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: '1.2.3.4.5'};false +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: 'a.b.c.d'};false +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: '127.000.000.001'};true +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: ''};false +matches(s, '^(\d{1,3}\.){3}\d{1,3}$');{s: ' 1.1.1.1'};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: '192.168.0.1'};true +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: '10.0.0.255'};true +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: '256.1.1.1'};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: '1.2.3'};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: '1.2.3.4.5'};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: 'a.b.c.d'};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: '127.000.000.001'};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: ''};false +matches(s, '^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$');{s: ' 1.1.1.1'};false +matches(s, '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');{s: '123e4567-e89b-12d3-a456-426614174000'};true +matches(s, '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');{s: '123E4567-E89B-12D3-A456-426614174000'};false +matches(s, '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');{s: '123e4567e89b12d3a456426614174000'};false +matches(s, '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');{s: '123e4567-e89b-12d3-a456-42661417400'};false +matches(s, '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');{s: 'zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz'};false +matches(s, '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');{s: ''};false +matches(s, '(?i)^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');{s: '123e4567-e89b-12d3-a456-426614174000'};true +matches(s, '(?i)^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');{s: '123E4567-E89B-12D3-A456-426614174000'};true +matches(s, '(?i)^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');{s: '123e4567e89b12d3a456426614174000'};false +matches(s, '(?i)^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');{s: '123e4567-e89b-12d3-a456-42661417400'};false +matches(s, '(?i)^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');{s: 'zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz'};false +matches(s, '(?i)^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');{s: ''};false +# regex matrix: URLs +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'https://example.com'};true +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'http://example.com:8080/path?q=1'};true +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'https://sub.example.co.uk/a/b'};true +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'ftp://example.com'};false +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'https://'};false +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'example.com'};false +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'HTTPS://EXAMPLE.COM/'};false +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: 'https://ex ample.com'};false +matches(s, '^https?://[^\s/$.?#].[^\s]*$');{s: ''};false +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'https://example.com'};['https://example.com', 'https', 'example.com', null, null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'http://example.com:8080/path?q=1'};['http://example.com:8080/path?q=1', 'http', 'example.com', '8080', '/path?q=1'] +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'https://sub.example.co.uk/a/b'};['https://sub.example.co.uk/a/b', 'https', 'sub.example.co.uk', null, '/a/b'];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'ftp://example.com'};[] +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'https://'};[] +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'example.com'};[] +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'HTTPS://EXAMPLE.COM/'};[] +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: 'https://ex ample.com'};['https://ex ample.com', 'https', 'ex ample.com', null, null];bug: non-participating groups are dropped, shifting group positions +extract(s, '^(https?)://([^/:]+)(?::(\d+))?(/.*)?$');{s: ''};[] +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'https://example.com'};'example.com' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'http://example.com:8080/path?q=1'};'example.com' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'https://sub.example.co.uk/a/b'};'sub.example.co.uk' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'ftp://example.com'};'invalid' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'https://'};'invalid' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'example.com'};'invalid' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'HTTPS://EXAMPLE.COM/'};'invalid' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: 'https://ex ample.com'};'ex ample.com' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: ''};'invalid' +extract(url, '^https?://([^/:]+)')[1] ?? 'invalid';{url: null};!error +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'https://example.com'};true +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'http://example.com:8080/path?q=1'};false +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'https://sub.example.co.uk/a/b'};true +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'ftp://example.com'};false +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'https://'};true +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'example.com'};false +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'HTTPS://EXAMPLE.COM/'};true +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: 'https://ex ample.com'};true +lower(extract(url, '(?i)^(https?)://')[1] ?? '') == 'https';{url: ''};false +# regex matrix: amounts and quantities +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '$1,234.56'};true +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '1234.56'};false +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '$12'};true +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '1,234'};true +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '12,34'};false +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '$1,234.5'};false +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '$0.99'};true +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '1,234,567.00'};true +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: '$'};false +matches(s, '^\$?\d{1,3}(,\d{3})*(\.\d{2})?$');{s: ''};false +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '$1,234.56'};true +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '1234.56'};true +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '$12'};true +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '1,234'};true +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '12,34'};false +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '$1,234.5'};false +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '$0.99'};true +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '1,234,567.00'};true +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: '$'};false +matches(s, '^\$?(\d+|\d{1,3}(,\d{3})*)(\.\d{2})?$');{s: ''};false +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: '2.5 kg'};['2.5 kg', '2.5', 'kg'] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: '10kg'};['10kg', '10', 'kg'] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: '500 g'};['500 g', '500', 'g'] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: '3 lb bag'};['3 lb', '3', 'lb'] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: '1.25lbs'};['1.25lb', '1.25', 'lb'] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: 'kg'};[] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: 'about 7 g'};['7 g', '7', 'g'] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: ''};[] +extract(s, '(\d+(?:\.\d+)?)\s*(kg|g|lb)');{s: 'weight: 0.5 KG'};[] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: '2.5 kg'};['2.5 kg', '2.5', 'kg'] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: '10kg'};['10kg', '10', 'kg'] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: '500 g'};['500 g', '500', 'g'] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: '3 lb bag'};['3 lb', '3', 'lb'] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: '1.25lbs'};[] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: 'kg'};[] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: 'about 7 g'};['7 g', '7', 'g'] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: ''};[] +extract(s, '(?i)(\d+(?:\.\d+)?)\s*(kg|g|lb)\b');{s: 'weight: 0.5 KG'};['0.5 KG', '0.5', 'KG'] +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: '2.5 kg'};2500.0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: '10kg'};10000 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: '500 g'};0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: '3 lb bag'};0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: '1.25lbs'};0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: 'kg'};0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: 'about 7 g'};0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: ''};0 +number(extract(s, '(\d+(?:\.\d+)?)\s*kg')[1] ?? '0') * 1000;{s: 'weight: 0.5 KG'};0 +# regex matrix: keyword alternation +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'Customer requests a REFUND'};true +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'chargeback initiated'};true +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'Dispute opened'};true +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'refunded already'};false +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'nothing to see'};false +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'prerefund'};false +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'Refund/Dispute'};true +matches(s, '(?i)\b(refund|chargeback|dispute)\b');{s: ''};false +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'Customer requests a REFUND'};true +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'chargeback initiated'};true +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'Dispute opened'};true +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'refunded already'};true +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'nothing to see'};false +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'prerefund'};true +matches(s, '(?i)(refund|chargeback|dispute)');{s: 'Refund/Dispute'};true +matches(s, '(?i)(refund|chargeback|dispute)');{s: ''};false +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'Customer requests a REFUND'};['REFUND', 'REFUND'] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'chargeback initiated'};['chargeback', 'chargeback'] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'Dispute opened'};['Dispute', 'Dispute'] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'refunded already'};[] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'nothing to see'};[] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'prerefund'};[] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: 'Refund/Dispute'};['Refund', 'Refund'] +extract(s, '(?i)\b(refund|chargeback|dispute)\b');{s: ''};[] +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'Customer requests a REFUND'};'REFUND' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'chargeback initiated'};'CHARGEBACK' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'Dispute opened'};'DISPUTE' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'refunded already'};'NONE' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'nothing to see'};'NONE' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'prerefund'};'NONE' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: 'Refund/Dispute'};'REFUND' +upper(extract(s, '(?i)\b(refund|chargeback|dispute)\b')[1] ?? 'none');{s: ''};'NONE' +extract(s, '(?i)order\s*#?\s*(\d+)');{s: 'Order #12345 shipped'};['Order #12345', '12345'] +extract(s, '(?i)order\s*#?\s*(\d+)');{s: 'order 987'};['order 987', '987'] +extract(s, '(?i)order\s*#?\s*(\d+)');{s: 'ORDER#42'};['ORDER#42', '42'] +extract(s, '(?i)order\s*#?\s*(\d+)');{s: 'Re: order no. 77'};[] +extract(s, '(?i)order\s*#?\s*(\d+)');{s: 'orders 5'};[] +extract(s, '(?i)order\s*#?\s*(\d+)');{s: 'no order'};[] +extract(s, '(?i)order\s*#?\s*(\d+)');{s: ''};[] +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: 'Order #12345 shipped'};12345 +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: 'order 987'};987 +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: 'ORDER#42'};42 +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: 'Re: order no. 77'};-1 +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: 'orders 5'};-1 +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: 'no order'};-1 +number(extract(s, '(?i)order\s*#?\s*(\d+)')[1] ?? '-1');{s: ''};-1 +# regex matrix: masks, usernames, passwords +matches(s, '^\d{4}( ?\*{4}){2} ?\d{4}$');{s: '4111 **** **** 1111'};true +matches(s, '^\d{4}( ?\*{4}){2} ?\d{4}$');{s: '4111********1111'};true +matches(s, '^\d{4}( ?\*{4}){2} ?\d{4}$');{s: '4111 1111 1111 1111'};false +matches(s, '^\d{4}( ?\*{4}){2} ?\d{4}$');{s: '**** **** **** 1111'};false +matches(s, '^\d{4}( ?\*{4}){2} ?\d{4}$');{s: '4111 **** 1111'};false +matches(s, '^\d{4}( ?\*{4}){2} ?\d{4}$');{s: ''};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'alice'};true +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'bob_99'};true +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'x1'};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'a_very_long_username_here'};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: '9lives'};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'Alice'};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'al'};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'abc'};true +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'ab-c'};false +matches(s, '^[a-z][a-z0-9_]{2,15}$');{s: 'ünï'};false +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: 'Passw0rd'};true +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: 'password'};false +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: 'PASSWORD1'};false +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: 'Pass1'};false +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: 'P4ssword!'};true +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: '12345678'};false +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: 'Ab1Ab1Ab1'};true +len(s) >= 8 and matches(s, '[A-Z]') and matches(s, '[a-z]') and matches(s, '\d');{s: ''};false +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: 'Passw0rd'};3 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: 'password'};1 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: 'PASSWORD1'};2 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: 'Pass1'};3 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: 'P4ssword!'};4 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: '12345678'};1 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: 'Ab1Ab1Ab1'};3 +count([matches(s, '[A-Z]'), matches(s, '[a-z]'), matches(s, '\d'), matches(s, '[^A-Za-z0-9]')], #);{s: ''};0 +# regex: key-value extraction +extract(s, '(?P\w+)=(?P[^&]*)');{s: 'key=value'};['key=value', 'key', 'value'] +extract(s, '(?P\w+)=(?P[^&]*)');{s: 'a=1&b=2'};['a=1', 'a', '1'] +extract(s, '(?P\w+)=(?P[^&]*)');{s: 'name = Ann'};[] +extract(s, '(?P\w+)=(?P[^&]*)');{s: '=empty'};[] +extract(s, '(?P\w+)=(?P[^&]*)');{s: 'noequals'};[] +extract(s, '(?P\w+)=(?P[^&]*)');{s: 'x='};['x=', 'x', ''] +extract(s, '(?P\w+)=(?P[^&]*)');{s: 'ä=ö'};['ä=ö', 'ä', 'ö'] +extract(s, '(?P\w+)=(?P[^&]*)');{s: ''};[] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: 'key=value'};['key=value', 'key', 'value'] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: 'a=1&b=2'};['a=1&b=2', 'a', '1&b=2'] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: 'name = Ann'};['name = Ann', 'name', 'Ann'] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: '=empty'};[] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: 'noequals'};[] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: 'x='};['x=', 'x', ''] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: 'ä=ö'};['ä=ö', 'ä', 'ö'] +extract(s, '^(\w+)\s*=\s*(.*)$');{s: ''};[] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: 'key=value'};['key'] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: 'a=1&b=2'};['a', 'b'] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: 'name = Ann'};[''] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: '=empty'};[''] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: 'noequals'};[''] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: 'x='};['x'] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: 'ä=ö'};['ä'] +map(split(s, '&'), extract(#, '^(\w+)=(.*)$')[1] ?? '');{s: ''};[''] +# regex: anchors and multiline text +matches(s, '^first');{s: 'first\nsecond'};true +matches(s, '^first');{s: 'second\nfirst'};false +matches(s, '^first');{s: 'first'};true +matches(s, '^first');{s: 'x first\nsecond'};false +matches(s, '^first');{s: ''};false +matches(s, '^first');{s: 'FIRST\nsecond'};false +matches(s, '(?m)^second$');{s: 'first\nsecond'};true +matches(s, '(?m)^second$');{s: 'second\nfirst'};true +matches(s, '(?m)^second$');{s: 'first'};false +matches(s, '(?m)^second$');{s: 'x first\nsecond'};true +matches(s, '(?m)^second$');{s: ''};false +matches(s, '(?m)^second$');{s: 'FIRST\nsecond'};true +matches(s, '(?i)^first');{s: 'first\nsecond'};true +matches(s, '(?i)^first');{s: 'second\nfirst'};false +matches(s, '(?i)^first');{s: 'first'};true +matches(s, '(?i)^first');{s: 'x first\nsecond'};false +matches(s, '(?i)^first');{s: ''};false +matches(s, '(?i)^first');{s: 'FIRST\nsecond'};true +matches(s, 'first$');{s: 'first\nsecond'};false +matches(s, 'first$');{s: 'second\nfirst'};true +matches(s, 'first$');{s: 'first'};true +matches(s, 'first$');{s: 'x first\nsecond'};false +matches(s, 'first$');{s: ''};false +matches(s, 'first$');{s: 'FIRST\nsecond'};false +matches(s, '(?m)first$');{s: 'first\nsecond'};true +matches(s, '(?m)first$');{s: 'second\nfirst'};true +matches(s, '(?m)first$');{s: 'first'};true +matches(s, '(?m)first$');{s: 'x first\nsecond'};true +matches(s, '(?m)first$');{s: ''};false +matches(s, '(?m)first$');{s: 'FIRST\nsecond'};false +# regex: patterns from the input across rows +matches(s, p);{s: 'ABC-1234', p: '^[A-Z]{3}-\\d{4}(-[A-Z]{2})?$'};true +matches(s, p);{s: 'john@example.com', p: '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'};true +matches(s, p);{s: '12345', p: '^\\d{5}$'};true +matches(s, p);{s: 'abc', p: '^[A-Z]+$'};false +matches(s, p);{s: 'abc', p: '(?i)^[A-Z]+$'};true +matches(s, p);{s: 'x', p: ''};true +matches(s, p);{s: 'x', p: '(unclosed'};!error +matches(s, p);{s: 'x', p: null};!error +matches(s, p);{s: null, p: 'x'};!error +matches(s, p);{s: 'ab', p: 'a|b'};true +len(extract(s, p));{s: 'ABC-1234', p: '^[A-Z]{3}-\\d{4}(-[A-Z]{2})?$'};2;bug: non-participating groups are dropped, shifting group positions +len(extract(s, p));{s: 'john@example.com', p: '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'};1 +len(extract(s, p));{s: '12345', p: '^\\d{5}$'};1 +len(extract(s, p));{s: 'abc', p: '^[A-Z]+$'};0 +len(extract(s, p));{s: 'abc', p: '(?i)^[A-Z]+$'};1 +len(extract(s, p));{s: 'x', p: ''};1 +len(extract(s, p));{s: 'x', p: '(unclosed'};!error +len(extract(s, p));{s: 'x', p: null};!error +len(extract(s, p));{s: null, p: 'x'};!error +len(extract(s, p));{s: 'ab', p: 'a|b'};1 +filter(patterns, matches(s, #));{s: '123', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};['^\\d+$'] +filter(patterns, matches(s, #));{s: 'abc', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};['^[a-z]+$'] +filter(patterns, matches(s, #));{s: 'Abc', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};['^[A-Z]'] +filter(patterns, matches(s, #));{s: 'a b', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};['\\s'] +filter(patterns, matches(s, #));{s: '', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};[] +filter(patterns, matches(s, #));{s: 'A 1', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};['^[A-Z]', '\\s'] +map(patterns, matches(s, #));{s: '123', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};[true, false, false, false] +map(patterns, matches(s, #));{s: 'abc', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};[false, true, false, false] +map(patterns, matches(s, #));{s: 'A 1', patterns: ['^\\d+$', '^[a-z]+$', '^[A-Z]', '\\s']};[false, false, true, true] +# regex: over arrays via closures +filter(codes, matches(#, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$'));{codes: ['ABC-1234', 'xyz-0001', 'DEF-9999-XL']};['ABC-1234', 'DEF-9999-XL'] +filter(codes, matches(#, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$'));{codes: []};[] +filter(codes, matches(#, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$'));{codes: ['bad']};[] +filter(codes, matches(#, '^[A-Z]{3}-\d{4}(-[A-Z]{2})?$'));{codes: ['GHI-0000', null]};!error +map(codes, extract(#, '(\d{4})')[1] ?? '');{codes: ['ABC-1234', 'xyz-0001', 'DEF-9999-XL']};['1234', '0001', '9999'] +map(codes, extract(#, '(\d{4})')[1] ?? '');{codes: []};[] +map(codes, extract(#, '(\d{4})')[1] ?? '');{codes: ['bad']};[''] +map(codes, extract(#, '(\d{4})')[1] ?? '');{codes: ['GHI-0000', null]};!error +all(codes, matches(upper(#), '^[A-Z]{3}-'));{codes: ['ABC-1234', 'xyz-0001', 'DEF-9999-XL']};true +all(codes, matches(upper(#), '^[A-Z]{3}-'));{codes: []};true +all(codes, matches(upper(#), '^[A-Z]{3}-'));{codes: ['bad']};false +all(codes, matches(upper(#), '^[A-Z]{3}-'));{codes: ['GHI-0000', null]};!error +count(codes, matches(#, '-XL$'));{codes: ['ABC-1234', 'xyz-0001', 'DEF-9999-XL']};1 +count(codes, matches(#, '-XL$'));{codes: []};0 +count(codes, matches(#, '-XL$'));{codes: ['bad']};0 +count(codes, matches(#, '-XL$'));{codes: ['GHI-0000', null]};!error +map(codes, len(extract(#, '^([A-Z]+)-(\d+)')));{codes: ['ABC-1234', 'xyz-0001', 'DEF-9999-XL']};[3, 0, 3] +map(codes, len(extract(#, '^([A-Z]+)-(\d+)')));{codes: []};[] +map(codes, len(extract(#, '^([A-Z]+)-(\d+)')));{codes: ['bad']};[0] +map(codes, len(extract(#, '^([A-Z]+)-(\d+)')));{codes: ['GHI-0000', null]};!error diff --git a/core/expression/tests/spec/standard/15-05-fuzzy-long-unicode.csv b/core/expression/tests/spec/standard/15-05-fuzzy-long-unicode.csv new file mode 100644 index 00000000..eb79c86b --- /dev/null +++ b/core/expression/tests/spec/standard/15-05-fuzzy-long-unicode.csv @@ -0,0 +1,551 @@ +expression (string);input (json 5);output (json 5);note +# fuzzyMatch: typo-tolerant lookups +fuzzyMatch(lower(trim(s)), 'london');{s: 'london'};1 +fuzzyMatch(lower(trim(s)), 'london');{s: 'London'};1 +fuzzyMatch(lower(trim(s)), 'london');{s: ' londn '};0.833333333333333;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(trim(s)), 'london');{s: 'lodnon'};0.833333333333333;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(trim(s)), 'london');{s: 'Londres'};0.571428571428571;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(trim(s)), 'london');{s: 'paris'};0 +fuzzyMatch(lower(trim(s)), 'london');{s: ''};0 +fuzzyMatch(lower(trim(s)), 'london');{s: 'LONDON'};1 +fuzzyMatch(lower(trim(s)), 'london');{s: null};!error +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: 'london'};true +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: 'London'};true +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: ' londn '};true +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: 'lodnon'};true +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: 'Londres'};false +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: 'paris'};false +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: ''};false +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: 'LONDON'};true +fuzzyMatch(lower(trim(s)), 'london') >= 0.8;{s: null};!error +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: 'london'};true +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: 'London'};true +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: ' londn '};false +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: 'lodnon'};true +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: 'Londres'};false +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: 'paris'};false +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: ''};false +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: 'LONDON'};true +fuzzyMatch(s, 'london') >= 0.8 or lower(s) == 'london';{s: null};!error +fuzzyMatch(a, b);{a: 'Jonathan', b: 'Johnathan'};0.888888888888889;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(a, b);{a: 'Smith', b: 'Smyth'};0.8 +fuzzyMatch(a, b);{a: 'Catherine', b: 'Katherine'};0.888888888888889;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(a, b);{a: 'Mohammed', b: 'Muhammad'};0.75 +fuzzyMatch(a, b);{a: 'Anne', b: 'Ann'};0.75 +fuzzyMatch(a, b);{a: 'acme corp', b: 'acme corporation'};0.5625 +fuzzyMatch(a, b);{a: 'Müller', b: 'Mueller'};0.714285714285714;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(a, b);{a: 'Zoë', b: 'Zoe'};0.666666666666667;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(a, b);{a: 'abc', b: 'cba'};0.3333333333333334;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(a, b);{a: 'teh', b: 'the'};0.666666666666667;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(a, b);{a: '', b: 'x'};0 +fuzzyMatch(a, b);{a: 'same', b: 'same'};1 +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Jonathan', b: 'Johnathan'};true +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Smith', b: 'Smyth'};true +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Catherine', b: 'Katherine'};true +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Mohammed', b: 'Muhammad'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Anne', b: 'Ann'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'acme corp', b: 'acme corporation'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Müller', b: 'Mueller'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'Zoë', b: 'Zoe'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'abc', b: 'cba'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'teh', b: 'the'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: '', b: 'x'};false +fuzzyMatch(lower(a), lower(b)) > 0.75;{a: 'same', b: 'same'};true +round(fuzzyMatch(a, b), 2);{a: 'Jonathan', b: 'Johnathan'};0.89 +round(fuzzyMatch(a, b), 2);{a: 'Smith', b: 'Smyth'};0.8 +round(fuzzyMatch(a, b), 2);{a: 'Catherine', b: 'Katherine'};0.89 +round(fuzzyMatch(a, b), 2);{a: 'Mohammed', b: 'Muhammad'};0.75 +round(fuzzyMatch(a, b), 2);{a: 'Anne', b: 'Ann'};0.75 +round(fuzzyMatch(a, b), 2);{a: 'acme corp', b: 'acme corporation'};0.56 +round(fuzzyMatch(a, b), 2);{a: 'Müller', b: 'Mueller'};0.71 +round(fuzzyMatch(a, b), 2);{a: 'Zoë', b: 'Zoe'};0.67 +round(fuzzyMatch(a, b), 2);{a: 'abc', b: 'cba'};0.33 +round(fuzzyMatch(a, b), 2);{a: 'teh', b: 'the'};0.67 +round(fuzzyMatch(a, b), 2);{a: '', b: 'x'};0 +round(fuzzyMatch(a, b), 2);{a: 'same', b: 'same'};1 +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Jonathan', b: 'Johnathan'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Smith', b: 'Smyth'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Catherine', b: 'Katherine'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Mohammed', b: 'Muhammad'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Anne', b: 'Ann'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'acme corp', b: 'acme corporation'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Müller', b: 'Mueller'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'Zoë', b: 'Zoe'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'abc', b: 'cba'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'teh', b: 'the'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: '', b: 'x'};true +fuzzyMatch(a, b) == fuzzyMatch(b, a);{a: 'same', b: 'same'};true +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Jonathan', b: 'Johnathan'};'close' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Smith', b: 'Smyth'};'close' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Catherine', b: 'Katherine'};'close' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Mohammed', b: 'Muhammad'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Anne', b: 'Ann'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'acme corp', b: 'acme corporation'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Müller', b: 'Mueller'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'Zoë', b: 'Zoe'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'abc', b: 'cba'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'teh', b: 'the'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: '', b: 'x'};'different' +a == b ? 'exact' : fuzzyMatch(a, b) >= 0.8 ? 'close' : 'different';{a: 'same', b: 'same'};'exact' +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'londn'};[0.833333333333333, 0, 0.1666666666666666, 0.3333333333333334, 0];question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'Paris'};[0, 1, 0.3333333333333334, 0, 0.5];question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'berln'};[0.1666666666666666, 0.2, 0.833333333333333, 0.1666666666666666, 0.1666666666666666];question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'lisboa'};[0.3333333333333334, 0, 0, 0.833333333333333, 0];question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'rome'};[0.1666666666666666, 0, 0.1666666666666666, 0, 0];question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: ''};[0, 0, 0, 0, 0] +fuzzyMatch(cities, lower(q));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'madird'};[0, 0.3333333333333334, 0, 0, 0.833333333333333];question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'londn'};['london'] +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'Paris'};['paris'] +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'berln'};['berlin'] +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'lisboa'};['lisbon'] +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'rome'};[] +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: ''};[] +filter(cities, fuzzyMatch(#, lower(q)) > 0.7);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'madird'};['madrid'] +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'londn'};0.833333333333333;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'Paris'};1 +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'berln'};0.833333333333333;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'lisboa'};0.833333333333333;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'rome'};0.1666666666666666;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: ''};0 +max(fuzzyMatch(cities, lower(q)));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'madird'};0.833333333333333;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'londn'};'london' +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'Paris'};'paris' +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'berln'};'berlin' +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'lisboa'};'lisbon' +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'rome'};'london' +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: ''};'london' +filter(cities, fuzzyMatch(#, lower(q)) == max(fuzzyMatch(cities, lower(q))))[0];{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'madird'};'madrid' +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'londn'};[83, 0, 17, 33, 0] +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'Paris'};[0, 100, 33, 0, 50] +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'berln'};[17, 20, 83, 17, 17] +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'lisboa'};[33, 0, 0, 83, 0] +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'rome'};[17, 0, 17, 0, 0] +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: ''};[0, 0, 0, 0, 0] +map(cities, round(fuzzyMatch(#, lower(q)) * 100));{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'madird'};[0, 33, 0, 0, 83] +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'londn'};false +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'Paris'};true +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'berln'};false +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'lisboa'};false +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'rome'};false +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: ''};false +some(cities, fuzzyMatch(#, lower(q)) == 1);{cities: ['london', 'paris', 'berlin', 'lisbon', 'madrid'], q: 'madird'};false +# dictionary-like repeated values across rows +lower(tier) == 'gold';{tier: 'GOLD'};true +lower(tier) == 'gold';{tier: 'GOLD'};true +lower(tier) == 'gold';{tier: 'silver'};false +lower(tier) == 'gold';{tier: 'GOLD'};true +lower(tier) == 'gold';{tier: 'bronze'};false +lower(tier) == 'gold';{tier: 'silver'};false +lower(tier) == 'gold';{tier: 'GOLD'};true +lower(tier) == 'gold';{tier: 'GOLD'};true +lower(tier) == 'gold';{tier: 'Gold'};true +lower(tier) == 'gold';{tier: 'silver'};false +lower(tier) == 'gold';{tier: 'GOLD'};true +lower(tier) == 'gold';{tier: 'bronze'};false +tier == 'GOLD';{tier: 'GOLD'};true +tier == 'GOLD';{tier: 'GOLD'};true +tier == 'GOLD';{tier: 'silver'};false +tier == 'GOLD';{tier: 'GOLD'};true +tier == 'GOLD';{tier: 'bronze'};false +tier == 'GOLD';{tier: 'silver'};false +tier == 'GOLD';{tier: 'GOLD'};true +tier == 'GOLD';{tier: 'GOLD'};true +tier == 'GOLD';{tier: 'Gold'};false +tier == 'GOLD';{tier: 'silver'};false +tier == 'GOLD';{tier: 'GOLD'};true +tier == 'GOLD';{tier: 'bronze'};false +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'GOLD'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'GOLD'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'silver'};50 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'GOLD'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'bronze'};10 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'silver'};50 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'GOLD'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'GOLD'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'Gold'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'silver'};50 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'GOLD'};100 +lower(tier) == 'gold' ? 100 : lower(tier) == 'silver' ? 50 : 10;{tier: 'bronze'};10 +upper(tier) + '-' + lower(tier);{tier: 'GOLD'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'GOLD'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'silver'};'SILVER-silver' +upper(tier) + '-' + lower(tier);{tier: 'GOLD'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'bronze'};'BRONZE-bronze' +upper(tier) + '-' + lower(tier);{tier: 'silver'};'SILVER-silver' +upper(tier) + '-' + lower(tier);{tier: 'GOLD'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'GOLD'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'Gold'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'silver'};'SILVER-silver' +upper(tier) + '-' + lower(tier);{tier: 'GOLD'};'GOLD-gold' +upper(tier) + '-' + lower(tier);{tier: 'bronze'};'BRONZE-bronze' +tier in ['GOLD', 'silver'];{tier: 'GOLD'};true +tier in ['GOLD', 'silver'];{tier: 'GOLD'};true +tier in ['GOLD', 'silver'];{tier: 'silver'};true +tier in ['GOLD', 'silver'];{tier: 'GOLD'};true +tier in ['GOLD', 'silver'];{tier: 'bronze'};false +tier in ['GOLD', 'silver'];{tier: 'silver'};true +tier in ['GOLD', 'silver'];{tier: 'GOLD'};true +tier in ['GOLD', 'silver'];{tier: 'GOLD'};true +tier in ['GOLD', 'silver'];{tier: 'Gold'};false +tier in ['GOLD', 'silver'];{tier: 'silver'};true +tier in ['GOLD', 'silver'];{tier: 'GOLD'};true +tier in ['GOLD', 'silver'];{tier: 'bronze'};false +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +status == 'active' ? 'on' : 'off';{status: 'inactive'};'off' +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +status == 'active' ? 'on' : 'off';{status: null};'off' +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +status == 'active' ? 'on' : 'off';{status: 'inactive'};'off' +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +status == 'active' ? 'on' : 'off';{status: 'active'};'on' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'inactive'};'inactive:INACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: null};'unknown:UNKNOWN' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'inactive'};'inactive:INACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +`${status ?? 'unknown'}:${upper(status ?? 'unknown')}`;{status: 'active'};'active:ACTIVE' +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'US'};true +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'US'};true +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'DE'};false +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'US'};true +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'US'};true +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'DE'};false +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'FR'};false +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'US'};true +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'US'};true +contains(['US', 'CA'], country) and startsWith(country, 'U');{country: 'DE'};false +map(xs, lower(#));{xs: ['GOLD', 'GOLD', 'GOLD', 'SILVER', 'GOLD']};['gold', 'gold', 'gold', 'silver', 'gold'] +map(xs, lower(#));{xs: ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']};['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] +map(xs, lower(#));{xs: ['x', 'x']};['x', 'x'] +map(xs, lower(#));{xs: []};[] +count(xs, # == 'GOLD');{xs: ['GOLD', 'GOLD', 'GOLD', 'SILVER', 'GOLD']};4 +count(xs, # == 'GOLD');{xs: ['GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD', 'GOLD']};20 +count(xs, # == 'GOLD');{xs: ['gold', 'gold', 'gold', 'gold', 'gold']};0 +count(xs, # == 'GOLD');{xs: []};0 +# long strings +len(s);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};1620 +len(s);{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};2000 +len(s);{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};4096 +len(s);{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};2004 +len(s);{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};3089 +len(s);{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};1500;bug: len counts UTF-8 bytes, intended character count +len(s);{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};729 +len(upper(s)) == len(s);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};true +len(upper(s)) == len(s);{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};true +len(upper(s)) == len(s);{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};true +len(upper(s)) == len(s);{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};true +len(upper(s)) == len(s);{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};true +len(upper(s)) == len(s);{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};true +len(upper(s)) == len(s);{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};true +upper(s) == s;{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};false +upper(s) == s;{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};false +upper(s) == s;{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};false +upper(s) == s;{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};false +upper(s) == s;{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +upper(s) == s;{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +upper(s) == s;{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};false +lower(upper(s)) == lower(s);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};true +lower(upper(s)) == lower(s);{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};true +lower(upper(s)) == lower(s);{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};true +lower(upper(s)) == lower(s);{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};true +lower(upper(s)) == lower(s);{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};true +lower(upper(s)) == lower(s);{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};true +lower(upper(s)) == lower(s);{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};true +contains(s, 'sit amet lorem');{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};true +contains(s, 'sit amet lorem');{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};false +contains(s, 'sit amet lorem');{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};false +contains(s, 'sit amet lorem');{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};false +contains(s, 'sit amet lorem');{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +contains(s, 'sit amet lorem');{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +contains(s, 'sit amet lorem');{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};false +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};true +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};false +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};false +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};false +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +startsWith(s, 'lorem') and endsWith(trim(s), 'amet');{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};false +endsWith(s, 'y');{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};false +endsWith(s, 'y');{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};false +endsWith(s, 'y');{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};true +endsWith(s, 'y');{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};false +endsWith(s, 'y');{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +endsWith(s, 'y');{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +endsWith(s, 'y');{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};false +len(split(s, ' '));{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};301 +len(split(s, ' '));{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};1 +len(split(s, ' '));{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};1 +len(split(s, ' '));{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};405 +len(split(s, ' '));{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};1 +len(split(s, ' '));{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};1 +len(split(s, ' '));{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};122 +len(filter(split(s, ' '), # != ''));{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};300 +len(filter(split(s, ' '), # != ''));{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};1 +len(filter(split(s, ' '), # != ''));{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};1 +len(filter(split(s, ' '), # != ''));{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};400 +len(filter(split(s, ' '), # != ''));{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};1 +len(filter(split(s, ' '), # != ''));{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};1 +len(filter(split(s, ' '), # != ''));{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};121 +len(split(s, ','));{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};1 +len(split(s, ','));{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};1 +len(split(s, ','));{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};1 +len(split(s, ','));{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};1 +len(split(s, ','));{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};400 +len(split(s, ','));{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};1 +len(split(s, ','));{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};1 +split(s, ',')[399];{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};null +split(s, ',')[399];{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};null +split(s, ',')[399];{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};null +split(s, ',')[399];{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};null +split(s, ',')[399];{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};'item399' +split(s, ',')[399];{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};null +split(s, ',')[399];{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};null +matches(s, '^(ab)+$');{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};false +matches(s, '^(ab)+$');{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};true +matches(s, '^(ab)+$');{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};false +matches(s, '^(ab)+$');{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};false +matches(s, '^(ab)+$');{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +matches(s, '^(ab)+$');{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +matches(s, '^(ab)+$');{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};false +matches(s, '^x+y$');{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};false +matches(s, '^x+y$');{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};false +matches(s, '^x+y$');{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};true +matches(s, '^x+y$');{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};false +matches(s, '^x+y$');{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +matches(s, '^x+y$');{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +matches(s, '^x+y$');{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};false +extract(s, 'ID-(\d+)');{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};[] +extract(s, 'ID-(\d+)');{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};[] +extract(s, 'ID-(\d+)');{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};[] +extract(s, 'ID-(\d+)');{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};[] +extract(s, 'ID-(\d+)');{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};[] +extract(s, 'ID-(\d+)');{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};[] +extract(s, 'ID-(\d+)');{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};['ID-04242', '04242'] +len(trim(s)) < len(s);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};true +len(trim(s)) < len(s);{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};false +len(trim(s)) < len(s);{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};false +len(trim(s)) < len(s);{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};true +len(trim(s)) < len(s);{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};false +len(trim(s)) < len(s);{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};false +len(trim(s)) < len(s);{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};true +len(`${s}${s}`) == 2 * len(s);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet '};true +len(`${s}${s}`) == 2 * len(s);{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'};true +len(`${s}${s}`) == 2 * len(s);{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};true +len(`${s}${s}`) == 2 * len(s);{s: ' word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word '};true +len(`${s}${s}`) == 2 * len(s);{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};true +len(`${s}${s}`) == 2 * len(s);{s: 'ääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääääää'};true +len(`${s}${s}`) == 2 * len(s);{s: 'filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text filler text ID-04242 more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler more filler '};true +s == t;{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy', t: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy'};true +s == t;{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy', t: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz'};false +s == t;{s: 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab', t: 'ababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababa'};false +s == t;{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet ', t: 'LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET '};false +lower(s) == lower(t);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet ', t: 'LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET '};true +lower(s) == lower(t);{s: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy', t: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz'};false +count(split(s, ','), endsWith(#, '9'));{s: 'item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20,item21,item22,item23,item24,item25,item26,item27,item28,item29,item30,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40,item41,item42,item43,item44,item45,item46,item47,item48,item49,item50,item51,item52,item53,item54,item55,item56,item57,item58,item59,item60,item61,item62,item63,item64,item65,item66,item67,item68,item69,item70,item71,item72,item73,item74,item75,item76,item77,item78,item79,item80,item81,item82,item83,item84,item85,item86,item87,item88,item89,item90,item91,item92,item93,item94,item95,item96,item97,item98,item99,item100,item101,item102,item103,item104,item105,item106,item107,item108,item109,item110,item111,item112,item113,item114,item115,item116,item117,item118,item119,item120,item121,item122,item123,item124,item125,item126,item127,item128,item129,item130,item131,item132,item133,item134,item135,item136,item137,item138,item139,item140,item141,item142,item143,item144,item145,item146,item147,item148,item149,item150,item151,item152,item153,item154,item155,item156,item157,item158,item159,item160,item161,item162,item163,item164,item165,item166,item167,item168,item169,item170,item171,item172,item173,item174,item175,item176,item177,item178,item179,item180,item181,item182,item183,item184,item185,item186,item187,item188,item189,item190,item191,item192,item193,item194,item195,item196,item197,item198,item199,item200,item201,item202,item203,item204,item205,item206,item207,item208,item209,item210,item211,item212,item213,item214,item215,item216,item217,item218,item219,item220,item221,item222,item223,item224,item225,item226,item227,item228,item229,item230,item231,item232,item233,item234,item235,item236,item237,item238,item239,item240,item241,item242,item243,item244,item245,item246,item247,item248,item249,item250,item251,item252,item253,item254,item255,item256,item257,item258,item259,item260,item261,item262,item263,item264,item265,item266,item267,item268,item269,item270,item271,item272,item273,item274,item275,item276,item277,item278,item279,item280,item281,item282,item283,item284,item285,item286,item287,item288,item289,item290,item291,item292,item293,item294,item295,item296,item297,item298,item299,item300,item301,item302,item303,item304,item305,item306,item307,item308,item309,item310,item311,item312,item313,item314,item315,item316,item317,item318,item319,item320,item321,item322,item323,item324,item325,item326,item327,item328,item329,item330,item331,item332,item333,item334,item335,item336,item337,item338,item339,item340,item341,item342,item343,item344,item345,item346,item347,item348,item349,item350,item351,item352,item353,item354,item355,item356,item357,item358,item359,item360,item361,item362,item363,item364,item365,item366,item367,item368,item369,item370,item371,item372,item373,item374,item375,item376,item377,item378,item379,item380,item381,item382,item383,item384,item385,item386,item387,item388,item389,item390,item391,item392,item393,item394,item395,item396,item397,item398,item399'};40 +count(split(s, ','), endsWith(#, '9'));{s: 'a9,b,c9'};2 +count(split(s, ','), endsWith(#, '9'));{s: ''};0 +fuzzyMatch(s, t) > 0.99;{s: 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc', t: 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc'};true +fuzzyMatch(s, t) > 0.99;{s: 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc', t: 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabd'};true +fuzzyMatch(s, t) > 0.99;{s: 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc', t: 'xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz'};false +upper(s);{s: 'lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum '};'LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM DOLOR SIT AMET LOREM IPSUM ' +upper(s);{s: 'ßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßß'};'SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS' +trim(s);{s: ' core\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'};'core' +trim(s);{s: '\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000x'};'x' +# whitespace variety through pipelines +trim(s);{s: ' gold '};'gold' +trim(s);{s: '\u00a0gold'};'gold' +trim(s);{s: 'gold\u3000'};'gold' +trim(s);{s: '\u200bgold'};'\u200bgold' +trim(s);{s: 'gold\u000d\n'};'gold' +trim(s);{s: '\tgold\t'};'gold' +trim(s);{s: 'go ld'};'go ld' +trim(s);{s: '\ufeffgold'};'\ufeffgold';question: BOM is not Unicode White_Space so it is kept (JS trim removes it) +trim(s);{s: '\u2003gold\u2009'};'gold' +trim(s);{s: '\u0085gold'};'gold' +lower(trim(s)) == 'gold';{s: ' gold '};true +lower(trim(s)) == 'gold';{s: '\u00a0gold'};true +lower(trim(s)) == 'gold';{s: 'gold\u3000'};true +lower(trim(s)) == 'gold';{s: '\u200bgold'};false +lower(trim(s)) == 'gold';{s: 'gold\u000d\n'};true +lower(trim(s)) == 'gold';{s: '\tgold\t'};true +lower(trim(s)) == 'gold';{s: 'go ld'};false +lower(trim(s)) == 'gold';{s: '\ufeffgold'};false;question: BOM is not Unicode White_Space so it is kept (JS trim removes it) +lower(trim(s)) == 'gold';{s: '\u2003gold\u2009'};true +lower(trim(s)) == 'gold';{s: '\u0085gold'};true +len(filter(split(s, ' '), # != ''));{s: ' gold '};1 +len(filter(split(s, ' '), # != ''));{s: '\u00a0gold'};1 +len(filter(split(s, ' '), # != ''));{s: 'gold\u3000'};1 +len(filter(split(s, ' '), # != ''));{s: '\u200bgold'};1 +len(filter(split(s, ' '), # != ''));{s: 'gold\u000d\n'};1 +len(filter(split(s, ' '), # != ''));{s: '\tgold\t'};1 +len(filter(split(s, ' '), # != ''));{s: 'go ld'};2 +len(filter(split(s, ' '), # != ''));{s: '\ufeffgold'};1 +len(filter(split(s, ' '), # != ''));{s: '\u2003gold\u2009'};1 +len(filter(split(s, ' '), # != ''));{s: '\u0085gold'};1 +matches(s, '^\s*gold\s*$');{s: ' gold '};true +matches(s, '^\s*gold\s*$');{s: '\u00a0gold'};true +matches(s, '^\s*gold\s*$');{s: 'gold\u3000'};true +matches(s, '^\s*gold\s*$');{s: '\u200bgold'};false +matches(s, '^\s*gold\s*$');{s: 'gold\u000d\n'};true +matches(s, '^\s*gold\s*$');{s: '\tgold\t'};true +matches(s, '^\s*gold\s*$');{s: 'go ld'};false +matches(s, '^\s*gold\s*$');{s: '\ufeffgold'};false +matches(s, '^\s*gold\s*$');{s: '\u2003gold\u2009'};true +matches(s, '^\s*gold\s*$');{s: '\u0085gold'};true +matches(s, '^[ \t]*gold[ \t]*$');{s: ' gold '};true +matches(s, '^[ \t]*gold[ \t]*$');{s: '\u00a0gold'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: 'gold\u3000'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: '\u200bgold'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: 'gold\u000d\n'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: '\tgold\t'};true +matches(s, '^[ \t]*gold[ \t]*$');{s: 'go ld'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: '\ufeffgold'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: '\u2003gold\u2009'};false +matches(s, '^[ \t]*gold[ \t]*$');{s: '\u0085gold'};false +contains(s, 'gold');{s: ' gold '};true +contains(s, 'gold');{s: '\u00a0gold'};true +contains(s, 'gold');{s: 'gold\u3000'};true +contains(s, 'gold');{s: '\u200bgold'};true +contains(s, 'gold');{s: 'gold\u000d\n'};true +contains(s, 'gold');{s: '\tgold\t'};true +contains(s, 'gold');{s: 'go ld'};false +contains(s, 'gold');{s: '\ufeffgold'};true +contains(s, 'gold');{s: '\u2003gold\u2009'};true +contains(s, 'gold');{s: '\u0085gold'};true +fuzzyMatch(trim(s), 'gold');{s: ' gold '};1 +fuzzyMatch(trim(s), 'gold');{s: '\u00a0gold'};1 +fuzzyMatch(trim(s), 'gold');{s: 'gold\u3000'};1 +fuzzyMatch(trim(s), 'gold');{s: '\u200bgold'};0.8 +fuzzyMatch(trim(s), 'gold');{s: 'gold\u000d\n'};1 +fuzzyMatch(trim(s), 'gold');{s: '\tgold\t'};1 +fuzzyMatch(trim(s), 'gold');{s: 'go ld'};0.8 +fuzzyMatch(trim(s), 'gold');{s: '\ufeffgold'};0.8;question: BOM is not Unicode White_Space so it is kept (JS trim removes it) +fuzzyMatch(trim(s), 'gold');{s: '\u2003gold\u2009'};1 +fuzzyMatch(trim(s), 'gold');{s: '\u0085gold'};1 +# unicode variety through pipelines +upper(s);{s: 'straße'};'STRASSE' +upper(s);{s: 'İstanbul'};'İSTANBUL' +upper(s);{s: 'ΣΊΣΥΦΟΣ'};'ΣΊΣΥΦΟΣ' +upper(s);{s: 'Džemal'};'DŽEMAL' +upper(s);{s: 'finance'};'FINANCE' +upper(s);{s: 'café'};'CAFÉ' +upper(s);{s: 'café'};'CAFÉ' +upper(s);{s: '日本語テキスト'};'日本語テキスト' +upper(s);{s: 'مرحبا'};'مرحبا' +upper(s);{s: '😀 smile'};'😀 SMILE' +upper(s);{s: 'Ⅻ'};'Ⅻ' +upper(s);{s: 'ABC'};'ABC' +lower(s);{s: 'straße'};'straße' +lower(s);{s: 'İstanbul'};'i̇stanbul' +lower(s);{s: 'ΣΊΣΥΦΟΣ'};'σίσυφος' +lower(s);{s: 'Džemal'};'džemal' +lower(s);{s: 'finance'};'finance' +lower(s);{s: 'café'};'café' +lower(s);{s: 'café'};'café' +lower(s);{s: '日本語テキスト'};'日本語テキスト' +lower(s);{s: 'مرحبا'};'مرحبا' +lower(s);{s: '😀 smile'};'😀 smile' +lower(s);{s: 'Ⅻ'};'ⅻ' +lower(s);{s: 'ABC'};'abc' +upper(lower(s)) == upper(s);{s: 'straße'};true +upper(lower(s)) == upper(s);{s: 'İstanbul'};false +upper(lower(s)) == upper(s);{s: 'ΣΊΣΥΦΟΣ'};true +upper(lower(s)) == upper(s);{s: 'Džemal'};true +upper(lower(s)) == upper(s);{s: 'finance'};true +upper(lower(s)) == upper(s);{s: 'café'};true +upper(lower(s)) == upper(s);{s: 'café'};true +upper(lower(s)) == upper(s);{s: '日本語テキスト'};true +upper(lower(s)) == upper(s);{s: 'مرحبا'};true +upper(lower(s)) == upper(s);{s: '😀 smile'};true +upper(lower(s)) == upper(s);{s: 'Ⅻ'};true +upper(lower(s)) == upper(s);{s: 'ABC'};true +contains(lower(s), 'caf');{s: 'straße'};false +contains(lower(s), 'caf');{s: 'İstanbul'};false +contains(lower(s), 'caf');{s: 'ΣΊΣΥΦΟΣ'};false +contains(lower(s), 'caf');{s: 'Džemal'};false +contains(lower(s), 'caf');{s: 'finance'};false +contains(lower(s), 'caf');{s: 'café'};true +contains(lower(s), 'caf');{s: 'café'};true +contains(lower(s), 'caf');{s: '日本語テキスト'};false +contains(lower(s), 'caf');{s: 'مرحبا'};false +contains(lower(s), 'caf');{s: '😀 smile'};false +contains(lower(s), 'caf');{s: 'Ⅻ'};false +contains(lower(s), 'caf');{s: 'ABC'};false +lower(s) == 'café';{s: 'straße'};false +lower(s) == 'café';{s: 'İstanbul'};false +lower(s) == 'café';{s: 'ΣΊΣΥΦΟΣ'};false +lower(s) == 'café';{s: 'Džemal'};false +lower(s) == 'café';{s: 'finance'};false +lower(s) == 'café';{s: 'café'};true +lower(s) == 'café';{s: 'café'};false +lower(s) == 'café';{s: '日本語テキスト'};false +lower(s) == 'café';{s: 'مرحبا'};false +lower(s) == 'café';{s: '😀 smile'};false +lower(s) == 'café';{s: 'Ⅻ'};false +lower(s) == 'café';{s: 'ABC'};false +matches(s, '^\p{L}+$');{s: 'straße'};true +matches(s, '^\p{L}+$');{s: 'İstanbul'};true +matches(s, '^\p{L}+$');{s: 'ΣΊΣΥΦΟΣ'};true +matches(s, '^\p{L}+$');{s: 'Džemal'};true +matches(s, '^\p{L}+$');{s: 'finance'};true +matches(s, '^\p{L}+$');{s: 'café'};true +matches(s, '^\p{L}+$');{s: 'café'};false +matches(s, '^\p{L}+$');{s: '日本語テキスト'};true +matches(s, '^\p{L}+$');{s: 'مرحبا'};true +matches(s, '^\p{L}+$');{s: '😀 smile'};false +matches(s, '^\p{L}+$');{s: 'Ⅻ'};false +matches(s, '^\p{L}+$');{s: 'ABC'};true +matches(s, '(?i)^STRASSE$');{s: 'straße'};false +matches(s, '(?i)^STRASSE$');{s: 'İstanbul'};false +matches(s, '(?i)^STRASSE$');{s: 'ΣΊΣΥΦΟΣ'};false +matches(s, '(?i)^STRASSE$');{s: 'Džemal'};false +matches(s, '(?i)^STRASSE$');{s: 'finance'};false +matches(s, '(?i)^STRASSE$');{s: 'café'};false +matches(s, '(?i)^STRASSE$');{s: 'café'};false +matches(s, '(?i)^STRASSE$');{s: '日本語テキスト'};false +matches(s, '(?i)^STRASSE$');{s: 'مرحبا'};false +matches(s, '(?i)^STRASSE$');{s: '😀 smile'};false +matches(s, '(?i)^STRASSE$');{s: 'Ⅻ'};false +matches(s, '(?i)^STRASSE$');{s: 'ABC'};false +fuzzyMatch(lower(s), 'cafe');{s: 'straße'};0.3333333333333334;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(s), 'cafe');{s: 'İstanbul'};0.1111111111111112;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(s), 'cafe');{s: 'ΣΊΣΥΦΟΣ'};0 +fuzzyMatch(lower(s), 'cafe');{s: 'Džemal'};0 +fuzzyMatch(lower(s), 'cafe');{s: 'finance'};0.3333333333333334;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(s), 'cafe');{s: 'café'};0.75 +fuzzyMatch(lower(s), 'cafe');{s: 'café'};0.8 +fuzzyMatch(lower(s), 'cafe');{s: '日本語テキスト'};0 +fuzzyMatch(lower(s), 'cafe');{s: 'مرحبا'};0 +fuzzyMatch(lower(s), 'cafe');{s: '😀 smile'};0.1428571428571429;question: score is an f64 converted with uneven precision (1/3 -> 0.3333333333333334 but 5/6 -> 0.833333333333333), not an exact decimal +fuzzyMatch(lower(s), 'cafe');{s: 'Ⅻ'};0 +fuzzyMatch(lower(s), 'cafe');{s: 'ABC'};0 +`${upper(s)}|${lower(s)}`;{s: 'straße'};'STRASSE|straße' +`${upper(s)}|${lower(s)}`;{s: 'İstanbul'};'İSTANBUL|i̇stanbul' +`${upper(s)}|${lower(s)}`;{s: 'ΣΊΣΥΦΟΣ'};'ΣΊΣΥΦΟΣ|σίσυφος' +`${upper(s)}|${lower(s)}`;{s: 'Džemal'};'DŽEMAL|džemal' +`${upper(s)}|${lower(s)}`;{s: 'finance'};'FINANCE|finance' +`${upper(s)}|${lower(s)}`;{s: 'café'};'CAFÉ|café' +`${upper(s)}|${lower(s)}`;{s: 'café'};'CAFÉ|café' +`${upper(s)}|${lower(s)}`;{s: '日本語テキスト'};'日本語テキスト|日本語テキスト' +`${upper(s)}|${lower(s)}`;{s: 'مرحبا'};'مرحبا|مرحبا' +`${upper(s)}|${lower(s)}`;{s: '😀 smile'};'😀 SMILE|😀 smile' +`${upper(s)}|${lower(s)}`;{s: 'Ⅻ'};'Ⅻ|ⅻ' +`${upper(s)}|${lower(s)}`;{s: 'ABC'};'ABC|abc' +split(s, ' ');{s: 'straße'};['straße'] +split(s, ' ');{s: 'İstanbul'};['İstanbul'] +split(s, ' ');{s: 'ΣΊΣΥΦΟΣ'};['ΣΊΣΥΦΟΣ'] +split(s, ' ');{s: 'Džemal'};['Džemal'] +split(s, ' ');{s: 'finance'};['finance'] +split(s, ' ');{s: 'café'};['café'] +split(s, ' ');{s: 'café'};['café'] +split(s, ' ');{s: '日本語テキスト'};['日本語テキスト'] +split(s, ' ');{s: 'مرحبا'};['مرحبا'] +split(s, ' ');{s: '😀 smile'};['😀', 'smile'] +split(s, ' ');{s: 'Ⅻ'};['Ⅻ'] +split(s, ' ');{s: 'ABC'};['ABC'] diff --git a/core/expression/tests/spec/standard/16-01-add-sub-matrix.csv b/core/expression/tests/spec/standard/16-01-add-sub-matrix.csv new file mode 100644 index 00000000..de037258 --- /dev/null +++ b/core/expression/tests/spec/standard/16-01-add-sub-matrix.csv @@ -0,0 +1,498 @@ +expression (string);input (json 5);output (json 5);note +# add/sub matrix in UTC (default zone) +d(s).add(45, 's');{s: '2024-01-31 10:20:30'};'2024-01-31T10:21:15Z' +d(s).add(45, 's');{s: '2024-02-29 23:59:59'};'2024-03-01T00:00:44Z' +d(s).add(45, 's');{s: '2023-12-31 23:30:15'};'2023-12-31T23:31:00Z' +d(s).add(45, 's');{s: '2024-03-31'};'2024-03-31T00:00:45Z' +d(s).add(45, 's');{s: '2025-06-30 12:00'};'2025-06-30T12:00:45Z' +d(s).add(45, 's');{s: null};'Invalid date' +d(s).sub(3601, 'seconds');{s: '2025-03-17'};'2025-03-16T22:59:59Z' +d(s).sub(3601, 'seconds');{s: '2024-05-31 06:07:08'};'2024-05-31T05:07:07Z' +d(s).sub(3601, 'seconds');{s: '2025-08-31 18:00'};'2025-08-31T16:59:59Z' +d(s).sub(3601, 'seconds');{s: '2023-02-28 00:00:01'};'2023-02-27T23:00:00Z' +d(s).sub(3601, 'seconds');{s: '2024-12-30 00:00:00'};'2024-12-29T22:59:59Z' +d(s).sub(3601, 'seconds');{};'Invalid date' +d(s).add(90, 'm');{s: '2024-07-31 13:14:15'};'2024-07-31T14:44:15Z' +d(s).add(90, 'm');{s: '2025-01-01'};'2025-01-01T01:30:00Z' +d(s).add(90, 'm');{s: '2024-09-30 21:45'};'2024-09-30T23:15:00Z' +d(s).add(90, 'm');{s: '2024-01-31 10:20:30'};'2024-01-31T11:50:30Z' +d(s).add(90, 'm');{s: '2024-02-29 23:59:59'};'2024-03-01T01:29:59Z' +d(s).add(90, 'm');{s: 'nope'};'Invalid date' +d(s).sub(1, 'minute');{s: '2024-03-31'};'2024-03-30T23:59:00Z' +d(s).sub(1, 'minute');{s: '2025-06-30 12:00'};'2025-06-30T11:59:00Z' +d(s).sub(1, 'minute');{s: '2025-03-16 08:45:00'};'2025-03-16T08:44:00Z' +d(s).sub(1, 'minute');{s: '2025-03-17'};'2025-03-16T23:59:00Z' +d(s).sub(1, 'minute');{s: '2024-05-31 06:07:08'};'2024-05-31T06:06:08Z' +d(s).sub(1, 'minute');{s: 1700000000123};'2023-11-14T22:12:20Z' +d(s).add(25, 'h');{s: '2023-02-28 00:00:01'};'2023-03-01T01:00:01Z' +d(s).add(25, 'h');{s: '2024-12-30 00:00:00'};'2024-12-31T01:00:00Z' +d(s).add(25, 'h');{s: '2025-11-30 23:59:59'};'2025-12-02T00:59:59Z' +d(s).add(25, 'h');{s: '2024-07-31 13:14:15'};'2024-08-01T14:14:15Z' +d(s).add(25, 'h');{s: '2025-01-01'};'2025-01-02T01:00:00Z' +d(s).add(25, 'h');{s: true};'Invalid date' +d(s).sub(1, 'hour');{s: '2024-01-31 10:20:30'};'2024-01-31T09:20:30Z' +d(s).sub(1, 'hour');{s: '2024-02-29 23:59:59'};'2024-02-29T22:59:59Z' +d(s).sub(1, 'hour');{s: '2023-12-31 23:30:15'};'2023-12-31T22:30:15Z' +d(s).sub(1, 'hour');{s: '2024-03-31'};'2024-03-30T23:00:00Z' +d(s).sub(1, 'hour');{s: '2025-06-30 12:00'};'2025-06-30T11:00:00Z' +d(s).sub(1, 'hour');{s: '2023-02-30'};'Invalid date' +d(s).add(1, 'd');{s: '2025-03-17'};'2025-03-18T00:00:00Z' +d(s).add(1, 'd');{s: '2024-05-31 06:07:08'};'2024-06-01T06:07:08Z' +d(s).add(1, 'd');{s: '2025-08-31 18:00'};'2025-09-01T18:00:00Z' +d(s).add(1, 'd');{s: '2023-02-28 00:00:01'};'2023-03-01T00:00:01Z' +d(s).add(1, 'd');{s: '2024-12-30 00:00:00'};'2024-12-31T00:00:00Z' +d(s).add(1, 'd');{s: 1735689599999};'2025-01-01T23:59:59Z' +d(s).sub(31, 'days');{s: '2024-07-31 13:14:15'};'2024-06-30T13:14:15Z' +d(s).sub(31, 'days');{s: '2025-01-01'};'2024-12-01T00:00:00Z' +d(s).sub(31, 'days');{s: '2024-09-30 21:45'};'2024-08-30T21:45:00Z' +d(s).sub(31, 'days');{s: '2024-01-31 10:20:30'};'2023-12-31T10:20:30Z' +d(s).sub(31, 'days');{s: '2024-02-29 23:59:59'};'2024-01-29T23:59:59Z' +d(s).sub(31, 'days');{s: ''};'Invalid date' +d(s).add(1, 'w');{s: '2024-03-31'};'2024-04-07T00:00:00Z' +d(s).add(1, 'w');{s: '2025-06-30 12:00'};'2025-07-07T12:00:00Z' +d(s).add(1, 'w');{s: '2025-03-16 08:45:00'};'2025-03-23T08:45:00Z' +d(s).add(1, 'w');{s: '2025-03-17'};'2025-03-24T00:00:00Z' +d(s).add(1, 'w');{s: '2024-05-31 06:07:08'};'2024-06-07T06:07:08Z' +d(s).add(1, 'w');{s: null};'Invalid date' +d(s).sub(2, 'weeks');{s: '2023-02-28 00:00:01'};'2023-02-14T00:00:01Z' +d(s).sub(2, 'weeks');{s: '2024-12-30 00:00:00'};'2024-12-16T00:00:00Z' +d(s).sub(2, 'weeks');{s: '2025-11-30 23:59:59'};'2025-11-16T23:59:59Z' +d(s).sub(2, 'weeks');{s: '2024-07-31 13:14:15'};'2024-07-17T13:14:15Z' +d(s).sub(2, 'weeks');{s: '2025-01-01'};'2024-12-18T00:00:00Z' +d(s).sub(2, 'weeks');{};'Invalid date' +d(s).add(1, 'M');{s: '2024-01-31 10:20:30'};'2024-02-29T10:20:30Z' +d(s).add(1, 'M');{s: '2024-02-29 23:59:59'};'2024-03-29T23:59:59Z' +d(s).add(1, 'M');{s: '2023-12-31 23:30:15'};'2024-01-31T23:30:15Z' +d(s).add(1, 'M');{s: '2024-03-31'};'2024-04-30T00:00:00Z' +d(s).add(1, 'M');{s: '2025-06-30 12:00'};'2025-07-30T12:00:00Z' +d(s).add(1, 'M');{s: 'nope'};'Invalid date' +d(s).sub(1, 'month');{s: '2025-03-17'};'2025-02-17T00:00:00Z' +d(s).sub(1, 'month');{s: '2024-05-31 06:07:08'};'2024-04-30T06:07:08Z' +d(s).sub(1, 'month');{s: '2025-08-31 18:00'};'2025-07-31T18:00:00Z' +d(s).sub(1, 'month');{s: '2023-02-28 00:00:01'};'2023-01-28T00:00:01Z' +d(s).sub(1, 'month');{s: '2024-12-30 00:00:00'};'2024-11-30T00:00:00Z' +d(s).sub(1, 'month');{s: 1700000000123};'2023-10-14T22:13:20Z' +d(s).add(1, 'q');{s: '2024-07-31 13:14:15'};'2024-10-31T13:14:15Z' +d(s).add(1, 'q');{s: '2025-01-01'};'2025-04-01T00:00:00Z' +d(s).add(1, 'q');{s: '2024-09-30 21:45'};'2024-12-30T21:45:00Z' +d(s).add(1, 'q');{s: '2024-01-31 10:20:30'};'2024-04-30T10:20:30Z' +d(s).add(1, 'q');{s: '2024-02-29 23:59:59'};'2024-05-29T23:59:59Z' +d(s).add(1, 'q');{s: true};'Invalid date' +d(s).sub(1, 'quarter');{s: '2024-03-31'};'2023-12-31T00:00:00Z' +d(s).sub(1, 'quarter');{s: '2025-06-30 12:00'};'2025-03-30T12:00:00Z' +d(s).sub(1, 'quarter');{s: '2025-03-16 08:45:00'};'2024-12-16T08:45:00Z' +d(s).sub(1, 'quarter');{s: '2025-03-17'};'2024-12-17T00:00:00Z' +d(s).sub(1, 'quarter');{s: '2024-05-31 06:07:08'};'2024-02-29T06:07:08Z' +d(s).sub(1, 'quarter');{s: '2023-02-30'};'Invalid date' +d(s).add(1, 'y');{s: '2023-02-28 00:00:01'};'2024-02-28T00:00:01Z' +d(s).add(1, 'y');{s: '2024-12-30 00:00:00'};'2025-12-30T00:00:00Z' +d(s).add(1, 'y');{s: '2025-11-30 23:59:59'};'2026-11-30T23:59:59Z' +d(s).add(1, 'y');{s: '2024-07-31 13:14:15'};'2025-07-31T13:14:15Z' +d(s).add(1, 'y');{s: '2025-01-01'};'2026-01-01T00:00:00Z' +d(s).add(1, 'y');{s: 1735689599999};'2025-12-31T23:59:59Z' +d(s).sub(4, 'years');{s: '2024-01-31 10:20:30'};'2020-01-31T10:20:30Z' +d(s).sub(4, 'years');{s: '2024-02-29 23:59:59'};'2020-02-29T23:59:59Z' +d(s).sub(4, 'years');{s: '2023-12-31 23:30:15'};'2019-12-31T23:30:15Z' +d(s).sub(4, 'years');{s: '2024-03-31'};'2020-03-31T00:00:00Z' +d(s).sub(4, 'years');{s: '2025-06-30 12:00'};'2021-06-30T12:00:00Z' +d(s).sub(4, 'years');{s: ''};'Invalid date' +d(s).add(13, 'M');{s: '2025-03-17'};'2026-04-17T00:00:00Z' +d(s).add(13, 'M');{s: '2024-05-31 06:07:08'};'2025-06-30T06:07:08Z' +d(s).add(13, 'M');{s: '2025-08-31 18:00'};'2026-09-30T18:00:00Z' +d(s).add(13, 'M');{s: '2023-02-28 00:00:01'};'2024-03-28T00:00:01Z' +d(s).add(13, 'M');{s: '2024-12-30 00:00:00'};'2026-01-30T00:00:00Z' +d(s).add(13, 'M');{s: null};'Invalid date' +d(s).add(-1, 'd');{s: '2024-07-31 13:14:15'};'2024-07-30T13:14:15Z' +d(s).add(-1, 'd');{s: '2025-01-01'};'2024-12-31T00:00:00Z' +d(s).add(-1, 'd');{s: '2024-09-30 21:45'};'2024-09-29T21:45:00Z' +d(s).add(-1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-30T10:20:30Z' +d(s).add(-1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-28T23:59:59Z' +d(s).add(-1, 'd');{};'Invalid date' +# add/sub matrix in Etc/GMT+5 +d(s, 'Etc/GMT+5').add(59, 's');{s: '2024-03-31'};'2024-03-31T00:00:59-05:00' +d(s, 'Etc/GMT+5').add(59, 's');{s: '2025-06-30 12:00'};'2025-06-30T12:00:59-05:00' +d(s, 'Etc/GMT+5').add(59, 's');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:59-05:00' +d(s, 'Etc/GMT+5').add(59, 's');{s: '2025-03-17'};'2025-03-17T00:00:59-05:00' +d(s, 'Etc/GMT+5').add(59, 's');{s: '2024-05-31 06:07:08'};'2024-05-31T06:08:07-05:00' +d(s, 'Etc/GMT+5').add(59, 's');{s: 'nope'};'Invalid date' +d(s, 'Etc/GMT+5').sub(86400, 's');{s: '2023-02-28 00:00:01'};'2023-02-27T00:00:01-05:00' +d(s, 'Etc/GMT+5').sub(86400, 's');{s: '2024-12-30 00:00:00'};'2024-12-29T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(86400, 's');{s: '2025-11-30 23:59:59'};'2025-11-29T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(86400, 's');{s: '2024-07-31 13:14:15'};'2024-07-30T13:14:15-05:00' +d(s, 'Etc/GMT+5').sub(86400, 's');{s: '2025-01-01'};'2024-12-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(86400, 's');{s: 1700000000123};'2023-11-13T17:13:20-05:00' +d(s, 'Etc/GMT+5').add(1440, 'm');{s: '2024-01-31 10:20:30'};'2024-02-01T10:20:30-05:00' +d(s, 'Etc/GMT+5').add(1440, 'm');{s: '2024-02-29 23:59:59'};'2024-03-01T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1440, 'm');{s: '2023-12-31 23:30:15'};'2024-01-01T23:30:15-05:00' +d(s, 'Etc/GMT+5').add(1440, 'm');{s: '2024-03-31'};'2024-04-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1440, 'm');{s: '2025-06-30 12:00'};'2025-07-01T12:00:00-05:00' +d(s, 'Etc/GMT+5').add(1440, 'm');{s: true};'Invalid date' +d(s, 'Etc/GMT+5').sub(30, 'm');{s: '2025-03-17'};'2025-03-16T23:30:00-05:00' +d(s, 'Etc/GMT+5').sub(30, 'm');{s: '2024-05-31 06:07:08'};'2024-05-31T05:37:08-05:00' +d(s, 'Etc/GMT+5').sub(30, 'm');{s: '2025-08-31 18:00'};'2025-08-31T17:30:00-05:00' +d(s, 'Etc/GMT+5').sub(30, 'm');{s: '2023-02-28 00:00:01'};'2023-02-27T23:30:01-05:00' +d(s, 'Etc/GMT+5').sub(30, 'm');{s: '2024-12-30 00:00:00'};'2024-12-29T23:30:00-05:00' +d(s, 'Etc/GMT+5').sub(30, 'm');{s: '2023-02-30'};'Invalid date' +d(s, 'Etc/GMT+5').add(5, 'h');{s: '2024-07-31 13:14:15'};'2024-07-31T18:14:15-05:00' +d(s, 'Etc/GMT+5').add(5, 'h');{s: '2025-01-01'};'2025-01-01T05:00:00-05:00' +d(s, 'Etc/GMT+5').add(5, 'h');{s: '2024-09-30 21:45'};'2024-10-01T02:45:00-05:00' +d(s, 'Etc/GMT+5').add(5, 'h');{s: '2024-01-31 10:20:30'};'2024-01-31T15:20:30-05:00' +d(s, 'Etc/GMT+5').add(5, 'h');{s: '2024-02-29 23:59:59'};'2024-03-01T04:59:59-05:00' +d(s, 'Etc/GMT+5').add(5, 'h');{s: 1735689599999};'2024-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(24, 'h');{s: '2024-03-31'};'2024-03-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(24, 'h');{s: '2025-06-30 12:00'};'2025-06-29T12:00:00-05:00' +d(s, 'Etc/GMT+5').sub(24, 'h');{s: '2025-03-16 08:45:00'};'2025-03-15T08:45:00-05:00' +d(s, 'Etc/GMT+5').sub(24, 'h');{s: '2025-03-17'};'2025-03-16T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(24, 'h');{s: '2024-05-31 06:07:08'};'2024-05-30T06:07:08-05:00' +d(s, 'Etc/GMT+5').sub(24, 'h');{s: ''};'Invalid date' +d(s, 'Etc/GMT+5').add(1, 'day');{s: '2023-02-28 00:00:01'};'2023-03-01T00:00:01-05:00' +d(s, 'Etc/GMT+5').add(1, 'day');{s: '2024-12-30 00:00:00'};'2024-12-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'day');{s: '2025-11-30 23:59:59'};'2025-12-01T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1, 'day');{s: '2024-07-31 13:14:15'};'2024-08-01T13:14:15-05:00' +d(s, 'Etc/GMT+5').add(1, 'day');{s: '2025-01-01'};'2025-01-02T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'day');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').sub(1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-30T10:20:30-05:00' +d(s, 'Etc/GMT+5').sub(1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-28T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(1, 'd');{s: '2023-12-31 23:30:15'};'2023-12-30T23:30:15-05:00' +d(s, 'Etc/GMT+5').sub(1, 'd');{s: '2024-03-31'};'2024-03-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'd');{s: '2025-06-30 12:00'};'2025-06-29T12:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'd');{};'Invalid date' +d(s, 'Etc/GMT+5').add(1, 'week');{s: '2025-03-17'};'2025-03-24T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'week');{s: '2024-05-31 06:07:08'};'2024-06-07T06:07:08-05:00' +d(s, 'Etc/GMT+5').add(1, 'week');{s: '2025-08-31 18:00'};'2025-09-07T18:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'week');{s: '2023-02-28 00:00:01'};'2023-03-07T00:00:01-05:00' +d(s, 'Etc/GMT+5').add(1, 'week');{s: '2024-12-30 00:00:00'};'2025-01-06T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'week');{s: 'nope'};'Invalid date' +d(s, 'Etc/GMT+5').sub(1, 'w');{s: '2024-07-31 13:14:15'};'2024-07-24T13:14:15-05:00' +d(s, 'Etc/GMT+5').sub(1, 'w');{s: '2025-01-01'};'2024-12-25T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'w');{s: '2024-09-30 21:45'};'2024-09-23T21:45:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'w');{s: '2024-01-31 10:20:30'};'2024-01-24T10:20:30-05:00' +d(s, 'Etc/GMT+5').sub(1, 'w');{s: '2024-02-29 23:59:59'};'2024-02-22T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(1, 'w');{s: 1700000000123};'2023-11-07T17:13:20-05:00' +d(s, 'Etc/GMT+5').add(1, 'month');{s: '2024-03-31'};'2024-04-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'month');{s: '2025-06-30 12:00'};'2025-07-30T12:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'month');{s: '2025-03-16 08:45:00'};'2025-04-16T08:45:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'month');{s: '2025-03-17'};'2025-04-17T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'month');{s: '2024-05-31 06:07:08'};'2024-06-30T06:07:08-05:00' +d(s, 'Etc/GMT+5').add(1, 'month');{s: true};'Invalid date' +d(s, 'Etc/GMT+5').sub(12, 'M');{s: '2023-02-28 00:00:01'};'2022-02-28T00:00:01-05:00' +d(s, 'Etc/GMT+5').sub(12, 'M');{s: '2024-12-30 00:00:00'};'2023-12-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(12, 'M');{s: '2025-11-30 23:59:59'};'2024-11-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(12, 'M');{s: '2024-07-31 13:14:15'};'2023-07-31T13:14:15-05:00' +d(s, 'Etc/GMT+5').sub(12, 'M');{s: '2025-01-01'};'2024-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(12, 'M');{s: '2023-02-30'};'Invalid date' +d(s, 'Etc/GMT+5').add(2, 'q');{s: '2024-01-31 10:20:30'};'2024-07-31T10:20:30-05:00' +d(s, 'Etc/GMT+5').add(2, 'q');{s: '2024-02-29 23:59:59'};'2024-08-29T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(2, 'q');{s: '2023-12-31 23:30:15'};'2024-06-30T23:30:15-05:00' +d(s, 'Etc/GMT+5').add(2, 'q');{s: '2024-03-31'};'2024-09-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(2, 'q');{s: '2025-06-30 12:00'};'2025-12-30T12:00:00-05:00' +d(s, 'Etc/GMT+5').add(2, 'q');{s: 1735689599999};'2025-06-30T18:59:59-05:00' +d(s, 'Etc/GMT+5').sub(1, 'qtr');{s: '2025-03-17'};'2024-12-17T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'qtr');{s: '2024-05-31 06:07:08'};'2024-02-29T06:07:08-05:00' +d(s, 'Etc/GMT+5').sub(1, 'qtr');{s: '2025-08-31 18:00'};'2025-05-31T18:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'qtr');{s: '2023-02-28 00:00:01'};'2022-11-28T00:00:01-05:00' +d(s, 'Etc/GMT+5').sub(1, 'qtr');{s: '2024-12-30 00:00:00'};'2024-09-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'qtr');{s: ''};'Invalid date' +d(s, 'Etc/GMT+5').add(1, 'year');{s: '2024-07-31 13:14:15'};'2025-07-31T13:14:15-05:00' +d(s, 'Etc/GMT+5').add(1, 'year');{s: '2025-01-01'};'2026-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'year');{s: '2024-09-30 21:45'};'2025-09-30T21:45:00-05:00' +d(s, 'Etc/GMT+5').add(1, 'year');{s: '2024-01-31 10:20:30'};'2025-01-31T10:20:30-05:00' +d(s, 'Etc/GMT+5').add(1, 'year');{s: '2024-02-29 23:59:59'};'2025-02-28T23:59:59-05:00';bug: adding a year to Feb 29 gives an invalid date instead of clamping to Feb 28 like months do +d(s, 'Etc/GMT+5').add(1, 'year');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').sub(1, 'y');{s: '2024-03-31'};'2023-03-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'y');{s: '2025-06-30 12:00'};'2024-06-30T12:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'y');{s: '2025-03-16 08:45:00'};'2024-03-16T08:45:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'y');{s: '2025-03-17'};'2024-03-17T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'y');{s: '2024-05-31 06:07:08'};'2023-05-31T06:07:08-05:00' +d(s, 'Etc/GMT+5').sub(1, 'y');{};'Invalid date' +# add/sub matrix in Europe/Berlin +d(s, 'Europe/Berlin').add(1, 's');{s: '2025-03-30 01:30'};'2025-03-30T01:30:01+01:00' +d(s, 'Europe/Berlin').add(1, 's');{s: '2025-10-27 00:30'};'2025-10-27T00:30:01+01:00' +d(s, 'Europe/Berlin').add(1, 's');{s: '2025-10-26 12:00'};'2025-10-26T12:00:01+01:00' +d(s, 'Europe/Berlin').add(1, 's');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:02+01:00' +d(s, 'Europe/Berlin').add(1, 's');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:01+01:00' +d(s, 'Europe/Berlin').add(1, 's');{s: 'nope'};'Invalid date' +d(s, 'Europe/Berlin').sub(1, 's');{s: '2025-10-27 00:30'};'2025-10-27T00:29:59+01:00' +d(s, 'Europe/Berlin').sub(1, 's');{s: '2025-10-26 12:00'};'2025-10-26T11:59:59+01:00' +d(s, 'Europe/Berlin').sub(1, 's');{s: '2025-10-26 04:00'};'2025-10-26T03:59:59+01:00' +d(s, 'Europe/Berlin').sub(1, 's');{s: '2024-07-31 13:14:15'};'2024-07-31T13:14:14+02:00' +d(s, 'Europe/Berlin').sub(1, 's');{s: '2025-01-01'};'2024-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').sub(1, 's');{s: 1700000000123};'2023-11-14T23:13:19+01:00' +d(s, 'Europe/Berlin').add(60, 'm');{s: '2025-10-26 12:00'};'2025-10-26T13:00:00+01:00' +d(s, 'Europe/Berlin').add(60, 'm');{s: '2025-10-26 04:00'};'2025-10-26T05:00:00+01:00' +d(s, 'Europe/Berlin').add(60, 'm');{s: '2025-03-30 12:00'};'2025-03-30T13:00:00+02:00' +d(s, 'Europe/Berlin').add(60, 'm');{s: '2024-01-31 10:20:30'};'2024-01-31T11:20:30+01:00' +d(s, 'Europe/Berlin').add(60, 'm');{s: '2024-02-29 23:59:59'};'2024-03-01T00:59:59+01:00' +d(s, 'Europe/Berlin').add(60, 'm');{s: true};'Invalid date' +d(s, 'Europe/Berlin').sub(45, 'm');{s: '2025-10-26 04:00'};'2025-10-26T03:15:00+01:00' +d(s, 'Europe/Berlin').sub(45, 'm');{s: '2025-03-30 12:00'};'2025-03-30T11:15:00+02:00' +d(s, 'Europe/Berlin').sub(45, 'm');{s: '2025-10-25 23:30'};'2025-10-25T22:45:00+02:00' +d(s, 'Europe/Berlin').sub(45, 'm');{s: '2024-03-31'};'2024-03-30T23:15:00+01:00' +d(s, 'Europe/Berlin').sub(45, 'm');{s: '2025-06-30 12:00'};'2025-06-30T11:15:00+02:00' +d(s, 'Europe/Berlin').sub(45, 'm');{s: '2023-02-30'};'Invalid date' +d(s, 'Europe/Berlin').add(1, 'h');{s: '2025-03-30 12:00'};'2025-03-30T13:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'h');{s: '2025-10-25 23:30'};'2025-10-26T00:30:00+02:00' +d(s, 'Europe/Berlin').add(1, 'h');{s: '2025-03-30 03:00'};'2025-03-30T04:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'h');{s: '2025-03-17'};'2025-03-17T01:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'h');{s: '2024-05-31 06:07:08'};'2024-05-31T07:07:08+02:00' +d(s, 'Europe/Berlin').add(1, 'h');{s: 1735689599999};'2025-01-01T01:59:59+01:00' +d(s, 'Europe/Berlin').sub(3, 'h');{s: '2025-10-25 23:30'};'2025-10-25T20:30:00+02:00' +d(s, 'Europe/Berlin').sub(3, 'h');{s: '2025-03-30 03:00'};'2025-03-29T23:00:00+01:00' +d(s, 'Europe/Berlin').sub(3, 'h');{s: '2025-03-29 12:00'};'2025-03-29T09:00:00+01:00' +d(s, 'Europe/Berlin').sub(3, 'h');{s: '2023-02-28 00:00:01'};'2023-02-27T21:00:01+01:00' +d(s, 'Europe/Berlin').sub(3, 'h');{s: '2024-12-30 00:00:00'};'2024-12-29T21:00:00+01:00' +d(s, 'Europe/Berlin').sub(3, 'h');{s: ''};'Invalid date' +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-03-30 03:00'};'2025-03-31T03:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-03-29 12:00'};'2025-03-30T13:00:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-03-30 01:30'};'2025-03-31T02:30:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').add(1, 'd');{s: '2024-07-31 13:14:15'};'2024-08-01T13:14:15+02:00' +d(s, 'Europe/Berlin').add(1, 'd');{s: '2025-01-01'};'2025-01-02T00:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'd');{s: null};'Invalid date' +d(s, 'Europe/Berlin').sub(1, 'd');{s: '2025-03-29 12:00'};'2025-03-28T12:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'd');{s: '2025-03-30 01:30'};'2025-03-29T01:30:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'd');{s: '2025-10-27 00:30'};'2025-10-26T01:30:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').sub(1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-30T10:20:30+01:00' +d(s, 'Europe/Berlin').sub(1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-28T23:59:59+01:00' +d(s, 'Europe/Berlin').sub(1, 'd');{};'Invalid date' +d(s, 'Europe/Berlin').add(1, 'w');{s: '2025-03-30 01:30'};'2025-04-06T02:30:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').add(1, 'w');{s: '2025-10-27 00:30'};'2025-11-03T00:30:00+01:00' +d(s, 'Europe/Berlin').add(1, 'w');{s: '2025-10-26 12:00'};'2025-11-02T12:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'w');{s: '2024-03-31'};'2024-04-07T01:00:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').add(1, 'w');{s: '2025-06-30 12:00'};'2025-07-07T12:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'w');{s: 'nope'};'Invalid date' +d(s, 'Europe/Berlin').sub(1, 'w');{s: '2025-10-27 00:30'};'2025-10-20T01:30:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').sub(1, 'w');{s: '2025-10-26 12:00'};'2025-10-19T13:00:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').sub(1, 'w');{s: '2025-10-26 04:00'};'2025-10-19T05:00:00+02:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'Europe/Berlin').sub(1, 'w');{s: '2025-03-17'};'2025-03-10T00:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'w');{s: '2024-05-31 06:07:08'};'2024-05-24T06:07:08+02:00' +d(s, 'Europe/Berlin').sub(1, 'w');{s: 1700000000123};'2023-11-07T23:13:20+01:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-10-26 12:00'};'2025-11-26T12:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-10-26 04:00'};'2025-11-26T04:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2025-03-30 12:00'};'2025-04-30T12:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2023-02-28 00:00:01'};'2023-03-28T00:00:01+02:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: '2024-12-30 00:00:00'};'2025-01-30T00:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'M');{s: true};'Invalid date' +d(s, 'Europe/Berlin').sub(1, 'M');{s: '2025-10-26 04:00'};'2025-09-26T04:00:00+02:00' +d(s, 'Europe/Berlin').sub(1, 'M');{s: '2025-03-30 12:00'};'2025-02-28T12:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'M');{s: '2025-10-25 23:30'};'2025-09-25T23:30:00+02:00' +d(s, 'Europe/Berlin').sub(1, 'M');{s: '2024-07-31 13:14:15'};'2024-06-30T13:14:15+02:00' +d(s, 'Europe/Berlin').sub(1, 'M');{s: '2025-01-01'};'2024-12-01T00:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'M');{s: '2023-02-30'};'Invalid date' +d(s, 'Europe/Berlin').add(1, 'q');{s: '2025-03-30 12:00'};'2025-06-30T12:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'q');{s: '2025-10-25 23:30'};'2026-01-25T23:30:00+01:00' +d(s, 'Europe/Berlin').add(1, 'q');{s: '2025-03-30 03:00'};'2025-06-30T03:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'q');{s: '2024-01-31 10:20:30'};'2024-04-30T10:20:30+02:00' +d(s, 'Europe/Berlin').add(1, 'q');{s: '2024-02-29 23:59:59'};'2024-05-29T23:59:59+02:00' +d(s, 'Europe/Berlin').add(1, 'q');{s: 1735689599999};'2025-04-01T00:59:59+02:00' +d(s, 'Europe/Berlin').sub(1, 'q');{s: '2025-10-25 23:30'};'2025-07-25T23:30:00+02:00' +d(s, 'Europe/Berlin').sub(1, 'q');{s: '2025-03-30 03:00'};'2024-12-30T03:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'q');{s: '2025-03-29 12:00'};'2024-12-29T12:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'q');{s: '2024-03-31'};'2023-12-31T00:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'q');{s: '2025-06-30 12:00'};'2025-03-30T12:00:00+02:00' +d(s, 'Europe/Berlin').sub(1, 'q');{s: ''};'Invalid date' +d(s, 'Europe/Berlin').add(1, 'y');{s: '2025-03-30 03:00'};'2026-03-30T03:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'y');{s: '2025-03-29 12:00'};'2026-03-29T12:00:00+02:00' +d(s, 'Europe/Berlin').add(1, 'y');{s: '2025-03-30 01:30'};'2026-03-30T01:30:00+02:00' +d(s, 'Europe/Berlin').add(1, 'y');{s: '2025-03-17'};'2026-03-17T00:00:00+01:00' +d(s, 'Europe/Berlin').add(1, 'y');{s: '2024-05-31 06:07:08'};'2025-05-31T06:07:08+02:00' +d(s, 'Europe/Berlin').add(1, 'y');{s: null};'Invalid date' +d(s, 'Europe/Berlin').sub(1, 'y');{s: '2025-03-29 12:00'};'2024-03-29T12:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'y');{s: '2025-03-30 01:30'};'2024-03-30T01:30:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'y');{s: '2025-10-27 00:30'};'2024-10-27T00:30:00+02:00' +d(s, 'Europe/Berlin').sub(1, 'y');{s: '2023-02-28 00:00:01'};'2022-02-28T00:00:01+01:00' +d(s, 'Europe/Berlin').sub(1, 'y');{s: '2024-12-30 00:00:00'};'2023-12-30T00:00:00+01:00' +d(s, 'Europe/Berlin').sub(1, 'y');{};'Invalid date' +# add/sub matrix in America/New_York +d(s, 'America/New_York').add(30, 's');{s: '2025-03-09 03:15'};'2025-03-09T03:15:30-04:00' +d(s, 'America/New_York').add(30, 's');{s: '2025-11-02 00:15'};'2025-11-02T00:15:30-04:00' +d(s, 'America/New_York').add(30, 's');{s: '2025-11-02 12:00'};'2025-11-02T12:00:30-05:00' +d(s, 'America/New_York').add(30, 's');{s: '2024-07-31 13:14:15'};'2024-07-31T13:14:45-04:00' +d(s, 'America/New_York').add(30, 's');{s: '2025-01-01'};'2025-01-01T00:00:30-05:00' +d(s, 'America/New_York').add(30, 's');{s: 'nope'};'Invalid date' +d(s, 'America/New_York').sub(7200, 's');{s: '2025-11-02 00:15'};'2025-11-01T22:15:00-04:00' +d(s, 'America/New_York').sub(7200, 's');{s: '2025-11-02 12:00'};'2025-11-02T10:00:00-05:00' +d(s, 'America/New_York').sub(7200, 's');{s: '2025-11-02 03:00'};'2025-11-02T01:00:00-05:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'America/New_York').sub(7200, 's');{s: '2024-01-31 10:20:30'};'2024-01-31T08:20:30-05:00' +d(s, 'America/New_York').sub(7200, 's');{s: '2024-02-29 23:59:59'};'2024-02-29T21:59:59-05:00' +d(s, 'America/New_York').sub(7200, 's');{s: 1700000000123};'2023-11-14T15:13:20-05:00' +d(s, 'America/New_York').add(15, 'm');{s: '2025-11-02 12:00'};'2025-11-02T12:15:00-05:00' +d(s, 'America/New_York').add(15, 'm');{s: '2025-11-02 03:00'};'2025-11-02T03:15:00-05:00' +d(s, 'America/New_York').add(15, 'm');{s: '2025-03-09 12:00'};'2025-03-09T12:15:00-04:00' +d(s, 'America/New_York').add(15, 'm');{s: '2024-03-31'};'2024-03-31T00:15:00-04:00' +d(s, 'America/New_York').add(15, 'm');{s: '2025-06-30 12:00'};'2025-06-30T12:15:00-04:00' +d(s, 'America/New_York').add(15, 'm');{s: true};'Invalid date' +d(s, 'America/New_York').sub(120, 'm');{s: '2025-11-02 03:00'};'2025-11-02T01:00:00-05:00';bug: any add/sub whose result is an ambiguous wall time gives an invalid date (the zero-month calendar step re-resolves the local time) +d(s, 'America/New_York').sub(120, 'm');{s: '2025-03-09 12:00'};'2025-03-09T10:00:00-04:00' +d(s, 'America/New_York').sub(120, 'm');{s: '2025-11-01 18:00'};'2025-11-01T16:00:00-04:00' +d(s, 'America/New_York').sub(120, 'm');{s: '2025-03-17'};'2025-03-16T22:00:00-04:00' +d(s, 'America/New_York').sub(120, 'm');{s: '2024-05-31 06:07:08'};'2024-05-31T04:07:08-04:00' +d(s, 'America/New_York').sub(120, 'm');{s: '2023-02-30'};'Invalid date' +d(s, 'America/New_York').add(2, 'h');{s: '2025-03-09 12:00'};'2025-03-09T14:00:00-04:00' +d(s, 'America/New_York').add(2, 'h');{s: '2025-11-01 18:00'};'2025-11-01T20:00:00-04:00' +d(s, 'America/New_York').add(2, 'h');{s: '2025-03-10 00:30'};'2025-03-10T02:30:00-04:00' +d(s, 'America/New_York').add(2, 'h');{s: '2023-02-28 00:00:01'};'2023-02-28T02:00:01-05:00' +d(s, 'America/New_York').add(2, 'h');{s: '2024-12-30 00:00:00'};'2024-12-30T02:00:00-05:00' +d(s, 'America/New_York').add(2, 'h');{s: 1735689599999};'2024-12-31T20:59:59-05:00' +d(s, 'America/New_York').sub(1, 'h');{s: '2025-11-01 18:00'};'2025-11-01T17:00:00-04:00' +d(s, 'America/New_York').sub(1, 'h');{s: '2025-03-10 00:30'};'2025-03-09T23:30:00-04:00' +d(s, 'America/New_York').sub(1, 'h');{s: '2025-03-08 23:30'};'2025-03-08T22:30:00-05:00' +d(s, 'America/New_York').sub(1, 'h');{s: '2024-07-31 13:14:15'};'2024-07-31T12:14:15-04:00' +d(s, 'America/New_York').sub(1, 'h');{s: '2025-01-01'};'2024-12-31T23:00:00-05:00' +d(s, 'America/New_York').sub(1, 'h');{s: ''};'Invalid date' +d(s, 'America/New_York').add(2, 'd');{s: '2025-03-10 00:30'};'2025-03-12T00:30:00-04:00' +d(s, 'America/New_York').add(2, 'd');{s: '2025-03-08 23:30'};'2025-03-11T00:30:00-04:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'America/New_York').add(2, 'd');{s: '2025-03-09 03:15'};'2025-03-11T03:15:00-04:00' +d(s, 'America/New_York').add(2, 'd');{s: '2024-01-31 10:20:30'};'2024-02-02T10:20:30-05:00' +d(s, 'America/New_York').add(2, 'd');{s: '2024-02-29 23:59:59'};'2024-03-02T23:59:59-05:00' +d(s, 'America/New_York').add(2, 'd');{s: null};'Invalid date' +d(s, 'America/New_York').sub(1, 'd');{s: '2025-03-08 23:30'};'2025-03-07T23:30:00-05:00' +d(s, 'America/New_York').sub(1, 'd');{s: '2025-03-09 03:15'};'2025-03-08T02:15:00-05:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'America/New_York').sub(1, 'd');{s: '2025-11-02 00:15'};'2025-11-01T00:15:00-04:00' +d(s, 'America/New_York').sub(1, 'd');{s: '2024-03-31'};'2024-03-30T00:00:00-04:00' +d(s, 'America/New_York').sub(1, 'd');{s: '2025-06-30 12:00'};'2025-06-29T12:00:00-04:00' +d(s, 'America/New_York').sub(1, 'd');{};'Invalid date' +d(s, 'America/New_York').add(3, 'w');{s: '2025-03-09 03:15'};'2025-03-30T03:15:00-04:00' +d(s, 'America/New_York').add(3, 'w');{s: '2025-11-02 00:15'};'2025-11-22T23:15:00-05:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'America/New_York').add(3, 'w');{s: '2025-11-02 12:00'};'2025-11-23T12:00:00-05:00' +d(s, 'America/New_York').add(3, 'w');{s: '2025-03-17'};'2025-04-07T00:00:00-04:00' +d(s, 'America/New_York').add(3, 'w');{s: '2024-05-31 06:07:08'};'2024-06-21T06:07:08-04:00' +d(s, 'America/New_York').add(3, 'w');{s: 'nope'};'Invalid date' +d(s, 'America/New_York').sub(1, 'w');{s: '2025-11-02 00:15'};'2025-10-26T00:15:00-04:00' +d(s, 'America/New_York').sub(1, 'w');{s: '2025-11-02 12:00'};'2025-10-26T13:00:00-04:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'America/New_York').sub(1, 'w');{s: '2025-11-02 03:00'};'2025-10-26T04:00:00-04:00';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(s, 'America/New_York').sub(1, 'w');{s: '2023-02-28 00:00:01'};'2023-02-21T00:00:01-05:00' +d(s, 'America/New_York').sub(1, 'w');{s: '2024-12-30 00:00:00'};'2024-12-23T00:00:00-05:00' +d(s, 'America/New_York').sub(1, 'w');{s: 1700000000123};'2023-11-07T17:13:20-05:00' +d(s, 'America/New_York').add(6, 'M');{s: '2025-11-02 12:00'};'2026-05-02T12:00:00-04:00' +d(s, 'America/New_York').add(6, 'M');{s: '2025-11-02 03:00'};'2026-05-02T03:00:00-04:00' +d(s, 'America/New_York').add(6, 'M');{s: '2025-03-09 12:00'};'2025-09-09T12:00:00-04:00' +d(s, 'America/New_York').add(6, 'M');{s: '2024-07-31 13:14:15'};'2025-01-31T13:14:15-05:00' +d(s, 'America/New_York').add(6, 'M');{s: '2025-01-01'};'2025-07-01T00:00:00-04:00' +d(s, 'America/New_York').add(6, 'M');{s: true};'Invalid date' +d(s, 'America/New_York').sub(1, 'M');{s: '2025-11-02 03:00'};'2025-10-02T03:00:00-04:00' +d(s, 'America/New_York').sub(1, 'M');{s: '2025-03-09 12:00'};'2025-02-09T12:00:00-05:00' +d(s, 'America/New_York').sub(1, 'M');{s: '2025-11-01 18:00'};'2025-10-01T18:00:00-04:00' +d(s, 'America/New_York').sub(1, 'M');{s: '2024-01-31 10:20:30'};'2023-12-31T10:20:30-05:00' +d(s, 'America/New_York').sub(1, 'M');{s: '2024-02-29 23:59:59'};'2024-01-29T23:59:59-05:00' +d(s, 'America/New_York').sub(1, 'M');{s: '2023-02-30'};'Invalid date' +d(s, 'America/New_York').add(1, 'q');{s: '2025-03-09 12:00'};'2025-06-09T12:00:00-04:00' +d(s, 'America/New_York').add(1, 'q');{s: '2025-11-01 18:00'};'2026-02-01T18:00:00-05:00' +d(s, 'America/New_York').add(1, 'q');{s: '2025-03-10 00:30'};'2025-06-10T00:30:00-04:00' +d(s, 'America/New_York').add(1, 'q');{s: '2024-03-31'};'2024-06-30T00:00:00-04:00' +d(s, 'America/New_York').add(1, 'q');{s: '2025-06-30 12:00'};'2025-09-30T12:00:00-04:00' +d(s, 'America/New_York').add(1, 'q');{s: 1735689599999};'2025-03-31T18:59:59-04:00' +d(s, 'America/New_York').sub(4, 'q');{s: '2025-11-01 18:00'};'2024-11-01T18:00:00-04:00' +d(s, 'America/New_York').sub(4, 'q');{s: '2025-03-10 00:30'};'2024-03-10T00:30:00-05:00' +d(s, 'America/New_York').sub(4, 'q');{s: '2025-03-08 23:30'};'2024-03-08T23:30:00-05:00' +d(s, 'America/New_York').sub(4, 'q');{s: '2025-03-17'};'2024-03-17T00:00:00-04:00' +d(s, 'America/New_York').sub(4, 'q');{s: '2024-05-31 06:07:08'};'2023-05-31T06:07:08-04:00' +d(s, 'America/New_York').sub(4, 'q');{s: ''};'Invalid date' +d(s, 'America/New_York').add(2, 'y');{s: '2025-03-10 00:30'};'2027-03-10T00:30:00-05:00' +d(s, 'America/New_York').add(2, 'y');{s: '2025-03-08 23:30'};'2027-03-08T23:30:00-05:00' +d(s, 'America/New_York').add(2, 'y');{s: '2025-03-09 03:15'};'2027-03-09T03:15:00-05:00' +d(s, 'America/New_York').add(2, 'y');{s: '2023-02-28 00:00:01'};'2025-02-28T00:00:01-05:00' +d(s, 'America/New_York').add(2, 'y');{s: '2024-12-30 00:00:00'};'2026-12-30T00:00:00-05:00' +d(s, 'America/New_York').add(2, 'y');{s: null};'Invalid date' +d(s, 'America/New_York').sub(1, 'y');{s: '2025-03-08 23:30'};'2024-03-08T23:30:00-05:00' +d(s, 'America/New_York').sub(1, 'y');{s: '2025-03-09 03:15'};'2024-03-09T03:15:00-05:00' +d(s, 'America/New_York').sub(1, 'y');{s: '2025-11-02 00:15'};'2024-11-02T00:15:00-04:00' +d(s, 'America/New_York').sub(1, 'y');{s: '2024-07-31 13:14:15'};'2023-07-31T13:14:15-04:00' +d(s, 'America/New_York').sub(1, 'y');{s: '2025-01-01'};'2024-01-01T00:00:00-05:00' +d(s, 'America/New_York').sub(1, 'y');{};'Invalid date' +# add/sub matrix in Asia/Kolkata +d(s, 'Asia/Kolkata').add(1, 's');{s: '2024-01-31 10:20:30'};'2024-01-31T10:20:31+05:30' +d(s, 'Asia/Kolkata').add(1, 's');{s: '2024-02-29 23:59:59'};'2024-03-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 's');{s: '2023-12-31 23:30:15'};'2023-12-31T23:30:16+05:30' +d(s, 'Asia/Kolkata').add(1, 's');{s: '2024-03-31'};'2024-03-31T00:00:01+05:30' +d(s, 'Asia/Kolkata').add(1, 's');{s: '2025-06-30 12:00'};'2025-06-30T12:00:01+05:30' +d(s, 'Asia/Kolkata').add(1, 's');{s: 'nope'};'Invalid date' +d(s, 'Asia/Kolkata').sub(61, 's');{s: '2025-03-17'};'2025-03-16T23:58:59+05:30' +d(s, 'Asia/Kolkata').sub(61, 's');{s: '2024-05-31 06:07:08'};'2024-05-31T06:06:07+05:30' +d(s, 'Asia/Kolkata').sub(61, 's');{s: '2025-08-31 18:00'};'2025-08-31T17:58:59+05:30' +d(s, 'Asia/Kolkata').sub(61, 's');{s: '2023-02-28 00:00:01'};'2023-02-27T23:59:00+05:30' +d(s, 'Asia/Kolkata').sub(61, 's');{s: '2024-12-30 00:00:00'};'2024-12-29T23:58:59+05:30' +d(s, 'Asia/Kolkata').sub(61, 's');{s: 1700000000123};'2023-11-15T03:42:19+05:30' +d(s, 'Asia/Kolkata').add(30, 'm');{s: '2024-07-31 13:14:15'};'2024-07-31T13:44:15+05:30' +d(s, 'Asia/Kolkata').add(30, 'm');{s: '2025-01-01'};'2025-01-01T00:30:00+05:30' +d(s, 'Asia/Kolkata').add(30, 'm');{s: '2024-09-30 21:45'};'2024-09-30T22:15:00+05:30' +d(s, 'Asia/Kolkata').add(30, 'm');{s: '2024-01-31 10:20:30'};'2024-01-31T10:50:30+05:30' +d(s, 'Asia/Kolkata').add(30, 'm');{s: '2024-02-29 23:59:59'};'2024-03-01T00:29:59+05:30' +d(s, 'Asia/Kolkata').add(30, 'm');{s: true};'Invalid date' +d(s, 'Asia/Kolkata').sub(330, 'm');{s: '2024-03-31'};'2024-03-30T18:30:00+05:30' +d(s, 'Asia/Kolkata').sub(330, 'm');{s: '2025-06-30 12:00'};'2025-06-30T06:30:00+05:30' +d(s, 'Asia/Kolkata').sub(330, 'm');{s: '2025-03-16 08:45:00'};'2025-03-16T03:15:00+05:30' +d(s, 'Asia/Kolkata').sub(330, 'm');{s: '2025-03-17'};'2025-03-16T18:30:00+05:30' +d(s, 'Asia/Kolkata').sub(330, 'm');{s: '2024-05-31 06:07:08'};'2024-05-31T00:37:08+05:30' +d(s, 'Asia/Kolkata').sub(330, 'm');{s: '2023-02-30'};'Invalid date' +d(s, 'Asia/Kolkata').add(18, 'h');{s: '2023-02-28 00:00:01'};'2023-02-28T18:00:01+05:30' +d(s, 'Asia/Kolkata').add(18, 'h');{s: '2024-12-30 00:00:00'};'2024-12-30T18:00:00+05:30' +d(s, 'Asia/Kolkata').add(18, 'h');{s: '2025-11-30 23:59:59'};'2025-12-01T17:59:59+05:30' +d(s, 'Asia/Kolkata').add(18, 'h');{s: '2024-07-31 13:14:15'};'2024-08-01T07:14:15+05:30' +d(s, 'Asia/Kolkata').add(18, 'h');{s: '2025-01-01'};'2025-01-01T18:00:00+05:30' +d(s, 'Asia/Kolkata').add(18, 'h');{s: 1735689599999};'2025-01-01T23:29:59+05:30' +d(s, 'Asia/Kolkata').sub(6, 'h');{s: '2024-01-31 10:20:30'};'2024-01-31T04:20:30+05:30' +d(s, 'Asia/Kolkata').sub(6, 'h');{s: '2024-02-29 23:59:59'};'2024-02-29T17:59:59+05:30' +d(s, 'Asia/Kolkata').sub(6, 'h');{s: '2023-12-31 23:30:15'};'2023-12-31T17:30:15+05:30' +d(s, 'Asia/Kolkata').sub(6, 'h');{s: '2024-03-31'};'2024-03-30T18:00:00+05:30' +d(s, 'Asia/Kolkata').sub(6, 'h');{s: '2025-06-30 12:00'};'2025-06-30T06:00:00+05:30' +d(s, 'Asia/Kolkata').sub(6, 'h');{s: ''};'Invalid date' +d(s, 'Asia/Kolkata').add(1, 'd');{s: '2025-03-17'};'2025-03-18T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'd');{s: '2024-05-31 06:07:08'};'2024-06-01T06:07:08+05:30' +d(s, 'Asia/Kolkata').add(1, 'd');{s: '2025-08-31 18:00'};'2025-09-01T18:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'd');{s: '2023-02-28 00:00:01'};'2023-03-01T00:00:01+05:30' +d(s, 'Asia/Kolkata').add(1, 'd');{s: '2024-12-30 00:00:00'};'2024-12-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'd');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').sub(366, 'd');{s: '2024-07-31 13:14:15'};'2023-07-31T13:14:15+05:30' +d(s, 'Asia/Kolkata').sub(366, 'd');{s: '2025-01-01'};'2024-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(366, 'd');{s: '2024-09-30 21:45'};'2023-09-30T21:45:00+05:30' +d(s, 'Asia/Kolkata').sub(366, 'd');{s: '2024-01-31 10:20:30'};'2023-01-30T10:20:30+05:30' +d(s, 'Asia/Kolkata').sub(366, 'd');{s: '2024-02-29 23:59:59'};'2023-02-28T23:59:59+05:30' +d(s, 'Asia/Kolkata').sub(366, 'd');{};'Invalid date' +d(s, 'Asia/Kolkata').add(52, 'w');{s: '2024-03-31'};'2025-03-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(52, 'w');{s: '2025-06-30 12:00'};'2026-06-29T12:00:00+05:30' +d(s, 'Asia/Kolkata').add(52, 'w');{s: '2025-03-16 08:45:00'};'2026-03-15T08:45:00+05:30' +d(s, 'Asia/Kolkata').add(52, 'w');{s: '2025-03-17'};'2026-03-16T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(52, 'w');{s: '2024-05-31 06:07:08'};'2025-05-30T06:07:08+05:30' +d(s, 'Asia/Kolkata').add(52, 'w');{s: 'nope'};'Invalid date' +d(s, 'Asia/Kolkata').sub(1, 'w');{s: '2023-02-28 00:00:01'};'2023-02-21T00:00:01+05:30' +d(s, 'Asia/Kolkata').sub(1, 'w');{s: '2024-12-30 00:00:00'};'2024-12-23T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'w');{s: '2025-11-30 23:59:59'};'2025-11-23T23:59:59+05:30' +d(s, 'Asia/Kolkata').sub(1, 'w');{s: '2024-07-31 13:14:15'};'2024-07-24T13:14:15+05:30' +d(s, 'Asia/Kolkata').sub(1, 'w');{s: '2025-01-01'};'2024-12-25T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'w');{s: 1700000000123};'2023-11-08T03:43:20+05:30' +d(s, 'Asia/Kolkata').add(1, 'M');{s: '2024-01-31 10:20:30'};'2024-02-29T10:20:30+05:30' +d(s, 'Asia/Kolkata').add(1, 'M');{s: '2024-02-29 23:59:59'};'2024-03-29T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'M');{s: '2023-12-31 23:30:15'};'2024-01-31T23:30:15+05:30' +d(s, 'Asia/Kolkata').add(1, 'M');{s: '2024-03-31'};'2024-04-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'M');{s: '2025-06-30 12:00'};'2025-07-30T12:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'M');{s: true};'Invalid date' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2025-03-17'};'2025-02-17T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2024-05-31 06:07:08'};'2024-04-30T06:07:08+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2025-08-31 18:00'};'2025-07-31T18:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2023-02-28 00:00:01'};'2023-01-28T00:00:01+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2024-12-30 00:00:00'};'2024-11-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'M');{s: '2023-02-30'};'Invalid date' +d(s, 'Asia/Kolkata').add(1, 'q');{s: '2024-07-31 13:14:15'};'2024-10-31T13:14:15+05:30' +d(s, 'Asia/Kolkata').add(1, 'q');{s: '2025-01-01'};'2025-04-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'q');{s: '2024-09-30 21:45'};'2024-12-30T21:45:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'q');{s: '2024-01-31 10:20:30'};'2024-04-30T10:20:30+05:30' +d(s, 'Asia/Kolkata').add(1, 'q');{s: '2024-02-29 23:59:59'};'2024-05-29T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'q');{s: 1735689599999};'2025-04-01T05:29:59+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q');{s: '2024-03-31'};'2023-12-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q');{s: '2025-06-30 12:00'};'2025-03-30T12:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q');{s: '2025-03-16 08:45:00'};'2024-12-16T08:45:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q');{s: '2025-03-17'};'2024-12-17T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q');{s: '2024-05-31 06:07:08'};'2024-02-29T06:07:08+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q');{s: ''};'Invalid date' +d(s, 'Asia/Kolkata').add(1, 'y');{s: '2023-02-28 00:00:01'};'2024-02-28T00:00:01+05:30' +d(s, 'Asia/Kolkata').add(1, 'y');{s: '2024-12-30 00:00:00'};'2025-12-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'y');{s: '2025-11-30 23:59:59'};'2026-11-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'y');{s: '2024-07-31 13:14:15'};'2025-07-31T13:14:15+05:30' +d(s, 'Asia/Kolkata').add(1, 'y');{s: '2025-01-01'};'2026-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').add(1, 'y');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').sub(1, 'y');{s: '2024-01-31 10:20:30'};'2023-01-31T10:20:30+05:30' +d(s, 'Asia/Kolkata').sub(1, 'y');{s: '2024-02-29 23:59:59'};'2023-02-28T23:59:59+05:30';bug: adding a year to Feb 29 gives an invalid date instead of clamping to Feb 28 like months do +d(s, 'Asia/Kolkata').sub(1, 'y');{s: '2023-12-31 23:30:15'};'2022-12-31T23:30:15+05:30' +d(s, 'Asia/Kolkata').sub(1, 'y');{s: '2024-03-31'};'2023-03-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'y');{s: '2025-06-30 12:00'};'2024-06-30T12:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'y');{};'Invalid date' diff --git a/core/expression/tests/spec/standard/16-02-start-end-matrix.csv b/core/expression/tests/spec/standard/16-02-start-end-matrix.csv new file mode 100644 index 00000000..e8cf262b --- /dev/null +++ b/core/expression/tests/spec/standard/16-02-start-end-matrix.csv @@ -0,0 +1,443 @@ +expression (string);input (json 5);output (json 5);note +# startOf/endOf matrix in UTC +d(s).startOf('s');{s: '2025-06-30 12:00'};'2025-06-30T12:00:00Z' +d(s).startOf('s');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:00Z' +d(s).startOf('s');{s: '2025-03-17'};'2025-03-17T00:00:00Z' +d(s).startOf('s');{s: '2024-05-31 06:07:08'};'2024-05-31T06:07:08Z' +d(s).startOf('s');{s: null};'Invalid date' +d(s).endOf('second');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:01Z' +d(s).endOf('second');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:00Z' +d(s).endOf('second');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59Z' +d(s).endOf('second');{s: '2024-07-31 13:14:15'};'2024-07-31T13:14:15Z' +d(s).endOf('second');{};'Invalid date' +d(s).startOf('minute');{s: '2024-09-30 21:45'};'2024-09-30T21:45:00Z' +d(s).startOf('minute');{s: '2024-01-31 10:20:30'};'2024-01-31T10:20:00Z' +d(s).startOf('minute');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:00Z' +d(s).startOf('minute');{s: '2023-12-31 23:30:15'};'2023-12-31T23:30:00Z' +d(s).startOf('minute');{s: 'nope'};'Invalid date' +d(s).endOf('minute');{s: '2025-06-30 12:00'};'2025-06-30T12:00:59Z' +d(s).endOf('minute');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:59Z' +d(s).endOf('minute');{s: '2025-03-17'};'2025-03-17T00:00:59Z' +d(s).endOf('minute');{s: '2024-05-31 06:07:08'};'2024-05-31T06:07:59Z' +d(s).endOf('minute');{s: 1700000000123};'2023-11-14T22:13:59Z' +d(s).startOf('h');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:00Z' +d(s).startOf('h');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:00Z' +d(s).startOf('h');{s: '2025-11-30 23:59:59'};'2025-11-30T23:00:00Z' +d(s).startOf('h');{s: '2024-07-31 13:14:15'};'2024-07-31T13:00:00Z' +d(s).startOf('h');{s: true};'Invalid date' +d(s).endOf('hour');{s: '2024-09-30 21:45'};'2024-09-30T21:59:59Z' +d(s).endOf('hour');{s: '2024-01-31 10:20:30'};'2024-01-31T10:59:59Z' +d(s).endOf('hour');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59Z' +d(s).endOf('hour');{s: '2023-12-31 23:30:15'};'2023-12-31T23:59:59Z' +d(s).endOf('hour');{s: '2023-02-30'};'Invalid date' +d(s).startOf('d');{s: '2025-06-30 12:00'};'2025-06-30T00:00:00Z' +d(s).startOf('d');{s: '2025-03-16 08:45:00'};'2025-03-16T00:00:00Z' +d(s).startOf('d');{s: '2025-03-17'};'2025-03-17T00:00:00Z' +d(s).startOf('d');{s: '2024-05-31 06:07:08'};'2024-05-31T00:00:00Z' +d(s).startOf('d');{s: 1735689599999};'2024-12-31T00:00:00Z' +d(s).endOf('day');{s: '2023-02-28 00:00:01'};'2023-02-28T23:59:59Z' +d(s).endOf('day');{s: '2024-12-30 00:00:00'};'2024-12-30T23:59:59Z' +d(s).endOf('day');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59Z' +d(s).endOf('day');{s: '2024-07-31 13:14:15'};'2024-07-31T23:59:59Z' +d(s).endOf('day');{s: ''};'Invalid date' +d(s).startOf('week');{s: '2024-09-30 21:45'};'2024-09-30T00:00:00Z' +d(s).startOf('week');{s: '2024-01-31 10:20:30'};'2024-01-29T00:00:00Z' +d(s).startOf('week');{s: '2024-02-29 23:59:59'};'2024-02-26T00:00:00Z' +d(s).startOf('week');{s: '2023-12-31 23:30:15'};'2023-12-25T00:00:00Z' +d(s).startOf('week');{s: null};'Invalid date' +d(s).endOf('week');{s: '2025-06-30 12:00'};'2025-07-06T23:59:59Z' +d(s).endOf('week');{s: '2025-03-16 08:45:00'};'2025-03-16T23:59:59Z' +d(s).endOf('week');{s: '2025-03-17'};'2025-03-23T23:59:59Z' +d(s).endOf('week');{s: '2024-05-31 06:07:08'};'2024-06-02T23:59:59Z' +d(s).endOf('week');{};'Invalid date' +d(s).startOf('M');{s: '2023-02-28 00:00:01'};'2023-02-01T00:00:00Z' +d(s).startOf('M');{s: '2024-12-30 00:00:00'};'2024-12-01T00:00:00Z' +d(s).startOf('M');{s: '2025-11-30 23:59:59'};'2025-11-01T00:00:00Z' +d(s).startOf('M');{s: '2024-07-31 13:14:15'};'2024-07-01T00:00:00Z' +d(s).startOf('M');{s: 'nope'};'Invalid date' +d(s).endOf('month');{s: '2024-09-30 21:45'};'2024-09-30T23:59:59Z' +d(s).endOf('month');{s: '2024-01-31 10:20:30'};'2024-01-31T23:59:59Z' +d(s).endOf('month');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59Z' +d(s).endOf('month');{s: '2023-12-31 23:30:15'};'2023-12-31T23:59:59Z' +d(s).endOf('month');{s: 1700000000123};'2023-11-30T23:59:59Z' +d(s).startOf('q');{s: '2025-06-30 12:00'};'2025-04-01T00:00:00Z' +d(s).startOf('q');{s: '2024-05-31 06:07:08'};'2024-04-01T00:00:00Z';bug: the month is moved before the day is reset, April 31 does not exist +d(s).startOf('q');{s: '2025-08-31 18:00'};'2025-07-01T00:00:00Z' +d(s).startOf('q');{s: '2024-07-31 13:14:15'};'2024-07-01T00:00:00Z' +d(s).startOf('q');{s: true};'Invalid date' +d(s).endOf('quarter');{s: '2023-02-28 00:00:01'};'2023-03-31T23:59:59Z' +d(s).endOf('quarter');{s: '2024-05-31 06:07:08'};'2024-06-30T23:59:59Z';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s).endOf('quarter');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59Z';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s).endOf('quarter');{s: '2024-07-31 13:14:15'};'2024-09-30T23:59:59Z';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s).endOf('quarter');{s: '2023-02-30'};'Invalid date' +d(s).startOf('year');{s: '2024-09-30 21:45'};'2024-01-01T00:00:00Z' +d(s).startOf('year');{s: '2024-01-31 10:20:30'};'2024-01-01T00:00:00Z' +d(s).startOf('year');{s: '2024-02-29 23:59:59'};'2024-01-01T00:00:00Z' +d(s).startOf('year');{s: '2023-12-31 23:30:15'};'2023-01-01T00:00:00Z' +d(s).startOf('year');{s: 1735689599999};'2024-01-01T00:00:00Z' +d(s).endOf('year');{s: '2025-06-30 12:00'};'2025-12-31T23:59:59Z' +d(s).endOf('year');{s: '2025-03-16 08:45:00'};'2025-12-31T23:59:59Z' +d(s).endOf('year');{s: '2025-03-17'};'2025-12-31T23:59:59Z' +d(s).endOf('year');{s: '2024-05-31 06:07:08'};'2024-12-31T23:59:59Z' +d(s).endOf('year');{s: ''};'Invalid date' +# startOf/endOf matrix in Etc/GMT+5 +d(s, 'Etc/GMT+5').startOf('s');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:01-05:00' +d(s, 'Etc/GMT+5').startOf('s');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('s');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('s');{s: '2024-07-31 13:14:15'};'2024-07-31T13:14:15-05:00' +d(s, 'Etc/GMT+5').startOf('s');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').endOf('second');{s: '2024-09-30 21:45'};'2024-09-30T21:45:00-05:00' +d(s, 'Etc/GMT+5').endOf('second');{s: '2024-01-31 10:20:30'};'2024-01-31T10:20:30-05:00' +d(s, 'Etc/GMT+5').endOf('second');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('second');{s: '2023-12-31 23:30:15'};'2023-12-31T23:30:15-05:00' +d(s, 'Etc/GMT+5').endOf('second');{};'Invalid date' +d(s, 'Etc/GMT+5').startOf('minute');{s: '2025-06-30 12:00'};'2025-06-30T12:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('minute');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:00-05:00' +d(s, 'Etc/GMT+5').startOf('minute');{s: '2025-03-17'};'2025-03-17T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('minute');{s: '2024-05-31 06:07:08'};'2024-05-31T06:07:00-05:00' +d(s, 'Etc/GMT+5').startOf('minute');{s: 'nope'};'Invalid date' +d(s, 'Etc/GMT+5').endOf('minute');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:59-05:00' +d(s, 'Etc/GMT+5').endOf('minute');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:59-05:00' +d(s, 'Etc/GMT+5').endOf('minute');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('minute');{s: '2024-07-31 13:14:15'};'2024-07-31T13:14:59-05:00' +d(s, 'Etc/GMT+5').endOf('minute');{s: 1700000000123};'2023-11-14T17:13:59-05:00' +d(s, 'Etc/GMT+5').startOf('h');{s: '2024-09-30 21:45'};'2024-09-30T21:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('h');{s: '2024-01-31 10:20:30'};'2024-01-31T10:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('h');{s: '2024-02-29 23:59:59'};'2024-02-29T23:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('h');{s: '2023-12-31 23:30:15'};'2023-12-31T23:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('h');{s: true};'Invalid date' +d(s, 'Etc/GMT+5').endOf('hour');{s: '2025-06-30 12:00'};'2025-06-30T12:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('hour');{s: '2025-03-16 08:45:00'};'2025-03-16T08:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('hour');{s: '2025-03-17'};'2025-03-17T00:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('hour');{s: '2024-05-31 06:07:08'};'2024-05-31T06:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('hour');{s: '2023-02-30'};'Invalid date' +d(s, 'Etc/GMT+5').startOf('d');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('d');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('d');{s: '2025-11-30 23:59:59'};'2025-11-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('d');{s: '2024-07-31 13:14:15'};'2024-07-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('d');{s: 1735689599999};'2024-12-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('day');{s: '2024-09-30 21:45'};'2024-09-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('day');{s: '2024-01-31 10:20:30'};'2024-01-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('day');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('day');{s: '2023-12-31 23:30:15'};'2023-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('day');{s: ''};'Invalid date' +d(s, 'Etc/GMT+5').startOf('week');{s: '2025-06-30 12:00'};'2025-06-30T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('week');{s: '2025-03-16 08:45:00'};'2025-03-10T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('week');{s: '2025-03-17'};'2025-03-17T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('week');{s: '2024-05-31 06:07:08'};'2024-05-27T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('week');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').endOf('week');{s: '2023-02-28 00:00:01'};'2023-03-05T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('week');{s: '2024-12-30 00:00:00'};'2025-01-05T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('week');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('week');{s: '2024-07-31 13:14:15'};'2024-08-04T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('week');{};'Invalid date' +d(s, 'Etc/GMT+5').startOf('M');{s: '2024-09-30 21:45'};'2024-09-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M');{s: '2024-01-31 10:20:30'};'2024-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M');{s: '2024-02-29 23:59:59'};'2024-02-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M');{s: '2023-12-31 23:30:15'};'2023-12-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M');{s: 'nope'};'Invalid date' +d(s, 'Etc/GMT+5').endOf('month');{s: '2025-06-30 12:00'};'2025-06-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('month');{s: '2025-03-16 08:45:00'};'2025-03-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('month');{s: '2025-03-17'};'2025-03-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('month');{s: '2024-05-31 06:07:08'};'2024-05-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('month');{s: 1700000000123};'2023-11-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('q');{s: '2023-02-28 00:00:01'};'2023-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('q');{s: '2024-05-31 06:07:08'};'2024-04-01T00:00:00-05:00';bug: the month is moved before the day is reset, April 31 does not exist +d(s, 'Etc/GMT+5').startOf('q');{s: '2025-08-31 18:00'};'2025-07-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('q');{s: '2024-07-31 13:14:15'};'2024-07-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('q');{s: true};'Invalid date' +d(s, 'Etc/GMT+5').endOf('quarter');{s: '2024-09-30 21:45'};'2024-09-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('quarter');{s: '2024-05-31 06:07:08'};'2024-06-30T23:59:59-05:00';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Etc/GMT+5').endOf('quarter');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59-05:00';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Etc/GMT+5').endOf('quarter');{s: '2024-07-31 13:14:15'};'2024-09-30T23:59:59-05:00';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Etc/GMT+5').endOf('quarter');{s: '2023-02-30'};'Invalid date' +d(s, 'Etc/GMT+5').startOf('year');{s: '2025-06-30 12:00'};'2025-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('year');{s: '2025-03-16 08:45:00'};'2025-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('year');{s: '2025-03-17'};'2025-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('year');{s: '2024-05-31 06:07:08'};'2024-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('year');{s: 1735689599999};'2024-01-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('year');{s: '2023-02-28 00:00:01'};'2023-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('year');{s: '2024-12-30 00:00:00'};'2024-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('year');{s: '2025-11-30 23:59:59'};'2025-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('year');{s: '2024-07-31 13:14:15'};'2024-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').endOf('year');{s: ''};'Invalid date' +# startOf/endOf matrix in Europe/Berlin +d(s, 'Europe/Berlin').startOf('s');{s: '2025-03-30 01:30'};'2025-03-30T01:30:00+01:00' +d(s, 'Europe/Berlin').startOf('s');{s: '2025-10-27 00:30'};'2025-10-27T00:30:00+01:00' +d(s, 'Europe/Berlin').startOf('s');{s: '2025-10-26 12:00'};'2025-10-26T12:00:00+01:00' +d(s, 'Europe/Berlin').startOf('s');{s: '2024-09-30 21:45'};'2024-09-30T21:45:00+02:00' +d(s, 'Europe/Berlin').startOf('s');{s: null};'Invalid date' +d(s, 'Europe/Berlin').endOf('second');{s: '2025-03-30 03:00'};'2025-03-30T03:00:00+02:00' +d(s, 'Europe/Berlin').endOf('second');{s: '2025-03-29 12:00'};'2025-03-29T12:00:00+01:00' +d(s, 'Europe/Berlin').endOf('second');{s: '2025-03-30 01:30'};'2025-03-30T01:30:00+01:00' +d(s, 'Europe/Berlin').endOf('second');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('second');{};'Invalid date' +d(s, 'Europe/Berlin').startOf('minute');{s: '2025-03-30 12:00'};'2025-03-30T12:00:00+02:00' +d(s, 'Europe/Berlin').startOf('minute');{s: '2025-10-25 23:30'};'2025-10-25T23:30:00+02:00' +d(s, 'Europe/Berlin').startOf('minute');{s: '2025-03-30 03:00'};'2025-03-30T03:00:00+02:00' +d(s, 'Europe/Berlin').startOf('minute');{s: '2024-03-31'};'2024-03-31T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('minute');{s: 'nope'};'Invalid date' +d(s, 'Europe/Berlin').endOf('minute');{s: '2025-10-26 12:00'};'2025-10-26T12:00:59+01:00' +d(s, 'Europe/Berlin').endOf('minute');{s: '2025-10-26 04:00'};'2025-10-26T04:00:59+01:00' +d(s, 'Europe/Berlin').endOf('minute');{s: '2025-03-30 12:00'};'2025-03-30T12:00:59+02:00' +d(s, 'Europe/Berlin').endOf('minute');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:59+01:00' +d(s, 'Europe/Berlin').endOf('minute');{s: 1700000000123};'2023-11-14T23:13:59+01:00' +d(s, 'Europe/Berlin').startOf('h');{s: '2025-03-30 01:30'};'2025-03-30T01:00:00+01:00' +d(s, 'Europe/Berlin').startOf('h');{s: '2025-10-27 00:30'};'2025-10-27T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('h');{s: '2025-10-26 12:00'};'2025-10-26T12:00:00+01:00' +d(s, 'Europe/Berlin').startOf('h');{s: '2024-05-31 06:07:08'};'2024-05-31T06:00:00+02:00' +d(s, 'Europe/Berlin').startOf('h');{s: true};'Invalid date' +d(s, 'Europe/Berlin').endOf('hour');{s: '2025-03-30 03:00'};'2025-03-30T03:59:59+02:00' +d(s, 'Europe/Berlin').endOf('hour');{s: '2025-03-29 12:00'};'2025-03-29T12:59:59+01:00' +d(s, 'Europe/Berlin').endOf('hour');{s: '2025-03-30 01:30'};'2025-03-30T01:59:59+01:00' +d(s, 'Europe/Berlin').endOf('hour');{s: '2023-02-28 00:00:01'};'2023-02-28T00:59:59+01:00' +d(s, 'Europe/Berlin').endOf('hour');{s: '2023-02-30'};'Invalid date' +d(s, 'Europe/Berlin').startOf('d');{s: '2025-03-30 12:00'};'2025-03-30T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('d');{s: '2025-10-25 23:30'};'2025-10-25T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('d');{s: '2025-03-30 03:00'};'2025-03-30T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('d');{s: '2025-11-30 23:59:59'};'2025-11-30T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('d');{s: 1735689599999};'2025-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-10-26 12:00'};'2025-10-26T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-10-26 04:00'};'2025-10-26T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-03-30 12:00'};'2025-03-30T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('day');{s: '2025-01-01'};'2025-01-01T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('day');{s: ''};'Invalid date' +d(s, 'Europe/Berlin').startOf('week');{s: '2025-03-30 01:30'};'2025-03-24T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('week');{s: '2025-10-27 00:30'};'2025-10-27T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('week');{s: '2025-10-26 12:00'};'2025-10-20T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('week');{s: '2024-01-31 10:20:30'};'2024-01-29T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('week');{s: null};'Invalid date' +d(s, 'Europe/Berlin').endOf('week');{s: '2025-03-30 03:00'};'2025-03-30T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('week');{s: '2025-03-29 12:00'};'2025-03-30T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('week');{s: '2025-03-30 01:30'};'2025-03-30T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('week');{s: '2023-12-31 23:30:15'};'2023-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('week');{};'Invalid date' +d(s, 'Europe/Berlin').startOf('M');{s: '2025-03-30 12:00'};'2025-03-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('M');{s: '2025-10-25 23:30'};'2025-10-01T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('M');{s: '2025-03-30 03:00'};'2025-03-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('M');{s: '2025-06-30 12:00'};'2025-06-01T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('M');{s: 'nope'};'Invalid date' +d(s, 'Europe/Berlin').endOf('month');{s: '2025-10-26 12:00'};'2025-10-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('month');{s: '2025-10-26 04:00'};'2025-10-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('month');{s: '2025-03-30 12:00'};'2025-03-31T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('month');{s: '2025-03-17'};'2025-03-31T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('month');{s: 1700000000123};'2023-11-30T23:59:59+01:00' +d(s, 'Europe/Berlin').startOf('q');{s: '2025-03-30 01:30'};'2025-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('q');{s: '2025-10-27 00:30'};'2025-10-01T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('q');{s: '2025-10-26 12:00'};'2025-10-01T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('q');{s: '2025-08-31 18:00'};'2025-07-01T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('q');{s: true};'Invalid date' +d(s, 'Europe/Berlin').endOf('quarter');{s: '2025-03-30 03:00'};'2025-03-31T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('quarter');{s: '2025-03-29 12:00'};'2025-03-31T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('quarter');{s: '2025-03-30 01:30'};'2025-03-31T23:59:59+02:00' +d(s, 'Europe/Berlin').endOf('quarter');{s: '2024-12-30 00:00:00'};'2024-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('quarter');{s: '2023-02-30'};'Invalid date' +d(s, 'Europe/Berlin').startOf('year');{s: '2025-03-30 12:00'};'2025-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('year');{s: '2025-10-25 23:30'};'2025-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('year');{s: '2025-03-30 03:00'};'2025-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('year');{s: '2024-07-31 13:14:15'};'2024-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').startOf('year');{s: 1735689599999};'2025-01-01T00:00:00+01:00' +d(s, 'Europe/Berlin').endOf('year');{s: '2025-10-26 12:00'};'2025-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('year');{s: '2025-10-26 04:00'};'2025-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('year');{s: '2025-03-30 12:00'};'2025-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('year');{s: '2024-09-30 21:45'};'2024-12-31T23:59:59+01:00' +d(s, 'Europe/Berlin').endOf('year');{s: ''};'Invalid date' +# startOf/endOf matrix in America/New_York +d(s, 'America/New_York').startOf('s');{s: '2025-03-09 03:15'};'2025-03-09T03:15:00-04:00' +d(s, 'America/New_York').startOf('s');{s: '2025-11-02 00:15'};'2025-11-02T00:15:00-04:00' +d(s, 'America/New_York').startOf('s');{s: '2025-11-02 12:00'};'2025-11-02T12:00:00-05:00' +d(s, 'America/New_York').startOf('s');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59-05:00' +d(s, 'America/New_York').startOf('s');{s: null};'Invalid date' +d(s, 'America/New_York').endOf('second');{s: '2025-03-10 00:30'};'2025-03-10T00:30:00-04:00' +d(s, 'America/New_York').endOf('second');{s: '2025-03-08 23:30'};'2025-03-08T23:30:00-05:00' +d(s, 'America/New_York').endOf('second');{s: '2025-03-09 03:15'};'2025-03-09T03:15:00-04:00' +d(s, 'America/New_York').endOf('second');{s: '2024-03-31'};'2024-03-31T00:00:00-04:00' +d(s, 'America/New_York').endOf('second');{};'Invalid date' +d(s, 'America/New_York').startOf('minute');{s: '2025-03-09 12:00'};'2025-03-09T12:00:00-04:00' +d(s, 'America/New_York').startOf('minute');{s: '2025-11-01 18:00'};'2025-11-01T18:00:00-04:00' +d(s, 'America/New_York').startOf('minute');{s: '2025-03-10 00:30'};'2025-03-10T00:30:00-04:00' +d(s, 'America/New_York').startOf('minute');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:00-04:00' +d(s, 'America/New_York').startOf('minute');{s: 'nope'};'Invalid date' +d(s, 'America/New_York').endOf('minute');{s: '2025-11-02 12:00'};'2025-11-02T12:00:59-05:00' +d(s, 'America/New_York').endOf('minute');{s: '2025-11-02 03:00'};'2025-11-02T03:00:59-05:00' +d(s, 'America/New_York').endOf('minute');{s: '2025-03-09 12:00'};'2025-03-09T12:00:59-04:00' +d(s, 'America/New_York').endOf('minute');{s: '2024-05-31 06:07:08'};'2024-05-31T06:07:59-04:00' +d(s, 'America/New_York').endOf('minute');{s: 1700000000123};'2023-11-14T17:13:59-05:00' +d(s, 'America/New_York').startOf('h');{s: '2025-03-09 03:15'};'2025-03-09T03:00:00-04:00' +d(s, 'America/New_York').startOf('h');{s: '2025-11-02 00:15'};'2025-11-02T00:00:00-04:00' +d(s, 'America/New_York').startOf('h');{s: '2025-11-02 12:00'};'2025-11-02T12:00:00-05:00' +d(s, 'America/New_York').startOf('h');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:00-05:00' +d(s, 'America/New_York').startOf('h');{s: true};'Invalid date' +d(s, 'America/New_York').endOf('hour');{s: '2025-03-10 00:30'};'2025-03-10T00:59:59-04:00' +d(s, 'America/New_York').endOf('hour');{s: '2025-03-08 23:30'};'2025-03-08T23:59:59-05:00' +d(s, 'America/New_York').endOf('hour');{s: '2025-03-09 03:15'};'2025-03-09T03:59:59-04:00' +d(s, 'America/New_York').endOf('hour');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59-05:00' +d(s, 'America/New_York').endOf('hour');{s: '2023-02-30'};'Invalid date' +d(s, 'America/New_York').startOf('d');{s: '2025-03-09 12:00'};'2025-03-09T00:00:00-05:00' +d(s, 'America/New_York').startOf('d');{s: '2025-11-01 18:00'};'2025-11-01T00:00:00-04:00' +d(s, 'America/New_York').startOf('d');{s: '2025-03-10 00:30'};'2025-03-10T00:00:00-04:00' +d(s, 'America/New_York').startOf('d');{s: '2025-01-01'};'2025-01-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('d');{s: 1735689599999};'2024-12-31T00:00:00-05:00' +d(s, 'America/New_York').endOf('day');{s: '2025-11-02 12:00'};'2025-11-02T23:59:59-05:00' +d(s, 'America/New_York').endOf('day');{s: '2025-11-02 03:00'};'2025-11-02T23:59:59-05:00' +d(s, 'America/New_York').endOf('day');{s: '2025-03-09 12:00'};'2025-03-09T23:59:59-04:00' +d(s, 'America/New_York').endOf('day');{s: '2024-01-31 10:20:30'};'2024-01-31T23:59:59-05:00' +d(s, 'America/New_York').endOf('day');{s: ''};'Invalid date' +d(s, 'America/New_York').startOf('week');{s: '2025-03-09 03:15'};'2025-03-03T00:00:00-05:00' +d(s, 'America/New_York').startOf('week');{s: '2025-11-02 00:15'};'2025-10-27T00:00:00-04:00' +d(s, 'America/New_York').startOf('week');{s: '2025-11-02 12:00'};'2025-10-27T00:00:00-04:00' +d(s, 'America/New_York').startOf('week');{s: '2023-12-31 23:30:15'};'2023-12-25T00:00:00-05:00' +d(s, 'America/New_York').startOf('week');{s: null};'Invalid date' +d(s, 'America/New_York').endOf('week');{s: '2025-03-10 00:30'};'2025-03-16T23:59:59-04:00' +d(s, 'America/New_York').endOf('week');{s: '2025-03-08 23:30'};'2025-03-09T23:59:59-04:00' +d(s, 'America/New_York').endOf('week');{s: '2025-03-09 03:15'};'2025-03-09T23:59:59-04:00' +d(s, 'America/New_York').endOf('week');{s: '2025-06-30 12:00'};'2025-07-06T23:59:59-04:00' +d(s, 'America/New_York').endOf('week');{};'Invalid date' +d(s, 'America/New_York').startOf('M');{s: '2025-03-09 12:00'};'2025-03-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('M');{s: '2025-11-01 18:00'};'2025-11-01T00:00:00-04:00' +d(s, 'America/New_York').startOf('M');{s: '2025-03-10 00:30'};'2025-03-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('M');{s: '2025-03-17'};'2025-03-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('M');{s: 'nope'};'Invalid date' +d(s, 'America/New_York').endOf('month');{s: '2025-11-02 12:00'};'2025-11-30T23:59:59-05:00' +d(s, 'America/New_York').endOf('month');{s: '2025-11-02 03:00'};'2025-11-30T23:59:59-05:00' +d(s, 'America/New_York').endOf('month');{s: '2025-03-09 12:00'};'2025-03-31T23:59:59-04:00' +d(s, 'America/New_York').endOf('month');{s: '2025-08-31 18:00'};'2025-08-31T23:59:59-04:00' +d(s, 'America/New_York').endOf('month');{s: 1700000000123};'2023-11-30T23:59:59-05:00' +d(s, 'America/New_York').startOf('q');{s: '2025-03-09 03:15'};'2025-01-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('q');{s: '2025-11-02 00:15'};'2025-10-01T00:00:00-04:00' +d(s, 'America/New_York').startOf('q');{s: '2025-11-02 12:00'};'2025-10-01T00:00:00-04:00' +d(s, 'America/New_York').startOf('q');{s: '2024-12-30 00:00:00'};'2024-10-01T00:00:00-04:00' +d(s, 'America/New_York').startOf('q');{s: true};'Invalid date' +d(s, 'America/New_York').endOf('quarter');{s: '2025-03-10 00:30'};'2025-03-31T23:59:59-04:00' +d(s, 'America/New_York').endOf('quarter');{s: '2025-03-08 23:30'};'2025-03-31T23:59:59-04:00' +d(s, 'America/New_York').endOf('quarter');{s: '2025-03-09 03:15'};'2025-03-31T23:59:59-04:00' +d(s, 'America/New_York').endOf('quarter');{s: '2024-07-31 13:14:15'};'2024-09-30T23:59:59-04:00';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'America/New_York').endOf('quarter');{s: '2023-02-30'};'Invalid date' +d(s, 'America/New_York').startOf('year');{s: '2025-03-09 12:00'};'2025-01-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('year');{s: '2025-11-01 18:00'};'2025-01-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('year');{s: '2025-03-10 00:30'};'2025-01-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('year');{s: '2024-09-30 21:45'};'2024-01-01T00:00:00-05:00' +d(s, 'America/New_York').startOf('year');{s: 1735689599999};'2024-01-01T00:00:00-05:00' +d(s, 'America/New_York').endOf('year');{s: '2025-11-02 12:00'};'2025-12-31T23:59:59-05:00' +d(s, 'America/New_York').endOf('year');{s: '2025-11-02 03:00'};'2025-12-31T23:59:59-05:00' +d(s, 'America/New_York').endOf('year');{s: '2025-03-09 12:00'};'2025-12-31T23:59:59-05:00' +d(s, 'America/New_York').endOf('year');{s: '2024-02-29 23:59:59'};'2024-12-31T23:59:59-05:00' +d(s, 'America/New_York').endOf('year');{s: ''};'Invalid date' +# startOf/endOf matrix in Asia/Kolkata +d(s, 'Asia/Kolkata').startOf('s');{s: '2024-03-31'};'2024-03-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('s');{s: '2025-06-30 12:00'};'2025-06-30T12:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('s');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:00+05:30' +d(s, 'Asia/Kolkata').startOf('s');{s: '2025-03-17'};'2025-03-17T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('s');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').endOf('second');{s: '2025-08-31 18:00'};'2025-08-31T18:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('second');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:01+05:30' +d(s, 'Asia/Kolkata').endOf('second');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('second');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('second');{};'Invalid date' +d(s, 'Asia/Kolkata').startOf('minute');{s: '2025-01-01'};'2025-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('minute');{s: '2024-09-30 21:45'};'2024-09-30T21:45:00+05:30' +d(s, 'Asia/Kolkata').startOf('minute');{s: '2024-01-31 10:20:30'};'2024-01-31T10:20:00+05:30' +d(s, 'Asia/Kolkata').startOf('minute');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:00+05:30' +d(s, 'Asia/Kolkata').startOf('minute');{s: 'nope'};'Invalid date' +d(s, 'Asia/Kolkata').endOf('minute');{s: '2024-03-31'};'2024-03-31T00:00:59+05:30' +d(s, 'Asia/Kolkata').endOf('minute');{s: '2025-06-30 12:00'};'2025-06-30T12:00:59+05:30' +d(s, 'Asia/Kolkata').endOf('minute');{s: '2025-03-16 08:45:00'};'2025-03-16T08:45:59+05:30' +d(s, 'Asia/Kolkata').endOf('minute');{s: '2025-03-17'};'2025-03-17T00:00:59+05:30' +d(s, 'Asia/Kolkata').endOf('minute');{s: 1700000000123};'2023-11-15T03:43:59+05:30' +d(s, 'Asia/Kolkata').startOf('h');{s: '2025-08-31 18:00'};'2025-08-31T18:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('h');{s: '2023-02-28 00:00:01'};'2023-02-28T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('h');{s: '2024-12-30 00:00:00'};'2024-12-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('h');{s: '2025-11-30 23:59:59'};'2025-11-30T23:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('h');{s: true};'Invalid date' +d(s, 'Asia/Kolkata').endOf('hour');{s: '2025-01-01'};'2025-01-01T00:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('hour');{s: '2024-09-30 21:45'};'2024-09-30T21:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('hour');{s: '2024-01-31 10:20:30'};'2024-01-31T10:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('hour');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('hour');{s: '2023-02-30'};'Invalid date' +d(s, 'Asia/Kolkata').startOf('d');{s: '2024-03-31'};'2024-03-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('d');{s: '2025-06-30 12:00'};'2025-06-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('d');{s: '2025-03-16 08:45:00'};'2025-03-16T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('d');{s: '2025-03-17'};'2025-03-17T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('d');{s: 1735689599999};'2025-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('day');{s: '2025-08-31 18:00'};'2025-08-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('day');{s: '2023-02-28 00:00:01'};'2023-02-28T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('day');{s: '2024-12-30 00:00:00'};'2024-12-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('day');{s: '2025-11-30 23:59:59'};'2025-11-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('day');{s: ''};'Invalid date' +d(s, 'Asia/Kolkata').startOf('week');{s: '2025-01-01'};'2024-12-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('week');{s: '2024-09-30 21:45'};'2024-09-30T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('week');{s: '2024-01-31 10:20:30'};'2024-01-29T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('week');{s: '2024-02-29 23:59:59'};'2024-02-26T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('week');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').endOf('week');{s: '2024-03-31'};'2024-03-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('week');{s: '2025-06-30 12:00'};'2025-07-06T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('week');{s: '2025-03-16 08:45:00'};'2025-03-16T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('week');{s: '2025-03-17'};'2025-03-23T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('week');{};'Invalid date' +d(s, 'Asia/Kolkata').startOf('M');{s: '2025-08-31 18:00'};'2025-08-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M');{s: '2023-02-28 00:00:01'};'2023-02-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M');{s: '2024-12-30 00:00:00'};'2024-12-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M');{s: '2025-11-30 23:59:59'};'2025-11-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M');{s: 'nope'};'Invalid date' +d(s, 'Asia/Kolkata').endOf('month');{s: '2025-01-01'};'2025-01-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('month');{s: '2024-09-30 21:45'};'2024-09-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('month');{s: '2024-01-31 10:20:30'};'2024-01-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('month');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('month');{s: 1700000000123};'2023-11-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').startOf('q');{s: '2024-03-31'};'2024-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('q');{s: '2024-05-31 06:07:08'};'2024-04-01T00:00:00+05:30';bug: the month is moved before the day is reset, April 31 does not exist +d(s, 'Asia/Kolkata').startOf('q');{s: '2025-08-31 18:00'};'2025-07-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('q');{s: '2024-07-31 13:14:15'};'2024-07-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('q');{s: true};'Invalid date' +d(s, 'Asia/Kolkata').endOf('quarter');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59+05:30';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Asia/Kolkata').endOf('quarter');{s: '2024-05-31 06:07:08'};'2024-06-30T23:59:59+05:30';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Asia/Kolkata').endOf('quarter');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59+05:30';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Asia/Kolkata').endOf('quarter');{s: '2024-07-31 13:14:15'};'2024-09-30T23:59:59+05:30';bug: the month is moved to the quarter's last month before the day is set, the 31st does not exist there so the result is invalid +d(s, 'Asia/Kolkata').endOf('quarter');{s: '2023-02-30'};'Invalid date' +d(s, 'Asia/Kolkata').startOf('year');{s: '2025-01-01'};'2025-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('year');{s: '2024-09-30 21:45'};'2024-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('year');{s: '2024-01-31 10:20:30'};'2024-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('year');{s: '2024-02-29 23:59:59'};'2024-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('year');{s: 1735689599999};'2025-01-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('year');{s: '2024-03-31'};'2024-12-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('year');{s: '2025-06-30 12:00'};'2025-12-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('year');{s: '2025-03-16 08:45:00'};'2025-12-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('year');{s: '2025-03-17'};'2025-12-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').endOf('year');{s: ''};'Invalid date' +# startOf/endOf observed through timestamp (the .999 of endOf is visible) +d(s).endOf('minute').timestamp() - d(s).startOf('minute').timestamp();{s: '2025-08-31 18:00'};59999 +d(s).endOf('minute').timestamp() - d(s).startOf('minute').timestamp();{s: '2023-02-28 00:00:01'};59999 +d(s).endOf('minute').timestamp() - d(s).startOf('minute').timestamp();{s: '2024-12-30 00:00:00'};59999 +d(s).endOf('day').timestamp() - d(s).startOf('day').timestamp();{s: '2024-07-31 13:14:15'};86399999 +d(s).endOf('day').timestamp() - d(s).startOf('day').timestamp();{s: '2025-01-01'};86399999 +d(s).endOf('day').timestamp() - d(s).startOf('day').timestamp();{s: '2024-09-30 21:45'};86399999 +d(s).endOf('month').timestamp() - d(s).startOf('month').timestamp();{s: '2024-02-29 23:59:59'};2505599999 +d(s).endOf('month').timestamp() - d(s).startOf('month').timestamp();{s: '2023-12-31 23:30:15'};2678399999 +d(s).endOf('month').timestamp() - d(s).startOf('month').timestamp();{s: '2024-03-31'};2678399999 +d(s).endOf('year').timestamp() - d(s).startOf('year').timestamp();{s: '2025-03-16 08:45:00'};31535999999 +d(s).endOf('year').timestamp() - d(s).startOf('year').timestamp();{s: '2025-03-17'};31535999999 +d(s).endOf('year').timestamp() - d(s).startOf('year').timestamp();{s: '2024-05-31 06:07:08'};31622399999 +d(s, 'Etc/GMT+5').endOf('minute').timestamp() - d(s, 'Etc/GMT+5').startOf('minute').timestamp();{s: '2023-02-28 00:00:01'};59999 +d(s, 'Etc/GMT+5').endOf('minute').timestamp() - d(s, 'Etc/GMT+5').startOf('minute').timestamp();{s: '2024-12-30 00:00:00'};59999 +d(s, 'Etc/GMT+5').endOf('minute').timestamp() - d(s, 'Etc/GMT+5').startOf('minute').timestamp();{s: '2025-11-30 23:59:59'};59999 +d(s, 'Etc/GMT+5').endOf('day').timestamp() - d(s, 'Etc/GMT+5').startOf('day').timestamp();{s: '2025-01-01'};86399999 +d(s, 'Etc/GMT+5').endOf('day').timestamp() - d(s, 'Etc/GMT+5').startOf('day').timestamp();{s: '2024-09-30 21:45'};86399999 +d(s, 'Etc/GMT+5').endOf('day').timestamp() - d(s, 'Etc/GMT+5').startOf('day').timestamp();{s: '2024-01-31 10:20:30'};86399999 +d(s, 'Etc/GMT+5').endOf('month').timestamp() - d(s, 'Etc/GMT+5').startOf('month').timestamp();{s: '2023-12-31 23:30:15'};2678399999 +d(s, 'Etc/GMT+5').endOf('month').timestamp() - d(s, 'Etc/GMT+5').startOf('month').timestamp();{s: '2024-03-31'};2678399999 +d(s, 'Etc/GMT+5').endOf('month').timestamp() - d(s, 'Etc/GMT+5').startOf('month').timestamp();{s: '2025-06-30 12:00'};2591999999 +d(s, 'Etc/GMT+5').endOf('year').timestamp() - d(s, 'Etc/GMT+5').startOf('year').timestamp();{s: '2025-03-17'};31535999999 +d(s, 'Etc/GMT+5').endOf('year').timestamp() - d(s, 'Etc/GMT+5').startOf('year').timestamp();{s: '2024-05-31 06:07:08'};31622399999 +d(s, 'Etc/GMT+5').endOf('year').timestamp() - d(s, 'Etc/GMT+5').startOf('year').timestamp();{s: '2025-08-31 18:00'};31535999999 +d(s, 'Asia/Kolkata').endOf('minute').timestamp() - d(s, 'Asia/Kolkata').startOf('minute').timestamp();{s: '2024-12-30 00:00:00'};59999 +d(s, 'Asia/Kolkata').endOf('minute').timestamp() - d(s, 'Asia/Kolkata').startOf('minute').timestamp();{s: '2025-11-30 23:59:59'};59999 +d(s, 'Asia/Kolkata').endOf('minute').timestamp() - d(s, 'Asia/Kolkata').startOf('minute').timestamp();{s: '2024-07-31 13:14:15'};59999 +d(s, 'Asia/Kolkata').endOf('day').timestamp() - d(s, 'Asia/Kolkata').startOf('day').timestamp();{s: '2024-09-30 21:45'};86399999 +d(s, 'Asia/Kolkata').endOf('day').timestamp() - d(s, 'Asia/Kolkata').startOf('day').timestamp();{s: '2024-01-31 10:20:30'};86399999 +d(s, 'Asia/Kolkata').endOf('day').timestamp() - d(s, 'Asia/Kolkata').startOf('day').timestamp();{s: '2024-02-29 23:59:59'};86399999 +d(s, 'Asia/Kolkata').endOf('month').timestamp() - d(s, 'Asia/Kolkata').startOf('month').timestamp();{s: '2024-03-31'};2678399999 +d(s, 'Asia/Kolkata').endOf('month').timestamp() - d(s, 'Asia/Kolkata').startOf('month').timestamp();{s: '2025-06-30 12:00'};2591999999 +d(s, 'Asia/Kolkata').endOf('month').timestamp() - d(s, 'Asia/Kolkata').startOf('month').timestamp();{s: '2025-03-16 08:45:00'};2678399999 +d(s, 'Asia/Kolkata').endOf('year').timestamp() - d(s, 'Asia/Kolkata').startOf('year').timestamp();{s: '2024-05-31 06:07:08'};31622399999 +d(s, 'Asia/Kolkata').endOf('year').timestamp() - d(s, 'Asia/Kolkata').startOf('year').timestamp();{s: '2025-08-31 18:00'};31535999999 +d(s, 'Asia/Kolkata').endOf('year').timestamp() - d(s, 'Asia/Kolkata').startOf('year').timestamp();{s: '2023-02-28 00:00:01'};31535999999 diff --git a/core/expression/tests/spec/standard/16-03-diff-matrix.csv b/core/expression/tests/spec/standard/16-03-diff-matrix.csv new file mode 100644 index 00000000..187cc7b9 --- /dev/null +++ b/core/expression/tests/spec/standard/16-03-diff-matrix.csv @@ -0,0 +1,241 @@ +expression (string);input (json 5);output (json 5);note +# diff to the fixed anchor 2024-02-29 12:00 in UTC +d(s).diff(d('2024-02-29 12:00'), 'second');{s: '2024-05-31 06:07:08'};7927628 +d(s).diff(d('2024-02-29 12:00'), 'second');{s: '2025-08-31 18:00'};47455200 +d(s).diff(d('2024-02-29 12:00'), 'second');{s: '2023-02-28 00:00:01'};-31665599 +d(s).diff(d('2024-02-29 12:00'), 'second');{s: '2024-12-30 00:00:00'};26308800 +d(s).diff(d('2024-02-29 12:00'), 'second');{s: null};null +d(s).diff(d('2024-02-29 12:00'), 'minute');{s: '2024-07-31 13:14:15'};220394 +d(s).diff(d('2024-02-29 12:00'), 'minute');{s: '2025-01-01'};441360 +d(s).diff(d('2024-02-29 12:00'), 'minute');{s: '2024-09-30 21:45'};308745 +d(s).diff(d('2024-02-29 12:00'), 'minute');{s: '2024-01-31 10:20:30'};-41859 +d(s).diff(d('2024-02-29 12:00'), 'minute');{};null +d(s).diff(d('2024-02-29 12:00'), 'hour');{s: '2023-12-31 23:30:15'};-1428 +d(s).diff(d('2024-02-29 12:00'), 'hour');{s: '2024-03-31'};732 +d(s).diff(d('2024-02-29 12:00'), 'hour');{s: '2025-06-30 12:00'};11688 +d(s).diff(d('2024-02-29 12:00'), 'hour');{s: '2025-03-16 08:45:00'};9140 +d(s).diff(d('2024-02-29 12:00'), 'hour');{s: 'nope'};null +d(s).diff(d('2024-02-29 12:00'), 'day');{s: '2024-05-31 06:07:08'};91 +d(s).diff(d('2024-02-29 12:00'), 'day');{s: '2025-08-31 18:00'};549 +d(s).diff(d('2024-02-29 12:00'), 'day');{s: '2023-02-28 00:00:01'};-366 +d(s).diff(d('2024-02-29 12:00'), 'day');{s: '2024-12-30 00:00:00'};304 +d(s).diff(d('2024-02-29 12:00'), 'day');{s: 1700000000123};-106 +d(s).diff(d('2024-02-29 12:00'), 'week');{s: '2024-07-31 13:14:15'};21 +d(s).diff(d('2024-02-29 12:00'), 'week');{s: '2025-01-01'};43 +d(s).diff(d('2024-02-29 12:00'), 'week');{s: '2024-09-30 21:45'};30 +d(s).diff(d('2024-02-29 12:00'), 'week');{s: '2024-01-31 10:20:30'};-4 +d(s).diff(d('2024-02-29 12:00'), 'week');{s: true};null +d(s).diff(d('2024-02-29 12:00'), 'month');{s: '2023-12-31 23:30:15'};-1 +d(s).diff(d('2024-02-29 12:00'), 'month');{s: '2024-03-31'};0 +d(s).diff(d('2024-02-29 12:00'), 'month');{s: '2025-06-30 12:00'};16 +d(s).diff(d('2024-02-29 12:00'), 'month');{s: '2025-03-16 08:45:00'};12 +d(s).diff(d('2024-02-29 12:00'), 'month');{s: '2023-02-30'};null +d(s).diff(d('2024-02-29 12:00'), 'quarter');{s: '2024-05-31 06:07:08'};0 +d(s).diff(d('2024-02-29 12:00'), 'quarter');{s: '2025-08-31 18:00'};6 +d(s).diff(d('2024-02-29 12:00'), 'quarter');{s: '2023-02-28 00:00:01'};-4 +d(s).diff(d('2024-02-29 12:00'), 'quarter');{s: '2024-12-30 00:00:00'};3 +d(s).diff(d('2024-02-29 12:00'), 'quarter');{s: 1735689599999};3 +d(s).diff(d('2024-02-29 12:00'), 'year');{s: '2024-07-31 13:14:15'};0 +d(s).diff(d('2024-02-29 12:00'), 'year');{s: '2025-01-01'};0 +d(s).diff(d('2024-02-29 12:00'), 'year');{s: '2024-09-30 21:45'};0 +d(s).diff(d('2024-02-29 12:00'), 'year');{s: '2024-01-31 10:20:30'};0 +d(s).diff(d('2024-02-29 12:00'), 'year');{s: ''};null +d('2024-02-29 12:00').diff(d(s), 'month');{s: '2023-12-31 23:30:15'};1 +d('2024-02-29 12:00').diff(d(s), 'month');{s: '2024-03-31'};0 +d('2024-02-29 12:00').diff(d(s), 'month');{s: '2025-06-30 12:00'};-16 +d('2024-02-29 12:00').diff(d(s), 'month');{s: '2025-03-16 08:45:00'};-12 +d(s).diff(d('2024-02-29 12:00'));{s: '2024-05-31 06:07:08'};7927628000 +d(s).diff(d('2024-02-29 12:00'));{s: '2025-08-31 18:00'};47455200000 +d(s).diff(d('2024-02-29 12:00'));{s: '2023-02-28 00:00:01'};-31665599000 +# diff to the fixed anchor 2024-01-01 in Etc/GMT+5 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'second');{s: '2025-11-30 23:59:59'};60479999 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'second');{s: '2024-07-31 13:14:15'};18364455 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'second');{s: '2025-01-01'};31622400 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'second');{s: '2024-09-30 21:45'};23665500 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'second');{s: null};null +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'minute');{s: '2024-02-29 23:59:59'};86399 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'minute');{s: '2023-12-31 23:30:15'};-29 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'minute');{s: '2024-03-31'};129600 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'minute');{s: '2025-06-30 12:00'};786960 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'minute');{};null +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'hour');{s: '2025-03-17'};10584 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'hour');{s: '2024-05-31 06:07:08'};3630 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'hour');{s: '2025-08-31 18:00'};14610 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'hour');{s: '2023-02-28 00:00:01'};-7367 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'hour');{s: 'nope'};null +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'day');{s: '2025-11-30 23:59:59'};699 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'day');{s: '2024-07-31 13:14:15'};212 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'day');{s: '2025-01-01'};366 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'day');{s: '2024-09-30 21:45'};273 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'day');{s: 1700000000123};-47 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'week');{s: '2024-02-29 23:59:59'};8 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'week');{s: '2023-12-31 23:30:15'};0 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'week');{s: '2024-03-31'};12 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'week');{s: '2025-06-30 12:00'};78 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'week');{s: true};null +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'month');{s: '2025-03-17'};14 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'month');{s: '2024-05-31 06:07:08'};4 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'month');{s: '2025-08-31 18:00'};19 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'month');{s: '2023-02-28 00:00:01'};-10 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'month');{s: '2023-02-30'};null +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'quarter');{s: '2025-11-30 23:59:59'};7 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'quarter');{s: '2024-07-31 13:14:15'};2 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'quarter');{s: '2025-01-01'};4 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'quarter');{s: '2024-09-30 21:45'};2 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'quarter');{s: 1735689599999};3 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'year');{s: '2024-02-29 23:59:59'};0 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'year');{s: '2023-12-31 23:30:15'};0 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'year');{s: '2024-03-31'};0 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'year');{s: '2025-06-30 12:00'};1 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'), 'year');{s: ''};null +d('2024-01-01', 'Etc/GMT+5').diff(d(s, 'Etc/GMT+5'), 'month');{s: '2025-03-17'};-14 +d('2024-01-01', 'Etc/GMT+5').diff(d(s, 'Etc/GMT+5'), 'month');{s: '2024-05-31 06:07:08'};-4 +d('2024-01-01', 'Etc/GMT+5').diff(d(s, 'Etc/GMT+5'), 'month');{s: '2025-08-31 18:00'};-19 +d('2024-01-01', 'Etc/GMT+5').diff(d(s, 'Etc/GMT+5'), 'month');{s: '2023-02-28 00:00:01'};10 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'));{s: '2025-11-30 23:59:59'};60479999000 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'));{s: '2024-07-31 13:14:15'};18364455000 +d(s, 'Etc/GMT+5').diff(d('2024-01-01', 'Etc/GMT+5'));{s: '2025-01-01'};31622400000 +# diff to the fixed anchor 2025-01-15 09:30 in Europe/Berlin +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'second');{s: '2025-03-29 12:00'};6316200 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'second');{s: '2025-03-30 01:30'};6364800 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'second');{s: '2025-10-27 00:30'};24591600 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'second');{s: '2024-01-31 10:20:30'};-30236970 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'second');{s: null};null +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'minute');{s: '2025-10-25 23:30'};408300 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'minute');{s: '2025-03-30 03:00'};106110 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'minute');{s: '2025-03-29 12:00'};105270 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'minute');{s: '2023-12-31 23:30:15'};-547799 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'minute');{};null +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'hour');{s: '2025-10-26 04:00'};6810 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'hour');{s: '2025-03-30 12:00'};1777 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'hour');{s: '2025-10-25 23:30'};6805 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'hour');{s: '2025-06-30 12:00'};3985 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'hour');{s: 'nope'};null +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'day');{s: '2025-10-27 00:30'};284 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'day');{s: '2025-10-26 12:00'};284 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'day');{s: '2025-10-26 04:00'};283 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'day');{s: '2025-03-17'};60 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'day');{s: 1700000000123};-427 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'week');{s: '2025-03-29 12:00'};10 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'week');{s: '2025-03-30 01:30'};10 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'week');{s: '2025-10-27 00:30'};40 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'week');{s: '2025-08-31 18:00'};32 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'week');{s: true};null +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'month');{s: '2025-10-25 23:30'};9 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'month');{s: '2025-03-30 03:00'};2 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'month');{s: '2025-03-29 12:00'};2 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'month');{s: '2024-12-30 00:00:00'};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'month');{s: '2023-02-30'};null +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'quarter');{s: '2025-10-26 04:00'};3 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'quarter');{s: '2025-03-30 12:00'};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'quarter');{s: '2025-10-25 23:30'};3 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'quarter');{s: '2024-07-31 13:14:15'};-1 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'quarter');{s: 1735689599999};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'year');{s: '2025-10-27 00:30'};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'year');{s: '2025-10-26 12:00'};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'year');{s: '2025-10-26 04:00'};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'year');{s: '2024-09-30 21:45'};0 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'), 'year');{s: ''};null +d('2025-01-15 09:30', 'Europe/Berlin').diff(d(s, 'Europe/Berlin'), 'month');{s: '2025-03-29 12:00'};-2 +d('2025-01-15 09:30', 'Europe/Berlin').diff(d(s, 'Europe/Berlin'), 'month');{s: '2025-03-30 01:30'};-2 +d('2025-01-15 09:30', 'Europe/Berlin').diff(d(s, 'Europe/Berlin'), 'month');{s: '2025-10-27 00:30'};-9 +d('2025-01-15 09:30', 'Europe/Berlin').diff(d(s, 'Europe/Berlin'), 'month');{s: '2024-02-29 23:59:59'};10 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'));{s: '2025-10-25 23:30'};24498000000 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'));{s: '2025-03-30 03:00'};6366600000 +d(s, 'Europe/Berlin').diff(d('2025-01-15 09:30', 'Europe/Berlin'));{s: '2025-03-29 12:00'};6316200000 +# diff to the fixed anchor 2025-06-01 00:00 in America/New_York +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'second');{s: '2025-03-09 03:15'};-7245900 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'second');{s: '2025-11-02 00:15'};13306500 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'second');{s: '2025-11-02 12:00'};13352400 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'second');{s: '2025-06-30 12:00'};2548800 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'second');{s: null};null +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'minute');{s: '2025-03-10 00:30'};-119490 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'minute');{s: '2025-03-08 23:30'};-120930 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'minute');{s: '2025-03-09 03:15'};-120765 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'minute');{s: '2025-03-17'};-109440 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'minute');{};null +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'hour');{s: '2025-03-09 12:00'};-2004 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'hour');{s: '2025-11-01 18:00'};3690 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'hour');{s: '2025-03-10 00:30'};-1991 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'hour');{s: '2025-08-31 18:00'};2202 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'hour');{s: 'nope'};null +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'day');{s: '2025-11-02 12:00'};154 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'day');{s: '2025-11-02 03:00'};154 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'day');{s: '2025-03-09 12:00'};-83 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'day');{s: '2024-12-30 00:00:00'};-153 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'day');{s: 1700000000123};-564 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'week');{s: '2025-03-09 03:15'};-11 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'week');{s: '2025-11-02 00:15'};22 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'week');{s: '2025-11-02 12:00'};22 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'week');{s: '2024-07-31 13:14:15'};-43 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'week');{s: true};null +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'month');{s: '2025-03-10 00:30'};-2 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'month');{s: '2025-03-08 23:30'};-2 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'month');{s: '2025-03-09 03:15'};-2 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'month');{s: '2024-09-30 21:45'};-8 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'month');{s: '2023-02-30'};null +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'quarter');{s: '2025-03-09 12:00'};0 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'quarter');{s: '2025-11-01 18:00'};1 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'quarter');{s: '2025-03-10 00:30'};0 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'quarter');{s: '2024-02-29 23:59:59'};-5 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'quarter');{s: 1735689599999};-1 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'year');{s: '2025-11-02 12:00'};0 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'year');{s: '2025-11-02 03:00'};0 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'year');{s: '2025-03-09 12:00'};0 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'year');{s: '2024-03-31'};-1 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'), 'year');{s: ''};null +d('2025-06-01 00:00', 'America/New_York').diff(d(s, 'America/New_York'), 'month');{s: '2025-03-09 03:15'};2 +d('2025-06-01 00:00', 'America/New_York').diff(d(s, 'America/New_York'), 'month');{s: '2025-11-02 00:15'};-5 +d('2025-06-01 00:00', 'America/New_York').diff(d(s, 'America/New_York'), 'month');{s: '2025-11-02 12:00'};-5 +d('2025-06-01 00:00', 'America/New_York').diff(d(s, 'America/New_York'), 'month');{s: '2025-03-16 08:45:00'};2 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'));{s: '2025-03-10 00:30'};-7169400000 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'));{s: '2025-03-08 23:30'};-7255800000 +d(s, 'America/New_York').diff(d('2025-06-01 00:00', 'America/New_York'));{s: '2025-03-09 03:15'};-7245900000 +# diff to the fixed anchor 2023-12-31 23:59:59 in Asia/Kolkata +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'second');{s: '2025-08-31 18:00'};52596001 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'second');{s: '2023-02-28 00:00:01'};-26524798 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'second');{s: '2024-12-30 00:00:00'};31449601 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'second');{s: '2025-11-30 23:59:59'};60480000 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'second');{s: null};null +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'minute');{s: '2025-01-01'};527040 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'minute');{s: '2024-09-30 21:45'};394425 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'minute');{s: '2024-01-31 10:20:30'};43820 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'minute');{s: '2024-02-29 23:59:59'};86400 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'minute');{};null +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'hour');{s: '2024-03-31'};2160 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'hour');{s: '2025-06-30 12:00'};13116 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'hour');{s: '2025-03-16 08:45:00'};10568 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'hour');{s: '2025-03-17'};10584 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'hour');{s: 'nope'};null +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'day');{s: '2025-08-31 18:00'};608 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'day');{s: '2023-02-28 00:00:01'};-306 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'day');{s: '2024-12-30 00:00:00'};364 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'day');{s: '2025-11-30 23:59:59'};700 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'day');{s: 1700000000123};-46 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'week');{s: '2025-01-01'};52 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'week');{s: '2024-09-30 21:45'};39 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'week');{s: '2024-01-31 10:20:30'};4 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'week');{s: '2024-02-29 23:59:59'};8 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'week');{s: true};null +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'month');{s: '2024-03-31'};2 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'month');{s: '2025-06-30 12:00'};17 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'month');{s: '2025-03-16 08:45:00'};14 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'month');{s: '2025-03-17'};14 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'month');{s: '2023-02-30'};null +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'quarter');{s: '2025-08-31 18:00'};6 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'quarter');{s: '2023-02-28 00:00:01'};-3 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'quarter');{s: '2024-12-30 00:00:00'};3 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'quarter');{s: '2025-11-30 23:59:59'};7 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'quarter');{s: 1735689599999};4 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'year');{s: '2025-01-01'};1 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'year');{s: '2024-09-30 21:45'};0 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'year');{s: '2024-01-31 10:20:30'};0 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'year');{s: '2024-02-29 23:59:59'};0 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'), 'year');{s: ''};null +d('2023-12-31 23:59:59', 'Asia/Kolkata').diff(d(s, 'Asia/Kolkata'), 'month');{s: '2024-03-31'};-2 +d('2023-12-31 23:59:59', 'Asia/Kolkata').diff(d(s, 'Asia/Kolkata'), 'month');{s: '2025-06-30 12:00'};-17 +d('2023-12-31 23:59:59', 'Asia/Kolkata').diff(d(s, 'Asia/Kolkata'), 'month');{s: '2025-03-16 08:45:00'};-14 +d('2023-12-31 23:59:59', 'Asia/Kolkata').diff(d(s, 'Asia/Kolkata'), 'month');{s: '2025-03-17'};-14 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'));{s: '2025-08-31 18:00'};52596001000 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'));{s: '2023-02-28 00:00:01'};-26524798000 +d(s, 'Asia/Kolkata').diff(d('2023-12-31 23:59:59', 'Asia/Kolkata'));{s: '2024-12-30 00:00:00'};31449601000 diff --git a/core/expression/tests/spec/standard/16-04-same-before-after.csv b/core/expression/tests/spec/standard/16-04-same-before-after.csv new file mode 100644 index 00000000..e9a9f0ff --- /dev/null +++ b/core/expression/tests/spec/standard/16-04-same-before-after.csv @@ -0,0 +1,345 @@ +expression (string);input (json 5);output (json 5);note +# isSame(other, unit) with both dates in UTC +d(a).isSame(d(b), 'second');{a: '2025-03-17', b: '2025-03-23 23:59:59'};false +d(a).isSame(d(b), 'second');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a).isSame(d(b), 'second');{a: '2024-03-31', b: '2024-01-01'};false +d(a).isSame(d(b), 'second');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isSame(d(b), 'second');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'minute');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a).isSame(d(b), 'minute');{a: '2024-03-31', b: '2024-01-01'};false +d(a).isSame(d(b), 'minute');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isSame(d(b), 'minute');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a).isSame(d(b), 'minute');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'hour');{a: '2024-03-31', b: '2024-01-01'};false +d(a).isSame(d(b), 'hour');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isSame(d(b), 'hour');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a).isSame(d(b), 'hour');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};false +d(a).isSame(d(b), 'hour');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'day');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isSame(d(b), 'day');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a).isSame(d(b), 'day');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};false +d(a).isSame(d(b), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a).isSame(d(b), 'day');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'week');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};true +d(a).isSame(d(b), 'week');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a).isSame(d(b), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a).isSame(d(b), 'week');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a).isSame(d(b), 'week');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'month');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a).isSame(d(b), 'month');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a).isSame(d(b), 'month');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a).isSame(d(b), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};true +d(a).isSame(d(b), 'month');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'quarter');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a).isSame(d(b), 'quarter');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a).isSame(d(b), 'quarter');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a).isSame(d(b), 'quarter');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};true +d(a).isSame(d(b), 'quarter');{a: null, b: '2024-01-01'};false +d(a).isSame(d(b), 'year');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a).isSame(d(b), 'year');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a).isSame(d(b), 'year');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a).isSame(d(b), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};true +d(a).isSame(d(b), 'year');{a: null, b: '2024-01-01'};false +# isBefore/isAfter with a unit in UTC +d(a).isBefore(d(b), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a).isBefore(d(b), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a).isBefore(d(b), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a).isBefore(d(b), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a).isAfter(d(b), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a).isAfter(d(b), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};true +d(a).isAfter(d(b), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a).isAfter(d(b), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a).isBefore(d(b), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a).isBefore(d(b), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a).isBefore(d(b), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a).isBefore(d(b), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a).isAfter(d(b), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a).isAfter(d(b), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a).isAfter(d(b), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a).isAfter(d(b), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a).isBefore(d(b), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a).isBefore(d(b), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a).isBefore(d(b), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};true +d(a).isBefore(d(b), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a).isAfter(d(b), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a).isAfter(d(b), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a).isAfter(d(b), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isAfter(d(b), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};true +d(a).isBefore(d(b), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a).isBefore(d(b), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a).isBefore(d(b), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isBefore(d(b), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a).isAfter(d(b), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a).isAfter(d(b), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a).isAfter(d(b), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a).isAfter(d(b), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +# isSame(other, unit) with both dates in Etc/GMT+5 +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'second');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'second');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'second');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'second');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'second');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'minute');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'minute');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'minute');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'minute');{a: '2025-03-17', b: '2025-03-23 23:59:59'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'minute');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'hour');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'hour');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'hour');{a: '2025-03-17', b: '2025-03-23 23:59:59'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'hour');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'hour');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'day');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'day');{a: '2025-03-17', b: '2025-03-23 23:59:59'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'day');{a: '2024-03-31', b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'day');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'week');{a: '2025-03-17', b: '2025-03-23 23:59:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'week');{a: '2024-03-31', b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'week');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'week');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'month');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'month');{a: '2024-03-31', b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'month');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'month');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'quarter');{a: '2024-03-31', b: '2024-01-01'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'quarter');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'quarter');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'quarter');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'quarter');{a: null, b: '2024-01-01'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'year');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'year');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'year');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'Etc/GMT+5').isSame(d(b, 'Etc/GMT+5'), 'year');{a: null, b: '2024-01-01'};false +# isBefore/isAfter with a unit in Etc/GMT+5 +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};true +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};true +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};true +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Etc/GMT+5').isBefore(d(b, 'Etc/GMT+5'), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Etc/GMT+5').isAfter(d(b, 'Etc/GMT+5'), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +# isSame(other, unit) with both dates in Europe/Berlin +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'second');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'second');{a: '2025-03-30 12:00', b: '2025-03-24 00:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'second');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'second');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'second');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'minute');{a: '2025-03-30 12:00', b: '2025-03-24 00:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'minute');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'minute');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'minute');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'minute');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'hour');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'hour');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'hour');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'hour');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'hour');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'day');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'day');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'day');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'day');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'week');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'week');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'week');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'week');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'month');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'month');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-17', b: '2025-03-23 23:59:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'month');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'quarter');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'quarter');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'quarter');{a: '2025-03-17', b: '2025-03-23 23:59:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'quarter');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'quarter');{a: null, b: '2024-01-01'};false +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-17', b: '2025-03-23 23:59:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'year');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'year');{a: '2024-03-31', b: '2024-01-01'};true +d(a, 'Europe/Berlin').isSame(d(b, 'Europe/Berlin'), 'year');{a: null, b: '2024-01-01'};false +# isBefore/isAfter with a unit in Europe/Berlin +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'day');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};true +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};true +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};true +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'day');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'week');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'week');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};true +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};true +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'month');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isBefore(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'Europe/Berlin').isAfter(d(b, 'Europe/Berlin'), 'year');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +# isSame(other, unit) with both dates in America/New_York +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'second');{a: '2025-03-17', b: '2025-03-23 23:59:59'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'second');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'second');{a: '2024-03-31', b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'second');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'second');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'minute');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'minute');{a: '2024-03-31', b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'minute');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'minute');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'minute');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'hour');{a: '2024-03-31', b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'hour');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'hour');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'hour');{a: '2025-03-30 12:00', b: '2025-03-24 00:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'hour');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'day');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'day');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'day');{a: '2025-03-30 12:00', b: '2025-03-24 00:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'day');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'day');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'week');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'week');{a: '2025-03-30 12:00', b: '2025-03-24 00:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'week');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'week');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'week');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'month');{a: '2025-03-30 12:00', b: '2025-03-24 00:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'month');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'month');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'month');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'month');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'quarter');{a: '2025-11-02 12:00', b: '2025-11-02 00:15'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'quarter');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'quarter');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'quarter');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'quarter');{a: null, b: '2024-01-01'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'year');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'year');{a: '2024-12-30 00:00:00', b: '2025-01-05 12:00'};false +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'year');{a: '2024-12-30 00:00:00', b: '2024-12-31 23:59:59'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'year');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'America/New_York').isSame(d(b, 'America/New_York'), 'year');{a: null, b: '2024-01-01'};false +# isBefore/isAfter with a unit in America/New_York +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};true +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'day');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};true +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};true +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};true +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'day');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'week');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2024-02-29 23:59:59', b: '2024-03-01 00:00:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2024-03-01 00:00:00', b: '2024-02-29 23:59:59'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2023-12-31 23:30:15', b: '2023-12-31 23:30:59'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2023-12-31 23:30:59', b: '2023-12-31 23:30:15'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2025-10-26 12:00', b: '2025-10-26 23:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2025-10-26 23:00', b: '2025-10-26 12:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'week');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};true +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'month');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'month');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'month');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'month');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'month');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'month');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};true +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'month');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'month');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'year');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isBefore(d(b, 'America/New_York'), 'year');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'year');{a: '2025-03-16 08:45:00', b: '2025-03-17 00:00:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'year');{a: '2025-03-17 00:00:00', b: '2025-03-16 08:45:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'year');{a: '2024-06-30 23:59:59', b: '2024-07-01 00:00:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'year');{a: '2024-07-01 00:00:00', b: '2024-06-30 23:59:59'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'year');{a: '2025-03-09 12:00', b: '2025-03-03 08:00'};false +d(a, 'America/New_York').isAfter(d(b, 'America/New_York'), 'year');{a: '2025-03-03 08:00', b: '2025-03-09 12:00'};false diff --git a/core/expression/tests/spec/standard/16-05-format-matrix.csv b/core/expression/tests/spec/standard/16-05-format-matrix.csv new file mode 100644 index 00000000..1de4423c --- /dev/null +++ b/core/expression/tests/spec/standard/16-05-format-matrix.csv @@ -0,0 +1,208 @@ +expression (string);input (json 5);output (json 5);note +# format pattern matrix over input dates and zones +d(s).format('%Y-%m-%d');{s: '2024-02-29 23:59:59'};'2024-02-29' +d(s).format('%Y-%m-%d');{s: '2024-12-30 07:05:09'};'2024-12-30' +d(s).format('%Y-%m-%d');{s: '2025-11-02 01:30'};'2025-11-02' +d(s).format('%Y-%m-%d');{s: '2020-12-31 00:00:01'};'2020-12-31' +d(s).format('%Y-%m-%d');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%d/%m/%Y');{s: '2023-01-01'};'01/01/2023' +d(s, 'Europe/Berlin').format('%d/%m/%Y');{s: '2025-03-30 12:00'};'30/03/2025' +d(s, 'Europe/Berlin').format('%d/%m/%Y');{s: '2021-01-03 13:00'};'03/01/2021' +d(s, 'Europe/Berlin').format('%d/%m/%Y');{s: '2025-07-04 16:20'};'04/07/2025' +d(s, 'Europe/Berlin').format('%d/%m/%Y');{s: null};'Invalid date' +d(s, 'America/New_York').format('%m/%d/%y');{s: '2024-12-30 07:05:09'};'12/30/24' +d(s, 'America/New_York').format('%m/%d/%y');{s: '2025-11-02 01:30'};'11/02/25' +d(s, 'America/New_York').format('%m/%d/%y');{s: '2020-12-31 00:00:01'};'12/31/20' +d(s, 'America/New_York').format('%m/%d/%y');{s: '2024-02-29 23:59:59'};'02/29/24' +d(s, 'America/New_York').format('%m/%d/%y');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%Y%m%d');{s: '2025-03-30 12:00'};'20250330' +d(s, 'Asia/Kolkata').format('%Y%m%d');{s: '2021-01-03 13:00'};'20210103' +d(s, 'Asia/Kolkata').format('%Y%m%d');{s: '2025-07-04 16:20'};'20250704' +d(s, 'Asia/Kolkata').format('%Y%m%d');{s: '2023-01-01'};'20230101' +d(s, 'Asia/Kolkata').format('%Y%m%d');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').format('%Y-%m-%dT%H:%M:%S%:z');{s: '2025-11-02 01:30'};'2025-11-02T01:30:00-05:00' +d(s, 'Etc/GMT+5').format('%Y-%m-%dT%H:%M:%S%:z');{s: '2020-12-31 00:00:01'};'2020-12-31T00:00:01-05:00' +d(s, 'Etc/GMT+5').format('%Y-%m-%dT%H:%M:%S%:z');{s: '2024-02-29 23:59:59'};'2024-02-29T23:59:59-05:00' +d(s, 'Etc/GMT+5').format('%Y-%m-%dT%H:%M:%S%:z');{s: '2024-12-30 07:05:09'};'2024-12-30T07:05:09-05:00' +d(s, 'Etc/GMT+5').format('%Y-%m-%dT%H:%M:%S%:z');{s: null};'Invalid date' +d(s).format('%Y-%m-%d %H:%M:%S %z');{s: '2021-01-03 13:00'};'2021-01-03 13:00:00 +0000' +d(s).format('%Y-%m-%d %H:%M:%S %z');{s: '2025-07-04 16:20'};'2025-07-04 16:20:00 +0000' +d(s).format('%Y-%m-%d %H:%M:%S %z');{s: '2023-01-01'};'2023-01-01 00:00:00 +0000' +d(s).format('%Y-%m-%d %H:%M:%S %z');{s: '2025-03-30 12:00'};'2025-03-30 12:00:00 +0000' +d(s).format('%Y-%m-%d %H:%M:%S %z');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%A, %B %-d, %Y');{s: '2020-12-31 00:00:01'};'Thursday, December 31, 2020' +d(s, 'Europe/Berlin').format('%A, %B %-d, %Y');{s: '2024-02-29 23:59:59'};'Thursday, February 29, 2024' +d(s, 'Europe/Berlin').format('%A, %B %-d, %Y');{s: '2024-12-30 07:05:09'};'Monday, December 30, 2024' +d(s, 'Europe/Berlin').format('%A, %B %-d, %Y');{s: '2025-11-02 01:30'};'Sunday, November 2, 2025' +d(s, 'Europe/Berlin').format('%A, %B %-d, %Y');{s: null};'Invalid date' +d(s, 'America/New_York').format('%a %d %b %Y');{s: '2025-07-04 16:20'};'Fri 04 Jul 2025' +d(s, 'America/New_York').format('%a %d %b %Y');{s: '2023-01-01'};'Sun 01 Jan 2023' +d(s, 'America/New_York').format('%a %d %b %Y');{s: '2025-03-30 12:00'};'Sun 30 Mar 2025' +d(s, 'America/New_York').format('%a %d %b %Y');{s: '2021-01-03 13:00'};'Sun 03 Jan 2021' +d(s, 'America/New_York').format('%a %d %b %Y');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%-d.%-m.%Y');{s: '2024-02-29 23:59:59'};'29.2.2024' +d(s, 'Asia/Kolkata').format('%-d.%-m.%Y');{s: '2024-12-30 07:05:09'};'30.12.2024' +d(s, 'Asia/Kolkata').format('%-d.%-m.%Y');{s: '2025-11-02 01:30'};'2.11.2025' +d(s, 'Asia/Kolkata').format('%-d.%-m.%Y');{s: '2020-12-31 00:00:01'};'31.12.2020' +d(s, 'Asia/Kolkata').format('%-d.%-m.%Y');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').format('%I:%M %p');{s: '2023-01-01'};'12:00 AM' +d(s, 'Etc/GMT+5').format('%I:%M %p');{s: '2025-03-30 12:00'};'12:00 PM' +d(s, 'Etc/GMT+5').format('%I:%M %p');{s: '2021-01-03 13:00'};'01:00 PM' +d(s, 'Etc/GMT+5').format('%I:%M %p');{s: '2025-07-04 16:20'};'04:20 PM' +d(s, 'Etc/GMT+5').format('%I:%M %p');{s: null};'Invalid date' +d(s).format('%-I:%M%P');{s: '2024-12-30 07:05:09'};'7:05am' +d(s).format('%-I:%M%P');{s: '2025-11-02 01:30'};'1:30am' +d(s).format('%-I:%M%P');{s: '2020-12-31 00:00:01'};'12:00am' +d(s).format('%-I:%M%P');{s: '2024-02-29 23:59:59'};'11:59pm' +d(s).format('%-I:%M%P');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%H:%M');{s: '2025-03-30 12:00'};'12:00' +d(s, 'Europe/Berlin').format('%H:%M');{s: '2021-01-03 13:00'};'13:00' +d(s, 'Europe/Berlin').format('%H:%M');{s: '2025-07-04 16:20'};'16:20' +d(s, 'Europe/Berlin').format('%H:%M');{s: '2023-01-01'};'00:00' +d(s, 'Europe/Berlin').format('%H:%M');{s: null};'Invalid date' +d(s, 'America/New_York').format('%T');{s: '2025-11-02 01:30'};'01:30:00' +d(s, 'America/New_York').format('%T');{s: '2020-12-31 00:00:01'};'00:00:01' +d(s, 'America/New_York').format('%T');{s: '2024-02-29 23:59:59'};'23:59:59' +d(s, 'America/New_York').format('%T');{s: '2024-12-30 07:05:09'};'07:05:09' +d(s, 'America/New_York').format('%T');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%R');{s: '2021-01-03 13:00'};'13:00' +d(s, 'Asia/Kolkata').format('%R');{s: '2025-07-04 16:20'};'16:20' +d(s, 'Asia/Kolkata').format('%R');{s: '2023-01-01'};'00:00' +d(s, 'Asia/Kolkata').format('%R');{s: '2025-03-30 12:00'};'12:00' +d(s, 'Asia/Kolkata').format('%R');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').format('%F');{s: '2020-12-31 00:00:01'};'2020-12-31' +d(s, 'Etc/GMT+5').format('%F');{s: '2024-02-29 23:59:59'};'2024-02-29' +d(s, 'Etc/GMT+5').format('%F');{s: '2024-12-30 07:05:09'};'2024-12-30' +d(s, 'Etc/GMT+5').format('%F');{s: '2025-11-02 01:30'};'2025-11-02' +d(s, 'Etc/GMT+5').format('%F');{s: null};'Invalid date' +d(s).format('%D');{s: '2025-07-04 16:20'};'07/04/25' +d(s).format('%D');{s: '2023-01-01'};'01/01/23' +d(s).format('%D');{s: '2025-03-30 12:00'};'03/30/25' +d(s).format('%D');{s: '2021-01-03 13:00'};'01/03/21' +d(s).format('%D');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%j');{s: '2024-02-29 23:59:59'};'060' +d(s, 'Europe/Berlin').format('%j');{s: '2024-12-30 07:05:09'};'365' +d(s, 'Europe/Berlin').format('%j');{s: '2025-11-02 01:30'};'306' +d(s, 'Europe/Berlin').format('%j');{s: '2020-12-31 00:00:01'};'366' +d(s, 'Europe/Berlin').format('%j');{s: null};'Invalid date' +d(s, 'America/New_York').format('%G-W%V-%u');{s: '2023-01-01'};'2022-W52-7' +d(s, 'America/New_York').format('%G-W%V-%u');{s: '2025-03-30 12:00'};'2025-W13-7' +d(s, 'America/New_York').format('%G-W%V-%u');{s: '2021-01-03 13:00'};'2020-W53-7' +d(s, 'America/New_York').format('%G-W%V-%u');{s: '2025-07-04 16:20'};'2025-W27-5' +d(s, 'America/New_York').format('%G-W%V-%u');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%U/%W');{s: '2024-12-30 07:05:09'};'52/53' +d(s, 'Asia/Kolkata').format('%U/%W');{s: '2025-11-02 01:30'};'44/43' +d(s, 'Asia/Kolkata').format('%U/%W');{s: '2020-12-31 00:00:01'};'52/52' +d(s, 'Asia/Kolkata').format('%U/%W');{s: '2024-02-29 23:59:59'};'08/09' +d(s, 'Asia/Kolkata').format('%U/%W');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').format('%y%j');{s: '2025-03-30 12:00'};'25089' +d(s, 'Etc/GMT+5').format('%y%j');{s: '2021-01-03 13:00'};'21003' +d(s, 'Etc/GMT+5').format('%y%j');{s: '2025-07-04 16:20'};'25185' +d(s, 'Etc/GMT+5').format('%y%j');{s: '2023-01-01'};'23001' +d(s, 'Etc/GMT+5').format('%y%j');{s: null};'Invalid date' +d(s).format('%B %Y');{s: '2025-11-02 01:30'};'November 2025' +d(s).format('%B %Y');{s: '2020-12-31 00:00:01'};'December 2020' +d(s).format('%B %Y');{s: '2024-02-29 23:59:59'};'February 2024' +d(s).format('%B %Y');{s: '2024-12-30 07:05:09'};'December 2024' +d(s).format('%B %Y');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%e %b');{s: '2021-01-03 13:00'};' 3 Jan' +d(s, 'Europe/Berlin').format('%e %b');{s: '2025-07-04 16:20'};' 4 Jul' +d(s, 'Europe/Berlin').format('%e %b');{s: '2023-01-01'};' 1 Jan' +d(s, 'Europe/Berlin').format('%e %b');{s: '2025-03-30 12:00'};'30 Mar' +d(s, 'Europe/Berlin').format('%e %b');{s: null};'Invalid date' +d(s, 'America/New_York').format('%k:%M');{s: '2020-12-31 00:00:01'};' 0:00' +d(s, 'America/New_York').format('%k:%M');{s: '2024-02-29 23:59:59'};'23:59' +d(s, 'America/New_York').format('%k:%M');{s: '2024-12-30 07:05:09'};' 7:05' +d(s, 'America/New_York').format('%k:%M');{s: '2025-11-02 01:30'};' 1:30' +d(s, 'America/New_York').format('%k:%M');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%Z');{s: '2025-07-04 16:20'};'IST' +d(s, 'Asia/Kolkata').format('%Z');{s: '2023-01-01'};'IST' +d(s, 'Asia/Kolkata').format('%Z');{s: '2025-03-30 12:00'};'IST' +d(s, 'Asia/Kolkata').format('%Z');{s: '2021-01-03 13:00'};'IST' +d(s, 'Asia/Kolkata').format('%Z');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').format('%s');{s: '2024-02-29 23:59:59'};'1709269199' +d(s, 'Etc/GMT+5').format('%s');{s: '2024-12-30 07:05:09'};'1735560309' +d(s, 'Etc/GMT+5').format('%s');{s: '2025-11-02 01:30'};'1762065000' +d(s, 'Etc/GMT+5').format('%s');{s: '2020-12-31 00:00:01'};'1609390801' +d(s, 'Etc/GMT+5').format('%s');{s: null};'Invalid date' +d(s).format('%c');{s: '2023-01-01'};'Sun Jan 1 00:00:00 2023' +d(s).format('%c');{s: '2025-03-30 12:00'};'Sun Mar 30 12:00:00 2025' +d(s).format('%c');{s: '2021-01-03 13:00'};'Sun Jan 3 13:00:00 2021' +d(s).format('%c');{s: '2025-07-04 16:20'};'Fri Jul 4 16:20:00 2025' +d(s).format('%c');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%v');{s: '2024-12-30 07:05:09'};'30-Dec-2024' +d(s, 'Europe/Berlin').format('%v');{s: '2025-11-02 01:30'};' 2-Nov-2025' +d(s, 'Europe/Berlin').format('%v');{s: '2020-12-31 00:00:01'};'31-Dec-2020' +d(s, 'Europe/Berlin').format('%v');{s: '2024-02-29 23:59:59'};'29-Feb-2024' +d(s, 'Europe/Berlin').format('%v');{s: null};'Invalid date' +d(s, 'America/New_York').format('%r');{s: '2025-03-30 12:00'};'12:00:00 PM' +d(s, 'America/New_York').format('%r');{s: '2021-01-03 13:00'};'01:00:00 PM' +d(s, 'America/New_York').format('%r');{s: '2025-07-04 16:20'};'04:20:00 PM' +d(s, 'America/New_York').format('%r');{s: '2023-01-01'};'12:00:00 AM' +d(s, 'America/New_York').format('%r');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%Y-%m-%d %H:%M:%S%.3f');{s: '2025-11-02 01:30'};'2025-11-02 01:30:00.000' +d(s, 'Asia/Kolkata').format('%Y-%m-%d %H:%M:%S%.3f');{s: '2020-12-31 00:00:01'};'2020-12-31 00:00:01.000' +d(s, 'Asia/Kolkata').format('%Y-%m-%d %H:%M:%S%.3f');{s: '2024-02-29 23:59:59'};'2024-02-29 23:59:59.000' +d(s, 'Asia/Kolkata').format('%Y-%m-%d %H:%M:%S%.3f');{s: '2024-12-30 07:05:09'};'2024-12-30 07:05:09.000' +d(s, 'Asia/Kolkata').format('%Y-%m-%d %H:%M:%S%.3f');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').format('%b %-d at %-H:%M');{s: '2021-01-03 13:00'};'Jan 3 at 13:00' +d(s, 'Etc/GMT+5').format('%b %-d at %-H:%M');{s: '2025-07-04 16:20'};'Jul 4 at 16:20' +d(s, 'Etc/GMT+5').format('%b %-d at %-H:%M');{s: '2023-01-01'};'Jan 1 at 0:00' +d(s, 'Etc/GMT+5').format('%b %-d at %-H:%M');{s: '2025-03-30 12:00'};'Mar 30 at 12:00' +d(s, 'Etc/GMT+5').format('%b %-d at %-H:%M');{s: null};'Invalid date' +d(s).format('week %V of %G');{s: '2020-12-31 00:00:01'};'week 53 of 2020' +d(s).format('week %V of %G');{s: '2024-02-29 23:59:59'};'week 09 of 2024' +d(s).format('week %V of %G');{s: '2024-12-30 07:05:09'};'week 01 of 2025' +d(s).format('week %V of %G');{s: '2025-11-02 01:30'};'week 44 of 2025' +d(s).format('week %V of %G');{s: null};'Invalid date' +d(s, 'Europe/Berlin').format('%w %u');{s: '2025-07-04 16:20'};'5 5' +d(s, 'Europe/Berlin').format('%w %u');{s: '2023-01-01'};'0 7' +d(s, 'Europe/Berlin').format('%w %u');{s: '2025-03-30 12:00'};'0 7' +d(s, 'Europe/Berlin').format('%w %u');{s: '2021-01-03 13:00'};'0 7' +d(s, 'Europe/Berlin').format('%w %u');{s: null};'Invalid date' +d(s, 'America/New_York').format('%h %C');{s: '2024-02-29 23:59:59'};'Feb 20' +d(s, 'America/New_York').format('%h %C');{s: '2024-12-30 07:05:09'};'Dec 20' +d(s, 'America/New_York').format('%h %C');{s: '2025-11-02 01:30'};'Nov 20' +d(s, 'America/New_York').format('%h %C');{s: '2020-12-31 00:00:01'};'Dec 20' +d(s, 'America/New_York').format('%h %C');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').format('%Y/%m/%d %Z');{s: '2023-01-01'};'2023/01/01 IST' +d(s, 'Asia/Kolkata').format('%Y/%m/%d %Z');{s: '2025-03-30 12:00'};'2025/03/30 IST' +d(s, 'Asia/Kolkata').format('%Y/%m/%d %Z');{s: '2021-01-03 13:00'};'2021/01/03 IST' +d(s, 'Asia/Kolkata').format('%Y/%m/%d %Z');{s: '2025-07-04 16:20'};'2025/07/04 IST' +d(s, 'Asia/Kolkata').format('%Y/%m/%d %Z');{s: null};'Invalid date' +# the pattern itself comes from the input +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%Y'};'2024' +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%d.%m.%Y'};'29.02.2024' +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%H:%M:%S'};'23:59:59' +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%A'};'Thursday' +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%B %d'};'February 29' +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%:z'};'+00:00' +d(s).format(f);{s: '2024-02-29 23:59:59', f: '%Y-%m-%dT%H:%M'};'2024-02-29T23:59' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%Y'};'2024' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%d.%m.%Y'};'29.02.2024' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%H:%M:%S'};'23:59:59' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%A'};'Thursday' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%B %d'};'February 29' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%:z'};'+05:30' +d(s, 'Asia/Kolkata').format(f);{s: '2024-02-29 23:59:59', f: '%Y-%m-%dT%H:%M'};'2024-02-29T23:59' +# the same instant formatted in every zone +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'UTC'};'2025-03-30 01:30 +00:00' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'UTC'};'UTC' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Etc/GMT+5'};'2025-03-29 20:30 -05:00' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Etc/GMT+5'};'-05' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Etc/GMT-14'};'2025-03-30 15:30 +14:00' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Etc/GMT-14'};'+14' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Europe/Berlin'};'2025-03-30 03:30 +02:00' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Europe/Berlin'};'CEST' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'America/New_York'};'2025-03-29 21:30 -04:00' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'America/New_York'};'EDT' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Asia/Kolkata'};'2025-03-30 07:00 +05:30' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Asia/Kolkata'};'IST' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Asia/Kathmandu'};'2025-03-30 07:15 +05:45' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Asia/Kathmandu'};'+0545' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Australia/Lord_Howe'};'2025-03-30 12:30 +11:00' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Australia/Lord_Howe'};'+11' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'Pacific/Chatham'};'2025-03-30 15:15 +13:45' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'Pacific/Chatham'};'+1345' +d('2025-03-30T01:30:00Z').tz(z).format('%Y-%m-%d %H:%M %:z');{z: 'America/St_Johns'};'2025-03-29 23:00 -02:30' +d('2025-03-30T01:30:00Z').tz(z).format('%Z');{z: 'America/St_Johns'};'NDT' diff --git a/core/expression/tests/spec/standard/16-06-dates-in-closures.csv b/core/expression/tests/spec/standard/16-06-dates-in-closures.csv new file mode 100644 index 00000000..474bc9c1 --- /dev/null +++ b/core/expression/tests/spec/standard/16-06-dates-in-closures.csv @@ -0,0 +1,111 @@ +expression (string);input (json 5);output (json 5);note +# map: date arithmetic per element +map(events, d(#.at).add(1, 'day').format('%Y-%m-%d'));{events: [{at: '2024-02-28 22:00'}, {at: '2024-02-29 23:30'}, {at: '2024-12-31 12:00'}]};['2024-02-29', '2024-03-01', '2025-01-01'] +map(events, d(#.at).add(1, 'day').format('%Y-%m-%d'));{events: [{at: '2025-03-29 12:00'}, {at: '2025-10-25 08:00'}]};['2025-03-30', '2025-10-26'] +map(events, d(#.at).add(1, 'day').format('%Y-%m-%d'));{events: [{at: '2023-01-31'}, {at: 'oops'}, {at: '2023-03-15 09:00:00'}]};['2023-02-01', 'Invalid date', '2023-03-16'] +map(events, d(#.at).add(1, 'day').format('%Y-%m-%d'));{events: []};[] +map(events, d(#.at).add(1, 'day').format('%Y-%m-%d'));{events: [{at: 1700000000000}, {at: '2023-11-14 22:13:20'}, {at: null}]};['2023-11-15', '2023-11-15', 'Invalid date'] +map(events, d(#.at).endOf('month'));{events: [{at: '2024-02-28 22:00'}, {at: '2024-02-29 23:30'}, {at: '2024-12-31 12:00'}]};['2024-02-29T23:59:59Z', '2024-02-29T23:59:59Z', '2024-12-31T23:59:59Z'] +map(events, d(#.at).endOf('month'));{events: [{at: '2025-03-29 12:00'}, {at: '2025-10-25 08:00'}]};['2025-03-31T23:59:59Z', '2025-10-31T23:59:59Z'] +map(events, d(#.at).endOf('month'));{events: [{at: '2023-01-31'}, {at: 'oops'}, {at: '2023-03-15 09:00:00'}]};['2023-01-31T23:59:59Z', 'Invalid date', '2023-03-31T23:59:59Z'] +map(events, d(#.at).endOf('month'));{events: []};[] +map(events, d(#.at).endOf('month'));{events: [{at: 1700000000000}, {at: '2023-11-14 22:13:20'}, {at: null}]};['2023-11-30T23:59:59Z', '2023-11-30T23:59:59Z', 'Invalid date'] +map(events, d(#.at).startOf('month').add(1, 'M'));{events: [{at: '2024-02-28 22:00'}, {at: '2024-02-29 23:30'}, {at: '2024-12-31 12:00'}]};['2024-03-01T00:00:00Z', '2024-03-01T00:00:00Z', '2025-01-01T00:00:00Z'] +map(events, d(#.at).startOf('month').add(1, 'M'));{events: [{at: '2025-03-29 12:00'}, {at: '2025-10-25 08:00'}]};['2025-04-01T00:00:00Z', '2025-11-01T00:00:00Z'] +map(events, d(#.at).startOf('month').add(1, 'M'));{events: [{at: '2023-01-31'}, {at: 'oops'}, {at: '2023-03-15 09:00:00'}]};['2023-02-01T00:00:00Z', 'Invalid date', '2023-04-01T00:00:00Z'] +map(events, d(#.at).startOf('month').add(1, 'M'));{events: []};[] +map(events, d(#.at).startOf('month').add(1, 'M'));{events: [{at: 1700000000000}, {at: '2023-11-14 22:13:20'}, {at: null}]};['2023-12-01T00:00:00Z', '2023-12-01T00:00:00Z', 'Invalid date'] +map(events, d(#.at).weekday());{events: [{at: '2024-02-28 22:00'}, {at: '2024-02-29 23:30'}, {at: '2024-12-31 12:00'}]};[3, 4, 2] +map(events, d(#.at).weekday());{events: [{at: '2025-03-29 12:00'}, {at: '2025-10-25 08:00'}]};[6, 6] +map(events, d(#.at).weekday());{events: [{at: '2023-01-31'}, {at: 'oops'}, {at: '2023-03-15 09:00:00'}]};[2, null, 3] +map(events, d(#.at).weekday());{events: []};[] +map(events, d(#.at).weekday());{events: [{at: 1700000000000}, {at: '2023-11-14 22:13:20'}, {at: null}]};[2, 2, null] +map(events, d(#.at, 'Europe/Berlin').format('%H:%M %Z'));{events: [{at: '2024-02-28 22:00'}, {at: '2024-02-29 23:30'}, {at: '2024-12-31 12:00'}]};['22:00 CET', '23:30 CET', '12:00 CET'] +map(events, d(#.at, 'Europe/Berlin').format('%H:%M %Z'));{events: [{at: '2025-03-29 12:00'}, {at: '2025-10-25 08:00'}]};['12:00 CET', '08:00 CEST'] +map(events, d(#.at, 'Europe/Berlin').format('%H:%M %Z'));{events: [{at: '2023-01-31'}, {at: 'oops'}, {at: '2023-03-15 09:00:00'}]};['00:00 CET', 'Invalid date', '09:00 CET'] +# map over plain date strings and numbers +map(xs, d(#).add(1, 'M').format('%F'));{xs: ['2024-01-31', '2024-03-31', '2024-05-31']};['2024-02-29', '2024-04-30', '2024-06-30'] +map(xs, d(#).add(1, 'M').format('%F'));{xs: ['2023-12-31 23:59:59']};['2024-01-31'] +map(xs, d(#).add(1, 'M').format('%F'));{xs: []};[] +map(xs, d(#).add(1, 'M').format('%F'));{xs: ['2025-02-28', 'bad', '2025-02-27']};['2025-03-28', 'Invalid date', '2025-03-27'] +map(xs, d(#).sub(1, 'q').format('%F'));{xs: ['2024-01-31', '2024-03-31', '2024-05-31']};['2023-10-31', '2023-12-31', '2024-02-29'] +map(xs, d(#).sub(1, 'q').format('%F'));{xs: ['2023-12-31 23:59:59']};['2023-09-30'] +map(xs, d(#).sub(1, 'q').format('%F'));{xs: []};[] +map(xs, d(#).sub(1, 'q').format('%F'));{xs: ['2025-02-28', 'bad', '2025-02-27']};['2024-11-28', 'Invalid date', '2024-11-27'] +map(xs, d(#, 'Etc/GMT+5').add(1, 'y'));{xs: ['2024-01-31', '2024-03-31', '2024-05-31']};['2025-01-31T00:00:00-05:00', '2025-03-31T00:00:00-05:00', '2025-05-31T00:00:00-05:00'] +map(xs, d(#, 'Etc/GMT+5').add(1, 'y'));{xs: ['2023-12-31 23:59:59']};['2024-12-31T23:59:59-05:00'] +map(xs, d(#, 'Etc/GMT+5').add(1, 'y'));{xs: []};[] +map(xs, d(#, 'Etc/GMT+5').add(1, 'y'));{xs: ['2025-02-28', 'bad', '2025-02-27']};['2026-02-28T00:00:00-05:00', 'Invalid date', '2026-02-27T00:00:00-05:00'] +map([0, 1, 2, 3], d(s).add(#, 'M').format('%F'));{s: '2024-01-31'};['2024-01-31', '2024-02-29', '2024-03-31', '2024-04-30'] +map([0, 1, 2, 3], d(s).add(#, 'M').format('%F'));{s: '2023-11-30'};['2023-11-30', '2023-12-30', '2024-01-30', '2024-02-29'] +map([0, 1, 2, 3], d(s).add(#, 'M').format('%F'));{s: '2024-08-31 10:00'};['2024-08-31', '2024-09-30', '2024-10-31', '2024-11-30'] +map([0, 1, 2, 3], d(s).add(#, 'M').format('%F'));{s: null};['Invalid date', 'Invalid date', 'Invalid date', 'Invalid date'] +map([1..4], d(s).add(# * 7, 'd').weekday());{s: '2025-03-17'};[1, 1, 1, 1] +map([1..4], d(s).add(# * 7, 'd').weekday());{s: '2025-03-16'};[7, 7, 7, 7] +map([1..4], d(s).add(# * 7, 'd').weekday());{s: 'x'};[null, null, null, null] +map([0..3], d(s, 'Asia/Kolkata').add(#, 'q').quarter());{s: '2024-11-30'};[4, 1, 2, 3] +map([0..3], d(s, 'Asia/Kolkata').add(#, 'q').quarter());{s: '2025-01-01'};[1, 2, 3, 4] +map([0..3], d(s, 'Asia/Kolkata').add(#, 'q').quarter());{s: '2024-05-31'};[2, 3, 4, 1] +# filter by comparisons with an outer cutoff +map(filter(events, d(#.at).isBefore(d(cutoff))), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-20'};[1] +map(filter(events, d(#.at).isBefore(d(cutoff))), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-22'};[1, 2, 3] +map(filter(events, d(#.at).isBefore(d(cutoff))), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-01-01'};[] +map(filter(events, d(#.at).isBefore(d(cutoff))), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: null};[] +map(filter(events, d(#.at).isBefore(d(cutoff))), #.id);{events: [], cutoff: '2025-03-20'};[] +map(filter(events, d(#.at).isSame(d(cutoff), 'day')), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-20 18:00'};[2] +map(filter(events, d(#.at).isSame(d(cutoff), 'day')), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-19'};[1] +map(filter(events, d(#.at).isSame(d(cutoff), 'day')), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: 'x'};[] +map(filter(events, d(#.at) < d(cutoff)), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-20'};[1, 4];question: an invalid date orders before every valid date instead of failing or comparing false +map(filter(events, d(#.at) < d(cutoff)), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-21 00:00:01'};[1, 2, 3, 4];question: an invalid date orders before every valid date instead of failing or comparing false +map(filter(events, d(#.at).isValid() and d(#.at) < d(cutoff)), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-20'};[1] +map(filter(events, d(#.at).isValid() and d(#.at) < d(cutoff)), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-21 00:00:01'};[1, 2, 3] +map(filter(events, d(#.at).isAfter(d(cutoff), 'day')), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-20 23:00'};[3] +map(filter(events, d(#.at).isAfter(d(cutoff), 'day')), #.id);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-19'};[2, 3] +count(events, d(#.at).isSameOrAfter(d(cutoff)));{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2025-03-20'};2 +count(events, d(#.at).isSameOrAfter(d(cutoff)));{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2020-01-01'};3 +count(events, d(#.at).isSameOrAfter(d(cutoff)));{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: '2030-01-01'};0 +count(events, d(#.at).isSameOrAfter(d(cutoff)));{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}], cutoff: null};0 +some(events, d(#.at).weekday() == 5);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}]};true +some(events, d(#.at).weekday() == 5);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}]};false +some(events, d(#.at).weekday() == 5);{events: []};false +all(events, d(#.at).isValid());{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}]};false +all(events, d(#.at).isValid());{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}]};true +all(events, d(#.at).isValid());{events: []};true +none(events, d(#.at).year() < 2025);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}]};true +none(events, d(#.at).year() < 2025);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}]};!error +none(events, d(#.at).year() < 2025);{events: [{at: '2024-12-31 23:59:59'}]};false +none(events, d(#.at).year() < 2025);{events: []};true +one(events, d(#.at).day() == 21);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}]};true +one(events, d(#.at).day() == 21);{events: [{id: 1, at: '2025-03-19 23:59'}, {id: 2, at: '2025-03-20 00:00'}, {id: 3, at: '2025-03-21'}, {id: 4, at: 'bad'}, {id: 5, at: '2025-04-21'}]};false +# min/max over mapped dates +max(map(xs, d(#)));{xs: ['2024-02-29', '2023-12-31 23:59:59', '2024-02-28 23:00']};'2024-02-29T00:00:00Z' +max(map(xs, d(#)));{xs: ['2025-01-01']};'2025-01-01T00:00:00Z' +max(map(xs, d(#)));{xs: ['2025-06-30 12:00', '2025-06-30 11:59:59']};'2025-06-30T12:00:00Z' +min(map(xs, d(#)));{xs: ['2024-02-29', '2023-12-31 23:59:59', '2024-02-28 23:00']};'2023-12-31T23:59:59Z' +min(map(xs, d(#)));{xs: ['2025-01-01']};'2025-01-01T00:00:00Z' +min(map(xs, d(#)));{xs: ['2025-06-30 12:00', '2025-06-30 11:59:59']};'2025-06-30T11:59:59Z' +max(map(xs, d(#).add(1, 'M'))).format('%F');{xs: ['2024-02-29', '2023-12-31 23:59:59', '2024-02-28 23:00']};'2024-03-29' +max(map(xs, d(#).add(1, 'M'))).format('%F');{xs: ['2025-01-01']};'2025-02-01' +max(map(xs, d(#).add(1, 'M'))).format('%F');{xs: ['2025-06-30 12:00', '2025-06-30 11:59:59']};'2025-07-30' +min(map(xs, d(#, 'America/New_York').startOf('day')));{xs: ['2024-02-29', '2023-12-31 23:59:59', '2024-02-28 23:00']};'2023-12-31T00:00:00-05:00' +min(map(xs, d(#, 'America/New_York').startOf('day')));{xs: ['2025-01-01']};'2025-01-01T00:00:00-05:00' +min(map(xs, d(#, 'America/New_York').startOf('day')));{xs: ['2025-06-30 12:00', '2025-06-30 11:59:59']};'2025-06-30T00:00:00-04:00' +max(map(xs, d(#))).diff(min(map(xs, d(#))), 'day');{xs: ['2024-02-29', '2023-12-31 23:59:59', '2024-02-28 23:00']};59 +max(map(xs, d(#))).diff(min(map(xs, d(#))), 'day');{xs: ['2025-01-01']};0 +max(map(xs, d(#))).diff(min(map(xs, d(#))), 'day');{xs: ['2025-06-30 12:00', '2025-06-30 11:59:59']};0 +sum(map(xs, d(#).diff(d(start), 'day')));{xs: ['2024-02-29', '2023-12-31 23:59:59', '2024-02-28 23:00'], start: '2023-12-01'};209 +sum(map(xs, d(#).diff(d(start), 'day')));{xs: ['2025-01-01'], start: '2024-01-01'};366 +sum(map(xs, d(#).diff(d(start), 'day')));{xs: ['2025-06-30 12:00', '2025-06-30 11:59:59'], start: '2025-06-01'};58 +sum(map(xs, d(#).diff(d(start), 'hour'))) / len(xs);{xs: ['2025-01-01 06:00', '2025-01-01 18:00'], start: '2025-01-01'};12.0 +sum(map(xs, d(#).diff(d(start), 'hour'))) / len(xs);{xs: ['2025-01-02'], start: '2025-01-01'};24.0 +# grouping keys and lookups built from dates +map(xs, d(#).format('%Y-Q') + string(d(#).quarter()));{xs: ['2024-03-31 23:59:59', '2024-04-01', '2025-12-31']};['2024-Q1', '2024-Q2', '2025-Q4'] +map(xs, d(#).format('%Y-Q') + string(d(#).quarter()));{xs: ['2023-07-15']};['2023-Q3'] +map(xs, d(#).format('%G-W%V'));{xs: ['2024-12-30', '2021-01-03', '2020-12-31', '2026-01-01']};['2025-W01', '2020-W53', '2020-W53', '2026-W01'] +filter(xs, d(#).weekday() <= 5);{xs: ['2025-03-14', '2025-03-15', '2025-03-16', '2025-03-17']};['2025-03-14', '2025-03-17'] +filter(xs, d(#).weekday() <= 5);{xs: []};[] +len(filter([0..30], d(s).add(#, 'd').weekday() < 6));{s: '2025-03-01'};21 +len(filter([0..30], d(s).add(#, 'd').weekday() < 6));{s: '2024-02-01'};22 +len(filter([0..30], d(s).add(#, 'd').weekday() < 6));{s: '2025-12-01'};23 +map(filter([0..13], d(s).add(#, 'd').weekday() == 1), d(s).add(#, 'd').format('%F'));{s: '2025-03-20'};['2025-03-24', '2025-03-31'] +map(filter([0..13], d(s).add(#, 'd').weekday() == 1), d(s).add(#, 'd').format('%F'));{s: '2024-12-25'};['2024-12-30', '2025-01-06'] diff --git a/core/expression/tests/spec/standard/16-07-date-rules.csv b/core/expression/tests/spec/standard/16-07-date-rules.csv new file mode 100644 index 00000000..c466d574 --- /dev/null +++ b/core/expression/tests/spec/standard/16-07-date-rules.csv @@ -0,0 +1,403 @@ +expression (string);input (json 5);output (json 5);note +# age from a birthdate at a fixed reference date +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: '2000-02-29'};25 +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: '2007-03-20'};18 +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: '2007-03-21'};17 +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: '1990-12-31'};34 +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: '2025-03-20'};0 +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: '2010-06-15 23:59'};14 +d(ref).diff(d(birth), 'year');{ref: '2025-03-20', birth: null};null +d(ref).diff(d(birth), 'year') >= 18;{ref: '2025-03-20', birth: '2000-02-29'};true +d(ref).diff(d(birth), 'year') >= 18;{ref: '2025-03-20', birth: '2007-03-20'};true +d(ref).diff(d(birth), 'year') >= 18;{ref: '2025-03-20', birth: '2007-03-21'};false +d(ref).diff(d(birth), 'year') >= 18;{ref: '2025-03-20', birth: '1990-12-31'};true +d(ref).diff(d(birth), 'year') >= 18;{ref: '2025-03-20', birth: '2025-03-20'};false +d(ref).diff(d(birth), 'year') >= 18;{ref: '2025-03-20', birth: '2010-06-15 23:59'};false +d(birth).add(18, 'y').isSameOrBefore(d(ref));{ref: '2025-03-20', birth: '2007-03-20'};true +d(birth).add(18, 'y').isSameOrBefore(d(ref));{ref: '2025-03-20', birth: '2007-03-21'};false +d(birth).add(18, 'y').isSameOrBefore(d(ref));{ref: '2025-03-20', birth: '1990-12-31'};true +d(birth).add(18, 'y').isSameOrBefore(d(ref));{ref: '2025-03-20', birth: '2025-03-20'};false +d(birth).add(18, 'y').isSameOrBefore(d(ref));{ref: '2025-03-20', birth: '2010-06-15 23:59'};false +d().diff(d(birth), 'year');{birth: '2000-02-29'};25 +d().diff(d(birth), 'year');{birth: '2007-03-20'};18 +d().diff(d(birth), 'year');{birth: '2007-03-21'};17 +d().diff(d(birth), 'year');{birth: '1990-12-31'};34 +d().diff(d(birth), 'year');{birth: '2025-03-20'};0 +d().diff(d(birth), 'year');{birth: '2010-06-15 23:59'};14 +d().diff(d(birth), 'year');{birth: null};null +d(ref).diff(d(birth), 'M') % 12;{ref: '2025-03-20', birth: '2000-01-31'};1 +d(ref).diff(d(birth), 'M') % 12;{ref: '2025-03-20', birth: '2024-03-21'};11 +d(ref).diff(d(birth), 'M') % 12;{ref: '2025-03-20', birth: '2024-12-20'};3 +d(ref).diff(d(birth), 'M') % 12;{ref: '2025-03-20', birth: '2025-01-19'};2 +# Feb 29 birthdays: the 18th birthday +d(birth).add(18, 'y').format('%F');{birth: '2004-02-29'};'2022-02-28';bug: adding a year to Feb 29 gives an invalid date instead of clamping to Feb 28 like months do +d(birth).add(18, 'y').format('%F');{birth: '2004-03-01'};'2022-03-01' +d(birth).add(18, 'y').format('%F');{birth: '2003-02-28'};'2021-02-28' +d(birth).add(216, 'M').format('%F');{birth: '2004-02-29'};'2022-02-28' +d(birth).add(216, 'M').format('%F');{birth: '2004-03-01'};'2022-03-01' +d(birth).add(216, 'M').format('%F');{birth: '2003-02-28'};'2021-02-28' +# SLA: resolution within N business hours / hours +d(resolved).isSameOrBefore(d(opened).add(48, 'h'));{opened: '2025-03-14 16:00', resolved: '2025-03-16 15:59'};true +d(resolved).isSameOrBefore(d(opened).add(48, 'h'));{opened: '2025-03-14 16:00', resolved: '2025-03-16 16:01'};false +d(resolved).isSameOrBefore(d(opened).add(48, 'h'));{opened: '2025-03-14 16:00', resolved: null};false +d(resolved).isSameOrBefore(d(opened).add(48, 'h'));{opened: '2025-03-17 09:00', resolved: '2025-03-17 09:00'};true +d(resolved).diff(d(opened), 'h') > 47 ? 'breach' : 'ok';{opened: '2025-03-14 16:00', resolved: '2025-03-16 15:59'};'ok' +d(resolved).diff(d(opened), 'h') > 47 ? 'breach' : 'ok';{opened: '2025-03-14 16:00', resolved: '2025-03-16 16:01'};'breach' +d(resolved).diff(d(opened), 'h') > 47 ? 'breach' : 'ok';{opened: '2025-03-17 09:00', resolved: '2025-03-17 09:00'};'ok' +(d(resolved).diff(d(opened), 'h') ?? 999) > 47 ? 'breach' : 'ok';{opened: '2025-03-14 16:00', resolved: '2025-03-16 15:59'};'ok' +(d(resolved).diff(d(opened), 'h') ?? 999) > 47 ? 'breach' : 'ok';{opened: '2025-03-14 16:00', resolved: '2025-03-16 16:01'};'breach' +(d(resolved).diff(d(opened), 'h') ?? 999) > 47 ? 'breach' : 'ok';{opened: '2025-03-14 16:00', resolved: null};'breach' +(d(resolved).diff(d(opened), 'h') ?? 999) > 47 ? 'breach' : 'ok';{opened: '2025-03-17 09:00', resolved: '2025-03-17 09:00'};'ok' +d(opened).weekday() >= 6 ? d(opened).add(8 - d(opened).weekday(), 'd').startOf('day').add(9, 'h') : d(opened);{opened: '2025-03-15 22:10'};'2025-03-17T09:00:00Z' +d(opened).weekday() >= 6 ? d(opened).add(8 - d(opened).weekday(), 'd').startOf('day').add(9, 'h') : d(opened);{opened: '2025-03-16 03:00'};'2025-03-17T09:00:00Z' +d(opened).weekday() >= 6 ? d(opened).add(8 - d(opened).weekday(), 'd').startOf('day').add(9, 'h') : d(opened);{opened: '2025-03-17 03:00'};'2025-03-17T03:00:00Z' +d(opened).weekday() >= 6 ? d(opened).add(8 - d(opened).weekday(), 'd').startOf('day').add(9, 'h') : d(opened);{opened: '2025-03-21 23:59'};'2025-03-21T23:59:00Z' +d(opened, 'America/New_York').add(24, 'h').format('%a %H:%M %Z');{opened: '2025-03-08 12:00'};'Sun 13:00 EDT' +d(opened, 'America/New_York').add(24, 'h').format('%a %H:%M %Z');{opened: '2025-11-01 12:00'};'Sun 11:00 EST' +d(opened, 'America/New_York').add(24, 'h').format('%a %H:%M %Z');{opened: '2025-06-01 12:00'};'Mon 12:00 EDT' +d(opened, 'Europe/Berlin').add(1, 'd').format('%a %H:%M %Z');{opened: '2025-03-29 12:00'};'Sun 13:00 CEST';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(opened, 'Europe/Berlin').add(1, 'd').format('%a %H:%M %Z');{opened: '2025-10-25 12:00'};'Sun 11:00 CET';"question: days are exact 86400-second spans, so crossing a DST change shifts the wall-clock hour; a calendar day (moment, Temporal) would keep it" +d(opened, 'Europe/Berlin').add(1, 'd').format('%a %H:%M %Z');{opened: '2025-07-01 12:00'};'Wed 12:00 CEST' +d(opened, 'Europe/Berlin').add(1, 'd').format('%a %H:%M %Z');{opened: 'bad'};'Invalid date' +# subscription renewal +d(start).add(n, 'M').format('%F');{start: '2024-01-31', n: 1};'2024-02-29' +d(start).add(n, 'M').format('%F');{start: '2024-02-29', n: 12};'2025-02-28' +d(start).add(n, 'M').format('%F');{start: '2023-08-31 12:00', n: 6};'2024-02-29' +d(start).add(n, 'M').format('%F');{start: '2025-03-20 10:15:30', n: 3};'2025-06-20' +d(start).add(n, 'M').format('%F');{start: 'x', n: 1};'Invalid date' +d(start).add(n, 'M').format('%F');{start: '2024-01-31', n: 13};'2025-02-28' +d(start).add(n, 'M').format('%F');{start: '2024-01-31', n: 0};'2024-01-31' +d(start).add(n, 'M').format('%F');{start: '2024-01-31', n: -1};'2023-12-31' +d(start).add(1, 'y').sub(1, 'd').format('%F');{start: '2024-01-31'};'2025-01-30' +d(start).add(1, 'y').sub(1, 'd').format('%F');{start: '2023-08-31 12:00'};'2024-08-30' +d(start).add(1, 'y').sub(1, 'd').format('%F');{start: '2025-03-20 10:15:30'};'2026-03-19' +d(start).add(1, 'y').sub(1, 'd').format('%F');{start: 'x'};'Invalid date' +d(start).add(1, 'y').sub(1, 'd').format('%F');{start: '2024-02-29'};'2025-02-27';bug: adding a year to Feb 29 gives an invalid date instead of clamping to Feb 28 like months do +d(start).add(12, 'M').sub(1, 'd').format('%F');{start: '2024-01-31'};'2025-01-30' +d(start).add(12, 'M').sub(1, 'd').format('%F');{start: '2024-02-29'};'2025-02-27' +d(start).add(12, 'M').sub(1, 'd').format('%F');{start: '2023-08-31 12:00'};'2024-08-30' +d(start).add(12, 'M').sub(1, 'd').format('%F');{start: '2025-03-20 10:15:30'};'2026-03-19' +d(start).add(12, 'M').sub(1, 'd').format('%F');{start: 'x'};'Invalid date' +d(start).add(d(ref).diff(d(start), 'M') + 1, 'M').format('%F');{start: '2024-01-31', ref: '2025-03-20'};'2025-03-31' +d(start).add(d(ref).diff(d(start), 'M') + 1, 'M').format('%F');{start: '2023-03-20', ref: '2025-03-20'};'2025-04-20' +d(start).add(d(ref).diff(d(start), 'M') + 1, 'M').format('%F');{start: '2025-02-28', ref: '2025-03-20'};'2025-03-28' +d(start).add(d(ref).diff(d(start), 'M') + 1, 'M').format('%F');{start: '2024-11-30 10:00', ref: '2025-03-20'};'2025-03-30' +d(end).isBefore(d(ref)) ? 'expired' : d(end).diff(d(ref), 'd') <= 30 ? 'renew-soon' : 'active';{end: '2025-03-19', ref: '2025-03-20'};'expired' +d(end).isBefore(d(ref)) ? 'expired' : d(end).diff(d(ref), 'd') <= 30 ? 'renew-soon' : 'active';{end: '2025-03-20', ref: '2025-03-20'};'renew-soon' +d(end).isBefore(d(ref)) ? 'expired' : d(end).diff(d(ref), 'd') <= 30 ? 'renew-soon' : 'active';{end: '2025-04-19', ref: '2025-03-20'};'renew-soon' +d(end).isBefore(d(ref)) ? 'expired' : d(end).diff(d(ref), 'd') <= 30 ? 'renew-soon' : 'active';{end: '2025-04-20', ref: '2025-03-20'};'active' +d(end).isBefore(d(ref)) ? 'expired' : d(end).diff(d(ref), 'd') <= 30 ? 'renew-soon' : 'active';{end: '2026-01-01', ref: '2025-03-20'};'active' +d(end).endOf('day').isBefore(d(ref)) ? 'expired' : 'active';{end: '2025-03-19', ref: '2025-03-20 10:15'};'expired' +d(end).endOf('day').isBefore(d(ref)) ? 'expired' : 'active';{end: '2025-03-20', ref: '2025-03-20 10:15'};'active' +d(end).endOf('day').isBefore(d(ref)) ? 'expired' : 'active';{end: '2025-03-21', ref: '2025-03-20 10:15'};'active' +map([1..4], d(start).add(# * 3, 'M').format('%F'));{start: '2024-11-30'};['2025-02-28', '2025-05-30', '2025-08-30', '2025-11-30'] +map([1..4], d(start).add(# * 3, 'M').format('%F'));{start: '2024-08-31'};['2024-11-30', '2025-02-28', '2025-05-31', '2025-08-31'] +map([1..4], d(start).add(# * 3, 'M').format('%F'));{start: '2025-01-01'};['2025-04-01', '2025-07-01', '2025-10-01', '2026-01-01'] +# weekday-based pricing +d(at).weekday() >= 6 ? price * 1.25 : price;{at: '2025-03-14 23:59', price: 80};80 +d(at).weekday() >= 6 ? price * 1.25 : price;{at: '2025-03-15', price: 80};100.0 +d(at).weekday() >= 6 ? price * 1.25 : price;{at: '2025-03-16 23:59:59', price: 80};100.0 +d(at).weekday() >= 6 ? price * 1.25 : price;{at: '2025-03-17', price: 80};80 +d(at, 'Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-14 23:59'};'weekday' +d(at, 'Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-15'};'weekend' +d(at, 'Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-17 00:00'};'weekday' +d(at).tz('Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-14 18:29'};'weekday' +d(at).tz('Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-14 18:30'};'weekend' +d(at).tz('Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-16 18:29'};'weekend' +d(at).tz('Asia/Kolkata').weekday() >= 6 ? 'weekend' : 'weekday';{at: '2025-03-16 18:30'};'weekday' +d(at).hour() >= 22 or d(at).hour() < 6 ? 'night' : 'day';{at: '2025-03-14 21:59:59'};'day' +d(at).hour() >= 22 or d(at).hour() < 6 ? 'night' : 'day';{at: '2025-03-14 22:00'};'night' +d(at).hour() >= 22 or d(at).hour() < 6 ? 'night' : 'day';{at: '2025-03-15 05:59'};'night' +d(at).hour() >= 22 or d(at).hour() < 6 ? 'night' : 'day';{at: '2025-03-15 06:00'};'day' +d(at, 'Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-30 08:59'};'closed' +d(at, 'Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-30 09:00'};'open' +d(at, 'Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-30 17:59'};'open' +d(at, 'Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-30 18:00'};'closed' +d(at).tz('Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-29 08:00'};'open' +d(at).tz('Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-31 07:00'};'open' +d(at).tz('Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-31 15:59'};'open' +d(at).tz('Europe/Berlin').hour() in [9..17] ? 'open' : 'closed';{at: '2025-03-31 16:00'};'closed' +price * (d(at).day() == d(at).endOf('month').day() ? 0.9 : 1);{at: '2024-02-29', price: 100};90.0 +price * (d(at).day() == d(at).endOf('month').day() ? 0.9 : 1);{at: '2023-02-28', price: 100};90.0 +price * (d(at).day() == d(at).endOf('month').day() ? 0.9 : 1);{at: '2024-02-28', price: 100};100 +price * (d(at).day() == d(at).endOf('month').day() ? 0.9 : 1);{at: '2025-04-30 12:00', price: 100};90.0 +price * (d(at).day() == d(at).endOf('month').day() ? 0.9 : 1);{at: '2025-04-29', price: 100};100 +d(at).isLeapYear() and d(at).month() == 2 ? 29 : d(at).endOf('M').day();{at: '2024-02-10'};29 +d(at).isLeapYear() and d(at).month() == 2 ? 29 : d(at).endOf('M').day();{at: '2023-02-10'};28 +d(at).isLeapYear() and d(at).month() == 2 ? 29 : d(at).endOf('M').day();{at: '2100-02-01'};28 +d(at).isLeapYear() and d(at).month() == 2 ? 29 : d(at).endOf('M').day();{at: '2000-02-01'};29 +d(at).isLeapYear() and d(at).month() == 2 ? 29 : d(at).endOf('M').day();{at: '2025-09-09'};30 +# templates with formatted dates +`Due ${d(s).add(30, 'd').format('%d %b %Y')}`;{s: '2024-02-01'};'Due 02 Mar 2024' +`Due ${d(s).add(30, 'd').format('%d %b %Y')}`;{s: '2024-12-15'};'Due 14 Jan 2025' +`Due ${d(s).add(30, 'd').format('%d %b %Y')}`;{s: '2025-01-31 23:00'};'Due 02 Mar 2025' +`Due ${d(s).add(30, 'd').format('%d %b %Y')}`;{s: 'bad'};'Due Invalid date' +`${d(s).format('%A')} is day ${d(s).weekday()} of week ${d(s).week()}`;{s: '2025-03-20'};'Thursday is day 4 of week 12' +`${d(s).format('%A')} is day ${d(s).weekday()} of week ${d(s).week()}`;{s: '2024-12-30'};'Monday is day 1 of week 1' +`${d(s).format('%A')} is day ${d(s).weekday()} of week ${d(s).week()}`;{s: '2021-01-03'};'Sunday is day 7 of week 53' +`Q${d(s).quarter()} ${d(s).year()}`;{s: '2025-03-31 23:59:59'};'Q1 2025' +`Q${d(s).quarter()} ${d(s).year()}`;{s: '2025-04-01'};'Q2 2025' +`Q${d(s).quarter()} ${d(s).year()}`;{s: '2024-12-31'};'Q4 2024' +`${d(s, z).format('%H:%M')} ${z}`;{s: '2025-03-20 09:30', z: 'UTC'};'09:30 UTC' +`${d(s, z).format('%H:%M')} ${z}`;{s: '2025-03-20 09:30', z: 'Europe/Berlin'};'09:30 Europe/Berlin' +`${d(s, z).format('%H:%M')} ${z}`;{s: '2025-03-20 09:30', z: 'Asia/Kolkata'};'09:30 Asia/Kolkata' +`${d(s, z).format('%H:%M')} ${z}`;{s: '2025-03-20 09:30', z: 'Etc/GMT+5'};'09:30 Etc/GMT+5' +`${d(s).diff(d(t), 'd')} days`;{s: '2025-03-20', t: '2025-01-01'};'78 days' +`${d(s).diff(d(t), 'd')} days`;{s: '2024-03-01', t: '2024-02-01'};'29 days' +`${d(s).diff(d(t), 'd')} days`;{s: '2024-01-01', t: '2024-03-01'};'-60 days' +`${d(s).diff(d(t), 'd')} days`;{s: 'x', t: '2025-01-01'};'null days' +`from ${d(s).startOf('week').format('%F')} to ${d(s).endOf('week').format('%F')}`;{s: '2025-03-20'};'from 2025-03-17 to 2025-03-23' +`from ${d(s).startOf('week').format('%F')} to ${d(s).endOf('week').format('%F')}`;{s: '2025-01-01'};'from 2024-12-30 to 2025-01-05' +`from ${d(s).startOf('week').format('%F')} to ${d(s).endOf('week').format('%F')}`;{s: '2024-02-29'};'from 2024-02-26 to 2024-03-03' +`from ${d(s).startOf('week').format('%F')} to ${d(s).endOf('week').format('%F')}`;{s: '2025-03-16 23:59:59'};'from 2025-03-10 to 2025-03-16' +# fallbacks for missing and invalid dates +d(s ?? '2000-01-01').format('%F');{s: '2024-02-29'};'2024-02-29' +d(s ?? '2000-01-01').format('%F');{s: null};'2000-01-01' +d(s ?? '2000-01-01').format('%F');{s: 'bad'};'Invalid date' +d(s ?? '2000-01-01').format('%F');{s: 1700000000000};'2023-11-14' +d(s).isValid() ? d(s).format('%F') : 'n/a';{s: '2024-02-29'};'2024-02-29' +d(s).isValid() ? d(s).format('%F') : 'n/a';{s: null};'n/a' +d(s).isValid() ? d(s).format('%F') : 'n/a';{s: 'bad'};'n/a' +d(s).isValid() ? d(s).format('%F') : 'n/a';{s: '2023-02-29'};'n/a' +d(s).isValid() ? d(s).format('%F') : 'n/a';{s: true};'n/a' +d(s).isValid() ? d(s).format('%F') : 'n/a';{s: 1700000000000};'2023-11-14' +d(s).year() ?? 0;{s: '2024-02-29'};2024 +d(s).year() ?? 0;{s: null};0 +d(s).year() ?? 0;{s: 'bad'};0 +d(s).year() ?? 0;{s: 0};1970 +d(s).diff(d(t), 'day') ?? -1;{s: '2024-03-01', t: '2024-02-01'};29 +d(s).diff(d(t), 'day') ?? -1;{s: null, t: '2024-02-01'};-1 +d(s).diff(d(t), 'day') ?? -1;{s: '2024-03-01', t: 'x'};-1 +(d(s).isValid() ? d(s) : d(t)).add(1, 'd').format('%F');{s: '2024-02-28', t: '2000-01-01'};'2024-02-29' +(d(s).isValid() ? d(s) : d(t)).add(1, 'd').format('%F');{s: 'x', t: '2000-01-01'};'2000-01-02' +(d(s).isValid() ? d(s) : d(t)).add(1, 'd').format('%F');{s: null, t: null};'Invalid date' +d(s).isValid() and d(s).isBefore(d(t));{s: '2024-02-28', t: '2024-03-01'};true +d(s).isValid() and d(s).isBefore(d(t));{s: 'x', t: '2024-03-01'};false +d(s).isValid() and d(s).isBefore(d(t));{s: '2024-03-02', t: '2024-03-01'};false +d(s).add(1, 'M').format('%F') ?? 'none';{s: '2024-01-31'};'2024-02-29' +d(s).add(1, 'M').format('%F') ?? 'none';{s: 'x'};'Invalid date' +d(s).timestamp() ?? 'none';{s: '2024-01-31'};1706659200000 +d(s).timestamp() ?? 'none';{s: 'x'};'none' +d(s).timestamp() ?? 'none';{s: null};'none' +# dates from different zones compared +d(a, za) == d(b, zb);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};true +d(a, za) == d(b, zb);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};true +d(a, za) == d(b, zb);{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};true +d(a, za) == d(b, zb);{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};true +d(a, za) == d(b, zb);{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};true +d(a, za) < d(b, zb);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};false +d(a, za) < d(b, zb);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};false +d(a, za) < d(b, zb);{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};false +d(a, za) < d(b, zb);{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};false +d(a, za) < d(b, zb);{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};false +d(a, za).isSame(d(b, zb));{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};true +d(a, za).isSame(d(b, zb));{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};true +d(a, za).isSame(d(b, zb));{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};true +d(a, za).isSame(d(b, zb));{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};true +d(a, za).isSame(d(b, zb));{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};true +d(a, za).diff(d(b, zb), 'minute');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};0 +d(a, za).diff(d(b, zb), 'minute');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};0 +d(a, za).diff(d(b, zb), 'minute');{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};0 +d(a, za).diff(d(b, zb), 'minute');{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};0 +d(a, za).diff(d(b, zb), 'minute');{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};0 +d(a, za).diff(d(b, zb));{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};0 +d(a, za).diff(d(b, zb));{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};0 +d(a, za).diff(d(b, zb));{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};0 +d(a, za).diff(d(b, zb));{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};0 +d(a, za).diff(d(b, zb));{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};0 +d(a, za).tz(zb).format('%F %R');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};'2025-03-20 05:00' +d(a, za).tz(zb).format('%F %R');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};'2025-03-20 14:30' +d(a, za).tz(zb).format('%F %R');{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};'2025-06-01 05:00' +d(a, za).tz(zb).format('%F %R');{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};'2025-10-25 19:30' +d(a, za).tz(zb).format('%F %R');{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};'2024-12-31 18:30' +d(a, za).tz(zb) == d(b, zb);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};true +d(a, za).tz(zb) == d(b, zb);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};true +d(a, za).tz(zb) == d(b, zb);{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};true +d(a, za).tz(zb) == d(b, zb);{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};true +d(a, za).tz(zb) == d(b, zb);{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};true +d(a, za).isSame(d(b, zb).tz(za), 'day');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};true +d(a, za).isSame(d(b, zb).tz(za), 'day');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};true +d(a, za).isSame(d(b, zb).tz(za), 'day');{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};true +d(a, za).isSame(d(b, zb).tz(za), 'day');{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};true +d(a, za).isSame(d(b, zb).tz(za), 'day');{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};true +max([d(a, za), d(b, zb).add(1, 'm')]);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};'2025-03-20T05:01:00-04:00' +max([d(a, za), d(b, zb).add(1, 'm')]);{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};'2025-03-20T14:31:00+05:30' +max([d(a, za), d(b, zb).add(1, 'm')]);{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};'2025-06-01T05:01:00Z' +max([d(a, za), d(b, zb).add(1, 'm')]);{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};'2025-10-25T19:31:00-04:00' +max([d(a, za), d(b, zb).add(1, 'm')]);{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};'2024-12-31T18:31:00Z' +d(a, za).startOf('day') < d(b, zb).startOf('day');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 05:00', zb: 'America/New_York'};true +d(a, za).startOf('day') < d(b, zb).startOf('day');{a: '2025-03-20 10:00', za: 'Europe/Berlin', b: '2025-03-20 14:30', zb: 'Asia/Kolkata'};false +d(a, za).startOf('day') < d(b, zb).startOf('day');{a: '2025-06-01 00:00', za: 'Etc/GMT+5', b: '2025-06-01 05:00', zb: 'UTC'};false +d(a, za).startOf('day') < d(b, zb).startOf('day');{a: '2025-10-26 01:30', za: 'Europe/Berlin', b: '2025-10-25 19:30', zb: 'America/New_York'};false +d(a, za).startOf('day') < d(b, zb).startOf('day');{a: '2025-01-01 00:00', za: 'Asia/Kolkata', b: '2024-12-31 18:30', zb: 'UTC'};false +# chained calendar arithmetic on input rows (fast-path shapes) +d(s).startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-31T00:00:00Z' +d(s).startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-29T00:00:00Z' +d(s).startOf('M').add(1, 'M').sub(1, 'd');{s: '2023-12-31 23:30:15'};'2023-12-31T00:00:00Z' +d(s).startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-08-31 18:00'};'2025-08-31T00:00:00Z' +d(s).startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-03-16 08:45:00'};'2025-03-31T00:00:00Z' +d(s).startOf('M').add(1, 'M').sub(1, 'd');{s: null};'Invalid date' +d(s).add(1, 'M').endOf('M');{s: '2024-01-31 10:20:30'};'2024-02-29T23:59:59Z' +d(s).add(1, 'M').endOf('M');{s: '2024-02-29 23:59:59'};'2024-03-31T23:59:59Z' +d(s).add(1, 'M').endOf('M');{s: '2023-12-31 23:30:15'};'2024-01-31T23:59:59Z' +d(s).add(1, 'M').endOf('M');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59Z' +d(s).add(1, 'M').endOf('M');{s: '2025-03-16 08:45:00'};'2025-04-30T23:59:59Z' +d(s).add(1, 'M').endOf('M');{s: null};'Invalid date' +d(s).startOf('y').add(6, 'M').sub(1, 's');{s: '2024-01-31 10:20:30'};'2024-06-30T23:59:59Z' +d(s).startOf('y').add(6, 'M').sub(1, 's');{s: '2024-02-29 23:59:59'};'2024-06-30T23:59:59Z' +d(s).startOf('y').add(6, 'M').sub(1, 's');{s: '2023-12-31 23:30:15'};'2023-06-30T23:59:59Z' +d(s).startOf('y').add(6, 'M').sub(1, 's');{s: '2025-08-31 18:00'};'2025-06-30T23:59:59Z' +d(s).startOf('y').add(6, 'M').sub(1, 's');{s: '2025-03-16 08:45:00'};'2025-06-30T23:59:59Z' +d(s).startOf('y').add(6, 'M').sub(1, 's');{s: null};'Invalid date' +d(s).startOf('w').add(4, 'd').add(17, 'h');{s: '2024-01-31 10:20:30'};'2024-02-02T17:00:00Z' +d(s).startOf('w').add(4, 'd').add(17, 'h');{s: '2024-02-29 23:59:59'};'2024-03-01T17:00:00Z' +d(s).startOf('w').add(4, 'd').add(17, 'h');{s: '2023-12-31 23:30:15'};'2023-12-29T17:00:00Z' +d(s).startOf('w').add(4, 'd').add(17, 'h');{s: '2025-08-31 18:00'};'2025-08-29T17:00:00Z' +d(s).startOf('w').add(4, 'd').add(17, 'h');{s: '2025-03-16 08:45:00'};'2025-03-14T17:00:00Z' +d(s).startOf('w').add(4, 'd').add(17, 'h');{s: null};'Invalid date' +d(s).endOf('d').startOf('h');{s: '2024-01-31 10:20:30'};'2024-01-31T23:00:00Z' +d(s).endOf('d').startOf('h');{s: '2024-02-29 23:59:59'};'2024-02-29T23:00:00Z' +d(s).endOf('d').startOf('h');{s: '2023-12-31 23:30:15'};'2023-12-31T23:00:00Z' +d(s).endOf('d').startOf('h');{s: '2025-08-31 18:00'};'2025-08-31T23:00:00Z' +d(s).endOf('d').startOf('h');{s: '2025-03-16 08:45:00'};'2025-03-16T23:00:00Z' +d(s).endOf('d').startOf('h');{s: null};'Invalid date' +d(s).sub(1, 'q').startOf('q');{s: '2024-01-31 10:20:30'};'2023-10-01T00:00:00Z' +d(s).sub(1, 'q').startOf('q');{s: '2024-02-29 23:59:59'};'2023-10-01T00:00:00Z' +d(s).sub(1, 'q').startOf('q');{s: '2023-12-31 23:30:15'};'2023-07-01T00:00:00Z' +d(s).sub(1, 'q').startOf('q');{s: '2025-08-31 18:00'};'2025-04-01T00:00:00Z';bug: the month is moved before the day is reset, April 31 does not exist +d(s).sub(1, 'q').startOf('q');{s: '2025-03-16 08:45:00'};'2024-10-01T00:00:00Z' +d(s).sub(1, 'q').startOf('q');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-29T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M').add(1, 'M').sub(1, 'd');{s: '2023-12-31 23:30:15'};'2023-12-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-08-31 18:00'};'2025-08-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-03-16 08:45:00'};'2025-03-31T00:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('M').add(1, 'M').sub(1, 'd');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').add(1, 'M').endOf('M');{s: '2024-01-31 10:20:30'};'2024-02-29T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1, 'M').endOf('M');{s: '2024-02-29 23:59:59'};'2024-03-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1, 'M').endOf('M');{s: '2023-12-31 23:30:15'};'2024-01-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1, 'M').endOf('M');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1, 'M').endOf('M');{s: '2025-03-16 08:45:00'};'2025-04-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').add(1, 'M').endOf('M');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').startOf('y').add(6, 'M').sub(1, 's');{s: '2024-01-31 10:20:30'};'2024-06-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('y').add(6, 'M').sub(1, 's');{s: '2024-02-29 23:59:59'};'2024-06-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('y').add(6, 'M').sub(1, 's');{s: '2023-12-31 23:30:15'};'2023-06-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('y').add(6, 'M').sub(1, 's');{s: '2025-08-31 18:00'};'2025-06-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('y').add(6, 'M').sub(1, 's');{s: '2025-03-16 08:45:00'};'2025-06-30T23:59:59-05:00' +d(s, 'Etc/GMT+5').startOf('y').add(6, 'M').sub(1, 's');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').startOf('w').add(4, 'd').add(17, 'h');{s: '2024-01-31 10:20:30'};'2024-02-02T17:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('w').add(4, 'd').add(17, 'h');{s: '2024-02-29 23:59:59'};'2024-03-01T17:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('w').add(4, 'd').add(17, 'h');{s: '2023-12-31 23:30:15'};'2023-12-29T17:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('w').add(4, 'd').add(17, 'h');{s: '2025-08-31 18:00'};'2025-08-29T17:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('w').add(4, 'd').add(17, 'h');{s: '2025-03-16 08:45:00'};'2025-03-14T17:00:00-05:00' +d(s, 'Etc/GMT+5').startOf('w').add(4, 'd').add(17, 'h');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').endOf('d').startOf('h');{s: '2024-01-31 10:20:30'};'2024-01-31T23:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('d').startOf('h');{s: '2024-02-29 23:59:59'};'2024-02-29T23:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('d').startOf('h');{s: '2023-12-31 23:30:15'};'2023-12-31T23:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('d').startOf('h');{s: '2025-08-31 18:00'};'2025-08-31T23:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('d').startOf('h');{s: '2025-03-16 08:45:00'};'2025-03-16T23:00:00-05:00' +d(s, 'Etc/GMT+5').endOf('d').startOf('h');{s: null};'Invalid date' +d(s, 'Etc/GMT+5').sub(1, 'q').startOf('q');{s: '2024-01-31 10:20:30'};'2023-10-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'q').startOf('q');{s: '2024-02-29 23:59:59'};'2023-10-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'q').startOf('q');{s: '2023-12-31 23:30:15'};'2023-07-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'q').startOf('q');{s: '2025-08-31 18:00'};'2025-04-01T00:00:00-05:00';bug: the month is moved before the day is reset, April 31 does not exist +d(s, 'Etc/GMT+5').sub(1, 'q').startOf('q');{s: '2025-03-16 08:45:00'};'2024-10-01T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(1, 'q').startOf('q');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-29T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M').add(1, 'M').sub(1, 'd');{s: '2023-12-31 23:30:15'};'2023-12-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-08-31 18:00'};'2025-08-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-03-16 08:45:00'};'2025-03-31T00:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('M').add(1, 'M').sub(1, 'd');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').add(1, 'M').endOf('M');{s: '2024-01-31 10:20:30'};'2024-02-29T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'M').endOf('M');{s: '2024-02-29 23:59:59'};'2024-03-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'M').endOf('M');{s: '2023-12-31 23:30:15'};'2024-01-31T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'M').endOf('M');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'M').endOf('M');{s: '2025-03-16 08:45:00'};'2025-04-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').add(1, 'M').endOf('M');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').startOf('y').add(6, 'M').sub(1, 's');{s: '2024-01-31 10:20:30'};'2024-06-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').startOf('y').add(6, 'M').sub(1, 's');{s: '2024-02-29 23:59:59'};'2024-06-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').startOf('y').add(6, 'M').sub(1, 's');{s: '2023-12-31 23:30:15'};'2023-06-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').startOf('y').add(6, 'M').sub(1, 's');{s: '2025-08-31 18:00'};'2025-06-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').startOf('y').add(6, 'M').sub(1, 's');{s: '2025-03-16 08:45:00'};'2025-06-30T23:59:59+05:30' +d(s, 'Asia/Kolkata').startOf('y').add(6, 'M').sub(1, 's');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').startOf('w').add(4, 'd').add(17, 'h');{s: '2024-01-31 10:20:30'};'2024-02-02T17:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('w').add(4, 'd').add(17, 'h');{s: '2024-02-29 23:59:59'};'2024-03-01T17:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('w').add(4, 'd').add(17, 'h');{s: '2023-12-31 23:30:15'};'2023-12-29T17:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('w').add(4, 'd').add(17, 'h');{s: '2025-08-31 18:00'};'2025-08-29T17:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('w').add(4, 'd').add(17, 'h');{s: '2025-03-16 08:45:00'};'2025-03-14T17:00:00+05:30' +d(s, 'Asia/Kolkata').startOf('w').add(4, 'd').add(17, 'h');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').endOf('d').startOf('h');{s: '2024-01-31 10:20:30'};'2024-01-31T23:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('d').startOf('h');{s: '2024-02-29 23:59:59'};'2024-02-29T23:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('d').startOf('h');{s: '2023-12-31 23:30:15'};'2023-12-31T23:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('d').startOf('h');{s: '2025-08-31 18:00'};'2025-08-31T23:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('d').startOf('h');{s: '2025-03-16 08:45:00'};'2025-03-16T23:00:00+05:30' +d(s, 'Asia/Kolkata').endOf('d').startOf('h');{s: null};'Invalid date' +d(s, 'Asia/Kolkata').sub(1, 'q').startOf('q');{s: '2024-01-31 10:20:30'};'2023-10-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q').startOf('q');{s: '2024-02-29 23:59:59'};'2023-10-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q').startOf('q');{s: '2023-12-31 23:30:15'};'2023-07-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q').startOf('q');{s: '2025-08-31 18:00'};'2025-04-01T00:00:00+05:30';bug: the month is moved before the day is reset, April 31 does not exist +d(s, 'Asia/Kolkata').sub(1, 'q').startOf('q');{s: '2025-03-16 08:45:00'};'2024-10-01T00:00:00+05:30' +d(s, 'Asia/Kolkata').sub(1, 'q').startOf('q');{s: null};'Invalid date' +d(s, 'Etc/GMT-14').startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-01-31 10:20:30'};'2024-01-31T00:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('M').add(1, 'M').sub(1, 'd');{s: '2024-02-29 23:59:59'};'2024-02-29T00:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('M').add(1, 'M').sub(1, 'd');{s: '2023-12-31 23:30:15'};'2023-12-31T00:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-08-31 18:00'};'2025-08-31T00:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('M').add(1, 'M').sub(1, 'd');{s: '2025-03-16 08:45:00'};'2025-03-31T00:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('M').add(1, 'M').sub(1, 'd');{s: null};'Invalid date' +d(s, 'Etc/GMT-14').add(1, 'M').endOf('M');{s: '2024-01-31 10:20:30'};'2024-02-29T23:59:59+14:00' +d(s, 'Etc/GMT-14').add(1, 'M').endOf('M');{s: '2024-02-29 23:59:59'};'2024-03-31T23:59:59+14:00' +d(s, 'Etc/GMT-14').add(1, 'M').endOf('M');{s: '2023-12-31 23:30:15'};'2024-01-31T23:59:59+14:00' +d(s, 'Etc/GMT-14').add(1, 'M').endOf('M');{s: '2025-08-31 18:00'};'2025-09-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').add(1, 'M').endOf('M');{s: '2025-03-16 08:45:00'};'2025-04-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').add(1, 'M').endOf('M');{s: null};'Invalid date' +d(s, 'Etc/GMT-14').startOf('y').add(6, 'M').sub(1, 's');{s: '2024-01-31 10:20:30'};'2024-06-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').startOf('y').add(6, 'M').sub(1, 's');{s: '2024-02-29 23:59:59'};'2024-06-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').startOf('y').add(6, 'M').sub(1, 's');{s: '2023-12-31 23:30:15'};'2023-06-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').startOf('y').add(6, 'M').sub(1, 's');{s: '2025-08-31 18:00'};'2025-06-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').startOf('y').add(6, 'M').sub(1, 's');{s: '2025-03-16 08:45:00'};'2025-06-30T23:59:59+14:00' +d(s, 'Etc/GMT-14').startOf('y').add(6, 'M').sub(1, 's');{s: null};'Invalid date' +d(s, 'Etc/GMT-14').startOf('w').add(4, 'd').add(17, 'h');{s: '2024-01-31 10:20:30'};'2024-02-02T17:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('w').add(4, 'd').add(17, 'h');{s: '2024-02-29 23:59:59'};'2024-03-01T17:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('w').add(4, 'd').add(17, 'h');{s: '2023-12-31 23:30:15'};'2023-12-29T17:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('w').add(4, 'd').add(17, 'h');{s: '2025-08-31 18:00'};'2025-08-29T17:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('w').add(4, 'd').add(17, 'h');{s: '2025-03-16 08:45:00'};'2025-03-14T17:00:00+14:00' +d(s, 'Etc/GMT-14').startOf('w').add(4, 'd').add(17, 'h');{s: null};'Invalid date' +d(s, 'Etc/GMT-14').endOf('d').startOf('h');{s: '2024-01-31 10:20:30'};'2024-01-31T23:00:00+14:00' +d(s, 'Etc/GMT-14').endOf('d').startOf('h');{s: '2024-02-29 23:59:59'};'2024-02-29T23:00:00+14:00' +d(s, 'Etc/GMT-14').endOf('d').startOf('h');{s: '2023-12-31 23:30:15'};'2023-12-31T23:00:00+14:00' +d(s, 'Etc/GMT-14').endOf('d').startOf('h');{s: '2025-08-31 18:00'};'2025-08-31T23:00:00+14:00' +d(s, 'Etc/GMT-14').endOf('d').startOf('h');{s: '2025-03-16 08:45:00'};'2025-03-16T23:00:00+14:00' +d(s, 'Etc/GMT-14').endOf('d').startOf('h');{s: null};'Invalid date' +d(s, 'Etc/GMT-14').sub(1, 'q').startOf('q');{s: '2024-01-31 10:20:30'};'2023-10-01T00:00:00+14:00' +d(s, 'Etc/GMT-14').sub(1, 'q').startOf('q');{s: '2024-02-29 23:59:59'};'2023-10-01T00:00:00+14:00' +d(s, 'Etc/GMT-14').sub(1, 'q').startOf('q');{s: '2023-12-31 23:30:15'};'2023-07-01T00:00:00+14:00' +d(s, 'Etc/GMT-14').sub(1, 'q').startOf('q');{s: '2025-08-31 18:00'};'2025-04-01T00:00:00+14:00';bug: the month is moved before the day is reset, April 31 does not exist +d(s, 'Etc/GMT-14').sub(1, 'q').startOf('q');{s: '2025-03-16 08:45:00'};'2024-10-01T00:00:00+14:00' +d(s, 'Etc/GMT-14').sub(1, 'q').startOf('q');{s: null};'Invalid date' +# amount and unit from the input +d(s).add(n, u);{s: '2024-01-31 12:00', n: 1, u: 'd'};'2024-02-01T12:00:00Z' +d(s).add(n, u);{s: '2024-01-31 12:00', n: -1, u: 'M'};'2023-12-31T12:00:00Z' +d(s).add(n, u);{s: '2024-01-31 12:00', n: 2, u: 'q'};'2024-07-31T12:00:00Z' +d(s).add(n, u);{s: '2024-01-31 12:00', n: 36, u: 'h'};'2024-02-02T00:00:00Z' +d(s).add(n, u);{s: '2024-01-31 12:00', n: 0, u: 'y'};'2024-01-31T12:00:00Z' +d(s).add(n, u);{s: '2024-01-31 12:00', n: 1.5, u: 'd'};'2024-02-02T00:00:00Z' +d(s).add(n, u);{s: '2024-01-31 12:00', n: 1, u: 'fortnight'};!error +d(s).add(n, u);{s: '2024-01-31 12:00', n: '2', u: 'd'};!error +d(s).add(n, u);{s: '2024-01-31 12:00', n: null, u: 'd'};!error +d(s).add(n, u);{s: '2024-01-31 12:00', n: 1, u: null};!error +d(s, 'Etc/GMT+5').sub(n, u);{s: '2024-03-31', n: 1, u: 'M'};'2024-02-29T00:00:00-05:00' +d(s, 'Etc/GMT+5').sub(n, u);{s: '2024-02-29', n: 1, u: 'y'};'2023-02-28T00:00:00-05:00';bug: adding a year to Feb 29 gives an invalid date instead of clamping to Feb 28 like months do +d(s, 'Etc/GMT+5').sub(n, u);{s: '2025-01-01', n: 1, u: 's'};'2024-12-31T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(n, u);{s: '2024-12-31 23:59:59', n: 52, u: 'w'};'2024-01-02T23:59:59-05:00' +d(s, 'Etc/GMT+5').sub(n, u);{s: '2024-05-31', n: 1, u: 'q'};'2024-02-29T00:00:00-05:00' +# startOf week stepping back through a transition day +d(s, 'Europe/Berlin').startOf('week');{s: '2025-04-02 02:30'};'2025-03-31T00:00:00+02:00' +d(s, 'Europe/Berlin').startOf('week');{s: '2025-04-02 12:00'};'2025-03-31T00:00:00+02:00' +d(s, 'America/New_York').startOf('week');{s: '2025-03-12 02:30'};'2025-03-10T00:00:00-04:00' +d(s, 'America/New_York').startOf('week');{s: '2025-03-12 09:00'};'2025-03-10T00:00:00-04:00' +d(s, 'Europe/Berlin').startOf('week');{s: '2025-03-26 02:30'};'2025-03-24T00:00:00+01:00' +d(s, 'Europe/Berlin').endOf('week');{s: '2025-03-26 02:30'};'2025-03-30T23:59:59+02:00';bug: endOf('week') steps through the transition day at the same wall time and gives an invalid date +d(s, 'Europe/Berlin').endOf('week');{s: '2025-10-22 02:30'};'2025-10-26T23:59:59+01:00';bug: endOf('week') steps through the transition day at the same wall time and gives an invalid date +d(s, 'America/New_York').endOf('week');{s: '2025-03-05 02:30'};'2025-03-09T23:59:59-04:00';bug: endOf('week') steps through the transition day at the same wall time and gives an invalid date +d(s, 'America/New_York').endOf('week');{s: '2025-03-05 12:00'};'2025-03-09T23:59:59-04:00' diff --git a/core/expression/tests/spec/standard/17-01-realistic.csv b/core/expression/tests/spec/standard/17-01-realistic.csv new file mode 100644 index 00000000..4e936388 --- /dev/null +++ b/core/expression/tests/spec/standard/17-01-realistic.csv @@ -0,0 +1,541 @@ +expression (string);input (json 5);output (json 5);note +# Quote: subtotal, discount over a threshold, rounded tax, total +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 10, qty: 5, rate: 0.2};60.0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 25, qty: 8, rate: 0.0825};194.85 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 19.99, qty: 3, rate: 0.07};64.17 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 100, qty: 1, rate: 0.1};110.0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 100.01, qty: 1, rate: 0};90.009 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 0, qty: 0, rate: 0.5};0.0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 33.33, qty: 7, rate: 0.19};249.879 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total";{price: 5, qty: 2};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 10, qty: 5, rate: 0.2};{subtotal: 50, discount: 0, taxable: 50, tax: 10.0, total: 60.0} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 25, qty: 8, rate: 0.0825};{subtotal: 200, discount: 20.0, taxable: 180.0, tax: 14.85, total: 194.85} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 19.99, qty: 3, rate: 0.07};{subtotal: 59.97, discount: 0, taxable: 59.97, tax: 4.20, total: 64.17} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 100, qty: 1, rate: 0.1};{subtotal: 100, discount: 0, taxable: 100, tax: 10.0, total: 110.0} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 100.01, qty: 1, rate: 0};{subtotal: 100.01, discount: 10.001, taxable: 90.009, tax: 0.00, total: 90.009} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 0, qty: 0, rate: 0.5};{subtotal: 0, discount: 0, taxable: 0, tax: 0.0, total: 0.0} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 33.33, qty: 7, rate: 0.19};{subtotal: 233.31, discount: 23.331, taxable: 209.979, tax: 39.90, total: 249.879} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax";{price: 5, qty: 2};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 10, qty: 5, rate: 0.2};{subtotal: 50, discount: 0, tax: 10.0, total: 60.0} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 25, qty: 8, rate: 0.0825};{subtotal: 200, discount: 20.0, tax: 14.85, total: 194.85} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 19.99, qty: 3, rate: 0.07};{subtotal: 59.97, discount: 0, tax: 4.20, total: 64.17} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 100, qty: 1, rate: 0.1};{subtotal: 100, discount: 0, tax: 10.0, total: 110.0} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 100.01, qty: 1, rate: 0};{subtotal: 100.01, discount: 10.001, tax: 0.00, total: 90.009} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 0, qty: 0, rate: 0.5};{subtotal: 0, discount: 0, tax: 0.0, total: 0.0} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 33.33, qty: 7, rate: 0.19};{subtotal: 233.31, discount: 23.331, tax: 39.90, total: 249.879} +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; {subtotal: subtotal, discount: discount, tax: tax, total: total}";{price: 5, qty: 2};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 10, qty: 5, rate: 0.2};[50, 60.0] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 25, qty: 8, rate: 0.0825};[200, 194.85] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 19.99, qty: 3, rate: 0.07};[59.97, 64.17] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 100, qty: 1, rate: 0.1};[100, 110.0] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 100.01, qty: 1, rate: 0};[100.01, 90.009] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 0, qty: 0, rate: 0.5};[0, 0.0] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 33.33, qty: 7, rate: 0.19};[233.31, 249.879] +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; [subtotal, total]";{price: 5, qty: 2};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 10, qty: 5, rate: 0.2};'50 -> 60.0' +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 25, qty: 8, rate: 0.0825};'200 -> 194.85' +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 19.99, qty: 3, rate: 0.07};'59.97 -> 64.17' +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 100, qty: 1, rate: 0.1};'100 -> 110.0' +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 100.01, qty: 1, rate: 0};'100.01 -> 90.009' +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 0, qty: 0, rate: 0.5};'0 -> 0';question: a zero product drops the operand scale (0 * 0.5 prints 0, see 02-numbers) +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 33.33, qty: 7, rate: 0.19};'233.31 -> 249.879' +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; `${subtotal} -> ${total}`";{price: 5, qty: 2};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 10, qty: 5, rate: 0.2};false +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 25, qty: 8, rate: 0.0825};true +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 19.99, qty: 3, rate: 0.07};false +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 100, qty: 1, rate: 0.1};true +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 100.01, qty: 1, rate: 0};false +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 0, qty: 0, rate: 0.5};false +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 33.33, qty: 7, rate: 0.19};true +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; total > 100";{price: 5, qty: 2};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 10, qty: 5, rate: 0.2};0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 25, qty: 8, rate: 0.0825};20.0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 19.99, qty: 3, rate: 0.07};0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 100, qty: 1, rate: 0.1};0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 100.01, qty: 1, rate: 0};10.001 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 0, qty: 0, rate: 0.5};0 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 33.33, qty: 7, rate: 0.19};23.331 +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: null, qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{qty: 2, rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 5, qty: '2', rate: 0.1};!error +"subtotal = price * qty; discount = subtotal > 100 ? subtotal * 0.1 : 0; taxable = subtotal - discount; tax = round(taxable * rate, 2); total = taxable + tax; discount";{price: 5, qty: 2};!error +# Quote: line items, percentage discount, free shipping over a threshold +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 10, qty: 2}, {price: 5, qty: 1}], threshold: 100, pct: 10};30.99 +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 60, qty: 2}], threshold: 100, pct: 10};108 +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 12.50, qty: 4}, {price: 0.99, qty: 10}], threshold: 50, pct: 15};50.91 +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [], threshold: 0, pct: 50};5.99 +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 55, qty: 1}], threshold: 1000, pct: 5};55 +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 49, qty: 1}, {price: 1, qty: 1}], threshold: 50, pct: 0};55.99 +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 10, qty: null}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 10}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: null, threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; total";{items: [{price: 200, qty: 1}], pct: 10};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 10, qty: 2}, {price: 5, qty: 1}], threshold: 100, pct: 10};{subtotal: 25, discount: 0, shipping: 5.99, total: 30.99} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 60, qty: 2}], threshold: 100, pct: 10};{subtotal: 120, discount: 12, shipping: 0, total: 108} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 12.50, qty: 4}, {price: 0.99, qty: 10}], threshold: 50, pct: 15};{subtotal: 59.90, discount: 8.99, shipping: 0, total: 50.91} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [], threshold: 0, pct: 50};{subtotal: 0, discount: 0, shipping: 5.99, total: 5.99} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 55, qty: 1}], threshold: 1000, pct: 5};{subtotal: 55, discount: 0, shipping: 0, total: 55} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 49, qty: 1}, {price: 1, qty: 1}], threshold: 50, pct: 0};{subtotal: 50, discount: 0, shipping: 5.99, total: 55.99} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 10, qty: null}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 10}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: null, threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping";{items: [{price: 200, qty: 1}], pct: 10};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 10, qty: 2}, {price: 5, qty: 1}], threshold: 100, pct: 10};{total: 30.99, free: false} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 60, qty: 2}], threshold: 100, pct: 10};{total: 108, free: true} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 12.50, qty: 4}, {price: 0.99, qty: 10}], threshold: 50, pct: 15};{total: 50.91, free: true} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [], threshold: 0, pct: 50};{total: 5.99, free: false} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 55, qty: 1}], threshold: 1000, pct: 5};{total: 55, free: true} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 49, qty: 1}, {price: 1, qty: 1}], threshold: 50, pct: 0};{total: 55.99, free: false} +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 10, qty: null}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 10}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: null, threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; {total: total, free: shipping == 0}";{items: [{price: 200, qty: 1}], pct: 10};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 10, qty: 2}, {price: 5, qty: 1}], threshold: 100, pct: 10};'25|0|5.99|30.99' +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 60, qty: 2}], threshold: 100, pct: 10};'120|12|0|108' +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 12.50, qty: 4}, {price: 0.99, qty: 10}], threshold: 50, pct: 15};'59.90|8.99|0|50.91' +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [], threshold: 0, pct: 50};'0|0|5.99|5.99' +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 55, qty: 1}], threshold: 1000, pct: 5};'55|0|0|55' +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 49, qty: 1}, {price: 1, qty: 1}], threshold: 50, pct: 0};'50|0|5.99|55.99' +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 10, qty: null}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 10}], threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: null, threshold: 0, pct: 0};!error +"subtotal = sum(map(items, #.price * #.qty)); discount = subtotal >= threshold ? round(subtotal * pct / 100, 2) : 0; shipping = subtotal - discount > 50 ? 0 : 5.99; total = subtotal - discount + shipping; `${subtotal}|${discount}|${shipping}|${total}`";{items: [{price: 200, qty: 1}], pct: 10};!error +# Quote: quantity tiers, coupon defaulting through ??, floor at zero +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 2, qty: 5};{tier: 'bronze', net: 10} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 2, qty: 10, coupon: 3};{tier: 'silver', net: 15.0} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 1.5, qty: 100, coupon: null};{tier: 'gold', net: 120.00} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 1, qty: 9, coupon: 20};{tier: 'bronze', net: 0} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 3, qty: 250, coupon: 0.5};{tier: 'gold', net: 599.5} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 2, qty: 0};{tier: 'bronze', net: 0} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 2, qty: 10, coupon: 'SAVE'};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{price: 2, qty: null};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); {tier: tier, net: net}";{qty: 5};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 2, qty: 5};10 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 2, qty: 10, coupon: 3};15.0 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 1.5, qty: 100, coupon: null};120.00 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 1, qty: 9, coupon: 20};0 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 3, qty: 250, coupon: 0.5};599.5 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 2, qty: 0};0 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 2, qty: 10, coupon: 'SAVE'};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{price: 2, qty: null};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); net";{qty: 5};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 2, qty: 5};{base: 10, tier: 'bronze', pct: 0, coupon: 0, net: 10} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 2, qty: 10, coupon: 3};{base: 20, tier: 'silver', pct: 0.1, coupon: 3, net: 15.0} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 1.5, qty: 100, coupon: null};{base: 150.0, tier: 'gold', pct: 0.2, coupon: 0, net: 120.00} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 1, qty: 9, coupon: 20};{base: 9, tier: 'bronze', pct: 0, coupon: 20, net: 0} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 3, qty: 250, coupon: 0.5};{base: 750, tier: 'gold', pct: 0.2, coupon: 0.5, net: 599.5} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 2, qty: 0};{base: 0, tier: 'bronze', pct: 0, coupon: 0, net: 0} +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 2, qty: 10, coupon: 'SAVE'};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{price: 2, qty: null};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0])";{qty: 5};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 2, qty: 5};'bronze:10' +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 2, qty: 10, coupon: 3};'silver:15.0' +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 1.5, qty: 100, coupon: null};'gold:120.00' +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 1, qty: 9, coupon: 20};'bronze:0' +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 3, qty: 250, coupon: 0.5};'gold:599.5' +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 2, qty: 0};'bronze:0' +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 2, qty: 10, coupon: 'SAVE'};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{price: 2, qty: null};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); `${tier}:${net}`";{qty: 5};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 2, qty: 5};0 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 2, qty: 10, coupon: 3};3 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 1.5, qty: 100, coupon: null};0 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 1, qty: 9, coupon: 20};20 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 3, qty: 250, coupon: 0.5};0.5 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 2, qty: 0};0 +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 2, qty: 10, coupon: 'SAVE'};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{price: 2, qty: null};!error +"base = price * qty; tier = qty >= 100 ? 'gold' : qty >= 10 ? 'silver' : 'bronze'; pct = tier == 'gold' ? 0.2 : tier == 'silver' ? 0.1 : 0; coupon = coupon ?? 0; net = max([base * (1 - pct) - coupon, 0]); coupon";{qty: 5};!error +# Quote: tax rate looked up from an object literal by input key +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 100, region: 'US'};107.00 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 59.99, region: 'EU'};71.99 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 10.05, region: 'UK'};12.06 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 100, region: 'JP'};100 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 100, region: null};100 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 100};100 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 100, region: 1};100 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: null, region: 'US'};!error +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; total";{amount: 0, region: 'EU'};0.0 +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 100, region: 'US'};'US: 107.00' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 59.99, region: 'EU'};'EU: 71.99' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 10.05, region: 'UK'};'UK: 12.06' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 100, region: 'JP'};'JP: 100' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 100, region: null};'NA: 100' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 100};'NA: 100' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 100, region: 1};'1: 100' +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: null, region: 'US'};!error +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; `${region ?? 'NA'}: ${total}`";{amount: 0, region: 'EU'};'EU: 0';question: a zero product drops the operand scale (0 * 0.5 prints 0, see 02-numbers) +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 100, region: 'US'};[0.07, 7.00] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 59.99, region: 'EU'};[0.2, 12.00] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 10.05, region: 'UK'};[0.2, 2.01] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 100, region: 'JP'};[0, 0] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 100, region: null};[0, 0] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 100};[0, 0] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 100, region: 1};[0, 0] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: null, region: 'US'};!error +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax; [rate, tax]";{amount: 0, region: 'EU'};[0.2, 0.0] +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 100, region: 'US'};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0.07, tax: 7.00, total: 107.00} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 59.99, region: 'EU'};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0.2, tax: 12.00, total: 71.99} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 10.05, region: 'UK'};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0.2, tax: 2.01, total: 12.06} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 100, region: 'JP'};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0, tax: 0, total: 100} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 100, region: null};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0, tax: 0, total: 100} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 100};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0, tax: 0, total: 100} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 100, region: 1};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0, tax: 0, total: 100} +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: null, region: 'US'};!error +"rates = {US: 0.07, EU: 0.2, UK: 0.2}; rate = rates[region] ?? 0; tax = round(amount * rate, 2); total = amount + tax";{amount: 0, region: 'EU'};{rates: {US: 0.07, EU: 0.2, UK: 0.2}, rate: 0.2, tax: 0.0, total: 0.0} +# Quote: per-line totals built with map, then aggregated +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: [{sku: 'A', price: 50, qty: 2}, {sku: 'B', price: 10, qty: 3}]};{count: 2, gross: 130, bigSkus: ['A']} +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: [{sku: 'A', price: 99.99, qty: 1}]};{count: 1, gross: 99.99, bigSkus: []} +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: []};{count: 0, gross: 0, bigSkus: []} +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: [{sku: 'X', price: 100, qty: 1}, {sku: 'Y', price: 200, qty: 1}, {sku: 'Z', price: 1, qty: 1}]};{count: 3, gross: 301, bigSkus: ['X', 'Y']} +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: [{sku: 'A', price: 1}]};!error +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: [{price: 150, qty: 1}]};{count: 1, gross: 150, bigSkus: [null]} +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{items: 'none'};!error +"lines = map(items, {sku: #.sku, amount: #.price * #.qty}); gross = sum(map(lines, #.amount)); big = filter(lines, #.amount >= 100); result = {count: len(lines), gross: gross, bigSkus: map(big, #.sku)}; result";{};!error +# Scoring: weighted components with caps and bands +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 50000, age: 30, defaults: 0};75 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 200000, age: 61, defaults: 1};80 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 0, age: 18, defaults: 5};15 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 12345, age: 25, defaults: 2};46 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 100000, age: 60, defaults: 4};80 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 50000, age: null, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 50000, age: 20, defaults: 0};60 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: 50000, age: 30};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; round(score)";{income: '50000', age: 30, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 50000, age: 30, defaults: 0};75.0 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 200000, age: 61, defaults: 1};80.0 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 0, age: 18, defaults: 5};15.0 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 12345, age: 25, defaults: 2};46.1725 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 100000, age: 60, defaults: 4};80.0 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 50000, age: null, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 50000, age: 20, defaults: 0};60.0 +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: 50000, age: 30};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; score";{income: '50000', age: 30, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 50000, age: 30, defaults: 0};{score: 75.0, band: 'high'} +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 200000, age: 61, defaults: 1};{score: 80.0, band: 'high'} +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 0, age: 18, defaults: 5};{score: 15.0, band: 'low'} +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 12345, age: 25, defaults: 2};{score: 46.2, band: 'mid'} +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 100000, age: 60, defaults: 4};{score: 80.0, band: 'high'} +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 50000, age: null, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 50000, age: 20, defaults: 0};{score: 60.0, band: 'mid'} +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: 50000, age: 30};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; {score: round(score, 1), band: score >= 70 ? 'high' : score >= 40 ? 'mid' : 'low'}";{income: '50000', age: 30, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 50000, age: 30, defaults: 0};[50, 100, 100] +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 200000, age: 61, defaults: 1};[100, 50, 75] +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 0, age: 18, defaults: 5};[0, 50, 0] +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 12345, age: 25, defaults: 2};[12.345, 100, 50] +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 100000, age: 60, defaults: 4};[100, 100, 0] +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 50000, age: null, defaults: 0};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 50000, age: 20, defaults: 0};[50, 50, 100] +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: 50000, age: 30};!error +"w = {income: 0.5, age: 0.3, history: 0.2}; incomeScore = min([income / 1000, 100]); ageScore = age >= 25 and age <= 60 ? 100 : 50; historyScore = max([100 - defaults * 25, 0]); score = incomeScore * w.income + ageScore * w.age + historyScore * w.history; [incomeScore, ageScore, historyScore]";{income: '50000', age: 30, defaults: 0};!error +# Scoring: weighted average over a list with a zero-weight guard +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: 80, weight: 1}, {value: 90, weight: 3}]};87.5 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: 70, weight: 2}, {value: 71, weight: 1}]};70.33 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: 100, weight: 0}]};null +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: []};null +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: 88.5, weight: 0.5}, {value: 60, weight: 1.5}]};67.13 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: 1, weight: 1}, {value: 2, weight: 1}, {value: 2, weight: 1}]};1.67 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: 80}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{scores: [{value: null, weight: 1}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore";{};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: 80, weight: 1}, {value: 90, weight: 3}]};{total: 350, weights: 4, avgScore: 87.5} +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: 70, weight: 2}, {value: 71, weight: 1}]};{total: 211, weights: 3, avgScore: 70.33} +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: 100, weight: 0}]};{total: 0, weights: 0, avgScore: null} +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: []};{total: 0, weights: 0, avgScore: null} +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: 88.5, weight: 0.5}, {value: 60, weight: 1.5}]};{total: 134.25, weights: 2.0, avgScore: 67.13} +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: 1, weight: 1}, {value: 2, weight: 1}, {value: 2, weight: 1}]};{total: 5, weights: 3, avgScore: 1.67} +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: 80}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{scores: [{value: null, weight: 1}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2)";{};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: 80, weight: 1}, {value: 90, weight: 3}]};87.5 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: 70, weight: 2}, {value: 71, weight: 1}]};70.33 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: 100, weight: 0}]};-1 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: []};-1 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: 88.5, weight: 0.5}, {value: 60, weight: 1.5}]};67.13 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: 1, weight: 1}, {value: 2, weight: 1}, {value: 2, weight: 1}]};1.67 +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: 80}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{scores: [{value: null, weight: 1}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); avgScore ?? -1";{};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: 80, weight: 1}, {value: 90, weight: 3}]};'87.50';question: division result scale is not normalized (350 / 4 prints 87.50, see 02-numbers) +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: 70, weight: 2}, {value: 71, weight: 1}]};'70.33' +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: 100, weight: 0}]};'null' +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: []};'null' +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: 88.5, weight: 0.5}, {value: 60, weight: 1.5}]};'67.13' +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: 1, weight: 1}, {value: 2, weight: 1}, {value: 2, weight: 1}]};'1.67' +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: 80}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{scores: [{value: null, weight: 1}]};!error +"total = sum(map(scores, #.value * #.weight)); weights = sum(map(scores, #.weight)); avgScore = weights == 0 ? null : round(total / weights, 2); `${avgScore}`";{};!error +# Scoring: grade bands from a percentage +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 45, maxPoints: 50};{pct: 90.0, grade: 'A', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 40, maxPoints: 50};{pct: 80.0, grade: 'B', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 35, maxPoints: 50};{pct: 70.0, grade: 'C', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 10, maxPoints: 50};{pct: 20.0, grade: 'F', passed: false} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 8999, maxPoints: 10000};{pct: 90.0, grade: 'A', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 89995, maxPoints: 100000};{pct: 90.0, grade: 'A', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 0, maxPoints: 1};{pct: 0, grade: 'F', passed: false} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: 1, maxPoints: 0};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{points: null, maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; {pct: pct, grade: grade, passed: passed}";{maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 45, maxPoints: 50};'A' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 40, maxPoints: 50};'B' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 35, maxPoints: 50};'C' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 10, maxPoints: 50};'F' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 8999, maxPoints: 10000};'A' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 89995, maxPoints: 100000};'A' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 0, maxPoints: 1};'F' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: 1, maxPoints: 0};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{points: null, maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; grade";{maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 45, maxPoints: 50};{pct: 90.0, grade: 'A', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 40, maxPoints: 50};{pct: 80.0, grade: 'B', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 35, maxPoints: 50};{pct: 70.0, grade: 'C', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 10, maxPoints: 50};{pct: 20.0, grade: 'F', passed: false} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 8999, maxPoints: 10000};{pct: 90.0, grade: 'A', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 89995, maxPoints: 100000};{pct: 90.0, grade: 'A', passed: true} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 0, maxPoints: 1};{pct: 0, grade: 'F', passed: false} +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: 1, maxPoints: 0};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{points: null, maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'";{maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 45, maxPoints: 50};'A (90.0%)' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 40, maxPoints: 50};'B (80.0%)' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 35, maxPoints: 50};'C (70.0%)' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 10, maxPoints: 50};'retake' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 8999, maxPoints: 10000};'A (90.0%)' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 89995, maxPoints: 100000};'A (90.0%)' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 0, maxPoints: 1};'retake' +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: 1, maxPoints: 0};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{points: null, maxPoints: 10};!error +"pct = round(points / maxPoints * 100, 1); grade = pct >= 90 ? 'A' : pct >= 80 ? 'B' : pct >= 70 ? 'C' : 'F'; passed = grade != 'F'; passed ? `${grade} (${pct}%)` : 'retake'";{maxPoints: 10};!error +# Scoring: points accumulated by reassignment +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 30, member: true, orders: 3};{score: 36} +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 20, member: false, orders: 0};{score: 0} +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 21, member: true, orders: 50, flags: 2};{score: 40} +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 40, member: false, orders: 10, flags: null};{score: 30} +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 40, member: null, orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 40, member: 'yes', orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{age: 40, member: true};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5";{member: true, orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 30, member: true, orders: 3};36 +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 20, member: false, orders: 0};0 +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 21, member: true, orders: 50, flags: 2};40 +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 40, member: false, orders: 10, flags: null};30 +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 40, member: null, orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 40, member: 'yes', orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{age: 40, member: true};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score";{member: true, orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 30, member: true, orders: 3};'vip' +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 20, member: false, orders: 0};'std' +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 21, member: true, orders: 50, flags: 2};'vip' +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 40, member: false, orders: 10, flags: null};'vip' +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 40, member: null, orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 40, member: 'yes', orders: 1};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{age: 40, member: true};!error +"score = 0; score = score + (age >= 21 ? 10 : 0); score = score + (member ? 20 : 0); score = score + min([orders, 10]) * 2; score = score - (flags ?? 0) * 5; score >= 30 ? 'vip' : 'std'";{member: true, orders: 1};!error +# Eligibility: intermediate flags and a reason +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 30, income: 5000, creditScore: 700};{eligible: true, reason: 'ok'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 17, income: 5000, creditScore: 700};{eligible: false, reason: 'underage'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 18, income: 0, creditScore: 800};{eligible: false, reason: 'no income'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 40, income: 1, creditScore: 649};{eligible: false, reason: 'credit'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 40, income: 1};{eligible: false, reason: 'credit'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 40, income: 1, creditScore: null};{eligible: false, reason: 'credit'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 40, income: 1, creditScore: 650};{eligible: true, reason: 'ok'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: null, income: 1, creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; {eligible: eligible, reason: reason}";{age: 40, income: '1', creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 30, income: 5000, creditScore: 700};true +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 17, income: 5000, creditScore: 700};false +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 18, income: 0, creditScore: 800};false +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 40, income: 1, creditScore: 649};false +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 40, income: 1};false +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 40, income: 1, creditScore: null};false +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 40, income: 1, creditScore: 650};true +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: null, income: 1, creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible";{age: 40, income: '1', creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 30, income: 5000, creditScore: 700};{isAdult: true, hasIncome: true, goodCredit: true, eligible: true, reason: 'ok'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 17, income: 5000, creditScore: 700};{isAdult: false, hasIncome: true, goodCredit: true, eligible: false, reason: 'underage'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 18, income: 0, creditScore: 800};{isAdult: true, hasIncome: false, goodCredit: true, eligible: false, reason: 'no income'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 40, income: 1, creditScore: 649};{isAdult: true, hasIncome: true, goodCredit: false, eligible: false, reason: 'credit'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 40, income: 1};{isAdult: true, hasIncome: true, goodCredit: false, eligible: false, reason: 'credit'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 40, income: 1, creditScore: null};{isAdult: true, hasIncome: true, goodCredit: false, eligible: false, reason: 'credit'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 40, income: 1, creditScore: 650};{isAdult: true, hasIncome: true, goodCredit: true, eligible: true, reason: 'ok'} +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: null, income: 1, creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'";{age: 40, income: '1', creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 30, income: 5000, creditScore: 700};'ok' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 17, income: 5000, creditScore: 700};'rejected: underage' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 18, income: 0, creditScore: 800};'rejected: no income' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 40, income: 1, creditScore: 649};'rejected: credit' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 40, income: 1};'rejected: credit' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 40, income: 1, creditScore: null};'rejected: credit' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 40, income: 1, creditScore: 650};'ok' +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: null, income: 1, creditScore: 700};!error +"isAdult = age >= 18; hasIncome = income > 0; goodCredit = (creditScore ?? 0) >= 650; eligible = isAdult and hasIncome and goodCredit; reason = not isAdult ? 'underage' : not hasIncome ? 'no income' : not goodCredit ? 'credit' : 'ok'; eligible ? reason : `rejected: ${reason}`";{age: 40, income: '1', creditScore: 700};!error +# Eligibility: membership test, nested limits +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'US', kyc: {status: 'verified', level: 2}, amount: 9999};true +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'US', kyc: {status: 'verified', level: 1}, amount: 1001};false +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'IR', kyc: {status: 'verified', level: 2}, amount: 1};false +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'DE', kyc: {status: 'pending'}, amount: 100};true +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'DE', kyc: null, amount: 50};true +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'DE', amount: 101};false +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: null, kyc: {status: 'verified', level: 2}, amount: 10000};true +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'KP', amount: null};false +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'DE', kyc: {status: 'verified', level: '2'}, amount: 5000};false +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; allowed";{country: 'DE', kyc: {status: 'verified', level: 2}};!error +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'US', kyc: {status: 'verified', level: 2}, amount: 9999};{allowed: true, limit: 10000} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'US', kyc: {status: 'verified', level: 1}, amount: 1001};{allowed: false, limit: 1000} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'IR', kyc: {status: 'verified', level: 2}, amount: 1};{allowed: false, limit: 10000} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'DE', kyc: {status: 'pending'}, amount: 100};{allowed: true, limit: 100} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'DE', kyc: null, amount: 50};{allowed: true, limit: 100} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'DE', amount: 101};{allowed: false, limit: 100} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: null, kyc: {status: 'verified', level: 2}, amount: 10000};{allowed: true, limit: 10000} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'KP', amount: null};{allowed: false, limit: 100} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'DE', kyc: {status: 'verified', level: '2'}, amount: 5000};{allowed: false, limit: 1000} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit; {allowed: allowed, limit: limit}";{country: 'DE', kyc: {status: 'verified', level: 2}};!error +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'US', kyc: {status: 'verified', level: 2}, amount: 9999};{blocked: false, verified: true, limit: 10000, allowed: true} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'US', kyc: {status: 'verified', level: 1}, amount: 1001};{blocked: false, verified: true, limit: 1000, allowed: false} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'IR', kyc: {status: 'verified', level: 2}, amount: 1};{blocked: true, verified: true, limit: 10000, allowed: false} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'DE', kyc: {status: 'pending'}, amount: 100};{blocked: false, verified: false, limit: 100, allowed: true} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'DE', kyc: null, amount: 50};{blocked: false, verified: false, limit: 100, allowed: true} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'DE', amount: 101};{blocked: false, verified: false, limit: 100, allowed: false} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: null, kyc: {status: 'verified', level: 2}, amount: 10000};{blocked: false, verified: true, limit: 10000, allowed: true} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'KP', amount: null};{blocked: true, verified: false, limit: 100, allowed: false} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'DE', kyc: {status: 'verified', level: '2'}, amount: 5000};{blocked: false, verified: true, limit: 1000, allowed: false} +"blocked = country in ['KP', 'IR', 'SY']; verified = kyc.status == 'verified'; limit = verified ? (kyc.level == 2 ? 10000 : 1000) : 100; allowed = not blocked and amount <= limit";{country: 'DE', kyc: {status: 'verified', level: 2}};!error +# Eligibility: flags derived from list closures +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'active', balance: 500}, {status: 'closed', balance: 10000}], minBalance: 500};true +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'active', balance: 100}, {status: 'active', balance: 450}], minBalance: 500};true +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'active', balance: 1000, overdue: 1}], minBalance: 500};false +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'closed', balance: 1000}], minBalance: 0};false +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [], minBalance: 0};false +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'active', balance: 1000, overdue: 0}], minBalance: null};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'active'}], minBalance: 0};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{accounts: [{status: 'active', balance: 10}, {status: 'frozen', overdue: 3}], minBalance: 5};false +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible";{minBalance: 0};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'active', balance: 500}, {status: 'closed', balance: 10000}], minBalance: 500};[1, 500, false] +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'active', balance: 100}, {status: 'active', balance: 450}], minBalance: 500};[2, 550, false] +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'active', balance: 1000, overdue: 1}], minBalance: 500};[1, 1000, true] +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'closed', balance: 1000}], minBalance: 0};[0, 0, false] +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [], minBalance: 0};[0, 0, false] +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'active', balance: 1000, overdue: 0}], minBalance: null};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'active'}], minBalance: 0};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{accounts: [{status: 'active', balance: 10}, {status: 'frozen', overdue: 3}], minBalance: 5};[1, 10, true] +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; [len(active), totalBalance, hasOverdue]";{minBalance: 0};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'active', balance: 500}, {status: 'closed', balance: 10000}], minBalance: 500};'approve' +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'active', balance: 100}, {status: 'active', balance: 450}], minBalance: 500};'approve' +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'active', balance: 1000, overdue: 1}], minBalance: 500};'overdue' +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'closed', balance: 1000}], minBalance: 0};'review' +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [], minBalance: 0};'review' +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'active', balance: 1000, overdue: 0}], minBalance: null};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'active'}], minBalance: 0};!error +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{accounts: [{status: 'active', balance: 10}, {status: 'frozen', overdue: 3}], minBalance: 5};'overdue' +"active = filter(accounts, #.status == 'active'); totalBalance = sum(map(active, #.balance)); hasOverdue = some(accounts, (#.overdue ?? 0) > 0); eligible = len(active) > 0 and totalBalance >= minBalance and not hasOverdue; eligible ? 'approve' : hasOverdue ? 'overdue' : 'review'";{minBalance: 0};!error +# Eligibility: age computed from years, with defaults for missing data +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 1990, baseFee: 40};['adult', 40] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 2010, baseFee: 40};['minor', 20] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 1950, baseFee: 25};['senior', 12.5] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 1960, baseFee: 25};['senior', 12.5] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 2007, baseFee: 10};['adult', 10] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, baseFee: 10};['minor', 5] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 1990, baseFee: null};['adult', null] +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: 2025, birthYear: 2010, baseFee: null};!error +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; [category, fee]";{year: null, birthYear: 1990, baseFee: 10};!error +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 1990, baseFee: 40};{age: 35, minor: false, senior: false, category: 'adult', fee: 40} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 2010, baseFee: 40};{age: 15, minor: true, senior: false, category: 'minor', fee: 20} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 1950, baseFee: 25};{age: 75, minor: false, senior: true, category: 'senior', fee: 12.5} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 1960, baseFee: 25};{age: 65, minor: false, senior: true, category: 'senior', fee: 12.5} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 2007, baseFee: 10};{age: 18, minor: false, senior: false, category: 'adult', fee: 10} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, baseFee: 10};{age: 0, minor: true, senior: false, category: 'minor', fee: 5} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 1990, baseFee: null};{age: 35, minor: false, senior: false, category: 'adult', fee: null} +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: 2025, birthYear: 2010, baseFee: null};!error +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2";{year: null, birthYear: 1990, baseFee: 10};!error +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 1990, baseFee: 40};'adult/35' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 2010, baseFee: 40};'minor/15' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 1950, baseFee: 25};'senior/75' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 1960, baseFee: 25};'senior/65' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 2007, baseFee: 10};'adult/18' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, baseFee: 10};'minor/0' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 1990, baseFee: null};'adult/35' +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: 2025, birthYear: 2010, baseFee: null};!error +"age = year - (birthYear ?? year); minor = age < 18; senior = age >= 65; category = minor ? 'minor' : senior ? 'senior' : 'adult'; fee = category == 'adult' ? baseFee : baseFee / 2; `${category}/${age}`";{year: null, birthYear: 1990, baseFee: 10};!error +# Reshaping: users into a summary object built by dotted assignments +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: [{first: 'Ann', last: 'Lee', age: 30}, {first: 'Bo', last: 'Kim', age: 12}]};{count: 2, adultNames: ['Ann'], names: ['Ann Lee', 'Bo Kim']} +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: []};{count: 0, adultNames: [], names: []} +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: [{first: 'X', last: 'Y', age: 18}]};{count: 1, adultNames: ['X'], names: ['X Y']} +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: [{first: 'X', last: null, age: 18}]};!error +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: [{first: 'X', last: 'Y'}]};!error +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: [{first: 'A', last: 'B', age: 1}, {first: 'C', last: 'D', age: 2}, {first: 'E', last: 'F', age: 99}]};{count: 3, adultNames: ['E'], names: ['A B', 'C D', 'E F']} +"names = map(users, #.first + ' ' + #.last); adults = filter(users, #.age >= 18); result.count = len(users); result.adultNames = map(adults, #.first); result.names = names; result";{users: null};!error +# Reshaping: counts per status built up key by key +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; byStatus";{tickets: [{status: 'open'}, {status: 'closed'}, {status: 'open'}, {status: 'hold'}]};{open: 2, closed: 1, other: 1} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; byStatus";{tickets: []};{open: 0, closed: 0, other: 0} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; byStatus";{tickets: [{status: 'closed'}]};{open: 0, closed: 1, other: 0} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; byStatus";{tickets: [{}, {status: null}, {status: 'OPEN'}]};{open: 0, closed: 0, other: 3} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; byStatus";{tickets: [{status: 'open'}], byStatus: {open: 99, legacy: 1}};{open: 1, legacy: 1, closed: 0, other: 0} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; byStatus";{tickets: 'x'};!error +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; [byStatus.open, byStatus.closed, byStatus.other]";{tickets: [{status: 'open'}, {status: 'closed'}, {status: 'open'}, {status: 'hold'}]};[2, 1, 1] +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; [byStatus.open, byStatus.closed, byStatus.other]";{tickets: []};[0, 0, 0] +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; [byStatus.open, byStatus.closed, byStatus.other]";{tickets: [{status: 'closed'}]};[0, 1, 0] +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; [byStatus.open, byStatus.closed, byStatus.other]";{tickets: [{}, {status: null}, {status: 'OPEN'}]};[0, 0, 3] +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; [byStatus.open, byStatus.closed, byStatus.other]";{tickets: [{status: 'open'}], byStatus: {open: 99, legacy: 1}};[1, 0, 0] +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed; [byStatus.open, byStatus.closed, byStatus.other]";{tickets: 'x'};!error +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed";{tickets: [{status: 'open'}, {status: 'closed'}, {status: 'open'}, {status: 'hold'}]};{byStatus: {open: 2, closed: 1, other: 1}} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed";{tickets: []};{byStatus: {open: 0, closed: 0, other: 0}} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed";{tickets: [{status: 'closed'}]};{byStatus: {open: 0, closed: 1, other: 0}} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed";{tickets: [{}, {status: null}, {status: 'OPEN'}]};{byStatus: {open: 0, closed: 0, other: 3}} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed";{tickets: [{status: 'open'}], byStatus: {open: 99, legacy: 1}};{byStatus: {open: 1, closed: 0, other: 0}} +"byStatus.open = count(tickets, #.status == 'open'); byStatus.closed = count(tickets, #.status == 'closed'); byStatus.other = len(tickets) - byStatus.open - byStatus.closed";{tickets: 'x'};!error +# Reshaping: order into an output document +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{order: {id: 7, customer: {name: 'ann'}, items: [{sku: 'a', price: 2, qty: 3}, {sku: 'b', price: 0.5, qty: 4}]}};{id: 7, customer: 'ANN', lines: [{sku: 'a', amount: 6}, {sku: 'b', amount: 2.0}], total: 8.0} +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{order: {id: 'X1', customer: {name: 'Bob'}, items: []}};{id: 'X1', customer: 'BOB', lines: [], total: 0} +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{order: {customer: {name: 'c'}, items: [{sku: 'z', price: 1, qty: 1}]}};{id: null, customer: 'C', lines: [{sku: 'z', amount: 1}], total: 1} +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{order: {id: 1, customer: {}, items: []}};!error +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{order: {id: 1, customer: {name: 'd'}}};!error +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{order: {id: 1, customer: {name: 'e'}, items: [{sku: 'q', price: 1}]}};!error +"out.id = order.id; out.customer = upper(order.customer.name); out.lines = map(order.items, {sku: #.sku, amount: #.price * #.qty}); out.total = sum(map(out.lines, #.amount)); out";{};!error +# Reshaping: pivot a list of pairs into named fields +"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: 'a'}, {name: 'b'}, {name: 'c'}]};{first: 'a', last: 'c', n: 3, 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: [{name: 'solo'}]};{first: 'solo', last: 'solo', n: 1, 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: '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: '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} +"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: 'Bo'}};{fullName: 'Bo ', email: 'none', age: 0, adult: false} +"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: null};{fullName: ' ', email: 'none', age: 0, adult: false} +"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";{};{fullName: ' ', email: 'none', age: 0, adult: false} +"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: {age: '30'}};!error +"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: {email: 5}};!error +"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: 'text'};{fullName: ' ', email: 'none', age: 0, adult: false} +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{profile: {first: 'Ann', last: 'Lee', email: 'A@X.IO', age: 30}};{src: {first: 'Ann', last: 'Lee', email: 'A@X.IO', age: 30}, out: {fullName: 'Ann Lee', email: 'a@x.io', age: 30, adult: true}} +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{profile: {first: 'Bo'}};{src: {first: 'Bo'}, out: {fullName: 'Bo ', email: 'none', age: 0, adult: false}} +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{profile: null};{src: {}, out: {fullName: ' ', email: 'none', age: 0, adult: false}} +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{};{src: {}, out: {fullName: ' ', email: 'none', age: 0, adult: false}} +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{profile: {age: '30'}};!error +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{profile: {email: 5}};!error +"src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18";{profile: 'text'};{src: 'text', out: {fullName: ' ', email: 'none', age: 0, adult: false}} +"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.fullName";{profile: {first: 'Ann', last: 'Lee', email: 'A@X.IO', age: 30}};'Ann Lee' +"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.fullName";{profile: {first: 'Bo'}};'Bo ' +"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.fullName";{profile: null};' ' +"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.fullName";{};' ' +"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.fullName";{profile: {age: '30'}};!error +"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.fullName";{profile: {email: 5}};!error +"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.fullName";{profile: 'text'};' ' diff --git a/core/expression/tests/spec/standard/17-02-results.csv b/core/expression/tests/spec/standard/17-02-results.csv new file mode 100644 index 00000000..559a558c --- /dev/null +++ b/core/expression/tests/spec/standard/17-02-results.csv @@ -0,0 +1,634 @@ +expression (string);input (json 5);output (json 5);note +# What a program returns: the final expression, or the assigned keys when it ends in an assignment +"a = x * 2; b = a + 1";{x: 1};{a: 2, b: 3} +"a = x * 2; b = a + 1";{x: 2.5};{a: 5.0, b: 6.0} +"a = x * 2; b = a + 1";{x: null};!error +"a = x * 2; b = a + 1";{};!error +"a = x * 2; b = a + 1";{x: 'a'};!error +"a = x * 2; b = a + 1; b";{x: 1};3 +"a = x * 2; b = a + 1; b";{x: 2.5};6.0 +"a = x * 2; b = a + 1; b";{x: null};!error +"a = x * 2; b = a + 1; b";{};!error +"a = x * 2; b = a + 1; b";{x: 'a'};!error +"a = x * 2; b = a + 1; a";{x: 1};2 +"a = x * 2; b = a + 1; a";{x: 2.5};5.0 +"a = x * 2; b = a + 1; a";{x: null};!error +"a = x * 2; b = a + 1; a";{};!error +"a = x * 2; b = a + 1; a";{x: 'a'};!error +"a = x * 2; b = a + 1; [a, b]";{x: 1};[2, 3] +"a = x * 2; b = a + 1; [a, b]";{x: 2.5};[5.0, 6.0] +"a = x * 2; b = a + 1; [a, b]";{x: null};!error +"a = x * 2; b = a + 1; [a, b]";{};!error +"a = x * 2; b = a + 1; [a, b]";{x: 'a'};!error +"a = x * 2; b = a + 1; {a: a, b: b}";{x: 1};{a: 2, b: 3} +"a = x * 2; b = a + 1; {a: a, b: b}";{x: 2.5};{a: 5.0, b: 6.0} +"a = x * 2; b = a + 1; {a: a, b: b}";{x: null};!error +"a = x * 2; b = a + 1; {a: a, b: b}";{};!error +"a = x * 2; b = a + 1; {a: a, b: b}";{x: 'a'};!error +"a = x * 2; b = a + 1; x";{x: 1};1 +"a = x * 2; b = a + 1; x";{x: 2.5};2.5 +"a = x * 2; b = a + 1; x";{x: null};!error +"a = x * 2; b = a + 1; x";{};!error +"a = x * 2; b = a + 1; x";{x: 'a'};!error +"a = x * 2; b = a + 1; b - a";{x: 1};1 +"a = x * 2; b = a + 1; b - a";{x: 2.5};1.0 +"a = x * 2; b = a + 1; b - a";{x: null};!error +"a = x * 2; b = a + 1; b - a";{};!error +"a = x * 2; b = a + 1; b - a";{x: 'a'};!error +"a = x * 2; b = a + 1; `${a},${b}`";{x: 1};'2,3' +"a = x * 2; b = a + 1; `${a},${b}`";{x: 2.5};'5.0,6.0' +"a = x * 2; b = a + 1; `${a},${b}`";{x: null};!error +"a = x * 2; b = a + 1; `${a},${b}`";{};!error +"a = x * 2; b = a + 1; `${a},${b}`";{x: 'a'};!error +"x = x * 2; y = x + 1";{x: 1};{x: 2, y: 3} +"x = x * 2; y = x + 1";{x: 2.5};{x: 5.0, y: 6.0} +"x = x * 2; y = x + 1";{x: null};!error +"x = x * 2; y = x + 1";{};!error +"x = x * 2; y = x + 1";{x: 'a'};!error +"x = x * 2; y = x + 1; x";{x: 1};2 +"x = x * 2; y = x + 1; x";{x: 2.5};5.0 +"x = x * 2; y = x + 1; x";{x: null};!error +"x = x * 2; y = x + 1; x";{};!error +"x = x * 2; y = x + 1; x";{x: 'a'};!error +"x = x * 2; y = x + 1; y";{x: 1};3 +"x = x * 2; y = x + 1; y";{x: 2.5};6.0 +"x = x * 2; y = x + 1; y";{x: null};!error +"x = x * 2; y = x + 1; y";{};!error +"x = x * 2; y = x + 1; y";{x: 'a'};!error +s = x + y;{x: 1, y: 2};{s: 3} +s = x + y;{x: 0.5, y: 0.25};{s: 0.75} +s = x + y;{x: null, y: 1};!error +s = x + y;{y: 1};!error +s = x + y;{x: 'a', y: 'b'};{s: 'ab'} +"s = x + y; s";{x: 1, y: 2};3 +"s = x + y; s";{x: 0.5, y: 0.25};0.75 +"s = x + y; s";{x: null, y: 1};!error +"s = x + y; s";{y: 1};!error +"s = x + y; s";{x: 'a', y: 'b'};'ab' +"s = x + y; p = x * y";{x: 1, y: 2};{s: 3, p: 2} +"s = x + y; p = x * y";{x: 0.5, y: 0.25};{s: 0.75, p: 0.125} +"s = x + y; p = x * y";{x: null, y: 1};!error +"s = x + y; p = x * y";{y: 1};!error +"s = x + y; p = x * y";{x: 'a', y: 'b'};!error +"s = x + y; p = x * y; s > p";{x: 1, y: 2};true +"s = x + y; p = x * y; s > p";{x: 0.5, y: 0.25};true +"s = x + y; p = x * y; s > p";{x: null, y: 1};!error +"s = x + y; p = x * y; s > p";{y: 1};!error +"s = x + y; p = x * y; s > p";{x: 'a', y: 'b'};!error +"s = x ?? y; t = y ?? x";{x: 1, y: 2};{s: 1, t: 2} +"s = x ?? y; t = y ?? x";{x: 0.5, y: 0.25};{s: 0.5, t: 0.25} +"s = x ?? y; t = y ?? x";{x: null, y: 1};{s: 1, t: 1} +"s = x ?? y; t = y ?? x";{y: 1};{s: 1, t: 1} +"s = x ?? y; t = y ?? x";{x: 'a', y: 'b'};{s: 'a', t: 'b'} +"s = x ?? y; t = y ?? x; [s, t]";{x: 1, y: 2};[1, 2] +"s = x ?? y; t = y ?? x; [s, t]";{x: 0.5, y: 0.25};[0.5, 0.25] +"s = x ?? y; t = y ?? x; [s, t]";{x: null, y: 1};[1, 1] +"s = x ?? y; t = y ?? x; [s, t]";{y: 1};[1, 1] +"s = x ?? y; t = y ?? x; [s, t]";{x: 'a', y: 'b'};['a', 'b'] +# Returned object: only assigned keys, never untouched input keys +r = x;{x: 1};{r: 1} +r = x;{x: 2.5};{r: 2.5} +r = x;{x: null};{r: null} +r = x;{};{r: null} +r = x;{x: 'a'};{r: 'a'} +"r = x; r2 = r";{x: 1};{r: 1, r2: 1} +"r = x; r2 = r";{x: 2.5};{r: 2.5, r2: 2.5} +"r = x; r2 = r";{x: null};{r: null, r2: null} +"r = x; r2 = r";{};{r: null, r2: null} +"r = x; r2 = r";{x: 'a'};{r: 'a', r2: 'a'} +x = x;{x: 1};{x: 1} +x = x;{x: 2.5};{x: 2.5} +x = x;{x: null};{x: null} +x = x;{};{x: null} +x = x;{x: 'a'};{x: 'a'} +"x = x; y = y";{x: 1, y: 2};{x: 1, y: 2} +"x = x; y = y";{x: 0.5, y: 0.25};{x: 0.5, y: 0.25} +"x = x; y = y";{x: null, y: 1};{x: null, y: 1} +"x = x; y = y";{y: 1};{x: null, y: 1} +"x = x; y = y";{x: 'a', y: 'b'};{x: 'a', y: 'b'} +"y = x; x = y";{x: 1, y: 2};{y: 1, x: 1} +"y = x; x = y";{x: 0.5, y: 0.25};{y: 0.5, x: 0.5} +"y = x; x = y";{x: null, y: 1};{y: null, x: null} +"y = x; x = y";{y: 1};{y: null, x: null} +"y = x; x = y";{x: 'a', y: 'b'};{y: 'a', x: 'a'} +"t = x; x = y; y = t";{x: 1, y: 2};{t: 1, x: 2, y: 1} +"t = x; x = y; y = t";{x: 0.5, y: 0.25};{t: 0.5, x: 0.25, y: 0.5} +"t = x; x = y; y = t";{x: null, y: 1};{t: null, x: 1, y: null} +"t = x; x = y; y = t";{y: 1};{t: null, x: 1, y: null} +"t = x; x = y; y = t";{x: 'a', y: 'b'};{t: 'a', x: 'b', y: 'a'} +"t = x; x = y; y = t; [x, y]";{x: 1, y: 2};[2, 1] +"t = x; x = y; y = t; [x, y]";{x: 0.5, y: 0.25};[0.25, 0.5] +"t = x; x = y; y = t; [x, y]";{x: null, y: 1};[1, null] +"t = x; x = y; y = t; [x, y]";{y: 1};[1, null] +"t = x; x = y; y = t; [x, y]";{x: 'a', y: 'b'};['b', 'a'] +"x = y; y = x; [x, y]";{x: 1, y: 2};[2, 2] +"x = y; y = x; [x, y]";{x: 0.5, y: 0.25};[0.25, 0.25] +"x = y; y = x; [x, y]";{x: null, y: 1};[1, 1] +"x = y; y = x; [x, y]";{y: 1};[1, 1] +"x = y; y = x; [x, y]";{x: 'a', y: 'b'};['b', 'b'] +"r = x; r = y";{x: 1, y: 2};{r: 2} +"r = x; r = y";{x: 0.5, y: 0.25};{r: 0.25} +"r = x; r = y";{x: null, y: 1};{r: 1} +"r = x; r = y";{y: 1};{r: 1} +"r = x; r = y";{x: 'a', y: 'b'};{r: 'b'} +"r = null; r = x";{x: 1};{r: 1} +"r = null; r = x";{x: 2.5};{r: 2.5} +"r = null; r = x";{x: null};{r: null} +"r = null; r = x";{};{r: null} +"r = null; r = x";{x: 'a'};{r: 'a'} +"r = x; r = null";{x: 1};{r: null} +"r = x; r = null";{x: 2.5};{r: null} +"r = x; r = null";{x: null};{r: null} +"r = x; r = null";{};{r: null} +"r = x; r = null";{x: 'a'};{r: null} +# Returned object: dotted targets build nested results +"r.a = x; r.b = y";{x: 1, y: 2};{r: {a: 1, b: 2}} +"r.a = x; r.b = y";{x: 0.5, y: 0.25};{r: {a: 0.5, b: 0.25}} +"r.a = x; r.b = y";{x: null, y: 1};{r: {a: null, b: 1}} +"r.a = x; r.b = y";{y: 1};{r: {a: null, b: 1}} +"r.a = x; r.b = y";{x: 'a', y: 'b'};{r: {a: 'a', b: 'b'}} +"r.a = x; r.b = y; r";{x: 1, y: 2};{a: 1, b: 2} +"r.a = x; r.b = y; r";{x: 0.5, y: 0.25};{a: 0.5, b: 0.25} +"r.a = x; r.b = y; r";{x: null, y: 1};{a: null, b: 1} +"r.a = x; r.b = y; r";{y: 1};{a: null, b: 1} +"r.a = x; r.b = y; r";{x: 'a', y: 'b'};{a: 'a', b: 'b'} +"r.a = x; r.b = y; r.a";{x: 1, y: 2};1 +"r.a = x; r.b = y; r.a";{x: 0.5, y: 0.25};0.5 +"r.a = x; r.b = y; r.a";{x: null, y: 1};null +"r.a = x; r.b = y; r.a";{y: 1};null +"r.a = x; r.b = y; r.a";{x: 'a', y: 'b'};'a' +"r.sum = x + y; r.diff = x - y";{x: 1, y: 2};{r: {sum: 3, diff: -1}} +"r.sum = x + y; r.diff = x - y";{x: 0.5, y: 0.25};{r: {sum: 0.75, diff: 0.25}} +"r.sum = x + y; r.diff = x - y";{x: null, y: 1};!error +"r.sum = x + y; r.diff = x - y";{y: 1};!error +"r.sum = x + y; r.diff = x - y";{x: 'a', y: 'b'};!error +"r.in.x = x; r.in.y = y; r.out = r.in.x * r.in.y";{x: 1, y: 2};{r: {in: {x: 1, y: 2}, out: 2}} +"r.in.x = x; r.in.y = y; r.out = r.in.x * r.in.y";{x: 0.5, y: 0.25};{r: {in: {x: 0.5, y: 0.25}, out: 0.125}} +"r.in.x = x; r.in.y = y; r.out = r.in.x * r.in.y";{x: null, y: 1};!error +"r.in.x = x; r.in.y = y; r.out = r.in.x * r.in.y";{y: 1};!error +"r.in.x = x; r.in.y = y; r.out = r.in.x * r.in.y";{x: 'a', y: 'b'};!error +"r = {}; r.a = x";{x: 1};{r: {a: 1}} +"r = {}; r.a = x";{x: 2.5};{r: {a: 2.5}} +"r = {}; r.a = x";{x: null};{r: {a: null}} +"r = {}; r.a = x";{};{r: {a: null}} +"r = {}; r.a = x";{x: 'a'};{r: {a: 'a'}} +"r = {k: 1}; r.a = x";{x: 1};{r: {k: 1, a: 1}} +"r = {k: 1}; r.a = x";{x: 2.5};{r: {k: 1, a: 2.5}} +"r = {k: 1}; r.a = x";{x: null};{r: {k: 1, a: null}} +"r = {k: 1}; r.a = x";{};{r: {k: 1, a: null}} +"r = {k: 1}; r.a = x";{x: 'a'};{r: {k: 1, a: 'a'}} +"r = {k: 1}; r.a = x; r";{x: 1};{k: 1, a: 1} +"r = {k: 1}; r.a = x; r";{x: 2.5};{k: 1, a: 2.5} +"r = {k: 1}; r.a = x; r";{x: null};{k: 1, a: null} +"r = {k: 1}; r.a = x; r";{};{k: 1, a: null} +"r = {k: 1}; r.a = x; r";{x: 'a'};{k: 1, a: 'a'} +"r.a = x; s = r.a";{x: 1};{r: {a: 1}, s: 1} +"r.a = x; s = r.a";{x: 2.5};{r: {a: 2.5}, s: 2.5} +"r.a = x; s = r.a";{x: null};{r: {a: null}, s: null} +"r.a = x; s = r.a";{};{r: {a: null}, s: null} +"r.a = x; s = r.a";{x: 'a'};{r: {a: 'a'}, s: 'a'} +"r.a.b.c = x; r.a.b.c";{x: 1};1 +"r.a.b.c = x; r.a.b.c";{x: 2.5};2.5 +"r.a.b.c = x; r.a.b.c";{x: null};null +"r.a.b.c = x; r.a.b.c";{};null +"r.a.b.c = x; r.a.b.c";{x: 'a'};'a' +r.a.b.c = x;{x: 1};{r: {a: {b: {c: 1}}}} +r.a.b.c = x;{x: 2.5};{r: {a: {b: {c: 2.5}}}} +r.a.b.c = x;{x: null};{r: {a: {b: {c: null}}}} +r.a.b.c = x;{};{r: {a: {b: {c: null}}}} +r.a.b.c = x;{x: 'a'};{r: {a: {b: {c: 'a'}}}} +# Building an output object step by step, reading earlier steps +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res";{name: 'ann'};{name: 'ann', meta: {len: 3, upper: 'ANN'}, short: true} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res";{name: 'Bob Ray'};{name: 'Bob Ray', meta: {len: 7, upper: 'BOB RAY'}, short: false} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res";{name: ''};{name: '', meta: {len: 0, upper: ''}, short: true} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res";{name: null};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res";{};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res";{name: 5};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4";{name: 'ann'};{res: {name: 'ann', meta: {len: 3, upper: 'ANN'}, short: true}} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4";{name: 'Bob Ray'};{res: {name: 'Bob Ray', meta: {len: 7, upper: 'BOB RAY'}, short: false}} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4";{name: ''};{res: {name: '', meta: {len: 0, upper: ''}, short: true}} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4";{name: null};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4";{};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4";{name: 5};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res.meta";{name: 'ann'};{len: 3, upper: 'ANN'} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res.meta";{name: 'Bob Ray'};{len: 7, upper: 'BOB RAY'} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res.meta";{name: ''};{len: 0, upper: ''} +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res.meta";{name: null};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res.meta";{};!error +"res.name = name; res.meta.len = len(name); res.meta.upper = upper(name); res.short = res.meta.len < 4; res.meta";{name: 5};!error +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{a: 1, b: 2};{flags: {a: true, b: true, both: true, any: true}} +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{a: 0, b: 5};{flags: {a: false, b: true, both: false, any: true}} +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{a: -1, b: -1};{flags: {a: false, b: false, both: false, any: false}} +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{a: 3, b: 0};{flags: {a: true, b: false, both: false, any: true}} +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{a: null, b: 1};!error +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{b: 1};!error +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res";{a: '1', b: 1};!error +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{a: 1, b: 2};true +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{a: 0, b: 5};false +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{a: -1, b: -1};false +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{a: 3, b: 0};false +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{a: null, b: 1};!error +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{b: 1};!error +"res.flags.a = a > 0; res.flags.b = b > 0; res.flags.both = res.flags.a and res.flags.b; res.flags.any = res.flags.a or res.flags.b; res.flags.both";{a: '1', b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{a: 1, b: 2};3 +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{a: 0, b: 5};5 +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{a: -1, b: -1};-2 +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{a: 3, b: 0};3 +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{a: null, b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res.total";{a: '1', b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{a: 1, b: 2};{res: {total: 3}} +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{a: 0, b: 5};{res: {total: 5}} +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{a: -1, b: -1};{res: {total: -2}} +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{a: 3, b: 0};{res: {total: 3}} +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{a: null, b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b";{a: '1', b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{a: 1, b: 2};{total: 3} +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{a: 0, b: 5};{total: 5} +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{a: -1, b: -1};{total: -2} +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{a: 3, b: 0};{total: 3} +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{a: null, b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{b: 1};!error +"res.total = 0; res.total = res.total + a; res.total = res.total + b; res";{a: '1', b: 1};!error +# Overwriting and extending nested results +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{a: 1, b: 2};{x: {z: 2, w: 3}} +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{a: 0, b: 5};{x: {z: 5, w: 3}} +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{a: -1, b: -1};{x: {z: -1, w: 3}} +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{a: 3, b: 0};{x: {z: 0, w: 3}} +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{a: null, b: 1};{x: {z: 1, w: 3}} +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{b: 1};{x: {z: 1, w: 3}} +"res.x.y = a; res.x = {z: b}; res.x.w = 3; res";{a: '1', b: 1};{x: {z: 1, w: 3}} +"res.x = {z: b}; res.x.y = a; res";{a: 1, b: 2};{x: {z: 2, y: 1}} +"res.x = {z: b}; res.x.y = a; res";{a: 0, b: 5};{x: {z: 5, y: 0}} +"res.x = {z: b}; res.x.y = a; res";{a: -1, b: -1};{x: {z: -1, y: -1}} +"res.x = {z: b}; res.x.y = a; res";{a: 3, b: 0};{x: {z: 0, y: 3}} +"res.x = {z: b}; res.x.y = a; res";{a: null, b: 1};{x: {z: 1, y: null}} +"res.x = {z: b}; res.x.y = a; res";{b: 1};{x: {z: 1, y: null}} +"res.x = {z: b}; res.x.y = a; res";{a: '1', b: 1};{x: {z: 1, y: '1'}} +"res.x = a; res.y = b; res.x = res.y; res";{a: 1, b: 2};{x: 2, y: 2} +"res.x = a; res.y = b; res.x = res.y; res";{a: 0, b: 5};{x: 5, y: 5} +"res.x = a; res.y = b; res.x = res.y; res";{a: -1, b: -1};{x: -1, y: -1} +"res.x = a; res.y = b; res.x = res.y; res";{a: 3, b: 0};{x: 0, y: 0} +"res.x = a; res.y = b; res.x = res.y; res";{a: null, b: 1};{x: 1, y: 1} +"res.x = a; res.y = b; res.x = res.y; res";{b: 1};{x: 1, y: 1} +"res.x = a; res.y = b; res.x = res.y; res";{a: '1', b: 1};{x: 1, y: 1} +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{a: 1, b: 2};[1, 2] +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{a: 0, b: 5};[0, 5] +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{a: -1, b: -1};[-1, -1] +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{a: 3, b: 0};[3, 0] +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{a: null, b: 1};[null, 1] +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{b: 1};[null, 1] +"res.list = [a]; res.list = flatten([res.list, [b]]); res.list";{a: '1', b: 1};['1', 1] +"res.n = a; res.n = res.n ?? b; res.n";{a: 1, b: 2};1 +"res.n = a; res.n = res.n ?? b; res.n";{a: 0, b: 5};0 +"res.n = a; res.n = res.n ?? b; res.n";{a: -1, b: -1};-1 +"res.n = a; res.n = res.n ?? b; res.n";{a: 3, b: 0};3 +"res.n = a; res.n = res.n ?? b; res.n";{a: null, b: 1};1 +"res.n = a; res.n = res.n ?? b; res.n";{b: 1};1 +"res.n = a; res.n = res.n ?? b; res.n";{a: '1', b: 1};'1' +"res.x.y = a; res.x.y = b; res";{a: 1, b: 2};{x: {y: 2}} +"res.x.y = a; res.x.y = b; res";{a: 0, b: 5};{x: {y: 5}} +"res.x.y = a; res.x.y = b; res";{a: -1, b: -1};{x: {y: -1}} +"res.x.y = a; res.x.y = b; res";{a: 3, b: 0};{x: {y: 0}} +"res.x.y = a; res.x.y = b; res";{a: null, b: 1};{x: {y: 1}} +"res.x.y = a; res.x.y = b; res";{b: 1};{x: {y: 1}} +"res.x.y = a; res.x.y = b; res";{a: '1', b: 1};{x: {y: 1}} +"res.x.y = a; res.x.z = b; res.x";{a: 1, b: 2};{y: 1, z: 2} +"res.x.y = a; res.x.z = b; res.x";{a: 0, b: 5};{y: 0, z: 5} +"res.x.y = a; res.x.z = b; res.x";{a: -1, b: -1};{y: -1, z: -1} +"res.x.y = a; res.x.z = b; res.x";{a: 3, b: 0};{y: 3, z: 0} +"res.x.y = a; res.x.z = b; res.x";{a: null, b: 1};{y: null, z: 1} +"res.x.y = a; res.x.z = b; res.x";{b: 1};{y: null, z: 1} +"res.x.y = a; res.x.z = b; res.x";{a: '1', b: 1};{y: '1', z: 1} +"res.x = a; res.x.y = b; res";{a: 1, b: 2};{x: {y: 2}} +"res.x = a; res.x.y = b; res";{a: 0, b: 5};{x: {y: 5}} +"res.x = a; res.x.y = b; res";{a: -1, b: -1};{x: {y: -1}} +"res.x = a; res.x.y = b; res";{a: 3, b: 0};{x: {y: 0}} +"res.x = a; res.x.y = b; res";{a: null, b: 1};{x: {y: 1}} +"res.x = a; res.x.y = b; res";{b: 1};{x: {y: 1}} +"res.x = a; res.x.y = b; res";{a: '1', b: 1};{x: {y: 1}} +# Dotted assignment into an input object merges and returns only assigned paths +"user.name = upper(user.name); user.age = user.age + 1; user";{user: {name: 'ann', age: 30}};{name: 'ANN', age: 31} +"user.name = upper(user.name); user.age = user.age + 1; user";{user: {name: 'Bo', age: 0, tags: ['a']}};{name: 'BO', age: 1, tags: ['a']} +"user.name = upper(user.name); user.age = user.age + 1; user";{user: {name: 'x'}};!error +"user.name = upper(user.name); user.age = user.age + 1; user";{user: {age: 5}};!error +"user.name = upper(user.name); user.age = user.age + 1; user";{user: null};!error +"user.name = upper(user.name); user.age = user.age + 1; user";{};!error +"user.name = upper(user.name); user.age = user.age + 1";{user: {name: 'ann', age: 30}};{user: {name: 'ANN', age: 31}} +"user.name = upper(user.name); user.age = user.age + 1";{user: {name: 'Bo', age: 0, tags: ['a']}};{user: {name: 'BO', age: 1}} +"user.name = upper(user.name); user.age = user.age + 1";{user: {name: 'x'}};!error +"user.name = upper(user.name); user.age = user.age + 1";{user: {age: 5}};!error +"user.name = upper(user.name); user.age = user.age + 1";{user: null};!error +"user.name = upper(user.name); user.age = user.age + 1";{};!error +"user.name = upper(user.name); user.age = user.age + 1; $root";{user: {name: 'ann', age: 30}};{user: {name: 'ANN', age: 31}} +"user.name = upper(user.name); user.age = user.age + 1; $root";{user: {name: 'Bo', age: 0, tags: ['a']}};{user: {name: 'BO', age: 1, tags: ['a']}} +"user.name = upper(user.name); user.age = user.age + 1; $root";{user: {name: 'x'}};!error +"user.name = upper(user.name); user.age = user.age + 1; $root";{user: {age: 5}};!error +"user.name = upper(user.name); user.age = user.age + 1; $root";{user: null};!error +"user.name = upper(user.name); user.age = user.age + 1; $root";{};!error +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user.label";{user: {name: 'ann', age: 30}};'ann#30' +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user.label";{user: {name: 'Bo', age: 0, tags: ['a']}};'Bo#0' +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user.label";{user: {name: 'x'}};'x#0' +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user.label";{user: {age: 5}};'?#5' +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user.label";{user: null};'?#0' +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user.label";{};'?#0' +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user";{user: {name: 'ann', age: 30}};{name: 'ann', age: 30, label: 'ann#30'} +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user";{user: {name: 'Bo', age: 0, tags: ['a']}};{name: 'Bo', age: 0, tags: ['a'], label: 'Bo#0'} +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user";{user: {name: 'x'}};{name: 'x', label: 'x#0'} +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user";{user: {age: 5}};{age: 5, label: '?#5'} +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user";{user: null};{label: '?#0'} +"user.label = `${user.name ?? '?'}#${user.age ?? 0}`; user";{};{label: '?#0'} +user.label = `${user.name ?? '?'}#${user.age ?? 0}`;{user: {name: 'ann', age: 30}};{user: {label: 'ann#30'}} +user.label = `${user.name ?? '?'}#${user.age ?? 0}`;{user: {name: 'Bo', age: 0, tags: ['a']}};{user: {label: 'Bo#0'}} +user.label = `${user.name ?? '?'}#${user.age ?? 0}`;{user: {name: 'x'}};{user: {label: 'x#0'}} +user.label = `${user.name ?? '?'}#${user.age ?? 0}`;{user: {age: 5}};{user: {label: '?#5'}} +user.label = `${user.name ?? '?'}#${user.age ?? 0}`;{user: null};{user: {label: '?#0'}} +user.label = `${user.name ?? '?'}#${user.age ?? 0}`;{};{user: {label: '?#0'}} +# Reassignment: accumulation over several statements +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: 1, b: 2, c: 3};6 +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: 0.1, b: 0.2, c: 0.3};0.6 +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: -1, b: 1, c: 0};0 +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: 1, b: null, c: 3};!error +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: 1, b: 2};!error +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: 1, b: 2, c: '3'};!error +"t = 0; t = t + a; t = t + b; t = t + c; t";{a: 100, b: 200, c: 300};600 +"t = 0; t = t + a; t = t + b; t = t + c";{a: 1, b: 2, c: 3};{t: 6} +"t = 0; t = t + a; t = t + b; t = t + c";{a: 0.1, b: 0.2, c: 0.3};{t: 0.6} +"t = 0; t = t + a; t = t + b; t = t + c";{a: -1, b: 1, c: 0};{t: 0} +"t = 0; t = t + a; t = t + b; t = t + c";{a: 1, b: null, c: 3};!error +"t = 0; t = t + a; t = t + b; t = t + c";{a: 1, b: 2};!error +"t = 0; t = t + a; t = t + b; t = t + c";{a: 1, b: 2, c: '3'};!error +"t = 0; t = t + a; t = t + b; t = t + c";{a: 100, b: 200, c: 300};{t: 600} +"t = a; t = t * b; t = t - c; t";{a: 1, b: 2, c: 3};-1 +"t = a; t = t * b; t = t - c; t";{a: 0.1, b: 0.2, c: 0.3};-0.28 +"t = a; t = t * b; t = t - c; t";{a: -1, b: 1, c: 0};-1 +"t = a; t = t * b; t = t - c; t";{a: 1, b: null, c: 3};!error +"t = a; t = t * b; t = t - c; t";{a: 1, b: 2};!error +"t = a; t = t * b; t = t - c; t";{a: 1, b: 2, c: '3'};!error +"t = a; t = t * b; t = t - c; t";{a: 100, b: 200, c: 300};19700 +"m = a; m = max([m, b]); m = max([m, c]); m";{a: 1, b: 2, c: 3};3 +"m = a; m = max([m, b]); m = max([m, c]); m";{a: 0.1, b: 0.2, c: 0.3};0.3 +"m = a; m = max([m, b]); m = max([m, c]); m";{a: -1, b: 1, c: 0};1 +"m = a; m = max([m, b]); m = max([m, c]); m";{a: 1, b: null, c: 3};!error +"m = a; m = max([m, b]); m = max([m, c]); m";{a: 1, b: 2};!error +"m = a; m = max([m, b]); m = max([m, c]); m";{a: 1, b: 2, c: '3'};!error +"m = a; m = max([m, b]); m = max([m, c]); m";{a: 100, b: 200, c: 300};300 +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: 1, b: 2, c: 3};3 +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: 0.1, b: 0.2, c: 0.3};0.3 +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: -1, b: 1, c: 0};1 +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: 1, b: null, c: 3};!error +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: 1, b: 2};!error +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: 1, b: 2, c: '3'};!error +"m = a; m = b > m ? b : m; m = c > m ? c : m; m";{a: 100, b: 200, c: 300};300 +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: 1, b: 2, c: 3};3 +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: 0.1, b: 0.2, c: 0.3};3 +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: -1, b: 1, c: 0};1 +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: 1, b: null, c: 3};!error +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: 1, b: 2};!error +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: 1, b: 2, c: '3'};!error +"cnt = 0; cnt = cnt + (a > 0 ? 1 : 0); cnt = cnt + (b > 0 ? 1 : 0); cnt = cnt + (c > 0 ? 1 : 0); cnt";{a: 100, b: 200, c: 300};3 +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: 1, b: 2, c: 3};[1, 2, 3] +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: 0.1, b: 0.2, c: 0.3};[0.1, 0.2, 0.3] +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: -1, b: 1, c: 0};[-1, 1, 0] +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: 1, b: null, c: 3};[1, null, 3] +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: 1, b: 2};[1, 2, null] +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: 1, b: 2, c: '3'};[1, 2, '3'] +"l = []; l = flatten([l, [a]]); l = flatten([l, [b]]); l = flatten([l, [c]]); l";{a: 100, b: 200, c: 300};[100, 200, 300] +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: 1, b: 2, c: 3};[4] +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: 0.1, b: 0.2, c: 0.3};[0.4] +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: -1, b: 1, c: 0};[-1] +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: 1, b: null, c: 3};!error +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: 1, b: 2};[4] +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: 1, b: 2, c: '3'};[4] +"l = [a]; l = map(l, # * 2); l = map(l, # + b); l";{a: 100, b: 200, c: 300};[400] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: 1, b: 2, c: 3};[2, 3, 1] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: 0.1, b: 0.2, c: 0.3};[0.2, 0.3, 0.1] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: -1, b: 1, c: 0};[1, 0, -1] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: 1, b: null, c: 3};[null, 3, 1] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: 1, b: 2};[2, null, 1] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: 1, b: 2, c: '3'};[2, '3', 1] +"prev = a; a = b; b = c; c = prev; [a, b, c]";{a: 100, b: 200, c: 300};[200, 300, 100] +"prev = a; a = b; b = c; c = prev";{a: 1, b: 2, c: 3};{prev: 1, a: 2, b: 3, c: 1} +"prev = a; a = b; b = c; c = prev";{a: 0.1, b: 0.2, c: 0.3};{prev: 0.1, a: 0.2, b: 0.3, c: 0.1} +"prev = a; a = b; b = c; c = prev";{a: -1, b: 1, c: 0};{prev: -1, a: 1, b: 0, c: -1} +"prev = a; a = b; b = c; c = prev";{a: 1, b: null, c: 3};{prev: 1, a: null, b: 3, c: 1} +"prev = a; a = b; b = c; c = prev";{a: 1, b: 2};{prev: 1, a: 2, b: null, c: 1} +"prev = a; a = b; b = c; c = prev";{a: 1, b: 2, c: '3'};{prev: 1, a: 2, b: '3', c: 1} +"prev = a; a = b; b = c; c = prev";{a: 100, b: 200, c: 300};{prev: 100, a: 200, b: 300, c: 100} +"s = ''; s = s + a; s = s + '-'; s = s + b; s";{a: 'x', b: 'y'};'x-y' +"s = ''; s = s + a; s = s + '-'; s = s + b; s";{a: '', b: ''};'-' +"s = ''; s = s + a; s = s + '-'; s = s + b; s";{a: 'A', b: 'b c'};'A-b c' +"s = ''; s = s + a; s = s + '-'; s = s + b; s";{a: null, b: 'y'};!error +"s = ''; s = s + a; s = s + '-'; s = s + b; s";{a: 'x'};!error +"s = ''; s = s + a; s = s + '-'; s = s + b; s";{a: 1, b: 'y'};!error +"s = a; s = upper(s); s = s + lower(b); s";{a: 'x', b: 'y'};'Xy' +"s = a; s = upper(s); s = s + lower(b); s";{a: '', b: ''};'' +"s = a; s = upper(s); s = s + lower(b); s";{a: 'A', b: 'b c'};'Ab c' +"s = a; s = upper(s); s = s + lower(b); s";{a: null, b: 'y'};!error +"s = a; s = upper(s); s = s + lower(b); s";{a: 'x'};!error +"s = a; s = upper(s); s = s + lower(b); s";{a: 1, b: 'y'};!error +"s = `${a}`; s = `${s}/${b}`; s = `[${s}]`; s";{a: 'x', b: 'y'};'[x/y]' +"s = `${a}`; s = `${s}/${b}`; s = `[${s}]`; s";{a: '', b: ''};'[/]' +"s = `${a}`; s = `${s}/${b}`; s = `[${s}]`; s";{a: 'A', b: 'b c'};'[A/b c]' +"s = `${a}`; s = `${s}/${b}`; s = `[${s}]`; s";{a: null, b: 'y'};'[null/y]' +"s = `${a}`; s = `${s}/${b}`; s = `[${s}]`; s";{a: 'x'};'[x/null]' +"s = `${a}`; s = `${s}/${b}`; s = `[${s}]`; s";{a: 1, b: 'y'};'[1/y]' +"s = a; s = len(s); s = s * 2; s";{a: 'x', b: 'y'};2 +"s = a; s = len(s); s = s * 2; s";{a: '', b: ''};0 +"s = a; s = len(s); s = s * 2; s";{a: 'A', b: 'b c'};2 +"s = a; s = len(s); s = s * 2; s";{a: null, b: 'y'};!error +"s = a; s = len(s); s = s * 2; s";{a: 'x'};2 +"s = a; s = len(s); s = s * 2; s";{a: 1, b: 'y'};!error +"s = a; s = [s, b]; s = len(s); s";{a: 'x', b: 'y'};2 +"s = a; s = [s, b]; s = len(s); s";{a: '', b: ''};2 +"s = a; s = [s, b]; s = len(s); s";{a: 'A', b: 'b c'};2 +"s = a; s = [s, b]; s = len(s); s";{a: null, b: 'y'};2 +"s = a; s = [s, b]; s = len(s); s";{a: 'x'};2 +"s = a; s = [s, b]; s = len(s); s";{a: 1, b: 'y'};2 +"s = a ?? 'none'; s = s == '' ? 'empty' : s; s";{a: 'x', b: 'y'};'x' +"s = a ?? 'none'; s = s == '' ? 'empty' : s; s";{a: '', b: ''};'empty' +"s = a ?? 'none'; s = s == '' ? 'empty' : s; s";{a: 'A', b: 'b c'};'A' +"s = a ?? 'none'; s = s == '' ? 'empty' : s; s";{a: null, b: 'y'};'none' +"s = a ?? 'none'; s = s == '' ? 'empty' : s; s";{a: 'x'};'x' +"s = a ?? 'none'; s = s == '' ? 'empty' : s; s";{a: 1, b: 'y'};1 +# Reassignment: the type of a variable may change between statements +"x = v; x = string(x); x = x + '!'; x";{v: 1};'1!' +"x = v; x = string(x); x = x + '!'; x";{v: 'a'};'a!' +"x = v; x = string(x); x = x + '!'; x";{v: null};'null!' +"x = v; x = string(x); x = x + '!'; x";{v: [1, 2]};!error +"x = v; x = string(x); x = x + '!'; x";{v: true};'true!' +"x = v; x = string(x); x = x + '!'; x";{};'null!' +"x = v; x = [x]; x = len(x); x";{v: 1};1 +"x = v; x = [x]; x = len(x); x";{v: 'a'};1 +"x = v; x = [x]; x = len(x); x";{v: null};1 +"x = v; x = [x]; x = len(x); x";{v: [1, 2]};1 +"x = v; x = [x]; x = len(x); x";{v: true};1 +"x = v; x = [x]; x = len(x); x";{};1 +"x = v; x = {inner: x}; x = x.inner; x";{v: 1};1 +"x = v; x = {inner: x}; x = x.inner; x";{v: 'a'};'a' +"x = v; x = {inner: x}; x = x.inner; x";{v: null};null +"x = v; x = {inner: x}; x = x.inner; x";{v: [1, 2]};[1, 2] +"x = v; x = {inner: x}; x = x.inner; x";{v: true};true +"x = v; x = {inner: x}; x = x.inner; x";{};null +"x = v; x = type(x); x";{v: 1};'number' +"x = v; x = type(x); x";{v: 'a'};'string' +"x = v; x = type(x); x";{v: null};'null' +"x = v; x = type(x); x";{v: [1, 2]};'array' +"x = v; x = type(x); x";{v: true};'bool' +"x = v; x = type(x); x";{};'null' +"x = v; x = v == null; x = not x; x";{v: 1};true +"x = v; x = v == null; x = not x; x";{v: 'a'};true +"x = v; x = v == null; x = not x; x";{v: null};false +"x = v; x = v == null; x = not x; x";{v: [1, 2]};true +"x = v; x = v == null; x = not x; x";{v: true};true +"x = v; x = v == null; x = not x; x";{};false +"x = v; x = x ?? 0; x = type(x) == 'number' ? x + 1 : x; x";{v: 1};2 +"x = v; x = x ?? 0; x = type(x) == 'number' ? x + 1 : x; x";{v: 'a'};'a' +"x = v; x = x ?? 0; x = type(x) == 'number' ? x + 1 : x; x";{v: null};1 +"x = v; x = x ?? 0; x = type(x) == 'number' ? x + 1 : x; x";{v: [1, 2]};[1, 2] +"x = v; x = x ?? 0; x = type(x) == 'number' ? x + 1 : x; x";{v: true};true +"x = v; x = x ?? 0; x = type(x) == 'number' ? x + 1 : x; x";{};1 +# Shadowing: variables named like input fields replace them for later statements +"price = price * 2; total = price * qty; [price, total]";{price: 10, qty: 3};[20, 60] +"price = price * 2; total = price * qty; [price, total]";{price: 2.5, qty: 4};[5.0, 20.0] +"price = price * 2; total = price * qty; [price, total]";{price: 0, qty: 9};[0, 0] +"price = price * 2; total = price * qty; [price, total]";{price: null, qty: 1};!error +"price = price * 2; total = price * qty; [price, total]";{qty: 1};!error +"price = price * 2; total = price * qty; [price, total]";{price: 1, qty: null};!error +"price = price * 2; total = price * qty; [price, total]";{price: '1', qty: 1};!error +"price = price * 2; total = price * qty";{price: 10, qty: 3};{price: 20, total: 60} +"price = price * 2; total = price * qty";{price: 2.5, qty: 4};{price: 5.0, total: 20.0} +"price = price * 2; total = price * qty";{price: 0, qty: 9};{price: 0, total: 0} +"price = price * 2; total = price * qty";{price: null, qty: 1};!error +"price = price * 2; total = price * qty";{qty: 1};!error +"price = price * 2; total = price * qty";{price: 1, qty: null};!error +"price = price * 2; total = price * qty";{price: '1', qty: 1};!error +"price = price * 2; total = price * qty; $root";{price: 10, qty: 3};{price: 20, qty: 3, total: 60} +"price = price * 2; total = price * qty; $root";{price: 2.5, qty: 4};{price: 5.0, qty: 4, total: 20.0} +"price = price * 2; total = price * qty; $root";{price: 0, qty: 9};{price: 0, qty: 9, total: 0} +"price = price * 2; total = price * qty; $root";{price: null, qty: 1};!error +"price = price * 2; total = price * qty; $root";{qty: 1};!error +"price = price * 2; total = price * qty; $root";{price: 1, qty: null};!error +"price = price * 2; total = price * qty; $root";{price: '1', qty: 1};!error +"price = price ?? 0; qty = qty ?? 1; price * qty";{price: 10, qty: 3};30 +"price = price ?? 0; qty = qty ?? 1; price * qty";{price: 2.5, qty: 4};10.0 +"price = price ?? 0; qty = qty ?? 1; price * qty";{price: 0, qty: 9};0 +"price = price ?? 0; qty = qty ?? 1; price * qty";{price: null, qty: 1};0 +"price = price ?? 0; qty = qty ?? 1; price * qty";{qty: 1};0 +"price = price ?? 0; qty = qty ?? 1; price * qty";{price: 1, qty: null};1 +"price = price ?? 0; qty = qty ?? 1; price * qty";{price: '1', qty: 1};!error +"qty = price; price = qty; price";{price: 10, qty: 3};10 +"qty = price; price = qty; price";{price: 2.5, qty: 4};2.5 +"qty = price; price = qty; price";{price: 0, qty: 9};0 +"qty = price; price = qty; price";{price: null, qty: 1};null +"qty = price; price = qty; price";{qty: 1};null +"qty = price; price = qty; price";{price: 1, qty: null};1 +"qty = price; price = qty; price";{price: '1', qty: 1};'1' +"total = price * qty; price = 0; total";{price: 10, qty: 3};30 +"total = price * qty; price = 0; total";{price: 2.5, qty: 4};10.0 +"total = price * qty; price = 0; total";{price: 0, qty: 9};0 +"total = price * qty; price = 0; total";{price: null, qty: 1};!error +"total = price * qty; price = 0; total";{qty: 1};!error +"total = price * qty; price = 0; total";{price: 1, qty: null};!error +"total = price * qty; price = 0; total";{price: '1', qty: 1};!error +"total = price * qty; price = 0; [total, price, qty]";{price: 10, qty: 3};[30, 0, 3] +"total = price * qty; price = 0; [total, price, qty]";{price: 2.5, qty: 4};[10.0, 0, 4] +"total = price * qty; price = 0; [total, price, qty]";{price: 0, qty: 9};[0, 0, 9] +"total = price * qty; price = 0; [total, price, qty]";{price: null, qty: 1};!error +"total = price * qty; price = 0; [total, price, qty]";{qty: 1};!error +"total = price * qty; price = 0; [total, price, qty]";{price: 1, qty: null};!error +"total = price * qty; price = 0; [total, price, qty]";{price: '1', qty: 1};!error +"age = age ?? 0; adult = age >= 18; adult";{age: 20};true +"age = age ?? 0; adult = age >= 18; adult";{age: 17};false +"age = age ?? 0; adult = age >= 18; adult";{age: null};false +"age = age ?? 0; adult = age >= 18; adult";{};false +"age = age ?? 0; adult = age >= 18; adult";{age: 18};true +"age = age ?? 0; adult = age >= 18; adult";{age: '20'};!error +"age = age ?? 0; adult = age >= 18";{age: 20};{age: 20, adult: true} +"age = age ?? 0; adult = age >= 18";{age: 17};{age: 17, adult: false} +"age = age ?? 0; adult = age >= 18";{age: null};{age: 0, adult: false} +"age = age ?? 0; adult = age >= 18";{};{age: 0, adult: false} +"age = age ?? 0; adult = age >= 18";{age: 18};{age: 18, adult: true} +"age = age ?? 0; adult = age >= 18";{age: '20'};!error +"age = age ?? 0; adult = age >= 18; age";{age: 20};20 +"age = age ?? 0; adult = age >= 18; age";{age: 17};17 +"age = age ?? 0; adult = age >= 18; age";{age: null};0 +"age = age ?? 0; adult = age >= 18; age";{};0 +"age = age ?? 0; adult = age >= 18; age";{age: 18};18 +"age = age ?? 0; adult = age >= 18; age";{age: '20'};!error +"name = trim(name); name = upper(name); name";{name: ' Ann '};'ANN' +"name = trim(name); name = upper(name); name";{name: 'bob'};'BOB' +"name = trim(name); name = upper(name); name";{name: ''};'' +"name = trim(name); name = upper(name); name";{name: null};!error +"name = trim(name); name = upper(name); name";{};!error +"name = trim(name); name = upper(name); name";{name: 3};!error +"name = name ?? 'anon'; name = trim(name); len(name) == 0 ? 'blank' : name";{name: ' Ann '};'Ann' +"name = name ?? 'anon'; name = trim(name); len(name) == 0 ? 'blank' : name";{name: 'bob'};'bob' +"name = name ?? 'anon'; name = trim(name); len(name) == 0 ? 'blank' : name";{name: ''};'blank' +"name = name ?? 'anon'; name = trim(name); len(name) == 0 ? 'blank' : name";{name: null};'anon' +"name = name ?? 'anon'; name = trim(name); len(name) == 0 ? 'blank' : name";{};'anon' +"name = name ?? 'anon'; name = trim(name); len(name) == 0 ? 'blank' : name";{name: 3};!error +"greeting = `Hi ${name}`; name = 'X'; [greeting, name]";{name: ' Ann '};['Hi Ann ', 'X'] +"greeting = `Hi ${name}`; name = 'X'; [greeting, name]";{name: 'bob'};['Hi bob', 'X'] +"greeting = `Hi ${name}`; name = 'X'; [greeting, name]";{name: ''};['Hi ', 'X'] +"greeting = `Hi ${name}`; name = 'X'; [greeting, name]";{name: null};['Hi null', 'X'] +"greeting = `Hi ${name}`; name = 'X'; [greeting, name]";{};['Hi null', 'X'] +"greeting = `Hi ${name}`; name = 'X'; [greeting, name]";{name: 3};['Hi 3', 'X'] +"limit = limit * 2; filter(list, # > limit)";{list: [1, 2, 3], limit: 2};[] +"limit = limit * 2; filter(list, # > limit)";{list: [], limit: 0};[] +"limit = limit * 2; filter(list, # > limit)";{list: [5], limit: 10};[] +"limit = limit * 2; filter(list, # > limit)";{list: [1, 2, 3], limit: null};!error +"limit = limit * 2; filter(list, # > limit)";{list: [1, 2, 3]};!error +"limit = limit * 2; filter(list, # > limit)";{list: null, limit: 1};!error +"limit = limit * 2; filter(list, # > limit)";{list: [3, 1, 2], limit: 1.5};[] +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: [1, 2, 3], limit: 2};1 +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: [], limit: 0};0 +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: [5], limit: 10};0 +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: [1, 2, 3], limit: null};3 +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: [1, 2, 3]};3 +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: null, limit: 1};!error +"limit = limit ?? 0; list = filter(list, # > limit); len(list)";{list: [3, 1, 2], limit: 1.5};2 +"list = map(list, # + 1); list = map(list, # * 2); list";{list: [1, 2, 3], limit: 2};[4, 6, 8] +"list = map(list, # + 1); list = map(list, # * 2); list";{list: [], limit: 0};[] +"list = map(list, # + 1); list = map(list, # * 2); list";{list: [5], limit: 10};[12] +"list = map(list, # + 1); list = map(list, # * 2); list";{list: [1, 2, 3], limit: null};[4, 6, 8] +"list = map(list, # + 1); list = map(list, # * 2); list";{list: [1, 2, 3]};[4, 6, 8] +"list = map(list, # + 1); list = map(list, # * 2); list";{list: null, limit: 1};!error +"list = map(list, # + 1); list = map(list, # * 2); list";{list: [3, 1, 2], limit: 1.5};[8, 4, 6] +"list = map(list, # + 1); list = map(list, # * 2)";{list: [1, 2, 3], limit: 2};{list: [4, 6, 8]} +"list = map(list, # + 1); list = map(list, # * 2)";{list: [], limit: 0};{list: []} +"list = map(list, # + 1); list = map(list, # * 2)";{list: [5], limit: 10};{list: [12]} +"list = map(list, # + 1); list = map(list, # * 2)";{list: [1, 2, 3], limit: null};{list: [4, 6, 8]} +"list = map(list, # + 1); list = map(list, # * 2)";{list: [1, 2, 3]};{list: [4, 6, 8]} +"list = map(list, # + 1); list = map(list, # * 2)";{list: null, limit: 1};!error +"list = map(list, # + 1); list = map(list, # * 2)";{list: [3, 1, 2], limit: 1.5};{list: [8, 4, 6]} +"orig = list; list = map(list, # * 10); [orig, list]";{list: [1, 2, 3], limit: 2};[[1, 2, 3], [10, 20, 30]] +"orig = list; list = map(list, # * 10); [orig, list]";{list: [], limit: 0};[[], []] +"orig = list; list = map(list, # * 10); [orig, list]";{list: [5], limit: 10};[[5], [50]] +"orig = list; list = map(list, # * 10); [orig, list]";{list: [1, 2, 3], limit: null};[[1, 2, 3], [10, 20, 30]] +"orig = list; list = map(list, # * 10); [orig, list]";{list: [1, 2, 3]};[[1, 2, 3], [10, 20, 30]] +"orig = list; list = map(list, # * 10); [orig, list]";{list: null, limit: 1};!error +"orig = list; list = map(list, # * 10); [orig, list]";{list: [3, 1, 2], limit: 1.5};[[3, 1, 2], [30, 10, 20]] +"limit = len(list); list = filter(list, # < limit); list";{list: [1, 2, 3], limit: 2};[1, 2] +"limit = len(list); list = filter(list, # < limit); list";{list: [], limit: 0};[] +"limit = len(list); list = filter(list, # < limit); list";{list: [5], limit: 10};[] +"limit = len(list); list = filter(list, # < limit); list";{list: [1, 2, 3], limit: null};[1, 2] +"limit = len(list); list = filter(list, # < limit); list";{list: [1, 2, 3]};[1, 2] +"limit = len(list); list = filter(list, # < limit); list";{list: null, limit: 1};!error +"limit = len(list); list = filter(list, # < limit); list";{list: [3, 1, 2], limit: 1.5};[1, 2] +"qty = qty ?? 1; map(items, #.qty * qty)";{items: [{qty: 2}, {qty: 0}, {qty: 5}], qty: 10};[20, 0, 50] +"qty = qty ?? 1; map(items, #.qty * qty)";{items: [], qty: 1};[] +"qty = qty ?? 1; map(items, #.qty * qty)";{items: [{qty: 1}], qty: null};[1] +"qty = qty ?? 1; map(items, #.qty * qty)";{items: [{qty: 1}]};[1] +"qty = qty ?? 1; map(items, #.qty * qty)";{items: [{}], qty: 2};!error +"items = filter(items, #.qty > 0); count = len(items); count";{items: [{qty: 2}, {qty: 0}, {qty: 5}], qty: 10};2 +"items = filter(items, #.qty > 0); count = len(items); count";{items: [], qty: 1};0 +"items = filter(items, #.qty > 0); count = len(items); count";{items: [{qty: 1}], qty: null};1 +"items = filter(items, #.qty > 0); count = len(items); count";{items: [{qty: 1}]};1 +"items = filter(items, #.qty > 0); count = len(items); count";{items: [{}], qty: 2};!error +"items = filter(items, (#.qty ?? 0) > 0); qty = sum(map(items, #.qty))";{items: [{qty: 2}, {qty: 0}, {qty: 5}], qty: 10};{items: [{qty: 2}, {qty: 5}], qty: 7} +"items = filter(items, (#.qty ?? 0) > 0); qty = sum(map(items, #.qty))";{items: [], qty: 1};{items: [], qty: 0} +"items = filter(items, (#.qty ?? 0) > 0); qty = sum(map(items, #.qty))";{items: [{qty: 1}], qty: null};{items: [{qty: 1}], qty: 1} +"items = filter(items, (#.qty ?? 0) > 0); qty = sum(map(items, #.qty))";{items: [{qty: 1}]};{items: [{qty: 1}], qty: 1} +"items = filter(items, (#.qty ?? 0) > 0); qty = sum(map(items, #.qty))";{items: [{}], qty: 2};{items: [], qty: 0} diff --git a/core/expression/tests/spec/standard/17-03-closures.csv b/core/expression/tests/spec/standard/17-03-closures.csv new file mode 100644 index 00000000..253f0648 --- /dev/null +++ b/core/expression/tests/spec/standard/17-03-closures.csv @@ -0,0 +1,302 @@ +expression (string);input (json 5);output (json 5);note +# Closures read variables computed by earlier statements +"threshold = avg(list); above = filter(list, # > threshold); above";{list: [1, 2, 3]};[3] +"threshold = avg(list); above = filter(list, # > threshold); above";{list: [2, 4, 6, 8]};[6, 8] +"threshold = avg(list); above = filter(list, # > threshold); above";{list: [5]};[] +"threshold = avg(list); above = filter(list, # > threshold); above";{list: [0.5, 1.5]};[1.5] +"threshold = avg(list); above = filter(list, # > threshold); above";{list: []};!error +"threshold = avg(list); above = filter(list, # > threshold); above";{list: [1, null]};!error +"threshold = avg(list); above = filter(list, # > threshold); above";{list: null};!error +"threshold = avg(list); above = filter(list, # > threshold); above";{};!error +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: [1, 2, 3]};'1 of 3 above 2' +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: [2, 4, 6, 8]};'2 of 4 above 5' +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: [5]};'0 of 1 above 5' +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: [0.5, 1.5]};'1 of 2 above 1.0' +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: []};!error +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: [1, null]};!error +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{list: null};!error +"threshold = avg(list); above = filter(list, # > threshold); `${len(above)} of ${len(list)} above ${threshold}`";{};!error +"threshold = avg(list); above = filter(list, # > threshold)";{list: [1, 2, 3]};{threshold: 2, above: [3]} +"threshold = avg(list); above = filter(list, # > threshold)";{list: [2, 4, 6, 8]};{threshold: 5, above: [6, 8]} +"threshold = avg(list); above = filter(list, # > threshold)";{list: [5]};{threshold: 5, above: []} +"threshold = avg(list); above = filter(list, # > threshold)";{list: [0.5, 1.5]};{threshold: 1.0, above: [1.5]} +"threshold = avg(list); above = filter(list, # > threshold)";{list: []};!error +"threshold = avg(list); above = filter(list, # > threshold)";{list: [1, null]};!error +"threshold = avg(list); above = filter(list, # > threshold)";{list: null};!error +"threshold = avg(list); above = filter(list, # > threshold)";{};!error +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: [1, 2, 3]};[0, 0.5, 1] +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: [2, 4, 6, 8]};[0, 0.333333333333333333333333333333333333333333333333333333333333, 0.666666666666666666666666666666666666666666666666666666666667, 1] +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: [5]};[null] +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: [0.5, 1.5]};[0, 1] +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: []};!error +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: [1, null]};!error +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{list: null};!error +"lo = min(list); hi = max(list); map(list, (# - lo) / (hi - lo))";{};!error +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: [1, 2, 3]};[0, 0.5, 1] +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: [2, 4, 6, 8]};[0, 0.333333333333333333333333333333333333333333333333333333333333, 0.666666666666666666666666666666666666666666666666666666666667, 1] +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: [5]};[0] +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: [0.5, 1.5]};[0, 1] +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: []};!error +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: [1, null]};!error +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{list: null};!error +"lo = min(list); hi = max(list); span = hi - lo; map(list, span == 0 ? 0 : (# - lo) / span)";{};!error +"n = len(list); total = sum(list); map(list, # * n - total)";{list: [1, 2, 3]};[-3, 0, 3] +"n = len(list); total = sum(list); map(list, # * n - total)";{list: [2, 4, 6, 8]};[-12, -4, 4, 12] +"n = len(list); total = sum(list); map(list, # * n - total)";{list: [5]};[0] +"n = len(list); total = sum(list); map(list, # * n - total)";{list: [0.5, 1.5]};[-1.0, 1.0] +"n = len(list); total = sum(list); map(list, # * n - total)";{list: []};[] +"n = len(list); total = sum(list); map(list, # * n - total)";{list: [1, null]};!error +"n = len(list); total = sum(list); map(list, # * n - total)";{list: null};!error +"n = len(list); total = sum(list); map(list, # * n - total)";{};!error +"first = list[0]; map(list, # - first)";{list: [1, 2, 3]};[0, 1, 2] +"first = list[0]; map(list, # - first)";{list: [2, 4, 6, 8]};[0, 2, 4, 6] +"first = list[0]; map(list, # - first)";{list: [5]};[0] +"first = list[0]; map(list, # - first)";{list: [0.5, 1.5]};[0.0, 1.0] +"first = list[0]; map(list, # - first)";{list: []};[] +"first = list[0]; map(list, # - first)";{list: [1, null]};!error +"first = list[0]; map(list, # - first)";{list: null};!error +"first = list[0]; map(list, # - first)";{};!error +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: [1, 2, 3]};[1, [2, 3]] +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: [2, 4, 6, 8]};[2, [4, 6, 8]] +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: [5]};[5, []] +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: [0.5, 1.5]};[0.5, [1.5]] +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: []};[0, []] +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: [1, null]};[1, [null]] +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{list: null};!error +"first = list[0] ?? 0; rest = filter(list, # != first); [first, rest]";{};!error +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [{price: 10}, {price: 9.99}], pct: 10};{prices: [11.0, 10.99], total: 21.99} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [{price: 100}], pct: 0};{prices: [100], total: 100} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [{price: 0.05}], pct: 50};{prices: [0.08], total: 0.08} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [], pct: 20};{prices: [], total: 0} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [{price: 1}], pct: null};!error +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [{price: null}], pct: 1};!error +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); {prices: prices, total: sum(prices)}";{items: [{}], pct: 1};!error +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [{price: 10}, {price: 9.99}], pct: 10};{factor: 1.1, prices: [11.0, 10.99], total: 21.99} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [{price: 100}], pct: 0};{factor: 1, prices: [100], total: 100} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [{price: 0.05}], pct: 50};{factor: 1.5, prices: [0.08], total: 0.08} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [], pct: 20};{factor: 1.2, prices: [], total: 0} +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [{price: 1}], pct: null};!error +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [{price: null}], pct: 1};!error +"factor = 1 + pct / 100; prices = map(items, round(#.price * factor, 2)); total = sum(prices)";{items: [{}], pct: 1};!error +# Variables inside templates inside closures +"unit = u; map(list, `${#}${unit}`)";{list: [1, 2], u: 'kg'};['1kg', '2kg'] +"unit = u; map(list, `${#}${unit}`)";{list: [0.50], u: ''};['0.50'] +"unit = u; map(list, `${#}${unit}`)";{list: [], u: 'm'};[] +"unit = u; map(list, `${#}${unit}`)";{list: [3], u: null};['3null'] +"unit = u; map(list, `${#}${unit}`)";{list: [3]};['3null'] +"unit = u; map(list, `${#}${unit}`)";{list: [3], u: 5};['35'] +"unit = u; map(list, `${#}${unit}`)";{list: ['a', true], u: '!'};['a!', 'true!'] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: [1, 2], u: 'kg'};['1 kg', '2 kg'] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: [0.50], u: ''};['0.50 '] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: [], u: 'm'};[] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: [3], u: null};['3 pcs'] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: [3]};['3 pcs'] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: [3], u: 5};['3 5'] +"unit = u ?? 'pcs'; labels = map(list, `${#} ${unit}`); labels";{list: ['a', true], u: '!'};['a !', 'true !'] +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: [1, 2], u: 'kg'};'2 kg: some' +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: [0.50], u: ''};'1 : some' +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: [], u: 'm'};'0 m: none' +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: [3], u: null};'1 pcs: some' +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: [3]};'1 pcs: some' +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: [3], u: 5};'1 5: some' +"unit = u ?? 'pcs'; n = len(list); `${n} ${unit}: ${n > 0 ? 'some' : 'none'}`";{list: ['a', true], u: '!'};'2 !: some' +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{name: 'Ann', score: 75};'Ann: pass (75)' +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{name: 'Bo', score: 50};'Bo: pass (50)' +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{name: 'Cy', score: 49.99};'Cy: fail (49.99)' +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{name: null, score: 90};'null: pass (90)' +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{score: 10};'null: fail (10)' +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{name: 'Di', score: null};!error +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`; msg";{name: 'Ed', score: 'high'};!error +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{name: 'Ann', score: 75};{label: 'pass', msg: 'Ann: pass (75)'} +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{name: 'Bo', score: 50};{label: 'pass', msg: 'Bo: pass (50)'} +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{name: 'Cy', score: 49.99};{label: 'fail', msg: 'Cy: fail (49.99)'} +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{name: null, score: 90};{label: 'pass', msg: 'null: pass (90)'} +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{score: 10};{label: 'fail', msg: 'null: fail (10)'} +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{name: 'Di', score: null};!error +"label = score >= 50 ? 'pass' : 'fail'; msg = `${name}: ${label} (${score})`";{name: 'Ed', score: 'high'};!error +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{name: 'Ann', score: 75};'[PASS]' +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{name: 'Bo', score: 50};'[PASS]' +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{name: 'Cy', score: 49.99};'[FAIL]' +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{name: null, score: 90};'[PASS]' +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{score: 10};'[FAIL]' +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{name: 'Di', score: null};!error +"label = score >= 50 ? 'pass' : 'fail'; label = upper(label); `[${label}]`";{name: 'Ed', score: 'high'};!error +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{name: 'Ann', score: 75};'' +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{name: 'Bo', score: 50};'' +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{name: 'Cy', score: 49.99};'' +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{name: null, score: 90};'' +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{score: 10};'' +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{name: 'Di', score: null};'' +"who = name ?? 'someone'; tag = `<${who}>`; tag = tag + tag; tag";{name: 'Ed', score: 'high'};'' +# Ternaries select values computed by earlier statements +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [1, 5, 9], cut: 5};['lo', 'hi', 'hi'] +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [], cut: 0};[] +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [0, -1], cut: 0};['hi', 'lo'] +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [2], cut: null};!error +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [2]};!error +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [2], cut: '1'};!error +"cut = cut; map(list, # >= cut ? 'hi' : 'lo')";{list: [4.99, 5], cut: 5};['lo', 'hi'] +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [1, 5, 9], cut: 5};[5, 9] +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [], cut: 0};[] +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [0, -1], cut: 0};[-1] +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [2], cut: null};[2] +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [2]};[2] +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [2], cut: '1'};!error +"c = cut ?? 0; hi = filter(list, # >= c); lo = filter(list, # < c); len(hi) > len(lo) ? hi : lo";{list: [4.99, 5], cut: 5};[4.99] +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [1, 5, 9], cut: 5};1 +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [], cut: 0};0 +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [0, -1], cut: 0};2 +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [2], cut: null};0 +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [2]};0 +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [2], cut: '1'};!error +"c = cut ?? 0; asc = c > 0; r = asc ? filter(list, # > c) : filter(list, # <= c); len(r)";{list: [4.99, 5], cut: 5};0 +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [1, 5, 9], cut: 5};'found' +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [], cut: 0};'below' +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [0, -1], cut: 0};'found' +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [2], cut: null};'mixed' +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [2]};'mixed' +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [2], cut: '1'};!error +"c = cut ?? 0; pick = some(list, # == c) ? 'found' : none(list, # > c) ? 'below' : 'mixed'; pick";{list: [4.99, 5], cut: 5};'found' +# Grouping and cross-referencing lists through variables +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: [{g: 'x', v: 1}, {g: 'y', v: 2}, {g: 'x', v: 3}]};[4, 2] +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: []};[0, 0] +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: [{g: 'z', v: 5}]};[0, 0] +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: [{g: 'x', v: 0.1}, {g: 'x', v: 0.2}]};[0.3, 0] +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: [{g: 'y'}]};!error +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: [{g: 'x', v: 'a'}]};!error +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); totals";{rows: null};!error +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: [{g: 'x', v: 1}, {g: 'y', v: 2}, {g: 'x', v: 3}]};{x: 4, y: 2} +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: []};{x: 0, y: 0} +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: [{g: 'z', v: 5}]};{x: 0, y: 0} +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: [{g: 'x', v: 0.1}, {g: 'x', v: 0.2}]};{x: 0.3, y: 0} +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: [{g: 'y'}]};!error +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: [{g: 'x', v: 'a'}]};!error +"groups = ['x', 'y']; totals = map(groups as g, sum(map(filter(rows, #.g == g), #.v))); {x: totals[0], y: totals[1]}";{rows: null};!error +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: [{g: 'x', v: 1}, {g: 'y', v: 2}, {g: 'x', v: 3}]};[[2, 1], 0] +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: []};[[0, 0], 0] +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: [{g: 'z', v: 5}]};[[0, 0], 1] +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: [{g: 'x', v: 0.1}, {g: 'x', v: 0.2}]};[[2, 0], 0] +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: [{g: 'y'}]};[[0, 1], 0] +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: [{g: 'x', v: 'a'}]};[[1, 0], 0] +"groups = ['x', 'y']; counts = map(groups as g, count(rows, #.g == g)); other = len(rows) - sum(counts); [counts, other]";{rows: null};!error +"ids = map(a, #.id); matches = filter(b, #.id in ids); map(matches, #.v)";{a: [{id: 1}, {id: 2}], b: [{id: 2, v: 'two'}, {id: 3, v: 'three'}]};['two'] +"ids = map(a, #.id); matches = filter(b, #.id in ids); map(matches, #.v)";{a: [], b: [{id: 1, v: 'x'}]};[] +"ids = map(a, #.id); matches = filter(b, #.id in ids); map(matches, #.v)";{a: [{id: 'k'}], b: [{id: 'k', v: 1}, {id: 'k', v: 2}]};[1, 2] +"ids = map(a, #.id); matches = filter(b, #.id in ids); map(matches, #.v)";{a: [{id: null}], b: [{v: 'missing id'}]};['missing id'] +"ids = map(a, #.id); matches = filter(b, #.id in ids); map(matches, #.v)";{a: [{id: 1}], b: []};[] +"ids = map(a, #.id); matches = filter(b, #.id in ids); map(matches, #.v)";{a: [{id: 1}], b: null};!error +"ids = map(a, #.id); missing = filter(b, not (#.id in ids)); len(missing)";{a: [{id: 1}, {id: 2}], b: [{id: 2, v: 'two'}, {id: 3, v: 'three'}]};1 +"ids = map(a, #.id); missing = filter(b, not (#.id in ids)); len(missing)";{a: [], b: [{id: 1, v: 'x'}]};1 +"ids = map(a, #.id); missing = filter(b, not (#.id in ids)); len(missing)";{a: [{id: 'k'}], b: [{id: 'k', v: 1}, {id: 'k', v: 2}]};0 +"ids = map(a, #.id); missing = filter(b, not (#.id in ids)); len(missing)";{a: [{id: null}], b: [{v: 'missing id'}]};0 +"ids = map(a, #.id); missing = filter(b, not (#.id in ids)); len(missing)";{a: [{id: 1}], b: []};0 +"ids = map(a, #.id); missing = filter(b, not (#.id in ids)); len(missing)";{a: [{id: 1}], b: null};!error +"ids = map(a, #.id); allKnown = all(b, #.id in ids); anyKnown = some(b, #.id in ids); [allKnown, anyKnown]";{a: [{id: 1}, {id: 2}], b: [{id: 2, v: 'two'}, {id: 3, v: 'three'}]};[false, true] +"ids = map(a, #.id); allKnown = all(b, #.id in ids); anyKnown = some(b, #.id in ids); [allKnown, anyKnown]";{a: [], b: [{id: 1, v: 'x'}]};[false, false] +"ids = map(a, #.id); allKnown = all(b, #.id in ids); anyKnown = some(b, #.id in ids); [allKnown, anyKnown]";{a: [{id: 'k'}], b: [{id: 'k', v: 1}, {id: 'k', v: 2}]};[true, true] +"ids = map(a, #.id); allKnown = all(b, #.id in ids); anyKnown = some(b, #.id in ids); [allKnown, anyKnown]";{a: [{id: null}], b: [{v: 'missing id'}]};[true, true] +"ids = map(a, #.id); allKnown = all(b, #.id in ids); anyKnown = some(b, #.id in ids); [allKnown, anyKnown]";{a: [{id: 1}], b: []};[true, false] +"ids = map(a, #.id); allKnown = all(b, #.id in ids); anyKnown = some(b, #.id in ids); [allKnown, anyKnown]";{a: [{id: 1}], b: null};!error +# Closures with aliases combining several top-level variables +"lo = min(r); hi = max(r); filter(list as x, x >= lo and x <= hi)";{list: [1, 5, 10], r: [2, 8]};[5] +"lo = min(r); hi = max(r); filter(list as x, x >= lo and x <= hi)";{list: [], r: [0, 1]};[] +"lo = min(r); hi = max(r); filter(list as x, x >= lo and x <= hi)";{list: [3, 3], r: [3]};[3, 3] +"lo = min(r); hi = max(r); filter(list as x, x >= lo and x <= hi)";{list: [1], r: []};!error +"lo = min(r); hi = max(r); filter(list as x, x >= lo and x <= hi)";{list: [1, 2], r: [null]};!error +"lo = min(r); hi = max(r); filter(list as x, x >= lo and x <= hi)";{list: [2.5], r: [2, 3]};[2.5] +"lo = min(r); hi = max(r); inside = count(list as x, x >= lo and x <= hi); outside = len(list) - inside; {inside: inside, outside: outside}";{list: [1, 5, 10], r: [2, 8]};{inside: 1, outside: 2} +"lo = min(r); hi = max(r); inside = count(list as x, x >= lo and x <= hi); outside = len(list) - inside; {inside: inside, outside: outside}";{list: [], r: [0, 1]};{inside: 0, outside: 0} +"lo = min(r); hi = max(r); inside = count(list as x, x >= lo and x <= hi); outside = len(list) - inside; {inside: inside, outside: outside}";{list: [3, 3], r: [3]};{inside: 2, outside: 0} +"lo = min(r); hi = max(r); inside = count(list as x, x >= lo and x <= hi); outside = len(list) - inside; {inside: inside, outside: outside}";{list: [1], r: []};!error +"lo = min(r); hi = max(r); inside = count(list as x, x >= lo and x <= hi); outside = len(list) - inside; {inside: inside, outside: outside}";{list: [1, 2], r: [null]};!error +"lo = min(r); hi = max(r); inside = count(list as x, x >= lo and x <= hi); outside = len(list) - inside; {inside: inside, outside: outside}";{list: [2.5], r: [2, 3]};{inside: 1, outside: 0} +"lo = min(r); hi = max(r); map(list as x, x < lo ? lo : x > hi ? hi : x)";{list: [1, 5, 10], r: [2, 8]};[2, 5, 8] +"lo = min(r); hi = max(r); map(list as x, x < lo ? lo : x > hi ? hi : x)";{list: [], r: [0, 1]};[] +"lo = min(r); hi = max(r); map(list as x, x < lo ? lo : x > hi ? hi : x)";{list: [3, 3], r: [3]};[3, 3] +"lo = min(r); hi = max(r); map(list as x, x < lo ? lo : x > hi ? hi : x)";{list: [1], r: []};!error +"lo = min(r); hi = max(r); map(list as x, x < lo ? lo : x > hi ? hi : x)";{list: [1, 2], r: [null]};!error +"lo = min(r); hi = max(r); map(list as x, x < lo ? lo : x > hi ? hi : x)";{list: [2.5], r: [2, 3]};[2.5] +"m = mult; map(groups, map(#, # * m))";{groups: [[1, 2], [3]], mult: 2};[[2, 4], [6]] +"m = mult; map(groups, map(#, # * m))";{groups: [], mult: 2};[] +"m = mult; map(groups, map(#, # * m))";{groups: [[]], mult: 2};[[]] +"m = mult; map(groups, map(#, # * m))";{groups: [[1]], mult: null};!error +"m = mult; map(groups, map(#, # * m))";{groups: [[1]]};!error +"m = mult; map(groups, map(#, # * m))";{groups: [[0.5, 1]], mult: 0.5};[[0.25, 0.5]] +"m = mult; map(groups, map(#, # * m))";{groups: [1], mult: 1};!error +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [[1, 2], [3]], mult: 2};[[6, 6], 12] +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [], mult: 2};[[], 0] +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [[]], mult: 2};[[0], 0] +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [[1]], mult: null};[[1], 1] +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [[1]]};[[1], 1] +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [[0.5, 1]], mult: 0.5};[[0.75], 0.75] +"m = mult ?? 1; sums = map(groups, sum(#) * m); total = sum(sums); [sums, total]";{groups: [1], mult: 1};!error +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [[1, 2], [3]], mult: 2};[2, 4, 6] +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [], mult: 2};[] +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [[]], mult: 2};[] +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [[1]], mult: null};[1] +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [[1]]};[1] +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [[0.5, 1]], mult: 0.5};[0.25, 0.5] +"m = mult ?? 1; flat = flatMap(groups, map(#, # * m)); flat";{groups: [1], mult: 1};!error +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [[1, 2], [3]], mult: 2};2 +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [], mult: 2};0 +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [[]], mult: 2};0 +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [[1]], mult: null};0 +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [[1]]};0 +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [[0.5, 1]], mult: 0.5};0 +"m = mult ?? 1; big = filter(groups, sum(#) * m > 2); len(big)";{groups: [1], mult: 1};!error +# Object literals inside closures reading top-level variables +"tax = r; map(items, {n: #.n, gross: #.net * (1 + tax)})";{items: [{n: 'a', net: 10}, {n: 'b', net: 2.5}], r: 0.2};[{n: 'a', gross: 12.0}, {n: 'b', gross: 3.00}] +"tax = r; map(items, {n: #.n, gross: #.net * (1 + tax)})";{items: [], r: 0};[] +"tax = r; map(items, {n: #.n, gross: #.net * (1 + tax)})";{items: [{n: 'c', net: 1}], r: null};!error +"tax = r; map(items, {n: #.n, gross: #.net * (1 + tax)})";{items: [{n: 'c', net: 1}]};!error +"tax = r; map(items, {n: #.n, gross: #.net * (1 + tax)})";{items: [{n: 'c'}], r: 1};!error +"tax = r ?? 0; rows = map(items, {n: #.n, gross: #.net * (1 + tax)}); {rows: rows, sum: sum(map(rows, #.gross))}";{items: [{n: 'a', net: 10}, {n: 'b', net: 2.5}], r: 0.2};{rows: [{n: 'a', gross: 12.0}, {n: 'b', gross: 3.00}], sum: 15.00} +"tax = r ?? 0; rows = map(items, {n: #.n, gross: #.net * (1 + tax)}); {rows: rows, sum: sum(map(rows, #.gross))}";{items: [], r: 0};{rows: [], sum: 0} +"tax = r ?? 0; rows = map(items, {n: #.n, gross: #.net * (1 + tax)}); {rows: rows, sum: sum(map(rows, #.gross))}";{items: [{n: 'c', net: 1}], r: null};{rows: [{n: 'c', gross: 1}], sum: 1} +"tax = r ?? 0; rows = map(items, {n: #.n, gross: #.net * (1 + tax)}); {rows: rows, sum: sum(map(rows, #.gross))}";{items: [{n: 'c', net: 1}]};{rows: [{n: 'c', gross: 1}], sum: 1} +"tax = r ?? 0; rows = map(items, {n: #.n, gross: #.net * (1 + tax)}); {rows: rows, sum: sum(map(rows, #.gross))}";{items: [{n: 'c'}], r: 1};!error +"tax = r ?? 0; names = map(items, #.n); out.names = names; out.rate = tax; out";{items: [{n: 'a', net: 10}, {n: 'b', net: 2.5}], r: 0.2};{names: ['a', 'b'], rate: 0.2} +"tax = r ?? 0; names = map(items, #.n); out.names = names; out.rate = tax; out";{items: [], r: 0};{names: [], rate: 0} +"tax = r ?? 0; names = map(items, #.n); out.names = names; out.rate = tax; out";{items: [{n: 'c', net: 1}], r: null};{names: ['c'], rate: 0} +"tax = r ?? 0; names = map(items, #.n); out.names = names; out.rate = tax; out";{items: [{n: 'c', net: 1}]};{names: ['c'], rate: 0} +"tax = r ?? 0; names = map(items, #.n); out.names = names; out.rate = tax; out";{items: [{n: 'c'}], r: 1};{names: ['c'], rate: 1} +# Dynamic keys held in variables +"k = key; vals = map(rows, #[k]); vals";{rows: [{a: 1, b: 2}, {a: 3}], key: 'a'};[1, 3] +"k = key; vals = map(rows, #[k]); vals";{rows: [{a: 1, b: 2}, {a: 3}], key: 'b'};[2, null] +"k = key; vals = map(rows, #[k]); vals";{rows: [{a: 1}], key: 'z'};[null] +"k = key; vals = map(rows, #[k]); vals";{rows: [], key: 'a'};[] +"k = key; vals = map(rows, #[k]); vals";{rows: [{a: 1}], key: null};[null] +"k = key; vals = map(rows, #[k]); vals";{rows: [{a: 1}]};[null] +"k = key; vals = map(rows, #[k] ?? 0); sum(vals)";{rows: [{a: 1, b: 2}, {a: 3}], key: 'a'};4 +"k = key; vals = map(rows, #[k] ?? 0); sum(vals)";{rows: [{a: 1, b: 2}, {a: 3}], key: 'b'};2 +"k = key; vals = map(rows, #[k] ?? 0); sum(vals)";{rows: [{a: 1}], key: 'z'};0 +"k = key; vals = map(rows, #[k] ?? 0); sum(vals)";{rows: [], key: 'a'};0 +"k = key; vals = map(rows, #[k] ?? 0); sum(vals)";{rows: [{a: 1}], key: null};0 +"k = key; vals = map(rows, #[k] ?? 0); sum(vals)";{rows: [{a: 1}]};0 +"k = key ?? 'a'; has = filter(rows, #[k] != null); len(has)";{rows: [{a: 1, b: 2}, {a: 3}], key: 'a'};2 +"k = key ?? 'a'; has = filter(rows, #[k] != null); len(has)";{rows: [{a: 1, b: 2}, {a: 3}], key: 'b'};1 +"k = key ?? 'a'; has = filter(rows, #[k] != null); len(has)";{rows: [{a: 1}], key: 'z'};0 +"k = key ?? 'a'; has = filter(rows, #[k] != null); len(has)";{rows: [], key: 'a'};0 +"k = key ?? 'a'; has = filter(rows, #[k] != null); len(has)";{rows: [{a: 1}], key: null};1 +"k = key ?? 'a'; has = filter(rows, #[k] != null); len(has)";{rows: [{a: 1}]};1 +# Variables with the same name as element fields +"qty = qty ?? 0; map(list, #.qty + qty)";{list: [{qty: 2, price: 3}, {qty: 1, price: 10}], qty: 5, price: 100};[7, 6] +"qty = qty ?? 0; map(list, #.qty + qty)";{list: [], qty: 1, price: 1};[] +"qty = qty ?? 0; map(list, #.qty + qty)";{list: [{qty: 0, price: 1}], qty: null, price: 1};[0] +"qty = qty ?? 0; map(list, #.qty + qty)";{list: [{qty: 1}], qty: 1, price: 2};[2] +"price = 1; map(list, #.price * price)";{list: [{qty: 2, price: 3}, {qty: 1, price: 10}], qty: 5, price: 100};[3, 10] +"price = 1; map(list, #.price * price)";{list: [], qty: 1, price: 1};[] +"price = 1; map(list, #.price * price)";{list: [{qty: 0, price: 1}], qty: null, price: 1};[1] +"price = 1; map(list, #.price * price)";{list: [{qty: 1}], qty: 1, price: 2};!error +"price = 1; map(list as price, price.qty)";{list: [{qty: 2, price: 3}, {qty: 1, price: 10}], qty: 5, price: 100};[2, 1] +"price = 1; map(list as price, price.qty)";{list: [], qty: 1, price: 1};[] +"price = 1; map(list as price, price.qty)";{list: [{qty: 0, price: 1}], qty: null, price: 1};[0] +"price = 1; map(list as price, price.qty)";{list: [{qty: 1}], qty: 1, price: 2};[1] +"price = 1; r = map(list as price, price.qty); [r, price]";{list: [{qty: 2, price: 3}, {qty: 1, price: 10}], qty: 5, price: 100};[[2, 1], 1] +"price = 1; r = map(list as price, price.qty); [r, price]";{list: [], qty: 1, price: 1};[[], 1] +"price = 1; r = map(list as price, price.qty); [r, price]";{list: [{qty: 0, price: 1}], qty: null, price: 1};[[0], 1] +"price = 1; r = map(list as price, price.qty); [r, price]";{list: [{qty: 1}], qty: 1, price: 2};[[1], 1] +"qty = sum(map(list, #.qty)); price = sum(map(list, #.qty * (#.price ?? 0))); price / qty";{list: [{qty: 2, price: 3}, {qty: 1, price: 10}], qty: 5, price: 100};5.33333333333333333333333333333333333333333333333333333333333 +"qty = sum(map(list, #.qty)); price = sum(map(list, #.qty * (#.price ?? 0))); price / qty";{list: [], qty: 1, price: 1};null +"qty = sum(map(list, #.qty)); price = sum(map(list, #.qty * (#.price ?? 0))); price / qty";{list: [{qty: 0, price: 1}], qty: null, price: 1};null +"qty = sum(map(list, #.qty)); price = sum(map(list, #.qty * (#.price ?? 0))); price / qty";{list: [{qty: 1}], qty: 1, price: 2};0 diff --git a/core/expression/tests/spec/standard/17-04-sequences-root.csv b/core/expression/tests/spec/standard/17-04-sequences-root.csv new file mode 100644 index 00000000..5867cdde --- /dev/null +++ b/core/expression/tests/spec/standard/17-04-sequences-root.csv @@ -0,0 +1,366 @@ +expression (string);input (json 5);output (json 5);note +# Parenthesized sequences as values inside assignments +"total = (s = a + b; s * 2); total";{a: 1, b: 2};6 +"total = (s = a + b; s * 2); total";{a: 0.5, b: 1.5};4.0 +"total = (s = a + b; s * 2); total";{a: -2, b: 2};0 +"total = (s = a + b; s * 2); total";{a: 0, b: 0};0 +"total = (s = a + b; s * 2); total";{a: null, b: 1};!error +"total = (s = a + b; s * 2); total";{b: 1};!error +"total = (s = a + b; s * 2); total";{a: 1, b: 'x'};!error +"total = (s = a + b; s * 2)";{a: 1, b: 2};{total: 6} +"total = (s = a + b; s * 2)";{a: 0.5, b: 1.5};{total: 4.0} +"total = (s = a + b; s * 2)";{a: -2, b: 2};{total: 0} +"total = (s = a + b; s * 2)";{a: 0, b: 0};{total: 0} +"total = (s = a + b; s * 2)";{a: null, b: 1};!error +"total = (s = a + b; s * 2)";{b: 1};!error +"total = (s = a + b; s * 2)";{a: 1, b: 'x'};!error +"total = (s = a + b; s * 2); s";{a: 1, b: 2};3;question: a parenthesized sequence has no scope of its own so s stays visible after it +"total = (s = a + b; s * 2); s";{a: 0.5, b: 1.5};2.0;question: a parenthesized sequence has no scope of its own so s stays visible after it +"total = (s = a + b; s * 2); s";{a: -2, b: 2};0;question: a parenthesized sequence has no scope of its own so s stays visible after it +"total = (s = a + b; s * 2); s";{a: 0, b: 0};0;question: a parenthesized sequence has no scope of its own so s stays visible after it +"total = (s = a + b; s * 2); s";{a: null, b: 1};!error;question: a parenthesized sequence has no scope of its own so s stays visible after it +"total = (s = a + b; s * 2); s";{b: 1};!error;question: a parenthesized sequence has no scope of its own so s stays visible after it +"total = (s = a + b; s * 2); s";{a: 1, b: 'x'};!error;question: a parenthesized sequence has no scope of its own so s stays visible after it +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{a: 1, b: 2};[2, 4] +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{a: 0.5, b: 1.5};[1.0, 3.0] +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{a: -2, b: 2};[-4, 4] +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{a: 0, b: 0};[0, 0] +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{a: null, b: 1};!error +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{b: 1};!error +"r = [(p = a * 2; p), (q = b * 2; q)]; r";{a: 1, b: 'x'};!error +"r = [(p = a * 2; p), (q = b * 2; q)]";{a: 1, b: 2};{r: [2, 4]} +"r = [(p = a * 2; p), (q = b * 2; q)]";{a: 0.5, b: 1.5};{r: [1.0, 3.0]} +"r = [(p = a * 2; p), (q = b * 2; q)]";{a: -2, b: 2};{r: [-4, 4]} +"r = [(p = a * 2; p), (q = b * 2; q)]";{a: 0, b: 0};{r: [0, 0]} +"r = [(p = a * 2; p), (q = b * 2; q)]";{a: null, b: 1};!error +"r = [(p = a * 2; p), (q = b * 2; q)]";{b: 1};!error +"r = [(p = a * 2; p), (q = b * 2; q)]";{a: 1, b: 'x'};!error +"r = {x: (t = a; t + 1), y: b}; r.x";{a: 1, b: 2};2 +"r = {x: (t = a; t + 1), y: b}; r.x";{a: 0.5, b: 1.5};1.5 +"r = {x: (t = a; t + 1), y: b}; r.x";{a: -2, b: 2};-1 +"r = {x: (t = a; t + 1), y: b}; r.x";{a: 0, b: 0};1 +"r = {x: (t = a; t + 1), y: b}; r.x";{a: null, b: 1};!error +"r = {x: (t = a; t + 1), y: b}; r.x";{b: 1};!error +"r = {x: (t = a; t + 1), y: b}; r.x";{a: 1, b: 'x'};2 +"r = {x: (t = a; t + 1), y: b}; r";{a: 1, b: 2};{x: 2, y: 2} +"r = {x: (t = a; t + 1), y: b}; r";{a: 0.5, b: 1.5};{x: 1.5, y: 1.5} +"r = {x: (t = a; t + 1), y: b}; r";{a: -2, b: 2};{x: -1, y: 2} +"r = {x: (t = a; t + 1), y: b}; r";{a: 0, b: 0};{x: 1, y: 0} +"r = {x: (t = a; t + 1), y: b}; r";{a: null, b: 1};!error +"r = {x: (t = a; t + 1), y: b}; r";{b: 1};!error +"r = {x: (t = a; t + 1), y: b}; r";{a: 1, b: 'x'};{x: 2, y: 'x'} +"x = (y = a; y) + (y = b; y); x";{a: 1, b: 2};3 +"x = (y = a; y) + (y = b; y); x";{a: 0.5, b: 1.5};2.0 +"x = (y = a; y) + (y = b; y); x";{a: -2, b: 2};0 +"x = (y = a; y) + (y = b; y); x";{a: 0, b: 0};0 +"x = (y = a; y) + (y = b; y); x";{a: null, b: 1};!error +"x = (y = a; y) + (y = b; y); x";{b: 1};!error +"x = (y = a; y) + (y = b; y); x";{a: 1, b: 'x'};!error +"s = `${(t = a + b; t)}`; s";{a: 1, b: 2};'3' +"s = `${(t = a + b; t)}`; s";{a: 0.5, b: 1.5};'2.0' +"s = `${(t = a + b; t)}`; s";{a: -2, b: 2};'0' +"s = `${(t = a + b; t)}`; s";{a: 0, b: 0};'0' +"s = `${(t = a + b; t)}`; s";{a: null, b: 1};!error +"s = `${(t = a + b; t)}`; s";{b: 1};!error +"s = `${(t = a + b; t)}`; s";{a: 1, b: 'x'};!error +"r = round((t = a / b; t * 100), 1); r";{a: 1, b: 2};50.0 +"r = round((t = a / b; t * 100), 1); r";{a: 0.5, b: 1.5};33.3 +"r = round((t = a / b; t * 100), 1); r";{a: -2, b: 2};-100 +"r = round((t = a / b; t * 100), 1); r";{a: 0, b: 0};!error +"r = round((t = a / b; t * 100), 1); r";{a: null, b: 1};!error +"r = round((t = a / b; t * 100), 1); r";{b: 1};!error +"r = round((t = a / b; t * 100), 1); r";{a: 1, b: 'x'};!error +"r = max([(t = a; t), (u = b; u)]); r";{a: 1, b: 2};2 +"r = max([(t = a; t), (u = b; u)]); r";{a: 0.5, b: 1.5};1.5 +"r = max([(t = a; t), (u = b; u)]); r";{a: -2, b: 2};2 +"r = max([(t = a; t), (u = b; u)]); r";{a: 0, b: 0};0 +"r = max([(t = a; t), (u = b; u)]); r";{a: null, b: 1};!error +"r = max([(t = a; t), (u = b; u)]); r";{b: 1};!error +"r = max([(t = a; t), (u = b; u)]); r";{a: 1, b: 'x'};!error +"r = (t = a > b; t) ? 'a' : 'b'; r";{a: 1, b: 2};'b' +"r = (t = a > b; t) ? 'a' : 'b'; r";{a: 0.5, b: 1.5};'b' +"r = (t = a > b; t) ? 'a' : 'b'; r";{a: -2, b: 2};'b' +"r = (t = a > b; t) ? 'a' : 'b'; r";{a: 0, b: 0};'b' +"r = (t = a > b; t) ? 'a' : 'b'; r";{a: null, b: 1};!error +"r = (t = a > b; t) ? 'a' : 'b'; r";{b: 1};!error +"r = (t = a > b; t) ? 'a' : 'b'; r";{a: 1, b: 'x'};!error +"r = (o.v = a; o.v * 2); r";{a: 1, b: 2};2 +"r = (o.v = a; o.v * 2); r";{a: 0.5, b: 1.5};1.0 +"r = (o.v = a; o.v * 2); r";{a: -2, b: 2};-4 +"r = (o.v = a; o.v * 2); r";{a: 0, b: 0};0 +"r = (o.v = a; o.v * 2); r";{a: null, b: 1};!error +"r = (o.v = a; o.v * 2); r";{b: 1};!error +"r = (o.v = a; o.v * 2); r";{a: 1, b: 'x'};2 +"r = (o.v = a; o.v * 2)";{a: 1, b: 2};{r: 2} +"r = (o.v = a; o.v * 2)";{a: 0.5, b: 1.5};{r: 1.0} +"r = (o.v = a; o.v * 2)";{a: -2, b: 2};{r: -4} +"r = (o.v = a; o.v * 2)";{a: 0, b: 0};{r: 0} +"r = (o.v = a; o.v * 2)";{a: null, b: 1};!error +"r = (o.v = a; o.v * 2)";{b: 1};!error +"r = (o.v = a; o.v * 2)";{a: 1, b: 'x'};{r: 2} +"m = 3; r = (k = a * m; k + b); r";{a: 1, b: 2};5 +"m = 3; r = (k = a * m; k + b); r";{a: 0.5, b: 1.5};3.0 +"m = 3; r = (k = a * m; k + b); r";{a: -2, b: 2};-4 +"m = 3; r = (k = a * m; k + b); r";{a: 0, b: 0};0 +"m = 3; r = (k = a * m; k + b); r";{a: null, b: 1};!error +"m = 3; r = (k = a * m; k + b); r";{b: 1};!error +"m = 3; r = (k = a * m; k + b); r";{a: 1, b: 'x'};!error +# Sequences inside ternary branches across statements +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{c: true, a: 1, b: 2};10 +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{c: false, a: 1, b: 2};200 +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{c: true, a: null, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{c: false, a: 1, b: null};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{c: null, a: 1, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{a: 1, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100); v";{c: 1, a: 1, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{c: true, a: 1, b: 2};{v: 10} +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{c: false, a: 1, b: 2};{v: 200} +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{c: true, a: null, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{c: false, a: 1, b: null};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{c: null, a: 1, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{a: 1, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100)";{c: 1, a: 1, b: 2};!error +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{c: true, a: 1, b: 2};1;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{c: false, a: 1, b: 2};2;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{c: true, a: null, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{c: false, a: 1, b: null};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{c: null, a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (t = a; t * 10) : (t = b; t * 100); t";{c: 1, a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{c: true, a: 1, b: 2};['yes', 'yes', null] +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{c: false, a: 1, b: 2};['no', null, 'no'] +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{c: true, a: null, b: 2};['yes', 'yes', null] +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{c: false, a: 1, b: null};['no', null, 'no'] +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{c: null, a: 1, b: 2};!error +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{a: 1, b: 2};!error +"v = c ? (p = 'yes'; p) : (q = 'no'; q); [v, p, q]";{c: 1, a: 1, b: 2};!error +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{c: true, a: 1, b: 2};1 +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{c: false, a: 1, b: 2};'unset' +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{c: true, a: null, b: 2};'unset' +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{c: false, a: 1, b: null};'unset' +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{c: null, a: 1, b: 2};!error +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{a: 1, b: 2};!error +"v = c ? (p = a; p) : b; w = p ?? 'unset'; w";{c: 1, a: 1, b: 2};!error +# Sequences on the right of ?? across statements +"v = a ?? (d = 5; d); v";{a: 1};1 +"v = a ?? (d = 5; d); v";{a: null};5 +"v = a ?? (d = 5; d); v";{};5 +"v = a ?? (d = 5; d); v";{a: 0};0 +"v = a ?? (d = 5; d); v";{a: false};false +"v = a ?? (d = 5; d); v";{a: 'x'};'x' +"v = a ?? (d = 5; d)";{a: 1};{v: 1} +"v = a ?? (d = 5; d)";{a: null};{v: 5} +"v = a ?? (d = 5; d)";{};{v: 5} +"v = a ?? (d = 5; d)";{a: 0};{v: 0} +"v = a ?? (d = 5; d)";{a: false};{v: false} +"v = a ?? (d = 5; d)";{a: 'x'};{v: 'x'} +"v = a ?? (d = 5; d); [v, d]";{a: 1};[1, null] +"v = a ?? (d = 5; d); [v, d]";{a: null};[5, 5] +"v = a ?? (d = 5; d); [v, d]";{};[5, 5] +"v = a ?? (d = 5; d); [v, d]";{a: 0};[0, null] +"v = a ?? (d = 5; d); [v, d]";{a: false};[false, null] +"v = a ?? (d = 5; d); [v, d]";{a: 'x'};['x', null] +"v = a ?? (d = 'dflt'; d); used = d != null; used";{a: 1};false +"v = a ?? (d = 'dflt'; d); used = d != null; used";{a: null};true +"v = a ?? (d = 'dflt'; d); used = d != null; used";{};true +"v = a ?? (d = 'dflt'; d); used = d != null; used";{a: 0};false +"v = a ?? (d = 'dflt'; d); used = d != null; used";{a: false};false +"v = a ?? (d = 'dflt'; d); used = d != null; used";{a: 'x'};false +# Sequences inside templates and function arguments across statements +"x = `${(t = a; t)}/${b}`; x";{a: 1, b: 2};'1/2' +"x = `${(t = a; t)}/${b}`; x";{a: 0.5, b: 1.5};'0.5/1.5' +"x = `${(t = a; t)}/${b}`; x";{a: -2, b: 2};'-2/2' +"x = `${(t = a; t)}/${b}`; x";{a: 0, b: 0};'0/0' +"x = `${(t = a; t)}/${b}`; x";{a: null, b: 1};'null/1' +"x = `${(t = a; t)}/${b}`; x";{b: 1};'null/1' +"x = `${(t = a; t)}/${b}`; x";{a: 1, b: 'x'};'1/x' +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{a: 1, b: 2};'1';question: a parenthesized sequence inside a template has no scope of its own +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{a: 0.5, b: 1.5};'0.5';question: a parenthesized sequence inside a template has no scope of its own +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{a: -2, b: 2};'-2';question: a parenthesized sequence inside a template has no scope of its own +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{a: 0, b: 0};'0';question: a parenthesized sequence inside a template has no scope of its own +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{a: null, b: 1};'null';question: a parenthesized sequence inside a template has no scope of its own +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{b: 1};'null';question: a parenthesized sequence inside a template has no scope of its own +"x = `${(t = a; t)}/${b}`; y = `${t}`; y";{a: 1, b: 'x'};'1';question: a parenthesized sequence inside a template has no scope of its own +"x = abs((t = a - b; t)); [x, t]";{a: 1, b: 2};[1, -1];question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = abs((t = a - b; t)); [x, t]";{a: 0.5, b: 1.5};[1.0, -1.0];question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = abs((t = a - b; t)); [x, t]";{a: -2, b: 2};[4, -4];question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = abs((t = a - b; t)); [x, t]";{a: 0, b: 0};[0, 0];question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = abs((t = a - b; t)); [x, t]";{a: null, b: 1};!error;question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = abs((t = a - b; t)); [x, t]";{b: 1};!error;question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = abs((t = a - b; t)); [x, t]";{a: 1, b: 'x'};!error;question: a parenthesized sequence has no scope of its own so t stays visible after it +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{a: 1, b: 2};[4, 2];question: nested sequences rebind y in the program environment +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{a: 0.5, b: 1.5};[2.5, 1.5];question: nested sequences rebind y in the program environment +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{a: -2, b: 2};[-2, 2];question: nested sequences rebind y in the program environment +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{a: 0, b: 0};[0, 0];question: nested sequences rebind y in the program environment +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{a: null, b: 1};!error;question: nested sequences rebind y in the program environment +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{b: 1};!error;question: nested sequences rebind y in the program environment +"x = ((y = a; y * 2) + (y = b; y)); [x, y]";{a: 1, b: 'x'};!error;question: nested sequences rebind y in the program environment +# Sequences containing closures +"r = (lim = a; filter(list, # > lim)); r";{list: [1, 2, 3], a: 1};[2, 3] +"r = (lim = a; filter(list, # > lim)); r";{list: [], a: 1};[] +"r = (lim = a; filter(list, # > lim)); r";{list: [5], a: 10};[] +"r = (lim = a; filter(list, # > lim)); r";{list: [1, 2], a: null};!error +"r = (lim = a; filter(list, # > lim)); r";{list: [1, 2]};!error +"r = (lim = a; filter(list, # > lim)); r";{list: null, a: 1};!error +"r = (lim = a ?? 0; filter(list, # > lim)); len(r)";{list: [1, 2, 3], a: 1};2 +"r = (lim = a ?? 0; filter(list, # > lim)); len(r)";{list: [], a: 1};0 +"r = (lim = a ?? 0; filter(list, # > lim)); len(r)";{list: [5], a: 10};0 +"r = (lim = a ?? 0; filter(list, # > lim)); len(r)";{list: [1, 2], a: null};2 +"r = (lim = a ?? 0; filter(list, # > lim)); len(r)";{list: [1, 2]};2 +"r = (lim = a ?? 0; filter(list, # > lim)); len(r)";{list: null, a: 1};!error +"r = (d = map(list, # * 2); sum(d)); r";{list: [1, 2, 3], a: 1};12 +"r = (d = map(list, # * 2); sum(d)); r";{list: [], a: 1};0 +"r = (d = map(list, # * 2); sum(d)); r";{list: [5], a: 10};10 +"r = (d = map(list, # * 2); sum(d)); r";{list: [1, 2], a: null};6 +"r = (d = map(list, # * 2); sum(d)); r";{list: [1, 2]};6 +"r = (d = map(list, # * 2); sum(d)); r";{list: null, a: 1};!error +"r = (lim = a ?? 0; count(list, # > lim)); lim";{list: [1, 2, 3], a: 1};1;question: a parenthesized sequence has no scope of its own so lim stays visible after it +"r = (lim = a ?? 0; count(list, # > lim)); lim";{list: [], a: 1};1;question: a parenthesized sequence has no scope of its own so lim stays visible after it +"r = (lim = a ?? 0; count(list, # > lim)); lim";{list: [5], a: 10};10;question: a parenthesized sequence has no scope of its own so lim stays visible after it +"r = (lim = a ?? 0; count(list, # > lim)); lim";{list: [1, 2], a: null};0;question: a parenthesized sequence has no scope of its own so lim stays visible after it +"r = (lim = a ?? 0; count(list, # > lim)); lim";{list: [1, 2]};0;question: a parenthesized sequence has no scope of its own so lim stays visible after it +"r = (lim = a ?? 0; count(list, # > lim)); lim";{list: null, a: 1};!error;question: a parenthesized sequence has no scope of its own so lim stays visible after it +# $root sees every assignment made so far +"subtotal = a * b; ($root).subtotal";{a: 1, b: 2};2 +"subtotal = a * b; ($root).subtotal";{a: 0.5, b: 1.5};0.75 +"subtotal = a * b; ($root).subtotal";{a: -2, b: 2};-4 +"subtotal = a * b; ($root).subtotal";{a: 0, b: 0};0 +"subtotal = a * b; ($root).subtotal";{a: null, b: 1};!error +"subtotal = a * b; ($root).subtotal";{b: 1};!error +"subtotal = a * b; ($root).subtotal";{a: 1, b: 'x'};!error +"subtotal = a * b; r = $root; r.subtotal";{a: 1, b: 2};2 +"subtotal = a * b; r = $root; r.subtotal";{a: 0.5, b: 1.5};0.75 +"subtotal = a * b; r = $root; r.subtotal";{a: -2, b: 2};-4 +"subtotal = a * b; r = $root; r.subtotal";{a: 0, b: 0};0 +"subtotal = a * b; r = $root; r.subtotal";{a: null, b: 1};!error +"subtotal = a * b; r = $root; r.subtotal";{b: 1};!error +"subtotal = a * b; r = $root; r.subtotal";{a: 1, b: 'x'};!error +"subtotal = a * b; k = 'subtotal'; $root[k]";{a: 1, b: 2};2 +"subtotal = a * b; k = 'subtotal'; $root[k]";{a: 0.5, b: 1.5};0.75 +"subtotal = a * b; k = 'subtotal'; $root[k]";{a: -2, b: 2};-4 +"subtotal = a * b; k = 'subtotal'; $root[k]";{a: 0, b: 0};0 +"subtotal = a * b; k = 'subtotal'; $root[k]";{a: null, b: 1};!error +"subtotal = a * b; k = 'subtotal'; $root[k]";{b: 1};!error +"subtotal = a * b; k = 'subtotal'; $root[k]";{a: 1, b: 'x'};!error +"subtotal = a * b; $root";{a: 1, b: 2};{a: 1, b: 2, subtotal: 2} +"subtotal = a * b; $root";{a: 0.5, b: 1.5};{a: 0.5, b: 1.5, subtotal: 0.75} +"subtotal = a * b; $root";{a: -2, b: 2};{a: -2, b: 2, subtotal: -4} +"subtotal = a * b; $root";{a: 0, b: 0};{a: 0, b: 0, subtotal: 0} +"subtotal = a * b; $root";{a: null, b: 1};!error +"subtotal = a * b; $root";{b: 1};!error +"subtotal = a * b; $root";{a: 1, b: 'x'};!error +"subtotal = a * b; $root.subtotal";{a: 1, b: 2};2;bug: $root.subtotal compiles to a fast path that reads the original input instead of the assigned value +"subtotal = a * b; $root.subtotal";{a: 0.5, b: 1.5};0.75;bug: $root.subtotal compiles to a fast path that reads the original input instead of the assigned value +"subtotal = a * b; $root.subtotal";{a: -2, b: 2};-4;bug: $root.subtotal compiles to a fast path that reads the original input instead of the assigned value +"subtotal = a * b; $root.subtotal";{a: 0, b: 0};0;bug: $root.subtotal compiles to a fast path that reads the original input instead of the assigned value +"subtotal = a * b; $root.subtotal";{a: null, b: 1};!error +"subtotal = a * b; $root.subtotal";{b: 1};!error +"subtotal = a * b; $root.subtotal";{a: 1, b: 'x'};!error +"a = a * 10; ($root).a";{a: 1, b: 2};10 +"a = a * 10; ($root).a";{a: 0.5, b: 1.5};5.0 +"a = a * 10; ($root).a";{a: -2, b: 2};-20 +"a = a * 10; ($root).a";{a: 0, b: 0};0 +"a = a * 10; ($root).a";{a: null, b: 1};!error +"a = a * 10; ($root).a";{b: 1};!error +"a = a * 10; ($root).a";{a: 1, b: 'x'};10 +"a = a * 10; $root.a";{a: 1, b: 2};10;bug: $root.a reads the original input while ($root).a reads the assigned value +"a = a * 10; $root.a";{a: 0.5, b: 1.5};5.0;bug: $root.a reads the original input while ($root).a reads the assigned value +"a = a * 10; $root.a";{a: -2, b: 2};-20;bug: $root.a reads the original input while ($root).a reads the assigned value +"a = a * 10; $root.a";{a: 0, b: 0};0 +"a = a * 10; $root.a";{a: null, b: 1};!error +"a = a * 10; $root.a";{b: 1};!error +"a = a * 10; $root.a";{a: 1, b: 'x'};10;bug: $root.a reads the original input while ($root).a reads the assigned value +"a = a * 10; b2 = ($root).a + b; b2";{a: 1, b: 2};12 +"a = a * 10; b2 = ($root).a + b; b2";{a: 0.5, b: 1.5};6.5 +"a = a * 10; b2 = ($root).a + b; b2";{a: -2, b: 2};-18 +"a = a * 10; b2 = ($root).a + b; b2";{a: 0, b: 0};0 +"a = a * 10; b2 = ($root).a + b; b2";{a: null, b: 1};!error +"a = a * 10; b2 = ($root).a + b; b2";{b: 1};!error +"a = a * 10; b2 = ($root).a + b; b2";{a: 1, b: 'x'};!error +"a = a * 10; $root.b";{a: 1, b: 2};2 +"a = a * 10; $root.b";{a: 0.5, b: 1.5};1.5 +"a = a * 10; $root.b";{a: -2, b: 2};2 +"a = a * 10; $root.b";{a: 0, b: 0};0 +"a = a * 10; $root.b";{a: null, b: 1};!error +"a = a * 10; $root.b";{b: 1};!error +"a = a * 10; $root.b";{a: 1, b: 'x'};'x' +"r.x = a; r.y = b; ($root).r";{a: 1, b: 2};{x: 1, y: 2} +"r.x = a; r.y = b; ($root).r";{a: 0.5, b: 1.5};{x: 0.5, y: 1.5} +"r.x = a; r.y = b; ($root).r";{a: -2, b: 2};{x: -2, y: 2} +"r.x = a; r.y = b; ($root).r";{a: 0, b: 0};{x: 0, y: 0} +"r.x = a; r.y = b; ($root).r";{a: null, b: 1};{x: null, y: 1} +"r.x = a; r.y = b; ($root).r";{b: 1};{x: null, y: 1} +"r.x = a; r.y = b; ($root).r";{a: 1, b: 'x'};{x: 1, y: 'x'} +"r.x = a; r.y = b; ($root).r.y";{a: 1, b: 2};2 +"r.x = a; r.y = b; ($root).r.y";{a: 0.5, b: 1.5};1.5 +"r.x = a; r.y = b; ($root).r.y";{a: -2, b: 2};2 +"r.x = a; r.y = b; ($root).r.y";{a: 0, b: 0};0 +"r.x = a; r.y = b; ($root).r.y";{a: null, b: 1};1 +"r.x = a; r.y = b; ($root).r.y";{b: 1};1 +"r.x = a; r.y = b; ($root).r.y";{a: 1, b: 'x'};'x' +"r.x = a; r.y = b; $root.r.y";{a: 1, b: 2};2;bug: $root.r.y reads the original input instead of the assigned value +"r.x = a; r.y = b; $root.r.y";{a: 0.5, b: 1.5};1.5;bug: $root.r.y reads the original input instead of the assigned value +"r.x = a; r.y = b; $root.r.y";{a: -2, b: 2};2;bug: $root.r.y reads the original input instead of the assigned value +"r.x = a; r.y = b; $root.r.y";{a: 0, b: 0};0;bug: $root.r.y reads the original input instead of the assigned value +"r.x = a; r.y = b; $root.r.y";{a: null, b: 1};1;bug: $root.r.y reads the original input instead of the assigned value +"r.x = a; r.y = b; $root.r.y";{b: 1};1;bug: $root.r.y reads the original input instead of the assigned value +"r.x = a; r.y = b; $root.r.y";{a: 1, b: 'x'};'x';bug: $root.r.y reads the original input instead of the assigned value +"snapshot = $root; a = 99; snapshot";{a: 1, b: 2};{a: 1, b: 2} +"snapshot = $root; a = 99; snapshot";{a: 0.5, b: 1.5};{a: 0.5, b: 1.5} +"snapshot = $root; a = 99; snapshot";{a: -2, b: 2};{a: -2, b: 2} +"snapshot = $root; a = 99; snapshot";{a: 0, b: 0};{a: 0, b: 0} +"snapshot = $root; a = 99; snapshot";{a: null, b: 1};{a: null, b: 1} +"snapshot = $root; a = 99; snapshot";{b: 1};{b: 1} +"snapshot = $root; a = 99; snapshot";{a: 1, b: 'x'};{a: 1, b: 'x'} +"snapshot = $root; a = 99; [snapshot.a, a]";{a: 1, b: 2};[1, 99] +"snapshot = $root; a = 99; [snapshot.a, a]";{a: 0.5, b: 1.5};[0.5, 99] +"snapshot = $root; a = 99; [snapshot.a, a]";{a: -2, b: 2};[-2, 99] +"snapshot = $root; a = 99; [snapshot.a, a]";{a: 0, b: 0};[0, 99] +"snapshot = $root; a = 99; [snapshot.a, a]";{a: null, b: 1};[null, 99] +"snapshot = $root; a = 99; [snapshot.a, a]";{b: 1};[null, 99] +"snapshot = $root; a = 99; [snapshot.a, a]";{a: 1, b: 'x'};[1, 99] +"x2 = a; y2 = b; len(keys($root))";{a: 1, b: 2};4 +"x2 = a; y2 = b; len(keys($root))";{a: 0.5, b: 1.5};4 +"x2 = a; y2 = b; len(keys($root))";{a: -2, b: 2};4 +"x2 = a; y2 = b; len(keys($root))";{a: 0, b: 0};4 +"x2 = a; y2 = b; len(keys($root))";{a: null, b: 1};4 +"x2 = a; y2 = b; len(keys($root))";{b: 1};3 +"x2 = a; y2 = b; len(keys($root))";{a: 1, b: 'x'};4 +"x2 = a; y2 = b; len(values($root))";{a: 1, b: 2};4 +"x2 = a; y2 = b; len(values($root))";{a: 0.5, b: 1.5};4 +"x2 = a; y2 = b; len(values($root))";{a: -2, b: 2};4 +"x2 = a; y2 = b; len(values($root))";{a: 0, b: 0};4 +"x2 = a; y2 = b; len(values($root))";{a: null, b: 1};4 +"x2 = a; y2 = b; len(values($root))";{b: 1};3 +"x2 = a; y2 = b; len(values($root))";{a: 1, b: 'x'};4 +# $root inside closures +"doubled = map(list, # * 2); $root";{list: [1, 3, 5], lim: 2};{list: [1, 3, 5], lim: 2, doubled: [2, 6, 10]} +"doubled = map(list, # * 2); $root";{list: [], lim: 2};{list: [], lim: 2, doubled: []} +"doubled = map(list, # * 2); $root";{list: [1, 3, 5], lim: null};{list: [1, 3, 5], lim: null, doubled: [2, 6, 10]} +"doubled = map(list, # * 2); $root";{list: [1, 3, 5]};{list: [1, 3, 5], doubled: [2, 6, 10]} +"doubled = map(list, # * 2); $root";{list: [2, 4], lim: 3};{list: [2, 4], lim: 3, doubled: [4, 8]} +"lim = 3; filter(list, # > ($root).lim)";{list: [1, 3, 5], lim: 2};[5] +"lim = 3; filter(list, # > ($root).lim)";{list: [], lim: 2};[] +"lim = 3; filter(list, # > ($root).lim)";{list: [1, 3, 5], lim: null};[5] +"lim = 3; filter(list, # > ($root).lim)";{list: [1, 3, 5]};[5] +"lim = 3; filter(list, # > ($root).lim)";{list: [2, 4], lim: 3};[4] +"lim = 3; filter(list, # > $root.lim)";{list: [1, 3, 5], lim: 2};[5];bug: $root.lim inside the closure reads the original input instead of the assigned 3 +"lim = 3; filter(list, # > $root.lim)";{list: [], lim: 2};[] +"lim = 3; filter(list, # > $root.lim)";{list: [1, 3, 5], lim: null};[5];bug: $root.lim inside the closure reads the original input instead of the assigned 3 +"lim = 3; filter(list, # > $root.lim)";{list: [1, 3, 5]};[5];bug: $root.lim inside the closure reads the original input instead of the assigned 3 +"lim = 3; filter(list, # > $root.lim)";{list: [2, 4], lim: 3};[4] +"lim = lim ?? 0; map(list, # > ($root).lim)";{list: [1, 3, 5], lim: 2};[false, true, true] +"lim = lim ?? 0; map(list, # > ($root).lim)";{list: [], lim: 2};[] +"lim = lim ?? 0; map(list, # > ($root).lim)";{list: [1, 3, 5], lim: null};[true, true, true] +"lim = lim ?? 0; map(list, # > ($root).lim)";{list: [1, 3, 5]};[true, true, true] +"lim = lim ?? 0; map(list, # > ($root).lim)";{list: [2, 4], lim: 3};[false, true] +"n = len(list); map(list, ($root).n)";{list: [1, 3, 5], lim: 2};[3, 3, 3] +"n = len(list); map(list, ($root).n)";{list: [], lim: 2};[] +"n = len(list); map(list, ($root).n)";{list: [1, 3, 5], lim: null};[3, 3, 3] +"n = len(list); map(list, ($root).n)";{list: [1, 3, 5]};[3, 3, 3] +"n = len(list); map(list, ($root).n)";{list: [2, 4], lim: 3};[2, 2] +"scale = 10; map(list as x, x * ($root).scale)";{list: [1, 3, 5], lim: 2};[10, 30, 50] +"scale = 10; map(list as x, x * ($root).scale)";{list: [], lim: 2};[] +"scale = 10; map(list as x, x * ($root).scale)";{list: [1, 3, 5], lim: null};[10, 30, 50] +"scale = 10; map(list as x, x * ($root).scale)";{list: [1, 3, 5]};[10, 30, 50] +"scale = 10; map(list as x, x * ($root).scale)";{list: [2, 4], lim: 3};[20, 40] diff --git a/core/expression/tests/spec/standard/17-05-scoping.csv b/core/expression/tests/spec/standard/17-05-scoping.csv new file mode 100644 index 00000000..0d3fe902 --- /dev/null +++ b/core/expression/tests/spec/standard/17-05-scoping.csv @@ -0,0 +1,308 @@ +expression (string);input (json 5);output (json 5);note +# Three nested closures reading top-level variables +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};[[[1111, 1211]], [[1112, 1212]]] +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [], ys: [10], zs: [100], k: 0};[] +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [1], ys: [], zs: [100], k: 0};[[]] +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [1], ys: [2], zs: [], k: 0};[[[]]] +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};[[[0.975]]] +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [1], ys: [2], zs: [3], k: null};!error +"k2 = k; map(xs as x, map(ys as y, map(zs as z, x + y + z + k2)))";{xs: [1], ys: [2], zs: [3]};!error +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};10000 +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [], ys: [10], zs: [100], k: 0};0 +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [1], ys: [], zs: [100], k: 0};0 +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [1], ys: [2], zs: [], k: 0};0 +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};0.115625 +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [1], ys: [2], zs: [3], k: null};6 +"k2 = k ?? 0; flat = flatMap(xs as x, flatMap(ys as y, map(zs as z, x * y * z))); sum(flat) + k2";{xs: [1], ys: [2], zs: [3]};6 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};0 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [], ys: [10], zs: [100], k: 0};0 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [1], ys: [], zs: [100], k: 0};0 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [1], ys: [2], zs: [], k: 0};0 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};1 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [1], ys: [2], zs: [3], k: null};1 +"k2 = k ?? 0; c = count(xs as x, some(ys as y, some(zs as z, x + y + z > k2))); c";{xs: [1], ys: [2], zs: [3]};1 +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};[[10], [10]] +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [], ys: [10], zs: [100], k: 0};[] +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [1], ys: [], zs: [100], k: 0};[[]] +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [1], ys: [2], zs: [], k: 0};[[2]] +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};[[]] +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [1], ys: [2], zs: [3], k: null};[[]] +"k2 = k ?? 0; r = map(xs as x, filter(ys as y, all(zs as z, x + y < z + k2))); r";{xs: [1], ys: [2], zs: [3]};[[]] +# Three nested closures with a body-local at each level +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};[[[120, 220]], [[130, 230]]] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [], ys: [10], zs: [100], k: 0};[] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [1], ys: [], zs: [100], k: 0};[[]] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [1], ys: [2], zs: [], k: 0};[[[]]] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};[[[5.375]]] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [1], ys: [2], zs: [3], k: null};[[[15]]] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); r";{xs: [1], ys: [2], zs: [3]};[[[15]]] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};{r: [[[120, 220]], [[130, 230]]]} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [], ys: [10], zs: [100], k: 0};{r: []} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [1], ys: [], zs: [100], k: 0};{r: [[]]} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [1], ys: [2], zs: [], k: 0};{r: [[[]]]} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};{r: [[[5.375]]]} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [1], ys: [2], zs: [3], k: null};{r: [[[15]]]} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c))))))";{xs: [1], ys: [2], zs: [3]};{r: [[[15]]]} +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};[null, null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [], ys: [10], zs: [100], k: 0};[null, null, null] +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [1], ys: [], zs: [100], k: 0};[null, null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [1], ys: [2], zs: [], k: 0};[null, null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};[null, null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [1], ys: [2], zs: [3], k: null};[null, null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); [a, b, c]";{xs: [1], ys: [2], zs: [3]};[null, null, null];bug: an assignment inside a closure body leaks to the outer scope +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};7;bug: an assignment inside a closure body leaks to the outer scope +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [], ys: [10], zs: [100], k: 0};7 +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [1], ys: [], zs: [100], k: 0};7;bug: an assignment inside a closure body leaks to the outer scope +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [1], ys: [2], zs: [], k: 0};7;bug: an assignment inside a closure body leaks to the outer scope +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};7;bug: an assignment inside a closure body leaks to the outer scope +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [1], ys: [2], zs: [3], k: null};7;bug: an assignment inside a closure body leaks to the outer scope +"a = 7; r = map(xs as x, (a = x * 10; map(ys as y, (b = a + y; map(zs as z, (c = b + z; c)))))); a";{xs: [1], ys: [2], zs: [3]};7;bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [1, 2], ys: [10], zs: [100, 200], k: 1000};[[[300, 400]], [[400, 500]]];bug: the same local name at three closure levels is shared, so inner iterations see the previous iteration value instead of the enclosing one +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [], ys: [10], zs: [100], k: 0};[] +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [1], ys: [], zs: [100], k: 0};[[]] +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [1], ys: [2], zs: [], k: 0};[[[]]] +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [0.5], ys: [0.25], zs: [0.125], k: 0.1};[[[52.625]]] +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [1], ys: [2], zs: [3], k: null};[[[123]]] +"r = map(xs, (t = #; map(ys, (t = t * 10 + #; map(zs, (t = t * 10 + #; t)))))); r";{xs: [1], ys: [2], zs: [3]};[[[123]]] +# Two nested closures: inner reads the outer iteration local +"r = map(xs, (o = #; map(ys, o * #))); r";{xs: [1, 2], ys: [10, 20]};[[10, 20], [20, 40]] +"r = map(xs, (o = #; map(ys, o * #))); r";{xs: [], ys: [1]};[] +"r = map(xs, (o = #; map(ys, o * #))); r";{xs: [3], ys: []};[[]] +"r = map(xs, (o = #; map(ys, o * #))); r";{xs: [0.5], ys: [2, 4]};[[1.0, 2.0]] +"r = map(xs, (o = #; map(ys, o * #))); r";{xs: [1, null], ys: [1]};!error +"r = map(xs, (o = #; map(ys, o * #))); r";{xs: [1], ys: null};!error +"r = map(xs, (o = # * 2; sum(map(ys, o + #)))); r";{xs: [1, 2], ys: [10, 20]};[34, 38] +"r = map(xs, (o = # * 2; sum(map(ys, o + #)))); r";{xs: [], ys: [1]};[] +"r = map(xs, (o = # * 2; sum(map(ys, o + #)))); r";{xs: [3], ys: []};[0] +"r = map(xs, (o = # * 2; sum(map(ys, o + #)))); r";{xs: [0.5], ys: [2, 4]};[8.0] +"r = map(xs, (o = # * 2; sum(map(ys, o + #)))); r";{xs: [1, null], ys: [1]};!error +"r = map(xs, (o = # * 2; sum(map(ys, o + #)))); r";{xs: [1], ys: null};!error +"r = map(xs, (o = #; filter(ys, # > o * 10))); r";{xs: [1, 2], ys: [10, 20]};[[20], []] +"r = map(xs, (o = #; filter(ys, # > o * 10))); r";{xs: [], ys: [1]};[] +"r = map(xs, (o = #; filter(ys, # > o * 10))); r";{xs: [3], ys: []};[[]] +"r = map(xs, (o = #; filter(ys, # > o * 10))); r";{xs: [0.5], ys: [2, 4]};[[]] +"r = map(xs, (o = #; filter(ys, # > o * 10))); r";{xs: [1, null], ys: [1]};!error +"r = map(xs, (o = #; filter(ys, # > o * 10))); r";{xs: [1], ys: null};!error +"r = map(xs, (o = #; map(ys, (p = o + #; p)))); [r, o, p]";{xs: [1, 2], ys: [10, 20]};[[[11, 21], [12, 22]], null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (o = #; map(ys, (p = o + #; p)))); [r, o, p]";{xs: [], ys: [1]};[[], null, null] +"r = map(xs, (o = #; map(ys, (p = o + #; p)))); [r, o, p]";{xs: [3], ys: []};[[[]], null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (o = #; map(ys, (p = o + #; p)))); [r, o, p]";{xs: [0.5], ys: [2, 4]};[[[2.5, 4.5]], null, null];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (o = #; map(ys, (p = o + #; p)))); [r, o, p]";{xs: [1, null], ys: [1]};!error +"r = map(xs, (o = #; map(ys, (p = o + #; p)))); [r, o, p]";{xs: [1], ys: null};!error +"r = map(xs, (o = #; w = map(ys, (o = o + #; o)); [o, w])); r";{xs: [1, 2], ys: [10, 20]};[[1, [11, 21]], [2, [12, 22]]];bug: an inner closure assignment overwrites the outer iteration local of the same name +"r = map(xs, (o = #; w = map(ys, (o = o + #; o)); [o, w])); r";{xs: [], ys: [1]};[] +"r = map(xs, (o = #; w = map(ys, (o = o + #; o)); [o, w])); r";{xs: [3], ys: []};[[3, []]] +"r = map(xs, (o = #; w = map(ys, (o = o + #; o)); [o, w])); r";{xs: [0.5], ys: [2, 4]};[[0.5, [2.5, 4.5]]];bug: an inner closure assignment overwrites the outer iteration local of the same name +"r = map(xs, (o = #; w = map(ys, (o = o + #; o)); [o, w])); r";{xs: [1, null], ys: [1]};!error +"r = map(xs, (o = #; w = map(ys, (o = o + #; o)); [o, w])); r";{xs: [1], ys: null};!error +"r = map(xs, (lim = #; f = filter(ys, (lim = lim + 1; # > lim)); [lim, f])); r";{xs: [1, 2], ys: [10, 20]};[[1, [10, 20]], [2, [10, 20]]];bug: an inner closure assignment overwrites the outer iteration local of the same name +"r = map(xs, (lim = #; f = filter(ys, (lim = lim + 1; # > lim)); [lim, f])); r";{xs: [], ys: [1]};[] +"r = map(xs, (lim = #; f = filter(ys, (lim = lim + 1; # > lim)); [lim, f])); r";{xs: [3], ys: []};[[3, []]] +"r = map(xs, (lim = #; f = filter(ys, (lim = lim + 1; # > lim)); [lim, f])); r";{xs: [0.5], ys: [2, 4]};[[0.5, [2, 4]]];bug: an inner closure assignment overwrites the outer iteration local of the same name +"r = map(xs, (lim = #; f = filter(ys, (lim = lim + 1; # > lim)); [lim, f])); r";{xs: [1, null], ys: [1]};!error +"r = map(xs, (lim = #; f = filter(ys, (lim = lim + 1; # > lim)); [lim, f])); r";{xs: [1], ys: null};!error +# Closures in different statements reusing a local name +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); [p, q]";{xs: [1, 2], ys: [5]};[[2, 4], [6]] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); [p, q]";{xs: [], ys: []};[[], []] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); [p, q]";{xs: [3], ys: [1, 2, 3]};[[6], [2, 3, 4]] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); [p, q]";{xs: [1.5], ys: [0]};[[3.0], [1]] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); [p, q]";{xs: [1], ys: []};[[2], []] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); [p, q]";{xs: [], ys: [7]};[[], [8]] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t))";{xs: [1, 2], ys: [5]};{p: [2, 4], q: [6]} +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t))";{xs: [], ys: []};{p: [], q: []} +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t))";{xs: [3], ys: [1, 2, 3]};{p: [6], q: [2, 3, 4]} +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t))";{xs: [1.5], ys: [0]};{p: [3.0], q: [1]} +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t))";{xs: [1], ys: []};{p: [2], q: []} +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t))";{xs: [], ys: [7]};{p: [], q: [8]} +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); t";{xs: [1, 2], ys: [5]};null;bug: an assignment inside a closure body leaks to the outer scope +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); t";{xs: [], ys: []};null +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); t";{xs: [3], ys: [1, 2, 3]};null;bug: an assignment inside a closure body leaks to the outer scope +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); t";{xs: [1.5], ys: [0]};null;bug: an assignment inside a closure body leaks to the outer scope +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); t";{xs: [1], ys: []};null;bug: an assignment inside a closure body leaks to the outer scope +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = # + 1; t)); t";{xs: [], ys: [7]};null;bug: an assignment inside a closure body leaks to the outer scope +"p = map(xs, (t = # * 2; t)); q = map(ys, t ?? 0); q";{xs: [1, 2], ys: [5]};[0];bug: t from the first closure is visible inside a later, unrelated closure +"p = map(xs, (t = # * 2; t)); q = map(ys, t ?? 0); q";{xs: [], ys: []};[] +"p = map(xs, (t = # * 2; t)); q = map(ys, t ?? 0); q";{xs: [3], ys: [1, 2, 3]};[0, 0, 0];bug: t from the first closure is visible inside a later, unrelated closure +"p = map(xs, (t = # * 2; t)); q = map(ys, t ?? 0); q";{xs: [1.5], ys: [0]};[0];bug: t from the first closure is visible inside a later, unrelated closure +"p = map(xs, (t = # * 2; t)); q = map(ys, t ?? 0); q";{xs: [1], ys: []};[] +"p = map(xs, (t = # * 2; t)); q = map(ys, t ?? 0); q";{xs: [], ys: [7]};[0] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = (t ?? 0) + #; t)); q";{xs: [1, 2], ys: [5]};[5];bug: the second closure starts from t leaked by the first closure and accumulates across iterations +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = (t ?? 0) + #; t)); q";{xs: [], ys: []};[] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = (t ?? 0) + #; t)); q";{xs: [3], ys: [1, 2, 3]};[1, 2, 3];bug: the second closure starts from t leaked by the first closure and accumulates across iterations +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = (t ?? 0) + #; t)); q";{xs: [1.5], ys: [0]};[0];bug: the second closure starts from t leaked by the first closure and accumulates across iterations +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = (t ?? 0) + #; t)); q";{xs: [1], ys: []};[] +"p = map(xs, (t = # * 2; t)); q = map(ys, (t = (t ?? 0) + #; t)); q";{xs: [], ys: [7]};[7] +"t = 5; p = map(xs, (t = #; t)); t + 1";{xs: [1, 2], ys: [5]};6;bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); t + 1";{xs: [], ys: []};6 +"t = 5; p = map(xs, (t = #; t)); t + 1";{xs: [3], ys: [1, 2, 3]};6;bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); t + 1";{xs: [1.5], ys: [0]};6;bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); t + 1";{xs: [1], ys: []};6;bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); t + 1";{xs: [], ys: [7]};6 +"t = 5; p = map(xs, (t = #; t)); q = map(ys, # + t); q";{xs: [1, 2], ys: [5]};[10];bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); q = map(ys, # + t); q";{xs: [], ys: []};[] +"t = 5; p = map(xs, (t = #; t)); q = map(ys, # + t); q";{xs: [3], ys: [1, 2, 3]};[6, 7, 8];bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); q = map(ys, # + t); q";{xs: [1.5], ys: [0]};[5];bug: an assignment inside a closure body leaks to the outer scope +"t = 5; p = map(xs, (t = #; t)); q = map(ys, # + t); q";{xs: [1], ys: []};[] +"t = 5; p = map(xs, (t = #; t)); q = map(ys, # + t); q";{xs: [], ys: [7]};[12] +"t = 5; p = map(xs, (t = #; t)); p";{xs: [1, 2], ys: [5]};[1, 2] +"t = 5; p = map(xs, (t = #; t)); p";{xs: [], ys: []};[] +"t = 5; p = map(xs, (t = #; t)); p";{xs: [3], ys: [1, 2, 3]};[3] +"t = 5; p = map(xs, (t = #; t)); p";{xs: [1.5], ys: [0]};[1.5] +"t = 5; p = map(xs, (t = #; t)); p";{xs: [1], ys: []};[1] +"t = 5; p = map(xs, (t = #; t)); p";{xs: [], ys: [7]};[] +"t = 5; p = map(xs, (t = #; t))";{xs: [1, 2], ys: [5]};{t: 5, p: [1, 2]} +"t = 5; p = map(xs, (t = #; t))";{xs: [], ys: []};{t: 5, p: []} +"t = 5; p = map(xs, (t = #; t))";{xs: [3], ys: [1, 2, 3]};{t: 5, p: [3]} +"t = 5; p = map(xs, (t = #; t))";{xs: [1.5], ys: [0]};{t: 5, p: [1.5]} +"t = 5; p = map(xs, (t = #; t))";{xs: [1], ys: []};{t: 5, p: [1]} +"t = 5; p = map(xs, (t = #; t))";{xs: [], ys: [7]};{t: 5, p: []} +"p = filter(xs, (v = #; v > 1)); q = count(ys, (v = #; v > 1)); [p, q, v ?? 0]";{xs: [1, 2], ys: [5]};[[2], 1, 0];bug: an assignment inside a closure body leaks to the outer scope +"p = filter(xs, (v = #; v > 1)); q = count(ys, (v = #; v > 1)); [p, q, v ?? 0]";{xs: [], ys: []};[[], 0, 0] +"p = filter(xs, (v = #; v > 1)); q = count(ys, (v = #; v > 1)); [p, q, v ?? 0]";{xs: [3], ys: [1, 2, 3]};[[3], 2, 0];bug: an assignment inside a closure body leaks to the outer scope +"p = filter(xs, (v = #; v > 1)); q = count(ys, (v = #; v > 1)); [p, q, v ?? 0]";{xs: [1.5], ys: [0]};[[1.5], 0, 0] +"p = filter(xs, (v = #; v > 1)); q = count(ys, (v = #; v > 1)); [p, q, v ?? 0]";{xs: [1], ys: []};[[], 0, 0];bug: an assignment inside a closure body leaks to the outer scope +"p = filter(xs, (v = #; v > 1)); q = count(ys, (v = #; v > 1)); [p, q, v ?? 0]";{xs: [], ys: [7]};[[], 1, 0];bug: an assignment inside a closure body leaks to the outer scope +# Closure-body locals do not persist across iterations (new shapes) +"r = map(xs, (seen = (seen ?? 0) + 1; seen)); r";{xs: [1, 2, 3]};[1, 1, 1];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (seen = (seen ?? 0) + 1; seen)); r";{xs: [5]};[1] +"r = map(xs, (seen = (seen ?? 0) + 1; seen)); r";{xs: []};[] +"r = map(xs, (seen = (seen ?? 0) + 1; seen)); r";{xs: [3, 1, 2]};[1, 1, 1];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (seen = (seen ?? 0) + 1; seen)); r";{xs: [0, 0]};[1, 1];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (m = max([m ?? #, #]); m)); r";{xs: [1, 2, 3]};[1, 2, 3] +"r = map(xs, (m = max([m ?? #, #]); m)); r";{xs: [5]};[5] +"r = map(xs, (m = max([m ?? #, #]); m)); r";{xs: []};[] +"r = map(xs, (m = max([m ?? #, #]); m)); r";{xs: [3, 1, 2]};[3, 1, 2];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (m = max([m ?? #, #]); m)); r";{xs: [0, 0]};[0, 0] +"r = filter(xs, (first = first ?? #; # == first)); r";{xs: [1, 2, 3]};[1, 2, 3];bug: a closure-body assignment carries over from one iteration to the next +"r = filter(xs, (first = first ?? #; # == first)); r";{xs: [5]};[5] +"r = filter(xs, (first = first ?? #; # == first)); r";{xs: []};[] +"r = filter(xs, (first = first ?? #; # == first)); r";{xs: [3, 1, 2]};[3, 1, 2];bug: a closure-body assignment carries over from one iteration to the next +"r = filter(xs, (first = first ?? #; # == first)); r";{xs: [0, 0]};[0, 0] +"r = map(xs, (acc = (acc ?? '') + string(#); acc)); r";{xs: [1, 2, 3]};['1', '2', '3'];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (acc = (acc ?? '') + string(#); acc)); r";{xs: [5]};['5'] +"r = map(xs, (acc = (acc ?? '') + string(#); acc)); r";{xs: []};[] +"r = map(xs, (acc = (acc ?? '') + string(#); acc)); r";{xs: [3, 1, 2]};['3', '1', '2'];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (acc = (acc ?? '') + string(#); acc)); r";{xs: [0, 0]};['0', '0'];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (prev = prev ?? null; cur = #; d = prev == null ? 0 : cur - prev; prev = cur; d)); r";{xs: [1, 2, 3]};[0, 0, 0];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (prev = prev ?? null; cur = #; d = prev == null ? 0 : cur - prev; prev = cur; d)); r";{xs: [5]};[0] +"r = map(xs, (prev = prev ?? null; cur = #; d = prev == null ? 0 : cur - prev; prev = cur; d)); r";{xs: []};[] +"r = map(xs, (prev = prev ?? null; cur = #; d = prev == null ? 0 : cur - prev; prev = cur; d)); r";{xs: [3, 1, 2]};[0, 0, 0];bug: a closure-body assignment carries over from one iteration to the next +"r = map(xs, (prev = prev ?? null; cur = #; d = prev == null ? 0 : cur - prev; prev = cur; d)); r";{xs: [0, 0]};[0, 0] +# Assignments inside ternary branches in one statement, read by the next +"r = c ? (t = a; t) : (u = b; u); [r, t, u]";{c: true, a: 1, b: 2};[1, 1, null];question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); [r, t, u]";{c: false, a: 1, b: 2};[2, null, 2];question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); [r, t, u]";{c: true, a: 'x', b: null};['x', 'x', null];question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); [r, t, u]";{c: false, a: null, b: 'y'};['y', null, 'y'];question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); [r, t, u]";{c: null, a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); [r, t, u]";{a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); s = t ?? u; s";{c: true, a: 1, b: 2};1;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); s = t ?? u; s";{c: false, a: 1, b: 2};2;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); s = t ?? u; s";{c: true, a: 'x', b: null};'x';question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); s = t ?? u; s";{c: false, a: null, b: 'y'};'y';question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); s = t ?? u; s";{c: null, a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; t) : (u = b; u); s = t ?? u; s";{a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'; out = {r: r, t: t}; out";{c: true, a: 1, b: 2};{r: 'A', t: 1};question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'; out = {r: r, t: t}; out";{c: false, a: 1, b: 2};{r: 'B', t: null};question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'; out = {r: r, t: t}; out";{c: true, a: 'x', b: null};{r: 'A', t: 'x'};question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'; out = {r: r, t: t}; out";{c: false, a: null, b: 'y'};{r: 'B', t: null};question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'; out = {r: r, t: t}; out";{c: null, a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'; out = {r: r, t: t}; out";{a: 1, b: 2};!error;question: t assigned inside the taken branch is visible after the program-level ternary +"r = c ? (t = a; 'A') : 'B'";{c: true, a: 1, b: 2};{r: 'A'} +"r = c ? (t = a; 'A') : 'B'";{c: false, a: 1, b: 2};{r: 'B'} +"r = c ? (t = a; 'A') : 'B'";{c: true, a: 'x', b: null};{r: 'A'} +"r = c ? (t = a; 'A') : 'B'";{c: false, a: null, b: 'y'};{r: 'B'} +"r = c ? (t = a; 'A') : 'B'";{c: null, a: 1, b: 2};!error +"r = c ? (t = a; 'A') : 'B'";{a: 1, b: 2};!error +# Assignments inside object literals in one statement, read by the next +"o = {x: (t = a; t)}; p = {y: t}; [o, p]";{a: 1};[{x: 1}, {y: 1}];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t)}; p = {y: t}; [o, p]";{a: 'x'};[{x: 'x'}, {y: 'x'}];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t)}; p = {y: t}; [o, p]";{a: null};[{x: null}, {y: null}];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t)}; p = {y: t}; [o, p]";{};[{x: null}, {y: null}];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t)}; p = {y: t}; [o, p]";{a: [1]};[{x: [1]}, {y: [1]}];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t), y: t}; o";{a: 1};{x: 1, y: 1};question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t), y: t}; o";{a: 'x'};{x: 'x', y: 'x'};question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t), y: t}; o";{a: null};{x: null, y: null};question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t), y: t}; o";{};{x: null, y: null};question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t), y: t}; o";{a: [1]};{x: [1], y: [1]};question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a; t)}; o";{a: 1};{x: 1} +"o = {x: (t = a; t)}; o";{a: 'x'};{x: 'x'} +"o = {x: (t = a; t)}; o";{a: null};{x: null} +"o = {x: (t = a; t)}; o";{};{x: null} +"o = {x: (t = a; t)}; o";{a: [1]};{x: [1]} +"o = {x: (t = a; t)}";{a: 1};{o: {x: 1}} +"o = {x: (t = a; t)}";{a: 'x'};{o: {x: 'x'}} +"o = {x: (t = a; t)}";{a: null};{o: {x: null}} +"o = {x: (t = a; t)}";{};{o: {x: null}} +"o = {x: (t = a; t)}";{a: [1]};{o: {x: [1]}} +"o = {x: (t = a; t)}; $root";{a: 1};{a: 1, o: {x: 1}, t: 1};question: $root contains t although the returned object does not +"o = {x: (t = a; t)}; $root";{a: 'x'};{a: 'x', o: {x: 'x'}, t: 'x'};question: $root contains t although the returned object does not +"o = {x: (t = a; t)}; $root";{a: null};{a: null, o: {x: null}, t: null};question: $root contains t although the returned object does not +"o = {x: (t = a; t)}; $root";{};{o: {x: null}, t: null};question: $root contains t although the returned object does not +"o = {x: (t = a; t)}; $root";{a: [1]};{a: [1], o: {x: [1]}, t: [1]};question: $root contains t although the returned object does not +"o = {x: (t = a ?? 'd'; t), y: (t = 'e'; t)}; [o, t]";{a: 1};[{x: 1, y: 'e'}, 'e'];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a ?? 'd'; t), y: (t = 'e'; t)}; [o, t]";{a: 'x'};[{x: 'x', y: 'e'}, 'e'];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a ?? 'd'; t), y: (t = 'e'; t)}; [o, t]";{a: null};[{x: 'd', y: 'e'}, 'e'];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a ?? 'd'; t), y: (t = 'e'; t)}; [o, t]";{};[{x: 'd', y: 'e'}, 'e'];question: a parenthesized sequence inside an object literal has no scope of its own +"o = {x: (t = a ?? 'd'; t), y: (t = 'e'; t)}; [o, t]";{a: [1]};[{x: [1], y: 'e'}, 'e'];question: a parenthesized sequence inside an object literal has no scope of its own +# Ternary, ?? and object-literal assignments inside closure bodies +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); r";{xs: [1, -2, 3]};[1, -2, 3] +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); r";{xs: []};[] +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); r";{xs: [-1]};[-1] +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); r";{xs: [0]};[0] +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); r";{xs: [1, null]};!error +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); [pos ?? 'none', neg ?? 'none']";{xs: [1, -2, 3]};['none', 'none'];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); [pos ?? 'none', neg ?? 'none']";{xs: []};['none', 'none'] +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); [pos ?? 'none', neg ?? 'none']";{xs: [-1]};['none', 'none'];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); [pos ?? 'none', neg ?? 'none']";{xs: [0]};['none', 'none'];bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, # > 0 ? (pos = #; pos) : (neg = #; neg)); [pos ?? 'none', neg ?? 'none']";{xs: [1, null]};!error +"r = map(xs, {v: #, sign: # > 0 ? (s = 'p'; s) : (s = 'n'; s)}); r";{xs: [1, -2, 3]};[{v: 1, sign: 'p'}, {v: -2, sign: 'n'}, {v: 3, sign: 'p'}] +"r = map(xs, {v: #, sign: # > 0 ? (s = 'p'; s) : (s = 'n'; s)}); r";{xs: []};[] +"r = map(xs, {v: #, sign: # > 0 ? (s = 'p'; s) : (s = 'n'; s)}); r";{xs: [-1]};[{v: -1, sign: 'n'}] +"r = map(xs, {v: #, sign: # > 0 ? (s = 'p'; s) : (s = 'n'; s)}); r";{xs: [0]};[{v: 0, sign: 'n'}] +"r = map(xs, {v: #, sign: # > 0 ? (s = 'p'; s) : (s = 'n'; s)}); r";{xs: [1, null]};!error +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); r";{xs: [1, -2, 3]};[{v: 1, s: 'p'}, {v: -2, s: 'n'}, {v: 3, s: 'p'}] +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); r";{xs: []};[] +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); r";{xs: [-1]};[{v: -1, s: 'n'}] +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); r";{xs: [0]};[{v: 0, s: 'n'}] +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); r";{xs: [1, null]};!error +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); s";{xs: [1, -2, 3]};null;bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); s";{xs: []};null +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); s";{xs: [-1]};null;bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); s";{xs: [0]};null;bug: an assignment inside a closure body leaks to the outer scope +"r = map(xs, (s = # > 0 ? 'p' : 'n'; {v: #, s: s})); s";{xs: [1, null]};!error +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); r";{xs: [1, -2, 3]};[2, -4, 6] +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); r";{xs: []};[] +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); r";{xs: [-1]};[-2] +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); r";{xs: [0]};[0] +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); r";{xs: [1, null]};[2, 0] +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); z ?? 'unset'";{xs: [1, -2, 3]};'unset' +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); z ?? 'unset'";{xs: []};'unset' +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); z ?? 'unset'";{xs: [-1]};'unset' +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); z ?? 'unset'";{xs: [0]};'unset' +"r = map(xs, (d = # ?? (z = 0; z); d * 2)); z ?? 'unset'";{xs: [1, null]};'unset';bug: an assignment inside a closure body leaks to the outer scope +# Closure assignments must not write through into the input +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); y";{list: [{v: 1}, {v: -1}]};[{v: 1, pos: true}, {v: -1, pos: false}] +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); y";{list: [{v: 0}]};[{v: 0, pos: false}] +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); y";{list: []};[] +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); y";{list: [{}]};[{pos: false}] +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); list";{list: [{v: 1}, {v: -1}]};[{v: 1}, {v: -1}];bug: a dotted assignment on a closure local writes through into the input element +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); list";{list: [{v: 0}]};[{v: 0}];bug: a dotted assignment on a closure local writes through into the input element +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); list";{list: []};[] +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); list";{list: [{}]};[{}];bug: a dotted assignment on a closure local writes through into the input element +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); map(list, #.pos)";{list: [{v: 1}, {v: -1}]};[null, null];bug: a dotted assignment on a closure local writes through into the input element +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); map(list, #.pos)";{list: [{v: 0}]};[null];bug: a dotted assignment on a closure local writes through into the input element +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); map(list, #.pos)";{list: []};[] +"y = map(list, (t = #; t.pos = (t.v ?? 0) > 0; t)); map(list, #.pos)";{list: [{}]};[null];bug: a dotted assignment on a closure local writes through into the input element +# Top-level aliases of input objects must not write through +"out = order; out.total = sum(order.lines ?? []); order";{order: {id: 1, lines: [1, 2]}};{id: 1, lines: [1, 2]};bug: a dotted assignment through an alias mutates the shared input object in place +"out = order; out.total = sum(order.lines ?? []); order";{order: {}};{};bug: a dotted assignment through an alias mutates the shared input object in place +"out = order; out.total = sum(order.lines ?? []); order";{order: {total: 5}};{total: 5};bug: a dotted assignment through an alias mutates the shared input object in place +"out = order; out.total = sum(order.lines ?? []); out";{order: {id: 1, lines: [1, 2]}};{id: 1, lines: [1, 2], total: 3} +"out = order; out.total = sum(order.lines ?? []); out";{order: {}};{total: 0} +"out = order; out.total = sum(order.lines ?? []); out";{order: {total: 5}};{total: 0} +"out = order; out.total = sum(order.lines ?? []); order.total";{order: {id: 1, lines: [1, 2]}};null;bug: a dotted assignment through an alias mutates the shared input object in place +"out = order; out.total = sum(order.lines ?? []); order.total";{order: {}};null;bug: a dotted assignment through an alias mutates the shared input object in place +"out = order; out.total = sum(order.lines ?? []); order.total";{order: {total: 5}};5;bug: a dotted assignment through an alias mutates the shared input object in place +"out = order; out.total = sum(order.lines ?? [])";{order: {id: 1, lines: [1, 2]}};{out: {id: 1, lines: [1, 2], total: 3}} +"out = order; out.total = sum(order.lines ?? [])";{order: {}};{out: {total: 0}} +"out = order; out.total = sum(order.lines ?? [])";{order: {total: 5}};{out: {total: 0}} diff --git a/core/expression/tests/spec/standard/18-date-inputs.csv b/core/expression/tests/spec/standard/18-date-inputs.csv new file mode 100644 index 00000000..a684888c --- /dev/null +++ b/core/expression/tests/spec/standard/18-date-inputs.csv @@ -0,0 +1,629 @@ +expression (string);input (json 5);output (json 5);note +# date inputs: text forms +x;{x: date('2024-03-15')};'2024-03-15' +x;{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +x;{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +x;{x: date('20240315')};'20240315' +x;{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +x;{x: '2024-03-15'};'2024-03-15' +x;{x: 'abc'};'abc' +x;{x: null};null +x;{};null +string(x);{x: date('2024-03-15')};'2024-03-15' +string(x);{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +string(x);{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +string(x);{x: date('20240315')};'20240315' +string(x);{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +string(x);{x: '2024-03-15'};'2024-03-15' +string(x);{x: 'abc'};'abc' +string(x);{x: null};'null' +string(x);{};'null' +x + '';{x: date('2024-03-15')};'2024-03-15' +x + '';{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +x + '';{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +x + '';{x: date('20240315')};'20240315' +x + '';{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +x + '';{x: '2024-03-15'};'2024-03-15' +x + '';{x: 'abc'};'abc' +x + '';{x: null};!error +x + '';{};!error +'on ' + x;{x: date('2024-03-15')};'on 2024-03-15' +'on ' + x;{x: date('2024-03-15T10:30:00+02:00')};'on 2024-03-15T10:30:00+02:00' +'on ' + x;{x: date('2024-03-15 10:30')};'on 2024-03-15 10:30' +'on ' + x;{x: date('20240315')};'on 20240315' +'on ' + x;{x: date('2024-03-15T23:30:00Z')};'on 2024-03-15T23:30:00Z' +'on ' + x;{x: '2024-03-15'};'on 2024-03-15' +'on ' + x;{x: 'abc'};'on abc' +'on ' + x;{x: null};!error +'on ' + x;{};!error +`${x}`;{x: date('2024-03-15')};'2024-03-15' +`${x}`;{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +`${x}`;{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +`${x}`;{x: date('20240315')};'20240315' +`${x}`;{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +`${x}`;{x: '2024-03-15'};'2024-03-15' +`${x}`;{x: 'abc'};'abc' +`${x}`;{x: null};'null' +`${x}`;{};'null' +`<${x}>`;{x: date('2024-03-15')};'<2024-03-15>' +`<${x}>`;{x: date('2024-03-15T10:30:00+02:00')};'<2024-03-15T10:30:00+02:00>' +`<${x}>`;{x: date('2024-03-15 10:30')};'<2024-03-15 10:30>' +`<${x}>`;{x: date('20240315')};'<20240315>' +`<${x}>`;{x: date('2024-03-15T23:30:00Z')};'<2024-03-15T23:30:00Z>' +`<${x}>`;{x: '2024-03-15'};'<2024-03-15>' +`<${x}>`;{x: 'abc'};'' +`<${x}>`;{x: null};'' +`<${x}>`;{};'' +len(x);{x: date('2024-03-15')};10 +len(x);{x: date('2024-03-15T10:30:00+02:00')};25 +len(x);{x: date('2024-03-15 10:30')};16 +len(x);{x: date('20240315')};8 +len(x);{x: date('2024-03-15T23:30:00Z')};20 +len(x);{x: '2024-03-15'};10 +len(x);{x: 'abc'};3 +len(x);{x: null};!error +len(x);{};!error +upper(x);{x: date('2024-03-15')};'2024-03-15' +upper(x);{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +upper(x);{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +upper(x);{x: date('20240315')};'20240315' +upper(x);{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +upper(x);{x: '2024-03-15'};'2024-03-15' +upper(x);{x: 'abc'};'ABC' +upper(x);{x: null};!error +upper(x);{};!error +lower(x);{x: date('2024-03-15')};'2024-03-15' +lower(x);{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15t10:30:00+02:00' +lower(x);{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +lower(x);{x: date('20240315')};'20240315' +lower(x);{x: date('2024-03-15T23:30:00Z')};'2024-03-15t23:30:00z' +lower(x);{x: '2024-03-15'};'2024-03-15' +lower(x);{x: 'abc'};'abc' +lower(x);{x: null};!error +lower(x);{};!error +trim(x);{x: date('2024-03-15')};'2024-03-15' +trim(x);{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +trim(x);{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +trim(x);{x: date('20240315')};'20240315' +trim(x);{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +trim(x);{x: '2024-03-15'};'2024-03-15' +trim(x);{x: 'abc'};'abc' +trim(x);{x: null};!error +trim(x);{};!error +x[0];{x: date('2024-03-15')};'2' +x[0];{x: date('2024-03-15T10:30:00+02:00')};'2' +x[0];{x: date('2024-03-15 10:30')};'2' +x[0];{x: date('20240315')};'2' +x[0];{x: date('2024-03-15T23:30:00Z')};'2' +x[0];{x: '2024-03-15'};'2' +x[0];{x: 'abc'};'a' +x[0];{x: null};null +x[0];{};null +x[0:3];{x: date('2024-03-15')};'2024' +x[0:3];{x: date('2024-03-15T10:30:00+02:00')};'2024' +x[0:3];{x: date('2024-03-15 10:30')};'2024' +x[0:3];{x: date('20240315')};'2024' +x[0:3];{x: date('2024-03-15T23:30:00Z')};'2024' +x[0:3];{x: '2024-03-15'};'2024' +x[0:3];{x: 'abc'};!error +x[0:3];{x: null};!error +x[0:3];{};!error +x[5:6];{x: date('2024-03-15')};'03' +x[5:6];{x: date('2024-03-15T10:30:00+02:00')};'03' +x[5:6];{x: date('2024-03-15 10:30')};'03' +x[5:6];{x: date('20240315')};'31' +x[5:6];{x: date('2024-03-15T23:30:00Z')};'03' +x[5:6];{x: '2024-03-15'};'03' +x[5:6];{x: 'abc'};!error +x[5:6];{x: null};!error +x[5:6];{};!error +startsWith(x, '2024');{x: date('2024-03-15')};true +startsWith(x, '2024');{x: date('2024-03-15T10:30:00+02:00')};true +startsWith(x, '2024');{x: date('2024-03-15 10:30')};true +startsWith(x, '2024');{x: date('20240315')};true +startsWith(x, '2024');{x: date('2024-03-15T23:30:00Z')};true +startsWith(x, '2024');{x: '2024-03-15'};true +startsWith(x, '2024');{x: 'abc'};false +startsWith(x, '2024');{x: null};!error +startsWith(x, '2024');{};!error +endsWith(x, '00');{x: date('2024-03-15')};false +endsWith(x, '00');{x: date('2024-03-15T10:30:00+02:00')};true +endsWith(x, '00');{x: date('2024-03-15 10:30')};false +endsWith(x, '00');{x: date('20240315')};false +endsWith(x, '00');{x: date('2024-03-15T23:30:00Z')};false +endsWith(x, '00');{x: '2024-03-15'};false +endsWith(x, '00');{x: 'abc'};false +endsWith(x, '00');{x: null};!error +endsWith(x, '00');{};!error +endsWith('prefix-2024-03-15', x);{x: date('2024-03-15')};true +endsWith('prefix-2024-03-15', x);{x: date('2024-03-15T10:30:00+02:00')};false +endsWith('prefix-2024-03-15', x);{x: date('2024-03-15 10:30')};false +endsWith('prefix-2024-03-15', x);{x: date('20240315')};false +endsWith('prefix-2024-03-15', x);{x: date('2024-03-15T23:30:00Z')};false +endsWith('prefix-2024-03-15', x);{x: '2024-03-15'};true +endsWith('prefix-2024-03-15', x);{x: 'abc'};false +endsWith('prefix-2024-03-15', x);{x: null};!error +endsWith('prefix-2024-03-15', x);{};!error +contains(x, 'T');{x: date('2024-03-15')};false +contains(x, 'T');{x: date('2024-03-15T10:30:00+02:00')};true +contains(x, 'T');{x: date('2024-03-15 10:30')};false +contains(x, 'T');{x: date('20240315')};false +contains(x, 'T');{x: date('2024-03-15T23:30:00Z')};true +contains(x, 'T');{x: '2024-03-15'};false +contains(x, 'T');{x: 'abc'};false +contains(x, 'T');{x: null};!error +contains(x, 'T');{};!error +contains('on 2024-03-15', x);{x: date('2024-03-15')};true +contains('on 2024-03-15', x);{x: date('2024-03-15T10:30:00+02:00')};false +contains('on 2024-03-15', x);{x: date('2024-03-15 10:30')};false +contains('on 2024-03-15', x);{x: date('20240315')};false +contains('on 2024-03-15', x);{x: date('2024-03-15T23:30:00Z')};false +contains('on 2024-03-15', x);{x: '2024-03-15'};true +contains('on 2024-03-15', x);{x: 'abc'};false +contains('on 2024-03-15', x);{x: null};!error +contains('on 2024-03-15', x);{};!error +split(x, '-');{x: date('2024-03-15')};['2024', '03', '15'] +split(x, '-');{x: date('2024-03-15T10:30:00+02:00')};['2024', '03', '15T10:30:00+02:00'] +split(x, '-');{x: date('2024-03-15 10:30')};['2024', '03', '15 10:30'] +split(x, '-');{x: date('20240315')};['20240315'] +split(x, '-');{x: date('2024-03-15T23:30:00Z')};['2024', '03', '15T23:30:00Z'] +split(x, '-');{x: '2024-03-15'};['2024', '03', '15'] +split(x, '-');{x: 'abc'};['abc'] +split(x, '-');{x: null};!error +split(x, '-');{};!error +matches(x, '^2024');{x: date('2024-03-15')};true +matches(x, '^2024');{x: date('2024-03-15T10:30:00+02:00')};true +matches(x, '^2024');{x: date('2024-03-15 10:30')};true +matches(x, '^2024');{x: date('20240315')};true +matches(x, '^2024');{x: date('2024-03-15T23:30:00Z')};true +matches(x, '^2024');{x: '2024-03-15'};true +matches(x, '^2024');{x: 'abc'};false +matches(x, '^2024');{x: null};!error +matches(x, '^2024');{};!error +extract(x, '(\d{4})');{x: date('2024-03-15')};['2024', '2024'] +extract(x, '(\d{4})');{x: date('2024-03-15T10:30:00+02:00')};['2024', '2024'] +extract(x, '(\d{4})');{x: date('2024-03-15 10:30')};['2024', '2024'] +extract(x, '(\d{4})');{x: date('20240315')};['2024', '2024'] +extract(x, '(\d{4})');{x: date('2024-03-15T23:30:00Z')};['2024', '2024'] +extract(x, '(\d{4})');{x: '2024-03-15'};['2024', '2024'] +extract(x, '(\d{4})');{x: 'abc'};[] +extract(x, '(\d{4})');{x: null};!error +extract(x, '(\d{4})');{};!error +fuzzyMatch(x, '2024-03-15');{x: date('2024-03-15')};1 +fuzzyMatch(x, '2024-03-15');{x: date('2024-03-15T10:30:00+02:00')};0.4 +fuzzyMatch(x, '2024-03-15');{x: date('2024-03-15 10:30')};0.625 +fuzzyMatch(x, '2024-03-15');{x: date('20240315')};0.8 +fuzzyMatch(x, '2024-03-15');{x: date('2024-03-15T23:30:00Z')};0.5 +fuzzyMatch(x, '2024-03-15');{x: '2024-03-15'};1 +fuzzyMatch(x, '2024-03-15');{x: 'abc'};0 +fuzzyMatch(x, '2024-03-15');{x: null};!error +fuzzyMatch(x, '2024-03-15');{};!error +bool(x);{x: date('2024-03-15')};true;bug: a date input converts through its source text, and non-empty text converts to false (inverted is_empty) +bool(x);{x: date('2024-03-15T10:30:00+02:00')};true;bug: a date input converts through its source text, and non-empty text converts to false (inverted is_empty) +bool(x);{x: date('2024-03-15 10:30')};true;bug: a date input converts through its source text, and non-empty text converts to false (inverted is_empty) +bool(x);{x: date('20240315')};true;bug: a date input converts through its source text, and non-empty text converts to false (inverted is_empty) +bool(x);{x: date('2024-03-15T23:30:00Z')};true;bug: a date input converts through its source text, and non-empty text converts to false (inverted is_empty) +bool(x);{x: '2024-03-15'};true;bug: non-empty string converts to false (inverted is_empty) +bool(x);{x: 'abc'};true;bug: non-empty string converts to false (inverted is_empty) +bool(x);{x: null};false +bool(x);{};false +number(x);{x: date('2024-03-15')};!error +number(x);{x: date('2024-03-15T10:30:00+02:00')};!error +number(x);{x: date('2024-03-15 10:30')};!error +number(x);{x: date('20240315')};!error +number(x);{x: date('2024-03-15T23:30:00Z')};!error +number(x);{x: '2024-03-15'};!error +number(x);{x: 'abc'};!error +number(x);{x: null};!error +number(x);{};!error +isNumeric(x);{x: date('2024-03-15')};false +isNumeric(x);{x: date('2024-03-15T10:30:00+02:00')};false +isNumeric(x);{x: date('2024-03-15 10:30')};false +isNumeric(x);{x: date('20240315')};false +isNumeric(x);{x: date('2024-03-15T23:30:00Z')};false +isNumeric(x);{x: '2024-03-15'};false +isNumeric(x);{x: 'abc'};false +isNumeric(x);{x: null};false +isNumeric(x);{};false +type(x);{x: date('2024-03-15')};'date' +type(x);{x: date('2024-03-15T10:30:00+02:00')};'date' +type(x);{x: date('2024-03-15 10:30')};'date' +type(x);{x: date('20240315')};'date' +type(x);{x: date('2024-03-15T23:30:00Z')};'date' +type(x);{x: '2024-03-15'};'string' +type(x);{x: 'abc'};'string' +type(x);{x: null};'null' +type(x);{};'null' +# date inputs: comparisons +x == '2024-03-15';{x: date('2024-03-15')};true +x == '2024-03-15';{x: date('2024-03-15T10:30:00+02:00')};false +x == '2024-03-15';{x: date('2024-03-15 10:30')};false +x == '2024-03-15';{x: date('20240315')};true +x == '2024-03-15';{x: date('2024-03-15T23:30:00Z')};false +x == '2024-03-15';{x: '2024-03-15'};true +x == '2024-03-15';{x: 'abc'};false +x == '2024-03-15';{x: null};false +x == '2024-03-15';{};false +'2024-03-15' == x;{x: date('2024-03-15')};true +'2024-03-15' == x;{x: date('2024-03-15T10:30:00+02:00')};false +'2024-03-15' == x;{x: date('2024-03-15 10:30')};false +'2024-03-15' == x;{x: date('20240315')};true +'2024-03-15' == x;{x: date('2024-03-15T23:30:00Z')};false +'2024-03-15' == x;{x: '2024-03-15'};true +'2024-03-15' == x;{x: 'abc'};false +'2024-03-15' == x;{x: null};false +'2024-03-15' == x;{};false +x == '2024-03-15T00:00:00Z';{x: date('2024-03-15')};true +x == '2024-03-15T00:00:00Z';{x: date('2024-03-15T10:30:00+02:00')};false +x == '2024-03-15T00:00:00Z';{x: date('2024-03-15 10:30')};false +x == '2024-03-15T00:00:00Z';{x: date('20240315')};true +x == '2024-03-15T00:00:00Z';{x: date('2024-03-15T23:30:00Z')};false +x == '2024-03-15T00:00:00Z';{x: '2024-03-15'};false +x == '2024-03-15T00:00:00Z';{x: 'abc'};false +x == '2024-03-15T00:00:00Z';{x: null};false +x == '2024-03-15T00:00:00Z';{};false +x == d('2024-03-15');{x: date('2024-03-15')};true +x == d('2024-03-15');{x: date('2024-03-15T10:30:00+02:00')};false +x == d('2024-03-15');{x: date('2024-03-15 10:30')};false +x == d('2024-03-15');{x: date('20240315')};true +x == d('2024-03-15');{x: date('2024-03-15T23:30:00Z')};false +x == d('2024-03-15');{x: '2024-03-15'};true +x == d('2024-03-15');{x: 'abc'};false +x == d('2024-03-15');{x: null};false +x == d('2024-03-15');{};false +x != '2024-03-15';{x: date('2024-03-15')};false +x != '2024-03-15';{x: date('2024-03-15T10:30:00+02:00')};true +x != '2024-03-15';{x: date('2024-03-15 10:30')};true +x != '2024-03-15';{x: date('20240315')};false +x != '2024-03-15';{x: date('2024-03-15T23:30:00Z')};true +x != '2024-03-15';{x: '2024-03-15'};false +x != '2024-03-15';{x: 'abc'};true +x != '2024-03-15';{x: null};true +x != '2024-03-15';{};true +x == x;{x: date('2024-03-15')};true +x == x;{x: date('2024-03-15T10:30:00+02:00')};true +x == x;{x: date('2024-03-15 10:30')};true +x == x;{x: date('20240315')};true +x == x;{x: date('2024-03-15T23:30:00Z')};true +x == x;{x: '2024-03-15'};true +x == x;{x: 'abc'};true +x == x;{x: null};true +x == x;{};true +x > '2024-03-14';{x: date('2024-03-15')};true +x > '2024-03-14';{x: date('2024-03-15T10:30:00+02:00')};true +x > '2024-03-14';{x: date('2024-03-15 10:30')};true +x > '2024-03-14';{x: date('20240315')};true +x > '2024-03-14';{x: date('2024-03-15T23:30:00Z')};true +x > '2024-03-14';{x: '2024-03-15'};!error +x > '2024-03-14';{x: 'abc'};!error +x > '2024-03-14';{x: null};!error +x > '2024-03-14';{};!error +x >= '2024-03-15';{x: date('2024-03-15')};true +x >= '2024-03-15';{x: date('2024-03-15T10:30:00+02:00')};true +x >= '2024-03-15';{x: date('2024-03-15 10:30')};true +x >= '2024-03-15';{x: date('20240315')};true +x >= '2024-03-15';{x: date('2024-03-15T23:30:00Z')};true +x >= '2024-03-15';{x: '2024-03-15'};!error +x >= '2024-03-15';{x: 'abc'};!error +x >= '2024-03-15';{x: null};!error +x >= '2024-03-15';{};!error +'2024-03-16' > x;{x: date('2024-03-15')};true +'2024-03-16' > x;{x: date('2024-03-15T10:30:00+02:00')};true +'2024-03-16' > x;{x: date('2024-03-15 10:30')};true +'2024-03-16' > x;{x: date('20240315')};true +'2024-03-16' > x;{x: date('2024-03-15T23:30:00Z')};true +'2024-03-16' > x;{x: '2024-03-15'};!error +'2024-03-16' > x;{x: 'abc'};!error +'2024-03-16' > x;{x: null};!error +'2024-03-16' > x;{};!error +x < d('2024-03-16');{x: date('2024-03-15')};true +x < d('2024-03-16');{x: date('2024-03-15T10:30:00+02:00')};true +x < d('2024-03-16');{x: date('2024-03-15 10:30')};true +x < d('2024-03-16');{x: date('20240315')};true +x < d('2024-03-16');{x: date('2024-03-15T23:30:00Z')};true +x < d('2024-03-16');{x: '2024-03-15'};true +x < d('2024-03-16');{x: 'abc'};!error +x < d('2024-03-16');{x: null};!error +x < d('2024-03-16');{};!error +x > 'abc';{x: date('2024-03-15')};!error +x > 'abc';{x: date('2024-03-15T10:30:00+02:00')};!error +x > 'abc';{x: date('2024-03-15 10:30')};!error +x > 'abc';{x: date('20240315')};!error +x > 'abc';{x: date('2024-03-15T23:30:00Z')};!error +x > 'abc';{x: '2024-03-15'};!error +x > 'abc';{x: 'abc'};!error +x > 'abc';{x: null};!error +x > 'abc';{};!error +x in ['2024-03-15', '2024-03-16'];{x: date('2024-03-15')};true +x in ['2024-03-15', '2024-03-16'];{x: date('2024-03-15T10:30:00+02:00')};false +x in ['2024-03-15', '2024-03-16'];{x: date('2024-03-15 10:30')};false +x in ['2024-03-15', '2024-03-16'];{x: date('20240315')};true +x in ['2024-03-15', '2024-03-16'];{x: date('2024-03-15T23:30:00Z')};false +x in ['2024-03-15', '2024-03-16'];{x: '2024-03-15'};true +x in ['2024-03-15', '2024-03-16'];{x: 'abc'};false +x in ['2024-03-15', '2024-03-16'];{x: null};false +x in ['2024-03-15', '2024-03-16'];{};false +x in [d('2024-03-15')];{x: date('2024-03-15')};true +x in [d('2024-03-15')];{x: date('2024-03-15T10:30:00+02:00')};false +x in [d('2024-03-15')];{x: date('2024-03-15 10:30')};false +x in [d('2024-03-15')];{x: date('20240315')};true +x in [d('2024-03-15')];{x: date('2024-03-15T23:30:00Z')};false +x in [d('2024-03-15')];{x: '2024-03-15'};true +x in [d('2024-03-15')];{x: 'abc'};false +x in [d('2024-03-15')];{x: null};false +x in [d('2024-03-15')];{};false +'2024-03-15' in [x];{x: date('2024-03-15')};true +'2024-03-15' in [x];{x: date('2024-03-15T10:30:00+02:00')};false +'2024-03-15' in [x];{x: date('2024-03-15 10:30')};false +'2024-03-15' in [x];{x: date('20240315')};true +'2024-03-15' in [x];{x: date('2024-03-15T23:30:00Z')};false +'2024-03-15' in [x];{x: '2024-03-15'};true +'2024-03-15' in [x];{x: 'abc'};false +'2024-03-15' in [x];{x: null};false +'2024-03-15' in [x];{};false +x not in ['2024-03-15'];{x: date('2024-03-15')};false +x not in ['2024-03-15'];{x: date('2024-03-15T10:30:00+02:00')};true +x not in ['2024-03-15'];{x: date('2024-03-15 10:30')};true +x not in ['2024-03-15'];{x: date('20240315')};false +x not in ['2024-03-15'];{x: date('2024-03-15T23:30:00Z')};true +x not in ['2024-03-15'];{x: '2024-03-15'};false +x not in ['2024-03-15'];{x: 'abc'};true +x not in ['2024-03-15'];{x: null};true +x not in ['2024-03-15'];{};true +contains([x], '2024-03-15');{x: date('2024-03-15')};true +contains([x], '2024-03-15');{x: date('2024-03-15T10:30:00+02:00')};false +contains([x], '2024-03-15');{x: date('2024-03-15 10:30')};false +contains([x], '2024-03-15');{x: date('20240315')};true +contains([x], '2024-03-15');{x: date('2024-03-15T23:30:00Z')};false +contains([x], '2024-03-15');{x: '2024-03-15'};true +contains([x], '2024-03-15');{x: 'abc'};false +contains([x], '2024-03-15');{x: null};false +contains([x], '2024-03-15');{};false +contains(['2024-03-15'], x);{x: date('2024-03-15')};true +contains(['2024-03-15'], x);{x: date('2024-03-15T10:30:00+02:00')};false +contains(['2024-03-15'], x);{x: date('2024-03-15 10:30')};false +contains(['2024-03-15'], x);{x: date('20240315')};true +contains(['2024-03-15'], x);{x: date('2024-03-15T23:30:00Z')};false +contains(['2024-03-15'], x);{x: '2024-03-15'};true +contains(['2024-03-15'], x);{x: 'abc'};false +contains(['2024-03-15'], x);{x: null};false +contains(['2024-03-15'], x);{};false +contains([x], d('2024-03-15'));{x: date('2024-03-15')};true +contains([x], d('2024-03-15'));{x: date('2024-03-15T10:30:00+02:00')};false +contains([x], d('2024-03-15'));{x: date('2024-03-15 10:30')};false +contains([x], d('2024-03-15'));{x: date('20240315')};true +contains([x], d('2024-03-15'));{x: date('2024-03-15T23:30:00Z')};false +contains([x], d('2024-03-15'));{x: '2024-03-15'};true +contains([x], d('2024-03-15'));{x: 'abc'};false +contains([x], d('2024-03-15'));{x: null};false +contains([x], d('2024-03-15'));{};false +x in [d('2024-03-10')..d('2024-03-20')];{x: date('2024-03-15')};true +x in [d('2024-03-10')..d('2024-03-20')];{x: date('2024-03-15T10:30:00+02:00')};true +x in [d('2024-03-10')..d('2024-03-20')];{x: date('2024-03-15 10:30')};true +x in [d('2024-03-10')..d('2024-03-20')];{x: date('20240315')};true +x in [d('2024-03-10')..d('2024-03-20')];{x: date('2024-03-15T23:30:00Z')};true +x in [d('2024-03-10')..d('2024-03-20')];{x: '2024-03-15'};!error +x in [d('2024-03-10')..d('2024-03-20')];{x: 'abc'};!error +x in [d('2024-03-10')..d('2024-03-20')];{x: null};!error +x in [d('2024-03-10')..d('2024-03-20')];{};!error +x == 1710460800000;{x: date('2024-03-15')};false +x == 1710460800000;{x: date('2024-03-15T10:30:00+02:00')};false +x == 1710460800000;{x: date('2024-03-15 10:30')};false +x == 1710460800000;{x: date('20240315')};false +x == 1710460800000;{x: date('2024-03-15T23:30:00Z')};false +x == 1710460800000;{x: '2024-03-15'};false +x == 1710460800000;{x: 'abc'};false +x == 1710460800000;{x: null};false +x == 1710460800000;{};false +x ?? 'none';{x: date('2024-03-15')};'2024-03-15' +x ?? 'none';{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +x ?? 'none';{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +x ?? 'none';{x: date('20240315')};'20240315' +x ?? 'none';{x: date('2024-03-15T23:30:00Z')};'2024-03-15T23:30:00Z' +x ?? 'none';{x: '2024-03-15'};'2024-03-15' +x ?? 'none';{x: 'abc'};'abc' +x ?? 'none';{x: null};'none' +x ?? 'none';{};'none' +# date inputs: date use +d(x);{x: date('2024-03-15')};'2024-03-15T00:00:00Z' +d(x);{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T08:30:00Z' +d(x);{x: date('2024-03-15 10:30')};'2024-03-15T10:30:00Z' +d(x);{x: '2024-03-15'};'2024-03-15T00:00:00Z' +d(x);{x: null};'Invalid date' +d(x).year();{x: date('2024-03-15')};2024 +d(x).year();{x: date('2024-03-15T10:30:00+02:00')};2024 +d(x).year();{x: date('2024-03-15 10:30')};2024 +d(x).year();{x: '2024-03-15'};2024 +d(x).year();{x: null};null +d(x, 'Europe/Berlin');{x: date('2024-03-15')};'2024-03-15T00:00:00+01:00' +d(x, 'Europe/Berlin');{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T09:30:00+01:00' +d(x, 'Europe/Berlin');{x: date('2024-03-15 10:30')};'2024-03-15T10:30:00+01:00' +d(x, 'Europe/Berlin');{x: '2024-03-15'};'2024-03-15T00:00:00+01:00' +d(x, 'Europe/Berlin');{x: null};'Invalid date' +d(x, 'America/New_York').hour();{x: date('2024-03-15')};0 +d(x, 'America/New_York').hour();{x: date('2024-03-15T10:30:00+02:00')};4 +d(x, 'America/New_York').hour();{x: date('2024-03-15 10:30')};10 +d(x, 'America/New_York').hour();{x: '2024-03-15'};0 +d(x, 'America/New_York').hour();{x: null};null +d(x, 'UTC');{x: date('2024-03-15')};'2024-03-15T00:00:00Z' +d(x, 'UTC');{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T08:30:00Z' +d(x, 'UTC');{x: date('2024-03-15 10:30')};'2024-03-15T10:30:00Z' +d(x, 'UTC');{x: '2024-03-15'};'2024-03-15T00:00:00Z' +d(x, 'UTC');{x: null};'Invalid date' +d(x).add(1, 'd');{x: date('2024-03-15')};'2024-03-16T00:00:00Z' +d(x).add(1, 'd');{x: date('2024-03-15T10:30:00+02:00')};'2024-03-16T08:30:00Z' +d(x).add(1, 'd');{x: date('2024-03-15 10:30')};'2024-03-16T10:30:00Z' +d(x).add(1, 'd');{x: '2024-03-15'};'2024-03-16T00:00:00Z' +d(x).add(1, 'd');{x: null};'Invalid date' +d(x).startOf('month');{x: date('2024-03-15')};'2024-03-01T00:00:00Z' +d(x).startOf('month');{x: date('2024-03-15T10:30:00+02:00')};'2024-03-01T00:00:00Z' +d(x).startOf('month');{x: date('2024-03-15 10:30')};'2024-03-01T00:00:00Z' +d(x).startOf('month');{x: '2024-03-15'};'2024-03-01T00:00:00Z' +d(x).startOf('month');{x: null};'Invalid date' +x.year();{x: date('2024-03-15')};2024 +x.year();{x: date('2024-03-15T10:30:00+02:00')};2024 +x.year();{x: date('2024-03-15 10:30')};2024 +x.year();{x: '2024-03-15'};!error +x.year();{x: null};!error +x.month();{x: date('2024-03-15')};3 +x.month();{x: date('2024-03-15T10:30:00+02:00')};3 +x.month();{x: date('2024-03-15 10:30')};3 +x.month();{x: '2024-03-15'};!error +x.month();{x: null};!error +x.hour();{x: date('2024-03-15')};0 +x.hour();{x: date('2024-03-15T10:30:00+02:00')};8 +x.hour();{x: date('2024-03-15 10:30')};10 +x.hour();{x: '2024-03-15'};!error +x.hour();{x: null};!error +x.add(1, 'd');{x: date('2024-03-15')};'2024-03-16T00:00:00Z' +x.add(1, 'd');{x: date('2024-03-15T10:30:00+02:00')};'2024-03-16T08:30:00Z' +x.add(1, 'd');{x: date('2024-03-15 10:30')};'2024-03-16T10:30:00Z' +x.add(1, 'd');{x: '2024-03-15'};!error +x.add(1, 'd');{x: null};!error +x.format('%Y/%m/%d');{x: date('2024-03-15')};'2024/03/15' +x.format('%Y/%m/%d');{x: date('2024-03-15T10:30:00+02:00')};'2024/03/15' +x.format('%Y/%m/%d');{x: date('2024-03-15 10:30')};'2024/03/15' +x.format('%Y/%m/%d');{x: '2024-03-15'};!error +x.format('%Y/%m/%d');{x: null};!error +x.tz('Asia/Tokyo');{x: date('2024-03-15')};'2024-03-15T09:00:00+09:00' +x.tz('Asia/Tokyo');{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T17:30:00+09:00' +x.tz('Asia/Tokyo');{x: date('2024-03-15 10:30')};'2024-03-15T19:30:00+09:00' +x.tz('Asia/Tokyo');{x: '2024-03-15'};!error +x.tz('Asia/Tokyo');{x: null};!error +x.diff('2024-03-01', 'd');{x: date('2024-03-15')};14 +x.diff('2024-03-01', 'd');{x: date('2024-03-15T10:30:00+02:00')};14 +x.diff('2024-03-01', 'd');{x: date('2024-03-15 10:30')};14 +x.diff('2024-03-01', 'd');{x: '2024-03-15'};!error +x.diff('2024-03-01', 'd');{x: null};!error +x.isAfter(d('2024-01-01'));{x: date('2024-03-15')};true +x.isAfter(d('2024-01-01'));{x: date('2024-03-15T10:30:00+02:00')};true +x.isAfter(d('2024-01-01'));{x: date('2024-03-15 10:30')};true +x.isAfter(d('2024-01-01'));{x: '2024-03-15'};!error +x.isAfter(d('2024-01-01'));{x: null};!error +x.isSame('2024-03-15', 'day');{x: date('2024-03-15')};true +x.isSame('2024-03-15', 'day');{x: date('2024-03-15T10:30:00+02:00')};true +x.isSame('2024-03-15', 'day');{x: date('2024-03-15 10:30')};true +x.isSame('2024-03-15', 'day');{x: '2024-03-15'};!error +x.isSame('2024-03-15', 'day');{x: null};!error +d('2024-03-20').diff(x, 'd');{x: date('2024-03-15')};5 +d('2024-03-20').diff(x, 'd');{x: date('2024-03-15T10:30:00+02:00')};4 +d('2024-03-20').diff(x, 'd');{x: date('2024-03-15 10:30')};4 +d('2024-03-20').diff(x, 'd');{x: '2024-03-15'};5 +d('2024-03-20').diff(x, 'd');{x: null};null +d('2024-03-15').isSame(x);{x: date('2024-03-15')};true +d('2024-03-15').isSame(x);{x: date('2024-03-15T10:30:00+02:00')};false +d('2024-03-15').isSame(x);{x: date('2024-03-15 10:30')};false +d('2024-03-15').isSame(x);{x: '2024-03-15'};true +d('2024-03-15').isSame(x);{x: null};false +d(x).isValid();{x: date('2024-03-15')};true +d(x).isValid();{x: date('2024-03-15T10:30:00+02:00')};true +d(x).isValid();{x: date('2024-03-15 10:30')};true +d(x).isValid();{x: '2024-03-15'};true +d(x).isValid();{x: null};false +x.isValid();{x: date('2024-03-15')};true +x.isValid();{x: date('2024-03-15T10:30:00+02:00')};true +x.isValid();{x: date('2024-03-15 10:30')};true +x.isValid();{x: '2024-03-15'};!error +x.isValid();{x: null};!error +# date inputs: legacy functions +year(x);{x: date('2024-03-15')};2024 +year(x);{x: date('2024-03-15T10:30:00+02:00')};2024 +year(x);{x: date('2024-03-15 10:30')};2024 +year(x);{x: '2024-03-15'};2024 +year(x);{x: null};!error +monthOfYear(x);{x: date('2024-03-15')};3 +monthOfYear(x);{x: date('2024-03-15T10:30:00+02:00')};3 +monthOfYear(x);{x: date('2024-03-15 10:30')};3 +monthOfYear(x);{x: '2024-03-15'};3 +monthOfYear(x);{x: null};!error +dayOfMonth(x);{x: date('2024-03-15')};15 +dayOfMonth(x);{x: date('2024-03-15T10:30:00+02:00')};15 +dayOfMonth(x);{x: date('2024-03-15 10:30')};15 +dayOfMonth(x);{x: '2024-03-15'};15 +dayOfMonth(x);{x: null};!error +dateString(x);{x: date('2024-03-15')};'2024-03-15 00:00:00' +dateString(x);{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15 08:30:00' +dateString(x);{x: date('2024-03-15 10:30')};'2024-03-15 10:30:00' +dateString(x);{x: '2024-03-15'};'2024-03-15 00:00:00' +dateString(x);{x: null};!error +time(x);{x: date('2024-03-15')};0 +time(x);{x: date('2024-03-15T10:30:00+02:00')};30600 +time(x);{x: date('2024-03-15 10:30')};37800 +time(x);{x: '2024-03-15'};!error +time(x);{x: null};!error +date(x);{x: date('2024-03-15')};1710460800 +date(x);{x: date('2024-03-15T10:30:00+02:00')};1710491400 +date(x);{x: date('2024-03-15 10:30')};1710498600 +date(x);{x: '2024-03-15'};1710460800 +date(x);{x: null};!error +startOf(x, 'day');{x: date('2024-03-15')};1710460800 +startOf(x, 'day');{x: date('2024-03-15T10:30:00+02:00')};1710460800 +startOf(x, 'day');{x: date('2024-03-15 10:30')};1710460800 +startOf(x, 'day');{x: '2024-03-15'};1710460800 +startOf(x, 'day');{x: null};!error +weekdayString(x);{x: date('2024-03-15')};'Fri' +weekdayString(x);{x: date('2024-03-15T10:30:00+02:00')};'Fri' +weekdayString(x);{x: date('2024-03-15 10:30')};'Fri' +weekdayString(x);{x: '2024-03-15'};'Fri' +weekdayString(x);{x: null};!error +# date inputs: containers +[x];{x: date('2024-03-15')};['2024-03-15'] +[x];{x: date('2024-03-15T10:30:00+02:00')};['2024-03-15T10:30:00+02:00'] +[x];{x: date('2024-03-15 10:30')};['2024-03-15 10:30'] +[x];{x: '2024-03-15'};['2024-03-15'] +[x];{x: null};[null] +{v: x};{x: date('2024-03-15')};{v: '2024-03-15'} +{v: x};{x: date('2024-03-15T10:30:00+02:00')};{v: '2024-03-15T10:30:00+02:00'} +{v: x};{x: date('2024-03-15 10:30')};{v: '2024-03-15 10:30'} +{v: x};{x: '2024-03-15'};{v: '2024-03-15'} +{v: x};{x: null};{v: null} +[x, 1][0];{x: date('2024-03-15')};'2024-03-15' +[x, 1][0];{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +[x, 1][0];{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +[x, 1][0];{x: '2024-03-15'};'2024-03-15' +[x, 1][0];{x: null};null +({a: x}).a;{x: date('2024-03-15')};'2024-03-15' +({a: x}).a;{x: date('2024-03-15T10:30:00+02:00')};'2024-03-15T10:30:00+02:00' +({a: x}).a;{x: date('2024-03-15 10:30')};'2024-03-15 10:30' +({a: x}).a;{x: '2024-03-15'};'2024-03-15' +({a: x}).a;{x: null};null +x in {a: 1};{x: date('2024-03-15')};false +x in {a: 1};{x: date('2024-03-15T10:30:00+02:00')};false +x in {a: 1};{x: date('2024-03-15 10:30')};false +x in {a: 1};{x: '2024-03-15'};false +x in {a: 1};{x: null};!error +({'2024-03-15': 1})[x];{x: date('2024-03-15')};1 +({'2024-03-15': 1})[x];{x: date('2024-03-15T10:30:00+02:00')};null +({'2024-03-15': 1})[x];{x: date('2024-03-15 10:30')};null +({'2024-03-15': 1})[x];{x: '2024-03-15'};1 +({'2024-03-15': 1})[x];{x: null};null +map([x, x], # + '');{x: date('2024-03-15')};['2024-03-15', '2024-03-15'] +map([x, x], # + '');{x: date('2024-03-15T10:30:00+02:00')};['2024-03-15T10:30:00+02:00', '2024-03-15T10:30:00+02:00'] +map([x, x], # + '');{x: date('2024-03-15 10:30')};['2024-03-15 10:30', '2024-03-15 10:30'] +map([x, x], # + '');{x: '2024-03-15'};['2024-03-15', '2024-03-15'] +map([x, x], # + '');{x: null};!error +filter([x], # == '2024-03-15');{x: date('2024-03-15')};['2024-03-15'] +filter([x], # == '2024-03-15');{x: date('2024-03-15T10:30:00+02:00')};[] +filter([x], # == '2024-03-15');{x: date('2024-03-15 10:30')};[] +filter([x], # == '2024-03-15');{x: '2024-03-15'};['2024-03-15'] +filter([x], # == '2024-03-15');{x: null};[] +len(filter([x, '2024-03-15'], # >= '2024-03-01'));{x: date('2024-03-15')};!error +len(filter([x, '2024-03-15'], # >= '2024-03-01'));{x: date('2024-03-15T10:30:00+02:00')};!error +len(filter([x, '2024-03-15'], # >= '2024-03-01'));{x: date('2024-03-15 10:30')};!error +len(filter([x, '2024-03-15'], # >= '2024-03-01'));{x: '2024-03-15'};!error +len(filter([x, '2024-03-15'], # >= '2024-03-01'));{x: null};!error +map([x], d(#).day());{x: date('2024-03-15')};[15] +map([x], d(#).day());{x: date('2024-03-15T10:30:00+02:00')};[15] +map([x], d(#).day());{x: date('2024-03-15 10:30')};[15] +map([x], d(#).day());{x: '2024-03-15'};[15] +map([x], d(#).day());{x: null};[null] +some([x], # > '2024-01-01');{x: date('2024-03-15')};true +some([x], # > '2024-01-01');{x: date('2024-03-15T10:30:00+02:00')};true +some([x], # > '2024-01-01');{x: date('2024-03-15 10:30')};true +some([x], # > '2024-01-01');{x: '2024-03-15'};!error +some([x], # > '2024-01-01');{x: null};!error +count([x, x], string(#) == '2024-03-15');{x: date('2024-03-15')};2 +count([x, x], string(#) == '2024-03-15');{x: date('2024-03-15T10:30:00+02:00')};0 +count([x, x], string(#) == '2024-03-15');{x: date('2024-03-15 10:30')};0 +count([x, x], string(#) == '2024-03-15');{x: '2024-03-15'};2 +count([x, x], string(#) == '2024-03-15');{x: null};0 diff --git a/core/expression/tests/spec/unary/00-harness.csv b/core/expression/tests/spec/unary/00-harness.csv new file mode 100644 index 00000000..04dc1e1b --- /dev/null +++ b/core/expression/tests/spec/unary/00-harness.csv @@ -0,0 +1,4 @@ +expression (string);input (json 5);output (json 5);note +# Harness self-checks +> 5;{$: 6};true +'a', 'b';{$: 'b'};true diff --git a/core/expression/tests/spec/unary/01-literals.csv b/core/expression/tests/spec/unary/01-literals.csv new file mode 100644 index 00000000..18fc43ce --- /dev/null +++ b/core/expression/tests/spec/unary/01-literals.csv @@ -0,0 +1,192 @@ +expression (string);input (json 5);output (json 5);note +# Bare number literal: equality with $ +5;{$: 5};true +5;{$: 5.0};true +5;{$: 5.00000};true +5;{$: 6};false +5;{$: -5};false +5;{$: '5'};false +5;{$: null};false +5;{};false +5;;false +5;{$: true};false +5;{$: [5]};false +5;{$: {a: 5}};false +0;{$: 0};true +0;{$: -0};true +0;{$: 0.0};true +0;{$: false};false +0;{$: null};false +0;{$: ''};false +1.5;{$: 1.5};true +1.5;{$: 1.50};true +1.5;{$: 1.49999999999999999999};false +1.5;{$: 1};false +1.5;{$: '1.5'};false +-3;{$: -3};true +-3;{$: 3};false +-3;{$: -3.0};true +-3;{$: '-3'};false +-3;{$: null};false +1e3;{$: 1000};true +1e3;{$: 1000.0};true +1e3;{$: 100};false +1e3;{$: '1e3'};false +1_000;{$: 1000};true +1_000;{$: 1};false +1_000;{$: '1_000'};false +1_000;{};false +0.1;{$: 0.1};true +0.1;{$: 0.1000000000000000000000000001};false +0.1;{$: 0.1000};true +0.1;{$: 0.2};false +# Bare string literal: case-sensitive equality with $ +'gold';{$: 'gold'};true +'gold';{$: 'Gold'};false +'gold';{$: 'GOLD'};false +'gold';{$: 'gold '};false +'gold';{$: ' gold'};false +'gold';{$: null};false +'gold';{};false +'gold';{$: ['gold']};false +'gold';{$: {gold: true}};false +"""gold""";{$: 'gold'};true +"""gold""";{$: 'silver'};false +"""gold""";{$: null};false +"""gold""";{$: 1};false +'';{$: ''};true +'';{$: ' '};false +'';{$: null};false +'';{};false +'';{$: 0};false +'';{$: false};false +'5';{$: '5'};true +'5';{$: 5};false +'5';{$: 5.0};false +'5';{$: '5.0'};false +'5';{$: null};false +'true';{$: 'true'};true +'true';{$: true};false +'true';{$: 'True'};false +'true';{$: null};false +'null';{$: 'null'};true +'null';{$: null};false +'null';{};false +'null';{$: ''};false +'Straße';{$: 'Straße'};true +'Straße';{$: 'STRASSE'};false +'Straße';{$: 'strasse'};false +'Straße';{$: null};false +# Bare boolean literal: equality with $, no truthiness +true;{$: true};true +true;{$: false};false +true;{$: 1};false +true;{$: 'true'};false +true;{$: null};false +true;{};false +true;{$: [true]};false +false;{$: false};true +false;{$: true};false +false;{$: 0};false +false;{$: ''};false +false;{$: null};false +false;{};false +false;{$: 'false'};false +# Bare null literal: equality with $, missing $ reads as null +null;{$: null};true +null;{};true +null;;true +null;{x: 1};true +null;{$: 0};false +null;{$: ''};false +null;{$: false};false +null;{$: 'null'};false +null;{$: []};false +null;{$: {}};false +# Negated and signed literals +-5;{$: -5};true +-5;{$: 5};false +-5;{$: '-5'};false +-5;{$: null};false ++5;{$: 5};true ++5;{$: -5};false ++5;{$: '+5'};false ++5;{$: null};false +-0.5;{$: -0.5};true +-0.5;{$: 0.5};false +-0.5;{$: -0.50};true +-0.5;{$: null};false +# Literal arithmetic is folded, then compared with $ +2 + 3;{$: 5};true +2 + 3;{$: 23};false +2 + 3;{$: '5'};false +2 + 3;{$: null};false +0.1 + 0.2;{$: 0.3};true +0.1 + 0.2;{$: 0.30000000000000004};false +0.1 + 0.2;{$: 0.30};true +0.1 + 0.2;{$: null};false +10 / 4;{$: 2.5};true +10 / 4;{$: 2};false +10 / 4;{$: 3};false +10 / 4;{$: '2.5'};false +2 ^ 3;{$: 8};true +2 ^ 3;{$: 6};false +2 ^ 3;{$: 9};false +2 ^ 3;{$: null};false +7 % 3;{$: 1};true +7 % 3;{$: 2};false +7 % 3;{$: 1.0};true +7 % 3;{$: true};false +'a' + 'b';{$: 'ab'};true +'a' + 'b';{$: 'a'};false +'a' + 'b';{$: 'AB'};false +'a' + 'b';{$: null};false +(2 + 3) * 2;{$: 10};true +(2 + 3) * 2;{$: 8};false +(2 + 3) * 2;{$: '10'};false +(2 + 3) * 2;{};false +# Template strings are compared with $ +`gold`;{$: 'gold'};true +`gold`;{$: 'GOLD'};false +`gold`;{$: null};false +`gold`;{};false +`tier-${1 + 1}`;{$: 'tier-2'};true +`tier-${1 + 1}`;{$: 'tier-1 + 1'};false +`tier-${1 + 1}`;{$: 'tier-'};false +`tier-${1 + 1}`;{$: null};false +`${x}-${y}`;{$: 'a-1', x: 'a', y: 1};true +`${x}-${y}`;{$: 'a-2', x: 'a', y: 1};false +`${x}-${y}`;{$: 'a-1', x: 'b', y: 1};false +`${x}-${y}`;{$: null, x: 'a', y: 1};false +# A bare identifier compares $ with that field +limit;{$: 3, limit: 3};true +limit;{$: 3, limit: 3.0};true +limit;{$: 3, limit: 4};false +limit;{$: 3, limit: '3'};false +limit;{$: 3};false +limit;{$: null};true +limit;{$: null, limit: null};true +limit;{};true +flag;{$: true, flag: true};true +flag;{$: 1, flag: true};false +flag;{$: false, flag: true};false +flag;{$: false};false +tier;{$: 'gold', tier: 'gold'};true +tier;{$: 'gold', tier: 'Gold'};false +tier;{$: 'gold'};false +tier;{$: 'gold', tier: ['gold']};false +user.tier;{$: 'gold', user: {tier: 'gold'}};true +user.tier;{$: 'gold', user: {tier: 'silver'}};false +user.tier;{$: 'gold', user: null};false +user.tier;{$: null, user: {}};true +user.tier;{$: null};true +user.tier;{$: 'gold', user: 5};false +# $ alone compares $ with itself +$;{$: 1};true +$;{$: 'a'};true +$;{$: true};true +$;{$: false};true +$;{$: null};true +$;{};true +$;{$: [1]};true;bug: $ == $ is false for arrays, == on arrays is always false +$;{$: {a: 1}};true;bug: $ == $ is false for objects, == on objects is always false diff --git a/core/expression/tests/spec/unary/02-comparisons.csv b/core/expression/tests/spec/unary/02-comparisons.csv new file mode 100644 index 00000000..dbc0312a --- /dev/null +++ b/core/expression/tests/spec/unary/02-comparisons.csv @@ -0,0 +1,197 @@ +expression (string);input (json 5);output (json 5);note +# Comparison shorthand: `op x` means `$ op x` +> 5;{$: 6};true +> 5;{$: 5};false +> 5;{$: 5.0000000001};true +> 5;{$: 4};false +> 5;{$: -10};false +> 5;{$: '6'};!error +> 5;{$: null};!error +> 5;{};!error +> 5;;!error +> 5;{$: true};!error +> 5;{$: [6]};!error +>= 5;{$: 5};true +>= 5;{$: 5.00};true +>= 5;{$: 4.99};false +>= 5;{$: 100};true +>= 5;{$: null};!error +>= 5;{$: '5'};!error +< 5;{$: 4};true +< 5;{$: 5};false +< 5;{$: -5};true +< 5;{$: 4.9999999999};true +< 5;{$: null};!error +< 5;{$: 'a'};!error +<= 5;{$: 5};true +<= 5;{$: 5.1};false +<= 5;{$: -100};true +<= 5;{$: 0};true +<= 5;{};!error +<= 5;{$: false};!error +> -5;{$: -4};true +> -5;{$: -5};false +> -5;{$: -6};false +> -5;{$: 0};true +> - 5;{$: -4};true +> - 5;{$: -6};false +> 0.5;{$: 0.51};true +> 0.5;{$: 0.5};false +> 0.5;{$: 0.49};false +> 0.5;{$: 1};true +>5;{$: 6};true +>5;{$: 5};false +>5;{$: 4};false +>5;{$: null};!error +# Equality shorthand agrees with the bare literal +== 5;{$: 5};true +== 5;{$: 5.0};true +== 5;{$: 6};false +== 5;{$: '5'};false +== 5;{$: null};false +== 5;{};false +== 5;{$: true};false +== 'gold';{$: 'gold'};true +== 'gold';{$: 'Gold'};false +== 'gold';{$: null};false +== 'gold';{$: 1};false +== true;{$: true};true +== true;{$: false};false +== true;{$: 1};false +== true;{$: 'true'};false +== true;{$: null};false +== null;{$: null};true +== null;{};true +== null;{$: 0};false +== null;{$: ''};false +== null;{$: false};false +# Inequality shorthand +!= 3;{$: 3};false +!= 3;{$: 3.0};false +!= 3;{$: 4};true +!= 3;{$: '3'};true +!= 3;{$: null};true +!= 3;{};true +!= 3;{$: true};true +!= 'gold';{$: 'gold'};false +!= 'gold';{$: 'silver'};true +!= 'gold';{$: 'GOLD'};true +!= 'gold';{$: null};true +!= 'gold';{};true +!= null;{$: null};false +!= null;{};false +!= null;{$: 0};true +!= null;{$: ''};true +!= null;{$: false};true +!= null;{$: []};true +# Strings have no ordering (consistent with standard mode) +< 'b';{$: 'a'};!error;question: strings have no ordering; is lexicographic comparison intended? +< 'b';{$: 'c'};!error;question: strings have no ordering; is lexicographic comparison intended? +< 'b';{$: 1};!error +< 'b';{$: null};!error +>= 'a';{$: 'a'};!error;question: strings have no ordering even when equal +>= 'a';{$: 'b'};!error;question: strings have no ordering; is lexicographic comparison intended? +>= 'a';{$: null};!error +>= 'a';{};!error +# Comparison against other input fields +> limit;{$: 5, limit: 3};true +> limit;{$: 3, limit: 3};false +> limit;{$: 2, limit: 3};false +> limit;{$: 5};!error +> limit;{$: 5, limit: null};!error +> limit;{$: 5, limit: '3'};!error +> limit;{$: null, limit: 3};!error +<= limit * 2;{$: 6, limit: 3};true +<= limit * 2;{$: 7, limit: 3};false +<= limit * 2;{$: -1, limit: 3};true +<= limit * 2;{$: 6};!error +<= limit * 2;{$: 6, limit: 3.5};true +== other;{$: 'a', other: 'a'};true +== other;{$: 'a', other: 'b'};false +== other;{$: 'a'};false +== other;{$: null};true +== other;{};true +== other;{$: 1, other: 1.0};true +!= other;{$: 'a', other: 'a'};false +!= other;{$: 'a', other: 'b'};true +!= other;{$: 'a'};true +!= other;{};false +> a.b;{$: 5, a: {b: 4}};true +> a.b;{$: 4, a: {b: 4}};false +> a.b;{$: 5, a: {}};!error +> a.b;{$: 5, a: null};!error +> a.b;{$: 5};!error +# Right-hand side is a full expression +>= 5 + 2;{$: 7};true +>= 5 + 2;{$: 6};false +>= 5 + 2;{$: 8};true +>= 5 + 2;{$: null};!error +< 5 * 3;{$: 15};false +< 5 * 3;{$: 14};true +< 5 * 3;{$: 16};false +< 5 * 3;{$: '14'};!error +!= 10 - 3;{$: 7};false +!= 10 - 3;{$: 3};true +!= 10 - 3;{$: 10};true +!= 10 - 3;{$: null};true +> max([1, 5, 3]);{$: 6};true +> max([1, 5, 3]);{$: 5};false +> max([1, 5, 3]);{$: 3};false +> max([1, 5, 3]);{$: null};!error +== upper('gold');{$: 'GOLD'};true +== upper('gold');{$: 'gold'};false +== upper('gold');{$: null};false +== upper('gold');{$: 1};false +>= 5 ?? 1;{$: 5};true +>= 5 ?? 1;{$: 1};false +>= 5 ?? 1;{$: null};!error +>= 5 ?? 1;{};!error +> (x ?? 0);{$: 1};true +> (x ?? 0);{$: 0};false +> (x ?? 0);{$: 1, x: 2};false +> (x ?? 0);{$: 3, x: 2};true +== -$;{$: 0};true +== -$;{$: 1};false +== -$;{$: -1};false +== -$;{$: null};!error +# `in` / `not in` shorthand +in [1, 2, 3];{$: 2};true +in [1, 2, 3];{$: 4};false +in [1, 2, 3];{$: 2.0};true +in [1, 2, 3];{$: '2'};false +in [1, 2, 3];{$: null};false +in [1, 2, 3];{};false +in [1, 2, 3];{$: true};false +not in [1, 2, 3];{$: 2};false +not in [1, 2, 3];{$: 4};true +not in [1, 2, 3];{$: '2'};true +not in [1, 2, 3];{$: null};true +not in [1, 2, 3];{};true +in ['a', 'b'];{$: 'a'};true +in ['a', 'b'];{$: 'A'};false +in ['a', 'b'];{$: 'c'};false +in ['a', 'b'];{$: null};false +in ['a', 'b'];{$: 1};false +in [1..5];{$: 3};true +in [1..5];{$: 5};true +in [1..5];{$: 6};false +in [1..5];{$: null};!error +in [1..5];{$: '3'};!error +not in [1..5];{$: 3};false +not in [1..5];{$: 0};true +not in [1..5];{$: 5.5};true +not in [1..5];{$: null};!error +in allowed;{$: 'a', allowed: ['a', 'b']};true +in allowed;{$: 'c', allowed: ['a', 'b']};false +in allowed;{$: 'a', allowed: []};false +in allowed;{$: 'a'};!error +in allowed;{$: 'a', allowed: 'abc'};!error +in {a: 1, b: 2};{$: 'a'};true +in {a: 1, b: 2};{$: 'c'};false +in {a: 1, b: 2};{$: 'A'};false +in {a: 1, b: 2};{$: 1};!error +in {a: 1, b: 2};{$: null};!error +in 'abc';{$: 'a'};!error +in 'abc';{$: 'x'};!error +in 'abc';{$: null};!error +in 'abc';{$: 1};!error diff --git a/core/expression/tests/spec/unary/03-lists.csv b/core/expression/tests/spec/unary/03-lists.csv new file mode 100644 index 00000000..0b402662 --- /dev/null +++ b/core/expression/tests/spec/unary/03-lists.csv @@ -0,0 +1,134 @@ +expression (string);input (json 5);output (json 5);note +# Comma list: $ matches any entry (each entry is its own unary test) +'a', 'b', 'c';{$: 'a'};true +'a', 'b', 'c';{$: 'b'};true +'a', 'b', 'c';{$: 'c'};true +'a', 'b', 'c';{$: 'd'};false +'a', 'b', 'c';{$: 'A'};false +'a', 'b', 'c';{$: 'a, b'};false +'a', 'b', 'c';{$: null};false +'a', 'b', 'c';{};false +'a', 'b', 'c';{$: ['a']};false +'a', 'b', 'c';{$: 1};false +'US','GB';{$: 'US'};true +'US','GB';{$: 'GB'};true +'US','GB';{$: 'us'};false +'US','GB';{$: 'US,GB'};false +'US','GB';{$: null};false +1, 2, 3;{$: 1};true +1, 2, 3;{$: 3.0};true +1, 2, 3;{$: 4};false +1, 2, 3;{$: 0};false +1, 2, 3;{$: '1'};false +1, 2, 3;{$: null};false +1, 2, 3;{$: true};false +1, 2, 3;{};false +true, false;{$: true};true +true, false;{$: false};true +true, false;{$: null};false +true, false;{$: 0};false +true, false;{$: 'true'};false +'x';{$: 'x'};true +'x';{$: 'y'};false +# Mixed types in a comma list: each entry uses its own type's equality +1, 'a', true, null;{$: 1};true +1, 'a', true, null;{$: 'a'};true +1, 'a', true, null;{$: true};true +1, 'a', true, null;{$: null};true +1, 'a', true, null;{};true +1, 'a', true, null;{$: '1'};false +1, 'a', true, null;{$: false};false +1, 'a', true, null;{$: 2};false +# Comma list with repeated entries +'a', 'a';{$: 'a'};true +'a', 'a';{$: 'b'};false +'a', 'a';{$: null};false +'a', 'a';{$: ''};false +# Comma list mixing shorthands +> 10, < -5;{$: 15};true +> 10, < -5;{$: -6};true +> 10, < -5;{$: 0};false +> 10, < -5;{$: 10};false +> 10, < -5;{$: -5};false +> 10, < -5;{$: null};!error +0, > 100;{$: 0};true +0, > 100;{$: 101};true +0, > 100;{$: 50};false +0, > 100;{$: null};!error +'a', > 5;{$: 'a'};true +'a', > 5;{$: 6};true +'a', > 5;{$: 5};false +'a', > 5;{$: 'b'};!error +> 5, 'a';{$: 6};true +> 5, 'a';{$: 'a'};!error;question: a list entry errors on a type mismatch even when a later entry would match; order of entries changes the outcome +> 5, 'a';{$: 3};false +[1..3], 7, > 10;{$: 2};true +[1..3], 7, > 10;{$: 7};true +[1..3], 7, > 10;{$: 11};true +[1..3], 7, > 10;{$: 5};false +[1..3], 7, > 10;{$: 3.5};false +[1..3], 7, > 10;{$: null};!error +null, > 0;{$: null};true +null, > 0;{$: 1};true +null, > 0;{$: 0};false +null, > 0;{$: -1};false +# `or` between entries is the same as comma +'a' or 'b';{$: 'a'};true +'a' or 'b';{$: 'b'};true +'a' or 'b';{$: 'c'};false +'a' or 'b';{$: null};false +'a' and 'b';{$: 'a'};false +'a' and 'b';{$: 'b'};false +'a' and 'b';{$: 'ab'};false +'a' and 'b';{$: null};false +# Array literal: $ in array +[1, 2];{$: 1};true +[1, 2];{$: 2.0};true +[1, 2];{$: 3};false +[1, 2];{$: '1'};false +[1, 2];{$: null};false +[1, 2];{};false +[1, 2];{$: true};false +[1, 2];{$: [1, 2]};!error;question: an array $ against an array cell errors instead of comparing or testing membership +['gold', 'silver'];{$: 'gold'};true +['gold', 'silver'];{$: 'bronze'};false +['gold', 'silver'];{$: 'Gold'};false +['gold', 'silver'];{$: null};false +['gold', 'silver'];{$: 1};false +[1, 'a'];{$: 1};true +[1, 'a'];{$: 'a'};true +[1, 'a'];{$: '1'};false +[1, 'a'];{$: null};false +[true];{$: true};true +[true];{$: false};false +[true];{$: 1};false +[true];{$: null};false +[null];{$: null};true +[null];{};true +[null];{$: 0};false +[null];{$: 'null'};false +[];{$: 1};false +[];{$: 'a'};false +[];{$: null};false +[];{$: true};false +# Nested arrays: membership does not look inside nested arrays +[[1], 2];{$: 2};true +[[1], 2];{$: 1};false +[[1], 2];{$: null};false +[[1], 2];{$: 'a'};false +[[1]];{$: [1]};!error;question: an array $ against a nested-array cell errors instead of deep membership +[[1]];{$: 1};false +# Array literal next to other entries +[1, 2], 5;{$: 1};true +[1, 2], 5;{$: 5};true +[1, 2], 5;{$: 3};false +[1, 2], 5;{$: null};false +# Malformed lists are parse errors +'a',;{$: 'a'};!error +'a',;{$: 'b'};!error +'a',,'b';{$: 'a'};!error +'a',,'b';{$: 'b'};!error +, 'a';{$: 'a'};!error +, 'a';{$: null};!error +'a' 'b';{$: 'a'};!error +'a' 'b';{$: 'b'};!error diff --git a/core/expression/tests/spec/unary/04-intervals.csv b/core/expression/tests/spec/unary/04-intervals.csv new file mode 100644 index 00000000..a57d2063 --- /dev/null +++ b/core/expression/tests/spec/unary/04-intervals.csv @@ -0,0 +1,155 @@ +expression (string);input (json 5);output (json 5);note +# Closed interval [a..b] +[1..5];{$: 1};true +[1..5];{$: 3};true +[1..5];{$: 5};true +[1..5];{$: 0.999};false +[1..5];{$: 5.001};false +[1..5];{$: 1.0};true +[1..5];{$: -3};false +[1..5];{$: '3'};!error +[1..5];{$: null};!error +[1..5];{};!error +[1..5];{$: true};!error +[1..5];{$: [3]};!error +# Open interval (a..b) +(1..5);{$: 1};false +(1..5);{$: 1.0000001};true +(1..5);{$: 3};true +(1..5);{$: 4.9999};true +(1..5);{$: 5};false +(1..5);{$: 0};false +(1..5);{$: null};!error +(1..5);{$: 'a'};!error +# Half-open intervals +[1..5);{$: 1};true +[1..5);{$: 5};false +[1..5);{$: 4.99};true +[1..5);{$: 0};false +[1..5);{$: null};!error +(1..5];{$: 1};false +(1..5];{$: 5};true +(1..5];{$: 1.01};true +(1..5];{$: 6};false +(1..5];{$: null};!error +# Negative and decimal bounds +[-10..0];{$: -10};true +[-10..0];{$: 0};true +[-10..0];{$: -5};true +[-10..0];{$: 0.01};false +[-10..0];{$: -10.01};false +(-10..0];{$: -10};false +(-10..0];{$: -9.99};true +(-10..0];{$: 0};true +[-10..0);{$: -10};true +[-10..0);{$: 0};false +[-10..0);{$: -0.0001};true +[-15..-5];{$: -4.99};false +[-15..-5];{$: -5};true +[-15..-5];{$: -15};true +[-15..-5];{$: -16};false +[0.1..0.3];{$: 0.1};true +[0.1..0.3];{$: 0.2};true +[0.1..0.3];{$: 0.3};true +[0.1..0.3];{$: 0.30000000000000001};false +[0.1..0.3];{$: 0.09999};false +[1.5..2.5];{$: 2};true +[1.5..2.5];{$: 1.5};true +[1.5..2.5];{$: 1.49};false +[1.5..2.5];{$: 2.51};false +(0..1);{$: 0.5};true +(0..1);{$: 0.0000000000000000000000000001};true +(0..1);{$: 0};false +(0..1);{$: 1};false +# Degenerate intervals +[0..0];{$: 0};true +[0..0];{$: 0.0};true +[0..0];{$: 5};false +[0..0];{$: -0.1};false +(0..0);{$: 0};false +(0..0);{$: 1};false +(0..0);{$: -1};false +(0..0);{$: null};!error +[0..0);{$: 0};false +[0..0);{$: 1};false +[0..0);{$: -1};false +[0..0);{$: 0.5};false +# Reversed bounds match nothing +[5..1];{$: 3};false +[5..1];{$: 1};false +[5..1];{$: 5};false +[5..1];{$: 6};false +[5..1];{$: 0};false +# Reversed brackets denote the complement (outside the interval) +]1..5[;{$: 0};true;question: reversed brackets are undocumented; they act as the complement of (1..5), so `]1..5[` includes 1 and 5 +]1..5[;{$: 1};true;question: reversed brackets are undocumented; they act as the complement of (1..5), so `]1..5[` includes 1 and 5 +]1..5[;{$: 3};false +]1..5[;{$: 5};true;question: reversed brackets are undocumented; they act as the complement of (1..5), so `]1..5[` includes 1 and 5 +]1..5[;{$: 6};true +]1..5[;{$: null};!error +)1..5(;{$: 0};true +)1..5(;{$: 1};false +)1..5(;{$: 3};false +)1..5(;{$: 5};false +)1..5(;{$: 6};true +]1..5];{$: 1};true;question: `]1..5]` is undocumented; it currently reduces to $ <= 5 +]1..5];{$: 3};true;question: `]1..5]` is undocumented; it currently reduces to $ <= 5 +]1..5];{$: 0};true;question: `]1..5]` is undocumented; it currently reduces to $ <= 5 +]1..5];{$: 9};false;question: `]1..5]` is undocumented; it currently reduces to $ <= 5 +[1..5[;{$: 5};true;question: `[1..5[` is undocumented; it currently reduces to $ >= 5 +[1..5[;{$: 3};false;question: `[1..5[` is undocumented; it currently reduces to $ >= 5 +[1..5[;{$: 0};false;question: `[1..5[` is undocumented; it currently reduces to $ >= 5 +[1..5[;{$: 9};true;question: `[1..5[` is undocumented; it currently reduces to $ >= 5 +# Bounds from other fields and expressions +[lo..hi];{$: 3, lo: 1, hi: 5};true +[lo..hi];{$: 1, lo: 1, hi: 5};true +[lo..hi];{$: 6, lo: 1, hi: 5};false +[lo..hi];{$: 3, lo: 1};!error +[lo..hi];{$: 3, lo: '1', hi: 5};!error +[lo..hi];{$: 3, lo: null, hi: 5};!error +[lo..hi];{$: null, lo: 1, hi: 5};!error +[1 + 1..2 * 3];{$: 2};true +[1 + 1..2 * 3];{$: 6};true +[1 + 1..2 * 3];{$: 1};false +[1 + 1..2 * 3];{$: 7};false +[1..'a'];{$: 1};!error +[1..'a'];{$: 'a'};!error +[1..'a'];{$: null};!error +[1..'a'];{$: 0};!error +['a'..'z'];{$: 'm'};!error +['a'..'z'];{$: 'A'};!error +['a'..'z'];{$: 1};!error +['a'..'z'];{$: null};!error +# Interval combined with other shorthands +[1..10] and != 5;{$: 5};false +[1..10] and != 5;{$: 4};true +[1..10] and != 5;{$: 11};false +[1..10] and != 5;{$: 1};true +[1..10] and != 5;{$: null};!error +[-10..0] and > -5;{$: -5};false +[-10..0] and > -5;{$: -4.99};true +[-10..0] and > -5;{$: -7};false +[-10..0] and > -5;{$: 0};true +(-10..0) or > 0;{$: 5};true +(-10..0) or > 0;{$: 0};false +(-10..0) or > 0;{$: -10};false +(-10..0) or > 0;{$: -1};true +[1..3], [7..9];{$: 2};true +[1..3], [7..9];{$: 8};true +[1..3], [7..9];{$: 5};false +[1..3], [7..9];{$: 3.5};false +[1..3], [7..9];{$: 9};true +[1..3], [7..9];{$: null};!error +# Explicit `$ in` with an interval equals the shorthand +$ in [1..5];{$: 3};true +$ in [1..5];{$: 5};true +$ in [1..5];{$: 0};false +$ in [1..5];{$: null};!error +$ in (1..5);{$: 1};false +$ in (1..5);{$: 2};true +$ in (1..5);{$: 5};false +$ in (1..5);{$: 'a'};!error +$ not in [1..5];{$: 3};false +$ not in [1..5];{$: 6};true +$ not in [1..5];{$: 1};false +$ not in [1..5];{$: null};!error diff --git a/core/expression/tests/spec/unary/05-logic.csv b/core/expression/tests/spec/unary/05-logic.csv new file mode 100644 index 00000000..43e555aa --- /dev/null +++ b/core/expression/tests/spec/unary/05-logic.csv @@ -0,0 +1,167 @@ +expression (string);input (json 5);output (json 5);note +# `and` joins shorthands, all must hold +> 5 and < 10;{$: 7};true +> 5 and < 10;{$: 5};false +> 5 and < 10;{$: 10};false +> 5 and < 10;{$: 5.5};true +> 5 and < 10;{$: 11};false +> 5 and < 10;{$: null};!error +> 5 and < 10;{$: '7'};!error +>= 5 and <= 10;{$: 5};true +>= 5 and <= 10;{$: 10};true +>= 5 and <= 10;{$: 4.9};false +>= 5 and <= 10;{$: 10.1};false +>= 5 and <= 10;{};!error +> 5 and < 10 and != 7;{$: 7};false +> 5 and < 10 and != 7;{$: 6};true +> 5 and < 10 and != 7;{$: 9.5};true +> 5 and < 10 and != 7;{$: 10};false +> 5 and < 10 and != 7;{$: 3};false +# `and` short-circuits: a failing left side skips a right side that would error +> 5 and < 'b';{$: 3};false +> 5 and < 'b';{$: 6};!error +!= null and > 5;{$: null};false +!= null and > 5;{};false +!= null and > 5;{$: 6};true +!= null and > 5;{$: 5};false +!= null and > 5;{$: 'a'};!error +# `or` joins shorthands, any may hold +>= 10 or < 5;{$: 10};true +>= 10 or < 5;{$: 4};true +>= 10 or < 5;{$: 5};false +>= 10 or < 5;{$: 9.99};false +>= 10 or < 5;{$: null};!error +== null or > 5;{$: null};true +== null or > 5;{};true +== null or > 5;{$: 6};true +== null or > 5;{$: 5};false +== null or > 5;{$: 'a'};!error +'a' or > 5;{$: 'a'};true +'a' or > 5;{$: 6};true +'a' or > 5;{$: 1};false +'a' or > 5;{$: 'b'};!error +# Mixed `and` / `or` follow standard precedence (`and` binds tighter) +> 5 and < 10 or == 20;{$: 7};true +> 5 and < 10 or == 20;{$: 20};true +> 5 and < 10 or == 20;{$: 15};false +> 5 and < 10 or == 20;{$: 1};false +== 20 or > 5 and < 10;{$: 7};true +== 20 or > 5 and < 10;{$: 20};true;bug: unary joins are folded left to right, giving (== 20 or > 5) and < 10; standard `$ == 20 or $ > 5 and $ < 10` is true +== 20 or > 5 and < 10;{$: 15};false +== 20 or > 5 and < 10;{$: 1};false +== 1 or > 5 and < 0;{$: 1};true;bug: unary joins are folded left to right, giving (== 1 or > 5) and < 0; standard `$ == 1 or $ > 5 and $ < 0` is true +== 1 or > 5 and < 0;{$: 6};false +== 1 or > 5 and < 0;{$: 0};false +== 1 or > 5 and < 0;{$: -1};false +'a', 'b' and 'c';{$: 'a'};true;bug: unary joins are folded left to right, giving ('a', 'b') and 'c'; standard `$ == 'a' or $ == 'b' and $ == 'c'` is true +'a', 'b' and 'c';{$: 'b'};false +'a', 'b' and 'c';{$: 'c'};false +'a', 'b' and 'c';{$: null};false +# Parenthesised groups of full expressions +($ > 5 and $ < 10);{$: 7};true;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +($ > 5 and $ < 10);{$: 5};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +($ > 5 and $ < 10);{$: 10};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +($ > 5 and $ < 10);{$: null};!error +($ == 1 or $ == 2) and $ != 2;{$: 1};true;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +($ == 1 or $ == 2) and $ != 2;{$: 2};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +($ == 1 or $ == 2) and $ != 2;{$: 3};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +($ == 1 or $ == 2) and $ != 2;{$: null};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +== 1 or ($ > 5 and $ < 0);{$: 1};true;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +== 1 or ($ > 5 and $ < 0);{$: 6};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +== 1 or ($ > 5 and $ < 0);{$: 2};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +== 1 or ($ > 5 and $ < 0);{$: -1};false;bug: parenthesised `and`/`or` in unary mode fails to parse (Incomplete parser output); the same text is valid in standard mode +# Shorthands cannot be parenthesised +(> 5);{$: 7};!error +(> 5);{$: 3};!error +(> 5);{$: null};!error +(> 5);{};!error +> 5 and (< 10);{$: 7};!error +> 5 and (< 10);{$: 11};!error +> 5 and (< 10);{$: 1};!error +> 5 and (< 10);{$: null};!error +# Mixing explicit $ with shorthands +$ > 5 and < 10;{$: 7};true +$ > 5 and < 10;{$: 5};false +$ > 5 and < 10;{$: 10};false +$ > 5 and < 10;{$: null};!error +> 5 and $ < 10;{$: 7};true +> 5 and $ < 10;{$: 12};false +> 5 and $ < 10;{$: 2};false +> 5 and $ < 10;{$: 'a'};!error +$ > 5 and $ < 10;{$: 7};true +$ > 5 and $ < 10;{$: 5};false +$ > 5 and $ < 10;{$: 10};false +$ > 5 and $ < 10;{$: null};!error +$ == 'a' or $ == 'b';{$: 'a'};true +$ == 'a' or $ == 'b';{$: 'b'};true +$ == 'a' or $ == 'b';{$: 'c'};false +$ == 'a' or $ == 'b';{$: null};false +contains($, 'a') and len($) > 2;{$: 'abc'};true +contains($, 'a') and len($) > 2;{$: 'ab'};false +contains($, 'a') and len($) > 2;{$: 'xyz'};false +contains($, 'a') and len($) > 2;{$: null};!error +# `not` / `!` negate a boolean expression +not ($ > 5);{$: 3};true +not ($ > 5);{$: 5};true +not ($ > 5);{$: 6};false +not ($ > 5);{$: null};!error +!($ == 'a');{$: 'b'};true +!($ == 'a');{$: 'a'};false +!($ == 'a');{$: null};true +!($ == 'a');{};true +not ($ in ['a', 'b']);{$: 'c'};true +not ($ in ['a', 'b']);{$: 'a'};false +not ($ in ['a', 'b']);{$: null};true +not ($ in ['a', 'b']);{$: 1};true +not contains($, 'x');{$: 'abc'};true +not contains($, 'x');{$: 'axc'};false +not contains($, 'x');{$: ''};true +not contains($, 'x');{$: null};!error +# `not` applied to a bare literal negates the literal, then compares with $ +not true;{$: false};true;question: `not true` is `$ == false`, not "not equal to true"; a FEEL-style reading would match $ != true +not true;{$: true};false +not true;{$: null};false;question: `not true` is `$ == false`, not "not equal to true"; a FEEL-style reading would match $ != true +not true;{$: 'x'};false;question: `not true` is `$ == false`, not "not equal to true"; a FEEL-style reading would match $ != true +not not true;{$: true};true +not not true;{$: false};false +not not true;{$: null};false +not not true;{$: 1};false +not 5;{$: 5};!error;question: `not 5` errors (not on a number); FEEL-style unary tests read it as "not equal to 5" +not 5;{$: 6};!error;question: `not 5` errors (not on a number); FEEL-style unary tests read it as "not equal to 5" +not 5;{$: null};!error +not 5;{};!error +not 'a';{$: 'a'};!error +not 'a';{$: 'b'};!error +not 'a';{$: false};!error +not 'a';{$: null};!error +not null;{$: null};!error +not null;{$: true};!error +not null;{$: false};!error +not null;{};!error +# `$` as a bare operand of and/or is compared with itself, not used as a boolean +$ or false;{$: true};true +$ or false;{$: false};true;question: `$ or false` is ($ == $) or ($ == false), so it is true for $ = false; standard `$ or false` is false +$ or false;{$: null};true;question: `$ or false` is ($ == $) or ($ == false), so it is true for $ = null; standard `$ or false` errors or is false +$ or false;{$: 1};true;question: `$ or false` is ($ == $) or ($ == false), so it is true for any non-array $ +$ and true;{$: true};true +$ and true;{$: false};false +$ and true;{$: 1};false +$ and true;{$: null};false +true and true;{$: true};true +true and true;{$: false};false +true and true;{$: 1};false +true and true;{};false +# C-style operators are not part of the language +> 5 && < 10;{$: 7};!error +> 5 && < 10;{$: 1};!error +> 5 || < 0;{$: 7};!error +> 5 || < 0;{$: -1};!error +# Malformed joins are parse errors +> 5 and;{$: 6};!error +> 5 and;{$: 1};!error +and > 5;{$: 6};!error +and > 5;{$: 1};!error +>;{$: 6};!error +>;{$: null};!error +> > 5;{$: 6};!error +> > 5;{$: 1};!error diff --git a/core/expression/tests/spec/unary/06-reference.csv b/core/expression/tests/spec/unary/06-reference.csv new file mode 100644 index 00000000..caba49ff --- /dev/null +++ b/core/expression/tests/spec/unary/06-reference.csv @@ -0,0 +1,266 @@ +expression (string);input (json 5);output (json 5);note +# Explicit comparisons on $ are used as the result +$ > 5;{$: 6};true +$ > 5;{$: 5};false +$ > 5;{$: -1};false +$ > 5;{$: null};!error +$ > 5;{};!error +$ > 5;{$: '6'};!error +$ == 'gold';{$: 'gold'};true +$ == 'gold';{$: 'GOLD'};false +$ == 'gold';{$: null};false +$ == 'gold';{$: 1};false +$ != 'gold';{$: 'gold'};false +$ != 'gold';{$: 'silver'};true +$ != 'gold';{$: null};true +$ != 'gold';{};true +$ == $;{$: 1};true +$ == $;{$: null};true +$ == $;{$: 'a'};true +$ == $;{$: [1]};true;bug: == on arrays is always false, even for a value compared with itself +$ != $;{$: 1};false +$ != $;{$: null};false +$ != $;{$: 'a'};false +$ != $;{$: [1]};false;bug: == on arrays is always false, so != on the same array is true +5 < $;{$: 6};true +5 < $;{$: 5};false +5 < $;{$: 4};false +5 < $;{$: null};!error +# `$ in` explicit membership +$ in ['a', 'b'];{$: 'a'};true +$ in ['a', 'b'];{$: 'c'};false +$ in ['a', 'b'];{$: null};false +$ in ['a', 'b'];{$: 1};false +$ in ['a', 'b'];{};false +$ not in ['a', 'b'];{$: 'a'};false +$ not in ['a', 'b'];{$: 'c'};true +$ not in ['a', 'b'];{$: null};true +$ not in ['a', 'b'];{$: 1};true +'a' in $;{$: ['a', 'b']};true +'a' in $;{$: ['b']};false +'a' in $;{$: []};false +'a' in $;{$: {a: 1}};true +'a' in $;{$: null};!error +'a' in $;{$: 'abc'};!error +# Functions whose result is a boolean are used as the result +contains($, 'x');{$: 'axb'};true +contains($, 'x');{$: 'abc'};false +contains($, 'x');{$: 'X'};false +contains($, 'x');{$: ''};false +contains($, 'x');{$: null};!error +contains($, 'x');{$: 5};!error +contains($, 'x');{$: ['x']};true +contains($, 'x');{$: ['xy']};false +contains($, 2);{$: [1, 2]};true +contains($, 2);{$: [1, 3]};false +contains($, 2);{$: []};false +contains($, 2);{$: [2.0]};true +startsWith($, 'G');{$: 'Gold'};true +startsWith($, 'G');{$: 'gold'};false +startsWith($, 'G');{$: 'AG'};false +startsWith($, 'G');{$: ''};false +startsWith($, 'G');{$: 5};!error +startsWith($, 'G');{$: null};!error +endsWith($, '.pdf');{$: 'a.pdf'};true +endsWith($, '.pdf');{$: 'a.PDF'};false +endsWith($, '.pdf');{$: '.pdf'};true +endsWith($, '.pdf');{$: 'pdf'};false +endsWith($, '.pdf');{$: null};!error +matches($, '^[A-Z]{2}[0-9]+$');{$: 'AB123'};true +matches($, '^[A-Z]{2}[0-9]+$');{$: 'ab123'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: 'AB'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: ''};false +matches($, '^[A-Z]{2}[0-9]+$');{$: null};!error +isNumeric($);{$: '12'};true +isNumeric($);{$: '12.5'};true +isNumeric($);{$: 'abc'};false +isNumeric($);{$: 12};true +isNumeric($);{$: null};false +isNumeric($);{$: ''};false +some($, # > 10);{$: [1, 15]};true +some($, # > 10);{$: [1, 2]};false +some($, # > 10);{$: []};false +some($, # > 10);{$: null};!error +some($, # > 10);{$: 15};!error +all($, # > 0);{$: [1, 2]};true +all($, # > 0);{$: [1, -2]};false +all($, # > 0);{$: []};true +all($, # > 0);{$: null};!error +none($, # == 'x');{$: ['a', 'b']};true +none($, # == 'x');{$: ['x']};false +none($, # == 'x');{$: []};true +none($, # == 'x');{$: 'x'};!error +one($, # == 'x');{$: ['x', 'y']};true +one($, # == 'x');{$: ['x', 'x']};false +one($, # == 'x');{$: []};false +one($, # == 'x');{$: null};!error +# Functions returning values are compared with $ +lower('GOLD');{$: 'gold'};true +lower('GOLD');{$: 'GOLD'};false +lower('GOLD');{$: 'Gold'};false +lower('GOLD');{$: null};false +upper('Hello, World!');{$: 'HELLO, WORLD!'};true +upper('Hello, World!');{$: 'Hello, World!'};false +upper('Hello, World!');{$: null};false +upper('Hello, World!');{$: 1};false +abs(-5);{$: 5};true +abs(-5);{$: -5};false +abs(-5);{$: '5'};false +abs(-5);{$: null};false +max([3, 5, 8]);{$: 8};true +max([3, 5, 8]);{$: 3};false +max([3, 5, 8]);{$: 8.0};true +max([3, 5, 8]);{$: null};false +round(3.5);{$: 4};true +round(3.5);{$: 3};false +round(3.5);{$: 3.5};false +round(3.5);{$: '4'};false +len('abc');{$: 3};true +len('abc');{$: 'abc'};false +len('abc');{$: 2};false +len('abc');{$: null};false +number('12.50');{$: 12.5};true +number('12.50');{$: '12.50'};false +number('12.50');{$: 12};false +number('12.50');{$: null};false +string(12);{$: '12'};true +string(12);{$: 12};false +string(12);{$: '12.0'};false +string(12);{$: null};false +bool('true');{$: true};true +bool('true');{$: false};false +bool('true');{$: 'true'};false +bool('true');{$: null};false +# Functions of $ returning non-booleans are compared with $ itself +lower($);{$: 'gold'};true +lower($);{$: 'Gold'};false;question: `lower($)` is `$ == lower($)` (true only for already-lowercase $); a user may expect a type error for a non-boolean test +lower($);{$: ''};true +lower($);{$: 5};!error +lower($);{$: null};!error +len($);{$: 'abc'};false;question: `len($)` is `$ == len($)`; a non-boolean test on $ is silently a self-comparison +len($);{$: ''};false +len($);{$: [1]};false +len($);{$: null};!error +trim($);{$: 'a'};true +trim($);{$: ' a '};false +trim($);{$: ''};true +trim($);{$: null};!error +number($);{$: 5};true +number($);{$: '5'};false +number($);{$: true};false +number($);{$: 'abc'};!error +string($);{$: 'a'};true +string($);{$: 5};false +string($);{$: true};false +string($);{$: null};false +type($);{$: 'string'};true +type($);{$: 'number'};false +type($);{$: 5};false +type($);{$: null};false +# Arithmetic on $ is compared with $ +$ + 1;{$: 1};false;question: `$ + 1` is `$ == $ + 1` (never true for numbers) instead of a type error for a non-boolean test +$ + 1;{$: 0};false +$ + 1;{$: -1};false +$ + 1;{$: null};!error +$ + 1;{$: 'a'};!error +$ * 1;{$: 5};true;question: `$ * 1` is `$ == $ * 1`, true for every number; a non-boolean test on $ is silently a self-comparison +$ * 1;{$: 0};true +$ * 1;{$: 0.5};true +$ * 1;{$: null};!error +$ * 0;{$: 0};true +$ * 0;{$: 5};false +$ * 0;{$: -0};true +$ * 0;{$: 'a'};!error +$ + 'x' == 'ax';{$: 'a'};true +$ + 'x' == 'ax';{$: 'b'};false +$ + 'x' == 'ax';{$: 1};!error +$ + 'x' == 'ax';{$: null};!error +# Functions applied to $ inside comparisons +len($) > 2;{$: 'abc'};true +len($) > 2;{$: 'ab'};false +len($) > 2;{$: [1, 2, 3]};true +len($) > 2;{$: []};false +len($) > 2;{$: null};!error +len($) > 2;{$: 5};!error +lower($) == 'gold';{$: 'GOLD'};true +lower($) == 'gold';{$: 'Gold'};true +lower($) == 'gold';{$: 'silver'};false +lower($) == 'gold';{$: null};!error +lower($) == 'gold';{$: 1};!error +upper($) in ['A', 'B'];{$: 'a'};true +upper($) in ['A', 'B'];{$: 'c'};false +upper($) in ['A', 'B'];{$: 'B'};true +upper($) in ['A', 'B'];{$: null};!error +trim($) == '';{$: ' '};true +trim($) == '';{$: ' a '};false +trim($) == '';{$: ''};true +trim($) == '';{$: null};!error +($ ?? 0) > 5;{$: null};false +($ ?? 0) > 5;{};false +($ ?? 0) > 5;{$: 6};true +($ ?? 0) > 5;{$: 5};false +$ % 2 == 0;{$: 4};true +$ % 2 == 0;{$: 3};false +$ % 2 == 0;{$: 0};true +$ % 2 == 0;{$: 2.5};false +$ % 2 == 0;{$: null};!error +$[0:5] == 'sample';{$: 'sample_string'};true +$[0:5] == 'sample';{$: 'sampl'};!error;question: a slice end past the string errors (same as standard mode) - clamp or error? +$[0:5] == 'sample';{$: 'other_string'};false +$[0:5] == 'sample';{$: null};!error +# $ as an object +$.a > 1;{$: {a: 2}};true +$.a > 1;{$: {a: 1}};false +$.a > 1;{$: {a: null}};!error +$.a > 1;{$: {}};!error +$.a > 1;{$: null};!error +$.a == 1;{$: {a: 1}};true +$.a == 1;{$: {a: 2}};false +$.a == 1;{$: {}};false +$.a == 1;{$: null};false +$.a == 1;{$: 5};false +$.tier in ['gold', 'silver'];{$: {tier: 'gold'}};true +$.tier in ['gold', 'silver'];{$: {tier: 'bronze'}};false +$.tier in ['gold', 'silver'];{$: {}};false +$.tier in ['gold', 'silver'];{$: null};false +$.a;{$: {a: 1}};false +$.a;{$: {a: {a: 1}}};false +$.a;{$: 1};false +$.a;{$: null};true;question: `$.a` is `$ == $.a`; with $ null both sides are null so it matches +{a: 1};{$: {a: 1}};true;bug: == on objects is always false; a literal object cell never matches an equal $ +{a: 1};{$: {a: 2}};false +{a: 1};{$: null};false +{a: 1};{$: 'a'};false +$.a.b == 1;{$: {a: {b: 1}}};true +$.a.b == 1;{$: {a: {b: 2}}};false +$.a.b == 1;{$: {a: null}};false +$.a.b == 1;{$: {}};false +'x' in keys($);{$: {x: 1}};true +'x' in keys($);{$: {y: 1}};false +'x' in keys($);{$: {}};false +'x' in keys($);{$: null};!error +# $ as an array +$[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) +len($) == 0;{$: []};true +len($) == 0;{$: [1]};false +len($) == 0;{$: ''};true +len($) == 0;{$: {}};!error +sum($) > 10;{$: [5, 6]};true +sum($) > 10;{$: [5, 5]};false +sum($) > 10;{$: []};false +sum($) > 10;{$: null};!error +filter([1, 2, 3], # > 1);{$: 2};true +filter([1, 2, 3], # > 1);{$: 1};false +filter([1, 2, 3], # > 1);{$: 3};true +filter([1, 2, 3], # > 1);{$: null};false +map(['a', 'b'], upper(#));{$: 'A'};true +map(['a', 'b'], upper(#));{$: 'a'};false +map(['a', 'b'], upper(#));{$: 'C'};false +map(['a', 'b'], upper(#));{$: null};false diff --git a/core/expression/tests/spec/unary/07-dates-conditionals.csv b/core/expression/tests/spec/unary/07-dates-conditionals.csv new file mode 100644 index 00000000..1ca6e777 --- /dev/null +++ b/core/expression/tests/spec/unary/07-dates-conditionals.csv @@ -0,0 +1,106 @@ +expression (string);input (json 5);output (json 5);note +# Date $: convert with d($) before comparing +d($) > d('2024-01-01');{$: '2024-05-01'};true +d($) > d('2024-01-01');{$: '2024-01-01'};false +d($) > d('2024-01-01');{$: '2023-12-31'};false +d($) > d('2024-01-01');{$: '2024-01-01T00:00:01Z'};true +d($) > d('2024-01-01');{$: 'not a date'};false;question: an invalid date orders before every valid date instead of erroring (same as standard mode) +d($) > d('2024-01-01');{$: null};false;question: d(null) is an invalid date, so ordering against it is false instead of an error +d($) >= d('2024-01-01') and d($) < d('2025-01-01');{$: '2024-01-01'};true +d($) >= d('2024-01-01') and d($) < d('2025-01-01');{$: '2024-12-31T23:59:59Z'};true +d($) >= d('2024-01-01') and d($) < d('2025-01-01');{$: '2025-01-01'};false +d($) >= d('2024-01-01') and d($) < d('2025-01-01');{$: '2023-06-01'};false +d($) == d('2024-05-01');{$: '2024-05-01'};true +d($) == d('2024-05-01');{$: '2024-05-01T00:00:00Z'};true +d($) == d('2024-05-01');{$: '2024-05-02'};false +d($) == d('2024-05-01');{$: '2024-05-01T00:00:01Z'};false +d($).year() == 2024;{$: '2024-05-01'};true +d($).year() == 2024;{$: '2024-12-31T23:59:59Z'};true +d($).year() == 2024;{$: '2023-05-01'};false +d($).year() == 2024;{$: '2025-01-01'};false +d($).year() == 2024;{$: 'garbage'};false +d($).month() in [6, 7, 8];{$: '2024-07-15'};true +d($).month() in [6, 7, 8];{$: '2024-06-01'};true +d($).month() in [6, 7, 8];{$: '2024-09-01'};false +d($).month() in [6, 7, 8];{$: '2024-01-31'};false +d($).isAfter(d('2024-01-01'));{$: '2024-05-01'};true +d($).isAfter(d('2024-01-01'));{$: '2024-01-01'};false +d($).isAfter(d('2024-01-01'));{$: '2020-01-01'};false +d($).isAfter(d('2024-01-01'));{$: '2024-01-02'};true +d($).isBefore(d());{$: '2025-03-20T10:15:29Z'};true +d($).isBefore(d());{$: '2025-03-20T10:15:31Z'};false +d($).isBefore(d());{$: '1999-01-01'};true +d($).isBefore(d());{$: '2030-01-01'};false +d($).isToday();{$: '2025-03-20'};true +d($).isToday();{$: '2025-03-20T23:00:00Z'};true +d($).isToday();{$: '2025-03-21'};false +d($).isToday();{$: '2025-03-19'};false +d($) in [d('2024-01-01')..d('2024-12-31')];{$: '2024-05-01'};true +d($) in [d('2024-01-01')..d('2024-12-31')];{$: '2024-01-01'};true +d($) in [d('2024-01-01')..d('2024-12-31')];{$: '2024-12-31'};true +d($) in [d('2024-01-01')..d('2024-12-31')];{$: '2025-01-01'};false +d($) in [d('2024-01-01')..d('2024-12-31')];{$: '2023-12-31'};false +d($) in (d('2024-01-01')..d('2024-12-31'));{$: '2024-01-01'};false +d($) in (d('2024-01-01')..d('2024-12-31'));{$: '2024-06-01'};true +d($) in (d('2024-01-01')..d('2024-12-31'));{$: '2024-12-31'};false +d($) in (d('2024-01-01')..d('2024-12-31'));{$: '2025-06-01'};false +# A date-string $ is not coerced by shorthands or date literals +> d('2024-01-01');{$: '2024-05-01'};true +> d('2024-01-01');{$: '2023-05-01'};false +> d('2024-01-01');{$: null};!error +> d('2024-01-01');{$: 5};!error +[d('2024-01-01')..d('2024-12-31')];{$: '2024-05-01'};!error;question: a date-string $ is not coerced to a date for date intervals +[d('2024-01-01')..d('2024-12-31')];{$: '2025-05-01'};!error;question: a date-string $ is not coerced to a date for date intervals +[d('2024-01-01')..d('2024-12-31')];{$: null};!error +[d('2024-01-01')..d('2024-12-31')];{$: 20240501};!error;bug: a number $ against a date interval is compared by enum variant order instead of erroring like a string $ +)d('2024-01-01')..d('2024-12-31')(;{$: 20240501};!error;bug: a number $ against a date interval is compared by enum variant order instead of erroring like a string $ +)d('2024-01-01')..d('2024-12-31')(;{$: '2025-05-01'};!error +)d('2024-01-01')..d('2024-12-31')(;{$: null};!error +$ in [d('2024-01-01')..d('2024-12-31')];{$: 0};!error;bug: a number $ against a date interval is compared by enum variant order instead of erroring like a string $ +d('2024-05-01');{$: '2024-05-01'};true +d('2024-05-01');{$: '2024-05-01T00:00:00Z'};true +d('2024-05-01');{$: null};false +d('2024-05-01');{$: 1714521600};false +== d('2024-05-01');{$: '2024-05-01'};true +== d('2024-05-01');{$: '2024-05-02'};false +== d('2024-05-01');{$: null};false +== d('2024-05-01');{};false +d($).year();{$: '2024-05-01'};false +d($).year();{$: '2024'};false +d($).year();{$: 2024};false +d($).year();{$: null};true;question: d(null).year() is null, so `d($).year()` matches a null $ through `$ == null` +d('2024-05-01').format('%Y');{$: '2024'};true +d('2024-05-01').format('%Y');{$: 2024};false +d('2024-05-01').format('%Y');{$: '2025'};false +d('2024-05-01').format('%Y');{$: null};false +d($).isValid();{$: '2024-02-29'};true +d($).isValid();{$: '2023-02-29'};false +d($).isValid();{$: 'garbage'};false +d($).isValid();{$: null};false +d($).isValid();{$: '2024-05-01T10:00:00Z'};true +# Ternaries: branch types decide whether the result is compared with $ +x > 5 ? 'hi' : 'lo';{$: 'hi', x: 7};true +x > 5 ? 'hi' : 'lo';{$: 'lo', x: 7};false +x > 5 ? 'hi' : 'lo';{$: 'lo', x: 3};true +x > 5 ? 'hi' : 'lo';{$: 'hi', x: 3};false +x > 5 ? 'hi' : 'lo';{$: 'hi'};!error +$ > 5 ? 10 : 0;{$: 10};true +$ > 5 ? 10 : 0;{$: 0};true +$ > 5 ? 10 : 0;{$: 6};false +$ > 5 ? 10 : 0;{$: null};!error +x > 5 ? contains($, 'a') : contains($, 'b');{$: 'a', x: 7};true +x > 5 ? contains($, 'a') : contains($, 'b');{$: 'b', x: 7};false +x > 5 ? contains($, 'a') : contains($, 'b');{$: 'b', x: 3};true +x > 5 ? contains($, 'a') : contains($, 'b');{$: 'a', x: 3};false +$ > 5 ? true : false;{$: 6};false;question: bool-literal branches make the ternary `$ == ($ > 5 ? true : false)`; the standard-mode reading is true +$ > 5 ? true : false;{$: 5};false +$ > 5 ? true : false;{$: true};!error +$ > 5 ? true : false;{$: null};!error +x > 5 ? true : false;{$: true, x: 7};true +x > 5 ? true : false;{$: false, x: 7};false +x > 5 ? true : false;{$: false, x: 3};true +x > 5 ? true : false;{$: 1, x: 7};false +x > 5 ? contains($, 'a') : false;{$: 'a', x: 7};false;question: mixed branch kinds (boolean function vs literal) fall back to comparing `$ == result`, so a matching contains() is compared with $ instead of used as the result +x > 5 ? contains($, 'a') : false;{$: 'b', x: 7};false +x > 5 ? contains($, 'a') : false;{$: false, x: 3};true;question: mixed branch kinds (boolean function vs literal) fall back to comparing `$ == result`, so $ = false matches the false branch +x > 5 ? contains($, 'a') : false;{$: 'a', x: 3};false diff --git a/core/expression/tests/spec/unary/10-numeric-bands.csv b/core/expression/tests/spec/unary/10-numeric-bands.csv new file mode 100644 index 00000000..d02dc932 --- /dev/null +++ b/core/expression/tests/spec/unary/10-numeric-bands.csv @@ -0,0 +1,569 @@ +expression (string);input (json 5);output (json 5);note +# Age column: the four bands of a first-hit table see the same rows +< 18;{$: 0};true +< 18;{$: 17};true +< 18;{$: 17.99};true +< 18;{$: 18};false +< 18;{$: 18.5};false +< 18;{$: 24};false +< 18;{$: 25};false +< 18;{$: 40};false +< 18;{$: 64};false +< 18;{$: 64.99};false +< 18;{$: 65};false +< 18;{$: 66};false +< 18;{$: 120};false +< 18;{$: -1};true +< 18;{$: '18'};!error +< 18;{$: null};!error +< 18;{};!error +< 18;{$: true};!error +[18..25);{$: 0};false +[18..25);{$: 17};false +[18..25);{$: 17.99};false +[18..25);{$: 18};true +[18..25);{$: 18.5};true +[18..25);{$: 24};true +[18..25);{$: 25};false +[18..25);{$: 40};false +[18..25);{$: 64};false +[18..25);{$: 64.99};false +[18..25);{$: 65};false +[18..25);{$: 66};false +[18..25);{$: 120};false +[18..25);{$: -1};false +[18..25);{$: '18'};!error +[18..25);{$: null};!error +[18..25);{};!error +[18..25);{$: true};!error +[25..65);{$: 0};false +[25..65);{$: 17};false +[25..65);{$: 17.99};false +[25..65);{$: 18};false +[25..65);{$: 18.5};false +[25..65);{$: 24};false +[25..65);{$: 25};true +[25..65);{$: 40};true +[25..65);{$: 64};true +[25..65);{$: 64.99};true +[25..65);{$: 65};false +[25..65);{$: 66};false +[25..65);{$: 120};false +[25..65);{$: -1};false +[25..65);{$: '18'};!error +[25..65);{$: null};!error +[25..65);{};!error +[25..65);{$: true};!error +>= 65;{$: 0};false +>= 65;{$: 17};false +>= 65;{$: 17.99};false +>= 65;{$: 18};false +>= 65;{$: 18.5};false +>= 65;{$: 24};false +>= 65;{$: 25};false +>= 65;{$: 40};false +>= 65;{$: 64};false +>= 65;{$: 64.99};false +>= 65;{$: 65};true +>= 65;{$: 66};true +>= 65;{$: 120};true +>= 65;{$: -1};false +>= 65;{$: '18'};!error +>= 65;{$: null};!error +>= 65;{};!error +>= 65;{$: true};!error +# Closed, open and half-open bands, probed on both sides of each bound +[0..100];{$: -0.01};false +[0..100];{$: 0};true +[0..100];{$: 0.01};true +[0..100];{$: 99.99};true +[0..100];{$: 100};true +[0..100];{$: 100.01};false +[0..100];{$: 50};true +[0..100];{$: '20'};!error +[0..100];{$: true};!error +[0..100];{$: null};!error +[0..100];{};!error +(0..100);{$: -0.01};false +(0..100);{$: 0};false +(0..100);{$: 0.01};true +(0..100);{$: 99.99};true +(0..100);{$: 100};false +(0..100);{$: 100.01};false +(0..100);{$: 50};true +(0..100);{$: '20'};!error +(0..100);{$: true};!error +(0..100);{$: null};!error +(0..100);{};!error +[0..100);{$: -0.01};false +[0..100);{$: 0};true +[0..100);{$: 0.01};true +[0..100);{$: 99.99};true +[0..100);{$: 100};false +[0..100);{$: 100.01};false +[0..100);{$: 50};true +[0..100);{$: '20'};!error +[0..100);{$: true};!error +[0..100);{$: null};!error +[0..100);{};!error +(0..100];{$: -0.01};false +(0..100];{$: 0};false +(0..100];{$: 0.01};true +(0..100];{$: 99.99};true +(0..100];{$: 100};true +(0..100];{$: 100.01};false +(0..100];{$: 50};true +(0..100];{$: '20'};!error +(0..100];{$: true};!error +(0..100];{$: null};!error +(0..100];{};!error +[300..850];{$: 299.99};false +[300..850];{$: 300};true +[300..850];{$: 300.01};true +[300..850];{$: 849.99};true +[300..850];{$: 850};true +[300..850];{$: 850.01};false +[300..850];{$: 700};true +[300..850];{$: 0};false +[300..850];{$: '20'};!error +[300..850];{$: true};!error +[300..850];{$: null};!error +[300..850];{};!error +(300..850);{$: 299.99};false +(300..850);{$: 300};false +(300..850);{$: 300.01};true +(300..850);{$: 849.99};true +(300..850);{$: 850};false +(300..850);{$: 850.01};false +(300..850);{$: 700};true +(300..850);{$: 0};false +(300..850);{$: '20'};!error +(300..850);{$: true};!error +(300..850);{$: null};!error +(300..850);{};!error +# Decimal bands (ratios, rates) +[0..0.2);{$: -0.01};false +[0..0.2);{$: 0};true +[0..0.2);{$: 0.01};true +[0..0.2);{$: 0.19};true +[0..0.2);{$: 0.2};false +[0..0.2);{$: 0.21};false +[0..0.2);{$: 0.1999999999};true +[0..0.2);{$: 0.2000000001};false +[0..0.2);{$: '20'};!error +[0..0.2);{$: true};!error +[0..0.2);{$: null};!error +[0..0.2);{};!error +[0.2..0.36];{$: 0.19};false +[0.2..0.36];{$: 0.2};true +[0.2..0.36];{$: 0.21};true +[0.2..0.36];{$: 0.35};true +[0.2..0.36];{$: 0.36};true +[0.2..0.36];{$: 0.37};false +[0.2..0.36];{$: 0.3600000001};false +[0.2..0.36];{$: '20'};!error +[0.2..0.36];{$: true};!error +[0.2..0.36];{$: null};!error +[0.2..0.36];{};!error +(0.36..0.43];{$: 0.35};false +(0.36..0.43];{$: 0.36};false +(0.36..0.43];{$: 0.37};true +(0.36..0.43];{$: 0.42};true +(0.36..0.43];{$: 0.43};true +(0.36..0.43];{$: 0.44};false +(0.36..0.43];{$: 0.365};true +(0.36..0.43];{$: '20'};!error +(0.36..0.43];{$: true};!error +(0.36..0.43];{$: null};!error +(0.36..0.43];{};!error +(0.01..0.99);{$: 0.00};false +(0.01..0.99);{$: 0.01};false +(0.01..0.99);{$: 0.02};true +(0.01..0.99);{$: 0.98};true +(0.01..0.99);{$: 0.99};false +(0.01..0.99);{$: 1.00};false +(0.01..0.99);{$: 0.5};true +(0.01..0.99);{$: 0.001};false +(0.01..0.99);{$: '20'};!error +(0.01..0.99);{$: true};!error +(0.01..0.99);{$: null};!error +(0.01..0.99);{};!error +[0.5..1.5];{$: 0.49};false +[0.5..1.5];{$: 0.5};true +[0.5..1.5];{$: 0.51};true +[0.5..1.5];{$: 1.49};true +[0.5..1.5];{$: 1.5};true +[0.5..1.5];{$: 1.51};false +[0.5..1.5];{$: 1};true +[0.5..1.5];{$: '20'};!error +[0.5..1.5];{$: true};!error +[0.5..1.5];{$: null};!error +[0.5..1.5];{};!error +# Negative bands +(-100..-10];{$: -100.01};false +(-100..-10];{$: -100};false +(-100..-10];{$: -99.99};true +(-100..-10];{$: -10.01};true +(-100..-10];{$: -10};true +(-100..-10];{$: -9.99};false +(-100..-10];{$: -50};true +(-100..-10];{$: 0};false +(-100..-10];{$: '20'};!error +(-100..-10];{$: true};!error +(-100..-10];{$: null};!error +(-100..-10];{};!error +[-1..1];{$: -1.01};false +[-1..1];{$: -1};true +[-1..1];{$: -0.99};true +[-1..1];{$: 0.99};true +[-1..1];{$: 1};true +[-1..1];{$: 1.01};false +[-1..1];{$: 0};true +[-1..1];{$: -0.0};true +[-1..1];{$: '20'};!error +[-1..1];{$: true};!error +[-1..1];{$: null};!error +[-1..1];{};!error +[-0.5..0);{$: -0.51};false +[-0.5..0);{$: -0.5};true +[-0.5..0);{$: -0.49};true +[-0.5..0);{$: -0.01};true +[-0.5..0);{$: 0};false +[-0.5..0);{$: 0.01};false +[-0.5..0);{$: -0.25};true +[-0.5..0);{$: '20'};!error +[-0.5..0);{$: true};!error +[-0.5..0);{$: null};!error +[-0.5..0);{};!error +# Large amounts +[1000..5000);{$: 999.99};false +[1000..5000);{$: 1000};true +[1000..5000);{$: 1000.01};true +[1000..5000);{$: 4999.99};true +[1000..5000);{$: 5000};false +[1000..5000);{$: 5000.01};false +[1000..5000);{$: 2500};true +[1000..5000);{$: 4999.999999};true +[1000..5000);{$: '20'};!error +[1000..5000);{$: true};!error +[1000..5000);{$: null};!error +[1000..5000);{};!error +[100000..1000000);{$: 99999.99};false +[100000..1000000);{$: 100000};true +[100000..1000000);{$: 100000.01};true +[100000..1000000);{$: 999999.99};true +[100000..1000000);{$: 1000000};false +[100000..1000000);{$: 1000000.01};false +[100000..1000000);{$: 999999.99};true +[100000..1000000);{$: '20'};!error +[100000..1000000);{$: true};!error +[100000..1000000);{$: null};!error +[100000..1000000);{};!error +[0..999999999999];{$: -0.01};false +[0..999999999999];{$: 0};true +[0..999999999999];{$: 0.01};true +[0..999999999999];{$: 999999999998.99};true +[0..999999999999];{$: 999999999999};true +[0..999999999999];{$: 999999999999.01};false +[0..999999999999];{$: 1000000000000};false +[0..999999999999];{$: '20'};!error +[0..999999999999];{$: true};!error +[0..999999999999];{$: null};!error +[0..999999999999];{};!error +# Open-ended bands +<= 0;{$: -1};true +<= 0;{$: 0};true +<= 0;{$: 0.01};false +<= 0;{$: 99999.98};false +<= 0;{$: 99999.99};false +<= 0;{$: 100000};false +<= 0;{$: -0.01};true +<= 0;{$: '20'};!error +<= 0;{$: true};!error +<= 0;{$: null};!error +<= 0;{};!error +> 0;{$: -1};false +> 0;{$: 0};false +> 0;{$: 0.01};true +> 0;{$: 99999.98};true +> 0;{$: 99999.99};true +> 0;{$: 100000};true +> 0;{$: -0.01};false +> 0;{$: '20'};!error +> 0;{$: true};!error +> 0;{$: null};!error +> 0;{};!error +> 99999.99;{$: -1};false +> 99999.99;{$: 0};false +> 99999.99;{$: 0.01};false +> 99999.99;{$: 99999.98};false +> 99999.99;{$: 99999.99};false +> 99999.99;{$: 100000};true +> 99999.99;{$: -0.01};false +> 99999.99;{$: '20'};!error +> 99999.99;{$: true};!error +> 99999.99;{$: null};!error +> 99999.99;{};!error +>= 99999.99;{$: -1};false +>= 99999.99;{$: 0};false +>= 99999.99;{$: 0.01};false +>= 99999.99;{$: 99999.98};false +>= 99999.99;{$: 99999.99};true +>= 99999.99;{$: 100000};true +>= 99999.99;{$: -0.01};false +>= 99999.99;{$: '20'};!error +>= 99999.99;{$: true};!error +>= 99999.99;{$: null};!error +>= 99999.99;{};!error +< 0.01;{$: -1};true +< 0.01;{$: 0};true +< 0.01;{$: 0.01};false +< 0.01;{$: 99999.98};false +< 0.01;{$: 99999.99};false +< 0.01;{$: 100000};false +< 0.01;{$: -0.01};true +< 0.01;{$: '20'};!error +< 0.01;{$: true};!error +< 0.01;{$: null};!error +< 0.01;{};!error +> -0.01;{$: -1};false +> -0.01;{$: 0};true +> -0.01;{$: 0.01};true +> -0.01;{$: 99999.98};true +> -0.01;{$: 99999.99};true +> -0.01;{$: 100000};true +> -0.01;{$: -0.01};false +> -0.01;{$: '20'};!error +> -0.01;{$: true};!error +> -0.01;{$: null};!error +> -0.01;{};!error +# A band written four ways gives the same answer on every row +[18..25);{$: 17};false +[18..25);{$: 17.99};false +[18..25);{$: 18};true +[18..25);{$: 21};true +[18..25);{$: 24.99};true +[18..25);{$: 25};false +[18..25);{$: 30};false +[18..25);{$: '20'};!error +[18..25);{$: null};!error +[18..25);{};!error +[18..25);{$: false};!error +>= 18 and < 25;{$: 17};false +>= 18 and < 25;{$: 17.99};false +>= 18 and < 25;{$: 18};true +>= 18 and < 25;{$: 21};true +>= 18 and < 25;{$: 24.99};true +>= 18 and < 25;{$: 25};false +>= 18 and < 25;{$: 30};false +>= 18 and < 25;{$: '20'};!error +>= 18 and < 25;{$: null};!error +>= 18 and < 25;{};!error +>= 18 and < 25;{$: false};!error +$ >= 18 and $ < 25;{$: 17};false +$ >= 18 and $ < 25;{$: 17.99};false +$ >= 18 and $ < 25;{$: 18};true +$ >= 18 and $ < 25;{$: 21};true +$ >= 18 and $ < 25;{$: 24.99};true +$ >= 18 and $ < 25;{$: 25};false +$ >= 18 and $ < 25;{$: 30};false +$ >= 18 and $ < 25;{$: '20'};!error +$ >= 18 and $ < 25;{$: null};!error +$ >= 18 and $ < 25;{};!error +$ >= 18 and $ < 25;{$: false};!error +$ in [18..25);{$: 17};false +$ in [18..25);{$: 17.99};false +$ in [18..25);{$: 18};true +$ in [18..25);{$: 21};true +$ in [18..25);{$: 24.99};true +$ in [18..25);{$: 25};false +$ in [18..25);{$: 30};false +$ in [18..25);{$: '20'};!error +$ in [18..25);{$: null};!error +$ in [18..25);{};!error +$ in [18..25);{$: false};!error +(0..1];{$: 0};false +(0..1];{$: 0.0001};true +(0..1];{$: 0.5};true +(0..1];{$: 1};true +(0..1];{$: 1.0};true +(0..1];{$: 1.0001};false +(0..1];{$: -1};false +(0..1];{$: '0.5'};!error +(0..1];{$: null};!error +(0..1];{};!error +> 0 and <= 1;{$: 0};false +> 0 and <= 1;{$: 0.0001};true +> 0 and <= 1;{$: 0.5};true +> 0 and <= 1;{$: 1};true +> 0 and <= 1;{$: 1.0};true +> 0 and <= 1;{$: 1.0001};false +> 0 and <= 1;{$: -1};false +> 0 and <= 1;{$: '0.5'};!error +> 0 and <= 1;{$: null};!error +> 0 and <= 1;{};!error +$ > 0 and $ <= 1;{$: 0};false +$ > 0 and $ <= 1;{$: 0.0001};true +$ > 0 and $ <= 1;{$: 0.5};true +$ > 0 and $ <= 1;{$: 1};true +$ > 0 and $ <= 1;{$: 1.0};true +$ > 0 and $ <= 1;{$: 1.0001};false +$ > 0 and $ <= 1;{$: -1};false +$ > 0 and $ <= 1;{$: '0.5'};!error +$ > 0 and $ <= 1;{$: null};!error +$ > 0 and $ <= 1;{};!error +$ in (0..1];{$: 0};false +$ in (0..1];{$: 0.0001};true +$ in (0..1];{$: 0.5};true +$ in (0..1];{$: 1};true +$ in (0..1];{$: 1.0};true +$ in (0..1];{$: 1.0001};false +$ in (0..1];{$: -1};false +$ in (0..1];{$: '0.5'};!error +$ in (0..1];{$: null};!error +$ in (0..1];{};!error +# Negated bands +$ not in [18..25);{$: 17};true +$ not in [18..25);{$: 17.99};true +$ not in [18..25);{$: 18};false +$ not in [18..25);{$: 21};false +$ not in [18..25);{$: 24.99};false +$ not in [18..25);{$: 25};true +$ not in [18..25);{$: 30};true +$ not in [18..25);{$: '20'};!error +$ not in [18..25);{$: null};!error +$ not in [18..25);{};!error +$ not in [18..25);{$: false};!error +not ($ in [18..25));{$: 17};true +not ($ in [18..25));{$: 17.99};true +not ($ in [18..25));{$: 18};false +not ($ in [18..25));{$: 21};false +not ($ in [18..25));{$: 24.99};false +not ($ in [18..25));{$: 25};true +not ($ in [18..25));{$: 30};true +not ($ in [18..25));{$: '20'};!error +not ($ in [18..25));{$: null};!error +not ($ in [18..25));{};!error +not ($ in [18..25));{$: false};!error +not in [18..25);{$: 17};true +not in [18..25);{$: 17.99};true +not in [18..25);{$: 18};false +not in [18..25);{$: 21};false +not in [18..25);{$: 24.99};false +not in [18..25);{$: 25};true +not in [18..25);{$: 30};true +not in [18..25);{$: '20'};!error +not in [18..25);{$: null};!error +not in [18..25);{};!error +not in [18..25);{$: false};!error +< 18, >= 25;{$: 17};true +< 18, >= 25;{$: 17.99};true +< 18, >= 25;{$: 18};false +< 18, >= 25;{$: 21};false +< 18, >= 25;{$: 24.99};false +< 18, >= 25;{$: 25};true +< 18, >= 25;{$: 30};true +< 18, >= 25;{$: '20'};!error +< 18, >= 25;{$: null};!error +< 18, >= 25;{};!error +< 18, >= 25;{$: false};!error +< 18 or >= 25;{$: 17};true +< 18 or >= 25;{$: 17.99};true +< 18 or >= 25;{$: 18};false +< 18 or >= 25;{$: 21};false +< 18 or >= 25;{$: 24.99};false +< 18 or >= 25;{$: 25};true +< 18 or >= 25;{$: 30};true +< 18 or >= 25;{$: '20'};!error +< 18 or >= 25;{$: null};!error +< 18 or >= 25;{};!error +< 18 or >= 25;{$: false};!error +# Several bands in one cell +[0..10), [90..100];{$: -1};false +[0..10), [90..100];{$: 0};true +[0..10), [90..100];{$: 9.99};true +[0..10), [90..100];{$: 10};false +[0..10), [90..100];{$: 50};false +[0..10), [90..100];{$: 89.99};false +[0..10), [90..100];{$: 90};true +[0..10), [90..100];{$: 100};true +[0..10), [90..100];{$: 100.01};false +[0..10), [90..100];{$: '5'};!error +[0..10), [90..100];{$: null};!error +[0..10), [90..100];{};!error +< 0, [10..20], > 100;{$: -5};true +< 0, [10..20], > 100;{$: 0};false +< 0, [10..20], > 100;{$: 9.99};false +< 0, [10..20], > 100;{$: 10};true +< 0, [10..20], > 100;{$: 15};true +< 0, [10..20], > 100;{$: 20};true +< 0, [10..20], > 100;{$: 20.01};false +< 0, [10..20], > 100;{$: 100};false +< 0, [10..20], > 100;{$: 101};true +< 0, [10..20], > 100;{$: null};!error +< 0, [10..20], > 100;{};!error +< 0, [10..20], > 100;{$: true};!error +(1..2), (2..3);{$: 1};false +(1..2), (2..3);{$: 1.5};true +(1..2), (2..3);{$: 2};false +(1..2), (2..3);{$: 2.5};true +(1..2), (2..3);{$: 3};false +(1..2), (2..3);{$: 0};false +(1..2), (2..3);{$: null};!error +(1..2), (2..3);{$: 'x'};!error +# Bands with an exclusion +[1..10] and != 5 and != 7;{$: 0};false +[1..10] and != 5 and != 7;{$: 1};true +[1..10] and != 5 and != 7;{$: 4};true +[1..10] and != 5 and != 7;{$: 5};false +[1..10] and != 5 and != 7;{$: 5.5};true +[1..10] and != 5 and != 7;{$: 7};false +[1..10] and != 5 and != 7;{$: 7.0};false +[1..10] and != 5 and != 7;{$: 10};true +[1..10] and != 5 and != 7;{$: 11};false +[1..10] and != 5 and != 7;{$: null};!error +[1..10] and != 5 and != 7;{};!error +[1..10] and != 5 and != 7;{$: '5'};!error +> 0 and $ % 1 == 0;{$: 0};false +> 0 and $ % 1 == 0;{$: 1};true +> 0 and $ % 1 == 0;{$: 1.5};false +> 0 and $ % 1 == 0;{$: 2};true +> 0 and $ % 1 == 0;{$: -2};false +> 0 and $ % 1 == 0;{$: 100};true +> 0 and $ % 1 == 0;{$: 0.999};false +> 0 and $ % 1 == 0;{$: null};!error +> 0 and $ % 1 == 0;{$: '1'};!error +# Integer steps: whole-number bands see fractional rows +[1..3];{$: 0.9};false +[1..3];{$: 0.999999999999};false +[1..3];{$: 1};true +[1..3];{$: 2};true +[1..3];{$: 2.5};true +[1..3];{$: 3};true +[1..3];{$: 3.000000000001};false +[1..3];{$: 4};false +[1..3];{$: null};!error +(1..3);{$: 1};false +(1..3);{$: 1.000000000001};true +(1..3);{$: 2};true +(1..3);{$: 2.999999999999};true +(1..3);{$: 3};false +(1..3);{$: null};!error +# Bands written with exact decimal bounds +[0.1..0.3];{$: 0.1};true +[0.1..0.3];{$: 0.10};true +[0.1..0.3];{$: 0.2};true +[0.1..0.3];{$: 0.3};true +[0.1..0.3];{$: 0.30000000000000004};false +[0.1..0.3];{$: 0.09999999999999999};false +[0.1..0.3];{$: null};!error +> 0.1 + 0.2;{$: 0.3};false +> 0.1 + 0.2;{$: 0.30000000000000004};true +> 0.1 + 0.2;{$: 0.31};true +> 0.1 + 0.2;{$: 0.29};false +> 0.1 + 0.2;{$: null};!error +== 0.1 + 0.2;{$: 0.3};true +== 0.1 + 0.2;{$: 0.30};true +== 0.1 + 0.2;{$: 0.30000000000000004};false +== 0.1 + 0.2;{$: null};false +== 0.1 + 0.2;{$: '0.3'};false diff --git a/core/expression/tests/spec/unary/11-string-enums.csv b/core/expression/tests/spec/unary/11-string-enums.csv new file mode 100644 index 00000000..65a57097 --- /dev/null +++ b/core/expression/tests/spec/unary/11-string-enums.csv @@ -0,0 +1,539 @@ +expression (string);input (json 5);output (json 5);note +# One enum value, written as a literal, a shorthand and an explicit comparison +'gold';{$: 'gold'};true +'gold';{$: 'Gold'};false +'gold';{$: 'GOLD'};false +'gold';{$: ' gold'};false +'gold';{$: 'gold '};false +'gold';{$: 'platinum'};false +'gold';{$: 'silver'};false +'gold';{$: ''};false +'gold';{$: null};false +'gold';{};false +'gold';{$: 1};false +'gold';{$: true};false +'gold';{$: ['gold']};false +$ == 'gold';{$: 'gold'};true +$ == 'gold';{$: 'Gold'};false +$ == 'gold';{$: 'GOLD'};false +$ == 'gold';{$: ' gold'};false +$ == 'gold';{$: 'gold '};false +$ == 'gold';{$: 'platinum'};false +$ == 'gold';{$: 'silver'};false +$ == 'gold';{$: ''};false +$ == 'gold';{$: null};false +$ == 'gold';{};false +$ == 'gold';{$: 1};false +$ == 'gold';{$: true};false +$ == 'gold';{$: ['gold']};false +"""gold""";{$: 'gold'};true +"""gold""";{$: 'Gold'};false +"""gold""";{$: 'GOLD'};false +"""gold""";{$: ' gold'};false +"""gold""";{$: 'gold '};false +"""gold""";{$: 'platinum'};false +"""gold""";{$: 'silver'};false +"""gold""";{$: ''};false +"""gold""";{$: null};false +"""gold""";{};false +"""gold""";{$: 1};false +"""gold""";{$: true};false +"""gold""";{$: ['gold']};false +`gold`;{$: 'gold'};true +`gold`;{$: 'Gold'};false +`gold`;{$: 'GOLD'};false +`gold`;{$: ' gold'};false +`gold`;{$: 'gold '};false +`gold`;{$: 'platinum'};false +`gold`;{$: 'silver'};false +`gold`;{$: ''};false +`gold`;{$: null};false +`gold`;{};false +`gold`;{$: 1};false +`gold`;{$: true};false +`gold`;{$: ['gold']};false +!= 'gold';{$: 'gold'};false +!= 'gold';{$: 'Gold'};true +!= 'gold';{$: 'GOLD'};true +!= 'gold';{$: ' gold'};true +!= 'gold';{$: 'gold '};true +!= 'gold';{$: 'platinum'};true +!= 'gold';{$: 'silver'};true +!= 'gold';{$: ''};true +!= 'gold';{$: null};true +!= 'gold';{};true +!= 'gold';{$: 1};true +!= 'gold';{$: true};true +!= 'gold';{$: ['gold']};true +# Several enum values +'gold', 'platinum';{$: 'gold'};true +'gold', 'platinum';{$: 'Gold'};false +'gold', 'platinum';{$: 'GOLD'};false +'gold', 'platinum';{$: ' gold'};false +'gold', 'platinum';{$: 'gold '};false +'gold', 'platinum';{$: 'platinum'};true +'gold', 'platinum';{$: 'silver'};false +'gold', 'platinum';{$: ''};false +'gold', 'platinum';{$: null};false +'gold', 'platinum';{};false +'gold', 'platinum';{$: 1};false +'gold', 'platinum';{$: true};false +'gold', 'platinum';{$: ['gold']};false +'gold' or 'platinum';{$: 'gold'};true +'gold' or 'platinum';{$: 'Gold'};false +'gold' or 'platinum';{$: 'GOLD'};false +'gold' or 'platinum';{$: ' gold'};false +'gold' or 'platinum';{$: 'gold '};false +'gold' or 'platinum';{$: 'platinum'};true +'gold' or 'platinum';{$: 'silver'};false +'gold' or 'platinum';{$: ''};false +'gold' or 'platinum';{$: null};false +'gold' or 'platinum';{};false +'gold' or 'platinum';{$: 1};false +'gold' or 'platinum';{$: true};false +'gold' or 'platinum';{$: ['gold']};false +$ == 'gold' or $ == 'platinum';{$: 'gold'};true +$ == 'gold' or $ == 'platinum';{$: 'Gold'};false +$ == 'gold' or $ == 'platinum';{$: 'GOLD'};false +$ == 'gold' or $ == 'platinum';{$: ' gold'};false +$ == 'gold' or $ == 'platinum';{$: 'gold '};false +$ == 'gold' or $ == 'platinum';{$: 'platinum'};true +$ == 'gold' or $ == 'platinum';{$: 'silver'};false +$ == 'gold' or $ == 'platinum';{$: ''};false +$ == 'gold' or $ == 'platinum';{$: null};false +$ == 'gold' or $ == 'platinum';{};false +$ == 'gold' or $ == 'platinum';{$: 1};false +$ == 'gold' or $ == 'platinum';{$: true};false +$ == 'gold' or $ == 'platinum';{$: ['gold']};false +'platinum', 'gold';{$: 'gold'};true +'platinum', 'gold';{$: 'Gold'};false +'platinum', 'gold';{$: 'GOLD'};false +'platinum', 'gold';{$: ' gold'};false +'platinum', 'gold';{$: 'gold '};false +'platinum', 'gold';{$: 'platinum'};true +'platinum', 'gold';{$: 'silver'};false +'platinum', 'gold';{$: ''};false +'platinum', 'gold';{$: null};false +'platinum', 'gold';{};false +'platinum', 'gold';{$: 1};false +'platinum', 'gold';{$: true};false +'platinum', 'gold';{$: ['gold']};false +$ in ['gold', 'platinum'];{$: 'gold'};true +$ in ['gold', 'platinum'];{$: 'Gold'};false +$ in ['gold', 'platinum'];{$: 'GOLD'};false +$ in ['gold', 'platinum'];{$: ' gold'};false +$ in ['gold', 'platinum'];{$: 'gold '};false +$ in ['gold', 'platinum'];{$: 'platinum'};true +$ in ['gold', 'platinum'];{$: 'silver'};false +$ in ['gold', 'platinum'];{$: ''};false +$ in ['gold', 'platinum'];{$: null};false +$ in ['gold', 'platinum'];{};false +$ in ['gold', 'platinum'];{$: 1};false +$ in ['gold', 'platinum'];{$: true};false +$ in ['gold', 'platinum'];{$: ['gold']};false;bug: membership of an array $ errors (Opcode In: Unsupported type) instead of the false that deep equality implies +in ['gold', 'platinum'];{$: 'gold'};true +in ['gold', 'platinum'];{$: 'Gold'};false +in ['gold', 'platinum'];{$: 'GOLD'};false +in ['gold', 'platinum'];{$: ' gold'};false +in ['gold', 'platinum'];{$: 'gold '};false +in ['gold', 'platinum'];{$: 'platinum'};true +in ['gold', 'platinum'];{$: 'silver'};false +in ['gold', 'platinum'];{$: ''};false +in ['gold', 'platinum'];{$: null};false +in ['gold', 'platinum'];{};false +in ['gold', 'platinum'];{$: 1};false +in ['gold', 'platinum'];{$: true};false +in ['gold', 'platinum'];{$: ['gold']};false;bug: membership of an array $ errors (Opcode In: Unsupported type) instead of the false that deep equality implies +$ not in ['gold', 'platinum'];{$: 'gold'};false +$ not in ['gold', 'platinum'];{$: 'Gold'};true +$ not in ['gold', 'platinum'];{$: 'GOLD'};true +$ not in ['gold', 'platinum'];{$: ' gold'};true +$ not in ['gold', 'platinum'];{$: 'gold '};true +$ not in ['gold', 'platinum'];{$: 'platinum'};false +$ not in ['gold', 'platinum'];{$: 'silver'};true +$ not in ['gold', 'platinum'];{$: ''};true +$ not in ['gold', 'platinum'];{$: null};true +$ not in ['gold', 'platinum'];{};true +$ not in ['gold', 'platinum'];{$: 1};true +$ not in ['gold', 'platinum'];{$: true};true +$ not in ['gold', 'platinum'];{$: ['gold']};true;bug: membership of an array $ errors (Opcode In: Unsupported type) instead of the false that deep equality implies +not in ['gold', 'platinum'];{$: 'gold'};false +not in ['gold', 'platinum'];{$: 'Gold'};true +not in ['gold', 'platinum'];{$: 'GOLD'};true +not in ['gold', 'platinum'];{$: ' gold'};true +not in ['gold', 'platinum'];{$: 'gold '};true +not in ['gold', 'platinum'];{$: 'platinum'};false +not in ['gold', 'platinum'];{$: 'silver'};true +not in ['gold', 'platinum'];{$: ''};true +not in ['gold', 'platinum'];{$: null};true +not in ['gold', 'platinum'];{};true +not in ['gold', 'platinum'];{$: 1};true +not in ['gold', 'platinum'];{$: true};true +not in ['gold', 'platinum'];{$: ['gold']};true;bug: membership of an array $ errors (Opcode In: Unsupported type) instead of the false that deep equality implies +not ($ in ['gold', 'platinum']);{$: 'gold'};false +not ($ in ['gold', 'platinum']);{$: 'Gold'};true +not ($ in ['gold', 'platinum']);{$: 'GOLD'};true +not ($ in ['gold', 'platinum']);{$: ' gold'};true +not ($ in ['gold', 'platinum']);{$: 'gold '};true +not ($ in ['gold', 'platinum']);{$: 'platinum'};false +not ($ in ['gold', 'platinum']);{$: 'silver'};true +not ($ in ['gold', 'platinum']);{$: ''};true +not ($ in ['gold', 'platinum']);{$: null};true +not ($ in ['gold', 'platinum']);{};true +not ($ in ['gold', 'platinum']);{$: 1};true +not ($ in ['gold', 'platinum']);{$: true};true +not ($ in ['gold', 'platinum']);{$: ['gold']};true;bug: membership of an array $ errors (Opcode In: Unsupported type) instead of the false that deep equality implies +# Case-insensitive cells normalise $ first +lower($) == 'gold';{$: 'gold'};true +lower($) == 'gold';{$: 'Gold'};true +lower($) == 'gold';{$: 'GOLD'};true +lower($) == 'gold';{$: ' gold'};false +lower($) == 'gold';{$: 'gold '};false +lower($) == 'gold';{$: 'platinum'};false +lower($) == 'gold';{$: 'silver'};false +lower($) == 'gold';{$: ''};false +lower($) == 'gold';{$: null};!error +lower($) == 'gold';{};!error +lower($) == 'gold';{$: 1};!error +lower($) == 'gold';{$: true};!error +lower($) == 'gold';{$: ['gold']};!error +upper($) == 'GOLD';{$: 'gold'};true +upper($) == 'GOLD';{$: 'Gold'};true +upper($) == 'GOLD';{$: 'GOLD'};true +upper($) == 'GOLD';{$: ' gold'};false +upper($) == 'GOLD';{$: 'gold '};false +upper($) == 'GOLD';{$: 'platinum'};false +upper($) == 'GOLD';{$: 'silver'};false +upper($) == 'GOLD';{$: ''};false +upper($) == 'GOLD';{$: null};!error +upper($) == 'GOLD';{};!error +upper($) == 'GOLD';{$: 1};!error +upper($) == 'GOLD';{$: true};!error +upper($) == 'GOLD';{$: ['gold']};!error +lower($) in ['gold', 'platinum'];{$: 'gold'};true +lower($) in ['gold', 'platinum'];{$: 'Gold'};true +lower($) in ['gold', 'platinum'];{$: 'GOLD'};true +lower($) in ['gold', 'platinum'];{$: ' gold'};false +lower($) in ['gold', 'platinum'];{$: 'gold '};false +lower($) in ['gold', 'platinum'];{$: 'platinum'};true +lower($) in ['gold', 'platinum'];{$: 'silver'};false +lower($) in ['gold', 'platinum'];{$: ''};false +lower($) in ['gold', 'platinum'];{$: null};!error +lower($) in ['gold', 'platinum'];{};!error +lower($) in ['gold', 'platinum'];{$: 1};!error +lower($) in ['gold', 'platinum'];{$: true};!error +lower($) in ['gold', 'platinum'];{$: ['gold']};!error +lower(trim($)) == 'gold';{$: 'gold'};true +lower(trim($)) == 'gold';{$: 'Gold'};true +lower(trim($)) == 'gold';{$: 'GOLD'};true +lower(trim($)) == 'gold';{$: ' gold'};true +lower(trim($)) == 'gold';{$: 'gold '};true +lower(trim($)) == 'gold';{$: 'platinum'};false +lower(trim($)) == 'gold';{$: 'silver'};false +lower(trim($)) == 'gold';{$: ''};false +lower(trim($)) == 'gold';{$: null};!error +lower(trim($)) == 'gold';{};!error +lower(trim($)) == 'gold';{$: 1};!error +lower(trim($)) == 'gold';{$: true};!error +lower(trim($)) == 'gold';{$: ['gold']};!error +trim($) == 'gold';{$: 'gold'};true +trim($) == 'gold';{$: 'Gold'};false +trim($) == 'gold';{$: 'GOLD'};false +trim($) == 'gold';{$: ' gold'};true +trim($) == 'gold';{$: 'gold '};true +trim($) == 'gold';{$: 'platinum'};false +trim($) == 'gold';{$: 'silver'};false +trim($) == 'gold';{$: ''};false +trim($) == 'gold';{$: null};!error +trim($) == 'gold';{};!error +trim($) == 'gold';{$: 1};!error +trim($) == 'gold';{$: true};!error +trim($) == 'gold';{$: ['gold']};!error +# Country codes +'GB', 'IE';{$: 'GB'};true +'GB', 'IE';{$: 'gb'};false +'GB', 'IE';{$: 'Gb'};false +'GB', 'IE';{$: 'IE'};true +'GB', 'IE';{$: 'FR'};false +'GB', 'IE';{$: 'GBR'};false +'GB', 'IE';{$: 'G'};false +'GB', 'IE';{$: ''};false +'GB', 'IE';{$: 'UK'};false +'GB', 'IE';{$: null};false +'GB', 'IE';{};false +'GB', 'IE';{$: 44};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'GB'};true +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'gb'};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'Gb'};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'IE'};true +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'FR'};true +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'GBR'};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'G'};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: ''};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 'UK'};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: null};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{};false +'GB', 'IE', 'FR', 'DE', 'ES', 'IT', 'NL', 'BE';{$: 44};false +not in ['GB', 'IE'];{$: 'GB'};false +not in ['GB', 'IE'];{$: 'gb'};true +not in ['GB', 'IE'];{$: 'Gb'};true +not in ['GB', 'IE'];{$: 'IE'};false +not in ['GB', 'IE'];{$: 'FR'};true +not in ['GB', 'IE'];{$: 'GBR'};true +not in ['GB', 'IE'];{$: 'G'};true +not in ['GB', 'IE'];{$: ''};true +not in ['GB', 'IE'];{$: 'UK'};true +not in ['GB', 'IE'];{$: null};true +not in ['GB', 'IE'];{};true +not in ['GB', 'IE'];{$: 44};true +upper($) in ['GB', 'IE'];{$: 'GB'};true +upper($) in ['GB', 'IE'];{$: 'gb'};true +upper($) in ['GB', 'IE'];{$: 'Gb'};true +upper($) in ['GB', 'IE'];{$: 'IE'};true +upper($) in ['GB', 'IE'];{$: 'FR'};false +upper($) in ['GB', 'IE'];{$: 'GBR'};false +upper($) in ['GB', 'IE'];{$: 'G'};false +upper($) in ['GB', 'IE'];{$: ''};false +upper($) in ['GB', 'IE'];{$: 'UK'};false +upper($) in ['GB', 'IE'];{$: null};!error +upper($) in ['GB', 'IE'];{};!error +upper($) in ['GB', 'IE'];{$: 44};!error +len($) == 2;{$: 'GB'};true +len($) == 2;{$: 'gb'};true +len($) == 2;{$: 'Gb'};true +len($) == 2;{$: 'IE'};true +len($) == 2;{$: 'FR'};true +len($) == 2;{$: 'GBR'};false +len($) == 2;{$: 'G'};false +len($) == 2;{$: ''};false +len($) == 2;{$: 'UK'};true +len($) == 2;{$: null};!error +len($) == 2;{};!error +len($) == 2;{$: 44};!error +# Values with spaces, punctuation and non-ASCII letters +'New York', 'Los Angeles';{$: 'New York'};true +'New York', 'Los Angeles';{$: 'new york'};false +'New York', 'Los Angeles';{$: 'NewYork'};false +'New York', 'Los Angeles';{$: 'New York'};false +'New York', 'Los Angeles';{$: 'Zürich'};false +'New York', 'Los Angeles';{$: 'Zurich'};false +'New York', 'Los Angeles';{$: 'A&B'};false +'New York', 'Los Angeles';{$: 'a,b'};false +'New York', 'Los Angeles';{$: '50%'};false +'New York', 'Los Angeles';{$: 'O\'Brien'};false +'New York', 'Los Angeles';"{$: 'say ""hi""'}";false +'New York', 'Los Angeles';{$: null};false +'Zürich';{$: 'New York'};false +'Zürich';{$: 'new york'};false +'Zürich';{$: 'NewYork'};false +'Zürich';{$: 'New York'};false +'Zürich';{$: 'Zürich'};true +'Zürich';{$: 'Zurich'};false +'Zürich';{$: 'A&B'};false +'Zürich';{$: 'a,b'};false +'Zürich';{$: '50%'};false +'Zürich';{$: 'O\'Brien'};false +'Zürich';"{$: 'say ""hi""'}";false +'Zürich';{$: null};false +'A&B', '50%';{$: 'New York'};false +'A&B', '50%';{$: 'new york'};false +'A&B', '50%';{$: 'NewYork'};false +'A&B', '50%';{$: 'New York'};false +'A&B', '50%';{$: 'Zürich'};false +'A&B', '50%';{$: 'Zurich'};false +'A&B', '50%';{$: 'A&B'};true +'A&B', '50%';{$: 'a,b'};false +'A&B', '50%';{$: '50%'};true +'A&B', '50%';{$: 'O\'Brien'};false +'A&B', '50%';"{$: 'say ""hi""'}";false +'A&B', '50%';{$: null};false +'a,b';{$: 'New York'};false +'a,b';{$: 'new york'};false +'a,b';{$: 'NewYork'};false +'a,b';{$: 'New York'};false +'a,b';{$: 'Zürich'};false +'a,b';{$: 'Zurich'};false +'a,b';{$: 'A&B'};false +'a,b';{$: 'a,b'};true +'a,b';{$: '50%'};false +'a,b';{$: 'O\'Brien'};false +'a,b';"{$: 'say ""hi""'}";false +'a,b';{$: null};false +'a', 'b';{$: 'New York'};false +'a', 'b';{$: 'new york'};false +'a', 'b';{$: 'NewYork'};false +'a', 'b';{$: 'New York'};false +'a', 'b';{$: 'Zürich'};false +'a', 'b';{$: 'Zurich'};false +'a', 'b';{$: 'A&B'};false +'a', 'b';{$: 'a,b'};false +'a', 'b';{$: '50%'};false +'a', 'b';{$: 'O\'Brien'};false +'a', 'b';"{$: 'say ""hi""'}";false +'a', 'b';{$: null};false +"""O'Brien""";{$: 'New York'};false +"""O'Brien""";{$: 'new york'};false +"""O'Brien""";{$: 'NewYork'};false +"""O'Brien""";{$: 'New York'};false +"""O'Brien""";{$: 'Zürich'};false +"""O'Brien""";{$: 'Zurich'};false +"""O'Brien""";{$: 'A&B'};false +"""O'Brien""";{$: 'a,b'};false +"""O'Brien""";{$: '50%'};false +"""O'Brien""";{$: 'O\'Brien'};true +"""O'Brien""";"{$: 'say ""hi""'}";false +"""O'Brien""";{$: null};false +'O\'Brien';{$: 'O\'Brien'};!error;"question: string literals have no escape sequences, so a quote cannot be escaped inside single quotes; use double quotes" +'O\'Brien';{$: null};!error +"'say ""hi""'";{$: 'New York'};false +"'say ""hi""'";{$: 'new york'};false +"'say ""hi""'";{$: 'NewYork'};false +"'say ""hi""'";{$: 'New York'};false +"'say ""hi""'";{$: 'Zürich'};false +"'say ""hi""'";{$: 'Zurich'};false +"'say ""hi""'";{$: 'A&B'};false +"'say ""hi""'";{$: 'a,b'};false +"'say ""hi""'";{$: '50%'};false +"'say ""hi""'";{$: 'O\'Brien'};false +"'say ""hi""'";"{$: 'say ""hi""'}";true +"'say ""hi""'";{$: null};false +'\u005A\u00FCrich';{$: 'Zürich'};false;question: string literals have no escape sequences, so a \u escape in a cell never matches the character +'\u005A\u00FCrich';{$: 'Zurich'};false +'\u005A\u00FCrich';{$: '\\u005A\\u00FCrich'};true +'\u005A\u00FCrich';{$: null};false +# Empty-string and null cells +'';{$: ''};true +'';{$: ' '};false +'';{$: 'x'};false +'';{$: null};false +'';{};false +'';{$: 0};false +'';{$: false};false +'';{$: []};false +'', null;{$: ''};true +'', null;{$: ' '};false +'', null;{$: 'x'};false +'', null;{$: null};true +'', null;{};true +'', null;{$: 0};false +'', null;{$: false};false +'', null;{$: []};false +null;{$: ''};false +null;{$: ' '};false +null;{$: 'x'};false +null;{$: null};true +null;{};true +null;{$: 0};false +null;{$: false};false +null;{$: []};false +!= '';{$: ''};false +!= '';{$: ' '};true +!= '';{$: 'x'};true +!= '';{$: null};true +!= '';{};true +!= '';{$: 0};true +!= '';{$: false};true +!= '';{$: []};true +!= '' and != null;{$: ''};false +!= '' and != null;{$: ' '};true +!= '' and != null;{$: 'x'};true +!= '' and != null;{$: null};false +!= '' and != null;{};false +!= '' and != null;{$: 0};true +!= '' and != null;{$: false};true +!= '' and != null;{$: []};true +$ == '' or $ == null;{$: ''};true +$ == '' or $ == null;{$: ' '};false +$ == '' or $ == null;{$: 'x'};false +$ == '' or $ == null;{$: null};true +$ == '' or $ == null;{};true +$ == '' or $ == null;{$: 0};false +$ == '' or $ == null;{$: false};false +$ == '' or $ == null;{$: []};false +# Enum values that look like other types +'1';{$: '1'};true +'1';{$: 1};false +'1';{$: 'true'};false +'1';{$: true};false +'1';{$: 'null'};false +'1';{$: null};false +'1';{$: '1.0'};false +'1';{$: 1.0};false +'1';{};false +'true';{$: '1'};false +'true';{$: 1};false +'true';{$: 'true'};true +'true';{$: true};false +'true';{$: 'null'};false +'true';{$: null};false +'true';{$: '1.0'};false +'true';{$: 1.0};false +'true';{};false +'null';{$: '1'};false +'null';{$: 1};false +'null';{$: 'true'};false +'null';{$: true};false +'null';{$: 'null'};true +'null';{$: null};false +'null';{$: '1.0'};false +'null';{$: 1.0};false +'null';{};false +'1', 1;{$: '1'};true +'1', 1;{$: 1};true +'1', 1;{$: 'true'};false +'1', 1;{$: true};false +'1', 1;{$: 'null'};false +'1', 1;{$: null};false +'1', 1;{$: '1.0'};false +'1', 1;{$: 1.0};true +'1', 1;{};false +'true', true;{$: '1'};false +'true', true;{$: 1};false +'true', true;{$: 'true'};true +'true', true;{$: true};true +'true', true;{$: 'null'};false +'true', true;{$: null};false +'true', true;{$: '1.0'};false +'true', true;{$: 1.0};false +'true', true;{};false +# Status codes: an enum column of a first-hit table +'APPROVED';{$: 'APPROVED'};true +'APPROVED';{$: 'approved'};false +'APPROVED';{$: 'PENDING'};false +'APPROVED';{$: 'REJECTED'};false +'APPROVED';{$: 'REVIEW'};false +'APPROVED';{$: 'PENDING_REVIEW'};false +'APPROVED';{$: ''};false +'APPROVED';{$: null};false +'APPROVED';{};false +'APPROVED';{$: 0};false +'PENDING', 'REVIEW';{$: 'APPROVED'};false +'PENDING', 'REVIEW';{$: 'approved'};false +'PENDING', 'REVIEW';{$: 'PENDING'};true +'PENDING', 'REVIEW';{$: 'REJECTED'};false +'PENDING', 'REVIEW';{$: 'REVIEW'};true +'PENDING', 'REVIEW';{$: 'PENDING_REVIEW'};false +'PENDING', 'REVIEW';{$: ''};false +'PENDING', 'REVIEW';{$: null};false +'PENDING', 'REVIEW';{};false +'PENDING', 'REVIEW';{$: 0};false +'REJECTED';{$: 'APPROVED'};false +'REJECTED';{$: 'approved'};false +'REJECTED';{$: 'PENDING'};false +'REJECTED';{$: 'REJECTED'};true +'REJECTED';{$: 'REVIEW'};false +'REJECTED';{$: 'PENDING_REVIEW'};false +'REJECTED';{$: ''};false +'REJECTED';{$: null};false +'REJECTED';{};false +'REJECTED';{$: 0};false +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 'APPROVED'};false +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 'approved'};true +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 'PENDING'};false +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 'REJECTED'};false +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 'REVIEW'};false +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 'PENDING_REVIEW'};true +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: ''};true +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: null};true +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{};true +not in ['APPROVED', 'PENDING', 'REVIEW', 'REJECTED'];{$: 0};true diff --git a/core/expression/tests/spec/unary/12-mixed-lists.csv b/core/expression/tests/spec/unary/12-mixed-lists.csv new file mode 100644 index 00000000..bcee726d --- /dev/null +++ b/core/expression/tests/spec/unary/12-mixed-lists.csv @@ -0,0 +1,308 @@ +expression (string);input (json 5);output (json 5);note +# Values and comparisons in one list +< 0, 10, > 100;{$: -1};true +< 0, 10, > 100;{$: -0.01};true +< 0, 10, > 100;{$: 0};false +< 0, 10, > 100;{$: 5};false +< 0, 10, > 100;{$: 10};true +< 0, 10, > 100;{$: 10.0};true +< 0, 10, > 100;{$: 11};false +< 0, 10, > 100;{$: 100};false +< 0, 10, > 100;{$: 100.01};true +< 0, 10, > 100;{$: 1000};true +< 0, 10, > 100;{$: null};!error +< 0, 10, > 100;{};!error +< 0, 10, > 100;{$: '10'};!error +< 0, 10, > 100;{$: true};!error +10, < 0, > 100;{$: -1};true +10, < 0, > 100;{$: -0.01};true +10, < 0, > 100;{$: 0};false +10, < 0, > 100;{$: 5};false +10, < 0, > 100;{$: 10};true +10, < 0, > 100;{$: 10.0};true +10, < 0, > 100;{$: 11};false +10, < 0, > 100;{$: 100};false +10, < 0, > 100;{$: 100.01};true +10, < 0, > 100;{$: 1000};true +10, < 0, > 100;{$: null};!error +10, < 0, > 100;{};!error +10, < 0, > 100;{$: '10'};!error +10, < 0, > 100;{$: true};!error +10, > 100, < 0;{$: -1};true +10, > 100, < 0;{$: -0.01};true +10, > 100, < 0;{$: 0};false +10, > 100, < 0;{$: 5};false +10, > 100, < 0;{$: 10};true +10, > 100, < 0;{$: 10.0};true +10, > 100, < 0;{$: 11};false +10, > 100, < 0;{$: 100};false +10, > 100, < 0;{$: 100.01};true +10, > 100, < 0;{$: 1000};true +10, > 100, < 0;{$: null};!error +10, > 100, < 0;{};!error +10, > 100, < 0;{$: '10'};!error +10, > 100, < 0;{$: true};!error +0, [1..5], > 9;{$: 0};true +0, [1..5], > 9;{$: 0.5};false +0, [1..5], > 9;{$: 1};true +0, [1..5], > 9;{$: 3};true +0, [1..5], > 9;{$: 5};true +0, [1..5], > 9;{$: 5.5};false +0, [1..5], > 9;{$: 9};false +0, [1..5], > 9;{$: 9.01};true +0, [1..5], > 9;{$: null};!error +0, [1..5], > 9;{};!error +0, [1..5], > 9;{$: '0'};!error +1, 2, 3, 5, 8, 13;{$: 1};true +1, 2, 3, 5, 8, 13;{$: 2};true +1, 2, 3, 5, 8, 13;{$: 3};true +1, 2, 3, 5, 8, 13;{$: 4};false +1, 2, 3, 5, 8, 13;{$: 5};true +1, 2, 3, 5, 8, 13;{$: 8};true +1, 2, 3, 5, 8, 13;{$: 13};true +1, 2, 3, 5, 8, 13;{$: 13.0};true +1, 2, 3, 5, 8, 13;{$: 21};false +1, 2, 3, 5, 8, 13;{$: 0};false +1, 2, 3, 5, 8, 13;{$: null};false +1, 2, 3, 5, 8, 13;{$: '1'};false +-1, 0, 1;{$: -1};true +-1, 0, 1;{$: -0};true +-1, 0, 1;{$: 0};true +-1, 0, 1;{$: 0.0};true +-1, 0, 1;{$: 1};true +-1, 0, 1;{$: 2};false +-1, 0, 1;{$: -2};false +-1, 0, 1;{$: null};false +-1, 0, 1;{$: false};false +0.5, 1.5, 2.5;{$: 0.5};true +0.5, 1.5, 2.5;{$: 0.50};true +0.5, 1.5, 2.5;{$: 1};false +0.5, 1.5, 2.5;{$: 1.5};true +0.5, 1.5, 2.5;{$: 2.5};true +0.5, 1.5, 2.5;{$: 2.49};false +0.5, 1.5, 2.5;{$: null};false +# A list with null next to comparisons +null, > 0;{$: null};true +null, > 0;{};true +null, > 0;{$: -1};false +null, > 0;{$: 0};false +null, > 0;{$: 1};true +null, > 0;{$: 50};true +null, > 0;{$: ''};!error +null, > 0;{$: 'x'};!error +null, > 0;{$: false};!error +> 0, null;{$: null};!error;"question: a list entry errors on a type mismatch even when a later entry would match; order of entries changes the outcome" +> 0, null;{};!error;"question: a list entry errors on a type mismatch even when a later entry would match; order of entries changes the outcome" +> 0, null;{$: -1};false +> 0, null;{$: 0};false +> 0, null;{$: 1};true +> 0, null;{$: 50};true +> 0, null;{$: ''};!error +> 0, null;{$: 'x'};!error +> 0, null;{$: false};!error +null, [1..10];{$: null};true +null, [1..10];{};true +null, [1..10];{$: -1};false +null, [1..10];{$: 0};false +null, [1..10];{$: 1};true +null, [1..10];{$: 50};false +null, [1..10];{$: ''};!error +null, [1..10];{$: 'x'};!error +null, [1..10];{$: false};!error +null, 0;{$: null};true +null, 0;{};true +null, 0;{$: -1};false +null, 0;{$: 0};true +null, 0;{$: 1};false +null, 0;{$: 50};false +null, 0;{$: ''};false +null, 0;{$: 'x'};false +null, 0;{$: false};false +null, '';{$: null};true +null, '';{};true +null, '';{$: -1};false +null, '';{$: 0};false +null, '';{$: 1};false +null, '';{$: 50};false +null, '';{$: ''};true +null, '';{$: 'x'};false +null, '';{$: false};false +'', null, 'N/A';{$: null};true +'', null, 'N/A';{};true +'', null, 'N/A';{$: -1};false +'', null, 'N/A';{$: 0};false +'', null, 'N/A';{$: 1};false +'', null, 'N/A';{$: 50};false +'', null, 'N/A';{$: ''};true +'', null, 'N/A';{$: 'x'};false +'', null, 'N/A';{$: false};false +'', null, 'N/A';{$: 'N/A'};true +'', null, 'N/A';{$: 'n/a'};false +# Strings next to comparisons: a string row reaching a comparison errors +'a', 'b', > 5;{$: 'a'};true +'a', 'b', > 5;{$: 'b'};true +'a', 'b', > 5;{$: 'c'};!error +'a', 'b', > 5;{$: 3};false +'a', 'b', > 5;{$: 6};true +'a', 'b', > 5;{$: null};!error +'a', 'b', > 5;{};!error +'a', 'b', > 5;{$: true};!error +> 5, 'a', 'b';{$: 'a'};!error;"question: a list entry errors on a type mismatch even when a later entry would match; order of entries changes the outcome" +> 5, 'a', 'b';{$: 'b'};!error;"question: a list entry errors on a type mismatch even when a later entry would match; order of entries changes the outcome" +> 5, 'a', 'b';{$: 'c'};!error +> 5, 'a', 'b';{$: 3};false +> 5, 'a', 'b';{$: 6};true +> 5, 'a', 'b';{$: null};!error +> 5, 'a', 'b';{};!error +> 5, 'a', 'b';{$: true};!error +'a', [1..5];{$: 'a'};true +'a', [1..5];{$: 'b'};!error +'a', [1..5];{$: 'c'};!error +'a', [1..5];{$: 3};true +'a', [1..5];{$: 6};false +'a', [1..5];{$: null};!error +'a', [1..5];{};!error +'a', [1..5];{$: true};!error +# Comma binds loosest, `and` inside an entry +> 5 and < 10, 20;{$: 5};false +> 5 and < 10, 20;{$: 6};true +> 5 and < 10, 20;{$: 7};true +> 5 and < 10, 20;{$: 9.99};true +> 5 and < 10, 20;{$: 10};false +> 5 and < 10, 20;{$: 15};false +> 5 and < 10, 20;{$: 20};true +> 5 and < 10, 20;{$: 20.0};true +> 5 and < 10, 20;{$: 25};false +> 5 and < 10, 20;{$: null};!error +20, > 5 and < 10;{$: 5};false +20, > 5 and < 10;{$: 6};true +20, > 5 and < 10;{$: 7};true +20, > 5 and < 10;{$: 9.99};true +20, > 5 and < 10;{$: 10};false +20, > 5 and < 10;{$: 15};false +20, > 5 and < 10;{$: 20};true;"bug: unary joins are folded left to right, giving (20, > 5) and < 10; each comma entry should be its own test" +20, > 5 and < 10;{$: 20.0};true;"bug: unary joins are folded left to right, giving (20, > 5) and < 10; each comma entry should be its own test" +20, > 5 and < 10;{$: 25};false +20, > 5 and < 10;{$: null};!error +> 5 and < 10, > 15 and < 25;{$: 5};false +> 5 and < 10, > 15 and < 25;{$: 6};true +> 5 and < 10, > 15 and < 25;{$: 7};true +> 5 and < 10, > 15 and < 25;{$: 9.99};true +> 5 and < 10, > 15 and < 25;{$: 10};false +> 5 and < 10, > 15 and < 25;{$: 15};false +> 5 and < 10, > 15 and < 25;{$: 20};true +> 5 and < 10, > 15 and < 25;{$: 20.0};true +> 5 and < 10, > 15 and < 25;{$: 25};false +> 5 and < 10, > 15 and < 25;{$: null};!error +[0..10] and != 7, 20;{$: 5};true +[0..10] and != 7, 20;{$: 6};true +[0..10] and != 7, 20;{$: 7};false +[0..10] and != 7, 20;{$: 9.99};true +[0..10] and != 7, 20;{$: 10};true +[0..10] and != 7, 20;{$: 15};false +[0..10] and != 7, 20;{$: 20};true +[0..10] and != 7, 20;{$: 20.0};true +[0..10] and != 7, 20;{$: 25};false +[0..10] and != 7, 20;{$: null};!error +[0..10] and != 7, 20;{$: 0};true +# `or` between list entries +10 or 20 or > 100;{$: -1};false +10 or 20 or > 100;{$: -0.01};false +10 or 20 or > 100;{$: 0};false +10 or 20 or > 100;{$: 5};false +10 or 20 or > 100;{$: 10};true +10 or 20 or > 100;{$: 10.0};true +10 or 20 or > 100;{$: 11};false +10 or 20 or > 100;{$: 100};false +10 or 20 or > 100;{$: 100.01};true +10 or 20 or > 100;{$: 1000};true +10 or 20 or > 100;{$: null};!error +10 or 20 or > 100;{};!error +10 or 20 or > 100;{$: '10'};!error +10 or 20 or > 100;{$: true};!error +10, 20 or > 100;{$: -1};false +10, 20 or > 100;{$: -0.01};false +10, 20 or > 100;{$: 0};false +10, 20 or > 100;{$: 5};false +10, 20 or > 100;{$: 10};true +10, 20 or > 100;{$: 10.0};true +10, 20 or > 100;{$: 11};false +10, 20 or > 100;{$: 100};false +10, 20 or > 100;{$: 100.01};true +10, 20 or > 100;{$: 1000};true +10, 20 or > 100;{$: null};!error +10, 20 or > 100;{};!error +10, 20 or > 100;{$: '10'};!error +10, 20 or > 100;{$: true};!error +< 0 or 10, 20;{$: -1};true +< 0 or 10, 20;{$: -0.01};true +< 0 or 10, 20;{$: 0};false +< 0 or 10, 20;{$: 5};false +< 0 or 10, 20;{$: 10};true +< 0 or 10, 20;{$: 10.0};true +< 0 or 10, 20;{$: 11};false +< 0 or 10, 20;{$: 100};false +< 0 or 10, 20;{$: 100.01};false +< 0 or 10, 20;{$: 1000};false +< 0 or 10, 20;{$: null};!error +< 0 or 10, 20;{};!error +< 0 or 10, 20;{$: '10'};!error +< 0 or 10, 20;{$: true};!error +# Array literal entries next to scalars +[1, 2], 10;{$: 1};true +[1, 2], 10;{$: 2};true +[1, 2], 10;{$: 3};false +[1, 2], 10;{$: 4};false +[1, 2], 10;{$: 10};true +[1, 2], 10;{$: null};false +[1, 2], 10;{$: 'x'};false +10, [1, 2];{$: 1};true +10, [1, 2];{$: 2};true +10, [1, 2];{$: 3};false +10, [1, 2];{$: 4};false +10, [1, 2];{$: 10};true +10, [1, 2];{$: null};false +10, [1, 2];{$: 'x'};false +[1, 2], [3], > 5;{$: 1};true +[1, 2], [3], > 5;{$: 2};true +[1, 2], [3], > 5;{$: 3};true +[1, 2], [3], > 5;{$: 4};false +[1, 2], [3], > 5;{$: 10};true +[1, 2], [3], > 5;{$: null};!error +[1, 2], [3], > 5;{$: 'x'};!error +# Boolean flags with null +true;{$: true};true +true;{$: false};false +true;{$: null};false +true;{};false +true;{$: 1};false +true;{$: 0};false +true;{$: 'true'};false +false, null;{$: true};false +false, null;{$: false};true +false, null;{$: null};true +false, null;{};true +false, null;{$: 1};false +false, null;{$: 0};false +false, null;{$: 'true'};false +true, false;{$: true};true +true, false;{$: false};true +true, false;{$: null};false +true, false;{};false +true, false;{$: 1};false +true, false;{$: 0};false +true, false;{$: 'true'};false +!= true;{$: true};false +!= true;{$: false};true +!= true;{$: null};true +!= true;{};true +!= true;{$: 1};true +!= true;{$: 0};true +!= true;{$: 'true'};true +$ == true or $ == null;{$: true};true +$ == true or $ == null;{$: false};false +$ == true or $ == null;{$: null};true +$ == true or $ == null;{};true +$ == true or $ == null;{$: 1};false +$ == true or $ == null;{$: 0};false +$ == true or $ == null;{$: 'true'};false diff --git a/core/expression/tests/spec/unary/13-date-cells.csv b/core/expression/tests/spec/unary/13-date-cells.csv new file mode 100644 index 00000000..4bdcab7c --- /dev/null +++ b/core/expression/tests/spec/unary/13-date-cells.csv @@ -0,0 +1,143 @@ +expression (string);input (json 5);output (json 5);note +# Cutoff from another field +d($) <= d(cutoff);{$: '2024-06-30', cutoff: '2024-06-30'};true +d($) <= d(cutoff);{$: '2024-06-30T00:00:01Z', cutoff: '2024-06-30'};false +d($) <= d(cutoff);{$: '2024-01-01', cutoff: '2024-06-30'};true +d($) <= d(cutoff);{$: '2024-07-01', cutoff: '2024-06-30'};false +d($) <= d(cutoff);{$: '2024-06-29T23:59:59Z', cutoff: '2024-06-30'};true +d($) <= d(cutoff);{$: '2024-06-30', cutoff: '2024-06-29'};false +d($) <= d(cutoff);{$: '2024-06-30'};false;question: d(null) is an invalid date, so ordering against a missing cutoff is false instead of an error +d($).isBefore(d(cutoff));{$: '2024-06-29', cutoff: '2024-06-30'};true +d($).isBefore(d(cutoff));{$: '2024-06-30', cutoff: '2024-06-30'};false +d($).isBefore(d(cutoff));{$: '2024-07-01', cutoff: '2024-06-30'};false +d($).isBefore(d(cutoff));{$: '1970-01-01', cutoff: '2024-06-30'};true +d($).isBefore(d(cutoff));{$: '2024-06-29T23:59:59.999Z', cutoff: '2024-06-30'};true +d($).isBefore(d(cutoff));{$: '2024-06-30T00:00:00+02:00', cutoff: '2024-06-30'};true +d($).isBefore(d(cutoff));{$: '2024-06-30T00:00:00-02:00', cutoff: '2024-06-30'};false +d($).isSameOrAfter(d(cutoff));{$: '2024-06-30', cutoff: '2024-06-30'};true +d($).isSameOrAfter(d(cutoff));{$: '2024-06-29', cutoff: '2024-06-30'};false +d($).isSameOrAfter(d(cutoff));{$: '2025-01-01', cutoff: '2024-06-30'};true +d($).isSameOrAfter(d(cutoff));{$: '2024-06-30T00:00:00+01:00', cutoff: '2024-06-30'};false +d($) >= d(start) and d($) < d(end);{$: '2024-01-01', start: '2024-01-01', end: '2024-04-01'};true +d($) >= d(start) and d($) < d(end);{$: '2024-03-31T23:59:59Z', start: '2024-01-01', end: '2024-04-01'};true +d($) >= d(start) and d($) < d(end);{$: '2024-04-01', start: '2024-01-01', end: '2024-04-01'};false +d($) >= d(start) and d($) < d(end);{$: '2023-12-31', start: '2024-01-01', end: '2024-04-01'};false +d($) >= d(start) and d($) < d(end);{$: '2024-02-29', start: '2024-01-01', end: '2024-04-01'};true +d($) >= d(start) and d($) < d(end);{$: '2024-05-01', start: '2024-04-01', end: '2024-07-01'};true +d($) in [d(start)..d(end)];{$: '2024-01-01', start: '2024-01-01', end: '2024-03-31'};true +d($) in [d(start)..d(end)];{$: '2024-03-31', start: '2024-01-01', end: '2024-03-31'};true +d($) in [d(start)..d(end)];{$: '2024-03-31T00:00:01Z', start: '2024-01-01', end: '2024-03-31'};false +d($) in [d(start)..d(end)];{$: '2024-04-01', start: '2024-01-01', end: '2024-03-31'};false +d($) in [d(start)..d(end)];{$: '2024-02-10', start: '2024-01-01', end: '2024-03-31'};true +# Calendar parts +d($).year() == 2024;{$: '2024-01-01'};true +d($).year() == 2024;{$: '2024-12-31'};true +d($).year() == 2024;{$: '2023-12-31T23:59:59Z'};false +d($).year() == 2024;{$: '2025-01-01'};false +d($).year() == 2024;{$: '2024-12-31T23:00:00-02:00'};false +d($).month() == 2 and d($).day() == 29;{$: '2024-02-29'};true +d($).month() == 2 and d($).day() == 29;{$: '2028-02-29'};true +d($).month() == 2 and d($).day() == 29;{$: '2024-02-28'};false +d($).month() == 2 and d($).day() == 29;{$: '2024-03-01'};false +d($).month() == 2 and d($).day() == 29;{$: '2023-03-01'};false +d($).quarter() == 2;{$: '2024-04-01'};true +d($).quarter() == 2;{$: '2024-06-30'};true +d($).quarter() == 2;{$: '2024-03-31'};false +d($).quarter() == 2;{$: '2024-07-01'};false +d($).quarter() == 2;{$: '2024-05-15T12:00:00Z'};true +d($).weekday() >= 6;{$: '2024-06-01'};true +d($).weekday() >= 6;{$: '2024-06-02'};true +d($).weekday() >= 6;{$: '2024-06-03'};false +d($).weekday() >= 6;{$: '2024-05-31'};false +d($).weekday() >= 6;{$: '2024-06-05'};false +d($).weekday() in [1, 2, 3, 4, 5];{$: '2024-06-01'};false +d($).weekday() in [1, 2, 3, 4, 5];{$: '2024-06-02'};false +d($).weekday() in [1, 2, 3, 4, 5];{$: '2024-06-03'};true +d($).weekday() in [1, 2, 3, 4, 5];{$: '2024-05-31'};true +d($).hour() < 9 or d($).hour() >= 17;{$: '2024-06-03T08:59:59Z'};true +d($).hour() < 9 or d($).hour() >= 17;{$: '2024-06-03T09:00:00Z'};false +d($).hour() < 9 or d($).hour() >= 17;{$: '2024-06-03T16:59:59Z'};false +d($).hour() < 9 or d($).hour() >= 17;{$: '2024-06-03T17:00:00Z'};true +d($).hour() < 9 or d($).hour() >= 17;{$: '2024-06-03'};true +d($).isLeapYear();{$: '2024-06-01'};true +d($).isLeapYear();{$: '2023-06-01'};false +d($).isLeapYear();{$: '2000-01-01'};true +d($).isLeapYear();{$: '1900-01-01'};false +d($).isLeapYear();{$: '2100-12-31'};false +d($).dayOfYear() <= 31;{$: '2024-01-01'};true +d($).dayOfYear() <= 31;{$: '2024-01-31'};true +d($).dayOfYear() <= 31;{$: '2024-02-01'};false +d($).dayOfYear() <= 31;{$: '2024-12-31'};false +# Age and tenure from a birth or start date +d().diff(d($), 'year') >= 18;{$: '2007-03-20'};true +d().diff(d($), 'year') >= 18;{$: '2007-03-21'};false +d().diff(d($), 'year') >= 18;{$: '2007-03-19'};true +d().diff(d($), 'year') >= 18;{$: '1960-01-01'};true +d().diff(d($), 'year') >= 18;{$: '2010-01-01'};false +d().diff(d($), 'year') >= 18;{$: '2025-03-20'};false +d($).diff(d('2024-01-01'), 'day') > 30;{$: '2024-02-01'};true +d($).diff(d('2024-01-01'), 'day') > 30;{$: '2024-01-31'};false +d($).diff(d('2024-01-01'), 'day') > 30;{$: '2024-01-31T23:59:59Z'};false +d($).diff(d('2024-01-01'), 'day') > 30;{$: '2023-12-01'};false +d($).diff(d('2024-01-01'), 'day') > 30;{$: '2025-01-01'};true +d($).add(30, 'd') < d();{$: '2025-02-17'};true +d($).add(30, 'd') < d();{$: '2025-02-18T10:15:30Z'};false +d($).add(30, 'd') < d();{$: '2025-02-18T10:15:29Z'};true +d($).add(30, 'd') < d();{$: '2025-03-01'};false +d($).add(30, 'd') < d();{$: '2020-01-01'};true +d($).add(1, 'y').isAfter(d('2025-03-20'));{$: '2024-03-21'};true +d($).add(1, 'y').isAfter(d('2025-03-20'));{$: '2024-03-20'};false +d($).add(1, 'y').isAfter(d('2025-03-20'));{$: '2024-03-19'};false +d($).add(1, 'y').isAfter(d('2025-03-20'));{$: '2025-01-01'};true +d($).isSame(d('2024-06-15'), 'month');{$: '2024-06-01'};true +d($).isSame(d('2024-06-15'), 'month');{$: '2024-06-30T23:59:59Z'};true +d($).isSame(d('2024-06-15'), 'month');{$: '2024-07-01'};false +d($).isSame(d('2024-06-15'), 'month');{$: '2023-06-15'};false +d($).isSame(d('2024-06-15'), 'month');{$: '2024-05-31'};false +d($).startOf('month') == d('2024-06-01');{$: '2024-06-15'};true +d($).startOf('month') == d('2024-06-01');{$: '2024-06-01'};true +d($).startOf('month') == d('2024-06-01');{$: '2024-07-01'};false +d($).startOf('month') == d('2024-06-01');{$: '2024-05-31T23:59:59Z'};false +# Relative to the evaluation time (2025-03-20T10:15:30Z) +d($).isToday();{$: '2025-03-20T00:00:00Z'};true +d($).isToday();{$: '2025-03-20T23:59:59Z'};true +d($).isToday();{$: '2025-03-19T23:59:59Z'};false +d($).isToday();{$: '2025-03-21'};false +d($).isYesterday();{$: '2025-03-19'};true +d($).isYesterday();{$: '2025-03-19T23:59:59Z'};true +d($).isYesterday();{$: '2025-03-20'};false +d($).isYesterday();{$: '2025-03-18'};false +d($).isTomorrow();{$: '2025-03-21'};true +d($).isTomorrow();{$: '2025-03-20'};false +d($).isTomorrow();{$: '2025-03-22'};false +d($) > d().sub(7, 'd');{$: '2025-03-14'};true +d($) > d().sub(7, 'd');{$: '2025-03-13T10:15:30Z'};false +d($) > d().sub(7, 'd');{$: '2025-03-13T10:15:31Z'};true +d($) > d().sub(7, 'd');{$: '2025-03-01'};false +d($) > d().sub(7, 'd');{$: '2025-04-01'};true +# Timestamps, offsets and bad values in the same column +d($) >= d('2024-01-01');{$: '2024-01-01'};true +d($) >= d('2024-01-01');{$: '2023-12-31T23:59:59Z'};false +d($) >= d('2024-01-01');{$: '2024-01-01T01:00:00+02:00'};false +d($) >= d('2024-01-01');{$: '2024-01-01T00:00:00-01:00'};true +d($) >= d('2024-01-01');{$: 1704067200000};true +d($) >= d('2024-01-01');{$: 1704067199999};false +d($) >= d('2024-01-01');{$: '2024-01-01 00:00'};true +d($) >= d('2024-01-01');{$: 'bad'};false +d($) >= d('2024-01-01');{$: ''};false +d($) >= d('2024-01-01');{$: null};false +d($) >= d('2024-01-01');{};false +d($).isValid();{$: '2024-01-01'};true +d($).isValid();{$: '2024-13-01'};false +d($).isValid();{$: '2024-02-30'};false +d($).isValid();{$: '24-01-01'};true +d($).isValid();{$: 1704067200000};true +d($).isValid();{$: ''};false +d($).isValid();{$: null};false +d($).isValid();{};false +d($).isValid();{$: true};false +d($).year() == 2024;{$: 1704067200000};true +d($).year() == 2024;{$: 0};false +d($).year() == 2024;{$: 'bad'};false +d($).year() == 2024;{$: null};false +d($).year() == 2024;{};false diff --git a/core/expression/tests/spec/unary/14-field-cells.csv b/core/expression/tests/spec/unary/14-field-cells.csv new file mode 100644 index 00000000..44dbc906 --- /dev/null +++ b/core/expression/tests/spec/unary/14-field-cells.csv @@ -0,0 +1,166 @@ +expression (string);input (json 5);output (json 5);note +# Threshold from another field +$ > limit;{$: 5, limit: 3};true +$ > limit;{$: 3, limit: 3};false +$ > limit;{$: 2, limit: 3};false +$ > limit;{$: 3.01, limit: 3.00};true +$ > limit;{$: 5, limit: -10};true +$ > limit;{$: 5};!error +$ > limit;{$: 5, limit: null};!error +$ > limit;{$: 5, limit: '3'};!error +$ > limit;{$: null, limit: 3};!error +$ > limit;{$: '5', limit: 3};!error +$ <= limit;{$: 5, limit: 3};false +$ <= limit;{$: 3, limit: 3};true +$ <= limit;{$: 2, limit: 3};true +$ <= limit;{$: 3.01, limit: 3.00};false +$ <= limit;{$: 5, limit: -10};false +$ <= limit;{$: 5};!error +$ <= limit;{$: 5, limit: null};!error +$ <= limit;{$: 5, limit: '3'};!error +$ <= limit;{$: null, limit: 3};!error +$ <= limit;{$: '5', limit: 3};!error +limit < $;{$: 5, limit: 3};true +limit < $;{$: 3, limit: 3};false +limit < $;{$: 2, limit: 3};false +limit < $;{$: 3.01, limit: 3.00};true +limit < $;{$: 5, limit: -10};true +limit < $;{$: 5};!error +limit < $;{$: 5, limit: null};!error +limit < $;{$: 5, limit: '3'};!error +limit < $;{$: null, limit: 3};!error +limit < $;{$: '5', limit: 3};!error +$ > limit * 1.1;{$: 3.31, limit: 3};true +$ > limit * 1.1;{$: 3.3, limit: 3};false +$ > limit * 1.1;{$: 100, limit: 90};true +$ > limit * 1.1;{$: 99, limit: 90};false +$ > limit * 1.1;{$: 5};!error +$ > limit * 1.1;{$: null, limit: 3};!error +$ <= (limit ?? 100);{$: 100};true +$ <= (limit ?? 100);{$: 101};false +$ <= (limit ?? 100);{$: 50, limit: 40};false +$ <= (limit ?? 100);{$: 40, limit: 40};true +$ <= (limit ?? 100);{$: 5, limit: null};true +$ <= (limit ?? 100);{$: null, limit: 40};!error +# Range bounds from fields +$ >= min and $ <= max;{$: 5, min: 1, max: 10};true +$ >= min and $ <= max;{$: 1, min: 1, max: 10};true +$ >= min and $ <= max;{$: 10, min: 1, max: 10};true +$ >= min and $ <= max;{$: 0.99, min: 1, max: 10};false +$ >= min and $ <= max;{$: 10.01, min: 1, max: 10};false +$ >= min and $ <= max;{$: 5, min: 10, max: 1};false +$ >= min and $ <= max;{$: 5, min: 1};!error +$ >= min and $ <= max;{$: 5, max: 10};!error +$ >= min and $ <= max;{$: null, min: 1, max: 10};!error +$ >= min and $ <= max;{$: 5, min: 5, max: 5};true +>= min and <= max;{$: 5, min: 1, max: 10};true +>= min and <= max;{$: 1, min: 1, max: 10};true +>= min and <= max;{$: 10, min: 1, max: 10};true +>= min and <= max;{$: 0.99, min: 1, max: 10};false +>= min and <= max;{$: 10.01, min: 1, max: 10};false +>= min and <= max;{$: 5, min: 10, max: 1};false +>= min and <= max;{$: 5, min: 1};!error +>= min and <= max;{$: 5, max: 10};!error +>= min and <= max;{$: null, min: 1, max: 10};!error +>= min and <= max;{$: 5, min: 5, max: 5};true +[min..max];{$: 5, min: 1, max: 10};true +[min..max];{$: 1, min: 1, max: 10};true +[min..max];{$: 10, min: 1, max: 10};true +[min..max];{$: 0.99, min: 1, max: 10};false +[min..max];{$: 10.01, min: 1, max: 10};false +[min..max];{$: 5, min: 10, max: 1};false +[min..max];{$: 5, min: 1};!error +[min..max];{$: 5, max: 10};!error +[min..max];{$: null, min: 1, max: 10};!error +[min..max];{$: 5, min: 5, max: 5};true +$ in [min..max];{$: 5, min: 1, max: 10};true +$ in [min..max];{$: 1, min: 1, max: 10};true +$ in [min..max];{$: 10, min: 1, max: 10};true +$ in [min..max];{$: 0.99, min: 1, max: 10};false +$ in [min..max];{$: 10.01, min: 1, max: 10};false +$ in [min..max];{$: 5, min: 10, max: 1};false +$ in [min..max];{$: 5, min: 1};!error +$ in [min..max];{$: 5, max: 10};!error +$ in [min..max];{$: null, min: 1, max: 10};!error +$ in [min..max];{$: 5, min: 5, max: 5};true +(min..max);{$: 5, min: 1, max: 10};true +(min..max);{$: 1, min: 1, max: 10};false +(min..max);{$: 10, min: 1, max: 10};false +(min..max);{$: 0.99, min: 1, max: 10};false +(min..max);{$: 10.01, min: 1, max: 10};false +(min..max);{$: 5, min: 10, max: 1};false +(min..max);{$: 5, min: 1};!error +(min..max);{$: 5, max: 10};!error +(min..max);{$: null, min: 1, max: 10};!error +(min..max);{$: 5, min: 5, max: 5};false +# Allowed values from a field +$ in allowed;{$: 'a', allowed: ['a', 'b']};true +$ in allowed;{$: 'c', allowed: ['a', 'b']};false +$ in allowed;{$: 'a', allowed: []};false +$ in allowed;{$: 1, allowed: [1, 2]};true +$ in allowed;{$: 1.0, allowed: [1, 2]};true +$ in allowed;{$: '1', allowed: [1, 2]};false +$ in allowed;{$: null, allowed: ['a', null]};true +$ in allowed;{$: null, allowed: ['a']};false +$ in allowed;{$: 'a'};!error +$ in allowed;{$: 'a', allowed: null};!error +$ in allowed;{$: 'a', allowed: 'abc'};!error +in allowed;{$: 'a', allowed: ['a', 'b']};true +in allowed;{$: 'c', allowed: ['a', 'b']};false +in allowed;{$: 'a', allowed: []};false +in allowed;{$: 1, allowed: [1, 2]};true +in allowed;{$: 1.0, allowed: [1, 2]};true +in allowed;{$: '1', allowed: [1, 2]};false +in allowed;{$: null, allowed: ['a', null]};true +in allowed;{$: null, allowed: ['a']};false +in allowed;{$: 'a'};!error +in allowed;{$: 'a', allowed: null};!error +in allowed;{$: 'a', allowed: 'abc'};!error +$ not in allowed;{$: 'a', allowed: ['a', 'b']};false +$ not in allowed;{$: 'c', allowed: ['a', 'b']};true +$ not in allowed;{$: 'a', allowed: []};true +$ not in allowed;{$: 1, allowed: [1, 2]};false +$ not in allowed;{$: 1.0, allowed: [1, 2]};false +$ not in allowed;{$: '1', allowed: [1, 2]};true +$ not in allowed;{$: null, allowed: ['a', null]};false +$ not in allowed;{$: null, allowed: ['a']};true +$ not in allowed;{$: 'a'};!error +$ not in allowed;{$: 'a', allowed: null};!error +$ not in allowed;{$: 'a', allowed: 'abc'};!error +$ in [first, second];{$: 'a', first: 'a', second: 'b'};true +$ in [first, second];{$: 'b', first: 'a', second: 'b'};true +$ in [first, second];{$: 'c', first: 'a', second: 'b'};false +$ in [first, second];{$: null, first: 'a'};true +$ in [first, second];{$: 'a'};false +$ in [first, second];{$: null};true +first, second;{$: 'a', first: 'a', second: 'b'};true +first, second;{$: 'b', first: 'a', second: 'b'};true +first, second;{$: 'c', first: 'a', second: 'b'};false +first, second;{$: null, first: 'a'};true +first, second;{$: 'a'};false +first, second;{$: 5, first: 5};true +# Nested and computed field references +== customer.tier;{$: 'gold', customer: {tier: 'gold'}};true +== customer.tier;{$: 'gold', customer: {tier: 'silver'}};false +== customer.tier;{$: 'gold', customer: {}};false +== customer.tier;{$: 'gold', customer: null};false +== customer.tier;{$: null, customer: {}};true +== customer.tier;{$: null};true +$ <= limits[tier];{$: 500, limits: {gold: 1000, silver: 500}, tier: 'gold'};true +$ <= limits[tier];{$: 1000, limits: {gold: 1000, silver: 500}, tier: 'gold'};true +$ <= limits[tier];{$: 501, limits: {gold: 1000, silver: 500}, tier: 'silver'};false +$ <= limits[tier];{$: 500, limits: {gold: 1000, silver: 500}, tier: 'silver'};true +$ <= limits[tier];{$: 1, limits: {gold: 1000}, tier: 'bronze'};!error +$ == other;{$: 1, other: 1};true +$ == other;{$: 1, other: 1.00};true +$ == other;{$: 1, other: '1'};false +$ == other;{$: true, other: true};true +$ == other;{$: null, other: null};true +$ == other;{$: null};true +$ == other;{$: 'a', other: 'A'};false +$ == other;{$: [1], other: [1]};true;bug: == on arrays is always false, even for equal arrays +$ >= sum(parts);{$: 6, parts: [1, 2, 3]};true +$ >= sum(parts);{$: 5, parts: [1, 2, 3]};false +$ >= sum(parts);{$: 0, parts: []};true +$ >= sum(parts);{$: 1};!error +$ >= sum(parts);{$: null, parts: [1]};!error diff --git a/core/expression/tests/spec/unary/15-function-cells.csv b/core/expression/tests/spec/unary/15-function-cells.csv new file mode 100644 index 00000000..b23d53fe --- /dev/null +++ b/core/expression/tests/spec/unary/15-function-cells.csv @@ -0,0 +1,347 @@ +expression (string);input (json 5);output (json 5);note +# Prefix and suffix cells +startsWith($, 'GB');{$: 'GB29NWBK60161331926819'};true +startsWith($, 'GB');{$: 'gb29NWBK'};false +startsWith($, 'GB');{$: 'GB'};true +startsWith($, 'GB');{$: 'G'};false +startsWith($, 'GB');{$: ''};false +startsWith($, 'GB');{$: 'DE89370400440532013000'};false +startsWith($, 'GB');{$: 'XGB12'};false +startsWith($, 'GB');{$: ' GB12'};false +startsWith($, 'GB');{$: null};!error +startsWith($, 'GB');{};!error +startsWith($, 'GB');{$: 1234};!error +startsWith($, 'GB');{$: true};!error +not startsWith($, 'GB');{$: 'GB29NWBK60161331926819'};false +not startsWith($, 'GB');{$: 'gb29NWBK'};true +not startsWith($, 'GB');{$: 'GB'};false +not startsWith($, 'GB');{$: 'G'};true +not startsWith($, 'GB');{$: ''};true +not startsWith($, 'GB');{$: 'DE89370400440532013000'};true +not startsWith($, 'GB');{$: 'XGB12'};true +not startsWith($, 'GB');{$: ' GB12'};true +not startsWith($, 'GB');{$: null};!error +not startsWith($, 'GB');{};!error +not startsWith($, 'GB');{$: 1234};!error +not startsWith($, 'GB');{$: true};!error +startsWith(upper($), 'GB');{$: 'GB29NWBK60161331926819'};true +startsWith(upper($), 'GB');{$: 'gb29NWBK'};true +startsWith(upper($), 'GB');{$: 'GB'};true +startsWith(upper($), 'GB');{$: 'G'};false +startsWith(upper($), 'GB');{$: ''};false +startsWith(upper($), 'GB');{$: 'DE89370400440532013000'};false +startsWith(upper($), 'GB');{$: 'XGB12'};false +startsWith(upper($), 'GB');{$: ' GB12'};false +startsWith(upper($), 'GB');{$: null};!error +startsWith(upper($), 'GB');{};!error +startsWith(upper($), 'GB');{$: 1234};!error +startsWith(upper($), 'GB');{$: true};!error +startsWith($, 'GB') or startsWith($, 'DE');{$: 'GB29NWBK60161331926819'};true +startsWith($, 'GB') or startsWith($, 'DE');{$: 'gb29NWBK'};false +startsWith($, 'GB') or startsWith($, 'DE');{$: 'GB'};true +startsWith($, 'GB') or startsWith($, 'DE');{$: 'G'};false +startsWith($, 'GB') or startsWith($, 'DE');{$: ''};false +startsWith($, 'GB') or startsWith($, 'DE');{$: 'DE89370400440532013000'};true +startsWith($, 'GB') or startsWith($, 'DE');{$: 'XGB12'};false +startsWith($, 'GB') or startsWith($, 'DE');{$: ' GB12'};false +startsWith($, 'GB') or startsWith($, 'DE');{$: null};!error +startsWith($, 'GB') or startsWith($, 'DE');{};!error +startsWith($, 'GB') or startsWith($, 'DE');{$: 1234};!error +startsWith($, 'GB') or startsWith($, 'DE');{$: true};!error +endsWith($, '19');{$: 'GB29NWBK60161331926819'};true +endsWith($, '19');{$: 'gb29NWBK'};false +endsWith($, '19');{$: 'GB'};false +endsWith($, '19');{$: 'G'};false +endsWith($, '19');{$: ''};false +endsWith($, '19');{$: 'DE89370400440532013000'};false +endsWith($, '19');{$: 'XGB12'};false +endsWith($, '19');{$: ' GB12'};false +endsWith($, '19');{$: null};!error +endsWith($, '19');{};!error +endsWith($, '19');{$: 1234};!error +endsWith($, '19');{$: true};!error +startsWith($, '');{$: 'GB29NWBK60161331926819'};true +startsWith($, '');{$: 'gb29NWBK'};true +startsWith($, '');{$: 'GB'};true +startsWith($, '');{$: 'G'};true +startsWith($, '');{$: ''};true +startsWith($, '');{$: 'DE89370400440532013000'};true +startsWith($, '');{$: 'XGB12'};true +startsWith($, '');{$: ' GB12'};true +startsWith($, '');{$: null};!error +startsWith($, '');{};!error +startsWith($, '');{$: 1234};!error +startsWith($, '');{$: true};!error +# Length cells +len($) == 5;{$: '12345'};true +len($) == 5;{$: '1234'};false +len($) == 5;{$: '123456'};false +len($) == 5;{$: ''};false +len($) == 5;{$: ' 345'};true +len($) == 5;{$: 'ABCDE'};true +len($) == 5;{$: null};!error +len($) == 5;{};!error +len($) == 5;{$: 12345};!error +len($) == 5;{$: ['1', '2', '3', '4', '5']};true +len($) >= 4 and len($) <= 5;{$: '12345'};true +len($) >= 4 and len($) <= 5;{$: '1234'};true +len($) >= 4 and len($) <= 5;{$: '123456'};false +len($) >= 4 and len($) <= 5;{$: ''};false +len($) >= 4 and len($) <= 5;{$: ' 345'};true +len($) >= 4 and len($) <= 5;{$: 'ABCDE'};true +len($) >= 4 and len($) <= 5;{$: null};!error +len($) >= 4 and len($) <= 5;{};!error +len($) >= 4 and len($) <= 5;{$: 12345};!error +len($) >= 4 and len($) <= 5;{$: ['1', '2', '3', '4', '5']};true +len(trim($)) == 5;{$: '12345'};true +len(trim($)) == 5;{$: '1234'};false +len(trim($)) == 5;{$: '123456'};false +len(trim($)) == 5;{$: ''};false +len(trim($)) == 5;{$: ' 345'};false +len(trim($)) == 5;{$: 'ABCDE'};true +len(trim($)) == 5;{$: null};!error +len(trim($)) == 5;{};!error +len(trim($)) == 5;{$: 12345};!error +len(trim($)) == 5;{$: ['1', '2', '3', '4', '5']};!error +len($) in [4..6];{$: '12345'};true +len($) in [4..6];{$: '1234'};true +len($) in [4..6];{$: '123456'};true +len($) in [4..6];{$: ''};false +len($) in [4..6];{$: ' 345'};true +len($) in [4..6];{$: 'ABCDE'};true +len($) in [4..6];{$: null};!error +len($) in [4..6];{};!error +len($) in [4..6];{$: 12345};!error +len($) in [4..6];{$: ['1', '2', '3', '4', '5']};true +len($) > 0;{$: '12345'};true +len($) > 0;{$: '1234'};true +len($) > 0;{$: '123456'};true +len($) > 0;{$: ''};false +len($) > 0;{$: ' 345'};true +len($) > 0;{$: 'ABCDE'};true +len($) > 0;{$: null};!error +len($) > 0;{};!error +len($) > 0;{$: 12345};!error +len($) > 0;{$: ['1', '2', '3', '4', '5']};true +# Contains cells +contains($, 'x');{$: 'express delivery'};true +contains($, 'x');{$: 'Express'};true +contains($, 'x');{$: 'EXPRESS'};false +contains($, 'x');{$: 'x'};true +contains($, 'x');{$: ''};false +contains($, 'x');{$: 'none'};false +contains($, 'x');{$: null};!error +contains($, 'x');{};!error +contains($, 'x');{$: 7};!error +contains($, 'x');{$: ['express']};false +contains($, 'x');{$: ['x', 'y']};true +contains($, 'express');{$: 'express delivery'};true +contains($, 'express');{$: 'Express'};false +contains($, 'express');{$: 'EXPRESS'};false +contains($, 'express');{$: 'x'};false +contains($, 'express');{$: ''};false +contains($, 'express');{$: 'none'};false +contains($, 'express');{$: null};!error +contains($, 'express');{};!error +contains($, 'express');{$: 7};!error +contains($, 'express');{$: ['express']};true +contains($, 'express');{$: ['x', 'y']};false +contains(lower($), 'express');{$: 'express delivery'};true +contains(lower($), 'express');{$: 'Express'};true +contains(lower($), 'express');{$: 'EXPRESS'};true +contains(lower($), 'express');{$: 'x'};false +contains(lower($), 'express');{$: ''};false +contains(lower($), 'express');{$: 'none'};false +contains(lower($), 'express');{$: null};!error +contains(lower($), 'express');{};!error +contains(lower($), 'express');{$: 7};!error +contains(lower($), 'express');{$: ['express']};!error +contains(lower($), 'express');{$: ['x', 'y']};!error +not contains($, 'x');{$: 'express delivery'};false +not contains($, 'x');{$: 'Express'};false +not contains($, 'x');{$: 'EXPRESS'};true +not contains($, 'x');{$: 'x'};false +not contains($, 'x');{$: ''};true +not contains($, 'x');{$: 'none'};true +not contains($, 'x');{$: null};!error +not contains($, 'x');{};!error +not contains($, 'x');{$: 7};!error +not contains($, 'x');{$: ['express']};true +not contains($, 'x');{$: ['x', 'y']};false +contains($, 'express') and not contains($, 'none');{$: 'express delivery'};true +contains($, 'express') and not contains($, 'none');{$: 'Express'};false +contains($, 'express') and not contains($, 'none');{$: 'EXPRESS'};false +contains($, 'express') and not contains($, 'none');{$: 'x'};false +contains($, 'express') and not contains($, 'none');{$: ''};false +contains($, 'express') and not contains($, 'none');{$: 'none'};false +contains($, 'express') and not contains($, 'none');{$: null};!error +contains($, 'express') and not contains($, 'none');{};!error +contains($, 'express') and not contains($, 'none');{$: 7};!error +contains($, 'express') and not contains($, 'none');{$: ['express']};true +contains($, 'express') and not contains($, 'none');{$: ['x', 'y']};false +# Regular-expression cells +matches($, '^[A-Z]{2}[0-9]+$');{$: 'AB123'};true +matches($, '^[A-Z]{2}[0-9]+$');{$: 'AB1'};true +matches($, '^[A-Z]{2}[0-9]+$');{$: 'ab123'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: 'A1'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: 'ABC123'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: 'AB123X'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: 'AB 123'};false +matches($, '^[A-Z]{2}[0-9]+$');{$: ''};false +matches($, '^[A-Z]{2}[0-9]+$');{$: null};!error +matches($, '^[A-Z]{2}[0-9]+$');{};!error +matches($, '^[A-Z]{2}[0-9]+$');{$: 123};!error +matches($, '[0-9]');{$: 'AB123'};true +matches($, '[0-9]');{$: 'AB1'};true +matches($, '[0-9]');{$: 'ab123'};true +matches($, '[0-9]');{$: 'A1'};true +matches($, '[0-9]');{$: 'ABC123'};true +matches($, '[0-9]');{$: 'AB123X'};true +matches($, '[0-9]');{$: 'AB 123'};true +matches($, '[0-9]');{$: ''};false +matches($, '[0-9]');{$: null};!error +matches($, '[0-9]');{};!error +matches($, '[0-9]');{$: 123};!error +matches($, '(?i)^ab');{$: 'AB123'};true +matches($, '(?i)^ab');{$: 'AB1'};true +matches($, '(?i)^ab');{$: 'ab123'};true +matches($, '(?i)^ab');{$: 'A1'};false +matches($, '(?i)^ab');{$: 'ABC123'};true +matches($, '(?i)^ab');{$: 'AB123X'};true +matches($, '(?i)^ab');{$: 'AB 123'};true +matches($, '(?i)^ab');{$: ''};false +matches($, '(?i)^ab');{$: null};!error +matches($, '(?i)^ab');{};!error +matches($, '(?i)^ab');{$: 123};!error +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'AB123'};true +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'AB1'};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'ab123'};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'A1'};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'ABC123'};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'AB123X'};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 'AB 123'};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: ''};false +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: null};!error +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{};!error +matches($, '^[A-Z]{2}[0-9]{3}$') or $ == null;{$: 123};!error +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'AB123'};true +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'AB1'};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'ab123'};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'A1'};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'ABC123'};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'AB123X'};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 'AB 123'};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: ''};false +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: null};true +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{};true +$ == null or matches($, '^[A-Z]{2}[0-9]{3}$');{$: 123};!error +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: 'a@b.co'};true +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: 'john.doe@example.com'};true +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: 'no-at-sign'};false +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: '@b.co'};false +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: 'a@b'};false +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: ''};false +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: null};!error +matches($, '^[^@]+@[^@]+\.[a-z]+$');{$: 5};!error +endsWith(lower($), '@example.com');{$: 'a@b.co'};false +endsWith(lower($), '@example.com');{$: 'john.doe@example.com'};true +endsWith(lower($), '@example.com');{$: 'no-at-sign'};false +endsWith(lower($), '@example.com');{$: '@b.co'};false +endsWith(lower($), '@example.com');{$: 'a@b'};false +endsWith(lower($), '@example.com');{$: ''};false +endsWith(lower($), '@example.com');{$: null};!error +endsWith(lower($), '@example.com');{$: 5};!error +matches($, '[');{$: 'a'};!error +matches($, '[');{$: '['};!error +matches($, '[');{$: null};!error +# Numeric-string cells +isNumeric($);{$: '12'};true +isNumeric($);{$: '12.5'};true +isNumeric($);{$: '-3'};true +isNumeric($);{$: '0'};true +isNumeric($);{$: 'abc'};false +isNumeric($);{$: ''};false +isNumeric($);{$: ' 12'};true +isNumeric($);{$: '1e3'};true +isNumeric($);{$: null};false +isNumeric($);{};false +isNumeric($);{$: 12};true +isNumeric($);{$: true};false +isNumeric($) and number($) > 10;{$: '12'};true +isNumeric($) and number($) > 10;{$: '12.5'};true +isNumeric($) and number($) > 10;{$: '-3'};false +isNumeric($) and number($) > 10;{$: '0'};false +isNumeric($) and number($) > 10;{$: 'abc'};false +isNumeric($) and number($) > 10;{$: ''};false +isNumeric($) and number($) > 10;{$: ' 12'};true +isNumeric($) and number($) > 10;{$: '1e3'};true +isNumeric($) and number($) > 10;{$: null};false +isNumeric($) and number($) > 10;{};false +isNumeric($) and number($) > 10;{$: 12};true +isNumeric($) and number($) > 10;{$: true};false +# Type checks in a cell +type($) == 'string';{$: 'a'};true +type($) == 'string';{$: 1};false +type($) == 'string';{$: 1.5};false +type($) == 'string';{$: true};false +type($) == 'string';{$: null};false +type($) == 'string';{};false +type($) == 'string';{$: [1]};false +type($) == 'string';{$: {a: 1}};false +type($) == 'number';{$: 'a'};false +type($) == 'number';{$: 1};true +type($) == 'number';{$: 1.5};true +type($) == 'number';{$: true};false +type($) == 'number';{$: null};false +type($) == 'number';{};false +type($) == 'number';{$: [1]};false +type($) == 'number';{$: {a: 1}};false +type($) in ['array', 'object'];{$: 'a'};false +type($) in ['array', 'object'];{$: 1};false +type($) in ['array', 'object'];{$: 1.5};false +type($) in ['array', 'object'];{$: true};false +type($) in ['array', 'object'];{$: null};false +type($) in ['array', 'object'];{};false +type($) in ['array', 'object'];{$: [1]};true +type($) in ['array', 'object'];{$: {a: 1}};true +type($) != 'null';{$: 'a'};true +type($) != 'null';{$: 1};true +type($) != 'null';{$: 1.5};true +type($) != 'null';{$: true};true +type($) != 'null';{$: null};false +type($) != 'null';{};false +type($) != 'null';{$: [1]};true +type($) != 'null';{$: {a: 1}};true +# Rounding helpers before a comparison +round($) == 5;{$: 4.4};false +round($) == 5;{$: 4.5};true +round($) == 5;{$: 4.49};false +round($) == 5;{$: 5.5};false +round($) == 5;{$: -4.5};false +round($) == 5;{$: 10};false +round($) == 5;{$: null};!error +round($) == 5;{$: '4.5'};!error +floor($) == 4;{$: 4.4};true +floor($) == 4;{$: 4.5};true +floor($) == 4;{$: 4.49};true +floor($) == 4;{$: 5.5};false +floor($) == 4;{$: -4.5};false +floor($) == 4;{$: 10};false +floor($) == 4;{$: null};!error +floor($) == 4;{$: '4.5'};!error +ceil($) >= 5;{$: 4.4};true +ceil($) >= 5;{$: 4.5};true +ceil($) >= 5;{$: 4.49};true +ceil($) >= 5;{$: 5.5};true +ceil($) >= 5;{$: -4.5};false +ceil($) >= 5;{$: 10};true +ceil($) >= 5;{$: null};!error +ceil($) >= 5;{$: '4.5'};!error +abs($) > 4.45;{$: 4.4};false +abs($) > 4.45;{$: 4.5};true +abs($) > 4.45;{$: 4.49};true +abs($) > 4.45;{$: 5.5};true +abs($) > 4.45;{$: -4.5};true +abs($) > 4.45;{$: 10};true +abs($) > 4.45;{$: null};!error +abs($) > 4.45;{$: '4.5'};!error diff --git a/core/expression/tests/spec/unary/16-collection-cells.csv b/core/expression/tests/spec/unary/16-collection-cells.csv new file mode 100644 index 00000000..cf326fb3 --- /dev/null +++ b/core/expression/tests/spec/unary/16-collection-cells.csv @@ -0,0 +1,172 @@ +expression (string);input (json 5);output (json 5);note +# some / all / none / one over a numeric array $ +some($, # > 5);{$: [1, 6]};true +some($, # > 5);{$: [1, 2]};false +some($, # > 5);{$: []};false +some($, # > 5);{$: [6]};true +some($, # > 5);{$: [5]};false +some($, # > 5);{$: [5.01]};true +some($, # > 5);{$: [-1, 10, 0]};true +some($, # > 5);{$: null};!error +some($, # > 5);{};!error +some($, # > 5);{$: 6};!error +some($, # > 5);{$: [1, 'x', 7]};!error +all($, # > 0);{$: [1, 6]};true +all($, # > 0);{$: [1, 2]};true +all($, # > 0);{$: []};true +all($, # > 0);{$: [6]};true +all($, # > 0);{$: [5]};true +all($, # > 0);{$: [5.01]};true +all($, # > 0);{$: [-1, 10, 0]};false +all($, # > 0);{$: null};!error +all($, # > 0);{};!error +all($, # > 0);{$: 6};!error +all($, # > 0);{$: [1, 'x', 7]};!error +none($, # < 0);{$: [1, 6]};true +none($, # < 0);{$: [1, 2]};true +none($, # < 0);{$: []};true +none($, # < 0);{$: [6]};true +none($, # < 0);{$: [5]};true +none($, # < 0);{$: [5.01]};true +none($, # < 0);{$: [-1, 10, 0]};false +none($, # < 0);{$: null};!error +none($, # < 0);{};!error +none($, # < 0);{$: 6};!error +none($, # < 0);{$: [1, 'x', 7]};!error +one($, # > 5);{$: [1, 6]};true +one($, # > 5);{$: [6, 7]};false +one($, # > 5);{$: []};false +one($, # > 5);{$: [6]};true +one($, # > 5);{$: [1, 2]};false +one($, # > 5);{$: null};!error +one($, # > 5);{$: [6, 'x']};!error +# count and sums compared with thresholds +count($, # > 0) >= 2;{$: [1, 6]};true +count($, # > 0) >= 2;{$: [1, 2]};true +count($, # > 0) >= 2;{$: []};false +count($, # > 0) >= 2;{$: [6]};false +count($, # > 0) >= 2;{$: [5]};false +count($, # > 0) >= 2;{$: [5.01]};false +count($, # > 0) >= 2;{$: [-1, 10, 0]};false +count($, # > 0) >= 2;{$: null};!error +count($, # > 0) >= 2;{};!error +count($, # > 0) >= 2;{$: 6};!error +count($, # > 0) >= 2;{$: [1, 2, 3]};true +count($, # > 0) >= 2;{$: [0, 0, 1]};false +len($) > 0 and all($, # >= 1);{$: [1, 2]};true +len($) > 0 and all($, # >= 1);{$: []};false +len($) > 0 and all($, # >= 1);{$: [0]};false +len($) > 0 and all($, # >= 1);{$: [1]};true +len($) > 0 and all($, # >= 1);{$: null};!error +len($) > 0 and all($, # >= 1);{$: 'ab'};!error +sum($) >= 100;{$: [50, 50]};true +sum($) >= 100;{$: [99.99]};false +sum($) >= 100;{$: []};false +sum($) >= 100;{$: [33.34, 33.33, 33.33]};true +sum($) >= 100;{$: null};!error +sum($) >= 100;{$: [1, 'a']};!error +max($) < 10;{$: [1, 9]};true +max($) < 10;{$: [1, 10]};false +max($) < 10;{$: [9.99]};true +max($) < 10;{$: null};!error +max($) < 10;{$: []};!error;question: max of an empty array errors instead of null or false +# String arrays against allowed sets +all($, # in ['a', 'b']);{$: ['a', 'b']};true +all($, # in ['a', 'b']);{$: ['a']};true +all($, # in ['a', 'b']);{$: []};true +all($, # in ['a', 'b']);{$: ['c']};false +all($, # in ['a', 'b']);{$: ['a', 'c']};false +all($, # in ['a', 'b']);{$: ['A']};false +all($, # in ['a', 'b']);{$: null};!error +all($, # in ['a', 'b']);{};!error +all($, # in ['a', 'b']);{$: 'a'};!error +all($, # in ['a', 'b']);{$: [1]};false +some($, # in ['a', 'b']);{$: ['a', 'b']};true +some($, # in ['a', 'b']);{$: ['a']};true +some($, # in ['a', 'b']);{$: []};false +some($, # in ['a', 'b']);{$: ['c']};false +some($, # in ['a', 'b']);{$: ['a', 'c']};true +some($, # in ['a', 'b']);{$: ['A']};false +some($, # in ['a', 'b']);{$: null};!error +some($, # in ['a', 'b']);{};!error +some($, # in ['a', 'b']);{$: 'a'};!error +some($, # in ['a', 'b']);{$: [1]};false +none($, # == 'c');{$: ['a', 'b']};true +none($, # == 'c');{$: ['a']};true +none($, # == 'c');{$: []};true +none($, # == 'c');{$: ['c']};false +none($, # == 'c');{$: ['a', 'c']};false +none($, # == 'c');{$: ['A']};true +none($, # == 'c');{$: null};!error +none($, # == 'c');{};!error +none($, # == 'c');{$: 'a'};!error +none($, # == 'c');{$: [1]};true +'a' in $;{$: ['a', 'b']};true +'a' in $;{$: ['a']};true +'a' in $;{$: []};false +'a' in $;{$: ['c']};false +'a' in $;{$: ['a', 'c']};true +'a' in $;{$: ['A']};false +'a' in $;{$: null};!error +'a' in $;{};!error +'a' in $;{$: 'a'};!error +'a' in $;{$: [1]};false +contains($, 'a');{$: ['a', 'b']};true +contains($, 'a');{$: ['a']};true +contains($, 'a');{$: []};false +contains($, 'a');{$: ['c']};false +contains($, 'a');{$: ['a', 'c']};true +contains($, 'a');{$: ['A']};false +contains($, 'a');{$: null};!error +contains($, 'a');{};!error +contains($, 'a');{$: 'a'};true +contains($, 'a');{$: [1]};false +some($, startsWith(#, 'a'));{$: ['ab']};true +some($, startsWith(#, 'a'));{$: ['ba']};false +some($, startsWith(#, 'a'));{$: []};false +some($, startsWith(#, 'a'));{$: ['x', 'abc']};true +some($, startsWith(#, 'a'));{$: null};!error +some($, startsWith(#, 'a'));{$: [1]};!error +some($, lower(#) == 'vip');{$: ['VIP']};true +some($, lower(#) == 'vip');{$: ['vip']};true +some($, lower(#) == 'vip');{$: ['Vip', 'x']};true +some($, lower(#) == 'vip');{$: ['v']};false +some($, lower(#) == 'vip');{$: []};false +some($, lower(#) == 'vip');{$: null};!error +# Arrays of objects +some($, #.qty > 10);{$: [{qty: 1, price: 10}, {qty: 3, price: 5}]};false +some($, #.qty > 10);{$: [{qty: 0, price: 10}]};false +some($, #.qty > 10);{$: []};false +some($, #.qty > 10);{$: [{price: 10}]};!error +some($, #.qty > 10);{$: null};!error +some($, #.qty > 10);{$: [{qty: 11, price: 1}]};true +all($, #.qty > 0);{$: [{qty: 1, price: 10}, {qty: 3, price: 5}]};true +all($, #.qty > 0);{$: [{qty: 0, price: 10}]};false +all($, #.qty > 0);{$: []};true +all($, #.qty > 0);{$: [{price: 10}]};!error +all($, #.qty > 0);{$: null};!error +all($, #.qty > 0);{$: [{qty: 11, price: 1}]};true +sum(map($, #.qty * #.price)) > 20;{$: [{qty: 1, price: 10}, {qty: 3, price: 5}]};true +sum(map($, #.qty * #.price)) > 20;{$: [{qty: 0, price: 10}]};false +sum(map($, #.qty * #.price)) > 20;{$: []};false +sum(map($, #.qty * #.price)) > 20;{$: [{price: 10}]};!error +sum(map($, #.qty * #.price)) > 20;{$: null};!error +sum(map($, #.qty * #.price)) > 20;{$: [{qty: 11, price: 1}]};false +count($, #.price >= 10) == 1;{$: [{qty: 1, price: 10}, {qty: 3, price: 5}]};true +count($, #.price >= 10) == 1;{$: [{qty: 0, price: 10}]};true +count($, #.price >= 10) == 1;{$: []};false +count($, #.price >= 10) == 1;{$: [{price: 10}]};true +count($, #.price >= 10) == 1;{$: null};!error +count($, #.price >= 10) == 1;{$: [{qty: 11, price: 1}]};false +# Closures reading another field +some($, # > limit);{$: [1, 5], limit: 4};true +some($, # > limit);{$: [1, 5], limit: 5};false +some($, # > limit);{$: [], limit: 0};false +some($, # > limit);{$: [1]};!error +some($, # > limit);{$: null, limit: 1};!error +some($, # > limit);{$: [10], limit: 9.99};true +all($, # in allowed);{$: ['a'], allowed: ['a', 'b']};true +all($, # in allowed);{$: ['a', 'z'], allowed: ['a', 'b']};false +all($, # in allowed);{$: [], allowed: []};true +all($, # in allowed);{$: ['a'], allowed: []};false +all($, # in allowed);{$: ['a']};!error diff --git a/core/expression/tests/spec/unary/17-object-arith-cells.csv b/core/expression/tests/spec/unary/17-object-arith-cells.csv new file mode 100644 index 00000000..f3ae3010 --- /dev/null +++ b/core/expression/tests/spec/unary/17-object-arith-cells.csv @@ -0,0 +1,273 @@ +expression (string);input (json 5);output (json 5);note +# $ as an object: field tests +$.tier == 'gold';{$: {tier: 'gold', age: 30, score: 720}};true +$.tier == 'gold';{$: {tier: 'silver', age: 17, score: 580}};false +$.tier == 'gold';{$: {tier: 'GOLD', age: 65, score: 850}};false +$.tier == 'gold';{$: {tier: null, age: null}};false +$.tier == 'gold';{$: {}};false +$.tier == 'gold';{$: null};false +$.tier == 'gold';{};false +$.tier == 'gold';{$: 'gold'};false +$.tier == 'gold';{$: 5};false +$.tier in ['gold', 'platinum'];{$: {tier: 'gold', age: 30, score: 720}};true +$.tier in ['gold', 'platinum'];{$: {tier: 'silver', age: 17, score: 580}};false +$.tier in ['gold', 'platinum'];{$: {tier: 'GOLD', age: 65, score: 850}};false +$.tier in ['gold', 'platinum'];{$: {tier: null, age: null}};false +$.tier in ['gold', 'platinum'];{$: {}};false +$.tier in ['gold', 'platinum'];{$: null};false +$.tier in ['gold', 'platinum'];{};false +$.tier in ['gold', 'platinum'];{$: 'gold'};false +$.tier in ['gold', 'platinum'];{$: 5};false +$.tier != 'gold';{$: {tier: 'gold', age: 30, score: 720}};false +$.tier != 'gold';{$: {tier: 'silver', age: 17, score: 580}};true +$.tier != 'gold';{$: {tier: 'GOLD', age: 65, score: 850}};true +$.tier != 'gold';{$: {tier: null, age: null}};true +$.tier != 'gold';{$: {}};true +$.tier != 'gold';{$: null};true +$.tier != 'gold';{};true +$.tier != 'gold';{$: 'gold'};true +$.tier != 'gold';{$: 5};true +$.age >= 18;{$: {tier: 'gold', age: 30, score: 720}};true +$.age >= 18;{$: {tier: 'silver', age: 17, score: 580}};false +$.age >= 18;{$: {tier: 'GOLD', age: 65, score: 850}};true +$.age >= 18;{$: {tier: null, age: null}};!error +$.age >= 18;{$: {}};!error +$.age >= 18;{$: null};!error +$.age >= 18;{};!error +$.age >= 18;{$: 'gold'};!error +$.age >= 18;{$: 5};!error +$.age >= 18 and $.score > 700;{$: {tier: 'gold', age: 30, score: 720}};true +$.age >= 18 and $.score > 700;{$: {tier: 'silver', age: 17, score: 580}};false +$.age >= 18 and $.score > 700;{$: {tier: 'GOLD', age: 65, score: 850}};true +$.age >= 18 and $.score > 700;{$: {tier: null, age: null}};!error +$.age >= 18 and $.score > 700;{$: {}};!error +$.age >= 18 and $.score > 700;{$: null};!error +$.age >= 18 and $.score > 700;{};!error +$.age >= 18 and $.score > 700;{$: 'gold'};!error +$.age >= 18 and $.score > 700;{$: 5};!error +$.tier == 'gold' and $.score > 700;{$: {tier: 'gold', age: 30, score: 720}};true +$.tier == 'gold' and $.score > 700;{$: {tier: 'silver', age: 17, score: 580}};false +$.tier == 'gold' and $.score > 700;{$: {tier: 'GOLD', age: 65, score: 850}};false +$.tier == 'gold' and $.score > 700;{$: {tier: null, age: null}};false +$.tier == 'gold' and $.score > 700;{$: {}};false +$.tier == 'gold' and $.score > 700;{$: null};false +$.tier == 'gold' and $.score > 700;{};false +$.tier == 'gold' and $.score > 700;{$: 'gold'};false +$.tier == 'gold' and $.score > 700;{$: 5};false +$.score in [700..800];{$: {tier: 'gold', age: 30, score: 720}};true +$.score in [700..800];{$: {tier: 'silver', age: 17, score: 580}};false +$.score in [700..800];{$: {tier: 'GOLD', age: 65, score: 850}};false +$.score in [700..800];{$: {tier: null, age: null}};!error +$.score in [700..800];{$: {}};!error +$.score in [700..800];{$: null};!error +$.score in [700..800];{};!error +$.score in [700..800];{$: 'gold'};!error +$.score in [700..800];{$: 5};!error +lower($.tier ?? '') == 'gold';{$: {tier: 'gold', age: 30, score: 720}};true +lower($.tier ?? '') == 'gold';{$: {tier: 'silver', age: 17, score: 580}};false +lower($.tier ?? '') == 'gold';{$: {tier: 'GOLD', age: 65, score: 850}};true +lower($.tier ?? '') == 'gold';{$: {tier: null, age: null}};false +lower($.tier ?? '') == 'gold';{$: {}};false +lower($.tier ?? '') == 'gold';{$: null};false +lower($.tier ?? '') == 'gold';{};false +lower($.tier ?? '') == 'gold';{$: 'gold'};false +lower($.tier ?? '') == 'gold';{$: 5};false +$.tier == null;{$: {tier: 'gold', age: 30, score: 720}};false +$.tier == null;{$: {tier: 'silver', age: 17, score: 580}};false +$.tier == null;{$: {tier: 'GOLD', age: 65, score: 850}};false +$.tier == null;{$: {tier: null, age: null}};true +$.tier == null;{$: {}};true +$.tier == null;{$: null};true +$.tier == null;{};true +$.tier == null;{$: 'gold'};true +$.tier == null;{$: 5};true +($.age ?? 0) < 18;{$: {tier: 'gold', age: 30, score: 720}};false +($.age ?? 0) < 18;{$: {tier: 'silver', age: 17, score: 580}};true +($.age ?? 0) < 18;{$: {tier: 'GOLD', age: 65, score: 850}};false +($.age ?? 0) < 18;{$: {tier: null, age: null}};true +($.age ?? 0) < 18;{$: {}};true +($.age ?? 0) < 18;{$: null};true +($.age ?? 0) < 18;{};true +($.age ?? 0) < 18;{$: 'gold'};true +($.age ?? 0) < 18;{$: 5};true +# Nested objects and arrays inside $ +$.address.country == 'GB';{$: {address: {country: 'GB', zip: 'SW1A'}}};true +$.address.country == 'GB';{$: {address: {country: 'US'}}};false +$.address.country == 'GB';{$: {address: null}};false +$.address.country == 'GB';{$: {address: {}}};false +$.address.country == 'GB';{$: {}};false +$.address.country == 'GB';{$: null};false +$.address.country in ['GB', 'IE'];{$: {address: {country: 'GB', zip: 'SW1A'}}};true +$.address.country in ['GB', 'IE'];{$: {address: {country: 'US'}}};false +$.address.country in ['GB', 'IE'];{$: {address: null}};false +$.address.country in ['GB', 'IE'];{$: {address: {}}};false +$.address.country in ['GB', 'IE'];{$: {}};false +$.address.country in ['GB', 'IE'];{$: null};false +startsWith($.address.zip ?? '', 'SW');{$: {address: {country: 'GB', zip: 'SW1A'}}};true +startsWith($.address.zip ?? '', 'SW');{$: {address: {country: 'US'}}};false +startsWith($.address.zip ?? '', 'SW');{$: {address: null}};false +startsWith($.address.zip ?? '', 'SW');{$: {address: {}}};false +startsWith($.address.zip ?? '', 'SW');{$: {}};false +startsWith($.address.zip ?? '', 'SW');{$: null};false +'country' in keys($.address ?? {});{$: {address: {country: 'GB', zip: 'SW1A'}}};true +'country' in keys($.address ?? {});{$: {address: {country: 'US'}}};true +'country' in keys($.address ?? {});{$: {address: null}};false +'country' in keys($.address ?? {});{$: {address: {}}};false +'country' in keys($.address ?? {});{$: {}};false +'country' in keys($.address ?? {});{$: null};false +$['address'].country == 'US';{$: {address: {country: 'GB', zip: 'SW1A'}}};false +$['address'].country == 'US';{$: {address: {country: 'US'}}};true +$['address'].country == 'US';{$: {address: null}};false +$['address'].country == 'US';{$: {address: {}}};false +$['address'].country == 'US';{$: {}};false +$['address'].country == 'US';{$: null};false +len($.items ?? []) >= 2;{$: {items: [1, 2, 3]}};true +len($.items ?? []) >= 2;{$: {items: []}};false +len($.items ?? []) >= 2;{$: {items: [10]}};false +len($.items ?? []) >= 2;{$: {}};false +len($.items ?? []) >= 2;{$: null};false +some($.items ?? [], # > 5);{$: {items: [1, 2, 3]}};false +some($.items ?? [], # > 5);{$: {items: []}};false +some($.items ?? [], # > 5);{$: {items: [10]}};true +some($.items ?? [], # > 5);{$: {}};false +some($.items ?? [], # > 5);{$: null};false +# Arithmetic on $ inside a comparison +$ * 1.2 > 100;{$: 100};true +$ * 1.2 > 100;{$: 83.33};false +$ * 1.2 > 100;{$: 83.34};true +$ * 1.2 > 100;{$: 0};false +$ * 1.2 > 100;{$: -100};false +$ * 1.2 > 100;{$: 1000000};true +$ * 1.2 > 100;{$: null};!error +$ * 1.2 > 100;{};!error +$ * 1.2 > 100;{$: '100'};!error +$ * 1.2 > 100;{$: true};!error +$ / 12 <= 1000;{$: 100};true +$ / 12 <= 1000;{$: 83.33};true +$ / 12 <= 1000;{$: 83.34};true +$ / 12 <= 1000;{$: 0};true +$ / 12 <= 1000;{$: -100};true +$ / 12 <= 1000;{$: 1000000};false +$ / 12 <= 1000;{$: null};!error +$ / 12 <= 1000;{};!error +$ / 12 <= 1000;{$: '100'};!error +$ / 12 <= 1000;{$: true};!error +$ / 12 <= 1000;{$: 12000};true +$ / 12 <= 1000;{$: 12000.01};false +$ - 50 >= 0;{$: 100};true +$ - 50 >= 0;{$: 83.33};true +$ - 50 >= 0;{$: 83.34};true +$ - 50 >= 0;{$: 0};false +$ - 50 >= 0;{$: -100};false +$ - 50 >= 0;{$: 1000000};true +$ - 50 >= 0;{$: null};!error +$ - 50 >= 0;{};!error +$ - 50 >= 0;{$: '100'};!error +$ - 50 >= 0;{$: true};!error +$ + 0.1 == 100.1;{$: 100};true +$ + 0.1 == 100.1;{$: 83.33};false +$ + 0.1 == 100.1;{$: 83.34};false +$ + 0.1 == 100.1;{$: 0};false +$ + 0.1 == 100.1;{$: -100};false +$ + 0.1 == 100.1;{$: 1000000};false +$ + 0.1 == 100.1;{$: null};!error +$ + 0.1 == 100.1;{};!error +$ + 0.1 == 100.1;{$: '100'};!error +$ + 0.1 == 100.1;{$: true};!error +abs($ - 100) <= 0.5;{$: 100};true +abs($ - 100) <= 0.5;{$: 83.33};false +abs($ - 100) <= 0.5;{$: 83.34};false +abs($ - 100) <= 0.5;{$: 0};false +abs($ - 100) <= 0.5;{$: -100};false +abs($ - 100) <= 0.5;{$: 1000000};false +abs($ - 100) <= 0.5;{$: null};!error +abs($ - 100) <= 0.5;{};!error +abs($ - 100) <= 0.5;{$: '100'};!error +abs($ - 100) <= 0.5;{$: true};!error +abs($ - 100) <= 0.5;{$: 99.5};true +abs($ - 100) <= 0.5;{$: 100.5};true +abs($ - 100) <= 0.5;{$: 100.51};false +$ % 10 == 0;{$: 100};true +$ % 10 == 0;{$: 83.33};false +$ % 10 == 0;{$: 83.34};false +$ % 10 == 0;{$: 0};true +$ % 10 == 0;{$: -100};true +$ % 10 == 0;{$: 1000000};true +$ % 10 == 0;{$: null};!error +$ % 10 == 0;{};!error +$ % 10 == 0;{$: '100'};!error +$ % 10 == 0;{$: true};!error +$ % 10 == 0;{$: 10.5};false +$ % 10 == 0;{$: -10};true +$ ^ 2 > 50;{$: 7};false +$ ^ 2 > 50;{$: 8};true +$ ^ 2 > 50;{$: -8};true +$ ^ 2 > 50;{$: 7.07};false +$ ^ 2 > 50;{$: 7.08};true +$ ^ 2 > 50;{$: 0};false +$ ^ 2 > 50;{$: null};!error +100 / $ > 2;{$: 10};true +100 / $ > 2;{$: 50};false +100 / $ > 2;{$: 49};true +100 / $ > 2;{$: -1};false +100 / $ > 2;{$: null};!error +100 / $ > 2;{$: 0};!error +# Arithmetic with another field +$ * rate >= 50;{$: 100, rate: 0.5};true +$ * rate >= 50;{$: 99, rate: 0.5};false +$ * rate >= 50;{$: 100, rate: 0};false +$ * rate >= 50;{$: 100};!error +$ * rate >= 50;{$: null, rate: 1};!error +$ * rate >= 50;{$: 500.01, rate: 0.1};true +$ > income * 0.4;{$: 400, income: 1000};false +$ > income * 0.4;{$: 401, income: 1000};true +$ > income * 0.4;{$: 0, income: 0};false +$ > income * 0.4;{$: 1, income: null};!error +($ - base) / base > 0.1;{$: 111, base: 100};true +($ - base) / base > 0.1;{$: 110, base: 100};false +($ - base) / base > 0.1;{$: 90, base: 100};false +($ - base) / base > 0.1;{$: 110.01, base: 100};true +($ - base) / base > 0.1;{$: 5};!error +# Null and missing $ across cell kinds +> 0;{$: null};!error +> 0;{};!error +[1..5];{$: null};!error +[1..5];{};!error +'gold';{$: null};false +'gold';{};false +'gold', 'silver';{$: null};false +'gold', 'silver';{};false +null;{$: null};true +null;{};true +!= 'gold';{$: null};true +!= 'gold';{};true +$ in ['a'];{$: null};false +$ in ['a'];{};false +$ not in ['a'];{$: null};true +$ not in ['a'];{};true +startsWith($, 'a');{$: null};!error +startsWith($, 'a');{};!error +len($) > 0;{$: null};!error +len($) > 0;{};!error +some($, # > 0);{$: null};!error +some($, # > 0);{};!error +$.tier == null;{$: null};true +$.tier == null;{};true +$.tier == 'a';{$: null};false +$.tier == 'a';{};false +$.age > 1;{$: null};!error +$.age > 1;{};!error +$ * 2 > 1;{$: null};!error +$ * 2 > 1;{};!error +d($).isValid();{$: null};false +d($).isValid();{};false +($ ?? 0) >= 0;{$: null};true +($ ?? 0) >= 0;{};true +$ == null or $ > 0;{$: null};true +$ == null or $ > 0;{};true +$ != null and $ > 0;{$: null};false +$ != null and $ > 0;{};false +isNumeric($);{$: null};false +isNumeric($);{};false +type($) == 'null';{$: null};true +type($) == 'null';{};true diff --git a/core/expression/tests/spec/unary/18-date-inputs.csv b/core/expression/tests/spec/unary/18-date-inputs.csv new file mode 100644 index 00000000..21825060 --- /dev/null +++ b/core/expression/tests/spec/unary/18-date-inputs.csv @@ -0,0 +1,77 @@ +expression (string);input (json 5);output (json 5);note +# date inputs as the reference +'2024-03-15';{$: date('2024-03-15')};true +'2024-03-15';{$: date('2024-03-15T10:30:00+02:00')};false +'2024-03-15';{$: date('2024-12-31 23:00')};false +'2024-03-15';{$: '2024-03-15'};true +'2024-03-15';{$: null};false +== '2024-03-15';{$: date('2024-03-15')};true +== '2024-03-15';{$: date('2024-03-15T10:30:00+02:00')};false +== '2024-03-15';{$: date('2024-12-31 23:00')};false +== '2024-03-15';{$: '2024-03-15'};true +== '2024-03-15';{$: null};false +!= '2024-03-15';{$: date('2024-03-15')};false +!= '2024-03-15';{$: date('2024-03-15T10:30:00+02:00')};true +!= '2024-03-15';{$: date('2024-12-31 23:00')};true +!= '2024-03-15';{$: '2024-03-15'};false +!= '2024-03-15';{$: null};true +> '2024-03-01';{$: date('2024-03-15')};true +> '2024-03-01';{$: date('2024-03-15T10:30:00+02:00')};true +> '2024-03-01';{$: date('2024-12-31 23:00')};true +> '2024-03-01';{$: '2024-03-15'};!error +> '2024-03-01';{$: null};!error +<= '2024-03-15';{$: date('2024-03-15')};true +<= '2024-03-15';{$: date('2024-03-15T10:30:00+02:00')};false +<= '2024-03-15';{$: date('2024-12-31 23:00')};false +<= '2024-03-15';{$: '2024-03-15'};!error +<= '2024-03-15';{$: null};!error +[d('2024-03-01')..d('2024-03-31')];{$: date('2024-03-15')};true +[d('2024-03-01')..d('2024-03-31')];{$: date('2024-03-15T10:30:00+02:00')};true +[d('2024-03-01')..d('2024-03-31')];{$: date('2024-12-31 23:00')};false +[d('2024-03-01')..d('2024-03-31')];{$: '2024-03-15'};!error +[d('2024-03-01')..d('2024-03-31')];{$: null};!error +d('2024-03-15');{$: date('2024-03-15')};true +d('2024-03-15');{$: date('2024-03-15T10:30:00+02:00')};false +d('2024-03-15');{$: date('2024-12-31 23:00')};false +d('2024-03-15');{$: '2024-03-15'};true +d('2024-03-15');{$: null};false +'2024-03-15', '2024-12-31';{$: date('2024-03-15')};true +'2024-03-15', '2024-12-31';{$: date('2024-03-15T10:30:00+02:00')};false +'2024-03-15', '2024-12-31';{$: date('2024-12-31 23:00')};false +'2024-03-15', '2024-12-31';{$: '2024-03-15'};true +'2024-03-15', '2024-12-31';{$: null};false +startsWith($, '2024');{$: date('2024-03-15')};true +startsWith($, '2024');{$: date('2024-03-15T10:30:00+02:00')};true +startsWith($, '2024');{$: date('2024-12-31 23:00')};true +startsWith($, '2024');{$: '2024-03-15'};true +startsWith($, '2024');{$: null};!error +len($) > 10;{$: date('2024-03-15')};false +len($) > 10;{$: date('2024-03-15T10:30:00+02:00')};true +len($) > 10;{$: date('2024-12-31 23:00')};true +len($) > 10;{$: '2024-03-15'};false +len($) > 10;{$: null};!error +$.year() == 2024;{$: date('2024-03-15')};true +$.year() == 2024;{$: date('2024-03-15T10:30:00+02:00')};true +$.year() == 2024;{$: date('2024-12-31 23:00')};true +$.year() == 2024;{$: '2024-03-15'};!error +$.year() == 2024;{$: null};!error +d($).month() == 3;{$: date('2024-03-15')};true +d($).month() == 3;{$: date('2024-03-15T10:30:00+02:00')};true +d($).month() == 3;{$: date('2024-12-31 23:00')};false +d($).month() == 3;{$: '2024-03-15'};true +d($).month() == 3;{$: null};false +< d('2025-01-01');{$: date('2024-03-15')};true +< d('2025-01-01');{$: date('2024-03-15T10:30:00+02:00')};true +< d('2025-01-01');{$: date('2024-12-31 23:00')};true +< d('2025-01-01');{$: '2024-03-15'};true +< d('2025-01-01');{$: null};!error +$ == d('2024-03-15T08:30:00Z');{$: date('2024-03-15')};false +$ == d('2024-03-15T08:30:00Z');{$: date('2024-03-15T10:30:00+02:00')};true +$ == d('2024-03-15T08:30:00Z');{$: date('2024-12-31 23:00')};false +$ == d('2024-03-15T08:30:00Z');{$: '2024-03-15'};false +$ == d('2024-03-15T08:30:00Z');{$: null};false +string($) == '2024-03-15';{$: date('2024-03-15')};true +string($) == '2024-03-15';{$: date('2024-03-15T10:30:00+02:00')};false +string($) == '2024-03-15';{$: date('2024-12-31 23:00')};false +string($) == '2024-03-15';{$: '2024-03-15'};true +string($) == '2024-03-15';{$: null};false diff --git a/core/expression/tests/typed.rs b/core/expression/tests/typed.rs new file mode 100644 index 00000000..fa9f0b59 --- /dev/null +++ b/core/expression/tests/typed.rs @@ -0,0 +1,492 @@ +mod conformance; + +use rust_decimal::Decimal; +use std::collections::BTreeMap; +use std::sync::Arc; +use zen_expression::lane::{Column, Fusion, Values}; +use zen_expression::typed::{ + Batch, Class, Data, Hir, List, Lowering, Program, Resolve, Resolved, Slot, +}; +use zen_expression::{ExpressionKind, Variable}; + +#[derive(Clone, Copy, PartialEq)] +enum Seen { + Absent, + Class(Class), + List, + Mixed, +} + +struct Probe<'c> { + rows: &'c [Variable], +} + +enum Store { + Num(Vec), + Text { offsets: Vec, data: String }, + Bool(Vec), +} + +struct Owned { + store: Store, + valid: Vec, +} + +struct OwnedList { + offsets: Vec, + valid: Vec, + fields: Vec, +} + +#[derive(Default)] +struct Tally { + rows: usize, + lowered: usize, + typed: usize, +} + +#[derive(Default)] +struct Report { + files: BTreeMap, + spurious: Vec, + mismatches: Vec, + reasons: BTreeMap, +} + +impl Seen { + fn of(value: &Variable) -> Seen { + match value { + Variable::Null => Seen::Absent, + Variable::Number(_) => Seen::Class(Class::Num), + Variable::String(_) => Seen::Class(Class::Text), + Variable::Bool(_) => Seen::Class(Class::Bool), + Variable::Array(_) => Seen::List, + _ => Seen::Mixed, + } + } + + fn join(self, other: Seen) -> Seen { + match (self, other) { + (Seen::Absent, x) | (x, Seen::Absent) => x, + (x, y) if x == y => x, + _ => Seen::Mixed, + } + } + + fn all<'v>(values: impl Iterator) -> Seen { + values.fold(Seen::Absent, |acc, v| acc.join(Seen::of(v))) + } +} + +impl Probe<'_> { + fn values(&self, path: &str) -> Vec { + self.rows + .iter() + .map(|row| row.dot(path).unwrap_or(Variable::Null)) + .collect() + } + + fn elements(values: &[Variable]) -> Vec { + values + .iter() + .filter_map(|v| match v { + Variable::Array(items) => Some(items.borrow().clone()), + _ => None, + }) + .flatten() + .collect() + } + + fn fields(elements: &[Variable]) -> Option, Class)>> { + if elements.iter().any(|e| matches!(e, Variable::Null)) { + return None; + } + if !elements.iter().all(|e| matches!(e, Variable::Object(_))) { + return match Seen::all(elements.iter()) { + Seen::Class(class) => Some(vec![(Arc::from(""), class)]), + Seen::Absent => Some(Vec::new()), + _ => None, + }; + } + let mut keys: Vec = Vec::new(); + for e in elements { + if let Variable::Object(o) = e { + for (k, _) in o.borrow().iter() { + if !keys.iter().any(|x| x.as_str() == k.as_str()) { + keys.push(k.to_string()); + } + } + } + } + let mut fields = Vec::new(); + for key in keys { + let values: Vec = elements + .iter() + .map(|e| e.dot(&key).unwrap_or(Variable::Null)) + .collect(); + if let Seen::Class(class) = Seen::all(values.iter()) { + fields.push((Arc::from(key.as_str()), class)); + } + } + Some(fields) + } +} + +impl Resolve for Probe<'_> { + fn path(&mut self, path: &str) -> Resolved { + let values = self.values(path); + match Seen::all(values.iter()) { + Seen::Absent => Resolved::Absent, + Seen::Class(class) => Resolved::Column(class), + Seen::List => match Self::fields(&Self::elements(&values)) { + Some(fields) => Resolved::List { fields }, + None => Resolved::Unsupported, + }, + Seen::Mixed => Resolved::Unsupported, + } + } + + fn alias(&mut self, _: &str) -> Resolved { + Resolved::Unsupported + } +} + +impl Owned { + fn build(class: Class, values: &[Variable]) -> Owned { + let mut valid = vec![0u64; values.len().div_ceil(64).max(1)]; + for (i, v) in values.iter().enumerate() { + if !matches!(v, Variable::Null) { + valid[i / 64] |= 1 << (i % 64); + } + } + let store = match class { + Class::Num => Store::Num( + values + .iter() + .map(|v| v.as_number().unwrap_or_default()) + .collect(), + ), + Class::Bool => { + let mut bits = vec![0u64; values.len().div_ceil(64).max(1)]; + for (i, v) in values.iter().enumerate() { + if matches!(v, Variable::Bool(true)) { + bits[i / 64] |= 1 << (i % 64); + } + } + Store::Bool(bits) + } + _ => { + let mut offsets = vec![0i32]; + let mut data = String::new(); + for v in values { + if let Variable::String(s) = v { + data.push_str(s); + } + offsets.push(data.len() as i32); + } + Store::Text { offsets, data } + } + }; + Owned { store, valid } + } + + fn column(&self) -> Column<'_> { + let values = match &self.store { + Store::Num(n) => Values::Dec(n), + Store::Text { offsets, data } => Values::Text { offsets, data }, + Store::Bool(bits) => Values::Bool { bits, offset: 0 }, + }; + Column::with_validity(values, &self.valid, 0) + } +} + +impl Report { + const DATES: [&'static str; 4] = [ + "standard/08-", + "standard/10-05", + "standard/16-", + "standard/18-", + ]; + + fn signature(value: &Variable) -> String { + match value { + Variable::Object(o) => { + let mut keys: Vec = o + .borrow() + .iter() + .map(|(k, v)| format!("{k}:{}", Self::signature(v))) + .collect(); + keys.sort(); + format!("{{{}}}", keys.join(",")) + } + Variable::Array(items) => format!( + "[{}]", + items + .borrow() + .iter() + .map(Self::signature) + .collect::>() + .join(",") + ), + other => other.type_name().to_string(), + } + } + + fn output(slot: &Slot, hir: &Hir, at: usize) -> Variable { + match &slot.data { + Data::Num { .. } => slot.decimal(at).map_or(Variable::Null, Variable::Number), + Data::Bool(_) => slot.boolean(at).map_or(Variable::Null, Variable::Bool), + Data::Code(_) => match (slot.code(at), slot.dict()) { + (Some(c), Some(d)) => hir + .dict(d) + .text(c) + .map_or(Variable::Null, |t| Variable::String(t.into())), + _ => Variable::Null, + }, + Data::Text { .. } => slot + .text(at) + .map_or(Variable::Null, |t| Variable::String(t.into())), + Data::Date(_) => slot.variable(at), + } + } + + fn same(a: &Variable, b: &Variable) -> bool { + a.type_name() == b.type_name() + && conformance::Spec::render(a) == conformance::Spec::render(b) + } + + fn group(&mut self, expression: &str, cases: &[&conformance::SpecCase]) { + let rows: Vec = cases + .iter() + .map(|c| c.input.clone().unwrap_or(Variable::Null)) + .collect(); + for case in cases { + self.files.entry(case.file.clone()).or_default().rows += 1; + } + let mut probe = Probe { rows: &rows }; + let mut lowering = Lowering::new(None); + let entry = Fusion::Output { + key: "zz__out".to_string(), + source: expression.to_string(), + }; + if let Err(e) = lowering.unit(&[entry], &mut probe) { + if cases + .iter() + .any(|c| Self::DATES.iter().any(|d| c.file.contains(d))) + { + let reason: String = e + .to_string() + .chars() + .map(|c| if c.is_ascii_digit() { 'N' } else { c }) + .collect(); + *self.reasons.entry(reason).or_default() += cases.len(); + } + return; + } + let Ok(program) = Program::new(lowering.finish()) else { + return; + }; + let hir = program.hir(); + let columns: Vec = hir + .schema + .columns + .iter() + .map(|c| Owned::build(Self::class(c.ty.kind), &probe.values(&c.path))) + .collect(); + let mut lists = Vec::new(); + for def in &hir.schema.lists { + if def.parent.is_some() { + return; + } + let values = probe.values(&def.path); + let mut offsets = vec![0i32]; + let mut valid = vec![0u64; rows.len().div_ceil(64).max(1)]; + let mut elements = Vec::new(); + for (r, v) in values.iter().enumerate() { + if let Variable::Array(items) = v { + valid[r / 64] |= 1 << (r % 64); + elements.extend(items.borrow().iter().cloned()); + } + offsets.push(elements.len() as i32); + } + let fields = def + .fields + .iter() + .map(|f| { + let values: Vec = elements + .iter() + .map(|e| match f.path.is_empty() { + true => e.clone(), + false => e.dot(&f.path).unwrap_or(Variable::Null), + }) + .collect(); + Owned::build(Self::class(f.ty.kind), &values) + }) + .collect(); + lists.push(OwnedList { + offsets, + valid, + fields, + }); + } + let mut batch = Batch::new(rows.len()); + for c in &columns { + batch.push_column(c.column()); + } + for l in &lists { + batch.push_list(List::new( + &l.offsets, + Some((&l.valid, 0)), + l.fields.iter().map(Owned::column).collect(), + )); + } + let mut out = program.outputs(); + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + program.run(&batch, &mut out, None) + })); + match ran { + Ok(Ok(())) => {} + Ok(Err(_)) => return, + Err(_) => { + self.mismatches.push(format!("PANIC {expression}")); + return; + } + } + let Some(slot) = out.slot(0) else { + return; + }; + for (row, case) in cases.iter().enumerate() { + let tally = self.files.entry(case.file.clone()).or_default(); + tally.lowered += 1; + let want = case.stack(); + if out.faults().get(row) { + if want.is_ok() { + self.spurious.push(format!( + "{} | {expression} | input {}", + case.location(), + case.input_text + )); + } + continue; + } + tally.typed += 1; + let got = match &slot.offsets { + Some(offsets) => { + let (lo, hi) = (offsets[row] as usize, offsets[row + 1] as usize); + Variable::from_array((lo..hi).map(|at| Self::output(slot, hir, at)).collect()) + } + None => Self::output(slot, hir, row), + }; + let rendered = conformance::Spec::guard(|| { + Ok(Variable::String(conformance::Spec::render(&got).into())) + }); + let fine = match (&want, &rendered) { + (Ok(v), Ok(_)) => Self::same(v, &got), + (Err(e), Err(r)) => { + e.starts_with(conformance::Spec::PANIC) + && r.starts_with(conformance::Spec::PANIC) + } + _ => false, + }; + if !fine { + self.mismatches.push(format!( + "{} | {expression} | input {} | vm {} | typed {}", + case.location(), + case.input_text, + want.as_ref() + .map_or_else(|e| format!("!error ({e})"), conformance::Spec::render), + rendered.map_or_else(|e| e, |r| r.as_str().unwrap_or_default().to_string()) + )); + } + } + } + + fn class(kind: zen_expression::typed::Kind) -> Class { + match kind { + zen_expression::typed::Kind::Num(_) => Class::Num, + zen_expression::typed::Kind::Bool => Class::Bool, + _ => Class::Text, + } + } + + fn print(&self) { + let mut all = Tally::default(); + let mut dates = Tally::default(); + for (file, t) in &self.files { + for acc in [&mut all].into_iter().chain( + Self::DATES + .iter() + .any(|d| file.contains(d)) + .then_some(&mut dates), + ) { + acc.rows += t.rows; + acc.lowered += t.lowered; + acc.typed += t.typed; + } + eprintln!( + "typed spec {file}: {} rows, {} lowered, {} typed", + t.rows, t.lowered, t.typed + ); + } + eprintln!( + "typed spec all: {} rows, {} lowered, {} typed", + all.rows, all.lowered, all.typed + ); + eprintln!( + "typed spec dates: {} rows, {} lowered, {} typed", + dates.rows, dates.lowered, dates.typed + ); + let mut reasons: Vec<(&String, &usize)> = self.reasons.iter().collect(); + reasons.sort_by_key(|(_, n)| std::cmp::Reverse(**n)); + for (reason, n) in reasons.iter().take(40) { + eprintln!("typed spec date rows not lowered: {n} {reason}"); + } + eprintln!("typed spec spurious faults: {}", self.spurious.len()); + for s in self.spurious.iter().take(20) { + eprintln!(" spurious {s}"); + } + } +} + +#[test] +fn typed_matches_spec() { + conformance::Spec::prepare(); + let (cases, problems) = conformance::Spec::cases(); + assert!( + problems.is_empty(), + "malformed spec:\n{}", + problems.join("\n") + ); + let mut groups: BTreeMap<(String, String), Vec<&conformance::SpecCase>> = BTreeMap::new(); + let rooted = |c: &&conformance::SpecCase| matches!(c.input, None | Some(Variable::Object(_))); + for case in cases + .iter() + .filter(|c| matches!(c.kind, ExpressionKind::Standard)) + .filter(rooted) + { + groups + .entry(( + case.expression.clone(), + Report::signature(&case.input.clone().unwrap_or(Variable::Null)), + )) + .or_default() + .push(case); + } + let mut report = Report::default(); + for ((expression, _), group) in &groups { + report.group(expression, group); + } + report.print(); + assert!( + report.mismatches.is_empty(), + "{} typed/stack differences:\n{}", + report.mismatches.len(), + report + .mismatches + .iter() + .take(60) + .cloned() + .collect::>() + .join("\n") + ); +} diff --git a/core/types/Cargo.toml b/core/types/Cargo.toml index 96474992..4f6c9d1a 100644 --- a/core/types/Cargo.toml +++ b/core/types/Cargo.toml @@ -3,6 +3,7 @@ name = "zen-types" description = "Zen Core Types" version = "2.1.6" edition = "2024" +rust-version = "1.88" license = "MIT" repository = "https://github.com/gorules/zen.git" homepage = "https://gorules.io" @@ -21,3 +22,6 @@ nohash-hasher = { workspace = true } [features] default = [] arbitrary_precision = ["serde_json/arbitrary_precision"] + +[target.'cfg(not(target_family = "wasm"))'.dependencies] +recursive = { workspace = true } diff --git a/core/types/src/lib.rs b/core/types/src/lib.rs index bb192e25..1f1caf93 100644 --- a/core/types/src/lib.rs +++ b/core/types/src/lib.rs @@ -3,6 +3,7 @@ mod constant; pub mod decision; mod number; +pub mod path; pub mod rccell; pub mod rcvalue; pub mod symbol; diff --git a/core/types/src/path.rs b/core/types/src/path.rs new file mode 100644 index 00000000..bc63055c --- /dev/null +++ b/core/types/src/path.rs @@ -0,0 +1,60 @@ +pub struct DotPath; + +impl DotPath { + #[inline] + pub fn tail<'a>(long: &'a str, short: &str) -> Option<&'a str> { + long.strip_prefix(short)?.strip_prefix('.') + } + + #[inline] + pub fn under(long: &str, short: &str) -> bool { + Self::tail(long, short).is_some() + } + + #[inline] + pub fn within(long: &str, short: &str) -> bool { + long == short || Self::under(long, short) + } + + #[inline] + pub fn nested(a: &str, b: &str) -> bool { + Self::under(a, b) || Self::under(b, a) + } + + #[inline] + pub fn overlaps(a: &str, b: &str) -> bool { + a == b || Self::nested(a, b) + } + + #[inline] + pub fn indexed(long: &str, short: &str) -> bool { + long.strip_prefix(short) + .is_some_and(|rest| rest.starts_with('.') || rest.starts_with('[')) + } +} + +#[cfg(test)] +mod tests { + use super::DotPath; + + #[test] + fn dotted_relations() { + assert_eq!(DotPath::tail("a.b.c", "a"), Some("b.c")); + assert_eq!(DotPath::tail("ab", "a"), None); + assert!(DotPath::under("a.b", "a")); + assert!(!DotPath::under("ab", "a")); + assert!(!DotPath::under("a", "a")); + assert!(DotPath::within("a", "a")); + assert!(DotPath::within("a.b.c", "a.b")); + assert!(!DotPath::within("a.bc", "a.b")); + assert!(DotPath::nested("a", "a.b") && DotPath::nested("a.b", "a")); + assert!(!DotPath::nested("a", "a")); + assert!( + DotPath::overlaps("a", "a") + && DotPath::overlaps("a.b", "a") + && !DotPath::overlaps("a", "b") + ); + assert!(DotPath::indexed("a[0]", "a") && DotPath::indexed("a.b", "a")); + assert!(!DotPath::indexed("ab", "a")); + } +} diff --git a/core/types/src/variable/map.rs b/core/types/src/variable/map.rs index cce12000..3355a823 100644 --- a/core/types/src/variable/map.rs +++ b/core/types/src/variable/map.rs @@ -1,19 +1,21 @@ use crate::symbol::Symbol; use crate::variable::Variable; +use crate::variable::shape::{Shape, ShapeHint}; use ahash::{HashMap, HashMapExt}; use smallvec::SmallVec; use std::fmt::{Debug, Formatter}; +use std::rc::Rc; const INLINE: usize = 8; const SPILL_AT: usize = 32; -type Entries = SmallVec<[(Symbol, Variable); INLINE]>; +type Values = SmallVec<[Variable; INLINE]>; #[derive(Clone)] enum Repr { - Small(Entries), - Large(HashMap), + Shaped { shape: Rc, values: Values }, + Dict(HashMap), } #[derive(Clone)] @@ -21,20 +23,40 @@ pub struct VariableMap(Repr); impl VariableMap { pub fn new() -> Self { - Self(Repr::Small(SmallVec::new())) + Self(Repr::Shaped { + shape: Shape::root(), + values: SmallVec::new(), + }) + } + + pub fn from_shape(shape: Rc, values: impl IntoIterator) -> Self { + Self(Repr::Shaped { + shape, + values: values.into_iter().collect(), + }) } pub fn with_capacity(capacity: usize) -> Self { match capacity > SPILL_AT { - true => Self(Repr::Large(HashMap::with_capacity(capacity))), - false => Self(Repr::Small(SmallVec::with_capacity(capacity))), + true => Self(Repr::Dict(HashMap::with_capacity(capacity))), + false => Self(Repr::Shaped { + shape: Shape::root(), + values: SmallVec::with_capacity(capacity), + }), + } + } + + pub fn reserve(&mut self, additional: usize) { + match &mut self.0 { + Repr::Shaped { values, .. } => values.reserve(additional), + Repr::Dict(map) => map.reserve(additional), } } pub fn len(&self) -> usize { match &self.0 { - Repr::Small(entries) => entries.len(), - Repr::Large(map) => map.len(), + Repr::Shaped { values, .. } => values.len(), + Repr::Dict(map) => map.len(), } } @@ -44,50 +66,95 @@ impl VariableMap { pub fn clear(&mut self) { match &mut self.0 { - Repr::Small(entries) => entries.clear(), - Repr::Large(map) => map.clear(), + Repr::Shaped { shape, values } => { + *shape = Shape::root(); + values.clear(); + } + Repr::Dict(map) => map.clear(), } } #[inline] - pub fn get(&self, key: &Symbol) -> Option<&Variable> { + pub fn shape(&self) -> Option<&Rc> { match &self.0 { - Repr::Small(entries) => entries - .iter() - .find(|(k, _)| k.as_str() == key.as_str()) - .map(|(_, v)| v), - Repr::Large(map) => map.get(key), + Repr::Shaped { shape, .. } => Some(shape), + Repr::Dict(_) => None, } } + #[inline] + pub fn slots(&self) -> Option<(&Shape, &[Variable])> { + match &self.0 { + Repr::Shaped { shape, values } => Some((shape, values)), + Repr::Dict(_) => None, + } + } + + #[inline] + pub fn shape_id(&self) -> Option { + self.shape().map(|shape| shape.id()) + } + + #[inline] + pub fn get(&self, key: &Symbol) -> Option<&Variable> { + self.get_str(key.as_str()) + } + #[inline] pub fn get_str(&self, key: &str) -> Option<&Variable> { match &self.0 { - Repr::Small(entries) => entries - .iter() - .find(|(k, _)| k.as_str() == key) - .map(|(_, v)| v), - Repr::Large(map) => map.get(key), + Repr::Shaped { shape, values } => shape.index_of(key).map(|index| &values[index]), + Repr::Dict(map) => map.get(key), + } + } + + #[inline] + pub fn get_hinted(&self, hint: &mut ShapeHint, key: &str) -> Option<&Variable> { + match &self.0 { + Repr::Shaped { shape, values } => { + let id = shape.id(); + if let Some(index) = hint.lookup(id) { + return values.get(index as usize); + } + let index = shape.index_of(key); + hint.record(id, index); + index.map(|index| &values[index]) + } + Repr::Dict(map) => map.get(key), + } + } + + pub fn map_values(&self, mut f: impl FnMut(&Variable) -> Variable) -> Self { + match &self.0 { + Repr::Shaped { shape, values } => Self(Repr::Shaped { + shape: shape.clone(), + values: values.iter().map(&mut f).collect(), + }), + Repr::Dict(map) => Self(Repr::Dict( + map.iter() + .map(|(key, value)| (key.clone(), f(value))) + .collect(), + )), } } pub fn get_mut(&mut self, key: &Symbol) -> Option<&mut Variable> { + self.get_mut_str(key.as_str()) + } + + pub fn get_mut_str(&mut self, key: &str) -> Option<&mut Variable> { match &mut self.0 { - Repr::Small(entries) => entries - .iter_mut() - .find(|(k, _)| k.as_str() == key.as_str()) - .map(|(_, v)| v), - Repr::Large(map) => map.get_mut(key), + Repr::Shaped { shape, values } => shape.index_of(key).map(|index| &mut values[index]), + Repr::Dict(map) => map.get_mut(key), } } pub fn get_key_value(&self, key: &Symbol) -> Option<(&Symbol, &Variable)> { match &self.0 { - Repr::Small(entries) => entries - .iter() - .find(|(k, _)| k.as_str() == key.as_str()) - .map(|(k, v)| (k, v)), - Repr::Large(map) => map.get_key_value(key), + Repr::Shaped { shape, values } => shape + .index_of(key.as_str()) + .and_then(|index| Some((shape.key_at(index)?, &values[index]))), + Repr::Dict(map) => map.get_key_value(key), } } @@ -101,58 +168,102 @@ impl VariableMap { pub fn remove_str(&mut self, key: &str) -> Option { match &mut self.0 { - Repr::Small(entries) => entries - .iter() - .position(|(k, _)| k.as_str() == key) - .map(|index| entries.remove(index).1), - Repr::Large(map) => map.remove(key), + Repr::Shaped { shape, values } => { + let index = shape.index_of(key)?; + *shape = shape.without(index); + Some(values.remove(index)) + } + Repr::Dict(map) => map.remove(key), } } pub fn insert(&mut self, key: Symbol, value: Variable) -> Option { match &mut self.0 { - Repr::Small(entries) => { - if let Some(slot) = entries.iter_mut().find(|(k, _)| k.as_str() == key.as_str()) { - return Some(std::mem::replace(&mut slot.1, value)); + Repr::Shaped { shape, values } => { + let transition = (values.len() < SPILL_AT) + .then(|| shape.transition(key.as_str())) + .flatten(); + if let Some(child) = transition { + *shape = child; + values.push(value); + return None; } - if entries.len() >= SPILL_AT { + if let Some(index) = shape.index_of(key.as_str()) { + return Some(std::mem::replace(&mut values[index], value)); + } + if values.len() >= SPILL_AT { self.spill(); - let Repr::Large(map) = &mut self.0 else { + let Repr::Dict(map) = &mut self.0 else { unreachable!("just spilled") }; return map.insert(key, value); } - entries.push((key, value)); - None + self.grow(key, value) } - Repr::Large(map) => map.insert(key, value), + Repr::Dict(map) => map.insert(key, value), + } + } + + pub fn insert_new(&mut self, key: Symbol, value: Variable) { + match &self.0 { + Repr::Shaped { values, .. } if values.len() < SPILL_AT => { + self.grow(key, value); + } + _ => { + self.insert(key, value); + } + } + } + + #[inline] + fn follow(&mut self, key: &str, value: Variable) -> Option { + let Repr::Shaped { shape, values } = &mut self.0 else { + return Some(value); + }; + if values.len() >= SPILL_AT { + return Some(value); + } + let Some(child) = shape.transition(key) else { + return Some(value); + }; + *shape = child; + values.push(value); + None + } + + fn grow(&mut self, key: Symbol, value: Variable) -> Option { + let Repr::Shaped { shape, values } = &mut self.0 else { + return self.insert(key, value); + }; + *shape = shape.with(&key); + values.push(value); + None + } + + pub fn insert_new_str(&mut self, key: &str, value: Variable) { + if let Some(value) = self.follow(key, value) { + self.insert_new(Symbol::from(key), value); } } pub fn remove(&mut self, key: &Symbol) -> Option { - match &mut self.0 { - Repr::Small(entries) => entries - .iter() - .position(|(k, _)| k.as_str() == key.as_str()) - .map(|index| entries.remove(index).1), - Repr::Large(map) => map.remove(key), - } + self.remove_str(key.as_str()) } fn spill(&mut self) { - let Repr::Small(entries) = &mut self.0 else { + let Repr::Shaped { shape, values } = &mut self.0 else { return; }; - let mut map = HashMap::with_capacity(entries.len() * 2); - for (key, value) in entries.drain(..) { - map.insert(key, value); + let mut map = HashMap::with_capacity(values.len() * 2); + for (key, value) in shape.keys().iter().zip(values.drain(..)) { + map.insert(key.clone(), value); } - self.0 = Repr::Large(map); + self.0 = Repr::Dict(map); } pub fn entry(&mut self, key: Symbol) -> Entry<'_> { - if matches!(&self.0, Repr::Small(entries) - if entries.len() >= SPILL_AT && self.get(&key).is_none()) + if matches!(&self.0, Repr::Shaped { values, .. } + if values.len() >= SPILL_AT && self.get(&key).is_none()) { self.spill(); } @@ -165,15 +276,17 @@ impl VariableMap { pub fn iter(&self) -> Iter<'_> { match &self.0 { - Repr::Small(entries) => Iter::Small(entries.iter()), - Repr::Large(map) => Iter::Large(map.iter()), + Repr::Shaped { shape, values } => Iter::Shaped(shape.keys().iter().zip(values.iter())), + Repr::Dict(map) => Iter::Dict(map.iter()), } } pub fn iter_mut(&mut self) -> IterMut<'_> { match &mut self.0 { - Repr::Small(entries) => IterMut::Small(entries.iter_mut()), - Repr::Large(map) => IterMut::Large(map.iter_mut()), + Repr::Shaped { shape, values } => { + IterMut::Shaped(shape.keys().iter().zip(values.iter_mut())) + } + Repr::Dict(map) => IterMut::Dict(map.iter_mut()), } } @@ -249,8 +362,8 @@ impl<'a> VacantEntry<'a> { } pub enum Iter<'a> { - Small(std::slice::Iter<'a, (Symbol, Variable)>), - Large(std::collections::hash_map::Iter<'a, Symbol, Variable>), + Shaped(std::iter::Zip, std::slice::Iter<'a, Variable>>), + Dict(std::collections::hash_map::Iter<'a, Symbol, Variable>), } impl<'a> Iterator for Iter<'a> { @@ -258,22 +371,22 @@ impl<'a> Iterator for Iter<'a> { fn next(&mut self) -> Option { match self { - Iter::Small(iter) => iter.next().map(|(key, value)| (key, value)), - Iter::Large(iter) => iter.next(), + Iter::Shaped(iter) => iter.next(), + Iter::Dict(iter) => iter.next(), } } fn size_hint(&self) -> (usize, Option) { match self { - Iter::Small(iter) => iter.size_hint(), - Iter::Large(iter) => iter.size_hint(), + Iter::Shaped(iter) => iter.size_hint(), + Iter::Dict(iter) => iter.size_hint(), } } } pub enum IterMut<'a> { - Small(std::slice::IterMut<'a, (Symbol, Variable)>), - Large(std::collections::hash_map::IterMut<'a, Symbol, Variable>), + Shaped(std::iter::Zip, std::slice::IterMut<'a, Variable>>), + Dict(std::collections::hash_map::IterMut<'a, Symbol, Variable>), } impl<'a> Iterator for IterMut<'a> { @@ -281,15 +394,19 @@ impl<'a> Iterator for IterMut<'a> { fn next(&mut self) -> Option { match self { - IterMut::Small(iter) => iter.next().map(|(key, value)| (&*key, value)), - IterMut::Large(iter) => iter.next(), + IterMut::Shaped(iter) => iter.next(), + IterMut::Dict(iter) => iter.next(), } } } pub enum IntoIter { - Small(smallvec::IntoIter<[(Symbol, Variable); INLINE]>), - Large(std::collections::hash_map::IntoIter), + Shaped { + shape: Rc, + index: usize, + values: smallvec::IntoIter<[Variable; INLINE]>, + }, + Dict(std::collections::hash_map::IntoIter), } impl Iterator for IntoIter { @@ -297,8 +414,17 @@ impl Iterator for IntoIter { fn next(&mut self) -> Option { match self { - IntoIter::Small(iter) => iter.next(), - IntoIter::Large(iter) => iter.next(), + IntoIter::Shaped { + shape, + index, + values, + } => { + let value = values.next()?; + let key = shape.key_at(*index)?.clone(); + *index += 1; + Some((key, value)) + } + IntoIter::Dict(iter) => iter.next(), } } } @@ -309,8 +435,12 @@ impl IntoIterator for VariableMap { fn into_iter(self) -> IntoIter { match self.0 { - Repr::Small(entries) => IntoIter::Small(entries.into_iter()), - Repr::Large(map) => IntoIter::Large(map.into_iter()), + Repr::Shaped { shape, values } => IntoIter::Shaped { + shape, + index: 0, + values: values.into_iter(), + }, + Repr::Dict(map) => IntoIter::Dict(map.into_iter()), } } } @@ -359,7 +489,88 @@ impl PartialEq for VariableMap { } impl VariableMap { + pub(crate) fn merge_cow( + &self, + patch: &VariableMap, + mut merge: impl FnMut(&mut Variable, &Variable) -> bool, + ) -> Option> { + let ( + Repr::Shaped { shape, values }, + Repr::Shaped { + shape: other, + values: incoming, + }, + ) = (&self.0, &patch.0) + else { + return None; + }; + if incoming.iter().any(|value| matches!(value, Variable::Null)) { + return None; + } + let plan = shape.merge_plan(other, SPILL_AT)?; + let copy = || { + let mut copied = Values::with_capacity(values.len() + plan.slots.len()); + copied.extend(values.iter().map(Variable::shallow_clone)); + copied + }; + let mut out: Option = None; + for (&slot, value) in plan.slots.iter().zip(incoming.iter()) { + let slot = slot as usize; + match values.get(slot) { + Some(existing) => { + let mut current = existing.shallow_clone(); + if merge(&mut current, value) + && let Some(target) = out.get_or_insert_with(copy).get_mut(slot) + { + *target = current; + } + } + None => out.get_or_insert_with(copy).push(value.shallow_clone()), + } + } + Some(out.map(|values| { + Self(Repr::Shaped { + shape: plan.shape.clone().unwrap_or_else(|| shape.clone()), + values, + }) + })) + } + + pub(crate) fn merge_in_place( + &mut self, + patch: &VariableMap, + mut merge: impl FnMut(&mut Variable, &Variable), + ) -> bool { + let ( + Repr::Shaped { shape, values }, + Repr::Shaped { + shape: other, + values: incoming, + }, + ) = (&mut self.0, &patch.0) + else { + return false; + }; + if incoming.iter().any(|value| matches!(value, Variable::Null)) { + return false; + } + let Some(plan) = shape.merge_plan(other, SPILL_AT) else { + return false; + }; + for (&slot, value) in plan.slots.iter().zip(incoming.iter()) { + match values.get_mut(slot as usize) { + Some(existing) => merge(existing, value), + None => values.push(value.shallow_clone()), + } + } + if let Some(next) = &plan.shape { + *shape = next.clone(); + } + true + } + pub fn insert_str(&mut self, key: &str, value: Variable) -> Option { + let value = self.follow(key, value)?; self.insert(Symbol::from(key), value) } } @@ -383,3 +594,142 @@ impl serde::Serialize for VariableMap { map.end() } } + +#[cfg(test)] +mod tests { + use super::*; + + fn map(keys: &[&str]) -> VariableMap { + let mut map = VariableMap::new(); + for (index, key) in keys.iter().enumerate() { + map.insert(Symbol::from(*key), Variable::Number(index.into())); + } + map + } + + #[test] + fn maps_built_from_the_same_keys_share_a_shape() { + let a = map(&["id", "balance", "apr"]); + let b = map(&["id", "balance", "apr"]); + let c = map(&["balance", "id", "apr"]); + assert_eq!(a.shape_id(), b.shape_id()); + assert_ne!(a.shape_id(), c.shape_id()); + assert_eq!(a.get_str("balance"), Some(&Variable::Number(1.into()))); + assert_eq!( + a.keys().map(Symbol::as_str).collect::>(), + ["id", "balance", "apr"] + ); + } + + #[test] + fn replacing_keeps_the_shape_and_removing_reshapes() { + let mut a = map(&["id", "balance", "apr"]); + let before = a.shape_id(); + assert_eq!( + a.insert(Symbol::from("balance"), Variable::Bool(true)), + Some(Variable::Number(1.into())) + ); + assert_eq!(a.shape_id(), before); + assert_eq!(a.remove_str("balance"), Some(Variable::Bool(true))); + assert_eq!(a.shape_id(), map(&["id", "apr"]).shape_id()); + assert_eq!(a.get_str("apr"), Some(&Variable::Number(2.into()))); + assert_eq!(a.len(), 2); + } + + #[test] + fn hinted_reads_cache_two_shapes_including_absence() { + let a = map(&["id", "balance", "apr"]); + let b = map(&["balance", "id"]); + let mut hint = ShapeHint::default(); + assert_eq!( + a.get_hinted(&mut hint, "balance"), + Some(&Variable::Number(1.into())) + ); + assert_eq!( + b.get_hinted(&mut hint, "balance"), + Some(&Variable::Number(0.into())) + ); + assert_eq!(hint.lookup(a.shape_id().unwrap()), Some(1)); + assert_eq!(hint.lookup(b.shape_id().unwrap()), Some(0)); + let mut missing = ShapeHint::default(); + assert_eq!(a.get_hinted(&mut missing, "missing"), None); + assert_eq!( + missing.lookup(a.shape_id().unwrap()), + Some(ShapeHint::ABSENT) + ); + assert_eq!(a.get_hinted(&mut missing, "missing"), None); + } + + #[test] + fn map_values_keeps_the_shape() { + let source = map(&["id", "balance"]); + let mapped = source.map_values(|value| match value { + Variable::Number(n) => Variable::Number(*n * rust_decimal::Decimal::TWO), + other => other.shallow_clone(), + }); + assert_eq!(mapped.shape_id(), source.shape_id()); + assert_eq!(mapped.get_str("balance"), Some(&Variable::Number(2.into()))); + } + + #[test] + fn spilled_maps_have_no_shape_but_keep_their_contents() { + let keys: Vec = (0..40).map(|i| format!("k{i}")).collect(); + let mut map = VariableMap::new(); + for key in &keys { + map.insert(Symbol::from(key.as_str()), Variable::Null); + } + assert!(map.shape().is_none()); + let mut hint = ShapeHint::default(); + assert_eq!(map.get_hinted(&mut hint, "k39"), Some(&Variable::Null)); + assert_eq!( + map.insert(Symbol::from("k39"), Variable::Bool(false)), + Some(Variable::Null) + ); + assert_eq!( + map.insert(Symbol::from("fresh"), Variable::Bool(true)), + None + ); + assert_eq!(map.len(), 41); + let owned: Vec<(Symbol, Variable)> = map.into_iter().collect(); + assert_eq!(owned.len(), 41); + } + + #[test] + fn string_keyed_inserts_follow_transitions_or_fall_back() { + let mut first = VariableMap::new(); + first.insert_new_str("approval", Variable::Bool(false)); + first.insert_new_str("rejectionReasons", Variable::Null); + assert_eq!(first.len(), 2); + assert_eq!(first.get_str("approval"), Some(&Variable::Bool(false))); + let mut second = VariableMap::new(); + assert_eq!(second.insert_str("approval", Variable::Bool(true)), None); + assert_eq!(second.insert_str("rejectionReasons", Variable::Null), None); + assert_eq!(second.shape_id(), first.shape_id()); + assert_eq!( + second.insert_str("approval", Variable::Null), + Some(Variable::Bool(true)) + ); + assert_eq!(second.len(), 2); + let mut spilled = VariableMap::new(); + for i in 0..40 { + spilled.insert_new_str(&format!("key{i}"), Variable::Null); + } + assert_eq!(spilled.len(), 40); + assert_eq!( + spilled.insert_str("key39", Variable::Bool(true)), + Some(Variable::Null) + ); + assert_eq!(spilled.insert_str("fresh", Variable::Bool(true)), None); + assert_eq!(spilled.len(), 41); + } + + #[test] + fn owned_iteration_preserves_order() { + let map = map(&["z", "a", "m"]); + let keys: Vec = map + .into_iter() + .map(|(key, _)| key.as_str().to_owned()) + .collect(); + assert_eq!(keys, ["z", "a", "m"]); + } +} diff --git a/core/types/src/variable/mod.rs b/core/types/src/variable/mod.rs index 1c2cff6a..2b112fe9 100644 --- a/core/types/src/variable/mod.rs +++ b/core/types/src/variable/mod.rs @@ -24,10 +24,12 @@ mod map; mod ref_deser; mod ref_ser; mod ser; +mod shape; pub use crate::rccell::RcCell; pub use crate::variable::map::{Iter as MapIter, VariableMap}; +pub use crate::variable::shape::{Shape, ShapeHint}; thread_local! { static DOLLAR_KEY_RC: Rc = Rc::from("$"); @@ -261,10 +263,12 @@ impl Variable { let head = parts.try_fold(self.shallow_clone(), |var, part| match var { Variable::Object(obj) => { let mut obj_ref = obj.borrow_mut(); - Some(match obj_ref.entry(Symbol::from(part)) { - Entry::Occupied(occ) => occ.get().shallow_clone(), - Entry::Vacant(vac) => vac.insert(Self::empty_object()).shallow_clone(), - }) + if let Some(existing) = obj_ref.get_str(part) { + return Some(existing.shallow_clone()); + } + let fresh = Self::empty_object(); + obj_ref.insert_str(part, fresh.shallow_clone()); + Some(fresh) } _ => None, })?; @@ -273,7 +277,7 @@ impl Variable { }; let mut object = object_ref.borrow_mut(); - object.insert(Symbol::from(last_part), variable) + object.insert_str(last_part, variable) } pub fn dot_insert_detached(&self, key: &str, variable: Variable) -> Option { @@ -318,36 +322,52 @@ impl Variable { match self { Variable::Array(a) => { let arr = a.borrow(); - Variable::from_array(arr.iter().map(|v| v.deep_clone()).collect()) + Variable::from_array(arr.iter().map(Variable::deep_child).collect()) } Variable::Object(o) => { - let obj = o.borrow(); - Variable::from_object( - obj.iter() - .map(|(k, v)| (k.clone(), v.deep_clone())) - .collect(), - ) + Variable::from_object(o.borrow().map_values(Variable::deep_child)) } _ => self.shallow_clone(), } } + fn deep_child(&self) -> Self { + match self { + Variable::Array(_) | Variable::Object(_) => self.deep_nested(), + _ => self.shallow_clone(), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn deep_nested(&self) -> Self { + self.deep_clone() + } + + fn depth_child(&self, depth: usize) -> Self { + match self { + Variable::Array(_) | Variable::Object(_) if !depth.is_zero() => { + self.depth_nested(depth) + } + _ => self.shallow_clone(), + } + } + + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] + fn depth_nested(&self, depth: usize) -> Self { + self.depth_clone(depth) + } + pub fn depth_clone(&self, depth: usize) -> Self { match depth.is_zero() { true => self.shallow_clone(), false => match self { Variable::Array(a) => { let arr = a.borrow(); - Variable::from_array(arr.iter().map(|v| v.depth_clone(depth - 1)).collect()) - } - Variable::Object(o) => { - let obj = o.borrow(); - Variable::from_object( - obj.iter() - .map(|(k, v)| (k.clone(), v.depth_clone(depth - 1))) - .collect(), - ) + Variable::from_array(arr.iter().map(|v| v.depth_child(depth - 1)).collect()) } + Variable::Object(o) => Variable::from_object( + o.borrow().map_values(|value| value.depth_child(depth - 1)), + ), _ => self.shallow_clone(), }, } @@ -389,6 +409,28 @@ fn merge_variables( } let patch = patch_ref.borrow(); + match strategy { + MergeStrategy::InPlace => { + if doc_ref.borrow_mut().merge_in_place(&patch, |entry, value| { + merge_variables(entry, value, false, strategy); + }) { + return true; + } + } + MergeStrategy::CloneOnWrite => { + let merged = doc_ref.borrow().merge_cow(&patch, |entry, value| { + merge_variables(entry, value, false, strategy) + }); + match merged { + Some(Some(map)) => { + *doc = Variable::from_object(map); + return true; + } + Some(None) => return false, + None => {} + } + } + } match strategy { MergeStrategy::InPlace => { let mut map = doc_ref.borrow_mut(); @@ -522,6 +564,39 @@ mod tests { use rust_decimal_macros::dec; use serde_json::json; + #[test] + fn merges_keep_order_and_sharing() { + let base: Variable = json!({ "b": 1, "a": { "x": 1, "y": [1] }, "c": "s" }).into(); + for _ in 0..3 { + let mut doc = base.clone(); + let patch: Variable = json!({ "a": { "y": [1], "z": 2 }, "d": true, "b": 1 }).into(); + let merged = doc.merge_clone(&patch); + assert_eq!( + merged.to_string(), + r#"{"a":{"x":1,"y":[1],"z":2},"b":1,"c":"s","d":true}"# + ); + assert_eq!(base.to_string(), r#"{"a":{"x":1,"y":[1]},"b":1,"c":"s"}"#); + let mut same = base.clone(); + let unchanged = same.merge_clone(&json!({ "b": 1, "c": "s" }).into()); + assert!(std::rc::Rc::ptr_eq( + &unchanged.as_object().unwrap(), + &base.as_object().unwrap() + )); + let mut empty = Variable::empty_object(); + let ending = empty.merge(&merged); + assert_eq!(ending.to_string(), merged.to_string()); + assert!(std::rc::Rc::ptr_eq( + &ending.dot("a").unwrap().as_object().unwrap(), + &merged.dot("a").unwrap().as_object().unwrap() + )); + let removed = doc.merge_clone(&json!({ "b": null, "e": 1 }).into()); + assert_eq!( + removed.to_string(), + r#"{"a":{"x":1,"y":[1]},"c":"s","e":1}"# + ); + } + } + #[test] fn insert_detached() { let some_data: Variable = json!({ "customer": { "firstName": "John" }}).into(); diff --git a/core/types/src/variable/shape.rs b/core/types/src/variable/shape.rs new file mode 100644 index 00000000..e36ba8be --- /dev/null +++ b/core/types/src/variable/shape.rs @@ -0,0 +1,504 @@ +use crate::symbol::Symbol; +use ahash::HashMap; +use smallvec::SmallVec; +use std::cell::RefCell; +use std::fmt::{Debug, Formatter}; +use std::rc::{Rc, Weak}; +use std::sync::atomic::{AtomicU64, Ordering}; + +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +const MANY_AT: usize = 8; + +const SWEEP_FLOOR: usize = 32; + +const MERGE_CACHE: usize = 8; + +pub(crate) struct MergePlan { + pub(crate) slots: Rc<[u32]>, + pub(crate) shape: Option>, +} + +#[derive(Clone)] +struct CachedPlan { + slots: Rc<[u32]>, + shape: Option>, +} + +type Cached = (u64, Option); + +#[derive(Default)] +enum Transitions { + #[default] + Empty, + Few(SmallVec<[(u64, Weak); 4]>), + Many { + len: usize, + sweep_at: usize, + map: HashMap; 1]>>, + }, +} + +impl Transitions { + #[cfg(test)] + fn len(&self) -> usize { + match self { + Transitions::Empty => 0, + Transitions::Few(few) => few.len(), + Transitions::Many { len, .. } => *len, + } + } + + fn find(&self, print: u64, matches: impl Fn(&Rc) -> bool) -> Option> { + match self { + Transitions::Empty => None, + Transitions::Few(few) => few + .iter() + .filter(|(known, _)| *known == print) + .filter_map(|(_, child)| child.upgrade()) + .find(|child| matches(child)), + Transitions::Many { map, .. } => map + .get(&print)? + .iter() + .filter_map(Weak::upgrade) + .find(|child| matches(child)), + } + } + + fn sweep(&mut self) { + match self { + Transitions::Empty => {} + Transitions::Few(few) => few.retain(|(_, child)| child.strong_count() > 0), + Transitions::Many { len, sweep_at, map } => { + map.retain(|_, children| { + children.retain(|child| child.strong_count() > 0); + !children.is_empty() + }); + *len = map.values().map(SmallVec::len).sum(); + *sweep_at = (*len * 2).max(SWEEP_FLOOR); + } + } + } + + fn push(&mut self, print: u64, child: &Rc) { + let child = Rc::downgrade(child); + match self { + Transitions::Empty => { + let mut few = SmallVec::new(); + few.push((print, child)); + *self = Transitions::Few(few); + } + Transitions::Few(few) => { + if let Some(dead) = few + .iter_mut() + .find(|(known, shape)| *known == print && shape.strong_count() == 0) + { + dead.1 = child; + return; + } + if few.len() >= MANY_AT { + few.retain(|(_, known)| known.strong_count() > 0); + } + if few.len() < MANY_AT { + few.push((print, child)); + return; + } + let mut map: HashMap; 1]>> = HashMap::default(); + for (known, shape) in few.drain(..) { + map.entry(known).or_default().push(shape); + } + map.entry(print).or_default().push(child); + let len = MANY_AT + 1; + *self = Transitions::Many { + len, + sweep_at: (len * 2).max(SWEEP_FLOOR), + map, + }; + } + Transitions::Many { len, sweep_at, map } => { + let children = map.entry(print).or_default(); + if let Some(dead) = children.iter_mut().find(|shape| shape.strong_count() == 0) { + *dead = child; + return; + } + children.push(child); + *len += 1; + if *len >= *sweep_at { + self.sweep(); + } + } + } + } +} + +thread_local! { + static ROOT: Rc = Rc::new(Shape::new(Box::new([]), None)); +} + +pub struct Shape { + id: u64, + keys: Box<[Symbol]>, + prints: Box<[u64]>, + parent: Option>, + transitions: RefCell, + merges: RefCell>, +} + +impl Shape { + fn new(keys: Box<[Symbol]>, parent: Option>) -> Self { + Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), + parent, + prints: keys.iter().map(|key| Self::print(key.as_str())).collect(), + keys, + transitions: RefCell::new(Transitions::default()), + merges: RefCell::new(SmallVec::new()), + } + } + + #[inline] + fn print(key: &str) -> u64 { + let bytes = key.as_bytes(); + let mut packed = [0u8; 8]; + let take = bytes.len().min(7); + packed[..take].copy_from_slice(&bytes[..take]); + packed[7] = bytes.len().min(255) as u8; + u64::from_le_bytes(packed) + } + + #[inline] + fn exact(key: &str) -> bool { + key.len() <= 7 + } + + pub fn root() -> Rc { + ROOT.with(Rc::clone) + } + + pub fn of<'a>(keys: impl IntoIterator) -> Rc { + keys.into_iter() + .fold(Self::root(), |shape, key| shape.with(key)) + } + + pub fn id(&self) -> u64 { + self.id + } + + pub fn keys(&self) -> &[Symbol] { + &self.keys + } + + pub fn parent(&self) -> Option<&Rc> { + self.parent.as_ref() + } + + pub fn len(&self) -> usize { + self.keys.len() + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } + + #[inline] + pub fn index_of(&self, key: &str) -> Option { + let print = Self::print(key); + if Self::exact(key) { + return self.prints.iter().position(|known| *known == print); + } + self.prints + .iter() + .enumerate() + .filter(|(_, known)| **known == print) + .map(|(index, _)| index) + .find(|&index| self.keys[index].as_str() == key) + } + + #[inline] + pub fn key_at(&self, index: usize) -> Option<&Symbol> { + self.keys.get(index) + } + + #[inline] + pub fn transition(&self, key: &str) -> Option> { + let position = self.keys.len(); + let exact = Self::exact(key); + self.transitions.borrow().find(Self::print(key), |child| { + exact + || child + .key_at(position) + .is_some_and(|known| known.as_str() == key) + }) + } + + pub fn with(self: &Rc, key: &Symbol) -> Rc { + if let Some(child) = self.transition(key.as_str()) { + return child; + } + let mut transitions = self.transitions.borrow_mut(); + let mut keys = Vec::with_capacity(self.keys.len() + 1); + keys.extend(self.keys.iter().cloned()); + keys.push(key.clone()); + let child = Rc::new(Shape::new(keys.into_boxed_slice(), Some(self.clone()))); + transitions.push(Self::print(key.as_str()), &child); + child + } + + pub(crate) fn merge_plan(self: &Rc, patch: &Shape, spill_at: usize) -> Option { + let id = patch.id; + let cached = self + .merges + .borrow() + .iter() + .find(|(known, _)| *known == id) + .map(|(_, plan)| plan.clone()); + match cached { + Some(None) => return None, + Some(Some(CachedPlan { slots, shape: None })) => { + return Some(MergePlan { slots, shape: None }); + } + Some(Some(CachedPlan { + slots, + shape: Some(weak), + })) => { + if let Some(shape) = weak.upgrade() { + return Some(MergePlan { + slots, + shape: Some(shape), + }); + } + } + None => {} + } + let plan = self.plan_merge(patch, spill_at); + let entry = plan.as_ref().map(|plan| CachedPlan { + slots: plan.slots.clone(), + shape: plan.shape.as_ref().map(Rc::downgrade), + }); + let mut merges = self.merges.borrow_mut(); + match merges.iter().position(|(known, _)| *known == id) { + Some(index) => merges[index] = (id, entry), + None if merges.len() < MERGE_CACHE => merges.push((id, entry)), + None => merges[(id as usize) % MERGE_CACHE] = (id, entry), + } + plan + } + fn plan_merge(self: &Rc, patch: &Shape, spill_at: usize) -> Option { + let base = self.len(); + let mut current = self.clone(); + let mut slots = Vec::with_capacity(patch.len()); + for key in patch.keys.iter() { + match current.index_of(key.as_str()) { + Some(index) if index < base => slots.push(index as u32), + Some(_) => return None, + None if current.len() >= spill_at => return None, + None => { + let child = current.with(key); + slots.push(current.len() as u32); + current = child; + } + } + } + Some(MergePlan { + slots: slots.into(), + shape: (!Rc::ptr_eq(¤t, self)).then_some(current), + }) + } + + pub fn without(&self, index: usize) -> Rc { + Self::of( + self.keys + .iter() + .enumerate() + .filter(|(position, _)| *position != index) + .map(|(_, key)| key), + ) + } +} + +#[derive(Clone, Debug, Default)] +pub struct ShapeHint { + shapes: [u64; 2], + indices: [u32; 2], + next: u8, +} + +impl ShapeHint { + pub const ABSENT: u32 = u32::MAX; + + #[inline] + pub fn lookup(&self, shape: u64) -> Option { + if self.shapes[0] == shape { + return Some(self.indices[0]); + } + if self.shapes[1] == shape { + return Some(self.indices[1]); + } + None + } + + #[inline] + pub fn record(&mut self, shape: u64, index: Option) { + let slot = self.next as usize; + self.shapes[slot] = shape; + self.indices[slot] = index.map_or(Self::ABSENT, |index| index as u32); + self.next ^= 1; + } +} + +impl Debug for Shape { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Shape") + .field("id", &self.id) + .field("keys", &self.keys) + .finish() + } +} + +impl PartialEq for Shape { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Eq for Shape {} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(text: &str) -> Symbol { + Symbol::from(text) + } + + fn chain(keys: &[&str]) -> Rc { + let keys: Vec = keys.iter().map(|k| key(k)).collect(); + Shape::of(keys.iter()) + } + + #[test] + fn transitions_are_interned_per_key_sequence() { + let a = chain(&["id", "balance"]); + let b = chain(&["id", "balance"]); + let c = chain(&["balance", "id"]); + assert!(Rc::ptr_eq(&a, &b)); + assert_eq!(a.id(), b.id()); + assert_ne!(a.id(), c.id()); + assert_eq!(a.index_of("balance"), Some(1)); + assert_eq!(c.index_of("balance"), Some(0)); + assert_eq!(a.index_of("missing"), None); + } + + #[test] + fn long_keys_with_a_shared_prefix_stay_distinct() { + let shape = chain(&["interestDue", "interestRate", "id"]); + assert_eq!(shape.index_of("interestDue"), Some(0)); + assert_eq!(shape.index_of("interestRate"), Some(1)); + assert_eq!(shape.index_of("interestDuo"), None); + assert_eq!(shape.index_of("id"), Some(2)); + assert_eq!(shape.index_of("idx"), None); + let a = chain(&["interestDue"]); + let b = chain(&["interestRate"]); + assert!(!Rc::ptr_eq(&a, &b)); + assert!(Rc::ptr_eq(&chain(&["interestRate"]), &b)); + } + + #[test] + fn removing_a_key_reuses_the_interned_shape() { + let shape = chain(&["a", "b", "c"]); + let without = shape.without(1); + assert!(Rc::ptr_eq(&without, &chain(&["a", "c"]))); + } + + #[test] + fn wide_fan_out_stays_interned() { + let root = chain(&["fanout-fixed"]); + let children: Vec> = (0..10_000) + .map(|i| root.with(&key(&format!("k{i}")))) + .collect(); + assert_eq!(root.transitions.borrow().len(), 10_000); + for (i, child) in children.iter().enumerate() { + assert_eq!(child.index_of(&format!("k{i}")), Some(1)); + assert!(Rc::ptr_eq(&root.with(&key(&format!("k{i}"))), child)); + } + } + + fn root_transitions() -> usize { + Shape::root().transitions.borrow().len() + } + + #[test] + fn a_shape_is_freed_once_nothing_uses_it() { + let leaf = chain(&["freed-a", "freed-b", "freed-c"]); + let middle = Rc::downgrade(leaf.parent().unwrap()); + let weak = Rc::downgrade(&leaf); + drop(leaf); + assert!(weak.upgrade().is_none()); + assert!(middle.upgrade().is_none()); + assert!(Shape::root().transition("freed-a").is_none()); + } + + #[test] + fn a_live_shape_keeps_its_prefixes_interned() { + let leaf = chain(&["kept-a", "kept-b", "kept-c"]); + let again = chain(&["kept-a", "kept-b", "kept-c"]); + assert!(Rc::ptr_eq(&leaf, &again)); + assert!(Rc::ptr_eq( + leaf.parent().unwrap(), + &chain(&["kept-a", "kept-b"]) + )); + let id = leaf.id(); + drop((leaf, again)); + assert_ne!(chain(&["kept-a", "kept-b", "kept-c"]).id(), id); + } + + #[test] + fn dead_transitions_are_swept_under_unbounded_key_layouts() { + let before = root_transitions(); + let first = Rc::downgrade(&chain(&["dyn-first", "id"])); + for i in 0..16_384 { + let shape = chain(&[&format!("dyn{i}"), "id"]); + assert_eq!(shape.index_of("id"), Some(1)); + } + assert!(root_transitions() <= (before + 1) * 2 + SWEEP_FLOOR); + assert!(first.upgrade().is_none()); + } + + #[test] + fn recreating_a_freed_key_reuses_its_dead_link() { + let base = chain(&["reuse-base"]); + let wide = chain(&["reuse-wide"]); + let alive: Vec> = (0..(MANY_AT * 2)) + .map(|i| wide.with(&key(&format!("w{i}")))) + .collect(); + for _ in 0..1000 { + let child = base.with(&key("reused")); + assert_eq!(child.index_of("reused"), Some(1)); + let child = wide.with(&key("reused")); + assert_eq!(child.index_of("reused"), Some(1)); + } + assert_eq!(base.transitions.borrow().len(), 1); + assert_eq!(wide.transitions.borrow().len(), MANY_AT * 2 + 1); + let Transitions::Many { map, .. } = &*wide.transitions.borrow() else { + panic!("wide shape should use the map"); + }; + assert_eq!(map.get(&Shape::print("reused")).map(SmallVec::len), Some(1)); + assert_eq!(alive.len(), MANY_AT * 2); + } + + #[test] + fn a_cached_merge_does_not_keep_shapes_alive() { + let base = chain(&["merge-a"]); + let patch = chain(&["merge-b"]); + let plan = base.merge_plan(&patch, 32).expect("plan"); + let merged = Rc::downgrade(plan.shape.as_ref().unwrap()); + assert_eq!(&*plan.slots, &[1]); + drop(plan); + assert!(merged.upgrade().is_none()); + let again = base.merge_plan(&patch, 32).expect("plan"); + assert_eq!(again.shape.as_ref().unwrap().keys().len(), 2); + let weak_base = Rc::downgrade(&base); + drop((base, again)); + assert!(weak_base.upgrade().is_none()); + } +}