feat: lane VM (register-based batch/columnar expression VM in zen-expression, value shapes in zen-types, differential tests against the stack VM)

This commit is contained in:
Stefan
2026-10-06 15:42:30 +02:00
parent 8021c84eac
commit c5c1ef1fd3
41 changed files with 20625 additions and 92 deletions
+6 -1
View File
@@ -48,6 +48,7 @@ default = ["regex-deprecated"]
regex-lite = ["dep:regex-lite"]
regex-deprecated = ["dep:regex"]
arbitrary_precision = ["serde_json/arbitrary_precision", "zen-types/arbitrary_precision"]
lane = []
[[bench]]
harness = false
@@ -63,4 +64,8 @@ name = "unary"
[[bench]]
harness = false
name = "isolate"
name = "isolate"
[[bench]]
harness = false
name = "lane"
+943
View File
@@ -0,0 +1,943 @@
use rust_decimal::Decimal;
use serde_json::Value;
use std::collections::BTreeMap;
use std::hint::black_box;
use std::time::{Duration, Instant};
use zen_expression::lane::{Column, Columns, LaneProgram, LaneRunner, Values};
use zen_expression::variable::VariableType;
use zen_expression::vm::VM;
use zen_expression::{ExpressionKind, Isolate, Scope, Variable};
const ROWS: usize = 512;
const GRAPHS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../test-data/graphs");
struct Case {
source: String,
scopes: Vec<Scope>,
}
struct Bench;
enum Data {
I64(Vec<i64>),
Dec(Vec<Decimal>),
Bool(Vec<u64>),
Str(Vec<String>),
Dict(Vec<i32>, Vec<String>),
ListDec(Vec<i32>, Vec<Decimal>),
ListI64(Vec<i32>, Vec<i64>),
ListStr(Vec<i32>, Vec<String>),
Any(Vec<Variable>),
}
struct Table {
rows: usize,
keys: Vec<String>,
data: Vec<Data>,
valid: Vec<Vec<u64>>,
}
impl Table {
fn flatten(value: &Variable, prefix: String, out: &mut BTreeMap<String, Variable>) {
match value {
Variable::Object(map) if !map.borrow().is_empty() => {
for (k, v) in map.borrow().iter() {
let path = if prefix.is_empty() {
k.to_string()
} else {
format!("{prefix}.{k}")
};
Self::flatten(v, path, out);
}
}
v if !prefix.is_empty() => {
out.insert(prefix, v.clone());
}
_ => {}
}
}
fn build(scopes: &[Scope]) -> Self {
let flat: Vec<BTreeMap<String, Variable>> = scopes
.iter()
.map(|s| {
let mut m = BTreeMap::new();
Self::flatten(s.base(), String::new(), &mut m);
m
})
.collect();
let mut keys: Vec<String> = flat.iter().flat_map(|m| m.keys().cloned()).collect();
keys.sort();
keys.dedup();
let rows = scopes.len();
let mut data = Vec::new();
let mut valid = Vec::new();
for key in &keys {
let values: Vec<Option<&Variable>> = flat.iter().map(|m| m.get(key)).collect();
let mut bits = vec![0u64; rows.div_ceil(64)];
for (i, v) in values.iter().enumerate() {
if v.is_some_and(|v| !matches!(v, Variable::Null)) {
bits[i / 64] |= 1 << (i % 64);
}
}
let present: Vec<&Variable> = values
.iter()
.flatten()
.copied()
.filter(|v| !matches!(v, Variable::Null))
.collect();
let all =
|f: fn(&Variable) -> bool| !present.is_empty() && present.iter().all(|v| f(v));
let integral = |v: &Variable| matches!(v, Variable::Number(n) if n.scale() == 0 && i64::try_from(n.mantissa()).is_ok());
let column = if !present.is_empty() && present.iter().all(|v| integral(v)) {
Data::I64(
values
.iter()
.map(|v| match v {
Some(Variable::Number(n)) => i64::try_from(n.mantissa()).unwrap_or(0),
_ => 0,
})
.collect(),
)
} else if all(|v| matches!(v, Variable::Number(_))) {
Data::Dec(
values
.iter()
.map(|v| match v {
Some(Variable::Number(n)) => *n,
_ => Decimal::ZERO,
})
.collect(),
)
} else if all(|v| matches!(v, Variable::Bool(_))) {
let mut words = vec![0u64; rows.div_ceil(64)];
for (i, v) in values.iter().enumerate() {
if matches!(v, Some(Variable::Bool(true))) {
words[i / 64] |= 1 << (i % 64);
}
}
Data::Bool(words)
} else if all(|v| matches!(v, Variable::String(_)))
&& std::env::var("LANE_DICT").is_ok()
{
let mut distinct: Vec<String> = Vec::new();
let codes = values
.iter()
.map(|v| {
let text = v.and_then(|v| v.as_str()).unwrap_or_default();
match distinct.iter().position(|d| d == text) {
Some(i) => i as i32,
None => {
distinct.push(text.to_string());
(distinct.len() - 1) as i32
}
}
})
.collect();
Data::Dict(codes, distinct)
} else if all(|v| matches!(v, Variable::String(_))) {
Data::Str(
values
.iter()
.map(|v| v.and_then(|v| v.as_str()).unwrap_or_default().to_string())
.collect(),
)
} else if std::env::var("LANE_LISTS").is_ok()
&& all(
|v| matches!(v, Variable::Array(a) if a.borrow().iter().all(|x| matches!(x, Variable::Number(_)))),
)
{
let mut offsets = vec![0i32];
let mut items = Vec::new();
for v in &values {
if let Some(Variable::Array(a)) = v {
items.extend(a.borrow().iter().map(|x| match x {
Variable::Number(n) => *n,
_ => Decimal::ZERO,
}));
}
offsets.push(items.len() as i32);
}
match items
.iter()
.all(|n| n.scale() == 0 && i64::try_from(n.mantissa()).is_ok())
{
true => Data::ListI64(
offsets,
items
.iter()
.map(|n| i64::try_from(n.mantissa()).unwrap_or(0))
.collect(),
),
false => Data::ListDec(offsets, items),
}
} else if std::env::var("LANE_LISTS").is_ok()
&& all(
|v| matches!(v, Variable::Array(a) if a.borrow().iter().all(|x| matches!(x, Variable::String(_)))),
)
{
let mut offsets = vec![0i32];
let mut items = Vec::new();
for v in &values {
if let Some(Variable::Array(a)) = v {
items.extend(
a.borrow()
.iter()
.map(|x| x.as_str().unwrap_or_default().to_string()),
);
}
offsets.push(items.len() as i32);
}
Data::ListStr(offsets, items)
} else {
Data::Any(
values
.iter()
.map(|v| v.cloned().unwrap_or(Variable::Null))
.collect(),
)
};
data.push(column);
valid.push(bits);
}
Self {
rows,
keys,
data,
valid,
}
}
fn children<'a>(&'a self, texts: &'a [(Vec<i32>, Vec<u8>)]) -> Vec<Column<'a>> {
self.data
.iter()
.enumerate()
.map(|(i, d)| match d {
Data::ListDec(_, items) => Column::new(Values::Dec(items)),
Data::ListI64(_, items) => Column::new(Values::I64(items)),
Data::ListStr(..) | Data::Dict(..) => Column::new(Values::Utf8 {
offsets: &texts[i].0,
data: &texts[i].1,
}),
_ => Column::new(Values::Any(&[])),
})
.collect()
}
fn columns<'a>(
&'a self,
texts: &'a [(Vec<i32>, Vec<u8>)],
children: &'a [Column<'a>],
) -> Columns<'a> {
let mut columns = Columns::new(self.rows);
for (i, ((key, data), valid)) in self
.keys
.iter()
.zip(&self.data)
.zip(&self.valid)
.enumerate()
{
let values = match data {
Data::I64(v) => Values::I64(v),
Data::Dec(v) => Values::Dec(v),
Data::Bool(bits) => Values::Bool { bits, offset: 0 },
Data::Str(_) => Values::Utf8 {
offsets: &texts[i].0,
data: &texts[i].1,
},
Data::ListDec(offsets, _)
| Data::ListI64(offsets, _)
| Data::ListStr(offsets, _) => Values::List {
offsets,
child: (&children[i]).into(),
},
Data::Dict(keys, _) => Values::Dict {
keys,
values: (&children[i]).into(),
},
Data::Any(v) => Values::Any(v),
};
columns = columns.column(key, Column::with_validity(values, valid, 0));
}
columns
}
fn texts(&self) -> Vec<(Vec<i32>, Vec<u8>)> {
self.data
.iter()
.map(|d| match d {
Data::Str(v) | Data::ListStr(_, v) | Data::Dict(_, v) => {
let mut offsets = vec![0i32];
let mut data = Vec::new();
for text in v {
data.extend_from_slice(text.as_bytes());
offsets.push(data.len() as i32);
}
(offsets, data)
}
_ => (Vec::new(), Vec::new()),
})
.collect()
}
}
impl Bench {
fn cases() -> Vec<Case> {
let mut names: Vec<_> = std::fs::read_dir(GRAPHS)
.map(|d| d.flatten().map(|e| e.path()).collect())
.unwrap_or_default();
names.sort();
let mut out = Vec::new();
for path in names {
let Ok(raw) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(doc) = serde_json::from_str::<Value>(&raw) else {
continue;
};
let inputs: Vec<Variable> = doc["tests"]
.as_array()
.into_iter()
.flatten()
.filter_map(|t| t.get("input").cloned())
.map(Variable::from)
.collect();
if inputs.is_empty() {
continue;
}
for node in doc["nodes"].as_array().into_iter().flatten() {
if node["type"] != "expressionNode" {
continue;
}
for e in node["content"]["expressions"]
.as_array()
.into_iter()
.flatten()
{
let Some(source) = e["value"].as_str() else {
continue;
};
let scopes: Vec<Scope> = (0..ROWS)
.map(|i| Scope::new(inputs[i % inputs.len()].depth_clone(64)))
.collect();
let ok = scopes.iter().take(inputs.len()).all(|s| {
let mut iso = Isolate::new();
iso.set_environment(s.base().clone());
matches!(iso.run_standard(source), Ok(v) if v != Variable::Null)
});
if ok && !source.contains("date(") {
out.push(Case {
source: source.to_string(),
scopes,
});
}
}
}
}
out
}
fn timed(budget: Duration, mut f: impl FnMut()) -> f64 {
f();
let start = Instant::now();
let mut n = 0u64;
while start.elapsed() < budget {
f();
n += 1;
}
start.elapsed().as_nanos() as f64 / n as f64
}
fn median(mut v: Vec<f64>) -> f64 {
v.sort_by(|a, b| a.total_cmp(b));
v.get(v.len() / 2).copied().unwrap_or(0.0)
}
fn geomean(v: &[f64]) -> f64 {
(v.iter().map(|x| x.ln()).sum::<f64>() / v.len() as f64).exp()
}
}
fn micro() -> bool {
let Ok(list) = std::env::var("LANE_EXPR") else {
return false;
};
let input = Variable::from(serde_json::json!({
"a": 5, "b": 7, "s": "gold", "flag": true, "items": [1, 2, 3, 4, 5, 6, 7, 8],
"tags": ["x", "diabetes", "y"], "o": {"x": 1, "y": {"z": 2}}, "d1": "2025-03-15T10:30:00Z", "d2": "2025-03-15", "d3": "2025-03-15 10:30:00",
"objs": [{"x": 1, "k": "a"}, {"x": 5, "k": "b"}, {"x": 9, "k": "c"}, {"x": 2, "k": "a"}],
"email": "john.doe@example.com", "phone": "+1-555-0100"
}));
let rows: usize = std::env::var("LANE_ROWS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(ROWS);
let mut runner = LaneRunner::new();
let budget = Duration::from_millis(300);
for entry in list.split('|') {
let (reference, source) = match entry.split_once(':') {
Some(("u", rest)) => (Some(Variable::Number(5.into())), rest),
Some(("us", rest)) => (Some(Variable::String("gold".into())), rest),
_ => (None, entry),
};
let vary = std::env::var("LANE_VARY").is_ok();
let scopes: Vec<Scope> = (0..rows)
.map(|i| {
let base = match vary {
true => {
let mut value = input.depth_clone(64);
if let Variable::Object(o) = &mut value {
let mut o = o.borrow_mut();
let day = |k: usize| {
format!("20{:02}-{:02}-{:02}", 10 + k % 15, 1 + k % 12, 1 + k % 28)
};
o.insert(
"a".into(),
Variable::Number(Decimal::from(((i * 7919) % 97) as i64 - 40)),
);
o.insert(
"b".into(),
Variable::Number(Decimal::from(((i * 104729) % 89) as i64 - 30)),
);
o.insert(
"d1".into(),
Variable::String(
format!("{}T{:02}:30:00Z", day(i), i % 24).as_str().into(),
),
);
o.insert(
"d2".into(),
Variable::String(day(i * 31 + 7).as_str().into()),
);
o.insert(
"s".into(),
Variable::String(
["gold", "silver", "Bronze", "platinum"][i % 4].into(),
),
);
}
value
}
false => input.depth_clone(64),
};
let mut scope = Scope::new(base);
if let Some(r) = &reference {
scope.set_local(Variable::dollar_key(), r.clone());
}
scope
})
.collect();
let program = match reference {
Some(_) => LaneProgram::unary(source),
None => LaneProgram::standard(source),
}
.expect("lane compile")
.specialize(&scopes)
.expect("specialize");
let mut vm = VM::new();
let s = match reference {
Some(_) => {
let expression = Isolate::new().compile_unary(source).expect("compile");
Bench::timed(budget, || {
for scope in &scopes {
black_box(expression.evaluate_with_scope(scope, &mut vm).is_ok());
}
})
}
None => {
let expression = Isolate::new().compile_standard(source).expect("compile");
Bench::timed(budget, || {
for scope in &scopes {
black_box(expression.evaluate_with_scope(scope, &mut vm).is_ok());
}
})
}
} / rows as f64;
if std::env::var("LANE_DUMP").is_ok() {
for step in &program.program().steps {
println!(" {:?}", step);
}
}
let profile = std::env::var("LANE_PROFILE").is_ok();
let one = Bench::timed(
if profile {
Duration::from_secs(4)
} else {
budget
},
|| {
for scope in &scopes {
black_box(runner.evaluate_one(&program, scope).is_ok());
}
},
) / rows as f64;
if profile {
println!("{source} lane-w1 {one:.1}");
continue;
}
let batch = Bench::timed(budget, || {
let mut n = 0usize;
runner.evaluate_with(&program, &scopes, |_, r| n += r.is_ok() as usize);
black_box(n);
}) / rows as f64;
let table = Table::build(&scopes);
let texts = table.texts();
let children = table.children(&texts);
let columns = table.columns(&texts, &children);
let columnar = match reference {
Some(_) => None,
None => LaneProgram::standard(source)
.ok()
.and_then(|p| p.specialize_columns(&columns).ok()),
};
let mut out = zen_expression::lane::Output::new();
if let (Ok(_), Some(p)) = (std::env::var("LANE_PROFILE_COLS"), &columnar) {
let ns = Bench::timed(Duration::from_secs(4), || {
runner.evaluate_columns_into(p, &columns, &mut out);
black_box(out.len());
}) / rows as f64;
println!("{entry} cols {ns:.1}");
continue;
}
let cols = match &columnar {
Some(p) => {
Bench::timed(budget, || {
runner.evaluate_columns_into(p, &columns, &mut out);
black_box(out.len());
}) / rows as f64
}
None => f64::NAN,
};
if std::env::var("LANE_TABLE").is_ok() {
let generic = match reference {
Some(_) => LaneProgram::unary(source),
None => LaneProgram::standard(source),
}
.expect("lane compile");
let cold1 = Bench::timed(budget, || {
for scope in &scopes {
black_box(runner.evaluate_one(&generic, scope).is_ok());
}
}) / rows as f64;
let cold64 = Bench::timed(budget, || {
let mut n = 0usize;
runner.evaluate_with(&generic, &scopes, |_, r| n += r.is_ok() as usize);
black_box(n);
}) / rows as f64;
println!(
"TSV\t{entry}\t{s:.1}\t{cold1:.1}\t{cold64:.1}\t{one:.1}\t{batch:.1}\t{cols:.1}"
);
continue;
}
println!(
"{:50} ops {:3} stack {s:7.1} lane-w1 {one:7.1} lane-w64 {batch:7.1} cols {cols:6.1} | w1 {:5.2}x w64 {:5.2}x cols {:5.1}x",
entry,
program.program().steps.len(),
s / one,
s / batch,
s / cols
);
}
true
}
fn cells() -> bool {
if std::env::var("LANE_CELLS").is_err() {
return false;
}
let mut state = 0x1234_5678_9ABC_DEF1u64;
let mut next = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
for rules in [100usize, 1000, 8000] {
let cells: Vec<String> = (0..rules)
.map(|r| match (next(10), r + 1 == rules) {
(_, true) | (0..=2, _) => String::new(),
(3 | 4, _) => format!(
"'{}'",
["US", "GB", "DE", "FR", "ES", "IT", "NL", "PL"][next(8) as usize]
),
(5 | 6, _) => format!(
"{} {}",
["<", "<=", ">", ">="][next(4) as usize],
next(20) * 5
),
(7, _) => format!("[{}..{}]", next(10) * 5, 50 + next(10) * 5),
(8, _) => format!(
"'{}', '{}'",
["US", "GB"][next(2) as usize],
["DE", "FR"][next(2) as usize]
),
_ => "$ > limit".to_string(),
})
.collect();
let refs: Vec<Option<&str>> = cells.iter().map(|c| Some(c.as_str())).collect();
let set = zen_expression::lane::CellSet::compile(&refs).expect("cells");
let values: Vec<Variable> = (0..ROWS)
.map(|i| match i % 2 {
0 => Variable::from(serde_json::json!(
["US", "GB", "DE", "SE"][next(4) as usize]
)),
_ => Variable::from(serde_json::json!(next(100))),
})
.collect();
let envs: Vec<Scope> = (0..ROWS)
.map(|_| Scope::new(serde_json::json!({"limit": next(50)}).into()))
.collect();
let exprs: Vec<Option<zen_expression::Expression<zen_expression::expression::Unary>>> =
cells
.iter()
.map(|c| (!c.is_empty()).then(|| Isolate::new().compile_unary(c).expect("unary")))
.collect();
let mut vm = VM::new();
let stack = Bench::timed(Duration::from_millis(400), || {
let mut hits = 0usize;
for (value, env) in values.iter().zip(&envs).take(64) {
let mut scope = Scope::new(env.base().clone());
scope.set_local(Variable::dollar_key(), value.clone());
for e in &exprs {
hits += match e {
None => 1,
Some(e) => e.evaluate_with_scope(&scope, &mut vm).unwrap_or(false) as usize,
};
}
}
black_box(hits);
}) / 64.0;
let mut runner = LaneRunner::new();
let mut out = Vec::new();
let lane = Bench::timed(Duration::from_millis(400), || {
set.evaluate(&mut runner, &values, &envs, &mut out);
black_box(out.len());
}) / ROWS as f64;
println!("cells rules {rules:5}: evaluate every cell (stack VM) {stack:10.0} ns/row | cell set {lane:8.1} ns/row | {:6.1}x", stack / lane);
}
true
}
fn nodes() -> bool {
if std::env::var("LANE_NODES").is_err() {
return false;
}
let mut names: Vec<_> = std::fs::read_dir(GRAPHS)
.map(|d| d.flatten().map(|e| e.path()).collect())
.unwrap_or_default();
names.sort();
let (mut stack_all, mut one_all, mut batch_all) = (Vec::new(), Vec::new(), Vec::new());
let mut runner = LaneRunner::new();
for path in names {
let Ok(raw) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(doc) = serde_json::from_str::<Value>(&raw) else {
continue;
};
let inputs: Vec<Variable> = doc["tests"]
.as_array()
.into_iter()
.flatten()
.filter_map(|t| t.get("input").cloned())
.map(Variable::from)
.collect();
if inputs.is_empty() {
continue;
}
for node in doc["nodes"].as_array().into_iter().flatten() {
if node["type"] != "expressionNode"
|| node["content"]["inputField"]
.as_str()
.is_some_and(|s| !s.is_empty())
{
continue;
}
let entries: Vec<(String, String)> = node["content"]["expressions"]
.as_array()
.into_iter()
.flatten()
.filter_map(|e| {
Some((
e["key"].as_str()?.to_string(),
e["value"].as_str()?.to_string(),
))
})
.filter(|(k, v)| !k.is_empty() && !v.is_empty())
.collect();
if entries.is_empty() {
continue;
}
let refs: Vec<(&str, &str)> = entries
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let Ok(program) = LaneProgram::compile_many(&refs, true) else {
continue;
};
let scopes: Vec<Scope> = (0..ROWS)
.map(|i| Scope::new(inputs[i % inputs.len()].depth_clone(64)))
.collect();
let program = program.specialize(&scopes).expect("specialize");
let codes: Vec<(
String,
zen_expression::Expression<zen_expression::expression::Standard>,
)> = entries
.iter()
.filter_map(|(k, v)| Some((k.clone(), Isolate::new().compile_standard(v).ok()?)))
.collect();
if codes.len() != entries.len() {
continue;
}
let mut vm = VM::new();
let budget = Duration::from_millis(80);
let stack = Bench::timed(budget, || {
for scope in &scopes {
let mut scope = scope.clone();
let dollar = Variable::empty_object();
scope.set_local(Variable::dollar_key(), dollar.clone());
for (key, e) in &codes {
match e.evaluate_with_scope(&scope, &mut vm) {
Ok(v) => {
dollar.dot_insert(key, v);
}
Err(_) => break,
}
}
black_box(&dollar);
}
}) / ROWS as f64;
let one = Bench::timed(budget, || {
for scope in &scopes {
runner.evaluate_many(&program, std::slice::from_ref(scope), None, |_, r| {
black_box(r.is_some());
});
}
}) / ROWS as f64;
let batch = Bench::timed(budget, || {
runner.evaluate_many(&program, &scopes, None, |_, r| {
black_box(r.is_some());
});
}) / ROWS as f64;
stack_all.push(stack);
one_all.push(one);
batch_all.push(batch);
}
}
let r1: Vec<f64> = stack_all.iter().zip(&one_all).map(|(s, l)| s / l).collect();
let r64: Vec<f64> = stack_all
.iter()
.zip(&batch_all)
.map(|(s, l)| s / l)
.collect();
println!(
"expression nodes {} | median ns/row: stack {:.0}, lane w1 {:.0}, lane w64 {:.0} | stack/lane geomean: w1 {:.2}x, w64 {:.2}x | sums: stack {:.0}, w1 {:.0}, w64 {:.0}",
stack_all.len(),
Bench::median(stack_all.clone()),
Bench::median(one_all.clone()),
Bench::median(batch_all.clone()),
Bench::geomean(&r1),
Bench::geomean(&r64),
stack_all.iter().sum::<f64>(),
one_all.iter().sum::<f64>(),
batch_all.iter().sum::<f64>()
);
true
}
fn main() {
if nodes() {
return;
}
if cells() {
return;
}
if micro() {
return;
}
let filter = std::env::args().nth(1).filter(|a| !a.starts_with('-'));
let budget = Duration::from_millis(60);
let cases = Bench::cases();
let (mut stack, mut w1, mut w64, mut cols, mut outs) =
(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut typing: Vec<[f64; 9]> = Vec::new();
let mut runner = LaneRunner::new();
for case in &cases {
if let Some(f) = &filter {
if !case.source.contains(f.as_str()) {
continue;
}
}
let expression = Isolate::new()
.compile_standard(&case.source)
.expect("compile");
let generic = LaneProgram::standard(&case.source).expect("lane compile");
let program = generic.specialize(&case.scopes).expect("specialize");
let mut vm = VM::new();
let only_columns = std::env::var("LANE_ONLY_COLUMNS").is_ok();
let budget = if only_columns {
Duration::from_millis(1)
} else {
budget
};
let s = Bench::timed(budget, || {
for scope in &case.scopes {
black_box(expression.evaluate_with_scope(scope, &mut vm).is_ok());
}
}) / ROWS as f64;
let one = Bench::timed(budget, || {
for scope in &case.scopes {
black_box(runner.evaluate_one(&program, scope).is_ok());
}
}) / ROWS as f64;
let batch = Bench::timed(budget, || {
let mut n = 0usize;
runner.evaluate_with(&program, &case.scopes, |_, r| n += r.is_ok() as usize);
black_box(n);
}) / ROWS as f64;
let table = Table::build(&case.scopes);
let texts = table.texts();
let children = table.children(&texts);
let columns = table.columns(&texts, &children);
let columnar = generic.specialize_columns(&columns).expect("specialize");
let col = Bench::timed(
if only_columns {
Duration::from_millis(300)
} else {
budget
},
|| {
let mut n = 0usize;
runner.evaluate_columns(&columnar, &columns, |_, r| n += r.is_ok() as usize);
black_box(n);
},
) / ROWS as f64;
let mut out = zen_expression::lane::Output::new();
let typed = Bench::timed(
if only_columns {
Duration::from_millis(300)
} else {
budget
},
|| {
runner.evaluate_columns_into(&columnar, &columns, &mut out);
black_box(out.len());
},
) / ROWS as f64;
if std::env::var("LANE_DEBUG").is_ok() {
let p = columnar.program();
let bound: Vec<zen_expression::lane::Binding> = p
.site_keys
.iter()
.map(|k| {
k.as_deref()
.map_or(zen_expression::lane::Binding::Row, |k| columns.bind(k))
})
.collect();
println!(
"keys {:?} bound {:?} rows {} kinds {:?}",
p.site_keys,
bound,
p.needs_rows(&bound),
p.kinds
);
for (k, c) in &columns.columns {
if k.contains("status") || k.contains("watch") {
println!(" column {k} {:?}", c.kind());
}
}
}
if std::env::var("LANE_DUMP").is_ok() {
println!("input {:?}", case.scopes[0].base().to_value());
for step in &program.program().steps {
println!(" {:?}", step);
}
}
if filter.is_some() {
println!("{:70} stack {s:8.1} lane-w1 {one:8.1} lane-w64 {batch:8.1} columns {col:8.1} typed {typed:8.1}", &case.source[..case.source.len().min(70)]);
}
stack.push(s);
w1.push(one);
w64.push(batch);
cols.push(col);
outs.push(typed);
if std::env::var("LANE_TYPING").is_ok() {
let first = VariableType::from(&case.scopes[0].base().to_value());
let typed_program =
LaneProgram::compile_typed(&case.source, ExpressionKind::Standard, &first)
.expect("typed");
let leg = |p: &LaneProgram, runner: &mut LaneRunner| {
let w1 = Bench::timed(budget, || {
for scope in &case.scopes {
black_box(runner.evaluate_one(p, scope).is_ok());
}
}) / ROWS as f64;
let w64 = Bench::timed(budget, || {
let mut n = 0usize;
runner.evaluate_with(p, &case.scopes, |_, r| n += r.is_ok() as usize);
black_box(n);
}) / ROWS as f64;
(w1, w64)
};
let (g1, g64) = leg(&generic, &mut runner);
let (t1, t64) = leg(&typed_program, &mut runner);
let gc = Bench::timed(budget, || {
runner.evaluate_columns_into(&generic, &columns, &mut out);
black_box(out.len());
}) / ROWS as f64;
typing.push([s, one, batch, typed, g1, g64, gc, t1, t64]);
}
}
let r1: Vec<f64> = stack.iter().zip(&w1).map(|(s, l)| s / l).collect();
let r64: Vec<f64> = stack.iter().zip(&w64).map(|(s, l)| s / l).collect();
let rc: Vec<f64> = stack.iter().zip(&cols).map(|(s, l)| s / l).collect();
let ro: Vec<f64> = stack.iter().zip(&outs).map(|(s, l)| s / l).collect();
if !typing.is_empty() {
let labels = [
"speculated w1",
"speculated w64",
"column-typed output",
"generic w1",
"generic w64",
"generic columns output",
"compile_typed w1",
"compile_typed w64",
];
for (i, label) in labels.iter().enumerate() {
let ratios: Vec<f64> = typing.iter().map(|t| t[0] / t[i + 1]).collect();
let times: Vec<f64> = typing.iter().map(|t| t[i + 1]).collect();
println!(
"typing | {label:24} geomean {:5.2}x median {:5.2}x | median {:6.1} ns/row",
Bench::geomean(&ratios),
Bench::median(ratios.clone()),
Bench::median(times)
);
}
}
println!(
"typed output: median {:.1} ns/row, stack/typed geomean {:.2}x, median {:.2}x, sum {:.0}",
Bench::median(outs.clone()),
Bench::geomean(&ro),
Bench::median(ro.clone()),
outs.iter().sum::<f64>()
);
println!(
"columns: median {:.1} ns/row, stack/columns geomean {:.2}x, median {:.2}x, sum {:.0}",
Bench::median(cols.clone()),
Bench::geomean(&rc),
Bench::median(rc.clone()),
cols.iter().sum::<f64>()
);
println!(
"{} expressions | median ns/eval: stack {:.1}, lane w1 {:.1}, lane w64 {:.1} | stack/lane geomean: w1 {:.2}x, w64 {:.2}x | sums: stack {:.0}, w1 {:.0}, w64 {:.0}",
stack.len(),
Bench::median(stack.clone()),
Bench::median(w1.clone()),
Bench::median(w64.clone()),
Bench::geomean(&r1),
Bench::geomean(&r64),
stack.iter().sum::<f64>(),
w1.iter().sum::<f64>(),
w64.iter().sum::<f64>()
);
}
+10
View File
@@ -142,6 +142,10 @@ impl Isolate {
}
pub fn run_standard(&mut self, source: &str) -> Result<Variable, IsolateError> {
#[cfg(feature = "lane")]
return crate::lane::Backend::run(source, ExpressionKind::Standard, &self.scope);
#[allow(unreachable_code)]
let cached = self
.cache
.as_ref()
@@ -171,6 +175,12 @@ impl Isolate {
}
pub fn run_unary(&mut self, source: &str) -> Result<bool, IsolateError> {
#[cfg(feature = "lane")]
return crate::lane::Backend::run(source, ExpressionKind::Unary, &self.scope)?
.as_bool()
.ok_or(IsolateError::ValueCastError);
#[allow(unreachable_code)]
let cached = self
.cache
.as_ref()
+166
View File
@@ -0,0 +1,166 @@
use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Outcome, Params};
use crate::variable::{Variable, VariableMap};
pub(crate) struct Arrays;
impl Arrays {
const ARRAY: &'static [(&'static str, bool)] = &[("array", false)];
pub(crate) const FLATTEN: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
Ok(a.with(|values| {
let mut flat = Vec::with_capacity(values.len());
for v in values {
match v {
Variable::Array(inner) => flat.extend(inner.borrow().iter().cloned()),
v => flat.push(v.clone()),
}
}
Variable::from_array(flat)
}))
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
pub(crate) const MERGE: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Array| a.with(Self::merge))],
fail: |args| Params::fail(args, Self::ARRAY),
};
fn merge(values: &[Variable]) -> Result<Variable, Fail> {
let Some(first) = values.iter().find(|item| !matches!(item, Variable::Null)) else {
return Ok(Variable::empty_object());
};
let capacity = values
.iter()
.map(|item| match item {
Variable::Object(o) => o.borrow().len(),
Variable::Array(a) => a.borrow().len(),
_ => 0,
})
.sum();
match first {
Variable::Array(_) => {
let mut merged = Vec::with_capacity(capacity);
for item in values {
match item {
Variable::Array(inner) => merged.extend(inner.borrow().iter().cloned()),
Variable::Null => {}
_ => return Err("Expected array of arrays".to_string()),
}
}
Ok(Variable::from_array(merged))
}
Variable::Object(_) => {
let mut merged = VariableMap::with_capacity(capacity);
for item in values {
match item {
Variable::Object(o) => {
for (key, value) in o.borrow().iter() {
merged.insert(key.clone(), value.clone());
}
}
Variable::Null => {}
_ => return Err("Expected array of objects".to_string()),
}
}
Ok(Variable::from_object(merged))
}
other => Err(format!(
"merge expects an array of arrays or objects, got {}",
other.type_name()
)),
}
}
pub(crate) const MERGE_DEEP: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
a.with(|values| {
let mut result = Variable::empty_object();
for item in values {
match item {
Variable::Object(_) => result = Self::deep(&result, item),
Variable::Null => {}
_ => return Err("Expected array of objects".to_string()),
}
}
Ok(result)
})
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
fn deep(base: &Variable, patch: &Variable) -> Variable {
match (base, patch) {
(Variable::Object(a), Variable::Object(b)) => {
let (a, b) = (a.borrow(), b.borrow());
let mut merged = VariableMap::with_capacity(a.len() + b.len());
for (key, value) in a.iter() {
merged.insert(key.clone(), value.clone());
}
for (key, value) in b.iter() {
let entry = merged
.get(key)
.map(|existing| Self::deep(existing, value))
.unwrap_or_else(|| value.clone());
merged.insert(key.clone(), entry);
}
Variable::from_object(merged)
}
(Variable::Array(a), Variable::Array(b)) => {
let (a, b) = (a.borrow(), b.borrow());
let mut merged = Vec::with_capacity(a.len() + b.len());
merged.extend(a.iter().cloned());
merged.extend(b.iter().cloned());
Variable::from_array(merged)
}
(_, patch) => patch.clone(),
}
}
pub(crate) const KEYS: Builtin = Builtin {
overloads: &[Self::keys],
fail: |_| "Argument on 0 position out of bounds".to_string(),
};
fn keys(args: &[Arg]) -> Outcome {
Apply::one(args, |a: Arg| match a {
Arg::Var(Variable::Array(_)) | Arg::List(_) => {
let len = match a {
Arg::List(l) => l.end - l.start,
Arg::Var(Variable::Array(v)) => v.borrow().len(),
_ => 0,
};
Ok(Variable::from_array(
(0..len).map(|i| Variable::Number(i.into())).collect(),
))
}
Arg::Var(Variable::Object(o)) => Ok(Variable::from_array(
o.borrow()
.iter()
.map(|(key, _)| Variable::String(key.as_str().into()))
.collect(),
)),
other => Err(format!(
"Cannot determine keys of type {}",
other.type_name()
)),
})
}
pub(crate) const VALUES: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: &Variable| match a {
Variable::Object(o) => {
Ok(Variable::from_array(o.borrow().values().cloned().collect()))
}
_ => Err("Argument on 0 is not a object".to_string()),
})
}],
fail: |args| Params::fail(args, &[("object", false)]),
};
}
@@ -0,0 +1,111 @@
use crate::lane::builtins::{Apply, Arg, Builtin, Params};
use crate::lane::date::Date;
use crate::variable::Variable;
use chrono_tz::Tz;
use rust_decimal::Decimal;
use std::str::FromStr;
pub(crate) struct Convert;
impl Convert {
fn parse(s: &str) -> Option<Decimal> {
let s = s.trim();
Decimal::from_str_exact(s)
.or_else(|_| Decimal::from_scientific(s))
.ok()
}
fn truthy(s: &str) -> bool {
match s.trim() {
"true" => true,
"false" => false,
_ => s.is_empty(),
}
}
pub(crate) const TYPE: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Arg| Ok(a.type_name()))],
fail: |_| "Argument on 0 position out of bounds".to_string(),
};
pub(crate) const BOOL: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| {
Ok(match a {
Arg::Null => false,
Arg::Bool(b) => b,
Arg::Num(n) => !n.is_zero(),
Arg::Str(s) => Self::truthy(s),
Arg::Var(v) if Date::sourced(v) => Self::truthy(Date::source(v).unwrap_or_default()),
Arg::Date(_) | Arg::Var(_) | Arg::List(_) => true,
})
})
}],
fail: |_| "Argument on 0 position out of bounds".to_string(),
};
pub(crate) const STRING: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| match a {
Arg::Null => Ok("null".to_string()),
Arg::Bool(b) => Ok(b.to_string()),
Arg::Num(n) => Ok(n.to_string()),
Arg::Str(s) => Ok(s.to_string()),
Arg::Date(d) => Ok(d.to_string()),
Arg::Var(v @ Variable::Dynamic(d)) if Date::of(v).is_some() => Ok(d.to_string()),
other => Err(format!(
"Cannot convert type {} to string",
other.type_name()
)),
})
}],
fail: |_| "Argument on 0 position out of bounds".to_string(),
};
pub(crate) const NUMBER: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| match a {
Arg::Num(n) => Ok(n),
Arg::Str(s) => Self::parse(s).ok_or_else(|| "Invalid number".to_string()),
Arg::Bool(true) => Ok(Decimal::ONE),
Arg::Bool(false) => Ok(Decimal::ZERO),
other => Err(format!(
"Cannot convert type {} to number",
other.type_name()
)),
})
}],
fail: |_| "Argument on 0 position out of bounds".to_string(),
};
pub(crate) const IS_NUMERIC: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| {
Ok(match a {
Arg::Num(_) => true,
Arg::Str(s) => Self::parse(s).is_some(),
_ => false,
})
})
}],
fail: |_| "Argument on 0 position out of bounds".to_string(),
};
pub(crate) const DATE: Builtin = Builtin {
overloads: &[|args| {
Apply::two(args, |value: Option<Arg>, zone: Option<&str>| {
let zone = match zone {
Some(z) => Some(Tz::from_str(z).map_err(|_| "Invalid timezone".to_string())?),
None => None,
};
Ok(match value {
Some(Arg::Date(d)) => zone.map_or(d, |zone| d.tz(zone)),
Some(Arg::Str(s)) => Date::text(s, zone),
Some(v) => Date::new(v.variable(), zone),
None => Date::now(),
})
})
}],
fail: |args| Params::fail(args, &[("value", true), ("string", true)]),
};
}
+408
View File
@@ -0,0 +1,408 @@
use crate::functions::{DateMethod, MethodKind};
use crate::lane::builtins::{Arg, Builtin, Fail, Out, Outcome};
use crate::lane::date::Date;
use crate::lane::date::{Duration, DurationUnit};
use crate::variable::Variable;
use chrono::{Datelike, Timelike};
use chrono_tz::Tz;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::Decimal;
use std::borrow::Cow;
use std::str::FromStr;
pub(crate) struct Dates;
pub(crate) enum Shift {
Add(Duration),
Sub(Duration),
Start(DurationUnit),
End(DurationUnit),
}
impl Shift {
#[inline]
pub(crate) fn apply(&self, date: &Date) -> Date {
match self {
Shift::Add(d) => date.add(d.clone()),
Shift::Sub(d) => date.sub(d.clone()),
Shift::Start(unit) => date.start_of(*unit),
Shift::End(unit) => date.end_of(*unit),
}
}
}
#[derive(Clone, Copy)]
enum Compare {
Same,
Before,
After,
SameOrBefore,
SameOrAfter,
}
#[derive(Clone, Copy)]
enum Part {
Second,
Minute,
Hour,
Day,
Weekday,
DayOfYear,
Week,
Month,
Quarter,
Year,
Timestamp,
OffsetName,
IsValid,
IsYesterday,
IsToday,
IsTomorrow,
IsLeapYear,
}
impl Dates {
const NEVER: fn(&[Arg]) -> Fail =
|_| "Argument on 0 position is not a valid dynamic".to_string();
fn this(args: &[Arg]) -> Result<Date, Fail> {
args.first()
.and_then(Arg::date)
.ok_or_else(|| "Argument on 0 position is not a valid dynamic".to_string())
}
fn var<'a>(args: &[Arg<'a>], pos: usize) -> Result<Arg<'a>, Fail> {
args.get(pos)
.copied()
.ok_or_else(|| format!("Argument on {pos} position out of bounds"))
}
fn ostr<'a>(args: &[Arg<'a>], pos: usize) -> Result<Option<Cow<'a, str>>, Fail> {
match args.get(pos) {
None => Ok(None),
Some(a) => a
.text()
.map(Some)
.ok_or_else(|| format!("Argument on {pos} is not a string")),
}
}
fn str<'a>(args: &[Arg<'a>], pos: usize) -> Result<Cow<'a, str>, Fail> {
Self::ostr(args, pos)?
.ok_or_else(|| format!("Argument on {pos} position is not a valid string"))
}
fn number(args: &[Arg], pos: usize) -> Result<Decimal, Fail> {
match args.get(pos) {
None => Err(format!("Argument on {pos} position is not a valid number")),
Some(Arg::Num(n)) => Ok(*n),
Some(_) => Err(format!("Argument on {pos} is not a number")),
}
}
fn unit(args: &[Arg], pos: usize) -> Result<DurationUnit, Fail> {
DurationUnit::parse(&Self::str(args, pos)?)
.ok_or_else(|| "Invalid duration unit".to_string())
}
fn unit_opt(args: &[Arg], pos: usize) -> Result<Option<DurationUnit>, Fail> {
match Self::ostr(args, pos)? {
None => Ok(None),
Some(u) => DurationUnit::parse(&u)
.map(Some)
.ok_or_else(|| "Invalid duration unit".to_string()),
}
}
fn duration(args: &[Arg], from: usize) -> Result<Duration, Fail> {
match Self::var(args, from)? {
Arg::Str(s) => Duration::parse(s).map_err(|e| e.to_string()),
Arg::Num(n) => {
let unit = Self::unit(args, from + 1)?;
Duration::from_unit(n, unit).ok_or_else(|| "Invalid duration unit".to_string())
}
_ => Err("Invalid duration arguments".to_string()),
}
}
fn other(args: &[Arg]) -> Result<Date, Fail> {
Ok(match Self::var(args, 1)? {
Arg::Date(d) => d,
Arg::Str(s) => Date::text(s, None),
other => Date::new(other.variable(), None),
})
}
fn date(d: Date) -> Out {
Out::Date(d)
}
fn run(f: impl FnOnce() -> Result<Out, Fail>) -> Outcome {
Some(f())
}
pub(crate) const ADD: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| Ok(Self::date(Self::this(args)?.add(Self::duration(args, 1)?))))
}],
fail: Self::NEVER,
};
pub(crate) const SUB: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| Ok(Self::date(Self::this(args)?.sub(Self::duration(args, 1)?))))
}],
fail: Self::NEVER,
};
pub(crate) const SET: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| {
let this = Self::this(args)?;
let unit = Self::unit(args, 1)?;
let value = Self::number(args, 2)?
.to_u32()
.ok_or_else(|| "Invalid duration value".to_string())?;
Ok(Self::date(this.set(value, unit)))
})
}],
fail: Self::NEVER,
};
pub(crate) const FORMAT: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| {
let this = Self::this(args)?;
Ok(this.format(Self::ostr(args, 1)?.as_deref()).into())
})
}],
fail: Self::NEVER,
};
pub(crate) const START_OF: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| Ok(Self::date(Self::this(args)?.start_of(Self::unit(args, 1)?))))
}],
fail: Self::NEVER,
};
pub(crate) const END_OF: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| Ok(Self::date(Self::this(args)?.end_of(Self::unit(args, 1)?))))
}],
fail: Self::NEVER,
};
pub(crate) const DIFF: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| {
let this = Self::this(args)?;
let other = Self::other(args)?;
let unit = Self::unit_opt(args, 2)?;
Ok(match this.diff(&other, unit).and_then(Decimal::from_i64) {
Some(n) => Out::Num(n),
None => Out::Var(Variable::Null),
})
})
}],
fail: Self::NEVER,
};
pub(crate) const TZ: Builtin = Builtin {
overloads: &[|args| {
Self::run(|| {
let this = Self::this(args)?;
let zone = Tz::from_str(&Self::str(args, 1)?)
.map_err(|_| "Invalid timezone".to_string())?;
Ok(Self::date(this.tz(zone)))
})
}],
fail: Self::NEVER,
};
fn compare(args: &[Arg], op: Compare) -> Outcome {
Self::run(|| {
let this = Self::this(args)?;
let other = Self::other(args)?;
let unit = Self::unit_opt(args, 2)?;
Ok(Out::Bool(match op {
Compare::Same => this.is_same(&other, unit),
Compare::Before => this.is_before(&other, unit),
Compare::After => this.is_after(&other, unit),
Compare::SameOrBefore => this.is_same_or_before(&other, unit),
Compare::SameOrAfter => this.is_same_or_after(&other, unit),
}))
})
}
pub(crate) const IS_SAME: Builtin = Builtin {
overloads: &[|args| Self::compare(args, Compare::Same)],
fail: Self::NEVER,
};
pub(crate) const IS_BEFORE: Builtin = Builtin {
overloads: &[|args| Self::compare(args, Compare::Before)],
fail: Self::NEVER,
};
pub(crate) const IS_AFTER: Builtin = Builtin {
overloads: &[|args| Self::compare(args, Compare::After)],
fail: Self::NEVER,
};
pub(crate) const IS_SAME_OR_BEFORE: Builtin = Builtin {
overloads: &[|args| Self::compare(args, Compare::SameOrBefore)],
fail: Self::NEVER,
};
pub(crate) const IS_SAME_OR_AFTER: Builtin = Builtin {
overloads: &[|args| Self::compare(args, Compare::SameOrAfter)],
fail: Self::NEVER,
};
pub(crate) fn shift(method: &MethodKind, args: &[Arg]) -> Option<Shift> {
let MethodKind::DateMethod(method) = method;
match method {
DateMethod::Add => Self::duration(args, 1).ok().map(Shift::Add),
DateMethod::Sub => Self::duration(args, 1).ok().map(Shift::Sub),
DateMethod::StartOf if args.len() == 2 => Self::unit(args, 1).ok().map(Shift::Start),
DateMethod::EndOf if args.len() == 2 => Self::unit(args, 1).ok().map(Shift::End),
_ => None,
}
}
pub(crate) fn part_of(method: &MethodKind, date: &Date) -> Option<i64> {
let MethodKind::DateMethod(method) = method;
let dt = date.0?;
Some(match method {
DateMethod::Second => dt.second() as i64,
DateMethod::Minute => dt.minute() as i64,
DateMethod::Hour => dt.hour() as i64,
DateMethod::Day => dt.day() as i64,
DateMethod::Weekday => dt.weekday().number_from_monday() as i64,
DateMethod::DayOfYear => dt.ordinal() as i64,
DateMethod::Week => dt.iso_week().week() as i64,
DateMethod::Month => dt.month() as i64,
DateMethod::Quarter => dt.quarter() as i64,
DateMethod::Year => dt.year() as i64,
DateMethod::Timestamp => dt.timestamp_millis(),
_ => return None,
})
}
pub(crate) fn order(method: &MethodKind, this: &Date, other: &Date) -> Option<bool> {
let MethodKind::DateMethod(method) = method;
Some(match method {
DateMethod::IsSame => this.is_same(other, None),
DateMethod::IsBefore => this.is_before(other, None),
DateMethod::IsAfter => this.is_after(other, None),
DateMethod::IsSameOrBefore => this.is_same_or_before(other, None),
DateMethod::IsSameOrAfter => this.is_same_or_after(other, None),
_ => return None,
})
}
fn part(args: &[Arg], part: Part) -> Outcome {
Self::run(|| {
let this = Self::this(args)?;
if let Part::IsValid = part {
return Ok(Out::Bool(this.is_valid()));
}
let Some(dt) = this.0 else {
return Ok(Out::Var(Variable::Null));
};
Ok(match part {
Part::Second => Out::Num(dt.second().into()),
Part::Minute => Out::Num(dt.minute().into()),
Part::Hour => Out::Num(dt.hour().into()),
Part::Day => Out::Num(dt.day().into()),
Part::Weekday => Out::Num(dt.weekday().number_from_monday().into()),
Part::DayOfYear => Out::Num(dt.ordinal().into()),
Part::Week => Out::Num(dt.iso_week().week().into()),
Part::Month => Out::Num(dt.month().into()),
Part::Quarter => Out::Num(dt.quarter().into()),
Part::Year => Out::Num(dt.year().into()),
Part::Timestamp => Out::Num(dt.timestamp_millis().into()),
Part::IsValid => Out::Bool(true),
Part::IsYesterday => {
Out::Bool(this.is_same(&Date::yesterday(), Some(DurationUnit::Day)))
}
Part::IsToday => Out::Bool(this.is_same(&Date::now(), Some(DurationUnit::Day))),
Part::IsTomorrow => {
Out::Bool(this.is_same(&Date::tomorrow(), Some(DurationUnit::Day)))
}
Part::IsLeapYear => Out::Bool(dt.date_naive().leap_year()),
Part::OffsetName => dt.timezone().name().into(),
})
})
}
pub(crate) const SECOND: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Second)],
fail: Self::NEVER,
};
pub(crate) const MINUTE: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Minute)],
fail: Self::NEVER,
};
pub(crate) const HOUR: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Hour)],
fail: Self::NEVER,
};
pub(crate) const DAY: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Day)],
fail: Self::NEVER,
};
pub(crate) const WEEKDAY: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Weekday)],
fail: Self::NEVER,
};
pub(crate) const DAY_OF_YEAR: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::DayOfYear)],
fail: Self::NEVER,
};
pub(crate) const WEEK: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Week)],
fail: Self::NEVER,
};
pub(crate) const MONTH: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Month)],
fail: Self::NEVER,
};
pub(crate) const QUARTER: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Quarter)],
fail: Self::NEVER,
};
pub(crate) const YEAR: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Year)],
fail: Self::NEVER,
};
pub(crate) const TIMESTAMP: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::Timestamp)],
fail: Self::NEVER,
};
pub(crate) const OFFSET_NAME: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::OffsetName)],
fail: Self::NEVER,
};
pub(crate) const IS_VALID: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::IsValid)],
fail: Self::NEVER,
};
pub(crate) const IS_YESTERDAY: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::IsYesterday)],
fail: Self::NEVER,
};
pub(crate) const IS_TODAY: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::IsToday)],
fail: Self::NEVER,
};
pub(crate) const IS_TOMORROW: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::IsTomorrow)],
fail: Self::NEVER,
};
pub(crate) const IS_LEAP_YEAR: Builtin = Builtin {
overloads: &[|a| Self::part(a, Part::IsLeapYear)],
fail: Self::NEVER,
};
}
@@ -0,0 +1,202 @@
use crate::functions::{
DateMethod as M, DeprecatedFunction as D, FunctionKind, InternalFunction as F, MethodKind,
};
use crate::lane::builtins::arrays::Arrays;
use crate::lane::builtins::convert::Convert;
use crate::lane::builtins::dates::Dates;
use crate::lane::builtins::legacy::Legacy;
use crate::lane::builtins::math::Math;
use crate::lane::builtins::text::Text;
use crate::lane::builtins::{Arg, Builtin, Fail, Out};
use crate::lane::exec::{CallFault, Fault};
use crate::lane::ops::Ops;
use crate::vm::VMError;
use smallvec::SmallVec;
use std::borrow::Cow;
pub(crate) struct Builtins;
impl Builtins {
pub(crate) fn of(kind: &FunctionKind) -> Option<&'static Builtin> {
let function = match kind {
FunctionKind::Internal(function) => function,
FunctionKind::Deprecated(function) => {
return Some(match function {
D::Date => &Legacy::DATE,
D::Time => &Legacy::TIME,
D::Duration => &Legacy::DURATION,
D::Year => &Legacy::YEAR,
D::DayOfWeek => &Legacy::DAY_OF_WEEK,
D::DayOfMonth => &Legacy::DAY_OF_MONTH,
D::DayOfYear => &Legacy::DAY_OF_YEAR,
D::WeekOfYear => &Legacy::WEEK_OF_YEAR,
D::MonthOfYear => &Legacy::MONTH_OF_YEAR,
D::MonthString => &Legacy::MONTH_STRING,
D::DateString => &Legacy::DATE_STRING,
D::WeekdayString => &Legacy::WEEKDAY_STRING,
D::StartOf => &Legacy::START_OF,
D::EndOf => &Legacy::END_OF,
})
}
FunctionKind::Closure(_) => return None,
};
Some(match function {
F::Len => &Text::LEN,
F::Contains => &Text::CONTAINS,
F::Upper => &Text::UPPER,
F::Lower => &Text::LOWER,
F::Trim => &Text::TRIM,
F::StartsWith => &Text::STARTS_WITH,
F::EndsWith => &Text::ENDS_WITH,
F::Matches => &Text::MATCHES,
F::Extract => &Text::EXTRACT,
F::FuzzyMatch => &Text::FUZZY_MATCH,
F::Split => &Text::SPLIT,
F::Abs => &Math::ABS,
F::Sum => &Math::SUM,
F::Avg => &Math::AVG,
F::Min => &Math::MIN,
F::Max => &Math::MAX,
F::Rand => &Math::RAND,
F::Median => &Math::MEDIAN,
F::Mode => &Math::MODE,
F::Floor => &Math::FLOOR,
F::Ceil => &Math::CEIL,
F::Round => &Math::ROUND,
F::Trunc => &Math::TRUNC,
F::Flatten => &Arrays::FLATTEN,
F::Merge => &Arrays::MERGE,
F::MergeDeep => &Arrays::MERGE_DEEP,
F::Keys => &Arrays::KEYS,
F::Values => &Arrays::VALUES,
F::IsNumeric => &Convert::IS_NUMERIC,
F::String => &Convert::STRING,
F::Number => &Convert::NUMBER,
F::Bool => &Convert::BOOL,
F::Type => &Convert::TYPE,
F::Date => &Convert::DATE,
})
}
pub(crate) fn method(kind: &MethodKind) -> &'static Builtin {
let MethodKind::DateMethod(method) = kind;
match method {
M::Add => &Dates::ADD,
M::Sub => &Dates::SUB,
M::Set => &Dates::SET,
M::Format => &Dates::FORMAT,
M::StartOf => &Dates::START_OF,
M::EndOf => &Dates::END_OF,
M::Diff => &Dates::DIFF,
M::Tz => &Dates::TZ,
M::IsSame => &Dates::IS_SAME,
M::IsBefore => &Dates::IS_BEFORE,
M::IsAfter => &Dates::IS_AFTER,
M::IsSameOrBefore => &Dates::IS_SAME_OR_BEFORE,
M::IsSameOrAfter => &Dates::IS_SAME_OR_AFTER,
M::Second => &Dates::SECOND,
M::Minute => &Dates::MINUTE,
M::Hour => &Dates::HOUR,
M::Day => &Dates::DAY,
M::DayOfYear => &Dates::DAY_OF_YEAR,
M::Week => &Dates::WEEK,
M::Weekday => &Dates::WEEKDAY,
M::Month => &Dates::MONTH,
M::Quarter => &Dates::QUARTER,
M::Year => &Dates::YEAR,
M::Timestamp => &Dates::TIMESTAMP,
M::OffsetName => &Dates::OFFSET_NAME,
M::IsValid => &Dates::IS_VALID,
M::IsYesterday => &Dates::IS_YESTERDAY,
M::IsToday => &Dates::IS_TODAY,
M::IsTomorrow => &Dates::IS_TOMORROW,
M::IsLeapYear => &Dates::IS_LEAP_YEAR,
}
}
fn attempt(builtin: &Builtin, args: &[Arg]) -> Option<Result<Out, Fail>> {
builtin.overloads.iter().find_map(|overload| overload(args))
}
#[cold]
#[inline(never)]
fn textual(builtin: &Builtin, args: &[Arg]) -> Option<Result<Out, Fail>> {
let texts: SmallVec<[Option<Cow<str>>; 4]> = args
.iter()
.map(|a| a.date().and_then(|_| a.text()))
.collect();
if texts.iter().all(Option::is_none) {
return None;
}
[1, 0].into_iter().find_map(|from| {
let converted: SmallVec<[Arg; 4]> = args
.iter()
.zip(&texts)
.enumerate()
.map(|(i, (a, text))| match text {
Some(text) if i >= from => Arg::Str(text),
_ => *a,
})
.collect();
Self::attempt(builtin, &converted)
})
}
#[inline]
fn resolve(builtin: &Builtin, args: &[Arg]) -> Result<Out, Fail> {
Self::attempt(builtin, args)
.or_else(|| Self::textual(builtin, args))
.unwrap_or_else(|| Err((builtin.fail)(args)))
}
pub(crate) fn call_method(
builtin: &Builtin,
kind: &MethodKind,
args: &[Arg],
) -> Result<Out, VMError> {
Self::resolve(builtin, args)
.map_err(|message| Ops::error("CallMethod", format!("Method `{kind}` failed: {message}")))
}
#[inline]
pub(crate) fn call_hinted(
builtin: &'static Builtin,
kind: &FunctionKind,
args: &[Arg],
hint: &mut usize,
) -> Result<Out, Fault> {
let failed = |message: Fail| CallFault::message(kind, message);
if let Some(overload) = builtin.overloads.get(*hint) {
if let Some(result) = overload(args) {
return result.map_err(failed);
}
}
for (index, overload) in builtin.overloads.iter().enumerate() {
if let Some(result) = overload(args) {
*hint = index;
return result.map_err(failed);
}
}
match Self::textual(builtin, args) {
Some(result) => result.map_err(failed),
None => Err(CallFault::fail(kind, builtin, args)),
}
}
pub(crate) fn raw(builtin: &Builtin, args: &[Arg]) -> Result<Out, Fail> {
Self::resolve(builtin, args)
}
pub(crate) fn call(
builtin: &Builtin,
kind: &FunctionKind,
args: &[Arg],
) -> Result<Out, VMError> {
Self::resolve(builtin, args).map_err(|message| {
Ops::error(
"CallFunction",
format!("Function `{kind}` failed: {message}"),
)
})
}
}
+189
View File
@@ -0,0 +1,189 @@
use crate::lane::builtins::{Apply, Arg, Builtin, Fail, Params};
use crate::lane::date::helpers::{date_time, date_time_end_of, date_time_start_of, time, DateUnit};
use crate::variable::Variable;
use chrono::{Datelike, NaiveDateTime, Timelike};
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
pub(crate) struct Legacy;
impl Legacy {
const ANY: fn(&[Arg]) -> Fail = |_| "Argument on 0 position out of bounds".to_string();
fn convert(timestamp: Arg) -> Result<NaiveDateTime, Fail> {
let instant = timestamp
.date()
.and_then(|date| date.0)
.map(|date| date.naive_local());
let converted = match timestamp {
Arg::Str(s) => date_time(s).ok(),
Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => match timestamp.text() {
Some(text) => date_time(&text).ok().or(instant),
None => instant,
},
#[allow(deprecated)]
Arg::Num(n) => n
.to_i64()
.and_then(|n| NaiveDateTime::from_timestamp_opt(n, 0)),
_ => None,
};
converted.ok_or_else(|| "Failed to convert value to date time".to_string())
}
pub(crate) const DATE: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| match a {
Arg::Str(s) => {
let dt = date_time(s).map_err(|e| e.to_string())?;
#[allow(deprecated)]
Ok(Decimal::from(dt.timestamp()))
}
Arg::Num(n) => n
.to_i64()
.map(Decimal::from)
.ok_or_else(|| "Number overflow".to_string()),
other => Self::convert(other)
.map_err(|_| "Unsupported type for date function".to_string())
.map(|dt| {
#[allow(deprecated)]
Decimal::from(dt.timestamp())
}),
})
}],
fail: Self::ANY,
};
pub(crate) const TIME: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| match a {
Arg::Str(s) => Ok(Decimal::from(
time(s)
.map_err(|e| e.to_string())?
.num_seconds_from_midnight(),
)),
Arg::Num(n) => n
.to_u32()
.map(Decimal::from)
.ok_or_else(|| "Number overflow".to_string()),
Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => {
match a.text().map(|text| time(&text)) {
Some(Ok(time)) => Ok(Decimal::from(time.num_seconds_from_midnight())),
_ => Self::convert(a).map(|dt| Decimal::from(dt.time().num_seconds_from_midnight())),
}
}
_ => Err("Unsupported type for time function".to_string()),
})
}],
fail: Self::ANY,
};
pub(crate) const DURATION: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Arg| match a {
Arg::Str(s) => Ok(Decimal::from(
humantime::parse_duration(s)
.map_err(|e| e.to_string())?
.as_secs(),
)),
Arg::Num(n) => n
.to_u64()
.map(Decimal::from)
.ok_or_else(|| "Number overflow".to_string()),
_ => Err("Unsupported type for duration function".to_string()),
})
}],
fail: Self::ANY,
};
pub(crate) const YEAR: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.year()).into()))
}],
fail: Self::ANY,
};
pub(crate) const DAY_OF_WEEK: Builtin = Builtin {
overloads: &[|args| {
Some(
Self::convert(*args.first()?)
.map(|t| Decimal::from(t.weekday().number_from_monday()).into()),
)
}],
fail: Self::ANY,
};
pub(crate) const DAY_OF_MONTH: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.day()).into()))
}],
fail: Self::ANY,
};
pub(crate) const DAY_OF_YEAR: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.ordinal()).into()))
}],
fail: Self::ANY,
};
pub(crate) const WEEK_OF_YEAR: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.iso_week().week()).into()))
}],
fail: Self::ANY,
};
pub(crate) const MONTH_OF_YEAR: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| Decimal::from(t.month()).into()))
}],
fail: Self::ANY,
};
pub(crate) const MONTH_STRING: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| t.format("%b").to_string().into()))
}],
fail: Self::ANY,
};
pub(crate) const WEEKDAY_STRING: Builtin = Builtin {
overloads: &[|args| {
Some(Self::convert(*args.first()?).map(|t| t.weekday().to_string().into()))
}],
fail: Self::ANY,
};
pub(crate) const DATE_STRING: Builtin = Builtin {
overloads: &[|args| Some(Self::convert(*args.first()?).map(|t| t.to_string().into()))],
fail: Self::ANY,
};
pub(crate) const START_OF: Builtin = Builtin {
overloads: &[|args| {
Apply::two(args, |timestamp: Arg, unit: &str| {
let datetime = Self::convert(timestamp)?;
let unit = DateUnit::try_from(unit).map_err(|_| "Invalid date unit".to_string())?;
let result = date_time_start_of(datetime, unit)
.ok_or_else(|| "Failed to calculate start of period".to_string())?;
#[allow(deprecated)]
Ok(Decimal::from(result.timestamp()))
})
}],
fail: |args| Params::fail(args, &[("value", false), ("string", false)]),
};
pub(crate) const END_OF: Builtin = Builtin {
overloads: &[|args| {
Apply::two(args, |timestamp: Arg, unit: &str| {
let datetime = Self::convert(timestamp)?;
let unit = DateUnit::try_from(unit).map_err(|_| "Invalid date unit".to_string())?;
let result = date_time_end_of(datetime, unit)
.ok_or_else(|| "Failed to calculate end of period".to_string())?;
#[allow(deprecated)]
Ok(Decimal::from(result.timestamp()))
})
}],
fail: |args| Params::fail(args, &[("value", false), ("string", false)]),
};
}
+219
View File
@@ -0,0 +1,219 @@
use crate::lane::builtins::{Apply, Array, Builtin, Fail, Params};
use crate::lane::date::Date;
use crate::lane::date::DynamicVariableExt;
use crate::variable::Variable;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::{Decimal, RoundingStrategy};
use std::collections::BTreeMap;
pub(crate) struct Math;
enum Extreme {
Numbers(Vec<Decimal>),
Dates(Vec<(Date, Variable)>),
}
impl Math {
const NUMBER: &'static [(&'static str, bool)] = &[("number", false)];
const PLACES: &'static [(&'static str, bool)] = &[("number", false), ("number", true)];
const ARRAY: &'static [(&'static str, bool)] = &[("array", false)];
fn places(places: Option<Decimal>) -> Result<u32, Fail> {
match places {
Some(p) => p
.to_u32()
.ok_or_else(|| "Invalid number of decimal places".to_string()),
None => Ok(0),
}
}
fn numbers(a: &Array) -> Result<Vec<Decimal>, Fail> {
a.numbers()
.map(|n| n.into_owned())
.ok_or_else(|| "Expected a number array".to_string())
}
fn total(values: &[Decimal]) -> Result<Decimal, Fail> {
values
.iter()
.try_fold(Decimal::ZERO, |acc, v| acc.checked_add(*v))
.ok_or_else(|| "Number overflow".to_string())
}
pub(crate) const ABS: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.abs()))],
fail: |args| Params::fail(args, Self::NUMBER),
};
pub(crate) const CEIL: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.ceil()))],
fail: |args| Params::fail(args, Self::NUMBER),
};
pub(crate) const FLOOR: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Decimal| Ok(a.floor()))],
fail: |args| Params::fail(args, Self::NUMBER),
};
pub(crate) const ROUND: Builtin = Builtin {
overloads: &[|args| {
Apply::two(args, |a: Decimal, places: Option<Decimal>| {
Ok(a.round_dp_with_strategy(
Self::places(places)?,
RoundingStrategy::MidpointAwayFromZero,
))
})
}],
fail: |args| Params::fail(args, Self::PLACES),
};
pub(crate) const TRUNC: Builtin = Builtin {
overloads: &[|args| {
Apply::two(args, |a: Decimal, places: Option<Decimal>| {
Ok(a.trunc_with_scale(Self::places(places)?))
})
}],
fail: |args| Params::fail(args, Self::PLACES),
};
pub(crate) const RAND: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Decimal| {
let upper = a
.round()
.to_i64()
.ok_or_else(|| "Invalid upper range".to_string())?;
Ok(Decimal::from(fastrand::i64(0..=upper)))
})
}],
fail: |args| Params::fail(args, Self::NUMBER),
};
pub(crate) const SUM: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
let numbers = a
.numbers()
.ok_or_else(|| "Expected a number array".to_string())?;
Self::total(&numbers)
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
pub(crate) const AVG: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
let numbers = a
.numbers()
.ok_or_else(|| "Expected a number array".to_string())?;
let sum = Self::total(&numbers)?;
sum.checked_div(Decimal::from(numbers.len()))
.ok_or_else(|| "Empty array".to_string())
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
pub(crate) const MEDIAN: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
let mut values = Self::numbers(&a)?;
values.sort();
let center = values.len() / 2;
match values.len() % 2 {
1 => values
.get(center)
.copied()
.ok_or_else(|| "Index out of bounds".to_string()),
_ => {
let left = center
.checked_sub(1)
.and_then(|i| values.get(i))
.ok_or_else(|| "Index out of bounds".to_string())?;
let right = values
.get(center)
.ok_or_else(|| "Index out of bounds".to_string())?;
let total = left
.checked_add(*right)
.ok_or_else(|| "Number overflow".to_string())?;
Ok(total / Decimal::TWO)
}
}
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
pub(crate) const MODE: Builtin = Builtin {
overloads: &[|args| {
Apply::one(args, |a: Array| {
let mut counts = BTreeMap::new();
for n in Self::numbers(&a)? {
*counts.entry(n).or_insert(0usize) += 1;
}
counts
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(n, _)| n)
.ok_or_else(|| "Empty array".to_string())
})
}],
fail: |args| Params::fail(args, Self::ARRAY),
};
fn extreme(a: &Array) -> Result<Extreme, Fail> {
a.with(|values| {
let numeric = values.first().and_then(Variable::as_number).is_some();
match numeric {
true => values
.iter()
.map(Variable::as_number)
.collect::<Option<Vec<_>>>()
.map(Extreme::Numbers)
.ok_or_else(|| "Expected a number array".to_string()),
false => values
.iter()
.map(|v| match v {
Variable::Dynamic(d) => d.as_date().map(|date| (date, v.clone())),
_ => None,
})
.collect::<Option<Vec<_>>>()
.map(Extreme::Dates)
.ok_or_else(|| "Expected a number array".to_string()),
}
})
}
fn pick(a: Array, largest: bool) -> Result<Variable, Fail> {
let empty = || "Empty array".to_string();
match (Self::extreme(&a)?, largest) {
(Extreme::Numbers(n), true) => {
n.into_iter().max().map(Variable::Number).ok_or_else(empty)
}
(Extreme::Numbers(n), false) => {
n.into_iter().min().map(Variable::Number).ok_or_else(empty)
}
(Extreme::Dates(d), true) => d
.into_iter()
.max_by(|a, b| a.0.cmp(&b.0))
.map(|(_, original)| original)
.ok_or_else(empty),
(Extreme::Dates(d), false) => d
.into_iter()
.min_by(|a, b| a.0.cmp(&b.0))
.map(|(_, original)| original)
.ok_or_else(empty),
}
}
pub(crate) const MIN: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Array| Self::pick(a, false))],
fail: |args| Params::fail(args, Self::ARRAY),
};
pub(crate) const MAX: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: Array| Self::pick(a, true))],
fail: |args| Params::fail(args, Self::ARRAY),
};
}
+362
View File
@@ -0,0 +1,362 @@
mod arrays;
mod convert;
pub(crate) mod dates;
mod functions;
mod legacy;
mod math;
mod text;
pub(crate) use dates::Dates;
pub(crate) use functions::Builtins;
pub(crate) use text::{Text, TextKernel};
use crate::lane::columns::{Column, Values};
use crate::lane::date::Date;
use crate::lane::date::DynamicVariableExt;
use crate::variable::Variable;
use rust_decimal::Decimal;
use std::borrow::Cow;
use zen_types::rccell::RcCell;
#[derive(Debug, Clone, Copy)]
pub(crate) struct ListView<'a> {
pub child: &'a Column<'a>,
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Arg<'a> {
Null,
Num(Decimal),
Bool(bool),
Str(&'a str),
Date(Date),
Var(&'a Variable),
List(ListView<'a>),
}
impl<'a> Arg<'a> {
pub(crate) fn of(v: &'a Variable) -> Self {
match v {
Variable::Null => Arg::Null,
Variable::Number(n) => Arg::Num(*n),
Variable::Bool(b) => Arg::Bool(*b),
Variable::String(s) => Arg::Str(s.as_str()),
Variable::Dynamic(d) => match d.as_date() {
Some(date) if !Date::sourced(v) => Arg::Date(date),
_ => Arg::Var(v),
},
v => Arg::Var(v),
}
}
pub(crate) fn date(&self) -> Option<Date> {
match self {
Arg::Date(d) => Some(*d),
Arg::Var(Variable::Dynamic(d)) => d.as_date(),
_ => None,
}
}
pub(crate) fn text(&self) -> Option<Cow<'a, str>> {
match self {
Arg::Str(s) => Some(Cow::Borrowed(s)),
Arg::Date(d) => d.rendered().map(Cow::Owned),
Arg::Var(v @ Variable::Dynamic(_)) => v.as_str().map(Cow::Borrowed),
_ => None,
}
}
pub(crate) fn coerce_date(&self) -> Option<Date> {
match self {
Arg::Str(s) => Some(Date::from_text(s)),
other => other.date(),
}
}
pub(crate) fn type_name(&self) -> &'static str {
match self {
Arg::Null => "null",
Arg::Num(_) => "number",
Arg::Bool(_) => "bool",
Arg::Str(_) => "string",
Arg::Date(_) => "date",
Arg::Var(v) => v.type_name(),
Arg::List(_) => "array",
}
}
pub(crate) fn variable(&self) -> Variable {
match self {
Arg::Null => Variable::Null,
Arg::Num(n) => Variable::Number(*n),
Arg::Bool(b) => Variable::Bool(*b),
Arg::Str(s) => Variable::String((*s).into()),
Arg::Date(d) => d.variable(),
Arg::Var(v) => (*v).clone(),
Arg::List(l) => {
Variable::from_array((l.start..l.end).map(|i| l.child.variable(i)).collect())
}
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Array<'a> {
Var(&'a RcCell<Vec<Variable>>),
List(ListView<'a>),
}
impl<'a> Array<'a> {
pub(crate) fn len(&self) -> usize {
match self {
Array::Var(a) => a.borrow().len(),
Array::List(l) => l.end - l.start,
}
}
pub(crate) fn numbers(&self) -> Option<Cow<'a, [Decimal]>> {
match self {
Array::List(l) => match l.child.values {
Values::Dec(values) if (l.start..l.end).all(|i| l.child.valid(i)) => {
values.get(l.start..l.end).map(Cow::Borrowed)
}
_ => (l.start..l.end)
.map(|i| l.child.valid(i).then(|| l.child.number(i)).flatten())
.collect::<Option<Vec<_>>>()
.map(Cow::Owned),
},
Array::Var(a) => a
.borrow()
.iter()
.map(Variable::as_number)
.collect::<Option<Vec<_>>>()
.map(Cow::Owned),
}
}
pub(crate) fn variables(&self) -> Vec<Variable> {
match self {
Array::Var(a) => a.borrow().clone(),
Array::List(l) => (l.start..l.end).map(|i| l.child.variable(i)).collect(),
}
}
pub(crate) fn with<T>(&self, f: impl FnOnce(&[Variable]) -> T) -> T {
match self {
Array::Var(a) => f(&a.borrow()),
Array::List(_) => f(&self.variables()),
}
}
pub(crate) fn any(&self, mut f: impl FnMut(Arg) -> bool) -> bool {
match self {
Array::Var(a) => a.borrow().iter().any(|v| f(Arg::of(v))),
Array::List(l) => (l.start..l.end).any(|i| {
let v = l.child.variable(i);
f(Arg::of(&v))
}),
}
}
}
pub(crate) trait FromArg<'a>: Sized {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self>;
}
impl<'a> FromArg<'a> for &'a str {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
match a? {
Arg::Str(s) => Some(s),
_ => None,
}
}
}
impl<'a> FromArg<'a> for Decimal {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
match a? {
Arg::Num(n) => Some(n),
_ => None,
}
}
}
impl<'a> FromArg<'a> for bool {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
match a? {
Arg::Bool(b) => Some(b),
_ => None,
}
}
}
impl<'a> FromArg<'a> for Array<'a> {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
match a? {
Arg::Var(Variable::Array(a)) => Some(Array::Var(a)),
Arg::List(l) => Some(Array::List(l)),
_ => None,
}
}
}
impl<'a> FromArg<'a> for Arg<'a> {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
a
}
}
impl<'a, T: FromArg<'a>> FromArg<'a> for Option<T> {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
match a {
None => Some(None),
Some(a) => T::from_arg(Some(a)).map(Some),
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum Out {
Num(Decimal),
Bool(bool),
Str(zen_types::symbol::Symbol),
Date(Date),
Var(Variable),
}
impl Out {
pub(crate) fn variable(self) -> Variable {
match self {
Out::Num(n) => Variable::Number(n),
Out::Bool(b) => Variable::Bool(b),
Out::Str(s) => Variable::String(s),
Out::Date(d) => d.variable(),
Out::Var(v) => v,
}
}
}
impl From<Decimal> for Out {
fn from(n: Decimal) -> Self {
Out::Num(n)
}
}
impl From<usize> for Out {
fn from(n: usize) -> Self {
Out::Num(n.into())
}
}
impl From<bool> for Out {
fn from(b: bool) -> Self {
Out::Bool(b)
}
}
impl From<String> for Out {
fn from(s: String) -> Self {
Out::Str(zen_types::symbol::Symbol::from(s.as_str()))
}
}
impl From<&str> for Out {
fn from(s: &str) -> Self {
Out::Str(zen_types::symbol::Symbol::from(s))
}
}
impl From<Date> for Out {
fn from(d: Date) -> Self {
Out::Date(d)
}
}
impl From<Variable> for Out {
fn from(v: Variable) -> Self {
Out::Var(v)
}
}
pub(crate) type Fail = String;
pub(crate) type Outcome = Option<Result<Out, Fail>>;
pub(crate) type Overload = for<'a> fn(&[Arg<'a>]) -> Outcome;
pub(crate) struct Apply;
impl Apply {
#[inline(always)]
pub(crate) fn one<'a, A, R>(args: &[Arg<'a>], f: impl FnOnce(A) -> Result<R, Fail>) -> Outcome
where
A: FromArg<'a>,
R: Into<Out>,
{
let a = A::from_arg(args.first().copied())?;
Some(f(a).map(Into::into))
}
#[inline(always)]
pub(crate) fn two<'a, A, B, R>(
args: &[Arg<'a>],
f: impl FnOnce(A, B) -> Result<R, Fail>,
) -> Outcome
where
A: FromArg<'a>,
B: FromArg<'a>,
R: Into<Out>,
{
let a = A::from_arg(args.first().copied())?;
let b = B::from_arg(args.get(1).copied())?;
Some(f(a, b).map(Into::into))
}
}
pub(crate) struct Params;
impl Params {
pub(crate) fn fail(args: &[Arg], wants: &[(&str, bool)]) -> Fail {
for (pos, (want, optional)) in wants.iter().enumerate() {
let matches = |a: &Arg| match *want {
"string" => a.text().is_some(),
"number" => matches!(a, Arg::Num(_)),
"bool" => matches!(a, Arg::Bool(_)),
"array" => matches!(a, Arg::Var(Variable::Array(_)) | Arg::List(_)),
"object" => matches!(a, Arg::Var(Variable::Object(_))),
_ => true,
};
match (args.get(pos), optional) {
(None, true) => {}
(None, false) => {
return format!("Argument on {pos} position is not a valid {want}")
}
(Some(a), _) if !matches(a) => return format!("Argument on {pos} is not a {want}"),
(Some(_), _) => {}
}
}
"No overload matches provided arguments".to_string()
}
}
pub(crate) struct Builtin {
pub(crate) overloads: &'static [Overload],
pub(crate) fail: fn(&[Arg]) -> Fail,
}
impl<'a> FromArg<'a> for &'a Variable {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
match a? {
Arg::Var(v) => Some(v),
_ => None,
}
}
}
impl<'a> FromArg<'a> for Date {
fn from_arg(a: Option<Arg<'a>>) -> Option<Self> {
a?.date()
}
}
+328
View File
@@ -0,0 +1,328 @@
use crate::functions::{FunctionKind, InternalFunction};
use crate::lane::builtins::{Apply, Arg, Array, Builtin, Fail, Out, Outcome, Params};
use crate::variable::Variable;
#[cfg(not(feature = "regex-lite"))]
use regex::Regex;
#[cfg(feature = "regex-lite")]
use regex_lite::Regex;
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;
pub(crate) struct Text;
#[derive(Clone, Copy)]
pub(crate) enum TextKernel {
Test(TextTest),
Map(TextMap),
Size,
}
#[derive(Clone, Copy)]
pub(crate) enum TextTest {
Contains,
Starts,
Ends,
}
impl TextTest {
#[inline(always)]
pub(crate) fn apply(self, a: &str, b: &str) -> bool {
match self {
TextTest::Contains => match (b.as_bytes(), a.len() <= 64) {
([byte], true) => a.as_bytes().iter().any(|c| c == byte),
_ => a.contains(b),
},
TextTest::Starts => a.starts_with(b),
TextTest::Ends => a.ends_with(b),
}
}
}
#[derive(Clone, Copy)]
pub(crate) enum TextMap {
Lower,
Upper,
Trim,
}
impl TextMap {
#[inline]
pub(crate) fn apply(self, a: &str, out: &mut String) -> Option<(usize, usize)> {
match self {
TextMap::Lower => Text::lower(a, out),
TextMap::Upper => Text::upper(a, out),
TextMap::Trim => Text::trim(a, out),
}
}
#[inline]
pub(crate) fn unchanged(self, a: &str) -> bool {
match self {
TextMap::Trim => {
!a.starts_with(char::is_whitespace) && !a.ends_with(char::is_whitespace)
}
TextMap::Lower | TextMap::Upper => false,
}
}
pub(crate) fn bytewise(self) -> Option<fn(&mut str)> {
match self {
TextMap::Lower => Some(str::make_ascii_lowercase),
TextMap::Upper => Some(str::make_ascii_uppercase),
TextMap::Trim => None,
}
}
}
struct Patterns;
impl Patterns {
const CAPACITY: usize = 256;
thread_local! {
static CACHE: std::cell::RefCell<ahash::HashMap<String, Regex>> = Default::default();
}
fn with<T>(pattern: &str, f: impl FnOnce(&Regex) -> T) -> Result<T, Fail> {
Self::CACHE.with_borrow_mut(|cache| {
if let Some(regex) = cache.get(pattern) {
return Ok(f(regex));
}
let regex =
Regex::new(pattern).map_err(|_| "Invalid regular expression".to_string())?;
if cache.len() >= Self::CAPACITY {
cache.clear();
}
let out = f(&regex);
cache.insert(pattern.to_string(), regex);
Ok(out)
})
}
}
impl Text {
pub(crate) fn kernel(kind: &FunctionKind) -> Option<TextKernel> {
let FunctionKind::Internal(function) = kind else {
return None;
};
Some(match function {
InternalFunction::Contains => TextKernel::Test(TextTest::Contains),
InternalFunction::StartsWith => TextKernel::Test(TextTest::Starts),
InternalFunction::EndsWith => TextKernel::Test(TextTest::Ends),
InternalFunction::Lower => TextKernel::Map(TextMap::Lower),
InternalFunction::Upper => TextKernel::Map(TextMap::Upper),
InternalFunction::Trim => TextKernel::Map(TextMap::Trim),
InternalFunction::Len => TextKernel::Size,
_ => return None,
})
}
fn lower(a: &str, out: &mut String) -> Option<(usize, usize)> {
match a.is_ascii() {
true if !a.bytes().any(|b| b.is_ascii_uppercase()) => Some((0, a.len())),
true => {
let start = out.len();
out.push_str(a);
if let Some(tail) = out.get_mut(start..) {
tail.make_ascii_lowercase();
}
None
}
false => {
out.push_str(&a.to_lowercase());
None
}
}
}
fn upper(a: &str, out: &mut String) -> Option<(usize, usize)> {
match a.is_ascii() {
true if !a.bytes().any(|b| b.is_ascii_lowercase()) => Some((0, a.len())),
true => {
let start = out.len();
out.push_str(a);
if let Some(tail) = out.get_mut(start..) {
tail.make_ascii_uppercase();
}
None
}
false => {
out.push_str(&a.to_uppercase());
None
}
}
}
fn trim(a: &str, _: &mut String) -> Option<(usize, usize)> {
let start = a.len() - a.trim_start().len();
Some((start, start + a[start..].trim_end().len()))
}
const TWO: &'static [(&'static str, bool)] = &[("string", false), ("string", false)];
const ONE: &'static [(&'static str, bool)] = &[("string", false)];
pub(crate) const LEN: Builtin = Builtin {
overloads: &[Self::len_str, Self::len_array],
fail: Self::len_fail,
};
fn len_str(args: &[Arg]) -> Outcome {
Apply::one(args, |a: &str| Ok(a.len()))
}
fn len_array(args: &[Arg]) -> Outcome {
Apply::one(args, |a: Array| Ok(a.len()))
}
fn len_fail(args: &[Arg]) -> Fail {
match args.first() {
Some(a) => format!("Cannot determine len of type {}", a.type_name()),
None => "Argument on 0 position out of bounds".to_string(),
}
}
pub(crate) const CONTAINS: Builtin = Builtin {
overloads: &[Self::contains_str, Self::contains_array],
fail: Self::contains_fail,
};
fn contains_str(args: &[Arg]) -> Outcome {
Apply::two(args, |a: &str, b: &str| Ok(a.contains(b)))
}
fn contains_array(args: &[Arg]) -> Outcome {
Apply::two(args, |a: Array, b: Arg| {
Ok(a.any(|x| match (x, b) {
(Arg::Num(x), Arg::Num(y)) => x == y,
(Arg::Str(x), Arg::Str(y)) => x == y,
(Arg::Bool(x), Arg::Bool(y)) => x == y,
(Arg::Null, Arg::Null) => true,
(x, y) => match (x.date(), y.date()) {
(Some(d), _) => d.is_valid() && y.coerce_date() == Some(d),
(None, Some(d)) => d.is_valid() && x.coerce_date() == Some(d),
(None, None) => false,
},
}))
})
}
fn contains_fail(args: &[Arg]) -> Fail {
match (args.first(), args.get(1)) {
(Some(a), Some(b)) => format!(
"Cannot determine contains for type {} and {}",
a.type_name(),
b.type_name()
),
(None, _) => "Argument on 0 position out of bounds".to_string(),
(_, None) => "Argument on 1 position out of bounds".to_string(),
}
}
pub(crate) const STARTS_WITH: Builtin = Builtin {
overloads: &[|args| Apply::two(args, |a: &str, b: &str| Ok(a.starts_with(b)))],
fail: |args| Params::fail(args, Self::TWO),
};
pub(crate) const ENDS_WITH: Builtin = Builtin {
overloads: &[|args| Apply::two(args, |a: &str, b: &str| Ok(a.ends_with(b)))],
fail: |args| Params::fail(args, Self::TWO),
};
pub(crate) const MATCHES: Builtin = Builtin {
overloads: &[|args| {
Apply::two(args, |a: &str, b: &str| {
Patterns::with(b, |regex| regex.is_match(a))
})
}],
fail: |args| Params::fail(args, Self::TWO),
};
pub(crate) const UPPER: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: &str| Ok(a.to_uppercase()))],
fail: |args| Params::fail(args, Self::ONE),
};
pub(crate) const LOWER: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: &str| Ok(a.to_lowercase()))],
fail: |args| Params::fail(args, Self::ONE),
};
pub(crate) const TRIM: Builtin = Builtin {
overloads: &[|args| Apply::one(args, |a: &str| Ok(Out::from(a.trim())))],
fail: |args| Params::fail(args, Self::ONE),
};
pub(crate) const EXTRACT: Builtin = Builtin {
overloads: &[Self::extract],
fail: |args| Params::fail(args, Self::TWO),
};
fn extract(args: &[Arg]) -> Outcome {
Apply::two(args, |a: &str, b: &str| {
let captures: Vec<Variable> = Patterns::with(b, |regex| {
regex
.captures(a)
.map(|capture| {
capture
.iter()
.flatten()
.map(|c| Variable::String(c.as_str().into()))
.collect()
})
.unwrap_or_default()
})?;
Ok(Variable::from_array(captures))
})
}
pub(crate) const SPLIT: Builtin = Builtin {
overloads: &[Self::split],
fail: |args| Params::fail(args, Self::TWO),
};
fn split(args: &[Arg]) -> Outcome {
Apply::two(args, |a: &str, b: &str| {
Ok(Variable::from_array(
a.split(b).map(|s| Variable::String(s.into())).collect(),
))
})
}
pub(crate) const FUZZY_MATCH: Builtin = Builtin {
overloads: &[Self::fuzzy],
fail: |args| Params::fail(args, &[("value", false), ("string", false)]),
};
fn similarity(a: &str, b: &str) -> Decimal {
Decimal::from_f64(strsim::normalized_damerau_levenshtein(a, b)).unwrap_or(Decimal::ZERO)
}
fn fuzzy(args: &[Arg]) -> Outcome {
Apply::two(args, |a: Arg, b: &str| match a {
Arg::Str(a) => Ok(Variable::Number(Self::similarity(a, b))),
Arg::Date(_) | Arg::Var(Variable::Dynamic(_)) => match a.text() {
Some(a) => Ok(Variable::Number(Self::similarity(&a, b))),
None => Err("Fuzzy match not available for type".to_string()),
},
Arg::Var(Variable::Array(_)) | Arg::List(_) => {
let items = match a {
Arg::List(l) => Array::List(l),
Arg::Var(Variable::Array(v)) => Array::Var(v),
_ => return Err("Fuzzy match not available for type".to_string()),
};
items.with(|values| {
values
.iter()
.map(|v| {
v.as_str()
.map(|s| Variable::Number(Self::similarity(s, b)))
.ok_or_else(|| "Expected string array".to_string())
})
.collect::<Result<Vec<_>, _>>()
.map(Variable::from_array)
})
}
_ => Err("Fuzzy match not available for type".to_string()),
})
}
}
+986
View File
@@ -0,0 +1,986 @@
use crate::lane::date::DynamicVariableExt;
use crate::lane::{Binding, Column, Columns, Kind, LaneProgram, LaneRunner, Values};
use crate::lexer::{ComparisonOperator, Lexer, LogicalOperator, Operator};
use crate::parser::{Node, Parser};
use crate::scope::Scope;
use crate::variable::Variable;
use crate::{Isolate, IsolateError};
use ahash::HashMap;
use bumpalo::Bump;
use rust_decimal::Decimal;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Key {
Num(Decimal),
Str(Arc<str>),
Bool(bool),
Null,
}
impl Key {
fn literal(node: &Node) -> Option<Key> {
match node {
Node::Number(n) => Some(Key::Num(n.normalize())),
Node::String(s) => Some(Key::Str(Arc::from(*s))),
Node::Bool(b) => Some(Key::Bool(*b)),
Node::Null => Some(Key::Null),
_ => None,
}
}
}
enum Shape {
Equal(Vec<Key>),
Range(Vec<Decimal>),
Other,
}
impl Shape {
fn classify(node: &Node) -> Shape {
if let Some(keys) = Self::equalities(node) {
return Shape::Equal(keys);
}
match node {
Node::Binary {
left: Node::Identifier("$"),
operator:
Operator::Comparison(
ComparisonOperator::LessThan
| ComparisonOperator::LessThanOrEqual
| ComparisonOperator::GreaterThan
| ComparisonOperator::GreaterThanOrEqual,
),
right: Node::Number(k),
} => Shape::Range(vec![*k]),
Node::Binary {
left: Node::Identifier("$"),
operator: Operator::Comparison(ComparisonOperator::In),
right:
Node::Interval {
left: Node::Number(a),
right: Node::Number(b),
..
},
} => Shape::Range(vec![*a, *b]),
Node::Binary {
left,
operator: Operator::Logical(LogicalOperator::And | LogicalOperator::Or),
right,
} => match (Self::classify(left), Self::classify(right)) {
(Shape::Range(mut a), Shape::Range(b)) => {
a.extend(b);
Shape::Range(a)
}
_ => Shape::Other,
},
Node::Parenthesized(inner) => match Self::classify(inner) {
range @ Shape::Range(_) => range,
_ => Shape::Other,
},
_ => Shape::Other,
}
}
fn equalities(node: &Node) -> Option<Vec<Key>> {
match node {
Node::Binary {
left: Node::Identifier("$"),
operator: Operator::Comparison(ComparisonOperator::Equal),
right,
} => Key::literal(right).map(|k| vec![k]),
Node::Binary {
left,
operator: Operator::Logical(LogicalOperator::Or),
right,
} => {
let mut keys = Self::equalities(left)?;
keys.extend(Self::equalities(right)?);
Some(keys)
}
Node::Parenthesized(inner) => Self::equalities(inner),
_ => None,
}
}
}
struct Other {
program: LaneProgram,
rules: Vec<u64>,
}
type Keyed = (u64, Box<[u8]>, Vec<u64>);
pub struct CellEnv<'a> {
pub scopes: &'a [Scope],
pub columns: &'a Columns<'a>,
pub bind: &'a dyn Fn(&str) -> Binding,
}
struct Scaling {
mult: i64,
bounds: Vec<i64>,
}
pub struct Pieces {
pub bits: Vec<Vec<u64>>,
null: u16,
truth: [u16; 2],
keys: Vec<(u64, usize, Box<[u8]>, u16)>,
text: u16,
regions: Vec<u16>,
other: u16,
pub failed: u16,
}
impl Pieces {
fn intern(bits: &mut Vec<Vec<u64>>, piece: Vec<u64>) -> u16 {
match bits.iter().position(|b| *b == piece) {
Some(at) => at as u16,
None => {
bits.push(piece);
(bits.len() - 1) as u16
}
}
}
#[inline]
fn word(text: &[u8]) -> u64 {
match text.get(..8) {
Some(head) => {
let mut word = [0u8; 8];
word.copy_from_slice(head);
u64::from_le_bytes(word)
}
None => text.iter().enumerate().fold(0u64, |w, (i, b)| w | (*b as u64) << (8 * i)),
}
}
#[inline]
fn text(&self, text: &[u8]) -> u16 {
let (word, len) = (Self::word(text), text.len());
self.keys
.iter()
.find(|(w, l, key, _)| *w == word && *l == len && (len <= 8 || key.as_ref() == text))
.map_or(self.text, |(_, _, _, piece)| *piece)
}
pub fn len(&self) -> usize {
self.bits.len()
}
pub fn is_empty(&self) -> bool {
self.bits.is_empty()
}
}
pub struct CellSet {
rules: usize,
words: usize,
always: Vec<u64>,
strs: HashMap<Box<[u8]>, Vec<u64>>,
few: Option<Vec<Keyed>>,
scaled: Option<(u32, Vec<i128>)>,
bools: [Option<Vec<u64>>; 2],
null: Option<Vec<u64>>,
bounds: Vec<Decimal>,
regions: Vec<Vec<u64>>,
others: Vec<Other>,
owners: Vec<Option<usize>>,
optimistic: Vec<u64>,
}
impl CellSet {
const FEW: usize = 8;
fn prefix(text: &[u8]) -> u64 {
let mut word = [0u8; 8];
let take = text.len().min(7);
word[..take].copy_from_slice(&text[..take]);
word[7] = text.len().min(255) as u8;
u64::from_le_bytes(word)
}
fn text(&self, text: &[u8]) -> Option<&Vec<u64>> {
match &self.few {
Some(few) => {
let prefix = Self::prefix(text);
few.iter()
.find(|(p, k, _)| *p == prefix && k.as_ref() == text)
.map(|(_, _, v)| v)
}
None => self.strs.get(text),
}
}
fn scaled_bounds(bounds: &[Decimal]) -> Option<(u32, Vec<i128>)> {
let scale = bounds.iter().map(Decimal::scale).max().unwrap_or(0);
if scale > 18 {
return None;
}
bounds
.iter()
.map(|b| b.mantissa().checked_mul(10i128.checked_pow(scale - b.scale())?))
.collect::<Option<Vec<_>>>()
.map(|v| (scale, v))
}
fn scaling(&self, scale: u8) -> Option<Scaling> {
let (target, bounds) = self.scaled.as_ref()?;
let (mult, lift) = match (scale as u32).checked_sub(*target) {
None => (10i64.checked_pow(target - scale as u32)?, 1i128),
Some(up) => (1, 10i128.checked_pow(up)?),
};
let bounds = bounds
.iter()
.map(|b| b.checked_mul(lift).and_then(|b| i64::try_from(b).ok()))
.collect::<Option<Vec<_>>>()?;
Some(Scaling { mult, bounds })
}
#[inline]
fn region_of(bounds: &[i64], value: i64) -> usize {
match bounds.len() <= 16 {
true => {
let (mut below, mut equal) = (0usize, false);
for bound in bounds {
below += usize::from(*bound < value);
equal |= *bound == value;
}
below * 2 + usize::from(equal)
}
false => match bounds.binary_search(&value) {
Ok(i) => i * 2 + 1,
Err(i) => i * 2,
},
}
}
fn numbers(&self, column: &Column, rows: usize, out: &mut [u64]) -> bool {
let words = self.words;
let parts = |row: usize| -> Option<(i64, u8)> {
match column.values {
Values::Scaled { mant, scale } => Some((*mant.get(row)?, *scale.get(row)?)),
Values::I64(values) => Some((*values.get(row)?, 0)),
Values::Dec(values) => {
let d = values.get(row)?;
Some((i64::try_from(d.mantissa()).ok()?, u8::try_from(d.scale()).ok()?))
}
_ => None,
}
};
if !matches!(column.values, Values::Scaled { .. } | Values::I64(_) | Values::Dec(_)) || column.len() < rows {
return false;
}
if self.regions.is_empty() {
for (row, bits) in out.chunks_exact_mut(words).enumerate().take(rows) {
bits.copy_from_slice(&self.always);
if !column.valid(row) {
if let Some(matched) = &self.null {
Self::or(bits, matched);
}
}
}
return true;
}
if self.scaled.is_none() {
return false;
}
let mut cached: Vec<Option<Option<Scaling>>> = Vec::new();
for (row, bits) in out.chunks_exact_mut(words).enumerate().take(rows) {
if !column.valid(row) {
bits.copy_from_slice(&self.always);
if let Some(matched) = &self.null {
Self::or(bits, matched);
}
continue;
}
let fast = parts(row).and_then(|(mant, scale)| {
let at = scale as usize;
if cached.len() <= at {
cached.resize_with(at + 1, || None);
}
let scaling = cached[at].get_or_insert_with(|| self.scaling(scale)).as_ref()?;
let value = mant.checked_mul(scaling.mult)?;
Some(Self::region_of(&scaling.bounds, value))
});
match fast.and_then(|region| self.regions.get(region)) {
Some(region) => bits
.iter_mut()
.zip(self.always.iter().zip(region))
.for_each(|(b, (a, r))| *b = a | r),
None => self.row_bits(column, row, (true, false, false), bits),
}
}
true
}
fn set(bits: &mut [u64], rule: usize) {
bits[rule / 64] |= 1 << (rule % 64);
}
fn or(into: &mut [u64], from: &[u64]) {
into.iter_mut().zip(from).for_each(|(a, b)| *a |= b);
}
pub fn compile(cells: &[Option<&str>]) -> Result<Self, IsolateError> {
let rules = cells.len();
let words = rules.div_ceil(64).max(1);
let mut always = vec![0u64; words];
let mut equal: HashMap<Key, Vec<u64>> = HashMap::default();
let mut ranges: Vec<(Arc<str>, Vec<usize>)> = Vec::new();
let mut others: Vec<(Arc<str>, Vec<usize>)> = Vec::new();
let mut bounds: Vec<Decimal> = Vec::new();
for (rule, cell) in cells.iter().enumerate() {
let source = match cell.map(str::trim) {
None | Some("") => {
Self::set(&mut always, rule);
continue;
}
Some(s) => s,
};
let bump = Bump::new();
let mut lexer = Lexer::new();
let shape = match lexer.tokenize(&bump, source).ok().and_then(|tokens| {
Parser::try_new(&tokens, &bump)
.ok()
.map(|p| p.unary().parse())
}) {
Some(parsed) if parsed.error().is_ok() => Shape::classify(parsed.root),
_ => Shape::Other,
};
match shape {
Shape::Equal(keys) => {
for key in keys {
let bits = equal.entry(key).or_insert_with(|| vec![0u64; words]);
Self::set(bits, rule);
}
}
Shape::Range(points) => {
bounds.extend(points);
match ranges.iter_mut().find(|(s, _)| s.as_ref() == source) {
Some((_, r)) => r.push(rule),
None => ranges.push((Arc::from(source), vec![rule])),
}
}
Shape::Other => match others.iter_mut().find(|(s, _)| s.as_ref() == source) {
Some((_, r)) => r.push(rule),
None => others.push((Arc::from(source), vec![rule])),
},
}
}
let mut nums: Vec<(Decimal, Vec<u64>)> = Vec::new();
let mut strs: HashMap<Box<[u8]>, Vec<u64>> = HashMap::default();
let mut bools: [Option<Vec<u64>>; 2] = [None, None];
let mut null: Option<Vec<u64>> = None;
for (key, bits) in equal {
match key {
Key::Num(n) => {
bounds.push(n);
nums.push((n, bits));
}
Key::Str(s) => {
strs.insert(Box::from(s.as_bytes()), bits);
}
Key::Bool(b) => bools[usize::from(b)] = Some(bits),
Key::Null => null = Some(bits),
}
}
bounds.sort();
bounds.dedup_by(|a, b| a == b);
let regions = match bounds.is_empty() {
true => Vec::new(),
false => {
let mut isolate = Isolate::new();
(0..bounds.len() * 2 + 1)
.map(|region| {
let mut bits = vec![0u64; words];
if !ranges.is_empty() {
let probe = Self::probe(&bounds, region);
isolate.set_environment(Variable::empty_object());
let _ = isolate.set_reference_value(Variable::Number(probe));
for (source, rules) in &ranges {
if isolate.run_unary(source).unwrap_or(false) {
rules.iter().for_each(|r| Self::set(&mut bits, *r));
}
}
}
if region % 2 == 1 {
for (n, matched) in &nums {
if *n == bounds[region / 2] {
Self::or(&mut bits, matched);
}
}
}
bits
})
.collect()
}
};
let others: Vec<Other> = others
.into_iter()
.filter_map(|(source, rules)| {
let mut bits = vec![0u64; words];
rules.iter().for_each(|r| Self::set(&mut bits, *r));
LaneProgram::unary(&source).ok().map(|program| Other {
program,
rules: bits,
})
})
.collect();
let mut owners = vec![None; rules];
let mut optimistic = vec![0u64; words];
for (index, other) in others.iter().enumerate() {
Self::or(&mut optimistic, &other.rules);
for (rule, owner) in owners.iter_mut().enumerate() {
if other.rules[rule / 64] >> (rule % 64) & 1 == 1 {
*owner = Some(index);
}
}
}
Ok(Self {
rules,
words,
always,
few: (strs.len() <= Self::FEW)
.then(|| strs.iter().map(|(k, v)| (Self::prefix(k), k.clone(), v.clone())).collect()),
scaled: Self::scaled_bounds(&bounds),
strs,
bools,
null,
bounds,
regions,
others,
owners,
optimistic,
})
}
fn probe(bounds: &[Decimal], region: usize) -> Decimal {
let i = region / 2;
if region % 2 == 1 {
return bounds[i];
}
match (i.checked_sub(1).map(|j| bounds[j]), bounds.get(i)) {
(None, Some(b)) => b.checked_sub(Decimal::ONE).unwrap_or(*b),
(Some(a), None) => a.checked_add(Decimal::ONE).unwrap_or(a),
(Some(a), Some(b)) => b
.checked_sub(a)
.and_then(|gap| a.checked_add(gap / Decimal::TWO))
.filter(|m| a < *m && *m < *b)
.unwrap_or_else(|| a / Decimal::TWO + *b / Decimal::TWO),
(None, None) => Decimal::ZERO,
}
}
pub fn rules(&self) -> usize {
self.rules
}
pub fn words(&self) -> usize {
self.words
}
pub fn evaluate(
&self,
runner: &mut LaneRunner,
values: &[Variable],
envs: &[Scope],
out: &mut Vec<u64>,
) {
let columns = Columns::new(values.len());
let env = CellEnv {
scopes: envs,
columns: &columns,
bind: &|_| Binding::Row,
};
self.evaluate_within(runner, values, &env, None, out)
}
pub fn programs(&self) -> impl Iterator<Item = &LaneProgram> {
self.others.iter().map(|o| &o.program)
}
pub fn scopes(values: &[Variable], env: &CellEnv) -> Vec<Scope> {
values
.iter()
.enumerate()
.map(|(row, value)| Self::scope(value, env.scopes.get(row)))
.collect()
}
fn run(
program: &LaneProgram,
runner: &mut LaneRunner,
scopes: &[Scope],
env: &CellEnv,
rows: &[usize],
mut sink: impl FnMut(usize, bool),
) {
runner.evaluate_bound(program, scopes, env.columns, env.bind, Some(rows), |row, result| {
sink(row, matches!(result.as_deref(), Ok([Variable::Bool(true)])))
});
}
pub fn evaluate_within(
&self,
runner: &mut LaneRunner,
values: &[Variable],
env: &CellEnv,
within: Option<&[u64]>,
out: &mut Vec<u64>,
) {
let words = self.words;
self.indexed(values, out);
if self.others.is_empty() {
return;
}
let scopes = Self::scopes(values, env);
for other in &self.others {
let rows: Vec<usize> = match within {
None => (0..values.len()).collect(),
Some(mask) => (0..values.len())
.filter(|&row| {
mask[row * words..(row + 1) * words]
.iter()
.zip(&other.rules)
.any(|(m, r)| m & r != 0)
})
.collect(),
};
if rows.is_empty() {
continue;
}
Self::run(&other.program, runner, &scopes, env, &rows, |row, pass| {
if pass {
Self::or(&mut out[row * words..(row + 1) * words], &other.rules);
}
});
}
}
pub fn test(
&self,
runner: &mut LaneRunner,
other: usize,
scopes: &[Scope],
env: &CellEnv,
rows: &[usize],
mut sink: impl FnMut(usize, bool),
) {
let Some(other) = self.others.get(other) else {
rows.iter().for_each(|&row| sink(row, false));
return;
};
Self::run(&other.program, runner, scopes, env, rows, sink);
}
fn matched(&self, value: &Variable) -> Option<&Vec<u64>> {
match value {
Variable::String(s) => self.text(s.as_bytes()),
Variable::Bool(b) => self.bools[usize::from(*b)].as_ref(),
Variable::Null => self.null.as_ref(),
_ => None,
}
}
fn dated(&self, value: &Variable, bits: &mut [u64]) {
let Variable::Dynamic(dynamic) = value else {
return;
};
let Some(date) = dynamic.as_date() else {
return;
};
let keys: Box<dyn Iterator<Item = (&[u8], &Vec<u64>)>> = match &self.few {
Some(few) => Box::new(few.iter().map(|(_, k, v)| (k.as_ref(), v))),
None => Box::new(self.strs.iter().map(|(k, v)| (k.as_ref(), v))),
};
for (key, matched) in keys {
let text = Variable::String(String::from_utf8_lossy(key).as_ref().into());
if date.matches(&text) {
Self::or(bits, matched);
}
}
}
fn region(&self, n: &Decimal) -> Option<&Vec<u64>> {
if self.regions.is_empty() {
return None;
}
let region = match self.bounds.binary_search(n) {
Ok(i) => i * 2 + 1,
Err(i) => i * 2,
};
self.regions.get(region)
}
pub fn indexed_column(&self, column: &Column, rows: usize, out: &mut Vec<u64>) {
let words = self.words;
out.clear();
out.resize(rows * words, 0);
let numeric = matches!(column.kind(), Kind::Num);
let text = matches!(column.kind(), Kind::Str);
let boolean = matches!(column.values, Values::Bool { .. });
if column.is_empty() && rows > 0 {
let (first, rest) = out.split_at_mut(words);
self.row_bits(column, 0, (numeric, text, boolean), first);
rest.chunks_exact_mut(words).for_each(|chunk| chunk.copy_from_slice(first));
return;
}
if let Values::Dict { keys, values } = column.values {
let dictionary = values.column();
let size = dictionary.len();
if keys.len() >= rows && size <= rows.saturating_mul(2) + 64 {
let mut table = Vec::new();
self.indexed_column(&dictionary, size, &mut table);
for (row, bits) in out.chunks_exact_mut(words).enumerate() {
let code = usize::try_from(keys[row]).ok().filter(|&c| c < size);
match (column.valid(row), code) {
(true, Some(code)) => bits.copy_from_slice(&table[code * words..(code + 1) * words]),
_ => self.row_bits(column, row, (numeric, text, boolean), bits),
}
}
return;
}
}
if numeric && self.numbers(column, rows, out) {
return;
}
if words == 1 && self.indexed_word(column, rows, out) {
return;
}
for row in 0..rows {
self.row_bits(column, row, (numeric, text, boolean), &mut out[row * words..(row + 1) * words]);
}
}
fn indexed_word(&self, column: &Column, rows: usize, out: &mut [u64]) -> bool {
let always = self.always[0];
let null = self.null.as_ref().map_or(0, |m| m[0]);
let word = |matched: Option<&Vec<u64>>| matched.map_or(0, |m| m[0]);
let texts = |offsets: &[i32], data: &[u8], out: &mut [u64]| {
for (row, bits) in out.iter_mut().enumerate().take(rows) {
*bits = always
| match column.valid(row) {
false => null,
true => {
let (a, b) = (offsets[row] as usize, offsets[row + 1] as usize);
word(data.get(a..b).and_then(|t| self.text(t)))
}
};
}
};
match column.values {
Values::Bool { bits, offset } => {
let on = word(self.bools[1].as_ref());
let off = word(self.bools[0].as_ref());
for (row, out) in out.iter_mut().enumerate().take(rows) {
*out = always
| match column.valid(row) {
false => null,
true => match bits.get((offset + row) / 64).map(|w| w >> ((offset + row) % 64) & 1 == 1) {
Some(true) => on,
Some(false) => off,
None => 0,
},
};
}
}
Values::Text { offsets, data } if offsets.len() > rows => texts(offsets, data.as_bytes(), out),
Values::Utf8 { offsets, data } if offsets.len() > rows => texts(offsets, data, out),
_ => return false,
}
true
}
fn row_bits(&self, column: &Column, row: usize, (numeric, text, boolean): (bool, bool, bool), bits: &mut [u64]) {
bits.copy_from_slice(&self.always);
if !column.valid(row) {
if let Some(matched) = &self.null {
Self::or(bits, matched);
}
return;
}
match (numeric, text, boolean) {
(true, _, _) => {
let Some(n) = column.number(row) else {
if let Some(matched) = &self.null {
Self::or(bits, matched);
}
return;
};
if let Some(region) = self.region(&n) {
Self::or(bits, region);
}
}
(_, true, _) => {
if let Some(matched) = column.bytes(row).and_then(|t| self.text(t)) {
Self::or(bits, matched);
}
}
(_, _, true) => {
if let Some(matched) = column.boolean(row).and_then(|b| self.bools[usize::from(b)].as_ref()) {
Self::or(bits, matched);
}
}
_ => {
let value = column.variable(row);
if let Some(matched) = self.matched(&value) {
Self::or(bits, matched);
}
self.dated(&value, bits);
if let Variable::Number(n) = &value {
if let Some(region) = self.region(n) {
Self::or(bits, region);
}
}
}
}
}
pub fn pieces(&self, empty: &[u64]) -> Option<Pieces> {
if !self.others.is_empty() || self.strs.len() > 64 {
return None;
}
let mut bits: Vec<Vec<u64>> = Vec::new();
let with = |extra: Option<&Vec<u64>>| {
let mut piece = self.always.clone();
if let Some(extra) = extra {
Self::or(&mut piece, extra);
}
piece
};
let null = Pieces::intern(&mut bits, with(self.null.as_ref()));
let truth = [
Pieces::intern(&mut bits, with(self.bools[0].as_ref())),
Pieces::intern(&mut bits, with(self.bools[1].as_ref())),
];
let keys = self
.strs
.iter()
.map(|(key, matched)| {
let piece = Pieces::intern(&mut bits, with(Some(matched)));
(Pieces::word(key), key.len(), key.clone(), piece)
})
.collect();
let text = Pieces::intern(&mut bits, with(None));
let regions = self.regions.iter().map(|r| Pieces::intern(&mut bits, with(Some(r)))).collect();
let other = text;
let failed = Pieces::intern(&mut bits, empty.to_vec());
Some(Pieces {
bits,
null,
truth,
keys,
text,
regions,
other,
failed,
})
}
fn piece_of(&self, pieces: &Pieces, value: &Variable) -> u16 {
match value {
Variable::Null => pieces.null,
Variable::Bool(b) => pieces.truth[usize::from(*b)],
Variable::String(s) => pieces.text(s.as_bytes()),
Variable::Number(n) => self.number_piece(pieces, n),
Variable::Dynamic(dynamic) => match dynamic.as_date() {
Some(date) => pieces
.keys
.iter()
.find(|(_, _, key, _)| date.matches(&Variable::String(String::from_utf8_lossy(key).as_ref().into())))
.map_or(pieces.other, |(_, _, _, piece)| *piece),
None => pieces.other,
},
_ => pieces.other,
}
}
fn number_piece(&self, pieces: &Pieces, n: &Decimal) -> u16 {
if pieces.regions.is_empty() {
return pieces.other;
}
let region = match self.bounds.binary_search(n) {
Ok(i) => i * 2 + 1,
Err(i) => i * 2,
};
pieces.regions.get(region).copied().unwrap_or(pieces.other)
}
fn numbers_into(&self, pieces: &Pieces, column: &Column, parts: impl Iterator<Item = Option<(i64, u8)>>, out: &mut [u16]) {
if pieces.regions.is_empty() {
for (row, piece) in out.iter_mut().enumerate() {
*piece = match column.valid(row) {
true => pieces.other,
false => pieces.null,
};
}
return;
}
let mut cached: Vec<Option<Option<Scaling>>> = Vec::new();
for ((row, piece), part) in out.iter_mut().enumerate().zip(parts) {
if !column.valid(row) {
*piece = pieces.null;
continue;
}
let fast = part.and_then(|(mant, scale)| {
let at = scale as usize;
if cached.len() <= at {
cached.resize_with(at + 1, || None);
}
let scaling = cached[at].get_or_insert_with(|| self.scaling(scale)).as_ref()?;
Some(Self::region_of(&scaling.bounds, mant.checked_mul(scaling.mult)?))
});
*piece = match fast {
Some(region) => pieces.regions.get(region).copied().unwrap_or(pieces.other),
None => match column.number(row) {
Some(n) => self.number_piece(pieces, &n),
None => pieces.null,
},
};
}
}
pub fn classify(&self, pieces: &Pieces, column: &Column, rows: usize, out: &mut [u16]) {
let out = &mut out[..rows];
if column.is_empty() {
out.fill(pieces.null);
return;
}
match column.values {
Values::Text { offsets, data } if offsets.len() > rows => {
let data = data.as_bytes();
for (row, (piece, pair)) in out.iter_mut().zip(offsets.windows(2)).enumerate() {
*piece = match column.valid(row) {
false => pieces.null,
true => match data.get(pair[0] as usize..pair[1] as usize) {
Some(text) => pieces.text(text),
None => pieces.text,
},
};
}
}
Values::Text { .. } | Values::Utf8 { .. } | Values::LargeUtf8 { .. } | Values::Strs(_) => {
for (row, piece) in out.iter_mut().enumerate() {
*piece = match (column.valid(row), column.bytes(row)) {
(true, Some(text)) => pieces.text(text),
(true, None) => pieces.text,
(false, _) => pieces.null,
};
}
}
Values::Bool { bits, offset } => {
for (row, piece) in out.iter_mut().enumerate() {
*piece = match column.valid(row) {
true => pieces.truth[usize::from(bits.get((offset + row) / 64).is_some_and(|w| w >> ((offset + row) % 64) & 1 == 1))],
false => pieces.null,
};
}
}
Values::Scaled { mant, scale } if mant.len() >= rows && scale.len() >= rows => {
self.numbers_into(pieces, column, mant.iter().zip(scale).map(|(m, s)| Some((*m, *s))), out)
}
Values::I64(values) if values.len() >= rows => {
self.numbers_into(pieces, column, values.iter().map(|v| Some((*v, 0u8))), out)
}
Values::Dec(values) if values.len() >= rows => self.numbers_into(
pieces,
column,
values
.iter()
.map(|d| Some((i64::try_from(d.mantissa()).ok()?, u8::try_from(d.scale()).ok()?))),
out,
),
Values::Dict { keys, values } => {
let dictionary = values.column();
let size = dictionary.len();
let mut coded = vec![0u16; size];
self.classify(pieces, &dictionary, size, &mut coded);
for (row, piece) in out.iter_mut().enumerate() {
let code = keys.get(row).and_then(|k| usize::try_from(*k).ok()).filter(|c| *c < size);
*piece = match (column.valid(row), code) {
(true, Some(code)) => coded[code],
_ => pieces.null,
};
}
}
_ => {
for (row, piece) in out.iter_mut().enumerate() {
*piece = self.piece_of(pieces, &column.variable(row));
}
}
}
}
pub fn evaluate_indexed_column(&self, column: &Column, rows: usize, out: &mut Vec<u64>) {
self.indexed_column(column, rows, out);
for row in 0..rows {
Self::or(&mut out[row * self.words..(row + 1) * self.words], &self.optimistic);
}
}
pub fn peelable(&self) -> bool {
self.others.iter().all(|other| {
let p = other.program.program();
!p.opaque() && !p.writes_env && p.site_keys.iter().all(|key| key.as_deref() == Some("$"))
})
}
pub fn others(&self) -> usize {
self.others.len()
}
pub fn other(&self, index: usize) -> Option<(&LaneProgram, &[u64])> {
self.others.get(index).map(|other| (&other.program, other.rules.as_slice()))
}
pub fn owner(&self, rule: usize) -> Option<usize> {
self.owners.get(rule).copied().flatten()
}
pub fn evaluate_indexed(&self, values: &[Variable], out: &mut Vec<u64>) {
self.indexed(values, out);
for row in 0..values.len() {
Self::or(&mut out[row * self.words..(row + 1) * self.words], &self.optimistic);
}
}
fn scope(value: &Variable, env: Option<&Scope>) -> Scope {
let mut scope = Scope::new(env.map_or(Variable::Null, |e| e.base().clone()));
if let Some(env) = env {
for (k, v) in env.locals() {
scope.set_local(k.clone(), v.clone());
}
}
scope.set_local(Variable::dollar_key(), value.clone());
scope
}
fn indexed(&self, values: &[Variable], out: &mut Vec<u64>) {
let words = self.words;
out.clear();
out.resize(values.len() * words, 0);
for (row, value) in values.iter().enumerate() {
let bits = &mut out[row * words..(row + 1) * words];
bits.copy_from_slice(&self.always);
if let Some(matched) = self.matched(value) {
Self::or(bits, matched);
}
self.dated(value, bits);
if let (Variable::Number(n), false) = (value, self.regions.is_empty()) {
let region = match self.bounds.binary_search(n) {
Ok(i) => i * 2 + 1,
Err(i) => i * 2,
};
Self::or(bits, &self.regions[region]);
}
}
}
}
+559
View File
@@ -0,0 +1,559 @@
use crate::lane::mask::{LaneSet, Lanes};
use crate::lane::program::{Binding, Kind};
use crate::variable::Variable;
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;
use std::str::FromStr;
#[derive(Debug, Clone, Copy)]
pub enum Values<'a> {
Dec(&'a [Decimal]),
Scaled {
mant: &'a [i64],
scale: &'a [u8],
},
I64(&'a [i64]),
F64(&'a [f64]),
Bool {
bits: &'a [u64],
offset: usize,
},
Utf8 {
offsets: &'a [i32],
data: &'a [u8],
},
Text {
offsets: &'a [i32],
data: &'a str,
},
LargeUtf8 {
offsets: &'a [i64],
data: &'a [u8],
},
Strs(&'a [&'a str]),
Dict {
keys: &'a [i32],
values: Dictionary<'a>,
},
List {
offsets: &'a [i32],
child: Dictionary<'a>,
},
Any(&'a [Variable]),
}
#[derive(Debug, Clone, Copy)]
pub enum Dictionary<'a> {
Column(&'a Column<'a>),
Text { offsets: &'a [i32], data: &'a str },
Scaled { mant: &'a [i64], scale: &'a [u8] },
Bool { bits: &'a [u64] },
Any(&'a [Variable]),
}
impl<'a> From<&'a Column<'a>> for Dictionary<'a> {
fn from(column: &'a Column<'a>) -> Self {
Dictionary::Column(column)
}
}
impl<'a> Dictionary<'a> {
pub fn column(self) -> Column<'a> {
match self {
Dictionary::Column(column) => *column,
Dictionary::Text { offsets, data } => Column::new(Values::Text { offsets, data }),
Dictionary::Scaled { mant, scale } => Column::new(Values::Scaled { mant, scale }),
Dictionary::Bool { bits } => Column::new(Values::Bool { bits, offset: 0 }),
Dictionary::Any(values) => Column::new(Values::Any(values)),
}
}
pub fn len(self) -> usize {
self.column().len()
}
pub fn is_empty(self) -> bool {
self.len() == 0
}
pub fn kind(self) -> Kind {
self.column().kind()
}
pub fn valid(self, row: usize) -> bool {
self.column().valid(row)
}
pub fn number(self, row: usize) -> Option<Decimal> {
self.column().number(row)
}
pub fn boolean(self, row: usize) -> Option<bool> {
self.column().boolean(row)
}
pub fn text(self, row: usize) -> Option<&'a str> {
self.column().text(row)
}
pub fn variable(self, row: usize) -> Variable {
self.column().variable(row)
}
pub fn equals(self, row: usize, k: &Variable) -> bool {
self.column().equals(row, k)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Column<'a> {
pub values: Values<'a>,
pub validity: Option<(&'a [u64], usize)>,
}
impl<'a> Column<'a> {
pub fn new(values: Values<'a>) -> Self {
Self {
values,
validity: None,
}
}
pub fn with_validity(values: Values<'a>, bits: &'a [u64], offset: usize) -> Self {
Self {
values,
validity: Some((bits, offset)),
}
}
pub fn kind(&self) -> Kind {
match self.values {
Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => Kind::Num,
Values::Bool { .. } => Kind::Bool,
Values::Utf8 { .. } | Values::Text { .. } | Values::LargeUtf8 { .. } | Values::Strs(_) => Kind::Str,
Values::Dict { values, .. } => values.kind(),
Values::List { child, .. } => match child.column().values {
Values::Scaled { .. } | Values::Text { .. } | Values::Bool { .. } if child.column().validity.is_none() => Kind::List,
_ => Kind::Dyn,
},
Values::Any(_) => Kind::Dyn,
}
}
#[inline]
pub(crate) fn bit(bits: &[u64], index: usize) -> bool {
bits.get(index / 64)
.is_some_and(|w| w >> (index % 64) & 1 == 1)
}
pub(crate) fn valid_mask<M: LaneSet>(&self, start: usize, width: usize) -> M {
match self.validity {
None => M::all(width),
Some((bits, offset)) => Self::mask(bits, offset + start, width),
}
}
pub(crate) fn mask<M: LaneSet>(bits: &[u64], at: usize, width: usize) -> M {
let mut mask = M::none(width);
for i in 0..width.div_ceil(64) {
let take = (width - i * 64).min(64);
mask.set_word(i, Self::word(bits, at + i * 64, take));
}
mask
}
#[inline]
pub fn word(bits: &[u64], at: usize, width: usize) -> u64 {
let all = match width >= 64 {
true => u64::MAX,
false => (1u64 << width) - 1,
};
if at == usize::MAX {
return all;
}
let (word, shift) = (at / 64, at % 64);
let low = bits.get(word).copied().unwrap_or(0) >> shift;
let high = match shift {
0 => 0,
_ => bits.get(word + 1).copied().unwrap_or(0) << (64 - shift),
};
(low | high) & all
}
#[inline]
pub fn range(&self, row: usize) -> Option<(usize, usize)> {
let Values::List { offsets, .. } = self.values else {
return None;
};
match (self.valid(row), offsets.get(row), offsets.get(row + 1)) {
(true, Some(a), Some(b)) => {
let a = usize::try_from(*a).unwrap_or(0);
Some((a, usize::try_from(*b).unwrap_or(0).max(a)))
}
_ => None,
}
}
#[inline]
pub fn valid(&self, row: usize) -> bool {
match self.validity {
None => true,
Some((bits, offset)) => Self::bit(bits, offset + row),
}
}
#[inline]
pub fn code(&self, row: usize) -> Option<usize> {
match self.values {
Values::Dict { keys, .. } => keys.get(row).and_then(|k| usize::try_from(*k).ok()),
_ => None,
}
}
pub fn len(&self) -> usize {
match self.values {
Values::Dec(v) => v.len(),
Values::Scaled { mant, .. } => mant.len(),
Values::I64(v) => v.len(),
Values::F64(v) => v.len(),
Values::Bool { bits, offset } => (bits.len() * 64).saturating_sub(offset),
Values::Utf8 { offsets, .. } => offsets.len().saturating_sub(1),
Values::Text { offsets, .. } => offsets.len().saturating_sub(1),
Values::LargeUtf8 { offsets, .. } => offsets.len().saturating_sub(1),
Values::Strs(v) => v.len(),
Values::Dict { keys, .. } => keys.len(),
Values::List { offsets, .. } => offsets.len().saturating_sub(1),
Values::Any(v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn number(&self, row: usize) -> Option<Decimal> {
match self.values {
Values::Dec(v) => v.get(row).copied(),
Values::Scaled { mant, scale } => Some(Decimal::new(*mant.get(row)?, *scale.get(row)? as u32)),
Values::I64(v) => v.get(row).map(|n| Decimal::from(*n)),
Values::F64(v) => v.get(row).and_then(|f| Self::float(*f)),
Values::Dict { values, .. } => {
let code = self.code(row)?;
values.valid(code).then(|| values.number(code)).flatten()
}
Values::Any(v) => match v.get(row) {
Some(Variable::Number(n)) => Some(*n),
_ => None,
},
_ => None,
}
}
fn float(f: f64) -> Option<Decimal> {
if !f.is_finite() {
return None;
}
let mut buffer = [0u8; 512];
let mut cursor = std::io::Cursor::new(&mut buffer[..]);
let written = std::io::Write::write_fmt(&mut cursor, format_args!("{f}")).is_ok();
let len = cursor.position() as usize;
written
.then(|| std::str::from_utf8(&buffer[..len]).ok())
.flatten()
.and_then(|text| Decimal::from_str(text).ok())
.or_else(|| Decimal::from_f64(f))
}
#[inline]
pub fn boolean(&self, row: usize) -> Option<bool> {
match self.values {
Values::Bool { bits, offset } => Some(Self::bit(bits, offset + row)),
Values::Dict { values, .. } => {
let code = self.code(row)?;
values.valid(code).then(|| values.boolean(code)).flatten()
}
_ => None,
}
}
pub(crate) fn texts(&self, base: usize, n: usize) -> Option<Texts<'a>> {
match self.values {
Values::Utf8 { offsets, data } => {
let window = offsets.get(base..=base + n)?;
let (first, last) = (*window.first()? as usize, *window.last()? as usize);
window.windows(2).all(|w| w[0] <= w[1]).then_some(())?;
let block = std::str::from_utf8(data.get(first..last)?).ok()?;
Some(Texts::Utf8(block, window, first))
}
Values::Text { offsets, data } => {
let window = offsets.get(base..=base + n)?;
let (first, last) = (*window.first()? as usize, *window.last()? as usize);
window.windows(2).all(|w| w[0] <= w[1]).then_some(())?;
Some(Texts::Utf8(data.get(first..last)?, window, first))
}
Values::LargeUtf8 { offsets, data } => {
let window = offsets.get(base..=base + n)?;
let (first, last) = (*window.first()? as usize, *window.last()? as usize);
window.windows(2).all(|w| w[0] <= w[1]).then_some(())?;
let block = std::str::from_utf8(data.get(first..last)?).ok()?;
Some(Texts::Large(block, window, first))
}
Values::Strs(v) => v.get(base..base + n).map(Texts::Strs),
_ => None,
}
}
pub fn bytes(&self, row: usize) -> Option<&'a [u8]> {
match self.values {
Values::Utf8 { offsets, data } => {
let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize);
data.get(a..b)
}
Values::Text { offsets, data } => {
let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize);
data.as_bytes().get(a..b)
}
Values::LargeUtf8 { offsets, data } => {
let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize);
data.get(a..b)
}
_ => self.text(row).map(str::as_bytes),
}
}
pub fn scaled(&self, row: usize) -> Option<(i128, u32)> {
match self.values {
Values::Scaled { mant, scale } => Some((*mant.get(row)? as i128, *scale.get(row)? as u32)),
Values::I64(v) => Some((*v.get(row)? as i128, 0)),
Values::Dec(v) => v.get(row).map(|d| (d.mantissa(), d.scale())),
_ => None,
}
}
pub fn text(&self, row: usize) -> Option<&'a str> {
match self.values {
Values::Utf8 { offsets, data } => {
let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize);
std::str::from_utf8(data.get(a..b)?).ok()
}
Values::Text { offsets, data } => {
let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize);
data.get(a..b)
}
Values::LargeUtf8 { offsets, data } => {
let (a, b) = (*offsets.get(row)? as usize, *offsets.get(row + 1)? as usize);
std::str::from_utf8(data.get(a..b)?).ok()
}
Values::Strs(v) => v.get(row).copied(),
Values::Dict { values, .. } => {
let code = self.code(row)?;
values.valid(code).then(|| values.text(code)).flatten()
}
_ => None,
}
}
pub fn equals(&self, row: usize, k: &Variable) -> bool {
if !self.valid(row) {
return matches!(k, Variable::Null);
}
match (self.values, k) {
(Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_), Variable::Number(n)) => self
.number(row)
.is_some_and(|m| crate::lane::ops::Ops::same_number(&m, n)),
(Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_), Variable::Null) => {
self.number(row).is_none()
}
(Values::Bool { .. }, Variable::Bool(b)) => self.boolean(row) == Some(*b),
(
Values::Utf8 { .. } | Values::Text { .. } | Values::LargeUtf8 { .. } | Values::Strs(_),
Variable::String(s),
) => self.bytes(row) == Some(s.as_bytes()),
(Values::Any(v), k) => v
.get(row)
.is_some_and(|v| crate::lane::ops::Ops::equal(v, k)),
(Values::Dict { values, .. }, k) => {
self.code(row).is_some_and(|code| values.equals(code, k))
}
(Values::List { .. }, _) => false,
_ => false,
}
}
pub fn borrowed(&self, row: usize) -> Option<&'a Variable> {
if !self.valid(row) {
return None;
}
match self.values {
Values::Any(values) => values.get(row),
Values::Dict {
values: Dictionary::Any(values),
..
} => values.get(self.code(row)?),
_ => None,
}
}
pub fn variable(&self, row: usize) -> Variable {
if !self.valid(row) {
return Variable::Null;
}
match self.values {
Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => {
self.number(row).map_or(Variable::Null, Variable::Number)
}
Values::Bool { .. } => self.boolean(row).map_or(Variable::Null, Variable::Bool),
Values::Any(v) => v.get(row).cloned().unwrap_or(Variable::Null),
Values::Dict { values, .. } => self
.code(row)
.map_or(Variable::Null, |code| values.variable(code)),
Values::List { child, .. } => {
let items = self
.range(row)
.map(|(a, b)| (a..b).map(|i| child.variable(i)).collect())
.unwrap_or_default();
Variable::from_array(items)
}
_ => self
.text(row)
.map_or(Variable::Null, |s| Variable::String(s.into())),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Columns<'a> {
pub rows: usize,
pub columns: Vec<(&'a str, Column<'a>)>,
}
impl<'a> Columns<'a> {
pub fn new(rows: usize) -> Self {
Self {
rows,
columns: Vec::new(),
}
}
pub fn column(mut self, path: &'a str, column: Column<'a>) -> Self {
self.columns.push((path, column));
self
}
pub fn find(&self, path: &str) -> Option<usize> {
self.columns.iter().rposition(|(p, _)| *p == path)
}
pub fn bind(&self, path: &str) -> Binding {
let covered = self.columns.iter().any(|(p, _)| {
p.strip_prefix(path)
.is_some_and(|rest| rest.starts_with('.'))
|| path
.strip_prefix(*p)
.is_some_and(|rest| rest.starts_with('.'))
});
match (covered, self.find(path)) {
(true, _) => Binding::Row,
(false, Some(i)) => Binding::Column(i),
(false, None) => Binding::Absent,
}
}
pub fn row(&self, row: usize) -> Variable {
let object = Variable::empty_object();
for (path, column) in &self.columns {
let value = match column.values {
Values::Any(_) => column.variable(row).depth_clone(usize::MAX),
_ => column.variable(row),
};
if !matches!(value, Variable::Null) || column.valid(row) {
object.dot_insert(path, value);
}
}
object
}
}
pub(crate) enum Texts<'a> {
Utf8(&'a str, &'a [i32], usize),
Large(&'a str, &'a [i64], usize),
Strs(&'a [&'a str]),
}
impl<'a> Texts<'a> {
#[inline]
pub(crate) fn each_bytes<M: LaneSet>(&self, lanes: M, mut f: impl FnMut(usize, &'a [u8])) {
match self {
Texts::Utf8(block, offsets, first) => {
let block = block.as_bytes();
for lane in Lanes::of(lanes) {
let range = offsets
.get(lane)
.zip(offsets.get(lane + 1))
.and_then(|(a, b)| (*a as usize).checked_sub(*first).zip((*b as usize).checked_sub(*first)));
if let Some(x) = range.and_then(|(a, b)| block.get(a..b)) {
f(lane, x);
}
}
}
Texts::Large(block, offsets, first) => {
let block = block.as_bytes();
for lane in Lanes::of(lanes) {
let range = offsets
.get(lane)
.zip(offsets.get(lane + 1))
.and_then(|(a, b)| (*a as usize).checked_sub(*first).zip((*b as usize).checked_sub(*first)));
if let Some(x) = range.and_then(|(a, b)| block.get(a..b)) {
f(lane, x);
}
}
}
Texts::Strs(v) => {
for lane in Lanes::of(lanes) {
if let Some(x) = v.get(lane) {
f(lane, x.as_bytes());
}
}
}
}
}
}
#[cfg(test)]
mod float_tests {
use super::Column;
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;
use std::str::FromStr;
#[test]
fn stack_formatting_matches_heap_formatting() {
let mut state = 0xBB67AE8584CAA73Bu64;
for i in 0..300_000u64 {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
let f = match i % 4 {
0 => f64::from_bits(state),
1 => (state % 10_000_000) as f64 / 100.0,
2 => (state as i64 as f64) * 1e-30,
_ => f64::from_bits(state % 0x0010_0000_0000_0000),
};
let expected = f
.is_finite()
.then(|| {
Decimal::from_str(&format!("{f}"))
.ok()
.or_else(|| Decimal::from_f64(f))
})
.flatten();
let got = Column::float(f);
assert_eq!(
got.map(|d| d.serialize()),
expected.map(|d| d.serialize()),
"{f:e}"
);
}
}
}
File diff suppressed because it is too large Load Diff
+63
View File
@@ -0,0 +1,63 @@
use crate::lane::date::duration_parser::{DurationParseError, DurationParser};
use crate::lane::date::duration_unit::DurationUnit;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::Decimal;
use std::ops::Neg;
#[derive(Debug, Clone, Default)]
pub(crate) struct Duration {
pub seconds: i64,
pub months: i32,
pub years: i32,
}
impl Duration {
pub fn parse(s: &str) -> Result<Self, DurationParseError> {
DurationParser {
iter: s.chars(),
src: s,
duration: Duration::default(),
}
.parse()
}
pub fn from_unit(n: Decimal, unit: DurationUnit) -> Option<Self> {
if let Some(secs) = unit.as_secs() {
return Some(Self {
seconds: n.checked_mul(Decimal::from_u64(secs)?)?.to_i64()?,
..Default::default()
});
};
match unit {
DurationUnit::Month => Some(Duration {
months: n.to_i32()?,
..Default::default()
}),
DurationUnit::Quarter => Some(Duration {
months: n.to_i32()? * 3,
..Default::default()
}),
DurationUnit::Year => Some(Duration {
years: n.to_i32()?,
..Default::default()
}),
_ => None,
}
}
pub fn negate(self) -> Self {
Self {
years: self.years.neg(),
months: self.months.neg(),
seconds: self.seconds.neg(),
}
}
pub fn day() -> Self {
Self {
seconds: DurationUnit::Day.as_secs().unwrap_or_default() as i64,
..Default::default()
}
}
}
@@ -0,0 +1,137 @@
use crate::lane::date::duration::Duration;
use crate::lane::date::duration_unit::DurationUnit;
use rust_decimal::prelude::ToPrimitive;
use std::str::Chars;
use thiserror::Error;
#[derive(Debug, PartialEq, Clone, Error)]
pub(crate) enum DurationParseError {
#[error("Invalid character at {0}")]
InvalidCharacter(usize),
#[error("Expected number at {0}")]
NumberExpected(usize),
#[error("Unknown time unit {unit}")]
UnknownUnit {
start: usize,
end: usize,
value: u64,
unit: String,
},
#[error("Number is too large")]
NumberOverflow,
#[error("Value is empty")]
Empty,
}
pub(crate) struct DurationParser<'a> {
pub iter: Chars<'a>,
pub src: &'a str,
pub duration: Duration,
}
impl DurationParser<'_> {
fn off(&self) -> usize {
self.src.len() - self.iter.as_str().len()
}
fn parse_first_char(&mut self) -> Result<Option<u64>, DurationParseError> {
let off = self.off();
for c in self.iter.by_ref() {
match c {
'0'..='9' => {
return Ok(Some(c as u64 - '0' as u64));
}
c if c.is_whitespace() => continue,
_ => {
return Err(DurationParseError::NumberExpected(off));
}
}
}
Ok(None)
}
fn parse_unit(&mut self, n: u64, start: usize, end: usize) -> Result<(), DurationParseError> {
let unit = DurationUnit::parse(&self.src[start..end]).ok_or_else(|| {
DurationParseError::UnknownUnit {
start,
end,
unit: self.src[start..end].to_string(),
value: n,
}
})?;
match unit {
DurationUnit::Quarter => {
self.duration.months = n.to_i32().ok_or(DurationParseError::NumberOverflow)? * 3
}
DurationUnit::Month => {
self.duration.months = n.to_i32().ok_or(DurationParseError::NumberOverflow)?
}
DurationUnit::Year => {
self.duration.years = n.to_i32().ok_or(DurationParseError::NumberOverflow)?
}
_ => {}
}
if let Some(secs) = unit.as_secs() {
self.duration.seconds = self
.duration
.seconds
.checked_add(
secs.to_i64()
.ok_or(DurationParseError::NumberOverflow)?
.checked_mul(n.to_i64().ok_or(DurationParseError::NumberOverflow)?)
.ok_or(DurationParseError::NumberOverflow)?,
)
.ok_or(DurationParseError::NumberOverflow)?
}
Ok(())
}
pub fn parse(mut self) -> Result<Duration, DurationParseError> {
let mut n = self.parse_first_char()?.ok_or(DurationParseError::Empty)?;
'outer: loop {
let mut off = self.off();
while let Some(c) = self.iter.next() {
match c {
'0'..='9' => {
n = n
.checked_mul(10)
.and_then(|x| x.checked_add(c as u64 - '0' as u64))
.ok_or(DurationParseError::NumberOverflow)?;
}
c if c.is_whitespace() => {}
'a'..='z' | 'A'..='Z' => {
break;
}
_ => {
return Err(DurationParseError::InvalidCharacter(off));
}
}
off = self.off();
}
let start = off;
let mut off = self.off();
while let Some(c) = self.iter.next() {
match c {
'0'..='9' => {
self.parse_unit(n, start, off)?;
n = c as u64 - '0' as u64;
continue 'outer;
}
c if c.is_whitespace() => break,
'a'..='z' | 'A'..='Z' => {}
_ => {
return Err(DurationParseError::InvalidCharacter(off));
}
}
off = self.off();
}
self.parse_unit(n, start, off)?;
n = match self.parse_first_char()? {
Some(n) => n,
None => return Ok(self.duration),
};
}
}
}
@@ -0,0 +1,44 @@
#[derive(Debug, Clone, Copy)]
pub(crate) enum DurationUnit {
Second,
Minute,
Hour,
Day,
Week,
Month,
Quarter,
Year,
}
impl DurationUnit {
pub fn parse(unit: &str) -> Option<Self> {
match unit {
"seconds" | "second" | "secs" | "sec" | "s" => Some(Self::Second),
"minutes" | "minute" | "min" | "mins" | "m" => Some(Self::Minute),
"hours" | "hour" | "hr" | "hrs" | "h" => Some(Self::Hour),
"days" | "day" | "d" => Some(Self::Day),
"weeks" | "week" | "w" => Some(Self::Week),
"months" | "month" | "mo" | "M" => Some(Self::Month),
"quarters" | "quarter" | "qtr" | "q" => Some(Self::Quarter),
"years" | "year" | "y" => Some(Self::Year),
_ => None,
}
}
pub fn as_secs(&self) -> Option<u64> {
match self {
DurationUnit::Second => Some(1),
DurationUnit::Minute => Some(60),
DurationUnit::Hour => Some(3600),
DurationUnit::Day => Some(86_400),
DurationUnit::Week => Some(86_400 * 7),
DurationUnit::Quarter => None,
DurationUnit::Month => None,
DurationUnit::Year => None,
}
}
pub fn as_millis(&self) -> Option<f64> {
self.as_secs().map(|s| s as f64 * 1000_f64)
}
}
+254
View File
@@ -0,0 +1,254 @@
use crate::lane::date::utc_now;
use crate::vm::VMError;
use chrono::format::{parse, Item, ParseResult, Parsed, StrftimeItems};
use chrono::{DateTime, Datelike, Days, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday};
use once_cell::sync::Lazy;
type VMResult<T> = Result<T, VMError>;
#[allow(clippy::unwrap_used)]
static ZERO_TIME: Lazy<NaiveTime> = Lazy::new(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
static DATE_TIME: &str = "%Y-%m-%d %H:%M:%S";
static DATE: &str = "%Y-%m-%d";
static TIME_HMS: &str = "%H:%M:%S";
static TIME_HM: &str = "%H:%M";
static TIME_H: &str = "%H";
static DATE_TIME_ITEMS: Lazy<Vec<Item<'static>>> = Lazy::new(|| StrftimeItems::new(DATE_TIME).parse_to_owned().unwrap_or_default());
static DATE_ITEMS: Lazy<Vec<Item<'static>>> = Lazy::new(|| StrftimeItems::new(DATE).parse_to_owned().unwrap_or_default());
pub(crate) struct Formats;
impl Formats {
fn date_time(s: &str) -> ParseResult<NaiveDateTime> {
let mut parsed = Parsed::new();
parse(&mut parsed, s, DATE_TIME_ITEMS.iter())?;
parsed.to_naive_datetime_with_offset(0)
}
fn date(s: &str) -> ParseResult<NaiveDate> {
let mut parsed = Parsed::new();
parse(&mut parsed, s, DATE_ITEMS.iter())?;
parsed.to_naive_date()
}
}
pub(crate) struct IsoDate;
impl IsoDate {
fn digits(bytes: &[u8]) -> Option<u32> {
bytes.iter().try_fold(0u32, |acc, c| {
c.is_ascii_digit().then(|| acc * 10 + (c - b'0') as u32)
})
}
pub(crate) fn utc(s: &str) -> bool {
s.as_bytes().get(10) == Some(&b'T')
}
pub(crate) fn parse(s: &str) -> Option<NaiveDateTime> {
let b = s.as_bytes();
if b.len() < 10 || b[4] != b'-' || b[7] != b'-' {
return None;
}
let date = NaiveDate::from_ymd_opt(
Self::digits(&b[0..4])? as i32,
Self::digits(&b[5..7])?,
Self::digits(&b[8..10])?,
)?;
let time = match &b[10..] {
[] => (0, 0, 0),
[sep, h1, h2, b':', m1, m2, b':', s1, s2, rest @ ..]
if (*sep == b' ' && rest.is_empty()) || (*sep == b'T' && rest == b"Z") =>
{
(
Self::digits(&[*h1, *h2])?,
Self::digits(&[*m1, *m2])?,
Self::digits(&[*s1, *s2])?,
)
}
_ => return None,
};
date.and_hms_opt(time.0, time.1, time.2)
}
}
pub(crate) fn date_time(str: &str) -> VMResult<NaiveDateTime> {
if str == "now" {
return Ok(utc_now().naive_utc());
}
if let Some(parsed) = IsoDate::parse(str) {
return Ok(parsed);
}
Formats::date_time(str)
.or_else(|_| Formats::date(str).map(|c| c.and_time(*ZERO_TIME)))
.or_else(|_| DateTime::parse_from_rfc3339(str).map(|dt| dt.naive_utc()))
.map_err(|_| VMError::ParseDateTimeErr {
timestamp: str.to_string(),
})
}
pub(crate) fn time(str: &str) -> VMResult<NaiveTime> {
let now = utc_now();
if str == "now" {
return Ok(now.naive_utc().time());
}
NaiveTime::parse_from_str(str, DATE_TIME)
.or(NaiveTime::parse_from_str(str, TIME_HMS))
.or(NaiveTime::parse_from_str(str, TIME_HM))
.or(NaiveTime::parse_from_str(str, TIME_H))
.or(DateTime::parse_from_rfc3339(str).map(|dt| dt.naive_utc().time()))
.map_err(|_| VMError::ParseDateTimeErr {
timestamp: str.to_string(),
})
}
pub(crate) enum DateUnit {
Second,
Minute,
Hour,
Day,
Week,
Month,
Year,
}
impl TryFrom<&str> for DateUnit {
type Error = VMError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"s" | "second" | "seconds" => Ok(Self::Second),
"m" | "minute" | "minutes" => Ok(Self::Minute),
"h" | "hour" | "hours" => Ok(Self::Hour),
"d" | "day" | "days" => Ok(Self::Day),
"w" | "week" | "weeks" => Ok(Self::Week),
"M" | "month" | "months" => Ok(Self::Month),
"y" | "year" | "years" => Ok(Self::Year),
_ => Err(VMError::OpcodeErr {
opcode: "DateUnit".into(),
message: "Unknown date unit".into(),
}),
}
}
}
pub(crate) fn date_time_start_of(date: NaiveDateTime, unit: DateUnit) -> Option<NaiveDateTime> {
match unit {
DateUnit::Second => Some(date),
DateUnit::Minute => date.with_second(0),
DateUnit::Hour => date.with_second(0)?.with_minute(0),
DateUnit::Day => date.with_second(0)?.with_minute(0)?.with_hour(0),
DateUnit::Week => date
.with_second(0)?
.with_minute(0)?
.with_hour(0)?
.checked_sub_days(Days::new(date.weekday().num_days_from_monday() as u64)),
DateUnit::Month => date
.with_second(0)?
.with_minute(0)?
.with_hour(0)?
.with_day0(0),
DateUnit::Year => date
.with_second(0)?
.with_minute(0)?
.with_hour(0)?
.with_day0(0)?
.with_month0(0),
}
}
pub(crate) fn date_time_end_of(date: NaiveDateTime, unit: DateUnit) -> Option<NaiveDateTime> {
match unit {
DateUnit::Second => Some(date),
DateUnit::Minute => date.with_second(59),
DateUnit::Hour => date.with_second(59)?.with_minute(59),
DateUnit::Day => date.with_second(59)?.with_minute(59)?.with_hour(23),
DateUnit::Week => date
.with_second(59)?
.with_minute(59)?
.with_hour(23)?
.checked_add_days(Days::new(Weekday::Sun as u64 - date.weekday() as u64)),
DateUnit::Month => date
.with_second(59)?
.with_minute(59)?
.with_hour(23)?
.with_day(get_month_days(&date)? as u32),
DateUnit::Year => date
.with_second(59)?
.with_minute(59)?
.with_hour(23)?
.with_day(get_month_days(&date)? as u32)?
.with_month0(11),
}
}
fn get_month_days(date: &NaiveDateTime) -> Option<i64> {
Some(
NaiveDate::from_ymd_opt(
match date.month() {
12 => date.year() + 1,
_ => date.year(),
},
match date.month() {
12 => 1,
_ => date.month() + 1,
},
1,
)?
.signed_duration_since(NaiveDate::from_ymd_opt(date.year(), date.month(), 1)?)
.num_days(),
)
}
#[cfg(test)]
mod iso_tests {
use super::{IsoDate, DATE, DATE_TIME, ZERO_TIME};
use chrono::{DateTime, NaiveDate, NaiveDateTime};
fn chrono_chain(s: &str) -> Option<NaiveDateTime> {
NaiveDateTime::parse_from_str(s, DATE_TIME)
.or_else(|_| NaiveDate::parse_from_str(s, DATE).map(|c| c.and_time(*ZERO_TIME)))
.or_else(|_| DateTime::parse_from_rfc3339(s).map(|dt| dt.naive_utc()))
.ok()
}
#[test]
fn iso_fast_path_agrees_with_chrono() {
let mut state = 0x2545F4914F6CDD1Du64;
let mut next = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let mut checked = 0;
for _ in 0..200_000 {
let year = 1900 + next(250);
let month = next(14);
let day = next(33);
let (h, m, sec) = (next(26), next(62), next(62));
let s = match next(8) {
0 => format!("{year:04}-{month:02}-{day:02}"),
1 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}:{sec:02}"),
2 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}Z"),
3 => format!("{year:04}-{month}-{day}"),
4 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}+02:00"),
5 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}"),
6 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}.5Z"),
_ => format!("{year:04}-{month:02}-{day:02}x"),
};
let fast = IsoDate::parse(&s);
if fast.is_some() {
checked += 1;
assert_eq!(fast, chrono_chain(&s), "{s}");
}
}
assert!(checked > 10_000);
}
}
+975
View File
@@ -0,0 +1,975 @@
pub(crate) use crate::lane::date::duration::Duration;
pub(crate) use crate::lane::date::duration_unit::DurationUnit;
use crate::variable::DynamicVariable;
use crate::Variable;
use chrono::{DateTime, SecondsFormat, Utc};
use chrono_tz::Tz;
use serde_json::Value;
use std::any::Any;
use std::fmt::{Display, Formatter};
use std::rc::Rc;
use std::sync::OnceLock;
mod duration;
mod duration_parser;
mod duration_unit;
pub(crate) mod helpers;
#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Ord, Eq)]
pub(crate) struct Date(pub Option<DateTime<Tz>>);
impl DynamicVariable for Date {
fn type_name(&self) -> &'static str {
"date"
}
fn as_any(&self) -> &dyn Any {
self
}
fn to_value(&self) -> Value {
match self.0 {
None => Value::String(String::from("Invalid date")),
Some(d) => Value::String(d.to_rfc3339_opts(SecondsFormat::Secs, true)),
}
}
}
impl Display for Date {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.0 {
None => write!(f, "Invalid date"),
Some(d) => write!(f, "{}", d.to_rfc3339_opts(SecondsFormat::Secs, true)),
}
}
}
impl From<Option<DateTime<Tz>>> for Date {
fn from(value: Option<DateTime<Tz>>) -> Self {
Self(value)
}
}
struct Formats;
impl Formats {
const CAPACITY: usize = 256;
thread_local! {
static CACHE: std::cell::RefCell<
ahash::HashMap<String, Option<Vec<chrono::format::Item<'static>>>>,
> = Default::default();
}
fn with<T>(format: &str, f: impl FnOnce(Option<&[chrono::format::Item<'static>]>) -> T) -> T {
Self::CACHE.with_borrow_mut(|cache| {
if !cache.contains_key(format) {
if cache.len() >= Self::CAPACITY {
cache.clear();
}
let items = chrono::format::StrftimeItems::new(format)
.parse_to_owned()
.ok();
cache.insert(format.to_string(), items);
}
f(cache.get(format).and_then(|items| items.as_deref()))
})
}
}
impl Date {
pub fn now() -> Self {
Self(Some(helper::now()))
}
pub fn yesterday() -> Self {
Self::now().sub(Duration::day())
}
pub fn tomorrow() -> Self {
Self::now().add(Duration::day())
}
pub fn new(var: Variable, tz_opt: Option<Tz>) -> Self {
Self(helper::parse_date(var, tz_opt))
}
pub(crate) fn text(str: &str, tz_opt: Option<Tz>) -> Self {
Self(helper::parse_str(str, tz_opt.unwrap_or_else(helper::tz)))
}
pub fn is_valid(&self) -> bool {
self.0.is_some()
}
pub fn tz(&self, timezone: Tz) -> Self {
let Some(date_time) = &self.0 else {
return *self;
};
Self(Some(date_time.with_timezone(&timezone)))
}
pub fn format(&self, format: Option<&str>) -> String {
let Some(date_time) = &self.0 else {
return self.to_string();
};
match format {
None => date_time.to_string(),
Some(fmt) => Formats::with(fmt, |items| {
let mut out = String::with_capacity(32);
let written = items.map(|items| {
std::fmt::Write::write_fmt(
&mut out,
format_args!("{}", date_time.format_with_items(items.iter())),
)
});
match written {
Some(Ok(())) => out,
_ => date_time.format(fmt).to_string(),
}
}),
}
}
pub fn add(&self, duration: Duration) -> Self {
let Some(date_time) = &self.0 else {
return Self(None);
};
Self(helper::add_duration(*date_time, duration))
}
pub fn sub(&self, duration: Duration) -> Self {
let Some(date_time) = &self.0 else {
return Self(None);
};
Self(helper::add_duration(*date_time, duration.negate()))
}
pub fn start_of(&self, unit: DurationUnit) -> Self {
let Some(date_time) = &self.0 else {
return Self(None);
};
Self(helper::start_of(*date_time, unit))
}
pub fn end_of(&self, unit: DurationUnit) -> Self {
let Some(date_time) = &self.0 else {
return Self(None);
};
Self(helper::end_of(*date_time, unit))
}
pub fn diff(&self, date_time: &Self, unit: Option<DurationUnit>) -> Option<i64> {
let (dt1, dt2) = match (self.0, date_time.0) {
(Some(a), Some(b)) => (a, b),
_ => return None,
};
helper::diff(dt1, dt2, unit)
}
pub fn set(&self, value: u32, unit: DurationUnit) -> Self {
let Some(date_time) = self.0 else {
return Self(None);
};
Self(helper::set(date_time, value, unit))
}
pub fn is_same(&self, other: &Self, unit: Option<DurationUnit>) -> bool {
let (dt1, dt2) = match (self.0, other.0) {
(Some(a), Some(b)) => (a, b),
_ => return false,
};
helper::is_same(dt1, dt2, unit).unwrap_or(false)
}
pub fn is_before(&self, other: &Self, unit: Option<DurationUnit>) -> bool {
let (dt1, dt2) = match (self.0, other.0) {
(Some(a), Some(b)) => (a, b),
_ => return false,
};
helper::is_before(dt1, dt2, unit).unwrap_or(false)
}
pub fn is_after(&self, other: &Self, unit: Option<DurationUnit>) -> bool {
let (dt1, dt2) = match (self.0, other.0) {
(Some(a), Some(b)) => (a, b),
_ => return false,
};
helper::is_after(dt1, dt2, unit).unwrap_or(false)
}
pub fn is_same_or_before(&self, other: &Self, unit: Option<DurationUnit>) -> bool {
self.is_before(other, unit) || self.is_same(other, unit)
}
pub fn is_same_or_after(&self, other: &Self, unit: Option<DurationUnit>) -> bool {
self.is_after(other, unit) || self.is_same(other, unit)
}
}
mod helper {
use crate::lane::date::{utc_now, Duration, DurationUnit, DynamicVariableExt};
use crate::Variable;
use chrono::{
DateTime, Datelike, Days, FixedOffset, LocalResult, Month, Months, NaiveDate,
NaiveDateTime, Offset, TimeDelta, TimeZone, Timelike,
};
use chrono_tz::Tz;
use rust_decimal::prelude::ToPrimitive;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::OnceLock;
pub(super) fn tz() -> Tz {
static CACHED_TZ: OnceLock<Tz> = OnceLock::new();
*CACHED_TZ.get_or_init(|| {
iana_time_zone::get_timezone()
.ok()
.and_then(|tz| Tz::from_str(&tz).ok())
.unwrap_or(Tz::UTC)
})
}
pub fn now() -> DateTime<Tz> {
now_tz(tz())
}
pub fn now_tz(tz: Tz) -> DateTime<Tz> {
utc_now().with_timezone(&tz)
}
pub fn parse_date(var: Variable, tz_opt: Option<Tz>) -> Option<DateTime<Tz>> {
match var {
Variable::Number(n) => {
let tz = tz_opt.unwrap_or_else(tz);
let n_i64 = n.to_i64()?;
let date_time = match tz.timestamp_millis_opt(n_i64) {
LocalResult::Single(date_time) => date_time,
LocalResult::Ambiguous(date_time, _) => date_time,
LocalResult::None => return None,
};
Some(date_time)
}
Variable::String(str) => parse_str(str.deref(), tz_opt.unwrap_or_else(tz)),
Variable::Dynamic(d) => {
let date = d.as_date()?;
let source = d
.as_any()
.downcast_ref::<crate::vm::VmDate>()
.and_then(|v| v.source());
match (tz_opt, source) {
(Some(tz), Some(text)) => parse_text(text, tz),
(Some(tz), None) => date.0.map(|date_time| date_time.with_timezone(&tz)),
(None, _) => date.0,
}
}
_ => None,
}
}
pub(crate) fn parse_str(str: &str, tz: Tz) -> Option<DateTime<Tz>> {
parse_text(str, tz).or_else(|| zone_now(str))
}
#[cold]
#[inline(never)]
fn zone_now(str: &str) -> Option<DateTime<Tz>> {
Tz::from_str(str).ok().map(now_tz)
}
pub(crate) fn from_text(str: &str) -> Option<DateTime<Tz>> {
parse_text(str, tz())
}
#[inline]
pub(crate) fn parse_text(str: &str, tz: Tz) -> Option<DateTime<Tz>> {
use crate::lane::date::helpers::IsoDate;
match IsoDate::parse(str) {
Some(naive) if IsoDate::utc(str) => Some(tz.from_utc_datetime(&naive)),
Some(naive) => resolve_local(naive, tz),
None => parse_slow(str, tz),
}
}
const LENIENT: [&str; 2] = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"];
const SHAPED: [(&str, &str); 11] = [
("9999-99-99T99:99:99", "%Y-%m-%dT%H:%M:%S%.f"),
("9999-99-99T99:99", "%Y-%m-%dT%H:%M"),
("9999-99-99 99:99:99", "%Y-%m-%d %H:%M:%S%.f"),
("99999999T999999", "%Y%m%dT%H%M%S%.f"),
("99999999T9999", "%Y%m%dT%H%M"),
("9999/99/99 99:99:99", "%Y/%m/%d %H:%M:%S%.f"),
("9999/99/99 99:99", "%Y/%m/%d %H:%M"),
("99999999", "%Y%m%d"),
("9999/99/99", "%Y/%m/%d"),
("9999-99", "%Y-%m"),
("9999", "%Y"),
];
fn shape(value: &str) -> String {
let seconds = value
.rfind('.')
.filter(|&dot| {
dot + 1 < value.len() && value[dot + 1..].bytes().all(|b| b.is_ascii_digit())
})
.map_or(value, |dot| &value[..dot]);
seconds
.chars()
.map(|c| if c.is_ascii_digit() { '9' } else { c })
.collect()
}
fn parse_shaped(value: &str) -> Option<NaiveDateTime> {
let shape = shape(value);
let (_, format) = SHAPED.iter().find(|(pattern, _)| *pattern == shape)?;
match *format {
"%Y" => NaiveDate::from_ymd_opt(value.parse().ok()?, 1, 1)?.and_hms_opt(0, 0, 0),
"%Y-%m" => NaiveDate::parse_from_str(&format!("{value}-01"), "%Y-%m-%d")
.ok()?
.and_hms_opt(0, 0, 0),
format if !format.contains("%H") => NaiveDate::parse_from_str(value, format)
.ok()?
.and_hms_opt(0, 0, 0),
format => NaiveDateTime::parse_from_str(value, format).ok(),
}
}
fn split_offset(value: &str) -> Option<(&str, FixedOffset)> {
if let Some(local) = value.strip_suffix('Z') {
return Some((local, FixedOffset::east_opt(0)?));
}
let time = value.find('T')?;
let sign_at = value[time..].rfind(['+', '-'])? + time;
let digits: String = value[sign_at + 1..].chars().filter(|c| *c != ':').collect();
let valid = matches!(value.len() - sign_at - 1, 2 | 4 | 5)
&& matches!(digits.len(), 2 | 4)
&& digits.bytes().all(|b| b.is_ascii_digit());
if !valid {
return None;
}
let hours: i32 = digits[..2].parse().ok()?;
let minutes: i32 = match &digits[2..] {
"" => 0,
minutes => minutes.parse().ok()?,
};
let sign = if value.as_bytes()[sign_at] == b'-' {
-1
} else {
1
};
let seconds = sign * (hours * 3600 + minutes * 60);
Some((&value[..sign_at], FixedOffset::east_opt(seconds)?))
}
#[inline]
pub(crate) fn resolve_local(naive: NaiveDateTime, tz: Tz) -> Option<DateTime<Tz>> {
tz.from_local_datetime(&naive)
.earliest()
.or_else(|| skip_gap(naive, tz))
}
#[cold]
#[inline(never)]
fn skip_gap(naive: NaiveDateTime, tz: Tz) -> Option<DateTime<Tz>> {
let before = tz
.from_local_datetime(&naive.checked_sub_signed(TimeDelta::hours(3))?)
.earliest()?;
Some(tz.from_utc_datetime(&naive.checked_sub_offset(before.offset().fix())?))
}
#[cold]
#[inline(never)]
pub(crate) fn parse_slow(value: &str, tz: Tz) -> Option<DateTime<Tz>> {
if let Ok(date_time) = DateTime::parse_from_rfc3339(value) {
return Some(date_time.with_timezone(&tz));
}
if let Some(naive) = LENIENT
.iter()
.find_map(|format| NaiveDateTime::parse_from_str(value, format).ok())
.or_else(|| {
NaiveDate::parse_from_str(value, "%Y-%m-%d")
.ok()?
.and_hms_opt(0, 0, 0)
})
{
return resolve_local(naive, tz);
}
match split_offset(value) {
Some((local, offset)) if local.contains('T') => {
let naive = parse_shaped(local)?;
let utc = naive.checked_sub_offset(offset)?;
(utc.year().abs() <= 9999).then(|| tz.from_utc_datetime(&utc))
}
_ => {
let naive = parse_shaped(value)?;
(naive.year().abs() <= 9999).then(|| resolve_local(naive, tz))?
}
}
}
pub fn add_duration(date_time: DateTime<Tz>, duration: Duration) -> Option<DateTime<Tz>> {
let tz = date_time.timezone();
match Calendar::fixed_utc(tz) {
true => Some(tz.from_utc_datetime(&Calendar::shift(date_time.naive_utc(), duration)?)),
false => Calendar::shift(date_time, duration),
}
}
pub fn start_of(date_time: DateTime<Tz>, unit: DurationUnit) -> Option<DateTime<Tz>> {
let tz = date_time.timezone();
match Calendar::fixed_utc(tz) {
true => Some(tz.from_utc_datetime(&Calendar::start_of(date_time.naive_utc(), unit)?)),
false => Calendar::start_of(date_time, unit),
}
}
pub fn end_of(date_time: DateTime<Tz>, unit: DurationUnit) -> Option<DateTime<Tz>> {
let tz = date_time.timezone();
match Calendar::fixed_utc(tz) {
true => Some(tz.from_utc_datetime(&Calendar::end_of(date_time.naive_utc(), unit)?)),
false => Calendar::end_of(date_time, unit),
}
}
pub(crate) trait Clock: Datelike + Timelike + Sized {
fn add_days(self, days: Days) -> Option<Self>;
fn sub_days(self, days: Days) -> Option<Self>;
fn plus(self, delta: TimeDelta) -> Option<Self>;
fn add_months(self, months: Months) -> Option<Self>;
fn sub_months(self, months: Months) -> Option<Self>;
}
impl Clock for DateTime<Tz> {
fn add_days(self, days: Days) -> Option<Self> {
self.checked_add_days(days)
}
fn sub_days(self, days: Days) -> Option<Self> {
self.checked_sub_days(days)
}
fn plus(self, delta: TimeDelta) -> Option<Self> {
self.checked_add_signed(delta)
}
fn add_months(self, months: Months) -> Option<Self> {
self.checked_add_months(months)
}
fn sub_months(self, months: Months) -> Option<Self> {
self.checked_sub_months(months)
}
}
impl Clock for NaiveDateTime {
fn add_days(self, days: Days) -> Option<Self> {
self.checked_add_days(days)
}
fn sub_days(self, days: Days) -> Option<Self> {
self.checked_sub_days(days)
}
fn plus(self, delta: TimeDelta) -> Option<Self> {
self.checked_add_signed(delta)
}
fn add_months(self, months: Months) -> Option<Self> {
self.checked_add_months(months)
}
fn sub_months(self, months: Months) -> Option<Self> {
self.checked_sub_months(months)
}
}
pub(crate) struct Calendar;
impl Calendar {
pub(crate) fn shift<T: Clock>(mut date_time: T, duration: Duration) -> Option<T> {
date_time = date_time.plus(TimeDelta::try_seconds(duration.seconds)?)?;
date_time = match duration.months < 0 {
true => date_time.sub_months(Months::new(duration.months.unsigned_abs()))?,
false => date_time.add_months(Months::new(duration.months.unsigned_abs()))?,
};
date_time.with_year(date_time.year().checked_add(duration.years)?)
}
pub(crate) fn fixed_utc(tz: Tz) -> bool {
matches!(
tz,
Tz::UTC
| Tz::Etc__UTC
| Tz::Etc__GMT
| Tz::GMT
| Tz::Etc__Universal
| Tz::Universal
| Tz::Zulu
| Tz::Etc__Zulu
| Tz::UCT
| Tz::Etc__UCT
)
}
pub(crate) fn start_of<T: Clock>(date_time: T, unit: DurationUnit) -> Option<T> {
Some(match unit {
DurationUnit::Second => date_time.with_nanosecond(0)?,
DurationUnit::Minute => date_time.with_second(0)?.with_nanosecond(0)?,
DurationUnit::Hour => date_time
.with_minute(0)?
.with_second(0)?
.with_nanosecond(0)?,
DurationUnit::Day => date_time
.with_hour(0)?
.with_minute(0)?
.with_second(0)?
.with_nanosecond(0)?,
DurationUnit::Week => {
let weekday = date_time.weekday().num_days_from_monday();
date_time
.sub_days(Days::new(weekday.to_u64()?))?
.with_hour(0)?
.with_minute(0)?
.with_second(0)?
.with_nanosecond(0)?
}
DurationUnit::Month => date_time
.with_day0(0)?
.with_hour(0)?
.with_minute(0)?
.with_second(0)?
.with_nanosecond(0)?,
DurationUnit::Quarter => date_time
.with_month0((date_time.quarter() - 1) * 3)?
.with_day0(0)?
.with_hour(0)?
.with_minute(0)?
.with_second(0)?
.with_nanosecond(0)?,
DurationUnit::Year => date_time
.with_month0(0)?
.with_day0(0)?
.with_hour(0)?
.with_minute(0)?
.with_second(0)?
.with_nanosecond(0)?,
})
}
pub(crate) fn end_of<T: Clock>(mut date_time: T, unit: DurationUnit) -> Option<T> {
date_time = date_time.with_nanosecond(999_999_999)?;
Some(match unit {
DurationUnit::Second => date_time,
DurationUnit::Minute => date_time.with_second(59)?,
DurationUnit::Hour => date_time.with_minute(59)?.with_second(59)?,
DurationUnit::Day => date_time.with_hour(23)?.with_minute(59)?.with_second(59)?,
DurationUnit::Week => {
let days_until_sunday = 6 - date_time.weekday().num_days_from_monday();
date_time
.add_days(Days::new(days_until_sunday.to_u64()?))?
.with_hour(23)?
.with_minute(59)?
.with_second(59)?
}
DurationUnit::Month => {
let month = Month::try_from(date_time.month().to_u8()?).ok()?;
let days_in_month = month.num_days(date_time.year())?.to_u32()?;
date_time
.with_day(days_in_month)?
.with_hour(23)?
.with_minute(59)?
.with_second(59)?
}
DurationUnit::Quarter => {
let new_month_index = date_time.quarter() * 3;
let month = Month::try_from(new_month_index.to_u8()?).ok()?;
let days_in_month = month.num_days(date_time.year())?.to_u32()?;
date_time
.with_month(month.number_from_month())?
.with_day(days_in_month)?
.with_hour(23)?
.with_minute(59)?
.with_second(59)?
}
DurationUnit::Year => {
let year = date_time.year();
let month = Month::December;
let days_in_month = month.num_days(year)?.to_u32()?;
date_time
.with_month(month.number_from_month())?
.with_day(days_in_month)?
.with_hour(23)?
.with_minute(59)?
.with_second(59)?
}
})
}
}
pub fn diff(a: DateTime<Tz>, b: DateTime<Tz>, maybe_unit: Option<DurationUnit>) -> Option<i64> {
let zone_delta = (b.offset().fix().local_minus_utc() as i64
- a.offset().fix().local_minus_utc() as i64)
* 1000;
let diff_ms = a.timestamp_millis() - b.timestamp_millis();
let Some(unit) = maybe_unit else {
return Some(diff_ms);
};
let result = match unit {
DurationUnit::Year => month_diff(a, b) / 12.0,
DurationUnit::Month => month_diff(a, b),
DurationUnit::Quarter => month_diff(a, b) / 3.0,
DurationUnit::Week => {
(diff_ms - zone_delta) as f64 / DurationUnit::Week.as_millis().unwrap_or_default()
}
DurationUnit::Day => {
(diff_ms - zone_delta) as f64 / DurationUnit::Day.as_millis().unwrap_or_default()
}
DurationUnit::Hour => {
diff_ms as f64 / DurationUnit::Hour.as_millis().unwrap_or_default()
}
DurationUnit::Minute => {
diff_ms as f64 / DurationUnit::Minute.as_millis().unwrap_or_default()
}
DurationUnit::Second => {
diff_ms as f64 / DurationUnit::Second.as_millis().unwrap_or_default()
}
};
Some(if result < 0.0 {
result.ceil() as i64
} else {
result.floor() as i64
})
}
pub fn set(date_time: DateTime<Tz>, value: u32, unit: DurationUnit) -> Option<DateTime<Tz>> {
match unit {
DurationUnit::Second => date_time.with_second(value),
DurationUnit::Minute => date_time.with_minute(value),
DurationUnit::Hour => date_time.with_hour(value),
DurationUnit::Day => date_time.with_day(value),
DurationUnit::Month => date_time.with_month(value),
DurationUnit::Year => date_time.with_year(value.to_i32()?),
DurationUnit::Week | DurationUnit::Quarter => Some(date_time),
}
}
pub fn is_same(a: DateTime<Tz>, b: DateTime<Tz>, unit: Option<DurationUnit>) -> Option<bool> {
match unit {
Some(unit) => {
let start_a = start_of(a, unit)?;
let end_a = end_of(a, unit)?;
Some(start_a <= b && b <= end_a)
}
None => Some(a.timestamp_millis() == b.timestamp_millis()),
}
}
pub fn is_before(a: DateTime<Tz>, b: DateTime<Tz>, unit: Option<DurationUnit>) -> Option<bool> {
match unit {
Some(unit) => {
let end_a = end_of(a, unit)?;
Some(end_a < b)
}
None => Some(a < b),
}
}
pub fn is_after(a: DateTime<Tz>, b: DateTime<Tz>, unit: Option<DurationUnit>) -> Option<bool> {
match unit {
Some(unit) => {
let start_a = start_of(a, unit)?;
Some(b < start_a)
}
None => Some(a > b),
}
}
fn month_diff(a: DateTime<Tz>, b: DateTime<Tz>) -> f64 {
if a.day() < b.day() {
return -month_diff(b, a);
}
let whole_month_diff = ((b.year() - a.year()) * 12) + (b.month() as i32 - a.month() as i32);
let anchor = add_months_to_date(a, whole_month_diff);
let c = (b.timestamp_millis() - anchor.timestamp_millis()) < 0;
let anchor2 = add_months_to_date(a, whole_month_diff + if c { -1 } else { 1 });
let numerator = b.timestamp_millis() - anchor.timestamp_millis();
let denominator = if c {
anchor.timestamp_millis() - anchor2.timestamp_millis()
} else {
anchor2.timestamp_millis() - anchor.timestamp_millis()
};
let fractional = if denominator != 0 {
numerator as f64 / denominator as f64
} else {
0.0
};
-((whole_month_diff as f64) + fractional)
}
fn add_months_to_date(date: DateTime<Tz>, months: i32) -> DateTime<Tz> {
if months >= 0 {
date.checked_add_months(Months::new(months as u32))
} else {
date.checked_sub_months(Months::new((-months) as u32))
}
.unwrap_or(date)
}
}
pub(crate) trait DynamicVariableExt {
fn as_date(&self) -> Option<Date>;
}
impl DynamicVariableExt for dyn DynamicVariable {
fn as_date(&self) -> Option<Date> {
let any = self.as_any();
any.downcast_ref::<Date>()
.copied()
.or_else(|| any.downcast_ref::<crate::vm::VmDate>().map(|d| Date(d.0)))
}
}
impl Date {
pub(crate) fn of(v: &Variable) -> Option<Date> {
match v {
Variable::Dynamic(d) => d.as_date(),
_ => None,
}
}
pub(crate) fn variable(self) -> Variable {
Variable::Dynamic(Rc::new(crate::vm::VmDate::from(self.0)))
}
pub(crate) fn coerce(v: &Variable) -> Option<Date> {
match v {
Variable::Dynamic(d) => d.as_date(),
Variable::String(text) => Some(Self::from_text(text)),
_ => None,
}
}
pub(crate) fn parses(text: &str) -> bool {
helper::parse_text(text, helper::tz()).is_some()
}
pub(crate) fn from_text(text: &str) -> Date {
Date(helper::from_text(text))
}
pub(crate) fn matches(&self, other: &Variable) -> bool {
self.0.is_some() && Self::coerce(other).is_some_and(|other| other == *self)
}
pub(crate) fn rendered(&self) -> Option<String> {
self.0
.map(|date_time| date_time.to_rfc3339_opts(SecondsFormat::Secs, true))
}
pub(crate) fn source(v: &Variable) -> Option<&str> {
match v {
Variable::Dynamic(d) => d.as_any().downcast_ref::<crate::vm::VmDate>()?.source(),
_ => None,
}
}
pub(crate) fn sourced(v: &Variable) -> bool {
Self::source(v).is_some()
}
#[inline]
pub(crate) fn textual(v: Variable) -> Variable {
match &v {
Variable::Dynamic(d) => match d.as_text() {
Some(text) => Variable::String(text.into()),
None => v,
},
_ => v,
}
}
}
pub(crate) fn utc_now() -> DateTime<Utc> {
static CURRENT_DATE_VALUE: OnceLock<Option<DateTime<Utc>>> = OnceLock::new();
CURRENT_DATE_VALUE
.get_or_init(|| match std::env::var("__ZEN_MOCK_UTC_TIME") {
Ok(v) => v.parse::<DateTime<Utc>>().ok(),
Err(_) => None,
})
.unwrap_or_else(Utc::now)
}
#[cfg(test)]
mod format_tests {
use super::Date;
use crate::Variable;
#[test]
fn cached_formats_match_chrono() {
let formats = [
"%Y-%m-%d",
"%d/%m/%Y %H:%M:%S",
"%A, %B %e %Y",
"%j %U %W %u",
"%s",
"%+",
"%.3f %Z %z",
"YYYY-MM-DD",
"%%",
"",
"%Y%m%d%H%M%S",
"%-d.%-m.%y",
];
let dates = [
"2025-03-15T10:30:00Z",
"1999-12-31 23:59:59",
"2024-02-29",
"2025-10-26 02:30:00",
];
for date in dates {
let vm = Date::new(Variable::String(date.into()), None);
let Some(dt) = vm.0 else { continue };
for format in formats {
for _ in 0..2 {
assert_eq!(
vm.format(Some(format)),
dt.format(format).to_string(),
"{date} {format}"
);
}
}
}
}
}
#[cfg(test)]
mod parse_tests {
use super::helper::{parse_slow, parse_text};
use chrono_tz::Tz;
#[test]
fn iso_fast_path_agrees_with_text_parsing() {
let mut state = 0x853C49E6748FEA9Bu64;
let mut next = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let zones = [
Tz::UTC,
Tz::Europe__Berlin,
Tz::America__New_York,
Tz::Asia__Kolkata,
];
for _ in 0..200_000 {
let year = 1900 + next(250);
let (month, day) = (next(14), next(33));
let (h, m, sec) = (next(26), next(62), next(62));
let text = match next(7) {
0 => format!("{year:04}-{month:02}-{day:02}"),
1 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}:{sec:02}"),
2 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}Z"),
3 => format!("{year:04}-03-{:02} 02:{m:02}:00", 25 + next(7)),
4 => format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{sec:02}+02:00"),
5 => format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02}"),
_ => format!("{year:04}-{month}-{day}"),
};
let tz = zones[next(zones.len() as u64) as usize];
assert_eq!(
parse_text(&text, tz),
parse_slow(&text, tz),
"{text} {tz}"
);
}
}
}
#[cfg(test)]
mod calendar_tests {
use super::helper::{add_duration, end_of, start_of, Calendar};
use super::DurationUnit;
use chrono::{TimeZone, Utc};
use chrono_tz::Tz;
#[test]
fn fixed_utc_shortcut_matches_chained_steps() {
let units = [
DurationUnit::Second,
DurationUnit::Minute,
DurationUnit::Hour,
DurationUnit::Day,
DurationUnit::Week,
DurationUnit::Month,
DurationUnit::Quarter,
DurationUnit::Year,
];
let mut state = 0x6A09E667F3BCC909u64;
let mut next = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
for _ in 0..50_000 {
let seconds = next(8_000_000_000) as i64 - 2_000_000_000;
let nanos = next(1_000_000_000) as u32;
let Some(instant) = Utc.timestamp_opt(seconds, nanos).single() else {
continue;
};
for tz in [Tz::UTC, Tz::Etc__UTC, Tz::GMT] {
let date_time = instant.with_timezone(&tz);
for unit in units {
assert_eq!(
start_of(date_time, unit),
Calendar::start_of(date_time, unit),
"{date_time} {unit:?}"
);
assert_eq!(
end_of(date_time, unit),
Calendar::end_of(date_time, unit),
"{date_time} {unit:?}"
);
let amount = rust_decimal::Decimal::from(next(80) as i64 - 40);
if let Some(duration) = super::Duration::from_unit(amount, unit) {
assert_eq!(
add_duration(date_time, duration.clone()),
Calendar::shift(date_time, duration),
"{date_time} {amount} {unit:?}"
);
}
}
}
}
}
}
+935
View File
@@ -0,0 +1,935 @@
use super::frame::Fault;
use super::context::Context;
use super::frame::{Frame, Scratch};
use super::Executor;
use crate::functions::ClosureFunction;
use crate::lane::columns::{Column, Values};
use crate::lane::mask::{LaneSet, Lanes, Mask};
use crate::lane::ops::Ops;
use crate::lane::output::Item;
use crate::lane::program::{ClosureOp, Kind, Reg};
use crate::lane::scaled::Scaled;
use crate::variable::Variable;
use crate::vm::VMError;
#[derive(Debug)]
pub(super) enum Pending {
Array(Variable),
Child { start: usize, end: usize },
}
impl Pending {
pub(super) fn len(&self) -> usize {
match self {
Pending::Array(Variable::Array(arr)) => arr.borrow().len(),
Pending::Array(_) => 0,
Pending::Child { start, end } => end - start,
}
}
}
pub(super) type Results<'a> = (
&'a mut [Variable],
&'a [(u32, VMError)],
&'a [u64],
&'a [u64],
);
pub(super) struct Outcomes<'a> {
pub(super) values: &'a mut [Variable],
pub(super) failures: &'a [(u32, VMError)],
pub(super) truths: &'a [u64],
pub(super) settled: &'a [u64],
pub(super) offset: usize,
pub(super) next: usize,
}
impl<'a> Outcomes<'a> {
pub(super) fn new(scratch: Results<'a>, start: usize, end: usize) -> Self {
let (results, failures, truths, settled) = scratch;
let lo = failures.partition_point(|(i, _)| (*i as usize) < start);
let hi = failures.partition_point(|(i, _)| (*i as usize) < end);
Self {
values: &mut results[start..end],
failures: &failures[lo..hi],
truths,
settled,
offset: start,
next: 0,
}
}
pub(super) fn len(&self) -> usize {
self.values.len()
}
pub(super) fn take(&mut self, i: usize) -> Result<Variable, VMError> {
match self.failures.get(self.next) {
Some((at, e)) if *at as usize == self.offset + i => {
self.next += 1;
Err(e.clone())
}
_ => Ok(std::mem::replace(&mut self.values[i], Variable::Null)),
}
}
pub(super) fn tally(&self) -> Option<(usize, usize)> {
let (start, end) = (self.offset, self.offset + self.values.len());
let mut trues = 0usize;
let mut at = start;
while at < end {
let (word, shift) = (at / 64, at % 64);
let take = (64 - shift).min(end - at);
let mask = match take {
64 => u64::MAX,
n => ((1u64 << n) - 1) << shift,
};
if self.settled.get(word).copied().unwrap_or(0) & mask != mask {
return None;
}
trues += (self.truths.get(word).copied().unwrap_or(0) & mask).count_ones() as usize;
at += take;
}
Some((trues, end - start))
}
pub(super) fn decide(&self, kind: ClosureFunction) -> Option<Option<bool>> {
let (trues, len) = self.tally()?;
Some(match kind {
ClosureFunction::Some => (trues > 0).then_some(true),
ClosureFunction::All => (trues < len).then_some(false),
_ => (trues > 0).then_some(false),
})
}
pub(super) fn peek(&mut self, i: usize) -> Result<Option<bool>, VMError> {
let at = self.offset + i;
if Mask::bit(self.settled, at) {
return Ok(Some(Mask::bit(self.truths, at)));
}
match self.failures.get(self.next) {
Some((at, e)) if *at as usize == self.offset + i => {
self.next += 1;
Err(e.clone())
}
_ => Ok(match self.values[i] {
Variable::Bool(b) => Some(b),
_ => None,
}),
}
}
pub(super) fn truth(&mut self, i: usize) -> Result<bool, VMError> {
match self.peek(i)? {
Some(b) => Ok(b),
None => Ops::truthy(&self.take(i)?, "JumpIfFalse"),
}
}
pub(super) fn verdict(
&mut self,
kind: ClosureFunction,
i: usize,
) -> Result<Option<bool>, VMError> {
match (self.peek(i)?, kind) {
(Some(b), ClosureFunction::Some) => Ok(b.then_some(true)),
(Some(b), ClosureFunction::All) => Ok((!b).then_some(false)),
(Some(b), _) => Ok(b.then_some(false)),
(None, _) => Executor::verdict(kind, self.take(i)),
}
}
}
impl Executor {
pub(super) fn ones(words: &[u64], a: usize, b: usize) -> usize {
let mut count = 0usize;
let mut at = a;
while at < b {
let (word, shift) = (at / 64, at % 64);
let take = (64 - shift).min(b - at);
let mask = match take {
64 => u64::MAX,
n => ((1u64 << n) - 1) << shift,
};
count += (words.get(word).copied().unwrap_or(0) & mask).count_ones() as usize;
at += take;
}
count
}
pub(super) fn sweep<M: LaneSet>(
c: &ClosureOp,
active: M,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) -> bool {
if c.sequential || matches!(c.kind, ClosureFunction::FlatMap) || active.is_empty() {
return false;
}
let Some((child, column)) = Self::list_children(c, ctx) else {
return false;
};
let child = &child;
let mut ranges = std::mem::take(&mut f.ranges);
ranges.clear();
ranges.resize(f.width, (0, 0));
let (mut lo, mut hi) = (None, 0usize);
for lane in Lanes::of(active) {
let row = ctx.base + f.rows[lane] as usize;
let Some((a, b)) = column.range(row) else {
return false;
};
match lo {
None => lo = Some(a),
Some(_) if a != hi => return false,
Some(_) => {}
}
ranges[lane] = (a, b);
hi = b;
}
let Some(lo) = lo else {
return false;
};
let total = hi - lo;
let (element, out) = (c.body.element.unwrap_or_default(), c.body.out as usize);
let predicate = !matches!(c.kind, ClosureFunction::Map);
if !predicate && f.kinds[c.dst as usize] != Kind::List {
return false;
}
let items = f.items.len();
let mut scratch = std::mem::take(&mut f.scratch);
let Scratch {
truths,
results,
rows,
parents,
..
} = &mut scratch;
truths.clear();
truths.resize(total.div_ceil(64), 0);
results.clear();
parents.clear();
rows.clear();
let pure = c.imports.is_empty() && c.body.pure();
match pure {
true => rows.extend(0..total.min(M::LANES) as u32),
false => {
for lane in Lanes::of(active) {
let (a, b) = ranges[lane];
parents.extend(std::iter::repeat_n(lane as u32, b - a));
rows.extend(std::iter::repeat_n(f.rows[lane], b - a));
}
}
}
let mut ok = true;
let mut start = 0usize;
while start < total {
let end = (start + M::LANES).min(total);
let width = end - start;
let Some(frame) = rest.first_mut() else {
ok = false;
break;
};
match pure {
true => Self::enter(&c.body, frame, &rows[..end - start], None),
false => Self::enter(
&c.body,
frame,
&rows[start..end],
Some((f, &parents[start..end], &c.imports)),
),
}
if !Self::fill_dense(frame, element, child, lo + start) {
Self::fill_with(frame, element, child, M::all(width), |_, lane| {
lo + start + lane
});
}
Self::execute(&c.body, rest, ctx);
let frame = &mut rest[0];
let all = M::all(width);
if frame.alive & !frame.boxed[out] & all != all {
ok = false;
break;
}
match (predicate, frame.kinds[out]) {
(true, Kind::Bool) => Self::put_bits(truths, start, width, frame.bits[out] & all),
(true, _) => {
ok = false;
break;
}
(false, _) => {
let (kind, base) = (frame.kinds[out], out * frame.width);
let clean = !frame.boxed[out] & !frame.wide[out];
if kind == Kind::Num && clean == M::all(width) {
f.items.extend_nums(
&frame.mant[base..base + width],
&frame.scales[base..base + width],
);
start = end;
continue;
}
for lane in 0..width {
let item = match (kind, clean.get(lane)) {
(Kind::Num, true) => {
Item::Num(frame.mant[base + lane], frame.scales[base + lane])
}
(Kind::Bool, true) => Item::Bool(frame.bits[out].get(lane)),
(Kind::Str, true) => {
let (x, y) = frame.spans[base + lane];
let text =
frame.arena.get(x as usize..y as usize).unwrap_or_default();
let (origin, end) = f.intern(text);
Item::Text(origin, end)
}
_ => Item::Value(frame.take(out as Reg, lane)),
};
f.items.push(item);
}
}
}
start = end;
}
if ok && predicate && !matches!(c.kind, ClosureFunction::Filter) {
let d = c.dst as usize;
let (base, kind) = (d * f.width, f.kinds[d]);
let mut word = f.none();
for lane in Lanes::of(active) {
let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo);
let n = Self::ones(truths, a, b);
match (c.kind, kind) {
(ClosureFunction::Count, Kind::Num) => {
f.mant[base + lane] = n as i64;
f.scales[base + lane] = 0;
}
(
ClosureFunction::One
| ClosureFunction::Some
| ClosureFunction::All
| ClosureFunction::None,
Kind::Bool,
) => word.put(lane, c.kind.holds(n, b - a)),
_ => {}
}
}
match kind {
Kind::Num => f.wide[d] &= !active,
_ => f.bits[d] = (f.bits[d] & !active) | word,
}
f.boxed[d] &= !active;
ok = matches!(kind, Kind::Num | Kind::Bool);
} else if ok && !predicate {
let base = c.dst as usize * f.width;
for lane in Lanes::of(active) {
let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo);
f.lists[base + lane] = ((items + a) as u32, (items + b) as u32);
}
f.boxed[c.dst as usize] &= !active;
} else if ok && f.kinds[c.dst as usize] == Kind::List {
let base = c.dst as usize * f.width;
for lane in Lanes::of(active) {
let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo);
let start = f.items.len() as u32;
match (child.values, child.validity.is_some()) {
(Values::I64(v), false) if lo + b <= v.len() => {
f.items
.extend_selected(v.get(lo..).unwrap_or_default(), truths, a, b)
}
_ => {
for i in (a..b).filter(|i| Mask::bit(truths, *i)) {
let item = Self::child_item(child, lo + i, f);
f.items.push(item);
}
}
}
f.lists[base + lane] = (start, f.items.len() as u32);
}
f.boxed[c.dst as usize] &= !active;
} else if ok {
for lane in Lanes::of(active) {
let (a, b) = (ranges[lane].0 - lo, ranges[lane].1 - lo);
let value = match c.kind {
ClosureFunction::Filter => Variable::from_array(
(a..b)
.filter(|i| Mask::bit(truths, *i))
.map(|i| child.variable(lo + i))
.collect(),
),
kind => {
let n = Self::ones(truths, a, b);
match kind {
ClosureFunction::Count => Variable::Number(n.into()),
kind => Variable::Bool(kind.holds(n, b - a)),
}
}
};
f.set(c.dst, lane, value);
}
}
if !ok {
f.items.truncate(items);
}
f.scratch = scratch;
f.ranges = ranges;
ok
}
pub(super) fn child_item<M: LaneSet>(child: &Column, index: usize, f: &mut Frame<M>) -> Item {
match (child.values, child.valid(index)) {
(Values::I64(v), true) => v
.get(index)
.map_or(Item::Value(Variable::Null), |n| Item::Num(*n, 0)),
(Values::Dec(v), true) => match v.get(index).and_then(Scaled::parts) {
Some((m, s)) => Item::Num(m, s),
None => Item::Value(child.variable(index)),
},
(Values::Utf8 { .. } | Values::Text { .. } | Values::LargeUtf8 { .. } | Values::Strs(_), true) => {
match child.text(index) {
Some(text) => {
let (origin, end) = f.intern(text);
Item::Text(origin, end)
}
None => Item::Value(child.variable(index)),
}
}
_ => Item::Value(child.variable(index)),
}
}
pub(super) fn closure<M: LaneSet>(
c: &ClosureOp,
active: M,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) {
if Self::sweep(c, active, f, rest, ctx) {
return;
}
let decisive = matches!(
c.kind,
ClosureFunction::Some | ClosureFunction::All | ClosureFunction::None
);
if decisive {
return Self::decisive(c, active, f, rest, ctx);
}
let mut scratch = std::mem::take(&mut f.scratch);
scratch.items.clear();
scratch.slots.clear();
scratch.spans.clear();
let children = Self::list_children(c, ctx);
if let Some((child, column)) = children {
let child = &child;
let lanes = Lanes::of(active).filter(|lane| {
let row = ctx.base + f.rows[*lane] as usize;
column.range(row).is_some()
});
let covered = lanes.fold(f.none(), |mut acc, lane| {
acc.set(lane);
acc
});
if covered == active {
for lane in Lanes::of(active) {
let row = ctx.base + f.rows[lane] as usize;
let (a, b) = column
.range(row)
.map_or((0, 0), |(a, b)| (a as u32, b as u32));
let start = scratch.slots.len();
scratch.slots.extend((a..b).map(|i| (lane as u32, i)));
scratch.spans.push((lane, start, scratch.slots.len()));
}
Self::body(c, &mut scratch, Some(child), f, rest, ctx);
let Scratch {
slots,
spans,
results,
failures,
truths,
settled,
..
} = &mut scratch;
for (lane, start, end) in spans.iter().copied() {
let out = Outcomes::new((results, failures, truths, settled), start, end);
let r =
Self::finish(c.kind, out, |i| child.variable(slots[start + i].1 as usize));
f.put(c.dst, lane, r);
}
f.scratch = scratch;
return;
}
}
for lane in Lanes::of(active) {
if let Some((child, column)) = children {
let child = &child;
let row = ctx.base + f.rows[lane] as usize;
if let Some((a, b)) = column.range(row) {
let start = scratch.items.len();
scratch
.items
.extend((a..b).map(|i| (lane as u32, child.variable(i))));
scratch.spans.push((lane, start, scratch.items.len()));
continue;
}
}
match Self::list_of(c, lane, f, ctx) {
Ok(Variable::Array(arr)) => {
let start = scratch.items.len();
scratch
.items
.extend(arr.borrow().iter().map(|v| (lane as u32, v.clone())));
scratch.spans.push((lane, start, scratch.items.len()));
}
Ok(_) => f.fail(lane, Ops::error("Begin", "Unsupported type")),
Err(e) => f.fail(lane, e),
}
}
Self::body(c, &mut scratch, None, f, rest, ctx);
let Scratch {
items,
spans,
results,
failures,
truths,
settled,
..
} = &mut scratch;
for (lane, start, end) in spans.iter().copied() {
let out = Outcomes::new((results, failures, truths, settled), start, end);
let r = Self::finish(c.kind, out, |i| items[start + i].1.clone());
f.put(c.dst, lane, r);
}
f.scratch = scratch;
}
pub(super) fn body<M: LaneSet>(
c: &ClosureOp,
scratch: &mut Scratch,
column: Option<&Column>,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) {
let element = c.body.element.unwrap_or_default();
let out = c.body.out;
let chunk = if c.sequential { 1 } else { M::LANES };
let keep = matches!(c.kind, ClosureFunction::Filter);
let Scratch {
items,
slots,
results,
failures,
rows,
parents,
truths,
settled,
..
} = scratch;
results.clear();
failures.clear();
let total = match column {
Some(_) => slots.len(),
None => items.len(),
};
let predicate = !matches!(c.kind, ClosureFunction::Map | ClosureFunction::FlatMap);
let words = total.div_ceil(64);
for bits in [&mut *truths, &mut *settled] {
bits.clear();
bits.resize(words, 0);
}
let mut start = 0;
while start < total {
let end = (start + chunk).min(total);
let width = end - start;
rows.clear();
parents.clear();
for j in start..end {
let parent = match column {
Some(_) => slots[j].0,
None => items[j].0,
};
parents.push(parent);
rows.push(f.rows[parent as usize]);
}
let Some(child) = rest.first_mut() else {
break;
};
Self::enter(&c.body, child, rows, Some((f, parents, &c.imports)));
match column {
Some(column) => {
let slots = &slots[start..end];
Self::fill_with(child, element, column, M::all(width), |_, lane| {
slots[lane].1 as usize
});
}
None => {
for (lane, (_, value)) in items[start..end].iter_mut().enumerate() {
let value = match keep {
true => value.clone(),
false => std::mem::replace(value, Variable::Null),
};
child.set(element, lane, value);
}
}
}
Self::execute(&c.body, rest, ctx);
let child = &mut rest[0];
let o = out as usize;
let (kind, boxed, bits) = (child.kinds[o], child.boxed[o], child.bits[o]);
let ok = match (predicate, kind) {
(true, Kind::Bool) => child.alive & !boxed & M::all(width),
_ => f.none(),
};
Self::put_bits(settled, start, width, ok);
Self::put_bits(truths, start, width, bits & ok);
for lane in 0..width {
if ok.get(lane) {
results.push(Variable::Null);
continue;
}
if !child.alive.get(lane) {
results.push(Variable::Null);
let e = child.errors[lane]
.take().map(Fault::vm)
.unwrap_or(VMError::NumberConversionError);
failures.push(((start + lane) as u32, e));
continue;
}
results.push(match (kind, boxed.get(lane)) {
(Kind::Bool, false) => Variable::Bool(bits.get(lane)),
(Kind::Num, false) => Variable::Number(child.number(out, lane)),
_ => child.take(out, lane),
});
}
start = end;
}
}
#[inline]
pub(super) fn put_bits<M: LaneSet>(words: &mut [u64], start: usize, width: usize, value: M) {
for i in 0..width.div_ceil(64) {
let chunk = (width - i * 64).min(64);
let bits = value.word(i);
let at = start + i * 64;
let (word, shift) = (at / 64, at % 64);
if let Some(w) = words.get_mut(word) {
*w |= bits << shift;
}
if shift > 0 && shift + chunk > 64 {
if let Some(w) = words.get_mut(word + 1) {
*w |= bits >> (64 - shift);
}
}
}
}
pub(super) fn decisive<M: LaneSet>(
c: &ClosureOp,
active: M,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) {
if active.count() == 1 {
let lane = active.first().unwrap_or_default();
let r = match Self::list_of(c, lane, f, ctx) {
Ok(list @ Variable::Array(_)) => Self::single(c, lane, &list, f, rest, ctx),
Ok(_) => Err(Ops::error("Begin", "Unsupported type")),
Err(e) => Err(e),
};
f.put(c.dst, lane, r);
return;
}
let mut scratch = std::mem::take(&mut f.scratch);
let mut lists = std::mem::take(&mut scratch.lists);
let mut done = std::mem::take(&mut scratch.done);
lists.clear();
let children = Self::list_children(c, ctx);
for lane in Lanes::of(active) {
if let Some((_, column)) = children {
let row = ctx.base + f.rows[lane] as usize;
if let Some((a, b)) = column.range(row) {
lists.push((lane, Pending::Child { start: a, end: b }, 0));
continue;
}
}
match Self::list_of(c, lane, f, ctx) {
Ok(list @ Variable::Array(_)) => lists.push((lane, Pending::Array(list), 0)),
Ok(_) => f.fail(lane, Ops::error("Begin", "Unsupported type")),
Err(e) => f.fail(lane, e),
}
}
if lists.len() == 1 && matches!(lists.first(), Some((_, Pending::Array(_), _))) {
if let Some((lane, Pending::Array(list), _)) = lists.pop() {
let r = Self::single(c, lane, &list, f, rest, ctx);
f.put(c.dst, lane, r);
}
scratch.lists = lists;
scratch.done = done;
f.scratch = scratch;
return;
}
let typed = match children {
Some(_) => lists
.iter()
.all(|(_, list, _)| matches!(list, Pending::Child { .. })),
None => false,
};
let column = children.filter(|_| typed).map(|(child, _)| child);
let mut step = 1usize;
while !lists.is_empty() {
scratch.items.clear();
scratch.slots.clear();
scratch.spans.clear();
for (index, (lane, list, next)) in lists.iter().enumerate() {
let end = (*next + step).min(list.len());
let (start, stop) = match (list, children) {
(Pending::Array(Variable::Array(arr)), _) => {
let arr = arr.borrow();
let start = scratch.items.len();
scratch
.items
.extend(arr[*next..end].iter().map(|v| (*lane as u32, v.clone())));
(start, scratch.items.len())
}
(Pending::Child { start: base, .. }, Some(_)) if typed => {
let start = scratch.slots.len();
let (a, b) = ((base + *next) as u32, (base + end) as u32);
scratch.slots.extend((a..b).map(|i| (*lane as u32, i)));
(start, scratch.slots.len())
}
(Pending::Child { start: base, .. }, Some((child, _))) => {
let start = scratch.items.len();
scratch.items.extend(
(base + *next..base + end).map(|i| (*lane as u32, child.variable(i))),
);
(start, scratch.items.len())
}
_ => continue,
};
scratch.spans.push((index, start, stop));
}
Self::body(c, &mut scratch, column.as_ref(), f, rest, ctx);
done.clear();
for (index, start, end) in scratch.spans.iter().copied() {
let (lane, list, next) = &mut lists[index];
let mut decided = None;
let results = (
scratch.results.as_mut_slice(),
scratch.failures.as_slice(),
scratch.truths.as_slice(),
scratch.settled.as_slice(),
);
let mut out = Outcomes::new(results, start, end);
let settled = out.decide(c.kind);
if let Some(verdict) = settled {
decided = verdict.map(|b| Ok(Variable::Bool(b)));
}
for i in (0..out.len()).filter(|_| settled.is_none()) {
match out.verdict(c.kind, i) {
Ok(Some(b)) => {
decided = Some(Ok(Variable::Bool(b)));
break;
}
Ok(None) => {}
Err(e) => {
decided = Some(Err(e));
break;
}
}
}
let len = list.len();
*next += end - start;
let decided = decided.or_else(|| {
(*next >= len)
.then(|| Ok(Variable::Bool(!matches!(c.kind, ClosureFunction::Some))))
});
if let Some(r) = decided {
f.put(c.dst, *lane, r);
done.push(index);
}
}
done.iter().rev().for_each(|i| {
lists.swap_remove(*i);
});
if !c.sequential {
step = match column {
Some(_) => M::LANES,
None => (step * 8).min(M::LANES),
};
}
}
scratch.lists = lists;
scratch.done = done;
f.scratch = scratch;
}
pub(super) fn list_children<'c>(
c: &ClosureOp,
ctx: &Context<'c>,
) -> Option<(Column<'c>, Column<'c>)> {
let (_, site) = c.source.as_ref()?;
match ctx.column(*site) {
Some(Some(column)) => match column.values {
Values::List { child, .. } => Some((child.column(), *column)),
_ => None,
},
_ => None,
}
}
pub(super) fn list_of<M: LaneSet>(
c: &ClosureOp,
lane: usize,
f: &mut Frame<M>,
ctx: &Context,
) -> Result<Variable, VMError> {
let Some((load, site)) = &c.source else {
return f.with(c.list, lane, Ops::elements);
};
let value = match ctx.column(*site) {
Some(Some(column)) => column.variable(ctx.base + f.rows[lane] as usize),
Some(None) => Variable::Null,
None => Self::row_value(load, *site, lane, f, ctx)?,
};
Ops::elements(&value)
}
pub(super) fn single<M: LaneSet>(
c: &ClosureOp,
lane: usize,
list: &Variable,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) -> Result<Variable, VMError> {
let fallback = Ok(Variable::Bool(!matches!(c.kind, ClosureFunction::Some)));
let Variable::Array(arr) = list else {
return fallback;
};
let len = arr.borrow().len();
if len == 0 {
return fallback;
}
let element = c.body.element.unwrap_or_default();
let (rows, parents) = ([f.rows[lane]], [lane as u32]);
let Some(child) = rest.first_mut() else {
return fallback;
};
Self::enter(&c.body, child, &rows, Some((f, &parents, &c.imports)));
for i in 0..len {
let Some(item) = arr.borrow().get(i).cloned() else {
break;
};
let child = &mut rest[0];
child.restart();
child.set(element, 0, item);
Self::execute(&c.body, rest, ctx);
let child = &mut rest[0];
let r = match child.alive.get(0) {
true => Ok(child.take(c.body.out, 0)),
_ => Err(child.errors[0]
.take().map(Fault::vm)
.unwrap_or(VMError::NumberConversionError)),
};
if let Some(b) = Self::verdict(c.kind, r)? {
return Ok(Variable::Bool(b));
}
}
fallback
}
pub(super) fn finish(
kind: ClosureFunction,
mut out: Outcomes,
item: impl Fn(usize) -> Variable,
) -> Result<Variable, VMError> {
match kind {
ClosureFunction::Map | ClosureFunction::FlatMap => {
if let Some((_, e)) = out.failures.first() {
return Err(e.clone());
}
let values: Vec<Variable> = out
.values
.iter_mut()
.map(|v| std::mem::replace(v, Variable::Null))
.collect();
match kind {
ClosureFunction::Map => Ok(Variable::from_array(values)),
_ => Ops::flatten(Variable::from_array(values)),
}
}
ClosureFunction::Filter => {
let mut kept = Vec::new();
for i in 0..out.len() {
if out.truth(i)? {
kept.push(item(i));
}
}
Ok(Variable::from_array(kept))
}
ClosureFunction::Count | ClosureFunction::One => {
let count = match out.tally() {
Some((trues, _)) => trues,
None => {
let mut count = 0usize;
for i in 0..out.len() {
if out.truth(i)? {
count += 1;
}
}
count
}
};
Ok(match kind {
ClosureFunction::One => Variable::Bool(count == 1),
_ => Variable::Number(count.into()),
})
}
ClosureFunction::All | ClosureFunction::Some | ClosureFunction::None
if out.tally().is_some() =>
{
let decided = out.decide(kind).flatten();
Ok(Variable::Bool(
decided.unwrap_or(!matches!(kind, ClosureFunction::Some)),
))
}
ClosureFunction::All | ClosureFunction::Some | ClosureFunction::None => {
for i in 0..out.len() {
if let Some(b) = out.verdict(kind, i)? {
return Ok(Variable::Bool(b));
}
}
Ok(Variable::Bool(!matches!(kind, ClosureFunction::Some)))
}
}
}
pub(super) fn verdict(
kind: ClosureFunction,
r: Result<Variable, VMError>,
) -> Result<Option<bool>, VMError> {
r.and_then(|v| match kind {
ClosureFunction::Some => Ops::truthy(&v, "JumpIfTrue").map(|t| t.then_some(true)),
ClosureFunction::All => Ops::truthy(&v, "JumpIfFalse").map(|t| (!t).then_some(false)),
_ => Ops::not(v)
.and_then(|n| Ops::truthy(&n, "JumpIfFalse"))
.map(|t| (!t).then_some(false)),
})
}
}
impl ClosureFunction {
pub(super) fn holds(self, trues: usize, total: usize) -> bool {
match self {
ClosureFunction::One => trues == 1,
ClosureFunction::Some => trues > 0,
ClosureFunction::All => trues == total,
_ => trues == 0,
}
}
}
+77
View File
@@ -0,0 +1,77 @@
use crate::lane::columns::{Column, Columns};
use crate::lane::program::{Binding, Program};
use crate::scope::Scope;
pub enum Envs<'a> {
Shared(&'a [Scope]),
Owned(Vec<Scope>),
}
impl Envs<'_> {
#[inline]
pub(super) fn get(&self, row: u32) -> &Scope {
match self {
Envs::Shared(s) => &s[row as usize],
Envs::Owned(s) => &s[row as usize],
}
}
pub(super) fn get_mut(&mut self, row: u32) -> Option<&mut Scope> {
match self {
Envs::Shared(_) => None,
Envs::Owned(s) => s.get_mut(row as usize),
}
}
}
pub struct Context<'a> {
pub roots: Envs<'a>,
pub envs: Envs<'a>,
pub columns: Option<&'a Columns<'a>>,
pub bound: &'a [Binding],
pub base: usize,
}
impl<'a> Context<'a> {
pub fn new(program: &Program, roots: &'a [Scope]) -> Self {
let envs = match program.writes_env {
true => Envs::Owned(roots.to_vec()),
false => Envs::Shared(roots),
};
let roots = match program.chain {
true => Envs::Owned(roots.to_vec()),
false => Envs::Shared(roots),
};
Self {
roots,
envs,
columns: None,
bound: &[],
base: 0,
}
}
pub fn columnar(
program: &Program,
roots: &'a [Scope],
columns: &'a Columns<'a>,
bound: &'a [Binding],
base: usize,
) -> Self {
let mut ctx = Self::new(program, roots);
ctx.columns = Some(columns);
ctx.bound = bound;
ctx.base = base;
ctx
}
#[inline]
pub(super) fn column(&self, site: u16) -> Option<Option<&'a Column<'a>>> {
let columns = self.columns?;
match self.bound.get(site as usize)? {
Binding::Column(index) => Some(columns.columns.get(*index).map(|(_, c)| c)),
Binding::Absent => Some(None),
Binding::Row => None,
}
}
}
+115
View File
@@ -0,0 +1,115 @@
use super::frame::Frame;
use super::Executor;
use crate::functions::{FunctionKind, InternalFunction, MethodKind};
use crate::lane::builtins::{Arg, Dates};
use crate::lane::date::Date;
use crate::lane::mask::{LaneSet, Lanes};
use crate::lane::program::{Input, Kind, Reg};
use std::str::FromStr;
impl Executor {
pub(super) fn date_call<M: LaneSet>(
dst: Reg,
kind: &FunctionKind,
args: &[Input],
active: M,
f: &mut Frame<M>,
) -> M {
let mut done = f.none();
let zone = match (kind, args) {
(FunctionKind::Internal(InternalFunction::Date), [Input::Reg(_)]) => None,
(FunctionKind::Internal(InternalFunction::Date), [Input::Reg(_), Input::Const(id)]) => {
match f.consts[*id as usize].as_str().map(chrono_tz::Tz::from_str) {
Some(Ok(zone)) => Some(zone),
_ => return done,
}
}
_ => return done,
};
let Some(Input::Reg(a)) = args.first().copied() else {
return done;
};
if f.kind(a) != Kind::Str || f.kind(dst) != Kind::Date {
return done;
}
let mut last: Option<((u32, u32), Date)> = None;
for lane in Lanes::of(active & !f.boxed[a as usize]) {
let span = f.spans[f.at(a, lane)];
let text = f
.arena
.get(span.0 as usize..span.1 as usize)
.unwrap_or_default();
let date = match &last {
Some((prev, date))
if f.arena.get(prev.0 as usize..prev.1 as usize) == Some(text) =>
{
*date
}
_ => Date::text(text, zone),
};
let at = f.at(dst, lane);
f.dates[at] = date;
f.boxed[dst as usize].unset(lane);
last = Some((span, date));
done.set(lane);
}
done
}
pub(super) fn date_method<M: LaneSet>(
dst: Reg,
kind: &MethodKind,
args: &[Input],
active: M,
f: &mut Frame<M>,
) -> M {
let mut done = f.none();
match (args, f.kind(dst)) {
([Input::Reg(this)], Kind::Num) if f.kind(*this) == Kind::Date => {
for lane in Lanes::of(active & !f.boxed[*this as usize]) {
let date = &f.dates[f.at(*this, lane)];
if let Some(n) = Dates::part_of(kind, date) {
f.put_scaled(dst, lane, n, 0);
done.set(lane);
}
}
}
([Input::Reg(this), rest @ ..], Kind::Date)
if f.kind(*this) == Kind::Date
&& rest.iter().all(|a| matches!(a, Input::Const(_))) =>
{
let consts: smallvec::SmallVec<[Arg; 4]> = std::iter::once(Arg::Null)
.chain(rest.iter().map(|a| match a {
Input::Const(id) => Arg::of(&f.consts[*id as usize]),
Input::Reg(_) => Arg::Null,
}))
.collect();
let Some(shift) = Dates::shift(kind, &consts) else {
return done;
};
for lane in Lanes::of(active & !f.boxed[*this as usize]) {
let date = shift.apply(&f.dates[f.at(*this, lane)]);
let at = f.at(dst, lane);
f.dates[at] = date;
f.boxed[dst as usize].unset(lane);
done.set(lane);
}
}
([Input::Reg(this), Input::Reg(other)], Kind::Bool)
if f.kind(*this) == Kind::Date && f.kind(*other) == Kind::Date =>
{
let lanes = active & !f.boxed[*this as usize] & !f.boxed[*other as usize];
for lane in Lanes::of(lanes) {
let (x, y) = (&f.dates[f.at(*this, lane)], &f.dates[f.at(*other, lane)]);
if let Some(hit) = Dates::order(kind, x, y) {
f.bits[dst as usize].put(lane, hit);
f.boxed[dst as usize].unset(lane);
done.set(lane);
}
}
}
_ => {}
}
done
}
}
+405
View File
@@ -0,0 +1,405 @@
use super::frame::Fault;
use super::frame::Frame;
use crate::lane::mask::{LaneSet, Lanes};
use crate::lane::output::{Output, Shape};
use crate::lane::program::{Kind, Layout, Program, Reg};
use crate::variable::Variable;
use crate::vm::VMError;
use std::rc::Rc;
use zen_types::symbol::Symbol;
use zen_types::variable::Shape as MapShape;
impl<M: LaneSet> Frame<M> {
pub(super) fn collect_shapes(layout: &Layout, out: &mut Vec<Option<Rc<MapShape>>>) {
match layout {
Layout::Value(_) => {}
Layout::Struct(fields) => {
let keys: Vec<Symbol> = fields
.iter()
.rev()
.map(|(key, _)| Symbol::from(key.as_ref()))
.collect();
let distinct = keys
.iter()
.enumerate()
.all(|(i, k)| keys[..i].iter().all(|x| x.as_str() != k.as_str()));
out.push(
(distinct && keys.len() <= 32)
.then(|| MapShape::of(keys.iter()))
.flatten(),
);
fields
.iter()
.rev()
.for_each(|(_, field)| Self::collect_shapes(field, out));
}
Layout::List(items) => items
.iter()
.for_each(|item| Self::collect_shapes(item, out)),
}
}
pub(super) fn assemble_taken(
&mut self,
layout: &Layout,
lane: usize,
mut next: Option<&mut usize>,
) -> Variable {
match layout {
Layout::Value(reg) => self.take(*reg, lane),
Layout::Struct(fields) => {
let shape = next.as_deref_mut().and_then(|n| {
*n += 1;
self.shapes.get(*n - 1).cloned().flatten()
});
if let Some(shape) = shape {
let values: Vec<Variable> = fields
.iter()
.rev()
.map(|(_, f)| self.assemble_taken(f, lane, next.as_deref_mut()))
.collect();
return Variable::from_object(crate::variable::VariableMap::from_shape(
shape, values,
));
}
let mut map = crate::variable::VariableMap::with_capacity(fields.len());
for (key, field) in fields.iter().rev() {
let value = self.assemble_taken(field, lane, next.as_deref_mut());
map.insert(Symbol::from(key.as_ref()), value);
}
Variable::from_object(map)
}
Layout::List(items) => {
let values = items
.iter()
.map(|i| self.assemble_taken(i, lane, next.as_deref_mut()))
.collect();
Variable::from_array(values)
}
}
}
pub(super) fn cell(
&mut self,
layout: &Layout,
lane: usize,
out: &mut Output,
at: usize,
failed: bool,
) {
if failed {
out.fail_at(at);
}
match (layout, &mut out.shape) {
(Layout::Struct(fields), Shape::Struct(outputs)) => {
for ((_, field), (_, output)) in fields.iter().zip(outputs.iter_mut()) {
self.cell(field, lane, output, at, failed);
}
}
(Layout::List(items), Shape::List(child)) => {
let width = items.len();
for (i, item) in items.iter().enumerate() {
self.cell(item, lane, child, at * width + i, failed);
}
}
_ if failed => {}
(Layout::Value(reg), Shape::Scalar) => self.scalar(*reg, lane, out, at),
(layout, _) => {
let value = self.assemble_taken(layout, lane, None);
match out.kind() {
Kind::Dyn => out.values[at] = value,
_ => out.box_at(at, value),
}
}
}
}
pub(super) fn scalar(&mut self, reg: Reg, lane: usize, out: &mut Output, at: usize) {
let kind = out.kind();
if kind == Kind::Dyn {
out.values[at] = self.take(reg, lane);
return;
}
let wide = kind == Kind::Num && self.wide[reg as usize].get(lane);
if self.kind(reg) != kind || self.boxed[reg as usize].get(lane) || wide {
let value = self.take(reg, lane);
out.box_at(at, value);
return;
}
let i = self.at(reg, lane);
match kind {
Kind::Num => {
out.mant[at] = self.mant[i];
out.scale[at] = self.scales[i];
}
Kind::Bool => out.set_bit(at, self.bits[reg as usize].get(lane)),
Kind::Date => out.dates[at] = self.dates[i].0,
Kind::List => self.push_list(i, out),
_ => {
let (a, b) = self.spans[i];
out.push_text(self.arena.get(a as usize..b as usize).unwrap_or_default());
}
}
}
pub(super) fn bulk_lists(&self, base: usize, n: usize, out: &mut Output) -> bool {
let Some(spans) = self.lists.get(base..base + n) else {
return false;
};
let Some((a, b)) = Self::block(spans) else {
return false;
};
let Some((mant, scales)) = self.items.numbers(a, b) else {
return false;
};
out.extend_lists(mant, scales, spans.iter().map(|(_, end)| end - a as u32))
}
pub(super) fn push_list(&self, at: usize, out: &mut Output) {
let (a, b) = self.lists[at];
if let Shape::List(child) = &mut out.shape {
match self.items.numbers(a as usize, b as usize) {
Some((mant, scales)) => child.extend_nums(mant, scales),
None => {
for i in a as usize..b as usize {
child.push_item(&self.items.get(i), &self.arena);
}
}
}
}
out.close();
}
pub fn export(&mut self, program: &Program, out: &mut Output, start: usize, n: usize) {
let failed = !self.alive & M::all(n);
match &program.layout {
Some(layout) => self.export_shape(layout, out, start, n, failed),
None => self.export_value(program.out, out, start, n, failed),
}
for lane in Lanes::of(failed) {
let fault = self.errors[lane]
.take()
.unwrap_or(Fault::Vm(VMError::NumberConversionError));
out.errors.push(((start + lane) as u32, crate::lane::output::Failure::new(fault)));
}
}
pub fn export_outputs(
&mut self,
program: &Program,
outs: &mut [Output],
start: usize,
n: usize,
mut failure: impl FnMut(usize, usize, Fault),
) {
if program.isolated {
self.revive();
}
let failed = !self.alive & M::all(n);
match (program.outputs.is_empty(), &program.layout, outs.first_mut()) {
(true, Some(layout), Some(out)) => self.export_shape(layout, out, start, n, failed),
(true, None, Some(out)) => self.export_value(program.out, out, start, n, failed),
_ => {
for (reg, out) in program.outputs.iter().zip(outs.iter_mut()) {
self.export_value(*reg, out, start, n, failed);
}
}
}
for (lane, stage, fault) in self.soft.drain(..) {
failure(start + lane, stage as usize, fault);
}
for lane in Lanes::of(failed) {
let fault = self.errors[lane]
.take()
.unwrap_or(Fault::Vm(VMError::NumberConversionError));
failure(start + lane, self.stages[lane] as usize, fault);
}
}
pub(super) fn export_shape(
&mut self,
layout: &Layout,
out: &mut Output,
start: usize,
n: usize,
failed: M,
) {
if let Layout::Value(reg) = layout {
if out.kind() == self.kinds[*reg as usize] && !matches!(out.shape, Shape::Struct(_)) {
return self.export_value(*reg, out, start, n, failed);
}
}
match (layout, &mut out.shape) {
(Layout::Struct(fields), Shape::Struct(outputs)) => {
for ((_, field), (_, output)) in fields.iter().zip(outputs.iter_mut()) {
self.export_shape(field, output, start, n, failed);
}
(failed).store(&mut out.failed, start / 64);
}
(Layout::List(items), Shape::List(child))
if failed.is_empty() && self.strided(items, child.kind(), n) =>
{
let width = items.len();
for (i, item) in items.iter().enumerate() {
let Layout::Value(reg) = item else {
continue;
};
let base = *reg as usize * self.width;
for lane in 0..n {
let at = (start + lane) * width + i;
match child.kind() {
Kind::Num => {
child.mant[at] = self.mant[base + lane];
child.scale[at] = self.scales[base + lane];
}
_ => child.set_bit(at, self.bits[*reg as usize].get(lane)),
}
}
}
}
_ => {
for lane in 0..n {
self.cell(layout, lane, out, start + lane, failed.get(lane));
}
}
}
}
pub(super) fn strided(&self, items: &[Layout], kind: Kind, n: usize) -> bool {
let lanes = M::all(n);
matches!(kind, Kind::Num | Kind::Bool)
&& items.iter().all(|item| match item {
Layout::Value(reg) => {
let r = *reg as usize;
self.kinds[r] == kind && ((self.boxed[r] | self.wide[r]) & lanes).is_empty()
}
_ => false,
})
}
pub(super) fn export_value(
&mut self,
reg: Reg,
out: &mut Output,
start: usize,
n: usize,
failed: M,
) {
let r = reg as usize;
let word = start / 64;
let lanes = M::all(n);
let base = r * self.width;
let boxed = match self.kinds[r] {
Kind::Num => {
out.mant[start..start + n].copy_from_slice(&self.mant[base..base + n]);
out.scale[start..start + n].copy_from_slice(&self.scales[base..base + n]);
(self.boxed[r] | self.wide[r]) & lanes & !failed
}
Kind::Bool => {
(self.bits[r] & lanes & !failed).store(&mut out.bits, word);
self.boxed[r] & lanes & !failed
}
Kind::Dyn => {
for lane in Lanes::of(lanes & !failed) {
out.values[start + lane] = self.take(reg, lane);
}
self.none()
}
Kind::List => {
let boxed = self.boxed[r] & lanes & !failed;
let plain = lanes & !failed & !boxed;
if plain != lanes || !self.bulk_lists(base, n, out) {
for lane in 0..n {
match plain.get(lane) {
true => self.push_list(base + lane, out),
_ => out.close(),
}
}
}
boxed
}
Kind::Date => {
for (o, d) in out.dates[start..start + n]
.iter_mut()
.zip(&self.dates[base..base + n])
{
*o = d.0;
}
self.boxed[r] & lanes & !failed
}
Kind::Str => {
let boxed = self.boxed[r] & lanes & !failed;
let spans = &self.spans[base..base + n];
let clean = failed.is_empty() && boxed.is_empty();
if let (true, Some(first)) = (clean, spans.first().copied()) {
if spans.iter().all(|span| *span == first) {
let text = self
.arena
.get(first.0 as usize..first.1 as usize)
.unwrap_or_default()
.as_bytes();
let origin = out.data.len();
out.data.extend_from_slice(text);
while out.data.len() - origin < text.len() * n {
let have = out.data.len() - origin;
let take = have.min(text.len() * n - have);
out.data.extend_from_within(origin..origin + take);
}
out.offsets
.extend((1..=n).map(|i| (origin + i * text.len()) as u32));
return self.export_rest(out, start, failed, self.none(), reg);
}
}
if let (true, Some((a, b))) = (clean, Self::block(spans)) {
if let Some(text) = self.arena.get(a..b) {
let shift = out.data.len() as i64 - a as i64;
out.data.extend_from_slice(text.as_bytes());
out.offsets
.extend(spans.iter().map(|(_, end)| (*end as i64 + shift) as u32));
return self.export_rest(out, start, failed, self.none(), reg);
}
}
let plain = lanes & !failed & !boxed;
for lane in 0..n {
if plain.get(lane) {
let (a, b) = self.spans[base + lane];
if let Some(text) = self.arena.get(a as usize..b as usize) {
out.data.extend_from_slice(text.as_bytes());
}
}
out.offsets.push(out.data.len() as u32);
}
boxed
}
};
self.export_rest(out, start, failed, boxed, reg)
}
pub(super) fn export_rest(
&mut self,
out: &mut Output,
start: usize,
failed: M,
boxed: M,
reg: Reg,
) {
for lane in Lanes::of(boxed) {
let v = self.take(reg, lane);
out.extra.push(((start + lane) as u32, v));
}
(boxed).store(&mut out.boxed, start / 64);
(failed).store(&mut out.failed, start / 64);
}
pub fn take_result(&mut self, program: &Program, lane: usize) -> Result<Variable, VMError> {
match self.alive.get(lane) {
true => Ok(match &program.layout {
Some(layout) => self.assemble_taken(layout, lane, Some(&mut 0)),
None => self.take(program.out, lane),
}),
_ => Err(self.errors[lane]
.take().map(Fault::vm)
.unwrap_or(VMError::NumberConversionError)),
}
}
}
+843
View File
@@ -0,0 +1,843 @@
use super::closure::Pending;
use crate::lane::builtins::{Arg, Out};
use crate::lane::date::Date;
use crate::lane::mask::{LaneSet, Lanes, Mask};
use crate::lane::ops::Ops;
use crate::lane::output::Items;
use crate::lane::program::{Const, Input, Kind, Operand, Program, Reg};
use crate::lane::scaled::Scaled;
use crate::variable::Variable;
use crate::vm::VMError;
use rust_decimal::Decimal;
use std::rc::Rc;
use zen_types::symbol::Symbol;
use zen_types::variable::{Shape as MapShape, ShapeHint};
#[derive(Debug, Default)]
pub struct Frame<M: LaneSet = Mask> {
pub(super) program: u64,
pub(super) capacity: usize,
pub(super) width: usize,
pub(super) kinds: Vec<Kind>,
pub(super) pinned: Vec<bool>,
pub(super) fixed: Vec<bool>,
pub(super) filled: Vec<M>,
pub(super) regs: Vec<Variable>,
pub(super) mant: Vec<i64>,
pub(super) spans: Vec<(u32, u32)>,
pub(super) lists: Vec<(u32, u32)>,
pub(super) items: Items,
pub(super) arena: String,
pub(super) bytes: Vec<u8>,
pub(super) ranges: Vec<(usize, usize)>,
pub(super) dicts: Vec<Vec<(u32, u32)>>,
pub(super) shared: Vec<Vec<(u32, u32)>>,
pub(super) scales: Vec<u8>,
pub(super) wide: Vec<M>,
pub(super) nums: Vec<Decimal>,
pub(super) dates: Vec<Date>,
pub(super) bits: Vec<M>,
pub(super) boxed: Vec<M>,
pub(super) masks: Vec<M>,
pub(super) alive: M,
pub(super) dense: bool,
pub(super) errors: Vec<Option<Fault>>,
pub(super) rows: Vec<u32>,
pub(super) parents: Vec<u32>,
pub(super) scratch: Scratch,
pub(super) hints: Vec<ShapeHint>,
pub(super) consts: Vec<Variable>,
pub(super) text: String,
pub(super) buffers: Buffers,
pub(super) memo: Vec<Vec<Option<Result<Out, Fault>>>>,
pub(super) owner: u64,
pub(super) parked: Vec<(u64, Caches)>,
pub(super) shapes: Vec<Option<Rc<MapShape>>>,
pub(super) stage: u16,
pub(super) stages: Vec<u16>,
pub(super) soft: Vec<(usize, u16, Fault)>,
}
#[derive(Debug, Default)]
pub(super) struct Caches {
pub(super) memo: Vec<Vec<Option<Result<Out, Fault>>>>,
pub(super) dicts: Vec<Vec<(u32, u32)>>,
pub(super) shared: Vec<Vec<(u32, u32)>>,
}
impl Caches {
pub(super) fn clear_spans(&mut self) {
self.dicts.iter_mut().for_each(Vec::clear);
self.shared.iter_mut().for_each(Vec::clear);
}
}
pub(super) const SEGMENTS: usize = 8;
#[derive(Debug, Default)]
pub(super) struct Buffers {
pub(super) m: Vec<i64>,
pub(super) s: Vec<u8>,
pub(super) ka: Vec<i64>,
pub(super) sa: Vec<u8>,
pub(super) kb: Vec<i64>,
pub(super) sb: Vec<u8>,
}
#[derive(Debug, Default)]
pub(super) struct Scratch {
pub(super) items: Vec<(u32, Variable)>,
pub(super) slots: Vec<(u32, u32)>,
pub(super) truths: Vec<u64>,
pub(super) settled: Vec<u64>,
pub(super) spans: Vec<(usize, usize, usize)>,
pub(super) results: Vec<Variable>,
pub(super) failures: Vec<(u32, VMError)>,
pub(super) rows: Vec<u32>,
pub(super) parents: Vec<u32>,
pub(super) lists: Vec<(usize, Pending, usize)>,
pub(super) done: Vec<usize>,
}
#[derive(Debug, Clone)]
pub enum Fault {
Vm(VMError),
Unsupported(&'static str),
Call(Box<CallFault>),
}
#[derive(Debug, Clone)]
pub struct CallFault {
kind: crate::functions::FunctionKind,
detail: CallDetail,
}
#[derive(Clone)]
enum CallDetail {
Message(String),
Fail(&'static crate::lane::builtins::Builtin, Box<[Variable]>),
}
impl std::fmt::Debug for CallDetail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CallDetail::Message(message) => f.debug_tuple("Message").field(message).finish(),
CallDetail::Fail(_, values) => f.debug_tuple("Fail").field(values).finish(),
}
}
}
impl CallFault {
pub(crate) fn message(kind: &crate::functions::FunctionKind, message: String) -> Fault {
Fault::Call(Box::new(CallFault {
kind: kind.clone(),
detail: CallDetail::Message(message),
}))
}
pub(crate) fn fail(
kind: &crate::functions::FunctionKind,
builtin: &'static crate::lane::builtins::Builtin,
args: &[crate::lane::builtins::Arg],
) -> Fault {
Fault::Call(Box::new(CallFault {
kind: kind.clone(),
detail: CallDetail::Fail(builtin, args.iter().map(|a| a.variable()).collect()),
}))
}
fn error(&self) -> VMError {
let message = match &self.detail {
CallDetail::Message(message) => message.clone(),
CallDetail::Fail(builtin, values) => {
let args: smallvec::SmallVec<[crate::lane::builtins::Arg; 4]> =
values.iter().map(crate::lane::builtins::Arg::of).collect();
(builtin.fail)(&args)
}
};
crate::lane::ops::Ops::error("CallFunction", format!("Function `{}` failed: {message}", self.kind))
}
}
impl Fault {
pub fn vm(self) -> VMError {
match self {
Fault::Vm(error) => error,
Fault::Unsupported(opcode) => crate::lane::ops::Ops::unsupported(opcode),
Fault::Call(call) => call.error(),
}
}
}
impl<M: LaneSet> Frame<M> {
pub(super) const ARENA: usize = 1 << 20;
#[inline]
pub(super) fn text_at(&self, reg: Reg, lane: usize) -> &str {
let (a, b) = self.spans[self.at(reg, lane)];
self.arena.get(a as usize..b as usize).unwrap_or_default()
}
#[inline]
pub(super) fn intern(&mut self, text: &str) -> (u32, u32) {
let start = self.arena.len() as u32;
self.arena.push_str(text);
(start, self.arena.len() as u32)
}
#[inline]
pub(super) fn put_scaled(&mut self, reg: Reg, lane: usize, mant: i64, scale: u8) {
let at = self.at(reg, lane);
self.mant[at] = mant;
self.scales[at] = scale;
self.wide[reg as usize].unset(lane);
self.boxed[reg as usize].unset(lane);
}
#[inline]
pub(super) fn put_mask(&mut self, reg: Reg, lanes: M, word: M) {
let r = reg as usize;
self.bits[r] = (self.bits[r] & !lanes) | word;
self.boxed[r] &= !lanes;
}
#[inline]
pub(super) fn fill_typed(&mut self, reg: Reg, lanes: M, value: &Variable) -> bool {
match (self.kind(reg), value) {
(Kind::Num, Variable::Number(n)) => self.fill_num(reg, lanes, *n),
(Kind::Str, Variable::String(text)) => self.fill_text(reg, lanes, text),
(Kind::Bool, Variable::Bool(b)) => self.fill_bool(reg, lanes, *b),
(Kind::List, Variable::Array(items)) if items.borrow().is_empty() => {
let start = self.items.len() as u32;
for lane in Lanes::of(lanes) {
let at = self.at(reg, lane);
self.lists[at] = (start, start);
}
self.boxed[reg as usize] &= !lanes;
}
_ => return false,
}
true
}
#[inline]
pub(super) fn split(&mut self, cond: Reg, active: M, opcode: &str) -> (M, M) {
let (mut t, mut e) = (self.none(), self.none());
let mut slow = active;
if self.kind(cond) == Kind::Bool {
let boxed = self.boxed[cond as usize];
let bits = self.bits[cond as usize];
t = active & !boxed & bits;
e = active & !boxed & !bits;
slow = active & boxed;
}
for lane in Lanes::of(slow) {
match self.with(cond, lane, |v| Ops::truthy(v, opcode)) {
Ok(true) => t.set(lane),
Ok(false) => e.set(lane),
Err(err) => self.fail(lane, err),
}
}
(t, e)
}
#[inline]
pub(super) fn fill_text(&mut self, reg: Reg, lanes: M, text: &str) {
let span = self.intern(text);
let base = reg as usize * self.width;
for lane in Lanes::of(lanes) {
self.spans[base + lane] = span;
}
self.boxed[reg as usize] &= !lanes;
}
pub(super) fn box_lists(&mut self, args: &[Input], lanes: M) {
for input in args {
let Input::Reg(r) = *input else {
continue;
};
if self.kinds[r as usize] != Kind::List {
continue;
}
for lane in Lanes::of(lanes & !self.boxed[r as usize]) {
let value = self.list_value(r, lane);
let at = self.at(r, lane);
self.regs[at] = value;
self.boxed[r as usize].set(lane);
}
}
}
pub(super) fn list_value(&self, reg: Reg, lane: usize) -> Variable {
let (a, b) = self.lists[self.at(reg, lane)];
Variable::from_array(
(a as usize..b as usize)
.map(|i| self.items.variable(i, &self.arena))
.collect(),
)
}
#[inline]
pub(super) fn put_text(&mut self, reg: Reg, lane: usize, text: &str) {
let span = self.intern(text);
let at = self.at(reg, lane);
self.spans[at] = span;
}
pub(super) fn park(&mut self, id: u64) {
if self.owner == id {
return;
}
let current = Caches {
memo: std::mem::take(&mut self.memo),
dicts: std::mem::take(&mut self.dicts),
shared: std::mem::take(&mut self.shared),
};
self.parked.push((self.owner, current));
let next = match self.parked.iter().position(|(owner, _)| *owner == id) {
Some(i) => self.parked.swap_remove(i).1,
None => Caches::default(),
};
if self.parked.len() > Self::PARKED {
self.parked.remove(0);
}
self.memo = next.memo;
self.dicts = next.dicts;
self.shared = next.shared;
self.owner = id;
}
pub(super) fn prepare(&mut self, program: &Program, width: usize) {
self.park(program.id);
if self.program != program.id || self.capacity < width {
let size = program.regs as usize * width.max(self.capacity);
if self.regs.len() < size {
self.regs.resize(size, Variable::Null);
self.mant.resize(size, 0);
self.spans.resize(size, (0, 0));
self.lists.resize(size, (0, 0));
self.scales.resize(size, 0);
self.nums.resize(size, Decimal::ZERO);
self.dates.resize(size, Date(None));
}
self.capacity = width.max(self.capacity);
self.kinds.clear();
self.kinds.extend_from_slice(&program.kinds);
self.pinned.clear();
self.pinned.extend_from_slice(&program.pinned);
self.fixed.clear();
self.fixed.extend_from_slice(&program.fixed);
self.consts.clear();
self.consts
.extend(program.consts.iter().map(Const::variable));
let hints = program.sites as usize * SEGMENTS;
self.hints.clear();
self.hints.resize(hints, ShapeHint::default());
self.masks.clear();
self.masks
.resize(program.masks as usize + 1, M::none(width));
if self.errors.len() < self.capacity {
self.errors.resize(self.capacity, None);
}
if self.stages.len() < self.capacity {
self.stages.resize(self.capacity, 0);
}
self.width = usize::MAX;
self.program = program.id;
self.shapes.clear();
if let Some(layout) = &program.layout {
Self::collect_shapes(layout, &mut self.shapes);
}
}
if self.arena.len() > Self::ARENA || self.items.len() > Self::ARENA {
self.arena.clear();
self.items.clear();
self.dicts.iter_mut().for_each(Vec::clear);
self.shared.iter_mut().for_each(Vec::clear);
self.parked
.iter_mut()
.for_each(|(_, caches)| caches.clear_spans());
self.filled.iter_mut().for_each(|w| *w = M::none(width));
}
if self.width != width || self.filled.len() != program.regs as usize {
let regs = program.regs as usize;
for bits in [
&mut self.filled,
&mut self.bits,
&mut self.boxed,
&mut self.wide,
] {
bits.clear();
bits.resize(regs, M::none(width));
}
}
self.width = width;
self.stage = 0;
self.soft.clear();
self.masks.iter_mut().for_each(|m| *m = M::none(width));
self.alive = M::all(width);
self.masks[0] = self.alive;
}
pub(super) fn restart(&mut self) {
self.stage = 0;
self.soft.clear();
let width = self.width;
self.masks.iter_mut().for_each(|m| *m = M::none(width));
self.alive = M::all(self.width);
self.masks[0] = self.alive;
}
pub fn forget(&mut self) {
self.memo.iter_mut().for_each(Vec::clear);
self.dicts.iter_mut().for_each(Vec::clear);
self.shared.iter_mut().for_each(Vec::clear);
self.parked.clear();
}
const PARKED: usize = 8;
const INLINE_TEXT: usize = 256;
pub(super) const UNSET: (u32, u32) = (u32::MAX, u32::MAX);
pub(super) fn cached(
cache: &mut Vec<Vec<(u32, u32)>>,
slot: usize,
size: usize,
) -> &mut Vec<(u32, u32)> {
if cache.len() <= slot {
cache.resize_with(slot + 1, Vec::new);
}
let entries = &mut cache[slot];
if entries.len() < size {
entries.resize(size, Self::UNSET);
}
entries
}
pub fn restrict(&mut self, mask: M) {
self.masks[0] &= mask;
}
pub fn stage_of(&self, lane: usize) -> u16 {
self.stages[lane]
}
pub fn active(&self, lane: usize) -> bool {
self.masks[0].get(lane)
}
pub fn outputs(&self, program: &Program, lane: usize) -> Vec<Variable> {
program
.outputs
.iter()
.map(|r| self.value(*r, lane))
.collect()
}
#[inline]
pub(super) fn none(&self) -> M {
M::none(self.width)
}
#[inline]
pub(super) fn at(&self, reg: Reg, lane: usize) -> usize {
reg as usize * self.width + lane
}
#[inline]
pub(super) fn kind(&self, reg: Reg) -> Kind {
self.kinds[reg as usize]
}
#[inline]
pub(super) fn generic(&self, reg: Reg, lane: usize) -> bool {
matches!(self.kinds[reg as usize], Kind::Dyn) || self.boxed[reg as usize].get(lane)
}
#[inline]
pub(super) fn value(&self, reg: Reg, lane: usize) -> Variable {
let at = self.at(reg, lane);
match self.generic(reg, lane) {
true => self.regs[at].clone(),
false => match self.kinds[reg as usize] {
Kind::Num => Variable::Number(self.number(reg, lane)),
Kind::Str => Variable::String(Symbol::from(self.text_at(reg, lane))),
Kind::List => self.list_value(reg, lane),
Kind::Date => self.dates[at].variable(),
_ => Variable::Bool(self.bits[reg as usize].get(lane)),
},
}
}
#[inline]
pub(super) fn with<T>(&self, reg: Reg, lane: usize, f: impl FnOnce(&Variable) -> T) -> T {
match self.generic(reg, lane) {
true => f(&self.regs[self.at(reg, lane)]),
false => f(&self.value(reg, lane)),
}
}
#[inline]
pub(super) fn take(&mut self, reg: Reg, lane: usize) -> Variable {
if self.pinned[reg as usize] {
return self.value(reg, lane);
}
match self.generic(reg, lane) {
true => {
let at = self.at(reg, lane);
std::mem::replace(&mut self.regs[at], Variable::Null)
}
false => self.value(reg, lane),
}
}
#[inline]
pub(super) fn set(&mut self, reg: Reg, lane: usize, value: Variable) {
let at = self.at(reg, lane);
let r = reg as usize;
match (self.kinds[r], value) {
(Kind::Dyn, v) => self.regs[at] = v,
(Kind::Str, Variable::String(text)) if text.len() <= Self::INLINE_TEXT => {
self.put_text(reg, lane, &text);
self.boxed[r].unset(lane);
}
(Kind::Num, Variable::Number(n)) => {
self.put_number(reg, lane, n);
self.boxed[r].unset(lane);
}
(Kind::Bool, Variable::Bool(b)) => {
self.bits[r].put(lane, b);
self.boxed[r].unset(lane);
}
(Kind::Date, v) => match Date::of(&v).filter(|_| !Date::sourced(&v)) {
Some(d) => {
self.dates[at] = d;
self.boxed[r].unset(lane);
}
None => {
self.regs[at] = v;
self.boxed[r].set(lane);
}
},
(_, v) => {
self.regs[at] = v;
self.boxed[r].set(lane);
}
}
}
#[inline]
pub(super) fn store(&mut self, reg: Reg, lane: usize, value: &Variable) {
let r = reg as usize;
match (self.kinds[r], value) {
(Kind::Num, Variable::Number(n)) => {
self.put_number(reg, lane, *n);
self.boxed[r].unset(lane);
}
(Kind::Str, Variable::String(text)) if text.len() <= Self::INLINE_TEXT => {
self.put_text(reg, lane, text);
self.boxed[r].unset(lane);
}
(Kind::Bool, Variable::Bool(b)) => {
self.bits[r].put(lane, *b);
self.boxed[r].unset(lane);
}
(_, v) => self.set(reg, lane, v.clone()),
}
}
pub(super) fn arg_view(&self, reg: Reg, lane: usize) -> Arg<'_> {
let r = reg as usize;
let boxed = self.boxed[r].get(lane);
match (self.kinds[r], boxed) {
(Kind::Num, false) => Arg::Num(self.number(reg, lane)),
(Kind::Bool, false) => Arg::Bool(self.bits[r].get(lane)),
(Kind::Str, false) => Arg::Str(self.text_at(reg, lane)),
(Kind::Date, false) => Arg::Date(self.dates[self.at(reg, lane)]),
_ => Arg::of(&self.regs[self.at(reg, lane)]),
}
}
#[inline]
pub(super) fn fill_num(&mut self, reg: Reg, active: M, n: Decimal) {
let base = reg as usize * self.width;
let r = reg as usize;
match (Scaled::parts(&n), active == M::all(self.width)) {
(Some((m, s)), true) => {
self.mant[base..base + self.width].fill(m);
self.scales[base..base + self.width].fill(s);
self.wide[r] &= !active;
}
(Some((m, s)), false) => {
for lane in Lanes::of(active) {
self.mant[base + lane] = m;
self.scales[base + lane] = s;
}
self.wide[r] &= !active;
}
(None, _) => {
Lanes::of(active).for_each(|lane| self.nums[base + lane] = n);
self.wide[r] |= active;
}
}
self.boxed[r] &= !active;
}
#[inline]
pub(super) fn number(&self, reg: Reg, lane: usize) -> Decimal {
let at = self.at(reg, lane);
match self.wide[reg as usize].get(lane) {
true => self.nums[at],
false => Scaled::decimal(self.mant[at], self.scales[at]),
}
}
#[inline]
pub(super) fn put_number(&mut self, reg: Reg, lane: usize, n: Decimal) {
let at = self.at(reg, lane);
match Scaled::parts(&n) {
Some((m, s)) => {
self.mant[at] = m;
self.scales[at] = s;
self.wide[reg as usize].unset(lane);
}
None => {
self.nums[at] = n;
self.wide[reg as usize].set(lane);
}
}
}
#[inline]
pub(super) fn fill_bool(&mut self, reg: Reg, active: M, b: bool) {
let word = if b { active } else { self.none() };
self.put_mask(reg, active, word);
}
#[inline]
pub(super) fn typed(&self, reg: Reg) -> M {
match self.kinds[reg as usize] {
Kind::Dyn => self.none(),
_ => !self.boxed[reg as usize],
}
}
#[inline]
pub(super) fn copy_typed(&mut self, dst: Reg, src: Reg, lanes: M) {
let (d, s) = (dst as usize, src as usize);
let (db, sb) = (d * self.width, s * self.width);
if lanes == M::all(self.width) && d != s {
let width = self.width;
match self.kinds[s] {
Kind::Num => {
self.mant.copy_within(sb..sb + width, db);
self.scales.copy_within(sb..sb + width, db);
for lane in Lanes::of(self.wide[s]) {
self.nums[db + lane] = self.nums[sb + lane];
}
self.wide[d] = self.wide[s];
}
Kind::Str => self.spans.copy_within(sb..sb + width, db),
Kind::List => self.lists.copy_within(sb..sb + width, db),
Kind::Date => {
for lane in 0..width {
self.dates[db + lane] = self.dates[sb + lane];
}
}
_ => self.bits[d] = self.bits[s],
}
self.boxed[d] &= !lanes;
return;
}
match self.kinds[s] {
Kind::Num => {
for w in 0..lanes.words() {
let (word, at) = (lanes.word(w), w * 64);
match word {
0 => {}
u64::MAX => {
self.mant.copy_within(sb + at..sb + at + 64, db + at);
self.scales.copy_within(sb + at..sb + at + 64, db + at);
}
mut bits => {
while bits != 0 {
let lane = at + bits.trailing_zeros() as usize;
self.mant[db + lane] = self.mant[sb + lane];
self.scales[db + lane] = self.scales[sb + lane];
bits &= bits - 1;
}
}
}
}
for lane in Lanes::of(lanes & self.wide[s]) {
self.nums[db + lane] = self.nums[sb + lane];
}
self.wide[d] = (self.wide[d] & !lanes) | (self.wide[s] & lanes);
}
Kind::Str => {
for lane in Lanes::of(lanes) {
self.spans[db + lane] = self.spans[sb + lane];
}
}
Kind::List => {
for lane in Lanes::of(lanes) {
self.lists[db + lane] = self.lists[sb + lane];
}
}
Kind::Date => {
for lane in Lanes::of(lanes) {
self.dates[db + lane] = self.dates[sb + lane];
}
}
_ => self.bits[d] = (self.bits[d] & !lanes) | (self.bits[s] & lanes),
}
self.boxed[d] &= !lanes;
}
pub(super) fn block(spans: &[(u32, u32)]) -> Option<(usize, usize)> {
let (first, last) = (spans.first()?, spans.last()?);
spans
.windows(2)
.all(|w| w[0].1 == w[1].0)
.then_some((first.0 as usize, last.1 as usize))
}
#[inline]
pub(super) fn num(&self, o: Operand, lane: usize) -> Decimal {
match o {
Operand::Num(n) => n,
Operand::Reg(r) => self.number(r, lane),
}
}
#[inline]
pub(super) fn operand_boxed(&self, o: Operand) -> M {
match o {
Operand::Num(_) => self.none(),
Operand::Reg(r) => match self.kinds[r as usize] {
Kind::Num => self.boxed[r as usize],
_ => M::all(self.width),
},
}
}
#[inline]
pub(super) fn side<'s>(
&'s self,
o: Operand,
m: &'s mut Vec<i64>,
sc: &'s mut Vec<u8>,
) -> Option<(&'s [i64], &'s [u8])> {
let width = self.width;
match o {
Operand::Num(n) => {
let (mm, ss) = Scaled::parts(&n)?;
if m.len() < width {
m.resize(width, 0);
sc.resize(width, 0);
}
m[..width].fill(mm);
sc[..width].fill(ss);
Some((&m[..width], &sc[..width]))
}
Operand::Reg(r) => {
let base = r as usize * width;
Some((
&self.mant[base..base + width],
&self.scales[base..base + width],
))
}
}
}
#[inline]
pub(super) fn operand_wide(&self, o: Operand) -> M {
match o {
Operand::Num(_) => self.none(),
Operand::Reg(r) => self.wide[r as usize],
}
}
#[inline]
pub(super) fn uniform(s: &[u8], lanes: M) -> Option<u8> {
let first = *s.get(lanes.first()?)?;
if lanes == M::all(s.len()) {
return (s.iter().fold(0u8, |acc, x| acc | (x ^ first)) == 0).then_some(first);
}
let mixed = s
.iter()
.enumerate()
.fold(0u8, |acc, (lane, x)| acc | ((x ^ first) & (lanes.get(lane) as u8).wrapping_neg()));
(mixed == 0).then_some(first)
}
#[inline]
pub(super) fn operand_value(&mut self, o: Operand, lane: usize) -> Variable {
match o {
Operand::Num(n) => Variable::Number(n),
Operand::Reg(r) => self.take(r, lane),
}
}
#[inline]
pub(super) fn fail(&mut self, lane: usize, error: VMError) {
self.fault(lane, Fault::Vm(error));
}
pub(super) fn revive(&mut self) {
let dead = self.masks[0] & !self.alive;
for lane in Lanes::of(dead) {
if let Some(fault) = self.errors[lane].take() {
self.soft.push((lane, self.stages[lane], fault));
}
}
self.alive |= dead;
}
pub(super) fn fault(&mut self, lane: usize, fault: Fault) {
if self.alive.get(lane) {
self.alive.unset(lane);
self.errors[lane] = Some(fault);
self.stages[lane] = self.stage;
}
}
#[inline]
pub(super) fn write(&mut self, reg: Reg, lane: usize, result: Result<Out, VMError>) {
let r = reg as usize;
match (self.kinds[r], result) {
(Kind::Num, Ok(Out::Num(n))) => {
self.put_number(reg, lane, n);
self.boxed[r].unset(lane);
}
(Kind::Bool, Ok(Out::Bool(b))) => {
self.bits[r].put(lane, b);
self.boxed[r].unset(lane);
}
(Kind::Date, Ok(Out::Date(d))) => {
let at = self.at(reg, lane);
self.dates[at] = d;
self.boxed[r].unset(lane);
}
(_, Ok(out)) => self.set(reg, lane, out.variable()),
(_, Err(e)) => self.fail(lane, e),
}
}
#[inline]
pub(super) fn write_call(&mut self, reg: Reg, lane: usize, result: Result<Out, Fault>) {
match result {
Ok(out) => self.write(reg, lane, Ok(out)),
Err(fault) => self.fault(lane, fault),
}
}
#[inline]
pub(super) fn put(&mut self, reg: Reg, lane: usize, result: Result<Variable, VMError>) {
match result {
Ok(v) => self.set(reg, lane, v),
Err(e) => self.fail(lane, e),
}
}
}
File diff suppressed because it is too large Load Diff
+985
View File
@@ -0,0 +1,985 @@
mod closure;
mod context;
mod date;
mod export;
mod frame;
mod load;
mod number;
mod text;
use crate::functions::{FunctionKind, InternalFunction};
use crate::lane::builtins::{Arg, Builtins, Out};
use crate::lane::interval::{Interval, IntervalData};
use crate::lane::output::Item;
use crate::lane::mask::{LaneSet, Lanes};
use crate::lane::ops::Ops;
use crate::lane::program::{
Binary, Const, Input, Kind, NumCmp, ObjectKey, Op, Operand, Program, Reg,
};
use crate::lane::scaled::Scaled;
use crate::variable::Variable;
use rust_decimal::Decimal;
use zen_types::symbol::Symbol;
pub use context::Context;
pub use frame::{CallFault, Fault, Frame};
pub(super) type Parent<'a, M> = (&'a Frame<M>, &'a [u32], &'a [(Reg, Reg)]);
pub struct Executor;
impl Executor {
fn member_call<M: LaneSet>(dst: Reg, kind: &FunctionKind, args: &[Input], active: M, f: &mut Frame<M>) -> M {
let (FunctionKind::Internal(InternalFunction::Contains), [Input::Reg(a), Input::Const(id)]) = (kind, args) else {
return f.none();
};
let Some(Variable::String(needle)) = f.consts.get(*id as usize).cloned() else {
return f.none();
};
let (mut word, mut done) = (f.none(), f.none());
let needle_bytes = needle.as_bytes();
for lane in Lanes::of(active) {
if f.kind(*a) == Kind::List && !f.generic(*a, lane) {
let (lo, hi) = f.lists[f.at(*a, lane)];
let mut hit = Some(false);
for i in lo as usize..hi as usize {
match f.items.get(i) {
Item::Text(x, y) => {
if f.arena.as_bytes().get(x as usize..y as usize) == Some(needle_bytes) {
hit = Some(true);
break;
}
}
Item::Value(Variable::String(s)) if s.as_str() == needle.as_str() => {
hit = Some(true);
break;
}
Item::Value(Variable::Dynamic(_)) => {
hit = None;
break;
}
_ => {}
}
}
if let Some(hit) = hit {
word.put(lane, hit);
done.set(lane);
}
continue;
}
if !f.generic(*a, lane) {
continue;
}
let Variable::Array(items) = &f.regs[f.at(*a, lane)] else {
continue;
};
let items = items.borrow();
if items.iter().any(|item| matches!(item, Variable::Dynamic(_))) {
continue;
}
word.put(lane, items.iter().any(|item| matches!(item, Variable::String(s) if s.as_str() == needle.as_str())));
done.set(lane);
}
match f.kind(dst) {
Kind::Bool => {
let d = dst as usize;
f.bits[d] = (f.bits[d] & !done) | word;
f.boxed[d] &= !done;
}
_ => {
for lane in Lanes::of(done) {
f.set(dst, lane, Variable::Bool(word.get(lane)));
}
}
}
done
}
#[inline]
fn equal_lane<M: LaneSet>(f: &Frame<M>, a: Reg, b: Reg, lane: usize) -> Option<bool> {
let typed = |reg: Reg, value: &Variable| match (f.kind(reg), value) {
(Kind::List, _) => Some(false),
(Kind::Str, Variable::String(s)) => Some(f.text_at(reg, lane) == s.as_str()),
(Kind::Str, Variable::Dynamic(_)) => None,
(Kind::Str, _) => Some(false),
(Kind::Num, Variable::Number(n)) => Some(Ops::same_number(&f.number(reg, lane), n)),
(Kind::Num, _) => Some(false),
(Kind::Bool, Variable::Bool(x)) => Some(f.bits[reg as usize].get(lane) == *x),
(Kind::Bool, _) => Some(false),
_ => None,
};
match (f.generic(a, lane), f.generic(b, lane)) {
(true, true) => Some(Ops::equal(&f.regs[f.at(a, lane)], &f.regs[f.at(b, lane)])),
(false, true) => typed(a, &f.regs[f.at(b, lane)]),
(true, false) => typed(b, &f.regs[f.at(a, lane)]),
(false, false) => match (f.kind(a), f.kind(b)) {
(Kind::List, _) | (_, Kind::List) => Some(false),
(Kind::Str, Kind::Str) => Some(f.text_at(a, lane) == f.text_at(b, lane)),
(Kind::Num, Kind::Num) => Some(Ops::same_number(&f.number(a, lane), &f.number(b, lane))),
(Kind::Bool, Kind::Bool) => Some(f.bits[a as usize].get(lane) == f.bits[b as usize].get(lane)),
_ => None,
},
}
}
pub fn run<M: LaneSet>(
program: &Program,
frames: &mut [Frame<M>],
ctx: &mut Context,
rows: &[u32],
) {
let Some((frame, _)) = frames.split_first_mut() else {
return;
};
Self::enter(program, frame, rows, None);
Self::execute(program, frames, ctx);
}
pub fn enter_top<M: LaneSet>(program: &Program, frame: &mut Frame<M>, rows: &[u32]) {
Self::enter(program, frame, rows, None);
}
pub fn execute_top<M: LaneSet>(program: &Program, frames: &mut [Frame<M>], ctx: &mut Context) {
Self::execute(program, frames, ctx);
}
pub(super) fn enter<M: LaneSet>(
program: &Program,
frame: &mut Frame<M>,
rows: &[u32],
parent: Option<Parent<M>>,
) {
let width = rows.len();
frame.prepare(program, width);
frame.rows.clear();
frame.rows.extend_from_slice(rows);
frame.dense = parent.is_none()
&& rows
.iter()
.zip(0u32..)
.fold(0u32, |acc, (r, i)| acc | (r ^ i))
== 0;
if let Some((parent, parents, imports)) = parent {
frame.parents.clear();
frame.parents.extend_from_slice(parents);
for (from, to) in imports {
for (lane, p) in parents.iter().enumerate() {
let value = parent.value(*from, *p as usize);
frame.set(*to, lane, value);
}
}
}
}
pub(super) fn execute<M: LaneSet>(
program: &Program,
frames: &mut [Frame<M>],
ctx: &mut Context,
) {
let Some((frame, rest)) = frames.split_first_mut() else {
return;
};
for step in &program.steps {
if program.isolated && matches!(step.op, Op::Stage { .. }) {
frame.revive();
}
let active = frame.masks[step.mask as usize] & frame.alive;
if active.is_empty() {
continue;
}
Self::step(&step.op, active, frame, rest, ctx);
}
}
pub(super) fn step<M: LaneSet>(
op: &Op,
active: M,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) {
match op {
Op::Const { dst, id } if matches!(f.kind(*dst), Kind::Num | Kind::Bool) => {
match (f.kind(*dst), &f.consts[*id as usize]) {
(Kind::Num, Variable::Number(n)) => f.fill_num(*dst, active, *n),
(Kind::Bool, Variable::Bool(b)) => f.fill_bool(*dst, active, *b),
_ => Self::cold(op, active, f, rest, ctx),
}
}
Op::Branch {
cond,
opcode,
on_true,
on_false,
} => {
let (t, e) = f.split(*cond, active, opcode);
f.masks[*on_true as usize] = t;
f.masks[*on_false as usize] = e;
}
Op::Merge { dst, mask, a, b }
if f.kind(*dst) == Kind::Bool
&& f.kind(*a) == Kind::Bool
&& f.kind(*b) == Kind::Bool =>
{
let m = f.masks[*mask as usize];
let (ta, tb) = (active & m, active & !m);
let (d, ra, rb) = (*dst as usize, *a as usize, *b as usize);
let bits = (f.bits[ra] & ta) | (f.bits[rb] & tb);
let boxed = (f.boxed[ra] & ta) | (f.boxed[rb] & tb);
for lane in Lanes::of(boxed) {
let src = if ta.get(lane) { *a } else { *b };
let v = f.take(src, lane);
let at = f.at(*dst, lane);
f.regs[at] = v;
}
f.bits[d] = (f.bits[d] & !active) | bits;
f.boxed[d] = (f.boxed[d] & !active) | boxed;
}
Op::Stage { index } => f.stage = *index,
Op::Num { dst, op, a, b } => Self::num(*op, *dst, *a, *b, active, f),
Op::Cmp { dst, op, a, b } => Self::cmp(*op, *dst, *a, *b, active, f),
Op::Env { site, dst, .. } | Op::Path { site, dst, .. }
if ctx.column(*site).is_some() =>
{
Self::column_load(site, dst, active, f, ctx)
}
Op::Env { dst, key, site } => Self::env(dst, key, site, active, f, ctx),
Op::Path { dst, path, site } => Self::path(dst, path, site, active, f, ctx),
Op::Field {
dst,
src,
key,
site,
} => Self::field(dst, src, key, site, active, f),
Op::LoadEq {
dst,
load,
site,
id,
not,
} => Self::load_eq(dst, load, site, id, not, active, f, ctx),
Op::LoadIn { dst, a, load, site } => Self::load_in(dst, a, load, site, active, f, ctx),
Op::Coalesce { dst, a, id } => Self::coalesce(dst, a, id, active, f),
Op::LoadCall(c) => Self::load_call(c, active, f, ctx),
_ => Self::cold(op, active, f, rest, ctx),
}
}
#[inline(never)]
fn static_object<M: LaneSet>(dst: Reg, pairs: &[(ObjectKey, Reg)], active: M, f: &mut Frame<M>) -> bool {
if pairs.len() >= 32 {
return false;
}
let mut template = crate::variable::VariableMap::with_capacity(pairs.len());
for (key, _) in pairs.iter().rev() {
let ObjectKey::Static(key) = key else {
return false;
};
template.insert(Symbol::from(key.as_ref()), Variable::Null);
}
let Some(shape) = template.shape().filter(|_| template.len() == pairs.len()).cloned() else {
return false;
};
for lane in Lanes::of(active) {
let values: Vec<Variable> = pairs.iter().rev().map(|(_, v)| f.take(*v, lane)).collect();
f.set(dst, lane, Variable::from_object(crate::variable::VariableMap::from_shape(shape.clone(), values)));
}
true
}
fn boxed_call<M: LaneSet>(dst: Reg, kind: &FunctionKind, args: &[Input], active: M, f: &mut Frame<M>) -> M {
let FunctionKind::Internal(function) = kind else {
return f.none();
};
let mut done = f.none();
match (function, args) {
(InternalFunction::Contains, [Input::Reg(a), Input::Const(id)]) if f.kind(*a) == Kind::Dyn => {
let Variable::String(needle) = f.consts[*id as usize].clone() else {
return done;
};
for lane in Lanes::of(active) {
let found = f.with(*a, lane, |value| match value {
Variable::String(text) => Some(text.contains(needle.as_ref() as &str)),
Variable::Array(items) => {
let items = items.borrow();
items
.iter()
.all(|item| matches!(item, Variable::String(_) | Variable::Null))
.then(|| items.iter().any(|item| matches!(item, Variable::String(text) if text.as_ref() as &str == needle.as_ref() as &str)))
}
_ => None,
});
if let Some(found) = found {
f.write(dst, lane, Ok(Out::Bool(found)));
done.set(lane);
}
}
}
(InternalFunction::Len, [Input::Reg(a)]) if f.kind(*a) == Kind::Dyn => {
for lane in Lanes::of(active) {
let len = f.with(*a, lane, |value| match value {
Variable::String(text) => Some(text.len()),
Variable::Array(items) => Some(items.borrow().len()),
_ => None,
});
if let Some(len) = len {
f.write(dst, lane, Ok(Out::Num(Decimal::from(len))));
done.set(lane);
}
}
}
_ => {}
}
done
}
fn identity_call<M: LaneSet>(dst: Reg, kind: &FunctionKind, args: &[Input], active: M, f: &mut Frame<M>) -> M {
let (FunctionKind::Internal(InternalFunction::Bool), [Input::Reg(a)]) = (kind, args) else {
return f.none();
};
let (a, d) = (*a as usize, dst as usize);
if f.kind(a as Reg) != Kind::Bool || f.kind(dst) != Kind::Bool {
return f.none();
}
let lanes = active & !f.boxed[a];
let bits = f.bits[a];
f.bits[d] = (bits & lanes) | (f.bits[d] & !lanes);
f.boxed[d] &= !lanes;
lanes
}
pub(super) fn cold<M: LaneSet>(
op: &Op,
active: M,
f: &mut Frame<M>,
rest: &mut [Frame<M>],
ctx: &mut Context,
) {
match op {
Op::Const { dst, id } => {
let r = *dst as usize;
let pinned = f.fixed[r];
let missing = match pinned {
true => active & !f.filled[r],
false => active,
};
if missing.any() {
let v = f.consts[*id as usize].clone();
match (f.kind(*dst), &v) {
(Kind::Str, Variable::String(text)) => {
let start = f.arena.len() as u32;
f.arena.push_str(text);
let span = (start, f.arena.len() as u32);
for lane in Lanes::of(missing) {
let at = f.at(*dst, lane);
f.spans[at] = span;
}
f.boxed[r] &= !missing;
}
_ => {
for lane in Lanes::of(missing) {
let value = match pinned {
true => v.clone(),
false => v.deep_clone(),
};
f.set(*dst, lane, value);
}
}
}
if pinned {
f.filled[r] |= missing;
}
}
}
Op::SelectConst { dst, cond, a, b } => {
let (va, vb) = (f.consts[*a as usize].clone(), f.consts[*b as usize].clone());
let (mut t, mut e) = (f.none(), f.none());
let mut slow = active;
if f.kind(*cond) == Kind::Bool {
let boxed = f.boxed[*cond as usize];
let bits = f.bits[*cond as usize];
t = active & !boxed & bits;
e = active & !boxed & !bits;
slow = active & boxed;
}
for lane in Lanes::of(slow) {
match f.with(*cond, lane, |v| Ops::truthy(v, "JumpIfFalse")) {
Ok(true) => t.set(lane),
Ok(false) => e.set(lane),
Err(err) => f.fail(lane, err),
}
}
for (lanes, v) in [(t, va), (e, vb)] {
match (f.kind(*dst), v) {
(Kind::Num, Variable::Number(n)) => f.fill_num(*dst, lanes, n),
(Kind::Str, Variable::String(text)) => f.fill_text(*dst, lanes, &text),
(Kind::Bool, Variable::Bool(b)) => f.fill_bool(*dst, lanes, b),
(_, v) => {
for lane in Lanes::of(lanes) {
f.set(*dst, lane, v.clone());
}
}
}
}
}
Op::Not { dst, a } if f.kind(*a) == Kind::Bool && f.kind(*dst) == Kind::Bool => {
let (d, r) = (*dst as usize, *a as usize);
let fast = active & !f.boxed[r];
f.bits[d] = (f.bits[d] & !fast) | (!f.bits[r] & fast);
f.boxed[d] &= !fast;
for lane in Lanes::of(active & f.boxed[r]) {
let v = Ops::not(f.take(*a, lane));
f.put(*dst, lane, v);
}
}
Op::Not { dst, a } => {
for lane in Lanes::of(active) {
let r = Ops::not(f.take(*a, lane));
f.put(*dst, lane, r);
}
}
Op::NullBranch { a, null, other } => {
let typed = active & f.typed(*a);
let (mut n, mut o) = (f.none(), typed);
for lane in Lanes::of(active & !typed) {
match f.with(*a, lane, |v| matches!(v, Variable::Null)) {
true => n.set(lane),
false => o.set(lane),
}
}
f.masks[*null as usize] = n;
f.masks[*other as usize] = o;
}
Op::Merge { dst, mask, a, b } => {
let m = f.masks[*mask as usize];
let kind = f.kind(*dst);
let (ta, tb) = match (kind == f.kind(*a), kind == f.kind(*b)) {
_ if kind == Kind::Dyn => (f.none(), f.none()),
(ka, kb) => (
if ka {
active & m & f.typed(*a)
} else {
f.none()
},
if kb {
active & !m & f.typed(*b)
} else {
f.none()
},
),
};
if ta.any() {
f.copy_typed(*dst, *a, ta);
}
if tb.any() {
f.copy_typed(*dst, *b, tb);
}
for lane in Lanes::of(active & !ta & !tb) {
let src = if m.get(lane) { *a } else { *b };
let v = f.take(src, lane);
f.set(*dst, lane, v);
}
}
Op::Move { dst, src } => {
let typed = match f.kind(*dst) == f.kind(*src) {
true => active & f.typed(*src),
false => f.none(),
};
if typed.any() {
f.copy_typed(*dst, *src, typed);
}
for lane in Lanes::of(active & !typed) {
let v = f.value(*src, lane);
f.set(*dst, lane, v);
}
}
Op::EqConst {
dst,
a,
value,
id,
not,
} => {
let d = *dst as usize;
let mut word = f.none();
let mut slow = active;
if let (Kind::Bool, Const::Bool(k)) = (f.kind(*a), value) {
let r = *a as usize;
let bits = if *k { f.bits[r] } else { !f.bits[r] };
word = active & !f.boxed[r] & bits;
slow = active & f.boxed[r];
}
if let (Kind::Str, Const::String(k)) = (f.kind(*a), value) {
let fast = active & !f.boxed[*a as usize];
for lane in Lanes::of(fast) {
word.put(lane, f.text_at(*a, lane) == k.as_ref());
}
slow = active & f.boxed[*a as usize];
}
if let (Kind::Num, Const::Number(k)) = (f.kind(*a), value) {
let fast = active & !f.boxed[*a as usize];
let (done, hits) = Self::scaled_cmp(
NumCmp::Equal,
Operand::Reg(*a),
Operand::Num(*k),
fast,
f,
);
word |= hits;
for lane in Lanes::of(fast & !done) {
if Ops::same_number(&f.number(*a, lane), k) {
word.set(lane);
}
}
slow = active & f.boxed[*a as usize];
}
if slow.any() {
let k = f.consts[*id as usize].clone();
for lane in Lanes::of(slow) {
if f.with(*a, lane, |v| Ops::equal(v, &k)) {
word.set(lane);
}
}
}
let word = if *not { !word & active } else { word };
f.bits[d] = (f.bits[d] & !active) | word;
f.boxed[d] &= !active;
}
Op::InRange {
dst,
a,
lo,
hi,
left,
right,
} => {
let interval = Interval {
left_bracket: *left,
right_bracket: *right,
left: IntervalData::Number(*lo),
right: IntervalData::Number(*hi),
};
let includes = |n: Decimal| {
interval
.includes(IntervalData::Number(n))
.map_err(|err| Ops::error("In", err.to_string()))
};
let d = *dst as usize;
let typed = match f.kind(*a) {
Kind::Num => active & !f.boxed[*a as usize],
_ => f.none(),
};
let (done, mut word) = Self::within(*a, *lo, *hi, *left, *right, typed, f);
for lane in Lanes::of(typed & !done) {
match includes(f.number(*a, lane)) {
Ok(h) => word.put(lane, h),
Err(e) => f.fail(lane, e),
}
}
let mut generic = None;
for lane in Lanes::of(active & !typed) {
let r = match f.take(*a, lane) {
Variable::Number(n) => includes(n),
x => match generic.get_or_insert_with(|| {
Ops::interval(
&Variable::Number(*lo),
&Variable::Number(*hi),
*left,
*right,
)
}) {
Ok(range) => Ops::membership(x, range),
Err(e) => Err(e.clone()),
},
};
match r {
Ok(h) => word.put(lane, h),
Err(e) => f.fail(lane, e),
}
}
f.bits[d] = (f.bits[d] & !active) | (word & active);
f.boxed[d] &= !active;
}
Op::EqAny { dst, a, id } => {
let d = *dst as usize;
let (done, mut word) = Self::any_number(*a, *id, active, f);
if let Variable::Array(list) = &f.consts[*id as usize] {
let list = list.borrow();
for lane in Lanes::of(active & !done) {
let hit = f.with(*a, lane, |x| list.iter().any(|k| Ops::equal(x, k)));
word.put(lane, hit);
}
}
f.bits[d] = (f.bits[d] & !active) | word;
f.boxed[d] &= !active;
}
Op::InConst { dst, a, id } => {
let (done, word) = Self::any_number(*a, *id, active, f);
let d = *dst as usize;
f.bits[d] = (f.bits[d] & !done) | word;
f.boxed[d] &= !done;
for lane in Lanes::of(active & !done) {
let x = f.take(*a, lane);
let r = Ops::membership(x, &f.consts[*id as usize]).map(Variable::Bool);
f.put(*dst, lane, r);
}
}
Op::RootEnv { dst } => {
for lane in Lanes::of(active) {
let v = ctx.envs.get(f.rows[lane]).materialize();
f.set(*dst, lane, v);
}
}
Op::Fetch { dst, a, b } => {
for lane in Lanes::of(active) {
let r = Ops::fetch(f.take(*a, lane), f.take(*b, lane));
f.put(*dst, lane, r);
}
}
Op::Negate { dst, a } => Self::negate(*dst, *a, active, f),
Op::Binary {
dst,
op: Binary::Compare(c),
a,
b,
} => {
for lane in Lanes::of(active) {
let (x, y) = (f.take(*a, lane), f.take(*b, lane));
match Ops::compared(&x, &y, *c) {
Some(hit) => f.set(*dst, lane, Variable::Bool(hit)),
None => f.fault(lane, Fault::Unsupported("Compare")),
}
}
}
Op::Binary {
dst,
op: Binary::Equal,
a,
b,
} => {
let (mut word, mut done) = (f.none(), f.none());
for lane in Lanes::of(active) {
if let Some(hit) = Self::equal_lane(f, *a, *b, lane) {
word.put(lane, hit);
done.set(lane);
}
}
match f.kind(*dst) {
Kind::Bool => {
let d = *dst as usize;
f.bits[d] = (f.bits[d] & !done) | word;
f.boxed[d] &= !done;
}
_ => {
for lane in Lanes::of(done) {
f.set(*dst, lane, Variable::Bool(word.get(lane)));
}
}
}
for lane in Lanes::of(active & !done) {
let (x, y) = (f.take(*a, lane), f.take(*b, lane));
f.put(*dst, lane, Ok(Variable::Bool(Ops::equal(&x, &y))));
}
}
Op::Binary { dst, op, a, b } => {
let unsupported = match op {
Binary::Subtract => Some("Subtract"),
Binary::Multiply => Some("Multiply"),
Binary::Divide => Some("Divide"),
Binary::Modulo => Some("Modulo"),
_ => None,
};
for lane in Lanes::of(active) {
let (x, y) = (f.take(*a, lane), f.take(*b, lane));
if let (false, Some(opcode)) = (matches!((&x, &y), (Variable::Number(_), Variable::Number(_))), unsupported) {
f.fault(lane, Fault::Unsupported(opcode));
continue;
}
let r = match op {
Binary::Add => Ops::add(x, y),
Binary::Subtract => Ops::subtract(x, y),
Binary::Multiply => Ops::multiply(x, y),
Binary::Divide => Ops::divide(x, y),
Binary::Modulo => Ops::modulo(x, y),
Binary::Exponent => Ops::exponent(x, y),
Binary::Equal => Ok(Variable::Bool(Ops::equal(&x, &y))),
Binary::In => Ops::membership(x, &y).map(Variable::Bool),
Binary::Compare(c) => Ops::compare(&x, &y, *c).map(Variable::Bool),
};
f.put(*dst, lane, r);
}
}
Op::Interval {
dst,
a,
b,
left,
right,
} => {
for lane in Lanes::of(active) {
let r = Ops::interval(&f.value(*a, lane), &f.value(*b, lane), *left, *right);
f.put(*dst, lane, r);
}
}
Op::Slice { dst, a, to, from } => {
for lane in Lanes::of(active) {
let r = Ops::slice(f.take(*a, lane), f.take(*to, lane), f.take(*from, lane));
f.put(*dst, lane, r);
}
}
Op::Len { dst, a } => {
for lane in Lanes::of(active) {
let r = f.with(*a, lane, Ops::len);
f.put(*dst, lane, r);
}
}
Op::Array { dst, items } => {
for lane in Lanes::of(active) {
let arr = items.iter().map(|r| f.take(*r, lane)).collect();
f.set(*dst, lane, Variable::from_array(arr));
}
}
Op::Object { dst, pairs } if Self::static_object(*dst, pairs, active, f) => {}
Op::Object { dst, pairs } => {
for lane in Lanes::of(active) {
let mut map = crate::variable::VariableMap::with_capacity(pairs.len());
let mut failed = None;
for (k, v) in pairs.iter().rev() {
let key = match k {
ObjectKey::Static(k) => Ok(Symbol::from(k.as_ref())),
ObjectKey::Reg(k) => Ops::object_key(f.take(*k, lane)),
};
match key {
Ok(key) => {
map.insert(key, f.take(*v, lane));
}
Err(e) => {
failed = Some(e);
break;
}
}
}
match failed {
Some(e) => f.fail(lane, e),
None => f.set(*dst, lane, Variable::from_object(map)),
}
}
}
Op::Join { dst, parts } => Self::join(*dst, parts, active, f),
Op::Extreme {
dst,
items,
largest,
} => Self::extreme(*dst, items, *largest, active, f),
Op::Concat { dst, a, b } => {
let typed = match f.kind(*dst) {
Kind::Str => active & !f.boxed[*a as usize] & !f.boxed[*b as usize],
_ => f.none(),
};
let (ba, bb, bd) = (
*a as usize * f.width,
*b as usize * f.width,
*dst as usize * f.width,
);
let mut text = std::mem::take(&mut f.text);
text.clear();
let origin = f.arena.len() as u32;
let (arena, spans) = (f.arena.as_str(), &mut f.spans);
for lane in Lanes::of(typed) {
let before = text.len() as u32;
for (x, y) in [spans[ba + lane], spans[bb + lane]] {
text.push_str(arena.get(x as usize..y as usize).unwrap_or_default());
}
spans[bd + lane] = (origin + before, origin + text.len() as u32);
}
f.arena.push_str(&text);
f.text = text;
f.boxed[*dst as usize] &= !typed;
for lane in Lanes::of(active & !typed) {
let r = Ops::add(f.take(*a, lane), f.take(*b, lane));
f.put(*dst, lane, r);
}
}
Op::Call {
dst,
kind: FunctionKind::Internal(InternalFunction::String),
args,
} if matches!(**args, [Input::Reg(a)] if matches!(f.kind(a), Kind::Str | Kind::Num))
&& f.kind(*dst) == Kind::Str =>
{
let [Input::Reg(a)] = **args else { return };
let typed = match f.kind(a) {
Kind::Str => {
let typed = active & f.typed(a);
f.copy_typed(*dst, a, typed);
typed
}
_ => {
let typed = active & !f.boxed[a as usize] & !f.wide[a as usize];
let (ba, bd) = (a as usize * f.width, *dst as usize * f.width);
for lane in Lanes::of(typed) {
let start = f.arena.len() as u32;
Scaled::write(f.mant[ba + lane], f.scales[ba + lane], &mut f.arena);
f.spans[bd + lane] = (start, f.arena.len() as u32);
}
f.boxed[*dst as usize] &= !typed;
typed
}
};
let kind = FunctionKind::Internal(InternalFunction::String);
let Some(builtin) = Builtins::of(&kind) else {
return;
};
let mut null = None;
for lane in Lanes::of(active & !typed) {
if f.with(a, lane, |value| matches!(value, Variable::Null)) {
let r = null.get_or_insert_with(|| Builtins::call(builtin, &kind, &[Arg::Null])).clone();
f.write(*dst, lane, r);
continue;
}
let r = {
let value = f.arg_view(a, lane);
Builtins::call(builtin, &kind, &[value])
};
f.write(*dst, lane, r);
}
}
Op::Call { dst, kind, args } => {
let Some(builtin) = Builtins::of(kind) else {
let e = Ops::error("CallFunction", format!("Function `{kind}` not found"));
for lane in Lanes::of(active) {
f.fail(lane, e.clone());
}
return;
};
let mut done = Self::text_call(*dst, kind, args, active, f);
if done.is_empty() {
done = Self::number_call(*dst, kind, args, active, f)
| Self::list_call(*dst, kind, args, active, f)
| Self::date_call(*dst, kind, args, active, f);
}
done |= Self::member_call(*dst, kind, args, active & !done, f);
done |= Self::identity_call(*dst, kind, args, active & !done, f);
done |= Self::boxed_call(*dst, kind, args, active & !done, f);
let mut hint = 0usize;
let rest = active & !done;
if rest.any() && args.iter().all(|a| matches!(a, Input::Const(_))) {
let result = {
let values: smallvec::SmallVec<[Arg; 4]> = args
.iter()
.filter_map(|a| match *a {
Input::Const(id) => Some(Arg::of(&f.consts[id as usize])),
Input::Reg(_) => None,
})
.collect();
Builtins::call_hinted(builtin, kind, &values, &mut hint)
};
for lane in Lanes::of(rest) {
let copy = match &result {
Ok(Out::Var(value @ (Variable::Array(_) | Variable::Object(_)))) => Ok(Out::Var(value.deep_clone())),
other => other.clone(),
};
f.write_call(*dst, lane, copy);
}
return;
}
f.box_lists(args, active & !done);
for lane in Lanes::of(active & !done) {
let result = {
let values: smallvec::SmallVec<[Arg; 4]> = args
.iter()
.map(|a| match *a {
Input::Const(id) => Arg::of(&f.consts[id as usize]),
Input::Reg(r) => f.arg_view(r, lane),
})
.collect();
Builtins::call_hinted(builtin, kind, &values, &mut hint)
};
f.write_call(*dst, lane, result);
}
}
Op::Method { dst, kind, args } => {
let builtin = Builtins::method(kind);
f.box_lists(args, active);
let done = Self::date_method(*dst, kind, args, active, f);
for lane in Lanes::of(active & !done) {
let result = {
let values: smallvec::SmallVec<[Arg; 4]> = args
.iter()
.map(|a| match *a {
Input::Const(id) => Arg::of(&f.consts[id as usize]),
Input::Reg(r) => f.arg_view(r, lane),
})
.collect();
Builtins::call_method(builtin, kind, &values)
};
f.write(*dst, lane, result);
}
}
Op::AssignBegin { dst } => {
for lane in Lanes::of(active) {
f.set(*dst, lane, Variable::empty_object());
}
}
Op::AssignStep { object, key, value } => {
for lane in Lanes::of(active) {
let key = match Ops::assigned_key(f.take(*key, lane)) {
Ok(k) => k,
Err(e) => {
f.fail(lane, e);
continue;
}
};
let (obj, val) = (f.value(*object, lane), f.take(*value, lane));
let r = match ctx.envs.get_mut(f.rows[lane]) {
Some(env) => Ops::assign(env, &obj, &key, val),
None => Err(Ops::error(
"AssignedObjectStep",
"Failed to mutate existing env",
)),
};
if let Err(e) = r {
f.fail(lane, e);
}
}
}
Op::Closure(closure) => Self::closure(closure, active, f, rest, ctx),
Op::Rewind => {
for lane in Lanes::of(active) {
let row = f.rows[lane];
let root = ctx.roots.get(row).clone();
if let Some(env) = ctx.envs.get_mut(row) {
*env = root;
}
}
}
Op::DollarInsert { key, value } => {
for lane in Lanes::of(active) {
let row = f.rows[lane];
let v = f.value(*value, lane);
let Some(root) = ctx.roots.get_mut(row) else {
continue;
};
let dollar = match root.local(&Variable::dollar_key()) {
Some(existing @ Variable::Object(_)) => existing.shallow_clone(),
_ => {
let created = Variable::empty_object();
root.set_local(Variable::dollar_key(), created.clone());
created
}
};
let _ = dollar.dot_insert(key, v);
if let Some(env) = ctx.envs.get_mut(row) {
env.set_local(Variable::dollar_key(), dollar);
}
}
}
Op::Fail { error } => {
for lane in Lanes::of(active) {
f.fail(lane, error.clone());
}
}
_ => {}
}
}
}
+707
View File
@@ -0,0 +1,707 @@
use super::frame::Fault;
use super::frame::{Buffers, Frame};
use super::Executor;
use crate::compiler::Compare;
use crate::functions::{FunctionKind, InternalFunction};
use crate::lane::builtins::{Arg, Builtins, Out};
use crate::lane::columns::{Column, Values};
use crate::lane::mask::{LaneSet, Lanes};
use crate::lane::ops::Ops;
use crate::lane::program::{Input, Kind, NumCmp, NumOp, Operand, Reg};
use crate::lane::scaled::{Kernel, Scaled};
use crate::lexer::Bracket;
use crate::variable::Variable;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
impl Executor {
pub(super) fn reducer(kind: &FunctionKind) -> Option<InternalFunction> {
match kind {
FunctionKind::Internal(
function @ (InternalFunction::Sum
| InternalFunction::Avg
| InternalFunction::Min
| InternalFunction::Max),
) => Some(*function),
_ => None,
}
}
pub(super) fn reduce(
function: InternalFunction,
mut values: impl Iterator<Item = Option<(i64, u8)>>,
) -> Option<Out> {
let first = values.next()??;
let (mut acc, mut len) = (first, 1usize);
if matches!(function, InternalFunction::Sum | InternalFunction::Avg) {
acc = Scaled::add((0, 0), first, false)?;
}
for value in values {
let x = value?;
len += 1;
acc = match function {
InternalFunction::Sum | InternalFunction::Avg => Scaled::add(acc, x, false)?,
InternalFunction::Max if Scaled::compare(x, acc)?.is_ge() => x,
InternalFunction::Min if Scaled::compare(x, acc)?.is_lt() => x,
_ => acc,
};
}
let total = Scaled::decimal(acc.0, acc.1);
Some(Out::Num(match function {
InternalFunction::Avg => total.checked_div(Decimal::from(len))?,
_ => total,
}))
}
pub(super) fn reduce_items(
function: InternalFunction,
numbers: Option<(&[i64], &[u8])>,
) -> Option<(i64, u8)> {
let (mant, scales) = numbers?;
let scale = *scales.first()?;
let uniform = scales.iter().all(|s| *s == scale);
match function {
InternalFunction::Sum if uniform => match Self::reduce_ints(function, mant)? {
0 if scale > 0 => None,
total => Some((total, scale)),
},
InternalFunction::Min | InternalFunction::Max if uniform => {
Some((Self::reduce_ints(function, mant)?, scale))
}
_ => None,
}
}
pub(super) fn reduce_ints(function: InternalFunction, items: &[i64]) -> Option<i64> {
let first = *items.first()?;
match function {
InternalFunction::Min => Some(items.iter().copied().fold(first, i64::min)),
InternalFunction::Max => Some(items.iter().copied().fold(first, i64::max)),
_ => i64::try_from(items.iter().map(|x| *x as i128).sum::<i128>()).ok(),
}
}
pub(super) fn reduce_scaled(function: InternalFunction, mant: &[i64], scale: &[u8]) -> Option<(i64, u8)> {
let (&first, &unit) = (mant.first()?, scale.first()?);
if scale.iter().any(|s| *s != unit) {
return None;
}
match function {
InternalFunction::Min => Some((mant.iter().copied().fold(first, i64::min), unit)),
InternalFunction::Max => Some((mant.iter().copied().fold(first, i64::max), unit)),
_ => i64::try_from(mant.iter().map(|x| *x as i128).sum::<i128>()).ok().map(|n| (n, unit)),
}
}
pub(super) fn child_number(child: &Column, index: usize) -> Option<(i64, u8)> {
match (child.values, child.valid(index)) {
(Values::I64(v), true) => v.get(index).map(|n| (*n, 0)),
(Values::Dec(v), true) => v.get(index).and_then(Scaled::parts),
(Values::Scaled { mant, scale }, true) => Some((*mant.get(index)?, *scale.get(index)?)),
_ => None,
}
}
pub(super) fn list_call<M: LaneSet>(
dst: Reg,
kind: &FunctionKind,
args: &[Input],
active: M,
f: &mut Frame<M>,
) -> M {
let (Some(function), [Input::Reg(a)]) = (Self::reducer(kind), args) else {
return f.none();
};
if f.kind(*a) != Kind::List {
return f.none();
}
let mut done = f.none();
for lane in Lanes::of(active & !f.boxed[*a as usize]) {
let (x, y) = f.lists[f.at(*a, lane)];
if let Some((v, scale)) =
Self::reduce_items(function, f.items.numbers(x as usize, y as usize))
{
match f.kind(dst) {
Kind::Num => {
f.put_scaled(dst, lane, v, scale);
}
_ => f.write(dst, lane, Ok(Out::Num(Scaled::decimal(v, scale)))),
}
done.set(lane);
continue;
}
let values = (x as usize..y as usize).map(|i| f.items.number(i));
if let Some(out) = Self::reduce(function, values) {
f.write(dst, lane, Ok(out));
done.set(lane);
}
}
done
}
pub(super) fn number_call<M: LaneSet>(
dst: Reg,
kind: &FunctionKind,
args: &[Input],
active: M,
f: &mut Frame<M>,
) -> M {
let FunctionKind::Internal(function) = kind else {
return f.none();
};
let (a, places) = match args {
[Input::Reg(a)] => (*a, None),
[Input::Reg(a), Input::Const(id)] => match &f.consts[*id as usize] {
Variable::Number(n) => match n.to_u32().filter(|p| *p <= 28) {
Some(p) => (*a, Some(p as u8)),
None => return f.none(),
},
_ => return f.none(),
},
_ => return f.none(),
};
let op: fn(i64, u8, u8) -> Option<(i64, u8)> = match (function, places) {
(InternalFunction::Abs, None) => |m, s, _| Scaled::abs(m, s),
(InternalFunction::Floor, None) => |m, s, _| Scaled::floor(m, s),
(InternalFunction::Ceil, None) => |m, s, _| Scaled::ceil(m, s),
(InternalFunction::Round, _) => Scaled::round,
(InternalFunction::Trunc, _) => Scaled::trunc,
_ => return f.none(),
};
if f.kind(a) != Kind::Num || f.kind(dst) != Kind::Num {
return f.none();
}
let places = places.unwrap_or(0);
let lanes = active & !f.boxed[a as usize] & !f.wide[a as usize];
let (from, base) = (a as usize * f.width, dst as usize * f.width);
let mut done = f.none();
for lane in Lanes::of(lanes) {
if let Some((m, s)) = op(f.mant[from + lane], f.scales[from + lane], places) {
f.mant[base + lane] = m;
f.scales[base + lane] = s;
done.set(lane);
}
}
f.wide[dst as usize] &= !done;
f.boxed[dst as usize] &= !done;
done
}
#[inline(never)]
pub(super) fn scaled_num<M: LaneSet>(
op: NumOp,
dst: Reg,
a: Operand,
b: Operand,
lanes: M,
f: &mut Frame<M>,
) -> M {
let ok = lanes & !f.operand_wide(a) & !f.operand_wide(b);
if ok.is_empty() {
return f.none();
}
let width = f.width;
let mut buffers = std::mem::take(&mut f.buffers);
let Buffers {
m,
s,
ka,
sa,
kb,
sb,
} = &mut buffers;
if m.len() < width {
m.resize(width, 0);
s.resize(width, 0);
}
let (m, s) = (&mut m[..width], &mut s[..width]);
let mut done = f.none();
if let (Some((xa, ya)), Some((xb, yb))) = (f.side(a, ka, sa), f.side(b, kb, sb)) {
let uniform = (ok == M::all(width))
.then(|| Frame::<M>::uniform(ya, ok).zip(Frame::<M>::uniform(yb, ok)))
.flatten();
let vector = uniform.is_some_and(|(x, y)| !match op {
NumOp::Multiply => Kernel::multiply((xa, x), (xb, y), m, s),
NumOp::Subtract => Kernel::add((xa, x), (xb, y), true, m, s),
_ => Kernel::add((xa, x), (xb, y), false, m, s),
});
done = match vector {
true => ok,
false => {
let mut done = f.none();
for lane in Lanes::of(ok) {
let (x, y) = ((xa[lane], ya[lane]), (xb[lane], yb[lane]));
if let Some((mm, sc)) = op.scaled(x, y) {
m[lane] = mm;
s[lane] = sc;
done.set(lane);
}
}
done
}
};
}
let base = dst as usize * width;
match done == M::all(width) {
true => {
f.mant[base..base + width].copy_from_slice(m);
f.scales[base..base + width].copy_from_slice(s);
}
false => {
for lane in Lanes::of(done) {
f.mant[base + lane] = m[lane];
f.scales[base + lane] = s[lane];
}
}
}
f.wide[dst as usize] &= !done;
f.buffers = buffers;
done
}
const NARROW: usize = 8;
#[inline]
pub(super) fn scaled_at<M: LaneSet>(
o: Operand,
lane: usize,
f: &Frame<M>,
) -> Option<(i64, u8)> {
match o {
Operand::Num(n) => Scaled::parts(&n),
Operand::Reg(r) => {
let at = f.at(r, lane);
(!f.wide[r as usize].get(lane)).then(|| (f.mant[at], f.scales[at]))
}
}
}
pub(super) fn extreme<M: LaneSet>(
dst: Reg,
items: &[Operand],
largest: bool,
active: M,
f: &mut Frame<M>,
) {
let mut slow = f.none();
for lane in Lanes::of(active) {
let mut best: Option<(i64, u8)> = None;
let mut ok = true;
for o in items {
let boxed = matches!(o, Operand::Reg(r) if f.boxed[*r as usize].get(lane));
let Some(x) = Self::scaled_at(*o, lane, f).filter(|_| !boxed) else {
ok = false;
break;
};
best = match best.map(|b| Scaled::compare(x, b).map(|o| (b, o))) {
None => Some(x),
Some(None) => {
ok = false;
break;
}
Some(Some((b, order))) => match largest {
true => Some(if order.is_ge() { x } else { b }),
false => Some(if order.is_lt() { x } else { b }),
},
};
}
match (ok, best) {
(true, Some((m, s))) => {
f.put_scaled(dst, lane, m, s);
}
_ => slow.set(lane),
}
}
if slow.is_empty() {
return;
}
let kind = FunctionKind::Internal(if largest {
InternalFunction::Max
} else {
InternalFunction::Min
});
let Some(builtin) = Builtins::of(&kind) else {
return;
};
for lane in Lanes::of(slow) {
let values: Vec<Variable> = items
.iter()
.map(|o| match o {
Operand::Num(n) => Variable::Number(*n),
Operand::Reg(r) => f.value(*r, lane),
})
.collect();
let array = Variable::from_array(values);
let r = Builtins::call(builtin, &kind, &[Arg::of(&array)]);
f.write(dst, lane, r);
}
}
pub(super) fn lane_num<M: LaneSet>(
op: NumOp,
dst: Reg,
a: Operand,
b: Operand,
lanes: M,
f: &mut Frame<M>,
) -> M {
let mut done = f.none();
for lane in Lanes::of(lanes) {
let (Some(x), Some(y)) = (Self::scaled_at(a, lane, f), Self::scaled_at(b, lane, f))
else {
continue;
};
if let Some((m, s)) = op.scaled(x, y) {
f.put_scaled(dst, lane, m, s);
done.set(lane);
}
}
done
}
pub(super) fn lane_cmp<M: LaneSet>(
op: NumCmp,
a: Operand,
b: Operand,
lanes: M,
f: &Frame<M>,
) -> (M, M) {
let (mut done, mut word) = (f.none(), f.none());
for lane in Lanes::of(lanes) {
let (Some(x), Some(y)) = (Self::scaled_at(a, lane, f), Self::scaled_at(b, lane, f))
else {
continue;
};
if let Some(o) = Scaled::compare(x, y) {
word.put(lane, op.test(o));
done.set(lane);
}
}
(done, word)
}
pub(super) fn num<M: LaneSet>(
op: NumOp,
dst: Reg,
a: Operand,
b: Operand,
active: M,
f: &mut Frame<M>,
) {
let slow = active & (f.operand_boxed(a) | f.operand_boxed(b));
let fast = active & !slow;
let d = dst as usize;
f.boxed[d] &= !fast;
let done = match (op, f.width < Self::NARROW) {
(NumOp::Add | NumOp::Subtract | NumOp::Multiply, false) => {
Self::scaled_num(op, dst, a, b, fast, f)
}
_ => Self::lane_num(op, dst, a, b, fast, f),
};
for lane in Lanes::of(fast & !done) {
let (x, y) = (f.num(a, lane), f.num(b, lane));
let r = match op {
NumOp::Add => x.checked_add(y).ok_or("Add"),
NumOp::Subtract => x.checked_sub(y).ok_or("Subtract"),
NumOp::Multiply => x.checked_mul(y).ok_or("Multiply"),
NumOp::Divide => x.checked_div(y).ok_or(""),
NumOp::Modulo => x.checked_rem(y).ok_or(""),
};
match r {
Ok(v) => f.put_number(dst, lane, v),
Err("") => f.set(dst, lane, Variable::Null),
Err(name) => f.fail(lane, Ops::error(name, "Number overflow")),
}
}
for lane in Lanes::of(slow) {
let (x, y) = (f.operand_value(a, lane), f.operand_value(b, lane));
let numeric = matches!((&x, &y), (Variable::Number(_), Variable::Number(_)));
let unsupported = match op {
NumOp::Add => None,
NumOp::Subtract => Some("Subtract"),
NumOp::Multiply => Some("Multiply"),
NumOp::Divide => Some("Divide"),
NumOp::Modulo => Some("Modulo"),
};
if let (false, Some(opcode)) = (numeric, unsupported) {
f.fault(lane, Fault::Unsupported(opcode));
continue;
}
let r = match op {
NumOp::Add => Ops::add(x, y),
NumOp::Subtract => Ops::subtract(x, y),
NumOp::Multiply => Ops::multiply(x, y),
NumOp::Divide => Ops::divide(x, y),
NumOp::Modulo => Ops::modulo(x, y),
};
f.put(dst, lane, r);
}
}
fn constant_cmp<M: LaneSet>(
op: NumCmp,
a: Operand,
b: Operand,
ok: M,
f: &Frame<M>,
) -> Option<M> {
let (reg, n, op) = match (a, b) {
(Operand::Reg(r), Operand::Num(n)) => (r, n, op),
(Operand::Num(n), Operand::Reg(r)) => (r, n, op.mirrored()),
_ => return None,
};
let base = reg as usize * f.width;
let values = f.mant.get(base..base + f.width)?;
let scale = Frame::<M>::uniform(f.scales.get(base..base + f.width)?, ok)?;
let (k, s) = Scaled::parts(&n)?;
match Threshold::of(op, scale, k, s)? {
Threshold::At(op, k) => Some(Kernel::threshold::<M>(values, k, |o| op.test(o))),
Threshold::Never => Some(f.none()),
}
}
pub(super) fn negate<M: LaneSet>(dst: Reg, a: Reg, active: M, f: &mut Frame<M>) {
let typed = match (f.kind(a), f.kind(dst)) {
(Kind::Num, Kind::Num) => active & !f.boxed[a as usize],
_ => f.none(),
};
let wide = f.wide[a as usize];
let sb = a as usize * f.width;
for lane in Lanes::of(typed) {
let (m, s) = (f.mant[sb + lane], f.scales[sb + lane]);
match (wide.get(lane), m) {
(false, m) if m != 0 && m != i64::MIN => f.put_scaled(dst, lane, -m, s),
(false, m) => f.put_number(dst, lane, -Scaled::decimal(m, s)),
(true, _) => {
let n = f.nums[sb + lane];
f.put_number(dst, lane, -n);
}
}
}
f.boxed[dst as usize] &= !typed;
for lane in Lanes::of(active & !typed) {
let r = Ops::negate(f.take(a, lane));
f.put(dst, lane, r);
}
}
pub(super) fn scaled_cmp<M: LaneSet>(
op: NumCmp,
a: Operand,
b: Operand,
lanes: M,
f: &mut Frame<M>,
) -> (M, M) {
let ok = lanes & !f.operand_wide(a) & !f.operand_wide(b);
if ok.is_empty() {
return (f.none(), f.none());
}
if let Some(word) = Self::constant_cmp(op, a, b, ok, f) {
return (ok, word & ok);
}
let mut buffers = std::mem::take(&mut f.buffers);
let Buffers { ka, sa, kb, sb, .. } = &mut buffers;
let mut out = (f.none(), f.none());
if let (Some((xa, ya)), Some((xb, yb))) = (f.side(a, ka, sa), f.side(b, kb, sb)) {
let vector = Frame::<M>::uniform(ya, ok)
.zip(Frame::<M>::uniform(yb, ok))
.and_then(|(x, y)| Kernel::compare::<M>((xa, x), (xb, y), |o| op.test(o)));
out = match vector {
Some(word) => (ok, word & ok),
None => {
let (mut done, mut word) = (f.none(), f.none());
for lane in Lanes::of(ok) {
if let Some(o) = Scaled::compare((xa[lane], ya[lane]), (xb[lane], yb[lane]))
{
word.put(lane, op.test(o));
done.set(lane);
}
}
(done, word)
}
};
}
f.buffers = buffers;
out
}
pub(super) fn any_number<M: LaneSet>(a: Reg, id: u16, active: M, f: &mut Frame<M>) -> (M, M) {
let lanes = match (f.kind(a), &f.consts[id as usize]) {
(Kind::Num | Kind::Str, Variable::Array(_)) => active & !f.boxed[a as usize],
_ => return (f.none(), f.none()),
};
if f.kind(a) == Kind::Str {
let Variable::Array(list) = &f.consts[id as usize] else {
return (f.none(), f.none());
};
let list = list.borrow();
let texts: smallvec::SmallVec<[&str; 8]> =
list.iter().filter_map(Variable::as_str).collect();
let mut word = f.none();
for lane in Lanes::of(lanes) {
let x = f.text_at(a, lane);
word.put(lane, texts.contains(&x));
}
return (lanes, word);
}
let numbers: smallvec::SmallVec<[Decimal; 8]> = match &f.consts[id as usize] {
Variable::Array(list) => list
.borrow()
.iter()
.filter_map(Variable::as_number)
.collect(),
_ => return (f.none(), f.none()),
};
let (mut done, mut word) = (lanes, f.none());
for k in numbers {
let (d, w) =
Self::scaled_cmp(NumCmp::Equal, Operand::Reg(a), Operand::Num(k), lanes, f);
done &= d;
word |= w;
}
(done, word & done)
}
pub(super) fn within<M: LaneSet>(
a: Reg,
lo: Decimal,
hi: Decimal,
left: Bracket,
right: Bracket,
lanes: M,
f: &mut Frame<M>,
) -> (M, M) {
let order = |k: Decimal, f: &mut Frame<M>| {
let (d1, less) = Self::scaled_cmp(
NumCmp::Order(Compare::Less),
Operand::Reg(a),
Operand::Num(k),
lanes,
f,
);
let (d2, equal) =
Self::scaled_cmp(NumCmp::Equal, Operand::Reg(a), Operand::Num(k), lanes, f);
(d1 & d2, less, equal)
};
let (d1, lt_lo, eq_lo) = order(lo, f);
let (d2, lt_hi, eq_hi) = order(hi, f);
let done = d1 & d2;
let (gt_lo, gt_hi) = (!lt_lo & !eq_lo, !lt_hi & !eq_hi);
let (first, open) = match left {
Bracket::LeftParenthesis => (gt_lo, false),
Bracket::LeftSquareBracket => (gt_lo | eq_lo, false),
Bracket::RightParenthesis => (lt_lo, true),
Bracket::RightSquareBracket => (lt_lo | eq_lo, true),
_ => return (f.none(), f.none()),
};
let second = match right {
Bracket::RightParenthesis => lt_hi,
Bracket::RightSquareBracket => lt_hi | eq_hi,
Bracket::LeftParenthesis => gt_hi,
Bracket::LeftSquareBracket => gt_hi | eq_hi,
_ => return (f.none(), f.none()),
};
let word = match open {
true => first | second,
false => first & second,
};
(done, word & done)
}
#[inline(never)]
pub(super) fn cmp<M: LaneSet>(
op: NumCmp,
dst: Reg,
a: Operand,
b: Operand,
active: M,
f: &mut Frame<M>,
) {
let slow = active & (f.operand_boxed(a) | f.operand_boxed(b));
let fast = active & !slow;
let d = dst as usize;
let (done, mut word) = match f.width < Self::NARROW {
true => Self::lane_cmp(op, a, b, fast, f),
false => Self::scaled_cmp(op, a, b, fast, f),
};
for lane in Lanes::of(fast & !done) {
let (x, y) = (f.num(a, lane), f.num(b, lane));
let hit = match op {
NumCmp::Order(c) => Ops::ordered_number(&x, &y, c),
NumCmp::Equal => Ops::same_number(&x, &y),
};
word.put(lane, hit);
}
f.put_mask(d as Reg, fast, word);
for lane in Lanes::of(slow) {
let (x, y) = (f.operand_value(a, lane), f.operand_value(b, lane));
match op {
NumCmp::Order(c) => match Ops::compared(&x, &y, c) {
Some(hit) => f.set(dst, lane, Variable::Bool(hit)),
None => f.fault(lane, Fault::Unsupported("Compare")),
},
NumCmp::Equal => f.set(dst, lane, Variable::Bool(Ops::equal(&x, &y))),
}
}
}
}
impl NumOp {
#[inline(always)]
pub(super) fn scaled(self, x: (i64, u8), y: (i64, u8)) -> Option<(i64, u8)> {
match self {
NumOp::Multiply => Scaled::multiply(x, y),
NumOp::Subtract => Scaled::add(x, y, true),
NumOp::Divide => Scaled::divide(x, y),
NumOp::Modulo => Scaled::remainder(x, y),
NumOp::Add => Scaled::add(x, y, false),
}
}
}
impl NumCmp {
pub(super) fn mirrored(self) -> Self {
match self {
NumCmp::Order(Compare::More) => NumCmp::Order(Compare::Less),
NumCmp::Order(Compare::Less) => NumCmp::Order(Compare::More),
NumCmp::Order(Compare::MoreOrEqual) => NumCmp::Order(Compare::LessOrEqual),
NumCmp::Order(Compare::LessOrEqual) => NumCmp::Order(Compare::MoreOrEqual),
NumCmp::Equal => NumCmp::Equal,
}
}
#[inline(always)]
pub(super) fn test(self, o: std::cmp::Ordering) -> bool {
match self {
NumCmp::Equal => o.is_eq(),
NumCmp::Order(Compare::More) => o.is_gt(),
NumCmp::Order(Compare::MoreOrEqual) => o.is_ge(),
NumCmp::Order(Compare::Less) => o.is_lt(),
NumCmp::Order(Compare::LessOrEqual) => o.is_le(),
}
}
}
pub(super) enum Threshold {
At(NumCmp, i64),
Never,
}
impl Threshold {
pub(super) fn of(op: NumCmp, scale: u8, k: i64, s: u8) -> Option<Threshold> {
if s <= scale {
let k = k.checked_mul(*Scaled::POW10.get((scale - s) as usize)?)?;
return Some(Threshold::At(op, k));
}
let p = *Scaled::POW10.get((s - scale) as usize)?;
let floor = k.div_euclid(p);
let exact = k.rem_euclid(p) == 0;
let ceil = floor + (!exact) as i64;
Some(match op {
NumCmp::Order(Compare::More | Compare::LessOrEqual) => Threshold::At(op, floor),
NumCmp::Order(Compare::MoreOrEqual | Compare::Less) => Threshold::At(op, ceil),
NumCmp::Equal if exact => Threshold::At(op, floor),
NumCmp::Equal => Threshold::Never,
})
}
}
+223
View File
@@ -0,0 +1,223 @@
use super::frame::Frame;
use super::Executor;
use crate::functions::FunctionKind;
use crate::lane::builtins::{Text, TextKernel};
use crate::lane::mask::{LaneSet, Lanes};
use crate::lane::ops::Ops;
use crate::lane::program::{Input, Kind, Reg};
use crate::variable::Variable;
use zen_types::symbol::Symbol;
impl Executor {
pub(super) fn text_call<M: LaneSet>(
dst: Reg,
kind: &FunctionKind,
args: &[Input],
active: M,
f: &mut Frame<M>,
) -> M {
let Some(kernel) = Text::kernel(kind) else {
return f.none();
};
let (a, k) = match (kernel, args) {
(TextKernel::Test(_), [Input::Reg(a), Input::Const(id)]) => {
match &f.consts[*id as usize] {
Variable::String(k) => (*a, Some(k.clone())),
_ => return f.none(),
}
}
(TextKernel::Map(_) | TextKernel::Size, [Input::Reg(a)]) => (*a, None),
_ => return f.none(),
};
if f.kind(a) != Kind::Str {
return f.none();
}
Self::text_kernel(kernel, dst, a, active, k.as_deref(), f)
}
pub(super) fn text_kernel<M: LaneSet>(
kernel: TextKernel,
dst: Reg,
a: Reg,
lanes: M,
k: Option<&str>,
f: &mut Frame<M>,
) -> M {
let d = dst as usize;
let (base, from) = (d * f.width, a as usize * f.width);
let done = lanes & !f.boxed[a as usize];
match kernel {
TextKernel::Test(op) => {
let (Some(k), Kind::Bool) = (k, f.kind(dst)) else {
return f.none();
};
let mut word = f.none();
for lane in Lanes::of(done) {
word.put(lane, op.apply(f.text_at(a, lane), k));
}
f.bits[d] = (f.bits[d] & !done) | word;
}
TextKernel::Size => {
if f.kind(dst) != Kind::Num {
return f.none();
}
for lane in Lanes::of(done) {
let (x, y) = f.spans[from + lane];
f.mant[base + lane] = (y - x) as i64;
f.scales[base + lane] = 0;
}
f.wide[d] &= !done;
}
TextKernel::Map(op) => {
if f.kind(dst) != Kind::Str {
return f.none();
}
let spans = &f.spans[from..from + f.width];
let block = (done == M::all(f.width))
.then(|| Frame::<M>::block(spans))
.flatten()
.and_then(|(x, y)| f.arena.get(x..y).map(|t| (x, y, t)));
let bulk = match (op.bytewise(), block) {
(Some(bytewise), Some((x, y, text))) if text.is_ascii() => {
Some((Some(bytewise), x, y))
}
(None, Some((x, y, text)))
if spans.iter().all(|(p, q)| {
op.unchanged(
text.get(*p as usize - x..*q as usize - x)
.unwrap_or_default(),
)
}) =>
{
Some((None, x, y))
}
_ => None,
};
match bulk {
Some((None, _, _)) => {
for lane in 0..f.width {
f.spans[base + lane] = f.spans[from + lane];
}
}
Some((Some(bytewise), x, y)) => {
let origin = f.arena.len();
f.arena.extend_from_within(x..y);
if let Some(tail) = f.arena.get_mut(origin..) {
bytewise(tail);
}
let shift = origin as u32 - x as u32;
for lane in 0..f.width {
let (p, q) = f.spans[from + lane];
f.spans[base + lane] = (p + shift, q + shift);
}
}
None => {
let mut scratch = std::mem::take(&mut f.text);
scratch.clear();
let origin = f.arena.len() as u32;
let (arena, spans) = (&f.arena, &mut f.spans);
for lane in Lanes::of(done) {
let before = scratch.len() as u32;
let (x, y) = spans[from + lane];
let text = arena.get(x as usize..y as usize).unwrap_or_default();
spans[base + lane] = match op.apply(text, &mut scratch) {
Some((p, q)) => (x + p as u32, x + q as u32),
None => (origin + before, origin + scratch.len() as u32),
};
}
f.arena.push_str(&scratch);
f.text = scratch;
}
}
}
}
f.boxed[d] &= !done;
done
}
pub(super) fn join<M: LaneSet>(dst: Reg, parts: &[Input], active: M, f: &mut Frame<M>) {
let texts = f.kind(dst) == Kind::Str
&& parts.iter().all(|p| match p {
Input::Const(id) => matches!(f.consts[*id as usize], Variable::String(_)),
Input::Reg(r) => f.kind(*r) == Kind::Str,
});
let typed = match texts {
true => parts.iter().fold(active, |acc, p| match p {
Input::Reg(r) => acc & !f.boxed[*r as usize],
Input::Const(_) => acc,
}),
false => f.none(),
};
if typed.any() {
let mut text = std::mem::take(&mut f.text);
text.clear();
let origin = f.arena.len() as u32;
let base = dst as usize * f.width;
let (arena, spans, consts, width) =
(f.arena.as_str(), &mut f.spans, &f.consts, f.width);
for lane in Lanes::of(typed) {
let before = text.len() as u32;
for part in parts {
let piece = match part {
Input::Const(id) => consts[*id as usize].as_str().unwrap_or_default(),
Input::Reg(r) => {
let (x, y) = spans[*r as usize * width + lane];
arena.get(x as usize..y as usize).unwrap_or_default()
}
};
text.push_str(piece);
}
spans[base + lane] = (origin + before, origin + text.len() as u32);
}
f.arena.push_str(&text);
f.text = text;
f.boxed[dst as usize] &= !typed;
}
Self::join_rows(dst, parts, active & !typed, f);
}
pub(super) fn join_rows<M: LaneSet>(dst: Reg, parts: &[Input], active: M, f: &mut Frame<M>) {
let mut text = std::mem::take(&mut f.text);
let typed = f.kind(dst) == Kind::Str;
for lane in Lanes::of(active) {
text.clear();
let mut failed = None;
for (i, p) in parts.iter().enumerate() {
let pushed = match p {
Input::Const(id) => Self::push_text(&mut text, &f.consts[*id as usize]),
Input::Reg(r) if f.kind(*r) == Kind::Str && !f.boxed[*r as usize].get(lane) => {
text.push_str(f.text_at(*r, lane));
true
}
Input::Reg(r) => f.with(*r, lane, |v| Self::push_text(&mut text, v)),
};
if !pushed {
failed = Some(i);
break;
}
}
match (failed, typed) {
(Some(i), _) => f.fail(
lane,
Ops::error("Join", format!("Unexpected type in array on index {i}")),
),
(None, true) => {
f.put_text(dst, lane, &text);
f.boxed[dst as usize].unset(lane);
}
(None, false) => f.set(dst, lane, Variable::String(Symbol::from(text.as_str()))),
}
}
f.text = text;
}
pub(super) fn push_text(text: &mut String, v: &Variable) -> bool {
match v {
Variable::String(s) => {
text.push_str(s);
true
}
_ => false,
}
}
}
+117
View File
@@ -0,0 +1,117 @@
use crate::lane::date::Date;
use crate::lexer::Bracket;
use crate::variable::DynamicVariable;
use crate::Variable;
use anyhow::anyhow;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use serde_json::Value;
use std::any::Any;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone)]
pub(crate) struct Interval {
pub left_bracket: Bracket,
pub right_bracket: Bracket,
pub left: IntervalData,
pub right: IntervalData,
}
impl DynamicVariable for Interval {
fn type_name(&self) -> &'static str {
"interval"
}
fn as_any(&self) -> &dyn Any {
self
}
fn to_value(&self) -> Value {
Value::String(self.to_string())
}
}
impl Interval {
pub fn to_array(&self) -> Option<Vec<Variable>> {
let (left, right) = match (&self.left, &self.right) {
(IntervalData::Number(l), IntervalData::Number(r)) => (*l, *r),
_ => return None,
};
let start = match &self.left_bracket {
Bracket::LeftParenthesis => left.to_i64()? + 1,
Bracket::LeftSquareBracket => left.to_i64()?,
_ => return None,
};
let end = match &self.right_bracket {
Bracket::RightParenthesis => right.to_i64()? - 1,
Bracket::RightSquareBracket => right.to_i64()?,
_ => return None,
};
let list = (start..=end)
.map(|n| Variable::Number(Decimal::from(n)))
.collect::<Vec<_>>();
Some(list)
}
pub fn includes(&self, v: IntervalData) -> anyhow::Result<bool> {
let mut is_open = false;
let l = &self.left;
let r = &self.right;
let first = match &self.left_bracket {
Bracket::LeftParenthesis => l < &v,
Bracket::LeftSquareBracket => l <= &v,
Bracket::RightParenthesis => {
is_open = true;
l > &v
}
Bracket::RightSquareBracket => {
is_open = true;
l >= &v
}
_ => return Err(anyhow!("Unsupported bracket")),
};
let second = match &self.right_bracket {
Bracket::RightParenthesis => r > &v,
Bracket::RightSquareBracket => r >= &v,
Bracket::LeftParenthesis => r < &v,
Bracket::LeftSquareBracket => r <= &v,
_ => return Err(anyhow!("Unsupported bracket")),
};
let open_stmt = is_open && (first || second);
let closed_stmt = !is_open && first && second;
Ok(open_stmt || closed_stmt)
}
}
impl Display for Interval {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}..{}{}",
self.left_bracket, self.left, self.right, self.right_bracket
)
}
}
#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq)]
pub(crate) enum IntervalData {
Number(Decimal),
Date(Date),
}
impl Display for IntervalData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
IntervalData::Number(n) => write!(f, "{n}"),
IntervalData::Date(d) => write!(f, "{d}"),
}
}
}
+478
View File
@@ -0,0 +1,478 @@
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
pub const LANES: usize = 1024;
const WORDS: usize = LANES / 64;
#[derive(Clone, Copy, Debug)]
pub struct Mask {
words: [u64; WORDS],
used: u8,
}
impl Default for Mask {
fn default() -> Self {
Self::none(LANES)
}
}
impl Mask {
#[inline]
pub fn span(width: usize) -> usize {
width.div_ceil(64).clamp(1, WORDS)
}
#[inline]
pub fn none(width: usize) -> Self {
Self {
words: [0; WORDS],
used: Self::span(width) as u8,
}
}
#[inline]
pub fn all(width: usize) -> Self {
let mut mask = Self::none(width);
if width <= 64 {
mask.words[0] = if width == 64 {
u64::MAX
} else {
(1u64 << width) - 1
};
return mask;
}
let full = width / 64;
mask.words[..full.min(WORDS)].fill(u64::MAX);
if full < WORDS && !width.is_multiple_of(64) {
mask.words[full] = (1u64 << (width % 64)) - 1;
}
mask
}
#[inline]
pub fn bit(words: &[u64], at: usize) -> bool {
words.get(at / 64).is_some_and(|w| w >> (at % 64) & 1 == 1)
}
#[inline]
pub fn used(&self) -> &[u64] {
&self.words[..self.used as usize]
}
#[inline]
pub fn used_mut(&mut self) -> &mut [u64] {
&mut self.words[..self.used as usize]
}
#[inline(always)]
pub fn word(&self, index: usize) -> u64 {
self.words[index & (WORDS - 1)]
}
#[inline(always)]
pub fn set_word(&mut self, index: usize, word: u64) {
self.words[index & (WORDS - 1)] = word;
}
#[inline(always)]
pub fn get(&self, lane: usize) -> bool {
self.words[(lane >> 6) & (WORDS - 1)] >> (lane & 63) & 1 == 1
}
#[inline(always)]
pub fn set(&mut self, lane: usize) {
self.words[(lane >> 6) & (WORDS - 1)] |= 1 << (lane & 63);
}
#[inline(always)]
pub fn unset(&mut self, lane: usize) {
self.words[(lane >> 6) & (WORDS - 1)] &= !(1 << (lane & 63));
}
#[inline(always)]
pub fn put(&mut self, lane: usize, on: bool) {
let w = &mut self.words[(lane >> 6) & (WORDS - 1)];
*w = (*w & !(1 << (lane & 63))) | ((on as u64) << (lane & 63));
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
match self.used {
1 => self.words[0] == 0,
_ => self.used().iter().all(|w| *w == 0),
}
}
#[inline]
pub fn count(&self) -> usize {
self.used().iter().map(|w| w.count_ones() as usize).sum()
}
#[inline]
pub fn first(&self) -> Option<usize> {
self.used()
.iter()
.enumerate()
.find(|(_, w)| **w != 0)
.map(|(i, w)| i * 64 + w.trailing_zeros() as usize)
}
#[inline(always)]
fn zip(self, other: Mask, f: impl Fn(u64, u64) -> u64) -> Mask {
if self.used == 1 && other.used == 1 {
let mut out = self;
out.words[0] = f(self.words[0], other.words[0]);
return out;
}
let mut out = if self.used >= other.used { self } else { other };
for i in 0..out.used as usize {
out.words[i] = f(self.words[i], other.words[i]);
}
out
}
}
impl PartialEq for Mask {
#[inline]
fn eq(&self, other: &Mask) -> bool {
let used = self.used.max(other.used) as usize;
self.words[..used] == other.words[..used]
}
}
impl Eq for Mask {}
impl BitAnd for Mask {
type Output = Mask;
#[inline]
fn bitand(self, other: Mask) -> Mask {
self.zip(other, |a, b| a & b)
}
}
impl BitOr for Mask {
type Output = Mask;
#[inline]
fn bitor(self, other: Mask) -> Mask {
self.zip(other, |a, b| a | b)
}
}
impl Not for Mask {
type Output = Mask;
#[inline(always)]
fn not(self) -> Mask {
let mut out = self;
if out.used == 1 {
out.words[0] = !out.words[0];
return out;
}
for w in out.used_mut() {
*w = !*w;
}
out
}
}
impl BitAndAssign for Mask {
#[inline]
fn bitand_assign(&mut self, other: Mask) {
*self = *self & other;
}
}
impl BitOrAssign for Mask {
#[inline]
fn bitor_assign(&mut self, other: Mask) {
*self = *self | other;
}
}
pub trait LaneSet:
Copy
+ Eq
+ std::fmt::Debug
+ Default
+ BitAnd<Output = Self>
+ BitOr<Output = Self>
+ Not<Output = Self>
+ BitAndAssign
+ BitOrAssign
{
const LANES: usize;
fn none(width: usize) -> Self;
fn all(width: usize) -> Self;
fn words(&self) -> usize;
fn word(&self, index: usize) -> u64;
fn set_word(&mut self, index: usize, word: u64);
fn get(&self, lane: usize) -> bool;
fn set(&mut self, lane: usize);
fn unset(&mut self, lane: usize);
fn put(&mut self, lane: usize, on: bool);
fn is_empty(&self) -> bool;
fn count(&self) -> usize;
fn first(&self) -> Option<usize>;
#[inline]
fn any(&self) -> bool {
!self.is_empty()
}
#[inline]
fn store(&self, target: &mut [u64], at: usize) {
for i in 0..self.words() {
if let Some(slot) = target.get_mut(at + i) {
*slot = self.word(i);
}
}
}
}
impl LaneSet for Mask {
const LANES: usize = LANES;
#[inline(always)]
fn none(width: usize) -> Self {
Mask::none(width)
}
#[inline(always)]
fn all(width: usize) -> Self {
Mask::all(width)
}
#[inline(always)]
fn words(&self) -> usize {
self.used as usize
}
#[inline(always)]
fn word(&self, index: usize) -> u64 {
Mask::word(self, index)
}
#[inline(always)]
fn set_word(&mut self, index: usize, word: u64) {
Mask::set_word(self, index, word)
}
#[inline(always)]
fn get(&self, lane: usize) -> bool {
Mask::get(self, lane)
}
#[inline(always)]
fn set(&mut self, lane: usize) {
Mask::set(self, lane)
}
#[inline(always)]
fn unset(&mut self, lane: usize) {
Mask::unset(self, lane)
}
#[inline(always)]
fn put(&mut self, lane: usize, on: bool) {
Mask::put(self, lane, on)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Mask::is_empty(self)
}
#[inline(always)]
fn count(&self) -> usize {
Mask::count(self)
}
#[inline(always)]
fn first(&self) -> Option<usize> {
Mask::first(self)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Word(u64);
impl LaneSet for Word {
const LANES: usize = 64;
#[inline]
fn none(_: usize) -> Self {
Word(0)
}
#[inline]
fn all(width: usize) -> Self {
Word(if width >= 64 {
u64::MAX
} else {
(1u64 << width) - 1
})
}
#[inline]
fn words(&self) -> usize {
1
}
#[inline(always)]
fn word(&self, index: usize) -> u64 {
if index == 0 {
self.0
} else {
0
}
}
#[inline(always)]
fn set_word(&mut self, index: usize, word: u64) {
if index == 0 {
self.0 = word;
}
}
#[inline(always)]
fn get(&self, lane: usize) -> bool {
self.0 >> (lane & 63) & 1 == 1
}
#[inline(always)]
fn set(&mut self, lane: usize) {
self.0 |= 1 << (lane & 63);
}
#[inline(always)]
fn unset(&mut self, lane: usize) {
self.0 &= !(1 << (lane & 63));
}
#[inline(always)]
fn put(&mut self, lane: usize, on: bool) {
self.0 = (self.0 & !(1 << (lane & 63))) | ((on as u64) << (lane & 63));
}
#[inline]
fn is_empty(&self) -> bool {
self.0 == 0
}
#[inline]
fn count(&self) -> usize {
self.0.count_ones() as usize
}
#[inline]
fn first(&self) -> Option<usize> {
(self.0 != 0).then(|| self.0.trailing_zeros() as usize)
}
}
impl BitAnd for Word {
type Output = Word;
#[inline]
fn bitand(self, other: Word) -> Word {
Word(self.0 & other.0)
}
}
impl BitOr for Word {
type Output = Word;
#[inline]
fn bitor(self, other: Word) -> Word {
Word(self.0 | other.0)
}
}
impl Not for Word {
type Output = Word;
#[inline]
fn not(self) -> Word {
Word(!self.0)
}
}
impl BitAndAssign for Word {
#[inline]
fn bitand_assign(&mut self, other: Word) {
self.0 &= other.0;
}
}
impl BitOrAssign for Word {
#[inline]
fn bitor_assign(&mut self, other: Word) {
self.0 |= other.0;
}
}
pub struct Lanes<M> {
mask: M,
index: usize,
current: u64,
}
impl<M: LaneSet> Lanes<M> {
#[inline]
pub fn of(mask: M) -> Self {
Self {
current: mask.word(0),
mask,
index: 0,
}
}
}
impl<M: LaneSet> Iterator for Lanes<M> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
loop {
if self.current != 0 {
let bit = self.current.trailing_zeros() as usize;
self.current &= self.current - 1;
return Some(self.index * 64 + bit);
}
self.index += 1;
if self.index >= self.mask.words() {
return None;
}
self.current = self.mask.word(self.index);
}
}
}
#[cfg(test)]
mod tests {
use super::{LaneSet, Mask, Word};
#[test]
fn lanes_and_ops() {
let mut m = Mask::none(300);
for lane in [0, 63, 64, 129, 299] {
m.set(lane);
}
assert_eq!(
super::Lanes::of(m).collect::<Vec<_>>(),
vec![0, 63, 64, 129, 299]
);
assert_eq!(m.count(), 5);
assert_eq!(m.first(), Some(0));
let all = Mask::all(300);
assert_eq!(all.count(), 300);
assert_eq!((!m & all).count(), 295);
assert!(Mask::none(1).is_empty());
assert_eq!(Mask::all(64).count(), 64);
assert_eq!(Mask::all(1024).count(), 1024);
let w = Word::all(10) & !Word::none(10);
assert_eq!(super::Lanes::of(w).count(), 10);
}
}
+960
View File
@@ -0,0 +1,960 @@
mod builtins;
mod cells;
mod columns;
mod compile;
mod date;
mod exec;
mod interval;
mod mask;
mod ops;
mod output;
mod program;
mod scaled;
mod source;
pub use cells::{CellEnv, CellSet, Pieces};
pub use columns::{Column, Columns, Dictionary, Values};
pub use compile::{Hints, LaneCompiler};
pub use exec::{Context, Executor, Fault, Frame};
pub use mask::{LaneSet, Mask, Word, LANES};
pub use output::{Cell, Output, Shape};
pub use source::SourceInfo;
pub use program::{Binary, Binding, ClosureOp, Const, Kind, Layout, Op, Program, Reg, Step};
use crate::lexer::Lexer;
use crate::parser::{Node, Parser};
use crate::scope::Scope;
use crate::variable::Variable;
use crate::{ExpressionKind, IsolateError};
use bumpalo::Bump;
#[derive(Debug, Clone)]
enum Source {
Single(std::sync::Arc<str>),
Many(std::sync::Arc<[(String, String)]>, bool),
Cells(std::sync::Arc<[(String, Option<String>)]>),
}
#[derive(Debug, Clone)]
pub struct LaneProgram {
program: Program,
kind: ExpressionKind,
source: Source,
constant: Option<Const>,
}
impl LaneProgram {
const NODES: usize = 20_000;
fn guard<'n>(roots: impl IntoIterator<Item = &'n Node<'n>>) -> Result<(), IsolateError> {
let count = std::cell::Cell::new(0usize);
for root in roots {
root.walk(|_| count.set(count.get() + 1));
}
match count.get() > Self::NODES {
false => Ok(()),
true => Err(IsolateError::VMError {
source: crate::vm::VMError::OpcodeErr {
opcode: "Compile".to_string(),
message: format!(
"expression is too large for the lane VM ({} nodes, limit {})",
count.get(),
Self::NODES
),
},
}),
}
}
pub fn compile(source: &str, kind: ExpressionKind) -> Result<Self, IsolateError> {
Self::compile_with(source, kind, None)
}
pub fn compile_with(
source: &str,
kind: ExpressionKind,
hints: Option<&Hints>,
) -> Result<Self, IsolateError> {
let bump = Bump::new();
let mut lexer = Lexer::new();
let tokens = lexer.tokenize(&bump, source)?;
let parser = Parser::try_new(&tokens, &bump)?;
let parsed = match kind {
ExpressionKind::Standard => parser.standard().parse(),
ExpressionKind::Unary => parser.unary().parse(),
};
parsed.error()?;
Self::guard([parsed.root])?;
let program = LaneCompiler::compile_with(parsed.root, hints)?;
let constant = match kind {
ExpressionKind::Standard => Const::of(parsed.root),
ExpressionKind::Unary => None,
};
Ok(Self {
program,
kind,
source: Source::Single(source.into()),
constant,
})
}
fn recompile(&self, hints: &Hints) -> Result<Self, IsolateError> {
match &self.source {
Source::Single(source) => Self::compile_with(source, self.kind.clone(), Some(hints)),
Source::Many(entries, chain) => {
let refs: Vec<(&str, &str)> = entries
.iter()
.map(|(k, s)| (k.as_str(), s.as_str()))
.collect();
Self::compile_many_with(&refs, *chain, Some(hints))
}
Source::Cells(cells) => {
let refs: Vec<(&str, Option<&str>)> = cells.iter().map(|(s, f)| (s.as_str(), f.as_deref())).collect();
Self::compile_cells_with(&refs, Some(hints))
}
}
}
pub fn source(&self) -> Option<&str> {
match &self.source {
Source::Single(source) => Some(source),
_ => None,
}
}
pub fn compile_cells(cells: &[(&str, Option<&str>)]) -> Result<Self, IsolateError> {
Self::compile_cells_with(cells, None)
}
fn compile_cells_with(cells: &[(&str, Option<&str>)], hints: Option<&Hints>) -> Result<Self, IsolateError> {
let bump = Bump::new();
let mut lexer = Lexer::new();
let mut roots = Vec::with_capacity(cells.len());
for (index, (source, field)) in cells.iter().enumerate() {
let tokens = lexer.tokenize(&bump, source)?;
let parser = Parser::try_new(&tokens, &bump)?;
let root = match field {
Some(field) => {
let parsed = parser.unary().parse();
parsed.error()?;
let tokens = lexer.tokenize(&bump, field)?;
let target = Parser::try_new(&tokens, &bump)?.standard().parse();
target.error()?;
Self::rooted(&bump, parsed.root, target.root).ok_or_else(|| Self::unsupported("cell"))?
}
None => {
let parsed = parser.standard().parse();
parsed.error()?;
parsed.root
}
};
let key: &str = bump.alloc_str(&format!("c{index}"));
roots.push((key, root));
}
Self::guard(roots.iter().map(|(_, root)| *root))?;
let program = LaneCompiler::compile_isolated(&roots, hints)?;
let owned: Vec<(String, Option<String>)> = cells.iter().map(|(s, f)| (s.to_string(), f.map(str::to_string))).collect();
Ok(Self {
program,
kind: ExpressionKind::Standard,
source: Source::Cells(owned.into()),
constant: None,
})
}
fn unsupported(what: &str) -> IsolateError {
IsolateError::VMError {
source: crate::vm::VMError::OpcodeErr {
opcode: "Compile".to_string(),
message: format!("{what} is not supported in a combined cell program"),
},
}
}
fn rooted<'b>(bump: &'b Bump, node: &'b Node<'b>, root: &'b Node<'b>) -> Option<&'b Node<'b>> {
let map = |n: &'b Node<'b>| Self::rooted(bump, n, root);
let list = |items: &'b [&'b Node<'b>]| -> Option<&'b [&'b Node<'b>]> {
let mapped: Vec<&'b Node<'b>> = items.iter().map(|n| map(n)).collect::<Option<_>>()?;
Some(bump.alloc_slice_copy(&mapped))
};
let rebuilt = match node {
Node::Identifier("$") => return Some(root),
Node::Null | Node::Bool(_) | Node::Number(_) | Node::String(_) | Node::Pointer | Node::Identifier(_) | Node::Root => {
return Some(node)
}
Node::TemplateString(parts) => Node::TemplateString(list(parts)?),
Node::Array(items) => Node::Array(list(items)?),
Node::Object(pairs) => {
let mapped: Vec<(&'b Node<'b>, &'b Node<'b>)> =
pairs.iter().map(|(k, v)| Some((map(k)?, map(v)?))).collect::<Option<_>>()?;
Node::Object(bump.alloc_slice_copy(&mapped))
}
Node::Closure { body, alias } => Node::Closure {
body: map(body)?,
alias: *alias,
},
Node::Parenthesized(inner) => Node::Parenthesized(map(inner)?),
Node::Member { node, property } => Node::Member {
node: map(node)?,
property: map(property)?,
},
Node::Slice { node, from, to } => Node::Slice {
node: map(node)?,
from: match from {
Some(n) => Some(map(n)?),
None => None,
},
to: match to {
Some(n) => Some(map(n)?),
None => None,
},
},
Node::Interval {
left,
right,
left_bracket,
right_bracket,
} => Node::Interval {
left: map(left)?,
right: map(right)?,
left_bracket: *left_bracket,
right_bracket: *right_bracket,
},
Node::Conditional {
condition,
on_true,
on_false,
} => Node::Conditional {
condition: map(condition)?,
on_true: map(on_true)?,
on_false: map(on_false)?,
},
Node::Unary { node, operator } => Node::Unary {
node: map(node)?,
operator: *operator,
},
Node::Binary { left, operator, right } => Node::Binary {
left: map(left)?,
operator: *operator,
right: map(right)?,
},
Node::FunctionCall { kind, arguments } => Node::FunctionCall {
kind: kind.clone(),
arguments: list(arguments)?,
},
Node::MethodCall { kind, this, arguments } => Node::MethodCall {
kind: kind.clone(),
this: map(this)?,
arguments: list(arguments)?,
},
Node::Assignments { .. } | Node::Error { .. } => return None,
};
Some(bump.alloc(rebuilt))
}
pub fn compile_typed(
source: &str,
kind: ExpressionKind,
input: &crate::variable::VariableType,
) -> Result<Self, IsolateError> {
use crate::intellisense::scope::IntelliSenseScope;
use crate::intellisense::type_provider::TypesProvider;
let bump = Bump::new();
let mut lexer = Lexer::new();
let tokens = lexer.tokenize(&bump, source)?;
let parser = Parser::try_new(&tokens, &bump)?;
let parsed = match kind {
ExpressionKind::Standard => parser.standard().parse(),
ExpressionKind::Unary => parser.unary().parse(),
};
parsed.error()?;
Self::guard([parsed.root])?;
let scope = IntelliSenseScope {
pointer_data: input.shallow_clone(),
root_data: input.shallow_clone(),
current_data: input.shallow_clone(),
..Default::default()
};
let types = TypesProvider::generate(parsed.root, scope, false);
let program = LaneCompiler::compile_typed(parsed.root, None, Some(&types))?;
Ok(Self {
program,
kind,
source: Source::Single(source.into()),
constant: None,
})
}
pub fn compile_many(entries: &[(&str, &str)], chain: bool) -> Result<Self, IsolateError> {
Self::compile_many_with(entries, chain, None)
}
fn compile_many_with(
entries: &[(&str, &str)],
chain: bool,
hints: Option<&Hints>,
) -> Result<Self, IsolateError> {
let bump = Bump::new();
let mut lexer = Lexer::new();
let mut roots = Vec::with_capacity(entries.len());
for (key, source) in entries {
let tokens = lexer.tokenize(&bump, source)?;
let parsed = Parser::try_new(&tokens, &bump)?.standard().parse();
parsed.error()?;
roots.push((*key, parsed.root));
}
Self::guard(roots.iter().map(|(_, root)| *root))?;
let program = LaneCompiler::compile_many(&roots, chain, hints)?;
let owned: Vec<(String, String)> = entries
.iter()
.map(|(k, s)| (k.to_string(), s.to_string()))
.collect();
Ok(Self {
program,
kind: ExpressionKind::Standard,
source: Source::Many(owned.into(), chain),
constant: None,
})
}
pub fn specialize(&self, samples: &[Scope]) -> Result<Self, IsolateError> {
let mut hints = Hints::default();
for key in &self.program.keys {
let segments: Vec<&str> = key.split('.').collect();
let mut counts = [0usize; 5];
for scope in samples {
Self::observe(scope.base(), &segments, &mut counts);
}
if let Some(kind) = Self::vote(counts) {
hints.insert(key.clone(), kind);
}
}
self.recompile(&hints)
}
fn vote(counts: [usize; 5]) -> Option<Kind> {
let [num, bool, str, other, _] = counts;
let total = num + bool + str + other;
match total {
0 => None,
_ if num * 2 > total => Some(Kind::Num),
_ if bool * 2 > total => Some(Kind::Bool),
_ if str * 2 > total => Some(Kind::Str),
_ => None,
}
}
fn column_hint(columns: &Columns, key: &str) -> Option<Kind> {
let segments: Vec<&str> = key.split('.').collect();
for split in (1..=segments.len()).rev() {
let last = segments[split - 1];
let (name, each) = match last.strip_suffix("[]") {
Some(name) => (name, true),
None => (last, false),
};
let mut path = segments[..split - 1].join(".");
if !path.is_empty() {
path.push('.');
}
path.push_str(name);
let Some(i) = columns.find(&path) else {
continue;
};
let column = &columns.columns[i].1;
let rest = &segments[split..];
if let (true, true, Values::List { child, .. }) = (each, rest.is_empty(), column.values)
{
return match child.kind() {
Kind::Dyn => None,
kind => Some(kind),
};
}
let mut counts = [0usize; 5];
for row in 0..columns.rows.min(256) {
let value = column.variable(row);
match (each, &value) {
(true, Variable::Array(items)) => {
for item in items.borrow().iter().take(64) {
Self::observe(item, rest, &mut counts);
}
}
(true, _) => {}
(false, v) => Self::observe(v, rest, &mut counts),
}
}
return Self::vote(counts);
}
None
}
pub fn specialize_bound(&self, columns: &Columns, bind: &dyn Fn(&str) -> Binding) -> Result<Self, IsolateError> {
let mut hints = Hints::default();
for key in &self.program.keys {
let kind = match bind(key) {
Binding::Column(i) => columns.columns.get(i).and_then(|(name, column)| match column.kind() {
Kind::Dyn => Self::column_hint(columns, name),
kind => Some(kind),
}),
_ => match columns.find(key).map(|i| columns.columns[i].1.kind()) {
Some(Kind::Dyn) | None => Self::column_hint(columns, key),
other => other,
},
};
if let Some(kind) = kind {
hints.insert(key.clone(), kind);
}
}
self.recompile(&hints)
}
pub fn specialize_columns(&self, columns: &Columns) -> Result<Self, IsolateError> {
let mut hints = Hints::default();
for key in &self.program.keys {
let exact = columns.find(key).map(|i| columns.columns[i].1.kind());
let kind = match exact {
Some(Kind::Dyn) | None => Self::column_hint(columns, key),
other => other,
};
if let Some(kind) = kind {
hints.insert(key.clone(), kind);
}
}
self.recompile(&hints)
}
fn observe(value: &Variable, segments: &[&str], counts: &mut [usize; 5]) {
let Some((segment, rest)) = segments.split_first() else {
match value {
Variable::Number(_) => counts[0] += 1,
Variable::Bool(_) => counts[1] += 1,
Variable::String(_) => counts[2] += 1,
Variable::Null => counts[4] += 1,
_ => counts[3] += 1,
}
return;
};
let (name, each) = match segment.strip_suffix("[]") {
Some(name) => (name, true),
None => (*segment, false),
};
let next = match value {
Variable::Object(o) => o.borrow().get_str(name).cloned().unwrap_or(Variable::Null),
_ => Variable::Null,
};
match (each, &next) {
(true, Variable::Array(items)) => {
for item in items.borrow().iter().take(64) {
Self::observe(item, rest, counts);
}
}
(true, _) => {}
(false, v) => Self::observe(v, rest, counts),
}
}
pub fn object_fields(source: &str) -> Option<Vec<(String, String)>> {
let bump = Bump::new();
let mut lexer = Lexer::new();
let tokens = lexer.tokenize(&bump, source).ok()?;
let parsed = Parser::try_new(&tokens, &bump).ok()?.with_metadata().standard().parse();
parsed.error().ok()?;
let metadata = parsed.metadata.as_ref()?;
let Node::Object(pairs) = parsed.root else {
return None;
};
let mut fields: Vec<(String, String)> = Vec::with_capacity(pairs.len());
for (key, value) in pairs.iter() {
let Node::String(key) = key else {
return None;
};
if key.is_empty() || key.contains('.') || fields.iter().any(|(k, _)| k == key) {
return None;
}
let (a, b) = metadata.get(&(*value as *const Node as usize))?.span;
let fragment = source.get(a as usize..b as usize)?;
let inner = Bump::new();
let mut relexer = Lexer::new();
let retokens = relexer.tokenize(&inner, fragment).ok()?;
let reparsed = Parser::try_new(&retokens, &inner).ok()?.standard().parse();
if reparsed.error().is_err() || reparsed.root != *value {
return None;
}
fields.push((key.to_string(), fragment.to_string()));
}
Some(fields)
}
pub fn standard(source: &str) -> Result<Self, IsolateError> {
Self::compile(source, ExpressionKind::Standard)
}
pub fn unary(source: &str) -> Result<Self, IsolateError> {
Self::compile(source, ExpressionKind::Unary)
}
pub fn kind(&self) -> &ExpressionKind {
&self.kind
}
pub fn path(&self) -> Option<&str> {
let p = &self.program;
match (p.steps.as_slice(), &p.layout, p.outputs.is_empty()) {
([step], None, true) => match &step.op {
Op::Env { dst, site, .. } | Op::Path { dst, site, .. } if *dst == p.out => {
p.site_keys.get(*site as usize)?.as_deref()
}
_ => None,
},
_ => None,
}
}
pub fn literal(&self) -> Option<Variable> {
if let Some(constant) = &self.constant {
return Some(constant.variable());
}
let p = &self.program;
match (p.steps.as_slice(), &p.layout, p.outputs.is_empty()) {
([step], None, true) => match step.op {
Op::Const { dst, id } if dst == p.out => p.consts.get(id as usize).map(Const::variable),
_ => None,
},
_ => None,
}
}
pub fn program(&self) -> &Program {
&self.program
}
}
#[derive(Debug, Default)]
pub struct LaneRunner {
frames: Vec<Frame<Word>>,
wide: Vec<Frame<Mask>>,
rows: Vec<u32>,
scopes: Vec<Scope>,
}
impl LaneRunner {
pub fn new() -> Self {
Self::default()
}
fn frames(&mut self, program: &Program) {
if self.frames.len() < program.frames {
self.frames.resize_with(program.frames, Frame::default);
}
}
fn wide(&mut self, program: &Program) {
if self.wide.len() < program.frames {
self.wide.resize_with(program.frames, Frame::default);
}
}
thread_local! {
static FOLD: std::cell::RefCell<Vec<Frame<Word>>> = Default::default();
}
pub(crate) fn constant(program: &Program) -> Option<Variable> {
Self::FOLD.with_borrow_mut(|frames| {
if frames.len() < program.frames {
frames.resize_with(program.frames, Frame::default);
}
let roots = [Scope::default()];
let mut ctx = Context::new(program, &roots);
Executor::run(program, frames, &mut ctx, &[0]);
frames.first_mut()?.take_result(program, 0).ok()
})
}
pub fn evaluate_one(
&mut self,
program: &LaneProgram,
scope: &Scope,
) -> Result<Variable, IsolateError> {
let p = &program.program;
self.frames(p);
let roots = std::slice::from_ref(scope);
let mut ctx = Context::new(p, roots);
Executor::run(p, &mut self.frames, &mut ctx, &[0]);
self.frames[0]
.take_result(p, 0)
.map_err(|source| IsolateError::VMError { source })
}
pub fn evaluate(
&mut self,
program: &LaneProgram,
scopes: &[Scope],
) -> Vec<Result<Variable, IsolateError>> {
let mut out = Vec::with_capacity(scopes.len());
self.evaluate_with(program, scopes, |_, r| out.push(r));
out
}
pub fn evaluate_with(
&mut self,
program: &LaneProgram,
scopes: &[Scope],
mut sink: impl FnMut(usize, Result<Variable, IsolateError>),
) {
let p = &program.program;
self.frames(p);
for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() {
self.rows.clear();
self.rows.extend(0..roots.len() as u32);
let mut ctx = Context::new(p, roots);
Executor::run(p, &mut self.frames, &mut ctx, &self.rows);
let frame = &mut self.frames[0];
for lane in 0..roots.len() {
let result = frame
.take_result(p, lane)
.map_err(|source| IsolateError::VMError { source });
sink(chunk * Word::LANES + lane, result);
}
}
}
pub fn evaluate_many(
&mut self,
program: &LaneProgram,
scopes: &[Scope],
mask: Option<&[bool]>,
mut sink: impl FnMut(usize, Option<Result<Vec<Variable>, (usize, IsolateError)>>),
) {
let p = &program.program;
self.frames(p);
for (chunk, roots) in scopes.chunks(Word::LANES).enumerate() {
let start = chunk * Word::LANES;
self.rows.clear();
self.rows.extend(0..roots.len() as u32);
let mut ctx = Context::new(p, roots);
let Some((frame, _)) = self.frames.split_first_mut() else {
return;
};
Executor::enter_top(p, frame, &self.rows);
if let Some(mask) = mask {
let mut bits = Word::none(roots.len());
for l in (0..roots.len()).filter(|l| mask.get(start + l).copied().unwrap_or(false))
{
bits.set(l);
}
frame.restrict(bits);
}
Executor::execute_top(p, &mut self.frames, &mut ctx);
let frame = &mut self.frames[0];
for lane in 0..roots.len() {
if !frame.active(lane) {
sink(start + lane, None);
continue;
}
let result = match frame.take_result(p, lane) {
Ok(_) => Ok(frame.outputs(p, lane)),
Err(source) => Err((
frame.stage_of(lane) as usize,
IsolateError::VMError { source },
)),
};
sink(start + lane, Some(result));
}
}
}
pub fn evaluate_bound(
&mut self,
program: &LaneProgram,
scopes: &[Scope],
columns: &Columns,
bind: &dyn Fn(&str) -> Binding,
subset: Option<&[usize]>,
mut sink: impl FnMut(usize, Result<Vec<Variable>, (usize, IsolateError)>),
) {
let p = &program.program;
let bound: Vec<Binding> = p
.site_keys
.iter()
.map(|k| match (p.writes_env, k.as_deref()) {
(true, _) | (_, None) => Binding::Row,
(false, Some(k)) => bind(k),
})
.collect();
let total = subset.map_or(scopes.len(), <[usize]>::len);
match total <= Word::LANES {
true => {
self.frames(p);
self.frames.iter_mut().for_each(Frame::forget);
let (frames, rows) = (&mut self.frames, &mut self.rows);
Self::bound_blocks(p, frames, rows, scopes, columns, &bound, subset, Word::LANES, &mut sink);
}
false => {
self.wide(p);
self.wide.iter_mut().for_each(Frame::forget);
let (frames, rows) = (&mut self.wide, &mut self.rows);
Self::bound_blocks(p, frames, rows, scopes, columns, &bound, subset, LANES, &mut sink);
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn evaluate_bound_into(
&mut self,
program: &LaneProgram,
scopes: &[Scope],
columns: &Columns,
bind: &dyn Fn(&str) -> Binding,
subset: Option<&[usize]>,
outs: &mut Vec<Output>,
failure: impl FnMut(usize, usize, Fault),
) {
let p = &program.program;
let bound: Vec<Binding> = p
.site_keys
.iter()
.map(|k| match (p.writes_env, k.as_deref()) {
(true, _) | (_, None) => Binding::Row,
(false, Some(k)) => bind(k),
})
.collect();
self.evaluate_sites(program, scopes, columns, &bound, subset, outs, failure)
}
#[allow(clippy::too_many_arguments)]
pub fn evaluate_sites(
&mut self,
program: &LaneProgram,
scopes: &[Scope],
columns: &Columns,
bound: &[Binding],
subset: Option<&[usize]>,
outs: &mut Vec<Output>,
mut failure: impl FnMut(usize, usize, Fault),
) {
let p = &program.program;
let total = subset.map_or(scopes.len(), <[usize]>::len);
let regs: Vec<Reg> = match p.outputs.is_empty() {
true => vec![p.out],
false => p.outputs.clone(),
};
outs.resize_with(regs.len(), Output::new);
for (reg, out) in regs.iter().zip(outs.iter_mut()) {
match (&p.layout, p.outputs.is_empty()) {
(Some(layout), true) => out.reset_layout(layout, &p.kinds, total),
_ => out.reset(p.kinds[*reg as usize], total),
}
}
let mut sink = |at: usize, stage: usize, fault| failure(at, stage, fault);
match total <= Word::LANES {
true => {
self.frames(p);
self.frames.iter_mut().for_each(Frame::forget);
let (frames, rows) = (&mut self.frames, &mut self.rows);
Self::export_blocks(p, frames, rows, scopes, columns, bound, subset, Word::LANES, outs, &mut sink);
}
false => {
self.wide(p);
self.wide.iter_mut().for_each(Frame::forget);
let (frames, rows) = (&mut self.wide, &mut self.rows);
Self::export_blocks(p, frames, rows, scopes, columns, bound, subset, LANES, outs, &mut sink);
}
}
}
#[allow(clippy::too_many_arguments)]
fn export_blocks<M: LaneSet>(
p: &Program,
frames: &mut [Frame<M>],
rows: &mut Vec<u32>,
scopes: &[Scope],
columns: &Columns,
bound: &[Binding],
subset: Option<&[usize]>,
width: usize,
outs: &mut [Output],
sink: &mut dyn FnMut(usize, usize, Fault),
) {
let total = subset.map_or(scopes.len(), <[usize]>::len);
let mut start = 0;
while start < total {
let n = (total - start).min(width);
rows.clear();
let (roots, base) = match subset {
None => {
rows.extend(0..n as u32);
(&scopes[start..start + n], start)
}
Some(list) => {
rows.extend(list[start..start + n].iter().map(|&r| r as u32));
(scopes, 0)
}
};
let mut ctx = Context::columnar(p, roots, columns, bound, base);
Executor::run(p, frames, &mut ctx, rows);
let Some(frame) = frames.first_mut() else {
return;
};
frame.export_outputs(p, outs, start, n, &mut *sink);
start += n;
}
}
#[allow(clippy::too_many_arguments)]
fn bound_blocks<M: LaneSet>(
p: &Program,
frames: &mut [Frame<M>],
rows: &mut Vec<u32>,
scopes: &[Scope],
columns: &Columns,
bound: &[Binding],
subset: Option<&[usize]>,
width: usize,
sink: &mut impl FnMut(usize, Result<Vec<Variable>, (usize, IsolateError)>),
) {
let many = !p.outputs.is_empty();
let total = subset.map_or(scopes.len(), <[usize]>::len);
let mut start = 0;
while start < total {
let n = (total - start).min(width);
rows.clear();
let (roots, base) = match subset {
None => {
rows.extend(0..n as u32);
(&scopes[start..start + n], start)
}
Some(list) => {
rows.extend(list[start..start + n].iter().map(|&r| r as u32));
(scopes, 0)
}
};
let mut ctx = Context::columnar(p, roots, columns, bound, base);
Executor::run(p, frames, &mut ctx, rows);
let Some(frame) = frames.first_mut() else {
return;
};
for lane in 0..n {
let row = match subset {
None => start + lane,
Some(list) => list[start + lane],
};
let result = match frame.take_result(p, lane) {
Ok(value) => Ok(match many {
true => frame.outputs(p, lane),
false => vec![value],
}),
Err(source) => Err((
frame.stage_of(lane) as usize,
IsolateError::VMError { source },
)),
};
sink(row, result);
}
start += n;
}
}
pub fn evaluate_columns(
&mut self,
program: &LaneProgram,
columns: &Columns,
mut sink: impl FnMut(usize, Result<Variable, IsolateError>),
) {
let p = &program.program;
self.columnar(p, columns, |frame, start, n| {
for lane in 0..n {
let result = frame
.take_result(p, lane)
.map_err(|source| IsolateError::VMError { source });
sink(start + lane, result);
}
});
}
pub fn evaluate_columns_into(
&mut self,
program: &LaneProgram,
columns: &Columns,
out: &mut Output,
) {
let p = &program.program;
match &p.layout {
Some(layout) => out.reset_layout(layout, &p.kinds, columns.rows),
None => out.reset(p.kinds[p.out as usize], columns.rows),
}
self.columnar(p, columns, |frame, start, n| frame.export(p, out, start, n));
}
fn columnar(
&mut self,
p: &Program,
columns: &Columns,
mut chunk: impl FnMut(&mut Frame<Mask>, usize, usize),
) {
self.wide(p);
let bound: Vec<Binding> = p
.site_keys
.iter()
.map(|k| match (p.writes_env, k.as_deref()) {
(true, _) | (_, None) => Binding::Row,
(false, Some(k)) => columns.bind(k),
})
.collect();
let rows = p.needs_rows(&bound);
self.wide.iter_mut().for_each(Frame::forget);
let mut start = 0;
while start < columns.rows {
let n = (columns.rows - start).min(LANES);
self.rows.clear();
self.rows.extend(0..n as u32);
self.scopes.clear();
if rows {
self.scopes
.extend((start..start + n).map(|r| Scope::new(columns.row(r))));
}
let mut ctx = Context::columnar(p, &self.scopes, columns, &bound, start);
Executor::run(p, &mut self.wide, &mut ctx, &self.rows);
chunk(&mut self.wide[0], start, n);
start += n;
}
}
}
pub struct Backend;
impl Backend {
thread_local! {
static STATE: std::cell::RefCell<BackendState> = Default::default();
}
pub fn run(
source: &str,
kind: ExpressionKind,
scope: &Scope,
) -> Result<Variable, IsolateError> {
Self::STATE.with_borrow_mut(|state| {
let BackendState {
runner,
standard,
unary,
} = state;
let programs = match kind {
ExpressionKind::Standard => standard,
ExpressionKind::Unary => unary,
};
if let Some(p) = programs.get(source) {
return runner.evaluate_one(p, scope);
}
let p = LaneProgram::compile(source, kind)?;
let result = runner.evaluate_one(&p, scope);
programs.insert(source.to_string(), p);
result
})
}
}
#[derive(Default)]
struct BackendState {
runner: LaneRunner,
standard: ahash::HashMap<String, LaneProgram>,
unary: ahash::HashMap<String, LaneProgram>,
}
+438
View File
@@ -0,0 +1,438 @@
use crate::compiler::{Compare, FetchFastTarget};
use crate::lane::builtins::{Arg, Builtins, Out, Text};
use crate::lane::date::{Date, DynamicVariableExt};
use crate::lane::interval::{Interval, IntervalData};
use crate::lexer::Bracket;
use crate::scope::Scope;
use crate::variable::Variable;
use crate::variable::Variable::*;
use crate::vm::VMError;
use crate::vm::VMError::*;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
use rust_decimal::{Decimal, MathematicalOps};
use std::rc::Rc;
use std::string::String as StdString;
use zen_types::symbol::Symbol;
pub(crate) struct Ops;
type VMResult<T> = Result<T, VMError>;
impl Ops {
pub(crate) fn error(opcode: &str, message: impl Into<StdString>) -> VMError {
OpcodeErr {
opcode: opcode.into(),
message: message.into(),
}
}
pub(crate) fn unsupported(opcode: &str) -> VMError {
Self::error(opcode, "Unsupported type")
}
pub(crate) fn fetch(a: Variable, b: Variable) -> VMResult<Variable> {
match (Date::textual(a), Date::textual(b)) {
(Object(o), String(s)) => Ok(o.borrow().get_str(s.as_str()).cloned().unwrap_or(Null)),
(Array(a), Number(n)) => {
let index = n
.to_usize()
.ok_or_else(|| Self::error("Fetch", "Failed to convert to usize"))?;
Ok(a.borrow().get(index).cloned().unwrap_or(Null))
}
(String(str), Number(n)) => {
let index = n
.to_usize()
.ok_or_else(|| Self::error("Fetch", "Failed to convert to usize"))?;
let slice = index.checked_add(1).and_then(|end| str.get(index..end));
Ok(slice.map_or(Null, |s| String(s.into())))
}
_ => Ok(Null),
}
}
pub(crate) fn step(
v: Variable,
target: &FetchFastTarget,
root: &Scope,
env: &Scope,
) -> Variable {
match target {
FetchFastTarget::Root => root.materialize(),
FetchFastTarget::Begin => env.materialize(),
FetchFastTarget::String(key) => match v {
Object(obj) => obj.borrow().get_str(key).cloned().unwrap_or(Null),
_ => Null,
},
FetchFastTarget::Number(num) => match Date::textual(v) {
Array(arr) => arr.borrow().get(*num as usize).cloned().unwrap_or(Null),
String(str) => {
let index = *num as usize;
str.get(index..index + 1)
.map(|slice| String(slice.into()))
.unwrap_or(Null)
}
_ => Null,
},
}
}
pub(crate) fn fetch_fast(path: &[FetchFastTarget], root: &Scope, env: &Scope) -> Variable {
let mut steps = path.iter();
let first = match steps.next() {
Some(FetchFastTarget::Root) => root.materialize(),
Some(FetchFastTarget::Begin) => match steps.clone().next() {
Some(FetchFastTarget::String(key)) => {
steps.next();
env.get_str(key).unwrap_or(Null)
}
_ => env.materialize(),
},
_ => Null,
};
steps.fold(first, |v, p| Self::step(v, p, root, env))
}
pub(crate) fn negate(a: Variable) -> VMResult<Variable> {
match a {
Number(n) => Ok(Number(-n)),
_ => Err(Self::unsupported("Negate")),
}
}
pub(crate) fn not(a: Variable) -> VMResult<Variable> {
match a {
Bool(b) => Ok(Bool(!b)),
_ => Err(Self::unsupported("Not")),
}
}
pub(crate) fn equal(a: &Variable, b: &Variable) -> bool {
match (a, b) {
(Number(a), Number(b)) => Self::same_number(a, b),
(Bool(a), Bool(b)) => a == b,
(String(a), String(b)) => a == b,
(Null, Null) => true,
(Dynamic(a), Dynamic(b)) => {
let (a, b) = (a.as_date(), b.as_date());
a.is_some() && b.is_some() && a == b
}
(Dynamic(a), b @ String(_)) | (b @ String(_), Dynamic(a)) => {
a.as_date().is_some_and(|a| a.matches(b))
}
_ => false,
}
}
pub(crate) fn truthy(a: &Variable, opcode: &str) -> VMResult<bool> {
match a {
Bool(b) => Ok(*b),
_ => Err(Self::unsupported(opcode)),
}
}
pub(crate) fn membership(a: Variable, b: &Variable) -> VMResult<bool> {
let a = match b {
Object(_) => Date::textual(a),
_ => a,
};
match (a, b) {
(Number(a), Array(b)) => Ok(b
.borrow()
.iter()
.any(|b| matches!(b, Number(b) if Self::same_number(&a, b)))),
(Number(v), Dynamic(d)) => {
let Some(i) = d.as_any().downcast_ref::<Interval>() else {
return Err(Self::unsupported("In"));
};
i.includes(IntervalData::Number(v))
.map_err(|err| Self::error("In", err.to_string()))
}
(Dynamic(d), Dynamic(i)) => {
let Some(d) = d.as_date() else {
return Err(Self::unsupported("In"));
};
let Some(i) = i.as_any().downcast_ref::<Interval>() else {
return Err(Self::unsupported("In"));
};
i.includes(IntervalData::Date(d))
.map_err(|err| Self::error("In", err.to_string()))
}
(Dynamic(a), Array(arr)) => {
let Some(a) = a.as_date() else {
return Err(Self::unsupported("In"));
};
Ok(arr.borrow().iter().any(|b| a.matches(b)))
}
(String(a), Array(b)) => {
let text = String(a.clone());
Ok(b.borrow().iter().any(|b| match b {
String(b) => &a == b,
Dynamic(d) => d.as_date().is_some_and(|d| d.matches(&text)),
_ => false,
}))
}
(String(a), Object(b)) => Ok(b.borrow().contains_key_str(a.as_str())),
(Bool(a), Array(b)) => Ok(b.borrow().iter().any(|b| matches!(b, Bool(b) if a == *b))),
(Null, Array(b)) => Ok(b.borrow().iter().any(|b| matches!(b, Null))),
_ => Err(Self::unsupported("In")),
}
}
#[inline]
pub(crate) fn order(a: &Decimal, b: &Decimal) -> std::cmp::Ordering {
match a.scale() == b.scale() {
true => a.mantissa().cmp(&b.mantissa()),
false => a.cmp(b),
}
}
#[inline]
pub(crate) fn same_number(a: &Decimal, b: &Decimal) -> bool {
Self::order(a, b).is_eq()
}
#[inline]
pub(crate) fn ordered_number(a: &Decimal, b: &Decimal, comparison: Compare) -> bool {
let o = Self::order(a, b);
match comparison {
Compare::More => o.is_gt(),
Compare::MoreOrEqual => o.is_ge(),
Compare::Less => o.is_lt(),
Compare::LessOrEqual => o.is_le(),
}
}
pub(crate) fn ordered<T: Ord>(a: &T, b: &T, comparison: Compare) -> bool {
match comparison {
Compare::More => a > b,
Compare::MoreOrEqual => a >= b,
Compare::Less => a < b,
Compare::LessOrEqual => a <= b,
}
}
pub(crate) fn compared(a: &Variable, b: &Variable, comparison: Compare) -> Option<bool> {
match (a, b) {
(Number(a), Number(b)) => Some(Self::ordered_number(a, b, comparison)),
(Dynamic(_), _) | (_, Dynamic(_)) => Self::compare(a, b, comparison).ok(),
_ => None,
}
}
pub(crate) fn compare(a: &Variable, b: &Variable, comparison: Compare) -> VMResult<bool> {
match (a, b) {
(Number(a), Number(b)) => Ok(Self::ordered_number(a, b, comparison)),
(Dynamic(a), Dynamic(b)) => match (a.as_date(), b.as_date()) {
(Some(a), Some(b)) => Ok(Self::ordered(&a, &b, comparison)),
_ => Err(Self::unsupported("Compare")),
},
(Dynamic(_), String(_)) | (String(_), Dynamic(_)) => {
let valid = |date: &Date| date.is_valid();
match (
Date::coerce(a).filter(valid),
Date::coerce(b).filter(valid),
) {
(Some(a), Some(b)) => Ok(Self::ordered(&a, &b, comparison)),
_ => Err(Self::unsupported("Compare")),
}
}
_ => Err(Self::unsupported("Compare")),
}
}
pub(crate) fn add(a: Variable, b: Variable) -> VMResult<Variable> {
match (Date::textual(a), Date::textual(b)) {
(Number(a), Number(b)) => a
.checked_add(b)
.map(Number)
.ok_or_else(|| Self::error("Add", "Number overflow")),
(String(a), String(b)) => {
let mut c = StdString::with_capacity(a.len() + b.len());
c.push_str(a.as_ref());
c.push_str(b.as_ref());
Ok(String(c.as_str().into()))
}
_ => Err(Self::unsupported("Add")),
}
}
pub(crate) fn subtract(a: Variable, b: Variable) -> VMResult<Variable> {
match (a, b) {
(Number(a), Number(b)) => a
.checked_sub(b)
.map(Number)
.ok_or_else(|| Self::error("Subtract", "Number overflow")),
_ => Err(Self::unsupported("Subtract")),
}
}
pub(crate) fn multiply(a: Variable, b: Variable) -> VMResult<Variable> {
match (a, b) {
(Number(a), Number(b)) => a
.checked_mul(b)
.map(Number)
.ok_or_else(|| Self::error("Multiply", "Number overflow")),
_ => Err(Self::unsupported("Multiply")),
}
}
pub(crate) fn divide(a: Variable, b: Variable) -> VMResult<Variable> {
match (a, b) {
(Number(a), Number(b)) => Ok(a.checked_div(b).map_or(Null, Number)),
_ => Err(Self::unsupported("Divide")),
}
}
pub(crate) fn modulo(a: Variable, b: Variable) -> VMResult<Variable> {
match (a, b) {
(Number(a), Number(b)) => Ok(a.checked_rem(b).map_or(Null, Number)),
_ => Err(Self::unsupported("Modulo")),
}
}
pub(crate) fn exponent(a: Variable, b: Variable) -> VMResult<Variable> {
match (a, b) {
(Number(a), Number(b)) => a
.checked_powd(b)
.or_else(|| Decimal::from_f64(a.to_f64()?.powf(b.to_f64()?)))
.map(Number)
.ok_or_else(|| Self::error("Exponent", "Failed to calculate exponent")),
_ => Err(Self::unsupported("Exponent")),
}
}
pub(crate) fn interval(
a: &Variable,
b: &Variable,
left_bracket: Bracket,
right_bracket: Bracket,
) -> VMResult<Variable> {
let (left, right) = match (a, b) {
(Number(a), Number(b)) => (IntervalData::Number(*a), IntervalData::Number(*b)),
(Dynamic(a), Dynamic(b)) => match (a.as_date(), b.as_date()) {
(Some(a), Some(b)) => {
(IntervalData::Date(a), IntervalData::Date(b))
}
_ => return Err(Self::unsupported("Interval")),
},
_ => return Err(Self::unsupported("Interval")),
};
Ok(Dynamic(Rc::new(Interval {
left_bracket,
right_bracket,
left,
right,
})))
}
pub(crate) fn slice(current: Variable, to: Variable, from: Variable) -> VMResult<Variable> {
let (Number(f), Number(t)) = (from, to) else {
return Err(Self::unsupported("Slice"));
};
let from = f
.to_usize()
.ok_or_else(|| Self::error("Slice", "Failed to get range from"))?;
let to = t
.to_usize()
.ok_or_else(|| Self::error("Slice", "Failed to get range to"))?;
match Date::textual(current) {
Array(a) => {
let arr = a.borrow();
let slice = arr
.get(from..=to)
.ok_or_else(|| Self::error("Slice", "Index out of range"))?;
Ok(Variable::from_array(slice.to_vec()))
}
String(s) => {
let slice = s
.get(from..=to)
.ok_or_else(|| Self::error("Slice", "Index out of range"))?;
Ok(String(slice.into()))
}
_ => Err(Self::unsupported("Slice")),
}
}
pub(crate) fn object_key(key: Variable) -> VMResult<Symbol> {
match key {
String(key) => Ok(Symbol::from(key.as_str())),
_ => Err(Self::error("Object", "Unexpected key value")),
}
}
pub(crate) fn assigned_key(key: Variable) -> VMResult<Symbol> {
match key {
String(key) => Ok(key),
_ => Err(Self::error("AssignedObjectStep", "Unexpected key value")),
}
}
pub(crate) fn assign(
env: &mut Scope,
assigned: &Variable,
key: &Symbol,
value: Variable,
) -> VMResult<()> {
if !matches!(env.base(), Object(_)) {
return Err(Self::error(
"AssignedObjectStep",
"Failed to mutate existing env",
));
}
match key.contains('.') {
false => env.set_local(Symbol::from(key.as_str()), value.clone()),
true => {
let Some(new_env) = env
.materialize()
.dot_insert_detached(key.as_ref(), value.clone())
else {
return Err(Self::error(
"AssignedObjectStep",
"Failed to mutate existing env",
));
};
*env = Scope::new(new_env);
}
}
assigned.dot_insert(key.as_ref(), value);
Ok(())
}
pub(crate) fn len(current: &Variable) -> VMResult<Variable> {
Builtins::raw(&Text::LEN, &[Arg::of(current)])
.map(Out::variable)
.map_err(|message| Self::error("Len", message))
}
pub(crate) fn flatten(current: Variable) -> VMResult<Variable> {
let Array(a) = current else {
return Err(Self::unsupported("Flatten"));
};
let arr = a.borrow();
let mut flat = Vec::with_capacity(arr.len());
arr.iter().for_each(|v| match v {
Array(b) => b.borrow().iter().for_each(|v| flat.push(v.clone())),
_ => flat.push(v.clone()),
});
Ok(Variable::from_array(flat))
}
pub(crate) fn elements(list: &Variable) -> VMResult<Variable> {
match list {
Array(_) => Ok(list.clone()),
_ => list
.dynamic::<Interval>()
.and_then(|s| s.to_array())
.map(Variable::from_array)
.ok_or_else(|| Self::unsupported("Begin")),
}
}
}
+600
View File
@@ -0,0 +1,600 @@
use crate::lane::date::Date;
use crate::lane::program::{Kind, Layout};
use crate::variable::{Variable, VariableMap};
use crate::vm::VMError;
use chrono::DateTime;
use chrono_tz::Tz;
use rust_decimal::Decimal;
use std::sync::Arc;
use zen_types::symbol::Symbol;
#[derive(Debug)]
pub enum Cell<'a> {
Number(Decimal),
Bool(bool),
Str(&'a str),
Date(Option<DateTime<Tz>>),
Value(&'a Variable),
Struct(&'a [(Arc<str>, Output)], usize),
List(&'a Output, usize, usize),
Error(&'a VMError),
}
#[derive(Debug, Clone)]
pub(crate) enum Item {
Num(i64, u8),
Text(u32, u32),
Bool(bool),
Value(Variable),
}
impl Item {
pub(crate) fn variable(&self, arena: &str) -> Variable {
match self {
Item::Num(m, s) => Variable::Number(Decimal::new(*m, *s as u32)),
Item::Text(a, b) => Variable::String(Symbol::from(
arena.get(*a as usize..*b as usize).unwrap_or_default(),
)),
Item::Bool(b) => Variable::Bool(*b),
Item::Value(v) => v.clone(),
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Items {
tags: Vec<u8>,
payload: Vec<i64>,
scales: Vec<u8>,
values: Vec<Variable>,
}
impl Items {
const NUM: u8 = 0;
const TEXT: u8 = 1;
const BOOL: u8 = 2;
const VALUE: u8 = 3;
pub(crate) fn len(&self) -> usize {
self.tags.len()
}
pub(crate) fn clear(&mut self) {
self.tags.clear();
self.payload.clear();
self.scales.clear();
self.values.clear();
}
pub(crate) fn truncate(&mut self, len: usize) {
self.tags.truncate(len);
self.payload.truncate(len);
self.scales.truncate(len);
let kept = self.tags.iter().filter(|t| **t == Self::VALUE).count();
self.values.truncate(kept);
}
pub(crate) fn push(&mut self, item: Item) {
let (tag, payload, scale) = match item {
Item::Num(m, s) => (Self::NUM, m, s),
Item::Text(a, b) => (Self::TEXT, ((a as i64) << 32) | b as i64, 0),
Item::Bool(b) => (Self::BOOL, b as i64, 0),
Item::Value(v) => {
self.values.push(v);
(Self::VALUE, self.values.len() as i64 - 1, 0)
}
};
self.tags.push(tag);
self.payload.push(payload);
self.scales.push(scale);
}
pub(crate) fn extend_nums(&mut self, mant: &[i64], scales: &[u8]) {
self.tags.resize(self.tags.len() + mant.len(), Self::NUM);
self.payload.extend_from_slice(mant);
self.scales.extend_from_slice(scales);
}
pub(crate) fn get(&self, index: usize) -> Item {
let (Some(tag), Some(payload), Some(scale)) = (
self.tags.get(index),
self.payload.get(index),
self.scales.get(index),
) else {
return Item::Value(Variable::Null);
};
match *tag {
Self::NUM => Item::Num(*payload, *scale),
Self::TEXT => Item::Text((*payload >> 32) as u32, *payload as u32),
Self::BOOL => Item::Bool(*payload != 0),
_ => Item::Value(
self.values
.get(*payload as usize)
.cloned()
.unwrap_or(Variable::Null),
),
}
}
pub(crate) fn number(&self, index: usize) -> Option<(i64, u8)> {
match self.tags.get(index) {
Some(&Self::NUM) => Some((*self.payload.get(index)?, *self.scales.get(index)?)),
_ => None,
}
}
pub(crate) fn extend_selected(&mut self, values: &[i64], truths: &[u64], a: usize, b: usize) {
let (Some(values), Some(words)) = (values.get(a..b), truths.get(a / 64..b.div_ceil(64)))
else {
return;
};
let start = self.payload.len();
self.payload.resize(start + values.len() + 1, 0);
let (out, first) = (&mut self.payload[start..], a / 64);
let mut k = 0;
for (i, v) in (a..b).zip(values) {
out[k] = *v;
k += ((words[i / 64 - first] >> (i % 64)) & 1) as usize;
}
self.payload.truncate(start + k);
self.tags.resize(start + k, Self::NUM);
self.scales.resize(start + k, 0);
}
pub(crate) fn numbers(&self, a: usize, b: usize) -> Option<(&[i64], &[u8])> {
let tags = self.tags.get(a..b)?;
tags.iter()
.all(|t| *t == Self::NUM)
.then(|| self.payload.get(a..b).zip(self.scales.get(a..b)))
.flatten()
}
pub(crate) fn variable(&self, index: usize, arena: &str) -> Variable {
self.get(index).variable(arena)
}
}
#[derive(Debug, Default)]
pub enum Shape {
#[default]
Scalar,
Struct(Vec<(Arc<str>, Output)>),
List(Box<Output>),
}
#[derive(Debug)]
pub struct Output {
rows: usize,
kind: Kind,
pending: bool,
pub(crate) shape: Shape,
pub(crate) mant: Vec<i64>,
pub(crate) scale: Vec<u8>,
pub(crate) dates: Vec<Option<DateTime<Tz>>>,
pub(crate) bits: Vec<u64>,
pub(crate) boxed: Vec<u64>,
pub(crate) failed: Vec<u64>,
pub(crate) values: Vec<Variable>,
pub(crate) offsets: Vec<u32>,
pub(crate) data: Vec<u8>,
pub(crate) extra: Vec<(u32, Variable)>,
pub(crate) errors: Vec<(u32, Failure)>,
}
#[derive(Debug, Clone)]
pub(crate) struct Failure {
fault: crate::lane::exec::Fault,
error: std::cell::OnceCell<VMError>,
}
impl Failure {
pub(crate) fn new(fault: crate::lane::exec::Fault) -> Self {
Self {
fault,
error: std::cell::OnceCell::new(),
}
}
fn error(&self) -> &VMError {
self.error.get_or_init(|| self.fault.clone().vm())
}
}
impl Default for Output {
fn default() -> Self {
Self {
rows: 0,
kind: Kind::Dyn,
pending: false,
shape: Shape::Scalar,
mant: Vec::new(),
scale: Vec::new(),
dates: Vec::new(),
bits: Vec::new(),
boxed: Vec::new(),
failed: Vec::new(),
values: Vec::new(),
offsets: Vec::new(),
data: Vec::new(),
extra: Vec::new(),
errors: Vec::new(),
}
}
}
impl Output {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn reset(&mut self, kind: Kind, rows: usize) {
let words = rows.div_ceil(64);
self.rows = rows;
self.kind = kind;
self.pending = false;
let child = match std::mem::take(&mut self.shape) {
Shape::List(child) => Some(child),
_ => None,
};
self.mant.clear();
self.scale.clear();
self.dates.clear();
self.values.clear();
self.offsets.clear();
self.data.clear();
self.extra.clear();
self.errors.clear();
match kind {
Kind::Num => {
self.mant.resize(rows, 0);
self.scale.resize(rows, 0);
}
Kind::Dyn => self.values.resize(rows, Variable::Null),
Kind::Str => self.offsets.push(0),
Kind::Date => self.dates.resize(rows, None),
Kind::Bool => {}
Kind::List => {
self.offsets.push(0);
let mut child = child.unwrap_or_default();
child.open();
self.shape = Shape::List(child);
}
}
for bits in [&mut self.bits, &mut self.boxed, &mut self.failed] {
bits.clear();
bits.resize(words, 0);
}
}
pub(crate) fn reset_layout(&mut self, layout: &Layout, kinds: &[Kind], rows: usize) {
match layout {
Layout::Value(reg) => self.reset(kinds[*reg as usize], rows),
Layout::Struct(fields) => {
self.reset(Kind::Bool, rows);
let mut outputs = match std::mem::take(&mut self.shape) {
Shape::Struct(outputs) if outputs.len() == fields.len() => outputs,
_ => fields
.iter()
.map(|(k, _)| (k.clone(), Output::new()))
.collect(),
};
for ((key, output), (name, field)) in outputs.iter_mut().zip(fields.iter()) {
key.clone_from(name);
output.reset_layout(field, kinds, rows);
}
self.shape = Shape::Struct(outputs);
}
Layout::List(items) => {
let mut child = match std::mem::take(&mut self.shape) {
Shape::List(child) => child,
_ => Box::default(),
};
self.reset(Kind::Bool, rows);
let width = items.len();
match Self::uniform(items, kinds) {
Some(kind) => child.reset(kind, rows * width),
None => child.reset(Kind::Dyn, rows * width),
}
self.offsets.extend((0..=rows).map(|r| (r * width) as u32));
self.shape = Shape::List(child);
}
}
}
fn open(&mut self) {
self.reset(Kind::Dyn, 0);
self.pending = true;
}
fn grow(&mut self) -> usize {
let row = self.rows;
self.rows += 1;
if row.is_multiple_of(64) {
for bits in [&mut self.bits, &mut self.boxed, &mut self.failed] {
bits.push(0);
}
}
row
}
pub(crate) fn extend_nums(&mut self, mant: &[i64], scales: &[u8]) {
if self.pending {
self.pending = false;
self.kind = Kind::Num;
}
if self.kind != Kind::Num {
for (m, s) in mant.iter().zip(scales) {
self.push_item(&Item::Num(*m, *s), "");
}
return;
}
self.rows += mant.len();
let words = self.rows.div_ceil(64);
for bits in [&mut self.bits, &mut self.boxed, &mut self.failed] {
bits.resize(words, 0);
}
self.mant.extend_from_slice(mant);
self.scale.extend_from_slice(scales);
}
pub(crate) fn push_item(&mut self, item: &Item, arena: &str) {
if self.pending {
self.pending = false;
self.kind = match item {
Item::Num(..) => Kind::Num,
Item::Text(..) => {
self.offsets.push(0);
Kind::Str
}
Item::Bool(_) => Kind::Bool,
Item::Value(_) => Kind::Dyn,
};
}
let row = self.grow();
match (self.kind, item) {
(Kind::Num, Item::Num(m, s)) => {
self.mant.push(*m);
self.scale.push(*s);
}
(Kind::Str, Item::Text(a, b)) => {
self.push_text(arena.get(*a as usize..*b as usize).unwrap_or_default())
}
(Kind::Bool, Item::Bool(b)) => self.set_bit(row, *b),
(Kind::Dyn, item) => self.values.push(item.variable(arena)),
(kind, item) => {
match kind {
Kind::Num => {
self.mant.push(0);
self.scale.push(0);
}
Kind::Date => self.dates.push(None),
_ => {}
}
self.box_at(row, item.variable(arena));
}
}
}
pub(crate) fn extend_lists(
&mut self,
mant: &[i64],
scales: &[u8],
ends: impl Iterator<Item = u32>,
) -> bool {
let Shape::List(child) = &mut self.shape else {
return false;
};
let base = child.rows as u32;
child.extend_nums(mant, scales);
self.offsets.extend(ends.map(|end| base + end));
true
}
pub(crate) fn close(&mut self) {
if let Shape::List(child) = &self.shape {
self.offsets.push(child.rows as u32);
}
}
pub(crate) fn uniform(items: &[Layout], kinds: &[Kind]) -> Option<Kind> {
let mut kinds = items.iter().map(|item| match item {
Layout::Value(reg) => Some(kinds[*reg as usize]),
_ => None,
});
let first = kinds.next().flatten()?;
kinds.all(|k| k == Some(first)).then_some(first)
}
pub fn len(&self) -> usize {
self.rows
}
pub fn is_empty(&self) -> bool {
self.rows == 0
}
pub fn kind(&self) -> Kind {
self.kind
}
pub fn shape(&self) -> &Shape {
&self.shape
}
pub fn fields(&self) -> &[(Arc<str>, Output)] {
match &self.shape {
Shape::Struct(fields) => fields,
_ => &[],
}
}
pub fn child(&self) -> Option<&Output> {
match &self.shape {
Shape::List(child) => Some(child),
_ => None,
}
}
pub fn mantissas(&self) -> &[i64] {
&self.mant
}
pub fn scales(&self) -> &[u8] {
&self.scale
}
pub fn dates(&self) -> &[Option<DateTime<Tz>>] {
&self.dates
}
pub fn bools(&self) -> &[u64] {
&self.bits
}
pub fn offsets(&self) -> &[u32] {
&self.offsets
}
pub fn data(&self) -> &[u8] {
&self.data
}
pub fn text(&self, row: usize) -> Option<&str> {
let (a, b) = (
*self.offsets.get(row)? as usize,
*self.offsets.get(row + 1)? as usize,
);
std::str::from_utf8(self.data.get(a..b)?).ok()
}
pub fn boxed(&self) -> &[u64] {
&self.boxed
}
pub fn failed(&self) -> &[u64] {
&self.failed
}
pub fn boxed_values(&self) -> &[(u32, Variable)] {
&self.extra
}
pub fn take_numbers(&mut self) -> (Vec<i64>, Vec<u8>) {
(std::mem::take(&mut self.mant), std::mem::take(&mut self.scale))
}
pub fn take_values(&mut self) -> Vec<Variable> {
std::mem::take(&mut self.values)
}
pub fn take_bits(&mut self) -> Vec<u64> {
std::mem::take(&mut self.bits)
}
pub fn take_text(&mut self) -> (Vec<u32>, Vec<u8>) {
(std::mem::take(&mut self.offsets), std::mem::take(&mut self.data))
}
pub(crate) fn fail_at(&mut self, at: usize) {
if let Some(w) = self.failed.get_mut(at / 64) {
*w |= 1 << (at % 64);
}
match (&self.shape, self.kind) {
(Shape::Scalar, Kind::Str) => self.offsets.push(self.data.len() as u32),
(Shape::List(_), Kind::List) => self.close(),
_ => {}
}
}
pub(crate) fn box_at(&mut self, at: usize, value: Variable) {
if let Some(w) = self.boxed.get_mut(at / 64) {
*w |= 1 << (at % 64);
}
match self.kind {
Kind::Str => self.offsets.push(self.data.len() as u32),
Kind::List => self.close(),
_ => {}
}
self.extra.push((at as u32, value));
}
pub(crate) fn set_bit(&mut self, at: usize, on: bool) {
if let Some(w) = self.bits.get_mut(at / 64) {
*w = (*w & !(1 << (at % 64))) | ((on as u64) << (at % 64));
}
}
pub(crate) fn push_text(&mut self, text: &str) {
self.data.extend_from_slice(text.as_bytes());
self.offsets.push(self.data.len() as u32);
}
fn bit(bits: &[u64], row: usize) -> bool {
bits.get(row / 64).is_some_and(|w| w >> (row % 64) & 1 == 1)
}
fn find<T>(entries: &[(u32, T)], row: usize) -> Option<&T> {
entries
.binary_search_by_key(&(row as u32), |(r, _)| *r)
.ok()
.map(|i| &entries[i].1)
}
pub fn get(&self, row: usize) -> Option<Cell<'_>> {
if row >= self.rows {
return None;
}
if Self::bit(&self.failed, row) {
return Self::find(&self.errors, row).map(|failure| Cell::Error(failure.error()));
}
if self.kind != Kind::Dyn && Self::bit(&self.boxed, row) {
return Self::find(&self.extra, row).map(Cell::Value);
}
match &self.shape {
Shape::Struct(fields) => return Some(Cell::Struct(fields, row)),
Shape::List(child) => {
let (a, b) = (
*self.offsets.get(row)? as usize,
*self.offsets.get(row + 1)? as usize,
);
return Some(Cell::List(child, a, b));
}
Shape::Scalar => {}
}
if self.kind == Kind::Dyn {
return self.values.get(row).map(Cell::Value);
}
if Self::bit(&self.boxed, row) {
return Self::find(&self.extra, row).map(Cell::Value);
}
Some(match self.kind {
Kind::Num => Cell::Number(Decimal::new(self.mant[row], self.scale[row] as u32)),
Kind::Str => Cell::Str(self.text(row)?),
Kind::Date => Cell::Date(*self.dates.get(row)?),
_ => Cell::Bool(Self::bit(&self.bits, row)),
})
}
pub fn variable(&self, row: usize) -> Option<Result<Variable, VMError>> {
Some(match self.get(row)? {
Cell::Number(n) => Ok(Variable::Number(n)),
Cell::Bool(b) => Ok(Variable::Bool(b)),
Cell::Str(s) => Ok(Variable::String(s.into())),
Cell::Date(d) => Ok(Date(d).variable()),
Cell::Value(v) => Ok(v.clone()),
Cell::Struct(fields, row) => {
let mut map = VariableMap::with_capacity(fields.len());
for (key, field) in fields.iter().rev() {
map.insert(Symbol::from(key.as_ref()), field.variable(row)?.ok()?);
}
Ok(Variable::from_object(map))
}
Cell::List(child, a, b) => Ok(Variable::from_array(
(a..b)
.map(|i| child.variable(i)?.ok())
.collect::<Option<Vec<_>>>()?,
)),
Cell::Error(e) => Err(e.clone()),
})
}
}
+538
View File
@@ -0,0 +1,538 @@
use crate::compiler::{Compare, FetchFastTarget};
use crate::functions::{ClosureFunction, FunctionKind, MethodKind};
use crate::lexer::Bracket;
use crate::variable::Variable;
use crate::vm::VMError;
use rust_decimal::Decimal;
use std::sync::Arc;
use zen_types::symbol::Symbol;
pub type Reg = u16;
pub type MaskId = u16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Dyn,
Num,
Bool,
Str,
Date,
List,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Binding {
Column(usize),
Absent,
Row,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Operand {
Reg(Reg),
Num(Decimal),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumOp {
Add,
Subtract,
Multiply,
Divide,
Modulo,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumCmp {
Order(Compare),
Equal,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Const {
Null,
Bool(bool),
Number(Decimal),
String(Arc<str>),
Array(Vec<Const>),
Date(Option<chrono::DateTime<chrono_tz::Tz>>),
}
impl Const {
pub fn same(&self, other: &Const) -> bool {
match (self, other) {
(Const::Number(a), Const::Number(b)) => a.serialize() == b.serialize(),
(Const::Date(a), Const::Date(b)) => {
let key = |d: chrono::DateTime<chrono_tz::Tz>| {
(d.timestamp(), d.timestamp_subsec_nanos(), d.timezone())
};
a.map(key) == b.map(key)
}
(Const::Array(a), Const::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.same(y))
}
(a, b) => a == b,
}
}
pub fn variable(&self) -> Variable {
match self {
Const::Null => Variable::Null,
Const::Bool(b) => Variable::Bool(*b),
Const::Number(n) => Variable::Number(*n),
Const::String(s) => Variable::String(Symbol::from(s.as_ref())),
Const::Array(items) => {
Variable::from_array(items.iter().map(Const::variable).collect())
}
Const::Date(d) => crate::lane::date::Date(*d).variable(),
}
}
pub fn number(node: &crate::parser::Node) -> Option<Decimal> {
use crate::lexer::{ArithmeticOperator, Operator};
use crate::parser::Node;
match node {
Node::Number(n) => Some(*n),
Node::Parenthesized(inner) => Const::number(inner),
Node::Unary {
node,
operator: Operator::Arithmetic(ArithmeticOperator::Subtract),
} => Const::number(node).map(|n| -n),
Node::Unary {
node,
operator: Operator::Arithmetic(ArithmeticOperator::Add),
} => Const::number(node),
_ => None,
}
}
pub fn of(node: &crate::parser::Node) -> Option<Const> {
use crate::parser::Node;
if let Some(n) = Const::number(node) {
return Some(Const::Number(n));
}
match node {
Node::Null => Some(Const::Null),
Node::Bool(b) => Some(Const::Bool(*b)),
Node::String(s) => Some(Const::String(Arc::from(*s))),
Node::Array(items) => items
.iter()
.map(|n| Const::of(n))
.collect::<Option<Vec<_>>>()
.map(Const::Array),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Binary {
Add,
Subtract,
Multiply,
Divide,
Modulo,
Exponent,
Equal,
In,
Compare(Compare),
}
#[derive(Debug, Clone)]
pub enum Op {
Const {
dst: Reg,
id: u16,
},
Env {
dst: Reg,
key: Arc<str>,
site: u16,
},
RootEnv {
dst: Reg,
},
Path {
dst: Reg,
path: Box<[FetchFastTarget]>,
site: u16,
},
Fetch {
dst: Reg,
a: Reg,
b: Reg,
},
Negate {
dst: Reg,
a: Reg,
},
Not {
dst: Reg,
a: Reg,
},
Binary {
dst: Reg,
op: Binary,
a: Reg,
b: Reg,
},
Interval {
dst: Reg,
a: Reg,
b: Reg,
left: Bracket,
right: Bracket,
},
InRange {
dst: Reg,
a: Reg,
lo: Decimal,
hi: Decimal,
left: Bracket,
right: Bracket,
},
Slice {
dst: Reg,
a: Reg,
to: Reg,
from: Reg,
},
Len {
dst: Reg,
a: Reg,
},
Array {
dst: Reg,
items: Box<[Reg]>,
},
Object {
dst: Reg,
pairs: Box<[(ObjectKey, Reg)]>,
},
Join {
dst: Reg,
parts: Box<[Input]>,
},
Concat {
dst: Reg,
a: Reg,
b: Reg,
},
Extreme {
dst: Reg,
items: Box<[Operand]>,
largest: bool,
},
Call {
dst: Reg,
kind: FunctionKind,
args: Box<[Input]>,
},
Method {
dst: Reg,
kind: MethodKind,
args: Box<[Input]>,
},
Branch {
cond: Reg,
opcode: &'static str,
on_true: MaskId,
on_false: MaskId,
},
NullBranch {
a: Reg,
null: MaskId,
other: MaskId,
},
Merge {
dst: Reg,
mask: MaskId,
a: Reg,
b: Reg,
},
Move {
dst: Reg,
src: Reg,
},
AssignBegin {
dst: Reg,
},
AssignStep {
object: Reg,
key: Reg,
value: Reg,
},
Closure(Box<ClosureOp>),
Fail {
error: VMError,
},
Num {
dst: Reg,
op: NumOp,
a: Operand,
b: Operand,
},
Cmp {
dst: Reg,
op: NumCmp,
a: Operand,
b: Operand,
},
EqConst {
dst: Reg,
a: Reg,
value: Const,
id: u16,
not: bool,
},
Field {
dst: Reg,
src: Reg,
key: Arc<str>,
site: u16,
},
LoadEq {
dst: Reg,
load: Load,
site: u16,
id: u16,
not: bool,
},
LoadIn {
dst: Reg,
a: Reg,
load: Load,
site: u16,
},
LoadCall(Box<LoadCall>),
EqAny {
dst: Reg,
a: Reg,
id: u16,
},
InConst {
dst: Reg,
a: Reg,
id: u16,
},
Coalesce {
dst: Reg,
a: Reg,
id: u16,
},
SelectConst {
dst: Reg,
cond: Reg,
a: u16,
b: u16,
},
Stage {
index: u16,
},
Rewind,
DollarInsert {
key: Arc<str>,
value: Reg,
},
}
#[derive(Debug, Clone)]
pub struct LoadCall {
pub dst: Reg,
pub load: Load,
pub site: u16,
pub kind: FunctionKind,
pub args: Box<[u16]>,
pub memo: u16,
pub scratch: Reg,
pub call: Op,
}
#[derive(Debug, Clone, Copy)]
pub enum Input {
Reg(Reg),
Const(u16),
}
#[derive(Debug, Clone)]
pub enum ObjectKey {
Static(Arc<str>),
Reg(Reg),
}
#[derive(Debug, Clone)]
pub enum Load {
Env(Arc<str>),
Path(Box<[FetchFastTarget]>),
}
#[derive(Debug, Clone)]
pub struct ClosureOp {
pub kind: ClosureFunction,
pub dst: Reg,
pub list: Reg,
pub source: Option<(Load, u16)>,
pub body: Program,
pub imports: Box<[(Reg, Reg)]>,
pub sequential: bool,
}
#[derive(Debug, Clone)]
pub struct Step {
pub mask: MaskId,
pub op: Op,
}
#[derive(Debug, Clone, Default)]
pub struct Program {
pub steps: Vec<Step>,
pub regs: u16,
pub masks: u16,
pub out: Reg,
pub element: Option<Reg>,
pub writes_env: bool,
pub chain: bool,
pub frames: usize,
pub kinds: Vec<Kind>,
pub sites: u16,
pub id: u64,
pub pinned: Vec<bool>,
pub fixed: Vec<bool>,
pub keys: Vec<String>,
pub site_keys: Vec<Option<String>>,
pub rows: bool,
pub consts: Vec<Const>,
pub outputs: Vec<Reg>,
pub memos: u16,
pub layout: Option<Layout>,
pub isolated: bool,
}
#[derive(Debug, Clone)]
pub enum Layout {
Value(Reg),
Struct(Box<[(Arc<str>, Layout)]>),
List(Box<[Layout]>),
}
impl Program {
pub fn finish(&mut self, sites: u16) {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
self.frames = self.depth() + 1;
self.sites = sites;
self.id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
for step in &mut self.steps {
if let Op::Closure(c) = &mut step.op {
c.body.finish(sites);
}
}
}
pub fn pure(&self) -> bool {
self.steps.iter().all(|step| {
!matches!(
step.op,
Op::Env { .. }
| Op::Path { .. }
| Op::RootEnv { .. }
| Op::LoadEq { .. }
| Op::LoadIn { .. }
| Op::LoadCall(_)
| Op::AssignBegin { .. }
| Op::AssignStep { .. }
| Op::Closure(_)
| Op::Rewind
| Op::DollarInsert { .. }
)
})
}
pub fn opaque(&self) -> bool {
self.opaque_with(&self.site_keys)
}
pub fn stable(&self) -> bool {
use crate::functions::InternalFunction;
let random = |kind: &FunctionKind| matches!(kind, FunctionKind::Internal(InternalFunction::Rand));
self.steps.iter().all(|step| match &step.op {
Op::Call { kind, .. } => !random(kind),
Op::LoadCall(call) => !random(&call.kind),
Op::Closure(closure) => closure.body.stable(),
_ => true,
})
}
pub fn timeless(&self) -> bool {
use crate::functions::{DateMethod, DeprecatedFunction, InternalFunction, MethodKind};
let clocked = |kind: &FunctionKind| {
matches!(
kind,
FunctionKind::Internal(InternalFunction::Rand | InternalFunction::Date)
| FunctionKind::Deprecated(DeprecatedFunction::Date | DeprecatedFunction::Time | DeprecatedFunction::DateString)
)
};
self.steps.iter().all(|step| match &step.op {
Op::Call { kind, .. } => !clocked(kind),
Op::LoadCall(call) => !clocked(&call.kind),
Op::Method { kind, .. } => !matches!(
kind,
MethodKind::DateMethod(DateMethod::IsToday | DateMethod::IsYesterday | DateMethod::IsTomorrow)
),
Op::Closure(closure) => closure.body.timeless(),
_ => true,
})
}
fn opaque_with(&self, keys: &[Option<String>]) -> bool {
let unkeyed = |site: u16| keys.get(site as usize).is_none_or(Option::is_none);
self.steps.iter().any(|step| match &step.op {
Op::Env { site, .. } | Op::Path { site, .. } | Op::LoadEq { site, .. } | Op::LoadIn { site, .. } => {
unkeyed(*site)
}
Op::LoadCall(c) => unkeyed(c.site),
Op::RootEnv { .. } | Op::AssignBegin { .. } | Op::AssignStep { .. } | Op::Rewind | Op::DollarInsert { .. } => true,
Op::Closure(c) => c.source.as_ref().is_some_and(|(_, site)| unkeyed(*site)) || c.body.opaque_with(keys),
_ => false,
})
}
pub fn needs_rows(&self, bound: &[Binding]) -> bool {
self.steps
.iter()
.any(|step| Self::op_needs_rows(&step.op, bound))
}
fn op_needs_rows(op: &Op, bound: &[Binding]) -> bool {
match op {
Op::Env { site, .. }
| Op::Path { site, .. }
| Op::LoadEq { site, .. }
| Op::LoadIn { site, .. } => {
matches!(bound.get(*site as usize), None | Some(Binding::Row))
}
Op::RootEnv { .. }
| Op::AssignBegin { .. }
| Op::AssignStep { .. }
| Op::Rewind
| Op::DollarInsert { .. } => true,
Op::Closure(c) => {
c.source.as_ref().is_some_and(|(_, site)| {
matches!(bound.get(*site as usize), None | Some(Binding::Row))
}) || c.body.needs_rows(bound)
}
Op::LoadCall(c) => matches!(bound.get(c.site as usize), None | Some(Binding::Row)),
_ => false,
}
}
pub fn depth(&self) -> usize {
self.steps
.iter()
.filter_map(|s| match &s.op {
Op::Closure(c) => Some(1 + c.body.depth()),
_ => None,
})
.max()
.unwrap_or(0)
}
}
+551
View File
@@ -0,0 +1,551 @@
use crate::lane::mask::LaneSet;
use rust_decimal::Decimal;
pub(crate) struct Scaled;
impl Scaled {
pub(crate) const POW10: [i64; 19] = [
1,
10,
100,
1_000,
10_000,
100_000,
1_000_000,
10_000_000,
100_000_000,
1_000_000_000,
10_000_000_000,
100_000_000_000,
1_000_000_000_000,
10_000_000_000_000,
100_000_000_000_000,
1_000_000_000_000_000,
10_000_000_000_000_000,
100_000_000_000_000_000,
1_000_000_000_000_000_000,
];
#[inline]
pub(crate) fn decimal(m: i64, s: u8) -> Decimal {
Decimal::new(m, s as u32)
}
#[inline]
fn signed(input: i64, result: (i64, u8)) -> Option<(i64, u8)> {
(result.0 != 0 || input >= 0).then_some(result)
}
pub(crate) fn divide(a: (i64, u8), b: (i64, u8)) -> Option<(i64, u8)> {
let ((m1, s1), (m2, s2)) = (a, b);
if m1 == 0 || m2 == 0 {
return None;
}
if s1 < s2 {
return None;
}
let (n, scale) = (m1 as i128, s1 - s2);
let d = m2 as i128;
(n % d == 0)
.then(|| i64::try_from(n / d).ok())
.flatten()
.map(|q| (q, scale))
}
pub(crate) fn remainder(a: (i64, u8), b: (i64, u8)) -> Option<(i64, u8)> {
let ((m1, s1), (m2, s2)) = (a, b);
if m1 == 0 || m2 == 0 {
return None;
}
let top = s1.max(s2);
let x = Self::rescale(m1, s1, top)?;
let y = Self::rescale(m2, s2, top)?;
if x.unsigned_abs() < y.unsigned_abs() {
return Some((m1, s1));
}
let r = x.checked_rem(y)?;
(r != 0).then_some((r, top))
}
pub(crate) fn abs(m: i64, s: u8) -> Option<(i64, u8)> {
Some((m.checked_abs()?, s))
}
pub(crate) fn trunc(m: i64, s: u8, places: u8) -> Option<(i64, u8)> {
let r = match places >= s {
true => (
m.checked_mul(*Self::POW10.get((places - s) as usize)?)?,
places,
),
false => (m / Self::POW10.get((s - places) as usize)?, places),
};
Self::signed(m, r)
}
pub(crate) fn round(m: i64, s: u8, places: u8) -> Option<(i64, u8)> {
if places >= s {
return Some((m, s));
}
let f = *Self::POW10.get((s - places) as usize)?;
let (q, r) = (m / f, m % f);
let up = r.unsigned_abs() >= (f as u64).div_ceil(2);
let q = match (up, m < 0) {
(true, true) => q.checked_sub(1)?,
(true, false) => q.checked_add(1)?,
_ => q,
};
Self::signed(m, (q, places))
}
pub(crate) fn floor(m: i64, s: u8) -> Option<(i64, u8)> {
let f = *Self::POW10.get(s as usize)?;
let (q, r) = (m / f, m % f);
Self::signed(m, (if r < 0 { q.checked_sub(1)? } else { q }, 0))
}
pub(crate) fn ceil(m: i64, s: u8) -> Option<(i64, u8)> {
let f = *Self::POW10.get(s as usize)?;
let (q, r) = (m / f, m % f);
Self::signed(m, (if r > 0 { q.checked_add(1)? } else { q }, 0))
}
pub(crate) fn write(m: i64, s: u8, out: &mut String) {
let mut digits = [0u8; 48];
let mut n = m.unsigned_abs();
let mut len = 0usize;
while n > 0 || len <= s as usize {
digits[len] = b'0' + (n % 10) as u8;
n /= 10;
len += 1;
}
if m < 0 {
out.push('-');
}
for i in (0..len).rev() {
out.push(digits[i] as char);
if i == s as usize && s > 0 {
out.push('.');
}
}
}
#[inline]
pub(crate) fn parts(d: &Decimal) -> Option<(i64, u8)> {
let bytes = d.serialize();
let flags = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
let lo = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as u64;
let mid = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as u64;
let hi = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
let negative = flags & 0x8000_0000 != 0;
let magnitude = mid << 32 | lo;
let limit = i64::MAX as u64 + u64::from(negative);
if hi != 0 || magnitude > limit || (negative && magnitude == 0) {
return None;
}
let m = match negative {
true => (magnitude as i64).wrapping_neg(),
false => magnitude as i64,
};
Some((m, ((flags >> 16) & 0xFF) as u8))
}
#[inline]
pub(crate) fn rescale(m: i64, from: u8, to: u8) -> Option<i64> {
m.checked_mul(*Self::POW10.get((to - from) as usize)?)
}
#[inline]
pub(crate) fn add(a: (i64, u8), b: (i64, u8), subtract: bool) -> Option<(i64, u8)> {
match (a.0 == 0, b.0 == 0) {
(true, _) => match subtract {
true => Some((b.0.checked_neg()?, b.1)),
false => Some(b),
},
(false, true) => Some(a),
(false, false) => {
let s = a.1.max(b.1);
let (x, y) = (Self::rescale(a.0, a.1, s)?, Self::rescale(b.0, b.1, s)?);
let m = match subtract {
true => x.checked_sub(y)?,
false => x.checked_add(y)?,
};
Some((m, s))
}
}
}
#[inline]
pub(crate) fn multiply(a: (i64, u8), b: (i64, u8)) -> Option<(i64, u8)> {
if a.0 == 0 || b.0 == 0 {
return Some((0, 0));
}
let s = a.1 + b.1;
(s <= 28).then_some(())?;
Some((a.0.checked_mul(b.0)?, s))
}
#[inline]
pub(crate) fn compare(a: (i64, u8), b: (i64, u8)) -> Option<std::cmp::Ordering> {
if a.1 == b.1 {
return Some(a.0.cmp(&b.0));
}
let s = a.1.max(b.1);
let up = |m: i64, from: u8| -> Option<i128> {
(m as i128).checked_mul(10i128.checked_pow((s - from) as u32)?)
};
Some(up(a.0, a.1)?.cmp(&up(b.0, b.1)?))
}
}
pub(crate) struct Kernel;
impl Kernel {
#[inline]
pub(crate) fn add(
a: (&[i64], u8),
b: (&[i64], u8),
subtract: bool,
m: &mut [i64],
s: &mut [u8],
) -> bool {
let ((xa, sa), (xb, sb)) = (a, b);
if sa == sb {
let mut flag = 0i64;
for ((o, x), y) in m.iter_mut().zip(xa).zip(xb) {
let r = match subtract {
true => x.wrapping_sub(*y),
false => x.wrapping_add(*y),
};
flag |= match subtract {
true => (x ^ y) & (x ^ r),
false => (x ^ r) & (y ^ r),
};
*o = r;
}
s.fill(sa);
return flag < 0;
}
let (top, up_a) = (sa.max(sb), sa < sb);
let Some(f) = Scaled::POW10.get((top - sa.min(sb)) as usize).copied() else {
return true;
};
match (subtract, up_a) {
(true, true) => Self::mixed::<true, true>(xa, xb, f, (sa, sb, top), m, s),
(true, false) => Self::mixed::<true, false>(xa, xb, f, (sa, sb, top), m, s),
(false, true) => Self::mixed::<false, true>(xa, xb, f, (sa, sb, top), m, s),
(false, false) => Self::mixed::<false, false>(xa, xb, f, (sa, sb, top), m, s),
}
}
#[inline(always)]
fn mixed<const SUB: bool, const UP_A: bool>(
xa: &[i64],
xb: &[i64],
f: i64,
(sa, sb, top): (u8, u8, u8),
m: &mut [i64],
s: &mut [u8],
) -> bool {
let mut flag = false;
for (((o, sc), x), y) in m.iter_mut().zip(s.iter_mut()).zip(xa).zip(xb) {
let (x, y) = (*x, *y);
let ((p, o1), (q, o2)) = match UP_A {
true => (x.overflowing_mul(f), (y, false)),
false => ((x, false), y.overflowing_mul(f)),
};
let (r, o3) = match SUB {
true => p.overflowing_sub(q),
false => p.overflowing_add(q),
};
let negated = if SUB { y.wrapping_neg() } else { y };
let (zx, zy) = (x == 0, y == 0);
*o = if zx {
negated
} else if zy {
x
} else {
r
};
*sc = if zx {
sb
} else if zy {
sa
} else {
top
};
flag |= (!zx & !zy & (o1 | o2 | o3)) | (zx & SUB & (y == i64::MIN));
}
flag
}
#[inline]
pub(crate) fn multiply(a: (&[i64], u8), b: (&[i64], u8), m: &mut [i64], s: &mut [u8]) -> bool {
let ((xa, sa), (xb, sb)) = (a, b);
let top = sa + sb;
if top > 28 {
return true;
}
let mut flag = false;
for (((o, sc), x), y) in m.iter_mut().zip(s.iter_mut()).zip(xa).zip(xb) {
let (r, of) = x.overflowing_mul(*y);
flag |= of;
*o = r;
*sc = if r == 0 { 0 } else { top };
}
flag
}
#[inline]
pub(crate) fn threshold<M: LaneSet>(
values: &[i64],
k: i64,
hit: impl Fn(std::cmp::Ordering) -> bool,
) -> M {
let mut mask = M::none(values.len());
for (w, chunk) in values.chunks(64).enumerate() {
let mut word = 0u64;
for (j, eight) in chunk.chunks(8).enumerate() {
let mut bytes = [0u8; 8];
for (b, x) in bytes.iter_mut().zip(eight) {
*b = hit(x.cmp(&k)) as u8;
}
let packed = u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;
word |= packed << (j * 8);
}
mask.set_word(w, word);
}
mask
}
pub(crate) fn compare<M: LaneSet>(
a: (&[i64], u8),
b: (&[i64], u8),
hit: impl Fn(std::cmp::Ordering) -> bool,
) -> Option<M> {
let ((xa, sa), (xb, sb)) = (a, b);
let mut mask = M::none(xa.len());
let (fa, fb) = match sa == sb {
true => (1, 1),
false => {
let top = sa.max(sb);
(
*Scaled::POW10.get((top - sa) as usize)?,
*Scaled::POW10.get((top - sb) as usize)?,
)
}
};
for (w, (ca, cb)) in xa.chunks(64).zip(xb.chunks(64)).enumerate() {
let mut word = 0u64;
match sa == sb {
true => {
for (i, (x, y)) in ca.iter().zip(cb).enumerate() {
word |= (hit(x.cmp(y)) as u64) << i;
}
}
false => {
for (i, (x, y)) in ca.iter().zip(cb).enumerate() {
word |= (hit((*x as i128 * fa as i128).cmp(&(*y as i128 * fb as i128)))
as u64)
<< i;
}
}
}
mask.set_word(w, word);
}
Some(mask)
}
}
#[cfg(test)]
mod tests {
use super::{Kernel, Scaled};
use rust_decimal::Decimal;
use std::cmp::Ordering;
struct Rng(u64);
impl Rng {
fn next(&mut self, n: u64) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0 % n
}
fn mantissa(&mut self) -> i64 {
match self.next(8) {
0 => 0,
1 => i64::MAX - self.next(3) as i64,
2 => i64::MIN + self.next(3) as i64,
3 => (self.next(1 << 62) as i64) * if self.next(2) == 0 { 1 } else { -1 },
_ => self.next(20_000) as i64 - 10_000,
}
}
fn scale(&mut self) -> u8 {
match self.next(6) {
0 => self.next(29) as u8,
_ => self.next(4) as u8,
}
}
}
fn exact(m: i64, s: u8, d: Decimal) -> bool {
Scaled::parts(&d).is_some_and(|(dm, ds)| dm == m && ds == s)
&& Scaled::decimal(m, s).to_string() == d.to_string()
}
#[test]
fn rounding_matches_rust_decimal() {
use rust_decimal::RoundingStrategy;
let mut rng = Rng(0xD1B54A32D192ED03);
let exact = |r: Option<(i64, u8)>, d: Decimal, what: &str| {
if let Some((m, s)) = r {
assert_eq!(Scaled::decimal(m, s).to_string(), d.to_string(), "{what}");
assert_eq!(Scaled::parts(&d), Some((m, s)), "{what} parts");
}
};
for _ in 0..300_000 {
let (m, s) = (rng.mantissa(), rng.scale());
let x = Decimal::new(m, s as u32);
let places = rng.next(6) as u8;
if !(x.is_zero() && x.is_sign_negative()) {
exact(Scaled::abs(m, s), x.abs(), &format!("abs {x}"));
exact(
Scaled::trunc(m, s, places),
x.trunc_with_scale(places as u32),
&format!("trunc {x} {places}"),
);
exact(
Scaled::round(m, s, places),
x.round_dp_with_strategy(places as u32, RoundingStrategy::MidpointAwayFromZero),
&format!("round {x} {places}"),
);
exact(Scaled::floor(m, s), x.floor(), &format!("floor {x}"));
exact(Scaled::ceil(m, s), x.ceil(), &format!("ceil {x}"));
}
}
}
#[test]
fn divide_matches_rust_decimal() {
let mut rng = Rng(0x94D049BB133111EB);
let mut checked = 0usize;
for _ in 0..500_000 {
let (m1, s1) = (rng.mantissa() / (1 + rng.next(1000) as i64), rng.scale());
let (m2, s2) = (
match rng.next(3) {
0 => rng.next(20) as i64 - 10,
1 => [2, 4, 5, 8, 10, 16, 25, 40, 100, 125][rng.next(10) as usize],
_ => rng.mantissa() / (1 + rng.next(100_000) as i64),
},
rng.scale(),
);
let (x, y) = (Decimal::new(m1, s1 as u32), Decimal::new(m2, s2 as u32));
if let Some((m, s)) = Scaled::divide((m1, s1), (m2, s2)) {
let expected = x.checked_div(y).unwrap_or_default();
assert_eq!(
Scaled::decimal(m, s).to_string(),
expected.to_string(),
"{x} / {y}"
);
checked += 1;
}
}
assert!(checked > 10_000, "{checked}");
}
#[test]
fn remainder_matches_rust_decimal() {
let mut rng = Rng(0xBF58476D1CE4E5B9);
let mut checked = 0usize;
for _ in 0..500_000 {
let (m1, s1) = (rng.mantissa() / (1 + rng.next(1000) as i64), rng.scale());
let (m2, s2) = (rng.next(200) as i64 - 100, rng.scale());
let (x, y) = (Decimal::new(m1, s1 as u32), Decimal::new(m2, s2 as u32));
if let Some((m, s)) = Scaled::remainder((m1, s1), (m2, s2)) {
let expected = x.checked_rem(y).unwrap_or_default();
assert_eq!(
Scaled::decimal(m, s).to_string(),
expected.to_string(),
"{x} % {y}"
);
checked += 1;
}
}
assert!(checked > 10_000, "{checked}");
}
#[test]
fn write_matches_decimal_display() {
let mut rng = Rng(0x9E3779B97F4A7C15);
let mut out = String::new();
for _ in 0..200_000 {
let (m, s) = (rng.mantissa(), rng.scale());
out.clear();
Scaled::write(m, s, &mut out);
assert_eq!(out, Decimal::new(m, s as u32).to_string(), "{m}e-{s}");
}
}
#[test]
fn kernels_match_rust_decimal() {
let mut rng = Rng(0x2545F4914F6CDD1D);
let mut checked = 0usize;
for _ in 0..20_000 {
let (sa, sb) = (rng.scale(), rng.scale());
let a: Vec<i64> = (0..64).map(|_| rng.mantissa()).collect();
let b: Vec<i64> = (0..64).map(|_| rng.mantissa()).collect();
let (mut m, mut s) = (vec![0i64; 64], vec![0u8; 64]);
for op in 0..3 {
let overflow = match op {
0 => Kernel::add((&a, sa), (&b, sb), false, &mut m, &mut s),
1 => Kernel::add((&a, sa), (&b, sb), true, &mut m, &mut s),
_ => Kernel::multiply((&a, sa), (&b, sb), &mut m, &mut s),
};
for i in 0..64 {
let (x, y) = (Decimal::new(a[i], sa as u32), Decimal::new(b[i], sb as u32));
let expected = match op {
0 => x.checked_add(y),
1 => x.checked_sub(y),
_ => x.checked_mul(y),
};
let lane = match op {
0 => Scaled::add((a[i], sa), (b[i], sb), false),
1 => Scaled::add((a[i], sa), (b[i], sb), true),
_ => Scaled::multiply((a[i], sa), (b[i], sb)),
};
if let (Some((lm, ls)), Some(e)) = (lane, expected) {
assert!(
exact(lm, ls, e),
"lane op {op}: {x} {y} -> {lm}e-{ls} vs {e}"
);
checked += 1;
}
if !overflow {
let e = expected.unwrap_or_default();
assert!(
expected.is_some() && exact(m[i], s[i], e),
"kernel op {op}: {x} {y} -> {}e-{} vs {e}",
m[i],
s[i]
);
}
}
}
let hit = |o: Ordering| o.is_lt();
if let Some(word) = Kernel::compare::<crate::lane::mask::Mask>((&a, sa), (&b, sb), hit)
{
for i in 0..64 {
let (x, y) = (Decimal::new(a[i], sa as u32), Decimal::new(b[i], sb as u32));
assert_eq!(word.get(i), x < y, "compare {x} {y}");
assert_eq!(
Scaled::compare((a[i], sa), (b[i], sb)).map(|o| o.is_lt()),
Some(x < y)
);
}
}
}
assert!(checked > 1_000_000);
}
}
+73
View File
@@ -0,0 +1,73 @@
use crate::lexer::Lexer;
use crate::parser::{Node, Parser};
use bumpalo::Bump;
use std::cell::Cell;
pub struct SourceInfo;
impl SourceInfo {
fn any(source: &str, test: fn(&Node) -> bool) -> bool {
Self::scan(source, false, test)
}
fn scan(source: &str, unary: bool, test: fn(&Node) -> bool) -> bool {
if source.trim().is_empty() {
return false;
}
let bump = Bump::new();
let mut lexer = Lexer::new();
let Ok(tokens) = lexer.tokenize(&bump, source) else {
return true;
};
let Ok(parser) = Parser::try_new(&tokens, &bump) else {
return true;
};
let parsed = match unary {
true => parser.unary().parse(),
false => parser.standard().parse(),
};
if parsed.error().is_err() {
return true;
}
let found = Cell::new(false);
let found_ref = &found;
parsed.root.walk(move |node| {
if test(node) {
found_ref.set(true);
}
});
found.get()
}
pub fn reads_dollar(source: &str) -> bool {
Self::any(source, |node| matches!(node, Node::Identifier("$")))
}
pub fn reads_env(source: &str) -> bool {
Self::scan(source, true, |node| match node {
Node::Identifier(name) => *name != "$",
Node::Root => true,
_ => false,
})
}
pub fn reads_nodes_unary(source: &str) -> bool {
Self::scan(source, true, |node| {
matches!(node, Node::Identifier("$nodes") | Node::Root)
})
}
pub fn reads_root_unary(source: &str) -> bool {
Self::scan(source, true, |node| matches!(node, Node::Root))
}
pub fn reads_root(source: &str) -> bool {
Self::any(source, |node| matches!(node, Node::Root))
}
pub fn reads_nodes(source: &str) -> bool {
Self::any(source, |node| {
matches!(node, Node::Identifier("$nodes") | Node::Root)
})
}
}
+1
View File
@@ -65,6 +65,7 @@ mod exports;
pub mod expression;
pub mod functions;
pub mod intellisense;
pub mod lane;
pub mod lexer;
pub mod parser;
pub mod scope;
File diff suppressed because it is too large Load Diff
+355 -77
View File
@@ -1,19 +1,21 @@
use crate::symbol::Symbol;
use crate::variable::Variable;
use crate::variable::shape::{Shape, ShapeHint};
use ahash::{HashMap, HashMapExt};
use smallvec::SmallVec;
use std::fmt::{Debug, Formatter};
use std::rc::Rc;
const INLINE: usize = 8;
const SPILL_AT: usize = 32;
type Entries = SmallVec<[(Symbol, Variable); INLINE]>;
type Values = SmallVec<[Variable; INLINE]>;
#[derive(Clone)]
enum Repr {
Small(Entries),
Large(HashMap<Symbol, Variable>),
Shaped { shape: Rc<Shape>, values: Values },
Dict(HashMap<Symbol, Variable>),
}
#[derive(Clone)]
@@ -21,20 +23,40 @@ pub struct VariableMap(Repr);
impl VariableMap {
pub fn new() -> Self {
Self(Repr::Small(SmallVec::new()))
Self(Repr::Shaped {
shape: Shape::root(),
values: SmallVec::new(),
})
}
pub fn from_shape(shape: Rc<Shape>, values: impl IntoIterator<Item = Variable>) -> Self {
Self(Repr::Shaped {
shape,
values: values.into_iter().collect(),
})
}
pub fn with_capacity(capacity: usize) -> Self {
match capacity > SPILL_AT {
true => Self(Repr::Large(HashMap::with_capacity(capacity))),
false => Self(Repr::Small(SmallVec::with_capacity(capacity))),
true => Self(Repr::Dict(HashMap::with_capacity(capacity))),
false => Self(Repr::Shaped {
shape: Shape::root(),
values: SmallVec::with_capacity(capacity),
}),
}
}
pub fn reserve(&mut self, additional: usize) {
match &mut self.0 {
Repr::Shaped { values, .. } => values.reserve(additional),
Repr::Dict(map) => map.reserve(additional),
}
}
pub fn len(&self) -> usize {
match &self.0 {
Repr::Small(entries) => entries.len(),
Repr::Large(map) => map.len(),
Repr::Shaped { values, .. } => values.len(),
Repr::Dict(map) => map.len(),
}
}
@@ -44,50 +66,87 @@ impl VariableMap {
pub fn clear(&mut self) {
match &mut self.0 {
Repr::Small(entries) => entries.clear(),
Repr::Large(map) => map.clear(),
Repr::Shaped { shape, values } => {
*shape = Shape::root();
values.clear();
}
Repr::Dict(map) => map.clear(),
}
}
#[inline]
pub fn get(&self, key: &Symbol) -> Option<&Variable> {
pub fn shape(&self) -> Option<&Rc<Shape>> {
match &self.0 {
Repr::Small(entries) => entries
.iter()
.find(|(k, _)| k.as_str() == key.as_str())
.map(|(_, v)| v),
Repr::Large(map) => map.get(key),
Repr::Shaped { shape, .. } => Some(shape),
Repr::Dict(_) => None,
}
}
#[inline]
pub fn shape_id(&self) -> Option<u64> {
self.shape().map(|shape| shape.id())
}
#[inline]
pub fn get(&self, key: &Symbol) -> Option<&Variable> {
self.get_str(key.as_str())
}
#[inline]
pub fn get_str(&self, key: &str) -> Option<&Variable> {
match &self.0 {
Repr::Small(entries) => entries
.iter()
.find(|(k, _)| k.as_str() == key)
.map(|(_, v)| v),
Repr::Large(map) => map.get(key),
Repr::Shaped { shape, values } => shape.index_of(key).map(|index| &values[index]),
Repr::Dict(map) => map.get(key),
}
}
#[inline]
pub fn get_hinted(&self, hint: &mut ShapeHint, key: &str) -> Option<&Variable> {
match &self.0 {
Repr::Shaped { shape, values } => {
let id = shape.id();
if let Some(index) = hint.lookup(id) {
return values.get(index as usize);
}
let index = shape.index_of(key);
hint.record(id, index);
index.map(|index| &values[index])
}
Repr::Dict(map) => map.get(key),
}
}
pub fn map_values(&self, mut f: impl FnMut(&Variable) -> Variable) -> Self {
match &self.0 {
Repr::Shaped { shape, values } => Self(Repr::Shaped {
shape: shape.clone(),
values: values.iter().map(&mut f).collect(),
}),
Repr::Dict(map) => Self(Repr::Dict(
map.iter()
.map(|(key, value)| (key.clone(), f(value)))
.collect(),
)),
}
}
pub fn get_mut(&mut self, key: &Symbol) -> Option<&mut Variable> {
self.get_mut_str(key.as_str())
}
pub fn get_mut_str(&mut self, key: &str) -> Option<&mut Variable> {
match &mut self.0 {
Repr::Small(entries) => entries
.iter_mut()
.find(|(k, _)| k.as_str() == key.as_str())
.map(|(_, v)| v),
Repr::Large(map) => map.get_mut(key),
Repr::Shaped { shape, values } => shape.index_of(key).map(|index| &mut values[index]),
Repr::Dict(map) => map.get_mut(key),
}
}
pub fn get_key_value(&self, key: &Symbol) -> Option<(&Symbol, &Variable)> {
match &self.0 {
Repr::Small(entries) => entries
.iter()
.find(|(k, _)| k.as_str() == key.as_str())
.map(|(k, v)| (k, v)),
Repr::Large(map) => map.get_key_value(key),
Repr::Shaped { shape, values } => shape
.index_of(key.as_str())
.and_then(|index| Some((shape.key_at(index)?, &values[index]))),
Repr::Dict(map) => map.get_key_value(key),
}
}
@@ -101,58 +160,118 @@ impl VariableMap {
pub fn remove_str(&mut self, key: &str) -> Option<Variable> {
match &mut self.0 {
Repr::Small(entries) => entries
.iter()
.position(|(k, _)| k.as_str() == key)
.map(|index| entries.remove(index).1),
Repr::Large(map) => map.remove(key),
Repr::Shaped { shape, values } => {
let index = shape.index_of(key)?;
match shape.without(index) {
Some(reduced) => {
*shape = reduced;
Some(values.remove(index))
}
None => {
self.spill();
self.remove_str(key)
}
}
}
Repr::Dict(map) => map.remove(key),
}
}
pub fn insert(&mut self, key: Symbol, value: Variable) -> Option<Variable> {
match &mut self.0 {
Repr::Small(entries) => {
if let Some(slot) = entries.iter_mut().find(|(k, _)| k.as_str() == key.as_str()) {
return Some(std::mem::replace(&mut slot.1, value));
Repr::Shaped { shape, values } => {
let transition = (values.len() < SPILL_AT)
.then(|| shape.transition(key.as_str()))
.flatten();
if let Some(child) = transition {
*shape = child;
values.push(value);
return None;
}
if entries.len() >= SPILL_AT {
if let Some(index) = shape.index_of(key.as_str()) {
return Some(std::mem::replace(&mut values[index], value));
}
if values.len() >= SPILL_AT {
self.spill();
let Repr::Large(map) = &mut self.0 else {
let Repr::Dict(map) = &mut self.0 else {
unreachable!("just spilled")
};
return map.insert(key, value);
}
entries.push((key, value));
self.grow(key, value)
}
Repr::Dict(map) => map.insert(key, value),
}
}
pub fn insert_new(&mut self, key: Symbol, value: Variable) {
match &self.0 {
Repr::Shaped { values, .. } if values.len() < SPILL_AT => {
self.grow(key, value);
}
_ => {
self.insert(key, value);
}
}
}
#[inline]
fn follow(&mut self, key: &str, value: Variable) -> Option<Variable> {
let Repr::Shaped { shape, values } = &mut self.0 else {
return Some(value);
};
if values.len() >= SPILL_AT {
return Some(value);
}
let Some(child) = shape.transition(key) else {
return Some(value);
};
*shape = child;
values.push(value);
None
}
fn grow(&mut self, key: Symbol, value: Variable) -> Option<Variable> {
let Repr::Shaped { shape, values } = &mut self.0 else {
return self.insert(key, value);
};
match shape.with(&key) {
Some(child) => {
*shape = child;
values.push(value);
None
}
Repr::Large(map) => map.insert(key, value),
None => {
self.spill();
self.insert(key, value)
}
}
}
pub fn insert_new_str(&mut self, key: &str, value: Variable) {
if let Some(value) = self.follow(key, value) {
self.insert_new(Symbol::from(key), value);
}
}
pub fn remove(&mut self, key: &Symbol) -> Option<Variable> {
match &mut self.0 {
Repr::Small(entries) => entries
.iter()
.position(|(k, _)| k.as_str() == key.as_str())
.map(|index| entries.remove(index).1),
Repr::Large(map) => map.remove(key),
}
self.remove_str(key.as_str())
}
fn spill(&mut self) {
let Repr::Small(entries) = &mut self.0 else {
let Repr::Shaped { shape, values } = &mut self.0 else {
return;
};
let mut map = HashMap::with_capacity(entries.len() * 2);
for (key, value) in entries.drain(..) {
map.insert(key, value);
let mut map = HashMap::with_capacity(values.len() * 2);
for (key, value) in shape.keys().iter().zip(values.drain(..)) {
map.insert(key.clone(), value);
}
self.0 = Repr::Large(map);
self.0 = Repr::Dict(map);
}
pub fn entry(&mut self, key: Symbol) -> Entry<'_> {
if matches!(&self.0, Repr::Small(entries)
if entries.len() >= SPILL_AT && self.get(&key).is_none())
if matches!(&self.0, Repr::Shaped { values, .. }
if values.len() >= SPILL_AT && self.get(&key).is_none())
{
self.spill();
}
@@ -165,15 +284,17 @@ impl VariableMap {
pub fn iter(&self) -> Iter<'_> {
match &self.0 {
Repr::Small(entries) => Iter::Small(entries.iter()),
Repr::Large(map) => Iter::Large(map.iter()),
Repr::Shaped { shape, values } => Iter::Shaped(shape.keys().iter().zip(values.iter())),
Repr::Dict(map) => Iter::Dict(map.iter()),
}
}
pub fn iter_mut(&mut self) -> IterMut<'_> {
match &mut self.0 {
Repr::Small(entries) => IterMut::Small(entries.iter_mut()),
Repr::Large(map) => IterMut::Large(map.iter_mut()),
Repr::Shaped { shape, values } => {
IterMut::Shaped(shape.keys().iter().zip(values.iter_mut()))
}
Repr::Dict(map) => IterMut::Dict(map.iter_mut()),
}
}
@@ -249,8 +370,8 @@ impl<'a> VacantEntry<'a> {
}
pub enum Iter<'a> {
Small(std::slice::Iter<'a, (Symbol, Variable)>),
Large(std::collections::hash_map::Iter<'a, Symbol, Variable>),
Shaped(std::iter::Zip<std::slice::Iter<'a, Symbol>, std::slice::Iter<'a, Variable>>),
Dict(std::collections::hash_map::Iter<'a, Symbol, Variable>),
}
impl<'a> Iterator for Iter<'a> {
@@ -258,22 +379,22 @@ impl<'a> Iterator for Iter<'a> {
fn next(&mut self) -> Option<Self::Item> {
match self {
Iter::Small(iter) => iter.next().map(|(key, value)| (key, value)),
Iter::Large(iter) => iter.next(),
Iter::Shaped(iter) => iter.next(),
Iter::Dict(iter) => iter.next(),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
Iter::Small(iter) => iter.size_hint(),
Iter::Large(iter) => iter.size_hint(),
Iter::Shaped(iter) => iter.size_hint(),
Iter::Dict(iter) => iter.size_hint(),
}
}
}
pub enum IterMut<'a> {
Small(std::slice::IterMut<'a, (Symbol, Variable)>),
Large(std::collections::hash_map::IterMut<'a, Symbol, Variable>),
Shaped(std::iter::Zip<std::slice::Iter<'a, Symbol>, std::slice::IterMut<'a, Variable>>),
Dict(std::collections::hash_map::IterMut<'a, Symbol, Variable>),
}
impl<'a> Iterator for IterMut<'a> {
@@ -281,15 +402,19 @@ impl<'a> Iterator for IterMut<'a> {
fn next(&mut self) -> Option<Self::Item> {
match self {
IterMut::Small(iter) => iter.next().map(|(key, value)| (&*key, value)),
IterMut::Large(iter) => iter.next(),
IterMut::Shaped(iter) => iter.next(),
IterMut::Dict(iter) => iter.next(),
}
}
}
pub enum IntoIter {
Small(smallvec::IntoIter<[(Symbol, Variable); INLINE]>),
Large(std::collections::hash_map::IntoIter<Symbol, Variable>),
Shaped {
shape: Rc<Shape>,
index: usize,
values: smallvec::IntoIter<[Variable; INLINE]>,
},
Dict(std::collections::hash_map::IntoIter<Symbol, Variable>),
}
impl Iterator for IntoIter {
@@ -297,8 +422,17 @@ impl Iterator for IntoIter {
fn next(&mut self) -> Option<Self::Item> {
match self {
IntoIter::Small(iter) => iter.next(),
IntoIter::Large(iter) => iter.next(),
IntoIter::Shaped {
shape,
index,
values,
} => {
let value = values.next()?;
let key = shape.key_at(*index)?.clone();
*index += 1;
Some((key, value))
}
IntoIter::Dict(iter) => iter.next(),
}
}
}
@@ -309,8 +443,12 @@ impl IntoIterator for VariableMap {
fn into_iter(self) -> IntoIter {
match self.0 {
Repr::Small(entries) => IntoIter::Small(entries.into_iter()),
Repr::Large(map) => IntoIter::Large(map.into_iter()),
Repr::Shaped { shape, values } => IntoIter::Shaped {
shape,
index: 0,
values: values.into_iter(),
},
Repr::Dict(map) => IntoIter::Dict(map.into_iter()),
}
}
}
@@ -360,6 +498,7 @@ impl PartialEq for VariableMap {
impl VariableMap {
pub fn insert_str(&mut self, key: &str, value: Variable) -> Option<Variable> {
let value = self.follow(key, value)?;
self.insert(Symbol::from(key), value)
}
}
@@ -383,3 +522,142 @@ impl serde::Serialize for VariableMap {
map.end()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn map(keys: &[&str]) -> VariableMap {
let mut map = VariableMap::new();
for (index, key) in keys.iter().enumerate() {
map.insert(Symbol::from(*key), Variable::Number(index.into()));
}
map
}
#[test]
fn maps_built_from_the_same_keys_share_a_shape() {
let a = map(&["id", "balance", "apr"]);
let b = map(&["id", "balance", "apr"]);
let c = map(&["balance", "id", "apr"]);
assert_eq!(a.shape_id(), b.shape_id());
assert_ne!(a.shape_id(), c.shape_id());
assert_eq!(a.get_str("balance"), Some(&Variable::Number(1.into())));
assert_eq!(
a.keys().map(Symbol::as_str).collect::<Vec<_>>(),
["id", "balance", "apr"]
);
}
#[test]
fn replacing_keeps_the_shape_and_removing_reshapes() {
let mut a = map(&["id", "balance", "apr"]);
let before = a.shape_id();
assert_eq!(
a.insert(Symbol::from("balance"), Variable::Bool(true)),
Some(Variable::Number(1.into()))
);
assert_eq!(a.shape_id(), before);
assert_eq!(a.remove_str("balance"), Some(Variable::Bool(true)));
assert_eq!(a.shape_id(), map(&["id", "apr"]).shape_id());
assert_eq!(a.get_str("apr"), Some(&Variable::Number(2.into())));
assert_eq!(a.len(), 2);
}
#[test]
fn hinted_reads_cache_two_shapes_including_absence() {
let a = map(&["id", "balance", "apr"]);
let b = map(&["balance", "id"]);
let mut hint = ShapeHint::default();
assert_eq!(
a.get_hinted(&mut hint, "balance"),
Some(&Variable::Number(1.into()))
);
assert_eq!(
b.get_hinted(&mut hint, "balance"),
Some(&Variable::Number(0.into()))
);
assert_eq!(hint.lookup(a.shape_id().unwrap()), Some(1));
assert_eq!(hint.lookup(b.shape_id().unwrap()), Some(0));
let mut missing = ShapeHint::default();
assert_eq!(a.get_hinted(&mut missing, "missing"), None);
assert_eq!(
missing.lookup(a.shape_id().unwrap()),
Some(ShapeHint::ABSENT)
);
assert_eq!(a.get_hinted(&mut missing, "missing"), None);
}
#[test]
fn map_values_keeps_the_shape() {
let source = map(&["id", "balance"]);
let mapped = source.map_values(|value| match value {
Variable::Number(n) => Variable::Number(*n * rust_decimal::Decimal::TWO),
other => other.shallow_clone(),
});
assert_eq!(mapped.shape_id(), source.shape_id());
assert_eq!(mapped.get_str("balance"), Some(&Variable::Number(2.into())));
}
#[test]
fn spilled_maps_have_no_shape_but_keep_their_contents() {
let keys: Vec<String> = (0..40).map(|i| format!("k{i}")).collect();
let mut map = VariableMap::new();
for key in &keys {
map.insert(Symbol::from(key.as_str()), Variable::Null);
}
assert!(map.shape().is_none());
let mut hint = ShapeHint::default();
assert_eq!(map.get_hinted(&mut hint, "k39"), Some(&Variable::Null));
assert_eq!(
map.insert(Symbol::from("k39"), Variable::Bool(false)),
Some(Variable::Null)
);
assert_eq!(
map.insert(Symbol::from("fresh"), Variable::Bool(true)),
None
);
assert_eq!(map.len(), 41);
let owned: Vec<(Symbol, Variable)> = map.into_iter().collect();
assert_eq!(owned.len(), 41);
}
#[test]
fn string_keyed_inserts_follow_transitions_or_fall_back() {
let mut first = VariableMap::new();
first.insert_new_str("approval", Variable::Bool(false));
first.insert_new_str("rejectionReasons", Variable::Null);
assert_eq!(first.len(), 2);
assert_eq!(first.get_str("approval"), Some(&Variable::Bool(false)));
let mut second = VariableMap::new();
assert_eq!(second.insert_str("approval", Variable::Bool(true)), None);
assert_eq!(second.insert_str("rejectionReasons", Variable::Null), None);
assert_eq!(second.shape_id(), first.shape_id());
assert_eq!(
second.insert_str("approval", Variable::Null),
Some(Variable::Bool(true))
);
assert_eq!(second.len(), 2);
let mut spilled = VariableMap::new();
for i in 0..40 {
spilled.insert_new_str(&format!("key{i}"), Variable::Null);
}
assert_eq!(spilled.len(), 40);
assert_eq!(
spilled.insert_str("key39", Variable::Bool(true)),
Some(Variable::Null)
);
assert_eq!(spilled.insert_str("fresh", Variable::Bool(true)), None);
assert_eq!(spilled.len(), 41);
}
#[test]
fn owned_iteration_preserves_order() {
let map = map(&["z", "a", "m"]);
let keys: Vec<String> = map
.into_iter()
.map(|(key, _)| key.as_str().to_owned())
.collect();
assert_eq!(keys, ["z", "a", "m"]);
}
}
+6 -14
View File
@@ -24,10 +24,12 @@ mod map;
mod ref_deser;
mod ref_ser;
mod ser;
mod shape;
pub use crate::rccell::RcCell;
pub use crate::variable::map::{Iter as MapIter, VariableMap};
pub use crate::variable::shape::{Shape, ShapeHint};
thread_local! {
static DOLLAR_KEY_RC: Rc<str> = Rc::from("$");
@@ -321,12 +323,7 @@ impl Variable {
Variable::from_array(arr.iter().map(|v| v.deep_clone()).collect())
}
Variable::Object(o) => {
let obj = o.borrow();
Variable::from_object(
obj.iter()
.map(|(k, v)| (k.clone(), v.deep_clone()))
.collect(),
)
Variable::from_object(o.borrow().map_values(|value| value.deep_clone()))
}
_ => self.shallow_clone(),
}
@@ -340,14 +337,9 @@ impl Variable {
let arr = a.borrow();
Variable::from_array(arr.iter().map(|v| v.depth_clone(depth - 1)).collect())
}
Variable::Object(o) => {
let obj = o.borrow();
Variable::from_object(
obj.iter()
.map(|(k, v)| (k.clone(), v.depth_clone(depth - 1)))
.collect(),
)
}
Variable::Object(o) => Variable::from_object(
o.borrow().map_values(|value| value.depth_clone(depth - 1)),
),
_ => self.shallow_clone(),
},
}
+304
View File
@@ -0,0 +1,304 @@
use crate::symbol::Symbol;
use ahash::HashMap;
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt::{Debug, Formatter};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
const MANY_AT: usize = 8;
const MAX_TRANSITIONS: usize = 4096;
#[derive(Default)]
enum Transitions {
#[default]
Empty,
Few(SmallVec<[(u64, Rc<Shape>); 4]>),
Many(usize, HashMap<u64, SmallVec<[Rc<Shape>; 1]>>),
}
impl Transitions {
fn len(&self) -> usize {
match self {
Transitions::Empty => 0,
Transitions::Few(few) => few.len(),
Transitions::Many(len, _) => *len,
}
}
fn candidates(&self, print: u64) -> impl Iterator<Item = &Rc<Shape>> {
let few = match self {
Transitions::Few(few) => Some(few.iter().filter(move |(known, _)| *known == print)),
_ => None,
};
let many = match self {
Transitions::Many(_, map) => map.get(&print).map(|list| list.iter()),
_ => None,
};
few.into_iter()
.flatten()
.map(|(_, child)| child)
.chain(many.into_iter().flatten())
}
fn push(&mut self, print: u64, child: Rc<Shape>) {
match self {
Transitions::Empty => {
let mut few = SmallVec::new();
few.push((print, child));
*self = Transitions::Few(few);
}
Transitions::Few(few) if few.len() < MANY_AT => few.push((print, child)),
Transitions::Few(few) => {
let mut map: HashMap<u64, SmallVec<[Rc<Shape>; 1]>> = HashMap::default();
for (known, shape) in few.drain(..) {
map.entry(known).or_default().push(shape);
}
map.entry(print).or_default().push(child);
*self = Transitions::Many(MANY_AT + 1, map);
}
Transitions::Many(len, map) => {
map.entry(print).or_default().push(child);
*len += 1;
}
}
}
}
thread_local! {
static ROOT: Rc<Shape> = Rc::new(Shape::new(Box::new([])));
}
pub struct Shape {
id: u64,
keys: Box<[Symbol]>,
prints: Box<[u64]>,
transitions: RefCell<Transitions>,
}
impl Shape {
fn new(keys: Box<[Symbol]>) -> Self {
Self {
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
prints: keys.iter().map(|key| Self::print(key.as_str())).collect(),
keys,
transitions: RefCell::new(Transitions::default()),
}
}
#[inline]
fn print(key: &str) -> u64 {
let bytes = key.as_bytes();
let mut packed = [0u8; 8];
let take = bytes.len().min(7);
packed[..take].copy_from_slice(&bytes[..take]);
packed[7] = bytes.len().min(255) as u8;
u64::from_le_bytes(packed)
}
#[inline]
fn exact(key: &str) -> bool {
key.len() <= 7
}
pub fn root() -> Rc<Shape> {
ROOT.with(Rc::clone)
}
pub fn of<'a>(keys: impl IntoIterator<Item = &'a Symbol>) -> Option<Rc<Shape>> {
keys.into_iter()
.try_fold(Self::root(), |shape, key| shape.with(key))
}
pub fn id(&self) -> u64 {
self.id
}
pub fn keys(&self) -> &[Symbol] {
&self.keys
}
pub fn len(&self) -> usize {
self.keys.len()
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
#[inline]
pub fn index_of(&self, key: &str) -> Option<usize> {
let print = Self::print(key);
if Self::exact(key) {
return self.prints.iter().position(|known| *known == print);
}
self.prints
.iter()
.enumerate()
.filter(|(_, known)| **known == print)
.map(|(index, _)| index)
.find(|&index| self.keys[index].as_str() == key)
}
#[inline]
pub fn key_at(&self, index: usize) -> Option<&Symbol> {
self.keys.get(index)
}
#[inline]
pub fn transition(&self, key: &str) -> Option<Rc<Shape>> {
let print = Self::print(key);
let transitions = self.transitions.borrow();
let position = self.keys.len();
transitions
.candidates(print)
.find(|child| {
Self::exact(key)
|| child
.key_at(position)
.is_some_and(|known| known.as_str() == key)
})
.cloned()
}
pub fn with(self: &Rc<Self>, key: &Symbol) -> Option<Rc<Shape>> {
if let Some(child) = self.transition(key.as_str()) {
return Some(child);
}
let mut transitions = self.transitions.borrow_mut();
if transitions.len() >= MAX_TRANSITIONS {
return None;
}
let mut keys = Vec::with_capacity(self.keys.len() + 1);
keys.extend(self.keys.iter().cloned());
keys.push(key.clone());
let child = Rc::new(Shape::new(keys.into_boxed_slice()));
transitions.push(Self::print(key.as_str()), child.clone());
Some(child)
}
pub fn without(&self, index: usize) -> Option<Rc<Shape>> {
Self::of(
self.keys
.iter()
.enumerate()
.filter(|(position, _)| *position != index)
.map(|(_, key)| key),
)
}
}
#[derive(Clone, Debug, Default)]
pub struct ShapeHint {
shapes: [u64; 2],
indices: [u32; 2],
next: u8,
}
impl ShapeHint {
pub const ABSENT: u32 = u32::MAX;
#[inline]
pub fn lookup(&self, shape: u64) -> Option<u32> {
if self.shapes[0] == shape {
return Some(self.indices[0]);
}
if self.shapes[1] == shape {
return Some(self.indices[1]);
}
None
}
#[inline]
pub fn record(&mut self, shape: u64, index: Option<usize>) {
let slot = self.next as usize;
self.shapes[slot] = shape;
self.indices[slot] = index.map_or(Self::ABSENT, |index| index as u32);
self.next ^= 1;
}
}
impl Debug for Shape {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Shape")
.field("id", &self.id)
.field("keys", &self.keys)
.finish()
}
}
impl PartialEq for Shape {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Shape {}
#[cfg(test)]
mod tests {
use super::*;
fn key(text: &str) -> Symbol {
Symbol::from(text)
}
fn chain(keys: &[&str]) -> Rc<Shape> {
let keys: Vec<Symbol> = keys.iter().map(|k| key(k)).collect();
Shape::of(keys.iter()).expect("unsaturated")
}
#[test]
fn transitions_are_interned_per_key_sequence() {
let a = chain(&["id", "balance"]);
let b = chain(&["id", "balance"]);
let c = chain(&["balance", "id"]);
assert!(Rc::ptr_eq(&a, &b));
assert_eq!(a.id(), b.id());
assert_ne!(a.id(), c.id());
assert_eq!(a.index_of("balance"), Some(1));
assert_eq!(c.index_of("balance"), Some(0));
assert_eq!(a.index_of("missing"), None);
}
#[test]
fn long_keys_with_a_shared_prefix_stay_distinct() {
let shape = chain(&["interestDue", "interestRate", "id"]);
assert_eq!(shape.index_of("interestDue"), Some(0));
assert_eq!(shape.index_of("interestRate"), Some(1));
assert_eq!(shape.index_of("interestDuo"), None);
assert_eq!(shape.index_of("id"), Some(2));
assert_eq!(shape.index_of("idx"), None);
let a = chain(&["interestDue"]);
let b = chain(&["interestRate"]);
assert!(!Rc::ptr_eq(&a, &b));
assert!(Rc::ptr_eq(&chain(&["interestRate"]), &b));
}
#[test]
fn removing_a_key_reuses_the_interned_shape() {
let shape = chain(&["a", "b", "c"]);
let without = shape.without(1).expect("unsaturated");
assert!(Rc::ptr_eq(&without, &chain(&["a", "c"])));
}
#[test]
fn wide_fan_out_stays_interned_until_saturation() {
let root = chain(&["fanout-fixed"]);
let children: Vec<Rc<Shape>> = (0..MAX_TRANSITIONS)
.map(|i| root.with(&key(&format!("k{i}"))).expect("below the cap"))
.collect();
assert_eq!(root.transitions.borrow().len(), MAX_TRANSITIONS);
for (i, child) in children.iter().enumerate() {
assert_eq!(child.index_of(&format!("k{i}")), Some(1));
assert!(Rc::ptr_eq(
&root.with(&key(&format!("k{i}"))).expect("interned"),
child
));
}
assert!(root.with(&key("one-too-many")).is_none());
}
}