diff --git a/core/expression/Cargo.toml b/core/expression/Cargo.toml index 5f6e3430..5c1cb70f 100644 --- a/core/expression/Cargo.toml +++ b/core/expression/Cargo.toml @@ -48,6 +48,7 @@ default = ["regex-deprecated"] regex-lite = ["dep:regex-lite"] regex-deprecated = ["dep:regex"] arbitrary_precision = ["serde_json/arbitrary_precision", "zen-types/arbitrary_precision"] +lane = [] [[bench]] harness = false @@ -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..daafba7f --- /dev/null +++ b/core/expression/benches/lane.rs @@ -0,0 +1,943 @@ +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), + Any(Vec), +} + +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_LISTS").is_ok() + && 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_LISTS").is_ok() + && 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 { + 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 children<'a>(&'a self, texts: &'a [(Vec, Vec)]) -> Vec> { + self.data + .iter() + .enumerate() + .map(|(i, d)| match d { + 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, _) => 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 children = table.children(&texts); + 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 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 children = table.children(&texts); + 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::() + ); +} diff --git a/core/expression/src/isolate.rs b/core/expression/src/isolate.rs index c7c59b6e..240b50bf 100644 --- a/core/expression/src/isolate.rs +++ b/core/expression/src/isolate.rs @@ -142,6 +142,10 @@ impl Isolate { } pub fn run_standard(&mut self, source: &str) -> Result { + #[cfg(feature = "lane")] + return crate::lane::Backend::run(source, ExpressionKind::Standard, &self.scope); + + #[allow(unreachable_code)] let cached = self .cache .as_ref() @@ -171,6 +175,12 @@ impl Isolate { } pub fn run_unary(&mut self, source: &str) -> Result { + #[cfg(feature = "lane")] + return crate::lane::Backend::run(source, ExpressionKind::Unary, &self.scope)? + .as_bool() + .ok_or(IsolateError::ValueCastError); + + #[allow(unreachable_code)] let cached = self .cache .as_ref() diff --git a/core/expression/src/lane/builtins/arrays.rs b/core/expression/src/lane/builtins/arrays.rs new file mode 100644 index 00000000..d434c626 --- /dev/null +++ b/core/expression/src/lane/builtins/arrays.rs @@ -0,0 +1,166 @@ +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), + }; + + 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..0ff0b700 --- /dev/null +++ b/core/expression/src/lane/builtins/convert.rs @@ -0,0 +1,111 @@ +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..ebc991a9 --- /dev/null +++ b/core/expression/src/lane/builtins/functions.rs @@ -0,0 +1,202 @@ +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..cd0671a8 --- /dev/null +++ b/core/expression/src/lane/builtins/legacy.rs @@ -0,0 +1,189 @@ +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..c4929d69 --- /dev/null +++ b/core/expression/src/lane/cells.rs @@ -0,0 +1,986 @@ +use crate::lane::date::DynamicVariableExt; +use crate::lane::{Binding, Column, Columns, Kind, LaneProgram, LaneRunner, Values}; +use crate::lexer::{ComparisonOperator, Lexer, LogicalOperator, Operator}; +use crate::parser::{Node, Parser}; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::{Isolate, 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 { + 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, + } + } + + 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: u16, + truth: [u16; 2], + keys: Vec<(u64, usize, Box<[u8]>, u16)>, + text: u16, + regions: Vec, + other: u16, + pub failed: u16, +} + +impl Pieces { + fn intern(bits: &mut Vec>, piece: Vec) -> u16 { + match bits.iter().position(|b| *b == piece) { + Some(at) => at as u16, + None => { + bits.push(piece); + (bits.len() - 1) as u16 + } + } + } + + #[inline] + fn word(text: &[u8]) -> u64 { + match text.get(..8) { + Some(head) => { + let mut word = [0u8; 8]; + word.copy_from_slice(head); + u64::from_le_bytes(word) + } + None => text.iter().enumerate().fold(0u64, |w, (i, b)| w | (*b as u64) << (8 * i)), + } + } + + #[inline] + fn text(&self, text: &[u8]) -> u16 { + let (word, len) = (Self::word(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 { + let mut word = [0u8; 8]; + let take = text.len().min(7); + word[..take].copy_from_slice(&text[..take]); + word[7] = text.len().min(255) as u8; + u64::from_le_bytes(word) + } + + fn text(&self, text: &[u8]) -> Option<&Vec> { + match &self.few { + Some(few) => { + let prefix = Self::prefix(text); + few.iter() + .find(|(p, k, _)| *p == prefix && 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 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 { + Self::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 { + Self::or(bits, matched); + } + continue; + } + let fast = parts(row).and_then(|(mant, scale)| { + 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()?; + let value = mant.checked_mul(scaling.mult)?; + Some(Self::region_of(&scaling.bounds, value)) + }); + 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); + } + + fn or(into: &mut [u64], from: &[u64]) { + into.iter_mut().zip(from).for_each(|(a, b)| *a |= b); + } + + 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 = Isolate::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] { + Self::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() { + Self::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, bool), + ) { + runner.evaluate_bound(program, scopes, env.columns, env.bind, Some(rows), |row, result| { + sink(row, matches!(result.as_deref(), Ok([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 { + Self::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, bool), + ) { + let Some(other) = self.others.get(other) else { + rows.iter().for_each(|&row| sink(row, 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) { + Self::or(bits, matched); + } + } + } + + fn region(&self, n: &Decimal) -> Option<&Vec> { + if self.regions.is_empty() { + return None; + } + let region = match self.bounds.binary_search(n) { + Ok(i) => i * 2 + 1, + Err(i) => i * 2, + }; + self.regions.get(region) + } + + 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 { + Self::or(bits, matched); + } + return; + } + match (numeric, text, boolean) { + (true, _, _) => { + let Some(n) = column.number(row) else { + if let Some(matched) = &self.null { + Self::or(bits, matched); + } + return; + }; + if let Some(region) = self.region(&n) { + Self::or(bits, region); + } + } + (_, true, _) => { + if let Some(matched) = column.bytes(row).and_then(|t| self.text(t)) { + Self::or(bits, matched); + } + } + (_, _, true) => { + if let Some(matched) = column.boolean(row).and_then(|b| self.bools[usize::from(b)].as_ref()) { + Self::or(bits, matched); + } + } + _ => { + let value = column.variable(row); + if let Some(matched) = self.matched(&value) { + Self::or(bits, matched); + } + self.dated(&value, bits); + if let Variable::Number(n) = &value { + if let Some(region) = self.region(n) { + Self::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 { + Self::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))); + (Pieces::word(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) -> u16 { + 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) -> u16 { + if pieces.regions.is_empty() { + return pieces.other; + } + let region = match self.bounds.binary_search(n) { + Ok(i) => i * 2 + 1, + Err(i) => i * 2, + }; + pieces.regions.get(region).copied().unwrap_or(pieces.other) + } + + fn numbers_into(&self, pieces: &Pieces, column: &Column, parts: impl Iterator>, out: &mut [u16]) { + 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(|(mant, scale)| { + 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)?)) + }); + *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 [u16]) { + 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![0u16; 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 { + Self::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() { + Self::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) { + let words = self.words; + out.clear(); + out.resize(values.len() * words, 0); + for (row, value) in values.iter().enumerate() { + let bits = &mut out[row * words..(row + 1) * words]; + bits.copy_from_slice(&self.always); + if let Some(matched) = self.matched(value) { + Self::or(bits, matched); + } + self.dated(value, bits); + if let (Variable::Number(n), false) = (value, self.regions.is_empty()) { + let region = match self.bounds.binary_search(n) { + Ok(i) => i * 2 + 1, + Err(i) => i * 2, + }; + Self::or(bits, &self.regions[region]); + } + } + } + +} diff --git a/core/expression/src/lane/columns.rs b/core/expression/src/lane/columns.rs new file mode 100644 index 00000000..9cb1415a --- /dev/null +++ b/core/expression/src/lane/columns.rs @@ -0,0 +1,559 @@ +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::program::{Binding, Kind}; +use crate::variable::Variable; +use rust_decimal::prelude::FromPrimitive; +use rust_decimal::Decimal; +use std::str::FromStr; + +#[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>, + }, + 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 { .. } if child.column().validity.is_none() => Kind::List, + _ => Kind::Dyn, + }, + Values::Any(_) => Kind::Dyn, + } + } + + #[inline] + pub(crate) fn bit(bits: &[u64], index: usize) -> bool { + bits.get(index / 64) + .is_some_and(|w| w >> (index % 64) & 1 == 1) + } + + 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, Self::word(bits, at + i * 64, take)); + } + mask + } + + #[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 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)) => Self::bit(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::Any(v) => v.len(), + } + } + + 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(Self::bit(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), + } + } + + 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) + } + _ => 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, _)| { + p.strip_prefix(path) + .is_some_and(|rest| rest.starts_with('.')) + || path + .strip_prefix(*p) + .is_some_and(|rest| rest.starts_with('.')) + }); + match (covered, self.find(path)) { + (true, _) => Binding::Row, + (false, Some(i)) => Binding::Column(i), + (false, None) => Binding::Absent, + } + } + + 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..75c8f7de --- /dev/null +++ b/core/expression/src/lane/compile.rs @@ -0,0 +1,1787 @@ +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::ops::Ops; +use crate::lane::program::{ + Binary, ClosureOp, Const, Input, Kind, Layout, Load, LoadCall, MaskId, NumCmp, NumOp, + ObjectKey, Op, Operand, Program, Reg, Step, +}; +use crate::lexer::{ArithmeticOperator, ComparisonOperator, LogicalOperator, Operator}; +use crate::parser::Node; +use crate::lane::date::Date; +use crate::variable::{Variable, VariableType}; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; +use std::sync::Arc; + +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>, + folding: bool, + pure: ahash::HashMap, + unresolved: 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, + folding, + pure: Default::default(), + unresolved: 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 u16; + 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, + } + } + + 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, _)| b.strip_prefix(*a).is_some_and(|rest| rest.starts_with('.'))) + }); + let resolvable = chain + && !assigns + && !nested + && roots.iter().all(|(_, n)| Self::dollar_static(n, false)); + 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), + folding: false, + pure: Default::default(), + unresolved: false, + }; + 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 u16, + }); + 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 u16; + program.site_keys = compiler.site_keys; + program.finish(sites); + Ok(program) + } + + fn dollar_static(node: &Node, closure: bool) -> 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 !closure && !dotted; + } + let ok = std::cell::Cell::new(true); + match node { + Node::Identifier("$") | Node::Root => false, + Node::Closure { body, .. } => Self::dollar_static(body, true), + Node::Member { node, property } => { + Self::dollar_static(node, closure) && Self::dollar_static(property, closure) + } + Node::Parenthesized(n) | Node::Unary { node: n, .. } => Self::dollar_static(n, closure), + Node::Binary { left, right, .. } | Node::Interval { left, right, .. } => { + Self::dollar_static(left, closure) && Self::dollar_static(right, closure) + } + Node::Conditional { + condition, + on_true, + on_false, + } => { + Self::dollar_static(condition, closure) + && Self::dollar_static(on_true, closure) + && Self::dollar_static(on_false, closure) + } + Node::Array(items) | Node::TemplateString(items) => { + items.iter().all(|n| Self::dollar_static(n, closure)) + } + Node::Object(pairs) => pairs + .iter() + .all(|(k, v)| Self::dollar_static(k, closure) && Self::dollar_static(v, closure)), + Node::FunctionCall { arguments, .. } => { + arguments.iter().all(|n| Self::dollar_static(n, closure)) + } + Node::MethodCall { + this, arguments, .. + } => { + Self::dollar_static(this, closure) + && arguments.iter().all(|n| Self::dollar_static(n, closure)) + } + Node::Slice { node, to, from } => { + Self::dollar_static(node, closure) + && to.is_none_or(|n| Self::dollar_static(n, closure)) + && from.is_none_or(|n| Self::dollar_static(n, closure)) + } + Node::Assignments { .. } | Node::Error { .. } => false, + _ => ok.get(), + } + } + + 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((mut 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))); + }; + 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, + }); + 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 || self.top().mask != 0 { + 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) -> u16 { + self.site_keys.push(key); + (self.site_keys.len() - 1) as u16 + } + + 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, + } + } + + 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() + } + + fn node_key(&self, node: &Node) -> Option { + match node { + 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}")), + _ => 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) -> u16 { + let consts = &mut self.top().program.consts; + match consts.iter().position(|c| c.same(&value)) { + Some(i) => i as u16, + None => { + consts.push(value); + (consts.len() - 1) as u16 + } + } + } + + 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; + } + 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 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 + } + + 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<[u16]> = 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 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 { + if self.folding || Self::literal(node).is_some() || !self.pure(node) { + return None; + } + let program = Self::build(node, None, None, true).ok()?; + let value = 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, + }; + Some(self.constant(value)) + } + + #[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)]) => { + Self::formats(pattern) + } + (crate::functions::DateMethod::Format, []) => true, + (crate::functions::DateMethod::Format, _) => false, + _ => true, + }; + format + && !matches!( + method, + crate::functions::DateMethod::IsToday + | crate::functions::DateMethod::IsYesterday + | crate::functions::DateMethod::IsTomorrow + ) && self.pure(this) + && arguments.iter().all(|n| self.pure(n)) + } + }; + self.pure.insert(key, pure); + pure + } + + fn formats(pattern: &str) -> bool { + use chrono::TimeZone; + let Ok(items) = chrono::format::StrftimeItems::new(pattern).parse_to_owned() else { + return false; + }; + let sample = chrono_tz::Tz::UTC.timestamp_opt(0, 0).earliest(); + sample.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() + }) + } + + fn pure_call(kind: &FunctionKind, arguments: &[&Node]) -> bool { + match kind { + FunctionKind::Internal(InternalFunction::Rand) => false, + FunctionKind::Internal(InternalFunction::Date) => match arguments { + [Node::Number(_)] | [Node::Number(_), Node::String(_)] => true, + [Node::String(text)] | [Node::String(text), Node::String(_)] => { + Date::parses(text) + } + _ => false, + }, + FunctionKind::Internal(_) => true, + FunctionKind::Deprecated(_) | FunctionKind::Closure(_) => false, + } + } + + 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 node(&mut self, node: &'a Node<'a>) -> Result { + if self.dollar.is_some() && self.stack.len() == 1 { + 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) => { + 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, + }); + 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 { + 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); + } + 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::assigns(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, + }))); + 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)) + } + + 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..4745a1ce --- /dev/null +++ b/core/expression/src/lane/date/helpers.rs @@ -0,0 +1,254 @@ +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..3c7b317d --- /dev/null +++ b/core/expression/src/lane/date/mod.rs @@ -0,0 +1,975 @@ +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/exec/closure.rs b/core/expression/src/lane/exec/closure.rs new file mode 100644 index 00000000..77e6a51b --- /dev/null +++ b/core/expression/src/lane/exec/closure.rs @@ -0,0 +1,935 @@ +use super::frame::Fault; +use super::context::Context; +use super::frame::{Frame, Scratch}; +use super::Executor; +use crate::functions::ClosureFunction; +use crate::lane::columns::{Column, Values}; +use crate::lane::mask::{LaneSet, Lanes, Mask}; +use crate::lane::ops::Ops; +use crate::lane::output::Item; +use crate::lane::program::{ClosureOp, Kind, Reg}; +use crate::lane::scaled::Scaled; +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 Mask::bit(self.settled, at) { + return Ok(Some(Mask::bit(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 Some((child, column)) = Self::list_children(c, ctx) else { + return false; + }; + let child = &child; + 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 row = ctx.base + f.rows[lane] as usize; + let Some((a, b)) = column.range(row) else { + 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 (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(); + 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 mut ok = true; + let mut start = 0usize; + 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)), + ), + } + if !Self::fill_dense(frame, element, child, lo + start) { + Self::fill_with(frame, element, child, M::all(width), |_, lane| { + 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 { + 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::I64(v), false) if lo + b <= v.len() => { + f.items + .extend_selected(v.get(lo..).unwrap_or_default(), truths, a, b) + } + _ => { + for i in (a..b).filter(|i| Mask::bit(truths, *i)) { + let item = Self::child_item(child, lo + i, f); + f.items.push(item); + } + } + } + f.lists[base + lane] = (start, f.items.len() as u32); + } + 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| Mask::bit(truths, *i)) + .map(|i| child.variable(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 + } + + 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; + } + 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 body( + c: &ClosureOp, + scratch: &mut Scratch, + column: Option<&Column>, + f: &mut Frame, + rest: &mut [Frame], + ctx: &mut Context, + ) { + 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]; + 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(VMError::NumberConversionError); + 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; + } + + 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(VMError::NumberConversionError)), + }; + 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, + } + } +} diff --git a/core/expression/src/lane/exec/context.rs b/core/expression/src/lane/exec/context.rs new file mode 100644 index 00000000..e87a6bbc --- /dev/null +++ b/core/expression/src/lane/exec/context.rs @@ -0,0 +1,77 @@ +use crate::lane::columns::{Column, Columns}; +use crate::lane::program::{Binding, Program}; +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, +} + +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, + } + } + + 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 + } + + #[inline] + pub(super) fn column(&self, site: u16) -> 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..57a037fe --- /dev/null +++ b/core/expression/src/lane/exec/export.rs @@ -0,0 +1,405 @@ +use super::frame::Fault; +use super::frame::Frame; +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 { + 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())) + .flatten(), + ); + 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) + } + } + } + + 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.cell(field, lane, output, at, failed); + } + } + (Layout::List(items), Shape::List(child)) => { + let width = items.len(); + for (i, item) in items.iter().enumerate() { + self.cell(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(Fault::Vm(VMError::NumberConversionError)); + 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(Fault::Vm(VMError::NumberConversionError)); + failure(start + lane, self.stages[lane] as usize, fault); + } + } + + 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 => { + 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(VMError::NumberConversionError)), + } + } +} diff --git a/core/expression/src/lane/exec/frame.rs b/core/expression/src/lane/exec/frame.rs new file mode 100644 index 00000000..70ac1794 --- /dev/null +++ b/core/expression/src/lane/exec/frame.rs @@ -0,0 +1,843 @@ +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) bytes: Vec, + 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: u16, + pub(super) stages: Vec, + pub(super) soft: Vec<(usize, u16, Fault)>, +} + +#[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(), + } + } +} + +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.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) -> u16 { + 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], + } + } + + #[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..25070f4f --- /dev/null +++ b/core/expression/src/lane/exec/load.rs @@ -0,0 +1,1130 @@ +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::output::Item; +use crate::lane::mask::{LaneSet, Lanes, Mask}; +use crate::lane::ops::Ops; +use crate::lane::program::{Kind, Load, LoadCall, Reg}; +use crate::lane::scaled::Scaled; +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 = !matches!(c.kind, FunctionKind::Internal(InternalFunction::Rand)); + 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: u16, + 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: u16, + 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: &u16, + 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: &u16, + 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: &u16, + 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: &u16, + 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), + } + } + } + + #[inline] + 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: &u16, + id: &u16, + 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)) => Mask::bit(&matched, code), + (true, None) => false, + }; + word.put(lane, hit); + } + } + Some(Some(column)) => { + let texts = match (&k, f.dense) { + (Variable::String(_), true) => column.texts(ctx.base, f.width), + _ => None, + }; + let bytes = match column.values { + Values::Text { offsets, data } => Some((offsets, data.as_bytes())), + Values::Utf8 { offsets, data } => Some((offsets, data)), + _ => None, + }; + match (texts, bytes, k.as_str()) { + (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 = column.valid(row) + && offsets + .get(row) + .zip(offsets.get(row + 1)) + .and_then(|(a, b)| data.get(*a as usize..*b as usize)) + .is_some_and(|x| Self::same(x, k)); + 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: &u16, + 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: &u16, 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: u16, + 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(_))) + } + + pub(super) fn path_with( + 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 { .. }) { + 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(Column::bit(bits, offset + i))); + } + } + _ => { + 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); + } + + 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..32e47598 --- /dev/null +++ b/core/expression/src/lane/exec/mod.rs @@ -0,0 +1,985 @@ +mod closure; +mod context; +mod date; +mod export; +mod frame; +mod load; +mod number; +mod text; + +use crate::functions::{FunctionKind, InternalFunction}; +use crate::lane::builtins::{Arg, Builtins, Out}; +use crate::lane::interval::{Interval, IntervalData}; +use crate::lane::output::Item; +use crate::lane::mask::{LaneSet, Lanes}; +use crate::lane::ops::Ops; +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, 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), Input::Const(id)]) = (kind, args) else { + return f.none(); + }; + let Some(Variable::String(needle)) = f.consts.get(*id as usize).cloned() else { + return f.none(); + }; + let (mut word, mut done) = (f.none(), f.none()); + let needle_bytes = needle.as_bytes(); + for lane in Lanes::of(active) { + 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.as_str() => { + 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.as_str()))); + 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 + } + + #[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, + }, + } + } + + 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.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); + } + } + } + } + + 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; + } + 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, + 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), + _ => 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 + } + + 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), + } + } + 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 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]; + for lane in Lanes::of(fast) { + word.put(lane, f.text_at(*a, lane) == k.as_ref()); + } + 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::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..1d3a60b7 --- /dev/null +++ b/core/expression/src/lane/exec/number.rs @@ -0,0 +1,707 @@ +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 = uniform.is_some_and(|(x, y)| !match op { + NumOp::Multiply => Kernel::multiply((xa, x), (xb, y), m, s), + NumOp::Subtract => Kernel::add((xa, x), (xb, y), true, m, s), + _ => Kernel::add((xa, x), (xb, y), false, m, s), + }); + 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 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) { + (NumOp::Add | NumOp::Subtract | NumOp::Multiply, false) => { + Self::scaled_num(op, dst, a, b, 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: u16, 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(super) 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(super) 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/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/mask.rs b/core/expression/src/lane/mask.rs new file mode 100644 index 00000000..b9cdcc7d --- /dev/null +++ b/core/expression/src/lane/mask.rs @@ -0,0 +1,478 @@ +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 bit(words: &[u64], at: usize) -> bool { + words.get(at / 64).is_some_and(|w| w >> (at % 64) & 1 == 1) + } + + #[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..6688d6db --- /dev/null +++ b/core/expression/src/lane/mod.rs @@ -0,0 +1,960 @@ +mod builtins; +mod cells; +mod columns; +mod compile; +mod date; +mod exec; +mod interval; +mod mask; +mod ops; +mod output; +mod program; +mod scaled; +mod source; + +pub use cells::{CellEnv, CellSet, Pieces}; +pub use columns::{Column, Columns, Dictionary, Values}; +pub use compile::{Hints, LaneCompiler}; +pub use exec::{Context, Executor, Fault, Frame}; +pub use mask::{LaneSet, Mask, Word, LANES}; +pub use output::{Cell, Output, Shape}; +pub use source::SourceInfo; +pub use program::{Binary, Binding, ClosureOp, Const, Kind, Layout, Op, Program, Reg, Step}; + +use crate::lexer::Lexer; +use crate::parser::{Node, Parser}; +use crate::scope::Scope; +use crate::variable::Variable; +use crate::{ExpressionKind, IsolateError}; +use bumpalo::Bump; + +#[derive(Debug, Clone)] +enum Source { + Single(std::sync::Arc), + Many(std::sync::Arc<[(String, String)]>, bool), + Cells(std::sync::Arc<[(String, Option)]>), +} + +#[derive(Debug, Clone)] +pub struct LaneProgram { + program: Program, + kind: ExpressionKind, + source: Source, + constant: Option, +} + +impl LaneProgram { + const NODES: usize = 20_000; + + fn guard<'n>(roots: impl IntoIterator>) -> Result<(), IsolateError> { + let count = std::cell::Cell::new(0usize); + for root in roots { + root.walk(|_| count.set(count.get() + 1)); + } + match count.get() > Self::NODES { + false => Ok(()), + true => Err(IsolateError::VMError { + source: crate::vm::VMError::OpcodeErr { + opcode: "Compile".to_string(), + message: format!( + "expression is too large for the lane VM ({} nodes, limit {})", + count.get(), + Self::NODES + ), + }, + }), + } + } + + 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 { + 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()?; + Self::guard([parsed.root])?; + 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, + }) + } + + 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)) + } + } + } + + 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)); + } + Self::guard(roots.iter().map(|(_, root)| *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, + }) + } + + 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"), + }, + } + } + + 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()?; + Self::guard([parsed.root])?; + 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, + }) + } + + 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)); + } + Self::guard(roots.iter().map(|(_, root)| *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, + }) + } + + 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), + }; + } + 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) + } + + 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 + } +} + +#[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 { + 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), + ) { + 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); + } + } + } + + pub fn evaluate_many( + &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 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(), + }; + 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)); + } + + 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); + 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(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; + } + } +} + +pub struct Backend; + +impl Backend { + thread_local! { + static STATE: std::cell::RefCell = Default::default(); + } + + pub fn run( + source: &str, + kind: ExpressionKind, + scope: &Scope, + ) -> Result { + Self::STATE.with_borrow_mut(|state| { + let BackendState { + runner, + standard, + unary, + } = state; + let programs = match kind { + ExpressionKind::Standard => standard, + ExpressionKind::Unary => unary, + }; + if let Some(p) = programs.get(source) { + return runner.evaluate_one(p, scope); + } + let p = LaneProgram::compile(source, kind)?; + let result = runner.evaluate_one(&p, scope); + programs.insert(source.to_string(), p); + result + }) + } +} + +#[derive(Default)] +struct BackendState { + runner: LaneRunner, + standard: ahash::HashMap, + unary: ahash::HashMap, +} diff --git a/core/expression/src/lane/ops.rs b/core/expression/src/lane/ops.rs new file mode 100644 index 00000000..f2e8fb5a --- /dev/null +++ b/core/expression/src/lane/ops.rs @@ -0,0 +1,438 @@ +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..5570e37e --- /dev/null +++ b/core/expression/src/lane/output.rs @@ -0,0 +1,600 @@ +use crate::lane::date::Date; +use crate::lane::program::{Kind, Layout}; +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), +} + +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(), + } + } +} + +#[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; + + 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) + } + }; + 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), + _ => Item::Value( + self.values + .get(*payload as usize) + .cloned() + .unwrap_or(Variable::Null), + ), + } + } + + 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 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)>, +} + +#[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(), + } + } +} + +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(); + 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.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); + } + } + + 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(_) => 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 text(&self, row: usize) -> Option<&str> { + 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) { + (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.offsets.push(self.data.len() as u32), + (Shape::List(_), Kind::List) => self.close(), + _ => {} + } + } + + 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.offsets.push(self.data.len() as u32), + Kind::List => self.close(), + _ => {} + } + self.extra.push((at as u32, value)); + } + + pub(crate) fn set_bit(&mut self, at: usize, on: bool) { + if let Some(w) = self.bits.get_mut(at / 64) { + *w = (*w & !(1 << (at % 64))) | ((on as u64) << (at % 64)); + } + } + + pub(crate) fn push_text(&mut self, text: &str) { + self.data.extend_from_slice(text.as_bytes()); + self.offsets.push(self.data.len() as u32); + } + + fn bit(bits: &[u64], row: usize) -> bool { + bits.get(row / 64).is_some_and(|w| w >> (row % 64) & 1 == 1) + } + + 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 Self::bit(&self.failed, row) { + return Self::find(&self.errors, row).map(|failure| Cell::Error(failure.error())); + } + if self.kind != Kind::Dyn && Self::bit(&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 Self::bit(&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(Self::bit(&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..b72f8a02 --- /dev/null +++ b/core/expression/src/lane/program.rs @@ -0,0 +1,538 @@ +use crate::compiler::{Compare, FetchFastTarget}; +use crate::functions::{ClosureFunction, FunctionKind, MethodKind}; +use crate::lexer::Bracket; +use crate::variable::Variable; +use crate::vm::VMError; +use rust_decimal::Decimal; +use std::sync::Arc; +use zen_types::symbol::Symbol; + +pub type Reg = u16; +pub type MaskId = u16; + +#[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 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(Const::variable).collect()) + } + Const::Date(d) => crate::lane::date::Date(*d).variable(), + } + } + + 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, + } + } + + 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: u16, + }, + Env { + dst: Reg, + key: Arc, + site: u16, + }, + RootEnv { + dst: Reg, + }, + Path { + dst: Reg, + path: Box<[FetchFastTarget]>, + site: u16, + }, + 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: u16, + not: bool, + }, + Field { + dst: Reg, + src: Reg, + key: Arc, + site: u16, + }, + LoadEq { + dst: Reg, + load: Load, + site: u16, + id: u16, + not: bool, + }, + LoadIn { + dst: Reg, + a: Reg, + load: Load, + site: u16, + }, + LoadCall(Box), + EqAny { + dst: Reg, + a: Reg, + id: u16, + }, + InConst { + dst: Reg, + a: Reg, + id: u16, + }, + Coalesce { + dst: Reg, + a: Reg, + id: u16, + }, + SelectConst { + dst: Reg, + cond: Reg, + a: u16, + b: u16, + }, + Stage { + index: u16, + }, + Rewind, + DollarInsert { + key: Arc, + value: Reg, + }, +} + +#[derive(Debug, Clone)] +pub struct LoadCall { + pub dst: Reg, + pub load: Load, + pub site: u16, + pub kind: FunctionKind, + pub args: Box<[u16]>, + pub memo: u16, + pub scratch: Reg, + pub call: Op, +} + +#[derive(Debug, Clone, Copy)] +pub enum Input { + Reg(Reg), + Const(u16), +} + +#[derive(Debug, Clone)] +pub enum ObjectKey { + Static(Arc), + Reg(Reg), +} + +#[derive(Debug, Clone)] +pub enum Load { + Env(Arc), + Path(Box<[FetchFastTarget]>), +} + +#[derive(Debug, Clone)] +pub struct ClosureOp { + pub kind: ClosureFunction, + pub dst: Reg, + pub list: Reg, + pub source: Option<(Load, u16)>, + pub body: Program, + pub imports: Box<[(Reg, Reg)]>, + pub sequential: bool, +} + +#[derive(Debug, Clone)] +pub struct Step { + pub mask: MaskId, + pub op: Op, +} + +#[derive(Debug, Clone, Default)] +pub struct Program { + pub steps: Vec, + pub regs: u16, + pub masks: u16, + pub out: Reg, + pub element: Option, + pub writes_env: bool, + pub chain: bool, + pub frames: usize, + pub kinds: Vec, + pub sites: u16, + 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: u16, + pub layout: Option, + pub isolated: bool, +} + +#[derive(Debug, Clone)] +pub enum Layout { + Value(Reg), + Struct(Box<[(Arc, Layout)]>), + List(Box<[Layout]>), +} + +impl Program { + pub fn finish(&mut self, sites: u16) { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + self.frames = self.depth() + 1; + self.sites = sites; + self.id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for step in &mut self.steps { + if let Op::Closure(c) = &mut step.op { + c.body.finish(sites); + } + } + } + + 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) + } + + pub fn stable(&self) -> bool { + use crate::functions::InternalFunction; + let random = |kind: &FunctionKind| matches!(kind, FunctionKind::Internal(InternalFunction::Rand)); + self.steps.iter().all(|step| match &step.op { + Op::Call { kind, .. } => !random(kind), + Op::LoadCall(call) => !random(&call.kind), + Op::Closure(closure) => closure.body.stable(), + _ => true, + }) + } + + pub fn timeless(&self) -> bool { + use crate::functions::{DateMethod, DeprecatedFunction, InternalFunction, MethodKind}; + let clocked = |kind: &FunctionKind| { + matches!( + kind, + FunctionKind::Internal(InternalFunction::Rand | InternalFunction::Date) + | FunctionKind::Deprecated(DeprecatedFunction::Date | DeprecatedFunction::Time | DeprecatedFunction::DateString) + ) + }; + self.steps.iter().all(|step| match &step.op { + Op::Call { kind, .. } => !clocked(kind), + Op::LoadCall(call) => !clocked(&call.kind), + Op::Method { kind, .. } => !matches!( + kind, + MethodKind::DateMethod(DateMethod::IsToday | DateMethod::IsYesterday | DateMethod::IsTomorrow) + ), + Op::Closure(closure) => closure.body.timeless(), + _ => true, + }) + } + + fn opaque_with(&self, keys: &[Option]) -> bool { + let unkeyed = |site: u16| 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, + }) + } + + 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 depth(&self) -> usize { + self.steps + .iter() + .filter_map(|s| match &s.op { + Op::Closure(c) => Some(1 + c.body.depth()), + _ => 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..33a6ddba --- /dev/null +++ b/core/expression/src/lane/scaled.rs @@ -0,0 +1,551 @@ +use crate::lane::mask::LaneSet; +use rust_decimal::Decimal; + +pub(crate) 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 m1 == 0 || m2 == 0 { + return None; + } + if s1 < s2 { + return None; + } + let (n, scale) = (m1 as i128, s1 - s2); + let d = m2 as i128; + (n % d == 0) + .then(|| i64::try_from(n / d).ok()) + .flatten() + .map(|q| (q, scale)) + } + + 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] + pub(crate) fn parts(d: &Decimal) -> Option<(i64, u8)> { + let bytes = d.serialize(); + let flags = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + let lo = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as u64; + let mid = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as u64; + let hi = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); + let negative = flags & 0x8000_0000 != 0; + let magnitude = mid << 32 | lo; + let limit = i64::MAX as u64 + u64::from(negative); + if hi != 0 || magnitude > limit || (negative && magnitude == 0) { + return None; + } + let m = match negative { + true => (magnitude as i64).wrapping_neg(), + false => magnitude as i64, + }; + Some((m, ((flags >> 16) & 0xFF) as u8)) + } + + #[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 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 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/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..a8bdf295 100644 --- a/core/expression/src/lib.rs +++ b/core/expression/src/lib.rs @@ -65,6 +65,7 @@ mod exports; pub mod expression; pub mod functions; pub mod intellisense; +pub mod lane; pub mod lexer; pub mod parser; pub mod scope; diff --git a/core/expression/tests/lane.rs b/core/expression/tests/lane.rs new file mode 100644 index 00000000..1e2ca4a9 --- /dev/null +++ b/core/expression/tests/lane.rs @@ -0,0 +1,3035 @@ +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, 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| e.to_string()), + ExpressionKind::Unary => isolate + .run_unary(expression) + .map(Value::Bool) + .map_err(|e| e.to_string()), + } + } + + fn lane( + &self, + result: Result, + ) -> Result { + match (self.kind.clone(), result) { + (ExpressionKind::Standard, r) => r.map(|v| v.to_value()).map_err(|e| e.to_string()), + (ExpressionKind::Unary, Ok(v)) => v + .as_bool() + .map(Value::Bool) + .ok_or_else(|| zen_expression::IsolateError::ValueCastError.to_string()), + (ExpressionKind::Unary, Err(e)) => Err(e.to_string()), + } + } + + 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(&e.to_string()) { + 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 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(); +} + +#[test] +fn lane_matches_stack_vm_date_csv() { + let mut d = Differential::new(ExpressionKind::Standard); + d.file(include_str!("data/date.csv")); + d.assert(); +} + +#[test] +fn lane_matches_stack_vm_unary_csv() { + let mut d = Differential::new(ExpressionKind::Unary); + d.file(include_str!("data/unary.csv")); + d.assert(); +} + +#[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); +} + +#[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(); +} + +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(); +} + +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(); +} + +#[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") + ); +} + +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, e.to_string())) + }); + }); + 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, e.to_string())); + 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") + ); +} + +#[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(); +} + +#[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(); +} + +#[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(); +} + +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(); +} + +struct SpecLane { + runner: LaneRunner, + failures: Vec, + compared: usize, + unstable: 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(|| zen_expression::IsolateError::ValueCastError.to_string()), + (_, r) => r.map_err(|e| e.to_string()), + } + } + + 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.stack()).collect(); + let again: Vec> = cases.iter().map(|c| c.stack()).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(e.to_string())); + } + return true; + } + }; + let scopes = || cases.iter().map(|c| Self::scope(c)).collect::>(); + 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)); + } + 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, + }; + 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", + cases.len(), + lane.compared, + lane.unstable + ); + 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(); + } + } +} + +#[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; + } + } +} + +#[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:?}"); + } +} + +#[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); +} + +#[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| e.to_string()); + 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| e.to_string()); + 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| e.to_string()); + assert_eq!(reread, want, "old vm re-reading lane output of {e}"); + } + } +} + +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)"]); +} + +#[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})); +} + +#[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()); +} + +#[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}"); + } + } +} + +#[test] +fn lane_regression_oversized_expression_errors_cleanly() { + let items: Vec = (0..30_000).map(|i| format!("'s{i}'")).collect(); + let source = format!("len([{}])", items.join(", ")); + assert!(LaneProgram::standard(&source).is_err()); +} + +#[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)"]); + } +} + +#[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"]); +} + +#[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:?}"); + } + } +} + +#[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}"); + } + } +} + +#[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}"); + } + } +} + +#[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é']"]); + 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)"]); + } +} + +#[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}"); + } + } +} + +#[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); +} + +#[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"]); +} + +#[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:?}"); + } +} + +#[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| e.to_string()); + 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| e.to_string()); + if lane != stack { + mismatches.push(format!("{expression}\n stack {stack:?}\n lane {lane:?}")); + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[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]); +} diff --git a/core/types/src/variable/map.rs b/core/types/src/variable/map.rs index cce12000..869b10e3 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,87 @@ 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 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 +160,118 @@ 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)?; + match shape.without(index) { + Some(reduced) => { + *shape = reduced; + Some(values.remove(index)) + } + None => { + self.spill(); + self.remove_str(key) + } + } + } + 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)); + self.grow(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); + }; + match shape.with(&key) { + Some(child) => { + *shape = child; + values.push(value); None } - Repr::Large(map) => map.insert(key, value), + None => { + self.spill(); + self.insert(key, value) + } + } + } + + 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 +284,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 +370,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 +379,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 +402,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 +422,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 +443,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()), } } } @@ -360,6 +498,7 @@ impl PartialEq for VariableMap { impl VariableMap { 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 +522,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..aa466da9 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("$"); @@ -321,12 +323,7 @@ impl Variable { Variable::from_array(arr.iter().map(|v| v.deep_clone()).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(|value| value.deep_clone())) } _ => self.shallow_clone(), } @@ -340,14 +337,9 @@ impl Variable { 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::Object(o) => Variable::from_object( + o.borrow().map_values(|value| value.depth_clone(depth - 1)), + ), _ => self.shallow_clone(), }, } diff --git a/core/types/src/variable/shape.rs b/core/types/src/variable/shape.rs new file mode 100644 index 00000000..832c5e85 --- /dev/null +++ b/core/types/src/variable/shape.rs @@ -0,0 +1,304 @@ +use crate::symbol::Symbol; +use ahash::HashMap; +use smallvec::SmallVec; +use std::cell::RefCell; +use std::fmt::{Debug, Formatter}; +use std::rc::Rc; +use std::sync::atomic::{AtomicU64, Ordering}; + +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +const MANY_AT: usize = 8; + +const MAX_TRANSITIONS: usize = 4096; + +#[derive(Default)] +enum Transitions { + #[default] + Empty, + Few(SmallVec<[(u64, Rc); 4]>), + Many(usize, HashMap; 1]>>), +} + +impl Transitions { + fn len(&self) -> usize { + match self { + Transitions::Empty => 0, + Transitions::Few(few) => few.len(), + Transitions::Many(len, _) => *len, + } + } + + fn candidates(&self, print: u64) -> impl Iterator> { + let few = match self { + Transitions::Few(few) => Some(few.iter().filter(move |(known, _)| *known == print)), + _ => None, + }; + let many = match self { + Transitions::Many(_, map) => map.get(&print).map(|list| list.iter()), + _ => None, + }; + few.into_iter() + .flatten() + .map(|(_, child)| child) + .chain(many.into_iter().flatten()) + } + + fn push(&mut self, print: u64, child: Rc) { + match self { + Transitions::Empty => { + let mut few = SmallVec::new(); + few.push((print, child)); + *self = Transitions::Few(few); + } + Transitions::Few(few) if few.len() < MANY_AT => few.push((print, child)), + Transitions::Few(few) => { + 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); + *self = Transitions::Many(MANY_AT + 1, map); + } + Transitions::Many(len, map) => { + map.entry(print).or_default().push(child); + *len += 1; + } + } + } +} + +thread_local! { + static ROOT: Rc = Rc::new(Shape::new(Box::new([]))); +} + +pub struct Shape { + id: u64, + keys: Box<[Symbol]>, + prints: Box<[u64]>, + transitions: RefCell, +} + +impl Shape { + fn new(keys: Box<[Symbol]>) -> Self { + Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), + prints: keys.iter().map(|key| Self::print(key.as_str())).collect(), + keys, + transitions: RefCell::new(Transitions::default()), + } + } + + #[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) -> Option> { + keys.into_iter() + .try_fold(Self::root(), |shape, key| shape.with(key)) + } + + pub fn id(&self) -> u64 { + self.id + } + + pub fn keys(&self) -> &[Symbol] { + &self.keys + } + + 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 print = Self::print(key); + let transitions = self.transitions.borrow(); + let position = self.keys.len(); + transitions + .candidates(print) + .find(|child| { + Self::exact(key) + || child + .key_at(position) + .is_some_and(|known| known.as_str() == key) + }) + .cloned() + } + + pub fn with(self: &Rc, key: &Symbol) -> Option> { + if let Some(child) = self.transition(key.as_str()) { + return Some(child); + } + let mut transitions = self.transitions.borrow_mut(); + if transitions.len() >= MAX_TRANSITIONS { + return None; + } + 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())); + transitions.push(Self::print(key.as_str()), child.clone()); + Some(child) + } + + pub fn without(&self, index: usize) -> Option> { + 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()).expect("unsaturated") + } + + #[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).expect("unsaturated"); + assert!(Rc::ptr_eq(&without, &chain(&["a", "c"]))); + } + + #[test] + fn wide_fan_out_stays_interned_until_saturation() { + let root = chain(&["fanout-fixed"]); + let children: Vec> = (0..MAX_TRANSITIONS) + .map(|i| root.with(&key(&format!("k{i}"))).expect("below the cap")) + .collect(); + assert_eq!(root.transitions.borrow().len(), MAX_TRANSITIONS); + 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}"))).expect("interned"), + child + )); + } + assert!(root.with(&key("one-too-many")).is_none()); + } +}