Skip to main content

zu_vector/
expr.rs

1//! Compiled expression programs (perf/02 section 3).
2//!
3//! A bound expression compiles once at plan time into a short register
4//! program over vectorized kernels; evaluation walks the ops, never the
5//! expression tree, and column loads resolve to flat indices, not name
6//! probes. The optimizer integration lands with the perf/03 executor;
7//! this module owns the program shape and the evaluator.
8
9use 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/// A constant at the program boundary. Becomes a Constant vector at
28/// evaluation, so kernels see one encoding for literals and correlated
29/// single values alike.
30#[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    /// A temporal value: one word, and the lane that says what the
42    /// count in it is a count of. The lane is on the constant rather
43    /// than worked out from the word because nothing about a number of
44    /// days tells you it is days.
45    Lane {
46        phys: PhysType,
47        word: i64,
48    },
49}
50
51#[derive(Clone, Debug)]
52pub enum ExprOp {
53    /// Read a chunk column into a register. A borrow at evaluation, not
54    /// a copy; the register remembers the column index.
55    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    /// One of the numeric functions over a single number, whose answer
70    /// is a value like any other. The op carries which function it is,
71    /// so a call costs no dispatch per row.
72    Math {
73        op: MathOp,
74        src: Reg,
75        dst: Reg,
76    },
77    /// One of the numeric functions over two numbers: POWER, LOG and
78    /// MOD under its function spelling. Two registers in and one out,
79    /// and both arguments hold the one type by the time they get here.
80    MathPair {
81        op: MathPair,
82        l: Reg,
83        r: Reg,
84        dst: Reg,
85    },
86    /// The length of a string, in characters or in bytes. The answer
87    /// is a number, so this is the one string function whose output
88    /// needs no room in the arena for bytes.
89    StrLen {
90        op: StrLen,
91        src: Reg,
92        dst: Reg,
93    },
94    /// A fold of a string, up or down. The answer is a string, so this
95    /// is the first op whose output carries bytes of its own rather
96    /// than only numbers.
97    StrFold {
98        op: StrFold,
99        src: Reg,
100        dst: Reg,
101    },
102    /// A trim of a string, off either end or both. The set of
103    /// characters is whatever the statement wrote, prepared once at
104    /// compile time and shared by every chunk the program runs over,
105    /// since it is the same set for all of them.
106    StrTrim {
107        ends: StrTrim,
108        set: Arc<TrimSet>,
109        src: Reg,
110        dst: Reg,
111    },
112    /// The characters at one end of a string, counted by a second
113    /// register rather than by something the statement wrote, since
114    /// LEFT and RIGHT take their count as an ordinary argument and a
115    /// column is one of the things that can arrive in it.
116    StrCut {
117        end: StrCut,
118        src: Reg,
119        n: Reg,
120        dst: Reg,
121    },
122    /// A string put into one of the four normal forms. The form is
123    /// whatever the statement wrote, or NFC where it wrote none, and it
124    /// is the same form for every chunk the program runs over.
125    StrNorm {
126        form: NormalForm,
127        src: Reg,
128        dst: Reg,
129    },
130    /// Whether a string is in a normal form already. This is the one
131    /// string op whose answer is a predicate rather than a value, so it
132    /// writes a bitmap the way a comparison does. `negated` carries the
133    /// NOT, which belongs in the kernel: a null row is off in either
134    /// answer, and a complement of the bitmap would have turned it on.
135    StrNormalized {
136        form: NormalForm,
137        negated: bool,
138        src: Reg,
139        dst: Reg,
140    },
141    /// The identifier of a node, which is the one element function
142    /// whose answer is a string. The table comes from the plan, a level
143    /// having one for every row it will ever produce, and the register
144    /// holds the rows themselves.
145    ElementId {
146        table: u32,
147        src: Reg,
148        dst: Reg,
149    },
150    /// The length of time from one instant to another. The op carries
151    /// the type both operands hold and the kind of duration asked for,
152    /// which is everything the kernel needs to pick its loop, so the
153    /// choice is made once a chunk and no value in the loop carries a
154    /// tag.
155    Between {
156        of: LogicalType,
157        kind: DurationKind,
158        from: Reg,
159        to: Reg,
160        dst: Reg,
161    },
162    /// Comparison produces a predicate bitmap register.
163    Compare {
164        op: CmpOp,
165        l: Reg,
166        r: Reg,
167        dst: Reg,
168    },
169    /// A null test reads the operand's validity, which is the answer
170    /// already: IS NULL is the complement of the validity bitmap, IS
171    /// NOT NULL is the bitmap itself. `negated` carries the NOT.
172    IsNull {
173        src: Reg,
174        negated: bool,
175        dst: Reg,
176    },
177    /// A predicate the rows cannot change: every row passes, or none
178    /// does. `IS TYPED` against the type a column already has is the
179    /// case that puts one here, since the answer is a fact about the
180    /// column and the compiler knows it before a row is read. Writing
181    /// it as an op rather than dropping the filter keeps the program
182    /// able to say `false`, which a dropped filter cannot.
183    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    /// Borrowed chunk column, resolved on use.
207    Col(u8),
208    Vec(ValueVector),
209    Bits(Bitmap),
210}
211
212impl Program {
213    /// Evaluate against a chunk, using the chunk's own selection.
214    /// Returns the final op's destination register.
215    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(&regs, *l, chunk)?;
233                        let rv = resolve(&regs, *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(&regs, *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(&regs, *from, chunk)?;
256                        let b = resolve(&regs, *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(&regs, *l, chunk)?;
265                        let rv = resolve(&regs, *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(&regs, *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(&regs, *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(&regs, *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(&regs, *src, chunk)?;
303                        let count = resolve(&regs, *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(&regs, *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(&regs, *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(&regs, *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(&regs, *l, chunk)?;
343                        let rv = resolve(&regs, *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(&regs, *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    /// Evaluate a predicate program to a bitmap over the chunk.
387    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    /// Evaluate a value program to a vector.
395    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
406/// Write a null test into `out`, which arrives cleared. Rows outside
407/// the chunk's selection may land either way: the filter refines the
408/// selection it already has, so a bit off the selection never reaches a
409/// row. Absent validity means every row is valid, the convention the
410/// vector reader keeps, so IS NULL over such a column is empty.
411fn 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 &regs[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
462/// A constant string vector: inline view when short, otherwise one
463/// shared buffer holding the payload.
464pub 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        // col0 > 10 AND col0 < 30
496        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        // col0 * 10 + 5
533        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    /// A kernel that missed a row leaves the value slot alone and
564    /// clears the validity bit, which is what the two null tests read.
565    #[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    /// A column with no validity is every row valid, so the tests
596    /// answer all or nothing without reading a bitmap that is not
597    /// there. The tail matters: a length that is not a multiple of the
598    /// word width must not report the padding as rows.
599    #[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}