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 {
34        /// Set when the baseline file was written for a single package.
35        file_package: Option<String>,
36        /// Entries that record their owning package (`package -> finding ids`).
37        scoped: BTreeMap<String, BTreeSet<String>>,
38        /// Legacy entries (v2 or v3 without `package`) that match any package.
39        unscoped: BTreeSet<String>,
40    },
41}
42
43impl Baseline {
44    /// Verifies that a single-package baseline file is not being applied to a different package.
45    pub fn validate_for_package(&self, package: &str, path: &Path) -> Result<()> {
46        if let Baseline::Ids {
47            file_package: Some(expected),
48            ..
49        } = self
50            && !package.is_empty()
51            && expected != package
52        {
53            anyhow::bail!(
54                "baseline {} is for package `{expected}`, not `{package}`",
55                path.display()
56            );
57        }
58        Ok(())
59    }
60
61    /// Whether this baseline suppresses `finding` when analysing `package`.
62    pub fn knows_in_package(&self, package: &str, finding: &Finding) -> bool {
63        let at = finding.at();
64        match self {
65            Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
66            Baseline::Ids {
67                scoped, unscoped, ..
68            } => {
69                !at.id.is_empty()
70                    && (unscoped.contains(&at.id)
71                        || (!package.is_empty()
72                            && scoped.get(package).is_some_and(|ids| ids.contains(&at.id))))
73            }
74        }
75    }
76
77    pub fn knows(&self, finding: &Finding) -> bool {
78        let at = finding.at();
79        match self {
80            Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
81            Baseline::Ids {
82                scoped, unscoped, ..
83            } => {
84                !at.id.is_empty()
85                    && (unscoped.contains(&at.id)
86                        || scoped.values().any(|ids| ids.contains(&at.id)))
87            }
88        }
89    }
90}
91
92/// The version of the file [`write`] writes.
93const VERSION: u64 = 3;
94/// Earlier v2 format (list of finding ID strings).
95const LEGACY_V2: u64 = 2;
96/// Upper bound on reading an existing baseline file before rewriting it (16 MiB).
97const MAX_BASELINE_BYTES: u64 = 16 * 1024 * 1024;
98
99/// One structured entry in a v3 baseline file.
100#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct BaselineEntry {
103    pub id: String,
104    #[serde(default, skip_serializing_if = "String::is_empty")]
105    pub package: String,
106    #[serde(default, skip_serializing_if = "String::is_empty")]
107    pub workspace_file: String,
108    #[serde(default, skip_serializing_if = "String::is_empty")]
109    pub kind: String,
110    #[serde(default, skip_serializing_if = "String::is_empty")]
111    pub file: String,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub line: Option<usize>,
114    #[serde(default, skip_serializing_if = "String::is_empty")]
115    pub item: String,
116    #[serde(default, skip_serializing_if = "String::is_empty")]
117    pub code: String,
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub survivors: Vec<String>,
120    #[serde(default)]
121    pub reason: String,
122}
123
124/// Scope filter describing which existing entries were evaluated by a partial run.
125pub struct PartialScope<'a> {
126    /// Workspace-relative line scope (`--lines` / `--since`), if any.
127    pub scope: Option<&'a crate::scope::Scope>,
128    /// Package-relative `--exclude-file` glob patterns.
129    pub exclude_files: &'a [String],
130    /// True for sharded runs or empty scopes where no existing entries should be pruned.
131    pub preserve_all_existing: bool,
132}
133
134/// Summary of a baseline write/merge operation.
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
136pub struct WriteSummary {
137    pub written: usize,
138    pub preserved: usize,
139    pub removed: usize,
140}
141
142#[derive(serde::Deserialize)]
143#[serde(untagged)]
144enum RawBaselineEntry {
145    Id(String),
146    Detailed(Box<BaselineEntry>),
147}
148
149struct ParsedBaseline {
150    baseline: Baseline,
151    is_legacy_fingerprints: bool,
152    entries: Vec<BaselineEntry>,
153    reasons: BTreeMap<(String, String), String>,
154    legacy_reasons: BTreeMap<String, String>,
155}
156
157fn read_regular_baseline(path: &Path) -> Result<String> {
158    use std::io::Read as _;
159
160    let metadata = std::fs::symlink_metadata(path)
161        .with_context(|| format!("inspecting {}", path.display()))?;
162    if !metadata.is_file() {
163        anyhow::bail!("{} is not a regular file", path.display());
164    }
165    let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
166    let mut text = String::new();
167    file.take(MAX_BASELINE_BYTES + 1)
168        .read_to_string(&mut text)
169        .with_context(|| format!("reading {}", path.display()))?;
170    let text_len = text.len() as u64;
171    if text_len > MAX_BASELINE_BYTES {
172        anyhow::bail!(
173            "{} exceeds maximum baseline size of {MAX_BASELINE_BYTES} bytes",
174            path.display()
175        );
176    }
177    Ok(text)
178}
179
180/// Reads a baseline: the object [`write`] writes, or the list of fingerprints earlier
181/// versions wrote.
182pub fn load(path: &Path) -> Result<Baseline> {
183    let text = read_regular_baseline(path)?;
184    parse(&text).with_context(|| format!("{} is not a tmt baseline", path.display()))
185}
186
187fn parse(text: &str) -> Result<Baseline> {
188    parse_full(text).map(|parsed| parsed.baseline)
189}
190
191fn parse_full(text: &str) -> Result<ParsedBaseline> {
192    let mut value: serde_json::Value = serde_json::from_str(text)?;
193    if value.is_array() {
194        return Ok(ParsedBaseline {
195            baseline: Baseline::Fingerprints(serde_json::from_value(value)?),
196            is_legacy_fingerprints: true,
197            entries: vec![],
198            reasons: BTreeMap::new(),
199            legacy_reasons: BTreeMap::new(),
200        });
201    }
202    let file_package = match value.get("package") {
203        None | Some(serde_json::Value::Null) => None,
204        Some(serde_json::Value::String(pkg)) if !pkg.is_empty() => Some(pkg.clone()),
205        Some(serde_json::Value::String(_)) => None,
206        Some(_) => anyhow::bail!("baseline `package` field must be a string"),
207    };
208    match value["version"].as_u64() {
209        Some(LEGACY_V2) => {
210            let ids: BTreeSet<String> = serde_json::from_value(value["findings"].take())?;
211            let entries = ids
212                .iter()
213                .map(|id| BaselineEntry {
214                    id: id.clone(),
215                    package: file_package.clone().unwrap_or_default(),
216                    workspace_file: String::new(),
217                    kind: String::new(),
218                    file: String::new(),
219                    line: None,
220                    item: String::new(),
221                    code: String::new(),
222                    survivors: vec![],
223                    reason: String::new(),
224                })
225                .collect();
226            let mut scoped = BTreeMap::new();
227            let mut unscoped = BTreeSet::new();
228            if let Some(pkg) = &file_package {
229                scoped.insert(pkg.clone(), ids);
230            } else {
231                unscoped = ids;
232            }
233            Ok(ParsedBaseline {
234                baseline: Baseline::Ids {
235                    file_package,
236                    scoped,
237                    unscoped,
238                },
239                is_legacy_fingerprints: false,
240                entries,
241                reasons: BTreeMap::new(),
242                legacy_reasons: BTreeMap::new(),
243            })
244        }
245        Some(VERSION) => {
246            let raw_entries: Vec<RawBaselineEntry> =
247                serde_json::from_value(value["findings"].take())?;
248            let mut scoped: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
249            let mut unscoped = BTreeSet::new();
250            let mut entries = Vec::with_capacity(raw_entries.len());
251            let mut reasons = BTreeMap::new();
252            let mut legacy_reasons = BTreeMap::new();
253            for raw in raw_entries {
254                match raw {
255                    RawBaselineEntry::Id(id) => {
256                        if let Some(pkg) = &file_package {
257                            scoped.entry(pkg.clone()).or_default().insert(id.clone());
258                        } else {
259                            unscoped.insert(id.clone());
260                        }
261                        entries.push(BaselineEntry {
262                            id,
263                            package: file_package.clone().unwrap_or_default(),
264                            workspace_file: String::new(),
265                            kind: String::new(),
266                            file: String::new(),
267                            line: None,
268                            item: String::new(),
269                            code: String::new(),
270                            survivors: vec![],
271                            reason: String::new(),
272                        });
273                    }
274                    RawBaselineEntry::Detailed(entry) => {
275                        let mut entry = *entry;
276                        if entry.package.is_empty()
277                            && let Some(pkg) = &file_package
278                        {
279                            entry.package = pkg.clone();
280                        }
281                        if !entry.reason.is_empty() {
282                            if !entry.package.is_empty() {
283                                reasons.insert(
284                                    (entry.package.clone(), entry.id.clone()),
285                                    entry.reason.clone(),
286                                );
287                            } else {
288                                legacy_reasons
289                                    .entry(entry.id.clone())
290                                    .or_insert_with(|| entry.reason.clone());
291                            }
292                        }
293                        if entry.package.is_empty() {
294                            unscoped.insert(entry.id.clone());
295                        } else {
296                            scoped
297                                .entry(entry.package.clone())
298                                .or_default()
299                                .insert(entry.id.clone());
300                        }
301                        entries.push(entry);
302                    }
303                }
304            }
305            Ok(ParsedBaseline {
306                baseline: Baseline::Ids {
307                    file_package,
308                    scoped,
309                    unscoped,
310                },
311                is_legacy_fingerprints: false,
312                entries,
313                reasons,
314                legacy_reasons,
315            })
316        }
317        Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
318        None => anyhow::bail!("neither a list nor an object with a version"),
319    }
320}
321
322fn read_existing(path: &Path) -> Result<Option<ParsedBaseline>> {
323    match std::fs::symlink_metadata(path) {
324        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
325        Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
326        Ok(meta) if !meta.is_file() => {
327            anyhow::bail!(
328                "refusing to overwrite non-regular baseline path {}",
329                path.display()
330            );
331        }
332        Ok(_) => {}
333    }
334    let text = read_regular_baseline(path)?;
335    let parsed = parse_full(&text).with_context(|| {
336        format!(
337            "cannot preserve reasons from existing baseline {} (fix or remove it before rewriting)",
338            path.display()
339        )
340    })?;
341    Ok(Some(parsed))
342}
343
344fn normalize_workspace_file(package_prefix: &str, file: &str) -> String {
345    let combined = if package_prefix.is_empty() {
346        Path::new(file).to_path_buf()
347    } else {
348        Path::new(package_prefix).join(file)
349    };
350    let mut parts: Vec<String> = Vec::new();
351    for component in combined.components() {
352        match component {
353            std::path::Component::Normal(name) => {
354                parts.push(name.to_string_lossy().into_owned());
355            }
356            std::path::Component::ParentDir => {
357                if parts.pop().is_none() {
358                    parts.push("..".to_string());
359                }
360            }
361            std::path::Component::CurDir => {}
362            std::path::Component::RootDir | std::path::Component::Prefix(_) => {}
363        }
364    }
365    parts.join("/")
366}
367
368/// OS-enforced advisory/exclusive file lock around baseline read-merge-write cycles.
369/// Automatically released by the OS even if the holder process is forcefully terminated.
370struct BaselineWriteLock {
371    _file: std::fs::File,
372}
373
374impl BaselineWriteLock {
375    fn acquire(path: &Path) -> Result<Self> {
376        let parent = path
377            .parent()
378            .filter(|p| !p.as_os_str().is_empty())
379            .unwrap_or_else(|| Path::new("."));
380        let file_name = path
381            .file_name()
382            .and_then(|n| n.to_str())
383            .unwrap_or("baseline");
384        let lock_path = parent.join(format!(".{file_name}.tmt-lock"));
385        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
386        loop {
387            match crate::work_lock::acquire(&lock_path) {
388                Ok(file) => return Ok(Self { _file: file }),
389                Err(err) if crate::work_lock::contended(&err) => {
390                    if std::time::Instant::now() >= deadline {
391                        anyhow::bail!(
392                            "timed out waiting for baseline write lock {}",
393                            lock_path.display()
394                        );
395                    }
396                    std::thread::sleep(std::time::Duration::from_millis(10));
397                }
398                Err(err) => {
399                    return Err(err).with_context(|| {
400                        format!("acquiring baseline lock {}", lock_path.display())
401                    });
402                }
403            }
404        }
405    }
406}
407
408fn entry_in_evaluated_scope(
409    entry: &BaselineEntry,
410    package: &str,
411    workspace_package_prefix: &str,
412    partial: Option<&PartialScope<'_>>,
413) -> bool {
414    // Entries belonging to another package are always outside this package's scope.
415    if !package.is_empty() && !entry.package.is_empty() && entry.package != package {
416        return false;
417    }
418    let Some(partial) = partial else {
419        // Full analysis of this package replaces all entries of this package.
420        return true;
421    };
422    if partial.preserve_all_existing {
423        return false;
424    }
425    // On partial updates, never prune entries whose owning package or file is unknown.
426    if (!package.is_empty() && entry.package.is_empty()) || entry.file.is_empty() {
427        return false;
428    }
429    if crate::scope::matches_any_glob(partial.exclude_files, &entry.file) {
430        return false;
431    }
432    if let Some(scope) = partial.scope {
433        let ws_file = if !entry.workspace_file.is_empty() {
434            entry.workspace_file.clone()
435        } else {
436            normalize_workspace_file(workspace_package_prefix, &entry.file)
437        };
438        // Only prune existing entries when the entire file was in scope; a narrow line
439        // range may miss an entry whose line number shifted after earlier edits.
440        if !scope.covers_whole_file(&ws_file) {
441            return false;
442        }
443    }
444    true
445}
446
447/// Writes or merges findings for one package into a v3 baseline file.
448///
449/// - `workspace_package_prefix` is the package directory relative to the Cargo workspace root
450///   (e.g. `"crates/pricing"` or `""`), used to normalize `workspace_file` consistently with `Scope`.
451/// - When `partial` is `Some`, existing entries outside the evaluated scope (and entries
452///   from other packages) are preserved along with their reasons. Legacy v1 fingerprint
453///   baselines cannot be partially merged and are rejected without modifying the file.
454/// - When `single_package` is `Some(pkg)` and all resulting entries belong to `pkg`,
455///   the top-level `package` metadata is set so misdirected single-package baselines are caught.
456pub fn write_scoped(
457    path: &Path,
458    package: &str,
459    workspace_package_prefix: &str,
460    findings: &[Finding],
461    partial: Option<&PartialScope<'_>>,
462    single_package: Option<&str>,
463) -> Result<WriteSummary> {
464    let _lock = BaselineWriteLock::acquire(path)?;
465    let existing = read_existing(path)?;
466    if let Some(parsed) = &existing
467        && parsed.is_legacy_fingerprints
468        && partial.is_some()
469    {
470        anyhow::bail!(
471            "cannot partially update legacy v1 fingerprint baseline {} (run a full package analysis without scope filters to migrate it to v3)",
472            path.display()
473        );
474    }
475    let (existing_entries, reasons, legacy_reasons) = match existing {
476        Some(parsed) => (parsed.entries, parsed.reasons, parsed.legacy_reasons),
477        None => (vec![], BTreeMap::new(), BTreeMap::new()),
478    };
479
480    let mut by_key: BTreeMap<(String, String), BaselineEntry> = BTreeMap::new();
481    let mut preserved = 0usize;
482    let mut in_scope_existing = 0usize;
483    for entry in existing_entries {
484        if entry_in_evaluated_scope(&entry, package, workspace_package_prefix, partial) {
485            in_scope_existing += 1;
486        } else {
487            by_key
488                .entry((entry.package.clone(), entry.id.clone()))
489                .or_insert(entry);
490            preserved += 1;
491        }
492    }
493
494    let mut new_keys = BTreeSet::new();
495    for finding in findings {
496        let at = finding.at();
497        let pkg = package.to_string();
498        let key = (pkg.clone(), at.id.clone());
499        new_keys.insert(key.clone());
500        let workspace_file = normalize_workspace_file(workspace_package_prefix, &at.file);
501        let reason = reasons
502            .get(&key)
503            .or_else(|| legacy_reasons.get(&at.id))
504            .cloned()
505            .unwrap_or_default();
506        by_key.insert(
507            key,
508            BaselineEntry {
509                id: at.id.clone(),
510                package: pkg,
511                workspace_file,
512                kind: finding.kind().to_string(),
513                file: at.file.clone(),
514                line: Some(at.line),
515                item: at.item.clone(),
516                code: at.code.clone(),
517                survivors: finding.survivors().to_vec(),
518                reason,
519            },
520        );
521    }
522
523    let removed = in_scope_existing.saturating_sub(new_keys.len());
524    let entries: Vec<BaselineEntry> = by_key.into_values().collect();
525    let written = entries.len();
526
527    let top_level_package = single_package.and_then(|pkg| {
528        if pkg.is_empty() {
529            return None;
530        }
531        let has_other_or_unscoped = entries
532            .iter()
533            .any(|e| e.package.is_empty() || e.package != pkg);
534        (!has_other_or_unscoped).then(|| pkg.to_string())
535    });
536
537    let mut text = render_entries(&entries, top_level_package.as_deref());
538    text.push('\n');
539    let text_len = text.len() as u64;
540    if text_len > MAX_BASELINE_BYTES {
541        anyhow::bail!(
542            "baseline {} would exceed maximum size of {MAX_BASELINE_BYTES} bytes",
543            path.display()
544        );
545    }
546    let parent = path
547        .parent()
548        .filter(|p| !p.as_os_str().is_empty())
549        .unwrap_or_else(|| Path::new("."));
550    let file_name = path
551        .file_name()
552        .and_then(|n| n.to_str())
553        .unwrap_or("baseline");
554    let tmp = parent.join(format!(
555        ".{file_name}.tmt-tmp-{}-{}",
556        std::process::id(),
557        std::time::SystemTime::now()
558            .duration_since(std::time::UNIX_EPOCH)
559            .map_or(0, |d| d.as_nanos())
560    ));
561    if let Err(err) = std::fs::write(&tmp, &text) {
562        let _ = std::fs::remove_file(&tmp);
563        return Err(err).with_context(|| format!("writing {}", path.display()));
564    }
565    if let Err(err) = std::fs::rename(&tmp, path) {
566        let _ = std::fs::remove_file(&tmp);
567        return Err(err).with_context(|| format!("replacing {}", path.display()));
568    }
569    Ok(WriteSummary {
570        written,
571        preserved,
572        removed,
573    })
574}
575
576pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
577    write_scoped(path, "", "", findings, None, None).map(|_| ())
578}
579
580#[cfg(test)]
581fn render(findings: &[Finding]) -> String {
582    let entries: Vec<BaselineEntry> = findings
583        .iter()
584        .map(|finding| {
585            let at = finding.at();
586            BaselineEntry {
587                id: at.id.clone(),
588                package: String::new(),
589                workspace_file: at.file.clone(),
590                kind: finding.kind().to_string(),
591                file: at.file.clone(),
592                line: Some(at.line),
593                item: at.item.clone(),
594                code: at.code.clone(),
595                survivors: finding.survivors().to_vec(),
596                reason: String::new(),
597            }
598        })
599        .collect();
600    render_entries(&entries, None)
601}
602
603fn render_entries(entries: &[BaselineEntry], package: Option<&str>) -> String {
604    #[derive(serde::Serialize)]
605    struct BaselineFile<'a> {
606        #[serde(skip_serializing_if = "Option::is_none")]
607        package: Option<&'a str>,
608        findings: &'a [BaselineEntry],
609        version: u64,
610    }
611
612    serde_json::to_string_pretty(&BaselineFile {
613        package,
614        findings: entries,
615        version: VERSION,
616    })
617    .expect("baseline entries serialise")
618}
619
620/// A single selector inside `// tmt:ignore[...]`: a finding kind, a 1-based column (`@COL`),
621/// an optional mutation suffix (`:MUTATION`, e.g. `:trunc`), or combinations (`kind@COL:MUTATION`).
622#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
623pub struct IgnoreFilter {
624    /// `None` matches any finding kind; `Some(kind)` matches only that kind.
625    pub kind: Option<String>,
626    /// `None` matches any column on the line; `Some(col)` matches only that 1-based column.
627    pub column: Option<usize>,
628    /// `None` matches any surviving mutation; `Some(m)` matches only findings whose survivors
629    /// all match `m` (e.g. `trunc` matches `.trunc()`, leaving `.ceil()` unhidden).
630    pub mutation: Option<String>,
631}
632
633fn survivor_matches_mutation(survivor: &str, mutation: &str) -> bool {
634    let trimmed = survivor.trim().trim_matches('`');
635    match mutation {
636        "floor" | "ceil" | "round" | "trunc" => trimmed.ends_with(&format!(".{mutation}()")),
637        other => survivor.contains(other),
638    }
639}
640
641impl IgnoreFilter {
642    pub fn matches(&self, kind: &str, column: usize) -> bool {
643        self.mutation.is_none()
644            && self.kind.as_deref().is_none_or(|k| k == kind)
645            && self.column.is_none_or(|c| c == column)
646    }
647
648    pub fn matches_finding(&self, kind: &str, column: usize, survivors: &[String]) -> bool {
649        if !self.kind.as_deref().is_none_or(|k| k == kind)
650            || !self.column.is_none_or(|c| c == column)
651        {
652            return false;
653        }
654        match &self.mutation {
655            None => true,
656            Some(pat) => {
657                !survivors.is_empty() && survivors.iter().all(|s| survivor_matches_mutation(s, pat))
658            }
659        }
660    }
661}
662
663/// Which findings a `// tmt:ignore` comment suppresses on a line.
664#[derive(Clone, Debug, PartialEq, Eq)]
665pub enum IgnoreScope {
666    /// Suppresses all finding kinds and columns on the line (`// tmt:ignore ...`).
667    All,
668    /// Suppresses only findings matching at least one filter (`// tmt:ignore[input_gap, @18, survivor@32] ...`).
669    Filters(BTreeSet<IgnoreFilter>),
670}
671
672/// Parsed `// tmt:ignore` directive(s) effective on a single source line.
673#[derive(Clone, Debug, PartialEq, Eq)]
674pub struct LineIgnore {
675    pub scope: IgnoreScope,
676    pub reason: String,
677}
678
679impl LineIgnore {
680    /// Returns true if this directive matches `kind` without column restriction (for backwards
681    /// compatibility with callers that only check finding kinds).
682    pub fn matches_kind(&self, kind: &str) -> bool {
683        match &self.scope {
684            IgnoreScope::All => true,
685            IgnoreScope::Filters(filters) => filters
686                .iter()
687                .any(|f| f.column.is_none() && f.kind.as_deref().is_none_or(|k| k == kind)),
688        }
689    }
690
691    /// Returns true if this directive matches a finding with `kind` at 1-based `column`
692    /// without mutation-specific filtering.
693    pub fn matches(&self, kind: &str, column: usize) -> bool {
694        match &self.scope {
695            IgnoreScope::All => true,
696            IgnoreScope::Filters(filters) => filters.iter().any(|f| f.matches(kind, column)),
697        }
698    }
699
700    /// Returns true if this directive matches a finding with `kind`, 1-based `column`,
701    /// and surviving mutant descriptions `survivors`.
702    pub fn matches_finding(&self, kind: &str, column: usize, survivors: &[String]) -> bool {
703        match &self.scope {
704            IgnoreScope::All => true,
705            IgnoreScope::Filters(filters) => filters
706                .iter()
707                .any(|f| f.matches_finding(kind, column, survivors)),
708        }
709    }
710
711    fn merge(&mut self, other: LineIgnore) {
712        match (&mut self.scope, other.scope) {
713            (IgnoreScope::All, IgnoreScope::All) => {
714                // Later (inline) unscoped comment overrides standalone line above.
715                self.reason = other.reason;
716            }
717            (IgnoreScope::All, IgnoreScope::Filters(_)) => {}
718            (slot, IgnoreScope::All) => {
719                *slot = IgnoreScope::All;
720                // An inline unscoped directive supersedes a scoped reason from above.
721                self.reason = other.reason;
722            }
723            (IgnoreScope::Filters(existing), IgnoreScope::Filters(extra)) => {
724                existing.extend(extra);
725                if !other.reason.is_empty() {
726                    self.reason = other.reason;
727                }
728            }
729        }
730    }
731}
732
733/// Diagnostic produced while parsing a `// tmt:ignore[...]` directive.
734#[derive(Clone, Debug, PartialEq, Eq)]
735pub enum IgnoreWarning {
736    /// `// tmt:ignore[]` with an empty selector list.
737    EmptyScope { line: usize },
738    /// An unrecognised kind or invalid `@COL` selector inside `// tmt:ignore[...]`.
739    InvalidToken { line: usize, token: String },
740}
741
742/// Individual `// tmt:ignore` comment entry for unused-directive diagnostics.
743#[derive(Clone, Debug, PartialEq, Eq)]
744pub struct IgnoreDirectiveEntry {
745    pub comment_line: usize,
746    pub target_lines: Vec<usize>,
747    pub scope: IgnoreScope,
748}
749
750impl IgnoreDirectiveEntry {
751    pub fn is_active(&self) -> bool {
752        match &self.scope {
753            IgnoreScope::All => true,
754            IgnoreScope::Filters(filters) => !filters.is_empty(),
755        }
756    }
757
758    pub fn matches(&self, line: usize, kind: &str, column: usize) -> bool {
759        if !self.target_lines.contains(&line) {
760            return false;
761        }
762        match &self.scope {
763            IgnoreScope::All => true,
764            IgnoreScope::Filters(filters) => filters.iter().any(|f| f.matches(kind, column)),
765        }
766    }
767
768    pub fn matches_finding(
769        &self,
770        line: usize,
771        kind: &str,
772        column: usize,
773        survivors: &[String],
774    ) -> bool {
775        if !self.target_lines.contains(&line) {
776            return false;
777        }
778        match &self.scope {
779            IgnoreScope::All => true,
780            IgnoreScope::Filters(filters) => filters
781                .iter()
782                .any(|f| f.matches_finding(kind, column, survivors)),
783        }
784    }
785}
786
787/// Full result of scanning a source file for `// tmt:ignore` comments.
788#[derive(Clone, Debug, Default, PartialEq, Eq)]
789pub struct ParsedLineIgnores {
790    pub directives: BTreeMap<usize, LineIgnore>,
791    pub entries: Vec<IgnoreDirectiveEntry>,
792    pub warnings: Vec<IgnoreWarning>,
793}
794
795/// Known finding-kind names accepted inside `// tmt:ignore[...]`.
796const IGNORE_KINDS: &[&str] = &["input_gap", "assertion_gap", "survivor"];
797
798fn levenshtein(a: &str, b: &str) -> usize {
799    let a: Vec<char> = a.chars().collect();
800    let b: Vec<char> = b.chars().collect();
801    let mut prev: Vec<usize> = (0..=b.len()).collect();
802    let mut curr = vec![0; b.len() + 1];
803    for (i, &ca) in a.iter().enumerate() {
804        curr[0] = i + 1;
805        for (j, &cb) in b.iter().enumerate() {
806            let cost = usize::from(ca != cb);
807            curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
808        }
809        std::mem::swap(&mut prev, &mut curr);
810    }
811    prev[b.len()]
812}
813
814/// Suggests the closest valid `// tmt:ignore[...]` selector for a mistyped token, if any.
815pub fn suggest_ignore_scope(raw: &str) -> Option<String> {
816    let token = raw.trim();
817    if token.is_empty() {
818        return None;
819    }
820    let (base, mutation_part) = match token.split_once(':') {
821        Some((b, m)) => {
822            let m = m.trim();
823            if m.is_empty() {
824                return None;
825            }
826            (b.trim(), Some(m))
827        }
828        None => (token, None),
829    };
830    let (kind_part, col_part) = match base.split_once('@') {
831        Some((k, c)) => (k.trim(), Some(c.trim())),
832        None => (base, None),
833    };
834    let valid_col = match col_part {
835        Some(c) => {
836            let parsed = c.parse::<usize>().ok()?;
837            if parsed == 0 {
838                return None;
839            }
840            Some(parsed)
841        }
842        None => None,
843    };
844    if kind_part.is_empty() {
845        return None;
846    }
847    let normalized = kind_part.to_ascii_lowercase().replace('-', "_");
848    let best = IGNORE_KINDS
849        .iter()
850        .copied()
851        .filter_map(|candidate| {
852            let dist = levenshtein(&normalized, candidate);
853            let max_dist = if candidate.starts_with(&normalized) && normalized.len() >= 3 {
854                candidate.len()
855            } else {
856                3
857            };
858            (dist <= max_dist).then_some((dist, candidate))
859        })
860        .min_by_key(|(dist, _)| *dist)
861        .map(|(_, candidate)| candidate)?;
862    let mut suggestion = match valid_col {
863        Some(col) => format!("{best}@{col}"),
864        None => best.to_string(),
865    };
866    if let Some(m) = mutation_part {
867        suggestion.push(':');
868        suggestion.push_str(m);
869    }
870    (suggestion != token).then_some(suggestion)
871}
872
873fn parse_ignore_filter(raw: &str) -> Option<IgnoreFilter> {
874    let token = raw.trim();
875    if token.is_empty() {
876        return None;
877    }
878    let (base, mutation) = match token.split_once(':') {
879        Some((b, m)) => {
880            let m = m.trim();
881            if m.is_empty() {
882                return None;
883            }
884            (b.trim(), Some(m.to_string()))
885        }
886        None => (token, None),
887    };
888    let (kind_part, col_part) = match base.split_once('@') {
889        Some((k, c)) => (k.trim(), Some(c.trim())),
890        None => (base, None),
891    };
892    let column = match col_part {
893        Some(c) => {
894            let parsed = c.parse::<usize>().ok()?;
895            if parsed == 0 {
896                return None;
897            }
898            Some(parsed)
899        }
900        None => None,
901    };
902    let kind = if kind_part.is_empty() {
903        column?;
904        None
905    } else {
906        let normalized = kind_part.replace('-', "_");
907        if matches!(
908            normalized.as_str(),
909            "input_gap" | "assertion_gap" | "survivor"
910        ) {
911            Some(normalized)
912        } else {
913            return None;
914        }
915    };
916    Some(IgnoreFilter {
917        kind,
918        column,
919        mutation,
920    })
921}
922
923fn parse_ignore_comment(
924    comment: &str,
925    line: usize,
926    warnings: &mut Vec<IgnoreWarning>,
927) -> Option<LineIgnore> {
928    let rest = comment.trim_start().strip_prefix("tmt:ignore")?;
929    if let Some(bracketed) = rest.strip_prefix('[') {
930        let close = bracketed.find(']')?;
931        let inside = &bracketed[..close];
932        let after = &bracketed[close + 1..];
933        if !(after.is_empty() || after.starts_with(|c: char| c.is_whitespace() || c == ':')) {
934            return None;
935        }
936        let mut filters = BTreeSet::new();
937        if inside.trim().is_empty() {
938            warnings.push(IgnoreWarning::EmptyScope { line });
939        } else {
940            for token in inside.split(',') {
941                if let Some(filter) = parse_ignore_filter(token) {
942                    filters.insert(filter);
943                } else {
944                    warnings.push(IgnoreWarning::InvalidToken {
945                        line,
946                        token: token.trim().to_string(),
947                    });
948                }
949            }
950        }
951        let reason = after.trim_start_matches(':').trim().to_string();
952        return Some(LineIgnore {
953            scope: IgnoreScope::Filters(filters),
954            reason,
955        });
956    }
957    if rest.is_empty() || rest.starts_with(|c: char| c.is_whitespace() || c == ':') {
958        let reason = rest.trim_start_matches(':').trim().to_string();
959        return Some(LineIgnore {
960            scope: IgnoreScope::All,
961            reason,
962        });
963    }
964    None
965}
966
967/// Lines covered by an unscoped `// tmt:ignore` comment, with the reason given after it. A
968/// standalone comment line covers its own line and the next one (so it can sit above the
969/// code); an end-of-line comment covers only its own line. For scoped directives
970/// (`// tmt:ignore[input_gap]` or `// tmt:ignore[@18]`), use [`line_ignores`] or [`parse_line_ignores`].
971pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
972    line_ignores(source)
973        .into_iter()
974        .filter(|(_, ignore)| matches!(ignore.scope, IgnoreScope::All))
975        .map(|(line, ignore)| (line, ignore.reason))
976        .collect()
977}
978
979/// Lines covered by `// tmt:ignore` or `// tmt:ignore[scope, ...]` comments.
980/// A standalone comment line covers its own line and the next one; an end-of-line
981/// comment covers only its own line. Multiple directives targeting the same line are merged.
982pub fn line_ignores(source: &str) -> BTreeMap<usize, LineIgnore> {
983    parse_line_ignores(source).directives
984}
985
986/// Scans `source` for `// tmt:ignore` directives, returning merged per-line rules,
987/// individual comment entries (for unused-directive detection), and syntax/scope warnings.
988pub fn parse_line_ignores(source: &str) -> ParsedLineIgnores {
989    let mut parsed = ParsedLineIgnores::default();
990    let bytes = source.as_bytes();
991    let mut i = 0;
992    let mut line = 1usize;
993    let mut line_start = 0usize;
994    let mut block_depth = 0usize;
995    while i < bytes.len() {
996        if block_depth > 0 {
997            if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
998                block_depth += 1;
999                i += 2;
1000            } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
1001                block_depth -= 1;
1002                i += 2;
1003            } else {
1004                if bytes[i] == b'\n' {
1005                    line += 1;
1006                    line_start = i + 1;
1007                }
1008                i += 1;
1009            }
1010            continue;
1011        }
1012        match bytes[i] {
1013            b'\n' => {
1014                line += 1;
1015                line_start = i + 1;
1016                i += 1;
1017            }
1018            b'/' if bytes.get(i + 1) == Some(&b'/') => {
1019                let comment_start = i + 2;
1020                let mut end = comment_start;
1021                while end < bytes.len() && bytes[end] != b'\n' {
1022                    end += 1;
1023                }
1024                let comment = &source[comment_start..end];
1025                if let Some(directive) = parse_ignore_comment(comment, line, &mut parsed.warnings) {
1026                    let standalone = source[line_start..i].trim().is_empty();
1027                    let target_lines = if standalone {
1028                        vec![line, line + 1]
1029                    } else {
1030                        vec![line]
1031                    };
1032                    parsed.entries.push(IgnoreDirectiveEntry {
1033                        comment_line: line,
1034                        target_lines,
1035                        scope: directive.scope.clone(),
1036                    });
1037                    parsed
1038                        .directives
1039                        .entry(line)
1040                        .and_modify(|existing| existing.merge(directive.clone()))
1041                        .or_insert_with(|| directive.clone());
1042                    if standalone {
1043                        parsed
1044                            .directives
1045                            .entry(line + 1)
1046                            .and_modify(|existing| existing.merge(directive.clone()))
1047                            .or_insert(directive);
1048                    }
1049                }
1050                i = end;
1051            }
1052            b'/' if bytes.get(i + 1) == Some(&b'*') => {
1053                block_depth = 1;
1054                i += 2;
1055            }
1056            // Raw strings: `r"..."`, `r#"..."#`, `br#"..."#`, `cr#"..."#`.
1057            b'r' if raw_string_hashes(bytes, i).is_some() => {
1058                let hashes = raw_string_hashes(bytes, i).unwrap();
1059                i += 1 + hashes + 1;
1060                while i < bytes.len() {
1061                    if bytes[i] == b'\n' {
1062                        line += 1;
1063                        line_start = i + 1;
1064                    }
1065                    if bytes[i] == b'"'
1066                        && bytes
1067                            .get(i + 1..i + 1 + hashes)
1068                            .is_some_and(|s| s.iter().all(|b| *b == b'#'))
1069                    {
1070                        i += 1 + hashes;
1071                        break;
1072                    }
1073                    i += 1;
1074                }
1075            }
1076            b'"' => {
1077                i += 1;
1078                while i < bytes.len() {
1079                    if bytes[i] == b'\\' {
1080                        if bytes.get(i + 1) == Some(&b'\n') {
1081                            line += 1;
1082                            line_start = i + 2;
1083                        }
1084                        i = (i + 2).min(bytes.len());
1085                        continue;
1086                    }
1087                    if bytes[i] == b'\n' {
1088                        line += 1;
1089                        line_start = i + 1;
1090                    }
1091                    if bytes[i] == b'"' {
1092                        i += 1;
1093                        break;
1094                    }
1095                    i += 1;
1096                }
1097            }
1098            // Character literals (`'"'`, `'\\'`, `'\''`, `'a'`); lifetimes (`'a`) have no closing `'`.
1099            b'\'' => {
1100                if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 2).is_some_and(|&b| b != b'\n')
1101                {
1102                    // Escape char literal such as `'\''`, `'\"'`, `'\\'`, `'\x7f'`, `'\u{...}'`.
1103                    // Start after the escaped byte so `'\''` does not close on the escaped quote.
1104                    let mut j = i + 3;
1105                    while j < bytes.len() && bytes[j] != b'\n' && bytes[j] != b'\'' {
1106                        j += 1;
1107                    }
1108                    if bytes.get(j) == Some(&b'\'') {
1109                        i = j + 1;
1110                    } else {
1111                        i += 1;
1112                    }
1113                } else if let Some(ch) = source[i + 1..].chars().next()
1114                    && bytes.get(i + 1 + ch.len_utf8()) == Some(&b'\'')
1115                {
1116                    i += 1 + ch.len_utf8() + 1;
1117                } else {
1118                    i += 1;
1119                }
1120            }
1121            _ => i += 1,
1122        }
1123    }
1124    parsed
1125}
1126
1127fn raw_string_hashes(bytes: &[u8], r_pos: usize) -> Option<usize> {
1128    // Reject identifier suffixes like `str"..."` (except `br"` / `cr"`).
1129    if r_pos > 0 {
1130        let prev = bytes[r_pos - 1];
1131        let is_prefix =
1132            (prev == b'b' || prev == b'c') && (r_pos == 1 || !is_ident_byte(bytes[r_pos - 2]));
1133        if is_ident_byte(prev) && !is_prefix {
1134            return None;
1135        }
1136    }
1137    let mut hashes = 0;
1138    while bytes.get(r_pos + 1 + hashes) == Some(&b'#') {
1139        hashes += 1;
1140    }
1141    (bytes.get(r_pos + 1 + hashes) == Some(&b'"')).then_some(hashes)
1142}
1143
1144fn is_ident_byte(b: u8) -> bool {
1145    b.is_ascii_alphanumeric() || b == b'_'
1146}
1147
1148#[cfg(test)]
1149mod tests {
1150    use super::*;
1151    use crate::report::Location;
1152
1153    fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
1154        Finding::AssertionGap {
1155            at: Location {
1156                file: "src/lib.rs".into(),
1157                line,
1158                column: 5,
1159                code: code.into(),
1160                ..Location::default()
1161            },
1162            survivors: survivors.iter().map(|s| s.to_string()).collect(),
1163            tests: vec!["tests::t".into()],
1164            effects: vec![],
1165            effects_of: None,
1166            witness: None,
1167            likely_equivalent: None,
1168        }
1169    }
1170
1171    #[test]
1172    fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
1173        let named = |id: &str, survivors: &[&str]| {
1174            let mut finding = gap(10, "a > b", survivors);
1175            let Finding::AssertionGap { at, .. } = &mut finding else {
1176                unreachable!()
1177            };
1178            at.id = id.to_string();
1179            finding
1180        };
1181        let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
1182        let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
1183        let written = render(std::slice::from_ref(&one));
1184        let baseline = parse(&written).unwrap();
1185        assert!(baseline.knows(&one));
1186        // The same code in another function is another finding.
1187        assert!(!baseline.knows(&other));
1188        // Other words for the mutants, or one more of them, and it is still the one.
1189        assert!(baseline.knows(&named(
1190            "assertion_gap|src/lib.rs|f|a > b|0",
1191            &["`a >= b`", "the negation"]
1192        )));
1193        // A finding without a name is not known by having none.
1194        assert!(
1195            !parse(&render(&[gap(1, "x", &[])]))
1196                .unwrap()
1197                .knows(&gap(2, "y", &[]))
1198        );
1199        // A file of an earlier version lists fingerprints, and still works as it did.
1200        let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
1201        let baseline = parse(&old).unwrap();
1202        assert!(matches!(baseline, Baseline::Fingerprints(_)));
1203        assert!(baseline.knows(&one) && baseline.knows(&other));
1204        assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
1205        // Anything else is refused, with a later version said to be one.
1206        let later = parse(r#"{"version": 4, "findings": []}"#).unwrap_err();
1207        assert!(later.to_string().contains("version 4"), "{later}");
1208        for bad in [
1209            "{}",
1210            "3",
1211            r#"{"version": 2}"#,
1212            r#"{"version": 2, "findings": null}"#,
1213            r#"{"version": 2, "findings": [1]}"#,
1214            r#"{"version": 3, "findings": [1]}"#,
1215            r#"["a", 1]"#,
1216        ] {
1217            assert!(parse(bad).is_err(), "{bad}");
1218        }
1219    }
1220
1221    #[test]
1222    fn fingerprints_ignore_position_but_not_content() {
1223        let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
1224        assert_eq!(
1225            base,
1226            fingerprint(&gap(99, "a > b", &["`a >= b`"])),
1227            "moved code"
1228        );
1229        assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
1230        assert_ne!(
1231            base,
1232            fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
1233            "a new survivor"
1234        );
1235        let input = Finding::InputGap {
1236            at: Location {
1237                file: "src/lib.rs".into(),
1238                line: 10,
1239                column: 5,
1240                code: "a > b".into(),
1241                ..Location::default()
1242            },
1243            survivors: vec!["`a >= b`".into()],
1244            survivor_count: 1,
1245            add_tests: vec![],
1246            observed: None,
1247            verified: true,
1248            likely_equivalent: None,
1249        };
1250        assert_ne!(base, fingerprint(&input), "another kind of finding");
1251    }
1252
1253    #[test]
1254    fn baseline_round_trip() {
1255        let path =
1256            std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
1257        let _ = std::fs::remove_file(&path);
1258        let mut findings = vec![
1259            gap(1, "a > b", &["`a >= b`"]),
1260            gap(2, "x();", &["delete `x();`"]),
1261        ];
1262        for (index, finding) in findings.iter_mut().enumerate() {
1263            let Finding::AssertionGap { at, .. } = finding else {
1264                unreachable!()
1265            };
1266            at.id = format!("id-{index}-é\n");
1267            at.item = format!("fn_{index}");
1268        }
1269        findings.reverse();
1270        findings.push(findings[0].clone());
1271        write(&path, &findings).unwrap();
1272        let written: serde_json::Value =
1273            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1274        assert_eq!(written["version"], 3);
1275        let entries = written["findings"].as_array().unwrap();
1276        assert_eq!(entries.len(), 2);
1277        assert_eq!(entries[0]["id"], "id-0-é\n");
1278        assert_eq!(entries[0]["kind"], "assertion_gap");
1279        assert_eq!(entries[0]["file"], "src/lib.rs");
1280        assert_eq!(entries[0]["item"], "fn_0");
1281        assert_eq!(entries[0]["code"], "a > b");
1282        assert_eq!(entries[0]["survivors"], serde_json::json!(["`a >= b`"]));
1283        assert_eq!(entries[0]["reason"], "");
1284        assert_eq!(entries[1]["id"], "id-1-é\n");
1285
1286        // Adding a reason in the file is preserved on subsequent `write` calls.
1287        let mut edited = written.clone();
1288        edited["findings"][0]["reason"] = serde_json::json!("equivalent in domain");
1289        std::fs::write(&path, serde_json::to_string_pretty(&edited).unwrap()).unwrap();
1290        write(&path, &findings).unwrap();
1291        let rewritten: serde_json::Value =
1292            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1293        assert_eq!(rewritten["findings"][0]["reason"], "equivalent in domain");
1294        assert_eq!(rewritten["findings"][1]["reason"], "");
1295
1296        let loaded = load(&path).unwrap();
1297        let ids: BTreeSet<String> = ["id-0-é\n", "id-1-é\n"].map(str::to_string).into();
1298        assert_eq!(
1299            loaded,
1300            Baseline::Ids {
1301                file_package: None,
1302                scoped: BTreeMap::new(),
1303                unscoped: ids,
1304            }
1305        );
1306        assert!(findings.iter().all(|f| loaded.knows(f)));
1307
1308        // Malformed existing baseline is never silently overwritten.
1309        let broken = r#"{"version": 3, "findings": [{"id": "id-0", "reasons": "typo"}]}"#;
1310        std::fs::write(&path, broken).unwrap();
1311        assert!(write(&path, &findings).is_err());
1312        assert_eq!(std::fs::read_to_string(&path).unwrap(), broken);
1313
1314        std::fs::write(&path, "not json").unwrap();
1315        assert!(load(&path).is_err());
1316        assert!(write(&path, &findings).is_err());
1317        assert_eq!(std::fs::read_to_string(&path).unwrap(), "not json");
1318        std::fs::remove_file(&path).unwrap();
1319        assert!(load(&path).is_err());
1320    }
1321
1322    #[test]
1323    fn baseline_accepts_legacy_strings_and_structured_entries_mixed() {
1324        let v2 = r#"{"version": 2, "findings": ["v2-id"]}"#;
1325        assert_eq!(
1326            parse(v2).unwrap(),
1327            Baseline::Ids {
1328                file_package: None,
1329                scoped: BTreeMap::new(),
1330                unscoped: ["v2-id"].map(str::to_string).into(),
1331            }
1332        );
1333
1334        let mixed = r#"{
1335  "version": 3,
1336  "findings": [
1337    "legacy-id",
1338    {
1339      "id": "structured-id",
1340      "kind": "input_gap",
1341      "file": "src/lib.rs",
1342      "code": "x > 0",
1343      "survivors": ["`x >= 0`"],
1344      "reason": "zero is unreachable"
1345    }
1346  ]
1347}"#;
1348        let parsed = parse_full(mixed).unwrap();
1349        assert_eq!(
1350            parsed.baseline,
1351            Baseline::Ids {
1352                file_package: None,
1353                scoped: BTreeMap::new(),
1354                unscoped: ["legacy-id", "structured-id"].map(str::to_string).into(),
1355            }
1356        );
1357        assert_eq!(
1358            parsed
1359                .legacy_reasons
1360                .get("structured-id")
1361                .map(String::as_str),
1362            Some("zero is unreachable")
1363        );
1364        assert!(!parsed.legacy_reasons.contains_key("legacy-id"));
1365
1366        // Unknown fields in structured entries are rejected to catch typos like `reasons`.
1367        let typo = r#"{"version": 3, "findings": [{"id": "x", "reasons": "typo"}]}"#;
1368        assert!(parse(typo).is_err());
1369        let missing_id = r#"{"version": 3, "findings": [{"reason": "no id"}]}"#;
1370        assert!(parse(missing_id).is_err());
1371    }
1372
1373    #[test]
1374    fn selective_ignore_comments() {
1375        let source = "\
1376fn f() {
1377    // tmt:ignore[input_gap] boundary is equivalent
1378    if a >= b { a } else { b }
1379    let x = 1; // tmt:ignore[assertion-gap, survivor]: intentional
1380    // tmt:ignore[input_gap] above
1381    let y = 2; // tmt:ignore[assertion_gap] inline
1382    // tmt:ignore[unknown_kind] should not suppress anything
1383    let z = 3;
1384    let empty = 4; // tmt:ignore[] empty list
1385    let unclosed = 5; // tmt:ignore[input_gap missing bracket
1386    let attached = 6; // tmt:ignore[input_gap]extra
1387}
1388";
1389        let ignores = line_ignores(source);
1390        // Line 2 & 3: input_gap only
1391        assert!(ignores[&3].matches_kind("input_gap"));
1392        assert!(!ignores[&3].matches_kind("assertion_gap"));
1393        assert!(!ignores[&3].matches_kind("survivor"));
1394        assert_eq!(ignores[&3].reason, "boundary is equivalent");
1395
1396        // Line 4: hyphenated assertion-gap + survivor
1397        assert!(!ignores[&4].matches_kind("input_gap"));
1398        assert!(ignores[&4].matches_kind("assertion_gap"));
1399        assert!(ignores[&4].matches_kind("survivor"));
1400        assert_eq!(ignores[&4].reason, "intentional");
1401
1402        // Line 6: merged from standalone line 5 + inline line 6
1403        assert!(ignores[&6].matches_kind("input_gap"));
1404        assert!(ignores[&6].matches_kind("assertion_gap"));
1405        assert!(!ignores[&6].matches_kind("survivor"));
1406
1407        // Line 8: unknown kind matches nothing (safe side)
1408        assert!(!ignores[&8].matches_kind("input_gap"));
1409        assert!(!ignores[&8].matches_kind("assertion_gap"));
1410        assert!(!ignores[&8].matches_kind("survivor"));
1411
1412        // Line 9: empty brackets match nothing (safe side)
1413        assert!(!ignores[&9].matches_kind("input_gap"));
1414
1415        // Line 10 & 11: malformed syntax is not recognized
1416        assert!(!ignores.contains_key(&10));
1417        assert!(!ignores.contains_key(&11));
1418
1419        // Legacy `ignored_lines` excludes kind-scoped directives.
1420        assert!(ignored_lines(source).is_empty());
1421
1422        // Standalone + inline overlap: inline unscoped reason takes precedence.
1423        let overlap = "\
1424fn g() {
1425    // tmt:ignore above
1426    let a = 1; // tmt:ignore inline
1427    // tmt:ignore[input_gap] scoped above
1428    let b = 2; // tmt:ignore unscoped inline
1429}
1430";
1431        let legacy = ignored_lines(overlap);
1432        assert_eq!(legacy.get(&3).map(String::as_str), Some("inline"));
1433        assert_eq!(legacy.get(&5).map(String::as_str), Some("unscoped inline"));
1434    }
1435
1436    #[test]
1437    fn ignore_comments() {
1438        let source = "\
1439fn f() {
1440    // tmt:ignore equivalent: both branches return the same
1441    if a >= b { a } else { b }
1442    let x = 1; // tmt:ignore
1443    let y = 2;
1444    let z = 3;
1445    let w = 4; // tmt:ignore: with a colon
1446    // tmt:ignored is another word
1447    // not tmt:ignore here? it is: tmt:ignore must start the comment
1448    let url = \"http://tmt:ignore reason\";
1449    let ok = \"https://example.com\"; // tmt:ignore after url
1450    let raw = r#\"// tmt:ignore inside raw string\"#;
1451    /* // tmt:ignore inside block comment */
1452    let ch = '\"'; // tmt:ignore after quote char
1453    let quotes = ['\\'', '\"'];
1454    let fake = \"// tmt:ignore fake after escaped quote\";
1455    let real = 5; // tmt:ignore after escaped quote
1456}
1457";
1458        let ignored = ignored_lines(source);
1459        assert_eq!(
1460            ignored.keys().copied().collect::<Vec<_>>(),
1461            [2, 3, 4, 7, 11, 14, 17]
1462        );
1463        assert_eq!(ignored[&7], "with a colon");
1464        assert_eq!(ignored[&2], "equivalent: both branches return the same");
1465        assert_eq!(ignored[&3], "equivalent: both branches return the same");
1466        assert_eq!(ignored[&4], "");
1467        assert_eq!(ignored[&11], "after url");
1468        assert_eq!(ignored[&14], "after quote char");
1469        assert_eq!(ignored[&17], "after escaped quote");
1470        assert!(ignored_lines("").is_empty());
1471    }
1472
1473    #[test]
1474    fn suggest_ignore_scope_matches_typos_and_preserves_column() {
1475        assert_eq!(
1476            suggest_ignore_scope("input_gaps"),
1477            Some("input_gap".to_string())
1478        );
1479        assert_eq!(
1480            suggest_ignore_scope("assertion"),
1481            Some("assertion_gap".to_string())
1482        );
1483        assert_eq!(
1484            suggest_ignore_scope("survivr@18"),
1485            Some("survivor@18".to_string())
1486        );
1487        assert_eq!(
1488            suggest_ignore_scope("input-gaps@42"),
1489            Some("input_gap@42".to_string())
1490        );
1491        assert_eq!(suggest_ignore_scope("input_gap"), None);
1492        assert_eq!(suggest_ignore_scope("completely_unrelated_xyz"), None);
1493        assert_eq!(suggest_ignore_scope("@0"), None);
1494        assert_eq!(suggest_ignore_scope("input_gaps@0"), None);
1495        assert_eq!(suggest_ignore_scope(""), None);
1496    }
1497}