1use serde::Serialize;
10
11#[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 #[inline]
74 pub fn truth_mask(self) -> u8 {
75 match self {
76 CmpOp::Lt => 0b0001,
77 CmpOp::Le => 0b0011,
78 CmpOp::Gt => 0b0100,
79 CmpOp::Ge => 0b0110,
80 CmpOp::Eq => 0b0010,
81 CmpOp::Ne => 0b1101,
82 }
83 }
84
85 pub fn eval_rel(self, rel: Rel) -> bool {
86 let bit = match rel {
87 Rel::Less => 1,
88 Rel::Equal => 2,
89 Rel::Greater => 4,
90 Rel::Unordered => 8,
91 };
92 self.truth_mask() & bit != 0
93 }
94
95 pub fn eval_d(self, d: i128) -> bool {
97 self.eval_rel(match d {
98 d if d < 0 => Rel::Less,
99 0 => Rel::Equal,
100 _ => Rel::Greater,
101 })
102 }
103
104 pub fn mistaken_for(self) -> &'static [CmpOp] {
106 match self {
107 CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt],
108 CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt],
109 _ => &[],
110 }
111 }
112
113 pub fn negated(self) -> CmpOp {
114 match self {
115 CmpOp::Lt => CmpOp::Ge,
116 CmpOp::Le => CmpOp::Gt,
117 CmpOp::Gt => CmpOp::Le,
118 CmpOp::Ge => CmpOp::Lt,
119 CmpOp::Eq => CmpOp::Ne,
120 CmpOp::Ne => CmpOp::Eq,
121 }
122 }
123
124 pub fn flip_eq(self) -> Option<CmpOp> {
126 match self {
127 CmpOp::Lt => Some(CmpOp::Le),
128 CmpOp::Le => Some(CmpOp::Lt),
129 CmpOp::Gt => Some(CmpOp::Ge),
130 CmpOp::Ge => Some(CmpOp::Gt),
131 CmpOp::Eq | CmpOp::Ne => None,
132 }
133 }
134
135 fn threshold(self) -> Option<(bool, i128)> {
138 match self {
139 CmpOp::Ge => Some((true, 0)),
140 CmpOp::Gt => Some((true, 1)),
141 CmpOp::Le => Some((false, 0)),
142 CmpOp::Lt => Some((false, -1)),
143 CmpOp::Eq | CmpOp::Ne => None,
144 }
145 }
146}
147
148#[derive(Clone, Copy, PartialEq, Debug, Default)]
151pub struct Obs {
152 pub lt: bool,
153 pub eq: bool,
154 pub gt: bool,
155 pub un: bool,
156 pub unvalued: bool,
158 pub max_neg: Option<i128>,
160 pub min_pos: Option<i128>,
162 pub unfloat: bool,
164 pub f_max_neg: Option<f64>,
166 pub f_min_pos: Option<f64>,
167}
168
169impl Obs {
170 #[inline]
172 pub fn rels_mask(&self) -> u8 {
173 (self.lt as u8) | ((self.eq as u8) << 1) | ((self.gt as u8) << 2) | ((self.un as u8) << 3)
174 }
175
176 pub fn reached(&self) -> bool {
177 self.rels_mask() != 0
178 }
179
180 pub fn valued(&self) -> bool {
181 self.reached() && !self.unvalued
182 }
183
184 pub fn merge(&mut self, other: &Obs) {
185 self.lt |= other.lt;
186 self.eq |= other.eq;
187 self.gt |= other.gt;
188 self.un |= other.un;
189 self.unvalued |= other.unvalued;
190 self.max_neg = match (self.max_neg, other.max_neg) {
191 (Some(a), Some(b)) => Some(a.max(b)),
192 (a, b) => a.or(b),
193 };
194 self.min_pos = match (self.min_pos, other.min_pos) {
195 (Some(a), Some(b)) => Some(a.min(b)),
196 (a, b) => a.or(b),
197 };
198 self.unfloat |= other.unfloat;
199 self.f_max_neg = match (self.f_max_neg, other.f_max_neg) {
200 (Some(a), Some(b)) => Some(a.max(b)),
201 (a, b) => a.or(b),
202 };
203 self.f_min_pos = match (self.f_min_pos, other.f_min_pos) {
204 (Some(a), Some(b)) => Some(a.min(b)),
205 (a, b) => a.or(b),
206 };
207 }
208
209 pub fn of_d(d: i128) -> Obs {
211 Obs {
212 lt: d < 0,
213 eq: d == 0,
214 gt: d > 0,
215 max_neg: (d < 0).then_some(d),
216 min_pos: (d > 0).then_some(d),
217 unfloat: true,
218 ..Obs::default()
219 }
220 }
221
222 pub fn of_rel(rel: Rel) -> Obs {
224 Obs {
225 lt: rel == Rel::Less,
226 eq: rel == Rel::Equal,
227 gt: rel == Rel::Greater,
228 un: rel == Rel::Unordered,
229 unvalued: true,
230 unfloat: true,
231 ..Obs::default()
232 }
233 }
234
235 pub fn of_f(d: f64) -> Obs {
237 Obs {
238 lt: d < 0.0,
239 eq: d == 0.0,
240 gt: d > 0.0,
241 unvalued: true,
242 f_max_neg: (d < 0.0).then_some(d),
243 f_min_pos: (d > 0.0).then_some(d),
244 ..Obs::default()
245 }
246 }
247
248 pub fn float_gap(&self) -> Option<(f64, f64)> {
251 if self.unfloat || self.un {
253 return None;
254 }
255 Some((self.f_max_neg?, self.f_min_pos?))
256 }
257
258 fn saw(&self, d: i128) -> bool {
260 match d {
261 0 => self.eq,
262 -1 => self.max_neg == Some(-1),
263 1 => self.min_pos == Some(1),
264 _ => unreachable!("only the values next to zero can be answered from the summary"),
265 }
266 }
267
268 fn max_le(&self, x: i128) -> Option<i128> {
270 debug_assert!(x == -1 || x == 0);
271 if x == 0 && self.eq {
272 Some(0)
273 } else {
274 self.max_neg
275 }
276 }
277
278 fn min_ge(&self, x: i128) -> Option<i128> {
280 debug_assert!(x == 0 || x == 1);
281 if x == 0 && self.eq {
282 Some(0)
283 } else {
284 self.min_pos
285 }
286 }
287
288 fn saw_any_in(&self, lo: i128, hi: i128) -> bool {
291 if lo > hi {
292 return false;
293 }
294 debug_assert!(
295 lo <= 1 && hi >= -1,
296 "interval {lo}..={hi} is not anchored at zero"
297 );
298 let zero = self.eq && lo <= 0 && 0 <= hi;
299 let neg = lo <= -1 && self.max_neg.is_some_and(|m| m >= lo);
300 let pos = hi >= 1 && self.min_pos.is_some_and(|p| p <= hi);
301 zero || neg || pos
302 }
303}
304
305#[derive(Clone, Copy, PartialEq, Debug, Serialize)]
306#[serde(rename_all = "snake_case")]
307pub enum Mutation {
308 Const(bool),
310 Negate,
312 Op(CmpOp),
314 Shift(i128),
316 ShiftF(f64),
318 Delete,
320 LogicSwap,
322 LogicDropRhs,
324 LogicDropLhs,
326 ArithSwap,
328 ArithSwap2,
331 DropNot,
333 RangeEnd,
335 MinMax,
337 OtherEnd,
339 StrContains,
341 StrReplaceMultiplicity,
343 ClampDropLower,
345 ClampDropUpper,
347 RoundAlt1,
349 RoundAlt2,
351 QuantifierSwap,
353 SaturatingSwap,
355 TrimAlt1,
357 TrimAlt2,
359 StrExactEq,
361 DropAbs,
363 IterLimitDrop,
365 EndianSwap,
367 BitCountSwap,
369 LoopCtrlSwap,
371 DropLiteralElem(u8),
373}
374
375impl Mutation {
376 pub fn encode(&self) -> String {
378 match self {
379 Mutation::Const(c) => format!("c{}", *c as u8),
380 Mutation::Negate => "neg".to_string(),
381 Mutation::Op(op) => format!("op{}", op.code()),
382 Mutation::Shift(d) => format!("sh{d}"),
383 Mutation::ShiftF(d) => format!("shf{d:?}"),
384 Mutation::Delete => "del".to_string(),
385 Mutation::LogicSwap => "lsw".to_string(),
386 Mutation::LogicDropRhs => "ldr".to_string(),
387 Mutation::LogicDropLhs => "ldl".to_string(),
388 Mutation::ArithSwap => "asw".to_string(),
389 Mutation::ArithSwap2 => "as2".to_string(),
390 Mutation::DropNot => "unn".to_string(),
391 Mutation::RangeEnd => "rng".to_string(),
392 Mutation::MinMax => "mmx".to_string(),
393 Mutation::OtherEnd => "end".to_string(),
394 Mutation::StrContains => "stc".to_string(),
395 Mutation::StrReplaceMultiplicity => "srp".to_string(),
396 Mutation::ClampDropLower => "cll".to_string(),
397 Mutation::ClampDropUpper => "clu".to_string(),
398 Mutation::RoundAlt1 => "rd1".to_string(),
399 Mutation::RoundAlt2 => "rd2".to_string(),
400 Mutation::QuantifierSwap => "qsw".to_string(),
401 Mutation::SaturatingSwap => "sat".to_string(),
402 Mutation::TrimAlt1 => "tr1".to_string(),
403 Mutation::TrimAlt2 => "tr2".to_string(),
404 Mutation::StrExactEq => "seq".to_string(),
405 Mutation::DropAbs => "abs".to_string(),
406 Mutation::IterLimitDrop => "ilp".to_string(),
407 Mutation::EndianSwap => "edn".to_string(),
408 Mutation::BitCountSwap => "btc".to_string(),
409 Mutation::LoopCtrlSwap => "lpc".to_string(),
410 Mutation::DropLiteralElem(idx) => format!("dle{idx}"),
411 }
412 }
413}
414
415pub fn eval_mutated_d(op: CmpOp, m: Mutation, d: i128) -> bool {
417 match m {
418 Mutation::Const(c) => c,
419 Mutation::Negate => !op.eval_d(d),
420 Mutation::Op(op2) => op2.eval_d(d),
421 Mutation::Shift(s) => op.eval_d(d - s),
422 _ => op.eval_d(d),
423 }
424}
425
426pub fn infects(op: CmpOp, m: Mutation, obs: &Obs) -> bool {
429 match m {
430 Mutation::Const(c) => {
431 let mask = if c {
432 !op.truth_mask() & 0x0f
433 } else {
434 op.truth_mask()
435 };
436 obs.rels_mask() & mask != 0
437 }
438 Mutation::Op(op2) => obs.rels_mask() & (op.truth_mask() ^ op2.truth_mask()) != 0,
439 Mutation::Shift(s) => {
440 let Some((lo, hi)) = shift_diff(op, s) else {
441 return false;
442 };
443 if !obs.valued() {
444 return obs.reached();
446 }
447 obs.saw_any_in(lo, hi)
448 }
449 Mutation::ShiftF(s) => match obs.float_gap() {
451 Some((lo, hi)) => !(lo < s && s < hi) || obs.eq,
452 None => obs.reached(),
453 },
454 _ => obs.reached(),
456 }
457}
458
459pub fn domain_equivalent(
463 op: CmpOp,
464 m1: Mutation,
465 m2: Mutation,
466 domain: (i128, i128),
467 zero_unreachable: bool,
468) -> bool {
469 let (lo, hi) = domain;
470 let supported = |m: Mutation| match m {
471 Mutation::Const(_) | Mutation::Negate | Mutation::Op(_) => true,
472 Mutation::Shift(-1) => hi < i128::MAX,
474 Mutation::Shift(1) => lo > i128::MIN,
475 _ => false,
476 };
477 if lo > hi || !supported(m1) || !supported(m2) {
478 return false;
479 }
480 let agrees = |d: i128| eval_mutated_d(op, m1, d) == eval_mutated_d(op, m2, d);
481 if lo <= -2 && !agrees(-2) {
482 return false;
483 }
484 if 2 <= hi && !agrees(2) {
485 return false;
486 }
487 for d in [-1_i128, 0, 1] {
488 if d == 0 && zero_unreachable {
489 continue;
490 }
491 if lo <= d && d <= hi && !agrees(d) {
492 return false;
493 }
494 }
495 true
496}
497
498fn shift_diff(op: CmpOp, s: i128) -> Option<(i128, i128)> {
500 let (up, t0) = op.threshold()?;
501 let t = t0 + s;
502 let (a, b) = (t0.min(t), t0.max(t));
503 Some(if up { (a, b - 1) } else { (a + 1, b) })
506}
507
508#[derive(Clone, PartialEq, Debug, Serialize)]
511#[serde(rename_all = "snake_case", tag = "kind")]
512pub enum InputGap {
513 Unreached,
515 OneSided { always: bool },
517 Boundary {
520 min_shift: i128,
521 max_shift: i128,
522 missing: Vec<i128>,
523 #[serde(skip_serializing_if = "no_shift")]
527 same: (i128, i128),
528 },
529 EqualNeverObserved {
533 flipped: CmpOp,
534 float_gap: Option<(f64, f64)>,
535 },
536}
537
538fn no_shift(range: &(i128, i128)) -> bool {
539 *range == (0, 0)
540}
541
542#[derive(Clone, PartialEq, Debug, Default)]
543pub struct CmpPlan {
544 pub cannot_differ: bool,
547 pub gap: Option<InputGap>,
548 pub run: Vec<Mutation>,
551}
552
553impl InputGap {
554 pub fn representative(&self) -> Option<Mutation> {
556 match self {
557 InputGap::Unreached => None,
558 InputGap::OneSided { always } => Some(Mutation::Const(*always)),
559 InputGap::Boundary {
560 min_shift,
561 max_shift,
562 same,
563 ..
564 } => {
565 if *max_shift > same.1 {
567 Some(Mutation::Shift(same.1 + 1))
568 } else if *min_shift < same.0 {
569 Some(Mutation::Shift(same.0 - 1))
570 } else {
571 None
572 }
573 }
574 InputGap::EqualNeverObserved { flipped, .. } => Some(Mutation::Op(*flipped)),
575 }
576 }
577
578 pub fn survivors(&self) -> Vec<Mutation> {
580 match self {
581 InputGap::Boundary {
582 min_shift,
583 max_shift,
584 same,
585 ..
586 } => (1..=3)
587 .flat_map(|n| [same.1 + n, same.0 - n])
588 .filter(|s| min_shift <= s && s <= max_shift)
589 .take(3)
590 .map(Mutation::Shift)
591 .collect(),
592 InputGap::EqualNeverObserved { flipped, float_gap } => {
593 let mut all = vec![Mutation::Op(*flipped)];
594 if let Some((lo, hi)) = float_gap {
595 all.extend([Mutation::ShiftF(hi / 2.0), Mutation::ShiftF(lo / 2.0)]);
596 }
597 all
598 }
599 other => other.representative().into_iter().collect(),
600 }
601 }
602}
603
604pub fn plan_cmp(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
608 let mut plan = plan_boundary(op, obs, domain);
609 let rels = obs.rels_mask();
617 let op_mask = op.truth_mask();
618 for other in op.mistaken_for() {
619 if rels & (op_mask ^ other.truth_mask()) != 0 {
620 plan.run.push(Mutation::Op(*other));
621 }
622 }
623 if matches!(op, CmpOp::Le | CmpOp::Ge)
629 && !obs.valued()
630 && rels & (op_mask ^ op.negated().truth_mask()) != 0
631 {
632 plan.run.push(Mutation::Op(op.negated()));
633 }
634 plan
635}
636
637fn plan_boundary(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
638 let rels = obs.rels_mask();
639 if rels == 0 {
640 return CmpPlan {
641 cannot_differ: false,
642 gap: Some(InputGap::Unreached),
643 run: vec![],
644 };
645 }
646 let op_mask = op.truth_mask();
647 let saw_true = rels & op_mask != 0;
648 let saw_false = rels & (!op_mask & 0x0f) != 0;
649 if !(saw_true && saw_false) {
650 let always = saw_true;
651 let other_possible = match domain {
653 Some((lo, hi)) if obs.valued() => [-1, 0, 1]
656 .into_iter()
657 .any(|d| lo <= d && d <= hi && op.eval_d(d) != always),
658 _ => true,
659 };
660 return CmpPlan {
661 cannot_differ: !other_possible,
662 gap: other_possible.then_some(InputGap::OneSided { always }),
663 run: vec![Mutation::Negate],
664 };
665 }
666
667 let Some((up, t0)) = op.threshold() else {
668 return CmpPlan {
670 cannot_differ: false,
671 gap: None,
672 run: vec![Mutation::Negate],
673 };
674 };
675
676 if !obs.valued() {
677 let flipped = op
678 .flip_eq()
679 .expect("ordering operators have a flipped form");
680 return if obs.eq {
681 CmpPlan {
682 cannot_differ: false,
683 gap: None,
684 run: vec![Mutation::Op(flipped), Mutation::Negate],
685 }
686 } else {
687 CmpPlan {
688 cannot_differ: false,
689 gap: Some(InputGap::EqualNeverObserved {
690 flipped,
691 float_gap: obs.float_gap(),
692 }),
693 run: vec![Mutation::Negate],
694 }
695 };
696 }
697
698 let (below, above, w_minus, w_plus) = if up {
701 (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
702 } else {
703 (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
704 };
705 let below = below.expect("both outcomes were observed");
706 let above = above.expect("both outcomes were observed");
707 let (min_shift, max_shift) = if up {
708 (below + 1 - t0, above - t0)
709 } else {
710 (below - t0, above - 1 - t0)
711 };
712
713 let mut missing = vec![];
716 let mut run = vec![];
717 for (w, shift) in [(w_minus, -1), (w_plus, 1)] {
718 if obs.saw(w) {
719 run.push(Mutation::Shift(shift));
720 } else {
721 missing.push(w);
722 }
723 }
724 run.push(Mutation::Negate);
725 let gap = (!missing.is_empty()).then_some(InputGap::Boundary {
726 min_shift,
727 max_shift,
728 missing,
729 same: (0, 0),
730 });
731 CmpPlan {
732 cannot_differ: false,
733 gap,
734 run,
735 }
736}
737
738#[derive(Clone, Copy, PartialEq, Eq, Debug)]
741pub enum Reach {
742 Multiples(i128),
744 Bits(i128),
746 Below(i128),
748}
749
750impl Reach {
751 pub fn holds(self, value: i128) -> bool {
752 match self {
753 Reach::Multiples(step) => value % step == 0,
754 Reach::Bits(mask) => value >= 0 && value & !mask == 0,
755 Reach::Below(limit) => -limit < value && value < limit,
756 }
757 }
758
759 pub fn of_shift(bits: u32, (low, high): (i128, i128)) -> Option<Reach> {
764 let values = high.checked_sub(low)?.checked_add(1)?;
765 if values < 2 || values & (values - 1) != 0 {
766 return None;
767 }
768 let effective = bits % values.trailing_zeros();
769 (effective > 0).then(|| Reach::Multiples(1 << effective))
770 }
771
772 pub fn within(self, low: i128, high: i128) -> Option<(i128, i128)> {
775 let least = if self.holds(low) {
776 low
777 } else {
778 self.next_above(low)?
779 };
780 let greatest = if self.holds(high) {
781 high
782 } else {
783 self.next_below(high)?
784 };
785 (least <= greatest).then_some((least, greatest))
786 }
787
788 pub fn interval(self) -> Option<(i128, i128)> {
790 match self {
791 Reach::Multiples(_) => None,
792 Reach::Bits(mask) => Some((0, mask)),
793 Reach::Below(limit) => Some((1 - limit, limit - 1)),
794 }
795 }
796
797 fn next_above(self, value: i128) -> Option<i128> {
799 match self {
800 Reach::Multiples(step) => value.div_euclid(step).checked_add(1)?.checked_mul(step),
801 Reach::Bits(_) if value < 0 => Some(0),
802 Reach::Bits(mask) => {
803 let over = value.checked_add(1)?;
804 let outside = over & !mask;
805 if outside == 0 {
806 return Some(over);
807 }
808 let top = 127 - outside.leading_zeros();
812 let low = 1_i128.checked_shl(top + 1)?.checked_sub(1)?;
813 let next = (over | !mask | low).wrapping_add(1) & mask;
814 (next > value).then_some(next)
815 }
816 Reach::Below(limit) => {
817 let next = value.checked_add(1)?.max(1 - limit);
818 (next < limit).then_some(next)
819 }
820 }
821 }
822
823 fn next_below(self, value: i128) -> Option<i128> {
825 match self {
826 Reach::Multiples(step) => value.checked_sub(1)?.div_euclid(step).checked_mul(step),
827 Reach::Bits(_) if value <= 0 => None,
828 Reach::Bits(mask) => {
829 let under = value - 1;
830 let outside = under & !mask;
831 Some(if outside == 0 {
832 under
833 } else {
834 let top = 127 - outside.leading_zeros();
836 let low = (1_i128 << top) - 1;
837 (under & !low & !(1_i128 << top)) | (mask & low)
838 })
839 }
840 Reach::Below(limit) => {
841 let next = value.checked_sub(1)?.min(limit - 1);
842 (next > -limit).then_some(next)
843 }
844 }
845 }
846}
847
848pub fn within_reach(
853 gap: InputGap,
854 op: CmpOp,
855 obs: &Obs,
856 reach: Reach,
857 literal: i128,
858 literal_is_rhs: bool,
859) -> Option<InputGap> {
860 let InputGap::Boundary {
861 min_shift,
862 max_shift,
863 missing,
864 same,
865 } = gap
866 else {
867 return Some(gap);
868 };
869 let Some((up, t0)) = op.threshold() else {
870 return Some(InputGap::Boundary {
871 min_shift,
872 max_shift,
873 missing,
874 same,
875 });
876 };
877 let (below, above, w_minus, w_plus) = if up {
880 (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
881 } else {
882 (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
883 };
884 let (below, above) = (below?, above?);
885 let value = |d: i128| {
887 if literal_is_rhs {
888 literal.checked_add(d)
889 } else {
890 literal.checked_sub(d)
891 }
892 };
893 let difference = |v: i128| {
894 if literal_is_rhs {
895 v.checked_sub(literal)
896 } else {
897 literal.checked_sub(v)
898 }
899 };
900 let nearest = |start: i128, bound: i128| -> Option<i128> {
903 if (start < bound) != (start <= bound) || start == bound {
904 return None;
905 }
906 let (from, to) = (value(start)?, value(bound)?);
907 let found = if reach.holds(from) {
908 from
909 } else if to > from {
910 reach.next_above(from)?
911 } else {
912 reach.next_below(from)?
913 };
914 let inside = if to > from { found < to } else { found > to };
915 inside.then(|| difference(found)).flatten()
916 };
917 let down = nearest(w_minus, below);
918 let up_side = nearest(w_plus, above);
919 let missing: Vec<i128> = [(w_minus, down), (w_plus, up_side)]
920 .into_iter()
921 .filter(|(w, _)| missing.contains(w))
922 .filter_map(|(_, nearest)| nearest)
923 .collect();
924 if missing.is_empty() {
925 return None;
926 }
927 let (first_under, first_over) = (down.unwrap_or(below), up_side.unwrap_or(above));
931 let same = if up {
932 (first_under - t0 + 1, first_over - t0)
933 } else {
934 (first_under - t0, first_over - t0 - 1)
935 };
936 Some(InputGap::Boundary {
937 min_shift,
938 max_shift,
939 missing,
940 same: (same.0.max(min_shift).min(0), same.1.min(max_shift).max(0)),
941 })
942}
943
944#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
946pub struct LogicObs {
947 pub short: bool,
949 pub rhs_true: bool,
950 pub rhs_false: bool,
951 pub rhs_started: bool,
954}
955
956impl LogicObs {
957 pub fn from_bits(bits: u8) -> LogicObs {
958 LogicObs {
959 short: bits & 1 != 0,
960 rhs_true: bits & 2 != 0,
961 rhs_false: bits & 4 != 0,
962 rhs_started: bits & 8 != 0,
963 }
964 }
965
966 pub fn merge(&mut self, other: &LogicObs) {
967 self.short |= other.short;
968 self.rhs_true |= other.rhs_true;
969 self.rhs_false |= other.rhs_false;
970 self.rhs_started |= other.rhs_started;
971 }
972
973 pub fn reached(&self) -> bool {
974 self.short || self.rhs_true || self.rhs_false || self.rhs_started
975 }
976
977 pub fn constant_value(&self, and: bool) -> Option<bool> {
979 let saw_true = self.rhs_true || (self.short && !and);
981 let saw_false = self.rhs_false || (self.short && and);
982 match (saw_true, saw_false) {
983 (true, false) => Some(true),
984 (false, true) => Some(false),
985 _ => None,
986 }
987 }
988
989 fn rhs_decided(&self, and: bool) -> bool {
991 if and { self.rhs_false } else { self.rhs_true }
992 }
993
994 pub fn swap_never_changes_value(&self, and: bool) -> bool {
1000 !self.short && !self.rhs_decided(and) && (self.rhs_true || self.rhs_false)
1001 }
1002}
1003
1004#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
1005#[serde(rename_all = "snake_case")]
1006pub enum LogicGap {
1007 Unreached,
1008 RhsNeverDecides,
1010 LhsNeverDecides,
1012}
1013
1014#[derive(Clone, PartialEq, Debug, Default)]
1015pub struct LogicPlan {
1016 pub gaps: Vec<LogicGap>,
1017 pub run: Vec<Mutation>,
1018}
1019
1020pub fn logic_infects(and: bool, m: Mutation, obs: &LogicObs) -> bool {
1024 match m {
1025 Mutation::LogicDropRhs => obs.rhs_decided(and),
1026 Mutation::LogicDropLhs => obs.short,
1027 _ => obs.reached(),
1028 }
1029}
1030
1031pub fn plan_logic(and: bool, obs: &LogicObs) -> LogicPlan {
1032 if !obs.reached() {
1033 return LogicPlan {
1034 gaps: vec![LogicGap::Unreached],
1035 run: vec![],
1036 };
1037 }
1038 let mut plan = LogicPlan::default();
1039 for (m, gap) in [
1040 (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1041 (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1042 ] {
1043 if logic_infects(and, m, obs) {
1044 plan.run.push(m);
1045 } else {
1046 plan.gaps.push(gap);
1047 }
1048 }
1049 plan.run.push(Mutation::LogicSwap);
1050 plan
1051}
1052
1053#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1055pub struct ArithObs {
1056 pub same: bool,
1058 pub differs: bool,
1060 pub opaque: bool,
1062 pub same2: bool,
1064 pub differs2: bool,
1065}
1066
1067impl ArithObs {
1068 pub fn from_bits(bits: u8) -> ArithObs {
1069 ArithObs {
1070 same: bits & 1 != 0,
1071 differs: bits & 2 != 0,
1072 opaque: bits & 4 != 0,
1073 same2: bits & 8 != 0,
1074 differs2: bits & 16 != 0,
1075 }
1076 }
1077
1078 pub fn merge(&mut self, other: &ArithObs) {
1079 self.same |= other.same;
1080 self.differs |= other.differs;
1081 self.opaque |= other.opaque;
1082 self.same2 |= other.same2;
1083 self.differs2 |= other.differs2;
1084 }
1085
1086 pub fn second(&self) -> ArithObs {
1088 ArithObs {
1089 same: self.same2,
1090 differs: self.differs2,
1091 opaque: self.opaque,
1092 same2: false,
1093 differs2: false,
1094 }
1095 }
1096
1097 pub fn infected_by(&self, m: Mutation) -> bool {
1099 if matches!(
1100 m,
1101 Mutation::ArithSwap2
1102 | Mutation::ClampDropUpper
1103 | Mutation::RoundAlt2
1104 | Mutation::TrimAlt2
1105 ) {
1106 self.differs2
1107 } else {
1108 self.differs
1109 }
1110 }
1111}
1112
1113#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1114pub enum ArithPlan {
1115 Unreached,
1116 Opaque,
1118 NeverDiffers,
1120 Run,
1122}
1123
1124pub fn plan_arith(obs: &ArithObs) -> ArithPlan {
1125 if obs.differs {
1126 ArithPlan::Run
1127 } else if obs.same {
1128 ArithPlan::NeverDiffers
1129 } else if obs.opaque {
1130 ArithPlan::Opaque
1131 } else {
1132 ArithPlan::Unreached
1133 }
1134}
1135
1136#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1138pub struct ReturnObs {
1139 pub saw_true: bool,
1140 pub saw_false: bool,
1141}
1142
1143impl ReturnObs {
1144 pub fn from_bits(bits: u8) -> ReturnObs {
1145 ReturnObs {
1146 saw_true: bits & 1 != 0,
1147 saw_false: bits & 2 != 0,
1148 }
1149 }
1150
1151 pub fn merge(&mut self, other: &ReturnObs) {
1152 self.saw_true |= other.saw_true;
1153 self.saw_false |= other.saw_false;
1154 }
1155
1156 pub fn reached(&self) -> bool {
1157 self.saw_true || self.saw_false
1158 }
1159
1160 pub fn infected_by_const(&self, value: bool) -> bool {
1162 if value { self.saw_false } else { self.saw_true }
1163 }
1164}
1165
1166#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1168pub struct LitSetObs {
1169 pub reached: bool,
1170 pub opaque: bool,
1171 pub matched: u8,
1173}
1174
1175impl LitSetObs {
1176 pub fn from_bits(bits: u16) -> LitSetObs {
1177 LitSetObs {
1178 reached: bits & 256 != 0,
1179 opaque: bits & 512 != 0,
1180 matched: (bits & 0xFF) as u8,
1181 }
1182 }
1183
1184 pub fn merge(&mut self, other: &LitSetObs) {
1185 self.reached |= other.reached;
1186 self.opaque |= other.opaque;
1187 self.matched |= other.matched;
1188 }
1189
1190 pub fn matched_elem(&self, idx: u8) -> bool {
1191 idx < 8 && (self.matched & (1u8 << idx)) != 0
1192 }
1193}
1194
1195#[derive(Clone, PartialEq, Debug, Default)]
1196pub struct ReturnPlan {
1197 pub unreached: bool,
1198 pub always: Option<bool>,
1200 pub run: Vec<Mutation>,
1201}
1202
1203pub fn plan_option_return(obs: &ReturnObs) -> ReturnPlan {
1206 match (obs.saw_true, obs.saw_false) {
1207 (false, false) => ReturnPlan {
1208 unreached: true,
1209 ..ReturnPlan::default()
1210 },
1211 (false, true) => ReturnPlan {
1213 unreached: false,
1214 always: Some(false),
1215 run: vec![],
1216 },
1217 (true, _) => ReturnPlan {
1218 unreached: false,
1219 always: None,
1220 run: vec![Mutation::Const(false)],
1221 },
1222 }
1223}
1224
1225pub fn plan_return(obs: &ReturnObs) -> ReturnPlan {
1226 match (obs.saw_true, obs.saw_false) {
1227 (false, false) => ReturnPlan {
1228 unreached: true,
1229 ..ReturnPlan::default()
1230 },
1231 (true, true) => ReturnPlan {
1232 run: vec![Mutation::Const(true), Mutation::Const(false)],
1233 ..ReturnPlan::default()
1234 },
1235 (always, _) => ReturnPlan {
1236 unreached: false,
1237 always: Some(always),
1238 run: vec![Mutation::Const(!always)],
1239 },
1240 }
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245 use super::*;
1246
1247 const REACHES: [Reach; 5] = [
1248 Reach::Multiples(4),
1249 Reach::Multiples(8),
1250 Reach::Bits(0b1010),
1251 Reach::Bits(0b0110),
1252 Reach::Below(5),
1253 ];
1254
1255 #[test]
1256 fn the_next_value_an_expression_can_be() {
1257 for reach in REACHES {
1258 for value in -40..=40_i128 {
1259 let above = (value + 1..=80).find(|v| reach.holds(*v));
1260 let below = (-80..value).rev().find(|v| reach.holds(*v));
1261 assert_eq!(reach.next_above(value), above, "{reach:?} above {value}");
1262 assert_eq!(reach.next_below(value), below, "{reach:?} below {value}");
1263 }
1264 }
1265 assert_eq!(Reach::Multiples(8).next_above(i128::MAX), None);
1267 assert_eq!(Reach::Multiples(8).next_below(i128::MIN), None);
1268 assert_eq!(Reach::Below(5).next_above(i128::MAX), None);
1269 assert_eq!(Reach::Below(5).next_below(i128::MIN), None);
1270 assert_eq!(Reach::Bits(i128::MAX).next_above(i128::MAX), None);
1271 assert!(Reach::Bits(0xF0).holds(0x30) && !Reach::Bits(0xF0).holds(0x31));
1272 assert!(!Reach::Bits(0xF0).holds(-16));
1273 }
1274
1275 #[test]
1279 fn a_gap_is_kept_only_for_values_the_expression_can_be() {
1280 let mut dropped = 0;
1281 let mut kept = 0;
1282 for reach in REACHES {
1283 let can_be: Vec<i128> = (-24..=24).filter(|v| reach.holds(*v)).collect();
1284 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1285 for literal in -6..=14_i128 {
1286 for literal_is_rhs in [true, false] {
1287 let d_of = |v: i128| {
1288 if literal_is_rhs {
1289 v - literal
1290 } else {
1291 literal - v
1292 }
1293 };
1294 for &low in &can_be {
1295 for &high in can_be.iter().filter(|v| **v > low) {
1296 let mut obs = Obs::of_d(d_of(low));
1297 obs.merge(&Obs::of_d(d_of(high)));
1298 let Some(gap @ InputGap::Boundary { .. }) =
1299 plan_boundary(op, &obs, None).gap
1300 else {
1301 continue;
1302 };
1303 let InputGap::Boundary {
1304 min_shift,
1305 max_shift,
1306 ..
1307 } = gap.clone()
1308 else {
1309 unreachable!()
1310 };
1311 let differs = |shift: i128, v: i128| {
1314 op.eval_d(d_of(v)) != op.eval_d(d_of(v) - shift)
1315 };
1316 let told_apart =
1317 |shift: i128| can_be.iter().any(|v| differs(shift, *v));
1318 let case = format!(
1319 "{reach:?} {op:?} literal {literal} rhs {literal_is_rhs}, saw {low} and {high}"
1320 );
1321 match within_reach(gap, op, &obs, reach, literal, literal_is_rhs) {
1322 None => {
1323 for shift in min_shift..=max_shift {
1325 assert!(!told_apart(shift), "{case}: shift {shift}");
1326 }
1327 dropped += 1;
1328 }
1329 Some(InputGap::Boundary {
1330 min_shift: least,
1331 max_shift: most,
1332 missing,
1333 same,
1334 }) => {
1335 assert!(!missing.is_empty(), "{case}");
1336 assert_eq!((least, most), (min_shift, max_shift), "{case}");
1337 for d in &missing {
1338 let v = if literal_is_rhs {
1339 literal + d
1340 } else {
1341 literal - d
1342 };
1343 assert!(reach.holds(v), "{case}: {v}");
1344 assert!(low < v && v < high, "{case}: {v}");
1345 }
1346 assert!(same.0 <= 0 && 0 <= same.1, "{case}: {same:?}");
1349 for shift in least..=most {
1350 assert_eq!(
1351 same.0 <= shift && shift <= same.1,
1352 !told_apart(shift),
1353 "{case}: shift {shift}, same {same:?}"
1354 );
1355 }
1356 let gap = InputGap::Boundary {
1359 min_shift: least,
1360 max_shift: most,
1361 missing: missing.clone(),
1362 same,
1363 };
1364 for mutation in gap.survivors() {
1365 let Mutation::Shift(shift) = mutation else {
1366 panic!("{case}: {mutation:?}")
1367 };
1368 assert!(told_apart(shift), "{case}: shift {shift}");
1369 }
1370 assert!(gap.representative().is_some(), "{case}");
1371 kept += 1;
1372 }
1373 Some(other) => panic!("{case}: {other:?}"),
1374 }
1375 }
1376 }
1377 }
1378 }
1379 }
1380 }
1381 assert!(
1382 dropped > 100 && kept > 1000,
1383 "{dropped} dropped, {kept} kept"
1384 );
1385 }
1386
1387 #[test]
1388 fn an_outcome_no_value_gives_is_not_asked_for() {
1389 for (reach, literal, op, differs) in [
1391 (Reach::Below(10), 10, CmpOp::Lt, false),
1392 (Reach::Below(10), 9, CmpOp::Lt, true),
1393 (Reach::Below(10), -10, CmpOp::Gt, false),
1394 (Reach::Bits(0xF0), 0xF0, CmpOp::Gt, false),
1395 (Reach::Bits(0xF0), 0xF0, CmpOp::Ge, true),
1396 (Reach::Bits(0xF0), 0, CmpOp::Lt, false),
1397 ] {
1398 let (lo, hi) = reach.interval().unwrap();
1399 assert!((lo..=hi).all(|v| !reach.holds(v) || (lo <= v && v <= hi)));
1400 assert!(reach.holds(lo) && reach.holds(hi), "{reach:?}");
1401 assert!(!reach.holds(lo - 1) && !reach.holds(hi + 1), "{reach:?}");
1402 let can_differ = (lo..=hi)
1403 .filter(|v| reach.holds(*v))
1404 .map(|v| op.eval_d(v - literal))
1405 .collect::<std::collections::BTreeSet<_>>()
1406 .len()
1407 == 2;
1408 assert_eq!(can_differ, differs, "{reach:?} {op:?} {literal}");
1409 let seen = (lo..=hi).find(|v| reach.holds(*v)).unwrap();
1411 let plan = plan_cmp(
1412 op,
1413 &Obs::of_d(seen - literal),
1414 Some((lo - literal, hi - literal)),
1415 );
1416 assert_eq!(plan.cannot_differ, !differs, "{reach:?} {op:?} {literal}");
1417 assert_eq!(plan.gap.is_some(), differs, "{reach:?} {op:?} {literal}");
1418 }
1419 assert_eq!(Reach::Multiples(8).interval(), None);
1420 }
1421
1422 #[test]
1423 fn a_shift_is_a_multiple_by_the_bits_that_are_shifted_in_fact() {
1424 let (byte, signed_byte) = ((0, 255), (-128, 127));
1425 for (bits, range, expected) in [
1426 (3, byte, Some(Reach::Multiples(8))),
1427 (7, byte, Some(Reach::Multiples(128))),
1428 (8, byte, None),
1430 (9, byte, Some(Reach::Multiples(2))),
1431 (16, byte, None),
1432 (9, signed_byte, Some(Reach::Multiples(2))),
1433 (33, (0, u32::MAX as i128), Some(Reach::Multiples(2))),
1434 (3, (0, u32::MAX as i128), Some(Reach::Multiples(8))),
1435 (3, (0, 9), None),
1437 (3, (0, 0), None),
1438 (3, (5, 4), None),
1439 (3, (i128::MIN, i128::MAX), None),
1440 ] {
1441 assert_eq!(Reach::of_shift(bits, range), expected, "{bits} {range:?}");
1442 }
1443 for bits in 1..=20u32 {
1445 let reach = Reach::of_shift(bits, byte);
1446 for n in 0..=255u8 {
1447 let shifted = i128::from(n.wrapping_shl(bits));
1448 assert!(
1449 reach.is_none_or(|reach| reach.holds(shifted)),
1450 "{n} << {bits}"
1451 );
1452 }
1453 }
1454 }
1455
1456 #[test]
1457 fn the_ends_of_what_an_expression_can_be_in_its_type() {
1458 for reach in REACHES {
1459 for (low, high) in [(0, 255), (-128, 127), (0, 0), (3, 3), (5, 9)] {
1460 let all: Vec<i128> = (low..=high).filter(|v| reach.holds(*v)).collect();
1461 assert_eq!(
1462 reach.within(low, high),
1463 all.first().copied().zip(all.last().copied()),
1464 "{reach:?} in {low}..={high}"
1465 );
1466 }
1467 }
1468 assert_eq!(Reach::Multiples(2).within(0, 255), Some((0, 254)));
1470 }
1471
1472 #[test]
1473 fn gaps_of_another_kind_are_not_touched() {
1474 let obs = Obs::of_d(3);
1475 for gap in [
1476 InputGap::Unreached,
1477 InputGap::OneSided { always: true },
1478 InputGap::EqualNeverObserved {
1479 flipped: CmpOp::Le,
1480 float_gap: None,
1481 },
1482 ] {
1483 assert_eq!(
1484 within_reach(gap.clone(), CmpOp::Lt, &obs, Reach::Multiples(8), 20, true),
1485 Some(gap)
1486 );
1487 }
1488 let mut obs = Obs::of_d(16 - 20);
1490 obs.merge(&Obs::of_d(24 - 20));
1491 let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1492 assert_eq!(
1493 within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1494 None
1495 );
1496 let mut obs = Obs::of_d(8 - 20);
1498 obs.merge(&Obs::of_d(40 - 20));
1499 let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1500 assert_eq!(
1501 within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1502 Some(InputGap::Boundary {
1503 min_shift: -12,
1504 max_shift: 19,
1505 missing: vec![-4, 4],
1506 same: (-4, 3),
1508 })
1509 );
1510 }
1511
1512 fn obs_of(ds: &[i128]) -> Obs {
1513 let mut obs = Obs::default();
1514 for d in ds {
1515 obs.merge(&Obs::of_d(*d));
1516 }
1517 obs
1518 }
1519
1520 fn rel_of(d: i128) -> Rel {
1521 match d {
1522 d if d < 0 => Rel::Less,
1523 0 => Rel::Equal,
1524 _ => Rel::Greater,
1525 }
1526 }
1527
1528 fn brute_infects(op: CmpOp, m: Mutation, ds: &[i128]) -> bool {
1530 ds.iter()
1531 .any(|d| op.eval_d(*d) != eval_mutated_d(op, m, *d))
1532 }
1533
1534 #[test]
1535 fn is_eligible_example_from_the_readme() {
1536 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[-1, 2]), None);
1538 assert_eq!(
1539 plan.gap,
1540 Some(InputGap::Boundary {
1541 min_shift: 0,
1542 max_shift: 2,
1543 missing: vec![0],
1544 same: (0, 0),
1545 })
1546 );
1547 assert_eq!(plan.run, vec![Mutation::Shift(-1), Mutation::Negate]);
1549 assert_eq!(plan.gap.unwrap().representative(), Some(Mutation::Shift(1)));
1550 }
1551
1552 #[test]
1557 fn the_operators_a_comparison_is_mistaken_for() {
1558 let rels = [Rel::Less, Rel::Equal, Rel::Greater, Rel::Unordered];
1559 for op in [CmpOp::Lt, CmpOp::Gt] {
1560 for seen in 1u8..16 {
1561 let mut obs = Obs::default();
1562 let seen: Vec<Rel> = (0..4)
1563 .filter(|i| seen & (1 << i) != 0)
1564 .map(|i| rels[i])
1565 .collect();
1566 for rel in &seen {
1567 obs.merge(&Obs::of_rel(*rel));
1568 }
1569 let plan = plan_cmp(op, &obs, None);
1570 for other in op.mistaken_for() {
1571 let like_the_original = seen
1572 .iter()
1573 .all(|rel| other.eval_rel(*rel) == op.eval_rel(*rel));
1574 let what = format!("{op:?} as {other:?} with {seen:?}: {plan:?}");
1575 let run = plan
1576 .run
1577 .iter()
1578 .filter(|m| **m == Mutation::Op(*other))
1579 .count();
1580 if like_the_original {
1581 assert!(plan.gap.is_some(), "{what}");
1582 assert_eq!(run, 0, "{what}");
1583 } else {
1584 assert_eq!(run, 1, "{what}");
1585 }
1586 }
1587 }
1588 }
1589 for op in [CmpOp::Le, CmpOp::Ge, CmpOp::Eq, CmpOp::Ne] {
1591 assert!(op.mistaken_for().is_empty());
1592 }
1593 let seen = |rels: &[Rel]| {
1598 let mut obs = Obs::default();
1599 for rel in rels {
1600 obs.merge(&Obs::of_rel(*rel));
1601 }
1602 obs
1603 };
1604 for (op, reverse) in [(CmpOp::Ge, CmpOp::Lt), (CmpOp::Le, CmpOp::Gt)] {
1605 let run = |rels: &[Rel]| plan_cmp(op, &seen(rels), None).run;
1606 let reversed = |rels: &[Rel]| run(rels).contains(&Mutation::Op(reverse));
1607 assert!(reversed(&[Rel::Unordered, Rel::Less]), "{op:?}");
1608 assert!(reversed(&[Rel::Less, Rel::Greater]), "{op:?}");
1609 assert!(reversed(&[Rel::Less, Rel::Equal, Rel::Greater]), "{op:?}");
1610 assert_eq!(run(&[Rel::Unordered]), vec![Mutation::Negate], "{op:?}");
1614 for ds in [&[-1i128, 1][..], &[-2, 0, 3], &[0, 1]] {
1616 let plan = plan_cmp(op, &obs_of(ds), None);
1617 assert!(!plan.run.contains(&Mutation::Op(reverse)), "{op:?} {ds:?}");
1618 }
1619 for d in -3..=3 {
1620 assert_eq!(eval_mutated_d(op, Mutation::Negate, d), reverse.eval_d(d));
1621 }
1622 }
1623 let run = plan_cmp(CmpOp::Eq, &seen(&[Rel::Unordered, Rel::Equal]), None).run;
1625 assert_eq!(run, vec![Mutation::Negate]);
1626 let plan = plan_cmp(CmpOp::Lt, &Obs::of_rel(Rel::Greater), None);
1629 assert_eq!(plan.run, vec![Mutation::Negate, Mutation::Op(CmpOp::Gt)]);
1630 }
1631
1632 #[test]
1633 fn pinned_boundary_has_no_input_gap() {
1634 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1635 let plan = plan_cmp(op, &obs_of(&[-1, 0, 1]), None);
1636 assert_eq!(plan.gap, None, "{op:?}");
1637 let mut run = vec![Mutation::Shift(-1), Mutation::Shift(1), Mutation::Negate];
1639 run.extend(op.mistaken_for().iter().map(|other| Mutation::Op(*other)));
1640 assert_eq!(plan.run, run, "{op:?}");
1641 }
1642 }
1643
1644 #[test]
1645 fn unreached_site() {
1646 let plan = plan_cmp(CmpOp::Lt, &Obs::default(), None);
1647 assert_eq!(
1648 plan,
1649 CmpPlan {
1650 cannot_differ: false,
1651 gap: Some(InputGap::Unreached),
1652 run: vec![]
1653 }
1654 );
1655 }
1656
1657 #[test]
1658 fn one_sided_condition() {
1659 let plan = plan_cmp(CmpOp::Gt, &obs_of(&[3, 5]), None);
1660 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1661 assert_eq!(
1663 plan.run,
1664 vec![
1665 Mutation::Negate,
1666 Mutation::Op(CmpOp::Eq),
1667 Mutation::Op(CmpOp::Lt)
1668 ]
1669 );
1670 }
1671
1672 #[test]
1673 fn unsigned_compared_with_zero_is_not_reported() {
1674 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((0, 255)));
1676 assert_eq!(plan.gap, None);
1677 assert!(plan.cannot_differ);
1678 assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 255))).cannot_differ);
1679 assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[-1, 4]), Some((-1, 255))).cannot_differ);
1680 let plan = plan_cmp(CmpOp::Lt, &obs_of(&[0, 4]), Some((0, 255)));
1682 assert_eq!(plan.gap, None);
1683 let plan = plan_cmp(CmpOp::Gt, &obs_of(&[0, 1]), Some((0, 255)));
1686 assert_eq!(plan.gap, None);
1687 assert_eq!(
1689 plan.run,
1690 vec![
1691 Mutation::Shift(-1),
1692 Mutation::Shift(1),
1693 Mutation::Negate,
1694 Mutation::Op(CmpOp::Eq),
1695 Mutation::Op(CmpOp::Lt)
1696 ]
1697 );
1698 let plan = plan_cmp(CmpOp::Le, &obs_of(&[0, 1]), Some((0, 255)));
1701 assert_eq!(plan.gap, None);
1702 }
1703
1704 #[test]
1705 fn one_sided_condition_at_the_edge_of_the_type() {
1706 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 10)));
1708 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1709 let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 1)));
1711 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1712 let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 0)));
1713 assert_eq!(plan.gap, None);
1714 let plan = plan_cmp(CmpOp::Ge, &Obs::of_rel(Rel::Greater), Some((0, 10)));
1716 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1717 }
1718
1719 #[test]
1720 fn representative_is_the_nearest_survivor() {
1721 let boundary = |min_shift, max_shift| InputGap::Boundary {
1722 min_shift,
1723 max_shift,
1724 missing: vec![0],
1725 same: (0, 0),
1726 };
1727 assert_eq!(boundary(-3, 1).representative(), Some(Mutation::Shift(1)));
1728 assert_eq!(boundary(-1, 0).representative(), Some(Mutation::Shift(-1)));
1729 assert_eq!(boundary(0, 0).representative(), None);
1730 assert_eq!(InputGap::Unreached.representative(), None);
1731 assert_eq!(
1732 InputGap::OneSided { always: false }.representative(),
1733 Some(Mutation::Const(false))
1734 );
1735 assert_eq!(
1736 InputGap::EqualNeverObserved {
1737 flipped: CmpOp::Ge,
1738 float_gap: None
1739 }
1740 .representative(),
1741 Some(Mutation::Op(CmpOp::Ge))
1742 );
1743 }
1744
1745 fn eval_logic(and: bool, m: Option<Mutation>, a: bool, b: bool) -> (bool, bool) {
1748 let decided = |and: bool| if and { !a } else { a };
1749 match m {
1750 None => {
1751 if decided(and) {
1752 (a, false)
1753 } else {
1754 (b, true)
1755 }
1756 }
1757 Some(Mutation::LogicSwap) => {
1758 if decided(!and) {
1759 (a, false)
1760 } else {
1761 (b, true)
1762 }
1763 }
1764 Some(Mutation::LogicDropRhs) => (a, !decided(and)),
1766 Some(Mutation::LogicDropLhs) => (b, true),
1767 other => panic!("{other:?}"),
1768 }
1769 }
1770
1771 #[test]
1772 fn logic_plans_match_a_reference_evaluator() {
1773 let cases = [(false, false), (false, true), (true, false), (true, true)];
1774 for and in [true, false] {
1775 for mask in 0u32..16 {
1776 let seen: Vec<(bool, bool)> = cases
1777 .iter()
1778 .enumerate()
1779 .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1780 .collect();
1781 let mut obs = LogicObs::default();
1782 for (a, b) in &seen {
1783 let (_, evaluated) = eval_logic(and, None, *a, *b);
1784 obs.short |= !evaluated;
1785 obs.rhs_true |= evaluated && *b;
1786 obs.rhs_false |= evaluated && !*b;
1787 }
1788 let ctx = format!("and={and} seen={seen:?}");
1789 let differs = |m: Mutation| {
1790 seen.iter().any(|(a, b)| {
1791 eval_logic(and, None, *a, *b) != eval_logic(and, Some(m), *a, *b)
1792 })
1793 };
1794 let plan = plan_logic(and, &obs);
1795 if seen.is_empty() {
1796 assert_eq!(
1797 plan,
1798 LogicPlan {
1799 gaps: vec![LogicGap::Unreached],
1800 run: vec![]
1801 }
1802 );
1803 continue;
1804 }
1805 for (m, gap) in [
1806 (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1807 (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1808 ] {
1809 assert_eq!(plan.gaps.contains(&gap), !differs(m), "{gap:?} {ctx}");
1811 assert_eq!(plan.run.contains(&m), differs(m), "{m:?} {ctx}");
1812 assert_eq!(logic_infects(and, m, &obs), differs(m), "{m:?} {ctx}");
1813 }
1814 assert!(plan.run.contains(&Mutation::LogicSwap), "{ctx}");
1816 assert!(logic_infects(and, Mutation::LogicSwap, &obs), "{ctx}");
1817 }
1818 }
1819 let started = LogicObs::from_bits(8);
1823 assert!(started.rhs_started && started.reached());
1824 for and in [true, false] {
1825 let plan = plan_logic(and, &started);
1826 assert_eq!(plan.run, vec![Mutation::LogicSwap]);
1827 assert_eq!(
1828 plan.gaps,
1829 vec![LogicGap::RhsNeverDecides, LogicGap::LhsNeverDecides]
1830 );
1831 assert!(logic_infects(and, Mutation::LogicSwap, &started));
1832 assert!(!logic_infects(and, Mutation::LogicDropRhs, &started));
1833 assert!(!logic_infects(and, Mutation::LogicDropLhs, &started));
1834 }
1835 let mut merged = LogicObs::from_bits(2);
1836 merged.merge(&started);
1837 assert_eq!(merged, LogicObs::from_bits(10));
1838 assert_eq!(
1839 LogicObs::from_bits(5),
1840 LogicObs {
1841 short: true,
1842 rhs_true: false,
1843 rhs_false: true,
1844 rhs_started: false,
1845 }
1846 );
1847 assert_eq!(
1848 LogicObs::from_bits(2),
1849 LogicObs {
1850 short: false,
1851 rhs_true: true,
1852 rhs_false: false,
1853 rhs_started: false,
1854 }
1855 );
1856 }
1857
1858 #[test]
1859 fn return_plans() {
1860 assert_eq!(
1861 plan_return(&ReturnObs::from_bits(0)),
1862 ReturnPlan {
1863 unreached: true,
1864 always: None,
1865 run: vec![]
1866 }
1867 );
1868 assert_eq!(
1869 plan_return(&ReturnObs::from_bits(1)),
1870 ReturnPlan {
1871 unreached: false,
1872 always: Some(true),
1873 run: vec![Mutation::Const(false)]
1874 }
1875 );
1876 assert_eq!(
1877 plan_return(&ReturnObs::from_bits(2)),
1878 ReturnPlan {
1879 unreached: false,
1880 always: Some(false),
1881 run: vec![Mutation::Const(true)]
1882 }
1883 );
1884 assert_eq!(
1885 plan_return(&ReturnObs::from_bits(3)),
1886 ReturnPlan {
1887 unreached: false,
1888 always: None,
1889 run: vec![Mutation::Const(true), Mutation::Const(false)]
1890 }
1891 );
1892 for bits in 0u8..4 {
1894 let obs = ReturnObs::from_bits(bits);
1895 assert_eq!(obs.infected_by_const(true), obs.saw_false);
1896 assert_eq!(obs.infected_by_const(false), obs.saw_true);
1897 assert_eq!(obs.reached(), bits != 0);
1898 let plan = plan_return(&obs);
1899 for m in &plan.run {
1900 let Mutation::Const(value) = m else { panic!() };
1901 assert!(
1902 obs.infected_by_const(*value),
1903 "a run mutant must change some test"
1904 );
1905 }
1906 if let Some(always) = plan.always {
1907 assert!(
1908 !obs.infected_by_const(always),
1909 "the survivor changes no test"
1910 );
1911 }
1912 }
1913 let mut merged = ReturnObs::from_bits(1);
1914 merged.merge(&ReturnObs::from_bits(2));
1915 assert_eq!(
1916 merged,
1917 ReturnObs {
1918 saw_true: true,
1919 saw_false: true
1920 }
1921 );
1922 }
1923
1924 #[test]
1925 fn logic_constant_value() {
1926 let cases = [(false, false), (false, true), (true, false), (true, true)];
1927 for and in [true, false] {
1928 for mask in 0u32..16 {
1929 let seen: Vec<(bool, bool)> = cases
1930 .iter()
1931 .enumerate()
1932 .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1933 .collect();
1934 let mut obs = LogicObs::default();
1935 let mut values = std::collections::BTreeSet::new();
1936 for (a, b) in &seen {
1937 let (value, evaluated) = eval_logic(and, None, *a, *b);
1938 values.insert(value);
1939 obs.short |= !evaluated;
1940 obs.rhs_true |= evaluated && *b;
1941 obs.rhs_false |= evaluated && !*b;
1942 }
1943 let expected = if values.len() == 1 {
1944 values.first().copied()
1945 } else {
1946 None
1947 };
1948 assert_eq!(obs.constant_value(and), expected, "and={and} seen={seen:?}");
1949 }
1950 }
1951 }
1952
1953 #[test]
1954 fn option_return_plans() {
1955 let plan = |bits| plan_option_return(&ReturnObs::from_bits(bits));
1956 assert_eq!(
1957 plan(0),
1958 ReturnPlan {
1959 unreached: true,
1960 always: None,
1961 run: vec![]
1962 }
1963 );
1964 assert_eq!(
1966 plan(2),
1967 ReturnPlan {
1968 unreached: false,
1969 always: Some(false),
1970 run: vec![]
1971 }
1972 );
1973 for bits in [1, 3] {
1975 assert_eq!(
1976 plan(bits),
1977 ReturnPlan {
1978 unreached: false,
1979 always: None,
1980 run: vec![Mutation::Const(false)]
1981 }
1982 );
1983 assert!(ReturnObs::from_bits(bits).infected_by_const(false));
1984 }
1985 assert!(!ReturnObs::from_bits(2).infected_by_const(false));
1986 }
1987
1988 #[test]
1989 fn arithmetic_plans() {
1990 for bits in 0u8..8 {
1991 let obs = ArithObs::from_bits(bits);
1992 let expected = if bits & 2 != 0 {
1993 ArithPlan::Run
1994 } else if bits & 1 != 0 {
1995 ArithPlan::NeverDiffers
1996 } else if bits & 4 != 0 {
1997 ArithPlan::Opaque
1998 } else {
1999 ArithPlan::Unreached
2000 };
2001 assert_eq!(plan_arith(&obs), expected, "bits={bits}");
2002 }
2003 let mut merged = ArithObs::from_bits(1);
2004 merged.merge(&ArithObs::from_bits(4));
2005 assert_eq!(
2006 merged,
2007 ArithObs {
2008 same: true,
2009 differs: false,
2010 opaque: true,
2011 ..Default::default()
2012 }
2013 );
2014 }
2015
2016 #[test]
2017 fn float_comparison_without_equal_operands() {
2018 let mut obs = Obs::of_f(-20.5);
2020 obs.merge(&Obs::of_f(9.5));
2021 let plan = plan_cmp(CmpOp::Gt, &obs, None);
2022 let gap = plan.gap.expect("a gap");
2023 assert_eq!(
2024 gap,
2025 InputGap::EqualNeverObserved {
2026 flipped: CmpOp::Ge,
2027 float_gap: Some((-20.5, 9.5))
2028 }
2029 );
2030 assert_eq!(
2031 gap.survivors(),
2032 vec![
2033 Mutation::Op(CmpOp::Ge),
2034 Mutation::ShiftF(4.75),
2035 Mutation::ShiftF(-10.25)
2036 ]
2037 );
2038 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
2041 assert!(!infects(op, Mutation::ShiftF(4.75), &obs));
2042 assert!(!infects(op, Mutation::ShiftF(-10.25), &obs));
2043 assert!(infects(op, Mutation::ShiftF(9.5), &obs));
2044 assert!(infects(op, Mutation::ShiftF(-20.5), &obs));
2045 }
2046 let mut with_eq = obs;
2047 with_eq.merge(&Obs::of_f(0.0));
2048 assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &with_eq));
2049 assert_eq!(plan_cmp(CmpOp::Gt, &with_eq, None).gap, None);
2050 let mut mixed = obs;
2052 mixed.merge(&Obs::of_rel(Rel::Less));
2053 assert_eq!(mixed.float_gap(), None);
2054 assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &mixed));
2055 assert_eq!(Obs::of_d(3).float_gap(), None);
2056 }
2057
2058 #[test]
2059 fn survivors_are_listed_nearest_first() {
2060 let boundary = |min_shift, max_shift| InputGap::Boundary {
2061 min_shift,
2062 max_shift,
2063 missing: vec![0],
2064 same: (0, 0),
2065 };
2066 assert_eq!(
2067 boundary(-9, 9).survivors(),
2068 vec![Mutation::Shift(1), Mutation::Shift(-1), Mutation::Shift(2)]
2069 );
2070 assert_eq!(boundary(-1, 0).survivors(), vec![Mutation::Shift(-1)]);
2071 assert_eq!(
2072 boundary(0, 2).survivors(),
2073 vec![Mutation::Shift(1), Mutation::Shift(2)]
2074 );
2075 assert_eq!(
2076 InputGap::OneSided { always: true }.survivors(),
2077 vec![Mutation::Const(true)]
2078 );
2079 assert_eq!(InputGap::Unreached.survivors(), vec![]);
2080 }
2081
2082 #[test]
2083 fn single_observation_summaries() {
2084 let bits = |o: Obs| (o.lt, o.eq, o.gt, o.un);
2085 assert_eq!(bits(Obs::of_f(-0.5)), (true, false, false, false));
2086 assert_eq!(bits(Obs::of_f(0.0)), (false, true, false, false));
2087 assert_eq!(bits(Obs::of_f(0.5)), (false, false, true, false));
2088 assert_eq!(
2089 (Obs::of_f(-0.5).f_max_neg, Obs::of_f(-0.5).f_min_pos),
2090 (Some(-0.5), None)
2091 );
2092 assert_eq!(
2093 (Obs::of_f(0.5).f_max_neg, Obs::of_f(0.5).f_min_pos),
2094 (None, Some(0.5))
2095 );
2096 assert_eq!(
2097 (Obs::of_f(0.0).f_max_neg, Obs::of_f(0.0).f_min_pos),
2098 (None, None)
2099 );
2100 assert!(Obs::of_f(1.0).unvalued && !Obs::of_f(1.0).unfloat);
2101 assert!(Obs::of_d(1).unfloat && !Obs::of_d(1).unvalued);
2102
2103 assert!(Obs::of_rel(Rel::Unordered).reached());
2105 assert!(!Obs::default().reached());
2106 assert!(!Obs::default().valued());
2108 assert!(Obs::of_d(0).valued());
2109 assert!(!Obs::of_rel(Rel::Equal).valued());
2110
2111 let mut nan = Obs::of_f(-1.0);
2113 nan.merge(&Obs::of_f(1.0));
2114 assert_eq!(nan.float_gap(), Some((-1.0, 1.0)));
2115 nan.un = true;
2116 assert_eq!(nan.float_gap(), None);
2117 assert_eq!(Obs::default().float_gap(), None);
2118 assert_eq!(Obs::of_f(-1.0).float_gap(), None, "one side only");
2119 }
2120
2121 #[test]
2122 fn interval_queries_look_at_the_right_side_of_zero() {
2123 assert!(!obs_of(&[2]).saw_any_in(-3, -1));
2125 assert!(!obs_of(&[-2]).saw_any_in(1, 3));
2126 assert!(obs_of(&[-2]).saw_any_in(-3, -1));
2127 assert!(obs_of(&[2]).saw_any_in(1, 3));
2128 assert!(!obs_of(&[-4]).saw_any_in(-3, 0));
2129 assert!(!obs_of(&[4]).saw_any_in(0, 3));
2130 let mut odd = obs_of(&[3]);
2132 odd.max_neg = Some(5);
2133 assert!(!odd.saw_any_in(0, 2));
2134 let mut odd = obs_of(&[-3]);
2135 odd.min_pos = Some(-5);
2136 assert!(!odd.saw_any_in(-2, 0));
2137 }
2138
2139 #[test]
2140 fn empty_interval_has_no_observations() {
2141 assert!(!obs_of(&[-1, 0, 1]).saw_any_in(1, 0));
2142 assert!(obs_of(&[0]).saw_any_in(0, 0));
2143 }
2144
2145 #[test]
2146 fn unvalued_ordering_without_equal_operands() {
2147 let mut obs = Obs::of_rel(Rel::Less);
2148 obs.merge(&Obs::of_rel(Rel::Greater));
2149 let plan = plan_cmp(CmpOp::Lt, &obs, None);
2150 assert_eq!(
2151 plan.gap,
2152 Some(InputGap::EqualNeverObserved {
2153 flipped: CmpOp::Le,
2154 float_gap: None
2155 })
2156 );
2157 assert_eq!(
2159 plan.run,
2160 vec![
2161 Mutation::Negate,
2162 Mutation::Op(CmpOp::Eq),
2163 Mutation::Op(CmpOp::Gt)
2164 ]
2165 );
2166
2167 obs.merge(&Obs::of_rel(Rel::Equal));
2168 let plan = plan_cmp(CmpOp::Lt, &obs, None);
2169 assert_eq!(plan.gap, None);
2170 assert_eq!(
2171 plan.run,
2172 vec![
2173 Mutation::Op(CmpOp::Le),
2174 Mutation::Negate,
2175 Mutation::Op(CmpOp::Eq),
2176 Mutation::Op(CmpOp::Gt)
2177 ]
2178 );
2179 }
2180
2181 #[test]
2182 fn equality_with_both_outcomes() {
2183 let plan = plan_cmp(CmpOp::Eq, &obs_of(&[0, 7]), None);
2184 assert_eq!(
2185 plan,
2186 CmpPlan {
2187 cannot_differ: false,
2188 gap: None,
2189 run: vec![Mutation::Negate]
2190 }
2191 );
2192 }
2193
2194 #[test]
2195 fn unordered_counts_as_not_equal() {
2196 let obs = Obs::of_rel(Rel::Unordered);
2197 assert!(infects(CmpOp::Ne, Mutation::Const(false), &obs));
2198 assert!(!infects(CmpOp::Lt, Mutation::Op(CmpOp::Ge), &obs));
2199 assert!(infects(CmpOp::Lt, Mutation::Op(CmpOp::Ne), &obs));
2200 }
2201
2202 #[test]
2203 fn merge_is_a_semilattice() {
2204 let samples: Vec<Obs> = [-3, -1, 0, 1, 4]
2205 .into_iter()
2206 .map(Obs::of_d)
2207 .chain([
2208 Obs::of_rel(Rel::Unordered),
2209 Obs::of_rel(Rel::Less),
2210 Obs::default(),
2211 ])
2212 .collect();
2213 for a in &samples {
2214 let mut aa = *a;
2215 aa.merge(a);
2216 assert_eq!(aa, *a, "idempotent");
2217 for b in &samples {
2218 let (mut ab, mut ba) = (*a, *b);
2219 ab.merge(b);
2220 ba.merge(a);
2221 assert_eq!(ab, ba, "commutative");
2222 for c in &samples {
2223 let mut ab_c = ab;
2224 ab_c.merge(c);
2225 let mut bc = *b;
2226 bc.merge(c);
2227 let mut a_bc = *a;
2228 a_bc.merge(&bc);
2229 assert_eq!(ab_c, a_bc, "associative");
2230 }
2231 }
2232 }
2233 }
2234
2235 #[test]
2236 fn mutation_wire_format() {
2237 assert_eq!(Mutation::Const(true).encode(), "c1");
2238 assert_eq!(Mutation::Const(false).encode(), "c0");
2239 assert_eq!(Mutation::Negate.encode(), "neg");
2240 assert_eq!(Mutation::Op(CmpOp::Ge).encode(), "op3");
2241 assert_eq!(Mutation::Shift(-2).encode(), "sh-2");
2242 assert_eq!(Mutation::Delete.encode(), "del");
2243 assert_eq!(Mutation::ShiftF(4.75).encode(), "shf4.75");
2244 assert_eq!(Mutation::ShiftF(-10.0).encode(), "shf-10.0");
2245 assert_eq!(Mutation::LogicSwap.encode(), "lsw");
2246 assert_eq!(Mutation::LogicDropRhs.encode(), "ldr");
2247 assert_eq!(Mutation::LogicDropLhs.encode(), "ldl");
2248 assert_eq!(Mutation::ArithSwap.encode(), "asw");
2249 assert_eq!(Mutation::DropNot.encode(), "unn");
2250 assert_eq!(Mutation::RangeEnd.encode(), "rng");
2251 assert_eq!(Mutation::MinMax.encode(), "mmx");
2252 assert_eq!(Mutation::OtherEnd.encode(), "end");
2253 }
2254
2255 fn candidate_mutations(op: CmpOp) -> Vec<Mutation> {
2256 let mut ms = vec![
2257 Mutation::Const(true),
2258 Mutation::Const(false),
2259 Mutation::Negate,
2260 ];
2261 ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
2262 if op.is_ordering() {
2263 ms.extend((-5..=5).filter(|s| *s != 0).map(Mutation::Shift));
2264 }
2265 ms
2266 }
2267
2268 fn check_plan(op: CmpOp, ds: &[i128], domain: Option<(i128, i128)>) {
2270 let obs = obs_of(ds);
2271 let ctx = format!("{op:?} ds={ds:?} domain={domain:?}");
2272 let (dom_lo, dom_hi) = domain.unwrap_or((-50, 50));
2273 let differs_somewhere =
2274 |m: Mutation| (dom_lo..=dom_hi).any(|d| op.eval_d(d) != eval_mutated_d(op, m, d));
2275
2276 for m in candidate_mutations(op) {
2277 assert_eq!(
2278 infects(op, m, &obs),
2279 brute_infects(op, m, ds),
2280 "infects {m:?} {ctx}"
2281 );
2282 }
2283
2284 let plan = plan_cmp(op, &obs, domain);
2285 for m in &plan.run {
2286 assert!(
2287 brute_infects(op, *m, ds),
2288 "run {m:?} must be infected: {ctx}"
2289 );
2290 assert!(differs_somewhere(*m), "run {m:?} is equivalent: {ctx}");
2291 }
2292 match &plan.gap {
2293 None => {}
2294 Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2295 Some(InputGap::OneSided { always }) => {
2296 assert!(ds.iter().all(|d| op.eval_d(*d) == *always), "{ctx}");
2297 assert!(differs_somewhere(Mutation::Const(*always)), "{ctx}");
2298 }
2299 Some(InputGap::Boundary {
2300 min_shift,
2301 max_shift,
2302 missing,
2303 same: _,
2304 }) => {
2305 assert!(*min_shift <= 0 && 0 <= *max_shift, "{ctx}");
2306 for s in (*min_shift..=*max_shift).filter(|s| *s != 0) {
2307 let m = Mutation::Shift(s);
2308 assert!(
2309 !brute_infects(op, m, ds),
2310 "survivor {m:?} is infected: {ctx}"
2311 );
2312 assert!(differs_somewhere(m), "survivor {m:?} is equivalent: {ctx}");
2313 }
2314 if domain.is_none() {
2315 for s in [min_shift - 1, max_shift + 1] {
2317 assert!(
2318 brute_infects(op, Mutation::Shift(s), ds),
2319 "range not maximal: {ctx}"
2320 );
2321 }
2322 }
2323 assert!(!missing.is_empty(), "{ctx}");
2324 for w in missing {
2325 assert!(!ds.contains(w), "missing value {w} was observed: {ctx}");
2326 assert!(
2327 dom_lo <= *w && *w <= dom_hi,
2328 "missing value {w} out of domain: {ctx}"
2329 );
2330 let s = if op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(1), *w) {
2331 1
2332 } else {
2333 -1
2334 };
2335 assert!(
2336 op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(s), *w),
2337 "missing value {w} separates nothing: {ctx}"
2338 );
2339 assert!(*min_shift <= s && s <= *max_shift, "{ctx}");
2340 }
2341 }
2342 Some(InputGap::EqualNeverObserved { .. }) => panic!("valued site: {ctx}"),
2343 }
2344 if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2345 assert!(
2346 !brute_infects(op, m, ds),
2347 "representative {m:?} is infected: {ctx}"
2348 );
2349 }
2350
2351 if op.is_ordering() && ds.iter().any(|d| op.eval_d(*d)) && ds.iter().any(|d| !op.eval_d(*d))
2353 {
2354 for s in [-1, 1] {
2355 let m = Mutation::Shift(s);
2356 let survivor = matches!(&plan.gap, Some(InputGap::Boundary { min_shift, max_shift, .. })
2357 if *min_shift <= s && s <= *max_shift);
2358 let ran = plan.run.contains(&m);
2359 assert!(
2360 survivor ^ ran || !differs_somewhere(m),
2361 "Shift({s}) unaccounted for: survivor={survivor} ran={ran} {ctx}"
2362 );
2363 }
2364 }
2365 }
2366
2367 #[test]
2368 fn exhaustive_small_observation_sets() {
2369 let universe: Vec<i128> = (-3..=3).collect();
2370 for op in CmpOp::ALL {
2371 for mask in 0u32..(1 << universe.len()) {
2372 let ds: Vec<i128> = universe
2373 .iter()
2374 .enumerate()
2375 .filter_map(|(i, d)| (mask & (1 << i) != 0).then_some(*d))
2376 .collect();
2377 check_plan(op, &ds, None);
2378 for (lo, hi) in [(0, 10), (-10, 0), (-2, 2), (1, 9), (-9, -1)] {
2380 if ds.iter().all(|d| lo <= *d && *d <= hi) {
2381 check_plan(op, &ds, Some((lo, hi)));
2382 }
2383 }
2384 }
2385 }
2386 }
2387
2388 #[test]
2390 fn pict_table() {
2391 let table = include_str!("../tests/data/planner.pict.tsv");
2392 let mut rows = 0;
2393 for line in table.lines().skip(1) {
2394 let cols: Vec<&str> = line.split('\t').collect();
2395 let [op, below, equal, above, valued, literal, domain] = cols[..] else {
2396 panic!("bad row: {line}");
2397 };
2398 let op = match op {
2399 "lt" => CmpOp::Lt,
2400 "le" => CmpOp::Le,
2401 "gt" => CmpOp::Gt,
2402 "ge" => CmpOp::Ge,
2403 "eq" => CmpOp::Eq,
2404 "ne" => CmpOp::Ne,
2405 other => panic!("op {other}"),
2406 };
2407 let mut ds: Vec<i128> = vec![];
2408 match below {
2409 "none" => {}
2410 "adjacent" => ds.extend([-1, -4]),
2411 "far" => ds.extend([-3, -6]),
2412 other => panic!("below {other}"),
2413 }
2414 if equal == "yes" {
2415 ds.push(0);
2416 }
2417 match above {
2418 "none" => {}
2419 "adjacent" => ds.extend([1, 5]),
2420 "far" => ds.extend([3, 7]),
2421 other => panic!("above {other}"),
2422 }
2423 rows += 1;
2424 if valued == "no" {
2425 let mut obs = Obs::default();
2426 for d in &ds {
2427 obs.merge(&Obs::of_rel(rel_of(*d)));
2428 }
2429 check_unvalued(op, &obs, &ds, line);
2430 continue;
2431 }
2432 let domain = match (literal, domain) {
2435 ("none", _) => None,
2436 (_, "wide") => Some((-40, 40)),
2437 ("rhs", "tight_low") | ("lhs", "tight_high") => Some((0, 40)),
2438 ("rhs", "tight_high") | ("lhs", "tight_low") => Some((-40, 0)),
2439 other => panic!("domain {other:?}"),
2440 };
2441 check_plan(op, &ds, domain);
2442 }
2443 assert_eq!(rows, table.lines().count() - 1);
2444 assert!(rows > 50, "the PICT table looks truncated: {rows} rows");
2445 }
2446
2447 fn check_unvalued(op: CmpOp, obs: &Obs, ds: &[i128], ctx: &str) {
2448 let plan = plan_cmp(op, obs, None);
2449 for m in [
2450 Mutation::Const(true),
2451 Mutation::Const(false),
2452 Mutation::Negate,
2453 ]
2454 .into_iter()
2455 .chain(CmpOp::ALL.into_iter().map(Mutation::Op))
2456 {
2457 assert_eq!(
2458 infects(op, m, obs),
2459 brute_infects(op, m, ds),
2460 "infects {m:?} {ctx}"
2461 );
2462 }
2463 for m in &plan.run {
2464 assert!(
2465 brute_infects(op, *m, ds),
2466 "run {m:?} must be infected: {ctx}"
2467 );
2468 }
2469 if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2470 assert!(
2471 !brute_infects(op, m, ds),
2472 "representative {m:?} is infected: {ctx}"
2473 );
2474 }
2475 match &plan.gap {
2476 Some(InputGap::Boundary { .. }) => panic!("unvalued site cannot shift: {ctx}"),
2477 Some(InputGap::EqualNeverObserved { flipped, .. }) => {
2478 assert!(!ds.contains(&0), "{ctx}");
2479 assert_eq!(op.flip_eq(), Some(*flipped), "{ctx}");
2480 }
2481 Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2482 _ => {}
2483 }
2484 if op.is_ordering() && obs.reached() {
2486 assert!(infects(op, Mutation::Shift(1), obs), "{ctx}");
2487 }
2488 }
2489
2490 #[test]
2491 fn logic_swap_never_changes_value_matches_pict_table() {
2492 let table = include_str!("../tests/data/logic-swap.pict.tsv");
2493 let mut rows = 0;
2494 for line in table.lines().skip(1).filter(|l| !l.trim().is_empty()) {
2495 let cols: Vec<&str> = line.split('\t').collect();
2496 assert_eq!(cols.len(), 5, "unexpected row: {line}");
2497 let and = match cols[0] {
2498 "and" => true,
2499 "or" => false,
2500 other => panic!("unexpected LogicOp: {other}"),
2501 };
2502 let obs = LogicObs {
2503 short: cols[1] == "true",
2504 rhs_true: cols[2] == "true",
2505 rhs_false: cols[3] == "true",
2506 rhs_started: cols[4] == "true",
2507 };
2508 let expected = if and {
2509 !obs.short && obs.rhs_true && !obs.rhs_false
2510 } else {
2511 !obs.short && !obs.rhs_true && obs.rhs_false
2512 };
2513 assert_eq!(
2514 obs.swap_never_changes_value(and),
2515 expected,
2516 "row={line} obs={obs:?}"
2517 );
2518 rows += 1;
2519 }
2520 assert!(rows >= 9, "expected PICT table rows, got {rows}");
2521 }
2522
2523 #[test]
2524 fn truth_mask_matches_all_operators_and_relations() {
2525 let expected = [
2526 (CmpOp::Lt, [true, false, false, false]),
2527 (CmpOp::Le, [true, true, false, false]),
2528 (CmpOp::Gt, [false, false, true, false]),
2529 (CmpOp::Ge, [false, true, true, false]),
2530 (CmpOp::Eq, [false, true, false, false]),
2531 (CmpOp::Ne, [true, false, true, true]),
2532 ];
2533 let rels = [
2534 (1u8, Rel::Less),
2535 (2u8, Rel::Equal),
2536 (4u8, Rel::Greater),
2537 (8u8, Rel::Unordered),
2538 ];
2539 for (op, table) in expected {
2540 for (idx, (bit, rel)) in rels.into_iter().enumerate() {
2541 assert_eq!(op.truth_mask() & bit != 0, table[idx], "{op:?} {rel:?}");
2542 assert_eq!(op.eval_rel(rel), table[idx], "{op:?} {rel:?}");
2543 }
2544 }
2545 }
2546
2547 #[test]
2548 fn domain_equivalent_matches_exhaustive_evaluation() {
2549 let mutations = [
2550 Mutation::Const(false),
2551 Mutation::Const(true),
2552 Mutation::Negate,
2553 Mutation::Shift(-1),
2554 Mutation::Shift(1),
2555 Mutation::Op(CmpOp::Lt),
2556 Mutation::Op(CmpOp::Le),
2557 Mutation::Op(CmpOp::Gt),
2558 Mutation::Op(CmpOp::Ge),
2559 Mutation::Op(CmpOp::Eq),
2560 Mutation::Op(CmpOp::Ne),
2561 ];
2562 let domains = [
2563 (0i128, 255),
2564 (-255, 0),
2565 (-128, 127),
2566 (1, 10),
2567 (-10, -1),
2568 (0, 0),
2569 (-1, 1),
2570 (-5, -3),
2571 (3, 5),
2572 ];
2573 for op in CmpOp::ALL {
2574 for &(lo, hi) in &domains {
2575 for zero_unreachable in [false, true] {
2576 for &m1 in &mutations {
2577 for &m2 in &mutations {
2578 let brute = (lo..=hi)
2579 .filter(|&d| !(zero_unreachable && d == 0))
2580 .all(|d| eval_mutated_d(op, m1, d) == eval_mutated_d(op, m2, d));
2581 assert_eq!(
2582 domain_equivalent(op, m1, m2, (lo, hi), zero_unreachable),
2583 brute,
2584 "{op:?} {m1:?} vs {m2:?} on [{lo}, {hi}] zero_unreachable={zero_unreachable}"
2585 );
2586 }
2587 }
2588 }
2589 }
2590 }
2591 assert!(domain_equivalent(
2592 CmpOp::Gt,
2593 Mutation::Negate,
2594 Mutation::Op(CmpOp::Eq),
2595 (0, u64::MAX as i128),
2596 false,
2597 ));
2598 assert!(domain_equivalent(
2599 CmpOp::Lt,
2600 Mutation::Negate,
2601 Mutation::Op(CmpOp::Gt),
2602 (-100, 100),
2603 true,
2604 ));
2605 assert!(!domain_equivalent(
2606 CmpOp::Gt,
2607 Mutation::Shift(2),
2608 Mutation::Shift(2),
2609 (0, 10),
2610 false,
2611 ));
2612 assert!(!domain_equivalent(
2614 CmpOp::Gt,
2615 Mutation::Shift(-1),
2616 Mutation::Const(true),
2617 (0, i128::MAX),
2618 false,
2619 ));
2620 assert!(!domain_equivalent(
2621 CmpOp::Lt,
2622 Mutation::Shift(1),
2623 Mutation::Const(true),
2624 (i128::MIN, 0),
2625 false,
2626 ));
2627 }
2628}