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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use super::{Simplify, dedup_operands, has_complement};
use std::mem;
use toasty_core::stmt::{self, BinaryOp, Expr};
impl Simplify<'_> {
/// Heavyweight AND rewrites. Cheap canonicalization (flatten, drop unit
/// literals, null propagation, single/empty collapse on canonical input)
/// runs in `fold::expr_and` before this is reached.
pub(super) fn simplify_expr_and(&mut self, expr: &mut stmt::ExprAnd) -> Option<stmt::Expr> {
self.merge_in_subqueries(&mut expr.operands);
dedup_operands(&mut expr.operands);
// Absorption law, `x and (x or y)` → `x`
// If an operand is an OR that contains another operand of the AND, remove the OR.
let non_or_operands: Vec<_> = expr
.operands
.iter()
.filter(|op| !matches!(op, stmt::Expr::Or(_)))
.cloned()
.collect();
expr.operands.retain(|operand| {
if let stmt::Expr::Or(or_expr) = operand {
// Remove this OR if any of its operands appears as a direct operand of the AND
!or_expr
.operands
.iter()
.any(|op| non_or_operands.iter().any(|e| e.is_equivalent_to(op)))
} else {
true
}
});
// Complement law, `a and not(a)` → `false` (only if `a` is non-nullable)
if has_complement(&expr.operands) {
return Some(false.into());
}
// Range to equality: `a >= c and a <= c` → `a = c`
self.try_range_to_equality(expr);
// Contradicting equality: `a == 1 AND a == 2` → false,
// `a == 1 AND a != 1` → false
if has_self_contradiction(&expr.operands) {
return Some(false.into());
}
// OR branch pruning: `AND(x == 1, OR(AND(x != 1, b), ...))` → prune
// branches whose eq/ne constraints contradict the outer AND constraints.
if let Some(result) = prune_or_branches(expr) {
return Some(result);
}
if expr.operands.is_empty() {
Some(true.into())
} else if expr.operands.len() == 1 {
Some(expr.operands.remove(0))
} else {
None
}
}
/// Finds pairs of range comparisons that collapse to equality.
///
/// `a >= c and a <= c` → `a = c`
///
/// When a pair is found, all other bounds on the same (lhs, rhs) are also
/// removed since equality implies them.
///
/// NOTE: This assumes comparisons are already canonicalized with literals
/// on the right-hand side (e.g., `a >= 5` not `5 <= a`).
fn try_range_to_equality(&mut self, expr: &mut stmt::ExprAnd) {
for i in 0..expr.operands.len() {
let Expr::BinaryOp(op_i) = &expr.operands[i] else {
continue;
};
if !matches!(op_i.op, BinaryOp::Ge | BinaryOp::Le) {
continue;
}
for j in (i + 1)..expr.operands.len() {
let Expr::BinaryOp(op_j) = &expr.operands[j] else {
continue;
};
if !matches!(
(op_i.op, op_j.op),
(BinaryOp::Ge, BinaryOp::Le) | (BinaryOp::Le, BinaryOp::Ge)
) {
continue;
}
if op_i.lhs.is_equivalent_to(&op_j.lhs) && op_i.rhs.is_equivalent_to(&op_j.rhs) {
let lhs = op_i.lhs.clone();
let rhs = op_i.rhs.clone();
// Replace the first operand with equality
expr.operands[i] = Expr::eq(lhs.as_ref().clone(), rhs.as_ref().clone());
// Mark all other `Ge`/`Le` bounds on the same (lhs, rhs)
// for removal
for k in (i + 1)..expr.operands.len() {
if let Expr::BinaryOp(op_k) = &expr.operands[k]
&& matches!(op_k.op, BinaryOp::Ge | BinaryOp::Le)
&& op_k.lhs.is_equivalent_to(&lhs)
&& op_k.rhs.is_equivalent_to(&rhs)
{
expr.operands[k] = true.into();
}
}
break;
}
}
}
expr.operands.retain(|e| !e.is_true());
}
}
/// Checks for contradicting equality constraints within a single operand
/// list: `a == 1 AND a == 2` → true, `a == 1 AND a != 1` → true.
fn has_self_contradiction(operands: &[Expr]) -> bool {
for i in 0..operands.len() {
if is_contradicting_eq_constraints(&operands[i..=i], &operands[i + 1..]) {
return true;
}
}
false
}
/// Prunes OR branches whose eq/ne constraints contradict the outer AND's
/// non-OR constraints. Returns `Some(false)` if pruning produces a false
/// operand; otherwise mutates `expr` in place and returns `None`.
fn prune_or_branches(expr: &mut stmt::ExprAnd) -> Option<Expr> {
// Separate OR operands from non-OR constraints.
let mut or_operands: Vec<Expr> = Vec::new();
for op in mem::take(&mut expr.operands) {
if matches!(&op, Expr::Or(_)) {
or_operands.push(op);
} else {
expr.operands.push(op);
}
}
if or_operands.is_empty() {
return None;
}
// Prune OR branches that contradict the outer constraints.
for or_op in &mut or_operands {
let Expr::Or(or_expr) = or_op else {
unreachable!()
};
or_expr.operands.retain(|branch| {
let branch_ops: &[Expr] = match branch {
Expr::And(and) => &and.operands,
other => std::slice::from_ref(other),
};
!is_contradicting_eq_constraints(&expr.operands, branch_ops)
});
match or_expr.operands.len() {
0 => *or_op = false.into(),
1 => *or_op = or_expr.operands.remove(0),
_ => {}
}
}
// Put OR operands back, flattening surviving AND branches.
for op in or_operands {
match op {
Expr::And(and) => expr.operands.extend(and.operands),
other => expr.operands.push(other),
}
}
// All OR branches pruned → false.
if expr.operands.iter().any(|e| e.is_false()) {
return Some(false.into());
}
// Flattening can reintroduce operands already present in the outer AND.
dedup_operands(&mut expr.operands);
None
}
/// Returns `true` if any eq/ne constraint in `a` contradicts any
/// eq/ne constraint in `b`.
fn is_contradicting_eq_constraints(a: &[Expr], b: &[Expr]) -> bool {
for outer_op in a {
let Some((o_lhs, o_op, o_val)) = extract_eq_ne(outer_op) else {
continue;
};
for branch_op in b {
let Some((b_lhs, b_op, b_val)) = extract_eq_ne(branch_op) else {
continue;
};
// Only consider the two lhs sides "the same value" when they are
// syntactically equal AND stable. Otherwise `f() == 1 AND f() == 2`
// would be rewritten to `false`, but two evaluations of a
// non-deterministic `f()` can produce 1 and 2.
if !o_lhs.is_equivalent_to(b_lhs) {
continue;
}
match (o_op, b_op) {
(BinaryOp::Eq, BinaryOp::Eq) if o_val != b_val => return true,
(BinaryOp::Eq, BinaryOp::Ne) | (BinaryOp::Ne, BinaryOp::Eq) if o_val == b_val => {
return true;
}
_ => {}
}
}
}
false
}
/// Extracts `(lhs, op, rhs_value)` from an `Expr::BinaryOp` if it is an
/// `==` or `!=` with a constant value on the right.
fn extract_eq_ne(expr: &Expr) -> Option<(&Expr, BinaryOp, &stmt::Value)> {
if let Expr::BinaryOp(binop) = expr
&& let Expr::Value(val) = binop.rhs.as_ref()
&& matches!(binop.op, BinaryOp::Eq | BinaryOp::Ne)
{
return Some((binop.lhs.as_ref(), binop.op, val));
}
None
}