Skip to main content

zu_vector/kernels/
math.rs

1//! The numeric functions of one argument, GF01 to GF03.
2//!
3//! They come in two halves and the halves differ in what they answer.
4//! ABS, CEIL, FLOOR, ROUND and SIGN keep an exact argument exact, which
5//! is the rule the row engine follows: the answer of every one of them
6//! over a whole number is a whole number, and widening it to a float
7//! would lose a digit above two to the fifty third for nothing the
8//! statement asked for. SIGN is the exception in the other direction,
9//! since minus one, nought and one are whole whatever arrived, so its
10//! answer is an integer even for a float argument. The rest, the root,
11//! the exponential, the logarithms and the angles, answer a float
12//! whatever arrived, because the answer of a root or a logarithm is
13//! irrational for all but a handful of arguments and a type that
14//! changed with the value would be a type nothing could be planned
15//! against.
16//!
17//! The conditions are the row engine's, in the row engine's words, and
18//! finding them is the whole of what makes this more than a loop. They
19//! are found the way the arithmetic kernels find theirs, by one cheap
20//! fold over the argument that a chunk of ordinary numbers passes, so
21//! the loop that computes the answers stays branch free and the walk
22//! that builds a condition runs only where the fold could not rule one
23//! out. The fold the exact half wants is how many bits the widest value
24//! takes, and the fold the approximate half wants is the lowest and
25//! highest value the column holds, since every one of those conditions
26//! is about where the argument sits: below nought for a root, at or
27//! below it for a logarithm, outside minus one to one for an inverse
28//! sine, and far enough out for an exponential or a reading in degrees
29//! to leave the range a double holds. The cotangent is the one that no
30//! fold rules out, its condition being about the sine of the argument
31//! rather than the argument, so it is walked whatever the column holds.
32
33use zu_common::{Result, ZuError, gqlstatus::codes};
34
35use crate::arena::{MorselArena, Pod};
36use crate::bitmap::Bitmap;
37use crate::sel::SelVector;
38use crate::vector::{PhysType, ValueVector, VecEncoding};
39
40/// The compute loop over one argument, with the function already chosen
41/// and the encoding already settled.
42///
43/// Both have to be settled outside, for the reason the arithmetic
44/// kernel settles its operation outside: a match standing in the loop
45/// is a branch the vectorizer will not lift, and a loop it will not
46/// lift runs a row at a time.
47#[inline(always)]
48fn fill1<S: Pod, D: Pod, F: Fn(S) -> D>(dst: &mut [D], v: &ValueVector, len: usize, f: F) {
49    match v.encoding {
50        VecEncoding::Constant => dst[..len].fill(f(v.constant_value::<S>())),
51        _ => {
52            let src = v.values::<S>();
53            for i in 0..len {
54                dst[i] = f(src[i]);
55            }
56        }
57    }
58}
59
60/// The same over two arguments, whose physical types agree because
61/// [`MathPair::answer_type`] answers only where they do.
62#[inline(always)]
63fn fill2<S: Pod, D: Pod, F: Fn(S, S) -> D>(
64    dst: &mut [D],
65    l: &ValueVector,
66    r: &ValueVector,
67    len: usize,
68    f: F,
69) {
70    match (l.encoding, r.encoding) {
71        (VecEncoding::Constant, VecEncoding::Constant) => {
72            dst[..len].fill(f(l.constant_value::<S>(), r.constant_value::<S>()));
73        }
74        (VecEncoding::Constant, _) => {
75            let c = l.constant_value::<S>();
76            let b = r.values::<S>();
77            for i in 0..len {
78                dst[i] = f(c, b[i]);
79            }
80        }
81        (_, VecEncoding::Constant) => {
82            let a = l.values::<S>();
83            let c = r.constant_value::<S>();
84            for i in 0..len {
85                dst[i] = f(a[i], c);
86            }
87        }
88        _ => {
89            let (a, b) = (l.values::<S>(), r.values::<S>());
90            for i in 0..len {
91                dst[i] = f(a[i], b[i]);
92            }
93        }
94    }
95}
96
97/// One of the numeric functions of one argument, with the digit count
98/// ROUND was written with. A second argument that is not a constant is
99/// not this op: the compiler leaves that call to the row engine rather
100/// than reading a column per row inside a loop that is here to avoid
101/// exactly that.
102#[derive(Clone, Copy, PartialEq, Eq, Debug)]
103pub enum MathOp {
104    Abs,
105    Ceil,
106    Floor,
107    Sign,
108    Round(i64),
109    Sqrt,
110    Exp,
111    Ln,
112    Log10,
113    Sin,
114    Cos,
115    Tan,
116    Cot,
117    Asin,
118    Acos,
119    Atan,
120    Degrees,
121    Radians,
122}
123
124impl MathOp {
125    /// The name the row engine builds its conditions with, so a message
126    /// says which function had no answer whichever engine raised it.
127    fn name(self) -> &'static str {
128        match self {
129            MathOp::Abs => "abs",
130            MathOp::Ceil => "ceil",
131            MathOp::Floor => "floor",
132            MathOp::Sign => "sign",
133            MathOp::Round(_) => "round",
134            MathOp::Sqrt => "sqrt",
135            MathOp::Exp => "exp",
136            MathOp::Ln => "ln",
137            MathOp::Log10 => "log10",
138            MathOp::Sin => "sin",
139            MathOp::Cos => "cos",
140            MathOp::Tan => "tan",
141            MathOp::Cot => "cot",
142            MathOp::Asin => "asin",
143            MathOp::Acos => "acos",
144            MathOp::Atan => "atan",
145            MathOp::Degrees => "degrees",
146            MathOp::Radians => "radians",
147        }
148    }
149
150    /// Whether the answer is a float whatever the argument was, which
151    /// is the half of these whose answer is irrational for all but a
152    /// handful of arguments.
153    fn is_real(self) -> bool {
154        !matches!(
155            self,
156            MathOp::Abs | MathOp::Ceil | MathOp::Floor | MathOp::Sign | MathOp::Round(_)
157        )
158    }
159
160    /// Whether an argument could leave this function with no answer.
161    /// The compiler reads it to decide what may sit behind a guard: a
162    /// function that cannot raise is safe anywhere, and one that can is
163    /// only safe where the query did not write an order for it.
164    pub fn may_raise(self) -> bool {
165        match self {
166            // The distance of the bottom integer from nought is one
167            // past the top of one, and a carry left of the point can
168            // push a number past the top the same way.
169            MathOp::Abs => true,
170            MathOp::Round(digits) => digits != 0,
171            MathOp::Ceil | MathOp::Floor | MathOp::Sign => false,
172            // A sine, a cosine and a tangent are answers for every
173            // number there is, an inverse tangent is bounded, and
174            // reading a number as radians divides it by about fifty
175            // seven, so none of these five can be asked for a number
176            // nobody has.
177            MathOp::Sin | MathOp::Cos | MathOp::Tan | MathOp::Atan | MathOp::Radians => false,
178            _ => true,
179        }
180    }
181
182    /// The type the answers land in, given the type the arguments have.
183    pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
184        match (self, arg) {
185            (_, PhysType::Int64 | PhysType::Float64) if self.is_real() => Some(PhysType::Float64),
186            (MathOp::Sign, PhysType::Int64 | PhysType::Float64) => Some(PhysType::Int64),
187            (_, PhysType::Int64) => Some(PhysType::Int64),
188            (_, PhysType::Float64) => Some(PhysType::Float64),
189            _ => None,
190        }
191    }
192}
193
194/// Evaluate `op(v)` into a new flat vector.
195///
196/// The whole vector is computed whatever the selection holds, for the
197/// reason the arithmetic kernels do it: the loop is branch free and
198/// cheaper than gathering, and a selection keeps its meaning by
199/// position. `sel` says which rows are the query's, which is what the
200/// conditions are raised over and the only thing it is read for.
201pub fn unary(
202    arena: &mut MorselArena,
203    op: MathOp,
204    v: &ValueVector,
205    sel: Option<&SelVector>,
206) -> Result<ValueVector> {
207    let len = v.len as usize;
208    if matches!(v.encoding, VecEncoding::Dict { .. }) {
209        return Err(ZuError::InvalidArgument(
210            "numeric functions on dict vectors: materialize first".into(),
211        ));
212    }
213    let Some(answer) = op.answer_type(v.phys) else {
214        return Err(ZuError::InvalidArgument(format!(
215            "no {}() kernel for {:?}",
216            op.name(),
217            v.phys
218        )));
219    };
220    check(op, v, sel, len)?;
221    let mut out = ValueVector::flat_uninit(arena, answer, len);
222    match (v.phys, answer) {
223        (PhysType::Int64, PhysType::Int64) => fill_exact(op, out.values_mut::<i64>(), v, len),
224        (PhysType::Float64, PhysType::Int64) => {
225            fill1(out.values_mut::<i64>(), v, len, sign_f64);
226        }
227        // A whole number through a root or an angle, which is the one
228        // shape where the answer is wider than what arrived.
229        (PhysType::Int64, PhysType::Float64) => {
230            fill_real(op, out.values_mut::<f64>(), v, len, |x: i64| x as f64);
231        }
232        (PhysType::Float64, PhysType::Float64) => {
233            fill_real(op, out.values_mut::<f64>(), v, len, |x: f64| x);
234        }
235        _ => unreachable!("answer_type answers for these four shapes only"),
236    }
237    // NULL in, NULL out: the answer is null exactly where the argument
238    // was, and the bitmap is copied only where the argument carries one.
239    out.validity = v.validity.as_ref().map(|valid| {
240        let mut copy = Bitmap::new_in(arena, len, true);
241        copy.and_with(valid);
242        copy
243    });
244    Ok(out)
245}
246
247/// One of the numeric functions over two numbers: POWER, LOG and MOD
248/// under its function spelling.
249///
250/// MOD is here rather than on the arithmetic kernel it shares its
251/// answers with because the two spellings do not share their words: the
252/// operator reports a remainder that does not fit the way the operator
253/// does, and the function reports it as the function. A statement
254/// cannot tell which engine answered it, so it must not be able to tell
255/// which kernel did either.
256#[derive(Clone, Copy, PartialEq, Eq, Debug)]
257pub enum MathPair {
258    Power,
259    Log,
260    Mod,
261}
262
263impl MathPair {
264    fn name(self) -> &'static str {
265        match self {
266            MathPair::Power => "power",
267            MathPair::Log => "log",
268            MathPair::Mod => "mod",
269        }
270    }
271
272    /// The type the answers land in. Both arguments have to be the one
273    /// type already, the compiler having moved a written number into
274    /// the column's type before it gets here.
275    pub fn answer_type(self, l: PhysType, r: PhysType) -> Option<PhysType> {
276        if l != r {
277            return None;
278        }
279        match (self, l) {
280            // A remainder of two whole numbers is a whole number, which
281            // is the operator's rule and so the function's.
282            (MathPair::Mod, PhysType::Int64) => Some(PhysType::Int64),
283            (_, PhysType::Int64 | PhysType::Float64) => Some(PhysType::Float64),
284            _ => None,
285        }
286    }
287}
288
289/// Evaluate `op(l, r)` into a new flat vector.
290///
291/// These are the expensive ones, a power and a logarithm each costing
292/// tens of instructions, so the order here is the other way round from
293/// the kernel above: the answers are computed first and the conditions
294/// are read off the answers. A power that left the range is an infinity
295/// sitting in the output, and finding it is a pass over the numbers the
296/// loop just wrote rather than a second power per row.
297pub fn pair(
298    arena: &mut MorselArena,
299    op: MathPair,
300    l: &ValueVector,
301    r: &ValueVector,
302    sel: Option<&SelVector>,
303) -> Result<ValueVector> {
304    debug_assert_eq!(l.len, r.len);
305    if matches!(l.encoding, VecEncoding::Dict { .. })
306        || matches!(r.encoding, VecEncoding::Dict { .. })
307    {
308        return Err(ZuError::InvalidArgument(
309            "numeric functions on dict vectors: materialize first".into(),
310        ));
311    }
312    let Some(answer) = op.answer_type(l.phys, r.phys) else {
313        return Err(ZuError::InvalidArgument(format!(
314            "no {}() kernel for {:?} and {:?}",
315            op.name(),
316            l.phys,
317            r.phys
318        )));
319    };
320    let len = l.len as usize;
321    let mut out = ValueVector::flat_uninit(arena, answer, len);
322    match answer {
323        PhysType::Int64 => {
324            // A divisor of nought is remapped to one so the hardware
325            // cannot trap on a row nobody selected, which is what the
326            // arithmetic kernel does and for the same reason.
327            fill2(out.values_mut::<i64>(), l, r, len, |x: i64, y: i64| {
328                x.wrapping_rem(if y == 0 { 1 } else { y })
329            });
330        }
331        _ if l.phys == PhysType::Int64 => {
332            fill_pair_real(op, out.values_mut::<f64>(), l, r, len, |x: i64| x as f64);
333        }
334        _ => {
335            fill_pair_real(op, out.values_mut::<f64>(), l, r, len, |x: f64| x);
336        }
337    }
338    verify_pair(op, l, r, &out, sel, len)?;
339    // NULL in, NULL out, which for two arguments is null where either
340    // of them was.
341    out.validity = merged_validity(arena, l, r, len);
342    Ok(out)
343}
344
345/// The two argument functions over approximate numbers, dispatched once
346/// for the whole chunk and computed for every row whatever the
347/// conditions say, since nothing here traps.
348#[inline(always)]
349fn fill_pair_real<S: Pod, C: Fn(S) -> f64 + Copy>(
350    op: MathPair,
351    dst: &mut [f64],
352    l: &ValueVector,
353    r: &ValueVector,
354    len: usize,
355    conv: C,
356) {
357    match op {
358        MathPair::Power => fill2(dst, l, r, len, |x, y| conv(x).powf(conv(y))),
359        // LOG takes the base first and the number second, which is the
360        // order ISO 20.22 writes it in.
361        MathPair::Log => fill2(dst, l, r, len, |x, y| conv(y).log(conv(x))),
362        MathPair::Mod => fill2(dst, l, r, len, |x, y| conv(x) % conv(y)),
363    }
364}
365
366/// Raises what the row engine raises for the first selected row with no
367/// answer, reading the answers the loop already wrote.
368fn verify_pair(
369    op: MathPair,
370    l: &ValueVector,
371    r: &ValueVector,
372    out: &ValueVector,
373    sel: Option<&SelVector>,
374    len: usize,
375) -> Result<()> {
376    if !risky_pair(op, l, r, out, len) {
377        return Ok(());
378    }
379    let visit = |i: usize| -> Result<()> {
380        if !l.is_valid(i) || !r.is_valid(i) {
381            return Ok(());
382        }
383        if out.phys == PhysType::Int64 {
384            let (x, y) = (at_i64(l, i), at_i64(r, i));
385            if y == 0 {
386                return Err(ZuError::gql(codes::C22012, "division by zero".to_string()));
387            }
388            return x.checked_rem(y).map(|_| ()).ok_or_else(|| {
389                out_of_range(op.name(), format!("of {x} and {y} does not fit an integer"))
390            });
391        }
392        one_pair(op, arg_f64(l, i), arg_f64(r, i), out.values::<f64>()[i])
393    };
394    match sel {
395        Some(sel) => {
396            for &row in sel.as_slice() {
397                visit(row as usize)?;
398            }
399        }
400        None => {
401            for i in 0..len {
402                visit(i)?;
403            }
404        }
405    }
406    Ok(())
407}
408
409/// Whether the folds leave any row that could have no answer.
410fn risky_pair(
411    op: MathPair,
412    l: &ValueVector,
413    r: &ValueVector,
414    out: &ValueVector,
415    len: usize,
416) -> bool {
417    if out.phys == PhysType::Int64 {
418        // A remainder is a condition where the divisor is nought, and
419        // the one pair of whole numbers whose remainder does not fit is
420        // the bottom integer by minus one, so the divisor's own span
421        // answers for the chunk.
422        let (lo, hi) = span(r, len);
423        return (lo <= 0.0 && hi >= 0.0) || (lo <= -1.0 && hi >= -1.0);
424    }
425    // An answer that left the range is an infinity in the output, and
426    // finding one is a pass over what the loop wrote. It is the only
427    // fold POWER has, its other conditions being about the pair rather
428    // than about either column.
429    if !all_finite(out, len) {
430        return true;
431    }
432    let (lo, hi) = span(l, len);
433    match op {
434        // Nought to a negative power and a negative number to a
435        // fraction are the two the standard names, and both need a base
436        // that is not above nought.
437        MathPair::Power => lo <= 0.0,
438        // A base is a base when it is above nought and is not one, so a
439        // column entirely above one, or entirely between nought and
440        // one, holds no base that is not. The number the logarithm is
441        // taken of has to be above nought as well.
442        MathPair::Log => {
443            let base = lo > 1.0 || (lo > 0.0 && hi < 1.0);
444            !base || span(r, len).0 <= 0.0
445        }
446        MathPair::Mod => {
447            let (lo, hi) = span(r, len);
448            lo <= 0.0 && hi >= 0.0
449        }
450    }
451}
452
453/// What one row of the two argument functions raises, or `Ok` where it
454/// has an answer, in the row engine's words.
455fn one_pair(op: MathPair, x: f64, y: f64, answer: f64) -> Result<()> {
456    match op {
457        MathPair::Mod if y == 0.0 => {
458            return Err(ZuError::gql(codes::C22012, "division by zero".to_string()));
459        }
460        MathPair::Power if x == 0.0 && y < 0.0 => {
461            return Err(ZuError::gql(
462                codes::C2201F,
463                "power() has no answer for nought raised to a negative power".to_string(),
464            ));
465        }
466        MathPair::Power if x < 0.0 && y.fract() != 0.0 && y.is_finite() => {
467            return Err(ZuError::gql(
468                codes::C2201F,
469                format!("power() has no answer for {x} raised to {y}, which is not whole"),
470            ));
471        }
472        MathPair::Log if x <= 0.0 || x == 1.0 => {
473            return Err(ZuError::gql(
474                codes::C2201E,
475                format!("log() has no answer in base {x}"),
476            ));
477        }
478        MathPair::Log if y <= 0.0 => {
479            return Err(ZuError::gql(
480                codes::C2201E,
481                format!("log() has no answer for {y}, which is not above nought"),
482            ));
483        }
484        _ => {}
485    }
486    if answer.is_finite() || !x.is_finite() || !y.is_finite() {
487        Ok(())
488    } else {
489        Err(out_of_range(
490            op.name(),
491            format!("of {x} and {y} is outside the range of a float"),
492        ))
493    }
494}
495
496/// Whether every answer in the output is a number a double holds.
497fn all_finite(out: &ValueVector, len: usize) -> bool {
498    out.values::<f64>()[..len].iter().all(|x| x.is_finite())
499}
500
501/// The validity of an answer over two arguments, which is null where
502/// either of them was null and carries no bitmap where neither did.
503fn merged_validity(
504    arena: &mut MorselArena,
505    l: &ValueVector,
506    r: &ValueVector,
507    len: usize,
508) -> Option<Bitmap> {
509    if l.validity.is_none() && r.validity.is_none() {
510        return None;
511    }
512    let mut copy = Bitmap::new_in(arena, len, true);
513    if let Some(valid) = l.validity.as_ref() {
514        copy.and_with(valid);
515    }
516    if let Some(valid) = r.validity.as_ref() {
517        copy.and_with(valid);
518    }
519    Some(copy)
520}
521
522/// The exact half, dispatched once for the whole chunk.
523///
524/// The two shapes that can have no answer wrap here rather than
525/// branching, the way the arithmetic loop wraps: a row the check ahead
526/// of the loop let through has an answer, and a row it did not is a row
527/// nobody reads.
528#[inline(always)]
529fn fill_exact(op: MathOp, dst: &mut [i64], v: &ValueVector, len: usize) {
530    match op {
531        MathOp::Abs => fill1(dst, v, len, i64::wrapping_abs),
532        MathOp::Sign => fill1(dst, v, len, i64::signum),
533        // A whole number is already at its own ceiling and its own
534        // floor, and rounding one to a digit inside the fraction leaves
535        // it where it is, so these answer what they were handed rather
536        // than going through a float that could not hold it.
537        MathOp::Ceil | MathOp::Floor => fill1(dst, v, len, |x: i64| x),
538        MathOp::Round(digits) if digits >= 0 => fill1(dst, v, len, |x: i64| x),
539        MathOp::Round(digits) => fill1(dst, v, len, move |x: i64| {
540            rounded_int(x, digits).unwrap_or(0)
541        }),
542        _ => unreachable!("the approximate half answers a float"),
543    }
544}
545
546/// The approximate half, which is every one of these but the sign,
547/// dispatched once for the whole chunk.
548///
549/// `conv` carries whatever arrived to the double the function takes, so
550/// one copy of these arms serves a column of whole numbers and a column
551/// of approximate ones.
552///
553/// Nothing in here branches on the value: a row the check ahead of the
554/// loop let through has an answer, and where it did not the hardware
555/// hands back an infinity or a NaN that nobody reads.
556#[inline(always)]
557fn fill_real<S: Pod, C: Fn(S) -> f64 + Copy>(
558    op: MathOp,
559    dst: &mut [f64],
560    v: &ValueVector,
561    len: usize,
562    conv: C,
563) {
564    match op {
565        MathOp::Abs => fill1(dst, v, len, |x| conv(x).abs()),
566        MathOp::Ceil => fill1(dst, v, len, |x| conv(x).ceil()),
567        MathOp::Floor => fill1(dst, v, len, |x| conv(x).floor()),
568        MathOp::Round(0) => fill1(dst, v, len, |x| conv(x).round()),
569        MathOp::Round(digits) => {
570            let scale = 10f64.powi(digits.clamp(-308, 308) as i32);
571            fill1(dst, v, len, move |x| (conv(x) * scale).round() / scale);
572        }
573        MathOp::Sqrt => fill1(dst, v, len, |x| conv(x).sqrt()),
574        MathOp::Exp => fill1(dst, v, len, |x| conv(x).exp()),
575        MathOp::Ln => fill1(dst, v, len, |x| conv(x).ln()),
576        MathOp::Log10 => fill1(dst, v, len, |x| conv(x).log10()),
577        MathOp::Sin => fill1(dst, v, len, |x| conv(x).sin()),
578        MathOp::Cos => fill1(dst, v, len, |x| conv(x).cos()),
579        MathOp::Tan => fill1(dst, v, len, |x| conv(x).tan()),
580        // The cotangent is the cosine over the sine, which is what the
581        // row engine computes and why a sine of nought is a division by
582        // nought there rather than a condition of its own. It is the
583        // one of these written out of line, for the reason [`cot`]
584        // gives.
585        MathOp::Cot => fill1(dst, v, len, |x| cot(conv(x))),
586        MathOp::Asin => fill1(dst, v, len, |x| conv(x).asin()),
587        MathOp::Acos => fill1(dst, v, len, |x| conv(x).acos()),
588        MathOp::Atan => fill1(dst, v, len, |x| conv(x).atan()),
589        MathOp::Degrees => fill1(dst, v, len, |x| conv(x).to_degrees()),
590        MathOp::Radians => fill1(dst, v, len, |x| conv(x).to_radians()),
591        MathOp::Sign => unreachable!("sign answers an integer"),
592    }
593}
594
595/// The cotangent, written once and called from both engines.
596///
597/// Every other function here is one libm call and rounds the same way
598/// wherever it is written. This one is a division of two of them, and
599/// that does not survive being written twice: the same expression in
600/// the row engine's crate and in this one comes out one place apart at
601/// 0.75, the optimizer being free to fold the pair of calls together
602/// in one and not in the other. Which of the two is the better answer
603/// is not the question. Nothing in a statement says which engine takes
604/// it, so the two have to agree, and the way to make two crates agree
605/// on a float is to give them one function rather than one formula.
606#[inline(never)]
607pub fn cot(x: f64) -> f64 {
608    x.cos() / x.sin()
609}
610
611#[inline(always)]
612fn sign_f64(x: f64) -> i64 {
613    if x > 0.0 {
614        1
615    } else if x < 0.0 {
616        -1
617    } else {
618        0
619    }
620}
621
622/// An integer rounded to a place left of the decimal point, kept in the
623/// integers the whole way, so a number wider than a double holds is
624/// rounded exactly. This is the row engine's `rounded_int` and answers
625/// what it answers.
626fn rounded_int(value: i64, digits: i64) -> Option<i64> {
627    let places = u32::try_from(-digits).ok()?;
628    // Past nineteen digits every integer rounds to nought, and the power
629    // below would overflow rather than say so.
630    if places > 19 {
631        return Some(0);
632    }
633    let factor = 10i128.checked_pow(places)?;
634    let value = value as i128;
635    let half = factor / 2;
636    let carried = if value >= 0 {
637        (value + half) / factor
638    } else {
639        (value - half) / factor
640    };
641    i64::try_from(carried.checked_mul(factor)?).ok()
642}
643
644/// Raises what the row engine raises for the first selected row that has
645/// no answer, and answers `Ok` when every one of them has one.
646///
647/// A row whose argument is null is skipped, since a null answers null
648/// rather than raising, and so is a row the selection dropped, since the
649/// row engine never evaluated it.
650fn check(op: MathOp, v: &ValueVector, sel: Option<&SelVector>, len: usize) -> Result<()> {
651    if !risky(op, v, len) {
652        return Ok(());
653    }
654    let visit = |i: usize| -> Result<()> {
655        if !v.is_valid(i) {
656            return Ok(());
657        }
658        match v.phys {
659            PhysType::Int64 if !op.is_real() => {
660                let x = at_i64(v, i);
661                match op {
662                    MathOp::Abs => x.checked_abs().map(|_| ()).ok_or_else(|| {
663                        out_of_range(
664                            op.name(),
665                            format!("of {x} is one past the top of an integer"),
666                        )
667                    }),
668                    MathOp::Round(digits) => rounded_int(x, digits).map(|_| ()).ok_or_else(|| {
669                        out_of_range(op.name(), format!("of {x} to {digits} digits does not fit"))
670                    }),
671                    _ => Ok(()),
672                }
673            }
674            _ => one_real(op, arg_f64(v, i)),
675        }
676    };
677    match sel {
678        Some(sel) => {
679            for &row in sel.as_slice() {
680                visit(row as usize)?;
681            }
682        }
683        None => {
684            for i in 0..len {
685                visit(i)?;
686            }
687        }
688    }
689    Ok(())
690}
691
692/// Whether the fold over the column leaves any row that could have no
693/// answer. False here is the ordinary case and means the loop below
694/// runs with nothing looked at twice.
695fn risky(op: MathOp, v: &ValueVector, len: usize) -> bool {
696    if !op.may_raise() {
697        return false;
698    }
699    if op.is_real() {
700        let (lo, hi) = span(v, len);
701        return match op {
702            MathOp::Sqrt => lo < 0.0,
703            MathOp::Ln | MathOp::Log10 => lo <= 0.0,
704            MathOp::Asin | MathOp::Acos => lo < -1.0 || hi > 1.0,
705            // The exponential passes the top of a double a little above
706            // seven hundred and nine, and nowhere below it.
707            MathOp::Exp => hi > 709.0,
708            // Reading a number as degrees multiplies it by about fifty
709            // seven, so only a number within that factor of the top can
710            // leave the range.
711            MathOp::Degrees => lo <= -3.0e306 || hi >= 3.0e306,
712            // The cotangent's condition is about the sine of the
713            // argument and not the argument, and no fold over a column
714            // of numbers says where the sine lands, so this one is
715            // walked whatever it holds.
716            _ => true,
717        };
718    }
719    match (v.phys, op) {
720        // Every integer but the bottom one has a distance from nought
721        // that fits, and the bottom one is the only value whose size
722        // without its sign reaches two to the sixty third, so one fold
723        // answers for the whole chunk.
724        (PhysType::Int64, MathOp::Abs) => magnitude(v, len) >= 1u64 << 63,
725        // Carrying a number left of the point can push it past the top,
726        // and how far depends on the digit count, so the fold here is
727        // the digit count itself: a chunk asked to round inside the
728        // fraction cannot carry at all.
729        (PhysType::Int64, MathOp::Round(digits)) => digits < 0,
730        // The approximate answers are infinities where they leave the
731        // range, which is what the row engine hands back for all but
732        // one of these. Rounding is the one that checks, because
733        // multiplying by the scale is where a finite number can leave.
734        (PhysType::Float64, MathOp::Round(digits)) => digits != 0,
735        _ => false,
736    }
737}
738
739/// The answer over one approximate number, which the walk needs and the
740/// loops do not: the walk runs before the answers are written and asks
741/// of a single row whether one exists, where [`fill_real`] settles the
742/// function once and writes a chunk of them. The two hold the same
743/// arms, and a change to either belongs in both.
744fn real(op: MathOp, x: f64) -> f64 {
745    match op {
746        MathOp::Abs => x.abs(),
747        MathOp::Ceil => x.ceil(),
748        MathOp::Floor => x.floor(),
749        MathOp::Round(0) => x.round(),
750        MathOp::Round(digits) => {
751            let scale = 10f64.powi(digits.clamp(-308, 308) as i32);
752            (x * scale).round() / scale
753        }
754        MathOp::Sqrt => x.sqrt(),
755        MathOp::Exp => x.exp(),
756        MathOp::Ln => x.ln(),
757        MathOp::Log10 => x.log10(),
758        MathOp::Sin => x.sin(),
759        MathOp::Cos => x.cos(),
760        MathOp::Tan => x.tan(),
761        MathOp::Cot => cot(x),
762        MathOp::Asin => x.asin(),
763        MathOp::Acos => x.acos(),
764        MathOp::Atan => x.atan(),
765        MathOp::Degrees => x.to_degrees(),
766        MathOp::Radians => x.to_radians(),
767        MathOp::Sign => unreachable!("sign answers an integer"),
768    }
769}
770
771/// What one row of the approximate half raises, or `Ok` where it has an
772/// answer. These are the row engine's conditions and the row engine's
773/// words, so a statement cannot tell which engine answered it.
774fn one_real(op: MathOp, x: f64) -> Result<()> {
775    match op {
776        // ISO 20.22 defines the square root as the power of one half,
777        // so a negative argument is the power function's condition
778        // rather than a condition of its own.
779        MathOp::Sqrt if x < 0.0 => {
780            return Err(ZuError::gql(
781                codes::C2201F,
782                format!("sqrt() has no answer for {x}, which is below nought"),
783            ));
784        }
785        MathOp::Ln | MathOp::Log10 if x <= 0.0 => {
786            return Err(ZuError::gql(
787                codes::C2201E,
788                format!(
789                    "{}() has no answer for {x}, which is not above nought",
790                    op.name()
791                ),
792            ));
793        }
794        MathOp::Cot if x.sin() == 0.0 => {
795            return Err(ZuError::gql(
796                codes::C22012,
797                format!("cot() has no answer for {x}, where the sine is nought"),
798            ));
799        }
800        MathOp::Asin | MathOp::Acos if !(-1.0..=1.0).contains(&x) && x.is_finite() => {
801            return Err(out_of_range(
802                op.name(),
803                format!("has no answer for {x}, which is outside minus one to one"),
804            ));
805        }
806        _ => {}
807    }
808    let answer = real(op, x);
809    if answer.is_finite() || !x.is_finite() {
810        Ok(())
811    } else {
812        Err(out_of_range(
813            op.name(),
814            format!("of {x} is outside the range of a float"),
815        ))
816    }
817}
818
819/// `22003 data exception, numeric value out of range`, named the way the
820/// row engine names it.
821fn out_of_range(name: &str, detail: String) -> ZuError {
822    ZuError::gql(codes::C22003, format!("{name}() {detail}"))
823}
824
825/// The bits every value in the vector fits inside, as the OR of what
826/// each one takes without its sign.
827fn magnitude(v: &ValueVector, len: usize) -> u64 {
828    match v.encoding {
829        VecEncoding::Constant => v.constant_value::<i64>().unsigned_abs(),
830        _ => v.values::<i64>()[..len]
831            .iter()
832            .fold(0u64, |acc, x| acc | x.unsigned_abs()),
833    }
834}
835
836fn at_i64(v: &ValueVector, i: usize) -> i64 {
837    match v.encoding {
838        VecEncoding::Constant => v.constant_value::<i64>(),
839        _ => v.values::<i64>()[i],
840    }
841}
842
843/// The lowest and highest value the column holds, which is the fold
844/// every condition of the approximate half is answered by. A NaN is
845/// left out of both, since `min` and `max` over a double skip one, and
846/// leaving it out is right: a function of a NaN is a NaN and the row
847/// engine raises nothing for it.
848fn span(v: &ValueVector, len: usize) -> (f64, f64) {
849    let mut lo = f64::INFINITY;
850    let mut hi = f64::NEG_INFINITY;
851    let mut fold = |x: f64| {
852        lo = lo.min(x);
853        hi = hi.max(x);
854    };
855    match (v.encoding, v.phys) {
856        (VecEncoding::Constant, PhysType::Int64) => fold(v.constant_value::<i64>() as f64),
857        (VecEncoding::Constant, _) => fold(v.constant_value::<f64>()),
858        (_, PhysType::Int64) => {
859            for &x in &v.values::<i64>()[..len] {
860                fold(x as f64);
861            }
862        }
863        _ => {
864            for &x in &v.values::<f64>()[..len] {
865                fold(x);
866            }
867        }
868    }
869    (lo, hi)
870}
871
872/// One row read as the approximate half reads it, whichever of the two
873/// types the column holds.
874fn arg_f64(v: &ValueVector, i: usize) -> f64 {
875    match v.phys {
876        PhysType::Int64 => at_i64(v, i) as f64,
877        _ => match v.encoding {
878            VecEncoding::Constant => v.constant_value::<f64>(),
879            _ => v.values::<f64>()[i],
880        },
881    }
882}
883
884#[cfg(test)]
885mod tests {
886    use super::*;
887
888    /// The condition a kernel raised, as the words a caller reads.
889    fn raised(out: Result<ValueVector>) -> String {
890        match out {
891            Ok(_) => panic!("the kernel answered where it has no answer"),
892            Err(err) => err.to_string(),
893        }
894    }
895
896    fn ints(arena: &mut MorselArena, vals: &[i64]) -> ValueVector {
897        ValueVector::flat_from(arena, PhysType::Int64, vals)
898    }
899
900    fn floats(arena: &mut MorselArena, vals: &[f64]) -> ValueVector {
901        ValueVector::flat_from(arena, PhysType::Float64, vals)
902    }
903
904    /// An integer argument keeps its type through all five, which is
905    /// what stops a number above two to the fifty third losing a digit
906    /// to a float nobody asked for.
907    #[test]
908    fn an_exact_argument_stays_exact() {
909        let mut arena = MorselArena::new();
910        let big = 9_007_199_254_740_993i64;
911        let v = ints(&mut arena, &[-3, 0, big]);
912        for op in [MathOp::Ceil, MathOp::Floor, MathOp::Round(0)] {
913            let out = unary(&mut arena, op, &v, None).unwrap();
914            assert_eq!(out.phys, PhysType::Int64);
915            assert_eq!(out.values::<i64>(), &[-3, 0, big]);
916        }
917        let out = unary(&mut arena, MathOp::Abs, &v, None).unwrap();
918        assert_eq!(out.values::<i64>(), &[3, 0, big]);
919        let out = unary(&mut arena, MathOp::Sign, &v, None).unwrap();
920        assert_eq!(out.values::<i64>(), &[-1, 0, 1]);
921    }
922
923    /// The sign of an approximate number is an exact one, so this is
924    /// the one shape whose answer is not the type of its argument.
925    #[test]
926    fn the_sign_of_a_float_is_an_integer() {
927        let mut arena = MorselArena::new();
928        let v = floats(&mut arena, &[-0.5, 0.0, 2.5]);
929        let out = unary(&mut arena, MathOp::Sign, &v, None).unwrap();
930        assert_eq!(out.phys, PhysType::Int64);
931        assert_eq!(out.values::<i64>(), &[-1, 0, 1]);
932    }
933
934    /// Halves go away from nought, which is the rule SQL rounds by and
935    /// the one a reader expects writing it out by hand.
936    #[test]
937    fn halves_round_away_from_nought() {
938        let mut arena = MorselArena::new();
939        let v = floats(&mut arena, &[2.5, -2.5, 1.4999]);
940        let out = unary(&mut arena, MathOp::Round(0), &v, None).unwrap();
941        assert_eq!(out.values::<f64>(), &[3.0, -3.0, 1.0]);
942    }
943
944    /// A negative digit count rounds tens and hundreds, and over the
945    /// integers it never goes through a float, so the answer is exact
946    /// however wide the number is.
947    #[test]
948    fn a_negative_digit_count_rounds_left_of_the_point() {
949        let mut arena = MorselArena::new();
950        let v = ints(&mut arena, &[150, -150, 149]);
951        let out = unary(&mut arena, MathOp::Round(-2), &v, None).unwrap();
952        assert_eq!(out.values::<i64>(), &[200, -200, 100]);
953
954        let v = floats(&mut arena, &[1.234, 1.236]);
955        let out = unary(&mut arena, MathOp::Round(2), &v, None).unwrap();
956        assert_eq!(out.values::<f64>(), &[1.23, 1.24]);
957    }
958
959    /// The distance of the bottom integer from nought is one past the
960    /// top of one, which is the row engine's condition and its words.
961    #[test]
962    fn the_bottom_integer_has_no_distance_from_nought() {
963        let mut arena = MorselArena::new();
964        let v = ints(&mut arena, &[1, i64::MIN]);
965        let out = unary(&mut arena, MathOp::Abs, &v, None);
966        assert_eq!(
967            raised(out),
968            "22003: abs() of -9223372036854775808 is one past the top of an integer"
969        );
970    }
971
972    /// Carrying a number left of the point can push it past the top the
973    /// same way.
974    #[test]
975    fn a_carry_past_the_top_of_an_integer_raises() {
976        let mut arena = MorselArena::new();
977        let v = ints(&mut arena, &[i64::MAX]);
978        let out = unary(&mut arena, MathOp::Round(-1), &v, None);
979        assert_eq!(
980            raised(out),
981            "22003: round() of 9223372036854775807 to -1 digits does not fit"
982        );
983    }
984
985    /// A row the selection dropped is a row the query never asked
986    /// about, so the argument it holds is not a condition.
987    #[test]
988    fn a_row_outside_the_selection_raises_nothing() {
989        let mut arena = MorselArena::new();
990        let v = ints(&mut arena, &[7, i64::MIN, 9]);
991        let mut sel = SelVector::with_capacity(&mut arena, 2);
992        sel.push(0);
993        sel.push(2);
994        let out = unary(&mut arena, MathOp::Abs, &v, Some(&sel)).unwrap();
995        assert_eq!(out.values::<i64>()[0], 7);
996        assert_eq!(out.values::<i64>()[2], 9);
997    }
998
999    /// A null argument answers null rather than raising, so the value
1000    /// sitting under it is never read.
1001    #[test]
1002    fn a_null_argument_is_not_a_condition() {
1003        let mut arena = MorselArena::new();
1004        let mut v = ints(&mut arena, &[7, i64::MIN, 9]);
1005        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1006        valid.clear(1);
1007        v.validity = Some(valid);
1008        let out = unary(&mut arena, MathOp::Abs, &v, None).unwrap();
1009        assert!(!out.is_valid(1), "null in, null out");
1010        assert!(out.is_valid(0) && out.is_valid(2));
1011    }
1012
1013    /// An argument that was already infinite is let through, because an
1014    /// engine that raises there is answering a question about IEEE
1015    /// arithmetic with a condition the statement did not cause.
1016    #[test]
1017    fn an_infinite_argument_is_not_a_condition() {
1018        let mut arena = MorselArena::new();
1019        let v = floats(&mut arena, &[f64::INFINITY]);
1020        let out = unary(&mut arena, MathOp::Round(2), &v, None).unwrap();
1021        assert!(out.values::<f64>()[0].is_infinite());
1022    }
1023
1024    /// A root, a logarithm or an angle answers a float whatever
1025    /// arrived, so a column of whole numbers comes back wider than it
1026    /// went in.
1027    #[test]
1028    fn the_approximate_half_answers_a_float_whatever_arrived() {
1029        let mut arena = MorselArena::new();
1030        let v = ints(&mut arena, &[0, 1, 4]);
1031        let out = unary(&mut arena, MathOp::Sqrt, &v, None).unwrap();
1032        assert_eq!(out.phys, PhysType::Float64);
1033        assert_eq!(out.values::<f64>(), &[0.0, 1.0, 2.0]);
1034
1035        let out = unary(&mut arena, MathOp::Cos, &v, None).unwrap();
1036        assert_eq!(out.values::<f64>()[0], 1.0);
1037
1038        let v = floats(&mut arena, &[100.0, 1000.0]);
1039        let out = unary(&mut arena, MathOp::Log10, &v, None).unwrap();
1040        assert_eq!(out.values::<f64>(), &[2.0, 3.0]);
1041    }
1042
1043    /// The five that have an answer for every number there is say so,
1044    /// which is what lets one of them sit behind a guard.
1045    #[test]
1046    fn the_angles_and_the_readings_cannot_raise() {
1047        for op in [
1048            MathOp::Sin,
1049            MathOp::Cos,
1050            MathOp::Tan,
1051            MathOp::Atan,
1052            MathOp::Radians,
1053            MathOp::Ceil,
1054            MathOp::Floor,
1055            MathOp::Sign,
1056            MathOp::Round(0),
1057        ] {
1058            assert!(!op.may_raise(), "{op:?} says it can raise");
1059        }
1060        for op in [
1061            MathOp::Sqrt,
1062            MathOp::Exp,
1063            MathOp::Ln,
1064            MathOp::Log10,
1065            MathOp::Cot,
1066            MathOp::Asin,
1067            MathOp::Acos,
1068            MathOp::Degrees,
1069            MathOp::Abs,
1070            MathOp::Round(1),
1071        ] {
1072            assert!(op.may_raise(), "{op:?} says it cannot raise");
1073        }
1074    }
1075
1076    /// A root of a negative number and a logarithm of nought have no
1077    /// answer at all, which the standard gives conditions of their own
1078    /// rather than leaving to IEEE arithmetic.
1079    #[test]
1080    fn a_root_or_a_logarithm_outside_its_domain_raises() {
1081        let mut arena = MorselArena::new();
1082        let v = floats(&mut arena, &[4.0, -1.0]);
1083        assert_eq!(
1084            raised(unary(&mut arena, MathOp::Sqrt, &v, None)),
1085            "2201F: sqrt() has no answer for -1, which is below nought"
1086        );
1087
1088        let v = floats(&mut arena, &[1.0, 0.0]);
1089        assert_eq!(
1090            raised(unary(&mut arena, MathOp::Ln, &v, None)),
1091            "2201E: ln() has no answer for 0, which is not above nought"
1092        );
1093        assert_eq!(
1094            raised(unary(&mut arena, MathOp::Log10, &v, None)),
1095            "2201E: log10() has no answer for 0, which is not above nought"
1096        );
1097
1098        let v = ints(&mut arena, &[2, -4]);
1099        assert_eq!(
1100            raised(unary(&mut arena, MathOp::Sqrt, &v, None)),
1101            "2201F: sqrt() has no answer for -4, which is below nought"
1102        );
1103    }
1104
1105    /// An inverse sine is an angle only for an argument between minus
1106    /// one and one, and outside that the standard says the value is out
1107    /// of range rather than letting a NaN travel.
1108    #[test]
1109    fn an_inverse_angle_outside_minus_one_to_one_raises() {
1110        let mut arena = MorselArena::new();
1111        let v = floats(&mut arena, &[0.5, 2.0]);
1112        assert_eq!(
1113            raised(unary(&mut arena, MathOp::Asin, &v, None)),
1114            "22003: asin() has no answer for 2, which is outside minus one to one"
1115        );
1116        assert_eq!(
1117            raised(unary(&mut arena, MathOp::Acos, &v, None)),
1118            "22003: acos() has no answer for 2, which is outside minus one to one"
1119        );
1120    }
1121
1122    /// The cotangent is the one whose condition no fold over the column
1123    /// rules out, since it is about the sine of the argument rather
1124    /// than the argument.
1125    #[test]
1126    fn a_cotangent_where_the_sine_is_nought_raises() {
1127        let mut arena = MorselArena::new();
1128        let v = floats(&mut arena, &[1.0, 0.0]);
1129        assert_eq!(
1130            raised(unary(&mut arena, MathOp::Cot, &v, None)),
1131            "22012: cot() has no answer for 0, where the sine is nought"
1132        );
1133
1134        let v = floats(&mut arena, &[1.0, 2.0]);
1135        let out = unary(&mut arena, MathOp::Cot, &v, None).unwrap();
1136        assert!(out.values::<f64>()[0].is_finite());
1137    }
1138
1139    /// An exponential leaves the range a little above seven hundred and
1140    /// nine, and a number read as degrees leaves it within about fifty
1141    /// seven of the top.
1142    #[test]
1143    fn an_answer_past_the_top_of_a_float_raises() {
1144        let mut arena = MorselArena::new();
1145        let v = floats(&mut arena, &[1.0, 710.0]);
1146        assert_eq!(
1147            raised(unary(&mut arena, MathOp::Exp, &v, None)),
1148            "22003: exp() of 710 is outside the range of a float"
1149        );
1150
1151        let v = floats(&mut arena, &[f64::MAX]);
1152        assert!(
1153            raised(unary(&mut arena, MathOp::Degrees, &v, None))
1154                .starts_with("22003: degrees() of "),
1155        );
1156
1157        // And the fold lets an ordinary column past without a walk.
1158        let v = floats(&mut arena, &[1.0, 700.0]);
1159        assert!(
1160            unary(&mut arena, MathOp::Exp, &v, None)
1161                .unwrap()
1162                .values::<f64>()[0]
1163                > 2.7
1164        );
1165    }
1166
1167    /// A row the selection dropped is not a condition here either, and
1168    /// neither is a null, which are the two things the approximate half
1169    /// has to get right for a filter to mean what it says.
1170    #[test]
1171    fn the_approximate_half_skips_what_nobody_asked_about() {
1172        let mut arena = MorselArena::new();
1173        let v = floats(&mut arena, &[4.0, -1.0, 9.0]);
1174        let mut sel = SelVector::with_capacity(&mut arena, 2);
1175        sel.push(0);
1176        sel.push(2);
1177        let out = unary(&mut arena, MathOp::Sqrt, &v, Some(&sel)).unwrap();
1178        assert_eq!(out.values::<f64>()[2], 3.0);
1179
1180        let mut v = floats(&mut arena, &[4.0, -1.0, 9.0]);
1181        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1182        valid.clear(1);
1183        v.validity = Some(valid);
1184        let out = unary(&mut arena, MathOp::Sqrt, &v, None).unwrap();
1185        assert!(!out.is_valid(1));
1186    }
1187
1188    /// A finite number the scale pushes out of the range is the one
1189    /// place rounding an approximate number raises.
1190    #[test]
1191    fn a_finite_number_rounded_out_of_range_raises() {
1192        let mut arena = MorselArena::new();
1193        let v = floats(&mut arena, &[f64::MAX]);
1194        let out = unary(&mut arena, MathOp::Round(2), &v, None);
1195        assert!(
1196            raised(out).starts_with("22003: round() of "),
1197            "the row engine's condition"
1198        );
1199    }
1200
1201    /// A remainder of two whole numbers is a whole number, and a power
1202    /// or a logarithm of them is not, which is the one place the two
1203    /// argument functions disagree about the type of an answer.
1204    #[test]
1205    fn a_remainder_stays_exact_and_the_other_two_do_not() {
1206        let mut arena = MorselArena::new();
1207        let l = ints(&mut arena, &[7, -7, 8]);
1208        let r = ints(&mut arena, &[3, 3, 2]);
1209        let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
1210        assert_eq!(out.phys, PhysType::Int64);
1211        assert_eq!(out.values::<i64>(), &[1, -1, 0]);
1212
1213        let out = pair(&mut arena, MathPair::Power, &l, &r, None).unwrap();
1214        assert_eq!(out.phys, PhysType::Float64);
1215        assert_eq!(out.values::<f64>(), &[343.0, -343.0, 64.0]);
1216
1217        let base = ints(&mut arena, &[2, 2, 2]);
1218        let of = ints(&mut arena, &[8, 4, 1]);
1219        let out = pair(&mut arena, MathPair::Log, &base, &of, None).unwrap();
1220        assert_eq!(out.values::<f64>(), &[3.0, 2.0, 0.0]);
1221    }
1222
1223    /// The remainder of an approximate number keeps the sign of the
1224    /// dividend, which is what the operator answers and so what the
1225    /// function has to.
1226    #[test]
1227    fn an_approximate_remainder_keeps_the_sign_of_the_dividend() {
1228        let mut arena = MorselArena::new();
1229        let l = floats(&mut arena, &[7.5, -7.5]);
1230        let r = floats(&mut arena, &[2.0, 2.0]);
1231        let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
1232        assert_eq!(out.values::<f64>(), &[1.5, -1.5]);
1233    }
1234
1235    /// A divisor of nought has no remainder, whichever type the two
1236    /// sides hold, and the one pair of whole numbers whose remainder
1237    /// does not fit says so as the function rather than as the
1238    /// operator.
1239    #[test]
1240    fn a_remainder_with_no_answer_raises() {
1241        let mut arena = MorselArena::new();
1242        let l = ints(&mut arena, &[7, 1]);
1243        let r = ints(&mut arena, &[3, 0]);
1244        assert_eq!(
1245            raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
1246            "22012: division by zero"
1247        );
1248
1249        let l = floats(&mut arena, &[7.0, 1.0]);
1250        let r = floats(&mut arena, &[3.0, 0.0]);
1251        assert_eq!(
1252            raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
1253            "22012: division by zero"
1254        );
1255
1256        let l = ints(&mut arena, &[i64::MIN]);
1257        let r = ints(&mut arena, &[-1]);
1258        assert_eq!(
1259            raised(pair(&mut arena, MathPair::Mod, &l, &r, None)),
1260            "22003: mod() of -9223372036854775808 and -1 does not fit an integer"
1261        );
1262    }
1263
1264    /// Nought to a negative power and a negative number to a fraction
1265    /// are the two the standard names, and both of them are conditions
1266    /// about the pair rather than about either column.
1267    #[test]
1268    fn a_power_with_no_answer_raises() {
1269        let mut arena = MorselArena::new();
1270        let l = floats(&mut arena, &[2.0, 0.0]);
1271        let r = floats(&mut arena, &[3.0, -1.0]);
1272        assert_eq!(
1273            raised(pair(&mut arena, MathPair::Power, &l, &r, None)),
1274            "2201F: power() has no answer for nought raised to a negative power"
1275        );
1276
1277        let l = floats(&mut arena, &[2.0, -2.0]);
1278        let r = floats(&mut arena, &[3.0, 0.5]);
1279        assert_eq!(
1280            raised(pair(&mut arena, MathPair::Power, &l, &r, None)),
1281            "2201F: power() has no answer for -2 raised to 0.5, which is not whole"
1282        );
1283
1284        // A negative number to a whole power has an answer, so the
1285        // fold that let the walk happen must not be the answer itself.
1286        let l = floats(&mut arena, &[-2.0]);
1287        let r = floats(&mut arena, &[3.0]);
1288        let out = pair(&mut arena, MathPair::Power, &l, &r, None).unwrap();
1289        assert_eq!(out.values::<f64>(), &[-8.0]);
1290    }
1291
1292    /// A base is a base when it is above nought and is not one, and the
1293    /// number a logarithm is taken of has to be above nought as well.
1294    #[test]
1295    fn a_logarithm_outside_its_domain_raises() {
1296        let mut arena = MorselArena::new();
1297        let base = floats(&mut arena, &[2.0, 1.0]);
1298        let of = floats(&mut arena, &[8.0, 8.0]);
1299        assert_eq!(
1300            raised(pair(&mut arena, MathPair::Log, &base, &of, None)),
1301            "2201E: log() has no answer in base 1"
1302        );
1303
1304        let base = floats(&mut arena, &[2.0, 2.0]);
1305        let of = floats(&mut arena, &[8.0, 0.0]);
1306        assert_eq!(
1307            raised(pair(&mut arena, MathPair::Log, &base, &of, None)),
1308            "2201E: log() has no answer for 0, which is not above nought"
1309        );
1310    }
1311
1312    /// An answer that left the range of a float is an infinity sitting
1313    /// in the output, which is the fold the power has and the reason
1314    /// this kernel computes first and reads the conditions after.
1315    #[test]
1316    fn a_power_past_the_top_of_a_float_raises() {
1317        let mut arena = MorselArena::new();
1318        let l = floats(&mut arena, &[1.0e300]);
1319        let r = floats(&mut arena, &[2.0]);
1320        assert!(
1321            raised(pair(&mut arena, MathPair::Power, &l, &r, None))
1322                .starts_with("22003: power() of "),
1323        );
1324    }
1325
1326    /// A row the selection dropped and a row holding a null are not
1327    /// conditions, which is what lets one of these stand in a filter.
1328    #[test]
1329    fn a_pair_skips_what_nobody_asked_about() {
1330        let mut arena = MorselArena::new();
1331        let l = ints(&mut arena, &[7, 1, 9]);
1332        let r = ints(&mut arena, &[3, 0, 2]);
1333        let mut sel = SelVector::with_capacity(&mut arena, 2);
1334        sel.push(0);
1335        sel.push(2);
1336        let out = pair(&mut arena, MathPair::Mod, &l, &r, Some(&sel)).unwrap();
1337        assert_eq!(out.values::<i64>()[0], 1);
1338        assert_eq!(out.values::<i64>()[2], 1);
1339
1340        let mut r = ints(&mut arena, &[3, 0, 2]);
1341        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1342        valid.clear(1);
1343        r.validity = Some(valid);
1344        let out = pair(&mut arena, MathPair::Mod, &l, &r, None).unwrap();
1345        assert!(!out.is_valid(1), "null in, null out");
1346        assert!(out.is_valid(0) && out.is_valid(2));
1347    }
1348
1349    /// Two arguments of two types are not this kernel's, the compiler
1350    /// having moved a written number into the column's type before it
1351    /// gets here.
1352    #[test]
1353    fn the_two_arguments_hold_the_one_type() {
1354        assert_eq!(
1355            MathPair::Mod.answer_type(PhysType::Int64, PhysType::Int64),
1356            Some(PhysType::Int64)
1357        );
1358        assert_eq!(
1359            MathPair::Power.answer_type(PhysType::Int64, PhysType::Int64),
1360            Some(PhysType::Float64)
1361        );
1362        assert_eq!(
1363            MathPair::Mod.answer_type(PhysType::Int64, PhysType::Float64),
1364            None
1365        );
1366        assert_eq!(
1367            MathPair::Log.answer_type(PhysType::Str, PhysType::Str),
1368            None
1369        );
1370    }
1371
1372    /// The approximate half is written twice, once as the chunk the
1373    /// kernel fills and once as the single answer the walk reads, and
1374    /// the two have to agree for every function or a statement can tell
1375    /// which path it took. This runs all eighteen through both, over an
1376    /// approximate column and a whole one, on arguments every one of
1377    /// them has an answer for.
1378    #[test]
1379    fn every_function_fills_what_one_row_answers() {
1380        const OPS: [MathOp; 18] = [
1381            MathOp::Abs,
1382            MathOp::Ceil,
1383            MathOp::Floor,
1384            MathOp::Round(0),
1385            MathOp::Round(2),
1386            MathOp::Sqrt,
1387            MathOp::Exp,
1388            MathOp::Ln,
1389            MathOp::Log10,
1390            MathOp::Sin,
1391            MathOp::Cos,
1392            MathOp::Tan,
1393            MathOp::Cot,
1394            MathOp::Asin,
1395            MathOp::Acos,
1396            MathOp::Atan,
1397            MathOp::Degrees,
1398            MathOp::Radians,
1399        ];
1400        let reals: [f64; 3] = [0.25, 0.5, 1.0];
1401        // One is the only whole number all eighteen have an answer for,
1402        // an inverse sine having none above it and a logarithm none at
1403        // nought, so the whole column carries the conversion rather
1404        // than the spread and the approximate column above carries the
1405        // spread.
1406        let wholes: [i64; 3] = [1, 1, 1];
1407        let mut arena = MorselArena::new();
1408        for op in OPS {
1409            let v = floats(&mut arena, &reals);
1410            let out = unary(&mut arena, op, &v, None).unwrap();
1411            for (i, x) in reals.iter().enumerate() {
1412                assert_eq!(out.values::<f64>()[i], real(op, *x), "{op:?} on {x}");
1413            }
1414            // Every one of these is real over a whole number too, bar
1415            // the four the exact half keeps exact, and those answer an
1416            // integer rather than going through here at all.
1417            if !matches!(
1418                op,
1419                MathOp::Abs | MathOp::Ceil | MathOp::Floor | MathOp::Round(_)
1420            ) {
1421                let v = ints(&mut arena, &wholes);
1422                let out = unary(&mut arena, op, &v, None).unwrap();
1423                for (i, x) in wholes.iter().enumerate() {
1424                    let want = real(op, *x as f64);
1425                    assert_eq!(out.values::<f64>()[i], want, "{op:?} on the whole {x}");
1426                }
1427            }
1428            // A column of one repeated value takes the constant arm,
1429            // which is the shape a pinned argument arrives in.
1430            let c = ValueVector::constant(&mut arena, PhysType::Float64, 0.5f64, 3);
1431            let out = unary(&mut arena, op, &c, None).unwrap();
1432            assert_eq!(
1433                out.values::<f64>()[2],
1434                real(op, 0.5),
1435                "{op:?} on a constant"
1436            );
1437        }
1438    }
1439}