targeted-mutation 0.16.0

Targeted mutation testing for Rust: find the wrong implementations your tests let through
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! Findings the user has already looked at: `// tmt:ignore` comments and baseline files.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use anyhow::{Context, Result};

use crate::report::Finding;

/// What identifies a finding across runs: its kind, file, code and surviving mutants.
/// Line numbers are left out, so code that merely moves keeps its fingerprint.
pub fn fingerprint(finding: &Finding) -> String {
    // A mutant built on its own was an assertion gap when fingerprints were written.
    let kind = match finding {
        Finding::InputGap { .. } => "input_gap",
        Finding::AssertionGap { .. } | Finding::Survivor { .. } => "assertion_gap",
    };
    let (at, survivors) = (finding.at(), finding.survivors());
    format!(
        "{kind}\t{}\t{}\t{}",
        at.file,
        at.code,
        survivors.join(" | ")
    )
}

/// The findings a baseline file lists.
#[derive(Debug, PartialEq)]
pub enum Baseline {
    /// As written before findings had names of their own: by [`fingerprint`].
    Fingerprints(BTreeSet<String>),
    /// By the name of the finding (`report::finding_id`).
    Ids(BTreeSet<String>),
}

impl Baseline {
    pub fn knows(&self, finding: &Finding) -> bool {
        let at = finding.at();
        match self {
            Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
            Baseline::Ids(ids) => !at.id.is_empty() && ids.contains(&at.id),
        }
    }
}

/// The version of the file [`write`] writes.
const VERSION: u64 = 3;
/// Earlier v2 format (list of finding ID strings).
const LEGACY_V2: u64 = 2;
/// Upper bound on reading an existing baseline file before rewriting it (16 MiB).
const MAX_BASELINE_BYTES: u64 = 16 * 1024 * 1024;

/// One structured entry in a v3 baseline file.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BaselineEntry {
    pub id: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub kind: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub file: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub item: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub code: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub survivors: Vec<String>,
    #[serde(default)]
    pub reason: String,
}

#[derive(serde::Deserialize)]
#[serde(untagged)]
enum RawBaselineEntry {
    Id(String),
    Detailed(BaselineEntry),
}

fn read_regular_baseline(path: &Path) -> Result<String> {
    use std::io::Read as _;

    let metadata = std::fs::symlink_metadata(path)
        .with_context(|| format!("inspecting {}", path.display()))?;
    if !metadata.is_file() {
        anyhow::bail!("{} is not a regular file", path.display());
    }
    let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
    let mut text = String::new();
    file.take(MAX_BASELINE_BYTES + 1)
        .read_to_string(&mut text)
        .with_context(|| format!("reading {}", path.display()))?;
    let text_len = text.len() as u64;
    if text_len > MAX_BASELINE_BYTES {
        anyhow::bail!(
            "{} exceeds maximum baseline size of {MAX_BASELINE_BYTES} bytes",
            path.display()
        );
    }
    Ok(text)
}

/// Reads a baseline: the object [`write`] writes, or the list of fingerprints earlier
/// versions wrote.
pub fn load(path: &Path) -> Result<Baseline> {
    let text = read_regular_baseline(path)?;
    parse(&text).with_context(|| format!("{} is not a tmt baseline", path.display()))
}

fn parse(text: &str) -> Result<Baseline> {
    parse_with_reasons(text).map(|(baseline, _)| baseline)
}

fn parse_with_reasons(text: &str) -> Result<(Baseline, BTreeMap<String, String>)> {
    let mut value: serde_json::Value = serde_json::from_str(text)?;
    if value.is_array() {
        return Ok((
            Baseline::Fingerprints(serde_json::from_value(value)?),
            BTreeMap::new(),
        ));
    }
    match value["version"].as_u64() {
        Some(LEGACY_V2) => {
            let ids: BTreeSet<String> = serde_json::from_value(value["findings"].take())?;
            Ok((Baseline::Ids(ids), BTreeMap::new()))
        }
        Some(VERSION) => {
            let entries: Vec<RawBaselineEntry> = serde_json::from_value(value["findings"].take())?;
            let mut ids = BTreeSet::new();
            let mut reasons = BTreeMap::new();
            for entry in entries {
                match entry {
                    RawBaselineEntry::Id(id) => {
                        ids.insert(id);
                    }
                    RawBaselineEntry::Detailed(entry) => {
                        if !entry.reason.is_empty() {
                            reasons.insert(entry.id.clone(), entry.reason);
                        }
                        ids.insert(entry.id);
                    }
                }
            }
            Ok((Baseline::Ids(ids), reasons))
        }
        Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
        None => anyhow::bail!("neither a list nor an object with a version"),
    }
}

fn existing_reasons(path: &Path) -> Result<BTreeMap<String, String>> {
    match std::fs::symlink_metadata(path) {
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
        Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
        Ok(meta) if !meta.is_file() => {
            anyhow::bail!(
                "refusing to overwrite non-regular baseline path {}",
                path.display()
            );
        }
        Ok(_) => {}
    }
    let text = read_regular_baseline(path)?;
    let (_, reasons) = parse_with_reasons(&text).with_context(|| {
        format!(
            "cannot preserve reasons from existing baseline {} (fix or remove it before rewriting)",
            path.display()
        )
    })?;
    Ok(reasons)
}

pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
    let reasons = existing_reasons(path)?;
    let mut text = render_with_reasons(findings, &reasons);
    text.push('\n');
    let text_len = text.len() as u64;
    if text_len > MAX_BASELINE_BYTES {
        anyhow::bail!(
            "baseline {} would exceed maximum size of {MAX_BASELINE_BYTES} bytes",
            path.display()
        );
    }
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("baseline");
    let tmp = parent.join(format!(
        ".{file_name}.tmt-tmp-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos())
    ));
    if let Err(err) = std::fs::write(&tmp, &text) {
        let _ = std::fs::remove_file(&tmp);
        return Err(err).with_context(|| format!("writing {}", path.display()));
    }
    if let Err(err) = std::fs::rename(&tmp, path) {
        let _ = std::fs::remove_file(&tmp);
        return Err(err).with_context(|| format!("replacing {}", path.display()));
    }
    Ok(())
}

#[cfg(test)]
fn render(findings: &[Finding]) -> String {
    render_with_reasons(findings, &BTreeMap::new())
}

fn render_with_reasons(
    findings: &[Finding],
    existing_reasons: &BTreeMap<String, String>,
) -> String {
    #[derive(serde::Serialize)]
    struct BaselineFile {
        findings: Vec<BaselineEntry>,
        version: u64,
    }

    let mut by_id: BTreeMap<String, BaselineEntry> = BTreeMap::new();
    for finding in findings {
        let at = finding.at();
        by_id.entry(at.id.clone()).or_insert_with(|| BaselineEntry {
            id: at.id.clone(),
            kind: finding.kind().to_string(),
            file: at.file.clone(),
            item: at.item.clone(),
            code: at.code.clone(),
            survivors: finding.survivors().to_vec(),
            reason: existing_reasons.get(&at.id).cloned().unwrap_or_default(),
        });
    }
    serde_json::to_string_pretty(&BaselineFile {
        findings: by_id.into_values().collect(),
        version: VERSION,
    })
    .expect("baseline entries serialise")
}

/// Which finding kinds a `// tmt:ignore` comment suppresses on a line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IgnoreScope {
    /// Suppresses all finding kinds on the line (`// tmt:ignore ...`).
    All,
    /// Suppresses only the named finding kinds (`// tmt:ignore[input_gap, ...] ...`).
    Kinds(BTreeSet<String>),
}

/// Parsed `// tmt:ignore` directive(s) effective on a single source line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LineIgnore {
    pub scope: IgnoreScope,
    pub reason: String,
}

impl LineIgnore {
    pub fn matches_kind(&self, kind: &str) -> bool {
        match &self.scope {
            IgnoreScope::All => true,
            IgnoreScope::Kinds(kinds) => kinds.contains(kind),
        }
    }

    fn merge(&mut self, other: LineIgnore) {
        match (&mut self.scope, other.scope) {
            (IgnoreScope::All, IgnoreScope::All) => {
                // Later (inline) unscoped comment overrides standalone line above.
                self.reason = other.reason;
            }
            (IgnoreScope::All, IgnoreScope::Kinds(_)) => {}
            (slot, IgnoreScope::All) => {
                *slot = IgnoreScope::All;
                // An inline unscoped directive supersedes a kind-scoped reason from above.
                self.reason = other.reason;
            }
            (IgnoreScope::Kinds(existing), IgnoreScope::Kinds(extra)) => {
                existing.extend(extra);
                if !other.reason.is_empty() {
                    self.reason = other.reason;
                }
            }
        }
    }
}

fn parse_ignore_comment(comment: &str) -> Option<LineIgnore> {
    let rest = comment.trim_start().strip_prefix("tmt:ignore")?;
    if let Some(bracketed) = rest.strip_prefix('[') {
        let close = bracketed.find(']')?;
        let inside = &bracketed[..close];
        let after = &bracketed[close + 1..];
        if !(after.is_empty() || after.starts_with(|c: char| c.is_whitespace() || c == ':')) {
            return None;
        }
        let mut kinds = BTreeSet::new();
        for token in inside.split(',') {
            let normalized = token.trim().replace('-', "_");
            if matches!(
                normalized.as_str(),
                "input_gap" | "assertion_gap" | "survivor"
            ) {
                kinds.insert(normalized);
            }
        }
        let reason = after.trim_start_matches(':').trim().to_string();
        return Some(LineIgnore {
            scope: IgnoreScope::Kinds(kinds),
            reason,
        });
    }
    if rest.is_empty() || rest.starts_with(|c: char| c.is_whitespace() || c == ':') {
        let reason = rest.trim_start_matches(':').trim().to_string();
        return Some(LineIgnore {
            scope: IgnoreScope::All,
            reason,
        });
    }
    None
}

/// Lines covered by an unscoped `// tmt:ignore` comment, with the reason given after it. A
/// standalone comment line covers its own line and the next one (so it can sit above the
/// code); an end-of-line comment covers only its own line. For kind-scoped directives
/// (`// tmt:ignore[input_gap]`), use [`line_ignores`].
pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
    line_ignores(source)
        .into_iter()
        .filter(|(_, ignore)| matches!(ignore.scope, IgnoreScope::All))
        .map(|(line, ignore)| (line, ignore.reason))
        .collect()
}

/// Lines covered by `// tmt:ignore` or `// tmt:ignore[kind, ...]` comments.
/// A standalone comment line covers its own line and the next one; an end-of-line
/// comment covers only its own line. Multiple directives targeting the same line are merged.
pub fn line_ignores(source: &str) -> BTreeMap<usize, LineIgnore> {
    let mut ignored: BTreeMap<usize, LineIgnore> = BTreeMap::new();
    let bytes = source.as_bytes();
    let mut i = 0;
    let mut line = 1usize;
    let mut line_start = 0usize;
    let mut block_depth = 0usize;
    while i < bytes.len() {
        if block_depth > 0 {
            if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
                block_depth += 1;
                i += 2;
            } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
                block_depth -= 1;
                i += 2;
            } else {
                if bytes[i] == b'\n' {
                    line += 1;
                    line_start = i + 1;
                }
                i += 1;
            }
            continue;
        }
        match bytes[i] {
            b'\n' => {
                line += 1;
                line_start = i + 1;
                i += 1;
            }
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                let comment_start = i + 2;
                let mut end = comment_start;
                while end < bytes.len() && bytes[end] != b'\n' {
                    end += 1;
                }
                let comment = &source[comment_start..end];
                if let Some(directive) = parse_ignore_comment(comment) {
                    let standalone = source[line_start..i].trim().is_empty();
                    ignored
                        .entry(line)
                        .and_modify(|existing| existing.merge(directive.clone()))
                        .or_insert_with(|| directive.clone());
                    if standalone {
                        ignored
                            .entry(line + 1)
                            .and_modify(|existing| existing.merge(directive.clone()))
                            .or_insert(directive);
                    }
                }
                i = end;
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                block_depth = 1;
                i += 2;
            }
            // Raw strings: `r"..."`, `r#"..."#`, `br#"..."#`, `cr#"..."#`.
            b'r' if raw_string_hashes(bytes, i).is_some() => {
                let hashes = raw_string_hashes(bytes, i).unwrap();
                i += 1 + hashes + 1;
                while i < bytes.len() {
                    if bytes[i] == b'\n' {
                        line += 1;
                        line_start = i + 1;
                    }
                    if bytes[i] == b'"'
                        && bytes
                            .get(i + 1..i + 1 + hashes)
                            .is_some_and(|s| s.iter().all(|b| *b == b'#'))
                    {
                        i += 1 + hashes;
                        break;
                    }
                    i += 1;
                }
            }
            b'"' => {
                i += 1;
                while i < bytes.len() {
                    if bytes[i] == b'\\' {
                        if bytes.get(i + 1) == Some(&b'\n') {
                            line += 1;
                            line_start = i + 2;
                        }
                        i = (i + 2).min(bytes.len());
                        continue;
                    }
                    if bytes[i] == b'\n' {
                        line += 1;
                        line_start = i + 1;
                    }
                    if bytes[i] == b'"' {
                        i += 1;
                        break;
                    }
                    i += 1;
                }
            }
            // Character literals (`'"'`, `'\\'`, `'\''`, `'a'`); lifetimes (`'a`) have no closing `'`.
            b'\'' => {
                if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 2).is_some_and(|&b| b != b'\n')
                {
                    // Escape char literal such as `'\''`, `'\"'`, `'\\'`, `'\x7f'`, `'\u{...}'`.
                    // Start after the escaped byte so `'\''` does not close on the escaped quote.
                    let mut j = i + 3;
                    while j < bytes.len() && bytes[j] != b'\n' && bytes[j] != b'\'' {
                        j += 1;
                    }
                    if bytes.get(j) == Some(&b'\'') {
                        i = j + 1;
                    } else {
                        i += 1;
                    }
                } else if let Some(ch) = source[i + 1..].chars().next()
                    && bytes.get(i + 1 + ch.len_utf8()) == Some(&b'\'')
                {
                    i += 1 + ch.len_utf8() + 1;
                } else {
                    i += 1;
                }
            }
            _ => i += 1,
        }
    }
    ignored
}

fn raw_string_hashes(bytes: &[u8], r_pos: usize) -> Option<usize> {
    // Reject identifier suffixes like `str"..."` (except `br"` / `cr"`).
    if r_pos > 0 {
        let prev = bytes[r_pos - 1];
        let is_prefix =
            (prev == b'b' || prev == b'c') && (r_pos == 1 || !is_ident_byte(bytes[r_pos - 2]));
        if is_ident_byte(prev) && !is_prefix {
            return None;
        }
    }
    let mut hashes = 0;
    while bytes.get(r_pos + 1 + hashes) == Some(&b'#') {
        hashes += 1;
    }
    (bytes.get(r_pos + 1 + hashes) == Some(&b'"')).then_some(hashes)
}

fn is_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::Location;

    fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
        Finding::AssertionGap {
            at: Location {
                file: "src/lib.rs".into(),
                line,
                column: 5,
                code: code.into(),
                ..Location::default()
            },
            survivors: survivors.iter().map(|s| s.to_string()).collect(),
            tests: vec!["tests::t".into()],
            effects: vec![],
            effects_of: None,
            witness: None,
        }
    }

    #[test]
    fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
        let named = |id: &str, survivors: &[&str]| {
            let mut finding = gap(10, "a > b", survivors);
            let Finding::AssertionGap { at, .. } = &mut finding else {
                unreachable!()
            };
            at.id = id.to_string();
            finding
        };
        let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
        let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
        let written = render(std::slice::from_ref(&one));
        let baseline = parse(&written).unwrap();
        assert!(baseline.knows(&one));
        // The same code in another function is another finding.
        assert!(!baseline.knows(&other));
        // Other words for the mutants, or one more of them, and it is still the one.
        assert!(baseline.knows(&named(
            "assertion_gap|src/lib.rs|f|a > b|0",
            &["`a >= b`", "the negation"]
        )));
        // A finding without a name is not known by having none.
        assert!(
            !parse(&render(&[gap(1, "x", &[])]))
                .unwrap()
                .knows(&gap(2, "y", &[]))
        );
        // A file of an earlier version lists fingerprints, and still works as it did.
        let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
        let baseline = parse(&old).unwrap();
        assert!(matches!(baseline, Baseline::Fingerprints(_)));
        assert!(baseline.knows(&one) && baseline.knows(&other));
        assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
        // Anything else is refused, with a later version said to be one.
        let later = parse(r#"{"version": 4, "findings": []}"#).unwrap_err();
        assert!(later.to_string().contains("version 4"), "{later}");
        for bad in [
            "{}",
            "3",
            r#"{"version": 2}"#,
            r#"{"version": 2, "findings": null}"#,
            r#"{"version": 2, "findings": [1]}"#,
            r#"{"version": 3, "findings": [1]}"#,
            r#"["a", 1]"#,
        ] {
            assert!(parse(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn fingerprints_ignore_position_but_not_content() {
        let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
        assert_eq!(
            base,
            fingerprint(&gap(99, "a > b", &["`a >= b`"])),
            "moved code"
        );
        assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
        assert_ne!(
            base,
            fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
            "a new survivor"
        );
        let input = Finding::InputGap {
            at: Location {
                file: "src/lib.rs".into(),
                line: 10,
                column: 5,
                code: "a > b".into(),
                ..Location::default()
            },
            survivors: vec!["`a >= b`".into()],
            survivor_count: 1,
            add_tests: vec![],
            observed: None,
            verified: true,
        };
        assert_ne!(base, fingerprint(&input), "another kind of finding");
    }

    #[test]
    fn baseline_round_trip() {
        let path =
            std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let mut findings = vec![
            gap(1, "a > b", &["`a >= b`"]),
            gap(2, "x();", &["delete `x();`"]),
        ];
        for (index, finding) in findings.iter_mut().enumerate() {
            let Finding::AssertionGap { at, .. } = finding else {
                unreachable!()
            };
            at.id = format!("id-{index}-é\n");
            at.item = format!("fn_{index}");
        }
        findings.reverse();
        findings.push(findings[0].clone());
        write(&path, &findings).unwrap();
        let written: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(written["version"], 3);
        let entries = written["findings"].as_array().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0]["id"], "id-0-é\n");
        assert_eq!(entries[0]["kind"], "assertion_gap");
        assert_eq!(entries[0]["file"], "src/lib.rs");
        assert_eq!(entries[0]["item"], "fn_0");
        assert_eq!(entries[0]["code"], "a > b");
        assert_eq!(entries[0]["survivors"], serde_json::json!(["`a >= b`"]));
        assert_eq!(entries[0]["reason"], "");
        assert_eq!(entries[1]["id"], "id-1-é\n");

        // Adding a reason in the file is preserved on subsequent `write` calls.
        let mut edited = written.clone();
        edited["findings"][0]["reason"] = serde_json::json!("equivalent in domain");
        std::fs::write(&path, serde_json::to_string_pretty(&edited).unwrap()).unwrap();
        write(&path, &findings).unwrap();
        let rewritten: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(rewritten["findings"][0]["reason"], "equivalent in domain");
        assert_eq!(rewritten["findings"][1]["reason"], "");

        let loaded = load(&path).unwrap();
        let ids: BTreeSet<String> = ["id-0-é\n", "id-1-é\n"].map(str::to_string).into();
        assert_eq!(loaded, Baseline::Ids(ids));
        assert!(findings.iter().all(|f| loaded.knows(f)));

        // Malformed existing baseline is never silently overwritten.
        let broken = r#"{"version": 3, "findings": [{"id": "id-0", "reasons": "typo"}]}"#;
        std::fs::write(&path, broken).unwrap();
        assert!(write(&path, &findings).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), broken);

        std::fs::write(&path, "not json").unwrap();
        assert!(load(&path).is_err());
        assert!(write(&path, &findings).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "not json");
        std::fs::remove_file(&path).unwrap();
        assert!(load(&path).is_err());
    }

    #[test]
    fn baseline_accepts_legacy_strings_and_structured_entries_mixed() {
        let v2 = r#"{"version": 2, "findings": ["v2-id"]}"#;
        assert_eq!(
            parse(v2).unwrap(),
            Baseline::Ids(["v2-id"].map(str::to_string).into())
        );

        let mixed = r#"{
  "version": 3,
  "findings": [
    "legacy-id",
    {
      "id": "structured-id",
      "kind": "input_gap",
      "file": "src/lib.rs",
      "code": "x > 0",
      "survivors": ["`x >= 0`"],
      "reason": "zero is unreachable"
    }
  ]
}"#;
        let (baseline, reasons) = parse_with_reasons(mixed).unwrap();
        assert_eq!(
            baseline,
            Baseline::Ids(["legacy-id", "structured-id"].map(str::to_string).into())
        );
        assert_eq!(
            reasons.get("structured-id").map(String::as_str),
            Some("zero is unreachable")
        );
        assert!(!reasons.contains_key("legacy-id"));

        // Unknown fields in structured entries are rejected to catch typos like `reasons`.
        let typo = r#"{"version": 3, "findings": [{"id": "x", "reasons": "typo"}]}"#;
        assert!(parse(typo).is_err());
        let missing_id = r#"{"version": 3, "findings": [{"reason": "no id"}]}"#;
        assert!(parse(missing_id).is_err());
    }

    #[test]
    fn selective_ignore_comments() {
        let source = "\
fn f() {
    // tmt:ignore[input_gap] boundary is equivalent
    if a >= b { a } else { b }
    let x = 1; // tmt:ignore[assertion-gap, survivor]: intentional
    // tmt:ignore[input_gap] above
    let y = 2; // tmt:ignore[assertion_gap] inline
    // tmt:ignore[unknown_kind] should not suppress anything
    let z = 3;
    let empty = 4; // tmt:ignore[] empty list
    let unclosed = 5; // tmt:ignore[input_gap missing bracket
    let attached = 6; // tmt:ignore[input_gap]extra
}
";
        let ignores = line_ignores(source);
        // Line 2 & 3: input_gap only
        assert!(ignores[&3].matches_kind("input_gap"));
        assert!(!ignores[&3].matches_kind("assertion_gap"));
        assert!(!ignores[&3].matches_kind("survivor"));
        assert_eq!(ignores[&3].reason, "boundary is equivalent");

        // Line 4: hyphenated assertion-gap + survivor
        assert!(!ignores[&4].matches_kind("input_gap"));
        assert!(ignores[&4].matches_kind("assertion_gap"));
        assert!(ignores[&4].matches_kind("survivor"));
        assert_eq!(ignores[&4].reason, "intentional");

        // Line 6: merged from standalone line 5 + inline line 6
        assert!(ignores[&6].matches_kind("input_gap"));
        assert!(ignores[&6].matches_kind("assertion_gap"));
        assert!(!ignores[&6].matches_kind("survivor"));

        // Line 8: unknown kind matches nothing (safe side)
        assert!(!ignores[&8].matches_kind("input_gap"));
        assert!(!ignores[&8].matches_kind("assertion_gap"));
        assert!(!ignores[&8].matches_kind("survivor"));

        // Line 9: empty brackets match nothing (safe side)
        assert!(!ignores[&9].matches_kind("input_gap"));

        // Line 10 & 11: malformed syntax is not recognized
        assert!(!ignores.contains_key(&10));
        assert!(!ignores.contains_key(&11));

        // Legacy `ignored_lines` excludes kind-scoped directives.
        assert!(ignored_lines(source).is_empty());

        // Standalone + inline overlap: inline unscoped reason takes precedence.
        let overlap = "\
fn g() {
    // tmt:ignore above
    let a = 1; // tmt:ignore inline
    // tmt:ignore[input_gap] scoped above
    let b = 2; // tmt:ignore unscoped inline
}
";
        let legacy = ignored_lines(overlap);
        assert_eq!(legacy.get(&3).map(String::as_str), Some("inline"));
        assert_eq!(legacy.get(&5).map(String::as_str), Some("unscoped inline"));
    }

    #[test]
    fn ignore_comments() {
        let source = "\
fn f() {
    // tmt:ignore equivalent: both branches return the same
    if a >= b { a } else { b }
    let x = 1; // tmt:ignore
    let y = 2;
    let z = 3;
    let w = 4; // tmt:ignore: with a colon
    // tmt:ignored is another word
    // not tmt:ignore here? it is: tmt:ignore must start the comment
    let url = \"http://tmt:ignore reason\";
    let ok = \"https://example.com\"; // tmt:ignore after url
    let raw = r#\"// tmt:ignore inside raw string\"#;
    /* // tmt:ignore inside block comment */
    let ch = '\"'; // tmt:ignore after quote char
    let quotes = ['\\'', '\"'];
    let fake = \"// tmt:ignore fake after escaped quote\";
    let real = 5; // tmt:ignore after escaped quote
}
";
        let ignored = ignored_lines(source);
        assert_eq!(
            ignored.keys().copied().collect::<Vec<_>>(),
            [2, 3, 4, 7, 11, 14, 17]
        );
        assert_eq!(ignored[&7], "with a colon");
        assert_eq!(ignored[&2], "equivalent: both branches return the same");
        assert_eq!(ignored[&3], "equivalent: both branches return the same");
        assert_eq!(ignored[&4], "");
        assert_eq!(ignored[&11], "after url");
        assert_eq!(ignored[&14], "after quote char");
        assert_eq!(ignored[&17], "after escaped quote");
        assert!(ignored_lines("").is_empty());
    }
}