Skip to main content

targeted_mutation/
trace.rs

1//! Reads the trace written by the injected runtime (`src/runtime/tmt_rt.rs`).
2//!
3//! Lines are tab separated:
4//! - `O <site> <test> <rels> <unvalued> <max_neg|-> <min_pos|-> <unfloat> <f_max_neg|-> <f_min_pos|->`:
5//!   cumulative summary of a comparison
6//! - `R <site> <test> <bits>`: a statement site was executed
7//! - `L <site> <test> <bits>`: observations at `&&` / `||` (cumulative)
8//! - `A <site> <test> <bits>`: observations at an arithmetic operator (cumulative)
9//! - `B <site> <test> <bits>`: values a `-> bool` function returned (cumulative)
10//! - `T <site> <lhs_min> <lhs_max> <rhs_min> <rhs_max>`: integer type bounds of the operands
11//!
12//! A process killed mid-write can leave a truncated last line; malformed lines are skipped
13//! and counted rather than trusted.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use crate::plan::{ArithObs, LogicObs, Obs, ReturnObs};
18
19/// Test name used when the observing thread is not a libtest test thread.
20pub const UNKNOWN_TEST: &str = "?";
21
22#[derive(Clone, Copy, PartialEq, Eq, Debug)]
23pub struct TypeBounds {
24    pub lhs: (i128, i128),
25    pub rhs: (i128, i128),
26}
27
28#[derive(Default, Debug, PartialEq)]
29pub struct Trace {
30    /// site -> test -> observations
31    pub cmp: BTreeMap<u32, BTreeMap<String, Obs>>,
32    pub logic: BTreeMap<u32, BTreeMap<String, LogicObs>>,
33    pub arith: BTreeMap<u32, BTreeMap<String, ArithObs>>,
34    pub returns: BTreeMap<u32, BTreeMap<String, ReturnObs>>,
35    /// site -> tests that executed the statement
36    pub reach: BTreeMap<u32, BTreeSet<String>>,
37    /// Ranges `a..b` that some test ran with `b` at the largest value of its type.
38    pub ranges_at_top: BTreeSet<u32>,
39    pub bounds: BTreeMap<u32, TypeBounds>,
40    pub malformed_lines: usize,
41}
42
43fn flag(text: &str) -> Option<bool> {
44    match text {
45        "0" => Some(false),
46        "1" => Some(true),
47        _ => None,
48    }
49}
50
51fn optional<T: std::str::FromStr>(text: &str) -> Option<Option<T>> {
52    if text == "-" {
53        Some(None)
54    } else {
55        text.parse().ok().map(Some)
56    }
57}
58
59/// How many keys of two maps of maps have another value in one than in the other.
60fn differing<T: PartialEq>(
61    a: &BTreeMap<u32, BTreeMap<String, T>>,
62    b: &BTreeMap<u32, BTreeMap<String, T>>,
63) -> usize {
64    let one_way = |from: &BTreeMap<u32, BTreeMap<String, T>>,
65                   to: &BTreeMap<u32, BTreeMap<String, T>>,
66                   both: bool| {
67        from.iter()
68            .flat_map(|(site, tests)| tests.iter().map(move |(test, seen)| (site, test, seen)))
69            .filter(
70                |(site, test, seen)| match to.get(site).and_then(|tests| tests.get(*test)) {
71                    Some(other) => both && other != *seen,
72                    None => true,
73                },
74            )
75            .count()
76    };
77    one_way(a, b, true) + one_way(b, a, false)
78}
79
80impl Trace {
81    /// How many records (what one test saw at one site) are not the same in two traces
82    /// of the same tests. Tests that always do the same give none.
83    pub fn differences(&self, other: &Trace) -> usize {
84        let reach = |from: &Trace, to: &Trace| {
85            from.reach
86                .iter()
87                .flat_map(|(site, tests)| tests.iter().map(move |test| (site, test)))
88                .filter(|(site, test)| {
89                    !to.reach
90                        .get(site)
91                        .is_some_and(|tests| tests.contains(*test))
92                })
93                .count()
94        };
95        differing(&self.cmp, &other.cmp)
96            + differing(&self.logic, &other.logic)
97            + differing(&self.arith, &other.arith)
98            + differing(&self.returns, &other.returns)
99            + reach(self, other)
100            + reach(other, self)
101    }
102
103    pub fn parse(text: &str) -> Trace {
104        let mut trace = Trace::default();
105        for line in text.lines() {
106            if trace.parse_line(line).is_none() {
107                trace.malformed_lines += 1;
108            }
109        }
110        trace
111    }
112
113    fn parse_line(&mut self, line: &str) -> Option<()> {
114        let cols: Vec<&str> = line.split('\t').collect();
115        match cols[..] {
116            [
117                "O",
118                site,
119                test,
120                rels,
121                unvalued,
122                max_neg,
123                min_pos,
124                unfloat,
125                f_max_neg,
126                f_min_pos,
127            ] => {
128                let rels: u8 = rels.parse().ok().filter(|r| *r < 16)?;
129                let obs = Obs {
130                    lt: rels & 1 != 0,
131                    eq: rels & 2 != 0,
132                    gt: rels & 4 != 0,
133                    un: rels & 8 != 0,
134                    unvalued: flag(unvalued)?,
135                    max_neg: optional::<i128>(max_neg)?.filter(|d| *d < 0),
136                    min_pos: optional::<i128>(min_pos)?.filter(|d| *d > 0),
137                    unfloat: flag(unfloat)?,
138                    f_max_neg: optional::<f64>(f_max_neg)?.filter(|d| d.is_finite() && *d < 0.0),
139                    f_min_pos: optional::<f64>(f_min_pos)?.filter(|d| d.is_finite() && *d > 0.0),
140                };
141                let site = site.parse().ok()?;
142                (!test.is_empty()).then_some(())?;
143                self.cmp
144                    .entry(site)
145                    .or_default()
146                    .entry(test.to_string())
147                    .or_default()
148                    .merge(&obs);
149            }
150            [kind @ ("R" | "L" | "A" | "B"), site, test, bits] => {
151                let site: u32 = site.parse().ok()?;
152                let limit = match kind {
153                    "B" => 4,
154                    "A" => 32,
155                    "L" => 16,
156                    _ => 8,
157                };
158                let bits: u8 = bits.parse().ok().filter(|b| (1..limit).contains(b))?;
159                (!test.is_empty()).then_some(())?;
160                let test = test.to_string();
161                match kind {
162                    "R" => {
163                        if bits & 2 != 0 {
164                            self.ranges_at_top.insert(site);
165                        }
166                        self.reach.entry(site).or_default().insert(test);
167                    }
168                    "B" => self
169                        .returns
170                        .entry(site)
171                        .or_default()
172                        .entry(test)
173                        .or_default()
174                        .merge(&ReturnObs::from_bits(bits)),
175                    "L" => self
176                        .logic
177                        .entry(site)
178                        .or_default()
179                        .entry(test)
180                        .or_default()
181                        .merge(&LogicObs::from_bits(bits)),
182                    _ => self
183                        .arith
184                        .entry(site)
185                        .or_default()
186                        .entry(test)
187                        .or_default()
188                        .merge(&ArithObs::from_bits(bits)),
189                }
190            }
191            ["T", site, lhs_min, lhs_max, rhs_min, rhs_max] => {
192                let bounds = TypeBounds {
193                    lhs: (lhs_min.parse().ok()?, lhs_max.parse().ok()?),
194                    rhs: (rhs_min.parse().ok()?, rhs_max.parse().ok()?),
195                };
196                self.bounds.insert(site.parse().ok()?, bounds);
197            }
198            _ => return None,
199        }
200        Some(())
201    }
202
203    /// Everything any test observed at a comparison site.
204    pub fn merged(&self, site: u32) -> Obs {
205        let mut all = Obs::default();
206        for obs in self
207            .cmp
208            .get(&site)
209            .into_iter()
210            .flat_map(|tests| tests.values())
211        {
212            all.merge(obs);
213        }
214        all
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::plan::{CmpOp, Mutation, Rel, eval_mutated_d};
222    use crate::tmt_rt;
223
224    #[test]
225    fn parses_and_merges_lines() {
226        let trace = Trace::parse(
227            "O\t3\ttests::a\t1\t0\t-4\t-\t1\t-\t-\n\
228             O\t3\ttests::a\t5\t0\t-1\t2\t1\t-\t-\n\
229             O\t3\ttests::b\t2\t0\t-\t-\t1\t-\t-\n\
230             R\t9\ttests::a\t1\n\
231             R\t9\t?\t1\n\
232             T\t3\t0\t255\t0\t255\n",
233        );
234        assert_eq!(trace.malformed_lines, 0);
235        let a = trace.cmp[&3]["tests::a"];
236        assert_eq!(
237            (a.lt, a.eq, a.gt, a.max_neg, a.min_pos),
238            (true, false, true, Some(-1), Some(2))
239        );
240        assert!(trace.merged(3).eq);
241        assert_eq!(
242            trace.reach[&9].iter().collect::<Vec<_>>(),
243            ["?", "tests::a"]
244        );
245        assert_eq!(
246            trace.bounds[&3],
247            TypeBounds {
248                lhs: (0, 255),
249                rhs: (0, 255)
250            }
251        );
252        assert_eq!(trace.merged(42), Obs::default());
253    }
254
255    #[test]
256    fn skips_truncated_and_malformed_lines() {
257        let trace = Trace::parse(
258            "O\t3\ttests::a\t1\t0\t-4\nX\t1\nO\tx\tt\t1\t0\t-\t-\t1\t-\t-\nO\t1\tt\t99\t0\t-\t-\t1\t-\t-\nR\t1\t\t1\nR\t2\tok\t1\n",
259        );
260        assert_eq!(trace.malformed_lines, 5);
261        assert!(trace.cmp.is_empty());
262        assert_eq!(trace.reach.len(), 1);
263    }
264
265    #[test]
266    fn relation_bits_and_field_validation() {
267        for (rels, expected) in [(1, "lt"), (2, "eq"), (4, "gt"), (8, "un")] {
268            let trace = Trace::parse(&format!("O\t1\tt\t{rels}\t1\t-\t-\t1\t-\t-\n"));
269            let o = trace.cmp[&1]["t"];
270            let set: Vec<&str> = [(o.lt, "lt"), (o.eq, "eq"), (o.gt, "gt"), (o.un, "un")]
271                .into_iter()
272                .filter_map(|(on, name)| on.then_some(name))
273                .collect();
274            assert_eq!(set, [expected]);
275            assert!(o.unvalued);
276        }
277        // 15 is every relation, 16 is not a relation mask.
278        assert_eq!(
279            Trace::parse("O\t1\tt\t15\t0\t-\t-\t1\t-\t-\n").malformed_lines,
280            0
281        );
282        assert_eq!(
283            Trace::parse("O\t1\tt\t16\t0\t-\t-\t1\t-\t-\n").malformed_lines,
284            1
285        );
286        // A comparison line needs a test name too.
287        let nameless = Trace::parse("O\t1\t\t1\t0\t-\t-\t1\t-\t-\n");
288        assert_eq!((nameless.malformed_lines, nameless.cmp.len()), (1, 0));
289        // The nearest-below value is negative and the nearest-above positive, or they are dropped.
290        let signs = Trace::parse("O\t1\tt\t5\t0\t0\t0\t1\t-\t-\nO\t2\tt\t5\t0\t3\t-3\t1\t-\t-\n");
291        for site in [1, 2] {
292            let o = signs.cmp[&site]["t"];
293            assert_eq!((o.max_neg, o.min_pos), (None, None));
294        }
295    }
296
297    fn rt_op(op: CmpOp) -> u8 {
298        op.code()
299    }
300
301    fn rt_mutant(m: Mutation) -> tmt_rt::Mutant {
302        let spec = format!("7:{}", m.encode());
303        let (site, parsed) =
304            tmt_rt::parse_mutant(&spec).unwrap_or_else(|| panic!("runtime rejects {spec}"));
305        assert_eq!(site, 7);
306        parsed
307    }
308
309    /// The injected runtime is a separate source file; it must agree with the planner on
310    /// what every mutation does and on how observations are summarised.
311    #[test]
312    fn runtime_agrees_with_the_planner() {
313        for op in CmpOp::ALL {
314            let mut ms = vec![
315                Mutation::Const(true),
316                Mutation::Const(false),
317                Mutation::Negate,
318            ];
319            ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
320            if op.is_ordering() {
321                ms.extend((-4..=4).filter(|s| *s != 0).map(Mutation::Shift));
322            }
323            for m in ms {
324                for d in -6..=6i128 {
325                    let rel = if d < 0 {
326                        1
327                    } else if d == 0 {
328                        2
329                    } else {
330                        4
331                    };
332                    assert_eq!(
333                        tmt_rt::apply(
334                            rt_op(op),
335                            rt_mutant(m),
336                            op.eval_d(d),
337                            rel,
338                            tmt_rt::Diff::Int(d)
339                        ),
340                        eval_mutated_d(op, m, d),
341                        "{op:?} {m:?} d={d}"
342                    );
343                }
344            }
345            // Unordered operands (NaN): only `!=` is true.
346            assert_eq!(
347                tmt_rt::apply(
348                    rt_op(op),
349                    tmt_rt::Mutant::Op(rt_op(op)),
350                    false,
351                    8,
352                    tmt_rt::Diff::None
353                ),
354                op.eval_rel(Rel::Unordered)
355            );
356            // A shift needs values of its own kind; without them the original result stands.
357            for orig in [true, false] {
358                assert_eq!(
359                    tmt_rt::apply(
360                        rt_op(op),
361                        tmt_rt::Mutant::Shift(1),
362                        orig,
363                        2,
364                        tmt_rt::Diff::None
365                    ),
366                    orig
367                );
368                assert_eq!(
369                    tmt_rt::apply(
370                        rt_op(op),
371                        tmt_rt::Mutant::ShiftF(1.0),
372                        orig,
373                        2,
374                        tmt_rt::Diff::Int(0)
375                    ),
376                    orig
377                );
378                assert_eq!(
379                    tmt_rt::apply(
380                        rt_op(op),
381                        tmt_rt::Mutant::Delete,
382                        orig,
383                        2,
384                        tmt_rt::Diff::Int(0)
385                    ),
386                    orig
387                );
388            }
389        }
390        assert_eq!(
391            tmt_rt::parse_mutant("12:del"),
392            Some((12, tmt_rt::Mutant::Delete))
393        );
394        for (m, expected) in [
395            (Mutation::LogicSwap, tmt_rt::Mutant::LogicSwap),
396            (Mutation::LogicDropRhs, tmt_rt::Mutant::LogicDropRhs),
397            (Mutation::LogicDropLhs, tmt_rt::Mutant::LogicDropLhs),
398            (Mutation::ArithSwap, tmt_rt::Mutant::ArithSwap),
399            (Mutation::ArithSwap2, tmt_rt::Mutant::ArithSwap2),
400            (Mutation::ShiftF(-10.25), tmt_rt::Mutant::ShiftF(-10.25)),
401            (Mutation::ShiftF(1e-7), tmt_rt::Mutant::ShiftF(1e-7)),
402        ] {
403            assert_eq!(rt_mutant(m), expected);
404        }
405        for bad in [
406            "", "x:neg", "1:", "1:op9", "1:shx", "1:zzz", "neg", "1:shfnan", "1:shfinf", "1:shf",
407        ] {
408            assert_eq!(tmt_rt::parse_mutant(bad), None, "{bad:?}");
409        }
410    }
411
412    /// Float shifts: the runtime's result on the observed differences never changes for a
413    /// shift the planner calls safe.
414    #[test]
415    fn runtime_float_shifts_agree_with_the_planner() {
416        let observed = [-20.5f64, -3.0, 9.5, 12.0];
417        let mut obs = Obs::default();
418        for d in observed {
419            obs.merge(&Obs::of_f(d));
420        }
421        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
422            for shift in [-20.5, -10.0, -3.0, -1.5, 4.75, 9.5, 11.0] {
423                let changes_something = observed.iter().any(|d| {
424                    let rel = if *d < 0.0 { 1 } else { 4 };
425                    let orig = op.eval_d(if *d < 0.0 { -1 } else { 1 });
426                    tmt_rt::apply(
427                        rt_op(op),
428                        tmt_rt::Mutant::ShiftF(shift),
429                        orig,
430                        rel,
431                        tmt_rt::Diff::Float(*d),
432                    ) != orig
433                });
434                let predicted = crate::plan::infects(op, Mutation::ShiftF(shift), &obs);
435                // Safe by the planner implies unchanged at run time (the converse need not hold
436                // exactly at the edges of the gap).
437                assert!(predicted || !changes_something, "{op:?} shift={shift}");
438            }
439        }
440        // Equal floats are reported as a zero difference even where subtraction is not finite.
441        use tmt_rt::{Diff, Val};
442        assert_eq!(
443            tmt_rt::diff(Val::Float(f64::INFINITY), Val::Float(f64::INFINITY), true),
444            Diff::Float(0.0)
445        );
446        assert_eq!(
447            tmt_rt::diff(Val::Float(f64::INFINITY), Val::Float(1.0), false),
448            Diff::None
449        );
450        assert_eq!(
451            tmt_rt::diff(Val::Float(f64::NAN), Val::Float(1.0), false),
452            Diff::None
453        );
454        assert_eq!(
455            tmt_rt::diff(Val::Float(1.5), Val::Float(1.0), false),
456            Diff::Float(0.5)
457        );
458        assert_eq!(
459            tmt_rt::diff(Val::Int(3, 0, 9), Val::Int(5, 0, 9), false),
460            Diff::Int(-2)
461        );
462        assert_eq!(
463            tmt_rt::diff(Val::Int(3, 0, 9), Val::Float(5.0), false),
464            Diff::None
465        );
466        assert_eq!(tmt_rt::diff(Val::None, Val::None, true), Diff::None);
467    }
468
469    /// `&&` / `||` in the runtime against the plain operators and the planner's bits.
470    #[test]
471    fn runtime_logic_matches_the_operators() {
472        let run = |and: bool, m: Option<tmt_rt::Mutant>, a: bool, b: bool| -> (bool, bool) {
473            match tmt_rt::lhs_code(and, a, m) {
474                2 => (tmt_rt::rhs_value(and, b, m), true),
475                code => (code == 1, false),
476            }
477        };
478        for and in [true, false] {
479            for a in [true, false] {
480                for b in [true, false] {
481                    let real = if and { a && b } else { a || b };
482                    let swapped = if and { a || b } else { a && b };
483                    assert_eq!(run(and, None, a, b).0, real);
484                    assert_eq!(run(and, Some(tmt_rt::Mutant::LogicSwap), a, b).0, swapped);
485                    assert_eq!(
486                        run(and, Some(tmt_rt::Mutant::LogicDropLhs), a, b),
487                        (b, true)
488                    );
489                    // The right operand is evaluated exactly when the original evaluates it.
490                    assert_eq!(
491                        run(and, Some(tmt_rt::Mutant::LogicDropRhs), a, b),
492                        (a, run(and, None, a, b).1)
493                    );
494                    // Short-circuiting: the right operand is skipped exactly as in Rust.
495                    assert_eq!(run(and, None, a, b).1, if and { a } else { !a });
496
497                    // What the planner predicts from the observation bits is what changes.
498                    let (_, evaluated) = run(and, None, a, b);
499                    let bits = if !evaluated {
500                        tmt_rt::LOGIC_SHORT
501                    } else if b {
502                        tmt_rt::LOGIC_RHS_TRUE
503                    } else {
504                        tmt_rt::LOGIC_RHS_FALSE
505                    };
506                    let obs = crate::plan::LogicObs::from_bits(bits);
507                    for (m, rt) in [
508                        (Mutation::LogicDropRhs, tmt_rt::Mutant::LogicDropRhs),
509                        (Mutation::LogicDropLhs, tmt_rt::Mutant::LogicDropLhs),
510                    ] {
511                        let changed = run(and, Some(rt), a, b) != run(and, None, a, b);
512                        assert_eq!(
513                            crate::plan::logic_infects(and, m, &obs),
514                            changed,
515                            "and={and} a={a} b={b} {m:?}"
516                        );
517                    }
518                }
519            }
520        }
521        // Without a mutant or a trace the probes are the plain operators.
522        assert_eq!(tmt_rt::lhs(0, true, false), 0);
523        assert_eq!(tmt_rt::lhs(0, false, true), 1);
524        assert_eq!(tmt_rt::lhs(0, true, true), 2);
525        assert!(tmt_rt::rhs(0, true, true));
526        assert!(!tmt_rt::rhs(0, false, false));
527    }
528
529    #[test]
530    #[allow(clippy::needless_borrow)] // the explicit `&` is the call form the probes use
531    fn runtime_arithmetic_probes() {
532        use tmt_rt::{AnyAdd as _, AnyMul as _, AnySub as _, ArithNum, ArithPrim as _};
533        // Primitive numbers: the real operator.
534        assert_eq!((&tmt_rt::Ar::new(7u32, 2u32)).tmt_add(0), 9);
535        assert_eq!((&tmt_rt::Ar::new(7i64, 2)).tmt_sub(0), 5);
536        assert_eq!((&tmt_rt::Ar::new(7usize, 2)).tmt_mul(0), 14);
537        assert_eq!((&tmt_rt::Ar::new(7u8, 2)).tmt_div(0), 3);
538        assert_eq!((&tmt_rt::Ar::new(7i16, 2)).tmt_rem(0), 1);
539        assert_eq!((&tmt_rt::Ar::new(1.5f64, 2.0)).tmt_mul(0), 3.0);
540        // Everything else falls back to the operator's own implementation.
541        assert_eq!((&tmt_rt::Ar::new(String::from("a"), "b")).tmt_add(0), "ab");
542        let second = std::time::Duration::from_secs(1);
543        assert_eq!((&tmt_rt::Ar::new(second, second)).tmt_add(0), second * 2);
544        assert_eq!((&tmt_rt::Ar::new(second, 3u32)).tmt_mul(0), second * 3);
545        assert_eq!((&tmt_rt::Ar::new(&5i32, &3i32)).tmt_sub(0), 2);
546
547        // The swapped operator of each operator, and when it agrees.
548        for (op, swapped) in [
549            (tmt_rt::ADD, tmt_rt::SUB),
550            (tmt_rt::SUB, tmt_rt::ADD),
551            (tmt_rt::MUL, tmt_rt::DIV),
552            (tmt_rt::DIV, tmt_rt::MUL),
553            (tmt_rt::REM, tmt_rt::DIV),
554        ] {
555            assert_eq!(tmt_rt::arith_swapped(op), swapped);
556            for a in -6..=6i32 {
557                for b in -6..=6i32 {
558                    let real = |op: u8| match op {
559                        tmt_rt::ADD => a.checked_add(b),
560                        tmt_rt::SUB => a.checked_sub(b),
561                        tmt_rt::MUL => a.checked_mul(b),
562                        tmt_rt::DIV => a.checked_div(b),
563                        _ => a.checked_rem(b),
564                    };
565                    // Equal only when both are defined: a fault on either side has to be run.
566                    let same = matches!((real(op), real(swapped)), (Some(x), Some(y)) if x == y);
567                    assert_eq!(
568                        i32::tmt_same(op, tmt_rt::arith_swapped(op), a, b),
569                        same,
570                        "op={op} {a} {b}"
571                    );
572                    if let Some(value) = real(op) {
573                        assert_eq!(i32::tmt_real(op, a, b), value);
574                    }
575                }
576            }
577        }
578        assert!(u8::tmt_same(
579            tmt_rt::ADD,
580            tmt_rt::arith_swapped(tmt_rt::ADD),
581            9,
582            0
583        ));
584        // Both shifts overflow: not "the same", the tests decide.
585        assert!(!u8::tmt_same(
586            tmt_rt::SHL,
587            tmt_rt::arith_swapped(tmt_rt::SHL),
588            2,
589            9
590        ));
591        assert!(u8::tmt_same(
592            tmt_rt::SHL,
593            tmt_rt::arith_swapped(tmt_rt::SHL),
594            2,
595            0
596        ));
597        assert!(!u8::tmt_same(
598            tmt_rt::DIV,
599            tmt_rt::arith_swapped(tmt_rt::DIV),
600            4,
601            0
602        ));
603        assert!(
604            !u8::tmt_same(tmt_rt::ADD, tmt_rt::arith_swapped(tmt_rt::ADD), 250, 9),
605            "overflow in one of the two counts as different"
606        );
607        assert!(
608            !u8::tmt_same(tmt_rt::MUL, tmt_rt::arith_swapped(tmt_rt::MUL), 4, 0),
609            "division by zero counts as different"
610        );
611        assert!(f64::tmt_same(
612            tmt_rt::MUL,
613            tmt_rt::arith_swapped(tmt_rt::MUL),
614            4.0,
615            1.0
616        ));
617        assert!(!f64::tmt_same(
618            tmt_rt::ADD,
619            tmt_rt::arith_swapped(tmt_rt::ADD),
620            4.0,
621            0.5
622        ));
623        assert!(
624            !f32::tmt_same(tmt_rt::MUL, tmt_rt::arith_swapped(tmt_rt::MUL), 4.0, 0.0),
625            "4*0 is 0, 4/0 is infinite"
626        );
627    }
628
629    #[test]
630    fn runtime_summary_lines_round_trip() {
631        use tmt_rt::Diff;
632        let observations = [
633            (1, Diff::Int(-5)),
634            (1, Diff::Int(-2)),
635            (4, Diff::Int(9)),
636            (2, Diff::Int(0)),
637            (4, Diff::Int(3)),
638            (1, Diff::Float(-2.5)),
639            (1, Diff::Float(-0.125)),
640            (4, Diff::Float(1e-7)),
641            (8, Diff::None),
642        ];
643        let mut summary = tmt_rt::Summary::default();
644        let mut expected = Obs::default();
645        let mut text = String::new();
646        for (rel, d) in observations {
647            let changed = summary.observe(rel, d);
648            assert!(
649                changed,
650                "each of these observations adds information: {d:?}"
651            );
652            assert!(
653                !summary.observe(rel, d),
654                "repeating an observation changes nothing"
655            );
656            text.push_str(&summary.line(4, "tests::t"));
657            expected.merge(&match d {
658                Diff::Int(d) => Obs::of_d(d),
659                Diff::Float(d) => Obs::of_f(d),
660                Diff::None => Obs::of_rel(Rel::Unordered),
661            });
662        }
663        let trace = Trace::parse(&text);
664        assert_eq!(trace.malformed_lines, 0);
665        assert_eq!(trace.cmp[&4]["tests::t"], expected);
666        assert_eq!(expected.f_min_pos, Some(1e-7));
667
668        // Floats only: the summary keeps the float gap.
669        let mut floats = tmt_rt::Summary::default();
670        floats.observe(1, Diff::Float(-20.5));
671        floats.observe(4, Diff::Float(9.5));
672        let trace = Trace::parse(&floats.line(1, "t"));
673        assert_eq!(trace.cmp[&1]["t"].float_gap(), Some((-20.5, 9.5)));
674    }
675
676    #[test]
677    fn float_columns_are_validated() {
678        let gap = |line: &str| {
679            let trace = Trace::parse(line);
680            assert_eq!(trace.malformed_lines, 0, "{line:?}");
681            let o = trace.cmp[&1]["t"];
682            (o.f_max_neg, o.f_min_pos)
683        };
684        assert_eq!(
685            gap("O\t1\tt\t5\t1\t-\t-\t0\t-2.5\t0.5\n"),
686            (Some(-2.5), Some(0.5))
687        );
688        // Wrong sign, zero, or not finite: dropped.
689        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t2.5\t-0.5\n"), (None, None));
690        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t0.0\t0.0\n"), (None, None));
691        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t-inf\tinf\n"), (None, None));
692        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\tNaN\tNaN\n"), (None, None));
693        assert_eq!(
694            Trace::parse("O\t1\tt\t5\t1\t-\t-\t2\t-\t-\n").malformed_lines,
695            1,
696            "bad flag"
697        );
698        assert_eq!(
699            Trace::parse("O\t1\tt\t5\t1\t-\t-\t0\tx\t-\n").malformed_lines,
700            1
701        );
702    }
703
704    #[test]
705    fn return_lines() {
706        let returns = Trace::parse("B\t4\tt\t1\nB\t4\tt\t2\nB\t4\tu\t2\n");
707        assert_eq!(returns.malformed_lines, 0);
708        assert_eq!(
709            returns.returns[&4]["t"],
710            ReturnObs {
711                saw_true: true,
712                saw_false: true
713            }
714        );
715        assert_eq!(
716            returns.returns[&4]["u"],
717            ReturnObs {
718                saw_true: false,
719                saw_false: true
720            }
721        );
722        assert_eq!(
723            Trace::parse("B\t4\tt\t4\n").malformed_lines,
724            1,
725            "only two return bits exist"
726        );
727        assert_eq!(Trace::parse("B\t4\tt\t3\n").malformed_lines, 0);
728        assert_eq!(Trace::parse("A\t4\tt\t7\n").malformed_lines, 0);
729    }
730
731    #[test]
732    fn logic_arithmetic_and_reach_lines() {
733        let trace = Trace::parse(
734            "L\t1\tt\t1\nL\t1\tt\t5\nL\t1\tu\t2\nA\t2\tt\t1\nA\t2\tu\t6\nR\t3\tt\t1\n",
735        );
736        assert_eq!(trace.malformed_lines, 0);
737        assert_eq!(
738            trace.logic[&1]["t"],
739            crate::plan::LogicObs {
740                short: true,
741                rhs_true: false,
742                rhs_false: true,
743                rhs_started: false,
744            }
745        );
746        assert_eq!(
747            trace.logic[&1]["u"],
748            crate::plan::LogicObs {
749                short: false,
750                rhs_true: true,
751                rhs_false: false,
752                rhs_started: false,
753            }
754        );
755        assert_eq!(
756            trace.arith[&2]["t"],
757            crate::plan::ArithObs {
758                same: true,
759                differs: false,
760                opaque: false,
761                ..Default::default()
762            }
763        );
764        assert_eq!(
765            trace.arith[&2]["u"],
766            crate::plan::ArithObs {
767                same: false,
768                differs: true,
769                opaque: true,
770                ..Default::default()
771            }
772        );
773        assert!(trace.reach[&3].contains("t"));
774        // A range that ended at the largest value of its type is remembered as one.
775        let ranges = Trace::parse("R\t7\tt\t3\nR\t8\tt\t1\n");
776        assert_eq!(ranges.malformed_lines, 0);
777        assert!(ranges.reach[&7].contains("t") && ranges.reach[&8].contains("t"));
778        assert_eq!(ranges.ranges_at_top.iter().collect::<Vec<_>>(), [&7]);
779        // A right operand that was started, with and without a value.
780        let started = Trace::parse("L\t1\tt\t8\nL\t1\tu\t10\n");
781        assert_eq!(started.malformed_lines, 0);
782        assert!(started.logic[&1]["t"].rhs_started && !started.logic[&1]["t"].rhs_true);
783        assert!(started.logic[&1]["u"].rhs_started && started.logic[&1]["u"].rhs_true);
784        for bad in [
785            "L\t1\tt\t0\n",
786            "L\t1\tt\t16\n",
787            "A\t1\t\t1\n",
788            "R\t1\tt\n",
789            "L\tx\tt\t1\n",
790            "Z\t1\tt\t1\n",
791        ] {
792            assert_eq!(Trace::parse(bad).malformed_lines, 1, "{bad:?}");
793        }
794    }
795
796    #[test]
797    #[allow(clippy::needless_borrow)] // the explicit `&` is the call form the probes use
798    fn runtime_probes_are_transparent_without_env() {
799        use tmt_rt::{Val, ValAny as _, ValNum as _};
800        // Autoref specialisation: numbers carry values, everything else does not.
801        assert_eq!((&tmt_rt::W(&7u8)).tmt_val(), Val::Int(7, 0, 255));
802        assert_eq!(
803            (&tmt_rt::W(&&-3i64)).tmt_val(),
804            Val::Int(-3, i64::MIN as i128, i64::MAX as i128)
805        );
806        assert_eq!((&tmt_rt::W(&1.5f64)).tmt_val(), Val::Float(1.5));
807        assert_eq!((&tmt_rt::W(&&2.5f32)).tmt_val(), Val::Float(2.5));
808        assert_eq!((&tmt_rt::W("text")).tmt_val(), Val::None);
809        assert_eq!((&tmt_rt::W(&'c')).tmt_val(), Val::None);
810
811        for (a, b) in [(1, 2), (2, 2), (3, 2)] {
812            assert_eq!(
813                tmt_rt::ord(0, tmt_rt::LT, &a, &b, Val::None, Val::None),
814                a < b
815            );
816            assert_eq!(
817                tmt_rt::ord(0, tmt_rt::LE, &a, &b, Val::None, Val::None),
818                a <= b
819            );
820            assert_eq!(
821                tmt_rt::ord(0, tmt_rt::GT, &a, &b, Val::None, Val::None),
822                a > b
823            );
824            assert_eq!(
825                tmt_rt::ord(0, tmt_rt::GE, &a, &b, Val::None, Val::None),
826                a >= b
827            );
828            assert_eq!(
829                tmt_rt::eq(0, tmt_rt::EQ, &a, &b, Val::None, Val::None),
830                a == b
831            );
832            assert_eq!(
833                tmt_rt::eq(0, tmt_rt::NE, &a, &b, Val::None, Val::None),
834                a != b
835            );
836        }
837        assert!(!tmt_rt::ord(
838            0,
839            tmt_rt::GE,
840            &f64::NAN,
841            &1.0,
842            Val::None,
843            Val::None
844        ));
845        assert!(tmt_rt::eq(0, tmt_rt::NE, "a", "b", Val::None, Val::None));
846        assert!(tmt_rt::live(0));
847    }
848    /// The two replacements of each operator are those of cargo-mutants, and the runtime
849    /// and the report name the same ones.
850    #[test]
851    fn both_replacements_of_every_operator() {
852        use crate::instrument::ArithOp;
853        let code = |op: ArithOp| match op {
854            ArithOp::Add => tmt_rt::ADD,
855            ArithOp::Sub => tmt_rt::SUB,
856            ArithOp::Mul => tmt_rt::MUL,
857            ArithOp::Div => tmt_rt::DIV,
858            ArithOp::Rem => tmt_rt::REM,
859            ArithOp::BitAnd => tmt_rt::BITAND,
860            ArithOp::BitOr => tmt_rt::BITOR,
861            ArithOp::BitXor => tmt_rt::BITXOR,
862            ArithOp::Shl => tmt_rt::SHL,
863            ArithOp::Shr => tmt_rt::SHR,
864        };
865        let table = [
866            (ArithOp::Add, "-", Some("*")),
867            (ArithOp::Sub, "+", Some("/")),
868            (ArithOp::Mul, "/", Some("+")),
869            (ArithOp::Div, "*", Some("%")),
870            (ArithOp::Rem, "/", Some("+")),
871            (ArithOp::BitAnd, "|", Some("^")),
872            (ArithOp::BitOr, "&", Some("^")),
873            (ArithOp::BitXor, "&", Some("|")),
874            (ArithOp::Shl, ">>", None),
875            (ArithOp::Shr, "<<", None),
876        ];
877        assert_eq!(table.map(|row| row.0), ArithOp::ALL);
878        for (op, first, second) in table {
879            assert_eq!(op.swapped().symbol(), first, "{op:?}");
880            assert_eq!(op.swapped2().map(ArithOp::symbol), second, "{op:?}");
881            assert_eq!(
882                tmt_rt::arith_swapped(code(op)),
883                code(op.swapped()),
884                "{op:?}"
885            );
886            assert_eq!(
887                tmt_rt::arith_swapped2(code(op)),
888                op.swapped2().map(code),
889                "{op:?}"
890            );
891        }
892        assert_eq!(
893            tmt_rt::parse_mutant("3:as2"),
894            Some((3, tmt_rt::Mutant::ArithSwap2))
895        );
896
897        // What is recorded for a pair of operands: whether each replacement agrees.
898        use tmt_rt::ArithNum;
899        // 2 + 2 = 2 * 2, but not 2 - 2.
900        assert!(!i32::tmt_same(tmt_rt::ADD, tmt_rt::SUB, 2, 2));
901        assert!(i32::tmt_same(tmt_rt::ADD, tmt_rt::MUL, 2, 2));
902        // 6 / 1 = 6 * 1, but not 6 % 1.
903        assert!(i32::tmt_same(tmt_rt::DIV, tmt_rt::MUL, 6, 1));
904        assert!(!i32::tmt_same(tmt_rt::DIV, tmt_rt::REM, 6, 1));
905        // 4 | 1 = 4 ^ 1, but not 4 & 1.
906        assert!(i32::tmt_same(tmt_rt::BITOR, tmt_rt::BITXOR, 4, 1));
907        assert!(!i32::tmt_same(tmt_rt::BITOR, tmt_rt::BITAND, 4, 1));
908        assert!(f64::tmt_same(tmt_rt::MUL, tmt_rt::ADD, 2.0, 2.0));
909
910        // And as the planner reads it.
911        let seen = |bits: u8| crate::plan::ArithObs::from_bits(bits);
912        let both = seen(tmt_rt::ARITH_DIFFERS | tmt_rt::ARITH_SAME2);
913        assert!(both.differs && both.same2 && !both.same && !both.differs2 && !both.opaque);
914        assert!(both.infected_by(Mutation::ArithSwap));
915        assert!(!both.infected_by(Mutation::ArithSwap2));
916        let other = seen(tmt_rt::ARITH_SAME | tmt_rt::ARITH_DIFFERS2);
917        assert!(!other.infected_by(Mutation::ArithSwap));
918        assert!(other.infected_by(Mutation::ArithSwap2));
919        assert_eq!(crate::plan::plan_arith(&both), crate::plan::ArithPlan::Run);
920        assert_eq!(
921            crate::plan::plan_arith(&both.second()),
922            crate::plan::ArithPlan::NeverDiffers
923        );
924        assert_eq!(
925            crate::plan::plan_arith(&other.second()),
926            crate::plan::ArithPlan::Run
927        );
928        let mut merged = both;
929        merged.merge(&other);
930        assert!(merged.same && merged.differs && merged.same2 && merged.differs2);
931        let mut merged = other;
932        merged.merge(&both);
933        assert!(merged.same && merged.differs && merged.same2 && merged.differs2);
934        // An assignment that collects bits has one replacement, as in cargo-mutants.
935        assert_eq!(ArithOp::BitOr.second(true), None);
936        assert_eq!(ArithOp::BitAnd.second(true), None);
937        assert_eq!(ArithOp::BitXor.second(true), Some(ArithOp::BitOr));
938        assert_eq!(ArithOp::BitOr.second(false), Some(ArithOp::BitXor));
939        assert_eq!(ArithOp::Add.second(true), Some(ArithOp::Mul));
940        // Operands that are not numbers stay that for both.
941        assert_eq!(
942            crate::plan::plan_arith(&seen(tmt_rt::ARITH_OPAQUE).second()),
943            crate::plan::ArithPlan::Opaque
944        );
945        assert_eq!(Mutation::ArithSwap2.encode(), "as2");
946
947        // A trace line with the wider bits is read; one beyond them is not.
948        let trace = Trace::parse("A\t1\tt\t18\nA\t2\tt\t31\nA\t3\tt\t32\n");
949        assert_eq!(trace.arith[&1]["t"], seen(18));
950        assert!(trace.arith.contains_key(&2) && !trace.arith.contains_key(&3));
951        assert_eq!(trace.malformed_lines, 1);
952    }
953
954    /// A probe in a loop asks the tracer only when it has something new to say.
955    #[test]
956    fn two_traces_differ_by_the_records_that_are_not_the_same() {
957        let text =
958            "O\t1\ta\t3\t0\t-2\t-\t1\t-\t-\nL\t2\ta\t1\nA\t3\ta\t1\nB\t4\ta\t1\nR\t5\ta\t1\n";
959        let base = Trace::parse(text);
960        assert_eq!(base.malformed_lines, 0);
961        assert_eq!(base.differences(&Trace::parse(text)), 0);
962        // Each kind of record counts, in whichever of the two it is missing or other.
963        for (other, differing) in [
964            ("O\t1\ta\t3\t0\t-1\t-\t1\t-\t-\n", 1), // a nearer value
965            ("O\t1\tb\t3\t0\t-2\t-\t1\t-\t-\n", 1), // seen by another test too
966            ("O\t9\ta\t3\t0\t-2\t-\t1\t-\t-\n", 1), // at another site too
967            ("L\t2\ta\t2\n", 1),
968            ("A\t3\ta\t2\n", 1),
969            ("B\t4\ta\t2\n", 1),
970            ("R\t5\tb\t1\n", 1),
971            ("R\t6\ta\t1\nL\t2\tb\t1\n", 2),
972        ] {
973            let more = Trace::parse(&format!("{text}{other}"));
974            assert_eq!(base.differences(&more), differing, "{other:?}");
975            assert_eq!(more.differences(&base), differing, "{other:?}");
976        }
977        assert_eq!(base.differences(&Trace::default()), 5);
978        assert_eq!(Trace::default().differences(&base), 5);
979    }
980
981    #[test]
982    fn only_a_known_distance_coming_closer_can_wait() {
983        use tmt_rt::{Diff, News, Summary};
984        let mut s = Summary::default();
985        // The first distance on each side is news of the other kind, and so is a new relation.
986        assert_eq!(s.news(1, Diff::Int(-9)), News::Other);
987        assert_eq!(s.news(1, Diff::Int(-9)), News::Nothing);
988        assert_eq!(s.news(1, Diff::Int(-10)), News::Nothing);
989        assert_eq!(s.news(1, Diff::Int(-4)), News::Closer);
990        assert_eq!(s.news(4, Diff::Int(7)), News::Other);
991        assert_eq!(s.news(4, Diff::Int(6)), News::Closer);
992        assert_eq!(s.news(1, Diff::Int(-1)), News::Closer);
993        assert_eq!(s.news(2, Diff::Int(0)), News::Other);
994        assert_eq!((s.max_neg, s.min_pos), (Some(-1), Some(6)));
995        // Floats alike; a closer distance together with something new does not wait.
996        assert_eq!(s.news(1, Diff::Float(-2.0)), News::Other);
997        assert_eq!(s.news(1, Diff::Float(-1.5)), News::Closer);
998        assert_eq!(s.news(4, Diff::Float(0.5)), News::Other);
999        assert_eq!(s.news(4, Diff::Float(0.25)), News::Closer);
1000        let mut t = Summary::default();
1001        assert_eq!(t.news(1, Diff::Int(-9)), News::Other);
1002        assert_eq!(t.news(8, Diff::Int(-3)), News::Other);
1003        assert_eq!(t.news(8, Diff::None), News::Other);
1004    }
1005
1006    #[test]
1007    fn a_backlog_hands_out_the_latest_of_each_site_once() {
1008        use tmt_rt::{Backlog, Diff, Summary};
1009        let at = |d: i128| {
1010            let mut s = Summary::default();
1011            s.observe(1, Diff::Int(d));
1012            s
1013        };
1014        let mut backlog = Backlog::default();
1015        assert!(backlog.drain().is_empty());
1016        backlog.keep(7, at(-5));
1017        backlog.keep(2, at(-8));
1018        backlog.keep(7, at(-3));
1019        assert_eq!(backlog.drain(), [(7, at(-3)), (2, at(-8))]);
1020        assert!(backlog.drain().is_empty(), "written once");
1021        // Kept again after it was written: written again.
1022        backlog.keep(7, at(-1));
1023        assert_eq!(backlog.drain(), [(7, at(-1))]);
1024        // A site written by other means is not written from here, the others are.
1025        backlog.keep(7, at(-1));
1026        backlog.keep(2, at(-2));
1027        backlog.keep(9, at(-4));
1028        backlog.forget(2);
1029        backlog.forget(100);
1030        backlog.forget(1);
1031        assert_eq!(backlog.drain(), [(7, at(-1)), (9, at(-4))]);
1032        backlog.keep(2, at(-1));
1033        assert_eq!(backlog.drain(), [(2, at(-1))]);
1034    }
1035
1036    #[test]
1037    fn a_thread_remembers_what_it_recorded() {
1038        // Sites of their own, far from the ones other tests of this binary use.
1039        let site = 900_000;
1040        assert!(!tmt_rt::bits_known(b'A', site, 1));
1041        assert!(tmt_rt::bits_are_news(b'A', site, 1));
1042        assert!(!tmt_rt::bits_are_news(b'A', site, 1));
1043        assert!(tmt_rt::bits_known(b'A', site, 1));
1044        // Another bit of the same site is news once, and then both are known.
1045        assert!(!tmt_rt::bits_known(b'A', site, 3));
1046        assert!(tmt_rt::bits_are_news(b'A', site, 3));
1047        assert!(!tmt_rt::bits_are_news(b'A', site, 2));
1048        assert!(tmt_rt::bits_known(b'A', site, 3));
1049        // Each kind of record and each site has its own memory.
1050        for kind in *b"RLB" {
1051            assert!(!tmt_rt::bits_known(kind, site, 1), "{}", kind as char);
1052            assert!(tmt_rt::bits_are_news(kind, site, 1), "{}", kind as char);
1053            assert!(!tmt_rt::bits_are_news(kind, site, 1), "{}", kind as char);
1054        }
1055        assert!(tmt_rt::bits_are_news(b'A', site + 1, 1));
1056        assert!(!tmt_rt::bits_known(b'A', site - 1, 1));
1057        // And each thread: a test is a thread.
1058        std::thread::spawn(move || {
1059            assert!(!tmt_rt::bits_known(b'A', site, 1));
1060            assert!(tmt_rt::bits_are_news(b'A', site, 1));
1061        })
1062        .join()
1063        .unwrap();
1064    }
1065}