From e6d20cb28f74ca51516453f3c8bc3abb5bf3771c Mon Sep 17 00:00:00 2001 From: Stefan Miljakovic Date: Fri, 9 Oct 2026 06:35:25 +0200 Subject: [PATCH] perf: typed runtime strings (text registers, string(), templates, concatenation, string builtins, text outputs and closures) --- core/engine/src/compiled/lowered.rs | 5 + core/engine/src/compiled/typed.rs | 6 +- core/engine/tests/compiled.rs | 68 +++- core/engine/tests/compiled_policy.rs | 82 ++++- core/expression/src/typed/batch.rs | 16 +- core/expression/src/typed/build.rs | 115 +++++- core/expression/src/typed/exec.rs | 150 ++------ core/expression/src/typed/hir.rs | 24 +- core/expression/src/typed/ins.rs | 47 ++- core/expression/src/typed/lower.rs | 249 +++++++++++-- core/expression/src/typed/mod.rs | 1 + core/expression/src/typed/output.rs | 50 ++- core/expression/src/typed/program.rs | 2 +- core/expression/src/typed/tests/exact.rs | 4 + core/expression/src/typed/tests/interp.rs | 60 ++- core/expression/src/typed/tests/lower.rs | 54 ++- core/expression/src/typed/tests/scale.rs | 1 + core/expression/src/typed/tests/workload.rs | 214 ++++++++++- core/expression/src/typed/text.rs | 383 ++++++++++++++++++++ 19 files changed, 1338 insertions(+), 193 deletions(-) create mode 100644 core/expression/src/typed/text.rs diff --git a/core/engine/src/compiled/lowered.rs b/core/engine/src/compiled/lowered.rs index 3dddffb9..1d1560be 100644 --- a/core/engine/src/compiled/lowered.rs +++ b/core/engine/src/compiled/lowered.rs @@ -92,6 +92,10 @@ impl Exports { } } } + Data::Text { .. } => match slot.take_text() { + Some((offsets, data, valid)) => Array::parts(Store::Text { offsets, data }, Self::validity(valid, len), len), + None => return Leaf::nulls(len), + }, }; Leaf::typed(array) } @@ -107,6 +111,7 @@ impl Exports { Data::Num { .. } => slot.decimal(at).map_or(Variable::Null, Variable::Number), Data::Bool(_) => slot.boolean(at).map_or(Variable::Null, Variable::Bool), Data::Code(_) => slot.code(at).and_then(text).map_or(Variable::Null, |t| Variable::String(t.into())), + Data::Text { .. } => slot.text(at).map_or(Variable::Null, |t| Variable::String(t.into())), } }; Leaf::Any( diff --git a/core/engine/src/compiled/typed.rs b/core/engine/src/compiled/typed.rs index 78a8a15b..2d840f18 100644 --- a/core/engine/src/compiled/typed.rs +++ b/core/engine/src/compiled/typed.rs @@ -1300,7 +1300,11 @@ impl<'a> Leaf<'a> { Some(dense) => dense.valued(rows), None => Bits::gather(&picked.source.valued(picked.source.len()), &picked.positions), }, - Leaf::Stitched(_) | Leaf::Records(_) => Bits::of(rows, |row| !self.null(row)), + Leaf::Stitched(stitched) => { + let parts: Vec> = stitched.sources.iter().map(|leaf| leaf.valued(leaf.len())).collect(); + Bits::of(rows, |row| stitched.located.get(row).is_some_and(|&(piece, at)| parts.get(piece).is_some_and(|bits| Bits::get(bits, at)))) + } + Leaf::Records(_) => Bits::of(rows, |row| !self.null(row)), Leaf::Typed(typed) if matches!(typed.values, Store::Coded { ref dict, .. } if !matches!(**dict, Dict::Any(_))) => { let Store::Coded { codes, .. } = &typed.values else { return Bits::of(rows, |row| !self.null(row)); diff --git a/core/engine/tests/compiled.rs b/core/engine/tests/compiled.rs index d6b6fedd..39b14c3d 100644 --- a/core/engine/tests/compiled.rs +++ b/core/engine/tests/compiled.rs @@ -922,7 +922,7 @@ impl Chain { #[tokio::test] async fn graph_typed_falls_back_per_unit() { let mut failures = Vec::new(); - let unsupported = Chain::expression("label", &[("label", "string(income) + ' ' + tier")]); + let unsupported = Chain::expression("label", &[("label", "split(tier, 'l')")]); let (typed, laned) = Chain::checked(Chain::graph(Chain::nodes(Some(unsupported))), &Chain::rows(300, 3), &mut failures).await; assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n")); if Chain::typed() { @@ -1017,6 +1017,72 @@ async fn graph_typed_lists_and_closures() { } } +#[tokio::test] +async fn graph_typed_strings() { + let mut noise = Noise::new(29); + let names = ["Anna", "bob", " Cara ", "Émile", "straße", "", "İstanbul", "日本", "Bart"]; + let cities = ["Berlin", "bonn", "Anna", " x ", ""]; + let tiers = ["gold", "silver", "Gold"]; + let mut rows: Vec = (0..300) + .map(|_| { + let items: Vec = (0..noise.below(4)).map(|_| json!({"name": names[noise.below(names.len())], "qty": noise.below(9), "tag": tiers[noise.below(3)]})).collect(); + let tags: Vec = (0..noise.below(3)).map(|_| json!(cities[noise.below(cities.len())])).collect(); + let amount = format!("{}.{}", noise.below(4000) as i64 - 2000, noise.below(100)).parse::().map(Value::Number).unwrap_or(Value::Null); + json!({"name": names[noise.below(names.len())], "city": cities[noise.below(cities.len())], "tier": tiers[noise.below(3)], "amount": amount, "qty": noise.below(10), "flag": noise.below(2) == 0, "items": items, "tags": tags}) + }) + .collect(); + let long = "ab".repeat(600); + let odd = [ + json!({"name": null, "city": "Berlin", "tier": null, "amount": null, "qty": 3, "flag": null, "items": null, "tags": null}), + json!({"name": long, "city": long, "tier": "gold", "amount": 79228162514264337593543950335u128, "qty": 9223372036854775807i64, "flag": false, "items": [], "tags": []}), + json!({"name": "ß", "city": "Dž", "tier": "", "amount": -0.0, "qty": 0, "flag": true, "items": [{"name": "ß", "qty": 1, "tag": null}], "tags": ["Dž"]}), + json!({"name": "\u{1F600} x", "city": "\u{2003}a\u{2003}", "tier": "silver", "amount": 0.000000001, "qty": 6, "flag": false, "items": [{"qty": 2}], "tags": ["\u{2003}a\u{2003}"]}), + json!({"qty": 5}), + json!({"name": "Anna", "city": "Anna", "tier": "gold", "amount": 1.50, "qty": 8, "flag": true, "items": [{"name": "gold", "qty": 9223372036854775807i64, "tag": "gold"}], "tags": ["Anna", "x"]}), + json!({"name": "", "city": "", "tier": "silver", "amount": 0.00, "qty": 2, "flag": true, "items": [{"name": "", "qty": 0}], "tags": [""]}), + ]; + for (at, row) in odd.into_iter().enumerate() { + rows.insert(at * 31 + 2, row); + } + let nodes = vec![ + Chain::expression( + "texts", + &[ + ("s", "string(amount)"), + ("tpl", "`${name}-${qty}:${amount} ${flag}`"), + ("cat", "name + '/' + city"), + ("up", "upper(name)"), + ("lo", "lower(city)"), + ("tr", "trim(name)"), + ("has", "contains(lower(name), 'an')"), + ("tierz", "tier ?? 'none'"), + ("pick", "qty > 4 ? name : 'nobody'"), + ("same", "name == city"), + ("pass", "city"), + ("rx", "matches(name, '^[A-Z]')"), + ("names", "map(items, #.name)"), + ("upn", "map(items, upper(#.name) + string(#.qty))"), + ("cnt", "count(items, #.name == tier)"), + ("intag", "city in tags"), + ("big", "string(amount * 1000000000000)"), + ("mixeq", "name == qty"), + ], + ), + Chain::table("level", &["qty", "tierz"], &["level", "who"], &[&["> 7", "'gold'", "'top'", "name"], &["> 3", "", "'mid'", "city"], &["", "", "'low'", "'nobody'"]]), + Chain::expression("later", &[("again", "upper(tierz) + '!'"), ("g", "tierz in ['gold', 'none']"), ("l", "len(cat)"), ("w", "level + ':' + (who ?? '-')")]), + ]; + let mut failures = Vec::new(); + let (typed, laned) = Chain::checked(Chain::graph(nodes.clone()), &rows, &mut failures).await; + eprintln!("strings typed {typed} laned {laned}"); + if Chain::typed() { + assert!(typed > laned, "units typed {typed}, laned {laned}"); + } + rows.insert(12, json!({"name": "q", "city": "q", "tier": "gold", "amount": 1, "qty": 2, "flag": true, "items": [{"name": null, "qty": 2}], "tags": [null]})); + rows.insert(9, json!({"name": 7, "city": true, "tier": 1.5, "amount": "x", "qty": 1, "flag": true, "items": [{"name": 3, "qty": "a"}], "tags": [1]})); + Chain::checked(Chain::graph(nodes), &rows, &mut failures).await; + assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.iter().take(10).cloned().collect::>().join("\n")); +} + #[tokio::test] async fn graph_typed_extremes() { let mut rows = Chain::rows(200, 9); diff --git a/core/engine/tests/compiled_policy.rs b/core/engine/tests/compiled_policy.rs index 9d07b7cf..774a7d19 100644 --- a/core/engine/tests/compiled_policy.rs +++ b/core/engine/tests/compiled_policy.rs @@ -778,7 +778,7 @@ fn policy_anchor_is_fully_typed() { fn policy_typed_falls_back_per_unit() { let policy = Anchor::POLICY.replace( " {match: \"customer.risk\"", - " {expression: \"customer.label\", value: \"string(customer.age)\"},\n {match: \"customer.risk\"", + " {expression: \"customer.label\", value: \"split(customer.tier, 'l')\"},\n {match: \"customer.risk\"", ); assert_ne!(policy, Anchor::POLICY); let ws = Anchor::workspace_with(&policy); @@ -798,7 +798,7 @@ fn policy_typed_falls_back_per_unit() { fn policy_typed_fuses_lane_runs() { let policy = Anchor::POLICY.replace( " {match: \"customer.risk\"", - " {expression: \"customer.label\", value: \"string(customer.age)\"},\n {expression: \"customer.tag\", value: \"string(customer.income)\"},\n {match: \"customer.risk\"", + " {expression: \"customer.label\", value: \"split(customer.tier, 'l')\"},\n {expression: \"customer.tag\", value: \"split(customer.tier, 'o')\"},\n {match: \"customer.risk\"", ); assert_ne!(policy, Anchor::POLICY); let ws = Anchor::workspace_with(&policy); @@ -914,6 +914,84 @@ fn policy_typed_lists_and_closures() { assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.join("\n")); } +#[test] +fn policy_typed_strings() { + let policy = r#"{ + models: { + customer: {name: "string", city: "string", tier: "string", amount: "number", qty: "number", flag: "boolean", tags: "string[]", items: "item[]"}, + item: {name: "string", qty: "number"}, + }, + blocks: [ + {expression: "item.label", value: "upper(item.name) + '-' + customer.tier"}, + {expression: "item.same", value: "item.name == customer.name"}, + {expression: "item.s", value: "string(item.qty * customer.amount)"}, + {expression: "customer.s", value: "string(customer.amount)"}, + {expression: "customer.tpl", value: "`${customer.name}:${customer.qty}:${customer.flag}`"}, + {expression: "customer.cat", value: "customer.name + '/' + customer.city"}, + {expression: "customer.up", value: "upper(customer.name)"}, + {expression: "customer.tr", value: "trim(customer.city)"}, + {expression: "customer.has", value: "contains(lower(customer.name), 'an')"}, + {expression: "customer.tz", value: "customer.tier ?? 'none'"}, + {expression: "customer.pick", value: "customer.qty > 4 ? customer.name : 'nobody'"}, + {expression: "customer.same", value: "customer.name == customer.city"}, + {expression: "customer.gold", value: "customer.tz in ['gold', 'none']"}, + {expression: "customer.names", value: "map(customer.items, #.name)"}, + {expression: "customer.cnt", value: "count(customer.items, #.name == customer.tier)"}, + {expression: "customer.intag", value: "customer.city in customer.tags"}, + {expression: "customer.rx", value: "matches(customer.name, '^[A-Z]')"}, + {expression: "customer.big", value: "string(customer.amount * 1000000000000)"}, + {expression: "customer.again", value: "upper(customer.tz) + '!'"}, + {table: "lvl", inputs: ["customer.qty"], outputs: ["customer.lvl"], rules: [ + ["> 7", "customer.name"], + ["> 3", "customer.city"], + ["", "'small'"], + ]}, + {expression: "customer.lv", value: "customer.lvl + ':' + customer.tz"}, + ], +}"#; + let mut state = 41u64; + let mut pick = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let names = ["Anna", "bob", " Cara ", "Émile", "straße", "", "İstanbul", "日本", "Bart"]; + let cities = ["Berlin", "bonn", "Anna", " x ", ""]; + let tiers = ["gold", "silver", "Gold"]; + let mut values: Vec = (0..300) + .map(|_| { + let items: Vec = (0..pick(4)).map(|_| json!({"name": names[pick(9) as usize], "qty": pick(9)})).collect(); + let tags: Vec = (0..pick(3)).map(|_| json!(cities[pick(5) as usize])).collect(); + json!({"customer": {"name": names[pick(9) as usize], "city": cities[pick(5) as usize], "tier": tiers[pick(3) as usize], "amount": pick(40_000) as f64 / 8.0 - 2000.0, "qty": pick(10), "flag": pick(2) == 0, "tags": tags, "items": items}}) + }) + .collect(); + let long = "ab".repeat(600); + let odd = [ + json!({"customer": {"name": null, "city": "Berlin", "tier": null, "amount": null, "qty": 3, "flag": null, "tags": null, "items": null}}), + json!({"customer": {"name": long, "city": long, "tier": "gold", "amount": 9223372036854775807i64, "qty": 9, "flag": false, "tags": [], "items": []}}), + json!({"customer": {"name": "ß", "city": "Dž", "tier": "", "amount": -0.0, "qty": 0, "flag": true, "tags": ["Dž"], "items": [{"name": "ß", "qty": 1}]}}), + json!({"customer": {"name": "\u{1F600} x", "city": "\u{2003}a\u{2003}", "tier": "silver", "amount": 0.000000001, "qty": 6, "flag": false, "tags": ["\u{2003}a\u{2003}"], "items": [{"qty": 2}]}}), + json!({"customer": {"qty": 5}}), + json!({"customer": {"name": "Anna", "city": "Anna", "tier": "gold", "amount": 1.50, "qty": 8, "flag": true, "tags": ["Anna"], "items": [{"name": "gold", "qty": 9223372036854775807i64}]}}), + ]; + for (at, row) in odd.into_iter().enumerate() { + values.insert(at * 37 + 4, row); + } + let ws = Anchor::workspace_with(policy); + let mut failures = Vec::new(); + for (typed, laned, hosted) in Anchor::checked(&ws, &values, &mut failures) { + eprintln!("strings typed {typed} laned {laned} hosted {hosted}"); + if Anchor::typed() { + assert!(typed > laned, "units typed {typed}, laned {laned}"); + } + } + values.insert(12, json!({"customer": {"name": "q", "city": "q", "tier": "gold", "amount": 1, "qty": 2, "flag": true, "tags": [null], "items": [{"name": null, "qty": 2}]}})); + values.insert(9, json!({"customer": {"name": 7, "city": true, "tier": 1.5, "amount": "x", "qty": 1, "flag": true, "tags": [1], "items": [{"name": 3, "qty": "a"}]}})); + Anchor::checked(&ws, &values, &mut failures); + assert!(failures.is_empty(), "{} mismatches:\n{}", failures.len(), failures.iter().take(10).cloned().collect::>().join("\n")); +} + #[test] fn policy_typed_extremes() { let customer = |accounts: Value| json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": accounts}}); diff --git a/core/expression/src/typed/batch.rs b/core/expression/src/typed/batch.rs index 2d61c507..cbcf11bf 100644 --- a/core/expression/src/typed/batch.rs +++ b/core/expression/src/typed/batch.rs @@ -70,10 +70,11 @@ pub(crate) struct Feeds<'x> { pub(crate) parents: Vec>, } -struct Matcher<'d> { +#[derive(Clone, Debug)] +pub(crate) struct Matcher<'d> { keys: Vec<(usize, u64)>, lengths: u64, - values: &'d [Box], + values: Cow<'d, [Box]>, other: i32, } @@ -400,10 +401,15 @@ impl<'x> Feed<'x> { } impl<'d> Matcher<'d> { - fn new(dict: &'d Dict) -> Self { + pub(crate) fn new(dict: &'d Dict) -> Self { let keys = dict.values.iter().map(|v| (v.len(), Self::key(v.as_bytes()))).collect(); let lengths = dict.values.iter().fold(0u64, |mask, v| mask | 1u64 << v.len().min(63)); - Self { keys, lengths, values: &dict.values, other: dict.values.len() as i32 } + Self { keys, lengths, values: Cow::Borrowed(&dict.values), other: dict.values.len() as i32 } + } + + pub(crate) fn owned(dict: &Dict) -> Matcher<'static> { + let Matcher { keys, lengths, values, other } = Matcher::new(dict); + Matcher { keys, lengths, values: Cow::Owned(values.into_owned()), other } } #[inline] @@ -433,7 +439,7 @@ impl<'d> Matcher<'d> { } #[inline] - fn code(&self, bytes: Option<&[u8]>) -> i32 { + pub(crate) fn code(&self, bytes: Option<&[u8]>) -> i32 { let Some(bytes) = bytes else { return self.other; }; diff --git a/core/expression/src/typed/build.rs b/core/expression/src/typed/build.rs index 86570da9..cc084762 100644 --- a/core/expression/src/typed/build.rs +++ b/core/expression/src/typed/build.rs @@ -1,9 +1,11 @@ +use crate::typed::batch::Matcher; use crate::typed::hir::{Arith, Cmp, Fold, Func, Hir, Kind, Lit, NodeId, Op, Scope, Unsupported}; -use crate::typed::ins::{Arg, Arm, BufDef, FixOp, Guard, Ins, Rep, Src, Tab, R}; +use crate::typed::ins::{Arg, Arm, BufDef, FixOp, Guard, Ins, Pattern, Rep, Src, Tab, R}; use crate::typed::kernel::K; use crate::typed::lookup::Lookup; use crate::typed::num::Dec; use std::collections::HashMap; +use std::sync::Arc; #[derive(Clone, Copy, Debug)] pub(crate) struct Passes { @@ -183,6 +185,9 @@ impl<'h> Build<'h> { Op::Parent(a) | Op::Neg(a) => r(a), Op::Const(lit) => Rep::of_lit(lit), Op::Classify(..) => Rep::Code, + Op::Str(_) | Op::Decode(_) | Op::Concat(_) => Rep::Text, + Op::Call(Func::Upper | Func::Lower | Func::Trim, _) => Rep::Text, + Op::Call(Func::Contains | Func::Matches, _) => Rep::Bool, Op::Not(_) | Op::Cmp(..) | Op::And(..) | Op::Or(..) | Op::InSet(..) | Op::InRange(..) => Rep::Bool, Op::Arith(op, a, b) => match (op, r(a), r(b)) { (Arith::Add | Arith::Sub, Rep::Fix(x), Rep::Fix(y)) if x == y => Rep::Fix(x), @@ -332,10 +337,13 @@ impl<'h> Build<'h> { } } for (i, node) in hir.nodes.iter().enumerate() { - if matches!(node.op, Op::Const(_)) || self.rep[i] == Rep::Text { + if matches!(node.op, Op::Const(_)) { continue; } for &u in &self.users[i] { + if self.direct(i as NodeId) && !self.wants(u, i as NodeId) { + continue; + } let cs = match hir.nodes[u as usize].op { Op::Fold { .. } => self.acc[u as usize], _ => self.stage[u as usize], @@ -377,9 +385,6 @@ impl<'h> Build<'h> { } fn konst(&mut self, lit: Lit, rep: Rep) -> Result { - if rep == Rep::Text { - return Err(Unsupported::new("typed: text constant as value")); - } if let Some(r) = self.const_of.get(&(lit.clone(), rep)) { return Ok(*r); } @@ -474,13 +479,36 @@ impl<'h> Build<'h> { Ok(d) } - fn arg(&self, i: NodeId) -> Result { + fn direct(&self, i: NodeId) -> bool { + self.rep[i as usize] == Rep::Text && matches!(self.hir.nodes[i as usize].op, Op::Column(_) | Op::Field(..)) + } + + fn wants(&self, u: NodeId, i: NodeId) -> bool { + let user = &self.hir.nodes[u as usize]; + let argful = match &user.op { + Op::Classify(..) | Op::Concat(_) | Op::Str(_) => true, + Op::Call(f, _) => f.text(), + Op::Cmp(_, a, b) => self.rep[*a as usize] == Rep::Text && self.rep[*b as usize] == Rep::Text, + _ => false, + }; + !(argful && user.scope == self.hir.nodes[i as usize].scope) + } + + fn arg(&mut self, i: NodeId) -> Result { let scope = self.keys[self.cur].1; + let direct = self.direct(i); match &self.hir.nodes[i as usize].op { - Op::Column(c) if self.rep[i as usize] == Rep::Text && scope == Scope::Row => Ok(Arg::Src(Src::Col(*c))), - Op::Field(l, f) if self.rep[i as usize] == Rep::Text && scope == Scope::Elem(*l) => Ok(Arg::Src(Src::Field(*l, *f))), + Op::Column(c) if direct && scope == Scope::Row => Ok(Arg::Src(Src::Col(*c))), + Op::Field(l, f) if direct && scope == Scope::Elem(*l) => Ok(Arg::Src(Src::Field(*l, *f))), Op::Const(Lit::Text(s)) => Ok(Arg::Lit(s.clone())), - _ => Err(Unsupported::new("typed: text argument")), + _ => Ok(Arg::Reg(self.val(i)?)), + } + } + + fn pattern(&self, i: NodeId) -> Result, Unsupported> { + match &self.hir.nodes[i as usize].op { + Op::Const(Lit::Text(s)) => Pattern::new(s).map(Box::new).map_err(|_| Unsupported::new("typed: invalid pattern")), + _ => Err(Unsupported::new("typed: pattern is not a literal")), } } @@ -507,7 +535,7 @@ impl<'h> Build<'h> { && self.outs[m].is_empty() && self.keeps[m].is_empty() && !self.cross[m] - && self.rep[m] != Rep::Text + && !self.direct(m as NodeId) && !self.vreg.contains_key(&(self.cur, m as NodeId)) && !self.users[m].is_empty() }; @@ -548,7 +576,7 @@ impl<'h> Build<'h> { continue; } for inp in self.hir.nodes[m as usize].op.inputs() { - if !set.contains(&inp) && !self.is_const(inp) && self.rep[inp as usize] != Rep::Text { + if !set.contains(&inp) && !self.is_const(inp) && (!self.direct(inp) || self.wants(m, inp)) { self.val(inp)?; } } @@ -746,7 +774,14 @@ impl<'h> Build<'h> { let (va, vb) = (self.val(a)?, self.val(b)?); Ins::EqBool { ne, dst: self.fresh()?, a: va, b: vb } } - (Rep::Text, Rep::Text) if eq => Ins::EqText { ne, dst: self.fresh()?, a: self.arg(a)?, b: self.arg(b)? }, + (Rep::Text, Rep::Text) if eq => { + let (x, y) = (self.arg(a)?, self.arg(b)?); + Ins::EqText { ne, dst: self.fresh()?, a: x, b: y } + } + (Rep::Text, Rep::Null) | (Rep::Null, Rep::Text) if eq => { + let (va, vb) = (self.val(a)?, self.val(b)?); + Ins::CmpGen { op, dst: self.fresh()?, a: va, ra, b: vb, rb } + } (Rep::Text, _) | (_, Rep::Text) => return Err(Unsupported::new("typed: text compare")), _ => { let (va, vb) = (self.val(a)?, self.val(b)?); @@ -824,7 +859,6 @@ impl<'h> Build<'h> { let rof = |b: &Build, x: &NodeId| b.rep[*x as usize]; let v = match &node.op { Op::Const(_) => self.konst_node(i)?, - Op::Column(_) | Op::Field(..) if rep == Rep::Text => return Err(Unsupported::new("typed: text value")), Op::Column(c) => { let d = self.fresh()?; self.emit(Ins::Load { dst: d, src: Src::Col(*c), rep }); @@ -835,10 +869,43 @@ impl<'h> Build<'h> { self.emit(Ins::Load { dst: d, src: Src::Field(*l, *f), rep }); d } - Op::Classify(..) => { - let k = self.classes.get(&i).copied().ok_or_else(|| Unsupported::new("typed: classify"))?; + Op::Classify(a, dict) => match self.classes.get(&i).copied() { + Some(k) => { + let d = self.fresh()?; + self.emit(Ins::Load { dst: d, src: Src::Class(k), rep }); + d + } + None => { + let x = self.arg(*a)?; + let matcher = Box::new(Matcher::owned(hir.dict(*dict))); + let d = self.fresh()?; + self.emit(Ins::Class { dst: d, a: x, matcher }); + d + } + }, + Op::Str(a) => { + let x = self.arg(*a)?; let d = self.fresh()?; - self.emit(Ins::Load { dst: d, src: Src::Class(k), rep }); + self.emit(Ins::Str { dst: d, a: x, rep: self.rep[*a as usize] }); + d + } + Op::Decode(a) => { + let Kind::Code(dict) = hir.nodes[*a as usize].ty.kind else { + return Err(Unsupported::new("typed: decode")); + }; + let values: Arc<[Box]> = hir.dict(dict).values.clone().into(); + let va = self.val(*a)?; + let d = self.fresh()?; + self.emit(Ins::Decode { dst: d, a: va, values }); + d + } + Op::Concat(parts) => { + let mut args = Vec::with_capacity(parts.len()); + for p in parts { + args.push(self.arg(*p)?); + } + let d = self.fresh()?; + self.emit(Ins::Concat { dst: d, parts: args }); d } Op::Parent(a) if self.is_const(*a) => self.konst_node(*a)?, @@ -971,9 +1038,19 @@ impl<'h> Build<'h> { } Op::Call(func, args) => { let a = self.arg(*args.first().ok_or_else(|| Unsupported::new("typed: call"))?)?; - let b = args.get(1).map(|x| self.arg(*x)).transpose()?; - let d = self.fresh()?; - self.emit(Ins::Text { func: *func, dst: d, a, b }); + let ins = match func { + Func::Matches => { + let pattern = self.pattern(*args.get(1).ok_or_else(|| Unsupported::new("typed: call"))?)?; + Ins::Matches { dst: self.fresh()?, a, pattern } + } + f if f.mapping() => Ins::Map { func: *f, dst: self.fresh()?, a }, + f => { + let b = args.get(1).map(|x| self.arg(*x)).transpose()?; + Ins::Text { func: *f, dst: self.fresh()?, a, b } + } + }; + let d = ins.dst().ok_or_else(|| Unsupported::new("typed: call"))?; + self.emit(ins); d } }; diff --git a/core/expression/src/typed/exec.rs b/core/expression/src/typed/exec.rs index a1603bad..c40aca70 100644 --- a/core/expression/src/typed/exec.rs +++ b/core/expression/src/typed/exec.rs @@ -1,7 +1,7 @@ use crate::lane::Column; -use crate::typed::batch::{Data, Feed, Feeds, Lists, Scales, Text}; +use crate::typed::batch::{Data, Feed, Feeds, Lists, Scales}; use crate::typed::hir::{Arith, Cmp, Fold, Func, Lit, Range, Scope}; -use crate::typed::ins::{Arg, FixOp, Guard, Ins, Rep, Src, Tab, R}; +use crate::typed::ins::{FixOp, Guard, Ins, Rep, Src, Tab, R}; use crate::typed::kernel::K; use crate::typed::lookup::{Domain, Lookup}; use crate::typed::num::{Dec, N}; @@ -30,6 +30,8 @@ pub(crate) struct Reg { pub(crate) wide: [u64; Reg::WORDS], pub(crate) big: Vec, pub(crate) masks: Vec, + pub(crate) text: Vec, + pub(crate) span: Vec<(u32, u32)>, } #[derive(Clone, Default)] @@ -43,21 +45,16 @@ pub(crate) struct Buf { pub(crate) wide: Vec, pub(crate) big: Vec, pub(crate) any: bool, + pub(crate) text: Vec, + pub(crate) span: Vec<(u32, u32)>, } -struct Others<'r> { +pub(crate) struct Others<'r> { lo: &'r [Reg], hi: &'r [Reg], at: usize, } -#[derive(Clone, Copy)] -enum TV<'a, 'x> { - Lit(&'a [u8]), - Col(&'a Text<'x>, &'a Feed<'x>), - Missing, -} - pub(crate) struct Exec<'e, 'x> { pub(crate) feeds: &'e Feeds<'x>, pub(crate) select: Option<&'e [u64]>, @@ -144,6 +141,7 @@ impl Buf { self.wide.clear(); self.wide.resize(words, 0); self.any = false; + self.text.clear(); } #[inline] @@ -218,6 +216,8 @@ impl Reg { wide: [0; Self::WORDS], big: Vec::new(), masks: Vec::new(), + text: Vec::new(), + span: Vec::new(), } } @@ -232,7 +232,8 @@ impl Reg { } Lit::Bool(b) => self.bits.fill(if *b { u64::MAX } else { 0 }), Lit::Code(_, c) => self.codes.fill(*c), - Lit::Null | Lit::Text(_) => self.valid.fill(0), + Lit::Text(t) => self.literal(t), + Lit::Null => self.valid.fill(0), } if rep == Rep::Null { self.valid.fill(0); @@ -325,28 +326,6 @@ impl Reg { } } -impl<'a, 'x> TV<'a, 'x> { - #[inline] - fn get(self, at: usize) -> Option<&'a [u8]> { - match self { - TV::Lit(b) => Some(b), - TV::Col(text, feed) => match feed.valid(at) { - true => text.get(at), - false => None, - }, - TV::Missing => None, - } - } - - fn valid_word(self, at: usize) -> u64 { - match self { - TV::Lit(_) => u64::MAX, - TV::Col(_, feed) => feed.valid_word(at, 64) & !feed.fault_word(at / 64), - TV::Missing => 0, - } - } -} - impl<'e, 'x> Exec<'e, 'x> { #[cfg(test)] thread_local! { @@ -363,7 +342,7 @@ impl<'e, 'x> Exec<'e, 'x> { } } - fn feed(&self, src: Src) -> Option<&'e Feed<'x>> { + pub(crate) fn feed(&self, src: Src) -> Option<&'e Feed<'x>> { match src { Src::Col(c) => self.feeds.columns.get(c as usize), Src::Field(l, f) => self.feeds.fields.get(l as usize).and_then(|l| l.get(f as usize)), @@ -371,19 +350,6 @@ impl<'e, 'x> Exec<'e, 'x> { } } - fn view<'a>(&'a self, arg: &'a Arg) -> TV<'a, 'x> { - match arg { - Arg::Lit(s) => TV::Lit(s.as_bytes()), - Arg::Src(src) => match self.feed(*src) { - Some(feed) => match feed.text() { - Some(text) => TV::Col(text, feed), - None => TV::Missing, - }, - None => TV::Missing, - }, - } - } - #[inline(always)] fn num(&self, op: Arith, d: &mut Reg, act: Option<&[u64; Reg::WORDS]>, ovf: &mut [u64; Reg::WORDS], x: impl Fn(usize) -> Dec, y: impl Fn(usize) -> Dec) { let words = self.words.min(Reg::WORDS); @@ -457,7 +423,7 @@ impl<'e, 'x> Exec<'e, 'x> { } #[inline] - fn def(regs: &mut [Reg], dst: R, f: impl FnOnce(&mut Reg, &Others)) { + pub(crate) fn def(regs: &mut [Reg], dst: R, f: impl FnOnce(&mut Reg, &Others)) { let at = dst as usize; let (lo, rest) = regs.split_at_mut(at); if let Some((d, hi)) = rest.split_first_mut() { @@ -517,7 +483,7 @@ impl<'e, 'x> Exec<'e, 'x> { } #[inline(always)] - fn bools(&self, act: Option<&[u64; Reg::WORDS]>, bits: &mut [u64; Reg::WORDS], mut f: impl FnMut(usize) -> bool) { + pub(crate) fn bools(&self, act: Option<&[u64; Reg::WORDS]>, bits: &mut [u64; Reg::WORDS], mut f: impl FnMut(usize) -> bool) { let words = self.words.min(Reg::WORDS); match act { None => K::pack_idx(self.n, &mut bits[..words], f), @@ -534,7 +500,7 @@ impl<'e, 'x> Exec<'e, 'x> { } #[inline(always)] - fn each(&self, act: Option<&[u64; Reg::WORDS]>, skip: &[u64; Reg::WORDS], mut f: impl FnMut(usize)) { + pub(crate) fn each(&self, act: Option<&[u64; Reg::WORDS]>, skip: &[u64; Reg::WORDS], mut f: impl FnMut(usize)) { for w in 0..self.words.min(Reg::WORDS) { let mut m = act.map_or(u64::MAX, |a| a[w]) & self.tail(w) & !skip[w]; while m != 0 { @@ -618,7 +584,8 @@ impl<'e, 'x> Exec<'e, 'x> { } } Rep::Bool => K::pack1(parent, &mut d.bits[..words], |p| K::get(&b.bits, p as usize)), - Rep::Text | Rep::Null => {} + Rep::Text => self.gather_text(d, b, parent), + Rep::Null => {} } let (r0, r1) = (parent.first().map_or(0, |p| *p as usize), parent.last().map_or(0, |p| *p as usize + 1)); if K::range(&b.valid, r0, r1, true) && K::range(&b.fault, r0, r1, false) { @@ -658,7 +625,8 @@ impl<'e, 'x> Exec<'e, 'x> { } Rep::Code => d.codes[..n].copy_from_slice(&b.codes[start..start + n]), Rep::Bool => d.bits[..words].copy_from_slice(&b.bits[w0..w0 + words]), - Rep::Text | Rep::Null => {} + Rep::Text => self.fill_text(d, b), + Rep::Null => {} } }); } @@ -688,7 +656,8 @@ impl<'e, 'x> Exec<'e, 'x> { } Rep::Code => b.codes[start..start + n].copy_from_slice(&r.codes[..n]), Rep::Bool => b.bits[w0..w0 + words].copy_from_slice(&r.bits[..words]), - Rep::Text | Rep::Null => {} + Rep::Text => self.spill_text(r, b), + Rep::Null => {} } } Ins::Fix { op, dst, a, b, rep } => Self::def(regs, *dst, |d, regs| { @@ -891,7 +860,7 @@ impl<'e, 'x> Exec<'e, 'x> { d.valid[w] = u64::MAX; } }), - Ins::CmpGen { op, dst, a, ra, b, rb } if matches!((ra, rb), (Rep::Null, _) | (_, Rep::Null)) && *ra != Rep::Text && *rb != Rep::Text => Self::def(regs, *dst, |d, regs| { + Ins::CmpGen { op, dst, a, ra, b, rb } if matches!((ra, rb), (Rep::Null, _) | (_, Rep::Null)) => Self::def(regs, *dst, |d, regs| { let (a, b) = (®s[*a as usize], ®s[*b as usize]); for w in 0..words { let va = if *ra == Rep::Null { 0 } else { a.valid[w] }; @@ -963,15 +932,14 @@ impl<'e, 'x> Exec<'e, 'x> { } self.eq_meta(d, a, b, *ne); }), - Ins::EqText { ne, dst, a, b } => { - let (x, y) = (self.view(a), self.view(b)); - Self::def(regs, *dst, |d, _| { - d.valid[..words].fill(u64::MAX); - d.fault[..words].fill(0); - let ne = *ne; - self.bools(act, &mut d.bits, |i| (x.get(start + i) == y.get(start + i)) != ne); - }) - } + Ins::EqText { .. } + | Ins::Text { .. } + | Ins::Matches { .. } + | Ins::Map { .. } + | Ins::Concat { .. } + | Ins::Str { .. } + | Ins::Decode { .. } + | Ins::Class { .. } => self.text(ins, regs, act), Ins::InCode { dst, a, set, null } => Self::def(regs, *dst, |d, regs| { let a = ®s[*a as usize]; let set = *set; @@ -1225,6 +1193,9 @@ impl<'e, 'x> Exec<'e, 'x> { d.valid[w] = 0; d.fault[w] = s.fault[w]; } + if *rep == Rep::Text { + d.texts(n); + } let mut m = [0u64; Reg::WORDS]; for (arm, ra, idx) in arms { let a = ®s[*arm as usize]; @@ -1252,7 +1223,8 @@ impl<'e, 'x> Exec<'e, 'x> { d.bits[w] = (d.bits[w] & !mw) | (a.bits[w] & mw); } } - Rep::Text | Rep::Null => {} + Rep::Text => self.pick_text(d, m, a), + Rep::Null => {} } } }), @@ -1305,50 +1277,6 @@ impl<'e, 'x> Exec<'e, 'x> { _ => {} } }), - Ins::Text { func, dst, a, b } => { - let x = self.view(a); - let y = b.as_ref().map_or(TV::Lit(b""), |b| self.view(b)); - Self::def(regs, *dst, |d, _| { - for w in 0..words { - d.valid[w] = u64::MAX; - d.fault[w] = !(x.valid_word(start + w * 64) & y.valid_word(start + w * 64)) & self.tail(w); - } - match (func, x) { - (Func::Len, TV::Col(Text::Str { offsets, .. }, _)) => { - for (m, p) in d.mant[..n].iter_mut().zip(offsets[start..=start + n].windows(2)) { - *m = (p[1] - p[0]) as i64; - } - } - (Func::Len, TV::Lit(l)) => d.mant[..n].fill(l.len() as i64), - (Func::Len, TV::Col(text, _)) => { - for (i, m) in d.mant[..n].iter_mut().enumerate() { - *m = text.get(start + i).map_or(0, |t| t.len() as i64); - } - } - (Func::Len, TV::Missing) => d.fault[..words].fill(u64::MAX), - (Func::StartsWith, TV::Col(Text::Str { offsets, data }, _)) if act.is_none() && matches!(y, TV::Lit(_)) => { - let p = match y { - TV::Lit(p) => p, - _ => b"", - }; - let offs = &offsets[start..=start + n]; - K::pack_idx(n, &mut d.bits[..words], |i| { - let (lo, hi) = (offs[i] as usize, offs[i + 1] as usize); - hi >= lo + p.len() && data.get(lo..lo + p.len()).is_some_and(|h| h == p) - }); - } - (Func::StartsWith, _) => self.bools(act, &mut d.bits, |i| match (x.get(start + i), y.get(start + i)) { - (Some(a), Some(b)) => a.starts_with(b), - _ => false, - }), - (Func::EndsWith, _) => self.bools(act, &mut d.bits, |i| match (x.get(start + i), y.get(start + i)) { - (Some(a), Some(b)) => a.ends_with(b), - _ => false, - }), - _ => {} - } - }) - } Ins::Out { slot, src, rep, scope } => self.out(*slot, ®s[*src as usize], *rep, *scope, out), Ins::Keep { slot, src } => { let r = ®s[*src as usize]; @@ -1438,7 +1366,7 @@ impl<'e, 'x> Exec<'e, 'x> { } } (Data::Codes(codes), _) => d.codes[..n].copy_from_slice(&codes[start..start + n]), - (Data::Text(_), _) => {} + (Data::Text(text), _) => self.load_text(d, text), } if let Some((bits, values)) = &feed.wide { for w in 0..words { @@ -1483,7 +1411,8 @@ impl<'e, 'x> Exec<'e, 'x> { d.bits[w] = (t.bits[w] & mw) | (e.bits[w] & !mw); } } - Rep::Text | Rep::Null => {} + Rep::Text => self.blend_text(d, m, t, e), + Rep::Null => {} } } @@ -1731,6 +1660,7 @@ impl<'e, 'x> Exec<'e, 'x> { }, SlotData::Bool(bits) => bits[w0..w0 + words].copy_from_slice(&r.bits[..words]), SlotData::Code(codes) => codes[start..start + n].copy_from_slice(&r.codes[..n]), + SlotData::Text { span, data } => self.out_text(r, span, data), } match rep { Rep::Null => s.valid[w0..w0 + words].fill(0), diff --git a/core/expression/src/typed/hir.rs b/core/expression/src/typed/hir.rs index 9801f6d3..03acc4ed 100644 --- a/core/expression/src/typed/hir.rs +++ b/core/expression/src/typed/hir.rs @@ -82,6 +82,11 @@ pub enum Func { Trunc(u8), Min, Max, + Upper, + Lower, + Trim, + Contains, + Matches, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -113,6 +118,9 @@ pub enum Op { Pick(NodeId, Vec), Call(Func, Vec), Classify(NodeId, DictId), + Str(NodeId), + Decode(NodeId), + Concat(Vec), } #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -281,13 +289,13 @@ impl Op { pub fn inputs(&self) -> Vec { match self { Op::Column(_) | Op::Field(..) | Op::Const(_) => Vec::new(), - Op::Parent(a) | Op::Neg(a) | Op::Not(a) | Op::InSet(a, _) | Op::InRange(a, _) | Op::Classify(a, _) => vec![*a], + Op::Parent(a) | Op::Neg(a) | Op::Not(a) | Op::InSet(a, _) | Op::InRange(a, _) | Op::Classify(a, _) | Op::Str(a) | Op::Decode(a) => vec![*a], Op::Arith(_, a, b) | Op::Cmp(_, a, b) | Op::And(a, b) | Op::Or(a, b) | Op::Coalesce(a, b) => vec![*a, *b], Op::If(c, t, e) => vec![*c, *t, *e], Op::Fold { filter, value, .. } => filter.iter().chain(value.iter()).copied().collect(), Op::FirstMatch { conds, .. } => conds.clone(), Op::Pick(sel, arms) => std::iter::once(*sel).chain(arms.iter().copied()).collect(), - Op::Call(_, args) => args.clone(), + Op::Call(_, args) | Op::Concat(args) => args.clone(), } } @@ -298,6 +306,9 @@ impl Op { Op::Neg(a) => Op::Neg(f(*a)), Op::Not(a) => Op::Not(f(*a)), Op::Classify(a, d) => Op::Classify(f(*a), *d), + Op::Str(a) => Op::Str(f(*a)), + Op::Decode(a) => Op::Decode(f(*a)), + Op::Concat(args) => Op::Concat(args.iter().map(|a| f(*a)).collect()), Op::Arith(op, a, b) => Op::Arith(*op, f(*a), f(*b)), Op::Cmp(op, a, b) => Op::Cmp(*op, f(*a), f(*b)), Op::And(a, b) => Op::And(f(*a), f(*b)), @@ -322,7 +333,11 @@ impl Fold { impl Func { pub fn text(self) -> bool { - matches!(self, Func::StartsWith | Func::EndsWith | Func::Len) + matches!(self, Func::StartsWith | Func::EndsWith | Func::Len | Func::Upper | Func::Lower | Func::Trim | Func::Contains | Func::Matches) + } + + pub fn mapping(self) -> bool { + matches!(self, Func::Upper | Func::Lower | Func::Trim) } } @@ -396,6 +411,9 @@ impl Hir { Op::Neg(a) => format!("neg %{a}"), Op::Not(a) => format!("not %{a}"), Op::Classify(a, d) => format!("classify %{a} dict {d}"), + Op::Str(a) => format!("string %{a}"), + Op::Decode(a) => format!("decode %{a}"), + Op::Concat(args) => format!("concat [{}]", ids(args)), Op::Arith(op, a, b) => format!("{op:?} %{a}, %{b}").to_lowercase(), Op::Cmp(op, a, b) => format!("{op:?} %{a}, %{b}").to_lowercase(), Op::And(a, b) => format!("and %{a}, %{b}"), diff --git a/core/expression/src/typed/ins.rs b/core/expression/src/typed/ins.rs index 864fa6ad..29b17595 100644 --- a/core/expression/src/typed/ins.rs +++ b/core/expression/src/typed/ins.rs @@ -1,7 +1,14 @@ +use crate::typed::batch::Matcher; use crate::typed::hir::{Arith, Cmp, Fold, Func, Lit, NodeId, Range, Scope, Unsupported}; use crate::typed::lookup::Lookup; use crate::typed::num::Dec; use std::fmt; +use std::sync::Arc; + +#[cfg(not(feature = "regex-lite"))] +pub(crate) use regex::Regex as Pattern; +#[cfg(feature = "regex-lite")] +pub(crate) use regex_lite::Regex as Pattern; pub(crate) type R = u16; @@ -26,6 +33,7 @@ pub(crate) enum Src { pub(crate) enum Arg { Src(Src), Lit(String), + Reg(R), } #[derive(Clone, Copy, Debug)] @@ -77,6 +85,12 @@ pub(crate) enum Ins { Skip { guard: Guard, len: u32 }, Fold { fold: Fold, buf: u16, list: u16, filter: Option, value: Option<(R, Rep)> }, Text { func: Func, dst: R, a: Arg, b: Option }, + Map { func: Func, dst: R, a: Arg }, + Str { dst: R, a: Arg, rep: Rep }, + Decode { dst: R, a: R, values: Arc<[Box]> }, + Concat { dst: R, parts: Vec }, + Class { dst: R, a: Arg, matcher: Box> }, + Matches { dst: R, a: Arg, pattern: Box }, Math { func: Func, dst: R, args: Vec<(R, Rep)>, rep: Rep }, Out { slot: u16, src: R, rep: Rep, scope: Scope }, Keep { slot: u16, src: R }, @@ -131,6 +145,14 @@ impl Rep { } } +impl Arg { + fn visit(&mut self, f: &mut impl FnMut(&mut R, bool)) { + if let Arg::Reg(r) = self { + f(r, false); + } + } +} + impl Tab { pub(crate) const MAX: usize = 255; @@ -174,7 +196,29 @@ impl fmt::Debug for Tab { impl Ins { pub(crate) fn regs(&mut self, f: &mut impl FnMut(&mut R, bool)) { match self { - Ins::Load { dst, .. } | Ins::Gather { dst, .. } | Ins::Fill { dst, .. } | Ins::EqText { dst, .. } | Ins::Text { dst, .. } => f(dst, true), + Ins::Load { dst, .. } | Ins::Gather { dst, .. } | Ins::Fill { dst, .. } => f(dst, true), + Ins::EqText { dst, a, b, .. } => { + a.visit(f); + b.visit(f); + f(dst, true); + } + Ins::Text { dst, a, b, .. } => { + a.visit(f); + if let Some(b) = b { + b.visit(f); + } + f(dst, true); + } + Ins::Map { dst, a, .. } | Ins::Str { dst, a, .. } | Ins::Class { dst, a, .. } | Ins::Matches { dst, a, .. } => { + a.visit(f); + f(dst, true); + } + Ins::Concat { dst, parts } => { + for p in parts.iter_mut() { + p.visit(f); + } + f(dst, true); + } Ins::Spill { src, .. } | Ins::Out { src, .. } | Ins::Keep { src, .. } => f(src, false), Ins::Fix { dst, a, b, .. } | Ins::Num { dst, a, b, .. } @@ -199,6 +243,7 @@ impl Ins { | Ins::InGen { dst, a, .. } | Ins::InRangeFix { dst, a, .. } | Ins::InRangeGen { dst, a, .. } + | Ins::Decode { dst, a, .. } | Ins::Not { dst, a } => { f(a, false); f(dst, true); diff --git a/core/expression/src/typed/lower.rs b/core/expression/src/typed/lower.rs index 732a6d8d..ff5a6990 100644 --- a/core/expression/src/typed/lower.rs +++ b/core/expression/src/typed/lower.rs @@ -6,6 +6,7 @@ use crate::typed::hir::{ Arith, Cmp, Collect, ColumnDef, Dict, DictId, DictKind, Fold, Func, Hir, Kind, ListDef, ListId, Lit, Node, NodeId, Op, Output, Range, Schema, Scope, Ty, Unsupported, }; +use crate::typed::ins::Pattern; use crate::typed::num::Dec; use bumpalo::Bump; use std::collections::HashMap; @@ -453,7 +454,7 @@ impl Lowering { let code = self.code(dict, &text); self.konst(Lit::Code(dict, code)) } - _ => return Err(Unsupported::new(format!("text output {name}"))), + _ => id, }, Kind::Code(d) if self.schema.dicts[d as usize].kind == DictKind::Classes => return Err(Unsupported::new(format!("class output {name}"))), _ => id, @@ -502,7 +503,7 @@ impl Lowering { let code = self.code(dict, &text); self.konst(Lit::Code(dict, code)) } - _ => return Err(Unsupported::new(format!("text list output {name}"))), + _ => item, }, Kind::Code(d) if self.schema.dicts[d as usize].kind == DictKind::Classes => return Err(Unsupported::new(format!("class list output {name}"))), _ => item, @@ -665,6 +666,7 @@ impl Lowering { Ok(self.add(Op::If(ids[0], ids[1], ids[2]), ty, scope)) } Ast::FunctionCall { kind, arguments } => self.call(kind, arguments, ctx, r), + Ast::TemplateString(parts) => self.template(parts, ctx, r), other => Err(Unsupported::new(format!("expression node {}", <&'static str>::from(other)))), } } @@ -867,7 +869,10 @@ impl Lowering { }; let a = self.expr(left, ctx, r)?; let b = self.expr(right, ctx, r)?; - self.arith(op, a, b) + match op == Arith::Add && (self.texty(a) || self.texty(b)) { + true => self.concat(vec![a, b]), + false => self.arith(op, a, b), + } } Operator::Comparison(ComparisonOperator::In | ComparisonOperator::NotIn) => { let a = self.expr(left, ctx, r)?; @@ -935,9 +940,7 @@ impl Lowering { } fn classify(&mut self, id: NodeId) -> Lowered { - if !matches!(self.nodes[id as usize].op, Op::Column(_) | Op::Field(..)) { - return Err(Unsupported::new("computed text")); - } + self.require(id, |k| k == Kind::Text, "classify")?; let dict = match self.classes.iter().find(|(n, _)| *n == id) { Some((_, d)) => *d, None => { @@ -984,22 +987,49 @@ impl Lowering { }; (self.coerce(a, d)?, y) } - (false, false) => return Err(Unsupported::new("text compared to text")), + (false, false) => (a, b), }, - (Kind::Text, Kind::Null) if eq => (self.classify(a)?, b), - (Kind::Null, Kind::Text) if eq => (a, self.classify(b)?), - (Kind::Code(d), Kind::Text) if eq => (a, self.coerce(b, d)?), - (Kind::Text, Kind::Code(d)) if eq => (self.coerce(a, d)?, b), + (Kind::Text, Kind::Null) if eq && self.direct(a) => (self.classify(a)?, b), + (Kind::Null, Kind::Text) if eq && self.direct(b) => (a, self.classify(b)?), + (Kind::Text, Kind::Null) | (Kind::Null, Kind::Text) if eq => (a, b), + (Kind::Code(d), Kind::Text) if eq && self.lit(b).is_some() => (a, self.coerce(b, d)?), + (Kind::Text, Kind::Code(d)) if eq && self.lit(a).is_some() => (self.coerce(a, d)?, b), + (Kind::Code(_), Kind::Text) if eq => (self.decode(a)?, b), + (Kind::Text, Kind::Code(_)) if eq => (a, self.decode(b)?), (Kind::Code(x), Kind::Code(y)) if eq && x == y => (a, b), (Kind::Num(_), Kind::Num(_)) | (Kind::Bool, Kind::Bool) if eq => (a, b), (Kind::Null, _) | (_, Kind::Null) if eq => (a, b), (Kind::Num(_), Kind::Num(_)) => (a, b), + (x, y) if eq && Self::family(x).zip(Self::family(y)).is_some_and(|(p, q)| p != q) => return self.mismatch(op, a, b), _ => return Err(Unsupported::new(format!("compare {op:?} between {ka} and {kb}"))), }; let (scope, ids) = self.scoped(&[a, b])?; Ok(self.add(Op::Cmp(op, ids[0], ids[1]), Ty::boolean(), scope)) } + fn family(kind: Kind) -> Option { + match kind { + Kind::Num(_) => Some(0), + Kind::Bool => Some(1), + Kind::Text | Kind::Code(_) => Some(2), + Kind::Null => None, + } + } + + fn mismatch(&mut self, op: Cmp, a: NodeId, b: NodeId) -> Lowered { + if !(self.ty(a).nullable && self.ty(b).nullable) { + return Ok(self.konst(Lit::Bool(op == Cmp::Ne))); + } + let null = self.konst(Lit::Null); + let x = self.compare(Cmp::Eq, a, null)?; + let y = self.compare(Cmp::Eq, b, null)?; + let both = self.logic(true, x, y)?; + match op { + Cmp::Eq => Ok(both), + _ => self.not(both), + } + } + fn coerce(&mut self, id: NodeId, dict: DictId) -> Lowered { match self.lit(id) { Some(Lit::Text(text)) => { @@ -1072,16 +1102,26 @@ impl Lowering { } fn unify(&mut self, ids: Vec) -> Result<(Vec, Ty), Unsupported> { + let computed = ids.iter().any(|id| self.kind(*id) == Kind::Text && self.lit(*id).is_none()); + let ids = match computed { + true => ids + .into_iter() + .map(|id| match self.kind(id) { + Kind::Code(_) => self.decode(id), + _ => Ok(id), + }) + .collect::, _>>()?, + false => ids, + }; let mut dict: Option = None; for id in &ids { match self.kind(*id) { Kind::Code(d) if dict.is_some_and(|x| x != d) => return Err(Unsupported::new("branches code different dictionaries")), Kind::Code(d) => dict = Some(d), - Kind::Text if self.lit(*id).is_none() => return Err(Unsupported::new("computed text branch")), _ => {} } } - let texts = ids.iter().any(|id| self.kind(*id) == Kind::Text); + let texts = !computed && ids.iter().any(|id| self.kind(*id) == Kind::Text); if texts { let d = match dict { Some(d) => d, @@ -1139,31 +1179,52 @@ impl Lowering { }; self.fold(Fold::Count, seq, Some(filter), None) } - (FunctionKind::Internal(InternalFunction::Contains), [list, x]) => { - let seq = self.seq(list, ctx, r)?; - let x = self.expr(x, ctx, r)?; - self.member(x, seq) - } + (FunctionKind::Internal(InternalFunction::Contains), [list, x]) => match self.seq(list, ctx, r) { + Ok(seq) => { + let x = self.expr(x, ctx, r)?; + self.member(x, seq) + } + Err(e) => { + let a = self.expr(list, ctx, r).map_err(|_| e)?; + let b = self.expr(x, ctx, r)?; + self.test(Func::Contains, a, b) + } + }, (FunctionKind::Internal(InternalFunction::Len), [arg]) => match self.seq(arg, ctx, r).and_then(Self::pure) { Ok(seq) => self.fold(Fold::Count, seq, seq.keep, None), Err(_) => { let a = self.expr(arg, ctx, r)?; - self.require(a, |k| k == Kind::Text, "len")?; + let a = self.textual(a)?; + if let Some(Lit::Text(t)) = self.lit(a) { + let n = Dec::int(t.len() as i64); + return Ok(self.konst(Lit::Num(n))); + } let scope = self.nodes[a as usize].scope; Ok(self.add(Op::Call(Func::Len, vec![a]), Ty::num(Some(0)), scope)) } }, - (FunctionKind::Internal(f @ (InternalFunction::StartsWith | InternalFunction::EndsWith)), [a, b]) => { + (FunctionKind::Internal(f @ (InternalFunction::StartsWith | InternalFunction::EndsWith | InternalFunction::Matches)), [a, b]) => { let a = self.expr(a, ctx, r)?; let b = self.expr(b, ctx, r)?; - self.require(a, |k| k == Kind::Text, "string function")?; - self.require(b, |k| k == Kind::Text, "string function")?; let func = match f { InternalFunction::StartsWith => Func::StartsWith, - _ => Func::EndsWith, + InternalFunction::EndsWith => Func::EndsWith, + _ => Func::Matches, }; - let (scope, ids) = self.scoped(&[a, b])?; - Ok(self.add(Op::Call(func, ids), Ty::boolean(), scope)) + self.test(func, a, b) + } + (FunctionKind::Internal(InternalFunction::String), [arg]) => { + let a = self.expr(arg, ctx, r)?; + self.stringify(a) + } + (FunctionKind::Internal(f @ (InternalFunction::Upper | InternalFunction::Lower | InternalFunction::Trim)), [arg]) => { + let a = self.expr(arg, ctx, r)?; + let func = match f { + InternalFunction::Upper => Func::Upper, + InternalFunction::Lower => Func::Lower, + _ => Func::Trim, + }; + self.mapped(func, a) } (FunctionKind::Internal(InternalFunction::Bool), [arg]) => { let a = self.expr(arg, ctx, r)?; @@ -1263,6 +1324,144 @@ impl Lowering { } } + fn direct(&self, id: NodeId) -> bool { + matches!(self.nodes[id as usize].op, Op::Column(_) | Op::Field(..)) + } + + fn texty(&self, id: NodeId) -> bool { + match self.kind(id) { + Kind::Text => true, + Kind::Code(d) => self.schema.dicts[d as usize].kind == DictKind::Literals, + _ => false, + } + } + + fn decode(&mut self, id: NodeId) -> Lowered { + let Kind::Code(d) = self.kind(id) else { + return Err(Unsupported::new(format!("decode of {}", self.ty(id)))); + }; + let dict = &self.schema.dicts[d as usize]; + if dict.kind != DictKind::Literals { + return Err(Unsupported::new("dictionary mixing")); + } + if let Some(Lit::Code(_, c)) = self.lit(id) { + let text = dict.text(*c).ok_or_else(|| Unsupported::new("decode of an unknown code"))?.to_string(); + return Ok(self.konst(Lit::Text(text))); + } + let node = &self.nodes[id as usize]; + let (nullable, scope) = (node.ty.nullable, node.scope); + Ok(self.add(Op::Decode(id), Ty::new(Kind::Text, nullable), scope)) + } + + fn textual(&mut self, id: NodeId) -> Lowered { + match self.kind(id) { + Kind::Text => Ok(id), + Kind::Code(_) => self.decode(id), + _ => Err(Unsupported::new(format!("string function on {}", self.ty(id)))), + } + } + + fn stringify(&mut self, a: NodeId) -> Lowered { + let text = match self.lit(a) { + Some(Lit::Text(_)) => return Ok(a), + Some(Lit::Null) => Some("null".to_string()), + Some(Lit::Bool(b)) => Some(b.to_string()), + Some(Lit::Num(d)) => Some(d.decimal().to_string()), + Some(Lit::Code(..)) => return self.decode(a), + None => None, + }; + if let Some(text) = text { + return Ok(self.konst(Lit::Text(text))); + } + let a = match self.ty(a) { + Ty { kind: Kind::Text, nullable: false } => return Ok(a), + Ty { kind: Kind::Code(_), .. } => self.decode(a)?, + Ty { kind: Kind::Text | Kind::Num(_) | Kind::Bool | Kind::Null, .. } => a, + }; + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::Str(a), Ty::new(Kind::Text, false), scope)) + } + + fn concat(&mut self, ids: Vec) -> Lowered { + let mut parts: Vec = Vec::with_capacity(ids.len()); + for id in ids { + let id = self.textual(id)?; + let nested = match &self.nodes[id as usize].op { + Op::Concat(inner) => inner.clone(), + _ => vec![id], + }; + for part in nested { + let joined = match (parts.last().and_then(|p| self.lit(*p)), self.lit(part)) { + (Some(Lit::Text(x)), Some(Lit::Text(y))) => Some(format!("{x}{y}")), + _ => None, + }; + match joined { + Some(text) => { + parts.pop(); + parts.push(self.konst(Lit::Text(text))); + } + None => parts.push(part), + } + } + } + if let [only] = parts.as_slice() { + if self.lit(*only).is_some() || !self.ty(*only).nullable { + return Ok(*only); + } + } + let (scope, ids) = self.scoped(&parts)?; + Ok(self.add(Op::Concat(ids), Ty::new(Kind::Text, false), scope)) + } + + fn template(&mut self, parts: &[&Ast], ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + if parts.is_empty() { + return Err(Unsupported::new("empty template")); + } + let mut ids = Vec::with_capacity(parts.len()); + for part in parts { + let id = self.expr(part, ctx, r)?; + ids.push(self.stringify(id)?); + } + self.concat(ids) + } + + fn mapped(&mut self, func: Func, a: NodeId) -> Lowered { + let a = self.textual(a)?; + if let Some(Lit::Text(t)) = self.lit(a) { + let text = match func { + Func::Upper => t.to_uppercase(), + Func::Lower => t.to_lowercase(), + _ => t.trim().to_string(), + }; + return Ok(self.konst(Lit::Text(text))); + } + let scope = self.nodes[a as usize].scope; + Ok(self.add(Op::Call(func, vec![a]), Ty::new(Kind::Text, false), scope)) + } + + fn test(&mut self, func: Func, a: NodeId, b: NodeId) -> Lowered { + let (a, b) = (self.textual(a)?, self.textual(b)?); + if func == Func::Matches { + let Some(Lit::Text(pattern)) = self.lit(b) else { + return Err(Unsupported::new("matches: pattern must be a string literal")); + }; + Pattern::new(pattern).map_err(|_| Unsupported::new("matches: invalid pattern"))?; + } + if let (Some(Lit::Text(x)), Some(Lit::Text(y))) = (self.lit(a), self.lit(b)) { + let hit = match func { + Func::StartsWith => Some(x.starts_with(y.as_str())), + Func::EndsWith => Some(x.ends_with(y.as_str())), + Func::Contains => Some(x.contains(y.as_str())), + _ => None, + }; + if let Some(hit) = hit { + return Ok(self.konst(Lit::Bool(hit))); + } + } + let (scope, ids) = self.scoped(&[a, b])?; + Ok(self.add(Op::Call(func, ids), Ty::boolean(), scope)) + } + fn math(&mut self, func: Func, args: Vec, ty: Ty) -> Lowered { let (scope, ids) = self.scoped(&args)?; Ok(self.add(Op::Call(func, ids), ty, scope)) diff --git a/core/expression/src/typed/mod.rs b/core/expression/src/typed/mod.rs index b19f5fdb..46645ec0 100644 --- a/core/expression/src/typed/mod.rs +++ b/core/expression/src/typed/mod.rs @@ -9,6 +9,7 @@ mod lookup; mod num; mod output; mod program; +mod text; #[cfg(test)] mod tests; diff --git a/core/expression/src/typed/output.rs b/core/expression/src/typed/output.rs index a3fbd67a..f0167770 100644 --- a/core/expression/src/typed/output.rs +++ b/core/expression/src/typed/output.rs @@ -9,6 +9,7 @@ pub enum Data { Num { mant: Vec, scale: Vec }, Bool(Vec), Code(Vec), + Text { span: Vec<(u32, u32)>, data: Vec }, } #[derive(Clone, Debug)] @@ -84,6 +85,47 @@ impl Slot { } } + pub fn text(&self, i: usize) -> Option<&str> { + match &self.data { + Data::Text { span, data } if self.is_valid(i) => { + let (lo, hi) = *span.get(i)?; + std::str::from_utf8(data.get(lo as usize..hi as usize)?).ok() + } + _ => None, + } + } + + pub fn take_text(&mut self) -> Option<(Vec, String, Vec)> { + let Data::Text { span, data } = &mut self.data else { + return None; + }; + let (span, data) = (std::mem::take(span), std::mem::take(data)); + let len = self.len.min(span.len()); + let mut offsets = Vec::with_capacity(len + 1); + offsets.push(0i32); + let packed = span[..len].iter().try_fold(0u32, |end, (lo, hi)| (end == *lo).then_some(*hi)); + let bytes = match packed { + Some(end) => { + let mut data = data; + data.truncate(end as usize); + offsets.extend(span[..len].iter().map(|(_, hi)| i32::try_from(*hi).unwrap_or(i32::MAX))); + data + } + None => { + let mut packed = Vec::with_capacity(data.len()); + for (at, (lo, hi)) in span[..len].iter().enumerate() { + if K::get(&self.valid, at) { + packed.extend_from_slice(data.get(*lo as usize..*hi as usize).unwrap_or_default()); + } + offsets.push(i32::try_from(packed.len()).unwrap_or(i32::MAX)); + } + packed + } + }; + let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()); + Some((offsets, text, std::mem::take(&mut self.valid))) + } + pub fn take_num(&mut self) -> Option<(Vec, Vec, Vec)> { match &mut self.data { Data::Num { mant, scale } => Some((std::mem::take(mant), std::mem::take(scale), std::mem::take(&mut self.valid))), @@ -131,6 +173,11 @@ impl Slot { codes.clear(); codes.resize(len, 0); } + Data::Text { span, data } => { + span.clear(); + span.resize(len, (0, 0)); + data.clear(); + } } } } @@ -191,7 +238,7 @@ impl Outputs { Kind::Num(_) | Kind::Null => Data::Num { mant: Vec::new(), scale: Vec::new() }, Kind::Bool => Data::Bool(Vec::new()), Kind::Code(_) => Data::Code(Vec::new()), - Kind::Text => return Err(Unsupported::new(format!("text output {}", o.name))), + Kind::Text => Data::Text { span: Vec::new(), data: Vec::new() }, }; slots.push(Slot { name: o.name.clone(), @@ -305,6 +352,7 @@ impl Slot { *bits = packed; } Data::Code(codes) => *codes = kept.iter().map(|&e| codes[e]).collect(), + Data::Text { span, .. } => *span = kept.iter().map(|&e| span[e]).collect(), } let wide = std::mem::take(&mut self.wide); self.wide = wide.into_iter().filter_map(|(e, d)| kept.binary_search(&e).ok().map(|to| (to, d))).collect(); diff --git a/core/expression/src/typed/program.rs b/core/expression/src/typed/program.rs index d4e349f2..f7acd465 100644 --- a/core/expression/src/typed/program.rs +++ b/core/expression/src/typed/program.rs @@ -84,7 +84,7 @@ impl Program { let origin = match hir.nodes.get(a as usize).map(|n| &n.op) { Some(Op::Column(c)) => Origin::Col(*c), Some(Op::Field(l, f)) => Origin::Field(*l, *f), - _ => return Err(Unsupported::new("typed: classify of a computed value")), + _ => continue, }; let k = match classes.iter().position(|c| *c == (origin, d)) { Some(k) => k, diff --git a/core/expression/src/typed/tests/exact.rs b/core/expression/src/typed/tests/exact.rs index 4cfa1a3e..88650a0d 100644 --- a/core/expression/src/typed/tests/exact.rs +++ b/core/expression/src/typed/tests/exact.rs @@ -19,6 +19,7 @@ struct Report { faults: usize, interp: usize, mismatches: usize, + spurious: usize, samples: Vec, } @@ -38,6 +39,7 @@ impl Lab { slot.code(i).map_or(Val::Null, |c| hir.dict(d).text(c).map_or(Val::Other(format!("code {c}")), |t| Val::Str(t.to_string()))) } (Data::Code(_), _) => Val::Other("code without dict".to_string()), + (Data::Text { .. }, _) => slot.text(i).map_or(Val::Null, |t| Val::Str(t.to_string())), } } @@ -83,6 +85,7 @@ impl Lab { let row = start + i; let want = &self.expected[row]; report.faults += t.is_none() as usize; + report.spurious += (t.is_none() && want.is_ok()) as usize; report.interp += r.is_none() as usize; let mut check = |got: &Option>, who: &str| { let ok = match (got, want) { @@ -118,6 +121,7 @@ impl Lab { let r = self.verify(program, size); assert_eq!(r.mismatches, 0, "{} @{size}: {:#?}", self.workload.name, r.samples); assert_eq!(r.faults, r.interp, "{} @{size}: typed faults {} vs interp {}: {:#?}", self.workload.name, r.faults, r.interp, r.samples); + assert_eq!(r.spurious, 0, "{} @{size}: typed faults on rows the VM evaluates", self.workload.name); if clean { assert_eq!(r.faults, 0, "{} @{size}", self.workload.name); } diff --git a/core/expression/src/typed/tests/interp.rs b/core/expression/src/typed/tests/interp.rs index d732d6a5..383f4e32 100644 --- a/core/expression/src/typed/tests/interp.rs +++ b/core/expression/src/typed/tests/interp.rs @@ -1,18 +1,20 @@ use crate::typed::batch::{Data, Feed, Feeds}; +use crate::typed::ins::Pattern; use crate::typed::kernel::K; use crate::typed::num::Exact; use crate::typed::tests::oracle::Val; use crate::typed::{Cmp, Fold, Func, Hir, Kind, Lit, NodeId, Op, Range, Scope}; use rust_decimal::Decimal; +use std::borrow::Cow; use std::cmp::Ordering; -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] enum V<'a> { Null, Num(Decimal), Bool(bool), Code(i32), - Text(&'a [u8]), + Text(Cow<'a, [u8]>), } #[derive(Clone, Copy, Debug, PartialEq)] @@ -157,17 +159,17 @@ impl<'a, 'x> Interp<'a, 'x> { (V::Bool(b), _) => Val::Bool(b), (V::Code(c), Kind::Code(d)) => self.hir.dict(d).text(c).map_or(Val::Other(format!("code {c}")), |t| Val::Str(t.to_string())), (V::Code(c), _) => Val::Other(format!("code {c}")), - (V::Text(t), _) => Val::Str(String::from_utf8_lossy(t).to_string()), + (V::Text(t), _) => Val::Str(String::from_utf8_lossy(&t).to_string()), } } fn eval(&mut self, id: NodeId) -> R<'a> { let at = id as usize; - if let Some(r) = self.cache[at] { - return r; + if let Some(r) = &self.cache[at] { + return r.clone(); } let r = self.compute(id); - self.cache[at] = Some(r); + self.cache[at] = Some(r.clone()); r } @@ -187,7 +189,7 @@ impl<'a, 'x> Interp<'a, 'x> { Data::Num { .. } => feed.num(i).map_or(V::Null, |d| V::Num(d.decimal())), Data::Bool { bits, offset } => V::Bool(K::get(bits, offset + i)), Data::Codes(codes) => V::Code(codes[i]), - Data::Text(text) => text.get(i).map_or(V::Null, V::Text), + Data::Text(text) => text.get(i).map_or(V::Null, |t| V::Text(Cow::Borrowed(t))), }) } @@ -197,11 +199,11 @@ impl<'a, 'x> Interp<'a, 'x> { Lit::Num(d) => V::Num(d.decimal()), Lit::Bool(b) => V::Bool(*b), Lit::Code(_, c) => V::Code(*c), - Lit::Text(t) => V::Text(t.as_bytes()), + Lit::Text(t) => V::Text(Cow::Borrowed(t.as_bytes())), } } - fn equal(a: V, b: V) -> bool { + fn equal(a: &V, b: &V) -> bool { a == b } @@ -223,7 +225,7 @@ impl<'a, 'x> Interp<'a, 'x> { Op::Classify(a, d) => match self.eval(*a)? { V::Text(t) => { let dict = hir.dict(*d); - Ok(V::Code(dict.values.iter().position(|v| v.as_bytes() == t).map_or(dict.values.len() as i32, |i| i as i32))) + Ok(V::Code(dict.values.iter().position(|v| v.as_bytes() == &*t).map_or(dict.values.len() as i32, |i| i as i32))) } _ => Ok(V::Null), }, @@ -249,8 +251,8 @@ impl<'a, 'x> Interp<'a, 'x> { Op::Cmp(op, a, b) => { let (x, y) = (self.eval(*a)?, self.eval(*b)?); match op { - Cmp::Eq => Ok(V::Bool(Self::equal(x, y))), - Cmp::Ne => Ok(V::Bool(!Self::equal(x, y))), + Cmp::Eq => Ok(V::Bool(Self::equal(&x, &y))), + Cmp::Ne => Ok(V::Bool(!Self::equal(&x, &y))), _ => { let (V::Num(x), V::Num(y)) = (x, y) else { return Err(Fault); @@ -286,7 +288,7 @@ impl<'a, 'x> Interp<'a, 'x> { }, Op::InSet(a, set) => { let x = self.eval(*a)?; - Ok(V::Bool(set.iter().any(|lit| Self::equal(x, Self::lit(lit))))) + Ok(V::Bool(set.iter().any(|lit| Self::equal(&x, &Self::lit(lit))))) } Op::InRange(a, r) => match self.eval(*a)? { V::Num(x) => Ok(V::Bool(Self::within(x, r))), @@ -376,9 +378,15 @@ impl<'a, 'x> Interp<'a, 'x> { for a in args { vals.push(self.eval(*a)?); } + let text = |t: &[u8]| std::str::from_utf8(t).map(str::to_string).map_err(|_| Fault); match (func, vals.as_slice()) { - (Func::StartsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.starts_with(b))), - (Func::EndsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.ends_with(b))), + (Func::StartsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.starts_with(&b[..]))), + (Func::EndsWith, [V::Text(a), V::Text(b)]) => Ok(V::Bool(a.ends_with(&b[..]))), + (Func::Contains, [V::Text(a), V::Text(b)]) => Ok(V::Bool(text(a)?.contains(text(b)?.as_str()))), + (Func::Matches, [V::Text(a), V::Text(b)]) => Ok(V::Bool(Pattern::new(&text(b)?).map_err(|_| Fault)?.is_match(&text(a)?))), + (Func::Upper, [V::Text(a)]) => Ok(V::Text(Cow::Owned(text(a)?.to_uppercase().into_bytes()))), + (Func::Lower, [V::Text(a)]) => Ok(V::Text(Cow::Owned(text(a)?.to_lowercase().into_bytes()))), + (Func::Trim, [V::Text(a)]) => Ok(V::Text(Cow::Owned(text(a)?.trim().as_bytes().to_vec()))), (Func::Len, [V::Text(a)]) => Ok(V::Num(Decimal::from(a.len()))), (Func::Min, items) => items.iter().map(|v| if let V::Num(d) = v { Ok(*d) } else { Err(Fault) }).collect::, _>>()?.into_iter().min().map(V::Num).ok_or(Fault), (Func::Max, items) => items.iter().map(|v| if let V::Num(d) = v { Ok(*d) } else { Err(Fault) }).collect::, _>>()?.into_iter().max().map(V::Num).ok_or(Fault), @@ -386,6 +394,28 @@ impl<'a, 'x> Interp<'a, 'x> { _ => Err(Fault), } } + Op::Str(a) => Ok(V::Text(Cow::Owned(match self.eval(*a)? { + V::Null => b"null".to_vec(), + V::Num(d) => d.to_string().into_bytes(), + V::Bool(b) => b.to_string().into_bytes(), + V::Text(t) => t.into_owned(), + V::Code(_) => return Err(Fault), + }))), + Op::Decode(a) => match (self.eval(*a)?, hir.nodes[*a as usize].ty.kind) { + (V::Null, _) => Ok(V::Null), + (V::Code(c), Kind::Code(d)) => hir.dict(d).text(c).map(|t| V::Text(Cow::Owned(t.as_bytes().to_vec()))).ok_or(Fault), + _ => Err(Fault), + }, + Op::Concat(parts) => { + let mut out = Vec::new(); + for p in parts { + match self.eval(*p)? { + V::Text(t) => out.extend_from_slice(&t), + _ => return Err(Fault), + } + } + Ok(V::Text(Cow::Owned(out))) + } } } } diff --git a/core/expression/src/typed/tests/lower.rs b/core/expression/src/typed/tests/lower.rs index d2e987d7..08958f40 100644 --- a/core/expression/src/typed/tests/lower.rs +++ b/core/expression/src/typed/tests/lower.rs @@ -1,6 +1,6 @@ use crate::lane::Fusion; use crate::typed::tests::data::{ColSpec, Enc, ListSpec, Mock, Spec}; -use crate::typed::{Class, DictKind, Hir, Hit, Kind, Lowering, Op, Program, Resolve, Resolved, TableRule, TableSpec}; +use crate::typed::{Class, DictKind, Hir, Hit, Kind, Lit, Lowering, Op, Program, Resolve, Resolved, TableRule, TableSpec}; use std::sync::Arc; struct Anchor; @@ -303,14 +303,15 @@ fn strict_rules_lower_to_firstmatch() { #[test] fn unsupported_shapes() { let cases = [ - ("computed text", "c.t == c.u"), - ("text output", "c.t"), - ("text branch", "c.b ? c.t : 'x'"), - ("dictionary mixing", "(c.n > 1 ? 'a' : 'b') == c.t"), ("text ordering", "c.t > 'a'"), + ("text plus number", "c.t + 1"), + ("text plus null", "c.t + null"), + ("pattern from a column", "matches(c.t, c.u)"), + ("invalid pattern", "matches(c.t, '(')"), + ("string of a list", "string(c.xs)"), + ("empty template", "``"), ("unsupported path", "c.weird + 1"), ("null arithmetic", "c.absent + 1"), - ("function", "string(c.n)"), ("variable exponent", "c.n ^ c.n"), ("fractional exponent", "c.n ^ 0.5"), ("round to variable places", "round(c.n, c.n)"), @@ -332,6 +333,46 @@ fn unsupported_shapes() { assert!(Probe::unit(&mut lowering, &mut probe, "c.q", "c.o").is_err(), "read of a partially written value"); } +#[test] +fn text_shapes() { + let supported = [ + "c.t == c.u", + "c.t", + "c.b ? c.t : 'x'", + "(c.n > 1 ? 'a' : 'b') == c.t", + "string(c.n)", + "`${c.t}:${c.n}`", + "c.t + '-' + upper(c.u)", + "contains(lower(c.t), 'x')", + "trim(c.t) in ['a', 'b']", + "matches(c.t, '^a+$')", + "c.t ?? 'none'", + "map(c.items, #.n)", + "count(c.items, #.n == c.t)", + "c.t in c.ts", + "map(c.ts, upper(#))", + "len(c.t + c.u)", + ]; + for source in supported { + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + assert!(Probe::unit(&mut lowering, &mut probe, "c.o", source).is_ok(), "{source}"); + let hir = lowering.finish(); + Program::new(hir.clone()).unwrap_or_else(|e| panic!("{source}: {e}\n{hir}")); + } + let mut lowering = Lowering::new(None); + let mut probe = Probe::new(); + Probe::unit(&mut lowering, &mut probe, "c.a", "'a' + 'b' + string(1.50) + `x${true}`").expect("constant"); + Probe::unit(&mut lowering, &mut probe, "c.b", "upper('ß') + trim(' q ')").expect("constant map"); + let hir = lowering.finish(); + let dict = &hir.schema.dicts[0]; + let texts: Vec<&str> = hir.outputs.iter().map(|o| match hir.node(o.node).op { + Op::Const(Lit::Code(_, c)) => dict.text(c).unwrap_or("?"), + _ => "?", + }).collect(); + assert_eq!(texts, ["ab1.50xtrue", "SSq"], "{hir}"); +} + #[test] fn list_shapes() { let supported = [ @@ -357,7 +398,6 @@ fn list_shapes() { ("filter over a computed map", "filter(map(c.xs, # * 2), # > 1)"), ("quantifier over a computed map", "some(map(c.xs, # * 2), # > 1)"), ("membership in a computed map", "1 in map(c.xs, # * 2)"), - ("text list output", "map(c.items, #.n)"), ("objects as values", "filter(c.items, #.q > 1)"), ("sum of objects", "sum(c.items)"), ("list as a scalar", "c.xs + 1"), diff --git a/core/expression/src/typed/tests/scale.rs b/core/expression/src/typed/tests/scale.rs index 692dc5f1..3d1c7a77 100644 --- a/core/expression/src/typed/tests/scale.rs +++ b/core/expression/src/typed/tests/scale.rs @@ -319,6 +319,7 @@ fn programs_share_across_threads() { Data::Num { .. } => s.decimal(r).map_or(Val::Null, Val::Num), Data::Bool(_) => s.boolean(r).map_or(Val::Null, Val::Bool), Data::Code(_) => s.code(r).zip(s.dict()).map_or(Val::Null, |(c, d)| Val::Str(hir.dict(d).text(c).unwrap_or("?").to_string())), + Data::Text { .. } => s.text(r).map_or(Val::Null, |t| Val::Str(t.to_string())), }) .collect(); assert_eq!(format!("{got:?}"), expected[c * size + r], "size {size} row {}", c * size + r); diff --git a/core/expression/src/typed/tests/workload.rs b/core/expression/src/typed/tests/workload.rs index 2d22ec22..6ccc97c2 100644 --- a/core/expression/src/typed/tests/workload.rs +++ b/core/expression/src/typed/tests/workload.rs @@ -77,9 +77,74 @@ impl Block { } impl Workload { - pub(crate) const NAMES: [&'static str; 10] = ["W1", "W2", "W3", "W4", "W5", "W6", "W7", "W8", "W9", "W10"]; + pub(crate) const NAMES: [&'static str; 13] = ["W1", "W2", "W3", "W4", "W5", "W6", "W7", "W8", "W9", "W10", "W11", "W12", "W13"]; - pub(crate) const FAULTY: [&'static str; 4] = ["W6", "W8", "W9", "W10"]; + pub(crate) const FAULTY: [&'static str; 7] = ["W6", "W8", "W9", "W10", "W11", "W12", "W13"]; + + const W11_KEYS: [(&'static str, &'static str); 41] = [ + ("s_amt", "string(u.amt)"), + ("s_qty", "string(u.qty)"), + ("s_flag", "string(u.flag)"), + ("s_tier", "string(u.tier)"), + ("s_big", "string(u.big * 1000000000000)"), + ("s_div", "string(u.amt / 3)"), + ("tpl", "`${u.name}-${u.qty}:${u.amt} ${u.flag}`"), + ("cat", "u.name + '/' + u.city"), + ("up", "upper(u.name)"), + ("lo", "lower(u.city)"), + ("tr", "trim(u.name)"), + ("has", "contains(lower(u.name), 'an')"), + ("sw", "startsWith(upper(u.city), 'B') or endsWith($.tr, 'e')"), + ("ln", "len(trim(u.name)) + len($.cat)"), + ("tierz", "u.tier ?? 'none'"), + ("pick", "u.qty > 4 ? u.name : 'nobody'"), + ("same", "u.name == u.city"), + ("eqlit", "upper(u.name) == 'ANNA'"), + ("gold", "$.tierz in ['gold', 'none']"), + ("pass", "u.city"), + ("rx", "matches(u.name, '^[A-Z][a-z]+$')"), + ("lbl", "u.qty > 3 ? 'big' : 'small'"), + ("lbl2", "$.lbl + '!'"), + ("mix", "u.qty > 5 ? $.lbl : u.tier"), + ("lenz", "len(u.tier ?? '')"), + ("cmpcode", "$.lbl == u.tier"), + ("nul", "$.mix == null"), + ("names", "map(items, #.name)"), + ("upn", "map(items, upper(#.name) + ':' + string(#.qty))"), + ("cnt", "count(items, #.name == u.tier)"), + ("intag", "u.city in tags"), + ("anyb", "some(items, contains(lower(#.tag), 'b'))"), + ("ups", "map(tags, upper(#))"), + ("fq", "map(filter(items, startsWith(#.name, 'A')), #.qty)"), + ("tt", "map(items, #.tag ?? 'x')"), + ("tc", "count(tags, # == $.pass)"), + ("mixeq", "u.name == u.amt"), + ("mixne", "u.tier != u.flag"), + ("mixlit", "u.amt == 'x' or $.lbl == 3"), + ("snull", "string(u.tier) == 'null'"), + ("negz", "string(-u.qty) + string(-u.amt)"), + ]; + + const W12_KEYS: [(&'static str, &'static str); 6] = [ + ("item.label", "upper(item.name) + '-' + c.code"), + ("item.same", "item.name == c.code"), + ("item.s", "string(item.qty * c.rate)"), + ("item.t", "`${item.name}:${item.qty}`"), + ("item.k", "item.qty > 2 ? item.name : c.code"), + ("item.n", "len(item.label)"), + ]; + + const W13_KEYS: [(&'static str, &'static str); 7] = [ + ("c.full", "c.code + '!'"), + ("c.again", "lower(c.full) == 'ab!'"), + ("c.names", "map(c.items, #.name)"), + ("c.joined", "c.full + string(len(c.items))"), + ("c.any", "some(c.items, #.name == c.code)"), + ("c.lab", "map(c.items, trim(#.name) + string(c.rate))"), + ("c.pick", "c.rate > 1 ? c.full : c.code"), + ]; + + const NAMES_W11: [&'static str; 12] = ["Anna", "bob", " Cara ", "Émile", "straße", "Džemal", "", "İstanbul", "日本", "x\u{a0}", "\tTabe\n", "Bart"]; const W8_KEYS: [(&'static str, &'static str); 24] = [ ("total", "sum(xs)"), @@ -237,6 +302,9 @@ impl Workload { "W8" => Self::w8(), "W9" => Self::w9(), "W10" => Self::w10(), + "W11" => Self::w11(), + "W12" => Self::w12(), + "W13" => Self::w13(), _ => Self::w4(), } } @@ -264,6 +332,8 @@ impl Workload { "W6" | "W7" => Self::w6_rows(count), "W8" => Self::w8_rows(count), "W9" | "W10" => Self::w9_rows(count), + "W11" => Self::w11_rows(count), + "W12" | "W13" => Self::w12_rows(count), _ => Self::w4_rows(count), } } @@ -277,6 +347,8 @@ impl Workload { "W6" | "W7" => Self::w6_extremes(), "W8" => Self::w8_extremes(), "W9" | "W10" => Self::w9_extremes(), + "W11" => Self::w11_extremes(), + "W12" | "W13" => Self::w12_extremes(), _ => Self::w4_extremes(), } } @@ -522,6 +594,144 @@ impl Workload { Workload { name: "W10", spec: Self::w9_spec(), dialect: Dialect::Policy, member: Some(0), blocks: Self::W10_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect() } } + fn w11() -> Workload { + Workload { + name: "W11", + spec: Spec { + columns: vec![ + Self::col("u.name", Class::Text, Enc::Text), + Self::col("u.city", Class::Text, Enc::Utf8), + Self::col("u.tier", Class::Text, Enc::Dict), + Self::col("u.amt", Class::Num, Enc::Scaled), + Self::col("u.qty", Class::Num, Enc::I64), + Self::col("u.big", Class::Num, Enc::Dec), + Self::col("u.flag", Class::Bool, Enc::Bool), + ], + lists: vec![ + Self::list( + None, + "items", + "item", + vec![Self::col("name", Class::Text, Enc::Dict), Self::col("qty", Class::Num, Enc::I64), Self::col("tag", Class::Text, Enc::Text)], + ), + Self::list(None, "tags", "t", vec![Self::col("", Class::Text, Enc::Utf8)]), + ], + }, + dialect: Dialect::Graph, + member: None, + blocks: Self::W11_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect(), + } + } + + fn w12_spec() -> Spec { + Spec { + columns: vec![Self::col("c.code", Class::Text, Enc::Text), Self::col("c.rate", Class::Num, Enc::Scaled)], + lists: vec![Self::list(None, "c.items", "item", vec![Self::col("name", Class::Text, Enc::Dict), Self::col("qty", Class::Num, Enc::I64)])], + } + } + + fn w12() -> Workload { + Workload { name: "W12", spec: Self::w12_spec(), dialect: Dialect::Policy, member: Some(0), blocks: Self::W12_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect() } + } + + fn w13() -> Workload { + Workload { name: "W13", spec: Self::w12_spec(), dialect: Dialect::Policy, member: None, blocks: Self::W13_KEYS.iter().map(|(k, s)| Self::expr(k, s)).collect() } + } + + fn text(rng: &mut Rng, pool: &[&str], nulls: u64) -> Value { + match rng.pick(nulls) { + 0 => Value::Null, + _ => Self::s(pool[rng.pick(pool.len() as u64) as usize]), + } + } + + fn w11_rows(count: usize) -> Vec { + let mut rng = Rng::new(31); + let tiers = ["gold", "silver", "big", "small", "Gold"]; + let cities = ["Berlin", "bonn", "Anna", " Bart", "Émile", "x\u{a0}", ""]; + let tags = ["b", "Berlin", "Anna", "Ünï", ""]; + (0..count) + .map(|_| { + let items: Vec> = match rng.pick(25) { + 0 => vec![Vec::new()], + _ => (0..rng.pick(5)) + .map(|_| vec![Self::text(&mut rng, &Self::NAMES_W11, 40), Self::n(rng.pick(9) as i64), Self::text(&mut rng, &tags, 40)]) + .collect(), + }; + let tg: Vec> = match rng.pick(30) { + 0 => vec![Vec::new()], + _ => (0..rng.pick(4)).map(|_| vec![Self::text(&mut rng, &cities, 40)]).collect(), + }; + let flag = match rng.pick(30) { + 0 => Value::Null, + k => Value::Bool(k % 2 == 0), + }; + let amt = match rng.pick(30) { + 0 => Value::Null, + _ => Self::d(rng.pick(200_001) as i64 - 100_000, rng.pick(4) as u8), + }; + let columns = vec![ + Self::text(&mut rng, &Self::NAMES_W11, 60), + Self::text(&mut rng, &cities, 60), + Self::text(&mut rng, &tiers, 5), + amt, + Self::n(rng.pick(10) as i64), + Self::d(rng.pick(2_000_001) as i64 - 1_000_000, rng.pick(3) as u8), + flag, + ]; + Row { columns, lists: vec![items, tg] } + }) + .collect() + } + + fn w11_extremes() -> Vec { + let row = |name: Value, city: Value, tier: Value, amt: Value, qty: Value, big: Value| Row { + columns: vec![name, city, tier, amt, qty, big, Value::Bool(true)], + lists: vec![vec![vec![Self::s("Ab"), Self::n(1), Value::Null]], vec![vec![Self::s("bonn")]]], + }; + let long = "ab".repeat(700); + vec![ + row(Self::s(""), Self::s(""), Self::s(""), Self::d(0, 3), Self::n(0), Self::d(0, 2)), + row(Self::s(&long), Self::s(&long), Value::Null, Self::n(i64::MAX), Self::n(i64::MAX), Self::n(i64::MAX)), + row(Self::s("ß"), Self::s("Dž"), Self::s("gold"), Self::d(1, 28), Self::n(-1), Self::n(i64::MIN)), + row(Self::s("\u{1F600} x"), Self::s("İ"), Self::s("big"), Self::d(-1, 28), Self::n(7), Self::d(-5, 1)), + row(Self::s(" \u{2003}a\u{2003} "), Self::s("\u{b}v\u{c}"), Self::s("small"), Self::n(i64::MIN), Self::n(4), Self::d(150, 2)), + row(Self::s("Anna"), Self::s("Anna"), Self::s("small"), Self::d(-1500, 3), Self::n(6), Self::d(1, 0)), + ] + } + + fn w12_rows(count: usize) -> Vec { + let mut rng = Rng::new(37); + let codes = ["AB", "ab", "Zoë", "", "q"]; + let names = ["ab", "AB", "q", "Zoë", "", " ab ", "ß"]; + (0..count) + .map(|r| { + let items: Vec> = match rng.pick(30) { + 0 => vec![Vec::new()], + _ => (0..if r % 113 == 5 { 1100 } else { rng.pick(5) as usize }) + .map(|_| vec![Self::text(&mut rng, &names, 50), Self::n(rng.pick(6) as i64)]) + .collect(), + }; + let rate = match rng.pick(40) { + 0 => Value::Null, + _ => Self::d(rng.pick(400) as i64, rng.pick(3) as u8), + }; + Row { columns: vec![Self::text(&mut rng, &codes, 40), rate], lists: vec![items] } + }) + .collect() + } + + fn w12_extremes() -> Vec { + let row = |code: Value, rate: Value, items: Vec<[Value; 2]>| Row { columns: vec![code, rate], lists: vec![items.into_iter().map(|i| i.to_vec()).collect()] }; + vec![ + row(Self::s(""), Self::n(0), Vec::new()), + row(Self::s("ab"), Self::d(1, 28), vec![[Self::s("ab"), Self::n(i64::MAX)], [Self::s(""), Self::n(0)]]), + row(Value::Null, Self::n(2), vec![[Self::s("x"), Self::n(3)]]), + row(Self::s("Dž"), Self::n(i64::MAX), vec![[Self::s("Dž"), Self::n(2)], [Value::Null, Self::n(1)]]), + row(Self::s("\u{1F600}"), Self::d(-5, 1), vec![[Self::s("\u{1F600}"), Value::Null]]), + ] + } + fn w8_rows(count: usize) -> Vec { let mut rng = Rng::new(23); let tags = ["a", "b", "vip", "c"]; diff --git a/core/expression/src/typed/text.rs b/core/expression/src/typed/text.rs new file mode 100644 index 00000000..b6993a24 --- /dev/null +++ b/core/expression/src/typed/text.rs @@ -0,0 +1,383 @@ +use crate::lane::scaled::Scaled; +use crate::typed::batch::{Feed, Text}; +use crate::typed::exec::{Buf, Exec, Others, Reg}; +use crate::typed::hir::Func; +use crate::typed::ins::{Arg, Ins, Rep}; +use crate::typed::kernel::K; + +#[derive(Clone, Copy)] +pub(crate) enum TV<'a, 'x> { + Lit(&'a [u8]), + Col(&'a Text<'x>, &'a Feed<'x>), + Reg(&'a Reg), + Missing, +} + +impl<'a, 'x> TV<'a, 'x> { + #[inline] + pub(crate) fn get(self, start: usize, i: usize) -> Option<&'a [u8]> { + match self { + TV::Lit(b) => Some(b), + TV::Col(text, feed) => match feed.valid(start + i) && !K::get(feed.faults.as_deref().unwrap_or_default(), start + i) { + true => text.get(start + i), + false => None, + }, + TV::Reg(r) => (K::get(&r.valid, i) && !K::get(&r.fault, i)).then(|| r.str(i)), + TV::Missing => None, + } + } + + #[inline] + pub(crate) fn ok(self, start: usize, w: usize) -> u64 { + match self { + TV::Lit(_) => u64::MAX, + TV::Col(_, feed) => feed.valid_word(start + w * 64, 64) & !feed.fault_word(start / 64 + w), + TV::Reg(r) => r.valid[w] & !r.fault[w], + TV::Missing => 0, + } + } + + #[inline] + pub(crate) fn bad(self, start: usize, w: usize) -> u64 { + match self { + TV::Col(_, feed) => feed.fault_word(start / 64 + w), + TV::Reg(r) => r.fault[w], + TV::Lit(_) | TV::Missing => 0, + } + } +} + +impl Reg { + pub(crate) fn texts(&mut self, n: usize) { + self.text.clear(); + if self.span.len() < Reg::LANES { + self.span.resize(Reg::LANES, (0, 0)); + } + self.span[..n].fill((0, 0)); + } + + #[inline] + pub(crate) fn str(&self, i: usize) -> &[u8] { + let (lo, hi) = self.span.get(i).copied().unwrap_or_default(); + self.text.get(lo as usize..hi as usize).unwrap_or_default() + } + + #[inline] + pub(crate) fn push(&mut self, i: usize, bytes: &[u8]) { + let lo = self.text.len() as u32; + self.text.extend_from_slice(bytes); + self.span[i] = (lo, self.text.len() as u32); + } + + pub(crate) fn literal(&mut self, text: &str) { + self.text.clear(); + self.text.extend_from_slice(text.as_bytes()); + self.span.clear(); + self.span.resize(Reg::LANES, (0, text.len() as u32)); + } +} + +impl Buf { + #[inline] + pub(crate) fn str(&self, i: usize) -> &[u8] { + let (lo, hi) = self.span.get(i).copied().unwrap_or_default(); + self.text.get(lo as usize..hi as usize).unwrap_or_default() + } + + pub(crate) fn spill(&mut self, at: usize, bytes: &[u8]) { + if self.span.len() < self.mant.len() { + self.span.resize(self.mant.len(), (0, 0)); + } + let lo = self.text.len() as u32; + self.text.extend_from_slice(bytes); + if let Some(s) = self.span.get_mut(at) { + *s = (lo, self.text.len() as u32); + } + } +} + +impl<'e, 'x> Exec<'e, 'x> { + pub(crate) fn view<'a>(&'a self, arg: &'a Arg, regs: &'a Others) -> TV<'a, 'x> { + match arg { + Arg::Lit(s) => TV::Lit(s.as_bytes()), + Arg::Reg(r) => TV::Reg(®s[*r as usize]), + Arg::Src(src) => match self.feed(*src) { + Some(feed) => match feed.text() { + Some(text) => TV::Col(text, feed), + None => TV::Missing, + }, + None => TV::Missing, + }, + } + } + + fn find(hay: &[u8], needle: &[u8]) -> bool { + needle.is_empty() || hay.windows(needle.len()).any(|w| w == needle) + } + + fn mapped(func: Func, bytes: &[u8], d: &mut Reg, i: usize) -> bool { + if bytes.is_ascii() && func != Func::Trim { + let lo = d.text.len(); + d.text.extend_from_slice(bytes); + let tail = &mut d.text[lo..]; + match func { + Func::Upper => tail.make_ascii_uppercase(), + _ => tail.make_ascii_lowercase(), + } + d.span[i] = (lo as u32, d.text.len() as u32); + return true; + } + let Ok(text) = std::str::from_utf8(bytes) else { + return false; + }; + match func { + Func::Upper => d.push(i, text.to_uppercase().as_bytes()), + Func::Lower => d.push(i, text.to_lowercase().as_bytes()), + _ => d.push(i, text.trim().as_bytes()), + } + true + } + + fn faults(&self, d: &mut Reg, views: &[TV]) { + for w in 0..self.words.min(Reg::WORDS) { + d.valid[w] = u64::MAX; + d.fault[w] = views.iter().fold(0, |acc, v| acc | !v.ok(self.start, w)) & self.tail(w); + } + } + + pub(crate) fn text(&self, ins: &Ins, regs: &mut [Reg], act: Option<&[u64; Reg::WORDS]>) { + let (n, words, start) = (self.n, self.words.min(Reg::WORDS), self.start); + match ins { + Ins::EqText { ne, dst, a, b } => Self::def(regs, *dst, |d, regs| { + let (x, y) = (self.view(a, regs), self.view(b, regs)); + for w in 0..words { + d.valid[w] = u64::MAX; + d.fault[w] = (x.bad(start, w) | y.bad(start, w)) & self.tail(w); + } + let ne = *ne; + self.bools(act, &mut d.bits, |i| (x.get(start, i) == y.get(start, i)) != ne); + }), + Ins::Text { func, dst, a, b } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + let y = b.as_ref().map_or(TV::Lit(b""), |b| self.view(b, regs)); + self.faults(d, &[x, y]); + match (func, x) { + (Func::Len, TV::Col(Text::Str { offsets, .. }, _)) => { + for (m, p) in d.mant[..n].iter_mut().zip(offsets[start..=start + n].windows(2)) { + *m = (p[1] - p[0]) as i64; + } + } + (Func::Len, TV::Lit(l)) => d.mant[..n].fill(l.len() as i64), + (Func::Len, x) => { + for (i, m) in d.mant[..n].iter_mut().enumerate() { + *m = x.get(start, i).map_or(0, |t| t.len() as i64); + } + } + (Func::StartsWith, TV::Col(Text::Str { offsets, data }, _)) if act.is_none() && matches!(y, TV::Lit(_)) => { + let p = match y { + TV::Lit(p) => p, + _ => b"", + }; + let offs = &offsets[start..=start + n]; + K::pack_idx(n, &mut d.bits[..words], |i| { + let (lo, hi) = (offs[i] as usize, offs[i + 1] as usize); + hi >= lo + p.len() && data.get(lo..lo + p.len()).is_some_and(|h| h == p) + }); + } + (Func::StartsWith | Func::EndsWith | Func::Contains, _) => { + let func = *func; + self.bools(act, &mut d.bits, |i| match (x.get(start, i), y.get(start, i)) { + (Some(a), Some(b)) => match func { + Func::StartsWith => a.starts_with(b), + Func::EndsWith => a.ends_with(b), + _ => Self::find(a, b), + }, + _ => false, + }) + } + _ => {} + } + }), + Ins::Matches { dst, a, pattern } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + self.faults(d, &[x]); + d.bits[..words].fill(0); + let skip = d.fault; + let mut broken = Vec::new(); + self.each(act, &skip, |i| match x.get(start, i).map(std::str::from_utf8) { + Some(Ok(t)) => K::set(&mut d.bits, i, pattern.is_match(t)), + _ => broken.push(i), + }); + broken.into_iter().for_each(|i| K::set(&mut d.fault, i, true)); + }), + Ins::Map { func, dst, a } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + self.faults(d, &[x]); + d.texts(n); + let skip = d.fault; + let mut broken = Vec::new(); + self.each(act, &skip, |i| { + let ok = x.get(start, i).is_some_and(|bytes| Self::mapped(*func, bytes, d, i)); + if !ok { + broken.push(i); + } + }); + broken.into_iter().for_each(|i| K::set(&mut d.fault, i, true)); + }), + Ins::Concat { dst, parts } => Self::def(regs, *dst, |d, regs| { + let views: Vec = parts.iter().map(|p| self.view(p, regs)).collect(); + self.faults(d, &views); + d.texts(n); + let skip = d.fault; + self.each(act, &skip, |i| { + let lo = d.text.len() as u32; + for v in &views { + d.text.extend_from_slice(v.get(start, i).unwrap_or_default()); + } + d.span[i] = (lo, d.text.len() as u32); + }); + }), + Ins::Str { dst, a, rep } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + for w in 0..words { + d.valid[w] = u64::MAX; + d.fault[w] = x.bad(start, w) & self.tail(w); + } + d.texts(n); + let skip = d.fault; + let mut scratch = String::new(); + let mut broken = Vec::new(); + match (rep, x) { + (Rep::Text, x) => self.each(act, &skip, |i| d.push(i, x.get(start, i).unwrap_or(b"null"))), + (Rep::Fix(_) | Rep::Dyn, TV::Reg(r)) => self.each(act, &skip, |i| { + scratch.clear(); + match (K::get(&r.valid, i), K::get(&r.wide, i)) { + (false, _) => scratch.push_str("null"), + (true, true) => scratch.push_str(&r.num(*rep, i).decimal().to_string()), + (true, false) => match rep.scale_at(r, i) { + s if s <= 28 => Scaled::write(r.mant[i], s, &mut scratch), + _ => broken.push(i), + }, + } + d.push(i, scratch.as_bytes()); + }), + (Rep::Bool, TV::Reg(r)) => self.each(act, &skip, |i| { + let text: &[u8] = match (K::get(&r.valid, i), K::get(&r.bits, i)) { + (false, _) => b"null", + (true, true) => b"true", + (true, false) => b"false", + }; + d.push(i, text); + }), + (Rep::Null, _) => self.each(act, &skip, |i| d.push(i, b"null")), + _ => d.fault[..words].fill(u64::MAX), + } + broken.into_iter().for_each(|i| K::set(&mut d.fault, i, true)); + }), + Ins::Decode { dst, a, values } => Self::def(regs, *dst, |d, regs| { + let a = ®s[*a as usize]; + d.valid[..words].copy_from_slice(&a.valid[..words]); + d.fault[..words].copy_from_slice(&a.fault[..words]); + d.texts(n); + let mut skip = [0u64; Reg::WORDS]; + for (w, s) in skip.iter_mut().enumerate().take(words) { + *s = !a.valid[w] | a.fault[w]; + } + let mut broken = Vec::new(); + self.each(act, &skip, |i| match usize::try_from(a.codes[i]).ok().and_then(|c| values.get(c)) { + Some(text) => d.push(i, text.as_bytes()), + None => broken.push(i), + }); + broken.into_iter().for_each(|i| K::set(&mut d.fault, i, true)); + }), + Ins::Class { dst, a, matcher } => Self::def(regs, *dst, |d, regs| { + let x = self.view(a, regs); + for w in 0..words { + d.valid[w] = x.ok(start, w); + d.fault[w] = x.bad(start, w) & self.tail(w); + } + for (i, c) in d.codes[..n].iter_mut().enumerate() { + *c = matcher.code(x.get(start, i)); + } + }), + _ => {} + } + } + + pub(crate) fn load_text(&self, d: &mut Reg, text: &Text) { + let (n, start) = (self.n, self.start); + d.texts(n); + match text { + Text::Str { offsets, data } => { + let (lo, hi) = (offsets[start] as usize, offsets[start + n] as usize); + d.text.extend_from_slice(data.get(lo..hi).unwrap_or_default()); + for (s, p) in d.span[..n].iter_mut().zip(offsets[start..=start + n].windows(2)) { + *s = ((p[0] as usize).saturating_sub(lo) as u32, (p[1] as usize).saturating_sub(lo) as u32); + } + } + Text::Dict { .. } => { + for i in 0..n { + if K::get(&d.valid, i) { + d.push(i, text.get(start + i).unwrap_or_default()); + } + } + } + } + } + + pub(crate) fn gather_text(&self, d: &mut Reg, b: &Buf, parent: &[u32]) { + d.texts(self.n); + for (i, &p) in parent.iter().enumerate() { + d.push(i, b.str(p as usize)); + } + } + + pub(crate) fn fill_text(&self, d: &mut Reg, b: &Buf) { + d.texts(self.n); + for i in 0..self.n { + d.push(i, b.str(self.start + i)); + } + } + + pub(crate) fn spill_text(&self, r: &Reg, b: &mut Buf) { + for i in 0..self.n { + b.spill(self.start + i, r.str(i)); + } + } + + pub(crate) fn blend_text(&self, d: &mut Reg, m: &[u64], t: &Reg, e: &Reg) { + d.texts(self.n); + for i in 0..self.n { + let src = match K::get(m, i) { + true => t, + false => e, + }; + if K::get(&src.valid, i) { + d.push(i, src.str(i)); + } + } + } + + pub(crate) fn pick_text(&self, d: &mut Reg, m: &[u64], a: &Reg) { + for (w, &word) in m.iter().enumerate() { + let mut bits = word & a.valid[w]; + while bits != 0 { + let i = w * 64 + bits.trailing_zeros() as usize; + bits &= bits - 1; + d.push(i, a.str(i)); + } + } + } + + pub(crate) fn out_text(&self, r: &Reg, span: &mut [(u32, u32)], data: &mut Vec) { + for i in 0..self.n { + let lo = data.len() as u32; + if K::get(&r.valid, i) && !K::get(&r.fault, i) { + data.extend_from_slice(r.str(i)); + } + if let Some(s) = span.get_mut(self.start + i) { + *s = (lo, data.len() as u32); + } + } + } +}