1use 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#[derive(Debug, Clone)]
52pub struct CompiledPredicate {
53 text: String,
54 tree: Predicate,
55 bare: Vec<std::ops::Range<usize>>,
58}
59
60#[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 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 pub fn text(&self) -> &str {
98 &self.text
99 }
100
101 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 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 let none = std::cell::Cell::new(false);
198 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
222fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum ValueKind {
254 Int,
256 Float,
258 Str,
260 Bool,
262}
263
264impl CompiledPredicate {
265 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
284fn 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 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
356fn has_truth(kind: ValueKind) -> bool {
358 kind != ValueKind::Str
359}
360
361pub 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
389fn 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
412fn 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
433fn 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 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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}