bitwright 0.32.16

Hash-consed fixed-width bit-vector expressions: exact evaluation, bit-level facts, and verified simplification.
Documentation
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! The shuffle pass: bit provenance of values assembled from pieces of other values.
//!
//! For a node of at most [`MAX_WIDTH`] bits, every output bit is traced to a constant or to one
//! bit of a *source* (an atom): through `&` with a constant, `|`, `^` and `+` of pieces whose
//! traced bits do not overlap (so no carry and no cancellation can occur), `a + a` (a shift by
//! one, as the linear pass writes it), shifts and rotations by constants, zero and sign
//! extension, `extract`, `concat` and `bswap`. When every bit is traced, the node is
//! re-emitted as the source itself, a rotation, a byte swap, one source in
//! place with constant bits (`(s & ~zeros) | ones`), or a `concat` of slices and constant runs,
//! and replaced when that is smaller. Limb recompositions, shifted-and-masked byte shuffles and
//! identity round trips collapse this way.

use super::{Fin, PassKind, Runner, Step, Stop};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::ops::{BinOp, UnOp};

/// The widest value traced.
pub(crate) const MAX_WIDTH: u16 = 128;

/// The most distinct sources and runs in one emission.
const MAX_PIECES: usize = 16;

/// Where one bit comes from.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum Prov {
    Zero,
    One,
    /// Bit `j` of source node `s`.
    Bit(u32, u16),
}

/// A node's bits, low first; `None` when some bit cannot be traced (then the node is a source
/// for its users).
pub(crate) type Bits = Option<Vec<Prov>>;

fn traced_op(op: OpCode) -> bool {
    matches!(
        op,
        OpCode::And
            | OpCode::Or
            | OpCode::Xor
            | OpCode::Add
            | OpCode::Shl
            | OpCode::LShr
            | OpCode::AShr
            | OpCode::RotL
            | OpCode::RotR
            | OpCode::Zext
            | OpCode::Sext
            | OpCode::Extract
            | OpCode::Concat
            | OpCode::Bswap
            | OpCode::Const
    )
}

fn source(i: u32, w: u16) -> Vec<Prov> {
    (0..w).map(|j| Prov::Bit(i, j)).collect()
}

fn const_bits(v: &BitVec) -> Vec<Prov> {
    let one = BitVec::one(v.width());
    (0..v.width().bits())
        .map(|j| {
            let b = BitVec::bin_unchecked(
                BinOp::LShr,
                v,
                &BitVec::wrapping_from_u64(v.width(), u64::from(j)),
            );
            if crate::facts::known::bv_and(&b, &one).is_zero() {
                Prov::Zero
            } else {
                Prov::One
            }
        })
        .collect()
}

/// Combines two traced values bit by bit where at most one side is non-zero at each bit.
fn disjoint(a: &[Prov], b: &[Prov]) -> Option<Vec<Prov>> {
    a.iter()
        .zip(b)
        .map(|(x, y)| match (x, y) {
            (Prov::Zero, v) | (v, Prov::Zero) => Some(*v),
            _ => None,
        })
        .collect()
}

fn small_const(cx: &Context, i: u32) -> Option<u64> {
    cx.const_val(i).and_then(|v| v.to_u64())
}

/// The bits of `i` from its operands' (already traced) bits.
fn trace(cx: &Context, bits: &crate::hash::IdMap<u32, Bits>, i: u32) -> Bits {
    let n = cx.node(i);
    let w = n.width;
    let get = |j: u32| -> Vec<Prov> {
        match bits.get(&j) {
            Some(Some(b)) => b.clone(),
            _ => source(j, cx.node(j).width),
        }
    };
    Some(match n.op {
        OpCode::Const => const_bits(&cx.const_val(i)?),
        OpCode::And => {
            let (a, b) = (get(n.a), get(n.b));
            let (x, m) = match (cx.const_val(n.a), cx.const_val(n.b)) {
                (Some(_), None) => (b, a),
                (None, Some(_)) => (a, b),
                _ => return None,
            };
            x.iter()
                .zip(&m)
                .map(|(p, k)| if *k == Prov::One { *p } else { Prov::Zero })
                .collect()
        }
        // `a + a` is `a << 1` (the linear pass writes it so).
        OpCode::Add if n.a == n.b => {
            let a = get(n.a);
            core::iter::once(Prov::Zero)
                .chain(a.iter().copied())
                .take(w as usize)
                .collect()
        }
        OpCode::Or | OpCode::Xor | OpCode::Add => {
            let (a, b) = (get(n.a), get(n.b));
            if n.op == OpCode::Or {
                // `1 | p` is 1: an or with a constant one bit is traced too.
                a.iter()
                    .zip(&b)
                    .map(|(x, y)| match (x, y) {
                        (Prov::One, _) | (_, Prov::One) => Some(Prov::One),
                        (Prov::Zero, v) | (v, Prov::Zero) => Some(*v),
                        _ => None,
                    })
                    .collect::<Option<Vec<_>>>()?
            } else {
                disjoint(&a, &b)?
            }
        }
        OpCode::Shl | OpCode::LShr | OpCode::AShr => {
            let k = small_const(cx, n.b)?.min(u64::from(w)) as usize;
            let a = get(n.a);
            let w = w as usize;
            (0..w)
                .map(|i| match n.op {
                    OpCode::Shl => {
                        if i >= k {
                            a[i - k]
                        } else {
                            Prov::Zero
                        }
                    }
                    OpCode::LShr => {
                        if i + k < w {
                            a[i + k]
                        } else {
                            Prov::Zero
                        }
                    }
                    _ => a[(i + k).min(w - 1)],
                })
                .collect()
        }
        OpCode::RotL | OpCode::RotR => {
            // (The builder turns constant rotations into `rotl` by a count below the width;
            // both directions and any count are handled here anyway.)
            // The count modulo the width, exactly at every width.
            let c = cx.const_val(n.b)?;
            let wv = BitVec::wrapping_from_u64(c.width(), u64::from(w));
            let k = BitVec::bin_unchecked(BinOp::URem, &c, &wv)
                .to_u64()
                .unwrap_or(0) as usize;
            let a = get(n.a);
            let w = w as usize;
            (0..w)
                .map(|i| {
                    if n.op == OpCode::RotL {
                        a[(i + w - k) % w]
                    } else {
                        a[(i + k) % w]
                    }
                })
                .collect()
        }
        OpCode::Zext | OpCode::Sext => {
            let a = get(n.a);
            let top = if n.op == OpCode::Zext {
                Prov::Zero
            } else {
                *a.last()?
            };
            let mut v = a;
            v.resize(w as usize, top);
            v
        }
        OpCode::Extract => {
            let a = get(n.a);
            let lo = n.b as usize;
            a.get(lo..lo + w as usize)?.to_vec()
        }
        OpCode::Concat => {
            let mut v = get(n.b);
            v.extend(get(n.a));
            v
        }
        OpCode::Bswap => {
            let a = get(n.a);
            let bytes = (w / 8) as usize;
            (0..w as usize)
                .map(|i| a[(bytes - 1 - i / 8) * 8 + i % 8])
                .collect()
        }
        _ => return None,
    })
}

fn bits_of(r: &mut Runner<'_, '_>, cx: &Context, root: u32) -> Result<Bits, Stop> {
    let mut stack: Vec<(u32, bool)> = vec![(root, false)];
    while let Some((i, expanded)) = stack.pop() {
        if r.shuffle.contains_key(&i) {
            continue;
        }
        let node = cx.node(i);
        if node.width > MAX_WIDTH || !traced_op(node.op) {
            r.shuffle.insert(i, None);
            continue;
        }
        if !expanded {
            stack.push((i, true));
            for c in node.children() {
                if !r.shuffle.contains_key(&c) {
                    stack.push((c, false));
                }
            }
            continue;
        }
        r.meter.charge(Counter::PassWork, u64::from(node.width))?;
        let b = trace(cx, &r.shuffle, i);
        r.shuffle.insert(i, b);
    }
    Ok(r.shuffle[&root].clone())
}

/// Maximal runs, low bits first: a constant run, or a slice of a source with consecutive bits.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Run {
    Const(bool, u16),
    Slice(u32, u16, u16),
}

fn runs(bits: &[Prov]) -> Vec<Run> {
    let mut out: Vec<Run> = Vec::new();
    for p in bits {
        match (out.last_mut(), p) {
            (Some(Run::Const(v, len)), Prov::Zero) if !*v => *len += 1,
            (Some(Run::Const(v, len)), Prov::One) if *v => *len += 1,
            (Some(Run::Slice(s, lo, len)), Prov::Bit(s2, j)) if s == s2 && *lo + *len == *j => {
                *len += 1
            }
            (_, Prov::Zero) => out.push(Run::Const(false, 1)),
            (_, Prov::One) => out.push(Run::Const(true, 1)),
            (_, Prov::Bit(s, j)) => out.push(Run::Slice(*s, *j, 1)),
        }
    }
    out
}

fn emit(r: &mut Runner<'_, '_>, cx: &mut Context, bits: &[Prov]) -> Result<Option<u32>, Stop> {
    let w = bits.len() as u16;
    let width = crate::Width::new(w).map_err(|e| Stop::Error(e.into()))?;
    let rs = runs(bits);
    if rs.len() > MAX_PIECES {
        return Ok(None);
    }
    // A whole source, possibly rotated or byte-swapped.
    if let Some(Prov::Bit(s, _)) = bits.first()
        && cx.node(*s).width == w
        && bits.iter().all(|p| matches!(p, Prov::Bit(t, _) if t == s))
    {
        let s = *s;
        let j = |i: usize| match bits[i] {
            Prov::Bit(_, j) => j as usize,
            _ => 0,
        };
        let wu = w as usize;
        let k = (wu - j(0)) % wu;
        if (0..wu).all(|i| j(i) == (i + wu - k) % wu) {
            if k == 0 {
                return Ok(Some(s));
            }
            let kv = BitVec::wrapping_from_u64(width, k as u64);
            return r
                .build(cx, |cx| {
                    let kc = cx.mk_const(&kv)?;
                    cx.c_bin(BinOp::RotL, s, kc)
                })
                .map(Some);
        }
        if w.is_multiple_of(8) && (0..wu).all(|i| j(i) == (wu / 8 - 1 - i / 8) * 8 + i % 8) {
            return r.build(cx, |cx| cx.c_un(UnOp::Bswap, s)).map(Some);
        }
    }
    // One source in place with some bits constant: `(s & ~zeros) | ones`, smaller than any
    // concat of its runs.
    if let Some(Prov::Bit(s, _)) = bits.iter().find(|p| matches!(p, Prov::Bit(..)))
        && cx.node(*s).width == w
        && bits
            .iter()
            .enumerate()
            .all(|(i, p)| !matches!(p, Prov::Bit(t, j) if t != s || usize::from(*j) != i))
    {
        let s = *s;
        let mask = |v: Prov| {
            bits.iter().enumerate().filter(|&(_, p)| *p == v).fold(
                BitVec::zero(width),
                |m, (i, _)| {
                    let bit = crate::facts::known::bv_shl(&BitVec::one(width), i as u32);
                    crate::facts::known::bv_or(&m, &bit)
                },
            )
        };
        let (zeros, ones) = (mask(Prov::Zero), mask(Prov::One));
        r.meter.charge(Counter::PassWork, u64::from(w))?;
        return r
            .build(cx, |cx| {
                let mut x = s;
                if !zeros.is_zero() {
                    let c = cx.mk_const(&crate::facts::known::bv_not(&zeros))?;
                    x = cx.c_bin(BinOp::And, x, c)?;
                }
                if !ones.is_zero() {
                    let c = cx.mk_const(&ones)?;
                    x = cx.c_bin(BinOp::Or, x, c)?;
                }
                Ok(x)
            })
            .map(Some);
    }
    // A concat of the runs, high first.
    let mut acc: Option<u32> = None;
    for run in rs.iter().rev() {
        r.meter.charge(Counter::PassWork, 1)?;
        let piece = match *run {
            Run::Const(v, len) => {
                let lw = crate::Width::new(len).map_err(|e| Stop::Error(e.into()))?;
                let c = if v {
                    BitVec::ones(lw)
                } else {
                    BitVec::zero(lw)
                };
                r.build(cx, |cx| cx.mk_const(&c))?
            }
            Run::Slice(s, lo, len) => r.build(cx, |cx| cx.c_extract(s, lo, len))?,
        };
        acc = Some(match acc {
            None => piece,
            Some(h) => r.build(cx, |cx| cx.c_concat(h, piece))?,
        });
    }
    r.meter.check()?;
    Ok(acc)
}

/// Strip a redundant `& (w - 1)` mask from a rotation count at a power-of-two width `w`.
fn strip_rot_mask(cx: &Context, s: u32, w: u16) -> u32 {
    let n = cx.node(s);
    if n.op == OpCode::And && w.is_power_of_two() {
        let want = u64::from(w - 1);
        if cx.const_val(n.b).and_then(|v| v.to_u64()) == Some(want) {
            return n.a;
        }
        if cx.const_val(n.a).and_then(|v| v.to_u64()) == Some(want) {
            return n.b;
        }
    }
    s
}

/// Recognize variable-count rotations:
/// - `(x << s1) | (x >>u s2)` (or their shared low truncation) where `0 <= s1, s2 < w` and
///   `(s1 + s2) ≡ 0 (mod w)` at power-of-two width `w <= 64` -> `rotr(x, s2)` or `rotl(x, s1)`;
/// - chained rotations `rot(rot(x, s1), s2)` at power-of-two width `w` -> `rot(x, s1 ± s2)`;
/// - redundant `& (w - 1)` mask on a rotation count at power-of-two width `w`.
fn var_rotate(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Option<Step>, Stop> {
    let node = cx.node(n);
    let w = node.width;
    if matches!(node.op, OpCode::RotL | OpCode::RotR) && w.is_power_of_two() && w >= 8 {
        let s = strip_rot_mask(cx, node.b, w);
        let inner = cx.node(node.a);
        if matches!(inner.op, OpCode::RotL | OpCode::RotR)
            && (cx.const_val(node.b).is_none() || cx.const_val(inner.b).is_none())
        {
            let before = cx.len() as u32;
            let s1 = strip_rot_mask(cx, inner.b, w);
            let same_dir = node.op == inner.op;
            let combined = r.build(cx, |cx| {
                if same_dir {
                    cx.c_bin(BinOp::Add, s1, s)
                } else {
                    cx.c_bin(BinOp::Sub, s, s1)
                }
            })?;
            let rop = if node.op == OpCode::RotL {
                BinOp::RotL
            } else {
                BinOp::RotR
            };
            let e = r.build(cx, |cx| cx.c_bin(rop, inner.a, combined))?;
            // Combining two nested rotates into one with summed count breaks the chain cleanly.
            return super::finish_with(
                r,
                cx,
                PassKind::Shuffle,
                n,
                e,
                before,
                &[inner.a, s1, s],
                Fin::FINAL,
                true,
            )
            .map(Some);
        }
        if s != node.b {
            let before = cx.len() as u32;
            let rop = if node.op == OpCode::RotL {
                BinOp::RotL
            } else {
                BinOp::RotR
            };
            let e = r.build(cx, |cx| cx.c_bin(rop, node.a, s))?;
            return super::finish(
                r,
                cx,
                PassKind::Shuffle,
                n,
                e,
                before,
                &[node.a, s],
                Fin::FINAL,
            )
            .map(Some);
        }
        return Ok(None);
    }
    if node.op != OpCode::Or {
        return Ok(None);
    }
    let unwrap_low = |id: u32| -> (u32, bool) {
        let m = cx.node(id);
        if m.op == OpCode::Extract && m.b == 0 {
            (m.a, true)
        } else {
            (id, false)
        }
    };
    let (la, ta) = unwrap_low(node.a);
    let (lb, tb) = unwrap_low(node.b);
    if ta != tb {
        return Ok(None);
    }
    let (na, nb) = (cx.node(la), cx.node(lb));
    let (x, s1, s2) = match (na.op, nb.op) {
        (OpCode::Shl, OpCode::LShr) if na.a == nb.a => (na.a, na.b, nb.b),
        (OpCode::LShr, OpCode::Shl) if na.a == nb.a => (na.a, nb.b, na.b),
        _ => return Ok(None),
    };
    if cx.const_val(s1).is_some() && cx.const_val(s2).is_some() {
        return Ok(None);
    }
    let wx = cx.wid(x);
    if !wx.is_power_of_two() || !(8..=64).contains(&wx) {
        return Ok(None);
    }
    let logw = wx.trailing_zeros() as u16;
    let hi_mask = (u64::MAX >> (64 - wx)) & !u64::from(wx - 1);
    let (k1, f1) = super::known_words(r, cx, s1)?;
    let (k2, f2) = super::known_words(r, cx, s2)?;
    let bounded = |k: Option<[u64; 2]>| k.is_some_and(|[kz, _]| (kz & hi_mask) == hi_mask);
    if !(bounded(k1) && bounded(k2)) {
        return Ok(None);
    }
    let fin = f1.and(f2);
    let before = cx.len() as u32;
    let neg_s2 = r.build(cx, |cx| cx.c_un(UnOp::Neg, s2))?;
    let mut complementary = super::poly::equal_mod(r, cx, s1, neg_s2, logw)?;
    #[cfg(feature = "mba")]
    if !complementary {
        complementary = super::mba::equal_lanes(r, cx, s1, neg_s2, logw)?;
    }
    if !complementary {
        super::discard(r, cx, before);
        return Ok(None);
    }
    let tree = |i: u32| cx.meta[i as usize].tree;
    let (rop, chosen_s) = if tree(s2) <= tree(s1) {
        (BinOp::RotR, strip_rot_mask(cx, s2, wx))
    } else {
        (BinOp::RotL, strip_rot_mask(cx, s1, wx))
    };
    let rot = r.build(cx, |cx| cx.c_bin(rop, x, chosen_s))?;
    let e = if ta {
        r.build(cx, |cx| cx.c_extract(rot, 0, w))?
    } else {
        rot
    };
    super::finish(r, cx, PassKind::Shuffle, n, e, before, &[x, chosen_s], fin).map(Some)
}

/// The shuffle pass at `n`.
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    if let Some(step) = var_rotate(r, cx, n)? {
        return Ok(step);
    }
    let node = cx.node(n);
    if node.width > MAX_WIDTH || !traced_op(node.op) || node.op == OpCode::Const {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let Some(bits) = bits_of(r, cx, n)? else {
        return Ok(Step::Normal(Fin::FINAL));
    };
    let mut atoms: Vec<u32> = bits
        .iter()
        .filter_map(|p| match p {
            Prov::Bit(s, _) => Some(*s),
            _ => None,
        })
        .collect();
    atoms.sort_unstable();
    atoms.dedup();
    if atoms.len() > MAX_PIECES || atoms == [n] {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let before = cx.len() as u32;
    let Some(e) = emit(r, cx, &bits)? else {
        return Ok(Step::Normal(Fin::FINAL));
    };
    r.explain_with(|| crate::engine::Explanation::Shuffle {
        bits: bits
            .iter()
            .map(|b| match *b {
                Prov::Zero => crate::engine::Source::Zero,
                Prov::One => crate::engine::Source::One,
                Prov::Bit(s, j) => crate::engine::Source::Bit {
                    of: cx.handle(s),
                    bit: j,
                },
            })
            .collect(),
    });
    let tie = node.op == OpCode::And && zext_slice(cx, e) && {
        let tree = |i: u32| cx.meta[i as usize].tree;
        tree(e) < tree(n)
    };
    super::finish_with(
        r,
        cx,
        PassKind::Shuffle,
        n,
        e,
        before,
        &atoms,
        Fin::FINAL,
        tie,
    )
}

/// Whether `e` is `zext<N>(extract<lo, k>(x))` with `x` not `N` bits wide: a mask keeping the
/// low bits of a slice, as the narrower slice zero-extended. Nothing rewrites that back (the
/// rule `zext_trunc` reads only a truncation of a value of the extension's own width), so the
/// pass commits it on a tie as well, when it is a smaller tree: masks sharing their constant
/// would otherwise each wait for the other to free it, as in the digit product
/// `(trunc<13>(x) & 127) * (extract<7, 13>(y) & 127)`.
fn zext_slice(cx: &Context, e: u32) -> bool {
    let z = cx.node(e);
    if z.op != OpCode::Zext {
        return false;
    }
    let s = cx.node(z.a);
    s.op == OpCode::Extract && cx.wid(s.a) != z.width
}

#[cfg(test)]
mod extra_tests {
    use crate::{Context, ParseOptions, Width};

    #[test]
    fn var_rotate_recognizes_complementary_bounded_shifts_and_folds_chains() {
        let mut cx = Context::new();
        let opt = ParseOptions::width(Width::W64);
        let prover = crate::prove::Simplifiers::new();
        let cfg = crate::prove::Config::default().with_simplify_fuel(1 << 14);
        for text in [
            // Complementary bounded shifts mod 64
            "let s = k & 63; let c = (0 - s) & 63; (x << c) | (x >>u s) == rotr(x, k)",
            // Chained variable rotates cancel
            "rotl(rotr(x, k & 63), k & 63) == x",
            // Redundant low-bit mask on power-of-two rotate count
            "rotr(x, k & 63) == rotr(x, k)",
        ] {
            let e = cx.parse(text, &opt).unwrap();
            let out = crate::prove::valid_under_with(&mut cx, e, None, &cfg, &prover).unwrap();
            assert!(
                matches!(out, crate::prove::Outcome::Proved(_)),
                "expected Proved for {text}, got {out:?}"
            );
        }
    }

    #[test]
    fn var_rotate_rejects_unbounded_shift_count_above_width() {
        let mut cx = Context::new();
        let opt = ParseOptions::width(Width::W64);
        let prover = crate::prove::Simplifiers::new();
        let cfg = crate::prove::Config::default().with_simplify_fuel(1 << 14);
        // At s == 65, `c = (64 - s) & 127 = 127`: both shifts are >= 64, so LHS == 0 while RHS == rotr(x, 1).
        let text = "let s = k & 127; let c = (64 - s) & 127; ((x << c) | (x >>u s)) == rotr(x, s)";
        let e = cx.parse(text, &opt).unwrap();
        let out = crate::prove::valid_under_with(&mut cx, e, None, &cfg, &prover).unwrap();
        assert!(
            matches!(out, crate::prove::Outcome::Refuted(_)),
            "expected Refuted for {text}, got {out:?}"
        );
    }
}