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