Skip to main content

polydat_core/iteration/comprehension/predicate/
eval.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Evaluating a comprehension's `where` predicate against a tuple.
5//!
6//! A [`CompiledPredicate`] parses the predicate once
7//! ([`parse_predicate`]) and tests each tuple against the tree. `||`,
8//! `&&`, `!`, the comparisons, and membership evaluate directly over
9//! the tuple's values. `&&` and `||` evaluate their operands left to
10//! right and stop at the first that decides the result, so filters
11//! folded into one conjunction (R6) evaluate exactly what the chain
12//! did; `!` negates its operand's truth. A
13//! `{name}` the tuple does not bind resolves in the scope the tuple was
14//! drawn in. Any other expression (arithmetic, a function call, a cast)
15//! is interpolated against the tuple over that scope and evaluated as a
16//! Polydat expression, charged to the scope's ledger. In it a
17//! placeholder that is a whole operand, such as a call argument, reads
18//! its value with its type, so `regex_match({size}, "^1m$")` tests the
19//! string `size` is bound to; a placeholder that is part of a larger
20//! token or inside a quoted string substitutes text
21//! (comprehension_forms.md §3.1.5).
22//!
23//! Values compare as scalars: integers and floats compare numerically
24//! with each other, strings and booleans with their own kind, and a
25//! value of one kind is never equal to a value of another, so
26//! `"s0" != 2` holds. Ordering values of different kinds is an error.
27//! A string is quoted; a bare word is a name, and a predicate has no
28//! names beside its elements. A predicate that does not parse is
29//! evaluated whole as a Polydat expression. The value a predicate
30//! yields is true when it is `true` or a non-zero number.
31//!
32//! None propagates (none_semantics.md Rule 1, comprehension_forms.md
33//! §10.9.1). An element the tuple binds to None, and a name that
34//! neither the tuple nor the scope binds, reads None, and so does a
35//! bare word. A comparison, a membership test, a negation, and an
36//! expression that reads None are None; `&&` and `||` stop at an
37//! operand that is None, and are None. A predicate whose value is None
38//! keeps no tuple.
39
40use crate::ast::Value;
41use crate::dsl::compile::eval_const_expr_for;
42use crate::iteration::comprehension::ast::Comprehension;
43use crate::iteration::comprehension::runtime::{RuntimeError, RuntimeTuple};
44use crate::iteration::comprehension::source::{LiteralValue, Source};
45use crate::kernel::interp::{Layered, Lookup, interpolate_operands};
46use polydat_grammar::comprehension::predicate::{
47    Comparison, Predicate, PredicateKind, PredicateLiteral, parse_predicate, predicate_reads,
48};
49
50/// A predicate parsed once, testing tuples.
51#[derive(Debug, Clone)]
52pub struct CompiledPredicate {
53    text: String,
54    tree: Predicate,
55    /// The spans of the expressions evaluated through the language that
56    /// read a bare word, which reads None, so each of them is None.
57    bare: Vec<std::ops::Range<usize>>,
58}
59
60/// A value a predicate compares.
61#[derive(Debug, Clone, PartialEq)]
62enum Scalar {
63    Int(i128),
64    Float(f64),
65    Str(String),
66    Bool(bool),
67}
68
69impl std::fmt::Display for Scalar {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Scalar::Int(n) => write!(f, "{n}"),
73            Scalar::Float(x) => write!(f, "{x}"),
74            Scalar::Str(s) => write!(f, "{s:?}"),
75            Scalar::Bool(b) => write!(f, "{b}"),
76        }
77    }
78}
79
80impl CompiledPredicate {
81    /// Parse `text`.
82    pub fn new(text: &str) -> Self {
83        let tree = parse_predicate(text).unwrap_or(Predicate {
84            kind: PredicateKind::Expr,
85            span: 0..text.len(),
86        });
87        let mut bare = Vec::new();
88        collect_bare(&tree, text, &mut bare);
89        Self {
90            text: text.to_string(),
91            tree,
92            bare,
93        }
94    }
95
96    /// The predicate as written.
97    pub fn text(&self) -> &str {
98        &self.text
99    }
100
101    /// Whether `tuple`, drawn in `scope`, passes: the predicate's value
102    /// is true. A predicate whose value is None keeps no tuple.
103    pub fn keeps(&self, tuple: &RuntimeTuple, scope: &dyn Lookup) -> Result<bool, RuntimeError> {
104        self.eval(&self.tree, tuple, scope)
105            .and_then(|v| v.map_or(Ok(false), |v| truth(&v)))
106            .map_err(|message| RuntimeError::FilterEval {
107                predicate: self.text.clone(),
108                message,
109            })
110    }
111
112    /// The value of `node` over `tuple`, `None` when it is None.
113    fn eval(
114        &self,
115        node: &Predicate,
116        tuple: &RuntimeTuple,
117        scope: &dyn Lookup,
118    ) -> Result<Option<Scalar>, String> {
119        Ok(Some(match &node.kind {
120            PredicateKind::Or(parts) => {
121                for part in parts {
122                    let Some(value) = self.eval(part, tuple, scope)? else {
123                        return Ok(None);
124                    };
125                    if truth(&value)? {
126                        return Ok(Some(Scalar::Bool(true)));
127                    }
128                }
129                Scalar::Bool(false)
130            }
131            PredicateKind::And(parts) => {
132                for part in parts {
133                    let Some(value) = self.eval(part, tuple, scope)? else {
134                        return Ok(None);
135                    };
136                    if !truth(&value)? {
137                        return Ok(Some(Scalar::Bool(false)));
138                    }
139                }
140                Scalar::Bool(true)
141            }
142            PredicateKind::Not(inner) => {
143                let Some(value) = self.eval(inner, tuple, scope)? else {
144                    return Ok(None);
145                };
146                Scalar::Bool(!truth(&value)?)
147            }
148            PredicateKind::Compare(op, a, b) => {
149                let Some(a) = self.eval(a, tuple, scope)? else {
150                    return Ok(None);
151                };
152                let Some(b) = self.eval(b, tuple, scope)? else {
153                    return Ok(None);
154                };
155                Scalar::Bool(compare(*op, &a, &b)?)
156            }
157            PredicateKind::In(needle, items) => {
158                let Some(needle) = self.eval(needle, tuple, scope)? else {
159                    return Ok(None);
160                };
161                let mut hit = false;
162                for item in items {
163                    let Some(item) = self.eval(item, tuple, scope)? else {
164                        return Ok(None);
165                    };
166                    hit |= scalar_eq(&needle, &item);
167                }
168                Scalar::Bool(hit)
169            }
170            PredicateKind::Element(name) => {
171                let value = match tuple.iter().find(|(n, _)| n == name) {
172                    Some((_, v)) => Some(v.clone()),
173                    None => scope.lookup(name),
174                };
175                match value {
176                    None | Some(Value::None) => return Ok(None),
177                    Some(value) => scalar(&value)
178                        .ok_or_else(|| format!("`{{{name}}}` is {value:?}, not a scalar"))?,
179                }
180            }
181            PredicateKind::Literal(literal) => match literal {
182                PredicateLiteral::Int(n) => Scalar::Int(*n),
183                PredicateLiteral::Float(f) => Scalar::Float(*f),
184                PredicateLiteral::Str(s) => Scalar::Str(s.clone()),
185                PredicateLiteral::Bool(b) => Scalar::Bool(*b),
186            },
187            PredicateKind::Arith(..) | PredicateKind::Expr => {
188                if self.bare.contains(&node.span) {
189                    return Ok(None);
190                }
191                let text = node.text(&self.text);
192                let layered = Layered {
193                    prefix: tuple,
194                    inner: scope,
195                };
196                // Interpolating None yields None (Rule 1).
197                let none = std::cell::Cell::new(false);
198                // A placeholder that is a whole operand, such as a call
199                // argument, is written as the value it reads, so a
200                // string stays a string (comprehension_forms.md §3.1.5).
201                let interpolated = interpolate_operands(text, |name| match layered.lookup(name) {
202                    None | Some(Value::None) => {
203                        none.set(true);
204                        None
205                    }
206                    Some(value) => Some(value),
207                });
208                if none.get() {
209                    return Ok(None);
210                }
211                let value = eval_const_expr_for(&interpolated?, scope.ledger())
212                    .map_err(|e| e.to_string())?;
213                if matches!(value, Value::None) {
214                    return Ok(None);
215                }
216                scalar(&value).ok_or_else(|| format!("`{text}` is {value:?}, not a scalar"))?
217            }
218        }))
219    }
220}
221
222/// The spans of the expressions under `node` that the evaluator hands to
223/// the language and that read a bare word.
224fn collect_bare(node: &Predicate, text: &str, out: &mut Vec<std::ops::Range<usize>>) {
225    match &node.kind {
226        PredicateKind::Or(parts) | PredicateKind::And(parts) => {
227            for part in parts {
228                collect_bare(part, text, out);
229            }
230        }
231        PredicateKind::Not(inner) => collect_bare(inner, text, out),
232        PredicateKind::Compare(_, a, b) => {
233            collect_bare(a, text, out);
234            collect_bare(b, text, out);
235        }
236        PredicateKind::In(needle, items) => {
237            collect_bare(needle, text, out);
238            for item in items {
239                collect_bare(item, text, out);
240            }
241        }
242        PredicateKind::Element(_) | PredicateKind::Literal(_) => {}
243        PredicateKind::Arith(..) | PredicateKind::Expr => {
244            if !predicate_reads(node.text(text)).bare.is_empty() {
245                out.push(node.span.clone());
246            }
247        }
248    }
249}
250
251/// The kind every value of an element has, as its source declares it.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum ValueKind {
254    /// Unsigned integers: a range, or a list of integers.
255    Int,
256    /// Floats: a list of floats, or a continuous interval.
257    Float,
258    /// Strings.
259    Str,
260    /// Booleans.
261    Bool,
262}
263
264impl CompiledPredicate {
265    /// Whether no evaluation of the predicate can fail over tuples whose
266    /// elements have the kinds `kind_of` gives, `None` for an element of
267    /// unknown or mixed kind (comprehension_forms.md §10.2 R5).
268    ///
269    /// The answer is read off the predicate's tree. `||`, `&&`, and `!`
270    /// are total over operands that are total and have a truth value (a
271    /// boolean or a number, never a string). `==`, `!=`, and membership
272    /// are total over total operands, since values of different kinds
273    /// are unequal; an ordering comparison is total only when both sides
274    /// are numbers, both strings, or both booleans. Arithmetic is total
275    /// over numeric operands, dividing only by a non-zero constant. An
276    /// element is total when its kind is known, a literal always is, and
277    /// any other expression (a function call, a cast, a bitwise
278    /// operator) can fail.
279    pub fn is_total(&self, kind_of: &dyn Fn(&str) -> Option<ValueKind>) -> bool {
280        total_kind(&self.tree, kind_of).is_some_and(has_truth)
281    }
282}
283
284/// The kind of value `node` yields when no evaluation of it can fail,
285/// or `None` when one can.
286fn total_kind(node: &Predicate, kind_of: &dyn Fn(&str) -> Option<ValueKind>) -> Option<ValueKind> {
287    use polydat_grammar::ast::BinOpKind;
288    let truthful = |p: &Predicate| total_kind(p, kind_of).is_some_and(has_truth);
289    match &node.kind {
290        PredicateKind::Or(parts) | PredicateKind::And(parts) => {
291            parts.iter().all(truthful).then_some(ValueKind::Bool)
292        }
293        PredicateKind::Not(inner) => truthful(inner).then_some(ValueKind::Bool),
294        PredicateKind::Compare(op, a, b) => {
295            let (a, b) = (total_kind(a, kind_of)?, total_kind(b, kind_of)?);
296            let ordered = matches!(
297                (a, b),
298                (
299                    ValueKind::Int | ValueKind::Float,
300                    ValueKind::Int | ValueKind::Float
301                ) | (ValueKind::Str, ValueKind::Str)
302                    | (ValueKind::Bool, ValueKind::Bool)
303            );
304            (matches!(op, Comparison::Eq | Comparison::Ne) || ordered).then_some(ValueKind::Bool)
305        }
306        PredicateKind::In(needle, items) => {
307            total_kind(needle, kind_of)?;
308            for item in items {
309                total_kind(item, kind_of)?;
310            }
311            Some(ValueKind::Bool)
312        }
313        PredicateKind::Element(name) => kind_of(name),
314        PredicateKind::Literal(literal) => Some(match literal {
315            PredicateLiteral::Int(_) => ValueKind::Int,
316            PredicateLiteral::Float(_) => ValueKind::Float,
317            PredicateLiteral::Str(_) => ValueKind::Str,
318            PredicateLiteral::Bool(_) => ValueKind::Bool,
319        }),
320        PredicateKind::Arith(op, a, b) => {
321            // An operand is written into the expression's text, so a
322            // literal is one the language reads back as itself: a
323            // non-negative integer within `u64`, or a non-negative float.
324            let operand = |p: &Predicate| {
325                let fits = match &p.kind {
326                    PredicateKind::Literal(PredicateLiteral::Int(n)) => u64::try_from(*n).is_ok(),
327                    PredicateKind::Literal(PredicateLiteral::Float(f)) => *f >= 0.0,
328                    _ => true,
329                };
330                total_kind(p, kind_of)
331                    .filter(|k| fits && matches!(k, ValueKind::Int | ValueKind::Float))
332            };
333            let (ka, kb) = (operand(a)?, operand(b)?);
334            if matches!(op, BinOpKind::Div | BinOpKind::Mod) {
335                let non_zero_constant = match &b.kind {
336                    PredicateKind::Literal(PredicateLiteral::Int(n)) => *n != 0,
337                    PredicateKind::Literal(PredicateLiteral::Float(f)) => *f != 0.0,
338                    _ => false,
339                };
340                if !non_zero_constant {
341                    return None;
342                }
343            }
344            Some(
345                if ka == ValueKind::Int && kb == ValueKind::Int && *op != BinOpKind::Pow {
346                    ValueKind::Int
347                } else {
348                    ValueKind::Float
349                },
350            )
351        }
352        PredicateKind::Expr => None,
353    }
354}
355
356/// Whether a value of this kind has a truth value.
357fn has_truth(kind: ValueKind) -> bool {
358    kind != ValueKind::Str
359}
360
361/// The kind of every value `name` takes in `c`: the kind its clause's
362/// source declares, the same in every branch of a union, or `None` when
363/// a source's values are of unknown or mixed kind or `c` does not bind
364/// `name`.
365pub fn element_kind(c: &Comprehension, name: &str) -> Option<ValueKind> {
366    let mut kinds = Vec::new();
367    collect_kinds(c, name, &mut kinds);
368    let first = (*kinds.first()?)?;
369    kinds.iter().all(|k| *k == Some(first)).then_some(first)
370}
371
372fn collect_kinds(c: &Comprehension, name: &str, out: &mut Vec<Option<ValueKind>>) {
373    match c {
374        Comprehension::Clause { name: n, source } if n == name => out.push(source_kind(source)),
375        Comprehension::Clause { .. } => {}
376        Comprehension::Cartesian { children }
377        | Comprehension::Zip { children, .. }
378        | Comprehension::Union { children } => {
379            for child in children {
380                collect_kinds(child, name, out);
381            }
382        }
383        Comprehension::Filter { child, .. } | Comprehension::Order { child, .. } => {
384            collect_kinds(child, name, out);
385        }
386    }
387}
388
389/// The kind of every value `source` yields, when it declares one.
390fn source_kind(source: &Source) -> Option<ValueKind> {
391    match source {
392        Source::IntRange { .. } => Some(ValueKind::Int),
393        Source::ContinuousInterval { .. } | Source::Distribution { .. } => Some(ValueKind::Float),
394        Source::Literal { values } => {
395            let kind = |v: &LiteralValue| match v {
396                LiteralValue::Int(_) | LiteralValue::UInt(_) => Some(ValueKind::Int),
397                LiteralValue::Float(_) => Some(ValueKind::Float),
398                LiteralValue::String(_) => Some(ValueKind::Str),
399                LiteralValue::Bool(_) => Some(ValueKind::Bool),
400                LiteralValue::Json(_) => None,
401            };
402            let first = kind(values.first()?)?;
403            values
404                .iter()
405                .all(|v| kind(v) == Some(first))
406                .then_some(first)
407        }
408        Source::Generator { .. } | Source::WorkloadParamList { .. } => None,
409    }
410}
411
412/// The scalar a value carries; a JSON list's item compares as its own
413/// scalar.
414fn scalar(value: &Value) -> Option<Scalar> {
415    Some(match value {
416        Value::U64(n) => Scalar::Int(i128::from(*n)),
417        Value::I64(n) => Scalar::Int(i128::from(*n)),
418        Value::F64(f) => Scalar::Float(*f),
419        Value::Str(s) => Scalar::Str(s.to_string()),
420        Value::Bool(b) => Scalar::Bool(*b),
421        Value::Json(j) => match j.as_ref() {
422            serde_json::Value::Number(n) if n.is_i64() => Scalar::Int(i128::from(n.as_i64()?)),
423            serde_json::Value::Number(n) if n.is_u64() => Scalar::Int(i128::from(n.as_u64()?)),
424            serde_json::Value::Number(n) => Scalar::Float(n.as_f64()?),
425            serde_json::Value::String(s) => Scalar::Str(s.clone()),
426            serde_json::Value::Bool(b) => Scalar::Bool(*b),
427            _ => return None,
428        },
429        _ => return None,
430    })
431}
432
433/// A value's truth: `true`, or a non-zero number.
434fn truth(value: &Scalar) -> Result<bool, String> {
435    match value {
436        Scalar::Bool(b) => Ok(*b),
437        Scalar::Int(n) => Ok(*n != 0),
438        Scalar::Float(f) => Ok(*f != 0.0),
439        Scalar::Str(s) => Err(format!("expected bool/u64/f64, got {s:?}")),
440    }
441}
442
443fn scalar_eq(a: &Scalar, b: &Scalar) -> bool {
444    match (a, b) {
445        (Scalar::Int(x), Scalar::Float(y)) | (Scalar::Float(y), Scalar::Int(x)) => {
446            (*x as f64) == *y
447        }
448        _ => a == b,
449    }
450}
451
452fn compare(op: Comparison, a: &Scalar, b: &Scalar) -> Result<bool, String> {
453    use std::cmp::Ordering;
454    let ordering = match op {
455        Comparison::Eq => return Ok(scalar_eq(a, b)),
456        Comparison::Ne => return Ok(!scalar_eq(a, b)),
457        _ => match (a, b) {
458            (Scalar::Int(x), Scalar::Int(y)) => Some(x.cmp(y)),
459            (Scalar::Float(x), Scalar::Float(y)) => x.partial_cmp(y),
460            (Scalar::Int(x), Scalar::Float(y)) => (*x as f64).partial_cmp(y),
461            (Scalar::Float(x), Scalar::Int(y)) => x.partial_cmp(&(*y as f64)),
462            (Scalar::Str(x), Scalar::Str(y)) => Some(x.cmp(y)),
463            (Scalar::Bool(x), Scalar::Bool(y)) => Some(x.cmp(y)),
464            _ => return Err(format!("cannot order {a} and {b}")),
465        },
466    };
467    // A NaN is unordered: no ordering comparison holds.
468    Ok(ordering.is_some_and(|o| match op {
469        Comparison::Lt => o == Ordering::Less,
470        Comparison::Le => o != Ordering::Greater,
471        Comparison::Gt => o == Ordering::Greater,
472        _ => o != Ordering::Less,
473    }))
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479    use crate::kernel::interp::NoScope;
480    use std::sync::Arc;
481
482    fn tuple(bindings: &[(&str, Value)]) -> RuntimeTuple {
483        bindings
484            .iter()
485            .map(|(n, v)| ((*n).to_string(), v.clone()))
486            .collect()
487    }
488
489    fn keeps(predicate: &str, t: &RuntimeTuple) -> bool {
490        CompiledPredicate::new(predicate)
491            .keeps(t, &NoScope::new())
492            .unwrap()
493    }
494
495    /// `!` binds tighter than `&&` and `||`: `!{done} || {retry}` keeps
496    /// a tuple that is not done, and one that is done and retried.
497    #[test]
498    fn not_binds_tighter_than_or() {
499        for (done, retry, kept) in [
500            (false, false, true),
501            (false, true, true),
502            (true, false, false),
503            (true, true, true),
504        ] {
505            let t = tuple(&[("done", Value::Bool(done)), ("retry", Value::Bool(retry))]);
506            assert_eq!(keeps("!{done} || {retry}", &t), kept, "{done} {retry}");
507            assert_eq!(keeps("!({done} || {retry})", &t), !done && !retry);
508            assert_eq!(keeps("!{done} && {retry}", &t), !done && retry);
509        }
510    }
511
512    /// Each operator pair evaluates as the one precedence table groups
513    /// it, checked against the grouping written out, over every
514    /// assignment of three booleans and small integers.
515    #[test]
516    fn every_operator_pair_evaluates_as_grouped() {
517        let pairs = [
518            ("{a} || {b} && {c}", "{a} || ({b} && {c})"),
519            ("{a} && {b} || {c}", "({a} && {b}) || {c}"),
520            ("!{a} || {b}", "(!{a}) || {b}"),
521            ("!{a} && {b}", "(!{a}) && {b}"),
522            ("{a} == {b} || {c}", "({a} == {b}) || {c}"),
523            ("{a} || {b} == {c}", "{a} || ({b} == {c})"),
524            ("{a} != {b} && {c}", "({a} != {b}) && {c}"),
525            (
526                "{x} < 2 || {y} >= 1 && {a}",
527                "({x} < 2) || (({y} >= 1) && {a})",
528            ),
529            ("{x} + 1 > {y} + {y}", "({x} + 1) > ({y} + {y})"),
530            (
531                "{x} + {x} == {y} + 1 || {c}",
532                "(({x} + {x}) == ({y} + 1)) || {c}",
533            ),
534            ("{x} < {y} == {a}", "({x} < {y}) == {a}"),
535            ("{x} in [0, 2] || {a}", "({x} in [0, 2]) || {a}"),
536            ("!{a} == {b}", "(!{a}) == {b}"),
537        ];
538        for bits in 0..8u8 {
539            for x in 0..3u64 {
540                for y in 0..3u64 {
541                    let t = tuple(&[
542                        ("a", Value::Bool(bits & 1 != 0)),
543                        ("b", Value::Bool(bits & 2 != 0)),
544                        ("c", Value::Bool(bits & 4 != 0)),
545                        ("x", Value::U64(x)),
546                        ("y", Value::U64(y)),
547                    ]);
548                    for (bare, grouped) in pairs {
549                        assert_eq!(keeps(bare, &t), keeps(grouped, &t), "{bare} at {t:?}");
550                    }
551                }
552            }
553        }
554    }
555
556    /// Totality is read off the tree against the elements' kinds: what
557    /// can fail is an ordering of unlike kinds, the truth of a string,
558    /// arithmetic over a string or a negative literal, division by
559    /// anything but a non-zero constant, an element of unknown kind, and
560    /// any call or cast. (The integration suite evaluates each total
561    /// predicate here over values of its kinds, with the node library
562    /// that arithmetic calls into.)
563    #[test]
564    fn totality_is_read_off_the_tree() {
565        let kind_of = |name: &str| match name {
566            "k" | "m" => Some(ValueKind::Int),
567            "x" => Some(ValueKind::Float),
568            "w" => Some(ValueKind::Str),
569            "b" => Some(ValueKind::Bool),
570            _ => None,
571        };
572        let total = [
573            "{k} > 1",
574            "{k} < {x}",
575            "{w} == 2",
576            "{w} != {k} && {b}",
577            "{w} >= \"m\" || !{b}",
578            "{k} in [1, \"a\", true]",
579            "{k} * 2 + 1 > {m}",
580            "{k} - {m} >= 0",
581            "{k} / 2 == 1",
582            "{x} % 1.5 < 1",
583            "{k} ** 2 > {x}",
584            "{k} + 1",
585            "{x}",
586        ];
587        let partial = [
588            "{w} > 2",
589            "{b} < 1",
590            "{w}",
591            "{w} && {b}",
592            "{k} / {m} == 1",
593            "{k} % 0 == 1",
594            "{w} + 1 > 2",
595            "{k} + -1 > 2",
596            "{z} > 1",
597            "u64_add({k}, 1) > 2",
598            "{x} as u64 > 2",
599            "{k} & 1 == 1",
600        ];
601        for p in total {
602            assert!(CompiledPredicate::new(p).is_total(&kind_of), "{p}");
603        }
604        for p in partial {
605            assert!(!CompiledPredicate::new(p).is_total(&kind_of), "{p}");
606        }
607    }
608
609    /// A string is quoted. A bare word is a name, which nothing binds, so
610    /// it reads None and the predicate keeps no tuple, a hyphenated one
611    /// (a subtraction of names) included. An unknown function is still
612    /// an error.
613    #[test]
614    fn a_bare_word_is_a_name_that_reads_none() {
615        let t = tuple(&[("region", Value::Str(Arc::from("us-east")))]);
616        assert!(keeps("{region} == \"us-east\"", &t));
617        for predicate in [
618            "{region} == us-east",
619            "{region} in [us-west, \"us-east\"]",
620            "{region} != eu",
621            "!({region} != eu)",
622            "u64_add(1, width) > 0",
623        ] {
624            assert!(!keeps(predicate, &t), "{predicate}");
625        }
626        let error = CompiledPredicate::new("nosuch({region}) > 1")
627            .keeps(&t, &NoScope::new())
628            .unwrap_err()
629            .to_string();
630        assert!(error.contains("nosuch"), "{error}");
631    }
632
633    /// Values of different kinds are unequal, and ordering them is an
634    /// error naming both.
635    #[test]
636    fn mixed_kinds_are_unequal_and_unordered() {
637        let t = tuple(&[("c", Value::Str(Arc::from("s0")))]);
638        assert!(keeps("{c} != 2", &t));
639        assert!(!keeps("{c} == 2", &t));
640        assert!(keeps("{c} == \"s0\"", &t));
641        assert!(keeps("{c} == 's0'", &t));
642        // An operand after the one that decides is not evaluated.
643        assert!(!keeps("{c} == 2 && {c} > 2", &t));
644        assert!(keeps("{c} != 2 || {c} > 2", &t));
645        let error = CompiledPredicate::new("{c} > 2")
646            .keeps(&t, &NoScope::new())
647            .unwrap_err();
648        assert!(
649            error.to_string().contains("cannot order \"s0\" and 2"),
650            "{error}"
651        );
652    }
653
654    /// A function call evaluates as a Polydat expression over the tuple.
655    #[test]
656    fn a_call_evaluates_through_the_kernel() {
657        let t = tuple(&[("a", Value::U64(3)), ("b", Value::U64(5))]);
658        assert!(keeps("u64_add({a}, {b}) > 7", &t));
659        assert!(!keeps("u64_add({a}, {b}) > 8", &t));
660        assert!(keeps("!(u64_add({a}, {b}) > 8)", &t));
661    }
662
663    /// An element nothing binds and an element bound to None read None
664    /// (none_semantics.md Rule 1): every operator over None is None, and
665    /// a predicate whose value is None keeps no tuple. `&&` and `||`
666    /// stop at the first operand that decides them, so an operand after
667    /// it is not read, and at an operand that is None.
668    #[test]
669    fn none_propagates_and_keeps_no_tuple() {
670        let unbound = tuple(&[("k", Value::U64(1))]);
671        let bound_none = tuple(&[("k", Value::U64(1)), ("z", Value::None)]);
672        for t in [&unbound, &bound_none] {
673            for predicate in [
674                "{z} > 1",
675                "{z} != 1",
676                "!({z} == 1)",
677                "{z} in [1, 2]",
678                "{k} in [{z}, 1]",
679                "{z} + 1 > 0",
680                "u64_add({z}, 1) > 0",
681                "{z} > 1 || {k} == 1",
682                "{k} == 1 && {z} != 1",
683                "{k} == 1 && !({z} > 1)",
684            ] {
685                assert!(!keeps(predicate, t), "{predicate} over {t:?}");
686            }
687            assert!(keeps("{k} == 1 || {z} > 1", t));
688            assert!(!keeps("{k} == 2 && {z} > 1", t));
689        }
690    }
691}