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