1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::cmp::PartialOrd;
use toasty_core::stmt::{self, BinaryOp, Expr};
/// Cheap canonicalization for binary ops: constant folding, null
/// propagation, boolean-constant simplification, literal-on-right swap.
///
/// Heavyweight rules (self-comparison with field nullability, tuple
/// decomposition, match elimination, derived-column null check, relation
/// path lifting) live in `simplify/expr_binary_op.rs` and run after this
/// fold pass on canonical input.
pub(super) fn fold_expr_binary_op(op: BinaryOp, lhs: &mut Expr, rhs: &mut Expr) -> Option<Expr> {
match (&mut *lhs, &mut *rhs) {
// Constant folding and null propagation:
//
// - `5 = 5` → `true`
// - `1 < 5` → `true`
// - `"a" >= "b"` → `false`
// - `null <op> x` → `null`
// - `x <op> null` → `null`
(Expr::Value(lhs_val), Expr::Value(rhs_val)) => {
if lhs_val.is_null() || rhs_val.is_null() {
return Some(Expr::null());
}
match op {
BinaryOp::Eq => Some((*lhs_val == *rhs_val).into()),
BinaryOp::Ne => Some((*lhs_val != *rhs_val).into()),
BinaryOp::Lt => {
PartialOrd::partial_cmp(&*lhs_val, &*rhs_val).map(|o| o.is_lt().into())
}
BinaryOp::Le => {
PartialOrd::partial_cmp(&*lhs_val, &*rhs_val).map(|o| o.is_le().into())
}
BinaryOp::Gt => {
PartialOrd::partial_cmp(&*lhs_val, &*rhs_val).map(|o| o.is_gt().into())
}
BinaryOp::Ge => {
PartialOrd::partial_cmp(&*lhs_val, &*rhs_val).map(|o| o.is_ge().into())
}
BinaryOp::Add => lhs_val.checked_add(rhs_val).map(Expr::from),
BinaryOp::Sub => lhs_val.checked_sub(rhs_val).map(Expr::from),
}
}
// Boolean constant comparisons:
//
// - `x = true` → `x`
// - `x = false` → `not(x)`
// - `x != true` → `not(x)`
// - `x != false` → `x`
(expr, Expr::Value(stmt::Value::Bool(b))) | (Expr::Value(stmt::Value::Bool(b)), expr)
if op.is_eq() || op.is_ne() =>
{
let is_eq_true = (op.is_eq() && *b) || (op.is_ne() && !*b);
if is_eq_true {
Some(expr.take())
} else {
Some(Expr::not(expr.take()))
}
}
// Null propagation: `expr <op> null` → `null` (and symmetric).
// SQL three-valued logic: any comparison with NULL yields NULL.
(_, Expr::Value(stmt::Value::Null)) | (Expr::Value(stmt::Value::Null), _) => {
Some(Expr::null())
}
// Canonicalization, `literal <op> col` → `col <op_commuted> literal`.
// Heavyweight rules can then assume the literal (when present) is on
// the right. Non-commutative ops (e.g. `Sub`) are left in place.
(Expr::Value(_), rhs) if !rhs.is_value() => {
let commuted = op.commute()?;
std::mem::swap(lhs, rhs);
Some(Expr::binary_op(lhs.take(), commuted, rhs.take()))
}
_ => None,
}
}