bitwright 0.32.13

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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! The linear-MBA pass: linear combinations of bitwise functions of at most [`MAX_ATOMS`]
//! atoms, `E = c + Σ aᵢ·fᵢ(x₁, …, xₜ)`.
//!
//! Every bitwise function is an integer combination of conjunctions,
//! `f(x) = Σ_S c_S · AND_S(x)` (with `AND_∅ = −1`), bit by bit and therefore exactly in
//! Z/2^W. So a linear MBA is determined by its *signature*: its values at the 2^t corners
//! where every atom is 0 or all-ones (`AND_S = −1` exactly when every atom of `S` is set). The
//! pass recognizes the fragment (linear operators over bitwise functions of atoms, with only 0
//! and all-ones constants inside the bitwise parts), evaluates the signature, and emits the
//! cheaper of:
//!
//! - the affine form `c + Σ kⱼ·xⱼ`, when no conjunction of two or more atoms has a coefficient;
//! - `u₀ + Σₖ (u₀ − uₖ)·gₖ`, where `u₀, u₁, …` are the distinct signature values and `gₖ` is
//!   the minimum form of the bitwise function true exactly at the corners with value `uₖ`
//!   (three atoms or fewer, from the bitwise pass's table);
//! - the conjunction form `c + Σ_S k_S·AND_S` itself, read off the Möbius transform (any number
//!   of atoms), when a conjunction of two or more atoms remains.
//!
//! Both have the input's signature and are linear MBAs, so they are equal to it. The result
//! replaces the node when the DAG gets smaller, or stays the same size and the node becomes a
//! smaller tree (an XOR written as a sum whose parts something else reads).
//!
//! *Extensions.* A fragment reaches through `sext` and `zext` of bitwise functions of narrower
//! values (a lifter's `sext<64>(a & b)` over 32-bit `a`, `b`): the function is read over the
//! narrow atoms lifted to the root's width by the same cast, since `sext(f(a, b))` is
//! `f(sext a, sext b)` for every bitwise `f`, and `zext(f(a, b))` is `f(zext a, zext b)` when
//! `f` is 0 at 0, else that plus `2^W` (see [`interior`]). The emission is over the lifted
//! atoms, which it builds; the commit rule's boundary stays at the narrow atoms, so they count.

use super::{
    Counts, Fin, Marks, PassKind, Runner, Step, Stop, bitwise, finish_with, linear, worth_building,
};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
use crate::ops::{BinOp, UnOp};

/// The most atoms (the signature has 2^t entries).
pub(crate) const MAX_ATOMS: usize = 8;

/// The part of a call's pass work one decomposition over the basis of small bitwise
/// functions may read (see [`solve`]): 1,024 units with fuel `1 << 14`, where a sum over
/// five or six atoms reads up to 13,000 and the forty-three sums of one question read more
/// than the call's other passes had left; 262,144 at the default.
const COBRA_SHARE: u64 = 256;

/// The most fragment nodes examined per candidate.
const MAX_REGION: usize = 2048;

/// The fragment below `root`: its atoms (in the context's canonical order), its interior nodes
/// in post-order, and whether it mixes linear and bitwise operators.
struct Region {
    /// The atoms the signature and the emission are over, in the canonical order: nodes of
    /// the root's width, among them the lifted atoms of the narrow atoms under casts.
    atoms: Vec<u32>,
    /// The interior nodes, operands first: the root's width, and under a cast its operand's.
    order: Vec<u32>,
    mixed: bool,
    /// The region's boundary for the commit rule: the atoms, with each narrow atom in place of
    /// its lifted one (which the emission builds, so it counts as new).
    bounds: Vec<u32>,
    /// Per narrow atom (under a cast): the lifted atom standing for it.
    lifts: Vec<(u32, u32)>,
}

fn is_linear(op: OpCode) -> bool {
    matches!(
        op,
        OpCode::Add | OpCode::Sub | OpCode::Neg | OpCode::Mul | OpCode::Shl
    )
}

fn is_bitwise(op: OpCode) -> bool {
    matches!(op, OpCode::And | OpCode::Or | OpCode::Xor | OpCode::Not)
}

/// How a node is read by its user: as a term of a linear combination, or as an operand of a
/// bitwise function (which must itself be a bitwise function of atoms).
#[derive(Copy, Clone, PartialEq, Eq)]
enum Mode {
    Linear,
    Bitwise,
}

/// Whether node `i` is interior when read in `mode` (otherwise it is an atom).
///
/// A cast is interior too (see the module notes on extensions): its operand is read as a
/// bitwise function at the narrower width, over narrow atoms the emission lifts. A sign
/// extension of a bitwise function is the function of the sign extensions (sign replication
/// commutes with every bitwise operator); a zero extension of one is the function of the zero
/// extensions when the function is 0 at 0 (above the operand's width every lifted atom is 0),
/// and that plus `2^W` when it is all ones there (`zext(~a)` is `~zext(a) + 2^W`, i.e.
/// `lowmask(W) − zext(a)`), which is a term but no operand of a bitwise function.
fn interior(cx: &Context, i: u32, mode: Mode) -> bool {
    let n = cx.node(i);
    if let Some(v) = cx.const_val(i) {
        // Inside bitwise functions only 0 and all-ones are uniform across bit positions.
        return mode == Mode::Linear || v.is_zero() || v.is_ones();
    }
    match n.op {
        OpCode::Sext => true,
        OpCode::Zext => mode == Mode::Linear || !at_zero(cx, n.a),
        // Linear operators are terms, never operands of a bitwise function.
        OpCode::Mul => {
            mode == Mode::Linear && (cx.const_val(n.a).is_some() || cx.const_val(n.b).is_some())
        }
        OpCode::Shl => mode == Mode::Linear && cx.const_val(n.b).is_some(),
        op if is_linear(op) => mode == Mode::Linear,
        // A bitwise operator whose constant operands are all 0 or all-ones.
        op if is_bitwise(op) => n
            .children()
            .all(|c| cx.const_val(c).is_none_or(|v| v.is_zero() || v.is_ones())),
        _ => false,
    }
}

/// Whether the bitwise function at `i` (over 0/all-ones constants and atoms) is all ones when
/// every atom is 0: its value above the operand's width once zero-extended.
fn at_zero(cx: &Context, i: u32) -> bool {
    fn go(cx: &Context, i: u32, depth: u32) -> bool {
        let n = cx.node(i);
        if let Some(v) = cx.const_val(i) {
            return v.is_ones();
        }
        if depth > 64 {
            return false;
        }
        match n.op {
            OpCode::Not => !go(cx, n.a, depth + 1),
            OpCode::And => go(cx, n.a, depth + 1) && go(cx, n.b, depth + 1),
            OpCode::Or => go(cx, n.a, depth + 1) || go(cx, n.b, depth + 1),
            OpCode::Xor => go(cx, n.a, depth + 1) ^ go(cx, n.b, depth + 1),
            _ => false,
        }
    }
    go(cx, i, 0)
}

/// The mode in which node `i`'s operands are read, when `i` is read in `mode`.
fn operand_mode(cx: &Context, i: u32, mode: Mode) -> Mode {
    match cx.node(i).op {
        OpCode::And | OpCode::Or | OpCode::Xor | OpCode::Zext | OpCode::Sext => Mode::Bitwise,
        // `~x` is `−x − 1` among terms and a bitwise function among bitwise operands.
        OpCode::Not => mode,
        _ => Mode::Linear,
    }
}

enum Walk {
    /// A node is interior in one reading and an atom in another: it must be an atom.
    Conflict(u32),
    Over,
}

/// A walk's stack entry: the node, its mode, whether its operands are listed, and the cast it
/// is under (its kind and the cast node).
type Frame = (u32, Mode, bool, Option<(OpCode, u32)>);

/// The walks' and signatures' buffers, kept by the runner and reused.
#[derive(Default)]
pub(crate) struct Scratch {
    /// In a walk, per node reached: bit 0 whether it is interior, bit 1 + mode the readings
    /// seen, bit 3 whether it is in the post-order. In a signature, per region node: its row
    /// of corner values in `words`.
    seen: Counts,
    /// Nodes that must be atoms.
    forced: Marks,
    stack: Vec<Frame>,
    words: Vec<u64>,
    /// In a walk, per node under a cast: the kind of cast it was first reached under, and that
    /// cast. A node reached under casts of two kinds would be two functions of the lifted
    /// atoms: the second cast is an atom.
    under: IdMap<u32, (OpCode, u32)>,
    /// In a phase run, per link of an additive chain that left its solve to its user: that
    /// user (see [`step`]).
    deferred: IdMap<u32, u32>,
}

impl Scratch {
    /// A phase run begins: what the chains deferred was of the one before.
    pub(crate) fn begin(&mut self) {
        self.deferred.clear();
    }
}

/// The `seen` bit of a node in the post-order.
const LISTED: u32 = 8;

fn walk<const QUICK: bool>(
    cx: &Context, root: u32, s: &mut Scratch, visits: &mut usize,
) -> Result<Region, Walk> {
    s.seen.begin(cx.len());
    s.under.clear();
    let mut reached = 0usize;
    let mut order = Vec::new();
    let mut atoms = Vec::new();
    // Narrow atoms, each with the kind of cast it is under (lifted after the walk).
    let mut narrow: Vec<(u32, OpCode)> = Vec::new();
    let (mut lin, mut bit) = (false, false);
    s.stack.clear();
    s.stack.push((root, Mode::Linear, false, None));
    while let Some((i, mode, expanded, lift)) = s.stack.pop() {
        if expanded {
            order.push(i);
            continue;
        }
        let op = cx.node(i).op;
        // Under a cast: bitwise operators over uniform constants, nothing else (a cast there
        // is an atom too, lifted by the outer one).
        let inner = (!QUICK || !matches!(op, OpCode::Sext | OpCode::Zext))
            && !s.forced.contains(i)
            && interior(cx, i, mode)
            && (lift.is_none() || is_bitwise(op) || cx.const_val(i).is_some());
        if let Some((kind, cast)) = lift {
            match s.under.get(&i) {
                Some(&(k, _)) if k != kind => return Err(Walk::Conflict(cast)),
                Some(_) => {}
                None => {
                    s.under.insert(i, (kind, cast));
                }
            }
        }
        let read = 2 << mode as u32;
        match s.seen.get(i) {
            Some(state) => {
                if (state & 1 == 1) != inner {
                    return Err(Walk::Conflict(i));
                }
                if state & read != 0 {
                    continue;
                }
                s.seen.set(i, state | read);
                if !inner {
                    continue;
                }
            }
            None => {
                s.seen.set(i, u32::from(inner) | read);
                reached += 1;
                if QUICK { *visits += 1; }
                if reached > if QUICK { 160 } else { MAX_REGION } {
                    return Err(Walk::Over);
                }
                if !inner {
                    match lift {
                        Some((kind, _)) => narrow.push((i, kind)),
                        None => atoms.push(i),
                    }
                    if atoms.len() + narrow.len() > if QUICK { 5 } else { MAX_ATOMS } {
                        return Err(Walk::Over);
                    }
                    continue;
                }
                s.stack.push((i, mode, true, lift));
            }
        }
        lin |= is_linear(op);
        // (A complement under a cast counts: `zext(~a)` is a term the linear pass cannot read
        // without the extension of `a`.)
        bit |= matches!(op, OpCode::And | OpCode::Or | OpCode::Xor)
            || (op == OpCode::Not && lift.is_some());
        let m = operand_mode(cx, i, mode);
        let under = match op {
            OpCode::Zext | OpCode::Sext => Some((op, i)),
            _ => lift,
        };
        for c in cx.node(i).children() {
            s.stack.push((c, m, false, under));
        }
    }
    // Keep each interior node once, operands first (a node read in both modes was pushed twice).
    order.retain(|&i| {
        let state = s.seen.get(i).unwrap_or(0);
        s.seen.set(i, state | LISTED);
        state & LISTED == 0
    });
    // The canonical order of the atoms, independent of node indices.
    atoms.sort_by(|a, b| cx.order(*a, *b));
    Ok(Region {
        bounds: atoms
            .iter()
            .copied()
            .chain(narrow.iter().map(|&(a, _)| a))
            .collect(),
        atoms,
        order,
        mixed: lin && bit,
        // The kinds, until the atoms are lifted (see `lift`).
        lifts: narrow.iter().map(|&(a, k)| (a, k as u32)).collect(),
    })
}

/// Lifts the region's narrow atoms: each becomes the cast of its kind to the root's width
/// (built, so counted as new by the commit rule, the narrow atom staying the boundary), and
/// joins the atoms in the canonical order.
fn lift(r: &mut Runner<'_, '_>, cx: &mut Context, reg: &mut Region, w: u16) -> Result<(), Stop> {
    let kinds = core::mem::take(&mut reg.lifts);
    for (a, kind) in kinds {
        let sext = kind == OpCode::Sext as u32;
        let l = r.build(cx, |cx| {
            if sext {
                cx.c_sext(a, w)
            } else {
                cx.c_zext(a, w)
            }
        })?;
        reg.lifts.push((a, l));
        if !reg.atoms.contains(&l) {
            reg.atoms.push(l);
        }
    }
    reg.atoms.sort_by(|a, b| cx.order(*a, *b));
    Ok(())
}

fn region(cx: &Context, root: u32, s: &mut Scratch) -> Option<Region> {
    s.forced.begin(cx.len());
    for _ in 0..32 {
        match walk::<false>(cx, root, s, &mut 0) {
            Ok(r) => return Some(r),
            Err(Walk::Conflict(i)) if i != root => {
                s.forced.insert(i);
            }
            Err(_) => return None,
        }
    }
    None
}

/// The values of the root at the 2^t corners (corner `p`: atom `j` is all-ones when bit `j` of
/// `p` is set).
fn signature(cx: &Context, reg: &Region, root: u32, s: &mut Scratch) -> Vec<BitVec> {
    let w = cx.width_of(root);
    match signature_words(cx, reg, root, s) {
        Some(row) => row.iter().map(|&v| BitVec::wrapping_from_u64(w, v)).collect(),
        None => signature_wide(cx, reg, root),
    }
}

fn signature_words<'a>(
    cx: &Context, reg: &Region, root: u32, s: &'a mut Scratch,
) -> Option<&'a [u64]> {
    let bits = u64::from(cx.wid(root));
    if bits > 64 {
        return None;
    }
    // Every region node has the root's width: a row of words per node, masked to it.
    let mask = u64::MAX >> (64 - bits);
    let t = reg.atoms.len();
    let corners = 1usize << t;
    s.seen.begin(cx.len());
    s.words.clear();
    s.words.resize((t + reg.order.len()) * corners, 0);
    for (j, &a) in reg.atoms.iter().enumerate() {
        s.seen.set(a, j as u32);
        for (p, v) in s.words[j * corners..(j + 1) * corners]
            .iter_mut()
            .enumerate()
        {
            if p >> j & 1 == 1 {
                *v = mask;
            }
        }
    }
    // A narrow atom reads as its lifted atom: under its cast, the nodes are evaluated at the
    // root's width over the lifted atoms (bitwise operators act by position).
    for &(a, l) in &reg.lifts {
        match s.seen.get(l) {
            Some(j) => s.seen.set(a, j),
            None => return None,
        }
    }
    for (k, &i) in reg.order.iter().enumerate() {
        let at = (t + k) * corners;
        s.seen.set(i, (t + k) as u32);
        let (done, rest) = s.words.split_at_mut(at);
        let out = &mut rest[..corners];
        if let Some(c) = cx.const_val(i) {
            // A uniform constant under a cast at the root's width.
            out.fill(if c.is_ones() { mask } else { c.limbs()[0] });
            continue;
        }
        let n = cx.node(i);
        let operand = |x: u32| {
            s.seen
                .get(x)
                .map(|r| &done[r as usize * corners..(r as usize + 1) * corners])
        };
        let Some(a) = operand(n.a) else {
            return None;
        };
        match n.op {
            OpCode::Sext => out.copy_from_slice(a),
            // The function of the lifted atoms, plus `2^W` where it is all ones at 0 (above
            // the operand's width, where the lifted atoms are 0).
            OpCode::Zext => {
                let above = if a[0] == mask {
                    1u64 << cx.width_of(n.a).bits()
                } else {
                    0
                };
                out.iter_mut()
                    .zip(a)
                    .for_each(|(o, &x)| *o = x.wrapping_add(above) & mask);
            }
            OpCode::Not => out.iter_mut().zip(a).for_each(|(o, &x)| *o = !x & mask),
            OpCode::Neg => out
                .iter_mut()
                .zip(a)
                .for_each(|(o, &x)| *o = x.wrapping_neg() & mask),
            op => {
                let Some(b) = operand(n.b) else {
                    return None;
                };
                let f: fn(u64, u64, u64) -> u64 = match op {
                    OpCode::Add => |x, y, _| x.wrapping_add(y),
                    OpCode::Sub => |x, y, _| x.wrapping_sub(y),
                    OpCode::Mul => |x, y, _| x.wrapping_mul(y),
                    OpCode::Shl => |x, y, bits| if y < bits { x << y } else { 0 },
                    OpCode::And => |x, y, _| x & y,
                    OpCode::Or => |x, y, _| x | y,
                    OpCode::Xor => |x, y, _| x ^ y,
                    _ => return None,
                };
                for (o, (&x, &y)) in out.iter_mut().zip(a.iter().zip(b)) {
                    *o = f(x, y, bits) & mask;
                }
            }
        }
    }
    let r = (t + reg.order.len() - 1) * corners;
    (s.seen.get(root)? as usize * corners == r).then_some(&s.words[r..r + corners])
}

/// Endpoints of a constant or one-variable signature. In particular, agreement
/// at zero and at each singleton is insufficient: a joint corner can differ.
#[cfg(feature = "mba")]
fn one_axis(sig: &[u64], vars: usize) -> Option<(u64, Option<usize>, u64)> {
    let bias = sig[0];
    let axis = (0..vars).find(|&j| sig[1 << j] != bias);
    let other = axis.map_or(bias, |j| sig[1 << j]);
    sig.iter().enumerate().all(|(p, &v)| {
        v == if axis.is_some_and(|j| p & (1 << j) != 0) { other } else { bias }
    }).then_some((bias, axis, other))
}

/// A cheap exact reading for the large-expression sweep. A linear MBA that agrees
/// with `k + c*x` on every corner *is* `k + c*x` for arbitrary word inputs. Only
/// that one-word form (or a constant) is interesting here: no basis search, no
/// lifting through casts, and no dynamic enumeration of the word inputs.
#[cfg(feature = "mba")]
pub(super) fn one_word(
    r: &mut Runner<'_, '_>, cx: &mut Context, root: u32, left: &mut u64,
) -> Result<Option<u32>, Stop> {
    let w = cx.wid(root);
    if w > 64 || !matches!(cx.node(root).op, OpCode::Add | OpCode::Sub) {
        return Ok(None);
    }
    let s = &mut r.linear_mba;
    s.forced.begin(cx.len());
    for _ in 0..3 {
        // walk::<true> stops at the 161st distinct node. A conflict can only
        // add another walk after the node has been fixed as a common cut.
        if *left < 161 { break; }
        let mut visits = 0;
        let region = walk::<true>(cx, root, s, &mut visits);
        *left -= visits as u64;
        let reg = match region {
            Ok(reg) => reg,
            Err(Walk::Conflict(i)) if i != root => {
                s.forced.insert(i);
                continue;
            }
            Err(_) => break,
        };
        if reg.order.len() < 2 { break; }
        let rows = 1usize << reg.atoms.len();
        let cost = ((reg.order.len() + reg.atoms.len() + 2) * rows) as u64;
        if cost > *left { break; }
        *left -= cost;
        let Some(sig) = signature_words(cx, &reg, root, s) else { break };
        let Some((bias, axis, other)) = one_axis(sig, reg.atoms.len()) else { break };
        let mask = u64::MAX >> (64 - w);
        let atom = axis.map(|j| reg.atoms[j]);
        return r.build(cx, |cx| {
            let k = cx.mk_const_u64(w, bias)?;
            let Some(x) = atom else { return Ok(Some(k)) };
            let coeff = bias.wrapping_sub(other) & mask;
            let out = if coeff == mask {
                cx.c_bin(BinOp::Sub, k, x)?
            } else {
                let c = cx.mk_const_u64(w, coeff)?;
                let term = cx.c_bin(BinOp::Mul, x, c)?;
                cx.c_bin(BinOp::Add, term, k)?
            };
            Ok((out != root).then_some(out))
        });
    }
    Ok(None)
}

#[cfg(all(test, feature = "mba"))]
#[test]
fn one_word_keeps_mixed_corners_in_its_proof() {
    let mut cx = Context::new();
    let opts = crate::ParseOptions::width(crate::Width::W8);
    let mut s = Scratch::default();
    for (text, fits) in [
        ("3 * (a & b) + 3 * (a & ~b) + 7", true),
        ("3 * (a & b) + 3 * (a & ~b) + (a & b) + 7", false),
    ] {
        let root = cx.parse(text, &opts).unwrap().index();
        s.forced.begin(cx.len());
        let reg = walk::<true>(&cx, root, &mut s, &mut 0).ok().unwrap();
        let row = signature_words(&cx, &reg, root, &mut s).unwrap();
        let answer = one_axis(row, reg.atoms.len());
        assert_eq!(answer.is_some(), fits);
        if let Some((bias, Some(axis), other)) = answer {
            assert_eq!(bias, 7);
            assert_eq!(bias.wrapping_sub(other) & 255, 3);
            assert_eq!(reg.atoms[axis], cx.parse("a", &opts).unwrap().index());
        }
    }
}

/// [`signature`] in `BitVec`s, for any width.
fn signature_wide(cx: &Context, reg: &Region, root: u32) -> Vec<BitVec> {
    let w = cx.width_of(root);
    let t = reg.atoms.len();
    let corners = 1usize << t;
    let mut vals: IdMap<u32, Vec<BitVec>> = IdMap::default();
    for (j, &a) in reg.atoms.iter().enumerate() {
        let v = (0..corners)
            .map(|p| {
                if p >> j & 1 == 1 {
                    BitVec::ones(w)
                } else {
                    BitVec::zero(w)
                }
            })
            .collect();
        vals.insert(a, v);
    }
    for &(a, l) in &reg.lifts {
        let v = vals.get(&l).cloned().unwrap_or_default();
        vals.insert(a, v);
    }
    for &i in &reg.order {
        let n = cx.node(i);
        let v: Vec<BitVec> = if let Some(c) = cx.const_val(i) {
            let c = if c.is_ones() {
                BitVec::ones(w)
            } else {
                c.zext(w).unwrap_or(c)
            };
            vec![c; corners]
        } else {
            let above = (n.op == OpCode::Zext && vals[&n.a][0].is_ones()).then(|| {
                crate::facts::known::bv_shl(&BitVec::one(w), u32::from(cx.width_of(n.a).bits()))
            });
            (0..corners)
                .map(|p| {
                    let get = |j: u32| vals[&j][p];
                    match n.op {
                        OpCode::Sext => get(n.a),
                        OpCode::Zext => match &above {
                            Some(k) => BitVec::bin_unchecked(BinOp::Add, &get(n.a), k),
                            None => get(n.a),
                        },
                        OpCode::Not => BitVec::un_unchecked(UnOp::Not, &get(n.a)),
                        OpCode::Neg => BitVec::un_unchecked(UnOp::Neg, &get(n.a)),
                        op => {
                            let b = op.as_bin().unwrap_or(BinOp::Add);
                            BitVec::bin_unchecked(b, &get(n.a), &get(n.b))
                        }
                    }
                })
                .collect()
        };
        vals.insert(i, v);
    }
    vals.remove(&root).unwrap_or_default()
}

/// The conjunction coefficients `d_S` from the signature: `−E(p) = Σ_{S ⊆ p} d_S`.
fn mobius(sig: &[BitVec]) -> Vec<BitVec> {
    let mut d: Vec<BitVec> = sig
        .iter()
        .map(|v| BitVec::un_unchecked(UnOp::Neg, v))
        .collect();
    let n = d.len();
    let mut bit = 1;
    while bit < n {
        for p in 0..n {
            if p & bit != 0 {
                d[p] = BitVec::bin_unchecked(BinOp::Sub, &d[p], &d[p ^ bit]);
            }
        }
        bit <<= 1;
    }
    d
}

/// The candidate forms, cheapest first by an estimate of new nodes.
enum Candidate {
    /// `konst + Σ k·atom` (atoms by position).
    Affine(BitVec, Vec<(usize, BitVec)>),
    /// `u0 + Σ (u0 − uk)·gk`: the base value, and per other value its coefficient and table.
    Indicators(BitVec, Vec<(BitVec, u8)>),
    /// CoBRA change-of-basis decomposition `konst + Σ k·B` over compact Boolean basis ops.
    Cobra(BitVec, Vec<(crate::cobra::BasisOp, BitVec)>),
    /// `konst + Σ k·AND_S`: per nonempty atom set (a bit mask over positions), its coefficient.
    Conjunctions(BitVec, Vec<(usize, BitVec)>),
}

/// A basis function over the region's atoms, as the pass's nodes (see `BasisOp::lower`).
fn emit_basis_op(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    op: &crate::cobra::BasisOp,
    atoms: &[u32],
) -> Result<u32, Stop> {
    op.lower(&mut Gates { r, cx, atoms })
}

/// The engine's nodes as the gates of a basis function.
struct Gates<'g, 'r, 'i> {
    r: &'g mut Runner<'r, 'i>,
    cx: &'g mut Context,
    atoms: &'g [u32],
}

impl crate::cobra::Gates for Gates<'_, '_, '_> {
    type Err = Stop;
    fn input(&mut self, i: usize) -> Result<u32, Stop> {
        Ok(self.atoms[i])
    }
    fn table(&mut self, tt8: u8, args: [u32; 3]) -> Result<u32, Stop> {
        bitwise::emit(self.r, self.cx, tt8, &args)
    }
    fn and(&mut self, a: u32, b: u32) -> Result<u32, Stop> {
        self.r.build(self.cx, |cx| cx.c_bin(BinOp::And, a, b))
    }
    fn or(&mut self, a: u32, b: u32) -> Result<u32, Stop> {
        self.r.build(self.cx, |cx| cx.c_bin(BinOp::Or, a, b))
    }
    fn not(&mut self, a: u32) -> Result<u32, Stop> {
        self.r.build(self.cx, |cx| cx.c_un(UnOp::Not, a))
    }
    fn ones(&mut self) -> Result<u32, Stop> {
        let ones = BitVec::ones(self.cx.width_of(self.atoms[0]));
        self.r.build(self.cx, |cx| cx.mk_const(&ones))
    }
}

fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::PassCounts {
    r.stats.passes.entry("linear_mba").or_default()
}

/// The linear-MBA pass at `n`.
///
/// An interior link of an additive chain whose user is itself a fitting linear-MBA region is
/// left to that user: the whole sum is solved once instead of at every partial prefix. The
/// user's solve can still decline (the lifted atoms are too many, the form is no smaller),
/// and the walk does not come back to the link: the user then solves the links it held back
/// (see [`held_back`]).
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    if let Some(p) = defers(r, cx, n) {
        r.linear_mba.deferred.insert(n, p);
        return Ok(Step::Normal(Fin::PROVISIONAL));
    }
    r.linear_mba.deferred.remove(&n);
    match solve(r, cx, n, true)?.0 {
        Step::Normal(fin) => held_back(r, cx, n, fin),
        step => Ok(step),
    }
}

/// The user in the chain that the link `n` leaves its solve to, if any (see [`step`]).
fn defers(r: &mut Runner<'_, '_>, cx: &Context, n: u32) -> Option<u32> {
    if !matches!(cx.node(n).op, OpCode::Add | OpCode::Sub) {
        return None;
    }
    let p = *r.chain_parent.get(&n)?;
    (matches!(cx.node(p).op, OpCode::Add | OpCode::Sub | OpCode::Neg)
        && interior(cx, p, Mode::Linear)
        && region(cx, p, &mut r.linear_mba)
            .is_some_and(|pr| pr.mixed && !pr.bounds.is_empty() && pr.bounds.len() <= MAX_ATOMS))
    .then_some(p)
}

/// Once `n`'s own solve declined (with `fin`): the links of its chain that left their solve to
/// it, each solved alone, down the chain (a link that declines in turn hands on to those that
/// left theirs to it). The first that is rewritten is rebuilt into `n`, as the walk would have
/// rebuilt `n` over it, and `n` is rewritten to that where it makes the DAG smaller (a link on
/// the way that something else reads stays for that reader).
fn held_back(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32, mut fin: Fin) -> Result<Step, Stop> {
    let before = cx.len() as u32;
    // The links solved, each with the index of its user here (`n` has none).
    let mut links: Vec<(u32, usize)> = vec![(n, usize::MAX)];
    let mut at = 0;
    while at < links.len() {
        let u = links[at].0;
        let node = cx.node(u);
        let kids = [node.a, node.b, node.c];
        for &c in &kids[..node.op.arity()] {
            // (Removed once solved: an operand read twice is solved once.)
            if r.linear_mba.deferred.get(&c) != Some(&u) {
                continue;
            }
            r.linear_mba.deferred.remove(&c);
            match solve(r, cx, c, true)?.0 {
                Step::Normal(f) => {
                    fin = fin.and(f);
                    links.push((c, at));
                }
                Step::To(e, _) => {
                    // `c` is `e`: so is every user up the chain, rebuilt over it.
                    let (mut old, mut new, mut i) = (c, e, at);
                    loop {
                        let (v, up) = links[i];
                        let node = cx.node(v);
                        let mut kids = [node.a, node.b, node.c];
                        for k in kids.iter_mut().take(node.op.arity()) {
                            if *k == old {
                                *k = new;
                            }
                        }
                        new = r.build(cx, |cx| cx.rebuild(v, kids))?;
                        if up == usize::MAX {
                            break;
                        }
                        (old, i) = (v, up);
                    }
                    if new == n {
                        super::discard(r, cx, before);
                        return Ok(Step::Normal(fin));
                    }
                    // What `new` reads that was there before: where the count of its nodes
                    // stops.
                    let mut stops = Vec::new();
                    let mut seen: IdMap<u32, ()> = IdMap::default();
                    let mut todo = vec![new];
                    while let Some(i) = todo.pop() {
                        if seen.insert(i, ()).is_some() {
                            continue;
                        }
                        if i < before {
                            stops.push(i);
                        } else {
                            todo.extend(cx.node(i).children());
                        }
                    }
                    let tree = |i: u32| cx.meta[i as usize].tree;
                    let tie = tree(n) != u32::MAX && tree(new) < tree(n);
                    let kind = PassKind::LinearMba;
                    return Ok(
                        match finish_with(r, cx, kind, n, new, before, &stops, Fin::FINAL, tie)? {
                            Step::Normal(f) => Step::Normal(fin.and(f)),
                            step => step,
                        },
                    );
                }
            }
        }
        at += 1;
    }
    Ok(Step::Normal(fin))
}

/// The cheapest form of the linear MBA at `n`, built whatever it costs and committed nowhere:
/// for a caller that measures the result itself. `None` when `n` is no mixed fragment.
#[cfg(feature = "prove")]
pub(super) fn normal(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    n: u32,
) -> Result<Option<u32>, Stop> {
    Ok(solve(r, cx, n, false)?.1)
}

/// Whether `a` and `b` are equal for every value of the symbols because their difference is a
/// linear MBA whose signature is zero: at every corner of its atoms it is 0, so every
/// coefficient of its form is, whatever the atoms are. `false` decides nothing (the
/// difference is no mixed fragment, has too many atoms, or is not zero at some corner, which
/// atoms that depend on each other may never reach).
///
/// The two sides of such an equality are often each as small as they get (`s + t` and
/// `s | t` for disjoint `s` and `t`), so that neither is rewritten into the other and only
/// their difference shows that they are the same function.
pub(super) fn equal(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    a: u32,
    b: u32,
) -> Result<bool, Stop> {
    // What this builds (the difference, the atoms lifted to its width) is of this test
    // only: retired whatever the answer, so that it never counts as a use of the operands.
    let before = cx.len() as u32;
    let zero = difference_is_zero(r, cx, a, b);
    super::discard(r, cx, before);
    zero
}

fn difference_is_zero(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    a: u32,
    b: u32,
) -> Result<bool, Stop> {
    let n = r.build(cx, |cx| cx.c_bin(crate::BinOp::Sub, a, b))?;
    let op = cx.node(n).op;
    if !(is_linear(op) || is_bitwise(op)) || !interior(cx, n, Mode::Linear) {
        return Ok(false);
    }
    let Some(mut reg) = region(cx, n, &mut r.linear_mba) else {
        return Ok(false);
    };
    if !reg.mixed || reg.bounds.is_empty() {
        return Ok(false);
    }
    lift(r, cx, &mut reg, cx.width_of(n).bits())?;
    let t = reg.atoms.len();
    if t > MAX_ATOMS {
        return Ok(false);
    }
    r.meter
        .charge(Counter::PassWork, (reg.order.len() << t) as u64)?;
    let sig = signature(cx, &reg, n, &mut r.linear_mba);
    Ok(sig.iter().all(BitVec::is_zero))
}

/// [`step`] when `commit`; else the form alone ([`normal`]).
fn solve(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    n: u32,
    commit: bool,
) -> Result<(Step, Option<u32>), Stop> {
    let op = cx.node(n).op;
    if !(is_linear(op) || is_bitwise(op)) || !interior(cx, n, Mode::Linear) {
        return Ok((Step::Normal(Fin::FINAL), None));
    }
    let Some(mut reg) = region(cx, n, &mut r.linear_mba) else {
        count(r).atomized += 1;
        return Ok((Step::Normal(Fin::FINAL), None));
    };
    // Pure linear or pure bitwise regions belong to those passes.
    if !reg.mixed || reg.bounds.is_empty() {
        return Ok((Step::Normal(Fin::FINAL), None));
    }
    let w = cx.width_of(n);
    // The lifted atoms are built now: `before` lets a rejection discard them.
    let before = cx.len() as u32;
    lift(r, cx, &mut reg, w.bits())?;
    let t = reg.atoms.len();
    if t > MAX_ATOMS {
        count(r).atomized += 1;
        return Ok((Step::Normal(Fin::FINAL), None));
    }
    let lifted = reg.lifts.len() as u32;
    r.meter
        .charge(Counter::PassWork, (reg.order.len() << t) as u64)?;
    let sig = signature(cx, &reg, n, &mut r.linear_mba);
    let d = mobius(&sig);
    // (The atoms, and so the corners, are already in the canonical order.)
    let canon = reg.atoms.clone();
    let mut cands: Vec<(u32, Candidate)> = Vec::new();
    if (0..d.len()).all(|s| (s as u32).count_ones() < 2 || d[s].is_zero()) {
        let konst = BitVec::un_unchecked(UnOp::Neg, &d[0]);
        let terms: Vec<(usize, BitVec)> = (0..t)
            .filter(|&j| !d[1 << j].is_zero())
            .map(|j| (j, d[1 << j]))
            .collect();
        let placeholder: Vec<(u32, BitVec)> =
            terms.iter().map(|(j, k)| (reg.atoms[*j], *k)).collect();
        let est = linear::estimate(&linear::Form::of(konst, &placeholder));
        cands.push((est, Candidate::Affine(konst, terms)));
    }
    if (0..d.len()).any(|s| (s as u32).count_ones() >= 2 && !d[s].is_zero()) {
        let konst = BitVec::un_unchecked(UnOp::Neg, &d[0]);
        let terms: Vec<(usize, BitVec)> = (1..d.len())
            .filter(|&s| !d[s].is_zero())
            .map(|s| (s, d[s]))
            .collect();
        // Each conjunction of m atoms costs m − 1 ands (an upper bound: none are shared).
        let ands: u32 = terms
            .iter()
            .map(|&(s, _)| (s as u32).count_ones() - 1)
            .sum();
        let placeholder: Vec<(u32, BitVec)> = terms
            .iter()
            .enumerate()
            .map(|(k, &(_, c))| (u32::MAX - k as u32, c))
            .collect();
        let est = ands + linear::estimate(&linear::Form::of(konst, &placeholder));
        cands.push((est, Candidate::Conjunctions(konst, terms)));

        // A form over the atoms the sum depends on has an operator fewer than there are of
        // them, at least: where replacing `n` frees no more than that, no form over the basis
        // commits, and the decomposition (the most this pass reads) is not looked for.
        let depends = (0..t)
            .filter(|&j| (1..d.len()).any(|s| s >> j & 1 == 1 && !d[s].is_zero()))
            .count() as u32;
        let least = (depends.saturating_sub(1) + lifted).saturating_sub(1);
        // (What the decomposition reads is pass work, within a share of the call's and what
        // is left of it: one that runs out of its share is no candidate, and the call goes
        // on. A chain's top that declines hands every link below it a decomposition of its
        // own.)
        let cobra = if r.inner.strategy.basis_sums
            && t >= 3
            && (!commit || super::can_pay(r, cx, n, &reg.bounds, least)?)
        {
            let share = (r.meter.limit.pass_work / COBRA_SHARE).max(1);
            let allow = r.meter.left_in(|b| b.pass_work).min(share);
            let mut left = allow;
            let terms = crate::cobra::decompose(t, w, u32::from(w.bits()), &d, &mut left);
            // An attempt cut short costs this pass its whole share.
            let spent = if terms.is_err() { allow } else { allow - left };
            r.meter.charge(Counter::PassWork, spent)?;
            terms.ok().flatten()
        } else {
            None
        };
        if let Some(cobra_terms) = cobra {
            let push_cobra =
                |cands: &mut Vec<(u32, Candidate)>,
                 k0: BitVec,
                 ts: Vec<(crate::cobra::BasisOp, BitVec)>| {
                    let gates: u32 = ts.iter().map(|(op, _)| op.gate_cost()).sum();
                    let ph: Vec<(u32, BitVec)> = ts
                        .iter()
                        .enumerate()
                        .map(|(idx, (_, c))| (u32::MAX - idx as u32, *c))
                        .collect();
                    let est = gates + linear::estimate(&linear::Form::of(k0, &ph));
                    cands.push((est, Candidate::Cobra(k0, ts)));
                };
            if !konst.is_zero() {
                let mut k_traded = konst;
                let mut t_traded = cobra_terms.clone();
                crate::cobra::trade_unmasked_constant(&mut k_traded, &mut t_traded);
                if k_traded.is_zero() {
                    push_cobra(&mut cands, k_traded, t_traded);
                }
            }
            push_cobra(&mut cands, konst, cobra_terms);
        }
    }
    if t <= 3 {
        // Distinct values, in order of first appearance; each as the base in turn.
        let mut distinct: Vec<BitVec> = Vec::new();
        for v in &sig {
            if !distinct.contains(v) {
                distinct.push(*v);
            }
        }
        // Corners in the canonical variable order.
        let pos: Vec<usize> = canon
            .iter()
            .map(|a| reg.atoms.iter().position(|b| b == a).unwrap_or(0))
            .collect();
        for &u0 in &distinct {
            let mut ind: Vec<(BitVec, u8)> = Vec::new();
            let mut funcs = 0u32;
            let mut placeholder: Vec<(u32, BitVec)> = Vec::new();
            for &uk in distinct.iter().filter(|&&u| u != u0) {
                let mut tt = 0u8;
                for i in 0..8usize {
                    // Canonical corner `i` → region corner.
                    let mut p = 0usize;
                    for (k, &j) in pos.iter().enumerate() {
                        p |= ((i >> k) & 1) << j;
                    }
                    if sig[p & ((1 << t) - 1)] == uk {
                        tt |= 1 << i;
                    }
                }
                // The function's operators and constants, plus its term in the sum.
                funcs += bitwise::min_forms().forms[tt as usize]
                    .0
                    .iter()
                    .filter(|t| !matches!(t, bitwise::T::Var(_)))
                    .count() as u32;
                let k = BitVec::bin_unchecked(BinOp::Sub, &u0, &uk);
                // (Distinct placeholder atoms: the estimate only needs the coefficients.)
                placeholder.push((u32::MAX - placeholder.len() as u32, k));
                ind.push((k, tt));
            }
            let est = funcs + linear::estimate(&linear::Form::of(u0, &placeholder));
            cands.push((est, Candidate::Indicators(u0, ind)));
        }
    }
    cands.sort_by_key(|c| c.0);
    let Some((est, cand)) = cands.into_iter().next() else {
        super::discard(r, cx, before);
        return Ok((Step::Normal(Fin::FINAL), None));
    };
    // (A form that only ties may still commit below: one node fewer is asked of it here.)
    let most = (est + lifted).saturating_sub(1);
    if commit && let Some(f) = worth_building(r, cx, n, &reg.bounds, most)? {
        count(r).rejected_cost += 1;
        super::discard(r, cx, before);
        return Ok((Step::Normal(f), None));
    }
    let kind = match &cand {
        Candidate::Affine(..) => "affine",
        Candidate::Indicators(..) => "indicators",
        Candidate::Cobra(..) => "cobra",
        Candidate::Conjunctions(..) => "conjunctions",
    };
    let form = match cand {
        Candidate::Affine(konst, terms) => {
            let terms: Vec<(u32, BitVec)> =
                terms.iter().map(|(j, k)| (reg.atoms[*j], *k)).collect();
            linear::Form::of(konst, &terms)
        }
        Candidate::Indicators(u0, ind) => {
            let mut terms = Vec::new();
            for (k, tt) in ind {
                let g = bitwise::emit(r, cx, tt, &canon)?;
                terms.push((g, k));
            }
            linear::Form::of(u0, &terms)
        }
        Candidate::Cobra(konst, ops) => {
            let mut terms = Vec::with_capacity(ops.len());
            for (op, k) in ops {
                let g = emit_basis_op(r, cx, &op, &reg.atoms)?;
                terms.push((g, k));
            }
            linear::Form::of(konst, &terms)
        }
        Candidate::Conjunctions(konst, sets) => {
            let mut terms = Vec::new();
            for (set, k) in sets {
                // The atoms of the set, in the canonical order, and-ed together.
                let mut acc: Option<u32> = None;
                for (j, &a) in reg.atoms.iter().enumerate() {
                    if set & (1 << j) != 0 {
                        acc = Some(match acc {
                            None => a,
                            Some(x) => r.build(cx, |cx| cx.c_bin(BinOp::And, x, a))?,
                        });
                    }
                }
                if let Some(g) = acc {
                    terms.push((g, k));
                }
            }
            linear::Form::of(konst, &terms)
        }
    };
    let e = linear::emit(r, cx, &form)?;
    if !commit {
        return Ok((Step::Normal(Fin::FINAL), Some(e)));
    }
    r.explain_with(|| crate::engine::Explanation::LinearMba {
        atoms: reg.atoms.iter().map(|&a| cx.handle(a)).collect(),
        corners: sig.clone(),
        form: kind,
    });
    // The form is the cheapest of its kind and nothing writes it back as the sum it was, so
    // it also commits where the DAG only ties and the tree gets smaller: `a + b - 2(a & b)`
    // whose `a + b` and `a & b` something else reads (the carries of limb arithmetic) frees
    // one node for the `a ^ b` it becomes, and every sum built on it then reads an XOR.
    let tree = |i: u32| cx.meta[i as usize].tree;
    let tie = tree(n) != u32::MAX && tree(e) < tree(n);
    let step = finish_with(
        r,
        cx,
        PassKind::LinearMba,
        n,
        e,
        before,
        &reg.bounds,
        Fin::FINAL,
        tie,
    )?;
    Ok((step, None))
}