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, LitSetObs, 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    pub lit_set: BTreeMap<u32, BTreeMap<String, LitSetObs>>,
36    /// site -> tests that executed the statement
37    pub reach: BTreeMap<u32, BTreeSet<String>>,
38    /// Ranges `a..b` that some test ran with `b` at the largest value of its type.
39    pub ranges_at_top: BTreeSet<u32>,
40    pub bounds: BTreeMap<u32, TypeBounds>,
41    /// `(site, slot)` -> observed source type bounds for a cast/`from` operand inside `|`/`^`,
42    /// or `None` when observed as non-primitive or polymorphically across distinct types.
43    pub cast_bounds: BTreeMap<(u32, u32), Option<(i128, i128)>>,
44    pub malformed_lines: usize,
45}
46
47fn parse_u32_ascii(text: &str) -> Option<u32> {
48    let bytes = text.as_bytes();
49    let bytes = bytes.strip_prefix(b"+").unwrap_or(bytes);
50    if bytes.is_empty() {
51        return None;
52    }
53    let mut acc = 0u32;
54    for &b in bytes {
55        let d = b.wrapping_sub(b'0');
56        if d > 9 {
57            return None;
58        }
59        acc = acc.checked_mul(10)?.checked_add(u32::from(d))?;
60    }
61    Some(acc)
62}
63
64#[inline]
65fn find_byte(haystack: &[u8], needle: u8) -> Option<usize> {
66    #[cfg(target_arch = "aarch64")]
67    {
68        use std::arch::aarch64::*;
69        let len = haystack.len();
70        let mut i = 0;
71        // SAFETY: NEON is mandatory on aarch64 and every load stays within `haystack[..len]`.
72        unsafe {
73            let n = vdupq_n_u8(needle);
74            let bit_mask: uint8x16_t =
75                vld1q_u8([1u8, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128].as_ptr());
76            while i + 16 <= len {
77                let chunk = vld1q_u8(haystack.as_ptr().add(i));
78                let eq = vceqq_u8(chunk, n);
79                if vmaxvq_u8(eq) != 0 {
80                    let masked = vandq_u8(eq, bit_mask);
81                    let lo = vaddv_u8(vget_low_u8(masked)) as u32;
82                    let hi = vaddv_u8(vget_high_u8(masked)) as u32;
83                    let bits = lo | (hi << 8);
84                    return Some(i + bits.trailing_zeros() as usize);
85                }
86                i += 16;
87            }
88        }
89        while i < len {
90            if haystack[i] == needle {
91                return Some(i);
92            }
93            i += 1;
94        }
95        None
96    }
97    #[cfg(target_arch = "x86_64")]
98    {
99        use std::arch::x86_64::*;
100        let len = haystack.len();
101        let mut i = 0;
102        // SAFETY: SSE2 is mandatory on x86_64 and every load stays within `haystack[..len]`.
103        unsafe {
104            let n = _mm_set1_epi8(needle as i8);
105            while i + 16 <= len {
106                let chunk = _mm_loadu_si128(haystack.as_ptr().add(i).cast());
107                let mask = _mm_movemask_epi8(_mm_cmpeq_epi8(chunk, n)) as u32;
108                if mask != 0 {
109                    return Some(i + mask.trailing_zeros() as usize);
110                }
111                i += 16;
112            }
113        }
114        while i < len {
115            if haystack[i] == needle {
116                return Some(i);
117            }
118            i += 1;
119        }
120        None
121    }
122    #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
123    {
124        haystack.iter().position(|&b| b == needle)
125    }
126}
127
128fn flag(text: &str) -> Option<bool> {
129    match text {
130        "0" => Some(false),
131        "1" => Some(true),
132        _ => None,
133    }
134}
135
136fn optional<T: std::str::FromStr>(text: &str) -> Option<Option<T>> {
137    if text == "-" {
138        Some(None)
139    } else {
140        text.parse().ok().map(Some)
141    }
142}
143
144/// Counts differing records from two streams ordered by the same key.
145fn differing<K: Ord, V: PartialEq>(
146    a: impl Iterator<Item = (K, V)>,
147    b: impl Iterator<Item = (K, V)>,
148) -> usize {
149    let mut a = a.peekable();
150    let mut b = b.peekable();
151    let mut count = 0;
152    while let (Some((left, _)), Some((right, _))) = (a.peek(), b.peek()) {
153        match left.cmp(right) {
154            std::cmp::Ordering::Less => {
155                a.next();
156                count += 1;
157            }
158            std::cmp::Ordering::Greater => {
159                b.next();
160                count += 1;
161            }
162            std::cmp::Ordering::Equal => {
163                let left = a.next().unwrap().1;
164                let right = b.next().unwrap().1;
165                count += usize::from(left != right);
166            }
167        }
168    }
169    count + a.count() + b.count()
170}
171
172fn records<T>(map: &BTreeMap<u32, BTreeMap<String, T>>) -> impl Iterator<Item = ((u32, &str), &T)> {
173    map.iter().flat_map(|(&site, tests)| {
174        tests
175            .iter()
176            .map(move |(test, seen)| ((site, test.as_str()), seen))
177    })
178}
179
180fn reached_records(
181    map: &BTreeMap<u32, BTreeSet<String>>,
182) -> impl Iterator<Item = ((u32, &str), ())> {
183    map.iter()
184        .flat_map(|(&site, tests)| tests.iter().map(move |test| ((site, test.as_str()), ())))
185}
186
187impl Trace {
188    /// How many records (what one test saw at one site) are not the same in two traces
189    /// of the same tests. Tests that always do the same give none.
190    pub fn differences(&self, other: &Trace) -> usize {
191        differing(records(&self.cmp), records(&other.cmp))
192            + differing(records(&self.logic), records(&other.logic))
193            + differing(records(&self.arith), records(&other.arith))
194            + differing(records(&self.returns), records(&other.returns))
195            + differing(records(&self.lit_set), records(&other.lit_set))
196            + differing(reached_records(&self.reach), reached_records(&other.reach))
197    }
198
199    pub fn parse(text: &str) -> Trace {
200        let mut trace = Trace::default();
201        let bytes = text.as_bytes();
202        let mut pos = 0;
203        while pos < bytes.len() {
204            let line_end = find_byte(&bytes[pos..], b'\n').map_or(bytes.len(), |d| pos + d);
205            let mut end = line_end;
206            if line_end < bytes.len() && end > pos && bytes[end - 1] == b'\r' {
207                end -= 1;
208            }
209            if trace.parse_line(&text[pos..end]).is_none() {
210                trace.malformed_lines += 1;
211            }
212            pos = if line_end < bytes.len() {
213                line_end + 1
214            } else {
215                bytes.len()
216            };
217        }
218        trace
219    }
220
221    fn parse_line(&mut self, line: &str) -> Option<()> {
222        // The comparison record is the widest. Reject extra fields without allocating.
223        let mut cols = [""; 10];
224        let mut len = 0;
225        let lb = line.as_bytes();
226        let mut fstart = 0;
227        loop {
228            let slot = cols.get_mut(len)?;
229            match find_byte(&lb[fstart..], b'\t') {
230                Some(d) => {
231                    *slot = &line[fstart..fstart + d];
232                    len += 1;
233                    fstart += d + 1;
234                }
235                None => {
236                    *slot = &line[fstart..];
237                    len += 1;
238                    break;
239                }
240            }
241        }
242        match cols[..len] {
243            [
244                "O",
245                site,
246                test,
247                rels,
248                unvalued,
249                max_neg,
250                min_pos,
251                unfloat,
252                f_max_neg,
253                f_min_pos,
254            ] => {
255                let rels: u8 = parse_u32_ascii(rels)
256                    .and_then(|r| u8::try_from(r).ok())
257                    .filter(|r| *r < 16)?;
258                let obs = Obs {
259                    lt: rels & 1 != 0,
260                    eq: rels & 2 != 0,
261                    gt: rels & 4 != 0,
262                    un: rels & 8 != 0,
263                    unvalued: flag(unvalued)?,
264                    max_neg: optional::<i128>(max_neg)?.filter(|d| *d < 0),
265                    min_pos: optional::<i128>(min_pos)?.filter(|d| *d > 0),
266                    unfloat: flag(unfloat)?,
267                    f_max_neg: optional::<f64>(f_max_neg)?.filter(|d| d.is_finite() && *d < 0.0),
268                    f_min_pos: optional::<f64>(f_min_pos)?.filter(|d| d.is_finite() && *d > 0.0),
269                };
270                let site = parse_u32_ascii(site)?;
271                (!test.is_empty()).then_some(())?;
272                let tests = self.cmp.entry(site).or_default();
273                if let Some(existing) = tests.get_mut(test) {
274                    existing.merge(&obs);
275                } else {
276                    tests.insert(test.to_owned(), obs);
277                }
278            }
279            [kind @ ("R" | "L" | "A" | "B"), site, test, bits] => {
280                let site = parse_u32_ascii(site)?;
281                let limit = match kind {
282                    "B" => 4,
283                    "A" => 32,
284                    "L" => 16,
285                    _ => 8,
286                };
287                let bits: u8 = parse_u32_ascii(bits)
288                    .and_then(|b| u8::try_from(b).ok())
289                    .filter(|b| (1..limit).contains(b))?;
290                (!test.is_empty()).then_some(())?;
291                match kind {
292                    "R" => {
293                        if bits & 2 != 0 {
294                            self.ranges_at_top.insert(site);
295                        }
296                        let tests = self.reach.entry(site).or_default();
297                        if !tests.contains(test) {
298                            tests.insert(test.to_owned());
299                        }
300                    }
301                    "B" => {
302                        let obs = ReturnObs::from_bits(bits);
303                        let tests = self.returns.entry(site).or_default();
304                        if let Some(existing) = tests.get_mut(test) {
305                            existing.merge(&obs);
306                        } else {
307                            tests.insert(test.to_owned(), obs);
308                        }
309                    }
310                    "L" => {
311                        let obs = LogicObs::from_bits(bits);
312                        let tests = self.logic.entry(site).or_default();
313                        if let Some(existing) = tests.get_mut(test) {
314                            existing.merge(&obs);
315                        } else {
316                            tests.insert(test.to_owned(), obs);
317                        }
318                    }
319                    _ => {
320                        let obs = ArithObs::from_bits(bits);
321                        let tests = self.arith.entry(site).or_default();
322                        if let Some(existing) = tests.get_mut(test) {
323                            existing.merge(&obs);
324                        } else {
325                            tests.insert(test.to_owned(), obs);
326                        }
327                    }
328                }
329            }
330            ["S", site, test, bits] => {
331                let site = parse_u32_ascii(site)?;
332                let bits: u16 = parse_u32_ascii(bits)
333                    .and_then(|b| u16::try_from(b).ok())
334                    .filter(|b| (1..1024).contains(b))?;
335                (!test.is_empty()).then_some(())?;
336                let obs = LitSetObs::from_bits(bits);
337                let tests = self.lit_set.entry(site).or_default();
338                if let Some(existing) = tests.get_mut(test) {
339                    existing.merge(&obs);
340                } else {
341                    tests.insert(test.to_owned(), obs);
342                }
343            }
344            ["T", site, lhs_min, lhs_max, rhs_min, rhs_max] => {
345                let bounds = TypeBounds {
346                    lhs: (lhs_min.parse().ok()?, lhs_max.parse().ok()?),
347                    rhs: (rhs_min.parse().ok()?, rhs_max.parse().ok()?),
348                };
349                self.bounds.insert(parse_u32_ascii(site)?, bounds);
350            }
351            ["C", site, slot, min, max] => {
352                let key = (parse_u32_ascii(site)?, parse_u32_ascii(slot)?);
353                let observed = if min == "-" && max == "-" {
354                    None
355                } else {
356                    let lo: i128 = min.parse().ok()?;
357                    let hi: i128 = max.parse().ok()?;
358                    Some((lo <= hi).then_some((lo, hi))?)
359                };
360                self.cast_bounds
361                    .entry(key)
362                    .and_modify(|existing| {
363                        if *existing != observed {
364                            *existing = None;
365                        }
366                    })
367                    .or_insert(observed);
368            }
369            _ => return None,
370        }
371        Some(())
372    }
373
374    /// Everything any test observed at a comparison site.
375    pub fn merged(&self, site: u32) -> Obs {
376        let mut all = Obs::default();
377        for obs in self
378            .cmp
379            .get(&site)
380            .into_iter()
381            .flat_map(|tests| tests.values())
382        {
383            all.merge(obs);
384        }
385        all
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392    use crate::plan::{CmpOp, Mutation, Rel, eval_mutated_d};
393    use crate::tmt_rt;
394
395    #[test]
396    fn parses_and_merges_lines() {
397        let trace = Trace::parse(
398            "O\t3\ttests::a\t1\t0\t-4\t-\t1\t-\t-\n\
399             O\t3\ttests::a\t5\t0\t-1\t2\t1\t-\t-\n\
400             O\t3\ttests::b\t2\t0\t-\t-\t1\t-\t-\n\
401             R\t9\ttests::a\t1\n\
402             R\t9\t?\t1\n\
403             T\t3\t0\t255\t0\t255\n",
404        );
405        assert_eq!(trace.malformed_lines, 0);
406        let a = trace.cmp[&3]["tests::a"];
407        assert_eq!(
408            (a.lt, a.eq, a.gt, a.max_neg, a.min_pos),
409            (true, false, true, Some(-1), Some(2))
410        );
411        assert!(trace.merged(3).eq);
412        assert_eq!(
413            trace.reach[&9].iter().collect::<Vec<_>>(),
414            ["?", "tests::a"]
415        );
416        assert_eq!(
417            trace.bounds[&3],
418            TypeBounds {
419                lhs: (0, 255),
420                rhs: (0, 255)
421            }
422        );
423        assert_eq!(trace.merged(42), Obs::default());
424    }
425
426    #[test]
427    fn skips_truncated_and_malformed_lines() {
428        let trace = Trace::parse(
429            "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",
430        );
431        assert_eq!(trace.malformed_lines, 5);
432        assert!(trace.cmp.is_empty());
433        assert_eq!(trace.reach.len(), 1);
434    }
435
436    #[test]
437    fn trace_records_need_the_exact_number_of_fields_with_any_line_ending() {
438        for record in [
439            "O\t3\ttests::a\t5\t0\t-1\t2\t1\t-\t-",
440            "R\t3\ttests::a\t1",
441            "L\t3\ttests::a\t1",
442            "A\t3\ttests::a\t1",
443            "B\t3\ttests::a\t1",
444            "T\t3\t0\t255\t0\t255",
445            "C\t3\t0\t0\t255",
446            "C\t3\t1\t-\t-",
447        ] {
448            let (short, _) = record.rsplit_once('\t').unwrap();
449            let long = format!("{record}\t");
450            for ending in ["\n", "\r\n", ""] {
451                let parsed = Trace::parse(&format!("{record}{ending}"));
452                assert_eq!(parsed.malformed_lines, 0, "{record:?} {ending:?}");
453                assert_ne!(parsed, Trace::default());
454                for malformed in [short, long.as_str()] {
455                    assert_eq!(
456                        Trace::parse(&format!("{malformed}{ending}")),
457                        Trace {
458                            malformed_lines: 1,
459                            ..Trace::default()
460                        },
461                        "{malformed:?} {ending:?}"
462                    );
463                }
464            }
465        }
466
467        let parsed = Trace::parse(&format!(
468            "R\t3\ttests::a\t1{}\nR\t4\ttests::b\t1\n",
469            "\t".repeat(32)
470        ));
471        assert_eq!(parsed.malformed_lines, 1);
472        assert!(!parsed.reach.contains_key(&3));
473        assert!(parsed.reach[&4].contains("tests::b"));
474    }
475
476    #[test]
477    fn relation_bits_and_field_validation() {
478        for (rels, expected) in [(1, "lt"), (2, "eq"), (4, "gt"), (8, "un")] {
479            let trace = Trace::parse(&format!("O\t1\tt\t{rels}\t1\t-\t-\t1\t-\t-\n"));
480            let o = trace.cmp[&1]["t"];
481            let set: Vec<&str> = [(o.lt, "lt"), (o.eq, "eq"), (o.gt, "gt"), (o.un, "un")]
482                .into_iter()
483                .filter_map(|(on, name)| on.then_some(name))
484                .collect();
485            assert_eq!(set, [expected]);
486            assert!(o.unvalued);
487        }
488        // 15 is every relation, 16 is not a relation mask.
489        assert_eq!(
490            Trace::parse("O\t1\tt\t15\t0\t-\t-\t1\t-\t-\n").malformed_lines,
491            0
492        );
493        assert_eq!(
494            Trace::parse("O\t1\tt\t16\t0\t-\t-\t1\t-\t-\n").malformed_lines,
495            1
496        );
497        // A comparison line needs a test name too.
498        let nameless = Trace::parse("O\t1\t\t1\t0\t-\t-\t1\t-\t-\n");
499        assert_eq!((nameless.malformed_lines, nameless.cmp.len()), (1, 0));
500        // The nearest-below value is negative and the nearest-above positive, or they are dropped.
501        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");
502        for site in [1, 2] {
503            let o = signs.cmp[&site]["t"];
504            assert_eq!((o.max_neg, o.min_pos), (None, None));
505        }
506    }
507
508    fn rt_op(op: CmpOp) -> u8 {
509        op.code()
510    }
511
512    fn rt_mutant(m: Mutation) -> tmt_rt::Mutant {
513        let spec = format!("7:{}", m.encode());
514        let (site, parsed) =
515            tmt_rt::parse_mutant(&spec).unwrap_or_else(|| panic!("runtime rejects {spec}"));
516        assert_eq!(site, 7);
517        parsed
518    }
519
520    /// The injected runtime is a separate source file; it must agree with the planner on
521    /// what every mutation does and on how observations are summarised.
522    #[test]
523    fn runtime_agrees_with_the_planner() {
524        for op in CmpOp::ALL {
525            let mut ms = vec![
526                Mutation::Const(true),
527                Mutation::Const(false),
528                Mutation::Negate,
529            ];
530            ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
531            if op.is_ordering() {
532                ms.extend((-4..=4).filter(|s| *s != 0).map(Mutation::Shift));
533            }
534            for m in ms {
535                for d in -6..=6i128 {
536                    let rel = if d < 0 {
537                        1
538                    } else if d == 0 {
539                        2
540                    } else {
541                        4
542                    };
543                    assert_eq!(
544                        tmt_rt::apply(
545                            rt_op(op),
546                            rt_mutant(m),
547                            op.eval_d(d),
548                            rel,
549                            tmt_rt::Diff::Int(d)
550                        ),
551                        eval_mutated_d(op, m, d),
552                        "{op:?} {m:?} d={d}"
553                    );
554                }
555            }
556            // Unordered operands (NaN): only `!=` is true.
557            assert_eq!(
558                tmt_rt::apply(
559                    rt_op(op),
560                    tmt_rt::Mutant::Op(rt_op(op)),
561                    false,
562                    8,
563                    tmt_rt::Diff::None
564                ),
565                op.eval_rel(Rel::Unordered)
566            );
567            // A shift needs values of its own kind; without them the original result stands.
568            for orig in [true, false] {
569                assert_eq!(
570                    tmt_rt::apply(
571                        rt_op(op),
572                        tmt_rt::Mutant::Shift(1),
573                        orig,
574                        2,
575                        tmt_rt::Diff::None
576                    ),
577                    orig
578                );
579                assert_eq!(
580                    tmt_rt::apply(
581                        rt_op(op),
582                        tmt_rt::Mutant::ShiftF(1.0),
583                        orig,
584                        2,
585                        tmt_rt::Diff::Int(0)
586                    ),
587                    orig
588                );
589                assert_eq!(
590                    tmt_rt::apply(
591                        rt_op(op),
592                        tmt_rt::Mutant::Delete,
593                        orig,
594                        2,
595                        tmt_rt::Diff::Int(0)
596                    ),
597                    orig
598                );
599            }
600        }
601        assert_eq!(
602            tmt_rt::parse_mutant("12:del"),
603            Some((12, tmt_rt::Mutant::Delete))
604        );
605        for (m, expected) in [
606            (Mutation::LogicSwap, tmt_rt::Mutant::LogicSwap),
607            (Mutation::LogicDropRhs, tmt_rt::Mutant::LogicDropRhs),
608            (Mutation::LogicDropLhs, tmt_rt::Mutant::LogicDropLhs),
609            (Mutation::ArithSwap, tmt_rt::Mutant::ArithSwap),
610            (Mutation::ArithSwap2, tmt_rt::Mutant::ArithSwap2),
611            (Mutation::ShiftF(-10.25), tmt_rt::Mutant::ShiftF(-10.25)),
612            (Mutation::ShiftF(1e-7), tmt_rt::Mutant::ShiftF(1e-7)),
613        ] {
614            assert_eq!(rt_mutant(m), expected);
615        }
616        for bad in [
617            "", "x:neg", "1:", "1:op9", "1:shx", "1:zzz", "neg", "1:shfnan", "1:shfinf", "1:shf",
618        ] {
619            assert_eq!(tmt_rt::parse_mutant(bad), None, "{bad:?}");
620        }
621    }
622
623    /// Float shifts: the runtime's result on the observed differences never changes for a
624    /// shift the planner calls safe.
625    #[test]
626    fn runtime_float_shifts_agree_with_the_planner() {
627        let observed = [-20.5f64, -3.0, 9.5, 12.0];
628        let mut obs = Obs::default();
629        for d in observed {
630            obs.merge(&Obs::of_f(d));
631        }
632        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
633            for shift in [-20.5, -10.0, -3.0, -1.5, 4.75, 9.5, 11.0] {
634                let changes_something = observed.iter().any(|d| {
635                    let rel = if *d < 0.0 { 1 } else { 4 };
636                    let orig = op.eval_d(if *d < 0.0 { -1 } else { 1 });
637                    tmt_rt::apply(
638                        rt_op(op),
639                        tmt_rt::Mutant::ShiftF(shift),
640                        orig,
641                        rel,
642                        tmt_rt::Diff::Float(*d),
643                    ) != orig
644                });
645                let predicted = crate::plan::infects(op, Mutation::ShiftF(shift), &obs);
646                // Safe by the planner implies unchanged at run time (the converse need not hold
647                // exactly at the edges of the gap).
648                assert!(predicted || !changes_something, "{op:?} shift={shift}");
649            }
650        }
651        // Equal floats are reported as a zero difference even where subtraction is not finite.
652        use tmt_rt::{Diff, Val};
653        assert_eq!(
654            tmt_rt::diff(Val::Float(f64::INFINITY), Val::Float(f64::INFINITY), true),
655            Diff::Float(0.0)
656        );
657        assert_eq!(
658            tmt_rt::diff(Val::Float(f64::INFINITY), Val::Float(1.0), false),
659            Diff::None
660        );
661        assert_eq!(
662            tmt_rt::diff(Val::Float(f64::NAN), Val::Float(1.0), false),
663            Diff::None
664        );
665        assert_eq!(
666            tmt_rt::diff(Val::Float(1.5), Val::Float(1.0), false),
667            Diff::Float(0.5)
668        );
669        assert_eq!(
670            tmt_rt::diff(Val::Int(3, 0, 9), Val::Int(5, 0, 9), false),
671            Diff::Int(-2)
672        );
673        assert_eq!(
674            tmt_rt::diff(Val::Int(3, 0, 9), Val::Float(5.0), false),
675            Diff::None
676        );
677        assert_eq!(tmt_rt::diff(Val::None, Val::None, true), Diff::None);
678    }
679
680    /// `&&` / `||` in the runtime against the plain operators and the planner's bits.
681    #[test]
682    fn runtime_logic_matches_the_operators() {
683        let run = |and: bool, m: Option<tmt_rt::Mutant>, a: bool, b: bool| -> (bool, bool) {
684            match tmt_rt::lhs_code(and, a, m) {
685                2 => (tmt_rt::rhs_value(and, b, m), true),
686                code => (code == 1, false),
687            }
688        };
689        for and in [true, false] {
690            for a in [true, false] {
691                for b in [true, false] {
692                    let real = if and { a && b } else { a || b };
693                    let swapped = if and { a || b } else { a && b };
694                    assert_eq!(run(and, None, a, b).0, real);
695                    assert_eq!(run(and, Some(tmt_rt::Mutant::LogicSwap), a, b).0, swapped);
696                    assert_eq!(
697                        run(and, Some(tmt_rt::Mutant::LogicDropLhs), a, b),
698                        (b, true)
699                    );
700                    // The right operand is evaluated exactly when the original evaluates it.
701                    assert_eq!(
702                        run(and, Some(tmt_rt::Mutant::LogicDropRhs), a, b),
703                        (a, run(and, None, a, b).1)
704                    );
705                    // Short-circuiting: the right operand is skipped exactly as in Rust.
706                    assert_eq!(run(and, None, a, b).1, if and { a } else { !a });
707
708                    // What the planner predicts from the observation bits is what changes.
709                    let (_, evaluated) = run(and, None, a, b);
710                    let bits = if !evaluated {
711                        tmt_rt::LOGIC_SHORT
712                    } else if b {
713                        tmt_rt::LOGIC_RHS_TRUE
714                    } else {
715                        tmt_rt::LOGIC_RHS_FALSE
716                    };
717                    let obs = crate::plan::LogicObs::from_bits(bits);
718                    for (m, rt) in [
719                        (Mutation::LogicDropRhs, tmt_rt::Mutant::LogicDropRhs),
720                        (Mutation::LogicDropLhs, tmt_rt::Mutant::LogicDropLhs),
721                    ] {
722                        let changed = run(and, Some(rt), a, b) != run(and, None, a, b);
723                        assert_eq!(
724                            crate::plan::logic_infects(and, m, &obs),
725                            changed,
726                            "and={and} a={a} b={b} {m:?}"
727                        );
728                    }
729                }
730            }
731        }
732        // Without a mutant or a trace the probes are the plain operators.
733        assert_eq!(tmt_rt::lhs(0, true, false), 0);
734        assert_eq!(tmt_rt::lhs(0, false, true), 1);
735        assert_eq!(tmt_rt::lhs(0, true, true), 2);
736        assert!(tmt_rt::rhs(0, true, true));
737        assert!(!tmt_rt::rhs(0, false, false));
738    }
739
740    #[test]
741    #[allow(clippy::needless_borrow)] // the explicit `&` is the call form the probes use
742    fn runtime_arithmetic_probes() {
743        use tmt_rt::{AnyAdd as _, AnyMul as _, AnySub as _, ArithNum, ArithPrim as _};
744        // Primitive numbers: the real operator.
745        assert_eq!((&tmt_rt::Ar::new(7u32, 2u32)).tmt_add(0), 9);
746        assert_eq!((&tmt_rt::Ar::new(7i64, 2)).tmt_sub(0), 5);
747        assert_eq!((&tmt_rt::Ar::new(7usize, 2)).tmt_mul(0), 14);
748        assert_eq!((&tmt_rt::Ar::new(7u8, 2)).tmt_div(0), 3);
749        assert_eq!((&tmt_rt::Ar::new(7i16, 2)).tmt_rem(0), 1);
750        assert_eq!((&tmt_rt::Ar::new(1.5f64, 2.0)).tmt_mul(0), 3.0);
751        // Everything else falls back to the operator's own implementation.
752        assert_eq!((&tmt_rt::Ar::new(String::from("a"), "b")).tmt_add(0), "ab");
753        let second = std::time::Duration::from_secs(1);
754        assert_eq!((&tmt_rt::Ar::new(second, second)).tmt_add(0), second * 2);
755        assert_eq!((&tmt_rt::Ar::new(second, 3u32)).tmt_mul(0), second * 3);
756        assert_eq!((&tmt_rt::Ar::new(&5i32, &3i32)).tmt_sub(0), 2);
757
758        // The swapped operator of each operator, and when it agrees.
759        for (op, swapped) in [
760            (tmt_rt::ADD, tmt_rt::SUB),
761            (tmt_rt::SUB, tmt_rt::ADD),
762            (tmt_rt::MUL, tmt_rt::DIV),
763            (tmt_rt::DIV, tmt_rt::MUL),
764            (tmt_rt::REM, tmt_rt::DIV),
765        ] {
766            assert_eq!(tmt_rt::arith_swapped(op), swapped);
767            for a in -6..=6i32 {
768                for b in -6..=6i32 {
769                    let real = |op: u8| match op {
770                        tmt_rt::ADD => a.checked_add(b),
771                        tmt_rt::SUB => a.checked_sub(b),
772                        tmt_rt::MUL => a.checked_mul(b),
773                        tmt_rt::DIV => a.checked_div(b),
774                        _ => a.checked_rem(b),
775                    };
776                    // Equal only when both are defined: a fault on either side has to be run.
777                    let same = matches!((real(op), real(swapped)), (Some(x), Some(y)) if x == y);
778                    assert_eq!(
779                        i32::tmt_same(op, tmt_rt::arith_swapped(op), a, b),
780                        same,
781                        "op={op} {a} {b}"
782                    );
783                    if let Some(value) = real(op) {
784                        assert_eq!(i32::tmt_real(op, a, b), value);
785                    }
786                }
787            }
788        }
789        assert!(u8::tmt_same(
790            tmt_rt::ADD,
791            tmt_rt::arith_swapped(tmt_rt::ADD),
792            9,
793            0
794        ));
795        // Both shifts overflow: not "the same", the tests decide.
796        assert!(!u8::tmt_same(
797            tmt_rt::SHL,
798            tmt_rt::arith_swapped(tmt_rt::SHL),
799            2,
800            9
801        ));
802        assert!(u8::tmt_same(
803            tmt_rt::SHL,
804            tmt_rt::arith_swapped(tmt_rt::SHL),
805            2,
806            0
807        ));
808        assert!(!u8::tmt_same(
809            tmt_rt::DIV,
810            tmt_rt::arith_swapped(tmt_rt::DIV),
811            4,
812            0
813        ));
814        assert!(
815            !u8::tmt_same(tmt_rt::ADD, tmt_rt::arith_swapped(tmt_rt::ADD), 250, 9),
816            "overflow in one of the two counts as different"
817        );
818        assert!(
819            !u8::tmt_same(tmt_rt::MUL, tmt_rt::arith_swapped(tmt_rt::MUL), 4, 0),
820            "division by zero counts as different"
821        );
822        assert!(f64::tmt_same(
823            tmt_rt::MUL,
824            tmt_rt::arith_swapped(tmt_rt::MUL),
825            4.0,
826            1.0
827        ));
828        assert!(!f64::tmt_same(
829            tmt_rt::ADD,
830            tmt_rt::arith_swapped(tmt_rt::ADD),
831            4.0,
832            0.5
833        ));
834        assert!(
835            !f32::tmt_same(tmt_rt::MUL, tmt_rt::arith_swapped(tmt_rt::MUL), 4.0, 0.0),
836            "4*0 is 0, 4/0 is infinite"
837        );
838    }
839
840    #[test]
841    fn runtime_summary_lines_round_trip() {
842        use tmt_rt::Diff;
843        let observations = [
844            (1, Diff::Int(-5)),
845            (1, Diff::Int(-2)),
846            (4, Diff::Int(9)),
847            (2, Diff::Int(0)),
848            (4, Diff::Int(3)),
849            (1, Diff::Float(-2.5)),
850            (1, Diff::Float(-0.125)),
851            (4, Diff::Float(1e-7)),
852            (8, Diff::None),
853        ];
854        let mut summary = tmt_rt::Summary::default();
855        let mut expected = Obs::default();
856        let mut text = String::new();
857        for (rel, d) in observations {
858            let changed = summary.observe(rel, d);
859            assert!(
860                changed,
861                "each of these observations adds information: {d:?}"
862            );
863            assert!(
864                !summary.observe(rel, d),
865                "repeating an observation changes nothing"
866            );
867            text.push_str(&summary.line(4, "tests::t"));
868            expected.merge(&match d {
869                Diff::Int(d) => Obs::of_d(d),
870                Diff::Float(d) => Obs::of_f(d),
871                Diff::None => Obs::of_rel(Rel::Unordered),
872            });
873        }
874        let trace = Trace::parse(&text);
875        assert_eq!(trace.malformed_lines, 0);
876        assert_eq!(trace.cmp[&4]["tests::t"], expected);
877        assert_eq!(expected.f_min_pos, Some(1e-7));
878
879        // Floats only: the summary keeps the float gap.
880        let mut floats = tmt_rt::Summary::default();
881        floats.observe(1, Diff::Float(-20.5));
882        floats.observe(4, Diff::Float(9.5));
883        let trace = Trace::parse(&floats.line(1, "t"));
884        assert_eq!(trace.cmp[&1]["t"].float_gap(), Some((-20.5, 9.5)));
885    }
886
887    #[test]
888    fn float_columns_are_validated() {
889        let gap = |line: &str| {
890            let trace = Trace::parse(line);
891            assert_eq!(trace.malformed_lines, 0, "{line:?}");
892            let o = trace.cmp[&1]["t"];
893            (o.f_max_neg, o.f_min_pos)
894        };
895        assert_eq!(
896            gap("O\t1\tt\t5\t1\t-\t-\t0\t-2.5\t0.5\n"),
897            (Some(-2.5), Some(0.5))
898        );
899        // Wrong sign, zero, or not finite: dropped.
900        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t2.5\t-0.5\n"), (None, None));
901        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t0.0\t0.0\n"), (None, None));
902        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t-inf\tinf\n"), (None, None));
903        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\tNaN\tNaN\n"), (None, None));
904        assert_eq!(
905            Trace::parse("O\t1\tt\t5\t1\t-\t-\t2\t-\t-\n").malformed_lines,
906            1,
907            "bad flag"
908        );
909        assert_eq!(
910            Trace::parse("O\t1\tt\t5\t1\t-\t-\t0\tx\t-\n").malformed_lines,
911            1
912        );
913    }
914
915    #[test]
916    fn return_lines() {
917        let returns = Trace::parse("B\t4\tt\t1\nB\t4\tt\t2\nB\t4\tu\t2\n");
918        assert_eq!(returns.malformed_lines, 0);
919        assert_eq!(
920            returns.returns[&4]["t"],
921            ReturnObs {
922                saw_true: true,
923                saw_false: true
924            }
925        );
926        assert_eq!(
927            returns.returns[&4]["u"],
928            ReturnObs {
929                saw_true: false,
930                saw_false: true
931            }
932        );
933        assert_eq!(
934            Trace::parse("B\t4\tt\t4\n").malformed_lines,
935            1,
936            "only two return bits exist"
937        );
938        assert_eq!(Trace::parse("B\t4\tt\t3\n").malformed_lines, 0);
939        assert_eq!(Trace::parse("A\t4\tt\t7\n").malformed_lines, 0);
940    }
941
942    #[test]
943    fn logic_arithmetic_and_reach_lines() {
944        let trace = Trace::parse(
945            "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",
946        );
947        assert_eq!(trace.malformed_lines, 0);
948        assert_eq!(
949            trace.logic[&1]["t"],
950            crate::plan::LogicObs {
951                short: true,
952                rhs_true: false,
953                rhs_false: true,
954                rhs_started: false,
955            }
956        );
957        assert_eq!(
958            trace.logic[&1]["u"],
959            crate::plan::LogicObs {
960                short: false,
961                rhs_true: true,
962                rhs_false: false,
963                rhs_started: false,
964            }
965        );
966        assert_eq!(
967            trace.arith[&2]["t"],
968            crate::plan::ArithObs {
969                same: true,
970                differs: false,
971                opaque: false,
972                ..Default::default()
973            }
974        );
975        assert_eq!(
976            trace.arith[&2]["u"],
977            crate::plan::ArithObs {
978                same: false,
979                differs: true,
980                opaque: true,
981                ..Default::default()
982            }
983        );
984        assert!(trace.reach[&3].contains("t"));
985        // A range that ended at the largest value of its type is remembered as one.
986        let ranges = Trace::parse("R\t7\tt\t3\nR\t8\tt\t1\n");
987        assert_eq!(ranges.malformed_lines, 0);
988        assert!(ranges.reach[&7].contains("t") && ranges.reach[&8].contains("t"));
989        assert_eq!(ranges.ranges_at_top.iter().collect::<Vec<_>>(), [&7]);
990        // A right operand that was started, with and without a value.
991        let started = Trace::parse("L\t1\tt\t8\nL\t1\tu\t10\n");
992        assert_eq!(started.malformed_lines, 0);
993        assert!(started.logic[&1]["t"].rhs_started && !started.logic[&1]["t"].rhs_true);
994        assert!(started.logic[&1]["u"].rhs_started && started.logic[&1]["u"].rhs_true);
995        for bad in [
996            "L\t1\tt\t0\n",
997            "L\t1\tt\t16\n",
998            "A\t1\t\t1\n",
999            "R\t1\tt\n",
1000            "L\tx\tt\t1\n",
1001            "Z\t1\tt\t1\n",
1002        ] {
1003            assert_eq!(Trace::parse(bad).malformed_lines, 1, "{bad:?}");
1004        }
1005    }
1006
1007    #[test]
1008    #[allow(clippy::needless_borrow)] // the explicit `&` is the call form the probes use
1009    fn runtime_probes_are_transparent_without_env() {
1010        use tmt_rt::{Val, ValAny as _, ValNum as _};
1011        // Autoref specialisation: numbers carry values, everything else does not.
1012        assert_eq!((&tmt_rt::W(&7u8)).tmt_val(), Val::Int(7, 0, 255));
1013        assert_eq!(
1014            (&tmt_rt::W(&&-3i64)).tmt_val(),
1015            Val::Int(-3, i64::MIN as i128, i64::MAX as i128)
1016        );
1017        assert_eq!((&tmt_rt::W(&1.5f64)).tmt_val(), Val::Float(1.5));
1018        assert_eq!((&tmt_rt::W(&&2.5f32)).tmt_val(), Val::Float(2.5));
1019        assert_eq!((&tmt_rt::W("text")).tmt_val(), Val::None);
1020        assert_eq!((&tmt_rt::W(&true)).tmt_val(), Val::None);
1021        assert_eq!(
1022            (&tmt_rt::W(&'c')).tmt_val(),
1023            Val::Int('c' as u32 as i128, 0, 0x10_D7FF)
1024        );
1025        assert_eq!(
1026            (&tmt_rt::W(&'\u{e000}')).tmt_val(),
1027            Val::Int(0xD800, 0, 0x10_D7FF)
1028        );
1029        {
1030            use tmt_rt::{CastAny as _, CastPrim as _};
1031            assert_eq!((&tmt_rt::W(&7u8)).tmt_cast_bounds(), Some((0, 255)));
1032            assert_eq!((&tmt_rt::W(&-1i8)).tmt_cast_bounds(), Some((-128, 127)));
1033            assert_eq!((&tmt_rt::W(&true)).tmt_cast_bounds(), Some((0, 1)));
1034            assert_eq!((&tmt_rt::W(&'a')).tmt_cast_bounds(), Some((0, 0x1f_ffff)));
1035            assert_eq!((&tmt_rt::W(&1.5f64)).tmt_cast_bounds(), None);
1036            assert_eq!((&tmt_rt::W("text")).tmt_cast_bounds(), None);
1037        }
1038        // Polymorphic or conflicting cast bounds collapse to None; reversed bounds are malformed.
1039        let poly = Trace::parse(
1040            "C\t5\t0\t0\t255\n\
1041             C\t5\t0\t0\t255\n\
1042             C\t5\t1\t0\t255\n\
1043             C\t5\t1\t0\t65535\n\
1044             C\t5\t2\t0\t255\n\
1045             C\t5\t2\t-\t-\n\
1046             C\t5\t3\t10\t5\n",
1047        );
1048        assert_eq!(poly.malformed_lines, 1);
1049        assert_eq!(poly.cast_bounds.get(&(5, 0)), Some(&Some((0, 255))));
1050        assert_eq!(poly.cast_bounds.get(&(5, 1)), Some(&None));
1051        assert_eq!(poly.cast_bounds.get(&(5, 2)), Some(&None));
1052        assert!(!poly.cast_bounds.contains_key(&(5, 3)));
1053
1054        for (a, b) in [(1, 2), (2, 2), (3, 2)] {
1055            assert_eq!(
1056                tmt_rt::ord(0, tmt_rt::LT, &a, &b, Val::None, Val::None),
1057                a < b
1058            );
1059            assert_eq!(
1060                tmt_rt::ord(0, tmt_rt::LE, &a, &b, Val::None, Val::None),
1061                a <= b
1062            );
1063            assert_eq!(
1064                tmt_rt::ord(0, tmt_rt::GT, &a, &b, Val::None, Val::None),
1065                a > b
1066            );
1067            assert_eq!(
1068                tmt_rt::ord(0, tmt_rt::GE, &a, &b, Val::None, Val::None),
1069                a >= b
1070            );
1071            assert_eq!(
1072                tmt_rt::eq(0, tmt_rt::EQ, &a, &b, Val::None, Val::None),
1073                a == b
1074            );
1075            assert_eq!(
1076                tmt_rt::eq(0, tmt_rt::NE, &a, &b, Val::None, Val::None),
1077                a != b
1078            );
1079        }
1080        assert!(!tmt_rt::ord(
1081            0,
1082            tmt_rt::GE,
1083            &f64::NAN,
1084            &1.0,
1085            Val::None,
1086            Val::None
1087        ));
1088        assert!(tmt_rt::eq(0, tmt_rt::NE, "a", "b", Val::None, Val::None));
1089        assert!(tmt_rt::live(0));
1090    }
1091    /// The two replacements of each operator are those of cargo-mutants, and the runtime
1092    /// and the report name the same ones.
1093    #[test]
1094    fn both_replacements_of_every_operator() {
1095        use crate::instrument::ArithOp;
1096        let code = |op: ArithOp| match op {
1097            ArithOp::Add => tmt_rt::ADD,
1098            ArithOp::Sub => tmt_rt::SUB,
1099            ArithOp::Mul => tmt_rt::MUL,
1100            ArithOp::Div => tmt_rt::DIV,
1101            ArithOp::Rem => tmt_rt::REM,
1102            ArithOp::BitAnd => tmt_rt::BITAND,
1103            ArithOp::BitOr => tmt_rt::BITOR,
1104            ArithOp::BitXor => tmt_rt::BITXOR,
1105            ArithOp::Shl => tmt_rt::SHL,
1106            ArithOp::Shr => tmt_rt::SHR,
1107        };
1108        let table = [
1109            (ArithOp::Add, "-", Some("*")),
1110            (ArithOp::Sub, "+", Some("/")),
1111            (ArithOp::Mul, "/", Some("+")),
1112            (ArithOp::Div, "*", Some("%")),
1113            (ArithOp::Rem, "/", Some("+")),
1114            (ArithOp::BitAnd, "|", Some("^")),
1115            (ArithOp::BitOr, "&", Some("^")),
1116            (ArithOp::BitXor, "&", Some("|")),
1117            (ArithOp::Shl, ">>", None),
1118            (ArithOp::Shr, "<<", None),
1119        ];
1120        assert_eq!(table.map(|row| row.0), ArithOp::ALL);
1121        for (op, first, second) in table {
1122            assert_eq!(op.swapped().symbol(), first, "{op:?}");
1123            assert_eq!(op.swapped2().map(ArithOp::symbol), second, "{op:?}");
1124            assert_eq!(
1125                tmt_rt::arith_swapped(code(op)),
1126                code(op.swapped()),
1127                "{op:?}"
1128            );
1129            assert_eq!(
1130                tmt_rt::arith_swapped2(code(op)),
1131                op.swapped2().map(code),
1132                "{op:?}"
1133            );
1134        }
1135        assert_eq!(
1136            tmt_rt::parse_mutant("3:as2"),
1137            Some((3, tmt_rt::Mutant::ArithSwap2))
1138        );
1139
1140        // What is recorded for a pair of operands: whether each replacement agrees.
1141        use tmt_rt::ArithNum;
1142        // 2 + 2 = 2 * 2, but not 2 - 2.
1143        assert!(!i32::tmt_same(tmt_rt::ADD, tmt_rt::SUB, 2, 2));
1144        assert!(i32::tmt_same(tmt_rt::ADD, tmt_rt::MUL, 2, 2));
1145        // 6 / 1 = 6 * 1, but not 6 % 1.
1146        assert!(i32::tmt_same(tmt_rt::DIV, tmt_rt::MUL, 6, 1));
1147        assert!(!i32::tmt_same(tmt_rt::DIV, tmt_rt::REM, 6, 1));
1148        // 4 | 1 = 4 ^ 1, but not 4 & 1.
1149        assert!(i32::tmt_same(tmt_rt::BITOR, tmt_rt::BITXOR, 4, 1));
1150        assert!(!i32::tmt_same(tmt_rt::BITOR, tmt_rt::BITAND, 4, 1));
1151        assert!(f64::tmt_same(tmt_rt::MUL, tmt_rt::ADD, 2.0, 2.0));
1152
1153        // And as the planner reads it.
1154        let seen = |bits: u8| crate::plan::ArithObs::from_bits(bits);
1155        let both = seen(tmt_rt::ARITH_DIFFERS | tmt_rt::ARITH_SAME2);
1156        assert!(both.differs && both.same2 && !both.same && !both.differs2 && !both.opaque);
1157        assert!(both.infected_by(Mutation::ArithSwap));
1158        assert!(!both.infected_by(Mutation::ArithSwap2));
1159        let other = seen(tmt_rt::ARITH_SAME | tmt_rt::ARITH_DIFFERS2);
1160        assert!(!other.infected_by(Mutation::ArithSwap));
1161        assert!(other.infected_by(Mutation::ArithSwap2));
1162        assert_eq!(crate::plan::plan_arith(&both), crate::plan::ArithPlan::Run);
1163        assert_eq!(
1164            crate::plan::plan_arith(&both.second()),
1165            crate::plan::ArithPlan::NeverDiffers
1166        );
1167        assert_eq!(
1168            crate::plan::plan_arith(&other.second()),
1169            crate::plan::ArithPlan::Run
1170        );
1171        let mut merged = both;
1172        merged.merge(&other);
1173        assert!(merged.same && merged.differs && merged.same2 && merged.differs2);
1174        let mut merged = other;
1175        merged.merge(&both);
1176        assert!(merged.same && merged.differs && merged.same2 && merged.differs2);
1177        // An assignment that collects bits has one replacement, as in cargo-mutants.
1178        assert_eq!(ArithOp::BitOr.second(true), None);
1179        assert_eq!(ArithOp::BitAnd.second(true), None);
1180        assert_eq!(ArithOp::BitXor.second(true), Some(ArithOp::BitOr));
1181        assert_eq!(ArithOp::BitOr.second(false), Some(ArithOp::BitXor));
1182        assert_eq!(ArithOp::Add.second(true), Some(ArithOp::Mul));
1183        // Operands that are not numbers stay that for both.
1184        assert_eq!(
1185            crate::plan::plan_arith(&seen(tmt_rt::ARITH_OPAQUE).second()),
1186            crate::plan::ArithPlan::Opaque
1187        );
1188        assert_eq!(Mutation::ArithSwap2.encode(), "as2");
1189
1190        // A trace line with the wider bits is read; one beyond them is not.
1191        let trace = Trace::parse("A\t1\tt\t18\nA\t2\tt\t31\nA\t3\tt\t32\n");
1192        assert_eq!(trace.arith[&1]["t"], seen(18));
1193        assert!(trace.arith.contains_key(&2) && !trace.arith.contains_key(&3));
1194        assert_eq!(trace.malformed_lines, 1);
1195    }
1196
1197    /// A probe in a loop asks the tracer only when it has something new to say.
1198    #[test]
1199    fn two_traces_differ_by_the_records_that_are_not_the_same() {
1200        let text =
1201            "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";
1202        let base = Trace::parse(text);
1203        assert_eq!(base.malformed_lines, 0);
1204        assert_eq!(base.differences(&Trace::parse(text)), 0);
1205        // Each kind of record counts, in whichever of the two it is missing or other.
1206        for (other, differing) in [
1207            ("O\t1\ta\t3\t0\t-1\t-\t1\t-\t-\n", 1), // a nearer value
1208            ("O\t1\tb\t3\t0\t-2\t-\t1\t-\t-\n", 1), // seen by another test too
1209            ("O\t9\ta\t3\t0\t-2\t-\t1\t-\t-\n", 1), // at another site too
1210            ("L\t2\ta\t2\n", 1),
1211            ("A\t3\ta\t2\n", 1),
1212            ("B\t4\ta\t2\n", 1),
1213            ("R\t5\tb\t1\n", 1),
1214            ("R\t6\ta\t1\nL\t2\tb\t1\n", 2),
1215        ] {
1216            let more = Trace::parse(&format!("{text}{other}"));
1217            assert_eq!(base.differences(&more), differing, "{other:?}");
1218            assert_eq!(more.differences(&base), differing, "{other:?}");
1219        }
1220        assert_eq!(base.differences(&Trace::default()), 5);
1221        assert_eq!(Trace::default().differences(&base), 5);
1222    }
1223
1224    #[test]
1225    fn sorted_audit_counts_changes_once_across_interleaved_keys() {
1226        let before = [((0, "a"), 1), ((1, "a"), 2), ((1, "ba"), 3), ((7, "u"), 4)];
1227        let after = [((1, "a"), 2), ((1, "b"), 3), ((1, "ba"), 7), ((8, "u"), 4)];
1228        assert_eq!(differing(before.into_iter(), after.into_iter()), 5);
1229        assert_eq!(differing(after.into_iter(), before.into_iter()), 5);
1230        assert_eq!(differing(before.into_iter(), before.into_iter()), 0);
1231        assert_eq!(differing(before.into_iter(), [].into_iter()), 4);
1232    }
1233
1234    #[test]
1235    fn only_a_known_distance_coming_closer_can_wait() {
1236        use tmt_rt::{Diff, News, Summary};
1237        let mut s = Summary::default();
1238        // The first distance on each side is news of the other kind, and so is a new relation.
1239        assert_eq!(s.news(1, Diff::Int(-9)), News::Other);
1240        assert_eq!(s.news(1, Diff::Int(-9)), News::Nothing);
1241        assert_eq!(s.news(1, Diff::Int(-10)), News::Nothing);
1242        assert_eq!(s.news(1, Diff::Int(-4)), News::Closer);
1243        assert_eq!(s.news(4, Diff::Int(7)), News::Other);
1244        assert_eq!(s.news(4, Diff::Int(6)), News::Closer);
1245        assert_eq!(s.news(1, Diff::Int(-1)), News::Closer);
1246        assert_eq!(s.news(2, Diff::Int(0)), News::Other);
1247        assert_eq!((s.max_neg, s.min_pos), (Some(-1), Some(6)));
1248        // Floats alike; a closer distance together with something new does not wait.
1249        assert_eq!(s.news(1, Diff::Float(-2.0)), News::Other);
1250        assert_eq!(s.news(1, Diff::Float(-1.5)), News::Closer);
1251        assert_eq!(s.news(4, Diff::Float(0.5)), News::Other);
1252        assert_eq!(s.news(4, Diff::Float(0.25)), News::Closer);
1253        let mut t = Summary::default();
1254        assert_eq!(t.news(1, Diff::Int(-9)), News::Other);
1255        assert_eq!(t.news(8, Diff::Int(-3)), News::Other);
1256        assert_eq!(t.news(8, Diff::None), News::Other);
1257    }
1258
1259    #[test]
1260    fn summary_classifies_type_and_distance_changes_independently() {
1261        use tmt_rt::{Diff, News, Summary};
1262
1263        let mut summary = Summary::default();
1264        for (rel, diff, expected) in [
1265            (1, Diff::Int(i128::MIN), News::Other),
1266            (1, Diff::Int(i128::MIN), News::Nothing),
1267            (1, Diff::Int(-1), News::Closer),
1268            (1, Diff::Int(i128::MAX), News::Other),
1269            (5, Diff::Int(1), News::Other),
1270            (2, Diff::Float(-0.0), News::Other),
1271            (2, Diff::Float(0.0), News::Nothing),
1272            (2, Diff::Float(f64::NAN), News::Nothing),
1273            (1, Diff::Float(-f64::MAX), News::Other),
1274            (1, Diff::Float(-f64::MIN_POSITIVE), News::Closer),
1275            (1, Diff::Float(-f64::MAX), News::Nothing),
1276            (4, Diff::Float(f64::MAX), News::Other),
1277            (4, Diff::Float(f64::MIN_POSITIVE), News::Closer),
1278            (1, Diff::None, News::Nothing),
1279        ] {
1280            assert_eq!(summary.news(rel, diff), expected, "{rel} {diff:?}");
1281        }
1282        assert_eq!(summary.rels, 7);
1283        assert!(summary.unvalued && summary.unfloat);
1284        assert_eq!((summary.max_neg, summary.min_pos), (Some(-1), Some(1)));
1285        assert_eq!(summary.f_max_neg, Some(-f64::MIN_POSITIVE));
1286        assert_eq!(summary.f_min_pos, Some(f64::MIN_POSITIVE));
1287    }
1288
1289    #[test]
1290    fn a_backlog_hands_out_the_latest_of_each_site_once() {
1291        use tmt_rt::{Backlog, Diff, Summary};
1292        let at = |d: i128| {
1293            let mut s = Summary::default();
1294            s.observe(1, Diff::Int(d));
1295            s
1296        };
1297        let mut backlog = Backlog::default();
1298        assert!(backlog.drain().is_empty());
1299        backlog.keep(7, at(-5));
1300        backlog.keep(2, at(-8));
1301        backlog.keep(7, at(-3));
1302        assert_eq!(backlog.drain(), [(7, at(-3)), (2, at(-8))]);
1303        assert!(backlog.drain().is_empty(), "written once");
1304        // Kept again after it was written: written again.
1305        backlog.keep(7, at(-1));
1306        assert_eq!(backlog.drain(), [(7, at(-1))]);
1307        // A site written by other means is not written from here, the others are.
1308        backlog.keep(7, at(-1));
1309        backlog.keep(2, at(-2));
1310        backlog.keep(9, at(-4));
1311        backlog.forget(2);
1312        backlog.forget(100);
1313        backlog.forget(1);
1314        assert_eq!(backlog.drain(), [(7, at(-1)), (9, at(-4))]);
1315        backlog.keep(2, at(-1));
1316        assert_eq!(backlog.drain(), [(2, at(-1))]);
1317    }
1318
1319    #[test]
1320    fn a_thread_remembers_what_it_recorded() {
1321        // Sites of their own, far from the ones other tests of this binary use.
1322        let site = 900_000;
1323        assert!(!tmt_rt::bits_known(b'A', site, 1));
1324        assert!(tmt_rt::bits_are_news(b'A', site, 1));
1325        assert!(!tmt_rt::bits_are_news(b'A', site, 1));
1326        assert!(tmt_rt::bits_known(b'A', site, 1));
1327        // Another bit of the same site is news once, and then both are known.
1328        assert!(!tmt_rt::bits_known(b'A', site, 3));
1329        assert!(tmt_rt::bits_are_news(b'A', site, 3));
1330        assert!(!tmt_rt::bits_are_news(b'A', site, 2));
1331        assert!(tmt_rt::bits_known(b'A', site, 3));
1332        // Each kind of record and each site has its own memory.
1333        for kind in *b"RLB" {
1334            assert!(!tmt_rt::bits_known(kind, site, 1), "{}", kind as char);
1335            assert!(tmt_rt::bits_are_news(kind, site, 1), "{}", kind as char);
1336            assert!(!tmt_rt::bits_are_news(kind, site, 1), "{}", kind as char);
1337        }
1338        assert!(tmt_rt::bits_are_news(b'A', site + 1, 1));
1339        assert!(!tmt_rt::bits_known(b'A', site - 1, 1));
1340        // And each thread: a test is a thread.
1341        std::thread::spawn(move || {
1342            assert!(!tmt_rt::bits_known(b'A', site, 1));
1343            assert!(tmt_rt::bits_are_news(b'A', site, 1));
1344        })
1345        .join()
1346        .unwrap();
1347    }
1348
1349    #[test]
1350    fn float_min_max_distinguishes_signed_zeros_and_nan() {
1351        assert!(tmt_rt::float_min_max_same(1.5, 1.5));
1352        assert!(tmt_rt::float_min_max_same(0.0, 0.0));
1353        assert!(tmt_rt::float_min_max_same(-0.0, -0.0));
1354        assert!(!tmt_rt::float_min_max_same(-0.0, 0.0));
1355        assert!(!tmt_rt::float_min_max_same(f64::NAN, f64::NAN));
1356        assert!(!tmt_rt::float_min_max_same(f64::NAN, 1.0));
1357    }
1358
1359    #[test]
1360    fn zero_alloc_str_replace_and_affix_match_std() {
1361        use tmt_rt::TmtStrPat as _;
1362        let haystacks = [
1363            "",
1364            "a",
1365            "aa",
1366            "aaa",
1367            "aaaa",
1368            "abc/def/ghi",
1369            "abc/def",
1370            "猫/犬/猫",
1371            "猫猫猫",
1372            "prefix_middle_suffix",
1373        ];
1374        let patterns = [
1375            "", "a", "aa", "/", "猫", "prefix", "suffix", "middle", "xyz",
1376        ];
1377        let targets = ["", "a", "b", "aa", "bb", "/", "-", "猫", "犬"];
1378        for s in haystacks {
1379            for p in patterns {
1380                for t in targets {
1381                    assert_eq!(
1382                        tmt_rt::str_replace_differs(s, p, t),
1383                        s.replace(p, t) != s.replacen(p, t, 1),
1384                        "replace s={s:?} p={p:?} t={t:?}"
1385                    );
1386                }
1387                for starts in [true, false] {
1388                    let expected = if starts {
1389                        s.starts_with(p) != s.contains(p)
1390                    } else {
1391                        s.ends_with(p) != s.contains(p)
1392                    };
1393                    assert_eq!(
1394                        p.tmt_affix_differs(s, starts),
1395                        expected,
1396                        "affix s={s:?} p={p:?} starts={starts}"
1397                    );
1398                }
1399            }
1400            for c in ['a', '/', '猫', 'z'] {
1401                for t in ["", "a", "b", "/", "猫", "犬"] {
1402                    assert_eq!(
1403                        c.tmt_replace_differs(s, t),
1404                        s.replace(c, t) != s.replacen(c, t, 1),
1405                        "char replace s={s:?} c={c:?} t={t:?}"
1406                    );
1407                }
1408                for starts in [true, false] {
1409                    let expected = if starts {
1410                        s.starts_with(c) != s.contains(c)
1411                    } else {
1412                        s.ends_with(c) != s.contains(c)
1413                    };
1414                    assert_eq!(
1415                        c.tmt_affix_differs(s, starts),
1416                        expected,
1417                        "char affix s={s:?} c={c:?} starts={starts}"
1418                    );
1419                }
1420            }
1421        }
1422    }
1423
1424    #[test]
1425    fn trace_parser_preserves_plus_prefix_and_bare_cr_semantics() {
1426        // Leading `+` is accepted by `str::parse::<u32>()`.
1427        let plus = Trace::parse("R\t+3\tt\t+1\n");
1428        assert_eq!(plus.malformed_lines, 0);
1429        assert!(plus.reach[&3].contains("t"));
1430        // A bare `\r` without `\n` is NOT stripped by `str::lines()`, so the bits field fails to parse.
1431        let bare_cr = Trace::parse("R\t3\tt\t1\r");
1432        assert_eq!(bare_cr.malformed_lines, 1);
1433        assert!(bare_cr.reach.is_empty());
1434    }
1435
1436    #[test]
1437    fn parses_lit_set_records_and_encodes_drop_literal_elem() {
1438        let trace = Trace::parse(
1439            "S\t4\ttests::a\t257\n\
1440             S\t4\ttests::a\t260\n\
1441             S\t4\ttests::b\t256\n\
1442             S\t5\ttests::c\t512\n\
1443             S\t6\ttests::bad\t0\n\
1444             S\t6\ttests::bad\t1024\n",
1445        );
1446        assert_eq!(trace.malformed_lines, 2);
1447        let a = trace.lit_set[&4]["tests::a"];
1448        assert!(a.reached && !a.opaque);
1449        assert!(a.matched_elem(0));
1450        assert!(!a.matched_elem(1));
1451        assert!(a.matched_elem(2));
1452        let b = trace.lit_set[&4]["tests::b"];
1453        assert!(b.reached && b.matched == 0);
1454        let c = trace.lit_set[&5]["tests::c"];
1455        assert!(!c.reached && c.opaque);
1456
1457        let other = Trace::parse("S\t4\ttests::a\t257\nS\t4\ttests::b\t256\nS\t5\ttests::c\t512\n");
1458        assert_eq!(trace.differences(&other), 1);
1459
1460        for idx in 0..8u8 {
1461            let encoded = format!("7:{}", Mutation::DropLiteralElem(idx).encode());
1462            assert_eq!(
1463                tmt_rt::parse_mutant(&encoded),
1464                Some((7, tmt_rt::Mutant::DropLiteralElem(idx)))
1465            );
1466        }
1467        assert_eq!(tmt_rt::parse_mutant("7:dle8"), None);
1468    }
1469}