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 pub fn eval_rel(self, rel: Rel) -> bool {
72 match (self, rel) {
73 (CmpOp::Ne, Rel::Unordered) => true,
74 (_, Rel::Unordered) => false,
75 (CmpOp::Lt, r) => r == Rel::Less,
76 (CmpOp::Le, r) => r != Rel::Greater,
77 (CmpOp::Gt, r) => r == Rel::Greater,
78 (CmpOp::Ge, r) => r != Rel::Less,
79 (CmpOp::Eq, r) => r == Rel::Equal,
80 (CmpOp::Ne, r) => r != Rel::Equal,
81 }
82 }
83
84 pub fn eval_d(self, d: i128) -> bool {
86 self.eval_rel(match d {
87 d if d < 0 => Rel::Less,
88 0 => Rel::Equal,
89 _ => Rel::Greater,
90 })
91 }
92
93 pub fn mistaken_for(self) -> &'static [CmpOp] {
95 match self {
96 CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt],
97 CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt],
98 _ => &[],
99 }
100 }
101
102 pub fn negated(self) -> CmpOp {
103 match self {
104 CmpOp::Lt => CmpOp::Ge,
105 CmpOp::Le => CmpOp::Gt,
106 CmpOp::Gt => CmpOp::Le,
107 CmpOp::Ge => CmpOp::Lt,
108 CmpOp::Eq => CmpOp::Ne,
109 CmpOp::Ne => CmpOp::Eq,
110 }
111 }
112
113 pub fn flip_eq(self) -> Option<CmpOp> {
115 match self {
116 CmpOp::Lt => Some(CmpOp::Le),
117 CmpOp::Le => Some(CmpOp::Lt),
118 CmpOp::Gt => Some(CmpOp::Ge),
119 CmpOp::Ge => Some(CmpOp::Gt),
120 CmpOp::Eq | CmpOp::Ne => None,
121 }
122 }
123
124 fn threshold(self) -> Option<(bool, i128)> {
127 match self {
128 CmpOp::Ge => Some((true, 0)),
129 CmpOp::Gt => Some((true, 1)),
130 CmpOp::Le => Some((false, 0)),
131 CmpOp::Lt => Some((false, -1)),
132 CmpOp::Eq | CmpOp::Ne => None,
133 }
134 }
135}
136
137#[derive(Clone, Copy, PartialEq, Debug, Default)]
140pub struct Obs {
141 pub lt: bool,
142 pub eq: bool,
143 pub gt: bool,
144 pub un: bool,
145 pub unvalued: bool,
147 pub max_neg: Option<i128>,
149 pub min_pos: Option<i128>,
151 pub unfloat: bool,
153 pub f_max_neg: Option<f64>,
155 pub f_min_pos: Option<f64>,
156}
157
158impl Obs {
159 pub fn reached(&self) -> bool {
160 self.lt || self.eq || self.gt || self.un
161 }
162
163 pub fn valued(&self) -> bool {
164 self.reached() && !self.unvalued
165 }
166
167 pub fn merge(&mut self, other: &Obs) {
168 self.lt |= other.lt;
169 self.eq |= other.eq;
170 self.gt |= other.gt;
171 self.un |= other.un;
172 self.unvalued |= other.unvalued;
173 self.max_neg = match (self.max_neg, other.max_neg) {
174 (Some(a), Some(b)) => Some(a.max(b)),
175 (a, b) => a.or(b),
176 };
177 self.min_pos = match (self.min_pos, other.min_pos) {
178 (Some(a), Some(b)) => Some(a.min(b)),
179 (a, b) => a.or(b),
180 };
181 self.unfloat |= other.unfloat;
182 self.f_max_neg = match (self.f_max_neg, other.f_max_neg) {
183 (Some(a), Some(b)) => Some(a.max(b)),
184 (a, b) => a.or(b),
185 };
186 self.f_min_pos = match (self.f_min_pos, other.f_min_pos) {
187 (Some(a), Some(b)) => Some(a.min(b)),
188 (a, b) => a.or(b),
189 };
190 }
191
192 pub fn of_d(d: i128) -> Obs {
194 Obs {
195 lt: d < 0,
196 eq: d == 0,
197 gt: d > 0,
198 max_neg: (d < 0).then_some(d),
199 min_pos: (d > 0).then_some(d),
200 unfloat: true,
201 ..Obs::default()
202 }
203 }
204
205 pub fn of_rel(rel: Rel) -> Obs {
207 Obs {
208 lt: rel == Rel::Less,
209 eq: rel == Rel::Equal,
210 gt: rel == Rel::Greater,
211 un: rel == Rel::Unordered,
212 unvalued: true,
213 unfloat: true,
214 ..Obs::default()
215 }
216 }
217
218 pub fn of_f(d: f64) -> Obs {
220 Obs {
221 lt: d < 0.0,
222 eq: d == 0.0,
223 gt: d > 0.0,
224 unvalued: true,
225 f_max_neg: (d < 0.0).then_some(d),
226 f_min_pos: (d > 0.0).then_some(d),
227 ..Obs::default()
228 }
229 }
230
231 pub fn float_gap(&self) -> Option<(f64, f64)> {
234 if self.unfloat || self.un {
236 return None;
237 }
238 Some((self.f_max_neg?, self.f_min_pos?))
239 }
240
241 fn rels(&self) -> impl Iterator<Item = Rel> {
242 [
243 (self.lt, Rel::Less),
244 (self.eq, Rel::Equal),
245 (self.gt, Rel::Greater),
246 (self.un, Rel::Unordered),
247 ]
248 .into_iter()
249 .filter_map(|(seen, rel)| seen.then_some(rel))
250 }
251
252 fn saw(&self, d: i128) -> bool {
254 match d {
255 0 => self.eq,
256 -1 => self.max_neg == Some(-1),
257 1 => self.min_pos == Some(1),
258 _ => unreachable!("only the values next to zero can be answered from the summary"),
259 }
260 }
261
262 fn max_le(&self, x: i128) -> Option<i128> {
264 debug_assert!(x == -1 || x == 0);
265 if x == 0 && self.eq {
266 Some(0)
267 } else {
268 self.max_neg
269 }
270 }
271
272 fn min_ge(&self, x: i128) -> Option<i128> {
274 debug_assert!(x == 0 || x == 1);
275 if x == 0 && self.eq {
276 Some(0)
277 } else {
278 self.min_pos
279 }
280 }
281
282 fn saw_any_in(&self, lo: i128, hi: i128) -> bool {
285 if lo > hi {
286 return false;
287 }
288 debug_assert!(
289 lo <= 1 && hi >= -1,
290 "interval {lo}..={hi} is not anchored at zero"
291 );
292 let zero = self.eq && lo <= 0 && 0 <= hi;
293 let neg = lo <= -1 && self.max_neg.is_some_and(|m| m >= lo);
294 let pos = hi >= 1 && self.min_pos.is_some_and(|p| p <= hi);
295 zero || neg || pos
296 }
297}
298
299#[derive(Clone, Copy, PartialEq, Debug, Serialize)]
300#[serde(rename_all = "snake_case")]
301pub enum Mutation {
302 Const(bool),
304 Negate,
306 Op(CmpOp),
308 Shift(i128),
310 ShiftF(f64),
312 Delete,
314 LogicSwap,
316 LogicDropRhs,
318 LogicDropLhs,
320 ArithSwap,
322 ArithSwap2,
325 DropNot,
327 RangeEnd,
329 MinMax,
331 OtherEnd,
333 StrContains,
335 StrReplaceMultiplicity,
337 ClampDropLower,
339 ClampDropUpper,
341 RoundAlt1,
343 RoundAlt2,
345 QuantifierSwap,
347}
348
349impl Mutation {
350 pub fn encode(&self) -> String {
352 match self {
353 Mutation::Const(c) => format!("c{}", *c as u8),
354 Mutation::Negate => "neg".to_string(),
355 Mutation::Op(op) => format!("op{}", op.code()),
356 Mutation::Shift(d) => format!("sh{d}"),
357 Mutation::ShiftF(d) => format!("shf{d:?}"),
358 Mutation::Delete => "del".to_string(),
359 Mutation::LogicSwap => "lsw".to_string(),
360 Mutation::LogicDropRhs => "ldr".to_string(),
361 Mutation::LogicDropLhs => "ldl".to_string(),
362 Mutation::ArithSwap => "asw".to_string(),
363 Mutation::ArithSwap2 => "as2".to_string(),
364 Mutation::DropNot => "unn".to_string(),
365 Mutation::RangeEnd => "rng".to_string(),
366 Mutation::MinMax => "mmx".to_string(),
367 Mutation::OtherEnd => "end".to_string(),
368 Mutation::StrContains => "stc".to_string(),
369 Mutation::StrReplaceMultiplicity => "srp".to_string(),
370 Mutation::ClampDropLower => "cll".to_string(),
371 Mutation::ClampDropUpper => "clu".to_string(),
372 Mutation::RoundAlt1 => "rd1".to_string(),
373 Mutation::RoundAlt2 => "rd2".to_string(),
374 Mutation::QuantifierSwap => "qsw".to_string(),
375 }
376 }
377}
378
379pub fn eval_mutated_d(op: CmpOp, m: Mutation, d: i128) -> bool {
381 match m {
382 Mutation::Const(c) => c,
383 Mutation::Negate => !op.eval_d(d),
384 Mutation::Op(op2) => op2.eval_d(d),
385 Mutation::Shift(s) => op.eval_d(d - s),
386 _ => op.eval_d(d),
387 }
388}
389
390pub fn infects(op: CmpOp, m: Mutation, obs: &Obs) -> bool {
393 match m {
394 Mutation::Const(c) => obs.rels().any(|r| op.eval_rel(r) != c),
395 Mutation::Op(op2) => obs.rels().any(|r| op.eval_rel(r) != op2.eval_rel(r)),
396 Mutation::Shift(s) => {
397 let Some((lo, hi)) = shift_diff(op, s) else {
398 return false;
399 };
400 if !obs.valued() {
401 return obs.reached();
403 }
404 obs.saw_any_in(lo, hi)
405 }
406 Mutation::ShiftF(s) => match obs.float_gap() {
408 Some((lo, hi)) => !(lo < s && s < hi) || obs.eq,
409 None => obs.reached(),
410 },
411 _ => obs.reached(),
413 }
414}
415
416fn shift_diff(op: CmpOp, s: i128) -> Option<(i128, i128)> {
418 let (up, t0) = op.threshold()?;
419 let t = t0 + s;
420 let (a, b) = (t0.min(t), t0.max(t));
421 Some(if up { (a, b - 1) } else { (a + 1, b) })
424}
425
426#[derive(Clone, PartialEq, Debug, Serialize)]
429#[serde(rename_all = "snake_case", tag = "kind")]
430pub enum InputGap {
431 Unreached,
433 OneSided { always: bool },
435 Boundary {
438 min_shift: i128,
439 max_shift: i128,
440 missing: Vec<i128>,
441 #[serde(skip_serializing_if = "no_shift")]
445 same: (i128, i128),
446 },
447 EqualNeverObserved {
451 flipped: CmpOp,
452 float_gap: Option<(f64, f64)>,
453 },
454}
455
456fn no_shift(range: &(i128, i128)) -> bool {
457 *range == (0, 0)
458}
459
460#[derive(Clone, PartialEq, Debug, Default)]
461pub struct CmpPlan {
462 pub cannot_differ: bool,
465 pub gap: Option<InputGap>,
466 pub run: Vec<Mutation>,
469}
470
471impl InputGap {
472 pub fn representative(&self) -> Option<Mutation> {
474 match self {
475 InputGap::Unreached => None,
476 InputGap::OneSided { always } => Some(Mutation::Const(*always)),
477 InputGap::Boundary {
478 min_shift,
479 max_shift,
480 same,
481 ..
482 } => {
483 if *max_shift > same.1 {
485 Some(Mutation::Shift(same.1 + 1))
486 } else if *min_shift < same.0 {
487 Some(Mutation::Shift(same.0 - 1))
488 } else {
489 None
490 }
491 }
492 InputGap::EqualNeverObserved { flipped, .. } => Some(Mutation::Op(*flipped)),
493 }
494 }
495
496 pub fn survivors(&self) -> Vec<Mutation> {
498 match self {
499 InputGap::Boundary {
500 min_shift,
501 max_shift,
502 same,
503 ..
504 } => (1..=3)
505 .flat_map(|n| [same.1 + n, same.0 - n])
506 .filter(|s| min_shift <= s && s <= max_shift)
507 .take(3)
508 .map(Mutation::Shift)
509 .collect(),
510 InputGap::EqualNeverObserved { flipped, float_gap } => {
511 let mut all = vec![Mutation::Op(*flipped)];
512 if let Some((lo, hi)) = float_gap {
513 all.extend([Mutation::ShiftF(hi / 2.0), Mutation::ShiftF(lo / 2.0)]);
514 }
515 all
516 }
517 other => other.representative().into_iter().collect(),
518 }
519 }
520}
521
522pub fn plan_cmp(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
526 let mut plan = plan_boundary(op, obs, domain);
527 let answers =
535 |other: CmpOp| -> Vec<bool> { obs.rels().map(|rel| other.eval_rel(rel)).collect() };
536 for other in op.mistaken_for() {
537 if answers(*other) != answers(op) {
538 plan.run.push(Mutation::Op(*other));
539 }
540 }
541 if matches!(op, CmpOp::Le | CmpOp::Ge) && !obs.valued() && answers(op.negated()) != answers(op)
547 {
548 plan.run.push(Mutation::Op(op.negated()));
549 }
550 plan
551}
552
553fn plan_boundary(op: CmpOp, obs: &Obs, domain: Option<(i128, i128)>) -> CmpPlan {
554 if !obs.reached() {
555 return CmpPlan {
556 cannot_differ: false,
557 gap: Some(InputGap::Unreached),
558 run: vec![],
559 };
560 }
561 let saw_true = obs.rels().any(|r| op.eval_rel(r));
562 let saw_false = obs.rels().any(|r| !op.eval_rel(r));
563 if !(saw_true && saw_false) {
564 let always = saw_true;
565 let other_possible = match domain {
567 Some((lo, hi)) if obs.valued() => [-1, 0, 1]
570 .into_iter()
571 .any(|d| lo <= d && d <= hi && op.eval_d(d) != always),
572 _ => true,
573 };
574 return CmpPlan {
575 cannot_differ: !other_possible,
576 gap: other_possible.then_some(InputGap::OneSided { always }),
577 run: vec![Mutation::Negate],
578 };
579 }
580
581 let Some((up, t0)) = op.threshold() else {
582 return CmpPlan {
584 cannot_differ: false,
585 gap: None,
586 run: vec![Mutation::Negate],
587 };
588 };
589
590 if !obs.valued() {
591 let flipped = op
592 .flip_eq()
593 .expect("ordering operators have a flipped form");
594 return if obs.eq {
595 CmpPlan {
596 cannot_differ: false,
597 gap: None,
598 run: vec![Mutation::Op(flipped), Mutation::Negate],
599 }
600 } else {
601 CmpPlan {
602 cannot_differ: false,
603 gap: Some(InputGap::EqualNeverObserved {
604 flipped,
605 float_gap: obs.float_gap(),
606 }),
607 run: vec![Mutation::Negate],
608 }
609 };
610 }
611
612 let (below, above, w_minus, w_plus) = if up {
615 (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
616 } else {
617 (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
618 };
619 let below = below.expect("both outcomes were observed");
620 let above = above.expect("both outcomes were observed");
621 let (min_shift, max_shift) = if up {
622 (below + 1 - t0, above - t0)
623 } else {
624 (below - t0, above - 1 - t0)
625 };
626
627 let mut missing = vec![];
630 let mut run = vec![];
631 for (w, shift) in [(w_minus, -1), (w_plus, 1)] {
632 if obs.saw(w) {
633 run.push(Mutation::Shift(shift));
634 } else {
635 missing.push(w);
636 }
637 }
638 run.push(Mutation::Negate);
639 let gap = (!missing.is_empty()).then_some(InputGap::Boundary {
640 min_shift,
641 max_shift,
642 missing,
643 same: (0, 0),
644 });
645 CmpPlan {
646 cannot_differ: false,
647 gap,
648 run,
649 }
650}
651
652#[derive(Clone, Copy, PartialEq, Eq, Debug)]
655pub enum Reach {
656 Multiples(i128),
658 Bits(i128),
660 Below(i128),
662}
663
664impl Reach {
665 pub fn holds(self, value: i128) -> bool {
666 match self {
667 Reach::Multiples(step) => value % step == 0,
668 Reach::Bits(mask) => value >= 0 && value & !mask == 0,
669 Reach::Below(limit) => -limit < value && value < limit,
670 }
671 }
672
673 pub fn of_shift(bits: u32, (low, high): (i128, i128)) -> Option<Reach> {
678 let values = high.checked_sub(low)?.checked_add(1)?;
679 if values < 2 || values & (values - 1) != 0 {
680 return None;
681 }
682 let effective = bits % values.trailing_zeros();
683 (effective > 0).then(|| Reach::Multiples(1 << effective))
684 }
685
686 pub fn within(self, low: i128, high: i128) -> Option<(i128, i128)> {
689 let least = if self.holds(low) {
690 low
691 } else {
692 self.next_above(low)?
693 };
694 let greatest = if self.holds(high) {
695 high
696 } else {
697 self.next_below(high)?
698 };
699 (least <= greatest).then_some((least, greatest))
700 }
701
702 pub fn interval(self) -> Option<(i128, i128)> {
704 match self {
705 Reach::Multiples(_) => None,
706 Reach::Bits(mask) => Some((0, mask)),
707 Reach::Below(limit) => Some((1 - limit, limit - 1)),
708 }
709 }
710
711 fn next_above(self, value: i128) -> Option<i128> {
713 match self {
714 Reach::Multiples(step) => value.div_euclid(step).checked_add(1)?.checked_mul(step),
715 Reach::Bits(_) if value < 0 => Some(0),
716 Reach::Bits(mask) => {
717 let over = value.checked_add(1)?;
718 let outside = over & !mask;
719 if outside == 0 {
720 return Some(over);
721 }
722 let top = 127 - outside.leading_zeros();
726 let low = 1_i128.checked_shl(top + 1)?.checked_sub(1)?;
727 let next = (over | !mask | low).wrapping_add(1) & mask;
728 (next > value).then_some(next)
729 }
730 Reach::Below(limit) => {
731 let next = value.checked_add(1)?.max(1 - limit);
732 (next < limit).then_some(next)
733 }
734 }
735 }
736
737 fn next_below(self, value: i128) -> Option<i128> {
739 match self {
740 Reach::Multiples(step) => value.checked_sub(1)?.div_euclid(step).checked_mul(step),
741 Reach::Bits(_) if value <= 0 => None,
742 Reach::Bits(mask) => {
743 let under = value - 1;
744 let outside = under & !mask;
745 Some(if outside == 0 {
746 under
747 } else {
748 let top = 127 - outside.leading_zeros();
750 let low = (1_i128 << top) - 1;
751 (under & !low & !(1_i128 << top)) | (mask & low)
752 })
753 }
754 Reach::Below(limit) => {
755 let next = value.checked_sub(1)?.min(limit - 1);
756 (next > -limit).then_some(next)
757 }
758 }
759 }
760}
761
762pub fn within_reach(
767 gap: InputGap,
768 op: CmpOp,
769 obs: &Obs,
770 reach: Reach,
771 literal: i128,
772 literal_is_rhs: bool,
773) -> Option<InputGap> {
774 let InputGap::Boundary {
775 min_shift,
776 max_shift,
777 missing,
778 same,
779 } = gap
780 else {
781 return Some(gap);
782 };
783 let Some((up, t0)) = op.threshold() else {
784 return Some(InputGap::Boundary {
785 min_shift,
786 max_shift,
787 missing,
788 same,
789 });
790 };
791 let (below, above, w_minus, w_plus) = if up {
794 (obs.max_le(t0 - 1), obs.min_ge(t0), t0 - 1, t0)
795 } else {
796 (obs.max_le(t0), obs.min_ge(t0 + 1), t0, t0 + 1)
797 };
798 let (below, above) = (below?, above?);
799 let value = |d: i128| {
801 if literal_is_rhs {
802 literal.checked_add(d)
803 } else {
804 literal.checked_sub(d)
805 }
806 };
807 let difference = |v: i128| {
808 if literal_is_rhs {
809 v.checked_sub(literal)
810 } else {
811 literal.checked_sub(v)
812 }
813 };
814 let nearest = |start: i128, bound: i128| -> Option<i128> {
817 if (start < bound) != (start <= bound) || start == bound {
818 return None;
819 }
820 let (from, to) = (value(start)?, value(bound)?);
821 let found = if reach.holds(from) {
822 from
823 } else if to > from {
824 reach.next_above(from)?
825 } else {
826 reach.next_below(from)?
827 };
828 let inside = if to > from { found < to } else { found > to };
829 inside.then(|| difference(found)).flatten()
830 };
831 let down = nearest(w_minus, below);
832 let up_side = nearest(w_plus, above);
833 let missing: Vec<i128> = [(w_minus, down), (w_plus, up_side)]
834 .into_iter()
835 .filter(|(w, _)| missing.contains(w))
836 .filter_map(|(_, nearest)| nearest)
837 .collect();
838 if missing.is_empty() {
839 return None;
840 }
841 let (first_under, first_over) = (down.unwrap_or(below), up_side.unwrap_or(above));
845 let same = if up {
846 (first_under - t0 + 1, first_over - t0)
847 } else {
848 (first_under - t0, first_over - t0 - 1)
849 };
850 Some(InputGap::Boundary {
851 min_shift,
852 max_shift,
853 missing,
854 same: (same.0.max(min_shift).min(0), same.1.min(max_shift).max(0)),
855 })
856}
857
858#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
860pub struct LogicObs {
861 pub short: bool,
863 pub rhs_true: bool,
864 pub rhs_false: bool,
865 pub rhs_started: bool,
868}
869
870impl LogicObs {
871 pub fn from_bits(bits: u8) -> LogicObs {
872 LogicObs {
873 short: bits & 1 != 0,
874 rhs_true: bits & 2 != 0,
875 rhs_false: bits & 4 != 0,
876 rhs_started: bits & 8 != 0,
877 }
878 }
879
880 pub fn merge(&mut self, other: &LogicObs) {
881 self.short |= other.short;
882 self.rhs_true |= other.rhs_true;
883 self.rhs_false |= other.rhs_false;
884 self.rhs_started |= other.rhs_started;
885 }
886
887 pub fn reached(&self) -> bool {
888 self.short || self.rhs_true || self.rhs_false || self.rhs_started
889 }
890
891 pub fn constant_value(&self, and: bool) -> Option<bool> {
893 let saw_true = self.rhs_true || (self.short && !and);
895 let saw_false = self.rhs_false || (self.short && and);
896 match (saw_true, saw_false) {
897 (true, false) => Some(true),
898 (false, true) => Some(false),
899 _ => None,
900 }
901 }
902
903 fn rhs_decided(&self, and: bool) -> bool {
905 if and { self.rhs_false } else { self.rhs_true }
906 }
907}
908
909#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
910#[serde(rename_all = "snake_case")]
911pub enum LogicGap {
912 Unreached,
913 RhsNeverDecides,
915 LhsNeverDecides,
917}
918
919#[derive(Clone, PartialEq, Debug, Default)]
920pub struct LogicPlan {
921 pub gaps: Vec<LogicGap>,
922 pub run: Vec<Mutation>,
923}
924
925pub fn logic_infects(and: bool, m: Mutation, obs: &LogicObs) -> bool {
929 match m {
930 Mutation::LogicDropRhs => obs.rhs_decided(and),
931 Mutation::LogicDropLhs => obs.short,
932 _ => obs.reached(),
933 }
934}
935
936pub fn plan_logic(and: bool, obs: &LogicObs) -> LogicPlan {
937 if !obs.reached() {
938 return LogicPlan {
939 gaps: vec![LogicGap::Unreached],
940 run: vec![],
941 };
942 }
943 let mut plan = LogicPlan::default();
944 for (m, gap) in [
945 (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
946 (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
947 ] {
948 if logic_infects(and, m, obs) {
949 plan.run.push(m);
950 } else {
951 plan.gaps.push(gap);
952 }
953 }
954 plan.run.push(Mutation::LogicSwap);
955 plan
956}
957
958#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
960pub struct ArithObs {
961 pub same: bool,
963 pub differs: bool,
965 pub opaque: bool,
967 pub same2: bool,
969 pub differs2: bool,
970}
971
972impl ArithObs {
973 pub fn from_bits(bits: u8) -> ArithObs {
974 ArithObs {
975 same: bits & 1 != 0,
976 differs: bits & 2 != 0,
977 opaque: bits & 4 != 0,
978 same2: bits & 8 != 0,
979 differs2: bits & 16 != 0,
980 }
981 }
982
983 pub fn merge(&mut self, other: &ArithObs) {
984 self.same |= other.same;
985 self.differs |= other.differs;
986 self.opaque |= other.opaque;
987 self.same2 |= other.same2;
988 self.differs2 |= other.differs2;
989 }
990
991 pub fn second(&self) -> ArithObs {
993 ArithObs {
994 same: self.same2,
995 differs: self.differs2,
996 opaque: self.opaque,
997 same2: false,
998 differs2: false,
999 }
1000 }
1001
1002 pub fn infected_by(&self, m: Mutation) -> bool {
1004 if matches!(
1005 m,
1006 Mutation::ArithSwap2 | Mutation::ClampDropUpper | Mutation::RoundAlt2
1007 ) {
1008 self.differs2
1009 } else {
1010 self.differs
1011 }
1012 }
1013}
1014
1015#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1016pub enum ArithPlan {
1017 Unreached,
1018 Opaque,
1020 NeverDiffers,
1022 Run,
1024}
1025
1026pub fn plan_arith(obs: &ArithObs) -> ArithPlan {
1027 if obs.differs {
1028 ArithPlan::Run
1029 } else if obs.same {
1030 ArithPlan::NeverDiffers
1031 } else if obs.opaque {
1032 ArithPlan::Opaque
1033 } else {
1034 ArithPlan::Unreached
1035 }
1036}
1037
1038#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1040pub struct ReturnObs {
1041 pub saw_true: bool,
1042 pub saw_false: bool,
1043}
1044
1045impl ReturnObs {
1046 pub fn from_bits(bits: u8) -> ReturnObs {
1047 ReturnObs {
1048 saw_true: bits & 1 != 0,
1049 saw_false: bits & 2 != 0,
1050 }
1051 }
1052
1053 pub fn merge(&mut self, other: &ReturnObs) {
1054 self.saw_true |= other.saw_true;
1055 self.saw_false |= other.saw_false;
1056 }
1057
1058 pub fn reached(&self) -> bool {
1059 self.saw_true || self.saw_false
1060 }
1061
1062 pub fn infected_by_const(&self, value: bool) -> bool {
1064 if value { self.saw_false } else { self.saw_true }
1065 }
1066}
1067
1068#[derive(Clone, PartialEq, Debug, Default)]
1069pub struct ReturnPlan {
1070 pub unreached: bool,
1071 pub always: Option<bool>,
1073 pub run: Vec<Mutation>,
1074}
1075
1076pub fn plan_option_return(obs: &ReturnObs) -> ReturnPlan {
1079 match (obs.saw_true, obs.saw_false) {
1080 (false, false) => ReturnPlan {
1081 unreached: true,
1082 ..ReturnPlan::default()
1083 },
1084 (false, true) => ReturnPlan {
1086 unreached: false,
1087 always: Some(false),
1088 run: vec![],
1089 },
1090 (true, _) => ReturnPlan {
1091 unreached: false,
1092 always: None,
1093 run: vec![Mutation::Const(false)],
1094 },
1095 }
1096}
1097
1098pub fn plan_return(obs: &ReturnObs) -> ReturnPlan {
1099 match (obs.saw_true, obs.saw_false) {
1100 (false, false) => ReturnPlan {
1101 unreached: true,
1102 ..ReturnPlan::default()
1103 },
1104 (true, true) => ReturnPlan {
1105 run: vec![Mutation::Const(true), Mutation::Const(false)],
1106 ..ReturnPlan::default()
1107 },
1108 (always, _) => ReturnPlan {
1109 unreached: false,
1110 always: Some(always),
1111 run: vec![Mutation::Const(!always)],
1112 },
1113 }
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118 use super::*;
1119
1120 const REACHES: [Reach; 5] = [
1121 Reach::Multiples(4),
1122 Reach::Multiples(8),
1123 Reach::Bits(0b1010),
1124 Reach::Bits(0b0110),
1125 Reach::Below(5),
1126 ];
1127
1128 #[test]
1129 fn the_next_value_an_expression_can_be() {
1130 for reach in REACHES {
1131 for value in -40..=40_i128 {
1132 let above = (value + 1..=80).find(|v| reach.holds(*v));
1133 let below = (-80..value).rev().find(|v| reach.holds(*v));
1134 assert_eq!(reach.next_above(value), above, "{reach:?} above {value}");
1135 assert_eq!(reach.next_below(value), below, "{reach:?} below {value}");
1136 }
1137 }
1138 assert_eq!(Reach::Multiples(8).next_above(i128::MAX), None);
1140 assert_eq!(Reach::Multiples(8).next_below(i128::MIN), None);
1141 assert_eq!(Reach::Below(5).next_above(i128::MAX), None);
1142 assert_eq!(Reach::Below(5).next_below(i128::MIN), None);
1143 assert_eq!(Reach::Bits(i128::MAX).next_above(i128::MAX), None);
1144 assert!(Reach::Bits(0xF0).holds(0x30) && !Reach::Bits(0xF0).holds(0x31));
1145 assert!(!Reach::Bits(0xF0).holds(-16));
1146 }
1147
1148 #[test]
1152 fn a_gap_is_kept_only_for_values_the_expression_can_be() {
1153 let mut dropped = 0;
1154 let mut kept = 0;
1155 for reach in REACHES {
1156 let can_be: Vec<i128> = (-24..=24).filter(|v| reach.holds(*v)).collect();
1157 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1158 for literal in -6..=14_i128 {
1159 for literal_is_rhs in [true, false] {
1160 let d_of = |v: i128| {
1161 if literal_is_rhs {
1162 v - literal
1163 } else {
1164 literal - v
1165 }
1166 };
1167 for &low in &can_be {
1168 for &high in can_be.iter().filter(|v| **v > low) {
1169 let mut obs = Obs::of_d(d_of(low));
1170 obs.merge(&Obs::of_d(d_of(high)));
1171 let Some(gap @ InputGap::Boundary { .. }) =
1172 plan_boundary(op, &obs, None).gap
1173 else {
1174 continue;
1175 };
1176 let InputGap::Boundary {
1177 min_shift,
1178 max_shift,
1179 ..
1180 } = gap.clone()
1181 else {
1182 unreachable!()
1183 };
1184 let differs = |shift: i128, v: i128| {
1187 op.eval_d(d_of(v)) != op.eval_d(d_of(v) - shift)
1188 };
1189 let told_apart =
1190 |shift: i128| can_be.iter().any(|v| differs(shift, *v));
1191 let case = format!(
1192 "{reach:?} {op:?} literal {literal} rhs {literal_is_rhs}, saw {low} and {high}"
1193 );
1194 match within_reach(gap, op, &obs, reach, literal, literal_is_rhs) {
1195 None => {
1196 for shift in min_shift..=max_shift {
1198 assert!(!told_apart(shift), "{case}: shift {shift}");
1199 }
1200 dropped += 1;
1201 }
1202 Some(InputGap::Boundary {
1203 min_shift: least,
1204 max_shift: most,
1205 missing,
1206 same,
1207 }) => {
1208 assert!(!missing.is_empty(), "{case}");
1209 assert_eq!((least, most), (min_shift, max_shift), "{case}");
1210 for d in &missing {
1211 let v = if literal_is_rhs {
1212 literal + d
1213 } else {
1214 literal - d
1215 };
1216 assert!(reach.holds(v), "{case}: {v}");
1217 assert!(low < v && v < high, "{case}: {v}");
1218 }
1219 assert!(same.0 <= 0 && 0 <= same.1, "{case}: {same:?}");
1222 for shift in least..=most {
1223 assert_eq!(
1224 same.0 <= shift && shift <= same.1,
1225 !told_apart(shift),
1226 "{case}: shift {shift}, same {same:?}"
1227 );
1228 }
1229 let gap = InputGap::Boundary {
1232 min_shift: least,
1233 max_shift: most,
1234 missing: missing.clone(),
1235 same,
1236 };
1237 for mutation in gap.survivors() {
1238 let Mutation::Shift(shift) = mutation else {
1239 panic!("{case}: {mutation:?}")
1240 };
1241 assert!(told_apart(shift), "{case}: shift {shift}");
1242 }
1243 assert!(gap.representative().is_some(), "{case}");
1244 kept += 1;
1245 }
1246 Some(other) => panic!("{case}: {other:?}"),
1247 }
1248 }
1249 }
1250 }
1251 }
1252 }
1253 }
1254 assert!(
1255 dropped > 100 && kept > 1000,
1256 "{dropped} dropped, {kept} kept"
1257 );
1258 }
1259
1260 #[test]
1261 fn an_outcome_no_value_gives_is_not_asked_for() {
1262 for (reach, literal, op, differs) in [
1264 (Reach::Below(10), 10, CmpOp::Lt, false),
1265 (Reach::Below(10), 9, CmpOp::Lt, true),
1266 (Reach::Below(10), -10, CmpOp::Gt, false),
1267 (Reach::Bits(0xF0), 0xF0, CmpOp::Gt, false),
1268 (Reach::Bits(0xF0), 0xF0, CmpOp::Ge, true),
1269 (Reach::Bits(0xF0), 0, CmpOp::Lt, false),
1270 ] {
1271 let (lo, hi) = reach.interval().unwrap();
1272 assert!((lo..=hi).all(|v| !reach.holds(v) || (lo <= v && v <= hi)));
1273 assert!(reach.holds(lo) && reach.holds(hi), "{reach:?}");
1274 assert!(!reach.holds(lo - 1) && !reach.holds(hi + 1), "{reach:?}");
1275 let can_differ = (lo..=hi)
1276 .filter(|v| reach.holds(*v))
1277 .map(|v| op.eval_d(v - literal))
1278 .collect::<std::collections::BTreeSet<_>>()
1279 .len()
1280 == 2;
1281 assert_eq!(can_differ, differs, "{reach:?} {op:?} {literal}");
1282 let seen = (lo..=hi).find(|v| reach.holds(*v)).unwrap();
1284 let plan = plan_cmp(
1285 op,
1286 &Obs::of_d(seen - literal),
1287 Some((lo - literal, hi - literal)),
1288 );
1289 assert_eq!(plan.cannot_differ, !differs, "{reach:?} {op:?} {literal}");
1290 assert_eq!(plan.gap.is_some(), differs, "{reach:?} {op:?} {literal}");
1291 }
1292 assert_eq!(Reach::Multiples(8).interval(), None);
1293 }
1294
1295 #[test]
1296 fn a_shift_is_a_multiple_by_the_bits_that_are_shifted_in_fact() {
1297 let (byte, signed_byte) = ((0, 255), (-128, 127));
1298 for (bits, range, expected) in [
1299 (3, byte, Some(Reach::Multiples(8))),
1300 (7, byte, Some(Reach::Multiples(128))),
1301 (8, byte, None),
1303 (9, byte, Some(Reach::Multiples(2))),
1304 (16, byte, None),
1305 (9, signed_byte, Some(Reach::Multiples(2))),
1306 (33, (0, u32::MAX as i128), Some(Reach::Multiples(2))),
1307 (3, (0, u32::MAX as i128), Some(Reach::Multiples(8))),
1308 (3, (0, 9), None),
1310 (3, (0, 0), None),
1311 (3, (5, 4), None),
1312 (3, (i128::MIN, i128::MAX), None),
1313 ] {
1314 assert_eq!(Reach::of_shift(bits, range), expected, "{bits} {range:?}");
1315 }
1316 for bits in 1..=20u32 {
1318 let reach = Reach::of_shift(bits, byte);
1319 for n in 0..=255u8 {
1320 let shifted = i128::from(n.wrapping_shl(bits));
1321 assert!(
1322 reach.is_none_or(|reach| reach.holds(shifted)),
1323 "{n} << {bits}"
1324 );
1325 }
1326 }
1327 }
1328
1329 #[test]
1330 fn the_ends_of_what_an_expression_can_be_in_its_type() {
1331 for reach in REACHES {
1332 for (low, high) in [(0, 255), (-128, 127), (0, 0), (3, 3), (5, 9)] {
1333 let all: Vec<i128> = (low..=high).filter(|v| reach.holds(*v)).collect();
1334 assert_eq!(
1335 reach.within(low, high),
1336 all.first().copied().zip(all.last().copied()),
1337 "{reach:?} in {low}..={high}"
1338 );
1339 }
1340 }
1341 assert_eq!(Reach::Multiples(2).within(0, 255), Some((0, 254)));
1343 }
1344
1345 #[test]
1346 fn gaps_of_another_kind_are_not_touched() {
1347 let obs = Obs::of_d(3);
1348 for gap in [
1349 InputGap::Unreached,
1350 InputGap::OneSided { always: true },
1351 InputGap::EqualNeverObserved {
1352 flipped: CmpOp::Le,
1353 float_gap: None,
1354 },
1355 ] {
1356 assert_eq!(
1357 within_reach(gap.clone(), CmpOp::Lt, &obs, Reach::Multiples(8), 20, true),
1358 Some(gap)
1359 );
1360 }
1361 let mut obs = Obs::of_d(16 - 20);
1363 obs.merge(&Obs::of_d(24 - 20));
1364 let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1365 assert_eq!(
1366 within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1367 None
1368 );
1369 let mut obs = Obs::of_d(8 - 20);
1371 obs.merge(&Obs::of_d(40 - 20));
1372 let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1373 assert_eq!(
1374 within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1375 Some(InputGap::Boundary {
1376 min_shift: -12,
1377 max_shift: 19,
1378 missing: vec![-4, 4],
1379 same: (-4, 3),
1381 })
1382 );
1383 }
1384
1385 fn obs_of(ds: &[i128]) -> Obs {
1386 let mut obs = Obs::default();
1387 for d in ds {
1388 obs.merge(&Obs::of_d(*d));
1389 }
1390 obs
1391 }
1392
1393 fn rel_of(d: i128) -> Rel {
1394 match d {
1395 d if d < 0 => Rel::Less,
1396 0 => Rel::Equal,
1397 _ => Rel::Greater,
1398 }
1399 }
1400
1401 fn brute_infects(op: CmpOp, m: Mutation, ds: &[i128]) -> bool {
1403 ds.iter()
1404 .any(|d| op.eval_d(*d) != eval_mutated_d(op, m, *d))
1405 }
1406
1407 #[test]
1408 fn is_eligible_example_from_the_readme() {
1409 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[-1, 2]), None);
1411 assert_eq!(
1412 plan.gap,
1413 Some(InputGap::Boundary {
1414 min_shift: 0,
1415 max_shift: 2,
1416 missing: vec![0],
1417 same: (0, 0),
1418 })
1419 );
1420 assert_eq!(plan.run, vec![Mutation::Shift(-1), Mutation::Negate]);
1422 assert_eq!(plan.gap.unwrap().representative(), Some(Mutation::Shift(1)));
1423 }
1424
1425 #[test]
1430 fn the_operators_a_comparison_is_mistaken_for() {
1431 let rels = [Rel::Less, Rel::Equal, Rel::Greater, Rel::Unordered];
1432 for op in [CmpOp::Lt, CmpOp::Gt] {
1433 for seen in 1u8..16 {
1434 let mut obs = Obs::default();
1435 let seen: Vec<Rel> = (0..4)
1436 .filter(|i| seen & (1 << i) != 0)
1437 .map(|i| rels[i])
1438 .collect();
1439 for rel in &seen {
1440 obs.merge(&Obs::of_rel(*rel));
1441 }
1442 let plan = plan_cmp(op, &obs, None);
1443 for other in op.mistaken_for() {
1444 let like_the_original = seen
1445 .iter()
1446 .all(|rel| other.eval_rel(*rel) == op.eval_rel(*rel));
1447 let what = format!("{op:?} as {other:?} with {seen:?}: {plan:?}");
1448 let run = plan
1449 .run
1450 .iter()
1451 .filter(|m| **m == Mutation::Op(*other))
1452 .count();
1453 if like_the_original {
1454 assert!(plan.gap.is_some(), "{what}");
1455 assert_eq!(run, 0, "{what}");
1456 } else {
1457 assert_eq!(run, 1, "{what}");
1458 }
1459 }
1460 }
1461 }
1462 for op in [CmpOp::Le, CmpOp::Ge, CmpOp::Eq, CmpOp::Ne] {
1464 assert!(op.mistaken_for().is_empty());
1465 }
1466 let seen = |rels: &[Rel]| {
1471 let mut obs = Obs::default();
1472 for rel in rels {
1473 obs.merge(&Obs::of_rel(*rel));
1474 }
1475 obs
1476 };
1477 for (op, reverse) in [(CmpOp::Ge, CmpOp::Lt), (CmpOp::Le, CmpOp::Gt)] {
1478 let run = |rels: &[Rel]| plan_cmp(op, &seen(rels), None).run;
1479 let reversed = |rels: &[Rel]| run(rels).contains(&Mutation::Op(reverse));
1480 assert!(reversed(&[Rel::Unordered, Rel::Less]), "{op:?}");
1481 assert!(reversed(&[Rel::Less, Rel::Greater]), "{op:?}");
1482 assert!(reversed(&[Rel::Less, Rel::Equal, Rel::Greater]), "{op:?}");
1483 assert_eq!(run(&[Rel::Unordered]), vec![Mutation::Negate], "{op:?}");
1487 for ds in [&[-1i128, 1][..], &[-2, 0, 3], &[0, 1]] {
1489 let plan = plan_cmp(op, &obs_of(ds), None);
1490 assert!(!plan.run.contains(&Mutation::Op(reverse)), "{op:?} {ds:?}");
1491 }
1492 for d in -3..=3 {
1493 assert_eq!(eval_mutated_d(op, Mutation::Negate, d), reverse.eval_d(d));
1494 }
1495 }
1496 let run = plan_cmp(CmpOp::Eq, &seen(&[Rel::Unordered, Rel::Equal]), None).run;
1498 assert_eq!(run, vec![Mutation::Negate]);
1499 let plan = plan_cmp(CmpOp::Lt, &Obs::of_rel(Rel::Greater), None);
1502 assert_eq!(plan.run, vec![Mutation::Negate, Mutation::Op(CmpOp::Gt)]);
1503 }
1504
1505 #[test]
1506 fn pinned_boundary_has_no_input_gap() {
1507 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1508 let plan = plan_cmp(op, &obs_of(&[-1, 0, 1]), None);
1509 assert_eq!(plan.gap, None, "{op:?}");
1510 let mut run = vec![Mutation::Shift(-1), Mutation::Shift(1), Mutation::Negate];
1512 run.extend(op.mistaken_for().iter().map(|other| Mutation::Op(*other)));
1513 assert_eq!(plan.run, run, "{op:?}");
1514 }
1515 }
1516
1517 #[test]
1518 fn unreached_site() {
1519 let plan = plan_cmp(CmpOp::Lt, &Obs::default(), None);
1520 assert_eq!(
1521 plan,
1522 CmpPlan {
1523 cannot_differ: false,
1524 gap: Some(InputGap::Unreached),
1525 run: vec![]
1526 }
1527 );
1528 }
1529
1530 #[test]
1531 fn one_sided_condition() {
1532 let plan = plan_cmp(CmpOp::Gt, &obs_of(&[3, 5]), None);
1533 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1534 assert_eq!(
1536 plan.run,
1537 vec![
1538 Mutation::Negate,
1539 Mutation::Op(CmpOp::Eq),
1540 Mutation::Op(CmpOp::Lt)
1541 ]
1542 );
1543 }
1544
1545 #[test]
1546 fn unsigned_compared_with_zero_is_not_reported() {
1547 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((0, 255)));
1549 assert_eq!(plan.gap, None);
1550 assert!(plan.cannot_differ);
1551 assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 255))).cannot_differ);
1552 assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[-1, 4]), Some((-1, 255))).cannot_differ);
1553 let plan = plan_cmp(CmpOp::Lt, &obs_of(&[0, 4]), Some((0, 255)));
1555 assert_eq!(plan.gap, None);
1556 let plan = plan_cmp(CmpOp::Gt, &obs_of(&[0, 1]), Some((0, 255)));
1559 assert_eq!(plan.gap, None);
1560 assert_eq!(
1562 plan.run,
1563 vec![
1564 Mutation::Shift(-1),
1565 Mutation::Shift(1),
1566 Mutation::Negate,
1567 Mutation::Op(CmpOp::Eq),
1568 Mutation::Op(CmpOp::Lt)
1569 ]
1570 );
1571 let plan = plan_cmp(CmpOp::Le, &obs_of(&[0, 1]), Some((0, 255)));
1574 assert_eq!(plan.gap, None);
1575 }
1576
1577 #[test]
1578 fn one_sided_condition_at_the_edge_of_the_type() {
1579 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 10)));
1581 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1582 let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 1)));
1584 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1585 let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 0)));
1586 assert_eq!(plan.gap, None);
1587 let plan = plan_cmp(CmpOp::Ge, &Obs::of_rel(Rel::Greater), Some((0, 10)));
1589 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1590 }
1591
1592 #[test]
1593 fn representative_is_the_nearest_survivor() {
1594 let boundary = |min_shift, max_shift| InputGap::Boundary {
1595 min_shift,
1596 max_shift,
1597 missing: vec![0],
1598 same: (0, 0),
1599 };
1600 assert_eq!(boundary(-3, 1).representative(), Some(Mutation::Shift(1)));
1601 assert_eq!(boundary(-1, 0).representative(), Some(Mutation::Shift(-1)));
1602 assert_eq!(boundary(0, 0).representative(), None);
1603 assert_eq!(InputGap::Unreached.representative(), None);
1604 assert_eq!(
1605 InputGap::OneSided { always: false }.representative(),
1606 Some(Mutation::Const(false))
1607 );
1608 assert_eq!(
1609 InputGap::EqualNeverObserved {
1610 flipped: CmpOp::Ge,
1611 float_gap: None
1612 }
1613 .representative(),
1614 Some(Mutation::Op(CmpOp::Ge))
1615 );
1616 }
1617
1618 fn eval_logic(and: bool, m: Option<Mutation>, a: bool, b: bool) -> (bool, bool) {
1621 let decided = |and: bool| if and { !a } else { a };
1622 match m {
1623 None => {
1624 if decided(and) {
1625 (a, false)
1626 } else {
1627 (b, true)
1628 }
1629 }
1630 Some(Mutation::LogicSwap) => {
1631 if decided(!and) {
1632 (a, false)
1633 } else {
1634 (b, true)
1635 }
1636 }
1637 Some(Mutation::LogicDropRhs) => (a, !decided(and)),
1639 Some(Mutation::LogicDropLhs) => (b, true),
1640 other => panic!("{other:?}"),
1641 }
1642 }
1643
1644 #[test]
1645 fn logic_plans_match_a_reference_evaluator() {
1646 let cases = [(false, false), (false, true), (true, false), (true, true)];
1647 for and in [true, false] {
1648 for mask in 0u32..16 {
1649 let seen: Vec<(bool, bool)> = cases
1650 .iter()
1651 .enumerate()
1652 .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1653 .collect();
1654 let mut obs = LogicObs::default();
1655 for (a, b) in &seen {
1656 let (_, evaluated) = eval_logic(and, None, *a, *b);
1657 obs.short |= !evaluated;
1658 obs.rhs_true |= evaluated && *b;
1659 obs.rhs_false |= evaluated && !*b;
1660 }
1661 let ctx = format!("and={and} seen={seen:?}");
1662 let differs = |m: Mutation| {
1663 seen.iter().any(|(a, b)| {
1664 eval_logic(and, None, *a, *b) != eval_logic(and, Some(m), *a, *b)
1665 })
1666 };
1667 let plan = plan_logic(and, &obs);
1668 if seen.is_empty() {
1669 assert_eq!(
1670 plan,
1671 LogicPlan {
1672 gaps: vec![LogicGap::Unreached],
1673 run: vec![]
1674 }
1675 );
1676 continue;
1677 }
1678 for (m, gap) in [
1679 (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1680 (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1681 ] {
1682 assert_eq!(plan.gaps.contains(&gap), !differs(m), "{gap:?} {ctx}");
1684 assert_eq!(plan.run.contains(&m), differs(m), "{m:?} {ctx}");
1685 assert_eq!(logic_infects(and, m, &obs), differs(m), "{m:?} {ctx}");
1686 }
1687 assert!(plan.run.contains(&Mutation::LogicSwap), "{ctx}");
1689 assert!(logic_infects(and, Mutation::LogicSwap, &obs), "{ctx}");
1690 }
1691 }
1692 let started = LogicObs::from_bits(8);
1696 assert!(started.rhs_started && started.reached());
1697 for and in [true, false] {
1698 let plan = plan_logic(and, &started);
1699 assert_eq!(plan.run, vec![Mutation::LogicSwap]);
1700 assert_eq!(
1701 plan.gaps,
1702 vec![LogicGap::RhsNeverDecides, LogicGap::LhsNeverDecides]
1703 );
1704 assert!(logic_infects(and, Mutation::LogicSwap, &started));
1705 assert!(!logic_infects(and, Mutation::LogicDropRhs, &started));
1706 assert!(!logic_infects(and, Mutation::LogicDropLhs, &started));
1707 }
1708 let mut merged = LogicObs::from_bits(2);
1709 merged.merge(&started);
1710 assert_eq!(merged, LogicObs::from_bits(10));
1711 assert_eq!(
1712 LogicObs::from_bits(5),
1713 LogicObs {
1714 short: true,
1715 rhs_true: false,
1716 rhs_false: true,
1717 rhs_started: false,
1718 }
1719 );
1720 assert_eq!(
1721 LogicObs::from_bits(2),
1722 LogicObs {
1723 short: false,
1724 rhs_true: true,
1725 rhs_false: false,
1726 rhs_started: false,
1727 }
1728 );
1729 }
1730
1731 #[test]
1732 fn return_plans() {
1733 assert_eq!(
1734 plan_return(&ReturnObs::from_bits(0)),
1735 ReturnPlan {
1736 unreached: true,
1737 always: None,
1738 run: vec![]
1739 }
1740 );
1741 assert_eq!(
1742 plan_return(&ReturnObs::from_bits(1)),
1743 ReturnPlan {
1744 unreached: false,
1745 always: Some(true),
1746 run: vec![Mutation::Const(false)]
1747 }
1748 );
1749 assert_eq!(
1750 plan_return(&ReturnObs::from_bits(2)),
1751 ReturnPlan {
1752 unreached: false,
1753 always: Some(false),
1754 run: vec![Mutation::Const(true)]
1755 }
1756 );
1757 assert_eq!(
1758 plan_return(&ReturnObs::from_bits(3)),
1759 ReturnPlan {
1760 unreached: false,
1761 always: None,
1762 run: vec![Mutation::Const(true), Mutation::Const(false)]
1763 }
1764 );
1765 for bits in 0u8..4 {
1767 let obs = ReturnObs::from_bits(bits);
1768 assert_eq!(obs.infected_by_const(true), obs.saw_false);
1769 assert_eq!(obs.infected_by_const(false), obs.saw_true);
1770 assert_eq!(obs.reached(), bits != 0);
1771 let plan = plan_return(&obs);
1772 for m in &plan.run {
1773 let Mutation::Const(value) = m else { panic!() };
1774 assert!(
1775 obs.infected_by_const(*value),
1776 "a run mutant must change some test"
1777 );
1778 }
1779 if let Some(always) = plan.always {
1780 assert!(
1781 !obs.infected_by_const(always),
1782 "the survivor changes no test"
1783 );
1784 }
1785 }
1786 let mut merged = ReturnObs::from_bits(1);
1787 merged.merge(&ReturnObs::from_bits(2));
1788 assert_eq!(
1789 merged,
1790 ReturnObs {
1791 saw_true: true,
1792 saw_false: true
1793 }
1794 );
1795 }
1796
1797 #[test]
1798 fn logic_constant_value() {
1799 let cases = [(false, false), (false, true), (true, false), (true, true)];
1800 for and in [true, false] {
1801 for mask in 0u32..16 {
1802 let seen: Vec<(bool, bool)> = cases
1803 .iter()
1804 .enumerate()
1805 .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1806 .collect();
1807 let mut obs = LogicObs::default();
1808 let mut values = std::collections::BTreeSet::new();
1809 for (a, b) in &seen {
1810 let (value, evaluated) = eval_logic(and, None, *a, *b);
1811 values.insert(value);
1812 obs.short |= !evaluated;
1813 obs.rhs_true |= evaluated && *b;
1814 obs.rhs_false |= evaluated && !*b;
1815 }
1816 let expected = if values.len() == 1 {
1817 values.first().copied()
1818 } else {
1819 None
1820 };
1821 assert_eq!(obs.constant_value(and), expected, "and={and} seen={seen:?}");
1822 }
1823 }
1824 }
1825
1826 #[test]
1827 fn option_return_plans() {
1828 let plan = |bits| plan_option_return(&ReturnObs::from_bits(bits));
1829 assert_eq!(
1830 plan(0),
1831 ReturnPlan {
1832 unreached: true,
1833 always: None,
1834 run: vec![]
1835 }
1836 );
1837 assert_eq!(
1839 plan(2),
1840 ReturnPlan {
1841 unreached: false,
1842 always: Some(false),
1843 run: vec![]
1844 }
1845 );
1846 for bits in [1, 3] {
1848 assert_eq!(
1849 plan(bits),
1850 ReturnPlan {
1851 unreached: false,
1852 always: None,
1853 run: vec![Mutation::Const(false)]
1854 }
1855 );
1856 assert!(ReturnObs::from_bits(bits).infected_by_const(false));
1857 }
1858 assert!(!ReturnObs::from_bits(2).infected_by_const(false));
1859 }
1860
1861 #[test]
1862 fn arithmetic_plans() {
1863 for bits in 0u8..8 {
1864 let obs = ArithObs::from_bits(bits);
1865 let expected = if bits & 2 != 0 {
1866 ArithPlan::Run
1867 } else if bits & 1 != 0 {
1868 ArithPlan::NeverDiffers
1869 } else if bits & 4 != 0 {
1870 ArithPlan::Opaque
1871 } else {
1872 ArithPlan::Unreached
1873 };
1874 assert_eq!(plan_arith(&obs), expected, "bits={bits}");
1875 }
1876 let mut merged = ArithObs::from_bits(1);
1877 merged.merge(&ArithObs::from_bits(4));
1878 assert_eq!(
1879 merged,
1880 ArithObs {
1881 same: true,
1882 differs: false,
1883 opaque: true,
1884 ..Default::default()
1885 }
1886 );
1887 }
1888
1889 #[test]
1890 fn float_comparison_without_equal_operands() {
1891 let mut obs = Obs::of_f(-20.5);
1893 obs.merge(&Obs::of_f(9.5));
1894 let plan = plan_cmp(CmpOp::Gt, &obs, None);
1895 let gap = plan.gap.expect("a gap");
1896 assert_eq!(
1897 gap,
1898 InputGap::EqualNeverObserved {
1899 flipped: CmpOp::Ge,
1900 float_gap: Some((-20.5, 9.5))
1901 }
1902 );
1903 assert_eq!(
1904 gap.survivors(),
1905 vec![
1906 Mutation::Op(CmpOp::Ge),
1907 Mutation::ShiftF(4.75),
1908 Mutation::ShiftF(-10.25)
1909 ]
1910 );
1911 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1914 assert!(!infects(op, Mutation::ShiftF(4.75), &obs));
1915 assert!(!infects(op, Mutation::ShiftF(-10.25), &obs));
1916 assert!(infects(op, Mutation::ShiftF(9.5), &obs));
1917 assert!(infects(op, Mutation::ShiftF(-20.5), &obs));
1918 }
1919 let mut with_eq = obs;
1920 with_eq.merge(&Obs::of_f(0.0));
1921 assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &with_eq));
1922 assert_eq!(plan_cmp(CmpOp::Gt, &with_eq, None).gap, None);
1923 let mut mixed = obs;
1925 mixed.merge(&Obs::of_rel(Rel::Less));
1926 assert_eq!(mixed.float_gap(), None);
1927 assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &mixed));
1928 assert_eq!(Obs::of_d(3).float_gap(), None);
1929 }
1930
1931 #[test]
1932 fn survivors_are_listed_nearest_first() {
1933 let boundary = |min_shift, max_shift| InputGap::Boundary {
1934 min_shift,
1935 max_shift,
1936 missing: vec![0],
1937 same: (0, 0),
1938 };
1939 assert_eq!(
1940 boundary(-9, 9).survivors(),
1941 vec![Mutation::Shift(1), Mutation::Shift(-1), Mutation::Shift(2)]
1942 );
1943 assert_eq!(boundary(-1, 0).survivors(), vec![Mutation::Shift(-1)]);
1944 assert_eq!(
1945 boundary(0, 2).survivors(),
1946 vec![Mutation::Shift(1), Mutation::Shift(2)]
1947 );
1948 assert_eq!(
1949 InputGap::OneSided { always: true }.survivors(),
1950 vec![Mutation::Const(true)]
1951 );
1952 assert_eq!(InputGap::Unreached.survivors(), vec![]);
1953 }
1954
1955 #[test]
1956 fn single_observation_summaries() {
1957 let bits = |o: Obs| (o.lt, o.eq, o.gt, o.un);
1958 assert_eq!(bits(Obs::of_f(-0.5)), (true, false, false, false));
1959 assert_eq!(bits(Obs::of_f(0.0)), (false, true, false, false));
1960 assert_eq!(bits(Obs::of_f(0.5)), (false, false, true, false));
1961 assert_eq!(
1962 (Obs::of_f(-0.5).f_max_neg, Obs::of_f(-0.5).f_min_pos),
1963 (Some(-0.5), None)
1964 );
1965 assert_eq!(
1966 (Obs::of_f(0.5).f_max_neg, Obs::of_f(0.5).f_min_pos),
1967 (None, Some(0.5))
1968 );
1969 assert_eq!(
1970 (Obs::of_f(0.0).f_max_neg, Obs::of_f(0.0).f_min_pos),
1971 (None, None)
1972 );
1973 assert!(Obs::of_f(1.0).unvalued && !Obs::of_f(1.0).unfloat);
1974 assert!(Obs::of_d(1).unfloat && !Obs::of_d(1).unvalued);
1975
1976 assert!(Obs::of_rel(Rel::Unordered).reached());
1978 assert!(!Obs::default().reached());
1979 assert!(!Obs::default().valued());
1981 assert!(Obs::of_d(0).valued());
1982 assert!(!Obs::of_rel(Rel::Equal).valued());
1983
1984 let mut nan = Obs::of_f(-1.0);
1986 nan.merge(&Obs::of_f(1.0));
1987 assert_eq!(nan.float_gap(), Some((-1.0, 1.0)));
1988 nan.un = true;
1989 assert_eq!(nan.float_gap(), None);
1990 assert_eq!(Obs::default().float_gap(), None);
1991 assert_eq!(Obs::of_f(-1.0).float_gap(), None, "one side only");
1992 }
1993
1994 #[test]
1995 fn interval_queries_look_at_the_right_side_of_zero() {
1996 assert!(!obs_of(&[2]).saw_any_in(-3, -1));
1998 assert!(!obs_of(&[-2]).saw_any_in(1, 3));
1999 assert!(obs_of(&[-2]).saw_any_in(-3, -1));
2000 assert!(obs_of(&[2]).saw_any_in(1, 3));
2001 assert!(!obs_of(&[-4]).saw_any_in(-3, 0));
2002 assert!(!obs_of(&[4]).saw_any_in(0, 3));
2003 let mut odd = obs_of(&[3]);
2005 odd.max_neg = Some(5);
2006 assert!(!odd.saw_any_in(0, 2));
2007 let mut odd = obs_of(&[-3]);
2008 odd.min_pos = Some(-5);
2009 assert!(!odd.saw_any_in(-2, 0));
2010 }
2011
2012 #[test]
2013 fn empty_interval_has_no_observations() {
2014 assert!(!obs_of(&[-1, 0, 1]).saw_any_in(1, 0));
2015 assert!(obs_of(&[0]).saw_any_in(0, 0));
2016 }
2017
2018 #[test]
2019 fn unvalued_ordering_without_equal_operands() {
2020 let mut obs = Obs::of_rel(Rel::Less);
2021 obs.merge(&Obs::of_rel(Rel::Greater));
2022 let plan = plan_cmp(CmpOp::Lt, &obs, None);
2023 assert_eq!(
2024 plan.gap,
2025 Some(InputGap::EqualNeverObserved {
2026 flipped: CmpOp::Le,
2027 float_gap: None
2028 })
2029 );
2030 assert_eq!(
2032 plan.run,
2033 vec![
2034 Mutation::Negate,
2035 Mutation::Op(CmpOp::Eq),
2036 Mutation::Op(CmpOp::Gt)
2037 ]
2038 );
2039
2040 obs.merge(&Obs::of_rel(Rel::Equal));
2041 let plan = plan_cmp(CmpOp::Lt, &obs, None);
2042 assert_eq!(plan.gap, None);
2043 assert_eq!(
2044 plan.run,
2045 vec![
2046 Mutation::Op(CmpOp::Le),
2047 Mutation::Negate,
2048 Mutation::Op(CmpOp::Eq),
2049 Mutation::Op(CmpOp::Gt)
2050 ]
2051 );
2052 }
2053
2054 #[test]
2055 fn equality_with_both_outcomes() {
2056 let plan = plan_cmp(CmpOp::Eq, &obs_of(&[0, 7]), None);
2057 assert_eq!(
2058 plan,
2059 CmpPlan {
2060 cannot_differ: false,
2061 gap: None,
2062 run: vec![Mutation::Negate]
2063 }
2064 );
2065 }
2066
2067 #[test]
2068 fn unordered_counts_as_not_equal() {
2069 let obs = Obs::of_rel(Rel::Unordered);
2070 assert!(infects(CmpOp::Ne, Mutation::Const(false), &obs));
2071 assert!(!infects(CmpOp::Lt, Mutation::Op(CmpOp::Ge), &obs));
2072 assert!(infects(CmpOp::Lt, Mutation::Op(CmpOp::Ne), &obs));
2073 }
2074
2075 #[test]
2076 fn merge_is_a_semilattice() {
2077 let samples: Vec<Obs> = [-3, -1, 0, 1, 4]
2078 .into_iter()
2079 .map(Obs::of_d)
2080 .chain([
2081 Obs::of_rel(Rel::Unordered),
2082 Obs::of_rel(Rel::Less),
2083 Obs::default(),
2084 ])
2085 .collect();
2086 for a in &samples {
2087 let mut aa = *a;
2088 aa.merge(a);
2089 assert_eq!(aa, *a, "idempotent");
2090 for b in &samples {
2091 let (mut ab, mut ba) = (*a, *b);
2092 ab.merge(b);
2093 ba.merge(a);
2094 assert_eq!(ab, ba, "commutative");
2095 for c in &samples {
2096 let mut ab_c = ab;
2097 ab_c.merge(c);
2098 let mut bc = *b;
2099 bc.merge(c);
2100 let mut a_bc = *a;
2101 a_bc.merge(&bc);
2102 assert_eq!(ab_c, a_bc, "associative");
2103 }
2104 }
2105 }
2106 }
2107
2108 #[test]
2109 fn mutation_wire_format() {
2110 assert_eq!(Mutation::Const(true).encode(), "c1");
2111 assert_eq!(Mutation::Const(false).encode(), "c0");
2112 assert_eq!(Mutation::Negate.encode(), "neg");
2113 assert_eq!(Mutation::Op(CmpOp::Ge).encode(), "op3");
2114 assert_eq!(Mutation::Shift(-2).encode(), "sh-2");
2115 assert_eq!(Mutation::Delete.encode(), "del");
2116 assert_eq!(Mutation::ShiftF(4.75).encode(), "shf4.75");
2117 assert_eq!(Mutation::ShiftF(-10.0).encode(), "shf-10.0");
2118 assert_eq!(Mutation::LogicSwap.encode(), "lsw");
2119 assert_eq!(Mutation::LogicDropRhs.encode(), "ldr");
2120 assert_eq!(Mutation::LogicDropLhs.encode(), "ldl");
2121 assert_eq!(Mutation::ArithSwap.encode(), "asw");
2122 assert_eq!(Mutation::DropNot.encode(), "unn");
2123 assert_eq!(Mutation::RangeEnd.encode(), "rng");
2124 assert_eq!(Mutation::MinMax.encode(), "mmx");
2125 assert_eq!(Mutation::OtherEnd.encode(), "end");
2126 }
2127
2128 fn candidate_mutations(op: CmpOp) -> Vec<Mutation> {
2129 let mut ms = vec![
2130 Mutation::Const(true),
2131 Mutation::Const(false),
2132 Mutation::Negate,
2133 ];
2134 ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
2135 if op.is_ordering() {
2136 ms.extend((-5..=5).filter(|s| *s != 0).map(Mutation::Shift));
2137 }
2138 ms
2139 }
2140
2141 fn check_plan(op: CmpOp, ds: &[i128], domain: Option<(i128, i128)>) {
2143 let obs = obs_of(ds);
2144 let ctx = format!("{op:?} ds={ds:?} domain={domain:?}");
2145 let (dom_lo, dom_hi) = domain.unwrap_or((-50, 50));
2146 let differs_somewhere =
2147 |m: Mutation| (dom_lo..=dom_hi).any(|d| op.eval_d(d) != eval_mutated_d(op, m, d));
2148
2149 for m in candidate_mutations(op) {
2150 assert_eq!(
2151 infects(op, m, &obs),
2152 brute_infects(op, m, ds),
2153 "infects {m:?} {ctx}"
2154 );
2155 }
2156
2157 let plan = plan_cmp(op, &obs, domain);
2158 for m in &plan.run {
2159 assert!(
2160 brute_infects(op, *m, ds),
2161 "run {m:?} must be infected: {ctx}"
2162 );
2163 assert!(differs_somewhere(*m), "run {m:?} is equivalent: {ctx}");
2164 }
2165 match &plan.gap {
2166 None => {}
2167 Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2168 Some(InputGap::OneSided { always }) => {
2169 assert!(ds.iter().all(|d| op.eval_d(*d) == *always), "{ctx}");
2170 assert!(differs_somewhere(Mutation::Const(*always)), "{ctx}");
2171 }
2172 Some(InputGap::Boundary {
2173 min_shift,
2174 max_shift,
2175 missing,
2176 same: _,
2177 }) => {
2178 assert!(*min_shift <= 0 && 0 <= *max_shift, "{ctx}");
2179 for s in (*min_shift..=*max_shift).filter(|s| *s != 0) {
2180 let m = Mutation::Shift(s);
2181 assert!(
2182 !brute_infects(op, m, ds),
2183 "survivor {m:?} is infected: {ctx}"
2184 );
2185 assert!(differs_somewhere(m), "survivor {m:?} is equivalent: {ctx}");
2186 }
2187 if domain.is_none() {
2188 for s in [min_shift - 1, max_shift + 1] {
2190 assert!(
2191 brute_infects(op, Mutation::Shift(s), ds),
2192 "range not maximal: {ctx}"
2193 );
2194 }
2195 }
2196 assert!(!missing.is_empty(), "{ctx}");
2197 for w in missing {
2198 assert!(!ds.contains(w), "missing value {w} was observed: {ctx}");
2199 assert!(
2200 dom_lo <= *w && *w <= dom_hi,
2201 "missing value {w} out of domain: {ctx}"
2202 );
2203 let s = if op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(1), *w) {
2204 1
2205 } else {
2206 -1
2207 };
2208 assert!(
2209 op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(s), *w),
2210 "missing value {w} separates nothing: {ctx}"
2211 );
2212 assert!(*min_shift <= s && s <= *max_shift, "{ctx}");
2213 }
2214 }
2215 Some(InputGap::EqualNeverObserved { .. }) => panic!("valued site: {ctx}"),
2216 }
2217 if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2218 assert!(
2219 !brute_infects(op, m, ds),
2220 "representative {m:?} is infected: {ctx}"
2221 );
2222 }
2223
2224 if op.is_ordering() && ds.iter().any(|d| op.eval_d(*d)) && ds.iter().any(|d| !op.eval_d(*d))
2226 {
2227 for s in [-1, 1] {
2228 let m = Mutation::Shift(s);
2229 let survivor = matches!(&plan.gap, Some(InputGap::Boundary { min_shift, max_shift, .. })
2230 if *min_shift <= s && s <= *max_shift);
2231 let ran = plan.run.contains(&m);
2232 assert!(
2233 survivor ^ ran || !differs_somewhere(m),
2234 "Shift({s}) unaccounted for: survivor={survivor} ran={ran} {ctx}"
2235 );
2236 }
2237 }
2238 }
2239
2240 #[test]
2241 fn exhaustive_small_observation_sets() {
2242 let universe: Vec<i128> = (-3..=3).collect();
2243 for op in CmpOp::ALL {
2244 for mask in 0u32..(1 << universe.len()) {
2245 let ds: Vec<i128> = universe
2246 .iter()
2247 .enumerate()
2248 .filter_map(|(i, d)| (mask & (1 << i) != 0).then_some(*d))
2249 .collect();
2250 check_plan(op, &ds, None);
2251 for (lo, hi) in [(0, 10), (-10, 0), (-2, 2), (1, 9), (-9, -1)] {
2253 if ds.iter().all(|d| lo <= *d && *d <= hi) {
2254 check_plan(op, &ds, Some((lo, hi)));
2255 }
2256 }
2257 }
2258 }
2259 }
2260
2261 #[test]
2263 fn pict_table() {
2264 let table = include_str!("../tests/data/planner.pict.tsv");
2265 let mut rows = 0;
2266 for line in table.lines().skip(1) {
2267 let cols: Vec<&str> = line.split('\t').collect();
2268 let [op, below, equal, above, valued, literal, domain] = cols[..] else {
2269 panic!("bad row: {line}");
2270 };
2271 let op = match op {
2272 "lt" => CmpOp::Lt,
2273 "le" => CmpOp::Le,
2274 "gt" => CmpOp::Gt,
2275 "ge" => CmpOp::Ge,
2276 "eq" => CmpOp::Eq,
2277 "ne" => CmpOp::Ne,
2278 other => panic!("op {other}"),
2279 };
2280 let mut ds: Vec<i128> = vec![];
2281 match below {
2282 "none" => {}
2283 "adjacent" => ds.extend([-1, -4]),
2284 "far" => ds.extend([-3, -6]),
2285 other => panic!("below {other}"),
2286 }
2287 if equal == "yes" {
2288 ds.push(0);
2289 }
2290 match above {
2291 "none" => {}
2292 "adjacent" => ds.extend([1, 5]),
2293 "far" => ds.extend([3, 7]),
2294 other => panic!("above {other}"),
2295 }
2296 rows += 1;
2297 if valued == "no" {
2298 let mut obs = Obs::default();
2299 for d in &ds {
2300 obs.merge(&Obs::of_rel(rel_of(*d)));
2301 }
2302 check_unvalued(op, &obs, &ds, line);
2303 continue;
2304 }
2305 let domain = match (literal, domain) {
2308 ("none", _) => None,
2309 (_, "wide") => Some((-40, 40)),
2310 ("rhs", "tight_low") | ("lhs", "tight_high") => Some((0, 40)),
2311 ("rhs", "tight_high") | ("lhs", "tight_low") => Some((-40, 0)),
2312 other => panic!("domain {other:?}"),
2313 };
2314 check_plan(op, &ds, domain);
2315 }
2316 assert_eq!(rows, table.lines().count() - 1);
2317 assert!(rows > 50, "the PICT table looks truncated: {rows} rows");
2318 }
2319
2320 fn check_unvalued(op: CmpOp, obs: &Obs, ds: &[i128], ctx: &str) {
2321 let plan = plan_cmp(op, obs, None);
2322 for m in [
2323 Mutation::Const(true),
2324 Mutation::Const(false),
2325 Mutation::Negate,
2326 ]
2327 .into_iter()
2328 .chain(CmpOp::ALL.into_iter().map(Mutation::Op))
2329 {
2330 assert_eq!(
2331 infects(op, m, obs),
2332 brute_infects(op, m, ds),
2333 "infects {m:?} {ctx}"
2334 );
2335 }
2336 for m in &plan.run {
2337 assert!(
2338 brute_infects(op, *m, ds),
2339 "run {m:?} must be infected: {ctx}"
2340 );
2341 }
2342 if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2343 assert!(
2344 !brute_infects(op, m, ds),
2345 "representative {m:?} is infected: {ctx}"
2346 );
2347 }
2348 match &plan.gap {
2349 Some(InputGap::Boundary { .. }) => panic!("unvalued site cannot shift: {ctx}"),
2350 Some(InputGap::EqualNeverObserved { flipped, .. }) => {
2351 assert!(!ds.contains(&0), "{ctx}");
2352 assert_eq!(op.flip_eq(), Some(*flipped), "{ctx}");
2353 }
2354 Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2355 _ => {}
2356 }
2357 if op.is_ordering() && obs.reached() {
2359 assert!(infects(op, Mutation::Shift(1), obs), "{ctx}");
2360 }
2361 }
2362}