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