Skip to main content

targeted_mutation/
plan.rs

1//! The planner: decides, from what the tests observed at a comparison, which mutations
2//! are guaranteed to survive (input gaps) and which ones the tests must be run against.
3//!
4//! Everything here is pure and works on `D = lhs - rhs`. Integer comparisons are threshold
5//! decisions on `D`, and the trace keeps only the observations nearest to zero. The proofs
6//! that this summary is enough, and that the survivor range is exact, are in
7//! `formal/lean/Planner.lean`.
8
9use serde::Serialize;
10
11/// Outcome of `partial_cmp`, as a bit in [`Obs`].
12#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13pub enum Rel {
14    Less,
15    Equal,
16    Greater,
17    Unordered,
18}
19
20#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
21#[serde(rename_all = "snake_case")]
22pub enum CmpOp {
23    Lt,
24    Le,
25    Gt,
26    Ge,
27    Eq,
28    Ne,
29}
30
31impl CmpOp {
32    pub const ALL: [CmpOp; 6] = [
33        CmpOp::Lt,
34        CmpOp::Le,
35        CmpOp::Gt,
36        CmpOp::Ge,
37        CmpOp::Eq,
38        CmpOp::Ne,
39    ];
40
41    pub fn code(self) -> u8 {
42        match self {
43            CmpOp::Lt => 0,
44            CmpOp::Le => 1,
45            CmpOp::Gt => 2,
46            CmpOp::Ge => 3,
47            CmpOp::Eq => 4,
48            CmpOp::Ne => 5,
49        }
50    }
51
52    pub fn from_code(code: u8) -> Option<CmpOp> {
53        CmpOp::ALL.into_iter().find(|op| op.code() == code)
54    }
55
56    pub fn symbol(self) -> &'static str {
57        match self {
58            CmpOp::Lt => "<",
59            CmpOp::Le => "<=",
60            CmpOp::Gt => ">",
61            CmpOp::Ge => ">=",
62            CmpOp::Eq => "==",
63            CmpOp::Ne => "!=",
64        }
65    }
66
67    pub fn is_ordering(self) -> bool {
68        !matches!(self, CmpOp::Eq | CmpOp::Ne)
69    }
70
71    /// 4-bit mask of `(lt, eq, gt, un)` relations on which this operator is `true`.
72    /// Proven equivalent to [`CmpOp::eval_rel`] in `formal/lean/Planner.lean`.
73    #[inline]
74    pub fn truth_mask(self) -> u8 {
75        match self {
76            CmpOp::Lt => 0b0001,
77            CmpOp::Le => 0b0011,
78            CmpOp::Gt => 0b0100,
79            CmpOp::Ge => 0b0110,
80            CmpOp::Eq => 0b0010,
81            CmpOp::Ne => 0b1101,
82        }
83    }
84
85    pub fn eval_rel(self, rel: Rel) -> bool {
86        let bit = match rel {
87            Rel::Less => 1,
88            Rel::Equal => 2,
89            Rel::Greater => 4,
90            Rel::Unordered => 8,
91        };
92        self.truth_mask() & bit != 0
93    }
94
95    /// The operator applied to integer operands whose difference is `d`.
96    pub fn eval_d(self, d: i128) -> bool {
97        self.eval_rel(match d {
98            d if d < 0 => Rel::Less,
99            0 => Rel::Equal,
100            _ => Rel::Greater,
101        })
102    }
103
104    /// `<` and `>` as each other and as `==`.
105    pub fn mistaken_for(self) -> &'static [CmpOp] {
106        match self {
107            CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt],
108            CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt],
109            _ => &[],
110        }
111    }
112
113    pub fn negated(self) -> CmpOp {
114        match self {
115            CmpOp::Lt => CmpOp::Ge,
116            CmpOp::Le => CmpOp::Gt,
117            CmpOp::Gt => CmpOp::Le,
118            CmpOp::Ge => CmpOp::Lt,
119            CmpOp::Eq => CmpOp::Ne,
120            CmpOp::Ne => CmpOp::Eq,
121        }
122    }
123
124    /// `<` <-> `<=`, `>` <-> `>=`: the classic off-by-one.
125    pub fn flip_eq(self) -> Option<CmpOp> {
126        match self {
127            CmpOp::Lt => Some(CmpOp::Le),
128            CmpOp::Le => Some(CmpOp::Lt),
129            CmpOp::Gt => Some(CmpOp::Ge),
130            CmpOp::Ge => Some(CmpOp::Gt),
131            CmpOp::Eq | CmpOp::Ne => None,
132        }
133    }
134
135    /// Threshold form over integers: `(up, t0)`. Up family is true iff `D >= t0`,
136    /// down family is true iff `D <= t0`.
137    fn threshold(self) -> Option<(bool, i128)> {
138        match self {
139            CmpOp::Ge => Some((true, 0)),
140            CmpOp::Gt => Some((true, 1)),
141            CmpOp::Le => Some((false, 0)),
142            CmpOp::Lt => Some((false, -1)),
143            CmpOp::Eq | CmpOp::Ne => None,
144        }
145    }
146}
147
148/// What the tests observed at one comparison, summarised. Merging is commutative,
149/// associative and idempotent, so trace lines can be folded in any order.
150#[derive(Clone, Copy, PartialEq, Debug, Default)]
151pub struct Obs {
152    pub lt: bool,
153    pub eq: bool,
154    pub gt: bool,
155    pub un: bool,
156    /// Some observation did not carry integer values, so `max_neg`/`min_pos` are incomplete.
157    pub unvalued: bool,
158    /// Largest observed `D < 0`.
159    pub max_neg: Option<i128>,
160    /// Smallest observed `D > 0`.
161    pub min_pos: Option<i128>,
162    /// Some observation did not carry float values, so the two fields below are incomplete.
163    pub unfloat: bool,
164    /// Largest observed negative and smallest observed positive float difference.
165    pub f_max_neg: Option<f64>,
166    pub f_min_pos: Option<f64>,
167}
168
169impl Obs {
170    /// Observed relations packed as a 4-bit mask (`lt=1, eq=2, gt=4, un=8`).
171    #[inline]
172    pub fn rels_mask(&self) -> u8 {
173        (self.lt as u8) | ((self.eq as u8) << 1) | ((self.gt as u8) << 2) | ((self.un as u8) << 3)
174    }
175
176    pub fn reached(&self) -> bool {
177        self.rels_mask() != 0
178    }
179
180    pub fn valued(&self) -> bool {
181        self.reached() && !self.unvalued
182    }
183
184    pub fn merge(&mut self, other: &Obs) {
185        self.lt |= other.lt;
186        self.eq |= other.eq;
187        self.gt |= other.gt;
188        self.un |= other.un;
189        self.unvalued |= other.unvalued;
190        self.max_neg = match (self.max_neg, other.max_neg) {
191            (Some(a), Some(b)) => Some(a.max(b)),
192            (a, b) => a.or(b),
193        };
194        self.min_pos = match (self.min_pos, other.min_pos) {
195            (Some(a), Some(b)) => Some(a.min(b)),
196            (a, b) => a.or(b),
197        };
198        self.unfloat |= other.unfloat;
199        self.f_max_neg = match (self.f_max_neg, other.f_max_neg) {
200            (Some(a), Some(b)) => Some(a.max(b)),
201            (a, b) => a.or(b),
202        };
203        self.f_min_pos = match (self.f_min_pos, other.f_min_pos) {
204            (Some(a), Some(b)) => Some(a.min(b)),
205            (a, b) => a.or(b),
206        };
207    }
208
209    /// Summary of a single observation of integer operands with difference `d`.
210    pub fn of_d(d: i128) -> Obs {
211        Obs {
212            lt: d < 0,
213            eq: d == 0,
214            gt: d > 0,
215            max_neg: (d < 0).then_some(d),
216            min_pos: (d > 0).then_some(d),
217            unfloat: true,
218            ..Obs::default()
219        }
220    }
221
222    /// Summary of a single observation without integer values.
223    pub fn of_rel(rel: Rel) -> Obs {
224        Obs {
225            lt: rel == Rel::Less,
226            eq: rel == Rel::Equal,
227            gt: rel == Rel::Greater,
228            un: rel == Rel::Unordered,
229            unvalued: true,
230            unfloat: true,
231            ..Obs::default()
232        }
233    }
234
235    /// Summary of a single observation of float operands with difference `d`.
236    pub fn of_f(d: f64) -> Obs {
237        Obs {
238            lt: d < 0.0,
239            eq: d == 0.0,
240            gt: d > 0.0,
241            unvalued: true,
242            f_max_neg: (d < 0.0).then_some(d),
243            f_min_pos: (d > 0.0).then_some(d),
244            ..Obs::default()
245        }
246    }
247
248    /// The gap around zero that no float observation fell into, when every observation
249    /// was a float and both sides were seen.
250    pub fn float_gap(&self) -> Option<(f64, f64)> {
251        // Nothing reached leaves both sides of the gap unset.
252        if self.unfloat || self.un {
253            return None;
254        }
255        Some((self.f_max_neg?, self.f_min_pos?))
256    }
257
258    /// Whether `d` itself was observed. Exact only for `d` in `-1..=1` on valued sites.
259    fn saw(&self, d: i128) -> bool {
260        match d {
261            0 => self.eq,
262            -1 => self.max_neg == Some(-1),
263            1 => self.min_pos == Some(1),
264            _ => unreachable!("only the values next to zero can be answered from the summary"),
265        }
266    }
267
268    /// Largest observation `<= x`, for `x` in `{-1, 0}`.
269    fn max_le(&self, x: i128) -> Option<i128> {
270        debug_assert!(x == -1 || x == 0);
271        if x == 0 && self.eq {
272            Some(0)
273        } else {
274            self.max_neg
275        }
276    }
277
278    /// Smallest observation `>= x`, for `x` in `{0, 1}`.
279    fn min_ge(&self, x: i128) -> Option<i128> {
280        debug_assert!(x == 0 || x == 1);
281        if x == 0 && self.eq {
282            Some(0)
283        } else {
284            self.min_pos
285        }
286    }
287
288    /// Whether any observation lies in `lo..=hi`. The interval must touch `-1..=1`
289    /// from the inside (no gap between it and zero), which is all the planner needs.
290    fn saw_any_in(&self, lo: i128, hi: i128) -> bool {
291        if lo > hi {
292            return false;
293        }
294        debug_assert!(
295            lo <= 1 && hi >= -1,
296            "interval {lo}..={hi} is not anchored at zero"
297        );
298        let zero = self.eq && lo <= 0 && 0 <= hi;
299        let neg = lo <= -1 && self.max_neg.is_some_and(|m| m >= lo);
300        let pos = hi >= 1 && self.min_pos.is_some_and(|p| p <= hi);
301        zero || neg || pos
302    }
303}
304
305#[derive(Clone, Copy, PartialEq, Debug, Serialize)]
306#[serde(rename_all = "snake_case")]
307pub enum Mutation {
308    /// Replace the comparison by a constant.
309    Const(bool),
310    /// Negate the comparison.
311    Negate,
312    /// Replace the operator.
313    Op(CmpOp),
314    /// `lhs op rhs + d` (integer operands only).
315    Shift(i128),
316    /// `lhs op rhs + d` for float operands.
317    ShiftF(f64),
318    /// Delete a statement.
319    Delete,
320    /// `&&` <-> `||`.
321    LogicSwap,
322    /// Ignore the value of the right operand of `&&` / `||` (`a && true`, `a || false`).
323    LogicDropRhs,
324    /// Ignore the value of the left operand of `&&` / `||`.
325    LogicDropLhs,
326    /// `+` <-> `-`, `*` <-> `/`, `%` -> `/`, `&` <-> `|`, `^` -> `&`, `<<` <-> `>>`.
327    ArithSwap,
328    /// The second replacement of an operator: `+` -> `*`, `-` -> `/`, `*` -> `+`,
329    /// `/` -> `%`, `%` -> `+`, `&` -> `^`, `|` -> `^`, `^` -> `|`.
330    ArithSwap2,
331    /// `!x` becomes `x`.
332    DropNot,
333    /// `a..b` becomes `a..=b` and the other way round.
334    RangeEnd,
335    /// `a.max(b)` becomes `a.min(b)` and the other way round.
336    MinMax,
337    /// `v.first()` becomes `v.last()` and the other way round.
338    OtherEnd,
339    /// `s.starts_with(p)` / `s.ends_with(p)` becomes `s.contains(p)`.
340    StrContains,
341    /// `s.replace(a, b)` becomes `s.replacen(a, b, 1)` and the other way round.
342    StrReplaceMultiplicity,
343    /// `x.clamp(lo, hi)` becomes `x.min(hi)` (drop lower bound).
344    ClampDropLower,
345    /// `x.clamp(lo, hi)` becomes `x.max(lo)` (drop upper bound).
346    ClampDropUpper,
347    /// First alternative rounding method (`floor`/`ceil`/`round`/`trunc`).
348    RoundAlt1,
349    /// Second alternative rounding method (`floor`/`ceil`/`round`/`trunc`).
350    RoundAlt2,
351    /// `iter.all(f)` <-> `iter.any(f)`.
352    QuantifierSwap,
353    /// `a.saturating_{add,sub,mul}(b)` <-> `a.wrapping_{add,sub,mul}(b)`.
354    SaturatingSwap,
355    /// First alternative trim method (`trim` -> `trim_start`, `trim_start`/`trim_end` -> `trim`).
356    TrimAlt1,
357    /// Second alternative trim method (`trim` -> `trim_end`).
358    TrimAlt2,
359    /// `a.eq_ignore_ascii_case(b)` -> `a == b`.
360    StrExactEq,
361    /// `x.abs()` -> `x`.
362    DropAbs,
363    /// `iter.take(n)` -> `iter.take(usize::MAX)` / `iter.skip(n)` -> `iter.skip(0)`.
364    IterLimitDrop,
365    /// `x.to_be_bytes()` <-> `x.to_le_bytes()`, `x.to_be()` <-> `x.to_le()`.
366    EndianSwap,
367    /// `x.leading_zeros()` <-> `x.trailing_zeros()`, `leading_ones` <-> `trailing_ones`.
368    BitCountSwap,
369    /// `break` <-> `continue`.
370    LoopCtrlSwap,
371    /// `[lit1, lit2, ...].contains(&x)`: drop the literal element at index `0..8`.
372    DropLiteralElem(u8),
373}
374
375impl Mutation {
376    /// Wire format shared with the injected runtime (`TMT_MUTANT=<site>:<encoded>`).
377    pub fn encode(&self) -> String {
378        match self {
379            Mutation::Const(c) => format!("c{}", *c as u8),
380            Mutation::Negate => "neg".to_string(),
381            Mutation::Op(op) => format!("op{}", op.code()),
382            Mutation::Shift(d) => format!("sh{d}"),
383            Mutation::ShiftF(d) => format!("shf{d:?}"),
384            Mutation::Delete => "del".to_string(),
385            Mutation::LogicSwap => "lsw".to_string(),
386            Mutation::LogicDropRhs => "ldr".to_string(),
387            Mutation::LogicDropLhs => "ldl".to_string(),
388            Mutation::ArithSwap => "asw".to_string(),
389            Mutation::ArithSwap2 => "as2".to_string(),
390            Mutation::DropNot => "unn".to_string(),
391            Mutation::RangeEnd => "rng".to_string(),
392            Mutation::MinMax => "mmx".to_string(),
393            Mutation::OtherEnd => "end".to_string(),
394            Mutation::StrContains => "stc".to_string(),
395            Mutation::StrReplaceMultiplicity => "srp".to_string(),
396            Mutation::ClampDropLower => "cll".to_string(),
397            Mutation::ClampDropUpper => "clu".to_string(),
398            Mutation::RoundAlt1 => "rd1".to_string(),
399            Mutation::RoundAlt2 => "rd2".to_string(),
400            Mutation::QuantifierSwap => "qsw".to_string(),
401            Mutation::SaturatingSwap => "sat".to_string(),
402            Mutation::TrimAlt1 => "tr1".to_string(),
403            Mutation::TrimAlt2 => "tr2".to_string(),
404            Mutation::StrExactEq => "seq".to_string(),
405            Mutation::DropAbs => "abs".to_string(),
406            Mutation::IterLimitDrop => "ilp".to_string(),
407            Mutation::EndianSwap => "edn".to_string(),
408            Mutation::BitCountSwap => "btc".to_string(),
409            Mutation::LoopCtrlSwap => "lpc".to_string(),
410            Mutation::DropLiteralElem(idx) => format!("dle{idx}"),
411        }
412    }
413}
414
415/// Result of the mutated comparison on integer operands with difference `d`.
416pub fn eval_mutated_d(op: CmpOp, m: Mutation, d: i128) -> bool {
417    match m {
418        Mutation::Const(c) => c,
419        Mutation::Negate => !op.eval_d(d),
420        Mutation::Op(op2) => op2.eval_d(d),
421        Mutation::Shift(s) => op.eval_d(d - s),
422        _ => op.eval_d(d),
423    }
424}
425
426/// Whether some observation in `obs` gets a different result under mutation `m`.
427/// A test that is not infected executes the mutant exactly like the original.
428pub fn infects(op: CmpOp, m: Mutation, obs: &Obs) -> bool {
429    match m {
430        Mutation::Const(c) => {
431            let mask = if c {
432                !op.truth_mask() & 0x0f
433            } else {
434                op.truth_mask()
435            };
436            obs.rels_mask() & mask != 0
437        }
438        Mutation::Op(op2) => obs.rels_mask() & (op.truth_mask() ^ op2.truth_mask()) != 0,
439        Mutation::Shift(s) => {
440            let Some((lo, hi)) = shift_diff(op, s) else {
441                return false;
442            };
443            if !obs.valued() {
444                // Without values we cannot rule the difference out.
445                return obs.reached();
446            }
447            obs.saw_any_in(lo, hi)
448        }
449        // A float shift is only ever proposed inside the unobserved gap.
450        Mutation::ShiftF(s) => match obs.float_gap() {
451            Some((lo, hi)) => !(lo < s && s < hi) || obs.eq,
452            None => obs.reached(),
453        },
454        // Negation, and what is not a mutation of a comparison: every execution differs.
455        _ => obs.reached(),
456    }
457}
458
459/// Whether two comparison mutations are universally equivalent on every integer
460/// difference `D` in `domain = [lo, hi]` (excluding `D = 0` when `zero_unreachable`).
461/// Proven sound in `formal/lean/Planner.lean` (`interval_equiv_from_samples`).
462pub fn domain_equivalent(
463    op: CmpOp,
464    m1: Mutation,
465    m2: Mutation,
466    domain: (i128, i128),
467    zero_unreachable: bool,
468) -> bool {
469    let (lo, hi) = domain;
470    let supported = |m: Mutation| match m {
471        Mutation::Const(_) | Mutation::Negate | Mutation::Op(_) => true,
472        // Runtime `Shift(s)` computes `d - s` in `i128`; exclude domains that can overflow.
473        Mutation::Shift(-1) => hi < i128::MAX,
474        Mutation::Shift(1) => lo > i128::MIN,
475        _ => false,
476    };
477    if lo > hi || !supported(m1) || !supported(m2) {
478        return false;
479    }
480    let agrees = |d: i128| eval_mutated_d(op, m1, d) == eval_mutated_d(op, m2, d);
481    if lo <= -2 && !agrees(-2) {
482        return false;
483    }
484    if 2 <= hi && !agrees(2) {
485        return false;
486    }
487    for d in [-1_i128, 0, 1] {
488        if d == 0 && zero_unreachable {
489            continue;
490        }
491        if lo <= d && d <= hi && !agrees(d) {
492            return false;
493        }
494    }
495    true
496}
497
498/// The values of `D` on which `lhs op rhs` and `lhs op rhs + s` disagree.
499fn shift_diff(op: CmpOp, s: i128) -> Option<(i128, i128)> {
500    let (up, t0) = op.threshold()?;
501    let t = t0 + s;
502    let (a, b) = (t0.min(t), t0.max(t));
503    // Up: true iff D >= threshold, so the two disagree on [a, b - 1].
504    // Down: true iff D <= threshold, so they disagree on [a + 1, b].
505    Some(if up { (a, b - 1) } else { (a + 1, b) })
506}
507
508/// A hole in the test inputs at one comparison: mutations that no test can tell apart
509/// from the original, because no test ever feeds the comparison a distinguishing value.
510#[derive(Clone, PartialEq, Debug, Serialize)]
511#[serde(rename_all = "snake_case", tag = "kind")]
512pub enum InputGap {
513    /// No test executes the comparison.
514    Unreached,
515    /// The comparison has the same result in every test; `Const(always)` survives.
516    OneSided { always: bool },
517    /// Every `Shift(d)` with `min_shift <= d <= max_shift`, `d != 0`, survives.
518    /// `missing` lists the unobserved values of `D` next to the boundary that would pin it.
519    Boundary {
520        min_shift: i128,
521        max_shift: i128,
522        missing: Vec<i128>,
523        /// The shifts from the first to the second of these answer like the original
524        /// for every value the expression can be (see [`within_reach`]): they are no
525        /// mutants. `(0, 0)` when it can be every number.
526        #[serde(skip_serializing_if = "no_shift")]
527        same: (i128, i128),
528    },
529    /// The operands were never equal (and carry no integer values); `Op(flipped)` survives.
530    /// For floats, `float_gap` is the range of differences no test observed: every
531    /// `ShiftF(d)` strictly inside it survives too.
532    EqualNeverObserved {
533        flipped: CmpOp,
534        float_gap: Option<(f64, f64)>,
535    },
536}
537
538fn no_shift(range: &(i128, i128)) -> bool {
539    *range == (0, 0)
540}
541
542#[derive(Clone, PartialEq, Debug, Default)]
543pub struct CmpPlan {
544    /// The comparison had one outcome in every test and its operand types allow no other
545    /// (`x >= 0` for unsigned `x`): whatever encloses it is constant for the same reason.
546    pub cannot_differ: bool,
547    pub gap: Option<InputGap>,
548    /// Mutations that change the outcome of at least one test's observation. Only running
549    /// the tests can tell whether an assertion notices.
550    pub run: Vec<Mutation>,
551}
552
553impl InputGap {
554    /// One concrete mutation that the gap lets through, nearest to the original.
555    pub fn representative(&self) -> Option<Mutation> {
556        match self {
557            InputGap::Unreached => None,
558            InputGap::OneSided { always } => Some(Mutation::Const(*always)),
559            InputGap::Boundary {
560                min_shift,
561                max_shift,
562                same,
563                ..
564            } => {
565                // The nearest shift that is a mutant.
566                if *max_shift > same.1 {
567                    Some(Mutation::Shift(same.1 + 1))
568                } else if *min_shift < same.0 {
569                    Some(Mutation::Shift(same.0 - 1))
570                } else {
571                    None
572                }
573            }
574            InputGap::EqualNeverObserved { flipped, .. } => Some(Mutation::Op(*flipped)),
575        }
576    }
577
578    /// Up to three concrete mutations the gap lets through, nearest to the original first.
579    pub fn survivors(&self) -> Vec<Mutation> {
580        match self {
581            InputGap::Boundary {
582                min_shift,
583                max_shift,
584                same,
585                ..
586            } => (1..=3)
587                .flat_map(|n| [same.1 + n, same.0 - n])
588                .filter(|s| min_shift <= s && s <= max_shift)
589                .take(3)
590                .map(Mutation::Shift)
591                .collect(),
592            InputGap::EqualNeverObserved { flipped, float_gap } => {
593                let mut all = vec![Mutation::Op(*flipped)];
594                if let Some((lo, hi)) = float_gap {
595                    all.extend([Mutation::ShiftF(hi / 2.0), Mutation::ShiftF(lo / 2.0)]);
596                }
597                all
598            }
599            other => other.representative().into_iter().collect(),
600        }
601    }
602}
603
604/// Plans one comparison site. `domain` is the range of `D` the operand types allow, when
605/// known. It only matters for a condition with a single observed outcome: if the types
606/// rule the other outcome out (`x >= 0` for unsigned `x`), there is nothing to report.
607pub fn plan_cmp(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
608    let mut plan = plan_boundary(op, obs, domain);
609    // The other operators a `<` or `>` is commonly mistaken for (the replacements
610    // cargo-mutants makes). One that answers like the original for every relation the
611    // tests saw runs like the original from the first step to the last and passes them
612    // all, which the gap already says. Every other one is run, also where it answers
613    // like another mutant for everything that was seen: once a mutant has changed the
614    // way the code goes, the comparison meets values the tests never gave it, and there
615    // the two may part.
616    let rels = obs.rels_mask();
617    let op_mask = op.truth_mask();
618    for other in op.mistaken_for() {
619        if rels & (op_mask ^ other.truth_mask()) != 0 {
620            plan.run.push(Mutation::Op(*other));
621        }
622    }
623    // `>` for `<=` and `<` for `>=` are the negation, except for operands that have no
624    // order (NaN): there the negation is true and the other operator false. Only
625    // integers are known to always have an order. For anything else the two are
626    // different mutants and both are run, whether or not the tests gave the comparison
627    // such operands: a mutant that changes the way the code goes can be the first to.
628    if matches!(op, CmpOp::Le | CmpOp::Ge)
629        && !obs.valued()
630        && rels & (op_mask ^ op.negated().truth_mask()) != 0
631    {
632        plan.run.push(Mutation::Op(op.negated()));
633    }
634    plan
635}
636
637fn plan_boundary(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
638    let rels = obs.rels_mask();
639    if rels == 0 {
640        return CmpPlan {
641            cannot_differ: false,
642            gap: Some(InputGap::Unreached),
643            run: vec![],
644        };
645    }
646    let op_mask = op.truth_mask();
647    let saw_true = rels & op_mask != 0;
648    let saw_false = rels & (!op_mask & 0x0f) != 0;
649    if !(saw_true && saw_false) {
650        let always = saw_true;
651        // Can the other outcome happen at all? Only checkable on integers with known types.
652        let other_possible = match domain {
653            // The domain is an interval that contains the observations, so if the other
654            // outcome is possible at all, it is possible next to zero.
655            Some((lo, hi)) if obs.valued() => [-1, 0, 1]
656                .into_iter()
657                .any(|d| lo <= d && d <= hi && op.eval_d(d) != always),
658            _ => true,
659        };
660        return CmpPlan {
661            cannot_differ: !other_possible,
662            gap: other_possible.then_some(InputGap::OneSided { always }),
663            run: vec![Mutation::Negate],
664        };
665    }
666
667    let Some((up, t0)) = op.threshold() else {
668        // `==` / `!=` with both outcomes observed: nothing to shift.
669        return CmpPlan {
670            cannot_differ: false,
671            gap: None,
672            run: vec![Mutation::Negate],
673        };
674    };
675
676    if !obs.valued() {
677        let flipped = op
678            .flip_eq()
679            .expect("ordering operators have a flipped form");
680        return if obs.eq {
681            CmpPlan {
682                cannot_differ: false,
683                gap: None,
684                run: vec![Mutation::Op(flipped), Mutation::Negate],
685            }
686        } else {
687            CmpPlan {
688                cannot_differ: false,
689                gap: Some(InputGap::EqualNeverObserved {
690                    flipped,
691                    float_gap: obs.float_gap(),
692                }),
693                run: vec![Mutation::Negate],
694            }
695        };
696    }
697
698    // Nearest observations on each side of the boundary, and the two values of D that
699    // straddle it: `w_minus` separates the original from Shift(-1), `w_plus` from Shift(+1).
700    let (below, above, w_minus, w_plus) = if up {
701        (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
702    } else {
703        (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
704    };
705    let below = below.expect("both outcomes were observed");
706    let above = above.expect("both outcomes were observed");
707    let (min_shift, max_shift) = if up {
708        (below + 1 - t0, above - t0)
709    } else {
710        (below - t0, above - 1 - t0)
711    };
712
713    // Both outcomes were observed, so both `w_minus` and `w_plus` lie between two observed
714    // values: they are inside the operand types' range and the mutants are not equivalent.
715    let mut missing = vec![];
716    let mut run = vec![];
717    for (w, shift) in [(w_minus, -1), (w_plus, 1)] {
718        if obs.saw(w) {
719            run.push(Mutation::Shift(shift));
720        } else {
721            missing.push(w);
722        }
723    }
724    run.push(Mutation::Negate);
725    let gap = (!missing.is_empty()).then_some(InputGap::Boundary {
726        min_shift,
727        max_shift,
728        missing,
729        same: (0, 0),
730    });
731    CmpPlan {
732        cannot_differ: false,
733        gap,
734        run,
735    }
736}
737
738/// What an integer expression can be whatever its inputs are, read from how it is
739/// written. Each holds also when the arithmetic wraps.
740#[derive(Clone, Copy, PartialEq, Eq, Debug)]
741pub enum Reach {
742    /// A multiple of this power of two (`x * 8`, `x << 3`).
743    Multiples(i128),
744    /// Not negative, with no bit outside of this mask (`x & 0xF0`).
745    Bits(i128),
746    /// Smaller in size than this (`x % 10`).
747    Below(i128),
748}
749
750impl Reach {
751    pub fn holds(self, value: i128) -> bool {
752        match self {
753            Reach::Multiples(step) => value % step == 0,
754            Reach::Bits(mask) => value >= 0 && value & !mask == 0,
755            Reach::Below(limit) => -limit < value && value < limit,
756        }
757    }
758
759    /// What `x << bits` can be for a type whose values go from `low` to `high`. Where
760    /// overflow is not checked, a shift by the width of the type or more is a shift by
761    /// the remainder: only that many low bits are sure to be zero. `None` when that is
762    /// none, or the width cannot be told.
763    pub fn of_shift(bits: u32, (low, high): (i128, i128)) -> Option<Reach> {
764        let values = high.checked_sub(low)?.checked_add(1)?;
765        if values < 2 || values & (values - 1) != 0 {
766            return None;
767        }
768        let effective = bits % values.trailing_zeros();
769        (effective > 0).then(|| Reach::Multiples(1 << effective))
770    }
771
772    /// The least and the greatest value the expression can be within `low..=high` (the
773    /// values of its type); `None` when there is none.
774    pub fn within(self, low: i128, high: i128) -> Option<(i128, i128)> {
775        let least = if self.holds(low) {
776            low
777        } else {
778            self.next_above(low)?
779        };
780        let greatest = if self.holds(high) {
781            high
782        } else {
783            self.next_below(high)?
784        };
785        (least <= greatest).then_some((least, greatest))
786    }
787
788    /// The numbers the expression lies between, where it has such bounds.
789    pub fn interval(self) -> Option<(i128, i128)> {
790        match self {
791            Reach::Multiples(_) => None,
792            Reach::Bits(mask) => Some((0, mask)),
793            Reach::Below(limit) => Some((1 - limit, limit - 1)),
794        }
795    }
796
797    /// The least value above `value` that the expression can be.
798    fn next_above(self, value: i128) -> Option<i128> {
799        match self {
800            Reach::Multiples(step) => value.div_euclid(step).checked_add(1)?.checked_mul(step),
801            Reach::Bits(_) if value < 0 => Some(0),
802            Reach::Bits(mask) => {
803                let over = value.checked_add(1)?;
804                let outside = over & !mask;
805                if outside == 0 {
806                    return Some(over);
807                }
808                // The bits from the highest one that is not of the mask down cannot
809                // stay: fill them and what else is not of the mask, so that adding one
810                // carries into the next bit of the mask above.
811                let top = 127 - outside.leading_zeros();
812                let low = 1_i128.checked_shl(top + 1)?.checked_sub(1)?;
813                let next = (over | !mask | low).wrapping_add(1) & mask;
814                (next > value).then_some(next)
815            }
816            Reach::Below(limit) => {
817                let next = value.checked_add(1)?.max(1 - limit);
818                (next < limit).then_some(next)
819            }
820        }
821    }
822
823    /// The greatest value below `value` that the expression can be.
824    fn next_below(self, value: i128) -> Option<i128> {
825        match self {
826            Reach::Multiples(step) => value.checked_sub(1)?.div_euclid(step).checked_mul(step),
827            Reach::Bits(_) if value <= 0 => None,
828            Reach::Bits(mask) => {
829                let under = value - 1;
830                let outside = under & !mask;
831                Some(if outside == 0 {
832                    under
833                } else {
834                    // Below the highest bit that is not of the mask, all of the mask.
835                    let top = 127 - outside.leading_zeros();
836                    let low = (1_i128 << top) - 1;
837                    (under & !low & !(1_i128 << top)) | (mask & low)
838                })
839            }
840            Reach::Below(limit) => {
841                let next = value.checked_sub(1)?.min(limit - 1);
842                (next > -limit).then_some(next)
843            }
844        }
845    }
846}
847
848/// The boundary gap of `expr op literal` (or `literal op expr`), given what the
849/// expression can be at all. `None` when no value it can be lies between the values
850/// the tests gave it: every shifted threshold then answers like the original, always.
851/// Otherwise the values to add are ones it can be, and a side that has none is left out.
852pub fn within_reach(
853    gap: InputGap,
854    op: CmpOp,
855    obs: &Obs,
856    reach: Reach,
857    literal: i128,
858    literal_is_rhs: bool,
859) -> Option<InputGap> {
860    let InputGap::Boundary {
861        min_shift,
862        max_shift,
863        missing,
864        same,
865    } = gap
866    else {
867        return Some(gap);
868    };
869    let Some((up, t0)) = op.threshold() else {
870        return Some(InputGap::Boundary {
871            min_shift,
872            max_shift,
873            missing,
874            same,
875        });
876    };
877    // As in `plan_boundary`: the nearest differences seen on each side, and the two
878    // next to the boundary.
879    let (below, above, w_minus, w_plus) = if up {
880        (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
881    } else {
882        (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
883    };
884    let (below, above) = (below?, above?);
885    // The expression's value for a difference, and back.
886    let value = |d: i128| {
887        if literal_is_rhs {
888            literal.checked_add(d)
889        } else {
890            literal.checked_sub(d)
891        }
892    };
893    let difference = |v: i128| {
894        if literal_is_rhs {
895            v.checked_sub(literal)
896        } else {
897            literal.checked_sub(v)
898        }
899    };
900    // The nearest difference the expression can make, from `start` towards `bound`
901    // (which it stops short of).
902    let nearest = |start: i128, bound: i128| -> Option<i128> {
903        if (start < bound) != (start <= bound) || start == bound {
904            return None;
905        }
906        let (from, to) = (value(start)?, value(bound)?);
907        let found = if reach.holds(from) {
908            from
909        } else if to > from {
910            reach.next_above(from)?
911        } else {
912            reach.next_below(from)?
913        };
914        let inside = if to > from { found < to } else { found > to };
915        inside.then(|| difference(found)).flatten()
916    };
917    let down = nearest(w_minus, below);
918    let up_side = nearest(w_plus, above);
919    let missing: Vec<i128> = [(w_minus, down), (w_plus, up_side)]
920        .into_iter()
921        .filter(|(w, _)| missing.contains(w))
922        .filter_map(|(_, nearest)| nearest)
923        .collect();
924    if missing.is_empty() {
925        return None;
926    }
927    // A threshold moved by less than it takes to reach the nearest value the expression
928    // can be, on either side, answers like the original for all of them. Where there is
929    // no such value short of what the tests gave, that is the whole side.
930    let (first_under, first_over) = (down.unwrap_or(below), up_side.unwrap_or(above));
931    let same = if up {
932        (first_under - t0 + 1, first_over - t0)
933    } else {
934        (first_under - t0, first_over - t0 - 1)
935    };
936    Some(InputGap::Boundary {
937        min_shift,
938        max_shift,
939        missing,
940        same: (same.0.max(min_shift).min(0), same.1.min(max_shift).max(0)),
941    })
942}
943
944/// What the tests observed at `a && b` / `a || b`.
945#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
946pub struct LogicObs {
947    /// The left operand decided alone (false for `&&`, true for `||`).
948    pub short: bool,
949    pub rhs_true: bool,
950    pub rhs_false: bool,
951    /// The right operand was started. Where it gave no value (a panic, a `?`, a
952    /// `return`) this is all there is to see of the expression having been executed.
953    pub rhs_started: bool,
954}
955
956impl LogicObs {
957    pub fn from_bits(bits: u8) -> LogicObs {
958        LogicObs {
959            short: bits & 1 != 0,
960            rhs_true: bits & 2 != 0,
961            rhs_false: bits & 4 != 0,
962            rhs_started: bits & 8 != 0,
963        }
964    }
965
966    pub fn merge(&mut self, other: &LogicObs) {
967        self.short |= other.short;
968        self.rhs_true |= other.rhs_true;
969        self.rhs_false |= other.rhs_false;
970        self.rhs_started |= other.rhs_started;
971    }
972
973    pub fn reached(&self) -> bool {
974        self.short || self.rhs_true || self.rhs_false || self.rhs_started
975    }
976
977    /// The value of the whole expression, if it was the same in every observation.
978    pub fn constant_value(&self, and: bool) -> Option<bool> {
979        // A short circuit yields false for `&&` and true for `||`.
980        let saw_true = self.rhs_true || (self.short && !and);
981        let saw_false = self.rhs_false || (self.short && and);
982        match (saw_true, saw_false) {
983            (true, false) => Some(true),
984            (false, true) => Some(false),
985            _ => None,
986        }
987    }
988
989    /// The right operand was evaluated and its value decided the result.
990    fn rhs_decided(&self, and: bool) -> bool {
991        if and { self.rhs_false } else { self.rhs_true }
992    }
993
994    /// Every observed evaluation produced a boolean value where `a && b == a || b`
995    /// (all `(false, false)` for `||`, or all `(true, true)` for `&&`).
996    ///
997    /// When the right operand only started without producing a value (panic / early exit),
998    /// swapping the operator skips that evaluation, so this returns `false`.
999    pub fn swap_never_changes_value(&self, and: bool) -> bool {
1000        !self.short && !self.rhs_decided(and) && (self.rhs_true || self.rhs_false)
1001    }
1002}
1003
1004#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
1005#[serde(rename_all = "snake_case")]
1006pub enum LogicGap {
1007    Unreached,
1008    /// No test has the right operand decide the result: `LogicDropRhs` survives.
1009    RhsNeverDecides,
1010    /// No test has the left operand decide the result: `LogicDropLhs` survives.
1011    LhsNeverDecides,
1012}
1013
1014#[derive(Clone, PartialEq, Debug, Default)]
1015pub struct LogicPlan {
1016    pub gaps: Vec<LogicGap>,
1017    pub run: Vec<Mutation>,
1018}
1019
1020/// Whether a test with these observations can execute differently under `m`.
1021/// Swapping the operator changes when the right operand is evaluated, so it is treated as
1022/// infecting every test that reaches the expression.
1023pub fn logic_infects(and: bool, m: Mutation, obs: &LogicObs) -> bool {
1024    match m {
1025        Mutation::LogicDropRhs => obs.rhs_decided(and),
1026        Mutation::LogicDropLhs => obs.short,
1027        _ => obs.reached(),
1028    }
1029}
1030
1031pub fn plan_logic(and: bool, obs: &LogicObs) -> LogicPlan {
1032    if !obs.reached() {
1033        return LogicPlan {
1034            gaps: vec![LogicGap::Unreached],
1035            run: vec![],
1036        };
1037    }
1038    let mut plan = LogicPlan::default();
1039    for (m, gap) in [
1040        (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1041        (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1042    ] {
1043        if logic_infects(and, m, obs) {
1044            plan.run.push(m);
1045        } else {
1046            plan.gaps.push(gap);
1047        }
1048    }
1049    plan.run.push(Mutation::LogicSwap);
1050    plan
1051}
1052
1053/// What the tests observed at an arithmetic operator on primitive numbers.
1054#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1055pub struct ArithObs {
1056    /// The swapped operator gave the same result.
1057    pub same: bool,
1058    /// The swapped operator gave a different result.
1059    pub differs: bool,
1060    /// The operands were not primitive numbers: nothing can be said.
1061    pub opaque: bool,
1062    /// The same for the operator's second replacement, where it has one.
1063    pub same2: bool,
1064    pub differs2: bool,
1065}
1066
1067impl ArithObs {
1068    pub fn from_bits(bits: u8) -> ArithObs {
1069        ArithObs {
1070            same: bits & 1 != 0,
1071            differs: bits & 2 != 0,
1072            opaque: bits & 4 != 0,
1073            same2: bits & 8 != 0,
1074            differs2: bits & 16 != 0,
1075        }
1076    }
1077
1078    pub fn merge(&mut self, other: &ArithObs) {
1079        self.same |= other.same;
1080        self.differs |= other.differs;
1081        self.opaque |= other.opaque;
1082        self.same2 |= other.same2;
1083        self.differs2 |= other.differs2;
1084    }
1085
1086    /// The observations as they are for the second replacement.
1087    pub fn second(&self) -> ArithObs {
1088        ArithObs {
1089            same: self.same2,
1090            differs: self.differs2,
1091            opaque: self.opaque,
1092            same2: false,
1093            differs2: false,
1094        }
1095    }
1096
1097    /// Whether mutation `m` computes another value in this test.
1098    pub fn infected_by(&self, m: Mutation) -> bool {
1099        if matches!(
1100            m,
1101            Mutation::ArithSwap2
1102                | Mutation::ClampDropUpper
1103                | Mutation::RoundAlt2
1104                | Mutation::TrimAlt2
1105        ) {
1106            self.differs2
1107        } else {
1108            self.differs
1109        }
1110    }
1111}
1112
1113#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1114pub enum ArithPlan {
1115    Unreached,
1116    /// Not primitive numbers: not mutated.
1117    Opaque,
1118    /// The swapped operator agrees on every observed pair of operands: it survives.
1119    NeverDiffers,
1120    /// Some test computes a different value: run `ArithSwap` against those tests.
1121    Run,
1122}
1123
1124pub fn plan_arith(obs: &ArithObs) -> ArithPlan {
1125    if obs.differs {
1126        ArithPlan::Run
1127    } else if obs.same {
1128        ArithPlan::NeverDiffers
1129    } else if obs.opaque {
1130        ArithPlan::Opaque
1131    } else {
1132        ArithPlan::Unreached
1133    }
1134}
1135
1136/// What a `-> bool` function returned at its normal exit.
1137#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1138pub struct ReturnObs {
1139    pub saw_true: bool,
1140    pub saw_false: bool,
1141}
1142
1143impl ReturnObs {
1144    pub fn from_bits(bits: u8) -> ReturnObs {
1145        ReturnObs {
1146            saw_true: bits & 1 != 0,
1147            saw_false: bits & 2 != 0,
1148        }
1149    }
1150
1151    pub fn merge(&mut self, other: &ReturnObs) {
1152        self.saw_true |= other.saw_true;
1153        self.saw_false |= other.saw_false;
1154    }
1155
1156    pub fn reached(&self) -> bool {
1157        self.saw_true || self.saw_false
1158    }
1159
1160    /// Whether replacing the returned value by `value` changes anything for this test.
1161    pub fn infected_by_const(&self, value: bool) -> bool {
1162        if value { self.saw_false } else { self.saw_true }
1163    }
1164}
1165
1166/// Observations at a `[lit1, lit2, ...].contains(&x)` site.
1167#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1168pub struct LitSetObs {
1169    pub reached: bool,
1170    pub opaque: bool,
1171    /// Bit `i` (`0..8`) is set when the argument equaled literal element `i`.
1172    pub matched: u8,
1173}
1174
1175impl LitSetObs {
1176    pub fn from_bits(bits: u16) -> LitSetObs {
1177        LitSetObs {
1178            reached: bits & 256 != 0,
1179            opaque: bits & 512 != 0,
1180            matched: (bits & 0xFF) as u8,
1181        }
1182    }
1183
1184    pub fn merge(&mut self, other: &LitSetObs) {
1185        self.reached |= other.reached;
1186        self.opaque |= other.opaque;
1187        self.matched |= other.matched;
1188    }
1189
1190    pub fn matched_elem(&self, idx: u8) -> bool {
1191        idx < 8 && (self.matched & (1u8 << idx)) != 0
1192    }
1193}
1194
1195#[derive(Clone, PartialEq, Debug, Default)]
1196pub struct ReturnPlan {
1197    pub unreached: bool,
1198    /// The function returned only this value: `Const(value)` survives.
1199    pub always: Option<bool>,
1200    pub run: Vec<Mutation>,
1201}
1202
1203/// Plans a function returning `Option<T>`, where `saw_true` stands for `Some` and
1204/// `saw_false` for `None`. The result can be replaced by `None` but not by a `Some`.
1205pub fn plan_option_return(obs: &ReturnObs) -> ReturnPlan {
1206    match (obs.saw_true, obs.saw_false) {
1207        (false, false) => ReturnPlan {
1208            unreached: true,
1209            ..ReturnPlan::default()
1210        },
1211        // Never `Some`: always returning `None` passes every test.
1212        (false, true) => ReturnPlan {
1213            unreached: false,
1214            always: Some(false),
1215            run: vec![],
1216        },
1217        (true, _) => ReturnPlan {
1218            unreached: false,
1219            always: None,
1220            run: vec![Mutation::Const(false)],
1221        },
1222    }
1223}
1224
1225pub fn plan_return(obs: &ReturnObs) -> ReturnPlan {
1226    match (obs.saw_true, obs.saw_false) {
1227        (false, false) => ReturnPlan {
1228            unreached: true,
1229            ..ReturnPlan::default()
1230        },
1231        (true, true) => ReturnPlan {
1232            run: vec![Mutation::Const(true), Mutation::Const(false)],
1233            ..ReturnPlan::default()
1234        },
1235        (always, _) => ReturnPlan {
1236            unreached: false,
1237            always: Some(always),
1238            run: vec![Mutation::Const(!always)],
1239        },
1240    }
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245    use super::*;
1246
1247    const REACHES: [Reach; 5] = [
1248        Reach::Multiples(4),
1249        Reach::Multiples(8),
1250        Reach::Bits(0b1010),
1251        Reach::Bits(0b0110),
1252        Reach::Below(5),
1253    ];
1254
1255    #[test]
1256    fn the_next_value_an_expression_can_be() {
1257        for reach in REACHES {
1258            for value in -40..=40_i128 {
1259                let above = (value + 1..=80).find(|v| reach.holds(*v));
1260                let below = (-80..value).rev().find(|v| reach.holds(*v));
1261                assert_eq!(reach.next_above(value), above, "{reach:?} above {value}");
1262                assert_eq!(reach.next_below(value), below, "{reach:?} below {value}");
1263            }
1264        }
1265        // At the ends of the numbers there is no next one.
1266        assert_eq!(Reach::Multiples(8).next_above(i128::MAX), None);
1267        assert_eq!(Reach::Multiples(8).next_below(i128::MIN), None);
1268        assert_eq!(Reach::Below(5).next_above(i128::MAX), None);
1269        assert_eq!(Reach::Below(5).next_below(i128::MIN), None);
1270        assert_eq!(Reach::Bits(i128::MAX).next_above(i128::MAX), None);
1271        assert!(Reach::Bits(0xF0).holds(0x30) && !Reach::Bits(0xF0).holds(0x31));
1272        assert!(!Reach::Bits(0xF0).holds(-16));
1273    }
1274
1275    /// Every pair of values the expression can be, one on each side of the boundary,
1276    /// as what the tests saw: the gap that is left is checked against all the values
1277    /// the expression can be.
1278    #[test]
1279    fn a_gap_is_kept_only_for_values_the_expression_can_be() {
1280        let mut dropped = 0;
1281        let mut kept = 0;
1282        for reach in REACHES {
1283            let can_be: Vec<i128> = (-24..=24).filter(|v| reach.holds(*v)).collect();
1284            for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1285                for literal in -6..=14_i128 {
1286                    for literal_is_rhs in [true, false] {
1287                        let d_of = |v: i128| {
1288                            if literal_is_rhs {
1289                                v - literal
1290                            } else {
1291                                literal - v
1292                            }
1293                        };
1294                        for &low in &can_be {
1295                            for &high in can_be.iter().filter(|v| **v > low) {
1296                                let mut obs = Obs::of_d(d_of(low));
1297                                obs.merge(&Obs::of_d(d_of(high)));
1298                                let Some(gap @ InputGap::Boundary { .. }) =
1299                                    plan_boundary(op, &obs, None).gap
1300                                else {
1301                                    continue;
1302                                };
1303                                let InputGap::Boundary {
1304                                    min_shift,
1305                                    max_shift,
1306                                    ..
1307                                } = gap.clone()
1308                                else {
1309                                    unreachable!()
1310                                };
1311                                // A threshold moved by `shift` answers `op` for the
1312                                // difference less the shift.
1313                                let differs = |shift: i128, v: i128| {
1314                                    op.eval_d(d_of(v)) != op.eval_d(d_of(v) - shift)
1315                                };
1316                                let told_apart =
1317                                    |shift: i128| can_be.iter().any(|v| differs(shift, *v));
1318                                let case = format!(
1319                                    "{reach:?} {op:?} literal {literal} rhs {literal_is_rhs}, saw {low} and {high}"
1320                                );
1321                                match within_reach(gap, op, &obs, reach, literal, literal_is_rhs) {
1322                                    None => {
1323                                        // Nothing it can be tells any of them apart.
1324                                        for shift in min_shift..=max_shift {
1325                                            assert!(!told_apart(shift), "{case}: shift {shift}");
1326                                        }
1327                                        dropped += 1;
1328                                    }
1329                                    Some(InputGap::Boundary {
1330                                        min_shift: least,
1331                                        max_shift: most,
1332                                        missing,
1333                                        same,
1334                                    }) => {
1335                                        assert!(!missing.is_empty(), "{case}");
1336                                        assert_eq!((least, most), (min_shift, max_shift), "{case}");
1337                                        for d in &missing {
1338                                            let v = if literal_is_rhs {
1339                                                literal + d
1340                                            } else {
1341                                                literal - d
1342                                            };
1343                                            assert!(reach.holds(v), "{case}: {v}");
1344                                            assert!(low < v && v < high, "{case}: {v}");
1345                                        }
1346                                        // The shifts called the same are exactly those that
1347                                        // nothing the expression can be tells apart.
1348                                        assert!(same.0 <= 0 && 0 <= same.1, "{case}: {same:?}");
1349                                        for shift in least..=most {
1350                                            assert_eq!(
1351                                                same.0 <= shift && shift <= same.1,
1352                                                !told_apart(shift),
1353                                                "{case}: shift {shift}, same {same:?}"
1354                                            );
1355                                        }
1356                                        // The values to add find out every other one of a
1357                                        // side that has a value to add.
1358                                        let gap = InputGap::Boundary {
1359                                            min_shift: least,
1360                                            max_shift: most,
1361                                            missing: missing.clone(),
1362                                            same,
1363                                        };
1364                                        for mutation in gap.survivors() {
1365                                            let Mutation::Shift(shift) = mutation else {
1366                                                panic!("{case}: {mutation:?}")
1367                                            };
1368                                            assert!(told_apart(shift), "{case}: shift {shift}");
1369                                        }
1370                                        assert!(gap.representative().is_some(), "{case}");
1371                                        kept += 1;
1372                                    }
1373                                    Some(other) => panic!("{case}: {other:?}"),
1374                                }
1375                            }
1376                        }
1377                    }
1378                }
1379            }
1380        }
1381        assert!(
1382            dropped > 100 && kept > 1000,
1383            "{dropped} dropped, {kept} kept"
1384        );
1385    }
1386
1387    #[test]
1388    fn an_outcome_no_value_gives_is_not_asked_for() {
1389        // `n % 10 < 10` is true for whatever `n` is, `flags & 0xF0 > 0xF0` never is.
1390        for (reach, literal, op, differs) in [
1391            (Reach::Below(10), 10, CmpOp::Lt, false),
1392            (Reach::Below(10), 9, CmpOp::Lt, true),
1393            (Reach::Below(10), -10, CmpOp::Gt, false),
1394            (Reach::Bits(0xF0), 0xF0, CmpOp::Gt, false),
1395            (Reach::Bits(0xF0), 0xF0, CmpOp::Ge, true),
1396            (Reach::Bits(0xF0), 0, CmpOp::Lt, false),
1397        ] {
1398            let (lo, hi) = reach.interval().unwrap();
1399            assert!((lo..=hi).all(|v| !reach.holds(v) || (lo <= v && v <= hi)));
1400            assert!(reach.holds(lo) && reach.holds(hi), "{reach:?}");
1401            assert!(!reach.holds(lo - 1) && !reach.holds(hi + 1), "{reach:?}");
1402            let can_differ = (lo..=hi)
1403                .filter(|v| reach.holds(*v))
1404                .map(|v| op.eval_d(v - literal))
1405                .collect::<std::collections::BTreeSet<_>>()
1406                .len()
1407                == 2;
1408            assert_eq!(can_differ, differs, "{reach:?} {op:?} {literal}");
1409            // One value seen: the plan asks for the other outcome only if there is one.
1410            let seen = (lo..=hi).find(|v| reach.holds(*v)).unwrap();
1411            let plan = plan_cmp(
1412                op,
1413                &Obs::of_d(seen - literal),
1414                Some((lo - literal, hi - literal)),
1415            );
1416            assert_eq!(plan.cannot_differ, !differs, "{reach:?} {op:?} {literal}");
1417            assert_eq!(plan.gap.is_some(), differs, "{reach:?} {op:?} {literal}");
1418        }
1419        assert_eq!(Reach::Multiples(8).interval(), None);
1420    }
1421
1422    #[test]
1423    fn a_shift_is_a_multiple_by_the_bits_that_are_shifted_in_fact() {
1424        let (byte, signed_byte) = ((0, 255), (-128, 127));
1425        for (bits, range, expected) in [
1426            (3, byte, Some(Reach::Multiples(8))),
1427            (7, byte, Some(Reach::Multiples(128))),
1428            // By the width and more: the remainder is what is shifted.
1429            (8, byte, None),
1430            (9, byte, Some(Reach::Multiples(2))),
1431            (16, byte, None),
1432            (9, signed_byte, Some(Reach::Multiples(2))),
1433            (33, (0, u32::MAX as i128), Some(Reach::Multiples(2))),
1434            (3, (0, u32::MAX as i128), Some(Reach::Multiples(8))),
1435            // No width to tell: nothing is said.
1436            (3, (0, 9), None),
1437            (3, (0, 0), None),
1438            (3, (5, 4), None),
1439            (3, (i128::MIN, i128::MAX), None),
1440        ] {
1441            assert_eq!(Reach::of_shift(bits, range), expected, "{bits} {range:?}");
1442        }
1443        // Against what a byte does when overflow is not checked.
1444        for bits in 1..=20u32 {
1445            let reach = Reach::of_shift(bits, byte);
1446            for n in 0..=255u8 {
1447                let shifted = i128::from(n.wrapping_shl(bits));
1448                assert!(
1449                    reach.is_none_or(|reach| reach.holds(shifted)),
1450                    "{n} << {bits}"
1451                );
1452            }
1453        }
1454    }
1455
1456    #[test]
1457    fn the_ends_of_what_an_expression_can_be_in_its_type() {
1458        for reach in REACHES {
1459            for (low, high) in [(0, 255), (-128, 127), (0, 0), (3, 3), (5, 9)] {
1460                let all: Vec<i128> = (low..=high).filter(|v| reach.holds(*v)).collect();
1461                assert_eq!(
1462                    reach.within(low, high),
1463                    all.first().copied().zip(all.last().copied()),
1464                    "{reach:?} in {low}..={high}"
1465                );
1466            }
1467        }
1468        // `x << 1` of a byte is 254 at most: `< 255` has no other outcome.
1469        assert_eq!(Reach::Multiples(2).within(0, 255), Some((0, 254)));
1470    }
1471
1472    #[test]
1473    fn gaps_of_another_kind_are_not_touched() {
1474        let obs = Obs::of_d(3);
1475        for gap in [
1476            InputGap::Unreached,
1477            InputGap::OneSided { always: true },
1478            InputGap::EqualNeverObserved {
1479                flipped: CmpOp::Le,
1480                float_gap: None,
1481            },
1482        ] {
1483            assert_eq!(
1484                within_reach(gap.clone(), CmpOp::Lt, &obs, Reach::Multiples(8), 20, true),
1485                Some(gap)
1486            );
1487        }
1488        // `blocks * 8 > 20` seen at 16 and 24: nothing between them is a multiple of 8.
1489        let mut obs = Obs::of_d(16 - 20);
1490        obs.merge(&Obs::of_d(24 - 20));
1491        let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1492        assert_eq!(
1493            within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1494            None
1495        );
1496        // Seen at 8 and 40: 16 and 24 are the values next to the boundary.
1497        let mut obs = Obs::of_d(8 - 20);
1498        obs.merge(&Obs::of_d(40 - 20));
1499        let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1500        assert_eq!(
1501            within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1502            Some(InputGap::Boundary {
1503                min_shift: -12,
1504                max_shift: 19,
1505                missing: vec![-4, 4],
1506                // `> 16` to `> 23` answer like `> 20` for 16 and 24, and all between.
1507                same: (-4, 3),
1508            })
1509        );
1510    }
1511
1512    fn obs_of(ds: &[i128]) -> Obs {
1513        let mut obs = Obs::default();
1514        for d in ds {
1515            obs.merge(&Obs::of_d(*d));
1516        }
1517        obs
1518    }
1519
1520    fn rel_of(d: i128) -> Rel {
1521        match d {
1522            d if d < 0 => Rel::Less,
1523            0 => Rel::Equal,
1524            _ => Rel::Greater,
1525        }
1526    }
1527
1528    /// Ground truth: does any concrete observation change under the mutation?
1529    fn brute_infects(op: CmpOp, m: Mutation, ds: &[i128]) -> bool {
1530        ds.iter()
1531            .any(|d| op.eval_d(*d) != eval_mutated_d(op, m, *d))
1532    }
1533
1534    #[test]
1535    fn is_eligible_example_from_the_readme() {
1536        // `age >= 18`, tests pass 17 and 20: D = -1 and 2.
1537        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[-1, 2]), None);
1538        assert_eq!(
1539            plan.gap,
1540            Some(InputGap::Boundary {
1541                min_shift: 0,
1542                max_shift: 2,
1543                missing: vec![0],
1544                same: (0, 0),
1545            })
1546        );
1547        // 17 is observed, so `age >= 17` flips a test outcome and has to be run.
1548        assert_eq!(plan.run, vec![Mutation::Shift(-1), Mutation::Negate]);
1549        assert_eq!(plan.gap.unwrap().representative(), Some(Mutation::Shift(1)));
1550    }
1551
1552    /// Every operator `<` and `>` are mistaken for is accounted for, whatever the tests
1553    /// saw: it answers like the original for all of it and passes (a gap says so), or
1554    /// it is run. It is never left to another mutant that answers alike: two mutants
1555    /// that both change the way the code goes meet different values afterwards.
1556    #[test]
1557    fn the_operators_a_comparison_is_mistaken_for() {
1558        let rels = [Rel::Less, Rel::Equal, Rel::Greater, Rel::Unordered];
1559        for op in [CmpOp::Lt, CmpOp::Gt] {
1560            for seen in 1u8..16 {
1561                let mut obs = Obs::default();
1562                let seen: Vec<Rel> = (0..4)
1563                    .filter(|i| seen & (1 << i) != 0)
1564                    .map(|i| rels[i])
1565                    .collect();
1566                for rel in &seen {
1567                    obs.merge(&Obs::of_rel(*rel));
1568                }
1569                let plan = plan_cmp(op, &obs, None);
1570                for other in op.mistaken_for() {
1571                    let like_the_original = seen
1572                        .iter()
1573                        .all(|rel| other.eval_rel(*rel) == op.eval_rel(*rel));
1574                    let what = format!("{op:?} as {other:?} with {seen:?}: {plan:?}");
1575                    let run = plan
1576                        .run
1577                        .iter()
1578                        .filter(|m| **m == Mutation::Op(*other))
1579                        .count();
1580                    if like_the_original {
1581                        assert!(plan.gap.is_some(), "{what}");
1582                        assert_eq!(run, 0, "{what}");
1583                    } else {
1584                        assert_eq!(run, 1, "{what}");
1585                    }
1586                }
1587            }
1588        }
1589        // The other operators get nothing added.
1590        for op in [CmpOp::Le, CmpOp::Ge, CmpOp::Eq, CmpOp::Ne] {
1591            assert!(op.mistaken_for().is_empty());
1592        }
1593        // `>` for `<=` and `<` for `>=` are the negation unless the operands have no
1594        // order, and only integers are known to always have one. For anything else the
1595        // operator is run beside the negation wherever it answers otherwise than the
1596        // original, whether or not the tests gave operands without an order.
1597        let seen = |rels: &[Rel]| {
1598            let mut obs = Obs::default();
1599            for rel in rels {
1600                obs.merge(&Obs::of_rel(*rel));
1601            }
1602            obs
1603        };
1604        for (op, reverse) in [(CmpOp::Ge, CmpOp::Lt), (CmpOp::Le, CmpOp::Gt)] {
1605            let run = |rels: &[Rel]| plan_cmp(op, &seen(rels), None).run;
1606            let reversed = |rels: &[Rel]| run(rels).contains(&Mutation::Op(reverse));
1607            assert!(reversed(&[Rel::Unordered, Rel::Less]), "{op:?}");
1608            assert!(reversed(&[Rel::Less, Rel::Greater]), "{op:?}");
1609            assert!(reversed(&[Rel::Less, Rel::Equal, Rel::Greater]), "{op:?}");
1610            // Where the operator answers like the original for all that was seen, it
1611            // passes and is not run: only operands without an order, or only the side
1612            // on which both are false.
1613            assert_eq!(run(&[Rel::Unordered]), vec![Mutation::Negate], "{op:?}");
1614            // Integers: the negation is the operator, at every distance.
1615            for ds in [&[-1i128, 1][..], &[-2, 0, 3], &[0, 1]] {
1616                let plan = plan_cmp(op, &obs_of(ds), None);
1617                assert!(!plan.run.contains(&Mutation::Op(reverse)), "{op:?} {ds:?}");
1618            }
1619            for d in -3..=3 {
1620                assert_eq!(eval_mutated_d(op, Mutation::Negate, d), reverse.eval_d(d));
1621            }
1622        }
1623        // `!=` for `==` is the negation with and without an order.
1624        let run = plan_cmp(CmpOp::Eq, &seen(&[Rel::Unordered, Rel::Equal]), None).run;
1625        assert_eq!(run, vec![Mutation::Negate]);
1626        // Seen above the bound only, `>=` and `>` in place of `<` answer alike, and
1627        // both are run: the first step they change, they go different ways.
1628        let plan = plan_cmp(CmpOp::Lt, &Obs::of_rel(Rel::Greater), None);
1629        assert_eq!(plan.run, vec![Mutation::Negate, Mutation::Op(CmpOp::Gt)]);
1630    }
1631
1632    #[test]
1633    fn pinned_boundary_has_no_input_gap() {
1634        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1635            let plan = plan_cmp(op, &obs_of(&[-1, 0, 1]), None);
1636            assert_eq!(plan.gap, None, "{op:?}");
1637            // With all three relations seen, no two operators answer alike.
1638            let mut run = vec![Mutation::Shift(-1), Mutation::Shift(1), Mutation::Negate];
1639            run.extend(op.mistaken_for().iter().map(|other| Mutation::Op(*other)));
1640            assert_eq!(plan.run, run, "{op:?}");
1641        }
1642    }
1643
1644    #[test]
1645    fn unreached_site() {
1646        let plan = plan_cmp(CmpOp::Lt, &Obs::default(), None);
1647        assert_eq!(
1648            plan,
1649            CmpPlan {
1650                cannot_differ: false,
1651                gap: Some(InputGap::Unreached),
1652                run: vec![]
1653            }
1654        );
1655    }
1656
1657    #[test]
1658    fn one_sided_condition() {
1659        let plan = plan_cmp(CmpOp::Gt, &obs_of(&[3, 5]), None);
1660        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1661        // Always true: the negation, `==` and `<` are all false here, and each is run.
1662        assert_eq!(
1663            plan.run,
1664            vec![
1665                Mutation::Negate,
1666                Mutation::Op(CmpOp::Eq),
1667                Mutation::Op(CmpOp::Lt)
1668            ]
1669        );
1670    }
1671
1672    #[test]
1673    fn unsigned_compared_with_zero_is_not_reported() {
1674        // `x >= 0` for unsigned x: D ranges over 0..=MAX, the condition cannot be false.
1675        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((0, 255)));
1676        assert_eq!(plan.gap, None);
1677        assert!(plan.cannot_differ);
1678        assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 255))).cannot_differ);
1679        assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[-1, 4]), Some((-1, 255))).cannot_differ);
1680        // `x < 0` for unsigned x can never be true either.
1681        let plan = plan_cmp(CmpOp::Lt, &obs_of(&[0, 4]), Some((0, 255)));
1682        assert_eq!(plan.gap, None);
1683        // `x >= 1` for unsigned x written as `x > 0`, observed at 0 and 1: both neighbours
1684        // are real mutants (`x > -1` is `x >= 0`, which differs at 0).
1685        let plan = plan_cmp(CmpOp::Gt, &obs_of(&[0, 1]), Some((0, 255)));
1686        assert_eq!(plan.gap, None);
1687        // `x == 0` answers like the negation at 0 and 1, and is run all the same.
1688        assert_eq!(
1689            plan.run,
1690            vec![
1691                Mutation::Shift(-1),
1692                Mutation::Shift(1),
1693                Mutation::Negate,
1694                Mutation::Op(CmpOp::Eq),
1695                Mutation::Op(CmpOp::Lt)
1696            ]
1697        );
1698        // `x <= 0` for unsigned x, observed at 0 and 1: `x <= -1` is a real mutant too,
1699        // but `x < 0`-style thresholds below the domain are not counted twice.
1700        let plan = plan_cmp(CmpOp::Le, &obs_of(&[0, 1]), Some((0, 255)));
1701        assert_eq!(plan.gap, None);
1702    }
1703
1704    #[test]
1705    fn one_sided_condition_at_the_edge_of_the_type() {
1706        // Always true, and the only value that makes it false is the type's minimum.
1707        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 10)));
1708        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1709        // ... or its maximum.
1710        let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 1)));
1711        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1712        let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 0)));
1713        assert_eq!(plan.gap, None);
1714        // Without values the types are unknown: report.
1715        let plan = plan_cmp(CmpOp::Ge, &Obs::of_rel(Rel::Greater), Some((0, 10)));
1716        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1717    }
1718
1719    #[test]
1720    fn representative_is_the_nearest_survivor() {
1721        let boundary = |min_shift, max_shift| InputGap::Boundary {
1722            min_shift,
1723            max_shift,
1724            missing: vec![0],
1725            same: (0, 0),
1726        };
1727        assert_eq!(boundary(-3, 1).representative(), Some(Mutation::Shift(1)));
1728        assert_eq!(boundary(-1, 0).representative(), Some(Mutation::Shift(-1)));
1729        assert_eq!(boundary(0, 0).representative(), None);
1730        assert_eq!(InputGap::Unreached.representative(), None);
1731        assert_eq!(
1732            InputGap::OneSided { always: false }.representative(),
1733            Some(Mutation::Const(false))
1734        );
1735        assert_eq!(
1736            InputGap::EqualNeverObserved {
1737                flipped: CmpOp::Ge,
1738                float_gap: None
1739            }
1740            .representative(),
1741            Some(Mutation::Op(CmpOp::Ge))
1742        );
1743    }
1744
1745    /// `a && b` / `a || b` with the tool's mutants, as a reference evaluator. Returns the
1746    /// result and whether the right operand was evaluated.
1747    fn eval_logic(and: bool, m: Option<Mutation>, a: bool, b: bool) -> (bool, bool) {
1748        let decided = |and: bool| if and { !a } else { a };
1749        match m {
1750            None => {
1751                if decided(and) {
1752                    (a, false)
1753                } else {
1754                    (b, true)
1755                }
1756            }
1757            Some(Mutation::LogicSwap) => {
1758                if decided(!and) {
1759                    (a, false)
1760                } else {
1761                    (b, true)
1762                }
1763            }
1764            // The right operand is evaluated as in the original, but its value is ignored.
1765            Some(Mutation::LogicDropRhs) => (a, !decided(and)),
1766            Some(Mutation::LogicDropLhs) => (b, true),
1767            other => panic!("{other:?}"),
1768        }
1769    }
1770
1771    #[test]
1772    fn logic_plans_match_a_reference_evaluator() {
1773        let cases = [(false, false), (false, true), (true, false), (true, true)];
1774        for and in [true, false] {
1775            for mask in 0u32..16 {
1776                let seen: Vec<(bool, bool)> = cases
1777                    .iter()
1778                    .enumerate()
1779                    .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1780                    .collect();
1781                let mut obs = LogicObs::default();
1782                for (a, b) in &seen {
1783                    let (_, evaluated) = eval_logic(and, None, *a, *b);
1784                    obs.short |= !evaluated;
1785                    obs.rhs_true |= evaluated && *b;
1786                    obs.rhs_false |= evaluated && !*b;
1787                }
1788                let ctx = format!("and={and} seen={seen:?}");
1789                let differs = |m: Mutation| {
1790                    seen.iter().any(|(a, b)| {
1791                        eval_logic(and, None, *a, *b) != eval_logic(and, Some(m), *a, *b)
1792                    })
1793                };
1794                let plan = plan_logic(and, &obs);
1795                if seen.is_empty() {
1796                    assert_eq!(
1797                        plan,
1798                        LogicPlan {
1799                            gaps: vec![LogicGap::Unreached],
1800                            run: vec![]
1801                        }
1802                    );
1803                    continue;
1804                }
1805                for (m, gap) in [
1806                    (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1807                    (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1808                ] {
1809                    // Exact: a gap iff no observed case evaluates differently.
1810                    assert_eq!(plan.gaps.contains(&gap), !differs(m), "{gap:?} {ctx}");
1811                    assert_eq!(plan.run.contains(&m), differs(m), "{m:?} {ctx}");
1812                    assert_eq!(logic_infects(and, m, &obs), differs(m), "{m:?} {ctx}");
1813                }
1814                // The swap is always run: never claimed safe.
1815                assert!(plan.run.contains(&Mutation::LogicSwap), "{ctx}");
1816                assert!(logic_infects(and, Mutation::LogicSwap, &obs), "{ctx}");
1817            }
1818        }
1819        // A right operand that was started and gave no value (it panicked, or left the
1820        // function): the expression was executed, the operator swapped is run against
1821        // this test, and the other two change nothing in it.
1822        let started = LogicObs::from_bits(8);
1823        assert!(started.rhs_started && started.reached());
1824        for and in [true, false] {
1825            let plan = plan_logic(and, &started);
1826            assert_eq!(plan.run, vec![Mutation::LogicSwap]);
1827            assert_eq!(
1828                plan.gaps,
1829                vec![LogicGap::RhsNeverDecides, LogicGap::LhsNeverDecides]
1830            );
1831            assert!(logic_infects(and, Mutation::LogicSwap, &started));
1832            assert!(!logic_infects(and, Mutation::LogicDropRhs, &started));
1833            assert!(!logic_infects(and, Mutation::LogicDropLhs, &started));
1834        }
1835        let mut merged = LogicObs::from_bits(2);
1836        merged.merge(&started);
1837        assert_eq!(merged, LogicObs::from_bits(10));
1838        assert_eq!(
1839            LogicObs::from_bits(5),
1840            LogicObs {
1841                short: true,
1842                rhs_true: false,
1843                rhs_false: true,
1844                rhs_started: false,
1845            }
1846        );
1847        assert_eq!(
1848            LogicObs::from_bits(2),
1849            LogicObs {
1850                short: false,
1851                rhs_true: true,
1852                rhs_false: false,
1853                rhs_started: false,
1854            }
1855        );
1856    }
1857
1858    #[test]
1859    fn return_plans() {
1860        assert_eq!(
1861            plan_return(&ReturnObs::from_bits(0)),
1862            ReturnPlan {
1863                unreached: true,
1864                always: None,
1865                run: vec![]
1866            }
1867        );
1868        assert_eq!(
1869            plan_return(&ReturnObs::from_bits(1)),
1870            ReturnPlan {
1871                unreached: false,
1872                always: Some(true),
1873                run: vec![Mutation::Const(false)]
1874            }
1875        );
1876        assert_eq!(
1877            plan_return(&ReturnObs::from_bits(2)),
1878            ReturnPlan {
1879                unreached: false,
1880                always: Some(false),
1881                run: vec![Mutation::Const(true)]
1882            }
1883        );
1884        assert_eq!(
1885            plan_return(&ReturnObs::from_bits(3)),
1886            ReturnPlan {
1887                unreached: false,
1888                always: None,
1889                run: vec![Mutation::Const(true), Mutation::Const(false)]
1890            }
1891        );
1892        // Forcing the value a test already sees changes nothing for that test.
1893        for bits in 0u8..4 {
1894            let obs = ReturnObs::from_bits(bits);
1895            assert_eq!(obs.infected_by_const(true), obs.saw_false);
1896            assert_eq!(obs.infected_by_const(false), obs.saw_true);
1897            assert_eq!(obs.reached(), bits != 0);
1898            let plan = plan_return(&obs);
1899            for m in &plan.run {
1900                let Mutation::Const(value) = m else { panic!() };
1901                assert!(
1902                    obs.infected_by_const(*value),
1903                    "a run mutant must change some test"
1904                );
1905            }
1906            if let Some(always) = plan.always {
1907                assert!(
1908                    !obs.infected_by_const(always),
1909                    "the survivor changes no test"
1910                );
1911            }
1912        }
1913        let mut merged = ReturnObs::from_bits(1);
1914        merged.merge(&ReturnObs::from_bits(2));
1915        assert_eq!(
1916            merged,
1917            ReturnObs {
1918                saw_true: true,
1919                saw_false: true
1920            }
1921        );
1922    }
1923
1924    #[test]
1925    fn logic_constant_value() {
1926        let cases = [(false, false), (false, true), (true, false), (true, true)];
1927        for and in [true, false] {
1928            for mask in 0u32..16 {
1929                let seen: Vec<(bool, bool)> = cases
1930                    .iter()
1931                    .enumerate()
1932                    .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1933                    .collect();
1934                let mut obs = LogicObs::default();
1935                let mut values = std::collections::BTreeSet::new();
1936                for (a, b) in &seen {
1937                    let (value, evaluated) = eval_logic(and, None, *a, *b);
1938                    values.insert(value);
1939                    obs.short |= !evaluated;
1940                    obs.rhs_true |= evaluated && *b;
1941                    obs.rhs_false |= evaluated && !*b;
1942                }
1943                let expected = if values.len() == 1 {
1944                    values.first().copied()
1945                } else {
1946                    None
1947                };
1948                assert_eq!(obs.constant_value(and), expected, "and={and} seen={seen:?}");
1949            }
1950        }
1951    }
1952
1953    #[test]
1954    fn option_return_plans() {
1955        let plan = |bits| plan_option_return(&ReturnObs::from_bits(bits));
1956        assert_eq!(
1957            plan(0),
1958            ReturnPlan {
1959                unreached: true,
1960                always: None,
1961                run: vec![]
1962            }
1963        );
1964        // Only `None` was ever returned: "always None" changes nothing.
1965        assert_eq!(
1966            plan(2),
1967            ReturnPlan {
1968                unreached: false,
1969                always: Some(false),
1970                run: vec![]
1971            }
1972        );
1973        // `Some` was returned: replacing it by `None` has to be run, against those tests.
1974        for bits in [1, 3] {
1975            assert_eq!(
1976                plan(bits),
1977                ReturnPlan {
1978                    unreached: false,
1979                    always: None,
1980                    run: vec![Mutation::Const(false)]
1981                }
1982            );
1983            assert!(ReturnObs::from_bits(bits).infected_by_const(false));
1984        }
1985        assert!(!ReturnObs::from_bits(2).infected_by_const(false));
1986    }
1987
1988    #[test]
1989    fn arithmetic_plans() {
1990        for bits in 0u8..8 {
1991            let obs = ArithObs::from_bits(bits);
1992            let expected = if bits & 2 != 0 {
1993                ArithPlan::Run
1994            } else if bits & 1 != 0 {
1995                ArithPlan::NeverDiffers
1996            } else if bits & 4 != 0 {
1997                ArithPlan::Opaque
1998            } else {
1999                ArithPlan::Unreached
2000            };
2001            assert_eq!(plan_arith(&obs), expected, "bits={bits}");
2002        }
2003        let mut merged = ArithObs::from_bits(1);
2004        merged.merge(&ArithObs::from_bits(4));
2005        assert_eq!(
2006            merged,
2007            ArithObs {
2008                same: true,
2009                differs: false,
2010                opaque: true,
2011                ..Default::default()
2012            }
2013        );
2014    }
2015
2016    #[test]
2017    fn float_comparison_without_equal_operands() {
2018        // `celsius > 30.5` with 10.0 and 40.0: differences -20.5 and 9.5.
2019        let mut obs = Obs::of_f(-20.5);
2020        obs.merge(&Obs::of_f(9.5));
2021        let plan = plan_cmp(CmpOp::Gt, &obs, None);
2022        let gap = plan.gap.expect("a gap");
2023        assert_eq!(
2024            gap,
2025            InputGap::EqualNeverObserved {
2026                flipped: CmpOp::Ge,
2027                float_gap: Some((-20.5, 9.5))
2028            }
2029        );
2030        assert_eq!(
2031            gap.survivors(),
2032            vec![
2033                Mutation::Op(CmpOp::Ge),
2034                Mutation::ShiftF(4.75),
2035                Mutation::ShiftF(-10.25)
2036            ]
2037        );
2038        // Shifts inside the unobserved gap infect nothing; outside it, or once equality
2039        // has been observed, they do.
2040        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
2041            assert!(!infects(op, Mutation::ShiftF(4.75), &obs));
2042            assert!(!infects(op, Mutation::ShiftF(-10.25), &obs));
2043            assert!(infects(op, Mutation::ShiftF(9.5), &obs));
2044            assert!(infects(op, Mutation::ShiftF(-20.5), &obs));
2045        }
2046        let mut with_eq = obs;
2047        with_eq.merge(&Obs::of_f(0.0));
2048        assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &with_eq));
2049        assert_eq!(plan_cmp(CmpOp::Gt, &with_eq, None).gap, None);
2050        // Mixed with a non-float observation there is no float gap to speak of.
2051        let mut mixed = obs;
2052        mixed.merge(&Obs::of_rel(Rel::Less));
2053        assert_eq!(mixed.float_gap(), None);
2054        assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &mixed));
2055        assert_eq!(Obs::of_d(3).float_gap(), None);
2056    }
2057
2058    #[test]
2059    fn survivors_are_listed_nearest_first() {
2060        let boundary = |min_shift, max_shift| InputGap::Boundary {
2061            min_shift,
2062            max_shift,
2063            missing: vec![0],
2064            same: (0, 0),
2065        };
2066        assert_eq!(
2067            boundary(-9, 9).survivors(),
2068            vec![Mutation::Shift(1), Mutation::Shift(-1), Mutation::Shift(2)]
2069        );
2070        assert_eq!(boundary(-1, 0).survivors(), vec![Mutation::Shift(-1)]);
2071        assert_eq!(
2072            boundary(0, 2).survivors(),
2073            vec![Mutation::Shift(1), Mutation::Shift(2)]
2074        );
2075        assert_eq!(
2076            InputGap::OneSided { always: true }.survivors(),
2077            vec![Mutation::Const(true)]
2078        );
2079        assert_eq!(InputGap::Unreached.survivors(), vec![]);
2080    }
2081
2082    #[test]
2083    fn single_observation_summaries() {
2084        let bits = |o: Obs| (o.lt, o.eq, o.gt, o.un);
2085        assert_eq!(bits(Obs::of_f(-0.5)), (true, false, false, false));
2086        assert_eq!(bits(Obs::of_f(0.0)), (false, true, false, false));
2087        assert_eq!(bits(Obs::of_f(0.5)), (false, false, true, false));
2088        assert_eq!(
2089            (Obs::of_f(-0.5).f_max_neg, Obs::of_f(-0.5).f_min_pos),
2090            (Some(-0.5), None)
2091        );
2092        assert_eq!(
2093            (Obs::of_f(0.5).f_max_neg, Obs::of_f(0.5).f_min_pos),
2094            (None, Some(0.5))
2095        );
2096        assert_eq!(
2097            (Obs::of_f(0.0).f_max_neg, Obs::of_f(0.0).f_min_pos),
2098            (None, None)
2099        );
2100        assert!(Obs::of_f(1.0).unvalued && !Obs::of_f(1.0).unfloat);
2101        assert!(Obs::of_d(1).unfloat && !Obs::of_d(1).unvalued);
2102
2103        // Reached through any one relation, including "unordered" alone.
2104        assert!(Obs::of_rel(Rel::Unordered).reached());
2105        assert!(!Obs::default().reached());
2106        // An unreached site has no values, even though nothing contradicts having them.
2107        assert!(!Obs::default().valued());
2108        assert!(Obs::of_d(0).valued());
2109        assert!(!Obs::of_rel(Rel::Equal).valued());
2110
2111        // A NaN comparison among floats spoils the float gap.
2112        let mut nan = Obs::of_f(-1.0);
2113        nan.merge(&Obs::of_f(1.0));
2114        assert_eq!(nan.float_gap(), Some((-1.0, 1.0)));
2115        nan.un = true;
2116        assert_eq!(nan.float_gap(), None);
2117        assert_eq!(Obs::default().float_gap(), None);
2118        assert_eq!(Obs::of_f(-1.0).float_gap(), None, "one side only");
2119    }
2120
2121    #[test]
2122    fn interval_queries_look_at_the_right_side_of_zero() {
2123        // Only positives were observed: an interval of negatives is empty, and vice versa.
2124        assert!(!obs_of(&[2]).saw_any_in(-3, -1));
2125        assert!(!obs_of(&[-2]).saw_any_in(1, 3));
2126        assert!(obs_of(&[-2]).saw_any_in(-3, -1));
2127        assert!(obs_of(&[2]).saw_any_in(1, 3));
2128        assert!(!obs_of(&[-4]).saw_any_in(-3, 0));
2129        assert!(!obs_of(&[4]).saw_any_in(0, 3));
2130        // A stray value on the far side must not leak into the answer.
2131        let mut odd = obs_of(&[3]);
2132        odd.max_neg = Some(5);
2133        assert!(!odd.saw_any_in(0, 2));
2134        let mut odd = obs_of(&[-3]);
2135        odd.min_pos = Some(-5);
2136        assert!(!odd.saw_any_in(-2, 0));
2137    }
2138
2139    #[test]
2140    fn empty_interval_has_no_observations() {
2141        assert!(!obs_of(&[-1, 0, 1]).saw_any_in(1, 0));
2142        assert!(obs_of(&[0]).saw_any_in(0, 0));
2143    }
2144
2145    #[test]
2146    fn unvalued_ordering_without_equal_operands() {
2147        let mut obs = Obs::of_rel(Rel::Less);
2148        obs.merge(&Obs::of_rel(Rel::Greater));
2149        let plan = plan_cmp(CmpOp::Lt, &obs, None);
2150        assert_eq!(
2151            plan.gap,
2152            Some(InputGap::EqualNeverObserved {
2153                flipped: CmpOp::Le,
2154                float_gap: None
2155            })
2156        );
2157        // Without equal operands `>` answers like the negation; it is run as well.
2158        assert_eq!(
2159            plan.run,
2160            vec![
2161                Mutation::Negate,
2162                Mutation::Op(CmpOp::Eq),
2163                Mutation::Op(CmpOp::Gt)
2164            ]
2165        );
2166
2167        obs.merge(&Obs::of_rel(Rel::Equal));
2168        let plan = plan_cmp(CmpOp::Lt, &obs, None);
2169        assert_eq!(plan.gap, None);
2170        assert_eq!(
2171            plan.run,
2172            vec![
2173                Mutation::Op(CmpOp::Le),
2174                Mutation::Negate,
2175                Mutation::Op(CmpOp::Eq),
2176                Mutation::Op(CmpOp::Gt)
2177            ]
2178        );
2179    }
2180
2181    #[test]
2182    fn equality_with_both_outcomes() {
2183        let plan = plan_cmp(CmpOp::Eq, &obs_of(&[0, 7]), None);
2184        assert_eq!(
2185            plan,
2186            CmpPlan {
2187                cannot_differ: false,
2188                gap: None,
2189                run: vec![Mutation::Negate]
2190            }
2191        );
2192    }
2193
2194    #[test]
2195    fn unordered_counts_as_not_equal() {
2196        let obs = Obs::of_rel(Rel::Unordered);
2197        assert!(infects(CmpOp::Ne, Mutation::Const(false), &obs));
2198        assert!(!infects(CmpOp::Lt, Mutation::Op(CmpOp::Ge), &obs));
2199        assert!(infects(CmpOp::Lt, Mutation::Op(CmpOp::Ne), &obs));
2200    }
2201
2202    #[test]
2203    fn merge_is_a_semilattice() {
2204        let samples: Vec<Obs> = [-3, -1, 0, 1, 4]
2205            .into_iter()
2206            .map(Obs::of_d)
2207            .chain([
2208                Obs::of_rel(Rel::Unordered),
2209                Obs::of_rel(Rel::Less),
2210                Obs::default(),
2211            ])
2212            .collect();
2213        for a in &samples {
2214            let mut aa = *a;
2215            aa.merge(a);
2216            assert_eq!(aa, *a, "idempotent");
2217            for b in &samples {
2218                let (mut ab, mut ba) = (*a, *b);
2219                ab.merge(b);
2220                ba.merge(a);
2221                assert_eq!(ab, ba, "commutative");
2222                for c in &samples {
2223                    let mut ab_c = ab;
2224                    ab_c.merge(c);
2225                    let mut bc = *b;
2226                    bc.merge(c);
2227                    let mut a_bc = *a;
2228                    a_bc.merge(&bc);
2229                    assert_eq!(ab_c, a_bc, "associative");
2230                }
2231            }
2232        }
2233    }
2234
2235    #[test]
2236    fn mutation_wire_format() {
2237        assert_eq!(Mutation::Const(true).encode(), "c1");
2238        assert_eq!(Mutation::Const(false).encode(), "c0");
2239        assert_eq!(Mutation::Negate.encode(), "neg");
2240        assert_eq!(Mutation::Op(CmpOp::Ge).encode(), "op3");
2241        assert_eq!(Mutation::Shift(-2).encode(), "sh-2");
2242        assert_eq!(Mutation::Delete.encode(), "del");
2243        assert_eq!(Mutation::ShiftF(4.75).encode(), "shf4.75");
2244        assert_eq!(Mutation::ShiftF(-10.0).encode(), "shf-10.0");
2245        assert_eq!(Mutation::LogicSwap.encode(), "lsw");
2246        assert_eq!(Mutation::LogicDropRhs.encode(), "ldr");
2247        assert_eq!(Mutation::LogicDropLhs.encode(), "ldl");
2248        assert_eq!(Mutation::ArithSwap.encode(), "asw");
2249        assert_eq!(Mutation::DropNot.encode(), "unn");
2250        assert_eq!(Mutation::RangeEnd.encode(), "rng");
2251        assert_eq!(Mutation::MinMax.encode(), "mmx");
2252        assert_eq!(Mutation::OtherEnd.encode(), "end");
2253    }
2254
2255    fn candidate_mutations(op: CmpOp) -> Vec<Mutation> {
2256        let mut ms = vec![
2257            Mutation::Const(true),
2258            Mutation::Const(false),
2259            Mutation::Negate,
2260        ];
2261        ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
2262        if op.is_ordering() {
2263            ms.extend((-5..=5).filter(|s| *s != 0).map(Mutation::Shift));
2264        }
2265        ms
2266    }
2267
2268    /// Checks a plan against concrete observations by brute force.
2269    fn check_plan(op: CmpOp, ds: &[i128], domain: Option<(i128, i128)>) {
2270        let obs = obs_of(ds);
2271        let ctx = format!("{op:?} ds={ds:?} domain={domain:?}");
2272        let (dom_lo, dom_hi) = domain.unwrap_or((-50, 50));
2273        let differs_somewhere =
2274            |m: Mutation| (dom_lo..=dom_hi).any(|d| op.eval_d(d) != eval_mutated_d(op, m, d));
2275
2276        for m in candidate_mutations(op) {
2277            assert_eq!(
2278                infects(op, m, &obs),
2279                brute_infects(op, m, ds),
2280                "infects {m:?} {ctx}"
2281            );
2282        }
2283
2284        let plan = plan_cmp(op, &obs, domain);
2285        for m in &plan.run {
2286            assert!(
2287                brute_infects(op, *m, ds),
2288                "run {m:?} must be infected: {ctx}"
2289            );
2290            assert!(differs_somewhere(*m), "run {m:?} is equivalent: {ctx}");
2291        }
2292        match &plan.gap {
2293            None => {}
2294            Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2295            Some(InputGap::OneSided { always }) => {
2296                assert!(ds.iter().all(|d| op.eval_d(*d) == *always), "{ctx}");
2297                assert!(differs_somewhere(Mutation::Const(*always)), "{ctx}");
2298            }
2299            Some(InputGap::Boundary {
2300                min_shift,
2301                max_shift,
2302                missing,
2303                same: _,
2304            }) => {
2305                assert!(*min_shift <= 0 && 0 <= *max_shift, "{ctx}");
2306                for s in (*min_shift..=*max_shift).filter(|s| *s != 0) {
2307                    let m = Mutation::Shift(s);
2308                    assert!(
2309                        !brute_infects(op, m, ds),
2310                        "survivor {m:?} is infected: {ctx}"
2311                    );
2312                    assert!(differs_somewhere(m), "survivor {m:?} is equivalent: {ctx}");
2313                }
2314                if domain.is_none() {
2315                    // Exactness: one step outside the range is caught by some observation.
2316                    for s in [min_shift - 1, max_shift + 1] {
2317                        assert!(
2318                            brute_infects(op, Mutation::Shift(s), ds),
2319                            "range not maximal: {ctx}"
2320                        );
2321                    }
2322                }
2323                assert!(!missing.is_empty(), "{ctx}");
2324                for w in missing {
2325                    assert!(!ds.contains(w), "missing value {w} was observed: {ctx}");
2326                    assert!(
2327                        dom_lo <= *w && *w <= dom_hi,
2328                        "missing value {w} out of domain: {ctx}"
2329                    );
2330                    let s = if op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(1), *w) {
2331                        1
2332                    } else {
2333                        -1
2334                    };
2335                    assert!(
2336                        op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(s), *w),
2337                        "missing value {w} separates nothing: {ctx}"
2338                    );
2339                    assert!(*min_shift <= s && s <= *max_shift, "{ctx}");
2340                }
2341            }
2342            Some(InputGap::EqualNeverObserved { .. }) => panic!("valued site: {ctx}"),
2343        }
2344        if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2345            assert!(
2346                !brute_infects(op, m, ds),
2347                "representative {m:?} is infected: {ctx}"
2348            );
2349        }
2350
2351        // Completeness for the off-by-one mutants: each is a survivor, is run, or is equivalent.
2352        if op.is_ordering() && ds.iter().any(|d| op.eval_d(*d)) && ds.iter().any(|d| !op.eval_d(*d))
2353        {
2354            for s in [-1, 1] {
2355                let m = Mutation::Shift(s);
2356                let survivor = matches!(&plan.gap, Some(InputGap::Boundary { min_shift, max_shift, .. })
2357                    if *min_shift <= s && s <= *max_shift);
2358                let ran = plan.run.contains(&m);
2359                assert!(
2360                    survivor ^ ran || !differs_somewhere(m),
2361                    "Shift({s}) unaccounted for: survivor={survivor} ran={ran} {ctx}"
2362                );
2363            }
2364        }
2365    }
2366
2367    #[test]
2368    fn exhaustive_small_observation_sets() {
2369        let universe: Vec<i128> = (-3..=3).collect();
2370        for op in CmpOp::ALL {
2371            for mask in 0u32..(1 << universe.len()) {
2372                let ds: Vec<i128> = universe
2373                    .iter()
2374                    .enumerate()
2375                    .filter_map(|(i, d)| (mask & (1 << i) != 0).then_some(*d))
2376                    .collect();
2377                check_plan(op, &ds, None);
2378                // Domains that contain every observation.
2379                for (lo, hi) in [(0, 10), (-10, 0), (-2, 2), (1, 9), (-9, -1)] {
2380                    if ds.iter().all(|d| lo <= *d && *d <= hi) {
2381                        check_plan(op, &ds, Some((lo, hi)));
2382                    }
2383                }
2384            }
2385        }
2386    }
2387
2388    /// Rows generated by `pict formal/pict/planner.pict /o:3 /e:formal/pict/planner.seed.tsv`.
2389    #[test]
2390    fn pict_table() {
2391        let table = include_str!("../tests/data/planner.pict.tsv");
2392        let mut rows = 0;
2393        for line in table.lines().skip(1) {
2394            let cols: Vec<&str> = line.split('\t').collect();
2395            let [op, below, equal, above, valued, literal, domain] = cols[..] else {
2396                panic!("bad row: {line}");
2397            };
2398            let op = match op {
2399                "lt" => CmpOp::Lt,
2400                "le" => CmpOp::Le,
2401                "gt" => CmpOp::Gt,
2402                "ge" => CmpOp::Ge,
2403                "eq" => CmpOp::Eq,
2404                "ne" => CmpOp::Ne,
2405                other => panic!("op {other}"),
2406            };
2407            let mut ds: Vec<i128> = vec![];
2408            match below {
2409                "none" => {}
2410                "adjacent" => ds.extend([-1, -4]),
2411                "far" => ds.extend([-3, -6]),
2412                other => panic!("below {other}"),
2413            }
2414            if equal == "yes" {
2415                ds.push(0);
2416            }
2417            match above {
2418                "none" => {}
2419                "adjacent" => ds.extend([1, 5]),
2420                "far" => ds.extend([3, 7]),
2421                other => panic!("above {other}"),
2422            }
2423            rows += 1;
2424            if valued == "no" {
2425                let mut obs = Obs::default();
2426                for d in &ds {
2427                    obs.merge(&Obs::of_rel(rel_of(*d)));
2428                }
2429                check_unvalued(op, &obs, &ds, line);
2430                continue;
2431            }
2432            // D = lhs - rhs. With the literal on the right, a tight lower bound on the other
2433            // operand is a lower bound on D; with the literal on the left it is an upper bound.
2434            let domain = match (literal, domain) {
2435                ("none", _) => None,
2436                (_, "wide") => Some((-40, 40)),
2437                ("rhs", "tight_low") | ("lhs", "tight_high") => Some((0, 40)),
2438                ("rhs", "tight_high") | ("lhs", "tight_low") => Some((-40, 0)),
2439                other => panic!("domain {other:?}"),
2440            };
2441            check_plan(op, &ds, domain);
2442        }
2443        assert_eq!(rows, table.lines().count() - 1);
2444        assert!(rows > 50, "the PICT table looks truncated: {rows} rows");
2445    }
2446
2447    fn check_unvalued(op: CmpOp, obs: &Obs, ds: &[i128], ctx: &str) {
2448        let plan = plan_cmp(op, obs, None);
2449        for m in [
2450            Mutation::Const(true),
2451            Mutation::Const(false),
2452            Mutation::Negate,
2453        ]
2454        .into_iter()
2455        .chain(CmpOp::ALL.into_iter().map(Mutation::Op))
2456        {
2457            assert_eq!(
2458                infects(op, m, obs),
2459                brute_infects(op, m, ds),
2460                "infects {m:?} {ctx}"
2461            );
2462        }
2463        for m in &plan.run {
2464            assert!(
2465                brute_infects(op, *m, ds),
2466                "run {m:?} must be infected: {ctx}"
2467            );
2468        }
2469        if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2470            assert!(
2471                !brute_infects(op, m, ds),
2472                "representative {m:?} is infected: {ctx}"
2473            );
2474        }
2475        match &plan.gap {
2476            Some(InputGap::Boundary { .. }) => panic!("unvalued site cannot shift: {ctx}"),
2477            Some(InputGap::EqualNeverObserved { flipped, .. }) => {
2478                assert!(!ds.contains(&0), "{ctx}");
2479                assert_eq!(op.flip_eq(), Some(*flipped), "{ctx}");
2480            }
2481            Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2482            _ => {}
2483        }
2484        // A shift on a reached site without values is never claimed to be safe.
2485        if op.is_ordering() && obs.reached() {
2486            assert!(infects(op, Mutation::Shift(1), obs), "{ctx}");
2487        }
2488    }
2489
2490    #[test]
2491    fn logic_swap_never_changes_value_matches_pict_table() {
2492        let table = include_str!("../tests/data/logic-swap.pict.tsv");
2493        let mut rows = 0;
2494        for line in table.lines().skip(1).filter(|l| !l.trim().is_empty()) {
2495            let cols: Vec<&str> = line.split('\t').collect();
2496            assert_eq!(cols.len(), 5, "unexpected row: {line}");
2497            let and = match cols[0] {
2498                "and" => true,
2499                "or" => false,
2500                other => panic!("unexpected LogicOp: {other}"),
2501            };
2502            let obs = LogicObs {
2503                short: cols[1] == "true",
2504                rhs_true: cols[2] == "true",
2505                rhs_false: cols[3] == "true",
2506                rhs_started: cols[4] == "true",
2507            };
2508            let expected = if and {
2509                !obs.short && obs.rhs_true && !obs.rhs_false
2510            } else {
2511                !obs.short && !obs.rhs_true && obs.rhs_false
2512            };
2513            assert_eq!(
2514                obs.swap_never_changes_value(and),
2515                expected,
2516                "row={line} obs={obs:?}"
2517            );
2518            rows += 1;
2519        }
2520        assert!(rows >= 9, "expected PICT table rows, got {rows}");
2521    }
2522
2523    #[test]
2524    fn truth_mask_matches_all_operators_and_relations() {
2525        let expected = [
2526            (CmpOp::Lt, [true, false, false, false]),
2527            (CmpOp::Le, [true, true, false, false]),
2528            (CmpOp::Gt, [false, false, true, false]),
2529            (CmpOp::Ge, [false, true, true, false]),
2530            (CmpOp::Eq, [false, true, false, false]),
2531            (CmpOp::Ne, [true, false, true, true]),
2532        ];
2533        let rels = [
2534            (1u8, Rel::Less),
2535            (2u8, Rel::Equal),
2536            (4u8, Rel::Greater),
2537            (8u8, Rel::Unordered),
2538        ];
2539        for (op, table) in expected {
2540            for (idx, (bit, rel)) in rels.into_iter().enumerate() {
2541                assert_eq!(op.truth_mask() & bit != 0, table[idx], "{op:?} {rel:?}");
2542                assert_eq!(op.eval_rel(rel), table[idx], "{op:?} {rel:?}");
2543            }
2544        }
2545    }
2546
2547    #[test]
2548    fn domain_equivalent_matches_exhaustive_evaluation() {
2549        let mutations = [
2550            Mutation::Const(false),
2551            Mutation::Const(true),
2552            Mutation::Negate,
2553            Mutation::Shift(-1),
2554            Mutation::Shift(1),
2555            Mutation::Op(CmpOp::Lt),
2556            Mutation::Op(CmpOp::Le),
2557            Mutation::Op(CmpOp::Gt),
2558            Mutation::Op(CmpOp::Ge),
2559            Mutation::Op(CmpOp::Eq),
2560            Mutation::Op(CmpOp::Ne),
2561        ];
2562        let domains = [
2563            (0i128, 255),
2564            (-255, 0),
2565            (-128, 127),
2566            (1, 10),
2567            (-10, -1),
2568            (0, 0),
2569            (-1, 1),
2570            (-5, -3),
2571            (3, 5),
2572        ];
2573        for op in CmpOp::ALL {
2574            for &(lo, hi) in &domains {
2575                for zero_unreachable in [false, true] {
2576                    for &m1 in &mutations {
2577                        for &m2 in &mutations {
2578                            let brute = (lo..=hi)
2579                                .filter(|&d| !(zero_unreachable && d == 0))
2580                                .all(|d| eval_mutated_d(op, m1, d) == eval_mutated_d(op, m2, d));
2581                            assert_eq!(
2582                                domain_equivalent(op, m1, m2, (lo, hi), zero_unreachable),
2583                                brute,
2584                                "{op:?} {m1:?} vs {m2:?} on [{lo}, {hi}] zero_unreachable={zero_unreachable}"
2585                            );
2586                        }
2587                    }
2588                }
2589            }
2590        }
2591        assert!(domain_equivalent(
2592            CmpOp::Gt,
2593            Mutation::Negate,
2594            Mutation::Op(CmpOp::Eq),
2595            (0, u64::MAX as i128),
2596            false,
2597        ));
2598        assert!(domain_equivalent(
2599            CmpOp::Lt,
2600            Mutation::Negate,
2601            Mutation::Op(CmpOp::Gt),
2602            (-100, 100),
2603            true,
2604        ));
2605        assert!(!domain_equivalent(
2606            CmpOp::Gt,
2607            Mutation::Shift(2),
2608            Mutation::Shift(2),
2609            (0, 10),
2610            false,
2611        ));
2612        // i128 overflow endpoints: Shift(-1) at i128::MAX and Shift(1) at i128::MIN are excluded.
2613        assert!(!domain_equivalent(
2614            CmpOp::Gt,
2615            Mutation::Shift(-1),
2616            Mutation::Const(true),
2617            (0, i128::MAX),
2618            false,
2619        ));
2620        assert!(!domain_equivalent(
2621            CmpOp::Lt,
2622            Mutation::Shift(1),
2623            Mutation::Const(true),
2624            (i128::MIN, 0),
2625            false,
2626        ));
2627    }
2628}