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 pub fn swap_never_changes_value(&self, and: bool) -> bool {
914 !self.short && !self.rhs_decided(and) && (self.rhs_true || self.rhs_false)
915 }
916}
917
918#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
919#[serde(rename_all = "snake_case")]
920pub enum LogicGap {
921 Unreached,
922 RhsNeverDecides,
924 LhsNeverDecides,
926}
927
928#[derive(Clone, PartialEq, Debug, Default)]
929pub struct LogicPlan {
930 pub gaps: Vec<LogicGap>,
931 pub run: Vec<Mutation>,
932}
933
934pub fn logic_infects(and: bool, m: Mutation, obs: &LogicObs) -> bool {
938 match m {
939 Mutation::LogicDropRhs => obs.rhs_decided(and),
940 Mutation::LogicDropLhs => obs.short,
941 _ => obs.reached(),
942 }
943}
944
945pub fn plan_logic(and: bool, obs: &LogicObs) -> LogicPlan {
946 if !obs.reached() {
947 return LogicPlan {
948 gaps: vec![LogicGap::Unreached],
949 run: vec![],
950 };
951 }
952 let mut plan = LogicPlan::default();
953 for (m, gap) in [
954 (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
955 (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
956 ] {
957 if logic_infects(and, m, obs) {
958 plan.run.push(m);
959 } else {
960 plan.gaps.push(gap);
961 }
962 }
963 plan.run.push(Mutation::LogicSwap);
964 plan
965}
966
967#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
969pub struct ArithObs {
970 pub same: bool,
972 pub differs: bool,
974 pub opaque: bool,
976 pub same2: bool,
978 pub differs2: bool,
979}
980
981impl ArithObs {
982 pub fn from_bits(bits: u8) -> ArithObs {
983 ArithObs {
984 same: bits & 1 != 0,
985 differs: bits & 2 != 0,
986 opaque: bits & 4 != 0,
987 same2: bits & 8 != 0,
988 differs2: bits & 16 != 0,
989 }
990 }
991
992 pub fn merge(&mut self, other: &ArithObs) {
993 self.same |= other.same;
994 self.differs |= other.differs;
995 self.opaque |= other.opaque;
996 self.same2 |= other.same2;
997 self.differs2 |= other.differs2;
998 }
999
1000 pub fn second(&self) -> ArithObs {
1002 ArithObs {
1003 same: self.same2,
1004 differs: self.differs2,
1005 opaque: self.opaque,
1006 same2: false,
1007 differs2: false,
1008 }
1009 }
1010
1011 pub fn infected_by(&self, m: Mutation) -> bool {
1013 if matches!(
1014 m,
1015 Mutation::ArithSwap2 | Mutation::ClampDropUpper | Mutation::RoundAlt2
1016 ) {
1017 self.differs2
1018 } else {
1019 self.differs
1020 }
1021 }
1022}
1023
1024#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1025pub enum ArithPlan {
1026 Unreached,
1027 Opaque,
1029 NeverDiffers,
1031 Run,
1033}
1034
1035pub fn plan_arith(obs: &ArithObs) -> ArithPlan {
1036 if obs.differs {
1037 ArithPlan::Run
1038 } else if obs.same {
1039 ArithPlan::NeverDiffers
1040 } else if obs.opaque {
1041 ArithPlan::Opaque
1042 } else {
1043 ArithPlan::Unreached
1044 }
1045}
1046
1047#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1049pub struct ReturnObs {
1050 pub saw_true: bool,
1051 pub saw_false: bool,
1052}
1053
1054impl ReturnObs {
1055 pub fn from_bits(bits: u8) -> ReturnObs {
1056 ReturnObs {
1057 saw_true: bits & 1 != 0,
1058 saw_false: bits & 2 != 0,
1059 }
1060 }
1061
1062 pub fn merge(&mut self, other: &ReturnObs) {
1063 self.saw_true |= other.saw_true;
1064 self.saw_false |= other.saw_false;
1065 }
1066
1067 pub fn reached(&self) -> bool {
1068 self.saw_true || self.saw_false
1069 }
1070
1071 pub fn infected_by_const(&self, value: bool) -> bool {
1073 if value { self.saw_false } else { self.saw_true }
1074 }
1075}
1076
1077#[derive(Clone, PartialEq, Debug, Default)]
1078pub struct ReturnPlan {
1079 pub unreached: bool,
1080 pub always: Option<bool>,
1082 pub run: Vec<Mutation>,
1083}
1084
1085pub fn plan_option_return(obs: &ReturnObs) -> ReturnPlan {
1088 match (obs.saw_true, obs.saw_false) {
1089 (false, false) => ReturnPlan {
1090 unreached: true,
1091 ..ReturnPlan::default()
1092 },
1093 (false, true) => ReturnPlan {
1095 unreached: false,
1096 always: Some(false),
1097 run: vec![],
1098 },
1099 (true, _) => ReturnPlan {
1100 unreached: false,
1101 always: None,
1102 run: vec![Mutation::Const(false)],
1103 },
1104 }
1105}
1106
1107pub fn plan_return(obs: &ReturnObs) -> ReturnPlan {
1108 match (obs.saw_true, obs.saw_false) {
1109 (false, false) => ReturnPlan {
1110 unreached: true,
1111 ..ReturnPlan::default()
1112 },
1113 (true, true) => ReturnPlan {
1114 run: vec![Mutation::Const(true), Mutation::Const(false)],
1115 ..ReturnPlan::default()
1116 },
1117 (always, _) => ReturnPlan {
1118 unreached: false,
1119 always: Some(always),
1120 run: vec![Mutation::Const(!always)],
1121 },
1122 }
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127 use super::*;
1128
1129 const REACHES: [Reach; 5] = [
1130 Reach::Multiples(4),
1131 Reach::Multiples(8),
1132 Reach::Bits(0b1010),
1133 Reach::Bits(0b0110),
1134 Reach::Below(5),
1135 ];
1136
1137 #[test]
1138 fn the_next_value_an_expression_can_be() {
1139 for reach in REACHES {
1140 for value in -40..=40_i128 {
1141 let above = (value + 1..=80).find(|v| reach.holds(*v));
1142 let below = (-80..value).rev().find(|v| reach.holds(*v));
1143 assert_eq!(reach.next_above(value), above, "{reach:?} above {value}");
1144 assert_eq!(reach.next_below(value), below, "{reach:?} below {value}");
1145 }
1146 }
1147 assert_eq!(Reach::Multiples(8).next_above(i128::MAX), None);
1149 assert_eq!(Reach::Multiples(8).next_below(i128::MIN), None);
1150 assert_eq!(Reach::Below(5).next_above(i128::MAX), None);
1151 assert_eq!(Reach::Below(5).next_below(i128::MIN), None);
1152 assert_eq!(Reach::Bits(i128::MAX).next_above(i128::MAX), None);
1153 assert!(Reach::Bits(0xF0).holds(0x30) && !Reach::Bits(0xF0).holds(0x31));
1154 assert!(!Reach::Bits(0xF0).holds(-16));
1155 }
1156
1157 #[test]
1161 fn a_gap_is_kept_only_for_values_the_expression_can_be() {
1162 let mut dropped = 0;
1163 let mut kept = 0;
1164 for reach in REACHES {
1165 let can_be: Vec<i128> = (-24..=24).filter(|v| reach.holds(*v)).collect();
1166 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1167 for literal in -6..=14_i128 {
1168 for literal_is_rhs in [true, false] {
1169 let d_of = |v: i128| {
1170 if literal_is_rhs {
1171 v - literal
1172 } else {
1173 literal - v
1174 }
1175 };
1176 for &low in &can_be {
1177 for &high in can_be.iter().filter(|v| **v > low) {
1178 let mut obs = Obs::of_d(d_of(low));
1179 obs.merge(&Obs::of_d(d_of(high)));
1180 let Some(gap @ InputGap::Boundary { .. }) =
1181 plan_boundary(op, &obs, None).gap
1182 else {
1183 continue;
1184 };
1185 let InputGap::Boundary {
1186 min_shift,
1187 max_shift,
1188 ..
1189 } = gap.clone()
1190 else {
1191 unreachable!()
1192 };
1193 let differs = |shift: i128, v: i128| {
1196 op.eval_d(d_of(v)) != op.eval_d(d_of(v) - shift)
1197 };
1198 let told_apart =
1199 |shift: i128| can_be.iter().any(|v| differs(shift, *v));
1200 let case = format!(
1201 "{reach:?} {op:?} literal {literal} rhs {literal_is_rhs}, saw {low} and {high}"
1202 );
1203 match within_reach(gap, op, &obs, reach, literal, literal_is_rhs) {
1204 None => {
1205 for shift in min_shift..=max_shift {
1207 assert!(!told_apart(shift), "{case}: shift {shift}");
1208 }
1209 dropped += 1;
1210 }
1211 Some(InputGap::Boundary {
1212 min_shift: least,
1213 max_shift: most,
1214 missing,
1215 same,
1216 }) => {
1217 assert!(!missing.is_empty(), "{case}");
1218 assert_eq!((least, most), (min_shift, max_shift), "{case}");
1219 for d in &missing {
1220 let v = if literal_is_rhs {
1221 literal + d
1222 } else {
1223 literal - d
1224 };
1225 assert!(reach.holds(v), "{case}: {v}");
1226 assert!(low < v && v < high, "{case}: {v}");
1227 }
1228 assert!(same.0 <= 0 && 0 <= same.1, "{case}: {same:?}");
1231 for shift in least..=most {
1232 assert_eq!(
1233 same.0 <= shift && shift <= same.1,
1234 !told_apart(shift),
1235 "{case}: shift {shift}, same {same:?}"
1236 );
1237 }
1238 let gap = InputGap::Boundary {
1241 min_shift: least,
1242 max_shift: most,
1243 missing: missing.clone(),
1244 same,
1245 };
1246 for mutation in gap.survivors() {
1247 let Mutation::Shift(shift) = mutation else {
1248 panic!("{case}: {mutation:?}")
1249 };
1250 assert!(told_apart(shift), "{case}: shift {shift}");
1251 }
1252 assert!(gap.representative().is_some(), "{case}");
1253 kept += 1;
1254 }
1255 Some(other) => panic!("{case}: {other:?}"),
1256 }
1257 }
1258 }
1259 }
1260 }
1261 }
1262 }
1263 assert!(
1264 dropped > 100 && kept > 1000,
1265 "{dropped} dropped, {kept} kept"
1266 );
1267 }
1268
1269 #[test]
1270 fn an_outcome_no_value_gives_is_not_asked_for() {
1271 for (reach, literal, op, differs) in [
1273 (Reach::Below(10), 10, CmpOp::Lt, false),
1274 (Reach::Below(10), 9, CmpOp::Lt, true),
1275 (Reach::Below(10), -10, CmpOp::Gt, false),
1276 (Reach::Bits(0xF0), 0xF0, CmpOp::Gt, false),
1277 (Reach::Bits(0xF0), 0xF0, CmpOp::Ge, true),
1278 (Reach::Bits(0xF0), 0, CmpOp::Lt, false),
1279 ] {
1280 let (lo, hi) = reach.interval().unwrap();
1281 assert!((lo..=hi).all(|v| !reach.holds(v) || (lo <= v && v <= hi)));
1282 assert!(reach.holds(lo) && reach.holds(hi), "{reach:?}");
1283 assert!(!reach.holds(lo - 1) && !reach.holds(hi + 1), "{reach:?}");
1284 let can_differ = (lo..=hi)
1285 .filter(|v| reach.holds(*v))
1286 .map(|v| op.eval_d(v - literal))
1287 .collect::<std::collections::BTreeSet<_>>()
1288 .len()
1289 == 2;
1290 assert_eq!(can_differ, differs, "{reach:?} {op:?} {literal}");
1291 let seen = (lo..=hi).find(|v| reach.holds(*v)).unwrap();
1293 let plan = plan_cmp(
1294 op,
1295 &Obs::of_d(seen - literal),
1296 Some((lo - literal, hi - literal)),
1297 );
1298 assert_eq!(plan.cannot_differ, !differs, "{reach:?} {op:?} {literal}");
1299 assert_eq!(plan.gap.is_some(), differs, "{reach:?} {op:?} {literal}");
1300 }
1301 assert_eq!(Reach::Multiples(8).interval(), None);
1302 }
1303
1304 #[test]
1305 fn a_shift_is_a_multiple_by_the_bits_that_are_shifted_in_fact() {
1306 let (byte, signed_byte) = ((0, 255), (-128, 127));
1307 for (bits, range, expected) in [
1308 (3, byte, Some(Reach::Multiples(8))),
1309 (7, byte, Some(Reach::Multiples(128))),
1310 (8, byte, None),
1312 (9, byte, Some(Reach::Multiples(2))),
1313 (16, byte, None),
1314 (9, signed_byte, Some(Reach::Multiples(2))),
1315 (33, (0, u32::MAX as i128), Some(Reach::Multiples(2))),
1316 (3, (0, u32::MAX as i128), Some(Reach::Multiples(8))),
1317 (3, (0, 9), None),
1319 (3, (0, 0), None),
1320 (3, (5, 4), None),
1321 (3, (i128::MIN, i128::MAX), None),
1322 ] {
1323 assert_eq!(Reach::of_shift(bits, range), expected, "{bits} {range:?}");
1324 }
1325 for bits in 1..=20u32 {
1327 let reach = Reach::of_shift(bits, byte);
1328 for n in 0..=255u8 {
1329 let shifted = i128::from(n.wrapping_shl(bits));
1330 assert!(
1331 reach.is_none_or(|reach| reach.holds(shifted)),
1332 "{n} << {bits}"
1333 );
1334 }
1335 }
1336 }
1337
1338 #[test]
1339 fn the_ends_of_what_an_expression_can_be_in_its_type() {
1340 for reach in REACHES {
1341 for (low, high) in [(0, 255), (-128, 127), (0, 0), (3, 3), (5, 9)] {
1342 let all: Vec<i128> = (low..=high).filter(|v| reach.holds(*v)).collect();
1343 assert_eq!(
1344 reach.within(low, high),
1345 all.first().copied().zip(all.last().copied()),
1346 "{reach:?} in {low}..={high}"
1347 );
1348 }
1349 }
1350 assert_eq!(Reach::Multiples(2).within(0, 255), Some((0, 254)));
1352 }
1353
1354 #[test]
1355 fn gaps_of_another_kind_are_not_touched() {
1356 let obs = Obs::of_d(3);
1357 for gap in [
1358 InputGap::Unreached,
1359 InputGap::OneSided { always: true },
1360 InputGap::EqualNeverObserved {
1361 flipped: CmpOp::Le,
1362 float_gap: None,
1363 },
1364 ] {
1365 assert_eq!(
1366 within_reach(gap.clone(), CmpOp::Lt, &obs, Reach::Multiples(8), 20, true),
1367 Some(gap)
1368 );
1369 }
1370 let mut obs = Obs::of_d(16 - 20);
1372 obs.merge(&Obs::of_d(24 - 20));
1373 let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1374 assert_eq!(
1375 within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1376 None
1377 );
1378 let mut obs = Obs::of_d(8 - 20);
1380 obs.merge(&Obs::of_d(40 - 20));
1381 let gap = plan_boundary(CmpOp::Gt, &obs, None).gap.unwrap();
1382 assert_eq!(
1383 within_reach(gap, CmpOp::Gt, &obs, Reach::Multiples(8), 20, true),
1384 Some(InputGap::Boundary {
1385 min_shift: -12,
1386 max_shift: 19,
1387 missing: vec![-4, 4],
1388 same: (-4, 3),
1390 })
1391 );
1392 }
1393
1394 fn obs_of(ds: &[i128]) -> Obs {
1395 let mut obs = Obs::default();
1396 for d in ds {
1397 obs.merge(&Obs::of_d(*d));
1398 }
1399 obs
1400 }
1401
1402 fn rel_of(d: i128) -> Rel {
1403 match d {
1404 d if d < 0 => Rel::Less,
1405 0 => Rel::Equal,
1406 _ => Rel::Greater,
1407 }
1408 }
1409
1410 fn brute_infects(op: CmpOp, m: Mutation, ds: &[i128]) -> bool {
1412 ds.iter()
1413 .any(|d| op.eval_d(*d) != eval_mutated_d(op, m, *d))
1414 }
1415
1416 #[test]
1417 fn is_eligible_example_from_the_readme() {
1418 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[-1, 2]), None);
1420 assert_eq!(
1421 plan.gap,
1422 Some(InputGap::Boundary {
1423 min_shift: 0,
1424 max_shift: 2,
1425 missing: vec![0],
1426 same: (0, 0),
1427 })
1428 );
1429 assert_eq!(plan.run, vec![Mutation::Shift(-1), Mutation::Negate]);
1431 assert_eq!(plan.gap.unwrap().representative(), Some(Mutation::Shift(1)));
1432 }
1433
1434 #[test]
1439 fn the_operators_a_comparison_is_mistaken_for() {
1440 let rels = [Rel::Less, Rel::Equal, Rel::Greater, Rel::Unordered];
1441 for op in [CmpOp::Lt, CmpOp::Gt] {
1442 for seen in 1u8..16 {
1443 let mut obs = Obs::default();
1444 let seen: Vec<Rel> = (0..4)
1445 .filter(|i| seen & (1 << i) != 0)
1446 .map(|i| rels[i])
1447 .collect();
1448 for rel in &seen {
1449 obs.merge(&Obs::of_rel(*rel));
1450 }
1451 let plan = plan_cmp(op, &obs, None);
1452 for other in op.mistaken_for() {
1453 let like_the_original = seen
1454 .iter()
1455 .all(|rel| other.eval_rel(*rel) == op.eval_rel(*rel));
1456 let what = format!("{op:?} as {other:?} with {seen:?}: {plan:?}");
1457 let run = plan
1458 .run
1459 .iter()
1460 .filter(|m| **m == Mutation::Op(*other))
1461 .count();
1462 if like_the_original {
1463 assert!(plan.gap.is_some(), "{what}");
1464 assert_eq!(run, 0, "{what}");
1465 } else {
1466 assert_eq!(run, 1, "{what}");
1467 }
1468 }
1469 }
1470 }
1471 for op in [CmpOp::Le, CmpOp::Ge, CmpOp::Eq, CmpOp::Ne] {
1473 assert!(op.mistaken_for().is_empty());
1474 }
1475 let seen = |rels: &[Rel]| {
1480 let mut obs = Obs::default();
1481 for rel in rels {
1482 obs.merge(&Obs::of_rel(*rel));
1483 }
1484 obs
1485 };
1486 for (op, reverse) in [(CmpOp::Ge, CmpOp::Lt), (CmpOp::Le, CmpOp::Gt)] {
1487 let run = |rels: &[Rel]| plan_cmp(op, &seen(rels), None).run;
1488 let reversed = |rels: &[Rel]| run(rels).contains(&Mutation::Op(reverse));
1489 assert!(reversed(&[Rel::Unordered, Rel::Less]), "{op:?}");
1490 assert!(reversed(&[Rel::Less, Rel::Greater]), "{op:?}");
1491 assert!(reversed(&[Rel::Less, Rel::Equal, Rel::Greater]), "{op:?}");
1492 assert_eq!(run(&[Rel::Unordered]), vec![Mutation::Negate], "{op:?}");
1496 for ds in [&[-1i128, 1][..], &[-2, 0, 3], &[0, 1]] {
1498 let plan = plan_cmp(op, &obs_of(ds), None);
1499 assert!(!plan.run.contains(&Mutation::Op(reverse)), "{op:?} {ds:?}");
1500 }
1501 for d in -3..=3 {
1502 assert_eq!(eval_mutated_d(op, Mutation::Negate, d), reverse.eval_d(d));
1503 }
1504 }
1505 let run = plan_cmp(CmpOp::Eq, &seen(&[Rel::Unordered, Rel::Equal]), None).run;
1507 assert_eq!(run, vec![Mutation::Negate]);
1508 let plan = plan_cmp(CmpOp::Lt, &Obs::of_rel(Rel::Greater), None);
1511 assert_eq!(plan.run, vec![Mutation::Negate, Mutation::Op(CmpOp::Gt)]);
1512 }
1513
1514 #[test]
1515 fn pinned_boundary_has_no_input_gap() {
1516 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1517 let plan = plan_cmp(op, &obs_of(&[-1, 0, 1]), None);
1518 assert_eq!(plan.gap, None, "{op:?}");
1519 let mut run = vec![Mutation::Shift(-1), Mutation::Shift(1), Mutation::Negate];
1521 run.extend(op.mistaken_for().iter().map(|other| Mutation::Op(*other)));
1522 assert_eq!(plan.run, run, "{op:?}");
1523 }
1524 }
1525
1526 #[test]
1527 fn unreached_site() {
1528 let plan = plan_cmp(CmpOp::Lt, &Obs::default(), None);
1529 assert_eq!(
1530 plan,
1531 CmpPlan {
1532 cannot_differ: false,
1533 gap: Some(InputGap::Unreached),
1534 run: vec![]
1535 }
1536 );
1537 }
1538
1539 #[test]
1540 fn one_sided_condition() {
1541 let plan = plan_cmp(CmpOp::Gt, &obs_of(&[3, 5]), None);
1542 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1543 assert_eq!(
1545 plan.run,
1546 vec![
1547 Mutation::Negate,
1548 Mutation::Op(CmpOp::Eq),
1549 Mutation::Op(CmpOp::Lt)
1550 ]
1551 );
1552 }
1553
1554 #[test]
1555 fn unsigned_compared_with_zero_is_not_reported() {
1556 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((0, 255)));
1558 assert_eq!(plan.gap, None);
1559 assert!(plan.cannot_differ);
1560 assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 255))).cannot_differ);
1561 assert!(!plan_cmp(CmpOp::Ge, &obs_of(&[-1, 4]), Some((-1, 255))).cannot_differ);
1562 let plan = plan_cmp(CmpOp::Lt, &obs_of(&[0, 4]), Some((0, 255)));
1564 assert_eq!(plan.gap, None);
1565 let plan = plan_cmp(CmpOp::Gt, &obs_of(&[0, 1]), Some((0, 255)));
1568 assert_eq!(plan.gap, None);
1569 assert_eq!(
1571 plan.run,
1572 vec![
1573 Mutation::Shift(-1),
1574 Mutation::Shift(1),
1575 Mutation::Negate,
1576 Mutation::Op(CmpOp::Eq),
1577 Mutation::Op(CmpOp::Lt)
1578 ]
1579 );
1580 let plan = plan_cmp(CmpOp::Le, &obs_of(&[0, 1]), Some((0, 255)));
1583 assert_eq!(plan.gap, None);
1584 }
1585
1586 #[test]
1587 fn one_sided_condition_at_the_edge_of_the_type() {
1588 let plan = plan_cmp(CmpOp::Ge, &obs_of(&[0, 4]), Some((-1, 10)));
1590 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1591 let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 1)));
1593 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1594 let plan = plan_cmp(CmpOp::Le, &obs_of(&[-4, 0]), Some((-10, 0)));
1595 assert_eq!(plan.gap, None);
1596 let plan = plan_cmp(CmpOp::Ge, &Obs::of_rel(Rel::Greater), Some((0, 10)));
1598 assert_eq!(plan.gap, Some(InputGap::OneSided { always: true }));
1599 }
1600
1601 #[test]
1602 fn representative_is_the_nearest_survivor() {
1603 let boundary = |min_shift, max_shift| InputGap::Boundary {
1604 min_shift,
1605 max_shift,
1606 missing: vec![0],
1607 same: (0, 0),
1608 };
1609 assert_eq!(boundary(-3, 1).representative(), Some(Mutation::Shift(1)));
1610 assert_eq!(boundary(-1, 0).representative(), Some(Mutation::Shift(-1)));
1611 assert_eq!(boundary(0, 0).representative(), None);
1612 assert_eq!(InputGap::Unreached.representative(), None);
1613 assert_eq!(
1614 InputGap::OneSided { always: false }.representative(),
1615 Some(Mutation::Const(false))
1616 );
1617 assert_eq!(
1618 InputGap::EqualNeverObserved {
1619 flipped: CmpOp::Ge,
1620 float_gap: None
1621 }
1622 .representative(),
1623 Some(Mutation::Op(CmpOp::Ge))
1624 );
1625 }
1626
1627 fn eval_logic(and: bool, m: Option<Mutation>, a: bool, b: bool) -> (bool, bool) {
1630 let decided = |and: bool| if and { !a } else { a };
1631 match m {
1632 None => {
1633 if decided(and) {
1634 (a, false)
1635 } else {
1636 (b, true)
1637 }
1638 }
1639 Some(Mutation::LogicSwap) => {
1640 if decided(!and) {
1641 (a, false)
1642 } else {
1643 (b, true)
1644 }
1645 }
1646 Some(Mutation::LogicDropRhs) => (a, !decided(and)),
1648 Some(Mutation::LogicDropLhs) => (b, true),
1649 other => panic!("{other:?}"),
1650 }
1651 }
1652
1653 #[test]
1654 fn logic_plans_match_a_reference_evaluator() {
1655 let cases = [(false, false), (false, true), (true, false), (true, true)];
1656 for and in [true, false] {
1657 for mask in 0u32..16 {
1658 let seen: Vec<(bool, bool)> = cases
1659 .iter()
1660 .enumerate()
1661 .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1662 .collect();
1663 let mut obs = LogicObs::default();
1664 for (a, b) in &seen {
1665 let (_, evaluated) = eval_logic(and, None, *a, *b);
1666 obs.short |= !evaluated;
1667 obs.rhs_true |= evaluated && *b;
1668 obs.rhs_false |= evaluated && !*b;
1669 }
1670 let ctx = format!("and={and} seen={seen:?}");
1671 let differs = |m: Mutation| {
1672 seen.iter().any(|(a, b)| {
1673 eval_logic(and, None, *a, *b) != eval_logic(and, Some(m), *a, *b)
1674 })
1675 };
1676 let plan = plan_logic(and, &obs);
1677 if seen.is_empty() {
1678 assert_eq!(
1679 plan,
1680 LogicPlan {
1681 gaps: vec![LogicGap::Unreached],
1682 run: vec![]
1683 }
1684 );
1685 continue;
1686 }
1687 for (m, gap) in [
1688 (Mutation::LogicDropRhs, LogicGap::RhsNeverDecides),
1689 (Mutation::LogicDropLhs, LogicGap::LhsNeverDecides),
1690 ] {
1691 assert_eq!(plan.gaps.contains(&gap), !differs(m), "{gap:?} {ctx}");
1693 assert_eq!(plan.run.contains(&m), differs(m), "{m:?} {ctx}");
1694 assert_eq!(logic_infects(and, m, &obs), differs(m), "{m:?} {ctx}");
1695 }
1696 assert!(plan.run.contains(&Mutation::LogicSwap), "{ctx}");
1698 assert!(logic_infects(and, Mutation::LogicSwap, &obs), "{ctx}");
1699 }
1700 }
1701 let started = LogicObs::from_bits(8);
1705 assert!(started.rhs_started && started.reached());
1706 for and in [true, false] {
1707 let plan = plan_logic(and, &started);
1708 assert_eq!(plan.run, vec![Mutation::LogicSwap]);
1709 assert_eq!(
1710 plan.gaps,
1711 vec![LogicGap::RhsNeverDecides, LogicGap::LhsNeverDecides]
1712 );
1713 assert!(logic_infects(and, Mutation::LogicSwap, &started));
1714 assert!(!logic_infects(and, Mutation::LogicDropRhs, &started));
1715 assert!(!logic_infects(and, Mutation::LogicDropLhs, &started));
1716 }
1717 let mut merged = LogicObs::from_bits(2);
1718 merged.merge(&started);
1719 assert_eq!(merged, LogicObs::from_bits(10));
1720 assert_eq!(
1721 LogicObs::from_bits(5),
1722 LogicObs {
1723 short: true,
1724 rhs_true: false,
1725 rhs_false: true,
1726 rhs_started: false,
1727 }
1728 );
1729 assert_eq!(
1730 LogicObs::from_bits(2),
1731 LogicObs {
1732 short: false,
1733 rhs_true: true,
1734 rhs_false: false,
1735 rhs_started: false,
1736 }
1737 );
1738 }
1739
1740 #[test]
1741 fn return_plans() {
1742 assert_eq!(
1743 plan_return(&ReturnObs::from_bits(0)),
1744 ReturnPlan {
1745 unreached: true,
1746 always: None,
1747 run: vec![]
1748 }
1749 );
1750 assert_eq!(
1751 plan_return(&ReturnObs::from_bits(1)),
1752 ReturnPlan {
1753 unreached: false,
1754 always: Some(true),
1755 run: vec![Mutation::Const(false)]
1756 }
1757 );
1758 assert_eq!(
1759 plan_return(&ReturnObs::from_bits(2)),
1760 ReturnPlan {
1761 unreached: false,
1762 always: Some(false),
1763 run: vec![Mutation::Const(true)]
1764 }
1765 );
1766 assert_eq!(
1767 plan_return(&ReturnObs::from_bits(3)),
1768 ReturnPlan {
1769 unreached: false,
1770 always: None,
1771 run: vec![Mutation::Const(true), Mutation::Const(false)]
1772 }
1773 );
1774 for bits in 0u8..4 {
1776 let obs = ReturnObs::from_bits(bits);
1777 assert_eq!(obs.infected_by_const(true), obs.saw_false);
1778 assert_eq!(obs.infected_by_const(false), obs.saw_true);
1779 assert_eq!(obs.reached(), bits != 0);
1780 let plan = plan_return(&obs);
1781 for m in &plan.run {
1782 let Mutation::Const(value) = m else { panic!() };
1783 assert!(
1784 obs.infected_by_const(*value),
1785 "a run mutant must change some test"
1786 );
1787 }
1788 if let Some(always) = plan.always {
1789 assert!(
1790 !obs.infected_by_const(always),
1791 "the survivor changes no test"
1792 );
1793 }
1794 }
1795 let mut merged = ReturnObs::from_bits(1);
1796 merged.merge(&ReturnObs::from_bits(2));
1797 assert_eq!(
1798 merged,
1799 ReturnObs {
1800 saw_true: true,
1801 saw_false: true
1802 }
1803 );
1804 }
1805
1806 #[test]
1807 fn logic_constant_value() {
1808 let cases = [(false, false), (false, true), (true, false), (true, true)];
1809 for and in [true, false] {
1810 for mask in 0u32..16 {
1811 let seen: Vec<(bool, bool)> = cases
1812 .iter()
1813 .enumerate()
1814 .filter_map(|(i, c)| (mask & (1 << i) != 0).then_some(*c))
1815 .collect();
1816 let mut obs = LogicObs::default();
1817 let mut values = std::collections::BTreeSet::new();
1818 for (a, b) in &seen {
1819 let (value, evaluated) = eval_logic(and, None, *a, *b);
1820 values.insert(value);
1821 obs.short |= !evaluated;
1822 obs.rhs_true |= evaluated && *b;
1823 obs.rhs_false |= evaluated && !*b;
1824 }
1825 let expected = if values.len() == 1 {
1826 values.first().copied()
1827 } else {
1828 None
1829 };
1830 assert_eq!(obs.constant_value(and), expected, "and={and} seen={seen:?}");
1831 }
1832 }
1833 }
1834
1835 #[test]
1836 fn option_return_plans() {
1837 let plan = |bits| plan_option_return(&ReturnObs::from_bits(bits));
1838 assert_eq!(
1839 plan(0),
1840 ReturnPlan {
1841 unreached: true,
1842 always: None,
1843 run: vec![]
1844 }
1845 );
1846 assert_eq!(
1848 plan(2),
1849 ReturnPlan {
1850 unreached: false,
1851 always: Some(false),
1852 run: vec![]
1853 }
1854 );
1855 for bits in [1, 3] {
1857 assert_eq!(
1858 plan(bits),
1859 ReturnPlan {
1860 unreached: false,
1861 always: None,
1862 run: vec![Mutation::Const(false)]
1863 }
1864 );
1865 assert!(ReturnObs::from_bits(bits).infected_by_const(false));
1866 }
1867 assert!(!ReturnObs::from_bits(2).infected_by_const(false));
1868 }
1869
1870 #[test]
1871 fn arithmetic_plans() {
1872 for bits in 0u8..8 {
1873 let obs = ArithObs::from_bits(bits);
1874 let expected = if bits & 2 != 0 {
1875 ArithPlan::Run
1876 } else if bits & 1 != 0 {
1877 ArithPlan::NeverDiffers
1878 } else if bits & 4 != 0 {
1879 ArithPlan::Opaque
1880 } else {
1881 ArithPlan::Unreached
1882 };
1883 assert_eq!(plan_arith(&obs), expected, "bits={bits}");
1884 }
1885 let mut merged = ArithObs::from_bits(1);
1886 merged.merge(&ArithObs::from_bits(4));
1887 assert_eq!(
1888 merged,
1889 ArithObs {
1890 same: true,
1891 differs: false,
1892 opaque: true,
1893 ..Default::default()
1894 }
1895 );
1896 }
1897
1898 #[test]
1899 fn float_comparison_without_equal_operands() {
1900 let mut obs = Obs::of_f(-20.5);
1902 obs.merge(&Obs::of_f(9.5));
1903 let plan = plan_cmp(CmpOp::Gt, &obs, None);
1904 let gap = plan.gap.expect("a gap");
1905 assert_eq!(
1906 gap,
1907 InputGap::EqualNeverObserved {
1908 flipped: CmpOp::Ge,
1909 float_gap: Some((-20.5, 9.5))
1910 }
1911 );
1912 assert_eq!(
1913 gap.survivors(),
1914 vec![
1915 Mutation::Op(CmpOp::Ge),
1916 Mutation::ShiftF(4.75),
1917 Mutation::ShiftF(-10.25)
1918 ]
1919 );
1920 for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1923 assert!(!infects(op, Mutation::ShiftF(4.75), &obs));
1924 assert!(!infects(op, Mutation::ShiftF(-10.25), &obs));
1925 assert!(infects(op, Mutation::ShiftF(9.5), &obs));
1926 assert!(infects(op, Mutation::ShiftF(-20.5), &obs));
1927 }
1928 let mut with_eq = obs;
1929 with_eq.merge(&Obs::of_f(0.0));
1930 assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &with_eq));
1931 assert_eq!(plan_cmp(CmpOp::Gt, &with_eq, None).gap, None);
1932 let mut mixed = obs;
1934 mixed.merge(&Obs::of_rel(Rel::Less));
1935 assert_eq!(mixed.float_gap(), None);
1936 assert!(infects(CmpOp::Gt, Mutation::ShiftF(4.75), &mixed));
1937 assert_eq!(Obs::of_d(3).float_gap(), None);
1938 }
1939
1940 #[test]
1941 fn survivors_are_listed_nearest_first() {
1942 let boundary = |min_shift, max_shift| InputGap::Boundary {
1943 min_shift,
1944 max_shift,
1945 missing: vec![0],
1946 same: (0, 0),
1947 };
1948 assert_eq!(
1949 boundary(-9, 9).survivors(),
1950 vec![Mutation::Shift(1), Mutation::Shift(-1), Mutation::Shift(2)]
1951 );
1952 assert_eq!(boundary(-1, 0).survivors(), vec![Mutation::Shift(-1)]);
1953 assert_eq!(
1954 boundary(0, 2).survivors(),
1955 vec![Mutation::Shift(1), Mutation::Shift(2)]
1956 );
1957 assert_eq!(
1958 InputGap::OneSided { always: true }.survivors(),
1959 vec![Mutation::Const(true)]
1960 );
1961 assert_eq!(InputGap::Unreached.survivors(), vec![]);
1962 }
1963
1964 #[test]
1965 fn single_observation_summaries() {
1966 let bits = |o: Obs| (o.lt, o.eq, o.gt, o.un);
1967 assert_eq!(bits(Obs::of_f(-0.5)), (true, false, false, false));
1968 assert_eq!(bits(Obs::of_f(0.0)), (false, true, false, false));
1969 assert_eq!(bits(Obs::of_f(0.5)), (false, false, true, false));
1970 assert_eq!(
1971 (Obs::of_f(-0.5).f_max_neg, Obs::of_f(-0.5).f_min_pos),
1972 (Some(-0.5), None)
1973 );
1974 assert_eq!(
1975 (Obs::of_f(0.5).f_max_neg, Obs::of_f(0.5).f_min_pos),
1976 (None, Some(0.5))
1977 );
1978 assert_eq!(
1979 (Obs::of_f(0.0).f_max_neg, Obs::of_f(0.0).f_min_pos),
1980 (None, None)
1981 );
1982 assert!(Obs::of_f(1.0).unvalued && !Obs::of_f(1.0).unfloat);
1983 assert!(Obs::of_d(1).unfloat && !Obs::of_d(1).unvalued);
1984
1985 assert!(Obs::of_rel(Rel::Unordered).reached());
1987 assert!(!Obs::default().reached());
1988 assert!(!Obs::default().valued());
1990 assert!(Obs::of_d(0).valued());
1991 assert!(!Obs::of_rel(Rel::Equal).valued());
1992
1993 let mut nan = Obs::of_f(-1.0);
1995 nan.merge(&Obs::of_f(1.0));
1996 assert_eq!(nan.float_gap(), Some((-1.0, 1.0)));
1997 nan.un = true;
1998 assert_eq!(nan.float_gap(), None);
1999 assert_eq!(Obs::default().float_gap(), None);
2000 assert_eq!(Obs::of_f(-1.0).float_gap(), None, "one side only");
2001 }
2002
2003 #[test]
2004 fn interval_queries_look_at_the_right_side_of_zero() {
2005 assert!(!obs_of(&[2]).saw_any_in(-3, -1));
2007 assert!(!obs_of(&[-2]).saw_any_in(1, 3));
2008 assert!(obs_of(&[-2]).saw_any_in(-3, -1));
2009 assert!(obs_of(&[2]).saw_any_in(1, 3));
2010 assert!(!obs_of(&[-4]).saw_any_in(-3, 0));
2011 assert!(!obs_of(&[4]).saw_any_in(0, 3));
2012 let mut odd = obs_of(&[3]);
2014 odd.max_neg = Some(5);
2015 assert!(!odd.saw_any_in(0, 2));
2016 let mut odd = obs_of(&[-3]);
2017 odd.min_pos = Some(-5);
2018 assert!(!odd.saw_any_in(-2, 0));
2019 }
2020
2021 #[test]
2022 fn empty_interval_has_no_observations() {
2023 assert!(!obs_of(&[-1, 0, 1]).saw_any_in(1, 0));
2024 assert!(obs_of(&[0]).saw_any_in(0, 0));
2025 }
2026
2027 #[test]
2028 fn unvalued_ordering_without_equal_operands() {
2029 let mut obs = Obs::of_rel(Rel::Less);
2030 obs.merge(&Obs::of_rel(Rel::Greater));
2031 let plan = plan_cmp(CmpOp::Lt, &obs, None);
2032 assert_eq!(
2033 plan.gap,
2034 Some(InputGap::EqualNeverObserved {
2035 flipped: CmpOp::Le,
2036 float_gap: None
2037 })
2038 );
2039 assert_eq!(
2041 plan.run,
2042 vec![
2043 Mutation::Negate,
2044 Mutation::Op(CmpOp::Eq),
2045 Mutation::Op(CmpOp::Gt)
2046 ]
2047 );
2048
2049 obs.merge(&Obs::of_rel(Rel::Equal));
2050 let plan = plan_cmp(CmpOp::Lt, &obs, None);
2051 assert_eq!(plan.gap, None);
2052 assert_eq!(
2053 plan.run,
2054 vec![
2055 Mutation::Op(CmpOp::Le),
2056 Mutation::Negate,
2057 Mutation::Op(CmpOp::Eq),
2058 Mutation::Op(CmpOp::Gt)
2059 ]
2060 );
2061 }
2062
2063 #[test]
2064 fn equality_with_both_outcomes() {
2065 let plan = plan_cmp(CmpOp::Eq, &obs_of(&[0, 7]), None);
2066 assert_eq!(
2067 plan,
2068 CmpPlan {
2069 cannot_differ: false,
2070 gap: None,
2071 run: vec![Mutation::Negate]
2072 }
2073 );
2074 }
2075
2076 #[test]
2077 fn unordered_counts_as_not_equal() {
2078 let obs = Obs::of_rel(Rel::Unordered);
2079 assert!(infects(CmpOp::Ne, Mutation::Const(false), &obs));
2080 assert!(!infects(CmpOp::Lt, Mutation::Op(CmpOp::Ge), &obs));
2081 assert!(infects(CmpOp::Lt, Mutation::Op(CmpOp::Ne), &obs));
2082 }
2083
2084 #[test]
2085 fn merge_is_a_semilattice() {
2086 let samples: Vec<Obs> = [-3, -1, 0, 1, 4]
2087 .into_iter()
2088 .map(Obs::of_d)
2089 .chain([
2090 Obs::of_rel(Rel::Unordered),
2091 Obs::of_rel(Rel::Less),
2092 Obs::default(),
2093 ])
2094 .collect();
2095 for a in &samples {
2096 let mut aa = *a;
2097 aa.merge(a);
2098 assert_eq!(aa, *a, "idempotent");
2099 for b in &samples {
2100 let (mut ab, mut ba) = (*a, *b);
2101 ab.merge(b);
2102 ba.merge(a);
2103 assert_eq!(ab, ba, "commutative");
2104 for c in &samples {
2105 let mut ab_c = ab;
2106 ab_c.merge(c);
2107 let mut bc = *b;
2108 bc.merge(c);
2109 let mut a_bc = *a;
2110 a_bc.merge(&bc);
2111 assert_eq!(ab_c, a_bc, "associative");
2112 }
2113 }
2114 }
2115 }
2116
2117 #[test]
2118 fn mutation_wire_format() {
2119 assert_eq!(Mutation::Const(true).encode(), "c1");
2120 assert_eq!(Mutation::Const(false).encode(), "c0");
2121 assert_eq!(Mutation::Negate.encode(), "neg");
2122 assert_eq!(Mutation::Op(CmpOp::Ge).encode(), "op3");
2123 assert_eq!(Mutation::Shift(-2).encode(), "sh-2");
2124 assert_eq!(Mutation::Delete.encode(), "del");
2125 assert_eq!(Mutation::ShiftF(4.75).encode(), "shf4.75");
2126 assert_eq!(Mutation::ShiftF(-10.0).encode(), "shf-10.0");
2127 assert_eq!(Mutation::LogicSwap.encode(), "lsw");
2128 assert_eq!(Mutation::LogicDropRhs.encode(), "ldr");
2129 assert_eq!(Mutation::LogicDropLhs.encode(), "ldl");
2130 assert_eq!(Mutation::ArithSwap.encode(), "asw");
2131 assert_eq!(Mutation::DropNot.encode(), "unn");
2132 assert_eq!(Mutation::RangeEnd.encode(), "rng");
2133 assert_eq!(Mutation::MinMax.encode(), "mmx");
2134 assert_eq!(Mutation::OtherEnd.encode(), "end");
2135 }
2136
2137 fn candidate_mutations(op: CmpOp) -> Vec<Mutation> {
2138 let mut ms = vec![
2139 Mutation::Const(true),
2140 Mutation::Const(false),
2141 Mutation::Negate,
2142 ];
2143 ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
2144 if op.is_ordering() {
2145 ms.extend((-5..=5).filter(|s| *s != 0).map(Mutation::Shift));
2146 }
2147 ms
2148 }
2149
2150 fn check_plan(op: CmpOp, ds: &[i128], domain: Option<(i128, i128)>) {
2152 let obs = obs_of(ds);
2153 let ctx = format!("{op:?} ds={ds:?} domain={domain:?}");
2154 let (dom_lo, dom_hi) = domain.unwrap_or((-50, 50));
2155 let differs_somewhere =
2156 |m: Mutation| (dom_lo..=dom_hi).any(|d| op.eval_d(d) != eval_mutated_d(op, m, d));
2157
2158 for m in candidate_mutations(op) {
2159 assert_eq!(
2160 infects(op, m, &obs),
2161 brute_infects(op, m, ds),
2162 "infects {m:?} {ctx}"
2163 );
2164 }
2165
2166 let plan = plan_cmp(op, &obs, domain);
2167 for m in &plan.run {
2168 assert!(
2169 brute_infects(op, *m, ds),
2170 "run {m:?} must be infected: {ctx}"
2171 );
2172 assert!(differs_somewhere(*m), "run {m:?} is equivalent: {ctx}");
2173 }
2174 match &plan.gap {
2175 None => {}
2176 Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2177 Some(InputGap::OneSided { always }) => {
2178 assert!(ds.iter().all(|d| op.eval_d(*d) == *always), "{ctx}");
2179 assert!(differs_somewhere(Mutation::Const(*always)), "{ctx}");
2180 }
2181 Some(InputGap::Boundary {
2182 min_shift,
2183 max_shift,
2184 missing,
2185 same: _,
2186 }) => {
2187 assert!(*min_shift <= 0 && 0 <= *max_shift, "{ctx}");
2188 for s in (*min_shift..=*max_shift).filter(|s| *s != 0) {
2189 let m = Mutation::Shift(s);
2190 assert!(
2191 !brute_infects(op, m, ds),
2192 "survivor {m:?} is infected: {ctx}"
2193 );
2194 assert!(differs_somewhere(m), "survivor {m:?} is equivalent: {ctx}");
2195 }
2196 if domain.is_none() {
2197 for s in [min_shift - 1, max_shift + 1] {
2199 assert!(
2200 brute_infects(op, Mutation::Shift(s), ds),
2201 "range not maximal: {ctx}"
2202 );
2203 }
2204 }
2205 assert!(!missing.is_empty(), "{ctx}");
2206 for w in missing {
2207 assert!(!ds.contains(w), "missing value {w} was observed: {ctx}");
2208 assert!(
2209 dom_lo <= *w && *w <= dom_hi,
2210 "missing value {w} out of domain: {ctx}"
2211 );
2212 let s = if op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(1), *w) {
2213 1
2214 } else {
2215 -1
2216 };
2217 assert!(
2218 op.eval_d(*w) != eval_mutated_d(op, Mutation::Shift(s), *w),
2219 "missing value {w} separates nothing: {ctx}"
2220 );
2221 assert!(*min_shift <= s && s <= *max_shift, "{ctx}");
2222 }
2223 }
2224 Some(InputGap::EqualNeverObserved { .. }) => panic!("valued site: {ctx}"),
2225 }
2226 if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2227 assert!(
2228 !brute_infects(op, m, ds),
2229 "representative {m:?} is infected: {ctx}"
2230 );
2231 }
2232
2233 if op.is_ordering() && ds.iter().any(|d| op.eval_d(*d)) && ds.iter().any(|d| !op.eval_d(*d))
2235 {
2236 for s in [-1, 1] {
2237 let m = Mutation::Shift(s);
2238 let survivor = matches!(&plan.gap, Some(InputGap::Boundary { min_shift, max_shift, .. })
2239 if *min_shift <= s && s <= *max_shift);
2240 let ran = plan.run.contains(&m);
2241 assert!(
2242 survivor ^ ran || !differs_somewhere(m),
2243 "Shift({s}) unaccounted for: survivor={survivor} ran={ran} {ctx}"
2244 );
2245 }
2246 }
2247 }
2248
2249 #[test]
2250 fn exhaustive_small_observation_sets() {
2251 let universe: Vec<i128> = (-3..=3).collect();
2252 for op in CmpOp::ALL {
2253 for mask in 0u32..(1 << universe.len()) {
2254 let ds: Vec<i128> = universe
2255 .iter()
2256 .enumerate()
2257 .filter_map(|(i, d)| (mask & (1 << i) != 0).then_some(*d))
2258 .collect();
2259 check_plan(op, &ds, None);
2260 for (lo, hi) in [(0, 10), (-10, 0), (-2, 2), (1, 9), (-9, -1)] {
2262 if ds.iter().all(|d| lo <= *d && *d <= hi) {
2263 check_plan(op, &ds, Some((lo, hi)));
2264 }
2265 }
2266 }
2267 }
2268 }
2269
2270 #[test]
2272 fn pict_table() {
2273 let table = include_str!("../tests/data/planner.pict.tsv");
2274 let mut rows = 0;
2275 for line in table.lines().skip(1) {
2276 let cols: Vec<&str> = line.split('\t').collect();
2277 let [op, below, equal, above, valued, literal, domain] = cols[..] else {
2278 panic!("bad row: {line}");
2279 };
2280 let op = match op {
2281 "lt" => CmpOp::Lt,
2282 "le" => CmpOp::Le,
2283 "gt" => CmpOp::Gt,
2284 "ge" => CmpOp::Ge,
2285 "eq" => CmpOp::Eq,
2286 "ne" => CmpOp::Ne,
2287 other => panic!("op {other}"),
2288 };
2289 let mut ds: Vec<i128> = vec![];
2290 match below {
2291 "none" => {}
2292 "adjacent" => ds.extend([-1, -4]),
2293 "far" => ds.extend([-3, -6]),
2294 other => panic!("below {other}"),
2295 }
2296 if equal == "yes" {
2297 ds.push(0);
2298 }
2299 match above {
2300 "none" => {}
2301 "adjacent" => ds.extend([1, 5]),
2302 "far" => ds.extend([3, 7]),
2303 other => panic!("above {other}"),
2304 }
2305 rows += 1;
2306 if valued == "no" {
2307 let mut obs = Obs::default();
2308 for d in &ds {
2309 obs.merge(&Obs::of_rel(rel_of(*d)));
2310 }
2311 check_unvalued(op, &obs, &ds, line);
2312 continue;
2313 }
2314 let domain = match (literal, domain) {
2317 ("none", _) => None,
2318 (_, "wide") => Some((-40, 40)),
2319 ("rhs", "tight_low") | ("lhs", "tight_high") => Some((0, 40)),
2320 ("rhs", "tight_high") | ("lhs", "tight_low") => Some((-40, 0)),
2321 other => panic!("domain {other:?}"),
2322 };
2323 check_plan(op, &ds, domain);
2324 }
2325 assert_eq!(rows, table.lines().count() - 1);
2326 assert!(rows > 50, "the PICT table looks truncated: {rows} rows");
2327 }
2328
2329 fn check_unvalued(op: CmpOp, obs: &Obs, ds: &[i128], ctx: &str) {
2330 let plan = plan_cmp(op, obs, None);
2331 for m in [
2332 Mutation::Const(true),
2333 Mutation::Const(false),
2334 Mutation::Negate,
2335 ]
2336 .into_iter()
2337 .chain(CmpOp::ALL.into_iter().map(Mutation::Op))
2338 {
2339 assert_eq!(
2340 infects(op, m, obs),
2341 brute_infects(op, m, ds),
2342 "infects {m:?} {ctx}"
2343 );
2344 }
2345 for m in &plan.run {
2346 assert!(
2347 brute_infects(op, *m, ds),
2348 "run {m:?} must be infected: {ctx}"
2349 );
2350 }
2351 if let Some(m) = plan.gap.as_ref().and_then(InputGap::representative) {
2352 assert!(
2353 !brute_infects(op, m, ds),
2354 "representative {m:?} is infected: {ctx}"
2355 );
2356 }
2357 match &plan.gap {
2358 Some(InputGap::Boundary { .. }) => panic!("unvalued site cannot shift: {ctx}"),
2359 Some(InputGap::EqualNeverObserved { flipped, .. }) => {
2360 assert!(!ds.contains(&0), "{ctx}");
2361 assert_eq!(op.flip_eq(), Some(*flipped), "{ctx}");
2362 }
2363 Some(InputGap::Unreached) => assert!(ds.is_empty(), "{ctx}"),
2364 _ => {}
2365 }
2366 if op.is_ordering() && obs.reached() {
2368 assert!(infects(op, Mutation::Shift(1), obs), "{ctx}");
2369 }
2370 }
2371
2372 #[test]
2373 fn logic_swap_never_changes_value_matches_pict_table() {
2374 let table = include_str!("../tests/data/logic-swap.pict.tsv");
2375 let mut rows = 0;
2376 for line in table.lines().skip(1).filter(|l| !l.trim().is_empty()) {
2377 let cols: Vec<&str> = line.split('\t').collect();
2378 assert_eq!(cols.len(), 5, "unexpected row: {line}");
2379 let and = match cols[0] {
2380 "and" => true,
2381 "or" => false,
2382 other => panic!("unexpected LogicOp: {other}"),
2383 };
2384 let obs = LogicObs {
2385 short: cols[1] == "true",
2386 rhs_true: cols[2] == "true",
2387 rhs_false: cols[3] == "true",
2388 rhs_started: cols[4] == "true",
2389 };
2390 let expected = if and {
2391 !obs.short && obs.rhs_true && !obs.rhs_false
2392 } else {
2393 !obs.short && !obs.rhs_true && obs.rhs_false
2394 };
2395 assert_eq!(
2396 obs.swap_never_changes_value(and),
2397 expected,
2398 "row={line} obs={obs:?}"
2399 );
2400 rows += 1;
2401 }
2402 assert!(rows >= 9, "expected PICT table rows, got {rows}");
2403 }
2404}