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    },
418    /// The operands were never equal (and carry no integer values); `Op(flipped)` survives.
419    /// For floats, `float_gap` is the range of differences no test observed: every
420    /// `ShiftF(d)` strictly inside it survives too.
421    EqualNeverObserved {
422        flipped: CmpOp,
423        float_gap: Option<(f64, f64)>,
424    },
425}
426
427#[derive(Clone, PartialEq, Debug, Default)]
428pub struct CmpPlan {
429    /// The comparison had one outcome in every test and its operand types allow no other
430    /// (`x >= 0` for unsigned `x`): whatever encloses it is constant for the same reason.
431    pub cannot_differ: bool,
432    pub gap: Option<InputGap>,
433    /// Mutations that change the outcome of at least one test's observation. Only running
434    /// the tests can tell whether an assertion notices.
435    pub run: Vec<Mutation>,
436}
437
438impl InputGap {
439    /// One concrete mutation that the gap lets through, nearest to the original.
440    pub fn representative(&self) -> Option<Mutation> {
441        match self {
442            InputGap::Unreached => None,
443            InputGap::OneSided { always } => Some(Mutation::Const(*always)),
444            InputGap::Boundary {
445                min_shift,
446                max_shift,
447                ..
448            } => {
449                if *max_shift >= 1 {
450                    Some(Mutation::Shift(1))
451                } else if *min_shift <= -1 {
452                    Some(Mutation::Shift(-1))
453                } else {
454                    None
455                }
456            }
457            InputGap::EqualNeverObserved { flipped, .. } => Some(Mutation::Op(*flipped)),
458        }
459    }
460
461    /// Up to three concrete mutations the gap lets through, nearest to the original first.
462    pub fn survivors(&self) -> Vec<Mutation> {
463        match self {
464            InputGap::Boundary {
465                min_shift,
466                max_shift,
467                ..
468            } => (1..=3)
469                .flat_map(|n| [n, -n])
470                .filter(|s| min_shift <= s && s <= max_shift)
471                .take(3)
472                .map(Mutation::Shift)
473                .collect(),
474            InputGap::EqualNeverObserved { flipped, float_gap } => {
475                let mut all = vec![Mutation::Op(*flipped)];
476                if let Some((lo, hi)) = float_gap {
477                    all.extend([Mutation::ShiftF(hi / 2.0), Mutation::ShiftF(lo / 2.0)]);
478                }
479                all
480            }
481            other => other.representative().into_iter().collect(),
482        }
483    }
484}
485
486/// Plans one comparison site. `domain` is the range of `D` the operand types allow, when
487/// known. It only matters for a condition with a single observed outcome: if the types
488/// rule the other outcome out (`x >= 0` for unsigned `x`), there is nothing to report.
489pub fn plan_cmp(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
490    let mut plan = plan_boundary(op, obs, domain);
491    // The other operators a `<` or `>` is commonly mistaken for (the replacements
492    // cargo-mutants makes). One that answers like the original for every relation the
493    // tests saw runs like the original from the first step to the last and passes them
494    // all, which the gap already says. Every other one is run, also where it answers
495    // like another mutant for everything that was seen: once a mutant has changed the
496    // way the code goes, the comparison meets values the tests never gave it, and there
497    // the two may part.
498    let answers =
499        |other: CmpOp| -> Vec<bool> { obs.rels().map(|rel| other.eval_rel(rel)).collect() };
500    for other in op.mistaken_for() {
501        if answers(*other) != answers(op) {
502            plan.run.push(Mutation::Op(*other));
503        }
504    }
505    // `>` for `<=` and `<` for `>=` are the negation, except for operands that have no
506    // order (NaN): there the negation is true and the other operator false. Only
507    // integers are known to always have an order. For anything else the two are
508    // different mutants and both are run, whether or not the tests gave the comparison
509    // such operands: a mutant that changes the way the code goes can be the first to.
510    if matches!(op, CmpOp::Le | CmpOp::Ge) && !obs.valued() && answers(op.negated()) != answers(op)
511    {
512        plan.run.push(Mutation::Op(op.negated()));
513    }
514    plan
515}
516
517fn plan_boundary(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
518    if !obs.reached() {
519        return CmpPlan {
520            cannot_differ: false,
521            gap: Some(InputGap::Unreached),
522            run: vec![],
523        };
524    }
525    let saw_true = obs.rels().any(|r| op.eval_rel(r));
526    let saw_false = obs.rels().any(|r| !op.eval_rel(r));
527    if !(saw_true && saw_false) {
528        let always = saw_true;
529        // Can the other outcome happen at all? Only checkable on integers with known types.
530        let other_possible = match domain {
531            // The domain is an interval that contains the observations, so if the other
532            // outcome is possible at all, it is possible next to zero.
533            Some((lo, hi)) if obs.valued() => [-1, 0, 1]
534                .into_iter()
535                .any(|d| lo <= d && d <= hi && op.eval_d(d) != always),
536            _ => true,
537        };
538        return CmpPlan {
539            cannot_differ: !other_possible,
540            gap: other_possible.then_some(InputGap::OneSided { always }),
541            run: vec![Mutation::Negate],
542        };
543    }
544
545    let Some((up, t0)) = op.threshold() else {
546        // `==` / `!=` with both outcomes observed: nothing to shift.
547        return CmpPlan {
548            cannot_differ: false,
549            gap: None,
550            run: vec![Mutation::Negate],
551        };
552    };
553
554    if !obs.valued() {
555        let flipped = op
556            .flip_eq()
557            .expect("ordering operators have a flipped form");
558        return if obs.eq {
559            CmpPlan {
560                cannot_differ: false,
561                gap: None,
562                run: vec![Mutation::Op(flipped), Mutation::Negate],
563            }
564        } else {
565            CmpPlan {
566                cannot_differ: false,
567                gap: Some(InputGap::EqualNeverObserved {
568                    flipped,
569                    float_gap: obs.float_gap(),
570                }),
571                run: vec![Mutation::Negate],
572            }
573        };
574    }
575
576    // Nearest observations on each side of the boundary, and the two values of D that
577    // straddle it: `w_minus` separates the original from Shift(-1), `w_plus` from Shift(+1).
578    let (below, above, w_minus, w_plus) = if up {
579        (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
580    } else {
581        (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
582    };
583    let below = below.expect("both outcomes were observed");
584    let above = above.expect("both outcomes were observed");
585    let (min_shift, max_shift) = if up {
586        (below + 1 - t0, above - t0)
587    } else {
588        (below - t0, above - 1 - t0)
589    };
590
591    // Both outcomes were observed, so both `w_minus` and `w_plus` lie between two observed
592    // values: they are inside the operand types' range and the mutants are not equivalent.
593    let mut missing = vec![];
594    let mut run = vec![];
595    for (w, shift) in [(w_minus, -1), (w_plus, 1)] {
596        if obs.saw(w) {
597            run.push(Mutation::Shift(shift));
598        } else {
599            missing.push(w);
600        }
601    }
602    run.push(Mutation::Negate);
603    let gap = (!missing.is_empty()).then_some(InputGap::Boundary {
604        min_shift,
605        max_shift,
606        missing,
607    });
608    CmpPlan {
609        cannot_differ: false,
610        gap,
611        run,
612    }
613}
614
615/// What the tests observed at `a && b` / `a || b`.
616#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
617pub struct LogicObs {
618    /// The left operand decided alone (false for `&&`, true for `||`).
619    pub short: bool,
620    pub rhs_true: bool,
621    pub rhs_false: bool,
622    /// The right operand was started. Where it gave no value (a panic, a `?`, a
623    /// `return`) this is all there is to see of the expression having been executed.
624    pub rhs_started: bool,
625}
626
627impl LogicObs {
628    pub fn from_bits(bits: u8) -> LogicObs {
629        LogicObs {
630            short: bits & 1 != 0,
631            rhs_true: bits & 2 != 0,
632            rhs_false: bits & 4 != 0,
633            rhs_started: bits & 8 != 0,
634        }
635    }
636
637    pub fn merge(&mut self, other: &LogicObs) {
638        self.short |= other.short;
639        self.rhs_true |= other.rhs_true;
640        self.rhs_false |= other.rhs_false;
641        self.rhs_started |= other.rhs_started;
642    }
643
644    pub fn reached(&self) -> bool {
645        self.short || self.rhs_true || self.rhs_false || self.rhs_started
646    }
647
648    /// The value of the whole expression, if it was the same in every observation.
649    pub fn constant_value(&self, and: bool) -> Option<bool> {
650        // A short circuit yields false for `&&` and true for `||`.
651        let saw_true = self.rhs_true || (self.short && !and);
652        let saw_false = self.rhs_false || (self.short && and);
653        match (saw_true, saw_false) {
654            (true, false) => Some(true),
655            (false, true) => Some(false),
656            _ => None,
657        }
658    }
659
660    /// The right operand was evaluated and its value decided the result.
661    fn rhs_decided(&self, and: bool) -> bool {
662        if and { self.rhs_false } else { self.rhs_true }
663    }
664}
665
666#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
667#[serde(rename_all = "snake_case")]
668pub enum LogicGap {
669    Unreached,
670    /// No test has the right operand decide the result: `LogicDropRhs` survives.
671    RhsNeverDecides,
672    /// No test has the left operand decide the result: `LogicDropLhs` survives.
673    LhsNeverDecides,
674}
675
676#[derive(Clone, PartialEq, Debug, Default)]
677pub struct LogicPlan {
678    pub gaps: Vec<LogicGap>,
679    pub run: Vec<Mutation>,
680}
681
682/// Whether a test with these observations can execute differently under `m`.
683/// Swapping the operator changes when the right operand is evaluated, so it is treated as
684/// infecting every test that reaches the expression.
685pub fn logic_infects(and: bool, m: Mutation, obs: &LogicObs) -> bool {
686    match m {
687        Mutation::LogicDropRhs => obs.rhs_decided(and),
688        Mutation::LogicDropLhs => obs.short,
689        _ => obs.reached(),
690    }
691}
692
693pub fn plan_logic(and: bool, obs: &LogicObs) -> LogicPlan {
694    if !obs.reached() {
695        return LogicPlan {
696            gaps: vec![LogicGap::Unreached],
697            run: vec![],
698        };
699    }
700    let mut plan = LogicPlan::default();
701    for (m, gap) in [
702        (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
703        (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
704    ] {
705        if logic_infects(and, m, obs) {
706            plan.run.push(m);
707        } else {
708            plan.gaps.push(gap);
709        }
710    }
711    plan.run.push(Mutation::LogicSwap);
712    plan
713}
714
715/// What the tests observed at an arithmetic operator on primitive numbers.
716#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
717pub struct ArithObs {
718    /// The swapped operator gave the same result.
719    pub same: bool,
720    /// The swapped operator gave a different result.
721    pub differs: bool,
722    /// The operands were not primitive numbers: nothing can be said.
723    pub opaque: bool,
724    /// The same for the operator's second replacement, where it has one.
725    pub same2: bool,
726    pub differs2: bool,
727}
728
729impl ArithObs {
730    pub fn from_bits(bits: u8) -> ArithObs {
731        ArithObs {
732            same: bits & 1 != 0,
733            differs: bits & 2 != 0,
734            opaque: bits & 4 != 0,
735            same2: bits & 8 != 0,
736            differs2: bits & 16 != 0,
737        }
738    }
739
740    pub fn merge(&mut self, other: &ArithObs) {
741        self.same |= other.same;
742        self.differs |= other.differs;
743        self.opaque |= other.opaque;
744        self.same2 |= other.same2;
745        self.differs2 |= other.differs2;
746    }
747
748    /// The observations as they are for the second replacement.
749    pub fn second(&self) -> ArithObs {
750        ArithObs {
751            same: self.same2,
752            differs: self.differs2,
753            opaque: self.opaque,
754            same2: false,
755            differs2: false,
756        }
757    }
758
759    /// Whether mutation `m` computes another value in this test.
760    pub fn infected_by(&self, m: Mutation) -> bool {
761        if m == Mutation::ArithSwap2 {
762            self.differs2
763        } else {
764            self.differs
765        }
766    }
767}
768
769#[derive(Clone, Copy, PartialEq, Eq, Debug)]
770pub enum ArithPlan {
771    Unreached,
772    /// Not primitive numbers: not mutated.
773    Opaque,
774    /// The swapped operator agrees on every observed pair of operands: it survives.
775    NeverDiffers,
776    /// Some test computes a different value: run `ArithSwap` against those tests.
777    Run,
778}
779
780pub fn plan_arith(obs: &ArithObs) -> ArithPlan {
781    if obs.differs {
782        ArithPlan::Run
783    } else if obs.same {
784        ArithPlan::NeverDiffers
785    } else if obs.opaque {
786        ArithPlan::Opaque
787    } else {
788        ArithPlan::Unreached
789    }
790}
791
792/// What a `-> bool` function returned at its normal exit.
793#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
794pub struct ReturnObs {
795    pub saw_true: bool,
796    pub saw_false: bool,
797}
798
799impl ReturnObs {
800    pub fn from_bits(bits: u8) -> ReturnObs {
801        ReturnObs {
802            saw_true: bits & 1 != 0,
803            saw_false: bits & 2 != 0,
804        }
805    }
806
807    pub fn merge(&mut self, other: &ReturnObs) {
808        self.saw_true |= other.saw_true;
809        self.saw_false |= other.saw_false;
810    }
811
812    pub fn reached(&self) -> bool {
813        self.saw_true || self.saw_false
814    }
815
816    /// Whether replacing the returned value by `value` changes anything for this test.
817    pub fn infected_by_const(&self, value: bool) -> bool {
818        if value { self.saw_false } else { self.saw_true }
819    }
820}
821
822#[derive(Clone, PartialEq, Debug, Default)]
823pub struct ReturnPlan {
824    pub unreached: bool,
825    /// The function returned only this value: `Const(value)` survives.
826    pub always: Option<bool>,
827    pub run: Vec<Mutation>,
828}
829
830/// Plans a function returning `Option<T>`, where `saw_true` stands for `Some` and
831/// `saw_false` for `None`. The result can be replaced by `None` but not by a `Some`.
832pub fn plan_option_return(obs: &ReturnObs) -> ReturnPlan {
833    match (obs.saw_true, obs.saw_false) {
834        (false, false) => ReturnPlan {
835            unreached: true,
836            ..ReturnPlan::default()
837        },
838        // Never `Some`: always returning `None` passes every test.
839        (false, true) => ReturnPlan {
840            unreached: false,
841            always: Some(false),
842            run: vec![],
843        },
844        (true, _) => ReturnPlan {
845            unreached: false,
846            always: None,
847            run: vec![Mutation::Const(false)],
848        },
849    }
850}
851
852pub fn plan_return(obs: &ReturnObs) -> ReturnPlan {
853    match (obs.saw_true, obs.saw_false) {
854        (false, false) => ReturnPlan {
855            unreached: true,
856            ..ReturnPlan::default()
857        },
858        (true, true) => ReturnPlan {
859            run: vec![Mutation::Const(true), Mutation::Const(false)],
860            ..ReturnPlan::default()
861        },
862        (always, _) => ReturnPlan {
863            unreached: false,
864            always: Some(always),
865            run: vec![Mutation::Const(!always)],
866        },
867    }
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873
874    fn obs_of(ds: &[i128]) -> Obs {
875        let mut obs = Obs::default();
876        for d in ds {
877            obs.merge(&Obs::of_d(*d));
878        }
879        obs
880    }
881
882    fn rel_of(d: i128) -> Rel {
883        match d {
884            d if d < 0 => Rel::Less,
885            0 => Rel::Equal,
886            _ => Rel::Greater,
887        }
888    }
889
890    /// Ground truth: does any concrete observation change under the mutation?
891    fn brute_infects(op: CmpOp, m: Mutation, ds: &[i128]) -> bool {
892        ds.iter()
893            .any(|d| op.eval_d(*d) != eval_mutated_d(op, m, *d))
894    }
895
896    #[test]
897    fn is_eligible_example_from_the_readme() {
898        // `age >= 18`, tests pass 17 and 20: D = -1 and 2.
899        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[-1, 2]), None);
900        assert_eq!(
901            plan.gap,
902            Some(InputGap::Boundary {
903                min_shift: 0,
904                max_shift: 2,
905                missing: vec![0]
906            })
907        );
908        // 17 is observed, so `age >= 17` flips a test outcome and has to be run.
909        assert_eq!(plan.run, vec![Mutation::Shift(-1), Mutation::Negate]);
910        assert_eq!(plan.gap.unwrap().representative(), Some(Mutation::Shift(1)));
911    }
912
913    /// Every operator `<` and `>` are mistaken for is accounted for, whatever the tests
914    /// saw: it answers like the original for all of it and passes (a gap says so), or
915    /// it is run. It is never left to another mutant that answers alike: two mutants
916    /// that both change the way the code goes meet different values afterwards.
917    #[test]
918    fn the_operators_a_comparison_is_mistaken_for() {
919        let rels = [Rel::Less, Rel::Equal, Rel::Greater, Rel::Unordered];
920        for op in [CmpOp::Lt, CmpOp::Gt] {
921            for seen in 1u8..16 {
922                let mut obs = Obs::default();
923                let seen: Vec<Rel> = (0..4)
924                    .filter(|i| seen & (1 << i) != 0)
925                    .map(|i| rels[i])
926                    .collect();
927                for rel in &seen {
928                    obs.merge(&Obs::of_rel(*rel));
929                }
930                let plan = plan_cmp(op, &obs, None);
931                for other in op.mistaken_for() {
932                    let like_the_original = seen
933                        .iter()
934                        .all(|rel| other.eval_rel(*rel) == op.eval_rel(*rel));
935                    let what = format!("{op:?} as {other:?} with {seen:?}: {plan:?}");
936                    let run = plan
937                        .run
938                        .iter()
939                        .filter(|m| **m == Mutation::Op(*other))
940                        .count();
941                    if like_the_original {
942                        assert!(plan.gap.is_some(), "{what}");
943                        assert_eq!(run, 0, "{what}");
944                    } else {
945                        assert_eq!(run, 1, "{what}");
946                    }
947                }
948            }
949        }
950        // The other operators get nothing added.
951        for op in [CmpOp::Le, CmpOp::Ge, CmpOp::Eq, CmpOp::Ne] {
952            assert!(op.mistaken_for().is_empty());
953        }
954        // `>` for `<=` and `<` for `>=` are the negation unless the operands have no
955        // order, and only integers are known to always have one. For anything else the
956        // operator is run beside the negation wherever it answers otherwise than the
957        // original, whether or not the tests gave operands without an order.
958        let seen = |rels: &[Rel]| {
959            let mut obs = Obs::default();
960            for rel in rels {
961                obs.merge(&Obs::of_rel(*rel));
962            }
963            obs
964        };
965        for (op, reverse) in [(CmpOp::Ge, CmpOp::Lt), (CmpOp::Le, CmpOp::Gt)] {
966            let run = |rels: &[Rel]| plan_cmp(op, &seen(rels), None).run;
967            let reversed = |rels: &[Rel]| run(rels).contains(&Mutation::Op(reverse));
968            assert!(reversed(&[Rel::Unordered, Rel::Less]), "{op:?}");
969            assert!(reversed(&[Rel::Less, Rel::Greater]), "{op:?}");
970            assert!(reversed(&[Rel::Less, Rel::Equal, Rel::Greater]), "{op:?}");
971            // Where the operator answers like the original for all that was seen, it
972            // passes and is not run: only operands without an order, or only the side
973            // on which both are false.
974            assert_eq!(run(&[Rel::Unordered]), vec![Mutation::Negate], "{op:?}");
975            // Integers: the negation is the operator, at every distance.
976            for ds in [&[-1i128, 1][..], &[-2, 0, 3], &[0, 1]] {
977                let plan = plan_cmp(op, &obs_of(ds), None);
978                assert!(!plan.run.contains(&Mutation::Op(reverse)), "{op:?} {ds:?}");
979            }
980            for d in -3..=3 {
981                assert_eq!(eval_mutated_d(op, Mutation::Negate, d), reverse.eval_d(d));
982            }
983        }
984        // `!=` for `==` is the negation with and without an order.
985        let run = plan_cmp(CmpOp::Eq, &seen(&[Rel::Unordered, Rel::Equal]), None).run;
986        assert_eq!(run, vec![Mutation::Negate]);
987        // Seen above the bound only, `>=` and `>` in place of `<` answer alike, and
988        // both are run: the first step they change, they go different ways.
989        let plan = plan_cmp(CmpOp::Lt, &Obs::of_rel(Rel::Greater), None);
990        assert_eq!(plan.run, vec![Mutation::Negate, Mutation::Op(CmpOp::Gt)]);
991    }
992
993    #[test]
994    fn pinned_boundary_has_no_input_gap() {
995        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
996            let plan = plan_cmp(op, &obs_of(&[-1, 0, 1]), None);
997            assert_eq!(plan.gap, None, "{op:?}");
998            // With all three relations seen, no two operators answer alike.
999            let mut run = vec![Mutation::Shift(-1), Mutation::Shift(1), Mutation::Negate];
1000            run.extend(op.mistaken_for().iter().map(|other| Mutation::Op(*other)));
1001            assert_eq!(plan.run, run, "{op:?}");
1002        }
1003    }
1004
1005    #[test]
1006    fn unreached_site() {
1007        let plan = plan_cmp(CmpOp::Lt, &Obs::default(), None);
1008        assert_eq!(
1009            plan,
1010            CmpPlan {
1011                cannot_differ: false,
1012                gap: Some(InputGap::Unreached),
1013                run: vec![]
1014            }
1015        );
1016    }
1017
1018    #[test]
1019    fn one_sided_condition() {
1020        let plan = plan_cmp(CmpOp::Gt, &obs_of(&[3, 5]), None);
1021        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1022        // Always true: the negation, `==` and `<` are all false here, and each is run.
1023        assert_eq!(
1024            plan.run,
1025            vec![
1026                Mutation::Negate,
1027                Mutation::Op(CmpOp::Eq),
1028                Mutation::Op(CmpOp::Lt)
1029            ]
1030        );
1031    }
1032
1033    #[test]
1034    fn unsigned_compared_with_zero_is_not_reported() {
1035        // `x >= 0` for unsigned x: D ranges over 0..=MAX, the condition cannot be false.
1036        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((0, 255)));
1037        assert_eq!(plan.gap, None);
1038        assert!(plan.cannot_differ);
1039        assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 255))).cannot_differ);
1040        assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[-1, 4]), Some((-1, 255))).cannot_differ);
1041        // `x < 0` for unsigned x can never be true either.
1042        let plan = plan_cmp(CmpOp::Lt, &obs_of(&[0, 4]), Some((0, 255)));
1043        assert_eq!(plan.gap, None);
1044        // `x >= 1` for unsigned x written as `x > 0`, observed at 0 and 1: both neighbours
1045        // are real mutants (`x > -1` is `x >= 0`, which differs at 0).
1046        let plan = plan_cmp(CmpOp::Gt, &obs_of(&[0, 1]), Some((0, 255)));
1047        assert_eq!(plan.gap, None);
1048        // `x == 0` answers like the negation at 0 and 1, and is run all the same.
1049        assert_eq!(
1050            plan.run,
1051            vec![
1052                Mutation::Shift(-1),
1053                Mutation::Shift(1),
1054                Mutation::Negate,
1055                Mutation::Op(CmpOp::Eq),
1056                Mutation::Op(CmpOp::Lt)
1057            ]
1058        );
1059        // `x <= 0` for unsigned x, observed at 0 and 1: `x <= -1` is a real mutant too,
1060        // but `x < 0`-style thresholds below the domain are not counted twice.
1061        let plan = plan_cmp(CmpOp::Le, &obs_of(&[0, 1]), Some((0, 255)));
1062        assert_eq!(plan.gap, None);
1063    }
1064
1065    #[test]
1066    fn one_sided_condition_at_the_edge_of_the_type() {
1067        // Always true, and the only value that makes it false is the type's minimum.
1068        let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 10)));
1069        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1070        // ... or its maximum.
1071        let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 1)));
1072        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1073        let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 0)));
1074        assert_eq!(plan.gap, None);
1075        // Without values the types are unknown: report.
1076        let plan = plan_cmp(CmpOp::Ge, &Obs::of_rel(Rel::Greater), Some((0, 10)));
1077        assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1078    }
1079
1080    #[test]
1081    fn representative_is_the_nearest_survivor() {
1082        let boundary = |min_shift, max_shift| InputGap::Boundary {
1083            min_shift,
1084            max_shift,
1085            missing: vec![0],
1086        };
1087        assert_eq!(boundary(-3, 1).representative(), Some(Mutation::Shift(1)));
1088        assert_eq!(boundary(-1, 0).representative(), Some(Mutation::Shift(-1)));
1089        assert_eq!(boundary(0, 0).representative(), None);
1090        assert_eq!(InputGap::Unreached.representative(), None);
1091        assert_eq!(
1092            InputGap::OneSided { always: false }.representative(),
1093            Some(Mutation::Const(false))
1094        );
1095        assert_eq!(
1096            InputGap::EqualNeverObserved {
1097                flipped: CmpOp::Ge,
1098                float_gap: None
1099            }
1100            .representative(),
1101            Some(Mutation::Op(CmpOp::Ge))
1102        );
1103    }
1104
1105    /// `a && b` / `a || b` with the tool's mutants, as a reference evaluator. Returns the
1106    /// result and whether the right operand was evaluated.
1107    fn eval_logic(and: bool, m: Option<Mutation>, a: bool, b: bool) -> (bool, bool) {
1108        let decided = |and: bool| if and { !a } else { a };
1109        match m {
1110            None => {
1111                if decided(and) {
1112                    (a, false)
1113                } else {
1114                    (b, true)
1115                }
1116            }
1117            Some(Mutation::LogicSwap) => {
1118                if decided(!and) {
1119                    (a, false)
1120                } else {
1121                    (b, true)
1122                }
1123            }
1124            // The right operand is evaluated as in the original, but its value is ignored.
1125            Some(Mutation::LogicDropRhs) => (a, !decided(and)),
1126            Some(Mutation::LogicDropLhs) => (b, true),
1127            other => panic!("{other:?}"),
1128        }
1129    }
1130
1131    #[test]
1132    fn logic_plans_match_a_reference_evaluator() {
1133        let cases = [(false, false), (false, true), (true, false), (true, true)];
1134        for and in [true, false] {
1135            for mask in 0u32..16 {
1136                let seen: Vec<(bool, bool)> = cases
1137                    .iter()
1138                    .enumerate()
1139                    .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1140                    .collect();
1141                let mut obs = LogicObs::default();
1142                for (a, b) in &seen {
1143                    let (_, evaluated) = eval_logic(and, None, *a, *b);
1144                    obs.short |= !evaluated;
1145                    obs.rhs_true |= evaluated && *b;
1146                    obs.rhs_false |= evaluated && !*b;
1147                }
1148                let ctx = format!("and={and} seen={seen:?}");
1149                let differs = |m: Mutation| {
1150                    seen.iter().any(|(a, b)| {
1151                        eval_logic(and, None, *a, *b) != eval_logic(and, Some(m), *a, *b)
1152                    })
1153                };
1154                let plan = plan_logic(and, &obs);
1155                if seen.is_empty() {
1156                    assert_eq!(
1157                        plan,
1158                        LogicPlan {
1159                            gaps: vec![LogicGap::Unreached],
1160                            run: vec![]
1161                        }
1162                    );
1163                    continue;
1164                }
1165                for (m, gap) in [
1166                    (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1167                    (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1168                ] {
1169                    // Exact: a gap iff no observed case evaluates differently.
1170                    assert_eq!(plan.gaps.contains(&gap), !differs(m), "{gap:?} {ctx}");
1171                    assert_eq!(plan.run.contains(&m), differs(m), "{m:?} {ctx}");
1172                    assert_eq!(logic_infects(and, m, &obs), differs(m), "{m:?} {ctx}");
1173                }
1174                // The swap is always run: never claimed safe.
1175                assert!(plan.run.contains(&Mutation::LogicSwap), "{ctx}");
1176                assert!(logic_infects(and, Mutation::LogicSwap, &obs), "{ctx}");
1177            }
1178        }
1179        // A right operand that was started and gave no value (it panicked, or left the
1180        // function): the expression was executed, the operator swapped is run against
1181        // this test, and the other two change nothing in it.
1182        let started = LogicObs::from_bits(8);
1183        assert!(started.rhs_started && started.reached());
1184        for and in [true, false] {
1185            let plan = plan_logic(and, &started);
1186            assert_eq!(plan.run, vec![Mutation::LogicSwap]);
1187            assert_eq!(
1188                plan.gaps,
1189                vec![LogicGap::RhsNeverDecides, LogicGap::LhsNeverDecides]
1190            );
1191            assert!(logic_infects(and, Mutation::LogicSwap, &started));
1192            assert!(!logic_infects(and, Mutation::LogicDropRhs, &started));
1193            assert!(!logic_infects(and, Mutation::LogicDropLhs, &started));
1194        }
1195        let mut merged = LogicObs::from_bits(2);
1196        merged.merge(&started);
1197        assert_eq!(merged, LogicObs::from_bits(10));
1198        assert_eq!(
1199            LogicObs::from_bits(5),
1200            LogicObs {
1201                short: true,
1202                rhs_true: false,
1203                rhs_false: true,
1204                rhs_started: false,
1205            }
1206        );
1207        assert_eq!(
1208            LogicObs::from_bits(2),
1209            LogicObs {
1210                short: false,
1211                rhs_true: true,
1212                rhs_false: false,
1213                rhs_started: false,
1214            }
1215        );
1216    }
1217
1218    #[test]
1219    fn return_plans() {
1220        assert_eq!(
1221            plan_return(&ReturnObs::from_bits(0)),
1222            ReturnPlan {
1223                unreached: true,
1224                always: None,
1225                run: vec![]
1226            }
1227        );
1228        assert_eq!(
1229            plan_return(&ReturnObs::from_bits(1)),
1230            ReturnPlan {
1231                unreached: false,
1232                always: Some(true),
1233                run: vec![Mutation::Const(false)]
1234            }
1235        );
1236        assert_eq!(
1237            plan_return(&ReturnObs::from_bits(2)),
1238            ReturnPlan {
1239                unreached: false,
1240                always: Some(false),
1241                run: vec![Mutation::Const(true)]
1242            }
1243        );
1244        assert_eq!(
1245            plan_return(&ReturnObs::from_bits(3)),
1246            ReturnPlan {
1247                unreached: false,
1248                always: None,
1249                run: vec![Mutation::Const(true), Mutation::Const(false)]
1250            }
1251        );
1252        // Forcing the value a test already sees changes nothing for that test.
1253        for bits in 0u8..4 {
1254            let obs = ReturnObs::from_bits(bits);
1255            assert_eq!(obs.infected_by_const(true), obs.saw_false);
1256            assert_eq!(obs.infected_by_const(false), obs.saw_true);
1257            assert_eq!(obs.reached(), bits != 0);
1258            let plan = plan_return(&obs);
1259            for m in &plan.run {
1260                let Mutation::Const(value) = m else { panic!() };
1261                assert!(
1262                    obs.infected_by_const(*value),
1263                    "a run mutant must change some test"
1264                );
1265            }
1266            if let Some(always) = plan.always {
1267                assert!(
1268                    !obs.infected_by_const(always),
1269                    "the survivor changes no test"
1270                );
1271            }
1272        }
1273        let mut merged = ReturnObs::from_bits(1);
1274        merged.merge(&ReturnObs::from_bits(2));
1275        assert_eq!(
1276            merged,
1277            ReturnObs {
1278                saw_true: true,
1279                saw_false: true
1280            }
1281        );
1282    }
1283
1284    #[test]
1285    fn logic_constant_value() {
1286        let cases = [(false, false), (false, true), (true, false), (true, true)];
1287        for and in [true, false] {
1288            for mask in 0u32..16 {
1289                let seen: Vec<(bool, bool)> = cases
1290                    .iter()
1291                    .enumerate()
1292                    .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1293                    .collect();
1294                let mut obs = LogicObs::default();
1295                let mut values = std::collections::BTreeSet::new();
1296                for (a, b) in &seen {
1297                    let (value, evaluated) = eval_logic(and, None, *a, *b);
1298                    values.insert(value);
1299                    obs.short |= !evaluated;
1300                    obs.rhs_true |= evaluated && *b;
1301                    obs.rhs_false |= evaluated && !*b;
1302                }
1303                let expected = if values.len() == 1 {
1304                    values.first().copied()
1305                } else {
1306                    None
1307                };
1308                assert_eq!(obs.constant_value(and), expected, "and={and} seen={seen:?}");
1309            }
1310        }
1311    }
1312
1313    #[test]
1314    fn option_return_plans() {
1315        let plan = |bits| plan_option_return(&ReturnObs::from_bits(bits));
1316        assert_eq!(
1317            plan(0),
1318            ReturnPlan {
1319                unreached: true,
1320                always: None,
1321                run: vec![]
1322            }
1323        );
1324        // Only `None` was ever returned: "always None" changes nothing.
1325        assert_eq!(
1326            plan(2),
1327            ReturnPlan {
1328                unreached: false,
1329                always: Some(false),
1330                run: vec![]
1331            }
1332        );
1333        // `Some` was returned: replacing it by `None` has to be run, against those tests.
1334        for bits in [1, 3] {
1335            assert_eq!(
1336                plan(bits),
1337                ReturnPlan {
1338                    unreached: false,
1339                    always: None,
1340                    run: vec![Mutation::Const(false)]
1341                }
1342            );
1343            assert!(ReturnObs::from_bits(bits).infected_by_const(false));
1344        }
1345        assert!(!ReturnObs::from_bits(2).infected_by_const(false));
1346    }
1347
1348    #[test]
1349    fn arithmetic_plans() {
1350        for bits in 0u8..8 {
1351            let obs = ArithObs::from_bits(bits);
1352            let expected = if bits & 2 != 0 {
1353                ArithPlan::Run
1354            } else if bits & 1 != 0 {
1355                ArithPlan::NeverDiffers
1356            } else if bits & 4 != 0 {
1357                ArithPlan::Opaque
1358            } else {
1359                ArithPlan::Unreached
1360            };
1361            assert_eq!(plan_arith(&obs), expected, "bits={bits}");
1362        }
1363        let mut merged = ArithObs::from_bits(1);
1364        merged.merge(&ArithObs::from_bits(4));
1365        assert_eq!(
1366            merged,
1367            ArithObs {
1368                same: true,
1369                differs: false,
1370                opaque: true,
1371                ..Default::default()
1372            }
1373        );
1374    }
1375
1376    #[test]
1377    fn float_comparison_without_equal_operands() {
1378        // `celsius > 30.5` with 10.0 and 40.0: differences -20.5 and 9.5.
1379        let mut obs = Obs::of_f(-20.5);
1380        obs.merge(&Obs::of_f(9.5));
1381        let plan = plan_cmp(CmpOp::Gt, &obs, None);
1382        let gap = plan.gap.expect("a gap");
1383        assert_eq!(
1384            gap,
1385            InputGap::EqualNeverObserved {
1386                flipped: CmpOp::Ge,
1387                float_gap: Some((-20.5, 9.5))
1388            }
1389        );
1390        assert_eq!(
1391            gap.survivors(),
1392            vec![
1393                Mutation::Op(CmpOp::Ge),
1394                Mutation::ShiftF(4.75),
1395                Mutation::ShiftF(-10.25)
1396            ]
1397        );
1398        // Shifts inside the unobserved gap infect nothing; outside it, or once equality
1399        // has been observed, they do.
1400        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1401            assert!(!infects(op, Mutation::ShiftF(4.75), &obs));
1402            assert!(!infects(op, Mutation::ShiftF(-10.25), &obs));
1403            assert!(infects(op, Mutation::ShiftF(9.5), &obs));
1404            assert!(infects(op, Mutation::ShiftF(-20.5), &obs));
1405        }
1406        let mut with_eq = obs;
1407        with_eq.merge(&Obs::of_f(0.0));
1408        assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &with_eq));
1409        assert_eq!(plan_cmp(CmpOp::Gt, &with_eq, None).gap, None);
1410        // Mixed with a non-float observation there is no float gap to speak of.
1411        let mut mixed = obs;
1412        mixed.merge(&Obs::of_rel(Rel::Less));
1413        assert_eq!(mixed.float_gap(), None);
1414        assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &mixed));
1415        assert_eq!(Obs::of_d(3).float_gap(), None);
1416    }
1417
1418    #[test]
1419    fn survivors_are_listed_nearest_first() {
1420        let boundary = |min_shift, max_shift| InputGap::Boundary {
1421            min_shift,
1422            max_shift,
1423            missing: vec![0],
1424        };
1425        assert_eq!(
1426            boundary(-9, 9).survivors(),
1427            vec![Mutation::Shift(1), Mutation::Shift(-1), Mutation::Shift(2)]
1428        );
1429        assert_eq!(boundary(-1, 0).survivors(), vec![Mutation::Shift(-1)]);
1430        assert_eq!(
1431            boundary(0, 2).survivors(),
1432            vec![Mutation::Shift(1), Mutation::Shift(2)]
1433        );
1434        assert_eq!(
1435            InputGap::OneSided { always: true }.survivors(),
1436            vec![Mutation::Const(true)]
1437        );
1438        assert_eq!(InputGap::Unreached.survivors(), vec![]);
1439    }
1440
1441    #[test]
1442    fn single_observation_summaries() {
1443        let bits = |o: Obs| (o.lt, o.eq, o.gt, o.un);
1444        assert_eq!(bits(Obs::of_f(-0.5)), (true, false, false, false));
1445        assert_eq!(bits(Obs::of_f(0.0)), (false, true, false, false));
1446        assert_eq!(bits(Obs::of_f(0.5)), (false, false, true, false));
1447        assert_eq!(
1448            (Obs::of_f(-0.5).f_max_neg, Obs::of_f(-0.5).f_min_pos),
1449            (Some(-0.5), None)
1450        );
1451        assert_eq!(
1452            (Obs::of_f(0.5).f_max_neg, Obs::of_f(0.5).f_min_pos),
1453            (None, Some(0.5))
1454        );
1455        assert_eq!(
1456            (Obs::of_f(0.0).f_max_neg, Obs::of_f(0.0).f_min_pos),
1457            (None, None)
1458        );
1459        assert!(Obs::of_f(1.0).unvalued && !Obs::of_f(1.0).unfloat);
1460        assert!(Obs::of_d(1).unfloat && !Obs::of_d(1).unvalued);
1461
1462        // Reached through any one relation, including "unordered" alone.
1463        assert!(Obs::of_rel(Rel::Unordered).reached());
1464        assert!(!Obs::default().reached());
1465        // An unreached site has no values, even though nothing contradicts having them.
1466        assert!(!Obs::default().valued());
1467        assert!(Obs::of_d(0).valued());
1468        assert!(!Obs::of_rel(Rel::Equal).valued());
1469
1470        // A NaN comparison among floats spoils the float gap.
1471        let mut nan = Obs::of_f(-1.0);
1472        nan.merge(&Obs::of_f(1.0));
1473        assert_eq!(nan.float_gap(), Some((-1.0, 1.0)));
1474        nan.un = true;
1475        assert_eq!(nan.float_gap(), None);
1476        assert_eq!(Obs::default().float_gap(), None);
1477        assert_eq!(Obs::of_f(-1.0).float_gap(), None, "one side only");
1478    }
1479
1480    #[test]
1481    fn interval_queries_look_at_the_right_side_of_zero() {
1482        // Only positives were observed: an interval of negatives is empty, and vice versa.
1483        assert!(!obs_of(&[2]).saw_any_in(-3, -1));
1484        assert!(!obs_of(&[-2]).saw_any_in(1, 3));
1485        assert!(obs_of(&[-2]).saw_any_in(-3, -1));
1486        assert!(obs_of(&[2]).saw_any_in(1, 3));
1487        assert!(!obs_of(&[-4]).saw_any_in(-3, 0));
1488        assert!(!obs_of(&[4]).saw_any_in(0, 3));
1489        // A stray value on the far side must not leak into the answer.
1490        let mut odd = obs_of(&[3]);
1491        odd.max_neg = Some(5);
1492        assert!(!odd.saw_any_in(0, 2));
1493        let mut odd = obs_of(&[-3]);
1494        odd.min_pos = Some(-5);
1495        assert!(!odd.saw_any_in(-2, 0));
1496    }
1497
1498    #[test]
1499    fn empty_interval_has_no_observations() {
1500        assert!(!obs_of(&[-1, 0, 1]).saw_any_in(1, 0));
1501        assert!(obs_of(&[0]).saw_any_in(0, 0));
1502    }
1503
1504    #[test]
1505    fn unvalued_ordering_without_equal_operands() {
1506        let mut obs = Obs::of_rel(Rel::Less);
1507        obs.merge(&Obs::of_rel(Rel::Greater));
1508        let plan = plan_cmp(CmpOp::Lt, &obs, None);
1509        assert_eq!(
1510            plan.gap,
1511            Some(InputGap::EqualNeverObserved {
1512                flipped: CmpOp::Le,
1513                float_gap: None
1514            })
1515        );
1516        // Without equal operands `>` answers like the negation; it is run as well.
1517        assert_eq!(
1518            plan.run,
1519            vec![
1520                Mutation::Negate,
1521                Mutation::Op(CmpOp::Eq),
1522                Mutation::Op(CmpOp::Gt)
1523            ]
1524        );
1525
1526        obs.merge(&Obs::of_rel(Rel::Equal));
1527        let plan = plan_cmp(CmpOp::Lt, &obs, None);
1528        assert_eq!(plan.gap, None);
1529        assert_eq!(
1530            plan.run,
1531            vec![
1532                Mutation::Op(CmpOp::Le),
1533                Mutation::Negate,
1534                Mutation::Op(CmpOp::Eq),
1535                Mutation::Op(CmpOp::Gt)
1536            ]
1537        );
1538    }
1539
1540    #[test]
1541    fn equality_with_both_outcomes() {
1542        let plan = plan_cmp(CmpOp::Eq, &obs_of(&[0, 7]), None);
1543        assert_eq!(
1544            plan,
1545            CmpPlan {
1546                cannot_differ: false,
1547                gap: None,
1548                run: vec![Mutation::Negate]
1549            }
1550        );
1551    }
1552
1553    #[test]
1554    fn unordered_counts_as_not_equal() {
1555        let obs = Obs::of_rel(Rel::Unordered);
1556        assert!(infects(CmpOp::Ne, Mutation::Const(false), &obs));
1557        assert!(!infects(CmpOp::Lt, Mutation::Op(CmpOp::Ge), &obs));
1558        assert!(infects(CmpOp::Lt, Mutation::Op(CmpOp::Ne), &obs));
1559    }
1560
1561    #[test]
1562    fn merge_is_a_semilattice() {
1563        let samples: Vec<Obs> = [-3, -1, 0, 1, 4]
1564            .into_iter()
1565            .map(Obs::of_d)
1566            .chain([
1567                Obs::of_rel(Rel::Unordered),
1568                Obs::of_rel(Rel::Less),
1569                Obs::default(),
1570            ])
1571            .collect();
1572        for a in &samples {
1573            let mut aa = *a;
1574            aa.merge(a);
1575            assert_eq!(aa, *a, "idempotent");
1576            for b in &samples {
1577                let (mut ab, mut ba) = (*a, *b);
1578                ab.merge(b);
1579                ba.merge(a);
1580                assert_eq!(ab, ba, "commutative");
1581                for c in &samples {
1582                    let mut ab_c = ab;
1583                    ab_c.merge(c);
1584                    let mut bc = *b;
1585                    bc.merge(c);
1586                    let mut a_bc = *a;
1587                    a_bc.merge(&bc);
1588                    assert_eq!(ab_c, a_bc, "associative");
1589                }
1590            }
1591        }
1592    }
1593
1594    #[test]
1595    fn mutation_wire_format() {
1596        assert_eq!(Mutation::Const(true).encode(), "c1");
1597        assert_eq!(Mutation::Const(false).encode(), "c0");
1598        assert_eq!(Mutation::Negate.encode(), "neg");
1599        assert_eq!(Mutation::Op(CmpOp::Ge).encode(), "op3");
1600        assert_eq!(Mutation::Shift(-2).encode(), "sh-2");
1601        assert_eq!(Mutation::Delete.encode(), "del");
1602        assert_eq!(Mutation::ShiftF(4.75).encode(), "shf4.75");
1603        assert_eq!(Mutation::ShiftF(-10.0).encode(), "shf-10.0");
1604        assert_eq!(Mutation::LogicSwap.encode(), "lsw");
1605        assert_eq!(Mutation::LogicDropRhs.encode(), "ldr");
1606        assert_eq!(Mutation::LogicDropLhs.encode(), "ldl");
1607        assert_eq!(Mutation::ArithSwap.encode(), "asw");
1608        assert_eq!(Mutation::DropNot.encode(), "unn");
1609        assert_eq!(Mutation::RangeEnd.encode(), "rng");
1610        assert_eq!(Mutation::MinMax.encode(), "mmx");
1611    }
1612
1613    fn candidate_mutations(op: CmpOp) -> Vec<Mutation> {
1614        let mut ms = vec![
1615            Mutation::Const(true),
1616            Mutation::Const(false),
1617            Mutation::Negate,
1618        ];
1619        ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
1620        if op.is_ordering() {
1621            ms.extend((-5..=5).filter(|s| *s != 0).map(Mutation::Shift));
1622        }
1623        ms
1624    }
1625
1626    /// Checks a plan against concrete observations by brute force.
1627    fn check_plan(op: CmpOp, ds: &[i128], domain: Option<(i128, i128)>) {
1628        let obs = obs_of(ds);
1629        let ctx = format!("{op:?} ds={ds:?} domain={domain:?}");
1630        let (dom_lo, dom_hi) = domain.unwrap_or((-50, 50));
1631        let differs_somewhere =
1632            |m: Mutation| (dom_lo..=dom_hi).any(|d| op.eval_d(d) != eval_mutated_d(op, m, d));
1633
1634        for m in candidate_mutations(op) {
1635            assert_eq!(
1636                infects(op, m, &obs),
1637                brute_infects(op, m, ds),
1638                "infects {m:?} {ctx}"
1639            );
1640        }
1641
1642        let plan = plan_cmp(op, &obs, domain);
1643        for m in &plan.run {
1644            assert!(
1645                brute_infects(op, *m, ds),
1646                "run {m:?} must be infected: {ctx}"
1647            );
1648            assert!(differs_somewhere(*m), "run {m:?} is equivalent: {ctx}");
1649        }
1650        match &plan.gap {
1651            None => {}
1652            Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
1653            Some(InputGap::OneSided { always }) => {
1654                assert!(ds.iter().all(|d| op.eval_d(*d) == *always), "{ctx}");
1655                assert!(differs_somewhere(Mutation::Const(*always)), "{ctx}");
1656            }
1657            Some(InputGap::Boundary {
1658                min_shift,
1659                max_shift,
1660                missing,
1661            }) => {
1662                assert!(*min_shift <= 0 && 0 <= *max_shift, "{ctx}");
1663                for s in (*min_shift..=*max_shift).filter(|s| *s != 0) {
1664                    let m = Mutation::Shift(s);
1665                    assert!(
1666                        !brute_infects(op, m, ds),
1667                        "survivor {m:?} is infected: {ctx}"
1668                    );
1669                    assert!(differs_somewhere(m), "survivor {m:?} is equivalent: {ctx}");
1670                }
1671                if domain.is_none() {
1672                    // Exactness: one step outside the range is caught by some observation.
1673                    for s in [min_shift - 1, max_shift + 1] {
1674                        assert!(
1675                            brute_infects(op, Mutation::Shift(s), ds),
1676                            "range not maximal: {ctx}"
1677                        );
1678                    }
1679                }
1680                assert!(!missing.is_empty(), "{ctx}");
1681                for w in missing {
1682                    assert!(!ds.contains(w), "missing value {w} was observed: {ctx}");
1683                    assert!(
1684                        dom_lo <= *w && *w <= dom_hi,
1685                        "missing value {w} out of domain: {ctx}"
1686                    );
1687                    let s = if op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(1), *w) {
1688                        1
1689                    } else {
1690                        -1
1691                    };
1692                    assert!(
1693                        op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(s), *w),
1694                        "missing value {w} separates nothing: {ctx}"
1695                    );
1696                    assert!(*min_shift <= s && s <= *max_shift, "{ctx}");
1697                }
1698            }
1699            Some(InputGap::EqualNeverObserved { .. }) => panic!("valued site: {ctx}"),
1700        }
1701        if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
1702            assert!(
1703                !brute_infects(op, m, ds),
1704                "representative {m:?} is infected: {ctx}"
1705            );
1706        }
1707
1708        // Completeness for the off-by-one mutants: each is a survivor, is run, or is equivalent.
1709        if op.is_ordering() && ds.iter().any(|d| op.eval_d(*d)) && ds.iter().any(|d| !op.eval_d(*d))
1710        {
1711            for s in [-1, 1] {
1712                let m = Mutation::Shift(s);
1713                let survivor = matches!(&plan.gap, Some(InputGap::Boundary { min_shift, max_shift, .. })
1714                    if *min_shift <= s && s <= *max_shift);
1715                let ran = plan.run.contains(&m);
1716                assert!(
1717                    survivor ^ ran || !differs_somewhere(m),
1718                    "Shift({s}) unaccounted for: survivor={survivor} ran={ran} {ctx}"
1719                );
1720            }
1721        }
1722    }
1723
1724    #[test]
1725    fn exhaustive_small_observation_sets() {
1726        let universe: Vec<i128> = (-3..=3).collect();
1727        for op in CmpOp::ALL {
1728            for mask in 0u32..(1 << universe.len()) {
1729                let ds: Vec<i128> = universe
1730                    .iter()
1731                    .enumerate()
1732                    .filter_map(|(i, d)| (mask & (1 << i) != 0).then_some(*d))
1733                    .collect();
1734                check_plan(op, &ds, None);
1735                // Domains that contain every observation.
1736                for (lo, hi) in [(0, 10), (-10, 0), (-2, 2), (1, 9), (-9, -1)] {
1737                    if ds.iter().all(|d| lo <= *d && *d <= hi) {
1738                        check_plan(op, &ds, Some((lo, hi)));
1739                    }
1740                }
1741            }
1742        }
1743    }
1744
1745    /// Rows generated by `pict formal/pict/planner.pict /o:3 /e:formal/pict/planner.seed.tsv`.
1746    #[test]
1747    fn pict_table() {
1748        let table = include_str!("../tests/data/planner.pict.tsv");
1749        let mut rows = 0;
1750        for line in table.lines().skip(1) {
1751            let cols: Vec<&str> = line.split('\t').collect();
1752            let [op, below, equal, above, valued, literal, domain] = cols[..] else {
1753                panic!("bad row: {line}");
1754            };
1755            let op = match op {
1756                "lt" => CmpOp::Lt,
1757                "le" => CmpOp::Le,
1758                "gt" => CmpOp::Gt,
1759                "ge" => CmpOp::Ge,
1760                "eq" => CmpOp::Eq,
1761                "ne" => CmpOp::Ne,
1762                other => panic!("op {other}"),
1763            };
1764            let mut ds: Vec<i128> = vec![];
1765            match below {
1766                "none" => {}
1767                "adjacent" => ds.extend([-1, -4]),
1768                "far" => ds.extend([-3, -6]),
1769                other => panic!("below {other}"),
1770            }
1771            if equal == "yes" {
1772                ds.push(0);
1773            }
1774            match above {
1775                "none" => {}
1776                "adjacent" => ds.extend([1, 5]),
1777                "far" => ds.extend([3, 7]),
1778                other => panic!("above {other}"),
1779            }
1780            rows += 1;
1781            if valued == "no" {
1782                let mut obs = Obs::default();
1783                for d in &ds {
1784                    obs.merge(&Obs::of_rel(rel_of(*d)));
1785                }
1786                check_unvalued(op, &obs, &ds, line);
1787                continue;
1788            }
1789            // D = lhs - rhs. With the literal on the right, a tight lower bound on the other
1790            // operand is a lower bound on D; with the literal on the left it is an upper bound.
1791            let domain = match (literal, domain) {
1792                ("none", _) => None,
1793                (_, "wide") => Some((-40, 40)),
1794                ("rhs", "tight_low") | ("lhs", "tight_high") => Some((0, 40)),
1795                ("rhs", "tight_high") | ("lhs", "tight_low") => Some((-40, 0)),
1796                other => panic!("domain {other:?}"),
1797            };
1798            check_plan(op, &ds, domain);
1799        }
1800        assert_eq!(rows, table.lines().count() - 1);
1801        assert!(rows > 50, "the PICT table looks truncated: {rows} rows");
1802    }
1803
1804    fn check_unvalued(op: CmpOp, obs: &Obs, ds: &[i128], ctx: &str) {
1805        let plan = plan_cmp(op, obs, None);
1806        for m in [
1807            Mutation::Const(true),
1808            Mutation::Const(false),
1809            Mutation::Negate,
1810        ]
1811        .into_iter()
1812        .chain(CmpOp::ALL.into_iter().map(Mutation::Op))
1813        {
1814            assert_eq!(
1815                infects(op, m, obs),
1816                brute_infects(op, m, ds),
1817                "infects {m:?} {ctx}"
1818            );
1819        }
1820        for m in &plan.run {
1821            assert!(
1822                brute_infects(op, *m, ds),
1823                "run {m:?} must be infected: {ctx}"
1824            );
1825        }
1826        if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
1827            assert!(
1828                !brute_infects(op, m, ds),
1829                "representative {m:?} is infected: {ctx}"
1830            );
1831        }
1832        match &plan.gap {
1833            Some(InputGap::Boundary { .. }) => panic!("unvalued site cannot shift: {ctx}"),
1834            Some(InputGap::EqualNeverObserved { flipped, .. }) => {
1835                assert!(!ds.contains(&0), "{ctx}");
1836                assert_eq!(op.flip_eq(), Some(*flipped), "{ctx}");
1837            }
1838            Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
1839            _ => {}
1840        }
1841        // A shift on a reached site without values is never claimed to be safe.
1842        if op.is_ordering() && obs.reached() {
1843            assert!(infects(op, Mutation::Shift(1), obs), "{ctx}");
1844        }
1845    }
1846}