Skip to main content

targeted_mutation/
baseline.rs

1//! Findings the user has already looked at: `// tmt:ignore` comments and baseline files.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6use anyhow::{Context, Result};
7
8use crate::report::Finding;
9
10/// What identifies a finding across runs: its kind, file, code and surviving mutants.
11/// Line numbers are left out, so code that merely moves keeps its fingerprint.
12pub fn fingerprint(finding: &Finding) -> String {
13    // A mutant built on its own was an assertion gap when fingerprints were written.
14    let kind = match finding {
15        Finding::InputGap { .. } => "input_gap",
16        Finding::AssertionGap { .. } | Finding::Survivor { .. } => "assertion_gap",
17    };
18    let (at, survivors) = (finding.at(), finding.survivors());
19    format!(
20        "{kind}\t{}\t{}\t{}",
21        at.file,
22        at.code,
23        survivors.join(" | ")
24    )
25}
26
27/// The findings a baseline file lists.
28#[derive(Debug, PartialEq)]
29pub enum Baseline {
30    /// As written before findings had names of their own: by [`fingerprint`].
31    Fingerprints(BTreeSet<String>),
32    /// By the name of the finding (`report::finding_id`).
33    Ids(BTreeSet<String>),
34}
35
36impl Baseline {
37    pub fn knows(&self, finding: &Finding) -> bool {
38        let at = finding.at();
39        match self {
40            Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
41            Baseline::Ids(ids) => !at.id.is_empty() && ids.contains(&at.id),
42        }
43    }
44}
45
46/// The version of the file [`write`] writes.
47const VERSION: u64 = 2;
48
49/// Reads a baseline: the object [`write`] writes, or the list of fingerprints earlier
50/// versions wrote.
51pub fn load(path: &Path) -> Result<Baseline> {
52    let text =
53        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
54    parse(&text).with_context(|| format!("{} is not a tmt baseline", path.display()))
55}
56
57fn parse(text: &str) -> Result<Baseline> {
58    let mut value: serde_json::Value = serde_json::from_str(text)?;
59    if value.is_array() {
60        return Ok(Baseline::Fingerprints(serde_json::from_value(value)?));
61    }
62    match value["version"].as_u64() {
63        Some(VERSION) => Ok(Baseline::Ids(serde_json::from_value(
64            value["findings"].take(),
65        )?)),
66        Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
67        None => anyhow::bail!("neither a list nor an object with a version"),
68    }
69}
70
71pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
72    let mut text = render(findings);
73    text.push('\n');
74    std::fs::write(path, text).with_context(|| format!("writing {}", path.display()))
75}
76
77fn render(findings: &[Finding]) -> String {
78    #[derive(serde::Serialize)]
79    struct BaselineFile<'a> {
80        findings: BTreeSet<&'a str>,
81        version: u64,
82    }
83
84    let ids: BTreeSet<&str> = findings
85        .iter()
86        .map(|finding| {
87            let at = finding.at();
88            at.id.as_str()
89        })
90        .collect();
91    serde_json::to_string_pretty(&BaselineFile {
92        findings: ids,
93        version: VERSION,
94    })
95    .expect("strings serialise")
96}
97
98/// Lines covered by a `// tmt:ignore` comment, with the reason given after it. A
99/// standalone comment line covers its own line and the next one (so it can sit above the
100/// code); an end-of-line comment covers only its own line.
101pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
102    let mut ignored = BTreeMap::new();
103    let bytes = source.as_bytes();
104    let mut i = 0;
105    let mut line = 1usize;
106    let mut line_start = 0usize;
107    let mut block_depth = 0usize;
108    while i < bytes.len() {
109        if block_depth > 0 {
110            if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
111                block_depth += 1;
112                i += 2;
113            } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
114                block_depth -= 1;
115                i += 2;
116            } else {
117                if bytes[i] == b'\n' {
118                    line += 1;
119                    line_start = i + 1;
120                }
121                i += 1;
122            }
123            continue;
124        }
125        match bytes[i] {
126            b'\n' => {
127                line += 1;
128                line_start = i + 1;
129                i += 1;
130            }
131            b'/' if bytes.get(i + 1) == Some(&b'/') => {
132                let comment_start = i + 2;
133                let mut end = comment_start;
134                while end < bytes.len() && bytes[end] != b'\n' {
135                    end += 1;
136                }
137                let comment = &source[comment_start..end];
138                if let Some(rest) = comment.trim_start().strip_prefix("tmt:ignore")
139                    && (rest.is_empty()
140                        || rest.starts_with(|c: char| c.is_whitespace() || c == ':'))
141                {
142                    let reason = rest.trim_start_matches(':').trim().to_string();
143                    let standalone = source[line_start..i].trim().is_empty();
144                    ignored.insert(line, reason.clone());
145                    if standalone {
146                        ignored.entry(line + 1).or_insert(reason);
147                    }
148                }
149                i = end;
150            }
151            b'/' if bytes.get(i + 1) == Some(&b'*') => {
152                block_depth = 1;
153                i += 2;
154            }
155            // Raw strings: `r"..."`, `r#"..."#`, `br#"..."#`, `cr#"..."#`.
156            b'r' if raw_string_hashes(bytes, i).is_some() => {
157                let hashes = raw_string_hashes(bytes, i).unwrap();
158                i += 1 + hashes + 1;
159                while i < bytes.len() {
160                    if bytes[i] == b'\n' {
161                        line += 1;
162                        line_start = i + 1;
163                    }
164                    if bytes[i] == b'"'
165                        && bytes
166                            .get(i + 1..i + 1 + hashes)
167                            .is_some_and(|s| s.iter().all(|b| *b == b'#'))
168                    {
169                        i += 1 + hashes;
170                        break;
171                    }
172                    i += 1;
173                }
174            }
175            b'"' => {
176                i += 1;
177                while i < bytes.len() {
178                    if bytes[i] == b'\\' {
179                        if bytes.get(i + 1) == Some(&b'\n') {
180                            line += 1;
181                            line_start = i + 2;
182                        }
183                        i = (i + 2).min(bytes.len());
184                        continue;
185                    }
186                    if bytes[i] == b'\n' {
187                        line += 1;
188                        line_start = i + 1;
189                    }
190                    if bytes[i] == b'"' {
191                        i += 1;
192                        break;
193                    }
194                    i += 1;
195                }
196            }
197            // Character literals (`'"'`, `'\\'`, `'\''`, `'a'`); lifetimes (`'a`) have no closing `'`.
198            b'\'' => {
199                if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 2).is_some_and(|&b| b != b'\n')
200                {
201                    // Escape char literal such as `'\''`, `'\"'`, `'\\'`, `'\x7f'`, `'\u{...}'`.
202                    // Start after the escaped byte so `'\''` does not close on the escaped quote.
203                    let mut j = i + 3;
204                    while j < bytes.len() && bytes[j] != b'\n' && bytes[j] != b'\'' {
205                        j += 1;
206                    }
207                    if bytes.get(j) == Some(&b'\'') {
208                        i = j + 1;
209                    } else {
210                        i += 1;
211                    }
212                } else if let Some(ch) = source[i + 1..].chars().next()
213                    && bytes.get(i + 1 + ch.len_utf8()) == Some(&b'\'')
214                {
215                    i += 1 + ch.len_utf8() + 1;
216                } else {
217                    i += 1;
218                }
219            }
220            _ => i += 1,
221        }
222    }
223    ignored
224}
225
226fn raw_string_hashes(bytes: &[u8], r_pos: usize) -> Option<usize> {
227    // Reject identifier suffixes like `str"..."` (except `br"` / `cr"`).
228    if r_pos > 0 {
229        let prev = bytes[r_pos - 1];
230        let is_prefix =
231            (prev == b'b' || prev == b'c') && (r_pos == 1 || !is_ident_byte(bytes[r_pos - 2]));
232        if is_ident_byte(prev) && !is_prefix {
233            return None;
234        }
235    }
236    let mut hashes = 0;
237    while bytes.get(r_pos + 1 + hashes) == Some(&b'#') {
238        hashes += 1;
239    }
240    (bytes.get(r_pos + 1 + hashes) == Some(&b'"')).then_some(hashes)
241}
242
243fn is_ident_byte(b: u8) -> bool {
244    b.is_ascii_alphanumeric() || b == b'_'
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use crate::report::Location;
251
252    fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
253        Finding::AssertionGap {
254            at: Location {
255                file: "src/lib.rs".into(),
256                line,
257                column: 5,
258                code: code.into(),
259                ..Location::default()
260            },
261            survivors: survivors.iter().map(|s| s.to_string()).collect(),
262            tests: vec!["tests::t".into()],
263            effects: vec![],
264            effects_of: None,
265            witness: None,
266        }
267    }
268
269    #[test]
270    fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
271        let named = |id: &str, survivors: &[&str]| {
272            let mut finding = gap(10, "a > b", survivors);
273            let Finding::AssertionGap { at, .. } = &mut finding else {
274                unreachable!()
275            };
276            at.id = id.to_string();
277            finding
278        };
279        let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
280        let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
281        let written = render(std::slice::from_ref(&one));
282        let baseline = parse(&written).unwrap();
283        assert!(baseline.knows(&one));
284        // The same code in another function is another finding.
285        assert!(!baseline.knows(&other));
286        // Other words for the mutants, or one more of them, and it is still the one.
287        assert!(baseline.knows(&named(
288            "assertion_gap|src/lib.rs|f|a > b|0",
289            &["`a >= b`", "the negation"]
290        )));
291        // A finding without a name is not known by having none.
292        assert!(
293            !parse(&render(&[gap(1, "x", &[])]))
294                .unwrap()
295                .knows(&gap(2, "y", &[]))
296        );
297        // A file of an earlier version lists fingerprints, and still works as it did.
298        let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
299        let baseline = parse(&old).unwrap();
300        assert!(matches!(baseline, Baseline::Fingerprints(_)));
301        assert!(baseline.knows(&one) && baseline.knows(&other));
302        assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
303        // Anything else is refused, with a later version said to be one.
304        let later = parse(r#"{"version": 3, "findings": []}"#).unwrap_err();
305        assert!(later.to_string().contains("version 3"), "{later}");
306        for bad in [
307            "{}",
308            "3",
309            r#"{"version": 2}"#,
310            r#"{"version": 2, "findings": null}"#,
311            r#"{"version": 2, "findings": [1]}"#,
312            r#"["a", 1]"#,
313        ] {
314            assert!(parse(bad).is_err(), "{bad}");
315        }
316    }
317
318    #[test]
319    fn fingerprints_ignore_position_but_not_content() {
320        let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
321        assert_eq!(
322            base,
323            fingerprint(&gap(99, "a > b", &["`a >= b`"])),
324            "moved code"
325        );
326        assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
327        assert_ne!(
328            base,
329            fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
330            "a new survivor"
331        );
332        let input = Finding::InputGap {
333            at: Location {
334                file: "src/lib.rs".into(),
335                line: 10,
336                column: 5,
337                code: "a > b".into(),
338                ..Location::default()
339            },
340            survivors: vec!["`a >= b`".into()],
341            survivor_count: 1,
342            add_tests: vec![],
343            observed: None,
344            verified: true,
345        };
346        assert_ne!(base, fingerprint(&input), "another kind of finding");
347    }
348
349    #[test]
350    fn baseline_round_trip() {
351        let path =
352            std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
353        let mut findings = vec![
354            gap(1, "a > b", &["`a >= b`"]),
355            gap(2, "x();", &["delete `x();`"]),
356        ];
357        for (index, finding) in findings.iter_mut().enumerate() {
358            let Finding::AssertionGap { at, .. } = finding else {
359                unreachable!()
360            };
361            at.id = format!("id-{index}-é\n");
362        }
363        findings.reverse();
364        findings.push(findings[0].clone());
365        write(&path, &findings).unwrap();
366        assert_eq!(
367            std::fs::read_to_string(&path).unwrap(),
368            "{\n  \"findings\": [\n    \"id-0-é\\n\",\n    \"id-1-é\\n\"\n  ],\n  \"version\": 2\n}\n"
369        );
370        let loaded = load(&path).unwrap();
371        let ids: BTreeSet<String> = ["id-0-é\n", "id-1-é\n"].map(str::to_string).into();
372        assert_eq!(loaded, Baseline::Ids(ids));
373        assert!(findings.iter().all(|f| loaded.knows(f)));
374        std::fs::write(&path, "not json").unwrap();
375        assert!(load(&path).is_err());
376        std::fs::remove_file(&path).unwrap();
377        assert!(load(&path).is_err());
378    }
379
380    #[test]
381    fn ignore_comments() {
382        let source = "\
383fn f() {
384    // tmt:ignore equivalent: both branches return the same
385    if a >= b { a } else { b }
386    let x = 1; // tmt:ignore
387    let y = 2;
388    let z = 3;
389    let w = 4; // tmt:ignore: with a colon
390    // tmt:ignored is another word
391    // not tmt:ignore here? it is: tmt:ignore must start the comment
392    let url = \"http://tmt:ignore reason\";
393    let ok = \"https://example.com\"; // tmt:ignore after url
394    let raw = r#\"// tmt:ignore inside raw string\"#;
395    /* // tmt:ignore inside block comment */
396    let ch = '\"'; // tmt:ignore after quote char
397    let quotes = ['\\'', '\"'];
398    let fake = \"// tmt:ignore fake after escaped quote\";
399    let real = 5; // tmt:ignore after escaped quote
400}
401";
402        let ignored = ignored_lines(source);
403        assert_eq!(
404            ignored.keys().copied().collect::<Vec<_>>(),
405            [2, 3, 4, 7, 11, 14, 17]
406        );
407        assert_eq!(ignored[&7], "with a colon");
408        assert_eq!(ignored[&2], "equivalent: both branches return the same");
409        assert_eq!(ignored[&3], "equivalent: both branches return the same");
410        assert_eq!(ignored[&4], "");
411        assert_eq!(ignored[&11], "after url");
412        assert_eq!(ignored[&14], "after quote char");
413        assert_eq!(ignored[&17], "after escaped quote");
414        assert!(ignored_lines("").is_empty());
415    }
416}