Skip to main content

mir_analyzer/
suppression.rs

1//! Inline issue suppression via source comments.
2//!
3//! Lets users silence a single false positive without touching `mir.xml` or a
4//! baseline file. A [`SuppressionMap`] is built once per file from its source
5//! text and consulted as a final post-filter over the analyzer's issues
6//! (`batch.rs`), so it applies uniformly across every emitting pass —
7//! body analysis, the collector, class checks and dead-code detection.
8//!
9//! ## Recognised directives
10//!
11//! Native (preferred), matching the existing `@mir-check` convention:
12//!
13//! | Directive                  | Scope                                   |
14//! |----------------------------|-----------------------------------------|
15//! | `@mir-ignore [Kind …]`     | trailing comment → its line; otherwise the next code line |
16//! | `@mir-ignore-line [Kind …]`      | the comment's own line            |
17//! | `@mir-ignore-next-line [Kind …]` | the next physical line            |
18//! | `@mir-ignore-file [Kind …]`      | the whole file                    |
19//!
20//! `@mir-suppress*` is accepted as an alias of `@mir-ignore*`.
21//!
22//! Third-party aliases for drop-in compatibility:
23//!
24//! | Directive                   | Scope / kinds                          |
25//! |-----------------------------|----------------------------------------|
26//! | `@psalm-suppress Kind …`    | like `@mir-ignore` (named kinds)       |
27//! | `@suppress Kind …`          | like `@mir-ignore` (named kinds)       |
28//! | `@phpstan-ignore-line`      | the comment's own line, all kinds      |
29//! | `@phpstan-ignore-next-line` | the next line, all kinds               |
30//! | `@phpstan-ignore …`         | the next line, all kinds               |
31//!
32//! When no `Kind` follows the directive, *all* issues on the target line are
33//! suppressed. Kinds may be given by name (`UndefinedClass`) or by code
34//! (`MIR0123`); multiple kinds are space- or comma-separated. PHPStan's
35//! `@phpstan-ignore*` forms always suppress every kind on their target, since
36//! PHPStan identifiers do not map onto mir's [`IssueKind`] names.
37//!
38//! [`IssueKind`]: mir_issues::IssueKind
39
40use rustc_hash::{FxHashMap, FxHashSet};
41
42/// Set of issue kinds a directive applies to.
43#[derive(Debug, Clone)]
44enum KindSet {
45    /// Every kind on the target.
46    All,
47    /// Specific kinds, matched against `IssueKind::name()` or `code()`.
48    Named(FxHashSet<String>),
49}
50
51impl KindSet {
52    fn matches(&self, name: &str, code: &str) -> bool {
53        match self {
54            KindSet::All => true,
55            KindSet::Named(set) => set.contains(name) || set.contains(code),
56        }
57    }
58
59    fn merge(&mut self, other: KindSet) {
60        match (self, other) {
61            // Already broadest possible.
62            (KindSet::All, _) => {}
63            (slot @ KindSet::Named(_), KindSet::All) => *slot = KindSet::All,
64            (KindSet::Named(a), KindSet::Named(b)) => a.extend(b),
65        }
66    }
67}
68
69/// Where a directive applies, relative to the comment's own line.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71enum Scope {
72    /// The comment's own physical line.
73    SameLine,
74    /// The next code line (next non-blank physical line).
75    NextLine,
76    /// Every line in the file.
77    File,
78}
79
80struct Directive {
81    scope: Scope,
82    kinds: KindSet,
83    /// For [`Scope::NextLine`]: whether to skip intervening comment lines (not
84    /// just blanks) when locating the target. Set for "documents the following
85    /// element" forms (`@psalm-suppress`, bare `@mir-ignore`, …) so a directive
86    /// inside a multi-line docblock still lands on the declaration it annotates,
87    /// past the closing `*/`.
88    skip_comments: bool,
89}
90
91/// Per-file map of suppressed lines, built from source comments.
92#[derive(Debug, Default)]
93pub struct SuppressionMap {
94    /// 1-based line number → kinds suppressed on that line.
95    lines: FxHashMap<u32, KindSet>,
96    /// Whole-file suppression, if any directive requested it.
97    file: Option<KindSet>,
98    /// Named (non-All) suppressions with their target lines, for
99    /// `UnusedSuppress` detection. Each entry is `(target_line, kind_name)`.
100    /// Only `@psalm-suppress X` / `@suppress X` / `@mir-suppress X` forms populate
101    /// this — blanket `@phpstan-ignore*` suppressions are intentionally excluded.
102    pub named_suppressions: Vec<(u32, String)>,
103}
104
105impl SuppressionMap {
106    /// No directives — used to skip work for files with no suppression comments.
107    pub fn is_empty(&self) -> bool {
108        self.lines.is_empty() && self.file.is_none()
109    }
110
111    /// Whether an issue of `name`/`code` reported at 1-based `line` is suppressed.
112    pub fn is_suppressed(&self, line: u32, name: &str, code: &str) -> bool {
113        if let Some(file) = &self.file {
114            if file.matches(name, code) {
115                return true;
116            }
117        }
118        self.lines.get(&line).is_some_and(|k| k.matches(name, code))
119    }
120
121    /// Scan `source` for suppression directives.
122    pub fn from_source(source: &str) -> Self {
123        let raw_lines: Vec<&str> = source.lines().collect();
124        let mut map = SuppressionMap::default();
125
126        for (idx, raw) in raw_lines.iter().enumerate() {
127            let Some((directive, track_named)) = parse_directive_with_tracking(raw) else {
128                continue;
129            };
130            match directive.scope {
131                Scope::File => match &mut map.file {
132                    Some(existing) => existing.merge(directive.kinds),
133                    None => map.file = Some(directive.kinds),
134                },
135                Scope::SameLine => {
136                    let line_no = idx as u32 + 1;
137                    if track_named {
138                        if let KindSet::Named(ref names) = directive.kinds {
139                            for name in names {
140                                map.named_suppressions.push((line_no, name.clone()));
141                            }
142                        }
143                    }
144                    insert_line(&mut map.lines, line_no, directive.kinds);
145                }
146                Scope::NextLine => {
147                    let target = next_code_line(&raw_lines, idx, directive.skip_comments);
148                    if track_named {
149                        if let KindSet::Named(ref names) = directive.kinds {
150                            for name in names {
151                                map.named_suppressions.push((target, name.clone()));
152                            }
153                        }
154                    }
155                    insert_line(&mut map.lines, target, directive.kinds);
156                }
157            }
158        }
159
160        map
161    }
162
163    /// Returns unused named suppressions: those that did not match any issue
164    /// in `all_issues`. The returned vec contains `(target_line, kind_name)`.
165    ///
166    /// `pre_suppressed` is the subset of `all_issues` that arrived already
167    /// suppressed (via the `IssueBuffer` mechanism in collector/body analysis).
168    /// These may be emitted at a different line than the suppression target
169    /// (e.g. `InvalidDocblock` at a docblock-start line vs. the following
170    /// declaration line), so they are matched within a 30-line window before
171    /// the target.
172    pub fn unused_named(
173        &self,
174        all_issues: &[&mir_issues::Issue],
175        pre_suppressed: &[&mir_issues::Issue],
176    ) -> Vec<(u32, String)> {
177        self.named_suppressions
178            .iter()
179            .filter(|(target_line, kind)| {
180                let kind_matches = |issue: &&mir_issues::Issue| {
181                    issue.kind.name() == kind.as_str() || issue.kind.code() == kind.as_str()
182                };
183                // Normal case: SuppressionMap-suppressed issue at the exact target line.
184                let at_target = all_issues
185                    .iter()
186                    .any(|issue| issue.location.line == *target_line && kind_matches(issue));
187                if at_target {
188                    return false; // suppression IS used
189                }
190                // Docblock case: collector-emitted issues (like `InvalidDocblock`)
191                // land at the docblock-start line, which precedes the declaration
192                // that the suppression targets. Allow a 30-line look-back so a
193                // `@psalm-suppress InvalidDocblock` in a multi-line docblock is
194                // recognised as used even though its issue line != target_line.
195                let min_line = target_line.saturating_sub(30);
196                let covered_by_pre_suppressed = pre_suppressed.iter().any(|issue| {
197                    issue.location.line >= min_line
198                        && issue.location.line < *target_line
199                        && kind_matches(issue)
200                });
201                !covered_by_pre_suppressed
202            })
203            .cloned()
204            .collect()
205    }
206}
207
208fn insert_line(lines: &mut FxHashMap<u32, KindSet>, line: u32, kinds: KindSet) {
209    match lines.get_mut(&line) {
210        Some(existing) => existing.merge(kinds),
211        None => {
212            lines.insert(line, kinds);
213        }
214    }
215}
216
217/// Locate a directive's target line strictly after `idx`, as a 1-based number.
218///
219/// Always skips blank lines. When `skip_comments` is set, also skips
220/// comment-only lines (`//`, `#`, `/* … */`, ` * …` docblock bodies and the
221/// closing `*/`) so a directive written inside a multi-line docblock lands on
222/// the declaration that follows it. Falls back to `idx + 2` when nothing
223/// qualifies, so the directive still has a deterministic target.
224fn next_code_line(raw_lines: &[&str], idx: usize, skip_comments: bool) -> u32 {
225    for (offset, line) in raw_lines.iter().enumerate().skip(idx + 1) {
226        let trimmed = line.trim();
227        if trimmed.is_empty() {
228            continue;
229        }
230        if skip_comments && is_comment_only(trimmed) {
231            continue;
232        }
233        return offset as u32 + 1;
234    }
235    idx as u32 + 2
236}
237
238/// Whether a trimmed line is purely a comment (no PHP code). `#[` is treated as
239/// a PHP 8 attribute (code), not a `#` comment.
240fn is_comment_only(trimmed: &str) -> bool {
241    trimmed.starts_with("//")
242        || trimmed.starts_with("/*")
243        || trimmed.starts_with('*')
244        || (trimmed.starts_with('#') && !trimmed.starts_with("#["))
245}
246
247/// Directive keyword table, ordered longest-first so that, e.g.,
248/// `@mir-ignore-next-line` is matched before the `@mir-ignore` prefix.
249///
250/// Each entry is `(keyword, scope, force_all)`. `force_all` makes the directive
251/// suppress every kind regardless of trailing tokens (PHPStan semantics).
252const KEYWORDS: &[(&str, Scope, bool)] = &[
253    ("@mir-ignore-next-line", Scope::NextLine, false),
254    ("@mir-suppress-next-line", Scope::NextLine, false),
255    ("@phpstan-ignore-next-line", Scope::NextLine, true),
256    ("@mir-ignore-line", Scope::SameLine, false),
257    ("@mir-suppress-line", Scope::SameLine, false),
258    ("@phpstan-ignore-line", Scope::SameLine, true),
259    ("@mir-ignore-file", Scope::File, false),
260    ("@mir-suppress-file", Scope::File, false),
261    // Bare forms (scope resolved below from comment position).
262    ("@mir-ignore", Scope::NextLine, false),
263    ("@mir-suppress", Scope::NextLine, false),
264    ("@psalm-suppress", Scope::NextLine, false),
265    ("@suppress", Scope::NextLine, false),
266    ("@phpstan-ignore", Scope::NextLine, true),
267];
268
269/// Bare directives (no `-line`/`-next-line`/`-file` suffix) resolve their scope
270/// from where the comment sits: a trailing comment annotates its own line, a
271/// standalone comment annotates the statement that follows it.
272const BARE_KEYWORDS: &[&str] = &[
273    "@mir-ignore",
274    "@mir-suppress",
275    "@psalm-suppress",
276    "@suppress",
277    "@phpstan-ignore",
278];
279
280/// Like `parse_directive` (which is parse_directive_with_tracking discarding the tracking flag),
281/// but also returns whether named suppression tracking
282/// should be applied (true for `@psalm-suppress`, `@mir-suppress`, `@suppress`
283/// and `@mir-ignore` forms; false for `@phpstan-*` which are blanket suppressors
284/// not tied to specific issue kinds).
285fn parse_directive_with_tracking(raw: &str) -> Option<(Directive, bool)> {
286    let comment = extract_comment(raw)?;
287
288    for &(keyword, scope, force_all) in KEYWORDS {
289        let Some(pos) = comment.content.find(keyword) else {
290            continue;
291        };
292        // Reject keyword matches that are really a prefix of a longer token
293        // (e.g. `@mir-ignore` inside `@mir-ignore-line`).
294        let after = &comment.content[pos + keyword.len()..];
295        if after
296            .chars()
297            .next()
298            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '-')
299        {
300            continue;
301        }
302
303        let is_bare = BARE_KEYWORDS.contains(&keyword);
304
305        // Bare forms: a trailing comment suppresses its own line.
306        let scope = if is_bare && comment.has_code_before {
307            Scope::SameLine
308        } else {
309            scope
310        };
311
312        // The "documents the following element" forms (bare `@psalm-suppress`,
313        // `@mir-ignore`, …) skip past intervening comment lines — e.g. the
314        // closing `*/` of a multi-line docblock — to reach the declaration.
315        // PHPStan's explicit `*-next-line` and bare `@phpstan-ignore` keep their
316        // literal next-non-blank-line semantics.
317        let skip_comments = scope == Scope::NextLine && is_bare && !force_all;
318
319        let kinds = if force_all {
320            KindSet::All
321        } else {
322            parse_kinds(after)
323        };
324
325        // Track named suppressions only for non-phpstan forms (phpstan forms
326        // always suppress all kinds, so they can never be "unused for a specific kind").
327        let track_named = !keyword.starts_with("@phpstan");
328
329        return Some((
330            Directive {
331                scope,
332                kinds,
333                skip_comments,
334            },
335            track_named,
336        ));
337    }
338
339    None
340}
341
342struct Comment<'a> {
343    /// Text from the comment introducer onward (still includes `*/`, `*`, etc.).
344    content: &'a str,
345    /// Whether non-whitespace code precedes the comment on the same line.
346    has_code_before: bool,
347}
348
349/// Isolate the comment portion of a physical line, if any. Handles `//`, `#`
350/// and `/* … */` introducers, block-comment continuation lines (` * …`) and
351/// bare directive lines inside block comments (`@psalm-suppress …`).
352fn extract_comment(raw: &str) -> Option<Comment<'_>> {
353    let trimmed = raw.trim_start();
354
355    // Block-comment continuation or a bare directive line: no code precedes it.
356    if trimmed.starts_with('*') {
357        return Some(Comment {
358            content: trimmed.trim_start_matches('*'),
359            has_code_before: false,
360        });
361    }
362    if trimmed.starts_with('@') {
363        return Some(Comment {
364            content: trimmed,
365            has_code_before: false,
366        });
367    }
368
369    // Earliest single-line / block introducer on the line.
370    let pos = [raw.find("//"), raw.find('#'), raw.find("/*")]
371        .into_iter()
372        .flatten()
373        .min()?;
374    let has_code_before = !raw[..pos].trim().is_empty();
375    Some(Comment {
376        content: &raw[pos..],
377        has_code_before,
378    })
379}
380
381/// Collect issue kind names/codes following a directive keyword. Stops at the
382/// block-comment terminator and ignores non-identifier tokens. An empty result
383/// means "all kinds".
384fn parse_kinds(rest: &str) -> KindSet {
385    let mut set = FxHashSet::default();
386    for token in rest.split([' ', '\t', ',']) {
387        let token = token.trim();
388        if token.is_empty() {
389            continue;
390        }
391        // End of the comment / docblock — stop scanning.
392        if token.starts_with("*/") || token.starts_with('*') {
393            break;
394        }
395        // A kind name is alphanumeric (plus `_`); anything else (a PHPStan
396        // identifier like `argument.type`, prose, etc.) is skipped.
397        if token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
398            set.insert(token.to_string());
399        }
400    }
401    if set.is_empty() {
402        KindSet::All
403    } else {
404        KindSet::Named(set)
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    fn map(src: &str) -> SuppressionMap {
413        SuppressionMap::from_source(src)
414    }
415
416    #[test]
417    fn line_comment_above_statement_suppresses_next_line() {
418        // line 2 comment → suppress line 3
419        let m = map("<?php\n// @psalm-suppress UndefinedClass\nnew NoSuchClass();\n");
420        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
421        assert!(!m.is_suppressed(2, "UndefinedClass", "MIR0000"));
422    }
423
424    #[test]
425    fn trailing_comment_suppresses_own_line() {
426        let m = map("<?php\nnew NoSuchClass(); // @mir-ignore UndefinedClass\n");
427        assert!(m.is_suppressed(2, "UndefinedClass", "MIR0000"));
428    }
429
430    #[test]
431    fn single_line_docblock_above_statement() {
432        let m = map("<?php\n/** @psalm-suppress UndefinedClass */\nnew NoSuchClass();\n");
433        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
434    }
435
436    #[test]
437    fn phpstan_ignore_next_line_suppresses_all() {
438        let m = map("<?php\n// @phpstan-ignore-next-line\nnew NoSuchClass();\n");
439        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
440        assert!(m.is_suppressed(3, "AnyOtherKind", "MIR9999"));
441    }
442
443    #[test]
444    fn ignore_line_targets_own_line() {
445        let m = map("<?php\nnew NoSuchClass(); // @mir-ignore-line\n");
446        assert!(m.is_suppressed(2, "UndefinedClass", "MIR0000"));
447    }
448
449    #[test]
450    fn next_line_skips_blank_lines() {
451        let m = map("<?php\n/** @psalm-suppress UndefinedClass */\n\n\nnew NoSuchClass();\n");
452        assert!(m.is_suppressed(5, "UndefinedClass", "MIR0000"));
453    }
454
455    #[test]
456    fn multiline_docblock_skips_to_declaration() {
457        // line 2: /**, line 3: * @psalm-suppress, line 4: */, line 5: declaration.
458        let src =
459            "<?php\n/**\n * @psalm-suppress UnusedMethod\n */\nprivate function a(): void {}\n";
460        let m = map(src);
461        assert!(m.is_suppressed(5, "UnusedMethod", "MIR0000"));
462    }
463
464    #[test]
465    fn phpstan_next_line_is_literal_not_comment_skipping() {
466        // PHPStan's -next-line targets the next non-blank line even if it's a
467        // comment; it does not hunt for the next code line.
468        let m = map("<?php\n// @phpstan-ignore-next-line\n// unrelated comment\nfoo();\n");
469        assert!(m.is_suppressed(3, "X", "MIR0000"));
470        assert!(!m.is_suppressed(4, "X", "MIR0000"));
471    }
472
473    #[test]
474    fn named_kind_does_not_suppress_other_kinds() {
475        let m = map("<?php\n// @mir-ignore UndefinedClass\nfoo();\n");
476        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
477        assert!(!m.is_suppressed(3, "UndefinedFunction", "MIR0001"));
478    }
479
480    #[test]
481    fn match_by_code() {
482        let m = map("<?php\n// @mir-ignore MIR1400\nfoo();\n");
483        assert!(m.is_suppressed(3, "ParseError", "MIR1400"));
484    }
485
486    #[test]
487    fn file_scope_suppresses_every_line() {
488        let m = map("<?php // @mir-ignore-file UndefinedClass\nfoo();\nbar();\n");
489        assert!(m.is_suppressed(2, "UndefinedClass", "MIR0000"));
490        assert!(m.is_suppressed(99, "UndefinedClass", "MIR0000"));
491        assert!(!m.is_suppressed(2, "UndefinedFunction", "MIR0001"));
492    }
493
494    #[test]
495    fn multiple_kinds_one_directive() {
496        let m = map("<?php\n// @psalm-suppress UndefinedClass, NullMethodCall\nfoo();\n");
497        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
498        assert!(m.is_suppressed(3, "NullMethodCall", "MIR0001"));
499    }
500
501    #[test]
502    fn no_directive_is_empty() {
503        let m = map("<?php\n$x = \"@psalm-suppress not a comment\";\nfoo();\n");
504        // It's inside a string but after `//`? No `//` here, so not detected.
505        assert!(m.is_empty());
506    }
507
508    #[test]
509    fn prefix_is_not_confused_with_longer_keyword() {
510        // `@mir-ignore-next-line` must be parsed as next-line, not bare same-line.
511        let m = map("<?php\nfoo(); // @mir-ignore-next-line\nbar();\n");
512        assert!(m.is_suppressed(3, "AnyKind", "MIR0000"));
513        assert!(!m.is_suppressed(2, "AnyKind", "MIR0000"));
514    }
515}