Skip to main content

foundry_evm_symbolic/runtime/expr/
bool.rs

1use super::{hashcons::HashConsed, *};
2
3/// Bounds both the number of distinct word nodes inspected by constant-ITE equality expansion and
4/// the unfolded size of the Boolean expression it could produce.
5const MAX_CONSTANT_ITE_EQ_NODES: usize = 128;
6const MAX_CONSTANT_ITE_EQ_UNFOLDED_NODES: usize = 8 * 1024;
7
8#[derive(Clone, PartialEq, Eq, Hash)]
9pub(crate) struct SymBoolExpr {
10    pub(in crate::runtime::expr) kind: HashConsed<SymBoolExprKind>,
11}
12
13impl fmt::Debug for SymBoolExpr {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        self.kind().fmt(f)
16    }
17}
18
19#[derive(Clone, Debug, PartialEq, Eq, Hash)]
20pub(in crate::runtime) enum SymBoolExprKind {
21    Const(bool),
22    Not(SymBoolExpr),
23    And(Arc<[SymBoolExpr]>),
24    Cmp(SymCmpOp, SymExpr, SymExpr),
25}
26
27impl SymBoolExpr {
28    #[inline]
29    pub(in crate::runtime) fn stable_hash_cmp(&self, other: &Self) -> std::cmp::Ordering {
30        self.kind.stable_hash_cmp(&other.kind)
31    }
32
33    pub(in crate::runtime) fn kind(&self) -> &SymBoolExprKind {
34        self.kind.value()
35    }
36
37    pub(in crate::runtime) fn from_kind(cx: &mut SymCx, kind: SymBoolExprKind) -> Self {
38        cx.mk_bool_kind(kind)
39    }
40
41    pub(crate) fn constant(cx: &mut SymCx, value: bool) -> Self {
42        cx.cached_bool(value)
43    }
44
45    pub(crate) fn cmp_word_const(
46        cx: &mut SymCx,
47        op: SymCmpOp,
48        word: &SymExpr,
49        value: U256,
50    ) -> Self {
51        if let Some(word) = word.as_const() {
52            Self::constant(cx, op.eval(word, value))
53        } else {
54            let value = SymExpr::constant(cx, value);
55            Self::cmp_word_expr(cx, op, word, value)
56        }
57    }
58
59    pub(crate) fn eq_word_const(cx: &mut SymCx, word: &SymExpr, value: U256) -> Self {
60        if let Some(word) = word.as_const() {
61            Self::constant(cx, word == value)
62        } else {
63            let value = SymExpr::constant(cx, value);
64            Self::eq(cx, word.clone(), value)
65        }
66    }
67
68    pub(crate) fn eq(cx: &mut SymCx, left: SymExpr, right: SymExpr) -> Self {
69        Self::cmp(cx, SymCmpOp::Eq, left, right)
70    }
71
72    pub(crate) fn cmp(cx: &mut SymCx, op: SymCmpOp, left: SymExpr, right: SymExpr) -> Self {
73        if let (
74            SymExprKind::Ite(left_condition, left_then, left_else),
75            SymExprKind::Ite(right_condition, right_then, right_else),
76        ) = (left.kind(), right.kind())
77            && left_condition == right_condition
78            && let (Some(left_then), Some(left_else), Some(right_then), Some(right_else)) = (
79                left_then.as_const(),
80                left_else.as_const(),
81                right_then.as_const(),
82                right_else.as_const(),
83            )
84        {
85            // Compare aligned constant-arm ITEs pointwise without expanding either expression.
86            return match (op.eval(left_then, right_then), op.eval(left_else, right_else)) {
87                (true, true) => Self::constant(cx, true),
88                (false, false) => Self::constant(cx, false),
89                (true, false) => left_condition.clone(),
90                (false, true) => Self::not_bool(cx, left_condition.clone()),
91            };
92        }
93
94        match op {
95            SymCmpOp::Eq => {
96                if let Some(condition) = Self::ite_eq_arm(cx, &left, &right)
97                    .or_else(|| Self::ite_eq_arm(cx, &right, &left))
98                    .or_else(|| Self::keccak_eq_known_preimage(cx, &left, &right))
99                    .or_else(|| Self::keccak_eq_known_preimage(cx, &right, &left))
100                {
101                    return condition;
102                }
103                match (left.kind(), right.kind()) {
104                    // `a == a => true`.
105                    _ if left == right => Self::constant(cx, true),
106                    (SymExprKind::Const(left), SymExprKind::Const(right)) => {
107                        // `const == const => const`.
108                        Self::constant(cx, left == right)
109                    }
110                    (_, SymExprKind::Const(right_value)) => {
111                        if let Some(condition) = Self::bool_word_eq_const(cx, &left, *right_value) {
112                            return condition;
113                        }
114                        if let Some(left_value) = left.known_word() {
115                            // `known(a) == const => const`.
116                            return Self::constant(cx, left_value == *right_value);
117                        }
118                        // `a == b => ordered(a, b)`.
119                        let (left, right) = SymExpr::ordered_commutative_operands(left, right);
120                        Self::from_kind(cx, SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right))
121                    }
122                    (SymExprKind::Const(left_value), _) => {
123                        if let Some(condition) = Self::bool_word_eq_const(cx, &right, *left_value) {
124                            return condition;
125                        }
126                        if let Some(right_value) = right.known_word() {
127                            // `const == known(a) => const`.
128                            return Self::constant(cx, *left_value == right_value);
129                        }
130                        // `a == b => ordered(a, b)`.
131                        let (left, right) = SymExpr::ordered_commutative_operands(left, right);
132                        Self::from_kind(cx, SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right))
133                    }
134                    (
135                        SymExprKind::BinOp(SymBinOp::Add, left_value, left_offset),
136                        SymExprKind::BinOp(SymBinOp::Add, right_value, right_offset),
137                    ) if left_offset == right_offset && left_offset.as_const().is_some() => {
138                        // `a + c == b + c => a == b`, so a common offset on two hashes still
139                        // reaches the Keccak rewrite below.
140                        Self::eq(cx, left_value.clone(), right_value.clone())
141                    }
142                    (
143                        SymExprKind::Keccak { len: left_len, .. },
144                        SymExprKind::Keccak { len: right_len, .. },
145                    ) if left_len
146                        .as_const()
147                        .zip(right_len.as_const())
148                        .is_some_and(|(left_len, right_len)| left_len != right_len) =>
149                    {
150                        // `keccak(a) == keccak(b) => false` for different input lengths.
151                        Self::constant(cx, false)
152                    }
153                    (
154                        SymExprKind::Keccak { len: left_len, bytes: left_bytes, .. },
155                        SymExprKind::Keccak { len: right_len, bytes: right_bytes, .. },
156                    ) if left_bytes.len() == right_bytes.len() => {
157                        // `keccak(a) == keccak(b) => len(a) == len(b) && bytes(a) == bytes(b)`.
158                        let mut conditions =
159                            vec![Self::eq(cx, left_len.clone(), right_len.clone())];
160                        conditions.extend(
161                            left_bytes
162                                .iter()
163                                .cloned()
164                                .zip(right_bytes.iter().cloned())
165                                .map(|(left, right)| Self::eq(cx, left, right)),
166                        );
167                        Self::and(cx, conditions)
168                    }
169                    (
170                        SymExprKind::Hash { algorithm: left_algorithm, bytes: left_bytes, .. },
171                        SymExprKind::Hash {
172                            algorithm: right_algorithm, bytes: right_bytes, ..
173                        },
174                    ) if left_algorithm == right_algorithm
175                        && matches!(*left_algorithm, "sha256" | "ripemd160")
176                        && left_bytes.len() == right_bytes.len() =>
177                    {
178                        // `hash(a) == hash(b) => bytes(a) == bytes(b)` for collision-resistant
179                        // hashes. Other precompile outputs, such as modexp, BLAKE2f with zero
180                        // rounds, and ecrecover, collide, so they compare as words.
181                        let conditions = left_bytes
182                            .iter()
183                            .cloned()
184                            .zip(right_bytes.iter().cloned())
185                            .map(|(left, right)| Self::eq(cx, left, right))
186                            .collect();
187                        Self::and(cx, conditions)
188                    }
189                    _ => {
190                        // `a == b => ordered(a, b)`.
191                        let (left, right) = SymExpr::ordered_commutative_operands(left, right);
192                        Self::from_kind(cx, SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right))
193                    }
194                }
195            }
196            SymCmpOp::Ult => match (left.kind(), right.kind()) {
197                // `a < a => false`.
198                _ if left == right => Self::constant(cx, false),
199                (SymExprKind::Const(left), SymExprKind::Const(right)) => {
200                    // `const < const => const`.
201                    Self::constant(cx, op.eval(*left, *right))
202                }
203                // `a < 0 => false`.
204                (_, SymExprKind::Const(value)) if value.is_zero() => Self::constant(cx, false),
205                // `MAX < a => false`.
206                (SymExprKind::Const(value), _) if *value == U256::MAX => Self::constant(cx, false),
207                // `a < a & low_mask => false`.
208                _ if low_masked_source_any(&right) == Some(&left) => Self::constant(cx, false),
209                _ => Self::from_kind(cx, SymBoolExprKind::Cmp(op, left, right)),
210            },
211            SymCmpOp::Ugt => match (left.kind(), right.kind()) {
212                // `a > a => false`.
213                _ if left == right => Self::constant(cx, false),
214                (SymExprKind::Const(left), SymExprKind::Const(right)) => {
215                    // `const > const => const`.
216                    Self::constant(cx, op.eval(*left, *right))
217                }
218                // `0 > a => false`.
219                (SymExprKind::Const(value), _) if value.is_zero() => Self::constant(cx, false),
220                // `a > MAX => false`.
221                (_, SymExprKind::Const(value)) if *value == U256::MAX => Self::constant(cx, false),
222                // `a & low_mask > a => false`.
223                _ if low_masked_source_any(&left) == Some(&right) => Self::constant(cx, false),
224                _ => Self::from_kind(cx, SymBoolExprKind::Cmp(op, left, right)),
225            },
226            SymCmpOp::Ule => match (left.kind(), right.kind()) {
227                // `a <= a => true`.
228                _ if left == right => Self::constant(cx, true),
229                (SymExprKind::Const(left), SymExprKind::Const(right)) => {
230                    // `const <= const => const`.
231                    Self::constant(cx, op.eval(*left, *right))
232                }
233                // `0 <= a => true`.
234                (SymExprKind::Const(value), _) if value.is_zero() => Self::constant(cx, true),
235                // `a <= MAX => true`.
236                (_, SymExprKind::Const(value)) if *value == U256::MAX => Self::constant(cx, true),
237                // `a & low_mask <= a => true`.
238                _ if low_masked_source_any(&left) == Some(&right) => Self::constant(cx, true),
239                _ => Self::from_kind(cx, SymBoolExprKind::Cmp(op, left, right)),
240            },
241            SymCmpOp::Uge => match (left.kind(), right.kind()) {
242                // `a >= a => true`.
243                _ if left == right => Self::constant(cx, true),
244                (SymExprKind::Const(left), SymExprKind::Const(right)) => {
245                    // `const >= const => const`.
246                    Self::constant(cx, op.eval(*left, *right))
247                }
248                // `a >= 0 => true`.
249                (_, SymExprKind::Const(value)) if value.is_zero() => Self::constant(cx, true),
250                // `MAX >= a => true`.
251                (SymExprKind::Const(value), _) if *value == U256::MAX => Self::constant(cx, true),
252                // `a >= a & low_mask => true`.
253                _ if low_masked_source_any(&right) == Some(&left) => Self::constant(cx, true),
254                _ => Self::from_kind(cx, SymBoolExprKind::Cmp(op, left, right)),
255            },
256            SymCmpOp::Slt | SymCmpOp::Sgt => match (left.kind(), right.kind()) {
257                // `a <s a => false`, `a >s a => false`.
258                _ if left == right => Self::constant(cx, false),
259                (SymExprKind::Const(left), SymExprKind::Const(right)) => {
260                    // `const <s const => const`.
261                    Self::constant(cx, op.eval(*left, *right))
262                }
263                _ => Self::from_kind(cx, SymBoolExprKind::Cmp(op, left, right)),
264            },
265        }
266    }
267
268    pub(crate) fn and(cx: &mut SymCx, values: Vec<Self>) -> Self {
269        let mut out = Vec::new();
270        for value in values {
271            match value.kind() {
272                // `true && a => a`.
273                SymBoolExprKind::Const(true) => {}
274                // `false && a => false`.
275                SymBoolExprKind::Const(false) => return Self::constant(cx, false),
276                // `(a && b) && c => a && b && c`.
277                SymBoolExprKind::And(values) => out.extend(values.iter().cloned()),
278                _ => out.push(value),
279            }
280        }
281        if out.is_empty() {
282            // `and() => true`.
283            Self::constant(cx, true)
284        } else if out.len() == 1 {
285            // `and(a) => a`.
286            out.pop().expect("single item exists")
287        } else {
288            Self::from_kind(cx, SymBoolExprKind::And(out.into()))
289        }
290    }
291
292    pub(crate) fn or(cx: &mut SymCx, values: Vec<Self>) -> Self {
293        let mut out = Vec::new();
294        for value in values {
295            match value.kind() {
296                // `false || a => a`.
297                SymBoolExprKind::Const(false) => {}
298                // `true || a => true`.
299                SymBoolExprKind::Const(true) => return Self::constant(cx, true),
300                _ => out.push(value),
301            }
302        }
303        if out.is_empty() {
304            // `or() => false`.
305            Self::constant(cx, false)
306        } else if out.len() == 1 {
307            // `or(a) => a`.
308            out.pop().expect("single item exists")
309        } else {
310            // `a || b => !(!a && !b)`.
311            let values = out.into_iter().map(|value| Self::not_bool(cx, value)).collect();
312            let and = Self::and(cx, values);
313            Self::not_bool(cx, and)
314        }
315    }
316
317    pub(crate) fn not_bool(cx: &mut SymCx, value: Self) -> Self {
318        match value.kind() {
319            // `!const => const`.
320            SymBoolExprKind::Const(value) => Self::constant(cx, !*value),
321            // `!!a => a`.
322            SymBoolExprKind::Not(value) => value.clone(),
323            _ => Self::from_kind(cx, SymBoolExprKind::Not(value)),
324        }
325    }
326
327    fn bool_word_eq_const(cx: &mut SymCx, word: &SymExpr, value: U256) -> Option<Self> {
328        let SymExprKind::Ite(condition, then_expr, else_expr) = word.kind() else { return None };
329        match (then_expr.as_const(), else_expr.as_const()) {
330            (Some(then_value), Some(else_value))
331                if then_value == U256::ONE && else_value.is_zero() =>
332            {
333                Some(if value.is_zero() {
334                    Self::not_bool(cx, condition.clone())
335                } else if value == U256::ONE {
336                    condition.clone()
337                } else {
338                    Self::constant(cx, false)
339                })
340            }
341            (Some(then_value), Some(else_value))
342                if then_value.is_zero() && else_value == U256::ONE =>
343            {
344                Some(if value.is_zero() {
345                    condition.clone()
346                } else if value == U256::ONE {
347                    Self::not_bool(cx, condition.clone())
348                } else {
349                    Self::constant(cx, false)
350                })
351            }
352            _ => None,
353        }
354    }
355
356    fn ite_eq_arm(cx: &mut SymCx, conditional: &SymExpr, expected: &SymExpr) -> Option<Self> {
357        let SymExprKind::Ite(condition, then_expr, else_expr) = conditional.kind() else {
358            return None;
359        };
360        if then_expr == expected {
361            let else_matches = Self::eq(cx, else_expr.clone(), expected.clone());
362            return Some(Self::or(cx, vec![condition.clone(), else_matches]));
363        }
364        if else_expr == expected {
365            let then_matches = Self::eq(cx, then_expr.clone(), expected.clone());
366            let condition = Self::not_bool(cx, condition.clone());
367            return Some(Self::or(cx, vec![condition, then_matches]));
368        }
369        if let Some(expected_value) = expected.as_const() {
370            let mut cost_cache = HashMap::default();
371            let mut remaining = MAX_CONSTANT_ITE_EQ_NODES;
372            if Self::constant_ite_eq_unfolded_nodes(conditional, &mut cost_cache, &mut remaining)
373                .is_none()
374            {
375                let (left, right) =
376                    SymExpr::ordered_commutative_operands(conditional.clone(), expected.clone());
377                return Some(Self::from_kind(cx, SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)));
378            }
379
380            let mut cache = HashMap::default();
381            let mut remaining = MAX_CONSTANT_ITE_EQ_NODES;
382            return Self::constant_ite_eq(
383                cx,
384                conditional,
385                expected_value,
386                &mut cache,
387                &mut remaining,
388            );
389        }
390        None
391    }
392
393    /// Compares a symbolic Keccak with a hash whose preimage was computed during the run.
394    ///
395    /// Assuming no collisions, the hashes are equal only when the inputs are equal.
396    fn keccak_eq_known_preimage(cx: &mut SymCx, keccak: &SymExpr, hash: &SymExpr) -> Option<Self> {
397        let SymExprKind::Keccak { len, bytes, .. } = keccak.kind() else {
398            return None;
399        };
400        let preimage = cx.concrete_keccak_preimage(hash.as_const()?)?;
401        let len = len.as_const()?;
402        if len != U256::from(preimage.len()) {
403            // `keccak(a) == keccak(b) => false` for different input lengths.
404            return Some(Self::constant(cx, false));
405        }
406        // `keccak(a) == keccak(b) => bytes(a) == bytes(b)`.
407        let conditions = bytes
408            .get(..preimage.len())?
409            .iter()
410            .cloned()
411            .zip(preimage.iter().cloned())
412            .map(|(byte, expected)| Self::eq(cx, byte, expected))
413            .collect();
414        Some(Self::and(cx, conditions))
415    }
416
417    /// Computes a conservative upper bound for the unfolded Boolean result without interning it.
418    ///
419    /// Cached child costs are deliberately added again at each use. This keeps construction of a
420    /// small shared word DAG from creating a Boolean DAG that becomes exponential when a later
421    /// consumer traverses occurrences instead of identities.
422    fn constant_ite_eq_unfolded_nodes(
423        expr: &SymExpr,
424        cache: &mut HashMap<SymExpr, Option<usize>>,
425        remaining: &mut usize,
426    ) -> Option<usize> {
427        if let Some(cached) = cache.get(expr) {
428            return *cached;
429        }
430        if *remaining == 0 {
431            cache.insert(expr.clone(), None);
432            return None;
433        }
434        *remaining -= 1;
435
436        let result = match expr.kind() {
437            SymExprKind::Const(_) => Some(1),
438            SymExprKind::Ite(condition, then_expr, else_expr) => {
439                let then_nodes = Self::constant_ite_eq_unfolded_nodes(then_expr, cache, remaining)?;
440                let else_nodes = Self::constant_ite_eq_unfolded_nodes(else_expr, cache, remaining)?;
441
442                let mut pending = vec![condition];
443                let mut condition_nodes = 0usize;
444                while let Some(condition) = pending.pop() {
445                    condition_nodes = condition_nodes.checked_add(1)?;
446                    if condition_nodes > MAX_CONSTANT_ITE_EQ_UNFOLDED_NODES {
447                        return None;
448                    }
449                    match condition.kind() {
450                        SymBoolExprKind::Not(value) => pending.push(value),
451                        SymBoolExprKind::And(values) => pending.extend(values.iter()),
452                        SymBoolExprKind::Const(_) | SymBoolExprKind::Cmp(_, _, _) => {}
453                    }
454                }
455
456                // Two selected branches and the `or` encoding add at most seven Boolean wrapper
457                // occurrences around both children and two occurrences of the condition.
458                then_nodes
459                    .checked_add(else_nodes)
460                    .and_then(|nodes| nodes.checked_add(2 * condition_nodes))
461                    .and_then(|nodes| nodes.checked_add(7))
462                    .filter(|nodes| *nodes <= MAX_CONSTANT_ITE_EQ_UNFOLDED_NODES)
463            }
464            _ => None,
465        };
466        cache.insert(expr.clone(), result);
467        result
468    }
469
470    fn constant_ite_eq(
471        cx: &mut SymCx,
472        expr: &SymExpr,
473        expected: U256,
474        cache: &mut HashMap<SymExpr, Option<Self>>,
475        remaining: &mut usize,
476    ) -> Option<Self> {
477        if let Some(cached) = cache.get(expr) {
478            return cached.clone();
479        }
480        if *remaining == 0 {
481            cache.insert(expr.clone(), None);
482            return None;
483        }
484        *remaining -= 1;
485
486        let result = match expr.kind() {
487            SymExprKind::Const(value) => Some(Self::constant(cx, *value == expected)),
488            SymExprKind::Ite(condition, then_expr, else_expr) => {
489                let condition = condition.clone();
490                let then_matches = Self::constant_ite_eq(cx, then_expr, expected, cache, remaining);
491                let else_matches = Self::constant_ite_eq(cx, else_expr, expected, cache, remaining);
492                match (then_matches, else_matches) {
493                    (Some(then_matches), Some(else_matches)) => {
494                        let then_selected =
495                            Self::and_ite_branch(cx, condition.clone(), then_matches);
496                        let condition = Self::not_bool(cx, condition);
497                        let else_selected = Self::and_ite_branch(cx, condition, else_matches);
498                        Some(Self::or(cx, vec![then_selected, else_selected]))
499                    }
500                    _ => None,
501                }
502            }
503            _ => None,
504        };
505        cache.insert(expr.clone(), result.clone());
506        result
507    }
508
509    /// Builds one selected ITE branch without flattening a cached child conjunction.
510    ///
511    /// Flattening here makes a linear ITE chain retain conjunctions of lengths `1..n` in the
512    /// per-call cache. Keeping this pair binary preserves the shared DAG and leaves flattening to
513    /// solver constraint normalization, where only the final expression is expanded.
514    fn and_ite_branch(cx: &mut SymCx, condition: Self, branch: Self) -> Self {
515        match (condition.as_const(), branch.as_const()) {
516            (Some(false), _) | (_, Some(false)) => Self::constant(cx, false),
517            (Some(true), _) => branch,
518            (_, Some(true)) => condition,
519            _ if condition == branch => condition,
520            _ => Self::from_kind(cx, SymBoolExprKind::And(vec![condition, branch].into())),
521        }
522    }
523
524    pub(crate) fn as_const(&self) -> Option<bool> {
525        match self.kind() {
526            SymBoolExprKind::Const(value) => Some(*value),
527            _ => None,
528        }
529    }
530
531    pub(in crate::runtime) fn zero_check_operand(&self) -> Option<&SymExpr> {
532        match self.kind() {
533            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right)
534                if right.as_const().is_some_and(|value| value.is_zero()) =>
535            {
536                Some(left)
537            }
538            _ => None,
539        }
540    }
541
542    pub(crate) fn contains_keccak(&self) -> bool {
543        self.visit_bool(|expr| matches!(expr.kind(), SymExprKind::Keccak { .. }))
544    }
545
546    pub(crate) fn contains_gasleft(&self) -> bool {
547        self.visit_bool(|expr| expr.is_raw_gasleft())
548    }
549
550    pub(crate) fn contains_udiv(&self) -> bool {
551        self.visit_bool(|expr| expr.contains_udiv())
552    }
553
554    pub(crate) fn implies_unsigned_less_or_equal(
555        &self,
556        expected: bool,
557        left: &SymExpr,
558        right: &SymExpr,
559        remaining: &mut usize,
560    ) -> bool {
561        if left == right {
562            return true;
563        }
564        let Some(next) = remaining.checked_sub(1) else { return false };
565        *remaining = next;
566
567        match self.kind() {
568            SymBoolExprKind::Not(value) => {
569                value.implies_unsigned_less_or_equal(!expected, left, right, remaining)
570            }
571            SymBoolExprKind::And(values) if expected => values
572                .iter()
573                .any(|value| value.implies_unsigned_less_or_equal(true, left, right, remaining)),
574            SymBoolExprKind::Cmp(op, fact_left, fact_right) => match (*op, expected) {
575                (SymCmpOp::Ult | SymCmpOp::Ule, true) => fact_left == left && fact_right == right,
576                (SymCmpOp::Uge | SymCmpOp::Ugt, true) => fact_right == left && fact_left == right,
577                (SymCmpOp::Ult | SymCmpOp::Ule, false) => fact_right == left && fact_left == right,
578                (SymCmpOp::Uge | SymCmpOp::Ugt, false) => fact_left == left && fact_right == right,
579                (SymCmpOp::Eq, true) => {
580                    (fact_left == left && fact_right == right)
581                        || (fact_right == left && fact_left == right)
582                }
583                (SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt, _) => false,
584            },
585            SymBoolExprKind::Const(_) | SymBoolExprKind::And(_) => false,
586        }
587    }
588
589    pub(crate) fn forces_expr_const_with_context(
590        &self,
591        expr: &SymExpr,
592        context: &[Self],
593    ) -> Option<U256> {
594        match self.kind() {
595            SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => match right.kind() {
596                SymExprKind::Const(value) => left.equality_forces_const(*value, expr, context),
597                _ => None,
598            },
599            SymBoolExprKind::Not(value) => match value.kind() {
600                SymBoolExprKind::Cmp(SymCmpOp::Eq, left, right) => match right.kind() {
601                    SymExprKind::Const(value) if value.is_zero() => {
602                        left.nonzero_forces_const(expr, context)
603                    }
604                    _ => None,
605                },
606                SymBoolExprKind::Not(value) => value.forces_expr_const_with_context(expr, context),
607                _ => None,
608            },
609            SymBoolExprKind::And(values) => {
610                values.iter().find_map(|value| value.forces_expr_const_with_context(expr, context))
611            }
612            _ => None,
613        }
614    }
615
616    pub(crate) fn upper_bound_usize(&self, expr: &SymExpr) -> Option<usize> {
617        match self.kind() {
618            SymBoolExprKind::Const(_) => None,
619            SymBoolExprKind::Not(value) => match value.kind() {
620                // `!(a > k) => a <= k`, so a negated comparison bounds through its complement.
621                SymBoolExprKind::Cmp(op, left, right) => {
622                    let complement = match op {
623                        SymCmpOp::Ult => SymCmpOp::Uge,
624                        SymCmpOp::Ugt => SymCmpOp::Ule,
625                        SymCmpOp::Ule => SymCmpOp::Ugt,
626                        SymCmpOp::Uge => SymCmpOp::Ult,
627                        SymCmpOp::Eq | SymCmpOp::Slt | SymCmpOp::Sgt => return None,
628                    };
629                    cmp_upper_bound_usize(complement, left, right, expr)
630                }
631                _ => None,
632            },
633            SymBoolExprKind::And(values) => {
634                let mut bound: Option<usize> = None;
635                for value in values.iter() {
636                    if let Some(candidate) = value.upper_bound_usize(expr) {
637                        bound = Some(bound.map_or(candidate, |bound| bound.min(candidate)));
638                    }
639                }
640                bound
641            }
642            SymBoolExprKind::Cmp(op, left, right) => cmp_upper_bound_usize(*op, left, right, expr),
643        }
644    }
645
646    pub(crate) fn eval_model<M: SymbolicModelLookup + ?Sized>(
647        &self,
648        model: &M,
649    ) -> Result<bool, SymbolicError> {
650        ModelEvaluator::new(model).eval_bool(self)
651    }
652
653    pub(crate) fn eval_model_if_complete<M: SymbolicModelLookup + ?Sized>(
654        &self,
655        model: &M,
656    ) -> Result<Option<bool>, SymbolicError> {
657        let mut vars = SymbolicVars::default();
658        self.collect_eval_vars(&mut vars);
659        if vars.iter().copied().all(|var| model.contains_name(var)) {
660            self.eval_model(model).map(Some)
661        } else {
662            Ok(None)
663        }
664    }
665
666    /// Visits each distinct word expression once, in depth-first, left-to-right order.
667    pub(crate) fn visit_exprs<B>(
668        &self,
669        visitor: &mut impl FnMut(&SymExpr) -> ControlFlow<B>,
670    ) -> ControlFlow<B> {
671        visit_unique(None, Some(self), visitor)
672    }
673
674    /// Returns whether any word node satisfies `visitor`, visiting each distinct node once.
675    pub(crate) fn visit_bool(&self, mut visitor: impl FnMut(&SymExpr) -> bool) -> bool {
676        self.visit_exprs(&mut |expr| {
677            if visitor(expr) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
678        })
679        .is_break()
680    }
681
682    /// Rewrites each distinct Boolean node once in bottom-up order.
683    ///
684    /// The folder must return the same result for every occurrence of one hash-consed node.
685    pub(crate) fn fold(
686        &self,
687        cx: &mut SymCx,
688        folder: &mut impl FnMut(&mut SymCx, Self) -> Self,
689    ) -> Self {
690        let mut folded = HashMap::default();
691        self.fold_cached(cx, folder, &mut folded)
692    }
693
694    fn fold_cached<'a>(
695        &'a self,
696        cx: &mut SymCx,
697        folder: &mut impl FnMut(&mut SymCx, Self) -> Self,
698        folded: &mut HashMap<&'a Self, Self>,
699    ) -> Self {
700        if let Some(expr) = folded.get(self) {
701            return expr.clone();
702        }
703
704        let expr = match self.kind() {
705            SymBoolExprKind::Const(_) => self.clone(),
706            SymBoolExprKind::Not(value) => {
707                let value = value.fold_cached(cx, folder, folded);
708                Self::not_bool(cx, value)
709            }
710            SymBoolExprKind::And(values) => {
711                let values =
712                    values.iter().map(|value| value.fold_cached(cx, folder, folded)).collect();
713                Self::and(cx, values)
714            }
715            SymBoolExprKind::Cmp(op, left, right) => {
716                Self::cmp_word_expr(cx, *op, left, right.clone())
717            }
718        };
719        let expr = folder(cx, expr);
720        folded.insert(self, expr.clone());
721        expr
722    }
723
724    /// Rewrites each distinct word node once while rebuilding this Boolean expression.
725    ///
726    /// The folder must return the same result for every occurrence of one hash-consed node.
727    pub(crate) fn fold_exprs(
728        &self,
729        cx: &mut SymCx,
730        folder: &mut impl FnMut(&mut SymCx, SymExpr) -> SymExpr,
731    ) -> Self {
732        let mut folded = ExpressionFoldCache::default();
733        self.fold_exprs_cached(cx, folder, &mut folded)
734    }
735
736    pub(in crate::runtime::expr) fn fold_exprs_cached<'a>(
737        &'a self,
738        cx: &mut SymCx,
739        folder: &mut impl FnMut(&mut SymCx, SymExpr) -> SymExpr,
740        folded: &mut ExpressionFoldCache<'a>,
741    ) -> Self {
742        if let Some(expr) = folded.bools.get(self) {
743            return expr.clone();
744        }
745
746        let expr = match self.kind() {
747            SymBoolExprKind::Const(_) => self.clone(),
748            SymBoolExprKind::Not(value) => {
749                let value = value.fold_exprs_cached(cx, folder, folded);
750                Self::not_bool(cx, value)
751            }
752            SymBoolExprKind::And(values) => {
753                let values = values
754                    .iter()
755                    .map(|value| value.fold_exprs_cached(cx, folder, folded))
756                    .collect();
757                Self::and(cx, values)
758            }
759            SymBoolExprKind::Cmp(op, left, right) => {
760                let left = left.fold_cached(cx, folder, folded);
761                let right = right.fold_cached(cx, folder, folded);
762                Self::cmp(cx, *op, left, right)
763            }
764        };
765        folded.bools.insert(self, expr.clone());
766        expr
767    }
768
769    pub(crate) fn cmp_word_expr(
770        cx: &mut SymCx,
771        op: SymCmpOp,
772        word: &SymExpr,
773        expr: SymExpr,
774    ) -> Self {
775        Self::cmp(cx, op, word.clone(), expr)
776    }
777
778    pub(crate) fn not(self, cx: &mut SymCx) -> Self {
779        Self::not_bool(cx, self)
780    }
781
782    pub(crate) fn collect_vars(&self, vars: &mut SymbolicVars) {
783        let _ = self.visit_exprs::<()>(&mut |expr| {
784            vars.extend(expr.kind().get_var());
785            ControlFlow::Continue(())
786        });
787    }
788
789    pub(crate) fn collect_eval_vars(&self, vars: &mut SymbolicVars) {
790        let _ = self.visit_exprs::<()>(&mut |expr| {
791            vars.extend(expr.kind().get_eval_var());
792            ControlFlow::Continue(())
793        });
794    }
795}
796
797#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
798pub(crate) enum SymCmpOp {
799    Eq,
800    Ult,
801    Ugt,
802    Ule,
803    Uge,
804    Slt,
805    Sgt,
806}
807
808impl SymCmpOp {
809    pub(crate) const fn smt(self) -> &'static str {
810        match self {
811            Self::Eq => "=",
812            Self::Ult => "bvult",
813            Self::Ugt => "bvugt",
814            Self::Ule => "bvule",
815            Self::Uge => "bvuge",
816            Self::Slt => "bvslt",
817            Self::Sgt => "bvsgt",
818        }
819    }
820
821    pub(crate) fn eval(self, left: U256, right: U256) -> bool {
822        match self {
823            Self::Eq => left == right,
824            Self::Ult => left < right,
825            Self::Ugt => left > right,
826            Self::Ule => left <= right,
827            Self::Uge => left >= right,
828            Self::Slt => I256::from_raw(left) < I256::from_raw(right),
829            Self::Sgt => I256::from_raw(left) > I256::from_raw(right),
830        }
831    }
832}
833
834/// Returns the constant upper bound a comparison places on `expr`, when it fits a `usize`.
835fn cmp_upper_bound_usize(
836    op: SymCmpOp,
837    left: &SymExpr,
838    right: &SymExpr,
839    expr: &SymExpr,
840) -> Option<usize> {
841    if op == SymCmpOp::Eq {
842        return match (left == expr, right == expr) {
843            (true, _) => right.as_const().and_then(|value| usize::try_from(value).ok()),
844            (_, true) => left.as_const().and_then(|value| usize::try_from(value).ok()),
845            _ => None,
846        };
847    }
848    if left == expr {
849        match op {
850            SymCmpOp::Ult => right
851                .as_const()
852                .and_then(|bound| (!bound.is_zero()).then(|| bound - U256::ONE))
853                .and_then(|value| usize::try_from(value).ok()),
854            SymCmpOp::Ule => right.as_const().and_then(|value| usize::try_from(value).ok()),
855            _ => None,
856        }
857    } else if right == expr {
858        match op {
859            SymCmpOp::Ugt => left
860                .as_const()
861                .and_then(|bound| (!bound.is_zero()).then(|| bound - U256::ONE))
862                .and_then(|value| usize::try_from(value).ok()),
863            SymCmpOp::Uge => left.as_const().and_then(|value| usize::try_from(value).ok()),
864            _ => None,
865        }
866    } else {
867        None
868    }
869}
870
871/// Visits reachable word nodes in depth-first, left-to-right order until the visitor breaks.
872///
873/// Expressions are hash-consed DAGs, so each distinct node is visited once. A tree walk would
874/// revisit shared subexpressions, which grows exponentially along chains such as nested hashes.
875pub(crate) fn visit_unique<'a, B>(
876    word: Option<&'a SymExpr>,
877    condition: Option<&'a SymBoolExpr>,
878    mut visitor: impl FnMut(&SymExpr) -> ControlFlow<B>,
879) -> ControlFlow<B> {
880    enum Node<'a> {
881        Word(&'a SymExpr),
882        Bool(&'a SymBoolExpr),
883    }
884
885    let mut pending = Vec::new();
886    pending.extend(word.map(Node::Word));
887    pending.extend(condition.map(Node::Bool));
888    let mut visited_bools = HashSet::<&SymBoolExpr>::default();
889    let mut visited_words = HashSet::<&SymExpr>::default();
890    while let Some(node) = pending.pop() {
891        match node {
892            Node::Bool(expr) => {
893                if !visited_bools.insert(expr) {
894                    continue;
895                }
896                match expr.kind() {
897                    SymBoolExprKind::Const(_) => {}
898                    SymBoolExprKind::Not(value) => pending.push(Node::Bool(value)),
899                    SymBoolExprKind::And(values) => {
900                        pending.extend(values.iter().rev().map(Node::Bool));
901                    }
902                    SymBoolExprKind::Cmp(_, left, right) => {
903                        pending.push(Node::Word(right));
904                        pending.push(Node::Word(left));
905                    }
906                }
907            }
908            Node::Word(expr) => {
909                if !visited_words.insert(expr) {
910                    continue;
911                }
912                visitor(expr)?;
913                match expr.kind() {
914                    SymExprKind::Const(_) | SymExprKind::Var(_) | SymExprKind::GasLeft(_) => {}
915                    SymExprKind::Keccak { len, bytes, .. } => {
916                        pending.extend(bytes.iter().rev().map(Node::Word));
917                        pending.push(Node::Word(len));
918                    }
919                    SymExprKind::Hash { bytes, .. } => {
920                        pending.extend(bytes.iter().rev().map(Node::Word));
921                    }
922                    SymExprKind::Not(value) => pending.push(Node::Word(value)),
923                    SymExprKind::BinOp(_, left, right) => {
924                        pending.push(Node::Word(right));
925                        pending.push(Node::Word(left));
926                    }
927                    SymExprKind::TernOp(_, left, right, modulus) => {
928                        pending.push(Node::Word(modulus));
929                        pending.push(Node::Word(right));
930                        pending.push(Node::Word(left));
931                    }
932                    SymExprKind::Ite(condition, left, right) => {
933                        pending.push(Node::Word(right));
934                        pending.push(Node::Word(left));
935                        pending.push(Node::Bool(condition));
936                    }
937                }
938            }
939        }
940    }
941    ControlFlow::Continue(())
942}