1use std::sync::Arc;
10
11use zu_common::types::LogicalType;
12use zu_common::unicode::NormalForm;
13use zu_common::{DurationKind, Result, ZuError};
14
15use crate::arena::MorselArena;
16use crate::bitmap::Bitmap;
17use crate::chunk::DataChunk;
18use crate::kernels::{
19 BinOp, CmpOp, MathOp, MathPair, StrCut, StrFold, StrLen, StrTrim, TrimSet, binary, compare,
20 cut, duration_between, element_ids, fold, length, normalize, normalized, pair, trim, unary,
21};
22use crate::str::StrView;
23use crate::vector::{Aux, PhysType, ValueVector};
24
25pub type Reg = u8;
26
27#[derive(Clone, Debug, PartialEq)]
31pub enum OwnedValue {
32 Null,
33 Bool(bool),
34 Int(i64),
35 Float(f64),
36 Str(Box<[u8]>),
37 Node {
38 table: u16,
39 row: u64,
40 },
41 Lane {
46 phys: PhysType,
47 word: i64,
48 },
49}
50
51#[derive(Clone, Debug)]
52pub enum ExprOp {
53 LoadCol {
56 col: u8,
57 dst: Reg,
58 },
59 LoadConst {
60 v: OwnedValue,
61 dst: Reg,
62 },
63 Binary {
64 op: BinOp,
65 l: Reg,
66 r: Reg,
67 dst: Reg,
68 },
69 Math {
73 op: MathOp,
74 src: Reg,
75 dst: Reg,
76 },
77 MathPair {
81 op: MathPair,
82 l: Reg,
83 r: Reg,
84 dst: Reg,
85 },
86 StrLen {
90 op: StrLen,
91 src: Reg,
92 dst: Reg,
93 },
94 StrFold {
98 op: StrFold,
99 src: Reg,
100 dst: Reg,
101 },
102 StrTrim {
107 ends: StrTrim,
108 set: Arc<TrimSet>,
109 src: Reg,
110 dst: Reg,
111 },
112 StrCut {
117 end: StrCut,
118 src: Reg,
119 n: Reg,
120 dst: Reg,
121 },
122 StrNorm {
126 form: NormalForm,
127 src: Reg,
128 dst: Reg,
129 },
130 StrNormalized {
136 form: NormalForm,
137 negated: bool,
138 src: Reg,
139 dst: Reg,
140 },
141 ElementId {
146 table: u32,
147 src: Reg,
148 dst: Reg,
149 },
150 Between {
156 of: LogicalType,
157 kind: DurationKind,
158 from: Reg,
159 to: Reg,
160 dst: Reg,
161 },
162 Compare {
164 op: CmpOp,
165 l: Reg,
166 r: Reg,
167 dst: Reg,
168 },
169 IsNull {
173 src: Reg,
174 negated: bool,
175 dst: Reg,
176 },
177 All {
184 on: bool,
185 dst: Reg,
186 },
187 And {
188 l: Reg,
189 r: Reg,
190 dst: Reg,
191 },
192 Or {
193 l: Reg,
194 r: Reg,
195 dst: Reg,
196 },
197}
198
199pub struct Program {
200 pub ops: Vec<ExprOp>,
201 pub regs: u8,
202}
203
204enum Slot {
205 Empty,
206 Col(u8),
208 Vec(ValueVector),
209 Bits(Bitmap),
210}
211
212impl Program {
213 fn run(&self, chunk: &DataChunk, arena: &mut MorselArena) -> Result<Slot> {
216 let mut regs: Vec<Slot> = (0..self.regs).map(|_| Slot::Empty).collect();
217 let sel = chunk.sel.as_ref();
218 let count = chunk.count as usize;
219 let mut last = 0;
220 for op in &self.ops {
221 match op {
222 ExprOp::LoadCol { col, dst } => {
223 regs[*dst as usize] = Slot::Col(*col);
224 last = *dst;
225 }
226 ExprOp::LoadConst { v, dst } => {
227 regs[*dst as usize] = Slot::Vec(const_vector(arena, v, count)?);
228 last = *dst;
229 }
230 ExprOp::Binary { op, l, r, dst } => {
231 let out = {
232 let lv = resolve(®s, *l, chunk)?;
233 let rv = resolve(®s, *r, chunk)?;
234 binary(arena, *op, lv, rv, sel)?
235 };
236 regs[*dst as usize] = Slot::Vec(out);
237 last = *dst;
238 }
239 ExprOp::Math { op, src, dst } => {
240 let out = {
241 let v = resolve(®s, *src, chunk)?;
242 unary(arena, *op, v, sel)?
243 };
244 regs[*dst as usize] = Slot::Vec(out);
245 last = *dst;
246 }
247 ExprOp::Between {
248 of,
249 kind,
250 from,
251 to,
252 dst,
253 } => {
254 let out = {
255 let a = resolve(®s, *from, chunk)?;
256 let b = resolve(®s, *to, chunk)?;
257 duration_between(arena, of, *kind, a, b, sel)?
258 };
259 regs[*dst as usize] = Slot::Vec(out);
260 last = *dst;
261 }
262 ExprOp::MathPair { op, l, r, dst } => {
263 let out = {
264 let lv = resolve(®s, *l, chunk)?;
265 let rv = resolve(®s, *r, chunk)?;
266 pair(arena, *op, lv, rv, sel)?
267 };
268 regs[*dst as usize] = Slot::Vec(out);
269 last = *dst;
270 }
271 ExprOp::StrLen { op, src, dst } => {
272 let out = {
273 let v = resolve(®s, *src, chunk)?;
274 length(arena, *op, v)?
275 };
276 regs[*dst as usize] = Slot::Vec(out);
277 last = *dst;
278 }
279 ExprOp::StrFold { op, src, dst } => {
280 let out = {
281 let v = resolve(®s, *src, chunk)?;
282 fold(arena, *op, v)?
283 };
284 regs[*dst as usize] = Slot::Vec(out);
285 last = *dst;
286 }
287 ExprOp::StrTrim {
288 ends,
289 set,
290 src,
291 dst,
292 } => {
293 let out = {
294 let v = resolve(®s, *src, chunk)?;
295 trim(arena, *ends, set, v)?
296 };
297 regs[*dst as usize] = Slot::Vec(out);
298 last = *dst;
299 }
300 ExprOp::StrCut { end, src, n, dst } => {
301 let out = {
302 let s = resolve(®s, *src, chunk)?;
303 let count = resolve(®s, *n, chunk)?;
304 cut(arena, *end, s, count, sel)?
305 };
306 regs[*dst as usize] = Slot::Vec(out);
307 last = *dst;
308 }
309 ExprOp::StrNorm { form, src, dst } => {
310 let out = {
311 let v = resolve(®s, *src, chunk)?;
312 normalize(arena, *form, v)?
313 };
314 regs[*dst as usize] = Slot::Vec(out);
315 last = *dst;
316 }
317 ExprOp::StrNormalized {
318 form,
319 negated,
320 src,
321 dst,
322 } => {
323 let mut bits = Bitmap::new_in(arena, count, false);
324 {
325 let v = resolve(®s, *src, chunk)?;
326 normalized(*form, *negated, v, &mut bits)?;
327 }
328 regs[*dst as usize] = Slot::Bits(bits);
329 last = *dst;
330 }
331 ExprOp::ElementId { table, src, dst } => {
332 let out = {
333 let v = resolve(®s, *src, chunk)?;
334 element_ids(arena, *table, v)?
335 };
336 regs[*dst as usize] = Slot::Vec(out);
337 last = *dst;
338 }
339 ExprOp::Compare { op, l, r, dst } => {
340 let mut bits = Bitmap::new_in(arena, count, false);
341 {
342 let lv = resolve(®s, *l, chunk)?;
343 let rv = resolve(®s, *r, chunk)?;
344 compare(*op, lv, rv, sel, &mut bits)?;
345 }
346 regs[*dst as usize] = Slot::Bits(bits);
347 last = *dst;
348 }
349 ExprOp::IsNull { src, negated, dst } => {
350 let mut bits = Bitmap::new_in(arena, count, false);
351 {
352 let v = resolve(®s, *src, chunk)?;
353 validity_bits(v, *negated, &mut bits);
354 }
355 regs[*dst as usize] = Slot::Bits(bits);
356 last = *dst;
357 }
358 ExprOp::All { on, dst } => {
359 let bits = Bitmap::new_in(arena, count, *on);
360 regs[*dst as usize] = Slot::Bits(bits);
361 last = *dst;
362 }
363 ExprOp::And { l, r, dst } | ExprOp::Or { l, r, dst } => {
364 let is_and = matches!(op, ExprOp::And { .. });
365 let rbits = match std::mem::replace(&mut regs[*r as usize], Slot::Empty) {
366 Slot::Bits(b) => b,
367 _ => return Err(bad_reg("boolean op on a non-predicate register")),
368 };
369 let mut lbits = match std::mem::replace(&mut regs[*l as usize], Slot::Empty) {
370 Slot::Bits(b) => b,
371 _ => return Err(bad_reg("boolean op on a non-predicate register")),
372 };
373 if is_and {
374 lbits.and_with(&rbits);
375 } else {
376 lbits.or_with(&rbits);
377 }
378 regs[*dst as usize] = Slot::Bits(lbits);
379 last = *dst;
380 }
381 }
382 }
383 Ok(std::mem::replace(&mut regs[last as usize], Slot::Empty))
384 }
385
386 pub fn eval_filter(&self, chunk: &DataChunk, arena: &mut MorselArena) -> Result<Bitmap> {
388 match self.run(chunk, arena)? {
389 Slot::Bits(b) => Ok(b),
390 _ => Err(bad_reg("filter program did not end in a predicate")),
391 }
392 }
393
394 pub fn eval(&self, chunk: &DataChunk, arena: &mut MorselArena) -> Result<ValueVector> {
396 match self.run(chunk, arena)? {
397 Slot::Vec(v) => Ok(v),
398 Slot::Col(c) => Err(ZuError::InvalidArgument(format!(
399 "bare column program (col {c}); the caller should read the chunk directly"
400 ))),
401 _ => Err(bad_reg("value program did not end in a vector")),
402 }
403 }
404}
405
406fn validity_bits(v: &ValueVector, negated: bool, out: &mut Bitmap) {
412 debug_assert_eq!(out.len(), v.len as usize);
413 match (&v.validity, negated) {
414 (None, false) => {}
415 (None, true) => {
416 out.words_mut().fill(!0u64);
417 }
418 (Some(valid), false) => {
419 for (w, o) in out.words_mut().iter_mut().zip(valid.words()) {
420 *w = !o;
421 }
422 }
423 (Some(valid), true) => {
424 out.words_mut().copy_from_slice(valid.words());
425 }
426 }
427 out.mask_tail();
428}
429
430fn bad_reg(what: &str) -> ZuError {
431 ZuError::InvalidArgument(what.to_string())
432}
433
434fn resolve<'a>(regs: &'a [Slot], r: Reg, chunk: &'a DataChunk) -> Result<&'a ValueVector> {
435 match ®s[r as usize] {
436 Slot::Col(c) => Ok(&chunk.vecs[*c as usize]),
437 Slot::Vec(v) => Ok(v),
438 _ => Err(bad_reg("operand register holds no vector")),
439 }
440}
441
442fn const_vector(arena: &mut MorselArena, v: &OwnedValue, len: usize) -> Result<ValueVector> {
443 Ok(match v {
444 OwnedValue::Int(i) => ValueVector::constant(arena, PhysType::Int64, *i, len),
445 OwnedValue::Float(f) => ValueVector::constant(arena, PhysType::Float64, *f, len),
446 OwnedValue::Node { table, row } => ValueVector::constant(
447 arena,
448 PhysType::NodeRef,
449 crate::vector::node_ref(*table, *row),
450 len,
451 ),
452 OwnedValue::Str(bytes) => const_str(arena, bytes, len),
453 OwnedValue::Lane { phys, word } => ValueVector::constant(arena, *phys, *word, len),
454 OwnedValue::Bool(_) | OwnedValue::Null => {
455 return Err(ZuError::InvalidArgument(
456 "bool and null constants land with the executor port".into(),
457 ));
458 }
459 })
460}
461
462pub fn const_str(arena: &mut MorselArena, bytes: &[u8], len: usize) -> ValueVector {
465 if bytes.len() <= crate::str::INLINE_LEN {
466 let mut v = ValueVector::constant(arena, PhysType::Str, StrView::inline(bytes), len);
467 v.aux = Aux::None;
468 v
469 } else {
470 let mut bufs = crate::str::StrBuffers::new();
471 let id = bufs.push(std::sync::Arc::from(bytes.to_vec().into_boxed_slice()));
472 let view = StrView::long(bytes, id, 0);
473 let mut v = ValueVector::constant(arena, PhysType::Str, view, len);
474 v.aux = Aux::Str(std::sync::Arc::new(bufs));
475 v
476 }
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482 use crate::sel::SelVector;
483
484 fn chunk_i64(arena: &mut MorselArena, vals: &[i64]) -> DataChunk {
485 DataChunk::new(
486 vec![ValueVector::flat_from(arena, PhysType::Int64, vals)],
487 vals.len() as u32,
488 )
489 }
490
491 #[test]
492 fn filter_program() {
493 let mut arena = MorselArena::new();
494 let chunk = chunk_i64(&mut arena, &[5i64, 15, 25, 35]);
495 let p = Program {
497 ops: vec![
498 ExprOp::LoadCol { col: 0, dst: 0 },
499 ExprOp::LoadConst {
500 v: OwnedValue::Int(10),
501 dst: 1,
502 },
503 ExprOp::Compare {
504 op: CmpOp::Gt,
505 l: 0,
506 r: 1,
507 dst: 2,
508 },
509 ExprOp::LoadConst {
510 v: OwnedValue::Int(30),
511 dst: 3,
512 },
513 ExprOp::Compare {
514 op: CmpOp::Lt,
515 l: 0,
516 r: 3,
517 dst: 4,
518 },
519 ExprOp::And { l: 2, r: 4, dst: 2 },
520 ],
521 regs: 5,
522 };
523 let bits = p.eval_filter(&chunk, &mut arena).unwrap();
524 let sel = SelVector::from_bitmap(&mut arena, &bits);
525 assert_eq!(sel.as_slice(), &[1, 2]);
526 }
527
528 #[test]
529 fn value_program() {
530 let mut arena = MorselArena::new();
531 let chunk = chunk_i64(&mut arena, &[1i64, 2, 3]);
532 let p = Program {
534 ops: vec![
535 ExprOp::LoadCol { col: 0, dst: 0 },
536 ExprOp::LoadConst {
537 v: OwnedValue::Int(10),
538 dst: 1,
539 },
540 ExprOp::Binary {
541 op: BinOp::Mul,
542 l: 0,
543 r: 1,
544 dst: 2,
545 },
546 ExprOp::LoadConst {
547 v: OwnedValue::Int(5),
548 dst: 1,
549 },
550 ExprOp::Binary {
551 op: BinOp::Add,
552 l: 2,
553 r: 1,
554 dst: 3,
555 },
556 ],
557 regs: 4,
558 };
559 let out = p.eval(&chunk, &mut arena).unwrap();
560 assert_eq!(out.values::<i64>(), &[15, 25, 35]);
561 }
562
563 #[test]
566 fn null_tests_read_the_validity() {
567 let mut arena = MorselArena::new();
568 let mut chunk = chunk_i64(&mut arena, &[7i64, 0, 9, 0, 11]);
569 let mut valid = Bitmap::new_in(&mut arena, 5, true);
570 valid.clear(1);
571 valid.clear(3);
572 chunk.vecs[0].validity = Some(valid);
573
574 let program = |negated| Program {
575 ops: vec![
576 ExprOp::LoadCol { col: 0, dst: 0 },
577 ExprOp::IsNull {
578 src: 0,
579 negated,
580 dst: 1,
581 },
582 ],
583 regs: 2,
584 };
585
586 let bits = program(true).eval_filter(&chunk, &mut arena).unwrap();
587 let sel = SelVector::from_bitmap(&mut arena, &bits);
588 assert_eq!(sel.as_slice(), &[0, 2, 4]);
589
590 let bits = program(false).eval_filter(&chunk, &mut arena).unwrap();
591 let sel = SelVector::from_bitmap(&mut arena, &bits);
592 assert_eq!(sel.as_slice(), &[1, 3]);
593 }
594
595 #[test]
600 fn a_dense_column_is_null_nowhere() {
601 let mut arena = MorselArena::new();
602 let vals: Vec<i64> = (0..70).collect();
603 let chunk = chunk_i64(&mut arena, &vals);
604
605 let program = |negated| Program {
606 ops: vec![
607 ExprOp::LoadCol { col: 0, dst: 0 },
608 ExprOp::IsNull {
609 src: 0,
610 negated,
611 dst: 1,
612 },
613 ],
614 regs: 2,
615 };
616
617 let bits = program(true).eval_filter(&chunk, &mut arena).unwrap();
618 assert_eq!(bits.count_ones(), 70);
619 let bits = program(false).eval_filter(&chunk, &mut arena).unwrap();
620 assert_eq!(bits.count_ones(), 0);
621 }
622}