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    /// The numbers the expression lies between, where it has such bounds.
650    pub fn interval(self) -> Option<(i128, i128)> {
651        match self {
652            Reach::Multiples(_) => None,
653            Reach::Bits(mask) => Some((0, mask)),
654            Reach::Below(limit) => Some((1 - limit, limit - 1)),
655        }
656    }
657
658    /// The least value above `value` that the expression can be.
659    fn next_above(self, value: i128) -> Option<i128> {
660        match self {
661            Reach::Multiples(step) => value.div_euclid(step).checked_add(1)?.checked_mul(step),
662            Reach::Bits(_) if value < 0 => Some(0),
663            Reach::Bits(mask) => {
664                let over = value.checked_add(1)?;
665                let outside = over & !mask;
666                if outside == 0 {
667                    return Some(over);
668                }
669                // The bits from the highest one that is not of the mask down cannot
670                // stay: fill them and what else is not of the mask, so that adding one
671                // carries into the next bit of the mask above.
672                let top = 127 - outside.leading_zeros();
673                let low = 1_i128.checked_shl(top + 1)?.checked_sub(1)?;
674                let next = (over | !mask | low).wrapping_add(1) & mask;
675                (next > value).then_some(next)
676            }
677            Reach::Below(limit) => {
678                let next = value.checked_add(1)?.max(1 - limit);
679                (next < limit).then_some(next)
680            }
681        }
682    }
683
684    /// The greatest value below `value` that the expression can be.
685    fn next_below(self, value: i128) -> Option<i128> {
686        match self {
687            Reach::Multiples(step) => value.checked_sub(1)?.div_euclid(step).checked_mul(step),
688            Reach::Bits(_) if value <= 0 => None,
689            Reach::Bits(mask) => {
690                let under = value - 1;
691                let outside = under & !mask;
692                Some(if outside == 0 {
693                    under
694                } else {
695                    // Below the highest bit that is not of the mask, all of the mask.
696                    let top = 127 - outside.leading_zeros();
697                    let low = (1_i128 << top) - 1;
698                    (under & !low & !(1_i128 << top)) | (mask & low)
699                })
700            }
701            Reach::Below(limit) => {
702                let next = value.checked_sub(1)?.min(limit - 1);
703                (next > -limit).then_some(next)
704            }
705        }
706    }
707}
708
709/// The boundary gap of `expr op literal` (or `literal op expr`), given what the
710/// expression can be at all. `None` when no value it can be lies between the values
711/// the tests gave it: every shifted threshold then answers like the original, always.
712/// Otherwise the values to add are ones it can be, and a side that has none is left out.
713pub fn within_reach(
714    gap: InputGap,
715    op: CmpOp,
716    obs: &Obs,
717    reach: Reach,
718    literal: i128,
719    literal_is_rhs: bool,
720) -> Option<InputGap> {
721    let InputGap::Boundary {
722        min_shift,
723        max_shift,
724        missing,
725        same,
726    } = gap
727    else {
728        return Some(gap);
729    };
730    let Some((up, t0)) = op.threshold() else {
731        return Some(InputGap::Boundary {
732            min_shift,
733            max_shift,
734            missing,
735            same,
736        });
737    };
738    // As in `plan_boundary`: the nearest differences seen on each side, and the two
739    // next to the boundary.
740    let (below, above, w_minus, w_plus) = if up {
741        (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
742    } else {
743        (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
744    };
745    let (below, above) = (below?, above?);
746    // The expression's value for a difference, and back.
747    let value = |d: i128| {
748        if literal_is_rhs {
749            literal.checked_add(d)
750        } else {
751            literal.checked_sub(d)
752        }
753    };
754    let difference = |v: i128| {
755        if literal_is_rhs {
756            v.checked_sub(literal)
757        } else {
758            literal.checked_sub(v)
759        }
760    };
761    // The nearest difference the expression can make, from `start` towards `bound`
762    // (which it stops short of).
763    let nearest = |start: i128, bound: i128| -> Option<i128> {
764        if (start < bound) != (start <= bound) || start == bound {
765            return None;
766        }
767        let (from, to) = (value(start)?, value(bound)?);
768        let found = if reach.holds(from) {
769            from
770        } else if to > from {
771            reach.next_above(from)?
772        } else {
773            reach.next_below(from)?
774        };
775        let inside = if to > from { found < to } else { found > to };
776        inside.then(|| difference(found)).flatten()
777    };
778    let down = nearest(w_minus, below);
779    let up_side = nearest(w_plus, above);
780    let missing: Vec<i128> = [(w_minus, down), (w_plus, up_side)]
781        .into_iter()
782        .filter(|(w, _)| missing.contains(w))
783        .filter_map(|(_, nearest)| nearest)
784        .collect();
785    if missing.is_empty() {
786        return None;
787    }
788    // A threshold moved by less than it takes to reach the nearest value the expression
789    // can be, on either side, answers like the original for all of them. Where there is
790    // no such value short of what the tests gave, that is the whole side.
791    let (first_under, first_over) = (down.unwrap_or(below), up_side.unwrap_or(above));
792    let same = if up {
793        (first_under - t0 + 1, first_over - t0)
794    } else {
795        (first_under - t0, first_over - t0 - 1)
796    };
797    Some(InputGap::Boundary {
798        min_shift,
799        max_shift,
800        missing,
801        same: (same.0.max(min_shift).min(0), same.1.min(max_shift).max(0)),
802    })
803}
804
805/// What the tests observed at `a && b` / `a || b`.
806#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
807pub struct LogicObs {
808    /// The left operand decided alone (false for `&&`, true for `||`).
809    pub short: bool,
810    pub rhs_true: bool,
811    pub rhs_false: bool,
812    /// The right operand was started. Where it gave no value (a panic, a `?`, a
813    /// `return`) this is all there is to see of the expression having been executed.
814    pub rhs_started: bool,
815}
816
817impl LogicObs {
818    pub fn from_bits(bits: u8) -> LogicObs {
819        LogicObs {
820            short: bits & 1 != 0,
821            rhs_true: bits & 2 != 0,
822            rhs_false: bits & 4 != 0,
823            rhs_started: bits & 8 != 0,
824        }
825    }
826
827    pub fn merge(&mut self, other: &LogicObs) {
828        self.short |= other.short;
829        self.rhs_true |= other.rhs_true;
830        self.rhs_false |= other.rhs_false;
831        self.rhs_started |= other.rhs_started;
832    }
833
834    pub fn reached(&self) -> bool {
835        self.short || self.rhs_true || self.rhs_false || self.rhs_started
836    }
837
838    /// The value of the whole expression, if it was the same in every observation.
839    pub fn constant_value(&self, and: bool) -> Option<bool> {
840        // A short circuit yields false for `&&` and true for `||`.
841        let saw_true = self.rhs_true || (self.short && !and);
842        let saw_false = self.rhs_false || (self.short && and);
843        match (saw_true, saw_false) {
844            (true, false) => Some(true),
845            (false, true) => Some(false),
846            _ => None,
847        }
848    }
849
850    /// The right operand was evaluated and its value decided the result.
851    fn rhs_decided(&self, and: bool) -> bool {
852        if and { self.rhs_false } else { self.rhs_true }
853    }
854}
855
856#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
857#[serde(rename_all = "snake_case")]
858pub enum LogicGap {
859    Unreached,
860    /// No test has the right operand decide the result: `LogicDropRhs` survives.
861    RhsNeverDecides,
862    /// No test has the left operand decide the result: `LogicDropLhs` survives.
863    LhsNeverDecides,
864}
865
866#[derive(Clone, PartialEq, Debug, Default)]
867pub struct LogicPlan {
868    pub gaps: Vec<LogicGap>,
869    pub run: Vec<Mutation>,
870}
871
872/// Whether a test with these observations can execute differently under `m`.
873/// Swapping the operator changes when the right operand is evaluated, so it is treated as
874/// infecting every test that reaches the expression.
875pub fn logic_infects(and: bool, m: Mutation, obs: &LogicObs) -> bool {
876    match m {
877        Mutation::LogicDropRhs => obs.rhs_decided(and),
878        Mutation::LogicDropLhs => obs.short,
879        _ => obs.reached(),
880    }
881}
882
883pub fn plan_logic(and: bool, obs: &LogicObs) -> LogicPlan {
884    if !obs.reached() {
885        return LogicPlan {
886            gaps: vec![LogicGap::Unreached],
887            run: vec![],
888        };
889    }
890    let mut plan = LogicPlan::default();
891    for (m, gap) in [
892        (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
893        (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
894    ] {
895        if logic_infects(and, m, obs) {
896            plan.run.push(m);
897        } else {
898            plan.gaps.push(gap);
899        }
900    }
901    plan.run.push(Mutation::LogicSwap);
902    plan
903}
904
905/// What the tests observed at an arithmetic operator on primitive numbers.
906#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
907pub struct ArithObs {
908    /// The swapped operator gave the same result.
909    pub same: bool,
910    /// The swapped operator gave a different result.
911    pub differs: bool,
912    /// The operands were not primitive numbers: nothing can be said.
913    pub opaque: bool,
914    /// The same for the operator's second replacement, where it has one.
915    pub same2: bool,
916    pub differs2: bool,
917}
918
919impl ArithObs {
920    pub fn from_bits(bits: u8) -> ArithObs {
921        ArithObs {
922            same: bits & 1 != 0,
923            differs: bits & 2 != 0,
924            opaque: bits & 4 != 0,
925            same2: bits & 8 != 0,
926            differs2: bits & 16 != 0,
927        }
928    }
929
930    pub fn merge(&mut self, other: &ArithObs) {
931        self.same |= other.same;
932        self.differs |= other.differs;
933        self.opaque |= other.opaque;
934        self.same2 |= other.same2;
935        self.differs2 |= other.differs2;
936    }
937
938    /// The observations as they are for the second replacement.
939    pub fn second(&self) -> ArithObs {
940        ArithObs {
941            same: self.same2,
942            differs: self.differs2,
943            opaque: self.opaque,
944            same2: false,
945            differs2: false,
946        }
947    }
948
949    /// Whether mutation `m` computes another value in this test.
950    pub fn infected_by(&self, m: Mutation) -> bool {
951        if m == Mutation::ArithSwap2 {
952            self.differs2
953        } else {
954            self.differs
955        }
956    }
957}
958
959#[derive(Clone, Copy, PartialEq, Eq, Debug)]
960pub enum ArithPlan {
961    Unreached,
962    /// Not primitive numbers: not mutated.
963    Opaque,
964    /// The swapped operator agrees on every observed pair of operands: it survives.
965    NeverDiffers,
966    /// Some test computes a different value: run `ArithSwap` against those tests.
967    Run,
968}
969
970pub fn plan_arith(obs: &ArithObs) -> ArithPlan {
971    if obs.differs {
972        ArithPlan::Run
973    } else if obs.same {
974        ArithPlan::NeverDiffers
975    } else if obs.opaque {
976        ArithPlan::Opaque
977    } else {
978        ArithPlan::Unreached
979    }
980}
981
982/// What a `-> bool` function returned at its normal exit.
983#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
984pub struct ReturnObs {
985    pub saw_true: bool,
986    pub saw_false: bool,
987}
988
989impl ReturnObs {
990    pub fn from_bits(bits: u8) -> ReturnObs {
991        ReturnObs {
992            saw_true: bits & 1 != 0,
993            saw_false: bits & 2 != 0,
994        }
995    }
996
997    pub fn merge(&mut self, other: &ReturnObs) {
998        self.saw_true |= other.saw_true;
999        self.saw_false |= other.saw_false;
1000    }
1001
1002    pub fn reached(&self) -> bool {
1003        self.saw_true || self.saw_false
1004    }
1005
1006    /// Whether replacing the returned value by `value` changes anything for this test.
1007    pub fn infected_by_const(&self, value: bool) -> bool {
1008        if value { self.saw_false } else { self.saw_true }
1009    }
1010}
1011
1012#[derive(Clone, PartialEq, Debug, Default)]
1013pub struct ReturnPlan {
1014    pub unreached: bool,
1015    /// The function returned only this value: `Const(value)` survives.
1016    pub always: Option<bool>,
1017    pub run: Vec<Mutation>,
1018}
1019
1020/// Plans a function returning `Option<T>`, where `saw_true` stands for `Some` and
1021/// `saw_false` for `None`. The result can be replaced by `None` but not by a `Some`.
1022pub fn plan_option_return(obs: &ReturnObs) -> ReturnPlan {
1023    match (obs.saw_true, obs.saw_false) {
1024        (false, false) => ReturnPlan {
1025            unreached: true,
1026            ..ReturnPlan::default()
1027        },
1028        // Never `Some`: always returning `None` passes every test.
1029        (false, true) => ReturnPlan {
1030            unreached: false,
1031            always: Some(false),
1032            run: vec![],
1033        },
1034        (true, _) => ReturnPlan {
1035            unreached: false,
1036            always: None,
1037            run: vec![Mutation::Const(false)],
1038        },
1039    }
1040}
1041
1042pub fn plan_return(obs: &ReturnObs) -> ReturnPlan {
1043    match (obs.saw_true, obs.saw_false) {
1044        (false, false) => ReturnPlan {
1045            unreached: true,
1046            ..ReturnPlan::default()
1047        },
1048        (true, true) => ReturnPlan {
1049            run: vec![Mutation::Const(true), Mutation::Const(false)],
1050            ..ReturnPlan::default()
1051        },
1052        (always, _) => ReturnPlan {
1053            unreached: false,
1054            always: Some(always),
1055            run: vec![Mutation::Const(!always)],
1056        },
1057    }
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062    use super::*;
1063
1064    const REACHES: [Reach; 5] = [
1065        Reach::Multiples(4),
1066        Reach::Multiples(8),
1067        Reach::Bits(0b1010),
1068        Reach::Bits(0b0110),
1069        Reach::Below(5),
1070    ];
1071
1072    #[test]
1073    fn the_next_value_an_expression_can_be() {
1074        for reach in REACHES {
1075            for value in -40..=40_i128 {
1076                let above = (value + 1..=80).find(|v| reach.holds(*v));
1077                let below = (-80..value).rev().find(|v| reach.holds(*v));
1078                assert_eq!(reach.next_above(value), above, "{reach:?} above {value}");
1079                assert_eq!(reach.next_below(value), below, "{reach:?} below {value}");
1080            }
1081        }
1082        // At the ends of the numbers there is no next one.
1083        assert_eq!(Reach::Multiples(8).next_above(i128::MAX), None);
1084        assert_eq!(Reach::Multiples(8).next_below(i128::MIN), None);
1085        assert_eq!(Reach::Below(5).next_above(i128::MAX), None);
1086        assert_eq!(Reach::Below(5).next_below(i128::MIN), None);
1087        assert_eq!(Reach::Bits(i128::MAX).next_above(i128::MAX), None);
1088        assert!(Reach::Bits(0xF0).holds(0x30) && !Reach::Bits(0xF0).holds(0x31));
1089        assert!(!Reach::Bits(0xF0).holds(-16));
1090    }
1091
1092    /// Every pair of values the expression can be, one on each side of the boundary,
1093    /// as what the tests saw: the gap that is left is checked against all the values
1094    /// the expression can be.
1095    #[test]
1096    fn a_gap_is_kept_only_for_values_the_expression_can_be() {
1097        let mut dropped = 0;
1098        let mut kept = 0;
1099        for reach in REACHES {
1100            let can_be: Vec<i128> = (-24..=24).filter(|v| reach.holds(*v)).collect();
1101            for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1102                for literal in -6..=14_i128 {
1103                    for literal_is_rhs in [true, false] {
1104                        let d_of = |v: i128| {
1105                            if literal_is_rhs {
1106                                v - literal
1107                            } else {
1108                                literal - v
1109                            }
1110                        };
1111                        for &low in &can_be {
1112                            for &high in can_be.iter().filter(|v| **v > low) {
1113                                let mut obs = Obs::of_d(d_of(low));
1114                                obs.merge(&Obs::of_d(d_of(high)));
1115                                let Some(gap @ InputGap::Boundary { .. }) =
1116                                    plan_boundary(op, &obs, None).gap
1117                                else {
1118                                    continue;
1119                                };
1120                                let InputGap::Boundary {
1121                                    min_shift,
1122                                    max_shift,
1123                                    ..
1124                                } = gap.clone()
1125                                else {
1126                                    unreachable!()
1127                                };
1128                                // A threshold moved by `shift` answers `op` for the
1129                                // difference less the shift.
1130                                let differs = |shift: i128, v: i128| {
1131                                    op.eval_d(d_of(v)) != op.eval_d(d_of(v) - shift)
1132                                };
1133                                let told_apart =
1134                                    |shift: i128| can_be.iter().any(|v| differs(shift, *v));
1135                                let case = format!(
1136                                    "{reach:?} {op:?} literal {literal} rhs {literal_is_rhs}, saw {low} and {high}"
1137                                );
1138                                match within_reach(gap, op, &obs, reach, literal, literal_is_rhs) {
1139                                    None => {
1140                                        // Nothing it can be tells any of them apart.
1141                                        for shift in min_shift..=max_shift {
1142                                            assert!(!told_apart(shift), "{case}: shift {shift}");
1143                                        }
1144                                        dropped += 1;
1145                                    }
1146                                    Some(InputGap::Boundary {
1147                                        min_shift: least,
1148                                        max_shift: most,
1149                                        missing,
1150                                        same,
1151                                    }) => {
1152                                        assert!(!missing.is_empty(), "{case}");
1153                                        assert_eq!((least, most), (min_shift, max_shift), "{case}");
1154                                        for d in &missing {
1155                                            let v = if literal_is_rhs {
1156                                                literal + d
1157                                            } else {
1158                                                literal - d
1159                                            };
1160                                            assert!(reach.holds(v), "{case}: {v}");
1161                                            assert!(low < v && v < high, "{case}: {v}");
1162                                        }
1163                                        // The shifts called the same are exactly those that
1164                                        // nothing the expression can be tells apart.
1165                                        assert!(same.0 <= 0 && 0 <= same.1, "{case}: {same:?}");
1166                                        for shift in least..=most {
1167                                            assert_eq!(
1168                                                same.0 <= shift && shift <= same.1,
1169                                                !told_apart(shift),
1170                                                "{case}: shift {shift}, same {same:?}"
1171                                            );
1172                                        }
1173                                        // The values to add find out every other one of a
1174                                        // side that has a value to add.
1175                                        let gap = InputGap::Boundary {
1176                                            min_shift: least,
1177                                            max_shift: most,
1178                                            missing: missing.clone(),
1179                                            same,
1180                                        };
1181                                        for mutation in gap.survivors() {
1182                                            let Mutation::Shift(shift) = mutation else {
1183                                                panic!("{case}: {mutation:?}")
1184                                            };
1185                                            assert!(told_apart(shift), "{case}: shift {shift}");
1186                                        }
1187                                        assert!(gap.representative().is_some(), "{case}");
1188                                        kept += 1;
1189                                    }
1190                                    Some(other) => panic!("{case}: {other:?}"),
1191                                }
1192                            }
1193                        }
1194                    }
1195                }
1196            }
1197        }
1198        assert!(
1199            dropped > 100 && kept > 1000,
1200            "{dropped} dropped, {kept} kept"
1201        );
1202    }
1203
1204    #[test]
1205    fn an_outcome_no_value_gives_is_not_asked_for() {
1206        // `n % 10 < 10` is true for whatever `n` is, `flags & 0xF0 > 0xF0` never is.
1207        for (reach, literal, op, differs) in [
1208            (Reach::Below(10), 10, CmpOp::Lt, false),
1209            (Reach::Below(10), 9, CmpOp::Lt, true),
1210            (Reach::Below(10), -10, CmpOp::Gt, false),
1211            (Reach::Bits(0xF0), 0xF0, CmpOp::Gt, false),
1212            (Reach::Bits(0xF0), 0xF0, CmpOp::Ge, true),
1213            (Reach::Bits(0xF0), 0, CmpOp::Lt, false),
1214        ] {
1215            let (lo, hi) = reach.interval().unwrap();
1216            assert!((lo..=hi).all(|v| !reach.holds(v) || (lo <= v && v <= hi)));
1217            assert!(reach.holds(lo) && reach.holds(hi), "{reach:?}");
1218            assert!(!reach.holds(lo - 1) && !reach.holds(hi + 1), "{reach:?}");
1219            let can_differ = (lo..=hi)
1220                .filter(|v| reach.holds(*v))
1221                .map(|v| op.eval_d(v - literal))
1222                .collect::<std::collections::BTreeSet<_>>()
1223                .len()
1224                == 2;
1225            assert_eq!(can_differ, differs, "{reach:?} {op:?} {literal}");
1226            // One value seen: the plan asks for the other outcome only if there is one.
1227            let seen = (lo..=hi).find(|v| reach.holds(*v)).unwrap();
1228            let plan = plan_cmp(
1229                op,
1230                &Obs::of_d(seen - literal),
1231                Some((lo - literal, hi - literal)),
1232            );
1233            assert_eq!(plan.cannot_differ, !differs, "{reach:?} {op:?} {literal}");
1234            assert_eq!(plan.gap.is_some(), differs, "{reach:?} {op:?} {literal}");
1235        }
1236        assert_eq!(Reach::Multiples(8).interval(), None);
1237    }
1238
1239    #[test]
1240    fn gaps_of_another_kind_are_not_touched() {
1241        let obs = Obs::of_d(3);
1242        for gap in [
1243            InputGap::Unreached,
1244            InputGap::OneSided { always: true },
1245            InputGap::EqualNeverObserved {
1246                flipped: CmpOp::Le,
1247                float_gap: None,
1248            },
1249        ] {
1250            assert_eq!(
1251                within_reach(gap.clone(), CmpOp::Lt, &obs, Reach::Multiples(8), 20, true),
1252                Some(gap)
1253            );
1254        }
1255        // `blocks * 8 > 20` seen at 16 and 24: nothing between them is a multiple of 8.
1256        let mut obs = Obs::of_d(16 - 20);
1257        obs.merge(&Obs::of_d(24 - 20));
1258        let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1259        assert_eq!(
1260            within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1261            None
1262        );
1263        // Seen at 8 and 40: 16 and 24 are the values next to the boundary.
1264        let mut obs = Obs::of_d(8 - 20);
1265        obs.merge(&Obs::of_d(40 - 20));
1266        let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1267        assert_eq!(
1268            within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1269            Some(InputGap::Boundary {
1270                min_shift: -12,
1271                max_shift: 19,
1272                missing: vec![-4, 4],
1273                // `> 16` to `> 23` answer like `> 20` for 16 and 24, and all between.
1274                same: (-4, 3),
1275            })
1276        );
1277    }
1278
1279    fn obs_of(ds: &[i128]) -> Obs {
1280        let mut obs = Obs::default();
1281        for d in ds {
1282            obs.merge(&Obs::of_d(*d));
1283        }
1284        obs
1285    }
1286
1287    fn rel_of(d: i128) -> Rel {
1288        match d {
1289            d if d < 0 => Rel::Less,
1290            0 => Rel::Equal,
1291            _ => Rel::Greater,
1292        }
1293    }
1294
1295    /// Ground truth: does any concrete observation change under the mutation?
1296    fn brute_infects(op: CmpOp, m: Mutation, ds: &[i128]) -> bool {
1297        ds.iter()
1298            .any(|d| op.eval_d(*d) != eval_mutated_d(op, m, *d))
1299    }
1300
1301    #[test]
1302    fn is_eligible_example_from_the_readme() {
1303        // `age >= 18`, tests pass 17 and 20: D = -1 and 2.
1304        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[-1, 2]), None);
1305        assert_eq!(
1306            plan.gap,
1307            Some(InputGap::Boundary {
1308                min_shift: 0,
1309                max_shift: 2,
1310                missing: vec![0],
1311                same: (0, 0),
1312            })
1313        );
1314        // 17 is observed, so `age >= 17` flips a test outcome and has to be run.
1315        assert_eq!(plan.run, vec![Mutation::Shift(-1), Mutation::Negate]);
1316        assert_eq!(plan.gap.unwrap().representative(), Some(Mutation::Shift(1)));
1317    }
1318
1319    /// Every operator `<` and `>` are mistaken for is accounted for, whatever the tests
1320    /// saw: it answers like the original for all of it and passes (a gap says so), or
1321    /// it is run. It is never left to another mutant that answers alike: two mutants
1322    /// that both change the way the code goes meet different values afterwards.
1323    #[test]
1324    fn the_operators_a_comparison_is_mistaken_for() {
1325        let rels = [Rel::Less, Rel::Equal, Rel::Greater, Rel::Unordered];
1326        for op in [CmpOp::Lt, CmpOp::Gt] {
1327            for seen in 1u8..16 {
1328                let mut obs = Obs::default();
1329                let seen: Vec<Rel> = (0..4)
1330                    .filter(|i| seen & (1 << i) != 0)
1331                    .map(|i| rels[i])
1332                    .collect();
1333                for rel in &seen {
1334                    obs.merge(&Obs::of_rel(*rel));
1335                }
1336                let plan = plan_cmp(op, &obs, None);
1337                for other in op.mistaken_for() {
1338                    let like_the_original = seen
1339                        .iter()
1340                        .all(|rel| other.eval_rel(*rel) == op.eval_rel(*rel));
1341                    let what = format!("{op:?} as {other:?} with {seen:?}: {plan:?}");
1342                    let run = plan
1343                        .run
1344                        .iter()
1345                        .filter(|m| **m == Mutation::Op(*other))
1346                        .count();
1347                    if like_the_original {
1348                        assert!(plan.gap.is_some(), "{what}");
1349                        assert_eq!(run, 0, "{what}");
1350                    } else {
1351                        assert_eq!(run, 1, "{what}");
1352                    }
1353                }
1354            }
1355        }
1356        // The other operators get nothing added.
1357        for op in [CmpOp::Le, CmpOp::Ge, CmpOp::Eq, CmpOp::Ne] {
1358            assert!(op.mistaken_for().is_empty());
1359        }
1360        // `>` for `<=` and `<` for `>=` are the negation unless the operands have no
1361        // order, and only integers are known to always have one. For anything else the
1362        // operator is run beside the negation wherever it answers otherwise than the
1363        // original, whether or not the tests gave operands without an order.
1364        let seen = |rels: &[Rel]| {
1365            let mut obs = Obs::default();
1366            for rel in rels {
1367                obs.merge(&Obs::of_rel(*rel));
1368            }
1369            obs
1370        };
1371        for (op, reverse) in [(CmpOp::Ge, CmpOp::Lt), (CmpOp::Le, CmpOp::Gt)] {
1372            let run = |rels: &[Rel]| plan_cmp(op, &seen(rels), None).run;
1373            let reversed = |rels: &[Rel]| run(rels).contains(&Mutation::Op(reverse));
1374            assert!(reversed(&[Rel::Unordered, Rel::Less]), "{op:?}");
1375            assert!(reversed(&[Rel::Less, Rel::Greater]), "{op:?}");
1376            assert!(reversed(&[Rel::Less, Rel::Equal, Rel::Greater]), "{op:?}");
1377            // Where the operator answers like the original for all that was seen, it
1378            // passes and is not run: only operands without an order, or only the side
1379            // on which both are false.
1380            assert_eq!(run(&[Rel::Unordered]), vec![Mutation::Negate], "{op:?}");
1381            // Integers: the negation is the operator, at every distance.
1382            for ds in [&[-1i128, 1][..], &[-2, 0, 3], &[0, 1]] {
1383                let plan = plan_cmp(op, &obs_of(ds), None);
1384                assert!(!plan.run.contains(&Mutation::Op(reverse)), "{op:?} {ds:?}");
1385            }
1386            for d in -3..=3 {
1387                assert_eq!(eval_mutated_d(op, Mutation::Negate, d), reverse.eval_d(d));
1388            }
1389        }
1390        // `!=` for `==` is the negation with and without an order.
1391        let run = plan_cmp(CmpOp::Eq, &seen(&[Rel::Unordered, Rel::Equal]), None).run;
1392        assert_eq!(run, vec![Mutation::Negate]);
1393        // Seen above the bound only, `>=` and `>` in place of `<` answer alike, and
1394        // both are run: the first step they change, they go different ways.
1395        let plan = plan_cmp(CmpOp::Lt, &Obs::of_rel(Rel::Greater), None);
1396        assert_eq!(plan.run, vec![Mutation::Negate, Mutation::Op(CmpOp::Gt)]);
1397    }
1398
1399    #[test]
1400    fn pinned_boundary_has_no_input_gap() {
1401        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1402            let plan = plan_cmp(op, &obs_of(&[-1, 0, 1]), None);
1403            assert_eq!(plan.gap, None, "{op:?}");
1404            // With all three relations seen, no two operators answer alike.
1405            let mut run = vec![Mutation::Shift(-1), Mutation::Shift(1), Mutation::Negate];
1406            run.extend(op.mistaken_for().iter().map(|other| Mutation::Op(*other)));
1407            assert_eq!(plan.run, run, "{op:?}");
1408        }
1409    }
1410
1411    #[test]
1412    fn unreached_site() {
1413        let plan = plan_cmp(CmpOp::Lt, &Obs::default(), None);
1414        assert_eq!(
1415            plan,
1416            CmpPlan {
1417                cannot_differ: false,
1418                gap: Some(InputGap::Unreached),
1419                run: vec![]
1420            }
1421        );
1422    }
1423
1424    #[test]
1425    fn one_sided_condition() {
1426        let plan = plan_cmp(CmpOp::Gt, &obs_of(&[3, 5]), None);
1427        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1428        // Always true: the negation, `==` and `<` are all false here, and each is run.
1429        assert_eq!(
1430            plan.run,
1431            vec![
1432                Mutation::Negate,
1433                Mutation::Op(CmpOp::Eq),
1434                Mutation::Op(CmpOp::Lt)
1435            ]
1436        );
1437    }
1438
1439    #[test]
1440    fn unsigned_compared_with_zero_is_not_reported() {
1441        // `x >= 0` for unsigned x: D ranges over 0..=MAX, the condition cannot be false.
1442        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((0, 255)));
1443        assert_eq!(plan.gap, None);
1444        assert!(plan.cannot_differ);
1445        assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 255))).cannot_differ);
1446        assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[-1, 4]), Some((-1, 255))).cannot_differ);
1447        // `x < 0` for unsigned x can never be true either.
1448        let plan = plan_cmp(CmpOp::Lt, &obs_of(&[0, 4]), Some((0, 255)));
1449        assert_eq!(plan.gap, None);
1450        // `x >= 1` for unsigned x written as `x > 0`, observed at 0 and 1: both neighbours
1451        // are real mutants (`x > -1` is `x >= 0`, which differs at 0).
1452        let plan = plan_cmp(CmpOp::Gt, &obs_of(&[0, 1]), Some((0, 255)));
1453        assert_eq!(plan.gap, None);
1454        // `x == 0` answers like the negation at 0 and 1, and is run all the same.
1455        assert_eq!(
1456            plan.run,
1457            vec![
1458                Mutation::Shift(-1),
1459                Mutation::Shift(1),
1460                Mutation::Negate,
1461                Mutation::Op(CmpOp::Eq),
1462                Mutation::Op(CmpOp::Lt)
1463            ]
1464        );
1465        // `x <= 0` for unsigned x, observed at 0 and 1: `x <= -1` is a real mutant too,
1466        // but `x < 0`-style thresholds below the domain are not counted twice.
1467        let plan = plan_cmp(CmpOp::Le, &obs_of(&[0, 1]), Some((0, 255)));
1468        assert_eq!(plan.gap, None);
1469    }
1470
1471    #[test]
1472    fn one_sided_condition_at_the_edge_of_the_type() {
1473        // Always true, and the only value that makes it false is the type's minimum.
1474        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 10)));
1475        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1476        // ... or its maximum.
1477        let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 1)));
1478        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1479        let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 0)));
1480        assert_eq!(plan.gap, None);
1481        // Without values the types are unknown: report.
1482        let plan = plan_cmp(CmpOp::Ge, &Obs::of_rel(Rel::Greater), Some((0, 10)));
1483        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1484    }
1485
1486    #[test]
1487    fn representative_is_the_nearest_survivor() {
1488        let boundary = |min_shift, max_shift| InputGap::Boundary {
1489            min_shift,
1490            max_shift,
1491            missing: vec![0],
1492            same: (0, 0),
1493        };
1494        assert_eq!(boundary(-3, 1).representative(), Some(Mutation::Shift(1)));
1495        assert_eq!(boundary(-1, 0).representative(), Some(Mutation::Shift(-1)));
1496        assert_eq!(boundary(0, 0).representative(), None);
1497        assert_eq!(InputGap::Unreached.representative(), None);
1498        assert_eq!(
1499            InputGap::OneSided { always: false }.representative(),
1500            Some(Mutation::Const(false))
1501        );
1502        assert_eq!(
1503            InputGap::EqualNeverObserved {
1504                flipped: CmpOp::Ge,
1505                float_gap: None
1506            }
1507            .representative(),
1508            Some(Mutation::Op(CmpOp::Ge))
1509        );
1510    }
1511
1512    /// `a && b` / `a || b` with the tool's mutants, as a reference evaluator. Returns the
1513    /// result and whether the right operand was evaluated.
1514    fn eval_logic(and: bool, m: Option<Mutation>, a: bool, b: bool) -> (bool, bool) {
1515        let decided = |and: bool| if and { !a } else { a };
1516        match m {
1517            None => {
1518                if decided(and) {
1519                    (a, false)
1520                } else {
1521                    (b, true)
1522                }
1523            }
1524            Some(Mutation::LogicSwap) => {
1525                if decided(!and) {
1526                    (a, false)
1527                } else {
1528                    (b, true)
1529                }
1530            }
1531            // The right operand is evaluated as in the original, but its value is ignored.
1532            Some(Mutation::LogicDropRhs) => (a, !decided(and)),
1533            Some(Mutation::LogicDropLhs) => (b, true),
1534            other => panic!("{other:?}"),
1535        }
1536    }
1537
1538    #[test]
1539    fn logic_plans_match_a_reference_evaluator() {
1540        let cases = [(false, false), (false, true), (true, false), (true, true)];
1541        for and in [true, false] {
1542            for mask in 0u32..16 {
1543                let seen: Vec<(bool, bool)> = cases
1544                    .iter()
1545                    .enumerate()
1546                    .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1547                    .collect();
1548                let mut obs = LogicObs::default();
1549                for (a, b) in &seen {
1550                    let (_, evaluated) = eval_logic(and, None, *a, *b);
1551                    obs.short |= !evaluated;
1552                    obs.rhs_true |= evaluated && *b;
1553                    obs.rhs_false |= evaluated && !*b;
1554                }
1555                let ctx = format!("and={and} seen={seen:?}");
1556                let differs = |m: Mutation| {
1557                    seen.iter().any(|(a, b)| {
1558                        eval_logic(and, None, *a, *b) != eval_logic(and, Some(m), *a, *b)
1559                    })
1560                };
1561                let plan = plan_logic(and, &obs);
1562                if seen.is_empty() {
1563                    assert_eq!(
1564                        plan,
1565                        LogicPlan {
1566                            gaps: vec![LogicGap::Unreached],
1567                            run: vec![]
1568                        }
1569                    );
1570                    continue;
1571                }
1572                for (m, gap) in [
1573                    (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1574                    (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1575                ] {
1576                    // Exact: a gap iff no observed case evaluates differently.
1577                    assert_eq!(plan.gaps.contains(&gap), !differs(m), "{gap:?} {ctx}");
1578                    assert_eq!(plan.run.contains(&m), differs(m), "{m:?} {ctx}");
1579                    assert_eq!(logic_infects(and, m, &obs), differs(m), "{m:?} {ctx}");
1580                }
1581                // The swap is always run: never claimed safe.
1582                assert!(plan.run.contains(&Mutation::LogicSwap), "{ctx}");
1583                assert!(logic_infects(and, Mutation::LogicSwap, &obs), "{ctx}");
1584            }
1585        }
1586        // A right operand that was started and gave no value (it panicked, or left the
1587        // function): the expression was executed, the operator swapped is run against
1588        // this test, and the other two change nothing in it.
1589        let started = LogicObs::from_bits(8);
1590        assert!(started.rhs_started && started.reached());
1591        for and in [true, false] {
1592            let plan = plan_logic(and, &started);
1593            assert_eq!(plan.run, vec![Mutation::LogicSwap]);
1594            assert_eq!(
1595                plan.gaps,
1596                vec![LogicGap::RhsNeverDecides, LogicGap::LhsNeverDecides]
1597            );
1598            assert!(logic_infects(and, Mutation::LogicSwap, &started));
1599            assert!(!logic_infects(and, Mutation::LogicDropRhs, &started));
1600            assert!(!logic_infects(and, Mutation::LogicDropLhs, &started));
1601        }
1602        let mut merged = LogicObs::from_bits(2);
1603        merged.merge(&started);
1604        assert_eq!(merged, LogicObs::from_bits(10));
1605        assert_eq!(
1606            LogicObs::from_bits(5),
1607            LogicObs {
1608                short: true,
1609                rhs_true: false,
1610                rhs_false: true,
1611                rhs_started: false,
1612            }
1613        );
1614        assert_eq!(
1615            LogicObs::from_bits(2),
1616            LogicObs {
1617                short: false,
1618                rhs_true: true,
1619                rhs_false: false,
1620                rhs_started: false,
1621            }
1622        );
1623    }
1624
1625    #[test]
1626    fn return_plans() {
1627        assert_eq!(
1628            plan_return(&ReturnObs::from_bits(0)),
1629            ReturnPlan {
1630                unreached: true,
1631                always: None,
1632                run: vec![]
1633            }
1634        );
1635        assert_eq!(
1636            plan_return(&ReturnObs::from_bits(1)),
1637            ReturnPlan {
1638                unreached: false,
1639                always: Some(true),
1640                run: vec![Mutation::Const(false)]
1641            }
1642        );
1643        assert_eq!(
1644            plan_return(&ReturnObs::from_bits(2)),
1645            ReturnPlan {
1646                unreached: false,
1647                always: Some(false),
1648                run: vec![Mutation::Const(true)]
1649            }
1650        );
1651        assert_eq!(
1652            plan_return(&ReturnObs::from_bits(3)),
1653            ReturnPlan {
1654                unreached: false,
1655                always: None,
1656                run: vec![Mutation::Const(true), Mutation::Const(false)]
1657            }
1658        );
1659        // Forcing the value a test already sees changes nothing for that test.
1660        for bits in 0u8..4 {
1661            let obs = ReturnObs::from_bits(bits);
1662            assert_eq!(obs.infected_by_const(true), obs.saw_false);
1663            assert_eq!(obs.infected_by_const(false), obs.saw_true);
1664            assert_eq!(obs.reached(), bits != 0);
1665            let plan = plan_return(&obs);
1666            for m in &plan.run {
1667                let Mutation::Const(value) = m else { panic!() };
1668                assert!(
1669                    obs.infected_by_const(*value),
1670                    "a run mutant must change some test"
1671                );
1672            }
1673            if let Some(always) = plan.always {
1674                assert!(
1675                    !obs.infected_by_const(always),
1676                    "the survivor changes no test"
1677                );
1678            }
1679        }
1680        let mut merged = ReturnObs::from_bits(1);
1681        merged.merge(&ReturnObs::from_bits(2));
1682        assert_eq!(
1683            merged,
1684            ReturnObs {
1685                saw_true: true,
1686                saw_false: true
1687            }
1688        );
1689    }
1690
1691    #[test]
1692    fn logic_constant_value() {
1693        let cases = [(false, false), (false, true), (true, false), (true, true)];
1694        for and in [true, false] {
1695            for mask in 0u32..16 {
1696                let seen: Vec<(bool, bool)> = cases
1697                    .iter()
1698                    .enumerate()
1699                    .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1700                    .collect();
1701                let mut obs = LogicObs::default();
1702                let mut values = std::collections::BTreeSet::new();
1703                for (a, b) in &seen {
1704                    let (value, evaluated) = eval_logic(and, None, *a, *b);
1705                    values.insert(value);
1706                    obs.short |= !evaluated;
1707                    obs.rhs_true |= evaluated && *b;
1708                    obs.rhs_false |= evaluated && !*b;
1709                }
1710                let expected = if values.len() == 1 {
1711                    values.first().copied()
1712                } else {
1713                    None
1714                };
1715                assert_eq!(obs.constant_value(and), expected, "and={and} seen={seen:?}");
1716            }
1717        }
1718    }
1719
1720    #[test]
1721    fn option_return_plans() {
1722        let plan = |bits| plan_option_return(&ReturnObs::from_bits(bits));
1723        assert_eq!(
1724            plan(0),
1725            ReturnPlan {
1726                unreached: true,
1727                always: None,
1728                run: vec![]
1729            }
1730        );
1731        // Only `None` was ever returned: "always None" changes nothing.
1732        assert_eq!(
1733            plan(2),
1734            ReturnPlan {
1735                unreached: false,
1736                always: Some(false),
1737                run: vec![]
1738            }
1739        );
1740        // `Some` was returned: replacing it by `None` has to be run, against those tests.
1741        for bits in [1, 3] {
1742            assert_eq!(
1743                plan(bits),
1744                ReturnPlan {
1745                    unreached: false,
1746                    always: None,
1747                    run: vec![Mutation::Const(false)]
1748                }
1749            );
1750            assert!(ReturnObs::from_bits(bits).infected_by_const(false));
1751        }
1752        assert!(!ReturnObs::from_bits(2).infected_by_const(false));
1753    }
1754
1755    #[test]
1756    fn arithmetic_plans() {
1757        for bits in 0u8..8 {
1758            let obs = ArithObs::from_bits(bits);
1759            let expected = if bits & 2 != 0 {
1760                ArithPlan::Run
1761            } else if bits & 1 != 0 {
1762                ArithPlan::NeverDiffers
1763            } else if bits & 4 != 0 {
1764                ArithPlan::Opaque
1765            } else {
1766                ArithPlan::Unreached
1767            };
1768            assert_eq!(plan_arith(&obs), expected, "bits={bits}");
1769        }
1770        let mut merged = ArithObs::from_bits(1);
1771        merged.merge(&ArithObs::from_bits(4));
1772        assert_eq!(
1773            merged,
1774            ArithObs {
1775                same: true,
1776                differs: false,
1777                opaque: true,
1778                ..Default::default()
1779            }
1780        );
1781    }
1782
1783    #[test]
1784    fn float_comparison_without_equal_operands() {
1785        // `celsius > 30.5` with 10.0 and 40.0: differences -20.5 and 9.5.
1786        let mut obs = Obs::of_f(-20.5);
1787        obs.merge(&Obs::of_f(9.5));
1788        let plan = plan_cmp(CmpOp::Gt, &obs, None);
1789        let gap = plan.gap.expect("a gap");
1790        assert_eq!(
1791            gap,
1792            InputGap::EqualNeverObserved {
1793                flipped: CmpOp::Ge,
1794                float_gap: Some((-20.5, 9.5))
1795            }
1796        );
1797        assert_eq!(
1798            gap.survivors(),
1799            vec![
1800                Mutation::Op(CmpOp::Ge),
1801                Mutation::ShiftF(4.75),
1802                Mutation::ShiftF(-10.25)
1803            ]
1804        );
1805        // Shifts inside the unobserved gap infect nothing; outside it, or once equality
1806        // has been observed, they do.
1807        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1808            assert!(!infects(op, Mutation::ShiftF(4.75), &obs));
1809            assert!(!infects(op, Mutation::ShiftF(-10.25), &obs));
1810            assert!(infects(op, Mutation::ShiftF(9.5), &obs));
1811            assert!(infects(op, Mutation::ShiftF(-20.5), &obs));
1812        }
1813        let mut with_eq = obs;
1814        with_eq.merge(&Obs::of_f(0.0));
1815        assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &with_eq));
1816        assert_eq!(plan_cmp(CmpOp::Gt, &with_eq, None).gap, None);
1817        // Mixed with a non-float observation there is no float gap to speak of.
1818        let mut mixed = obs;
1819        mixed.merge(&Obs::of_rel(Rel::Less));
1820        assert_eq!(mixed.float_gap(), None);
1821        assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &mixed));
1822        assert_eq!(Obs::of_d(3).float_gap(), None);
1823    }
1824
1825    #[test]
1826    fn survivors_are_listed_nearest_first() {
1827        let boundary = |min_shift, max_shift| InputGap::Boundary {
1828            min_shift,
1829            max_shift,
1830            missing: vec![0],
1831            same: (0, 0),
1832        };
1833        assert_eq!(
1834            boundary(-9, 9).survivors(),
1835            vec![Mutation::Shift(1), Mutation::Shift(-1), Mutation::Shift(2)]
1836        );
1837        assert_eq!(boundary(-1, 0).survivors(), vec![Mutation::Shift(-1)]);
1838        assert_eq!(
1839            boundary(0, 2).survivors(),
1840            vec![Mutation::Shift(1), Mutation::Shift(2)]
1841        );
1842        assert_eq!(
1843            InputGap::OneSided { always: true }.survivors(),
1844            vec![Mutation::Const(true)]
1845        );
1846        assert_eq!(InputGap::Unreached.survivors(), vec![]);
1847    }
1848
1849    #[test]
1850    fn single_observation_summaries() {
1851        let bits = |o: Obs| (o.lt, o.eq, o.gt, o.un);
1852        assert_eq!(bits(Obs::of_f(-0.5)), (true, false, false, false));
1853        assert_eq!(bits(Obs::of_f(0.0)), (false, true, false, false));
1854        assert_eq!(bits(Obs::of_f(0.5)), (false, false, true, false));
1855        assert_eq!(
1856            (Obs::of_f(-0.5).f_max_neg, Obs::of_f(-0.5).f_min_pos),
1857            (Some(-0.5), None)
1858        );
1859        assert_eq!(
1860            (Obs::of_f(0.5).f_max_neg, Obs::of_f(0.5).f_min_pos),
1861            (None, Some(0.5))
1862        );
1863        assert_eq!(
1864            (Obs::of_f(0.0).f_max_neg, Obs::of_f(0.0).f_min_pos),
1865            (None, None)
1866        );
1867        assert!(Obs::of_f(1.0).unvalued && !Obs::of_f(1.0).unfloat);
1868        assert!(Obs::of_d(1).unfloat && !Obs::of_d(1).unvalued);
1869
1870        // Reached through any one relation, including "unordered" alone.
1871        assert!(Obs::of_rel(Rel::Unordered).reached());
1872        assert!(!Obs::default().reached());
1873        // An unreached site has no values, even though nothing contradicts having them.
1874        assert!(!Obs::default().valued());
1875        assert!(Obs::of_d(0).valued());
1876        assert!(!Obs::of_rel(Rel::Equal).valued());
1877
1878        // A NaN comparison among floats spoils the float gap.
1879        let mut nan = Obs::of_f(-1.0);
1880        nan.merge(&Obs::of_f(1.0));
1881        assert_eq!(nan.float_gap(), Some((-1.0, 1.0)));
1882        nan.un = true;
1883        assert_eq!(nan.float_gap(), None);
1884        assert_eq!(Obs::default().float_gap(), None);
1885        assert_eq!(Obs::of_f(-1.0).float_gap(), None, "one side only");
1886    }
1887
1888    #[test]
1889    fn interval_queries_look_at_the_right_side_of_zero() {
1890        // Only positives were observed: an interval of negatives is empty, and vice versa.
1891        assert!(!obs_of(&[2]).saw_any_in(-3, -1));
1892        assert!(!obs_of(&[-2]).saw_any_in(1, 3));
1893        assert!(obs_of(&[-2]).saw_any_in(-3, -1));
1894        assert!(obs_of(&[2]).saw_any_in(1, 3));
1895        assert!(!obs_of(&[-4]).saw_any_in(-3, 0));
1896        assert!(!obs_of(&[4]).saw_any_in(0, 3));
1897        // A stray value on the far side must not leak into the answer.
1898        let mut odd = obs_of(&[3]);
1899        odd.max_neg = Some(5);
1900        assert!(!odd.saw_any_in(0, 2));
1901        let mut odd = obs_of(&[-3]);
1902        odd.min_pos = Some(-5);
1903        assert!(!odd.saw_any_in(-2, 0));
1904    }
1905
1906    #[test]
1907    fn empty_interval_has_no_observations() {
1908        assert!(!obs_of(&[-1, 0, 1]).saw_any_in(1, 0));
1909        assert!(obs_of(&[0]).saw_any_in(0, 0));
1910    }
1911
1912    #[test]
1913    fn unvalued_ordering_without_equal_operands() {
1914        let mut obs = Obs::of_rel(Rel::Less);
1915        obs.merge(&Obs::of_rel(Rel::Greater));
1916        let plan = plan_cmp(CmpOp::Lt, &obs, None);
1917        assert_eq!(
1918            plan.gap,
1919            Some(InputGap::EqualNeverObserved {
1920                flipped: CmpOp::Le,
1921                float_gap: None
1922            })
1923        );
1924        // Without equal operands `>` answers like the negation; it is run as well.
1925        assert_eq!(
1926            plan.run,
1927            vec![
1928                Mutation::Negate,
1929                Mutation::Op(CmpOp::Eq),
1930                Mutation::Op(CmpOp::Gt)
1931            ]
1932        );
1933
1934        obs.merge(&Obs::of_rel(Rel::Equal));
1935        let plan = plan_cmp(CmpOp::Lt, &obs, None);
1936        assert_eq!(plan.gap, None);
1937        assert_eq!(
1938            plan.run,
1939            vec![
1940                Mutation::Op(CmpOp::Le),
1941                Mutation::Negate,
1942                Mutation::Op(CmpOp::Eq),
1943                Mutation::Op(CmpOp::Gt)
1944            ]
1945        );
1946    }
1947
1948    #[test]
1949    fn equality_with_both_outcomes() {
1950        let plan = plan_cmp(CmpOp::Eq, &obs_of(&[0, 7]), None);
1951        assert_eq!(
1952            plan,
1953            CmpPlan {
1954                cannot_differ: false,
1955                gap: None,
1956                run: vec![Mutation::Negate]
1957            }
1958        );
1959    }
1960
1961    #[test]
1962    fn unordered_counts_as_not_equal() {
1963        let obs = Obs::of_rel(Rel::Unordered);
1964        assert!(infects(CmpOp::Ne, Mutation::Const(false), &obs));
1965        assert!(!infects(CmpOp::Lt, Mutation::Op(CmpOp::Ge), &obs));
1966        assert!(infects(CmpOp::Lt, Mutation::Op(CmpOp::Ne), &obs));
1967    }
1968
1969    #[test]
1970    fn merge_is_a_semilattice() {
1971        let samples: Vec<Obs> = [-3, -1, 0, 1, 4]
1972            .into_iter()
1973            .map(Obs::of_d)
1974            .chain([
1975                Obs::of_rel(Rel::Unordered),
1976                Obs::of_rel(Rel::Less),
1977                Obs::default(),
1978            ])
1979            .collect();
1980        for a in &samples {
1981            let mut aa = *a;
1982            aa.merge(a);
1983            assert_eq!(aa, *a, "idempotent");
1984            for b in &samples {
1985                let (mut ab, mut ba) = (*a, *b);
1986                ab.merge(b);
1987                ba.merge(a);
1988                assert_eq!(ab, ba, "commutative");
1989                for c in &samples {
1990                    let mut ab_c = ab;
1991                    ab_c.merge(c);
1992                    let mut bc = *b;
1993                    bc.merge(c);
1994                    let mut a_bc = *a;
1995                    a_bc.merge(&bc);
1996                    assert_eq!(ab_c, a_bc, "associative");
1997                }
1998            }
1999        }
2000    }
2001
2002    #[test]
2003    fn mutation_wire_format() {
2004        assert_eq!(Mutation::Const(true).encode(), "c1");
2005        assert_eq!(Mutation::Const(false).encode(), "c0");
2006        assert_eq!(Mutation::Negate.encode(), "neg");
2007        assert_eq!(Mutation::Op(CmpOp::Ge).encode(), "op3");
2008        assert_eq!(Mutation::Shift(-2).encode(), "sh-2");
2009        assert_eq!(Mutation::Delete.encode(), "del");
2010        assert_eq!(Mutation::ShiftF(4.75).encode(), "shf4.75");
2011        assert_eq!(Mutation::ShiftF(-10.0).encode(), "shf-10.0");
2012        assert_eq!(Mutation::LogicSwap.encode(), "lsw");
2013        assert_eq!(Mutation::LogicDropRhs.encode(), "ldr");
2014        assert_eq!(Mutation::LogicDropLhs.encode(), "ldl");
2015        assert_eq!(Mutation::ArithSwap.encode(), "asw");
2016        assert_eq!(Mutation::DropNot.encode(), "unn");
2017        assert_eq!(Mutation::RangeEnd.encode(), "rng");
2018        assert_eq!(Mutation::MinMax.encode(), "mmx");
2019    }
2020
2021    fn candidate_mutations(op: CmpOp) -> Vec<Mutation> {
2022        let mut ms = vec![
2023            Mutation::Const(true),
2024            Mutation::Const(false),
2025            Mutation::Negate,
2026        ];
2027        ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
2028        if op.is_ordering() {
2029            ms.extend((-5..=5).filter(|s| *s != 0).map(Mutation::Shift));
2030        }
2031        ms
2032    }
2033
2034    /// Checks a plan against concrete observations by brute force.
2035    fn check_plan(op: CmpOp, ds: &[i128], domain: Option<(i128, i128)>) {
2036        let obs = obs_of(ds);
2037        let ctx = format!("{op:?} ds={ds:?} domain={domain:?}");
2038        let (dom_lo, dom_hi) = domain.unwrap_or((-50, 50));
2039        let differs_somewhere =
2040            |m: Mutation| (dom_lo..=dom_hi).any(|d| op.eval_d(d) != eval_mutated_d(op, m, d));
2041
2042        for m in candidate_mutations(op) {
2043            assert_eq!(
2044                infects(op, m, &obs),
2045                brute_infects(op, m, ds),
2046                "infects {m:?} {ctx}"
2047            );
2048        }
2049
2050        let plan = plan_cmp(op, &obs, domain);
2051        for m in &plan.run {
2052            assert!(
2053                brute_infects(op, *m, ds),
2054                "run {m:?} must be infected: {ctx}"
2055            );
2056            assert!(differs_somewhere(*m), "run {m:?} is equivalent: {ctx}");
2057        }
2058        match &plan.gap {
2059            None => {}
2060            Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2061            Some(InputGap::OneSided { always }) => {
2062                assert!(ds.iter().all(|d| op.eval_d(*d) == *always), "{ctx}");
2063                assert!(differs_somewhere(Mutation::Const(*always)), "{ctx}");
2064            }
2065            Some(InputGap::Boundary {
2066                min_shift,
2067                max_shift,
2068                missing,
2069                same: _,
2070            }) => {
2071                assert!(*min_shift <= 0 && 0 <= *max_shift, "{ctx}");
2072                for s in (*min_shift..=*max_shift).filter(|s| *s != 0) {
2073                    let m = Mutation::Shift(s);
2074                    assert!(
2075                        !brute_infects(op, m, ds),
2076                        "survivor {m:?} is infected: {ctx}"
2077                    );
2078                    assert!(differs_somewhere(m), "survivor {m:?} is equivalent: {ctx}");
2079                }
2080                if domain.is_none() {
2081                    // Exactness: one step outside the range is caught by some observation.
2082                    for s in [min_shift - 1, max_shift + 1] {
2083                        assert!(
2084                            brute_infects(op, Mutation::Shift(s), ds),
2085                            "range not maximal: {ctx}"
2086                        );
2087                    }
2088                }
2089                assert!(!missing.is_empty(), "{ctx}");
2090                for w in missing {
2091                    assert!(!ds.contains(w), "missing value {w} was observed: {ctx}");
2092                    assert!(
2093                        dom_lo <= *w && *w <= dom_hi,
2094                        "missing value {w} out of domain: {ctx}"
2095                    );
2096                    let s = if op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(1), *w) {
2097                        1
2098                    } else {
2099                        -1
2100                    };
2101                    assert!(
2102                        op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(s), *w),
2103                        "missing value {w} separates nothing: {ctx}"
2104                    );
2105                    assert!(*min_shift <= s && s <= *max_shift, "{ctx}");
2106                }
2107            }
2108            Some(InputGap::EqualNeverObserved { .. }) => panic!("valued site: {ctx}"),
2109        }
2110        if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2111            assert!(
2112                !brute_infects(op, m, ds),
2113                "representative {m:?} is infected: {ctx}"
2114            );
2115        }
2116
2117        // Completeness for the off-by-one mutants: each is a survivor, is run, or is equivalent.
2118        if op.is_ordering() && ds.iter().any(|d| op.eval_d(*d)) && ds.iter().any(|d| !op.eval_d(*d))
2119        {
2120            for s in [-1, 1] {
2121                let m = Mutation::Shift(s);
2122                let survivor = matches!(&plan.gap, Some(InputGap::Boundary { min_shift, max_shift, .. })
2123                    if *min_shift <= s && s <= *max_shift);
2124                let ran = plan.run.contains(&m);
2125                assert!(
2126                    survivor ^ ran || !differs_somewhere(m),
2127                    "Shift({s}) unaccounted for: survivor={survivor} ran={ran} {ctx}"
2128                );
2129            }
2130        }
2131    }
2132
2133    #[test]
2134    fn exhaustive_small_observation_sets() {
2135        let universe: Vec<i128> = (-3..=3).collect();
2136        for op in CmpOp::ALL {
2137            for mask in 0u32..(1 << universe.len()) {
2138                let ds: Vec<i128> = universe
2139                    .iter()
2140                    .enumerate()
2141                    .filter_map(|(i, d)| (mask & (1 << i) != 0).then_some(*d))
2142                    .collect();
2143                check_plan(op, &ds, None);
2144                // Domains that contain every observation.
2145                for (lo, hi) in [(0, 10), (-10, 0), (-2, 2), (1, 9), (-9, -1)] {
2146                    if ds.iter().all(|d| lo <= *d && *d <= hi) {
2147                        check_plan(op, &ds, Some((lo, hi)));
2148                    }
2149                }
2150            }
2151        }
2152    }
2153
2154    /// Rows generated by `pict formal/pict/planner.pict /o:3 /e:formal/pict/planner.seed.tsv`.
2155    #[test]
2156    fn pict_table() {
2157        let table = include_str!("../tests/data/planner.pict.tsv");
2158        let mut rows = 0;
2159        for line in table.lines().skip(1) {
2160            let cols: Vec<&str> = line.split('\t').collect();
2161            let [op, below, equal, above, valued, literal, domain] = cols[..] else {
2162                panic!("bad row: {line}");
2163            };
2164            let op = match op {
2165                "lt" => CmpOp::Lt,
2166                "le" => CmpOp::Le,
2167                "gt" => CmpOp::Gt,
2168                "ge" => CmpOp::Ge,
2169                "eq" => CmpOp::Eq,
2170                "ne" => CmpOp::Ne,
2171                other => panic!("op {other}"),
2172            };
2173            let mut ds: Vec<i128> = vec![];
2174            match below {
2175                "none" => {}
2176                "adjacent" => ds.extend([-1, -4]),
2177                "far" => ds.extend([-3, -6]),
2178                other => panic!("below {other}"),
2179            }
2180            if equal == "yes" {
2181                ds.push(0);
2182            }
2183            match above {
2184                "none" => {}
2185                "adjacent" => ds.extend([1, 5]),
2186                "far" => ds.extend([3, 7]),
2187                other => panic!("above {other}"),
2188            }
2189            rows += 1;
2190            if valued == "no" {
2191                let mut obs = Obs::default();
2192                for d in &ds {
2193                    obs.merge(&Obs::of_rel(rel_of(*d)));
2194                }
2195                check_unvalued(op, &obs, &ds, line);
2196                continue;
2197            }
2198            // D = lhs - rhs. With the literal on the right, a tight lower bound on the other
2199            // operand is a lower bound on D; with the literal on the left it is an upper bound.
2200            let domain = match (literal, domain) {
2201                ("none", _) => None,
2202                (_, "wide") => Some((-40, 40)),
2203                ("rhs", "tight_low") | ("lhs", "tight_high") => Some((0, 40)),
2204                ("rhs", "tight_high") | ("lhs", "tight_low") => Some((-40, 0)),
2205                other => panic!("domain {other:?}"),
2206            };
2207            check_plan(op, &ds, domain);
2208        }
2209        assert_eq!(rows, table.lines().count() - 1);
2210        assert!(rows > 50, "the PICT table looks truncated: {rows} rows");
2211    }
2212
2213    fn check_unvalued(op: CmpOp, obs: &Obs, ds: &[i128], ctx: &str) {
2214        let plan = plan_cmp(op, obs, None);
2215        for m in [
2216            Mutation::Const(true),
2217            Mutation::Const(false),
2218            Mutation::Negate,
2219        ]
2220        .into_iter()
2221        .chain(CmpOp::ALL.into_iter().map(Mutation::Op))
2222        {
2223            assert_eq!(
2224                infects(op, m, obs),
2225                brute_infects(op, m, ds),
2226                "infects {m:?} {ctx}"
2227            );
2228        }
2229        for m in &plan.run {
2230            assert!(
2231                brute_infects(op, *m, ds),
2232                "run {m:?} must be infected: {ctx}"
2233            );
2234        }
2235        if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2236            assert!(
2237                !brute_infects(op, m, ds),
2238                "representative {m:?} is infected: {ctx}"
2239            );
2240        }
2241        match &plan.gap {
2242            Some(InputGap::Boundary { .. }) => panic!("unvalued site cannot shift: {ctx}"),
2243            Some(InputGap::EqualNeverObserved { flipped, .. }) => {
2244                assert!(!ds.contains(&0), "{ctx}");
2245                assert_eq!(op.flip_eq(), Some(*flipped), "{ctx}");
2246            }
2247            Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2248            _ => {}
2249        }
2250        // A shift on a reached site without values is never claimed to be safe.
2251        if op.is_ordering() && obs.reached() {
2252            assert!(infects(op, Mutation::Shift(1), obs), "{ctx}");
2253        }
2254    }
2255}