mirror of
https://github.com/gorules/zen.git
synced 2026-11-30 00:07:34 +00:00
perf: typed coverage for math builtins, list folds and member tables; exact wide-value slow path; table rule lookup
This commit is contained in:
@@ -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<i32>, 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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -154,6 +154,9 @@ impl Fused {
|
||||
let mut entries: Vec<Fusion> = 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<str>, 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, _) => {
|
||||
|
||||
@@ -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}});
|
||||
|
||||
@@ -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<Vec<u64>>,
|
||||
pub(crate) faults: Option<Vec<u64>>,
|
||||
pub(crate) wide: Option<(Vec<u64>, Vec<(usize, Decimal)>)>,
|
||||
pub(crate) fixed: Option<u8>,
|
||||
}
|
||||
|
||||
@@ -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<u8> = 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<usize> = 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<Option<u8>>) {
|
||||
into.clear();
|
||||
for (feed, def) in self.columns.iter().zip(&hir.schema.columns) {
|
||||
|
||||
@@ -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<Lookup> {
|
||||
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<R, Unsupported> {
|
||||
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<Built, Unsupported> {
|
||||
let Build { mut code, keys, next, pinned, consts, defs, passes, .. } = self;
|
||||
let mut phys: Vec<R> = (0..next).map(|v| v as R).collect();
|
||||
|
||||
+639
-156
File diff suppressed because it is too large
Load Diff
@@ -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]
|
||||
|
||||
@@ -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<i64>, 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<Lit> },
|
||||
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<R>, sel: bool, strict: bool },
|
||||
Lookup { dst: R, keys: Vec<Option<(R, Rep)>>, tab: Box<Lookup> },
|
||||
Pick { dst: R, sel: R, arms: Vec<(R, Rep, Vec<u16>)>, rep: Rep },
|
||||
Skip { guard: Guard, len: u32 },
|
||||
Fold { fold: Fold, buf: u16, list: u16, filter: Option<R>, value: Option<(R, Rep)> },
|
||||
Text { func: Func, dst: R, a: Arg, b: Option<Arg> },
|
||||
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<u16>,
|
||||
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);
|
||||
|
||||
@@ -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<Key>,
|
||||
pub(crate) rules: usize,
|
||||
pub(crate) words: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Key {
|
||||
pub(crate) node: Option<NodeId>,
|
||||
pub(crate) domain: Domain,
|
||||
pub(crate) hit: Vec<u64>,
|
||||
pub(crate) bad: Vec<u64>,
|
||||
pub(crate) fixed: Option<(u8, Vec<i64>)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Domain {
|
||||
Unit,
|
||||
Bools,
|
||||
Codes(usize),
|
||||
Points(Vec<Dec>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Val {
|
||||
Null,
|
||||
Num(N),
|
||||
Bool(bool),
|
||||
Code(i32),
|
||||
Fault,
|
||||
}
|
||||
|
||||
struct Test {
|
||||
rule: usize,
|
||||
key: Option<NodeId>,
|
||||
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<Lookup> {
|
||||
let rules = conds.len();
|
||||
if rules == 0 || rules > Self::RULES {
|
||||
return None;
|
||||
}
|
||||
let mut tests: Vec<Test> = 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::<Option<Vec<i64>>>().map(|m| (*s, m));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn chain(hir: &Hir, node: NodeId, out: &mut Vec<NodeId>) {
|
||||
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<NodeId>) -> 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<Vec<Option<NodeId>>> {
|
||||
let mut keys: Vec<Option<NodeId>> = 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<usize> = 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<usize> = (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<NodeId>, tests: &[Test]) -> Option<Domain> {
|
||||
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<Dec> = 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<Dec>) {
|
||||
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<Vec<Val>> {
|
||||
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<NodeId>, value: Val) -> Option<Val> {
|
||||
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<usize> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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::<Result<Vec<_>, _>>()?),
|
||||
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<NodeId>, 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))
|
||||
|
||||
@@ -5,6 +5,7 @@ mod hir;
|
||||
mod ins;
|
||||
mod kernel;
|
||||
mod lower;
|
||||
mod lookup;
|
||||
mod num;
|
||||
mod output;
|
||||
mod program;
|
||||
|
||||
@@ -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<Option<Self>, 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<Self> {
|
||||
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<Option<Self>, 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<Self, Fault> {
|
||||
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<Option<Decimal>, 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<Option<N>, 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())
|
||||
|
||||
@@ -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<u64>,
|
||||
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<Dec> {
|
||||
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<Decimal> {
|
||||
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<bool> {
|
||||
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() })
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<bool> = 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::<Result<Vec<_>, _>>()?.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::<Result<Vec<_>, _>>()?.into_iter().max().map(V::Num).ok_or(Fault),
|
||||
(func, [V::Num(d)]) => Ok(V::Num(Exact::func(*func, *d))),
|
||||
_ => Err(Fault),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<String> = frame.range(0, r).map(|e| out.slots()[0].num(e).map_or("null".to_string(), |d| d.to_string())).collect();
|
||||
let got: Vec<String> = 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::<Vec<_>>(), "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<String> = (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<String> = (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<Row> = [(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());
|
||||
}
|
||||
|
||||
@@ -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<Row> {
|
||||
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<Row> {
|
||||
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<Row> {
|
||||
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<Row> {
|
||||
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<AnchorCustomer> {
|
||||
let mut rng = Rng::new(7);
|
||||
(0..count)
|
||||
|
||||
Reference in New Issue
Block a user