From 14332639cebf477d1aa3ee4e6729f9af513dc5fd Mon Sep 17 00:00:00 2001 From: Stefan Miljakovic Date: Fri, 9 Oct 2026 03:03:33 +0200 Subject: [PATCH] perf: typed coverage for math builtins, list folds and member tables; exact wide-value slow path; table rule lookup --- core/engine/src/compiled/lowered.rs | 4 + core/engine/src/compiled/plan/run.rs | 22 +- core/engine/src/compiled/plan/typed.rs | 14 +- .../src/compiled/policy/columnar/fuse.rs | 15 +- core/engine/tests/compiled_policy.rs | 25 + core/expression/src/typed/batch.rs | 49 +- core/expression/src/typed/build.rs | 112 ++- core/expression/src/typed/exec.rs | 795 ++++++++++++++---- core/expression/src/typed/hir.rs | 28 + core/expression/src/typed/ins.rs | 24 +- core/expression/src/typed/lookup.rs | 369 ++++++++ core/expression/src/typed/lower.rs | 134 ++- core/expression/src/typed/mod.rs | 1 + core/expression/src/typed/num.rs | 128 ++- core/expression/src/typed/output.rs | 18 +- core/expression/src/typed/program.rs | 12 +- core/expression/src/typed/tests/exact.rs | 9 +- core/expression/src/typed/tests/interp.rs | 115 ++- core/expression/src/typed/tests/lower.rs | 6 +- core/expression/src/typed/tests/scale.rs | 61 +- core/expression/src/typed/tests/workload.rs | 166 +++- 21 files changed, 1822 insertions(+), 285 deletions(-) create mode 100644 core/expression/src/typed/lookup.rs diff --git a/core/engine/src/compiled/lowered.rs b/core/engine/src/compiled/lowered.rs index ed145ae0..3fdccfa8 100644 --- a/core/engine/src/compiled/lowered.rs +++ b/core/engine/src/compiled/lowered.rs @@ -2,6 +2,7 @@ use crate::compiled::typed::{Array, Bits, Dict, Leaf, Store}; use std::rc::Rc; use std::sync::OnceLock; use zen_expression::typed::{Data, Hir, Outputs, Slot}; +use zen_expression::Variable; pub(crate) struct Exports { dicts: Vec<(Vec, String)>, @@ -48,6 +49,9 @@ impl Exports { let len = slot.len; let dict = slot.dict(); let array = match &slot.data { + Data::Num { .. } if !slot.wide.is_empty() => { + return Leaf::Any((0..len).map(|at| slot.decimal(at).map_or(Variable::Null, Variable::Number)).collect()); + } Data::Num { .. } => match slot.take_num() { Some((mut mant, mut scale, valid)) => { let valid = Self::validity(valid, len); diff --git a/core/engine/src/compiled/plan/run.rs b/core/engine/src/compiled/plan/run.rs index e4811708..bb73847c 100644 --- a/core/engine/src/compiled/plan/run.rs +++ b/core/engine/src/compiled/plan/run.rs @@ -481,6 +481,7 @@ struct Run<'r, 'a> { runner: LaneRunner, host: Host<'r>, store: Store<'a>, + settled: bool, } impl<'a> Run<'_, 'a> { @@ -618,6 +619,10 @@ impl<'a> Run<'_, 'a> { } } } + if self.store.failed != seen { + live = self.alive(live, &mut seen); + positions = live.as_ref(); + } match &seg.end { SegEnd::Finish(refs) if matches!(refs.as_slice(), [(path, _)] if path.is_empty()) => { let leaves = self.flattened(refs[0].1, positions); @@ -864,10 +869,14 @@ impl<'a> Run<'_, 'a> { } let path = op.cost.path(); let start = Instant::now(); + let failed = self.store.failed; let typed = match path.0 { Path::Typed => self.lowered(seg, op, positions).map(|lowered| self.merged(seg, op, units, positions, lowered)).is_some(), Path::Lane => false, }; + if typed { + op.cost.failing(self.store.failed.saturating_sub(failed), local); + } if !typed { self.laned(seg, units, positions); } @@ -923,7 +932,9 @@ impl<'a> Run<'_, 'a> { take.iter_mut().for_each(|word| *word = 0); if !rerun.is_empty() { let rerun: Rc<[usize]> = rerun.into(); + self.settled = false; self.unit(seg, unit, Some(&rerun)); + self.settled = true; rerun.iter().filter(|&&row| self.store.errors[row].is_none()).for_each(|&row| Bits::set(&mut take, row, true)); } faulted = !Bits::none(&take); @@ -1712,11 +1723,11 @@ impl<'a> Run<'_, 'a> { }; columns = columns.column(key.as_ref(), view); } - let program = op - .specialized - .get_or_init(|| program.specialize_columns(&columns).ok()) - .as_ref() - .unwrap_or(program); + let program = match (op.specialized.get(), self.settled) { + (Some(special), _) => special.as_ref().unwrap_or(program), + (None, true) => op.specialized.get_or_init(|| program.specialize_columns(&columns).ok()).as_ref().unwrap_or(program), + (None, false) => program, + }; let scopes = Bound::blank(rows); let mut outs = Outs::take(); let mut failures: Vec<(usize, usize)> = Vec::new(); @@ -2298,6 +2309,7 @@ impl Plan { max_depth, }, store, + settled: true, }; let done = run.walk(root.clone()).await; let Run { runner, store, .. } = run; diff --git a/core/engine/src/compiled/plan/typed.rs b/core/engine/src/compiled/plan/typed.rs index 42dddaec..cf3b28dd 100644 --- a/core/engine/src/compiled/plan/typed.rs +++ b/core/engine/src/compiled/plan/typed.rs @@ -4,7 +4,7 @@ use crate::compiled::lowered::Exports; use crate::compiled::shred::Seen; use crate::compiled::table::Table; use crate::compiled::{Body, CompiledGraph, Kind}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, RwLock}; use std::time::Duration; use zen_expression::lane::{Binding as Site, Fusion}; @@ -61,6 +61,7 @@ pub(crate) struct Cost { calls: AtomicU32, typed: AtomicU64, lane: AtomicU64, + heavy: AtomicBool, } struct Probe<'p> { @@ -126,11 +127,18 @@ impl Cost { calls: AtomicU32::new(0), typed: AtomicU64::new(u64::MAX), lane: AtomicU64::new(u64::MAX), + heavy: AtomicBool::new(false), } } pub fn path(&self) -> (Path, bool) { let call = self.calls.fetch_add(1, Ordering::Relaxed); + if self.heavy.load(Ordering::Relaxed) { + return match call % Self::PERIOD { + 0 => (Path::Typed, true), + _ => (Path::Lane, false), + }; + } if call < Self::WARM { return (Path::Typed, false); } @@ -148,6 +156,10 @@ impl Cost { } } + pub fn failing(&self, failed: usize, rows: usize) { + self.heavy.store(failed * 4 > rows, Ordering::Relaxed); + } + pub fn record(&self, (path, fresh): (Path, bool), elapsed: Duration, rows: usize) { let per = u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128).unwrap_or(u64::MAX - 1); let cell = match path { diff --git a/core/engine/src/compiled/policy/columnar/fuse.rs b/core/engine/src/compiled/policy/columnar/fuse.rs index dd651e25..ef2a916d 100644 --- a/core/engine/src/compiled/policy/columnar/fuse.rs +++ b/core/engine/src/compiled/policy/columnar/fuse.rs @@ -154,6 +154,9 @@ impl Fused { let mut entries: Vec = Vec::new(); let mut sinks = Vec::with_capacity(blocks.len()); for &block in blocks { + if member && plan.tables[block].is_some() { + return None; + } let (unit, sunk) = Self::entries(plan, block, member)?; entries.extend(unit); sinks.extend(sunk); @@ -500,9 +503,17 @@ impl<'s, 'a> Pass<'s, 'a> { } let (entity, programs, writes) = match (&plan.tables[block], &plan.blocks.rules[block].kind) { (Some(table), BlockKind::DecisionTable(ir)) => { - let ready = len == 2 && self.owners[block].is_none() && self.quiet(block) && plan.fusions.table(block, ir); + let entity = match self.owners[block] { + Some(_) if Exports::enabled() => { + let at = self.entity_of(block)?; + self.supported(at, block, rows).then_some(Some(at))? + } + Some(_) => return None, + None => None, + }; + let ready = len == 2 && self.quiet(block) && plan.fusions.table(block, ir); let writes: Vec<(Arc, bool)> = table.outputs.iter().map(|o| (o.field.clone(), true)).collect(); - ready.then_some((None, table.programs(), writes))? + ready.then_some((entity, table.programs(), writes))? } (Some(_), _) => return None, (None, _) => { diff --git a/core/engine/tests/compiled_policy.rs b/core/engine/tests/compiled_policy.rs index 2ca39741..cd4d02d3 100644 --- a/core/engine/tests/compiled_policy.rs +++ b/core/engine/tests/compiled_policy.rs @@ -815,6 +815,31 @@ fn policy_typed_fuses_lane_runs() { assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n")); } +#[test] +fn policy_typed_member_tables_and_math() { + let policy = Anchor::POLICY + .replace( + " {expression: \"customer.total\"", + " {table: \"band\", inputs: [\"account.balance\", \"customer.tier\"], outputs: [\"account.band\", \"account.boost\"], rules: [\n [\"> 4000\", \"'gold'\", \"'A'\", \"1.5\"],\n [\"> 2000\", \"\", \"'B'\", \"2\"],\n [\"\", \"\", \"'C'\", \"0\"],\n ]},\n {expression: \"customer.total\"", + ) + .replace( + " {assertion: \"customer.eligible\"", + " {expression: \"customer.rich\", value: \"some(customer.accounts, #.balance > 4000)\"},\n {expression: \"customer.active\", value: \"all(customer.accounts, #.active)\"},\n {expression: \"customer.loans\", value: \"count(customer.accounts, #.kind == 'loan')\"},\n {expression: \"customer.third\", value: \"round(customer.total / 3, 2) + customer.total % 7\"},\n {expression: \"customer.gap\", value: \"abs(customer.total - customer.income) + min([customer.total, customer.income, 100])\"},\n {expression: \"customer.square\", value: \"floor(customer.income / 7) ^ 2\"},\n {assertion: \"customer.eligible\"", + ); + assert!(policy.contains("account.band") && policy.contains("customer.square")); + let ws = Anchor::workspace_with(&policy); + let mut failures = Vec::new(); + for seed in [5, 9] { + for (typed, laned, hosted) in Anchor::checked(&ws, &Anchor::rows(300, seed), &mut failures) { + assert_eq!(hosted, 0, "rows hosted"); + if Anchor::typed() { + assert_eq!((typed, laned), (15, 0), "units typed {typed}, laned {laned}"); + } + } + } + assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n")); +} + #[test] fn policy_typed_extremes() { let customer = |accounts: Value| json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": accounts}}); diff --git a/core/expression/src/typed/batch.rs b/core/expression/src/typed/batch.rs index ff98943d..349efa7c 100644 --- a/core/expression/src/typed/batch.rs +++ b/core/expression/src/typed/batch.rs @@ -2,6 +2,8 @@ use crate::lane::{Column, Values}; use crate::typed::hir::{ColumnDef, Dict, Hir, Kind, Unsupported}; use crate::typed::kernel::K; use crate::typed::num::Dec; +use crate::typed::output::Outputs; +use rust_decimal::Decimal; use std::borrow::Cow; #[derive(Clone, Debug, Default)] @@ -44,6 +46,7 @@ pub(crate) struct Feed<'x> { pub(crate) validity: Option<(&'x [u64], usize)>, pub(crate) holes: Option>, pub(crate) faults: Option>, + pub(crate) wide: Option<(Vec, Vec<(usize, Decimal)>)>, pub(crate) fixed: Option, } @@ -178,7 +181,7 @@ impl<'x> Feed<'x> { } fn new(data: Data<'x>, validity: Option<(&'x [u64], usize)>) -> Self { - Self { data, validity, holes: None, faults: None, fixed: None } + Self { data, validity, holes: None, faults: None, wide: None, fixed: None } } fn fault(&mut self, at: usize, len: usize) { @@ -213,19 +216,21 @@ impl<'x> Feed<'x> { (Kind::Num(_), Values::Dec(values)) => { let mut mant = Vec::with_capacity(len); let mut scale = Vec::with_capacity(len); - let mut bad = Vec::new(); + let mut wide: Vec<(usize, Decimal)> = Vec::new(); for (i, d) in values[base..base + len].iter().enumerate() { let parts = Dec::from_decimal(d); if parts.is_none() && column.valid(base + i) { - bad.push(i); + wide.push((i, *d)); } let p = parts.unwrap_or(Dec::ZERO); mant.push(p.mant); scale.push(p.scale); } let mut feed = Self::new(Data::Num { mant: Cow::Owned(mant), scale: Scales::Each(Cow::Owned(scale)) }, validity); - for i in bad { - feed.fault(i, len); + if !wide.is_empty() { + let mut bits = vec![0u64; K::words(len)]; + wide.iter().for_each(|(i, _)| K::set(&mut bits, *i, true)); + feed.wide = Some((bits, wide)); } feed.scan(len) } @@ -321,14 +326,15 @@ impl<'x> Feed<'x> { }; let mut fixed: Option = None; let mut mixed = false; - let plain = self.validity.is_none() && self.holes.is_none() && self.faults.is_none(); + let plain = self.validity.is_none() && self.holes.is_none() && self.faults.is_none() && self.wide.is_none(); if plain && !each.is_empty() { let s = each[0]; fixed = Some(s); mixed = each.iter().fold(0u8, |acc, x| acc | (x ^ s)) != 0; } for (w, chunk) in each.chunks(64).enumerate().filter(|_| !plain) { - let mut valid = self.valid_word(w * 64, chunk.len()) & !self.fault_word(w); + let wide = self.wide.as_ref().map_or(0, |(bits, _)| bits.get(w).copied().unwrap_or(0)); + let mut valid = self.valid_word(w * 64, chunk.len()) & !self.fault_word(w) & !wide; if valid == 0 { continue; } @@ -377,7 +383,7 @@ impl<'x> Feed<'x> { }, _ => vec![matcher.other; len], }; - Feed { data: Data::Codes(codes), validity: self.validity, holes: self.holes.clone(), faults: self.faults.clone(), fixed: None } + Feed { data: Data::Codes(codes), validity: self.validity, holes: self.holes.clone(), faults: self.faults.clone(), wide: None, fixed: None } } } @@ -493,6 +499,33 @@ impl<'x> Feeds<'x> { Ok(feeds) } + pub(crate) fn prefaults(&self, out: &mut Outputs, select: Option<&[u64]>) { + let mut rows: Vec = Vec::new(); + for feed in &self.columns { + if let Some(faults) = &feed.faults { + rows.extend((0..self.rows).filter(|&r| K::get(faults, r))); + } + } + for (list, feeds) in self.lists.iter().zip(&self.fields) { + for feed in feeds { + if let Some(faults) = &feed.faults { + rows.extend((0..list.len()).filter(|&e| K::get(faults, e)).map(|e| list.parent[e] as usize)); + } + } + } + rows.retain(|&r| select.is_none_or(|sel| K::get(sel, r))); + if rows.is_empty() { + return; + } + let (slots, faults) = out.parts(); + for &row in &rows { + faults.set(row); + for slot in slots.iter_mut() { + slot.fault.set(row); + } + } + } + pub(crate) fn sig(&self, hir: &Hir, into: &mut Vec>) { into.clear(); for (feed, def) in self.columns.iter().zip(&hir.schema.columns) { diff --git a/core/expression/src/typed/build.rs b/core/expression/src/typed/build.rs index fb6e1b7d..358ff682 100644 --- a/core/expression/src/typed/build.rs +++ b/core/expression/src/typed/build.rs @@ -1,6 +1,7 @@ -use crate::typed::hir::{Arith, Cmp, Fold, Hir, Kind, Lit, NodeId, Op, Scope, Unsupported}; +use crate::typed::hir::{Arith, Cmp, Fold, Func, Hir, Kind, Lit, NodeId, Op, Scope, Unsupported}; use crate::typed::ins::{Arg, Arm, BufDef, FixOp, Guard, Ins, Rep, Src, Tab, R}; use crate::typed::kernel::K; +use crate::typed::lookup::Lookup; use crate::typed::num::Dec; use std::collections::HashMap; @@ -12,6 +13,7 @@ pub(crate) struct Passes { pub(crate) reuse: bool, pub(crate) elide: bool, pub(crate) skip_min: u32, + pub(crate) lookup_min: usize, } pub(crate) struct Stage { @@ -54,7 +56,7 @@ pub(crate) struct Build<'h> { } impl Passes { - pub(crate) const ALL: Passes = Passes { fold: true, factor: true, skip: true, reuse: true, elide: true, skip_min: 2 }; + pub(crate) const ALL: Passes = Passes { fold: true, factor: true, skip: true, reuse: true, elide: true, skip_min: 2, lookup_min: 128 }; } impl Rep { @@ -185,9 +187,26 @@ impl<'h> Build<'h> { Rep::Fix(0) => Rep::Fix(0), _ => Rep::Dyn, }, - Op::Fold { fold: Fold::Sum, value: None, .. } => return Err(Unsupported::new("typed: sum without value")), - Op::Fold { .. } | Op::FirstMatch { .. } | Op::Call(crate::typed::hir::Func::Len, _) => Rep::Fix(0), - Op::Call(..) => Rep::Bool, + Op::Fold { fold: Fold::Sum | Fold::Min | Fold::Max | Fold::Avg, value: None, .. } => return Err(Unsupported::new("typed: fold without value")), + Op::Fold { fold: Fold::Min | Fold::Max, value: Some(v), .. } => match r(v) { + Rep::Fix(s) => Rep::Fix(s), + _ => Rep::Dyn, + }, + Op::Fold { fold: Fold::Avg, .. } => Rep::Dyn, + Op::Fold { fold, .. } if fold.quantifier() => Rep::Bool, + Op::Fold { .. } | Op::FirstMatch { .. } | Op::Call(Func::Len, _) => Rep::Fix(0), + Op::Call(Func::StartsWith | Func::EndsWith, _) => Rep::Bool, + Op::Call(Func::Abs, args) => args.first().map_or(Rep::Dyn, r), + Op::Call(Func::Floor | Func::Ceil, _) => Rep::Fix(0), + Op::Call(Func::Round(p), args) => match args.first().map(r) { + Some(Rep::Fix(s)) => Rep::Fix(s.min(*p)), + _ => Rep::Dyn, + }, + Op::Call(Func::Trunc(p), _) => Rep::Fix(*p), + Op::Call(Func::Min | Func::Max, args) => match args.split_first() { + Some((first, rest)) if matches!(r(first), Rep::Fix(_)) && rest.iter().all(|a| r(a) == r(first)) => r(first), + _ => Rep::Dyn, + }, }) } @@ -303,11 +322,12 @@ impl<'h> Build<'h> { } } match node.op { - Op::Fold { list, .. } => { - self.buf_of[i] = Some(self.new_buf(BufDef { scope: Scope::Row, fold: Some(list) })?); + Op::Fold { list, fold, .. } => { + let def = BufDef { scope: Scope::Row, fold: Some((list, fold, self.rep[i])), stage: self.acc[i] }; + self.buf_of[i] = Some(self.new_buf(def)?); } _ if self.cross[i] => { - self.buf_of[i] = Some(self.new_buf(BufDef { scope: node.scope, fold: None })?); + self.buf_of[i] = Some(self.new_buf(BufDef { scope: node.scope, fold: None, stage: self.stage[i] })?); } _ => {} } @@ -392,8 +412,8 @@ impl<'h> Build<'h> { }; let filter = filter.map(|x| self.val(x)).transpose()?; let value = match (fold, value) { - (Fold::Sum, Some(v)) => Some((self.val(v)?, self.rep[v as usize])), - _ => None, + (Fold::Count, _) | (_, None) => None, + (_, Some(v)) => Some((self.val(v)?, self.rep[v as usize])), }; let buf = self.buf(f as NodeId)?; self.emit(Ins::Fold { fold, buf, list, filter, value }); @@ -442,6 +462,7 @@ impl<'h> Build<'h> { Some(_) => 4, None => 30, }, + Op::Arith(Arith::Rem | Arith::Pow, ..) => 30, Op::Arith(Arith::Mul, ..) if rep != Rep::Dyn => 2, Op::Arith(..) | Op::Neg(_) if rep == Rep::Dyn => 6, Op::Call(..) => 4, @@ -612,9 +633,9 @@ impl<'h> Build<'h> { let va = self.val(a)?; let d = self.fresh()?; let ins = match (op, rep, power) { - (Arith::Add, Rep::Fix(_), _) => Ins::Fix { op: FixOp::Add, dst: d, a: va, b: self.val(b)? }, - (Arith::Sub, Rep::Fix(_), _) => Ins::Fix { op: FixOp::Sub, dst: d, a: va, b: self.val(b)? }, - (Arith::Mul, Rep::Fix(_), _) => Ins::Fix { op: FixOp::Mul, dst: d, a: va, b: self.val(b)? }, + (Arith::Add, Rep::Fix(_), _) => Ins::Fix { op: FixOp::Add, dst: d, a: va, b: self.val(b)?, rep }, + (Arith::Sub, Rep::Fix(_), _) => Ins::Fix { op: FixOp::Sub, dst: d, a: va, b: self.val(b)?, rep }, + (Arith::Mul, Rep::Fix(_), _) => Ins::Fix { op: FixOp::Mul, dst: d, a: va, b: self.val(b)?, rep }, (Arith::Div, _, Some((k, by))) => Ins::DivPow { dst: d, a: va, ra, k, by }, _ => Ins::Num { op, dst: d, a: va, ra, b: self.val(b)?, rb }, }; @@ -668,19 +689,19 @@ impl<'h> Build<'h> { let ins = match (ra, rb) { (Rep::Fix(x), Rep::Fix(y)) if x == y => { let (va, vb) = (self.val(a)?, self.val(b)?); - Ins::CmpFix { op, dst: self.fresh()?, a: va, b: vb } + Ins::CmpFix { op, dst: self.fresh()?, a: va, b: vb, rep: ra } } (Rep::Fix(x), Rep::Fix(y)) if self.passes.fold && x < y && up(self.konst_num(a), y).is_some() => { let u = up(self.konst_num(a), y).ok_or_else(|| Unsupported::new("typed: upscale"))?; let k = self.konst(Lit::Num(u), Rep::Fix(y))?; let vb = self.val(b)?; - Ins::CmpFix { op, dst: self.fresh()?, a: k, b: vb } + Ins::CmpFix { op, dst: self.fresh()?, a: k, b: vb, rep: rb } } (Rep::Fix(x), Rep::Fix(y)) if self.passes.fold && y < x && up(self.konst_num(b), x).is_some() => { let u = up(self.konst_num(b), x).ok_or_else(|| Unsupported::new("typed: upscale"))?; let k = self.konst(Lit::Num(u), Rep::Fix(x))?; let va = self.val(a)?; - Ins::CmpFix { op, dst: self.fresh()?, a: va, b: k } + Ins::CmpFix { op, dst: self.fresh()?, a: va, b: k, rep: ra } } (x, y) if x.num() && y.num() => self.cmp_num(op, a, b)?, (Rep::Code, Rep::Code) if eq => { @@ -736,7 +757,7 @@ impl<'h> Build<'h> { let d = self.fresh()?; let mr = match (self.rep[*x as usize], tr) { (Rep::Fix(0), Rep::Fix(0)) => { - self.emit(Ins::Fix { op: FixOp::Mul, dst: d, a: vx, b: t }); + self.emit(Ins::Fix { op: FixOp::Mul, dst: d, a: vx, b: t, rep: Rep::Fix(0) }); Rep::Fix(0) } (rx, _) => { @@ -885,23 +906,35 @@ impl<'h> Build<'h> { Some((l, h)) if h >= l => (l, h.wrapping_sub(l) as u64, false), _ => (0, 0, true), }; - self.emit(Ins::InRangeFix { dst: d, a: va, lo, span, empty }) + self.emit(Ins::InRangeFix { dst: d, a: va, lo, span, empty, range: *r }) } None => self.emit(Ins::InRangeGen { dst: d, a: va, ra, range: *r }), } d } - Op::FirstMatch { conds, strict } => { - let mut vs = Vec::with_capacity(conds.len()); - for c in conds { - vs.push(self.val(*c)?); + Op::FirstMatch { conds, strict } => match self.lookup(conds, *strict) { + Some(tab) => self.looked(tab)?, + None => { + let mut vs = Vec::with_capacity(conds.len()); + for c in conds { + vs.push(self.val(*c)?); + } + let sel = self.needs_sel(i); + let d = self.fresh()?; + self.emit(Ins::First { dst: d, conds: vs, sel, strict: *strict }); + d + } + }, + Op::Pick(sel, arms) => self.pick(i, *sel, arms, rep)?, + Op::Call(func, args) if !func.text() => { + let mut vs = Vec::with_capacity(args.len()); + for a in args { + vs.push((self.val(*a)?, self.rep[*a as usize])); } - let sel = self.needs_sel(i); let d = self.fresh()?; - self.emit(Ins::First { dst: d, conds: vs, sel, strict: *strict }); + self.emit(Ins::Math { func: *func, dst: d, args: vs, rep }); d } - Op::Pick(sel, arms) => self.pick(i, *sel, arms, rep)?, Op::Call(func, args) => { let a = self.arg(*args.first().ok_or_else(|| Unsupported::new("typed: call"))?)?; let b = args.get(1).map(|x| self.arg(*x)).transpose()?; @@ -921,6 +954,35 @@ impl<'h> Build<'h> { Ok(()) } + fn lookup(&self, conds: &[NodeId], strict: bool) -> Option { + if !self.passes.fold { + return None; + } + let tab = Lookup::plan(self.hir, conds, strict, self.passes.lookup_min)?; + tab.keys.iter().filter_map(|k| k.node).all(|n| self.stage[n as usize] == self.cur || self.is_const(n)).then_some(tab) + } + + fn looked(&mut self, mut tab: Lookup) -> Result { + let mut keys = Vec::with_capacity(tab.keys.len()); + let mut reps = Vec::with_capacity(tab.keys.len()); + for key in &tab.keys { + match key.node { + Some(n) => { + keys.push(Some((self.val(n)?, self.rep[n as usize]))); + reps.push(self.rep[n as usize]); + } + None => { + keys.push(None); + reps.push(Rep::Null); + } + } + } + tab.fix(&reps); + let d = self.fresh()?; + self.emit(Ins::Lookup { dst: d, keys, tab: Box::new(tab) }); + Ok(d) + } + fn finish(self) -> Result { let Build { mut code, keys, next, pinned, consts, defs, passes, .. } = self; let mut phys: Vec = (0..next).map(|v| v as R).collect(); diff --git a/core/expression/src/typed/exec.rs b/core/expression/src/typed/exec.rs index 6b7c4930..7e2650db 100644 --- a/core/expression/src/typed/exec.rs +++ b/core/expression/src/typed/exec.rs @@ -1,16 +1,19 @@ use crate::lane::Column; use crate::typed::batch::{Data, Feed, Feeds, Lists, Scales, Text}; -use crate::typed::hir::{Arith, Cmp, Fold, Func, Lit, Scope}; +use crate::typed::hir::{Arith, Cmp, Fold, Func, Lit, Range, Scope}; use crate::typed::ins::{Arg, FixOp, Guard, Ins, Rep, Src, Tab, R}; use crate::typed::kernel::K; -use crate::typed::num::Dec; +use crate::typed::lookup::{Domain, Lookup}; +use crate::typed::num::{Dec, N}; use crate::typed::output::{Data as SlotData, Outputs}; +use rust_decimal::Decimal; use std::cmp::Ordering; #[derive(Clone, Copy, Debug, PartialEq)] enum V { Null, Num(Dec), + Big(Decimal), Bool(bool), Code(i32), Other, @@ -24,6 +27,8 @@ pub(crate) struct Reg { pub(crate) bits: [u64; Reg::WORDS], pub(crate) valid: [u64; Reg::WORDS], pub(crate) fault: [u64; Reg::WORDS], + pub(crate) wide: [u64; Reg::WORDS], + pub(crate) big: Vec, pub(crate) masks: Vec, } @@ -35,6 +40,9 @@ pub(crate) struct Buf { pub(crate) bits: Vec, pub(crate) valid: Vec, pub(crate) fault: Vec, + pub(crate) wide: Vec, + pub(crate) big: Vec, + pub(crate) any: bool, } struct Others<'r> { @@ -71,15 +79,35 @@ impl V { } } + fn number(self) -> Option { + match self { + V::Num(d) => Some(N::Dec(d)), + V::Big(d) => Some(N::Big(d)), + _ => None, + } + } + fn same(self, other: V) -> bool { + if let (Some(x), Some(y)) = (self.number(), other.number()) { + return x.compare(y) == Ordering::Equal; + } match (self, other) { - (V::Num(x), V::Num(y)) => x.eq_value(y), (V::Other, _) | (_, V::Other) => false, (x, y) => x == y, } } } +impl Range { + #[inline] + fn holds(&self, x: N) -> bool { + let (lo, hi) = (x.compare(N::Dec(self.lo)), x.compare(N::Dec(self.hi))); + let above = lo == Ordering::Greater || (self.lo_closed && lo == Ordering::Equal); + let below = hi == Ordering::Less || (self.hi_closed && hi == Ordering::Equal); + above && below + } +} + impl Rep { #[inline] pub(crate) fn scale_at(self, reg: &Reg, i: usize) -> u8 { @@ -113,6 +141,65 @@ impl Buf { self.bits.resize(words, 0); self.valid.resize(words, 0); self.fault.resize(words, 0); + self.wide.clear(); + self.wide.resize(words, 0); + self.any = false; + } + + #[inline] + pub(crate) fn num(&self, rep: Rep, r: usize) -> N { + match self.any && K::get(&self.wide, r) { + true => N::Big(self.big.get(r).copied().unwrap_or_default()), + false => N::Dec(Dec::new(self.mant[r], match rep { + Rep::Fix(s) => s, + _ => self.scale[r], + })), + } + } + + #[inline] + pub(crate) fn keep(&mut self, rep: Rep, r: usize, n: N) { + match n { + N::Dec(d) if rep == Rep::Dyn || rep == Rep::Fix(d.scale) => { + self.mant[r] = d.mant; + self.scale[r] = d.scale; + if self.any { + K::set(&mut self.wide, r, false); + } + } + n => { + if self.big.len() < self.mant.len() { + self.big.resize(self.mant.len(), Decimal::ZERO); + } + self.big[r] = n.decimal(); + self.mant[r] = 0; + self.scale[r] = 0; + self.any = true; + K::set(&mut self.wide, r, true); + } + } + } + + pub(crate) fn finish(&mut self, fold: Fold, rep: Rep) { + let len = self.mant.len(); + for r in 0..len { + if K::get(&self.fault, r) { + continue; + } + let seen = self.codes[r]; + match fold { + Fold::Any if seen == 0 => K::set(&mut self.bits, r, false), + Fold::All | Fold::None if seen == 0 => K::set(&mut self.bits, r, true), + Fold::One => K::set(&mut self.bits, r, self.mant[r] == 1), + Fold::Min | Fold::Max if seen == 0 => K::set(&mut self.fault, r, true), + Fold::Avg if seen == 0 => K::set(&mut self.fault, r, true), + Fold::Avg => match self.num(rep, r).arith(Arith::Div, N::Dec(Dec::int(i64::from(seen)))) { + Ok(Some(q)) => self.keep(rep, r, q), + _ => K::set(&mut self.fault, r, true), + }, + _ => {} + } + } } } @@ -128,6 +215,8 @@ impl Reg { bits: [0; Self::WORDS], valid: [0; Self::WORDS], fault: [0; Self::WORDS], + wide: [0; Self::WORDS], + big: Vec::new(), masks: Vec::new(), } } @@ -135,6 +224,7 @@ impl Reg { pub(crate) fn fill(&mut self, rep: Rep, lit: &Lit) { self.valid.fill(u64::MAX); self.fault.fill(0); + self.wide.fill(0); match lit { Lit::Num(d) => { self.mant.fill(d.mant); @@ -164,6 +254,9 @@ impl Reg { if !self.ok(i) { return V::Null; } + if self.wide(i) { + return V::Big(self.big.get(i).copied().unwrap_or_default()); + } match rep { Rep::Fix(s) => V::Num(Dec::new(self.mant[i], s)), Rep::Dyn => V::Num(Dec::new(self.mant[i], self.scale[i])), @@ -178,6 +271,58 @@ impl Reg { self.mant[i] = d.mant; self.scale[i] = d.scale; } + + #[inline] + fn wide(&self, i: usize) -> bool { + K::get(&self.wide, i) + } + + #[inline] + pub(crate) fn num(&self, rep: Rep, i: usize) -> N { + match self.wide(i) { + true => N::Big(self.big.get(i).copied().unwrap_or_default()), + false => N::Dec(Dec::new(self.mant[i], rep.scale_at(self, i))), + } + } + + #[inline] + pub(crate) fn keep(&mut self, rep: Rep, i: usize, n: N) { + match n { + N::Dec(d) if rep == Rep::Dyn || rep == Rep::Fix(d.scale) => { + self.put(i, d); + K::set(&mut self.wide, i, false); + } + n => { + if self.big.len() < Self::LANES { + self.big.resize(Self::LANES, Decimal::ZERO); + } + self.big[i] = n.decimal(); + self.put(i, Dec::ZERO); + K::set(&mut self.wide, i, true); + } + } + } + + #[inline] + fn widened(&self, words: usize) -> bool { + self.wide[..words].iter().any(|w| *w != 0) + } + + #[inline] + fn adopt(&mut self, from: &Reg, mask: &[u64]) { + for (w, &m) in mask.iter().enumerate() { + let mut bits = m & from.wide[w]; + self.wide[w] |= bits; + while bits != 0 { + let i = w * 64 + bits.trailing_zeros() as usize; + bits &= bits - 1; + if self.big.len() < Self::LANES { + self.big.resize(Self::LANES, Decimal::ZERO); + } + self.big[i] = from.big.get(i).copied().unwrap_or_default(); + } + } + } } impl<'a, 'x> TV<'a, 'x> { @@ -240,12 +385,11 @@ impl<'e, 'x> Exec<'e, 'x> { } #[inline(always)] - fn num(&self, op: Arith, d: &mut Reg, act: Option<&[u64; Reg::WORDS]>, x: impl Fn(usize) -> Dec, y: impl Fn(usize) -> Dec) { + fn num(&self, op: Arith, d: &mut Reg, act: Option<&[u64; Reg::WORDS]>, ovf: &mut [u64; Reg::WORDS], x: impl Fn(usize) -> Dec, y: impl Fn(usize) -> Dec) { let words = self.words.min(Reg::WORDS); - if act.is_none() && op != Arith::Div { - let mut bad = [0u64; Reg::WORDS]; + if act.is_none() && matches!(op, Arith::Add | Arith::Sub | Arith::Mul) { let (mant, scale) = (&mut d.mant, &mut d.scale); - K::pack_idx(self.n, &mut bad[..words], |i| { + K::pack_idx(self.n, &mut ovf[..words], |i| { let (p, q) = (x(i), y(i)); let (r, s, o) = match op { Arith::Mul => K::mul(p.mant, q.mant, p.scale, q.scale), @@ -255,32 +399,66 @@ impl<'e, 'x> Exec<'e, 'x> { scale[i] = s; o }); - for (f, b) in d.fault[..words].iter_mut().zip(&bad) { - *f |= b; - } return; } let skip = d.fault; - self.each(act, &skip, |i| { - let r = match op { - Arith::Add => x(i).checked_add(y(i)).map(Some), - Arith::Sub => x(i).checked_sub(y(i)).map(Some), - Arith::Mul => x(i).checked_mul(y(i)).map(Some), - Arith::Div => x(i).checked_div(y(i)), - }; - match r { - Ok(Some(q)) => d.put(i, q), - Ok(None) => K::set(&mut d.valid, i, false), - Err(_) => K::set(&mut d.fault, i, true), - } + self.each(act, &skip, |i| match x(i).arith(op, y(i)) { + Ok(Some(q)) => d.put(i, q), + Ok(None) => K::set(&mut d.valid, i, false), + Err(_) => K::set(ovf, i, true), }); } + fn redo(&self, d: &mut Reg, act: Option<&[u64; Reg::WORDS]>, ovf: &[u64; Reg::WORDS], rep: Rep, mut f: impl FnMut(usize) -> Result, ()>) { + let words = self.words.min(Reg::WORDS); + let mut m = [0u64; Reg::WORDS]; + for w in 0..words { + m[w] = ovf[w] & !d.fault[w] & d.valid[w]; + } + if m[..words].iter().all(|w| *w == 0) { + return; + } + self.over(act, &m, |i| match f(i) { + Ok(Some(v)) => d.keep(rep, i, v), + Ok(None) => K::set(&mut d.valid, i, false), + Err(()) => K::set(&mut d.fault, i, true), + }); + } + + #[inline(always)] + fn over(&self, act: Option<&[u64; Reg::WORDS]>, mask: &[u64; Reg::WORDS], mut f: impl FnMut(usize)) { + for w in 0..self.words.min(Reg::WORDS) { + let mut m = act.map_or(u64::MAX, |a| a[w]) & self.tail(w) & mask[w]; + while m != 0 { + let i = w * 64 + m.trailing_zeros() as usize; + m &= m - 1; + f(i); + } + } + } + + fn patch(&self, d: &mut Reg, a: &Reg, b: Option<&Reg>, mut f: impl FnMut(usize) -> bool) { + for w in 0..self.words.min(Reg::WORDS) { + let (bw, bv) = b.map_or((0, u64::MAX), |b| (b.wide[w], b.valid[w])); + let mut m = (a.wide[w] | bw) & a.valid[w] & bv & self.tail(w); + while m != 0 { + let j = m.trailing_zeros() as usize; + m &= m - 1; + let bit = 1u64 << j; + match f(w * 64 + j) { + true => d.bits[w] |= bit, + false => d.bits[w] &= !bit, + } + } + } + } + #[inline] fn def(regs: &mut [Reg], dst: R, f: impl FnOnce(&mut Reg, &Others)) { let at = dst as usize; let (lo, rest) = regs.split_at_mut(at); if let Some((d, hi)) = rest.split_first_mut() { + d.wide = [0; Reg::WORDS]; f(d, &Others { lo, hi, at }); } } @@ -447,6 +625,13 @@ impl<'e, 'x> Exec<'e, 'x> { K::pack1(parent, &mut d.valid[..words], |p| K::get(&b.valid, p as usize)); K::pack1(parent, &mut d.fault[..words], |p| K::get(&b.fault, p as usize)); } + if b.any && !K::range(&b.wide, r0, r1, false) { + for (i, &p) in parent.iter().enumerate() { + if K::get(&b.wide, p as usize) { + d.keep(Rep::Dyn, i, N::Big(b.big.get(p as usize).copied().unwrap_or_default())); + } + } + } }); } Ins::Fill { dst, buf, rep } => { @@ -455,6 +640,13 @@ impl<'e, 'x> Exec<'e, 'x> { Self::def(regs, *dst, |d, _| { d.valid[..words].copy_from_slice(&b.valid[w0..w0 + words]); d.fault[..words].copy_from_slice(&b.fault[w0..w0 + words]); + if b.any && !K::range(&b.wide, start, start + n, false) { + for i in 0..n { + if K::get(&b.wide, start + i) { + d.keep(Rep::Dyn, i, N::Big(b.big.get(start + i).copied().unwrap_or_default())); + } + } + } match rep { Rep::Fix(_) => d.mant[..n].copy_from_slice(&b.mant[start..start + n]), Rep::Dyn => { @@ -473,6 +665,18 @@ impl<'e, 'x> Exec<'e, 'x> { let w0 = start / 64; b.valid[w0..w0 + words].copy_from_slice(&r.valid[..words]); b.fault[w0..w0 + words].copy_from_slice(&r.fault[..words]); + b.wide[w0..w0 + words].copy_from_slice(&r.wide[..words]); + if r.widened(words) { + if b.big.len() < b.mant.len() { + b.big.resize(b.mant.len(), Decimal::ZERO); + } + b.any = true; + for i in 0..n { + if r.wide(i) { + b.big[start + i] = r.big.get(i).copied().unwrap_or_default(); + } + } + } match rep { Rep::Fix(_) => b.mant[start..start + n].copy_from_slice(&r.mant[..n]), Rep::Dyn => { @@ -484,49 +688,72 @@ impl<'e, 'x> Exec<'e, 'x> { Rep::Text | Rep::Null => {} } } - Ins::Fix { op, dst, a, b } => Self::def(regs, *dst, |d, regs| { + Ins::Fix { op, dst, a, b, rep } => Self::def(regs, *dst, |d, regs| { let (a, b) = (®s[*a as usize], ®s[*b as usize]); self.strict2(d, a, b); - let (x, y, o, f) = (&a.mant[..n], &b.mant[..n], &mut d.mant[..n], &mut d.fault[..words]); + let mut ovf = [0u64; Reg::WORDS]; + let (x, y, o, f) = (&a.mant[..n], &b.mant[..n], &mut d.mant[..n], &mut ovf[..words]); match op { FixOp::Add => K::ovf2(x, y, o, f, i64::overflowing_add), FixOp::Sub => K::ovf2(x, y, o, f, i64::overflowing_sub), FixOp::Mul => K::ovf2(x, y, o, f, i64::overflowing_mul), } + for w in 0..words { + ovf[w] |= a.wide[w] | b.wide[w]; + } + let op = match op { + FixOp::Add => Arith::Add, + FixOp::Sub => Arith::Sub, + FixOp::Mul => Arith::Mul, + }; + let rep = *rep; + self.redo(d, act, &ovf, rep, |i| a.num(rep, i).arith(op, b.num(rep, i)).map_err(|_| ())); }), Ins::Neg { dst, a, rep } => Self::def(regs, *dst, |d, regs| { let a = ®s[*a as usize]; self.strict1(d, a); - K::ovf1(&a.mant[..n], &mut d.mant[..n], &mut d.fault[..words], |x| (x.wrapping_neg(), (x == 0) | (x == i64::MIN))); + let mut ovf = [0u64; Reg::WORDS]; + K::ovf1(&a.mant[..n], &mut d.mant[..n], &mut ovf[..words], |x| (x.wrapping_neg(), (x == 0) | (x == i64::MIN))); if *rep == Rep::Dyn { d.scale[..n].copy_from_slice(&a.scale[..n]); } + for w in 0..words { + ovf[w] |= a.wide[w]; + } + let rep = *rep; + self.redo(d, act, &ovf, rep, |i| Ok(Some(a.num(rep, i).neg()))); }), Ins::Num { op, dst, a, ra, b, rb } => Self::def(regs, *dst, |d, regs| { let (a, b) = (®s[*a as usize], ®s[*b as usize]); self.strict2(d, a, b); let (am, bm) = (&a.mant[..n], &b.mant[..n]); - if act.is_none() && *op != Arith::Div { + let mut ovf = [0u64; Reg::WORDS]; + let (op, ra, rb) = (*op, *ra, *rb); + if act.is_none() && matches!(op, Arith::Add | Arith::Sub | Arith::Mul) { let (mut pa, mut pb) = ([0u8; Reg::LANES], [0u8; Reg::LANES]); - let (asc, bsc) = (Self::scales(*ra, a, &mut pa, n), Self::scales(*rb, b, &mut pb, n)); - let (sub, mul) = (*op == Arith::Sub, *op == Arith::Mul); - let (dm, ds, df) = (&mut d.mant[..n], &mut d.scale[..n], &mut d.fault[..words]); + let (asc, bsc) = (Self::scales(ra, a, &mut pa, n), Self::scales(rb, b, &mut pb, n)); + let (sub, mul) = (op == Arith::Sub, op == Arith::Mul); + let (dm, ds, df) = (&mut d.mant[..n], &mut d.scale[..n], &mut ovf[..words]); match mul { true => K::dyn2(am, bm, asc, bsc, dm, ds, df, K::mul), false => K::dyn2(am, bm, asc, bsc, dm, ds, df, |x, y, p, q| K::add(sub, x, y, p, q)), } - return; + } else { + self.num(op, d, act, &mut ovf, |i| Dec::new(am[i], ra.scale_at(a, i)), |i| Dec::new(bm[i], rb.scale_at(b, i))); } - let (ra, rb) = (*ra, *rb); - self.num(*op, d, act, |i| Dec::new(am[i], ra.scale_at(a, i)), |i| Dec::new(bm[i], rb.scale_at(b, i))); + for w in 0..words { + ovf[w] |= a.wide[w] | b.wide[w]; + } + self.redo(d, act, &ovf, Rep::Dyn, |i| a.num(ra, i).arith(op, b.num(rb, i)).map_err(|_| ())); }), Ins::DivPow { dst, a, ra, k, by } => Self::def(regs, *dst, |d, regs| { let a = ®s[*a as usize]; self.strict1(d, a); let (k, by, ra) = (*k, *by, *ra); - let slow_lane = |i: usize, d: &mut Reg| match Dec::new(a.mant[i], ra.scale_at(a, i)).div_power(k, by) { + let mut ovf = [0u64; Reg::WORDS]; + let mut slow_lane = |i: usize, d: &mut Reg| match Dec::new(a.mant[i], ra.scale_at(a, i)).div_power(k, by) { Ok(q) => d.put(i, q), - Err(_) => K::set(&mut d.fault, i, true), + Err(_) => K::set(&mut ovf, i, true), }; let mut slow = [0u64; Reg::WORDS]; let shift = match ra { @@ -562,6 +789,11 @@ impl<'e, 'x> Exec<'e, 'x> { *word = !(*word & !d.fault[w]); } self.each(None, &slow, |i| slow_lane(i, d)); + for w in 0..words { + ovf[w] |= a.wide[w]; + } + let divisor = N::Dec(Dec::new(Dec::POW10[k as usize], by)); + self.redo(d, act, &ovf, Rep::Dyn, |i| a.num(ra, i).arith(Arith::Div, divisor).map_err(|_| ())); }), Ins::PickTab { dst, sel, tab, rep } => Self::def(regs, *dst, |d, regs| { let s = ®s[*sel as usize]; @@ -589,7 +821,7 @@ impl<'e, 'x> Exec<'e, 'x> { K::pack1(sm, &mut d.valid[..words], |x| Tab::bit(&tab.ok, x as usize)); d.fault[..words].copy_from_slice(&s.fault[..words]); }), - Ins::CmpFix { op, dst, a, b } => Self::def(regs, *dst, |d, regs| { + Ins::CmpFix { op, dst, a, b, rep } => Self::def(regs, *dst, |d, regs| { let (a, b) = (®s[*a as usize], ®s[*b as usize]); let (x, y, o) = (&a.mant[..n], &b.mant[..n], &mut d.bits[..words]); match op { @@ -599,8 +831,10 @@ impl<'e, 'x> Exec<'e, 'x> { Cmp::Gt => K::pack2(x, y, o, |x, y| x > y), Cmp::Ge => K::pack2(x, y, o, |x, y| x >= y), } + let (op, rep) = (*op, *rep); + self.patch(d, a, Some(b), |i| K::ord(op, a.num(rep, i).compare(b.num(rep, i)))); match op { - Cmp::Eq | Cmp::Ne => self.eq_meta(d, a, b, *op == Cmp::Ne), + Cmp::Eq | Cmp::Ne => self.eq_meta(d, a, b, op == Cmp::Ne), _ => self.strict2(d, a, b), } }), @@ -620,6 +854,7 @@ impl<'e, 'x> Exec<'e, 'x> { K::ord(op, x.compare(y)) }; self.bools(act, &mut d.bits, f); + self.patch(d, a, Some(b), |i| K::ord(op, a.num(ra, i).compare(b.num(rb, i)))); match op { Cmp::Eq | Cmp::Ne => self.eq_meta(d, a, b, op == Cmp::Ne), _ => self.strict2(d, a, b), @@ -639,6 +874,8 @@ impl<'e, 'x> Exec<'e, 'x> { Rep::Fix(s) => K::pack1(am, o, |m| slow(m, s)), _ => K::pack2(am, asc, o, slow), } + let ra = *ra; + self.patch(d, a, None, |i| K::ord(op, a.num(ra, i).compare(N::Dec(k)))); for w in 0..words { match op { Cmp::Eq | Cmp::Ne => { @@ -677,7 +914,7 @@ impl<'e, 'x> Exec<'e, 'x> { let mut hit = 0u64; for j in 0..(n - w * 64).min(64) { let i = w * 64 + j; - let order = Dec::new(a.mant[i], ra.scale_at(a, i)).compare(Dec::new(b.mant[i], rb.scale_at(b, i))); + let order = a.num(*ra, i).compare(b.num(*rb, i)); hit |= u64::from(K::ord(*op, order)) << j; } let both = a.valid[w] & b.valid[w]; @@ -703,8 +940,7 @@ impl<'e, 'x> Exec<'e, 'x> { let r = match (op, x, y) { (Cmp::Eq, x, y) => Some(x.same(y)), (Cmp::Ne, x, y) => Some(!x.same(y)), - (_, V::Num(x), V::Num(y)) => Some(K::ord(*op, x.compare(y))), - _ => None, + (_, x, y) => x.number().zip(y.number()).map(|(x, y)| K::ord(*op, x.compare(y))), }; match r { Some(v) => K::set(&mut d.bits, i, v), @@ -756,13 +992,14 @@ impl<'e, 'x> Exec<'e, 'x> { K::set(&mut d.bits, i, set.iter().any(|l| x.same(V::lit(l)))); } }), - Ins::InRangeFix { dst, a, lo, span, empty } => Self::def(regs, *dst, |d, regs| { + Ins::InRangeFix { dst, a, lo, span, empty, range } => Self::def(regs, *dst, |d, regs| { let a = ®s[*a as usize]; let (lo, span) = (*lo, *span); match empty { true => d.bits[..words].fill(0), false => K::pack1(&a.mant[..n], &mut d.bits[..words], |x| (x.wrapping_sub(lo) as u64) <= span), } + self.patch(d, a, None, |i| range.holds(a.num(Rep::Dyn, i))); self.strict1(d, a); }), Ins::InRangeGen { dst, a, ra, range } => Self::def(regs, *dst, |d, regs| { @@ -772,11 +1009,7 @@ impl<'e, 'x> Exec<'e, 'x> { let mut hit = 0u64; for j in 0..(n - w * 64).min(64) { let i = w * 64 + j; - let x = Dec::new(a.mant[i], ra.scale_at(a, i)); - let (lo, hi) = (x.compare(range.lo), x.compare(range.hi)); - let above = lo == Ordering::Greater || (range.lo_closed && lo == Ordering::Equal); - let below = hi == Ordering::Less || (range.hi_closed && hi == Ordering::Equal); - hit |= u64::from(above && below) << j; + hit |= u64::from(range.holds(a.num(*ra, i))) << j; } d.bits[w] = hit & a.valid[w]; } @@ -818,6 +1051,14 @@ impl<'e, 'x> Exec<'e, 'x> { d.fault[w] = c.fault[w] | !c.valid[w] | (ct[w] & t.fault[w]) | (cf & e.fault[w]); } self.values(d, &ct[..words], (t, *rt), (e, *re), *rep); + if rep.num() && (t.widened(words) || e.widened(words)) { + let mut cf = [0u64; Reg::WORDS]; + for w in 0..words { + cf[w] = !c.bits[w] & c.valid[w]; + } + d.adopt(t, &ct[..words]); + d.adopt(e, &cf[..words]); + } }), Ins::SelK { dst, c, t, e, rep } => Self::def(regs, *dst, |d, regs| { let c = ®s[*c as usize]; @@ -849,6 +1090,97 @@ impl<'e, 'x> Exec<'e, 'x> { d.fault[w] = a.fault[w] | (!a.valid[w] & b.fault[w]); } self.values(d, &m[..words], (a, *ra), (b, *rb), *rep); + if rep.num() && (a.widened(words) || b.widened(words)) { + let mut e = [0u64; Reg::WORDS]; + for w in 0..words { + e[w] = !a.valid[w]; + } + d.adopt(a, &m[..words]); + d.adopt(b, &e[..words]); + } + }), + Ins::Lookup { dst, keys, tab } => Self::def(regs, *dst, |d, regs| { + let (rules, rw) = (tab.rules, tab.words); + if d.masks.len() < (rules + 1) * Reg::WORDS { + d.masks.resize((rules + 1) * Reg::WORDS, 0); + } + for ci in 0..=rules { + d.masks[ci * Reg::WORDS..ci * Reg::WORDS + words].fill(0); + } + d.valid[..words].fill(u64::MAX); + d.fault[..words].fill(0); + for (r, _) in keys.iter().flatten() { + let x = ®s[*r as usize]; + for w in 0..words { + d.fault[w] |= x.fault[w]; + } + } + let mut full = [0u64; Lookup::WORDS]; + for (w, f) in full.iter_mut().enumerate().take(rw) { + *f = match rules - w * 64 { + left if left >= 64 => u64::MAX, + left => (1u64 << left) - 1, + }; + } + if rw == 1 { + let (mut acc, mut bad, mut at) = ([full[0]; Reg::LANES], [0u64; Reg::LANES], [0usize; Reg::LANES]); + for (key, reg) in tab.keys.iter().zip(keys) { + Self::indexes(key, reg.map(|(r, rep)| (®s[r as usize], rep)), &mut at[..n]); + if key.bad.iter().any(|b| *b != 0) { + for ((a, b), &v) in acc[..n].iter_mut().zip(bad[..n].iter_mut()).zip(&at[..n]) { + *b |= *a & key.bad[v]; + } + } + let hit = &key.hit[..]; + for (a, &v) in acc[..n].iter_mut().zip(&at[..n]) { + *a &= hit.get(v).copied().unwrap_or(0); + } + } + for i in 0..n { + let m = acc[i] | bad[i]; + let sel = match m { + 0 => rules, + m => m.trailing_zeros() as usize, + }; + if (bad[i] & m & m.wrapping_neg()) != 0 { + K::set(&mut d.fault, i, true); + } + d.mant[i] = sel as i64; + d.masks[sel * Reg::WORDS + i / 64] |= 1u64 << (i % 64); + } + return; + } + let mut at = [0usize; Reg::LANES]; + let mut acc = vec![[0u64; Lookup::WORDS]; n]; + let mut bad = vec![[0u64; Lookup::WORDS]; n]; + acc.iter_mut().for_each(|a| *a = full); + for (key, reg) in tab.keys.iter().zip(keys) { + Self::indexes(key, reg.map(|(r, rep)| (®s[r as usize], rep)), &mut at[..n]); + for i in 0..n { + let v = at[i]; + let (h, b) = (&key.hit[v * rw..(v + 1) * rw], &key.bad[v * rw..(v + 1) * rw]); + for w in 0..rw { + bad[i][w] |= acc[i][w] & b[w]; + acc[i][w] &= h[w]; + } + } + } + for i in 0..n { + let first = (0..rw).find_map(|w| { + let m = acc[i][w] | bad[i][w]; + (m != 0).then(|| (w * 64 + m.trailing_zeros() as usize, (bad[i][w] >> m.trailing_zeros()) & 1 == 1)) + }); + let sel = match first { + Some((rule, true)) => { + K::set(&mut d.fault, i, true); + rule + } + Some((rule, false)) => rule, + None => rules, + }; + d.mant[i] = sel as i64; + d.masks[sel * Reg::WORDS + i / 64] |= 1u64 << (i % 64); + } }), Ins::First { dst, conds, sel, strict } => Self::def(regs, *dst, |d, regs| { let k = conds.len(); @@ -868,7 +1200,7 @@ impl<'e, 'x> Exec<'e, 'x> { m[w] = hit; let fail = match strict { true => (!c.valid[w] | c.fault[w]) & rem[w], - false => c.fault[w] & rem[w], + false => 0, }; bad[w] |= fail; rem[w] &= !(hit | fail); @@ -899,6 +1231,9 @@ impl<'e, 'x> Exec<'e, 'x> { d.fault[w] |= *mw & a.fault[w]; } let m = &m[..words]; + if rep.num() && a.widened(words) { + d.adopt(a, m); + } match rep { Rep::Fix(_) => K::copy_masked(m, &a.mant[..n], &mut d.mant[..n]), Rep::Dyn => { @@ -919,6 +1254,54 @@ impl<'e, 'x> Exec<'e, 'x> { } }), Ins::Fold { fold, buf, list, filter, value } => self.fold(*fold, &mut bufs[*buf as usize], *list, (*filter, *value), regs, scratch), + Ins::Math { func, dst, args, rep } => Self::def(regs, *dst, |d, regs| { + let (func, rep) = (*func, *rep); + d.valid[..words].fill(u64::MAX); + d.fault[..words].fill(0); + for (a, _) in args { + let a = ®s[*a as usize]; + for w in 0..words { + d.fault[w] |= a.fault[w] | !a.valid[w]; + } + } + let skip = d.fault; + match (func, args.as_slice()) { + (Func::Min | Func::Max, _) => self.each(act, &skip, |i| { + let mut best: Option = None; + for (a, ra) in args { + let x = regs[*a as usize].num(*ra, i); + best = Some(match best { + None => x, + Some(b) => { + let order = x.compare(b); + let take = match func { + Func::Min => order == Ordering::Less, + _ => order != Ordering::Less, + }; + if take { x } else { b } + } + }); + } + if let Some(b) = best { + d.keep(rep, i, b); + } + }), + (_, [(a, ra)]) => { + let (a, ra) = (®s[*a as usize], *ra); + self.each(act, &skip, |i| { + let fast = match a.wide(i) { + false => Dec::new(a.mant[i], ra.scale_at(a, i)).func(func).filter(|r| rep == Rep::Dyn || rep == Rep::Fix(r.scale)), + true => None, + }; + match fast { + Some(r) => d.put(i, r), + None => d.keep(rep, i, a.num(ra, i).func(func)), + } + }); + } + _ => {} + } + }), Ins::Text { func, dst, a, b } => { let x = self.view(a); let y = b.as_ref().map_or(TV::Lit(b""), |b| self.view(b)); @@ -959,6 +1342,7 @@ impl<'e, 'x> Exec<'e, 'x> { (Some(a), Some(b)) => a.ends_with(b), _ => false, }), + _ => {} } }) } @@ -966,6 +1350,45 @@ impl<'e, 'x> Exec<'e, 'x> { } } + fn indexes(key: &crate::typed::lookup::Key, reg: Option<(&Reg, Rep)>, at: &mut [usize]) { + let Some((x, rep)) = reg else { + at.fill(0); + return; + }; + let null = key.null(); + match &key.domain { + Domain::Codes(_) => at.iter_mut().zip(&x.codes).for_each(|(a, c)| *a = key.code(*c)), + Domain::Bools => at.iter_mut().enumerate().for_each(|(i, a)| *a = usize::from(K::get(&x.bits, i))), + Domain::Unit => at.fill(0), + Domain::Points(_) => match &key.fixed { + Some((_, mants)) if mants.len() <= 32 => { + let n = at.len(); + at.fill(0); + for p in mants { + for (a, m) in at.iter_mut().zip(&x.mant[..n]) { + *a += usize::from(*p < *m) * 2 + usize::from(*p == *m); + } + } + } + _ => at.iter_mut().enumerate().for_each(|(i, a)| *a = key.mant(x.mant[i]).unwrap_or_else(|| key.num(x.num(rep, i)))), + }, + } + for (w, chunk) in at.chunks_mut(64).enumerate() { + let odd = !x.valid[w] | x.wide[w]; + if odd == 0 { + continue; + } + for (j, a) in chunk.iter_mut().enumerate() { + if (odd >> j) & 1 == 1 { + *a = match x.ok(w * 64 + j) { + false => null, + true => key.num(x.num(rep, w * 64 + j)), + }; + } + } + } + } + #[inline(always)] fn scales<'r>(rep: Rep, reg: &'r Reg, buf: &'r mut [u8; Reg::LANES], n: usize) -> &'r [u8] { match rep { @@ -1003,6 +1426,19 @@ impl<'e, 'x> Exec<'e, 'x> { (Data::Codes(codes), _) => d.codes[..n].copy_from_slice(&codes[start..start + n]), (Data::Text(_), _) => {} } + if let Some((bits, values)) = &feed.wide { + for w in 0..words { + let take = (n - w * 64).min(64); + let mut m = Column::word(bits, start + w * 64, take) & d.valid[w] & !d.fault[w]; + while m != 0 { + let i = w * 64 + m.trailing_zeros() as usize; + m &= m - 1; + if let Ok(at) = values.binary_search_by_key(&(start + i), |(row, _)| *row) { + d.keep(Rep::Dyn, i, N::Big(values[at].1)); + } + } + } + } } fn values(&self, d: &mut Reg, m: &[u64], (t, rt): (&Reg, Rep), (e, re): (&Reg, Rep), rep: Rep) { @@ -1048,125 +1484,160 @@ impl<'e, 'x> Exec<'e, 'x> { let (r0, r1) = (l.parent[s0] as usize, l.parent[s1 - 1] as usize); let filter = filter.map(|f| ®s[f as usize]); let value = value.map(|(v, rep)| (®s[v as usize], rep)); - let fast = matches!((fold, value), (Fold::Count, _) | (Fold::Sum, Some((_, Rep::Fix(_))))); - if let (Fold::Sum, Some((v, Rep::Dyn))) = (fold, value) { - return self.sum_dyn(b, l, filter, v); - } - if fast { - let mark = match (fold, value) { - (Fold::Sum, Some((_, Rep::Fix(s)))) if s > 0 => Some(s), - _ => None, - }; - let sum = fold == Fold::Sum; - let words = self.words.min(Reg::WORDS); - let (keep, bad) = self.kept(filter, value.filter(|_| sum).map(|(v, _)| v)); - let n = self.n; - if scratch.len() < 2 * Reg::LANES + 1 { - return; - } - let (vals, pre) = scratch.split_at_mut(Reg::LANES); - match (sum, value) { - (true, Some((v, _))) => K::mask(&keep[..words], &v.mant[..n], &mut vals[..n]), - _ => { - for (&w, co) in keep[..words].iter().zip(vals[..n].chunks_mut(64)) { - for (j, o) in co.iter_mut().enumerate() { - *o = ((w >> j) & 1) as i64; - } - } - } - } - let big = vals[..n].iter().fold(0u64, |m, v| m.max(v.unsigned_abs())); - let safe = big.checked_mul(n as u64).is_some_and(|t| t < i64::MAX as u64); - for (w, &bw) in bad.iter().enumerate().take(words) { - let mut m = bw; - while m != 0 { - let i = w * 64 + m.trailing_zeros() as usize; - m &= m - 1; - K::set(&mut b.fault, l.parent[s0 + i] as usize, true); - } - } - if safe { - pre[0] = 0; - let mut acc = 0i64; - for (p, v) in pre[1..=n].iter_mut().zip(&vals[..n]) { - acc = acc.wrapping_add(*v); - *p = acc; - } - } + let words = self.words.min(Reg::WORDS); + let wide = b.any || value.is_some_and(|(v, _)| v.widened(words)); + if wide || !matches!(fold, Fold::Sum | Fold::Count) { for r in r0..=r1 { let lo = (l.offsets[r] as usize).max(s0) - s0; let hi = (l.offsets[r + 1] as usize).min(s1) - s0; - if lo >= hi { - continue; - } - let part = match safe { - true => Some(pre[hi] - pre[lo]), - false => { - let (mut acc, mut ovf) = (0i64, false); - for v in &vals[lo..hi] { - let (x, o) = acc.overflowing_add(*v); - acc = x; - ovf |= o; - } - (!ovf).then_some(acc) - } - }; - match part.and_then(|p| b.mant[r].checked_add(p)) { - Some(x) => b.mant[r] = x, - None => K::set(&mut b.fault, r, true), - } - if let Some(s) = mark { - if filter.is_none() || !K::range(&keep, lo, hi, false) { - b.scale[r] = s; - } - } + self.tally(fold, b, r, lo..hi, filter, value); } return; } + let mark = match (fold, value) { + (Fold::Sum, Some((v, Rep::Dyn))) => return self.sum_dyn(b, l, filter, value, v), + (Fold::Sum, Some((_, Rep::Fix(s)))) if s > 0 => Some(s), + (Fold::Sum, Some((_, Rep::Fix(_)))) | (Fold::Count, _) => None, + _ => return, + }; + let sum = fold == Fold::Sum; + let (keep, bad) = self.kept(filter, value.filter(|_| sum).map(|(v, _)| v)); + let n = self.n; + if scratch.len() < 2 * Reg::LANES + 1 { + return; + } + let (vals, pre) = scratch.split_at_mut(Reg::LANES); + match (sum, value) { + (true, Some((v, _))) => K::mask(&keep[..words], &v.mant[..n], &mut vals[..n]), + _ => { + for (&w, co) in keep[..words].iter().zip(vals[..n].chunks_mut(64)) { + for (j, o) in co.iter_mut().enumerate() { + *o = ((w >> j) & 1) as i64; + } + } + } + } + let big = vals[..n].iter().fold(0u64, |m, v| m.max(v.unsigned_abs())); + let safe = big.checked_mul(n as u64).is_some_and(|t| t < i64::MAX as u64); + for (w, &bw) in bad.iter().enumerate().take(words) { + let mut m = bw; + while m != 0 { + let i = w * 64 + m.trailing_zeros() as usize; + m &= m - 1; + K::set(&mut b.fault, l.parent[s0 + i] as usize, true); + } + } + if safe { + pre[0] = 0; + let mut acc = 0i64; + for (p, v) in pre[1..=n].iter_mut().zip(&vals[..n]) { + acc = acc.wrapping_add(*v); + *p = acc; + } + } for r in r0..=r1 { - if K::get(&b.fault, r) { + let lo = (l.offsets[r] as usize).max(s0) - s0; + let hi = (l.offsets[r + 1] as usize).min(s1) - s0; + if lo >= hi { continue; } - let lo = (l.offsets[r] as usize).max(s0); - let hi = (l.offsets[r + 1] as usize).min(s1); - let mut bad = false; - for e in lo..hi { - let i = e - s0; - if let Some(f) = filter { - if !f.ok(i) || f.bad(i) { - bad = true; - break; - } - if !K::get(&f.bits, i) { - continue; + let part = match safe { + true => Some(pre[hi] - pre[lo]), + false => { + let (mut acc, mut ovf) = (0i64, false); + for v in &vals[lo..hi] { + let (x, o) = acc.overflowing_add(*v); + acc = x; + ovf |= o; } + (!ovf).then_some(acc) } - match (fold, value) { - (Fold::Count, _) => b.mant[r] += 1, - (Fold::Sum, Some((v, rep))) => { - if !v.ok(i) || v.bad(i) { - bad = true; - break; - } - match Dec::new(b.mant[r], b.scale[r]).checked_add(Dec::new(v.mant[i], rep.scale_at(v, i))) { - Ok(s) => { - b.mant[r] = s.mant; - b.scale[r] = s.scale; - } - Err(_) => { - bad = true; - break; - } - } - } - (Fold::Sum, None) => { - bad = true; - break; - } + }; + match part.and_then(|p| b.mant[r].checked_add(p)) { + Some(x) => b.mant[r] = x, + None => { + self.tally(fold, b, r, lo..hi, filter, value); + continue; } } - if bad { + if let Some(s) = mark { + if filter.is_none() || !K::range(&keep, lo, hi, false) { + b.scale[r] = s; + } + } + } + } + + fn tally(&self, fold: Fold, b: &mut Buf, r: usize, range: std::ops::Range, filter: Option<&Reg>, value: Option<(&Reg, Rep)>) { + let rep = match (fold, value) { + (Fold::Sum, Some((_, Rep::Fix(0)))) => Rep::Fix(0), + (Fold::Min | Fold::Max, Some((_, rep))) => rep, + _ => Rep::Dyn, + }; + for i in range { + if K::get(&b.fault, r) { + return; + } + if let Some(f) = filter { + if !f.ok(i) || f.bad(i) { + K::set(&mut b.fault, r, true); + return; + } + if !K::get(&f.bits, i) { + continue; + } + } + if fold == Fold::Count { + b.mant[r] += 1; + continue; + } + let Some((v, vr)) = value else { K::set(&mut b.fault, r, true); + return; + }; + if matches!(fold, Fold::Any | Fold::All | Fold::None) && b.codes[r] != 0 { + match filter { + Some(_) => continue, + None => return, + } + } + if !v.ok(i) || v.bad(i) { + K::set(&mut b.fault, r, true); + return; + } + match fold { + Fold::Any | Fold::All | Fold::None => { + let bit = K::get(&v.bits, i); + if bit != (fold == Fold::All) { + b.codes[r] = 1; + K::set(&mut b.bits, r, fold == Fold::Any); + } + } + Fold::One => b.mant[r] += i64::from(K::get(&v.bits, i)), + Fold::Min | Fold::Max => { + let x = v.num(vr, i); + let take = b.codes[r] == 0 || { + let order = x.compare(b.num(rep, r)); + match fold { + Fold::Min => order == Ordering::Less, + _ => order != Ordering::Less, + } + }; + if take { + b.keep(rep, r, x); + } + b.codes[r] = 1; + } + _ => match b.num(rep, r).arith(Arith::Add, v.num(vr, i)) { + Ok(Some(x)) => { + b.keep(rep, r, x); + b.codes[r] = b.codes[r].saturating_add(1); + } + _ => { + K::set(&mut b.fault, r, true); + return; + } + }, } } } @@ -1190,7 +1661,7 @@ impl<'e, 'x> Exec<'e, 'x> { (keep, bad) } - fn sum_dyn(&self, b: &mut Buf, l: &Lists, filter: Option<&Reg>, v: &Reg) { + fn sum_dyn(&self, b: &mut Buf, l: &Lists, filter: Option<&Reg>, value: Option<(&Reg, Rep)>, v: &Reg) { let (n, s0) = (self.n, self.start); let s1 = s0 + n; let (r0, r1) = (l.parent[s0] as usize, l.parent[s1 - 1] as usize); @@ -1215,10 +1686,12 @@ impl<'e, 'x> Exec<'e, 'x> { s = if k { t } else { s }; o |= k & f; } - b.mant[r] = m; - b.scale[r] = s; - if o { - K::set(&mut b.fault, r, true); + match o { + true => self.tally(Fold::Sum, b, r, lo..hi, filter, value), + false => { + b.mant[r] = m; + b.scale[r] = s; + } } } } @@ -1249,6 +1722,16 @@ impl<'e, 'x> Exec<'e, 'x> { Rep::Null => s.valid[w0..w0 + words].fill(0), _ => s.valid[w0..w0 + words].copy_from_slice(&r.valid[..words]), } + if rep.num() && r.widened(words) { + for w in 0..words { + let mut m = r.wide[w] & r.valid[w] & !r.fault[w] & self.tail(w); + while m != 0 { + let i = w * 64 + m.trailing_zeros() as usize; + m &= m - 1; + s.wide.push((start + i, r.big.get(i).copied().unwrap_or_default())); + } + } + } let parent = match scope { Scope::Row => None, Scope::Elem(l) => self.feeds.lists.get(l as usize).map(|l| &l.parent), diff --git a/core/expression/src/typed/hir.rs b/core/expression/src/typed/hir.rs index bc838fbf..822ebb52 100644 --- a/core/expression/src/typed/hir.rs +++ b/core/expression/src/typed/hir.rs @@ -43,6 +43,8 @@ pub enum Arith { Sub, Mul, Div, + Rem, + Pow, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -59,6 +61,13 @@ pub enum Cmp { pub enum Fold { Sum, Count, + Any, + All, + None, + One, + Min, + Max, + Avg, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -66,6 +75,13 @@ pub enum Func { StartsWith, EndsWith, Len, + Abs, + Floor, + Ceil, + Round(u8), + Trunc(u8), + Min, + Max, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -245,6 +261,18 @@ impl Op { } } +impl Fold { + pub fn quantifier(self) -> bool { + matches!(self, Fold::Any | Fold::All | Fold::None | Fold::One) + } +} + +impl Func { + pub fn text(self) -> bool { + matches!(self, Func::StartsWith | Func::EndsWith | Func::Len) + } +} + impl Hir { pub fn node(&self, id: NodeId) -> &Node { &self.nodes[id as usize] diff --git a/core/expression/src/typed/ins.rs b/core/expression/src/typed/ins.rs index 0e0a8d48..62cd9f00 100644 --- a/core/expression/src/typed/ins.rs +++ b/core/expression/src/typed/ins.rs @@ -1,4 +1,5 @@ use crate::typed::hir::{Arith, Cmp, Fold, Func, Lit, NodeId, Range, Scope, Unsupported}; +use crate::typed::lookup::Lookup; use crate::typed::num::Dec; use std::fmt; @@ -48,11 +49,11 @@ pub(crate) enum Ins { Gather { dst: R, buf: u16, list: u16, rep: Rep }, Fill { dst: R, buf: u16, rep: Rep }, Spill { src: R, buf: u16, rep: Rep }, - Fix { op: FixOp, dst: R, a: R, b: R }, + Fix { op: FixOp, dst: R, a: R, b: R, rep: Rep }, Neg { dst: R, a: R, rep: Rep }, Num { op: Arith, dst: R, a: R, ra: Rep, b: R, rb: Rep }, DivPow { dst: R, a: R, ra: Rep, k: u32, by: u8 }, - CmpFix { op: Cmp, dst: R, a: R, b: R }, + CmpFix { op: Cmp, dst: R, a: R, b: R, rep: Rep }, CmpGen { op: Cmp, dst: R, a: R, ra: Rep, b: R, rb: Rep }, CmpNum { op: Cmp, dst: R, a: R, ra: Rep, b: R, rb: Rep }, CmpNumK { op: Cmp, dst: R, a: R, ra: Rep, k: Dec, tab: Vec, fits: u32 }, @@ -63,7 +64,7 @@ pub(crate) enum Ins { EqText { ne: bool, dst: R, a: Arg, b: Arg }, InCode { dst: R, a: R, set: u64, null: bool }, InGen { dst: R, a: R, ra: Rep, set: Vec }, - InRangeFix { dst: R, a: R, lo: i64, span: u64, empty: bool }, + InRangeFix { dst: R, a: R, lo: i64, span: u64, empty: bool, range: Range }, InRangeGen { dst: R, a: R, ra: Rep, range: Range }, Not { dst: R, a: R }, And { dst: R, a: R, b: R }, @@ -71,10 +72,12 @@ pub(crate) enum Ins { Blend { dst: R, c: R, t: R, rt: Rep, e: R, re: Rep, rep: Rep }, Coalesce { dst: R, a: R, ra: Rep, b: R, rb: Rep, rep: Rep }, First { dst: R, conds: Vec, sel: bool, strict: bool }, + Lookup { dst: R, keys: Vec>, tab: Box }, Pick { dst: R, sel: R, arms: Vec<(R, Rep, Vec)>, rep: Rep }, Skip { guard: Guard, len: u32 }, Fold { fold: Fold, buf: u16, list: u16, filter: Option, value: Option<(R, Rep)> }, Text { func: Func, dst: R, a: Arg, b: Option }, + Math { func: Func, dst: R, args: Vec<(R, Rep)>, rep: Rep }, Out { slot: u16, src: R, rep: Rep, scope: Scope }, } @@ -98,7 +101,8 @@ pub(crate) enum Arm { #[derive(Clone, Copy, Debug)] pub(crate) struct BufDef { pub(crate) scope: Scope, - pub(crate) fold: Option, + pub(crate) fold: Option<(u16, Fold, Rep)>, + pub(crate) stage: usize, } impl Rep { @@ -198,12 +202,24 @@ impl Ins { f(a, false); f(dst, true); } + Ins::Math { dst, args, .. } => { + for (a, _) in args.iter_mut() { + f(a, false); + } + f(dst, true); + } Ins::Blend { dst, c, t, e, .. } => { f(c, false); f(t, false); f(e, false); f(dst, true); } + Ins::Lookup { dst, keys, .. } => { + for (r, _) in keys.iter_mut().flatten() { + f(r, false); + } + f(dst, true); + } Ins::First { dst, conds, .. } => { for c in conds.iter_mut() { f(c, false); diff --git a/core/expression/src/typed/lookup.rs b/core/expression/src/typed/lookup.rs new file mode 100644 index 00000000..9fa6751b --- /dev/null +++ b/core/expression/src/typed/lookup.rs @@ -0,0 +1,369 @@ +use crate::typed::hir::{Cmp, Hir, Kind, Lit, NodeId, Op, Range}; +use crate::typed::ins::Rep; +use crate::typed::kernel::K; +use crate::typed::num::{Dec, N}; +use std::cmp::Ordering; + +#[derive(Clone, Debug)] +pub(crate) struct Lookup { + pub(crate) keys: Vec, + pub(crate) rules: usize, + pub(crate) words: usize, +} + +#[derive(Clone, Debug)] +pub(crate) struct Key { + pub(crate) node: Option, + pub(crate) domain: Domain, + pub(crate) hit: Vec, + pub(crate) bad: Vec, + pub(crate) fixed: Option<(u8, Vec)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Domain { + Unit, + Bools, + Codes(usize), + Points(Vec), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Val { + Null, + Num(N), + Bool(bool), + Code(i32), + Fault, +} + +struct Test { + rule: usize, + key: Option, + node: NodeId, +} + +impl Lookup { + pub(crate) const RULES: usize = 256; + pub(crate) const WORDS: usize = 4; + const POINTS: usize = 512; + + pub(crate) fn plan(hir: &Hir, conds: &[NodeId], strict: bool, least: usize) -> Option { + let rules = conds.len(); + if rules == 0 || rules > Self::RULES { + return None; + } + let mut tests: Vec = Vec::new(); + for (rule, &cond) in conds.iter().enumerate() { + let mut chain = Vec::new(); + Self::chain(hir, cond, &mut chain); + for node in chain { + let mut keys = Vec::new(); + Self::keys(hir, node, &mut keys)?; + match keys.as_slice() { + [] => tests.push(Test { rule, key: None, node }), + [key] => tests.push(Test { rule, key: Some(*key), node }), + _ => return None, + } + } + } + if tests.len() < least { + return None; + } + let order = Self::order(&tests, rules, strict)?; + let words = rules.div_ceil(64); + let mut keys = Vec::with_capacity(order.len()); + for key in order { + let domain = Self::domain(hir, key, &tests)?; + let values = Self::values(&domain)?; + let mut hit = vec![0u64; values.len() * words]; + let mut bad = vec![0u64; values.len() * words]; + for (at, value) in values.iter().enumerate() { + for rule in 0..rules { + let mut state = Val::Bool(true); + for test in tests.iter().filter(|t| t.rule == rule && t.key == key) { + if state != Val::Bool(true) { + break; + } + state = Self::eval(hir, test.node, key, *value)?; + } + match state { + Val::Bool(true) => K::set(&mut hit[at * words..(at + 1) * words], rule, true), + Val::Bool(false) => {} + _ if strict => K::set(&mut bad[at * words..(at + 1) * words], rule, true), + _ => {} + } + } + } + keys.push(Key { node: key, domain, hit, bad, fixed: None }); + } + Some(Lookup { keys, rules, words }) + } + + pub(crate) fn fix(&mut self, reps: &[Rep]) { + for (key, rep) in self.keys.iter_mut().zip(reps) { + if let (Domain::Points(points), Rep::Fix(s)) = (&key.domain, rep) { + key.fixed = points.iter().map(|p| p.upscale(*s).map(|u| u.mant)).collect::>>().map(|m| (*s, m)); + } + } + } + + fn chain(hir: &Hir, node: NodeId, out: &mut Vec) { + match hir.node(node).op { + Op::And(a, b) => { + Self::chain(hir, a, out); + Self::chain(hir, b, out); + } + _ => out.push(node), + } + } + + fn keys(hir: &Hir, node: NodeId, out: &mut Vec) -> Option<()> { + let n = hir.node(node); + if matches!(n.ty.kind, Kind::Code(_)) && !matches!(n.op, Op::Const(_)) { + if !out.contains(&node) { + out.push(node); + } + return Some(()); + } + match &n.op { + Op::Const(Lit::Text(_)) => return None, + Op::Const(_) => {} + Op::Column(_) | Op::Field(..) if matches!(n.ty.kind, Kind::Num(_) | Kind::Bool) => { + if !out.contains(&node) { + out.push(node); + } + } + Op::Cmp(..) | Op::InSet(..) | Op::InRange(..) | Op::Not(_) | Op::And(..) | Op::Or(..) | Op::If(..) | Op::Coalesce(..) => { + for input in n.op.inputs() { + Self::keys(hir, input, out)?; + } + } + _ => return None, + } + Some(()) + } + + fn order(tests: &[Test], rules: usize, strict: bool) -> Option>> { + let mut keys: Vec> = Vec::new(); + for t in tests { + if !keys.contains(&t.key) { + keys.push(t.key); + } + } + if !strict { + return Some(keys); + } + let mut before: Vec<(usize, usize)> = Vec::new(); + for rule in 0..rules { + let mut seen: Vec = Vec::new(); + for t in tests.iter().filter(|t| t.rule == rule) { + let k = keys.iter().position(|x| *x == t.key)?; + match seen.last() { + Some(last) if *last == k => continue, + _ if seen.contains(&k) => return None, + _ => {} + } + for &s in &seen { + if !before.contains(&(s, k)) { + before.push((s, k)); + } + } + seen.push(k); + } + } + let mut left: Vec = (0..keys.len()).collect(); + let mut ordered = Vec::with_capacity(keys.len()); + while !left.is_empty() { + let at = left.iter().position(|k| !before.iter().any(|(a, b)| b == k && left.contains(a)))?; + ordered.push(keys[left.remove(at)]); + } + Some(ordered) + } + + fn domain(hir: &Hir, key: Option, tests: &[Test]) -> Option { + let Some(key) = key else { + return Some(Domain::Unit); + }; + let node = hir.node(key); + match (&node.op, node.ty.kind) { + (_, Kind::Code(d)) => Some(Domain::Codes(hir.schema.dicts.get(d as usize)?.values.len())), + (_, Kind::Bool) => Some(Domain::Bools), + (_, Kind::Num(_)) => { + let mut points: Vec = Vec::new(); + for t in tests.iter().filter(|t| t.key == Some(key)) { + Self::points(hir, t.node, &mut points); + } + points.sort_by(|a, b| a.compare(*b)); + points.dedup_by(|a, b| a.compare(*b) == Ordering::Equal); + (points.len() <= Self::POINTS).then_some(Domain::Points(points)) + } + _ => None, + } + } + + fn points(hir: &Hir, node: NodeId, out: &mut Vec) { + match &hir.node(node).op { + Op::Const(Lit::Num(d)) => out.push(*d), + Op::InRange(_, r) => out.extend([r.lo, r.hi]), + Op::InSet(_, set) => out.extend(set.iter().filter_map(|l| match l { + Lit::Num(d) => Some(*d), + _ => None, + })), + _ => {} + } + for input in hir.node(node).op.inputs() { + Self::points(hir, input, out); + } + } + + fn values(domain: &Domain) -> Option> { + Some(match domain { + Domain::Unit => vec![Val::Null], + Domain::Bools => vec![Val::Bool(false), Val::Bool(true), Val::Null], + Domain::Codes(k) => (0..=*k as i32).map(Val::Code).chain(std::iter::once(Val::Null)).collect(), + Domain::Points(points) => { + let mut values = Vec::with_capacity(2 * points.len() + 2); + let one = N::Dec(Dec::int(1)); + let two = N::Dec(Dec::int(2)); + for (j, p) in points.iter().enumerate() { + let below = match j { + 0 => N::Dec(*p).arith(crate::typed::hir::Arith::Sub, one).ok()??, + _ => { + let sum = N::Dec(points[j - 1]).arith(crate::typed::hir::Arith::Add, N::Dec(*p)).ok()??; + sum.arith(crate::typed::hir::Arith::Div, two).ok()?? + } + }; + values.push(Val::Num(below)); + values.push(Val::Num(N::Dec(*p))); + } + let above = match points.last() { + Some(p) => N::Dec(*p).arith(crate::typed::hir::Arith::Add, one).ok()??, + None => N::Dec(Dec::ZERO), + }; + values.push(Val::Num(above)); + values.push(Val::Null); + values + } + }) + } + + fn eval(hir: &Hir, node: NodeId, key: Option, value: Val) -> Option { + if Some(node) == key { + return Some(value); + } + let ev = |n: NodeId| Self::eval(hir, n, key, value); + Some(match &hir.node(node).op { + Op::Const(Lit::Null) => Val::Null, + Op::Const(Lit::Num(d)) => Val::Num(N::Dec(*d)), + Op::Const(Lit::Bool(b)) => Val::Bool(*b), + Op::Const(Lit::Code(_, c)) => Val::Code(*c), + Op::Cmp(op, a, b) => { + let (x, y) = (ev(*a)?, ev(*b)?); + match (op, x, y) { + (_, Val::Fault, _) | (_, _, Val::Fault) => Val::Fault, + (Cmp::Eq | Cmp::Ne, x, y) => Val::Bool(Self::same(x, y) == (*op == Cmp::Eq)), + (_, Val::Num(x), Val::Num(y)) => Val::Bool(K::ord(*op, x.compare(y))), + _ => Val::Fault, + } + } + Op::InSet(a, set) => match ev(*a)? { + Val::Fault => Val::Fault, + x => Val::Bool(set.iter().any(|l| Self::same(x, Self::lit(l)))), + }, + Op::InRange(a, r) => match ev(*a)? { + Val::Num(x) => Val::Bool(Self::within(x, r)), + _ => Val::Fault, + }, + Op::Not(a) => match ev(*a)? { + Val::Bool(b) => Val::Bool(!b), + _ => Val::Fault, + }, + Op::And(a, b) => match ev(*a)? { + Val::Bool(false) => Val::Bool(false), + Val::Bool(true) => ev(*b)?, + _ => Val::Fault, + }, + Op::Or(a, b) => match ev(*a)? { + Val::Bool(true) => Val::Bool(true), + Val::Bool(false) => ev(*b)?, + _ => Val::Fault, + }, + Op::If(c, t, e) => match ev(*c)? { + Val::Bool(true) => ev(*t)?, + Val::Bool(false) => ev(*e)?, + _ => Val::Fault, + }, + Op::Coalesce(a, b) => match ev(*a)? { + Val::Null => ev(*b)?, + x => x, + }, + _ => return None, + }) + } + + fn lit(lit: &Lit) -> Val { + match lit { + Lit::Null => Val::Null, + Lit::Num(d) => Val::Num(N::Dec(*d)), + Lit::Bool(b) => Val::Bool(*b), + Lit::Code(_, c) => Val::Code(*c), + Lit::Text(_) => Val::Fault, + } + } + + fn same(x: Val, y: Val) -> bool { + match (x, y) { + (Val::Num(a), Val::Num(b)) => a.compare(b) == Ordering::Equal, + (Val::Fault, _) | (_, Val::Fault) => false, + (a, b) => a == b, + } + } + + fn within(x: N, r: &Range) -> bool { + let (lo, hi) = (x.compare(N::Dec(r.lo)), x.compare(N::Dec(r.hi))); + let above = lo == Ordering::Greater || (r.lo_closed && lo == Ordering::Equal); + let below = hi == Ordering::Less || (r.hi_closed && hi == Ordering::Equal); + above && below + } +} + +impl Key { + #[inline] + pub(crate) fn null(&self) -> usize { + match &self.domain { + Domain::Unit => 0, + Domain::Bools => 2, + Domain::Codes(k) => k + 1, + Domain::Points(points) => 2 * points.len() + 1, + } + } + + #[inline] + pub(crate) fn code(&self, code: i32) -> usize { + match &self.domain { + Domain::Codes(k) => usize::try_from(code).map_or(*k, |c| c.min(*k)), + _ => 0, + } + } + + #[inline] + pub(crate) fn mant(&self, m: i64) -> Option { + let (_, mants) = self.fixed.as_ref()?; + Some(match mants.binary_search(&m) { + Ok(j) => 2 * j + 1, + Err(j) => 2 * j, + }) + } + + #[inline] + pub(crate) fn num(&self, x: N) -> usize { + match &self.domain { + Domain::Points(points) => match points.binary_search_by(|p| N::Dec(*p).compare(x)) { + Ok(j) => 2 * j + 1, + Err(j) => 2 * j, + }, + _ => 0, + } + } +} diff --git a/core/expression/src/typed/lower.rs b/core/expression/src/typed/lower.rs index b35cd927..599cad09 100644 --- a/core/expression/src/typed/lower.rs +++ b/core/expression/src/typed/lower.rs @@ -304,7 +304,10 @@ impl Lowering { }); } let total = conds.iter().any(|c| self.nodes[*c as usize].op == Op::Const(Lit::Bool(true))); - let (scope, conds) = self.scoped(&conds)?; + let (scope, conds) = match self.member { + Some(_) => (ctx.scope, conds.iter().map(|c| self.parent(*c, ctx.scope)).collect::, _>>()?), + None => self.scoped(&conds)?, + }; let sel = self.add(Op::FirstMatch { conds, strict: spec.hit == Hit::Strict }, Ty::num(Some(0)), scope); let mut picks = Vec::with_capacity(spec.outputs.len()); for at in 0..spec.outputs.len() { @@ -732,7 +735,8 @@ impl Lowering { ArithmeticOperator::Subtract => Arith::Sub, ArithmeticOperator::Multiply => Arith::Mul, ArithmeticOperator::Divide => Arith::Div, - other => return Err(Unsupported::new(format!("arithmetic {other}"))), + ArithmeticOperator::Modulus => Arith::Rem, + ArithmeticOperator::Power => Arith::Pow, }; let a = self.expr(left, ctx, r)?; let b = self.expr(right, ctx, r)?; @@ -792,7 +796,9 @@ impl Lowering { let ty = match op { Arith::Add | Arith::Sub => Ty::num(sa.filter(|x| sb == Some(*x))), Arith::Mul => Ty::num((sa == Some(0) && sb == Some(0)).then_some(0)), - Arith::Div => Ty::new(Kind::Num(None), divisor.is_none_or(|d| d.is_zero())), + Arith::Div | Arith::Rem => Ty::new(Kind::Num(None), divisor.is_none_or(|d| d.is_zero())), + Arith::Pow if divisor.is_some_and(|d| d.scale == 0) => Ty::num(None), + Arith::Pow => return Err(Unsupported::new("exponent must be an integer literal")), }; let (scope, ids) = self.scoped(&[a, b])?; Ok(self.add(Op::Arith(op, ids[0], ids[1]), ty, scope)) @@ -981,7 +987,7 @@ impl Lowering { fn call(&mut self, kind: &FunctionKind, args: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { match (kind, args) { - (FunctionKind::Internal(InternalFunction::Sum), [arg]) => { + (FunctionKind::Internal(InternalFunction::Sum), [arg]) if !matches!(arg, Ast::Array(_)) => { let Ast::FunctionCall { kind: FunctionKind::Closure(ClosureFunction::Map), arguments: [source, body] } = arg else { return Err(Unsupported::new("sum over something other than map(...)")); }; @@ -1015,10 +1021,122 @@ impl Lowering { let (scope, ids) = self.scoped(&[a, b])?; Ok(self.add(Op::Call(func, ids), Ty::boolean(), scope)) } + (FunctionKind::Internal(InternalFunction::Bool), [arg]) => { + let a = self.expr(arg, ctx, r)?; + match self.ty(a) { + Ty { kind: Kind::Bool, nullable: false } => Ok(a), + Ty { kind: Kind::Bool, nullable: true } => { + let no = self.konst(Lit::Bool(false)); + let (scope, ids) = self.scoped(&[a, no])?; + Ok(self.add(Op::Coalesce(ids[0], ids[1]), Ty::boolean(), scope)) + } + Ty { kind: Kind::Null, .. } => Ok(self.konst(Lit::Bool(false))), + ty => Err(Unsupported::new(format!("bool of {ty}"))), + } + } + (FunctionKind::Internal(f @ (InternalFunction::Abs | InternalFunction::Floor | InternalFunction::Ceil)), [arg]) => { + let a = self.expr(arg, ctx, r)?; + let Kind::Num(scale) = self.kind(a) else { + return Err(Unsupported::new(format!("{f:?} of {}", self.ty(a)))); + }; + let (func, ty) = match f { + InternalFunction::Abs => (Func::Abs, Ty::num(scale)), + InternalFunction::Floor => (Func::Floor, Ty::num(Some(0))), + _ => (Func::Ceil, Ty::num(Some(0))), + }; + self.math(func, vec![a], ty) + } + (FunctionKind::Internal(f @ (InternalFunction::Round | InternalFunction::Trunc)), [arg, rest @ ..]) => { + let a = self.expr(arg, ctx, r)?; + let Kind::Num(scale) = self.kind(a) else { + return Err(Unsupported::new(format!("{f:?} of {}", self.ty(a)))); + }; + let places = match rest { + [] => 0, + [places] => { + let p = self.expr(places, ctx, r)?; + match self.lit(p) { + Some(Lit::Num(d)) if d.scale == 0 && (0..=i64::from(Dec::MAX_SCALE)).contains(&d.mant) => d.mant as u8, + _ => return Err(Unsupported::new("decimal places must be a small integer literal")), + } + } + _ => return Err(Unsupported::new(format!("{f:?} arity"))), + }; + let (func, ty) = match f { + InternalFunction::Round => (Func::Round(places), Ty::num(scale.map(|s| s.min(places)))), + _ => (Func::Trunc(places), Ty::num(Some(places))), + }; + self.math(func, vec![a], ty) + } + (FunctionKind::Internal(f @ (InternalFunction::Min | InternalFunction::Max | InternalFunction::Avg | InternalFunction::Sum)), [Ast::Array(items)]) => { + if items.is_empty() { + return Err(Unsupported::new("aggregate of an empty list")); + } + let mut args = Vec::with_capacity(items.len()); + for item in items.iter() { + let a = self.expr(item, ctx, r)?; + self.require(a, |k| matches!(k, Kind::Num(_)), "aggregate item")?; + args.push(a); + } + match f { + InternalFunction::Min | InternalFunction::Max => { + let first = self.kind(args[0]); + let kind = match args.iter().all(|a| self.kind(*a) == first) { + true => first, + false => Kind::Num(None), + }; + let func = if *f == InternalFunction::Min { Func::Min } else { Func::Max }; + self.math(func, args, Ty::new(kind, false)) + } + _ => { + let zero = self.konst(Lit::Num(Dec::ZERO)); + let mut acc = zero; + for a in &args { + acc = self.arith(Arith::Add, acc, *a)?; + } + match f { + InternalFunction::Sum => Ok(acc), + _ => { + let count = self.konst(Lit::Num(Dec::int(args.len() as i64))); + self.arith(Arith::Div, acc, count) + } + } + } + } + } + (FunctionKind::Internal(f @ (InternalFunction::Min | InternalFunction::Max | InternalFunction::Avg)), [arg]) => { + let Ast::FunctionCall { kind: FunctionKind::Closure(ClosureFunction::Map), arguments: [source, body] } = arg else { + return Err(Unsupported::new(format!("{f:?} over something other than map(...)"))); + }; + let (list, filter) = self.source(source, ctx, r)?; + let body = Self::closure(body)?; + let fold = match f { + InternalFunction::Min => Fold::Min, + InternalFunction::Max => Fold::Max, + _ => Fold::Avg, + }; + self.fold(fold, list, filter, Some(body), r) + } + (FunctionKind::Closure(c @ (ClosureFunction::Some | ClosureFunction::All | ClosureFunction::None | ClosureFunction::One)), [source, body]) => { + let (list, filter) = self.source(source, ctx, r)?; + let body = Self::closure(body)?; + let fold = match c { + ClosureFunction::Some => Fold::Any, + ClosureFunction::All => Fold::All, + ClosureFunction::None => Fold::None, + _ => Fold::One, + }; + self.fold(fold, list, filter, Some(body), r) + } (kind, _) => Err(Unsupported::new(format!("function {kind:?}"))), } } + fn math(&mut self, func: Func, args: Vec, ty: Ty) -> Lowered { + let (scope, ids) = self.scoped(&args)?; + Ok(self.add(Op::Call(func, ids), ty, scope)) + } + fn closure<'a>(ast: &'a Ast<'a>) -> Result<&'a Ast<'a>, Unsupported> { match ast { Ast::Closure { body, alias: None } => Ok(body), @@ -1079,13 +1197,19 @@ impl Lowering { let value = match value { Some(ast) => { let id = self.expr(ast, inner, r)?; - self.require(id, |k| matches!(k, Kind::Num(_)), "sum value")?; + match fold.quantifier() { + true => self.require(id, |k| k == Kind::Bool, "predicate")?, + false => self.require(id, |k| matches!(k, Kind::Num(_)), "fold value")?, + } Some(self.parent(id, scope)?) } None => None, }; let ty = match (fold, value) { (Fold::Sum, Some(v)) => Ty::num((self.kind(v) == Kind::Num(Some(0))).then_some(0)), + (Fold::Min | Fold::Max, Some(v)) => Ty::new(self.kind(v), false), + (Fold::Avg, _) => Ty::num(None), + (Fold::Any | Fold::All | Fold::None | Fold::One, _) => Ty::boolean(), _ => Ty::num(Some(0)), }; Ok(self.add(Op::Fold { fold, list, filter, value }, ty, Scope::Row)) diff --git a/core/expression/src/typed/mod.rs b/core/expression/src/typed/mod.rs index 252d6503..79b64a56 100644 --- a/core/expression/src/typed/mod.rs +++ b/core/expression/src/typed/mod.rs @@ -5,6 +5,7 @@ mod hir; mod ins; mod kernel; mod lower; +mod lookup; mod num; mod output; mod program; diff --git a/core/expression/src/typed/num.rs b/core/expression/src/typed/num.rs index 456e5208..3c3c651a 100644 --- a/core/expression/src/typed/num.rs +++ b/core/expression/src/typed/num.rs @@ -1,5 +1,7 @@ use crate::lane::scaled::Scaled; -use rust_decimal::Decimal; +use crate::typed::hir::{Arith, Func}; +use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; +use rust_decimal::{Decimal, MathematicalOps, RoundingStrategy}; use std::cmp::Ordering; use std::fmt; @@ -12,6 +14,14 @@ pub struct Dec { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Fault; +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum N { + Dec(Dec), + Big(Decimal), +} + +pub(crate) struct Exact; + impl Dec { pub const MAX_SCALE: u8 = 28; pub const ZERO: Dec = Dec { mant: 0, scale: 0 }; @@ -77,6 +87,40 @@ impl Dec { q.map(|q| Some(Self::of(q))).ok_or(Fault) } + #[inline] + pub fn checked_rem(self, rhs: Self) -> Result, Fault> { + if rhs.mant == 0 { + return Ok(None); + } + Scaled::remainder(self.parts(), rhs.parts()).map(|r| Some(Self::of(r))).ok_or(Fault) + } + + #[inline] + pub(crate) fn func(self, func: Func) -> Option { + let (m, s) = self.parts(); + match func { + Func::Abs => Scaled::abs(m, s), + Func::Floor => Scaled::floor(m, s), + Func::Ceil => Scaled::ceil(m, s), + Func::Round(p) => Scaled::round(m, s, p), + Func::Trunc(p) => Scaled::trunc(m, s, p), + _ => None, + } + .map(Self::of) + } + + #[inline] + pub(crate) fn arith(self, op: Arith, rhs: Self) -> Result, Fault> { + match op { + Arith::Add => self.checked_add(rhs).map(Some), + Arith::Sub => self.checked_sub(rhs).map(Some), + Arith::Mul => self.checked_mul(rhs).map(Some), + Arith::Div => self.checked_div(rhs), + Arith::Rem => self.checked_rem(rhs), + Arith::Pow => Err(Fault), + } + } + #[inline] pub fn div_power(self, k: u32, scale: u8) -> Result { Scaled::divide_power(self.parts(), k, scale).map(Self::of).ok_or(Fault) @@ -113,6 +157,88 @@ impl Dec { } } +impl Exact { + pub(crate) fn arith(op: Arith, x: Decimal, y: Decimal) -> Result, Fault> { + match op { + Arith::Add => x.checked_add(y).map(Some).ok_or(Fault), + Arith::Sub => x.checked_sub(y).map(Some).ok_or(Fault), + Arith::Mul => x.checked_mul(y).map(Some).ok_or(Fault), + Arith::Div => Ok(x.checked_div(y)), + Arith::Rem => Ok(x.checked_rem(y)), + Arith::Pow => x.checked_powd(y).or_else(|| Decimal::from_f64(x.to_f64()?.powf(y.to_f64()?))).map(Some).ok_or(Fault), + } + } + + pub(crate) fn func(func: Func, x: Decimal) -> Decimal { + match func { + Func::Abs => x.abs(), + Func::Floor => x.floor(), + Func::Ceil => x.ceil(), + Func::Round(p) => x.round_dp_with_strategy(u32::from(p), RoundingStrategy::MidpointAwayFromZero), + Func::Trunc(p) => x.trunc_with_scale(u32::from(p)), + _ => x, + } + } +} + +impl N { + #[inline] + pub(crate) fn decimal(self) -> Decimal { + match self { + N::Dec(d) => d.decimal(), + N::Big(d) => d, + } + } + + #[inline] + pub(crate) fn of(d: Decimal) -> N { + match Dec::from_decimal(&d) { + Some(n) => N::Dec(n), + None => N::Big(d), + } + } + + #[inline] + pub(crate) fn compare(self, rhs: N) -> Ordering { + match (self, rhs) { + (N::Dec(x), N::Dec(y)) => x.compare(y), + (x, y) => x.decimal().cmp(&y.decimal()), + } + } + + #[inline] + pub(crate) fn arith(self, op: Arith, rhs: N) -> Result, Fault> { + if let (N::Dec(x), N::Dec(y)) = (self, rhs) { + if let Ok(r) = x.arith(op, y) { + return Ok(r.map(N::Dec)); + } + } + Exact::arith(op, self.decimal(), rhs.decimal()).map(|r| r.map(N::of)) + } + + #[inline] + pub(crate) fn func(self, func: Func) -> N { + match self { + N::Dec(d) => match d.func(func) { + Some(r) => N::Dec(r), + None => N::of(Exact::func(func, d.decimal())), + }, + N::Big(d) => N::of(Exact::func(func, d)), + } + } + + #[inline] + pub(crate) fn neg(self) -> N { + match self { + N::Dec(d) => match d.checked_neg() { + Ok(r) => N::Dec(r), + Err(_) => N::of(-d.decimal()), + }, + N::Big(d) => N::of(-d), + } + } +} + impl fmt::Display for Dec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.decimal()) diff --git a/core/expression/src/typed/output.rs b/core/expression/src/typed/output.rs index 0fb83ac3..8d06339c 100644 --- a/core/expression/src/typed/output.rs +++ b/core/expression/src/typed/output.rs @@ -1,6 +1,7 @@ use crate::typed::hir::{DictId, Hir, Kind, Scope, Unsupported}; use crate::typed::kernel::K; use crate::typed::num::Dec; +use rust_decimal::Decimal; #[derive(Clone, Debug)] pub enum Data { @@ -18,6 +19,7 @@ pub struct Slot { pub data: Data, pub valid: Vec, pub fault: Faults, + pub wide: Vec<(usize, Decimal)>, } #[derive(Clone, Debug, Default)] @@ -49,11 +51,22 @@ impl Slot { pub fn num(&self, i: usize) -> Option { match &self.data { - Data::Num { mant, scale } if self.is_valid(i) => Some(Dec::new(*mant.get(i)?, *scale.get(i)?)), + Data::Num { mant, scale } if self.is_valid(i) && self.wide.binary_search_by_key(&i, |(at, _)| *at).is_err() => Some(Dec::new(*mant.get(i)?, *scale.get(i)?)), _ => None, } } + pub fn decimal(&self, i: usize) -> Option { + match self.wide.binary_search_by_key(&i, |(at, _)| *at) { + Ok(at) if self.is_valid(i) => self.wide.get(at).map(|(_, d)| *d), + Ok(_) => None, + Err(_) => match &self.data { + Data::Num { mant, scale } if self.is_valid(i) => Some(Dec::new(*mant.get(i)?, *scale.get(i)?).decimal()), + _ => None, + }, + } + } + pub fn boolean(&self, i: usize) -> Option { match &self.data { Data::Bool(bits) if self.is_valid(i) => Some(K::get(bits, i)), @@ -91,6 +104,7 @@ impl Slot { fn reset(&mut self, len: usize) { self.len = len; + self.wide.clear(); let words = K::words(len); self.valid.clear(); self.valid.resize(words, u64::MAX); @@ -171,7 +185,7 @@ impl Outputs { Kind::Code(_) => Data::Code(Vec::new()), Kind::Text => return Err(Unsupported::new(format!("text output {}", o.name))), }; - slots.push(Slot { name: o.name.clone(), scope: o.scope, kind: o.ty.kind, len: 0, data, valid: Vec::new(), fault: Faults::default() }); + slots.push(Slot { name: o.name.clone(), scope: o.scope, kind: o.ty.kind, len: 0, data, valid: Vec::new(), fault: Faults::default(), wide: Vec::new() }); } Ok(Self { rows: 0, slots, faults: Faults::default() }) } diff --git a/core/expression/src/typed/program.rs b/core/expression/src/typed/program.rs index e6f1a09c..96d144aa 100644 --- a/core/expression/src/typed/program.rs +++ b/core/expression/src/typed/program.rs @@ -119,6 +119,7 @@ impl Program { let plan = self.plan(&machine.sig); machine.exec(&plan, &feeds, out, select); }); + feeds.prefaults(out, select); Ok(()) } @@ -204,9 +205,11 @@ impl Machine { for (buf, def) in bufs.iter_mut().zip(&plan.defs) { let len = feeds.len(def.scope); buf.sized(len); - if let Some(list) = def.fold { + if let Some((list, _, _)) = def.fold { buf.mant.fill(0); buf.scale.fill(0); + buf.codes.fill(0); + buf.bits.fill(0); buf.fault.fill(0); buf.valid.fill(u64::MAX); if let Some(null) = feeds.lists.get(list as usize).and_then(|l| l.null.as_ref()) { @@ -216,7 +219,7 @@ impl Machine { } } } - for stage in &plan.stages { + for (at, stage) in plan.stages.iter().enumerate() { let len = feeds.len(stage.scope); let mut start = 0; while start < len { @@ -225,6 +228,11 @@ impl Machine { exec.run(&stage.code, regs, bufs, scratch, stack, out); start += Reg::LANES; } + for (buf, def) in bufs.iter_mut().zip(&plan.defs) { + if let (Some((_, fold, rep)), true) = (def.fold, def.stage == at) { + buf.finish(fold, rep); + } + } } } } diff --git a/core/expression/src/typed/tests/exact.rs b/core/expression/src/typed/tests/exact.rs index 5b308696..db08d01b 100644 --- a/core/expression/src/typed/tests/exact.rs +++ b/core/expression/src/typed/tests/exact.rs @@ -32,7 +32,7 @@ impl Lab { fn val(slot: &Slot, hir: &Hir, i: usize) -> Val { match (&slot.data, slot.kind) { - (Data::Num { .. }, _) => slot.num(i).map_or(Val::Null, |d| Val::Num(d.decimal())), + (Data::Num { .. }, _) => slot.decimal(i).map_or(Val::Null, Val::Num), (Data::Bool(_), _) => slot.boolean(i).map_or(Val::Null, Val::Bool), (Data::Code(_), Kind::Code(d)) => { slot.code(i).map_or(Val::Null, |c| hir.dict(d).text(c).map_or(Val::Other(format!("code {c}")), |t| Val::Str(t.to_string()))) @@ -156,7 +156,7 @@ fn workloads_match_vm_and_interp() { let rows = workload.rows(1024); let lab = Lab::new(workload, rows); let program = Program::new(lab.hir.clone()).expect("program"); - lab.check(&program, &SIZES, true); + lab.check(&program, &SIZES, name != "W6"); } } @@ -173,13 +173,14 @@ fn extremes_match_vm_and_interp() { #[test] fn passes_off_match_vm() { - let offs: [fn(&mut Passes); 6] = [ + let offs: [fn(&mut Passes); 7] = [ |p| p.fold = false, |p| p.factor = false, |p| p.skip = false, |p| p.reuse = false, |p| p.elide = false, - |p| *p = Passes { fold: false, factor: false, skip: false, reuse: false, elide: false, skip_min: 2 }, + |p| *p = Passes { fold: false, factor: false, skip: false, reuse: false, elide: false, skip_min: 2, lookup_min: 128 }, + |p| p.lookup_min = 1, ]; for name in Workload::NAMES { let workload = Workload::get(name); diff --git a/core/expression/src/typed/tests/interp.rs b/core/expression/src/typed/tests/interp.rs index 30decf3e..48beb6fc 100644 --- a/core/expression/src/typed/tests/interp.rs +++ b/core/expression/src/typed/tests/interp.rs @@ -1,13 +1,15 @@ use crate::typed::batch::{Data, Feed, Feeds}; use crate::typed::kernel::K; +use crate::typed::num::Exact; use crate::typed::tests::oracle::Val; -use crate::typed::{Arith, Cmp, Dec, Fold, Func, Hir, Kind, Lit, NodeId, Op, Scope}; +use crate::typed::{Cmp, Fold, Func, Hir, Kind, Lit, NodeId, Op, Range, Scope}; +use rust_decimal::Decimal; use std::cmp::Ordering; #[derive(Clone, Copy, Debug, PartialEq)] enum V<'a> { Null, - Num(Dec), + Num(Decimal), Bool(bool), Code(i32), Text(&'a [u8]), @@ -67,7 +69,7 @@ impl<'a, 'x> Interp<'a, 'x> { fn val(&self, v: V, kind: Kind) -> Val { match (v, kind) { (V::Null, _) => Val::Null, - (V::Num(d), _) => Val::Num(d.decimal()), + (V::Num(d), _) => Val::Num(d), (V::Bool(b), _) => Val::Bool(b), (V::Code(c), Kind::Code(d)) => self.hir.dict(d).text(c).map_or(Val::Other(format!("code {c}")), |t| Val::Str(t.to_string())), (V::Code(c), _) => Val::Other(format!("code {c}")), @@ -100,8 +102,13 @@ impl<'a, 'x> Interp<'a, 'x> { if !feed.valid(i) { return Ok(V::Null); } + if let Some((bits, values)) = &feed.wide { + if K::get(bits, i) { + return Ok(values.binary_search_by_key(&i, |(at, _)| *at).map_or(V::Null, |at| V::Num(values[at].1))); + } + } Ok(match &feed.data { - Data::Num { .. } => feed.num(i).map_or(V::Null, V::Num), + Data::Num { .. } => feed.num(i).map_or(V::Null, |d| V::Num(d.decimal())), Data::Bool { bits, offset } => V::Bool(K::get(bits, offset + i)), Data::Codes(codes) => V::Code(codes[i]), Data::Text(text) => text.get(i).map_or(V::Null, V::Text), @@ -111,7 +118,7 @@ impl<'a, 'x> Interp<'a, 'x> { fn lit(lit: &'a Lit) -> V<'a> { match lit { Lit::Null => V::Null, - Lit::Num(d) => V::Num(*d), + Lit::Num(d) => V::Num(d.decimal()), Lit::Bool(b) => V::Bool(*b), Lit::Code(_, c) => V::Code(*c), Lit::Text(t) => V::Text(t.as_bytes()), @@ -119,10 +126,14 @@ impl<'a, 'x> Interp<'a, 'x> { } fn equal(a: V, b: V) -> bool { - match (a, b) { - (V::Num(x), V::Num(y)) => x.eq_value(y), - (x, y) => x == y, - } + a == b + } + + fn within(x: Decimal, r: &Range) -> bool { + let (lo, hi) = (x.cmp(&r.lo.decimal()), x.cmp(&r.hi.decimal())); + let above = lo == Ordering::Greater || (r.lo_closed && lo == Ordering::Equal); + let below = hi == Ordering::Less || (r.hi_closed && hi == Ordering::Equal); + above && below } fn compute(&mut self, id: NodeId) -> R<'a> { @@ -141,7 +152,7 @@ impl<'a, 'x> Interp<'a, 'x> { _ => Ok(V::Null), }, Op::Neg(a) => match self.eval(*a)? { - V::Num(d) => d.checked_neg().map(V::Num).map_err(|_| Fault), + V::Num(d) => Ok(V::Num(-d)), _ => Err(Fault), }, Op::Not(a) => match self.eval(*a)? { @@ -153,13 +164,7 @@ impl<'a, 'x> Interp<'a, 'x> { let (V::Num(x), V::Num(y)) = (x, y) else { return Err(Fault); }; - let r = match op { - Arith::Add => x.checked_add(y).map(Some), - Arith::Sub => x.checked_sub(y).map(Some), - Arith::Mul => x.checked_mul(y).map(Some), - Arith::Div => x.checked_div(y), - }; - match r { + match Exact::arith(*op, x, y) { Ok(Some(q)) => Ok(V::Num(q)), Ok(None) => Ok(V::Null), Err(_) => Err(Fault), @@ -174,7 +179,7 @@ impl<'a, 'x> Interp<'a, 'x> { let (V::Num(x), V::Num(y)) = (x, y) else { return Err(Fault); }; - let o = x.compare(y); + let o = x.cmp(&y); Ok(V::Bool(match op { Cmp::Lt => o == Ordering::Less, Cmp::Le => o != Ordering::Greater, @@ -208,13 +213,7 @@ impl<'a, 'x> Interp<'a, 'x> { Ok(V::Bool(set.iter().any(|lit| Self::equal(x, Self::lit(lit))))) } Op::InRange(a, r) => match self.eval(*a)? { - V::Num(x) => { - let lo = x.compare(r.lo); - let hi = x.compare(r.hi); - let above = lo == Ordering::Greater || (r.lo_closed && lo == Ordering::Equal); - let below = hi == Ordering::Less || (r.hi_closed && hi == Ordering::Equal); - Ok(V::Bool(above && below)) - } + V::Num(x) => Ok(V::Bool(Self::within(x, r))), _ => Err(Fault), }, Op::Fold { fold, list, filter, value } => { @@ -225,8 +224,7 @@ impl<'a, 'x> Interp<'a, 'x> { let range = l.offsets[self.row] as usize..l.offsets[self.row + 1] as usize; let saved = (self.elem, std::mem::take(&mut self.elems)); self.elems = vec![None; hir.nodes.len()]; - let mut acc = Dec::ZERO; - let mut count = 0i64; + let mut kept = Vec::new(); let mut result = Ok(()); for e in range { self.elem = e; @@ -241,43 +239,65 @@ impl<'a, 'x> Interp<'a, 'x> { } } } - count += 1; - if let (Fold::Sum, Some(v)) = (fold, value) { - match self.eval(*v) { - Ok(V::Num(d)) => match acc.checked_add(d) { - Ok(next) => acc = next, - Err(_) => { - result = Err(Fault); - break; - } + kept.push(e); + } + let mut values = Vec::new(); + let mut decided: Option = None; + let mut ones = 0; + if result.is_ok() && *fold != Fold::Count { + for e in kept.iter().copied() { + self.elem = e; + self.elems.fill(None); + let Some(v) = value else { + result = Err(Fault); + break; + }; + match (fold, self.eval(*v)) { + (Fold::Any | Fold::All | Fold::None | Fold::One, Ok(V::Bool(b))) => match fold { + Fold::Any if b => decided = Some(true), + Fold::All if !b => decided = Some(false), + Fold::None if b => decided = Some(false), + Fold::One => ones += i64::from(b), + _ => {} }, + (Fold::Sum | Fold::Min | Fold::Max | Fold::Avg, Ok(V::Num(d))) => values.push(d), _ => { result = Err(Fault); break; } } + if decided.is_some() { + break; + } } } self.elem = saved.0; self.elems = saved.1; result?; - Ok(V::Num(match fold { - Fold::Sum => acc, - Fold::Count => Dec::int(count), - })) + let sum = || values.iter().try_fold(Decimal::ZERO, |acc, v| acc.checked_add(*v)).ok_or(Fault); + Ok(match fold { + Fold::Count => V::Num(Decimal::from(kept.len())), + Fold::Sum => V::Num(sum()?), + Fold::Any => V::Bool(decided.unwrap_or(false)), + Fold::All | Fold::None => V::Bool(decided.unwrap_or(true)), + Fold::One => V::Bool(ones == 1), + Fold::Min => V::Num(values.iter().copied().min().ok_or(Fault)?), + Fold::Max => V::Num(values.iter().copied().max().ok_or(Fault)?), + Fold::Avg => V::Num(sum()?.checked_div(Decimal::from(values.len())).ok_or(Fault)?), + }) } Op::FirstMatch { conds, strict } => { for (i, c) in conds.iter().enumerate() { match (self.eval(*c), strict) { - (Ok(V::Bool(true)), _) => return Ok(V::Num(Dec::int(i as i64))), - (Ok(V::Bool(false)), _) | (Ok(_), false) => {} - (Ok(_), true) | (Err(_), _) => return Err(Fault), + (Ok(V::Bool(true)), _) => return Ok(V::Num(Decimal::from(i))), + (Ok(V::Bool(false)), _) | (Ok(_), false) | (Err(_), false) => {} + (Ok(_), true) | (Err(_), true) => return Err(Fault), } } - Ok(V::Num(Dec::int(conds.len() as i64))) + Ok(V::Num(Decimal::from(conds.len()))) } Op::Pick(sel, arms) => match self.eval(*sel)? { - V::Num(d) => match usize::try_from(d.mant).ok().and_then(|i| arms.get(i)) { + V::Num(d) => match usize::try_from(d.mantissa()).ok().and_then(|i| arms.get(i)) { Some(arm) => self.eval(*arm), None => Ok(V::Null), }, @@ -291,7 +311,10 @@ impl<'a, 'x> Interp<'a, 'x> { match (func, vals.as_slice()) { (Func::StartsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.starts_with(b))), (Func::EndsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.ends_with(b))), - (Func::Len, [V::Text(a)]) => Ok(V::Num(Dec::int(a.len() as i64))), + (Func::Len, [V::Text(a)]) => Ok(V::Num(Decimal::from(a.len()))), + (Func::Min, items) => items.iter().map(|v| if let V::Num(d) = v { Ok(*d) } else { Err(Fault) }).collect::, _>>()?.into_iter().min().map(V::Num).ok_or(Fault), + (Func::Max, items) => items.iter().map(|v| if let V::Num(d) = v { Ok(*d) } else { Err(Fault) }).collect::, _>>()?.into_iter().max().map(V::Num).ok_or(Fault), + (func, [V::Num(d)]) => Ok(V::Num(Exact::func(*func, *d))), _ => Err(Fault), } } diff --git a/core/expression/src/typed/tests/lower.rs b/core/expression/src/typed/tests/lower.rs index 56fcdaa5..004c1c5f 100644 --- a/core/expression/src/typed/tests/lower.rs +++ b/core/expression/src/typed/tests/lower.rs @@ -299,7 +299,11 @@ fn unsupported_shapes() { ("unsupported path", "c.weird + 1"), ("null arithmetic", "c.absent + 1"), ("function", "string(c.n)"), - ("modulo", "c.n % 2"), + ("variable exponent", "c.n ^ c.n"), + ("fractional exponent", "c.n ^ 0.5"), + ("round to variable places", "round(c.n, c.n)"), + ("bool of a number", "bool(c.n)"), + ("min of nothing", "min([])"), ("closure over a column", "sum(map(c.n, #))"), ]; for (what, source) in cases { diff --git a/core/expression/src/typed/tests/scale.rs b/core/expression/src/typed/tests/scale.rs index e2390ed7..b39dbdc5 100644 --- a/core/expression/src/typed/tests/scale.rs +++ b/core/expression/src/typed/tests/scale.rs @@ -1,3 +1,4 @@ +use crate::typed::build::Passes; use crate::typed::tests::data::{ColSpec, Enc, Frame, ListSpec, Mock, Row, Spec, Value}; use crate::typed::tests::oracle::{Oracle, Val}; use crate::typed::tests::workload::{Block, Dialect, Workload}; @@ -37,7 +38,7 @@ impl Case { out.slots() .iter() .map(|s| match (&s.data, s.scope) { - (Data::Num { .. }, Scope::Row) => s.num(r).map_or("null".to_string(), |d| d.to_string()), + (Data::Num { .. }, Scope::Row) => s.decimal(r).map_or("null".to_string(), |d| d.to_string()), (Data::Bool(_), Scope::Row) => s.boolean(r).map_or("null".to_string(), |b| b.to_string()), _ => "?".to_string(), }) @@ -181,21 +182,19 @@ fn dyn_sums_match_vm() { assert_eq!(out[0].as_deref(), Some(&["7", "7"].map(String::from)[..])); assert_eq!(out[1].as_deref(), Some(&["0.000", "0.000"].map(String::from)[..])); assert_eq!(out[2].as_deref(), Some(&["0.0", "0.000"].map(String::from)[..])); - assert_eq!(out[3], None); + assert_eq!(out[3].as_deref(), Some(&["9223372036854775807.01", "9223372036854775807.01"].map(String::from)[..])); } #[test] -fn negating_zero_faults() { - let case = Case::new(Case::nums(&["a"], Enc::Scaled), &[("x.neg", "-a"), ("x.lit", "-(a * 0)")]); - let out = case.check(&[Case::row(&[Case::d(5, 1)]), Case::row(&[Case::d(0, 2)])]); - assert!(out[0].is_none()); - assert!(out[1].is_none()); - let out = case.check(&[Case::row(&[Case::d(5, 1)])]); - assert!(out[0].is_none()); +fn negating_zero_is_exact() { + let case = Case::new(Case::nums(&["a"], Enc::Scaled), &[("x.neg", "-a"), ("x.lit", "-(a * 0)"), ("x.sum", "-a + 1")]); + let out = case.check(&[Case::row(&[Case::d(5, 1)]), Case::row(&[Case::d(0, 2)]), Case::row(&[Case::d(i64::MIN, 0)])]); + assert!(out.iter().all(Option::is_some), "{out:?}"); + assert_eq!(out[2].as_ref().map(|v| v[0].as_str()), Some("9223372036854775808")); let case = Case::new(Case::nums(&["a"], Enc::Scaled), &[("x.neg", "-a")]); let out = case.check(&[Case::row(&[Case::d(5, 1)]), Case::row(&[Case::d(0, 2)]), Case::row(&[Value::Null])]); assert_eq!(out[0].as_deref(), Some(&["-0.5".to_string()][..])); - assert!(out[1].is_none()); + assert!(out[1].is_some()); assert!(out[2].is_none()); } @@ -228,7 +227,7 @@ fn member_outputs_with_offset_lists() { let Val::List(fees) = &want[0] else { panic!("fee list"); }; - let got: Vec = frame.range(0, r).map(|e| out.slots()[0].num(e).map_or("null".to_string(), |d| d.to_string())).collect(); + let got: Vec = frame.range(0, r).map(|e| out.slots()[0].decimal(e).map_or("null".to_string(), |d| d.to_string())).collect(); assert_eq!(got, fees.iter().map(Val::to_string).collect::>(), "shift {shift} row {r}"); } } @@ -264,7 +263,7 @@ fn rules_fault_strictly() { let mut lowering = Lowering::new(None); lowering.table(&table, &mut Mock { spec: &spec, member: None }).expect("lowering"); let hir = lowering.finish(); - let program = Program::new(hir.clone()).expect("program"); + let looked = Passes { lookup_min: 1, ..Passes::ALL }; let rows = [ Case::row(&[Case::d(20, 0), Value::Str("gold".into())]), Case::row(&[Case::d(5, 0), Value::Str("silver".into())]), @@ -272,15 +271,17 @@ fn rules_fault_strictly() { Case::row(&[Case::d(20, 0), Value::Null]), Case::row(&[Case::d(20, 0), Value::Str("bronze".into())]), ]; - let frame = Frame::new(&hir, &spec, &rows, 0); - let mut out = program.outputs(); - program.run(&frame.batch(), &mut out, None).expect("run"); - let got: Vec = (0..rows.len()) - .map(|r| if out.faults().get(r) { "fault".to_string() } else { out.slots()[0].num(r).map_or("null".to_string(), |d| d.to_string()) }) - .collect(); - match hit { - Hit::Strict => assert_eq!(got, ["1", "2", "fault", "3", "3"]), - Hit::Lenient => assert_eq!(got, ["1", "2", "2", "3", "3"]), + for program in [Program::new(hir.clone()).expect("program"), Program::with(hir.clone(), looked).expect("program")] { + let frame = Frame::new(&hir, &spec, &rows, 0); + let mut out = program.outputs(); + program.run(&frame.batch(), &mut out, None).expect("run"); + let got: Vec = (0..rows.len()) + .map(|r| if out.faults().get(r) { "fault".to_string() } else { out.slots()[0].decimal(r).map_or("null".to_string(), |d| d.to_string()) }) + .collect(); + match hit { + Hit::Strict => assert_eq!(got, ["1", "2", "fault", "3", "3"]), + Hit::Lenient => assert_eq!(got, ["1", "2", "2", "3", "3"]), + } } } } @@ -313,7 +314,7 @@ fn programs_share_across_threads() { .slots() .iter() .map(|s| match &s.data { - Data::Num { .. } => s.num(r).map_or(Val::Null, |d| Val::Num(d.decimal())), + Data::Num { .. } => s.decimal(r).map_or(Val::Null, Val::Num), Data::Bool(_) => s.boolean(r).map_or(Val::Null, Val::Bool), Data::Code(_) => s.code(r).zip(s.dict()).map_or(Val::Null, |(c, d)| Val::Str(hir.dict(d).text(c).unwrap_or("?").to_string())), }) @@ -334,3 +335,19 @@ fn signature_cap_falls_back_to_generic() { case.check(&rows); } } + +#[test] +fn wide_lanes_stay_exact() { + let blocks = [("x.third", "a / 3"), ("x.round", "round(a / 3, 2)"), ("x.big", "a * 1000000000"), ("x.back", "a * 1000000000 / 1000000000"), ("x.cmp", "a / 3 > b")]; + let case = Case::new(Case::nums(&["a", "b"], Enc::Scaled), &blocks); + let rows: Vec = [(10, 0), (i64::MAX, 0), (-7, 2), (0, 3), (1, 28), (i64::MIN, 0)].iter().map(|(m, s)| Case::row(&[Case::d(*m, *s), Case::d(3, 0)])).collect(); + let out = case.check(&rows); + assert!(out.iter().all(Option::is_some), "{out:?}"); + assert_eq!(out[0].as_ref().map(|v| v[0].as_str()), Some("3.3333333333333333333333333333")); + assert_eq!(out[0].as_ref().map(|v| v[1].as_str()), Some("3.33")); + let frame = Frame::new(&case.hir, &case.workload.spec, &rows, 0); + let mut out = case.program.outputs(); + case.program.run(&frame.batch(), &mut out, None).expect("run"); + assert!(!out.slots()[0].wide.is_empty()); + assert!(!out.slots()[2].wide.is_empty()); +} diff --git a/core/expression/src/typed/tests/workload.rs b/core/expression/src/typed/tests/workload.rs index 7a0c0138..18e95c42 100644 --- a/core/expression/src/typed/tests/workload.rs +++ b/core/expression/src/typed/tests/workload.rs @@ -77,7 +77,7 @@ impl Block { } impl Workload { - pub(crate) const NAMES: [&'static str; 4] = ["W1", "W2", "W3", "W4"]; + pub(crate) const NAMES: [&'static str; 7] = ["W1", "W2", "W3", "W4", "W5", "W6", "W7"]; const KINDS: [&'static str; 3] = ["savings", "checking", "loan"]; const TIERS: [&'static str; 3] = ["gold", "silver", "bronze"]; @@ -117,6 +117,47 @@ impl Workload { (["[300..400)", "", "", ""], ["'X'", "0"]), ]; + const W5_KEYS: [(&'static str, &'static str); 18] = [ + ("r2", "round(m.x * 1.075, 2)"), + ("r0", "round(m.x / 3)"), + ("fl", "floor(m.x) + ceil(m.y)"), + ("tr", "trunc(m.y / 7, 3)"), + ("ab", "abs(m.x - m.y)"), + ("md", "m.n % 7"), + ("mx", "m.x % 0.3"), + ("pw", "m.x ^ 2"), + ("pw3", "m.n ^ 3 + m.y ^ -1"), + ("lo", "min([m.x, m.y, 10])"), + ("hi", "max([m.x, $.r2, m.n])"), + ("av", "avg([m.x, m.y])"), + ("sm", "sum([m.x, m.y, m.n])"), + ("b", "bool(m.flag) and m.x > 0"), + ("q3", "m.x / 3 > 1"), + ("neg", "-m.x"), + ("c", "$.q3 ? round($.av, 1) : $.lo"), + ("k", "m.n > 2 ? m.x / 7 : (m.n < -2 ? m.x * m.y : $.pw)"), + ]; + + const W6_KEYS: [(&'static str, &'static str); 10] = [ + ("c.any", "some(c.items, #.qty > 3)"), + ("c.all", "all(c.items, #.ok)"), + ("c.none", "none(c.items, #.price > c.limit)"), + ("c.one", "one(c.items, #.ok)"), + ("c.cnt", "count(c.items, #.qty > 2)"), + ("c.min", "min(map(c.items, #.price))"), + ("c.max", "max(map(filter(c.items, #.ok), #.qty * #.price))"), + ("c.avg", "avg(map(c.items, #.price))"), + ("c.sfilt", "some(filter(c.items, #.ok), #.price / #.qty > 2)"), + ("c.total", "sum(map(c.items, #.price * #.qty / 3))"), + ]; + + const W7_KEYS: [(&'static str, &'static str); 4] = [ + ("item.r", "round(item.price * c.limit / 100, 2)"), + ("item.m", "item.qty % 2 == 0 ? abs(item.price) : -item.price"), + ("item.w", "item.price / 3"), + ("item.f", "floor(item.w * 10) ^ 2"), + ]; + const W4_KEYS: [(&'static str, &'static str); 11] = [ ("subtotal", "order.qty * order.price"), ("rate", "order.discount ?? 0"), @@ -136,6 +177,9 @@ impl Workload { "W1" => Self::w1(), "W2" => Self::w2(), "W3" => Self::w3(), + "W5" => Self::w5(), + "W6" => Self::w6(), + "W7" => Self::w7(), _ => Self::w4(), } } @@ -159,6 +203,8 @@ impl Workload { "W1" => Self::anchor(count).iter().map(Self::w1_row).collect(), "W2" => Self::anchor(count).iter().map(Self::w2_row).collect(), "W3" => Self::w3_rows(count), + "W5" => Self::w5_rows(count), + "W6" | "W7" => Self::w6_rows(count), _ => Self::w4_rows(count), } } @@ -168,6 +214,8 @@ impl Workload { "W1" => Self::w1_extremes(), "W2" => Self::w2_extremes(), "W3" => Self::w3_extremes(), + "W5" => Self::w5_extremes(), + "W6" | "W7" => Self::w6_extremes(), _ => Self::w4_extremes(), } } @@ -317,6 +365,122 @@ impl Workload { } } + fn w5() -> Workload { + Workload { + name: "W5", + spec: Spec { + columns: vec![ + Self::col("m.x", Class::Num, Enc::Scaled), + Self::col("m.y", Class::Num, Enc::Dec), + Self::col("m.n", Class::Num, Enc::I64), + Self::col("m.flag", Class::Bool, Enc::Bool), + ], + lists: Vec::new(), + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W5_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect(), + } + } + + fn w6_spec() -> Spec { + Spec { + columns: vec![Self::col("c.limit", Class::Num, Enc::Scaled)], + lists: vec![ListSpec { + path: "c.items", + alias: "item", + fields: vec![Self::col("qty", Class::Num, Enc::I64), Self::col("price", Class::Num, Enc::Dec), Self::col("ok", Class::Bool, Enc::Bool)], + }], + } + } + + fn w6() -> Workload { + Workload { name: "W6", spec: Self::w6_spec(), dialect: Dialect::Policy, member: None, blocks: Self::W6_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect() } + } + + fn w7() -> Workload { + Workload { name: "W7", spec: Self::w6_spec(), dialect: Dialect::Policy, member: Some(0), blocks: Self::W7_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect() } + } + + fn w5_rows(count: usize) -> Vec { + let mut rng = Rng::new(17); + (0..count) + .map(|_| { + let x = Self::d(rng.pick(2_000_001) as i64 - 1_000_000, rng.pick(5) as u8); + let y = match rng.pick(25) { + 0 => Self::d(0, rng.pick(3) as u8), + _ => Self::d(rng.pick(20_001) as i64 - 10_000, rng.pick(4) as u8), + }; + let n = Self::n(rng.pick(41) as i64 - 20); + let flag = match rng.pick(5) { + 0 => Value::Null, + k => Value::Bool(k % 2 == 0), + }; + Row { columns: vec![x, y, n, flag], lists: Vec::new() } + }) + .collect() + } + + fn w6_rows(count: usize) -> Vec { + let mut rng = Rng::new(19); + (0..count) + .map(|r| { + let len = match r % 211 { + 5 => 1500, + _ => rng.pick(7) as usize, + }; + let items = (0..len) + .map(|_| { + let qty = Self::n(rng.pick(8) as i64); + let price = Self::d(rng.pick(100_000) as i64, rng.pick(3) as u8); + let ok = match rng.pick(40) { + 0 => Value::Null, + k => Value::Bool(k % 3 != 0), + }; + vec![qty, price, ok] + }) + .collect(); + Row { columns: vec![Self::d(rng.pick(50_000) as i64, 1)], lists: vec![items] } + }) + .collect() + } + + fn w5_extremes() -> Vec { + let row = |x: Value, y: Value, n: Value, flag: Value| Row { columns: vec![x, y, n, flag], lists: Vec::new() }; + let t = || Value::Bool(true); + vec![ + row(Self::n(i64::MAX), Self::n(1), Self::n(3), t()), + row(Self::n(i64::MIN), Self::d(-5, 1), Self::n(-3), t()), + row(Self::d(0, 2), Self::d(0, 3), Self::n(0), Value::Bool(false)), + row(Value::Null, Self::n(2), Self::n(1), t()), + row(Self::n(5), Value::Null, Self::n(1), Value::Null), + row(Self::n(5), Self::n(2), Value::Null, t()), + row(Self::d(1, 28), Self::d(-1, 28), Self::n(i64::MAX), t()), + row(Self::d(-25, 1), Self::d(-15, 1), Self::n(-1), t()), + row(Self::d(-4, 1), Self::d(5, 1), Self::n(7), t()), + row(Self::d(i64::MAX, 9), Self::d(i64::MIN, 4), Self::n(9), t()), + row(Self::n(10), Self::n(3), Self::n(2_000_000), t()), + ] + } + + fn w6_extremes() -> Vec { + let row = |limit: Value, items: Vec<[Value; 3]>| Row { columns: vec![limit], lists: vec![items.into_iter().map(|i| i.to_vec()).collect()] }; + let t = || Value::Bool(true); + let f = || Value::Bool(false); + vec![ + row(Self::n(10), Vec::new()), + row(Value::Null, vec![[Self::n(1), Self::n(5), t()]]), + row(Self::n(10), vec![[Self::n(5), Self::n(i64::MAX), t()], [Self::n(4), Self::n(i64::MAX), t()]]), + row(Self::n(10), vec![[Self::n(0), Self::n(7), t()], [Self::n(2), Self::n(9), f()]]), + row(Self::n(10), vec![[Self::n(1), Value::Null, t()], [Self::n(5), Self::n(1), t()]]), + row(Self::n(10), vec![[Self::n(5), Self::n(1), t()], [Self::n(1), Value::Null, Value::Null]]), + row(Self::n(10), vec![[Value::Null, Self::n(1), f()], [Self::n(9), Self::n(3), t()]]), + row(Self::d(1, 28), vec![[Self::n(3), Self::d(-1, 28), t()], [Self::n(3), Self::d(-0, 2), t()]]), + row(Self::n(10), vec![[Self::n(1), Self::d(15, 1), t()], [Self::n(1), Self::n(15), t()], [Self::n(1), Self::d(150, 2), f()]]), + row(Self::n(-1), vec![[Self::n(7), Self::n(i64::MIN), t()]]), + ] + } + fn anchor(count: usize) -> Vec { let mut rng = Rng::new(7); (0..count)