mir-analyzer 0.66.1

Analysis engine for the mir PHP static analyzer
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Inline issue suppression via source comments.
//!
//! Lets users silence a single false positive without touching `mir.xml` or a
//! baseline file. A [`SuppressionMap`] is built once per file from its source
//! text and consulted as a final post-filter over the analyzer's issues
//! (`batch.rs`), so it applies uniformly across every emitting pass —
//! body analysis, the collector, class checks and dead-code detection.
//!
//! ## Recognised directives
//!
//! Native (preferred), matching the existing `@mir-check` convention:
//!
//! | Directive                  | Scope                                   |
//! |----------------------------|-----------------------------------------|
//! | `@mir-ignore [Kind …]`     | trailing comment → its line; otherwise the next code line |
//! | `@mir-ignore-line [Kind …]`      | the comment's own line            |
//! | `@mir-ignore-next-line [Kind …]` | the next physical line            |
//! | `@mir-ignore-file [Kind …]`      | the whole file                    |
//!
//! `@mir-suppress*` is accepted as an alias of `@mir-ignore*`.
//!
//! Third-party aliases for drop-in compatibility:
//!
//! | Directive                   | Scope / kinds                          |
//! |-----------------------------|----------------------------------------|
//! | `@psalm-suppress Kind …`    | like `@mir-ignore` (named kinds)       |
//! | `@suppress Kind …`          | like `@mir-ignore` (named kinds)       |
//! | `@phpstan-ignore-line`      | the comment's own line, all kinds      |
//! | `@phpstan-ignore-next-line` | the next line, all kinds               |
//! | `@phpstan-ignore …`         | the next line, all kinds               |
//!
//! When no `Kind` follows the directive, *all* issues on the target line are
//! suppressed. Kinds may be given by name (`UndefinedClass`) or by code
//! (`MIR0123`); multiple kinds are space- or comma-separated. PHPStan's
//! `@phpstan-ignore*` forms always suppress every kind on their target, since
//! PHPStan identifiers do not map onto mir's [`IssueKind`] names.
//!
//! [`IssueKind`]: mir_issues::IssueKind

use rustc_hash::{FxHashMap, FxHashSet};

/// Set of issue kinds a directive applies to.
#[derive(Debug, Clone)]
enum KindSet {
    /// Every kind on the target.
    All,
    /// Specific kinds, matched against `IssueKind::name()` or `code()`.
    Named(FxHashSet<String>),
}

impl KindSet {
    fn matches(&self, name: &str, code: &str) -> bool {
        match self {
            KindSet::All => true,
            // Kind names/codes are matched case-insensitively — a directive
            // author writing `@mir-ignore undefinedclass` (or any other casing
            // that doesn't exactly match `IssueKind::name()`'s PascalCase)
            // must still suppress the issue instead of silently doing nothing.
            // The set is small (a handful of kinds per directive at most), and
            // preserving each entry's original casing (rather than
            // lowercasing at parse time) keeps `UnusedSuppress`'s message
            // quoting the text the author actually wrote.
            KindSet::Named(set) => set
                .iter()
                .any(|k| k.eq_ignore_ascii_case(name) || k.eq_ignore_ascii_case(code)),
        }
    }

    fn merge(&mut self, other: KindSet) {
        match (self, other) {
            // Already broadest possible.
            (KindSet::All, _) => {}
            (slot @ KindSet::Named(_), KindSet::All) => *slot = KindSet::All,
            (KindSet::Named(a), KindSet::Named(b)) => a.extend(b),
        }
    }
}

/// Where a directive applies, relative to the comment's own line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// The comment's own physical line.
    SameLine,
    /// The next code line (next non-blank physical line).
    NextLine,
    /// Every line in the file.
    File,
}

struct Directive {
    scope: Scope,
    kinds: KindSet,
    /// For [`Scope::NextLine`]: whether to skip intervening comment lines (not
    /// just blanks) when locating the target. Set for "documents the following
    /// element" forms (`@psalm-suppress`, bare `@mir-ignore`, …) so a directive
    /// inside a multi-line docblock still lands on the declaration it annotates,
    /// past the closing `*/`.
    skip_comments: bool,
}

/// A named (non-All) suppression, tracked for `UnusedSuppress` detection.
/// `report_line` is where an `UnusedSuppress` issue is emitted if this
/// directive never matches anything; `covered_lines` is every line an
/// issue of `kind` may legitimately land on to count as "used" — normally
/// just `report_line` itself, but a multi-line signature's continuation
/// lines (where a per-parameter issue like `UnusedParam` actually fires)
/// are included too, since the directive covers those the same way
/// `SuppressionMap::lines` already does.
#[derive(Debug, Clone)]
pub struct NamedSuppression {
    pub report_line: u32,
    pub covered_lines: Vec<u32>,
    pub kind: String,
}

/// Per-file map of suppressed lines, built from source comments.
#[derive(Debug, Default)]
pub struct SuppressionMap {
    /// 1-based line number → kinds suppressed on that line.
    lines: FxHashMap<u32, KindSet>,
    /// Whole-file suppression, if any directive requested it.
    file: Option<KindSet>,
    /// Named (non-All) suppressions, for `UnusedSuppress` detection. Only
    /// `@psalm-suppress X` / `@suppress X` / `@mir-suppress X` forms populate
    /// this — blanket `@phpstan-ignore*` suppressions are intentionally excluded.
    pub named_suppressions: Vec<NamedSuppression>,
}

impl SuppressionMap {
    /// No directives — used to skip work for files with no suppression comments.
    pub fn is_empty(&self) -> bool {
        self.lines.is_empty() && self.file.is_none()
    }

    /// Whether an issue of `name`/`code` reported at 1-based `line` is suppressed.
    pub fn is_suppressed(&self, line: u32, name: &str, code: &str) -> bool {
        if let Some(file) = &self.file {
            if file.matches(name, code) {
                return true;
            }
        }
        self.lines.get(&line).is_some_and(|k| k.matches(name, code))
    }

    /// Scan `source` for suppression directives.
    pub fn from_source(source: &str) -> Self {
        let raw_lines: Vec<&str> = source.lines().collect();
        let in_heredoc_body = heredoc_body_mask(&raw_lines);
        let mut map = SuppressionMap::default();

        for (idx, raw) in raw_lines.iter().enumerate() {
            // A `#`/`//`-looking line INSIDE a heredoc/nowdoc body (embedded
            // shell/SQL/etc.) is not a real comment — without this, a line
            // like `# @mir-ignore-file UndefinedClass` in an embedded script
            // is indistinguishable from a genuine suppression directive.
            if in_heredoc_body[idx] {
                continue;
            }
            let Some((directive, track_named)) = parse_directive_with_tracking(raw) else {
                continue;
            };
            match directive.scope {
                Scope::File => match &mut map.file {
                    Some(existing) => existing.merge(directive.kinds),
                    None => map.file = Some(directive.kinds),
                },
                Scope::SameLine => {
                    let line_no = idx as u32 + 1;
                    if track_named {
                        if let KindSet::Named(ref names) = directive.kinds {
                            for name in names {
                                map.named_suppressions.push(NamedSuppression {
                                    report_line: line_no,
                                    covered_lines: vec![line_no],
                                    kind: name.clone(),
                                });
                            }
                        }
                    }
                    insert_line(&mut map.lines, line_no, directive.kinds);
                }
                Scope::NextLine => {
                    let (target, extra_covered_lines) =
                        next_code_line(&raw_lines, idx, directive.skip_comments);
                    if track_named {
                        if let KindSet::Named(ref names) = directive.kinds {
                            // A continuation line of `target`'s own multi-line
                            // signature (a later parameter, e.g.) is where a
                            // per-parameter issue like `UnusedParam` actually
                            // fires — track it alongside `target` as a single
                            // suppression that's "used" if EITHER line has a
                            // matching issue, so a genuinely-used directive
                            // whose issue lands on a continuation line isn't
                            // misreported as unused.
                            let mut covered_lines = extra_covered_lines.clone();
                            covered_lines.push(target);
                            for name in names {
                                map.named_suppressions.push(NamedSuppression {
                                    report_line: target,
                                    covered_lines: covered_lines.clone(),
                                    kind: name.clone(),
                                });
                            }
                        }
                    }
                    // An attribute line skipped en route to `target`, or a
                    // continuation line of `target`'s own multi-line
                    // signature, stays covered by the same directive — an
                    // issue about the attribute itself (e.g.
                    // `UndefinedAttributeClass`) or about a later parameter
                    // (e.g. `UnusedParam`) fires there, not at `target`.
                    for extra_line in extra_covered_lines {
                        insert_line(&mut map.lines, extra_line, directive.kinds.clone());
                    }
                    insert_line(&mut map.lines, target, directive.kinds);
                }
            }
        }

        map
    }

    /// Returns unused named suppressions: those that did not match any issue
    /// in `all_issues`. The returned vec contains `(target_line, kind_name)`.
    ///
    /// `pre_suppressed` is the subset of `all_issues` that arrived already
    /// suppressed (via the `IssueBuffer` mechanism in collector/body analysis).
    /// These may be emitted at a different line than the suppression target
    /// (e.g. `InvalidDocblock` at a docblock-start line vs. the following
    /// declaration line), so they are matched within a 30-line window before
    /// the target.
    pub fn unused_named(
        &self,
        all_issues: &[&mir_issues::Issue],
        pre_suppressed: &[&mir_issues::Issue],
    ) -> Vec<(u32, String)> {
        self.named_suppressions
            .iter()
            .filter(|ns| {
                let target_line = ns.report_line;
                let kind = &ns.kind;
                // Compare case-insensitively, same as `KindSet::matches` —
                // a directive can name a kind in any casing.
                let kind_matches = |issue: &&mir_issues::Issue| {
                    issue
                        .kind
                        .display_name()
                        .eq_ignore_ascii_case(kind.as_str())
                        || issue.kind.code().eq_ignore_ascii_case(kind.as_str())
                };
                // Normal case: a SuppressionMap-suppressed issue at the report
                // line itself, OR any other line this same directive covers
                // (a multi-line signature's continuation lines, where a
                // per-parameter issue like `UnusedParam` actually fires).
                let at_covered_line = all_issues.iter().any(|issue| {
                    ns.covered_lines.contains(&issue.location.line) && kind_matches(issue)
                });
                if at_covered_line {
                    return false; // suppression IS used
                }
                // Docblock case: collector-emitted issues (like `InvalidDocblock`)
                // land at the docblock-start line, which precedes the declaration
                // that the suppression targets. Allow a 100-line look-back so a
                // `@psalm-suppress InvalidDocblock` in an unusually long
                // multi-line docblock (heavy @template/@method/@property lists)
                // is still recognised as used even though its issue line !=
                // target_line — 30 lines was too easy to exceed for such a
                // docblock, wrongly reporting a real, used suppression as unused.
                let min_line = target_line.saturating_sub(100);
                let covered_by_pre_suppressed = pre_suppressed.iter().any(|issue| {
                    issue.location.line >= min_line
                        && issue.location.line < target_line
                        && kind_matches(issue)
                });
                !covered_by_pre_suppressed
            })
            .map(|ns| (ns.report_line, ns.kind.clone()))
            .collect()
    }
}

fn insert_line(lines: &mut FxHashMap<u32, KindSet>, line: u32, kinds: KindSet) {
    match lines.get_mut(&line) {
        Some(existing) => existing.merge(kinds),
        None => {
            lines.insert(line, kinds);
        }
    }
}

/// Per-line mask: `true` for a physical line that falls INSIDE a heredoc or
/// nowdoc body (between the `<<<IDENT` opener line and its closing `IDENT`
/// line), `false` everywhere else — including the opener line itself, which
/// still carries real PHP code (`$x = <<<EOT`) before the body starts.
///
/// Deliberately simple, matching this file's existing line-based scanning:
/// doesn't defend against a `<<<` that itself appears inside an unrelated
/// string literal on the same line (a separate, rarer gap) — only real
/// heredoc/nowdoc openers are expected to actually appear this way in
/// practice.
fn heredoc_body_mask(raw_lines: &[&str]) -> Vec<bool> {
    let mut mask = vec![false; raw_lines.len()];
    let mut closing_ident: Option<&str> = None;
    for (idx, line) in raw_lines.iter().enumerate() {
        if let Some(ident) = closing_ident {
            mask[idx] = true;
            if is_heredoc_closing_line(line, ident) {
                closing_ident = None;
            }
            continue;
        }
        closing_ident = find_heredoc_opener(line);
    }
    mask
}

/// If `line` opens a heredoc (`<<<IDENT`) or nowdoc (`<<<'IDENT'`/`<<<"IDENT"`),
/// return the closing identifier to watch for.
fn find_heredoc_opener(line: &str) -> Option<&str> {
    let pos = line.find("<<<")?;
    let rest = line[pos + 3..].trim_start();
    let (quote, rest) = match rest.as_bytes().first() {
        Some(b'\'') => (Some(b'\''), &rest[1..]),
        Some(b'"') => (Some(b'"'), &rest[1..]),
        _ => (None, rest),
    };
    let end = rest
        .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
        .unwrap_or(rest.len());
    let ident = &rest[..end];
    if ident.is_empty() {
        return None;
    }
    if let Some(q) = quote {
        if rest.as_bytes().get(end) != Some(&q) {
            return None;
        }
    }
    Some(ident)
}

/// Whether `line` is the closing line of a heredoc/nowdoc body started with
/// `ident` — optional leading whitespace (PHP 7.3+ flexible heredoc
/// indentation), then the identifier as a whole word (not a prefix of a
/// longer identifier).
fn is_heredoc_closing_line(line: &str, ident: &str) -> bool {
    let Some(rest) = line.trim_start().strip_prefix(ident) else {
        return false;
    };
    rest.chars()
        .next()
        .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '_')
}

/// Locate a directive's target line strictly after `idx`, as a 1-based
/// number, plus every single-line PHP 8 attribute (`#[Foo]`) line skipped
/// along the way.
///
/// Always skips blank lines and an attribute line sitting between the
/// directive and the declaration it modifies — real code, but never what a
/// suppression directive means to target (the declaration that follows).
/// The skipped attribute lines are returned too, not just discarded: an
/// issue about the attribute ITSELF (e.g. `UndefinedAttributeClass`, "this
/// attribute class does not exist") fires on the attribute's own line, not
/// the final target, and must stay covered by the same directive as the
/// declaration it annotates. When `skip_comments` is set, also skips
/// comment-only lines (`//`, `#`, `/* … */`, ` * …` docblock bodies and the
/// closing `*/`) so a directive written inside a multi-line docblock lands
/// on the declaration that follows it. Falls back to `idx + 2` when nothing
/// qualifies, so the directive still has a deterministic target.
fn next_code_line(raw_lines: &[&str], idx: usize, skip_comments: bool) -> (u32, Vec<u32>) {
    let mut extra_covered_lines = Vec::new();
    // Net `[`/`]` depth of an in-progress multi-line attribute (`#[` opener
    // whose closing `]` is on a later line) — 0 when not currently inside
    // one. Every line consumed while this is positive is itself an
    // attribute line, same treatment the single-line case already gets.
    let mut multiline_attr_depth: i32 = 0;
    for (offset, line) in raw_lines.iter().enumerate().skip(idx + 1) {
        let trimmed = line.trim();
        if multiline_attr_depth > 0 {
            extra_covered_lines.push(offset as u32 + 1);
            multiline_attr_depth += bracket_delta(trimmed);
            continue;
        }
        if trimmed.is_empty() {
            continue;
        }
        if is_attribute_only(trimmed) {
            extra_covered_lines.push(offset as u32 + 1);
            continue;
        }
        // A `#[` opener with no matching `]` on the SAME line (net positive
        // bracket delta) starts a multi-line attribute — track depth across
        // subsequent lines instead of wrongly treating this opener line as
        // the real target.
        if trimmed.starts_with("#[") {
            let delta = bracket_delta(trimmed);
            if delta > 0 {
                extra_covered_lines.push(offset as u32 + 1);
                multiline_attr_depth = delta;
                continue;
            }
        }
        if skip_comments && is_comment_only(trimmed) {
            continue;
        }
        // A declaration whose own signature spans multiple physical lines
        // (one parameter per line is a common style) still has exactly one
        // target line for suppression purposes — but a per-line issue
        // reported later in the SAME signature (e.g. `UnusedParam` on a
        // parameter several lines down) previously escaped the directive
        // entirely, since only the signature's first line was ever recorded
        // as covered. Track open/close paren depth from the target line
        // onward and keep covering every continuation line until the
        // signature's parens close.
        let target = offset as u32 + 1;
        let mut paren_depth = paren_delta(trimmed);
        let mut cont_idx = offset + 1;
        while paren_depth > 0 {
            let Some(cont_line) = raw_lines.get(cont_idx) else {
                break;
            };
            extra_covered_lines.push(cont_idx as u32 + 1);
            paren_depth += paren_delta(cont_line.trim());
            cont_idx += 1;
        }
        // A "documents the following element" directive above a function or
        // method covers its whole body in real Psalm/PHPStan semantics, not
        // just the signature line — extend coverage to every line spanned by
        // the function's own `{ ... }`, if it has one (abstract/interface
        // methods don't).
        if skip_comments && is_function_like(trimmed) {
            if let Some(body_lines) = function_body_lines(raw_lines, offset) {
                extra_covered_lines.extend(body_lines);
            }
        }
        return (target, extra_covered_lines);
    }
    (idx as u32 + 2, extra_covered_lines)
}

/// Whether a trimmed line is itself a function/method DECLARATION (after
/// skipping any leading visibility/`static`/`abstract`/`final` modifiers, the
/// next word is `function`). Used to decide whether a "documents the
/// following element" suppression directive's target has a body worth
/// extending coverage into.
///
/// Deliberately does not match on `function` appearing anywhere in the line —
/// a directive whose target statement merely CONTAINS a closure (`return
/// function () {…};`, `$cb = function () {…};`, an `array_map(function ()
/// {…}, …)` call) annotates that statement, not the closure's own nested
/// scope, so it must not be treated as covering the closure's body.
fn is_function_like(trimmed: &str) -> bool {
    const MODIFIERS: &[&str] = &[
        "public",
        "private",
        "protected",
        "static",
        "abstract",
        "final",
    ];
    for word in trimmed.split_whitespace() {
        let lower = word.to_ascii_lowercase();
        if MODIFIERS.contains(&lower.as_str()) {
            continue;
        }
        return lower == "function" || lower.starts_with("function(");
    }
    false
}

/// Physical line numbers (1-based, excluding `start_idx`'s own line) spanned
/// by a function/method body starting at 0-based `start_idx`, found by
/// scanning forward for a balanced `{`...`}` pair. Returns `None` if a bare
/// `;` terminates the declaration before any `{` appears — an abstract or
/// interface method, which has no body to extend suppression coverage into.
/// No quote-awareness, same conservative scope as `paren_delta`/`bracket_delta`:
/// a stray unmatched `{`/`}` inside a plain string literal (as opposed to
/// `"{$expr}"` interpolation, which is always balanced) could throw off depth
/// tracking — an accepted rare edge case.
fn function_body_lines(raw_lines: &[&str], start_idx: usize) -> Option<Vec<u32>> {
    let mut depth: i32 = 0;
    let mut opened = false;
    let mut covered = Vec::new();
    for (offset, line) in raw_lines.iter().enumerate().skip(start_idx) {
        for c in line.chars() {
            match c {
                '{' => {
                    depth += 1;
                    opened = true;
                }
                '}' => depth -= 1,
                ';' if !opened && depth == 0 => return None,
                _ => {}
            }
        }
        if offset != start_idx {
            covered.push(offset as u32 + 1);
        }
        if opened && depth <= 0 {
            return Some(covered);
        }
    }
    None
}

/// Net count of `(` minus `)` in `s` — no quote-awareness, matching
/// `bracket_delta`'s same conservative scope.
fn paren_delta(s: &str) -> i32 {
    s.chars().fold(0i32, |depth, c| match c {
        '(' => depth + 1,
        ')' => depth - 1,
        _ => depth,
    })
}

/// Net count of `[` minus `]` in `s` — no quote-awareness, matching the
/// same conservative scope `is_attribute_only`'s plain `ends_with(']')`
/// already accepts (real attribute argument text containing a bracket
/// inside a string literal is out of scope here).
fn bracket_delta(s: &str) -> i32 {
    s.chars().fold(0i32, |depth, c| match c {
        '[' => depth + 1,
        ']' => depth - 1,
        _ => depth,
    })
}

/// Whether a trimmed line is purely a comment (no PHP code). `#[` is treated as
/// a PHP 8 attribute (code), not a `#` comment.
fn is_comment_only(trimmed: &str) -> bool {
    trimmed.starts_with("//")
        || trimmed.starts_with("/*")
        || trimmed.starts_with('*')
        || (trimmed.starts_with('#') && !trimmed.starts_with("#["))
}

/// A single-line PHP 8 attribute (`#[Foo]`, `#[Foo(bar: 1)]`) with no other
/// code on the same line — a trailing same-line comment (`#[Foo] // note`,
/// `#[Foo] /* note */`) is stripped first so it doesn't re-defeat this
/// check (it previously required `]` to be the line's last character,
/// which a trailing comment always violates). Doesn't attempt multi-line
/// bracket-depth tracking for a `#[` that spans several lines — only the
/// common single-line case, mirroring the scope this suppression logic
/// already accepts elsewhere (e.g. no nested-comment tracking either).
fn is_attribute_only(trimmed: &str) -> bool {
    if !trimmed.starts_with("#[") {
        return false;
    }
    // Skip the leading `#` (part of the attribute marker, not a comment)
    // before scanning for a trailing comment introducer — the same
    // string-literal-aware scan `extract_comment` uses for a suppression
    // directive's own line, applied here to the attribute's line instead.
    let rest = &trimmed[1..];
    let body = match find_comment_introducer(rest) {
        Some(pos) => rest[..pos].trim_end(),
        None => rest,
    };
    body.ends_with(']')
}

/// Directive keyword table, ordered longest-first so that, e.g.,
/// `@mir-ignore-next-line` is matched before the `@mir-ignore` prefix.
///
/// Each entry is `(keyword, scope, force_all)`. `force_all` makes the directive
/// suppress every kind regardless of trailing tokens (PHPStan semantics).
const KEYWORDS: &[(&str, Scope, bool)] = &[
    ("@mir-ignore-next-line", Scope::NextLine, false),
    ("@mir-suppress-next-line", Scope::NextLine, false),
    ("@phpstan-ignore-next-line", Scope::NextLine, true),
    ("@mir-ignore-line", Scope::SameLine, false),
    ("@mir-suppress-line", Scope::SameLine, false),
    ("@phpstan-ignore-line", Scope::SameLine, true),
    ("@mir-ignore-file", Scope::File, false),
    ("@mir-suppress-file", Scope::File, false),
    // Bare forms (scope resolved below from comment position).
    ("@mir-ignore", Scope::NextLine, false),
    ("@mir-suppress", Scope::NextLine, false),
    ("@psalm-suppress", Scope::NextLine, false),
    ("@suppress", Scope::NextLine, false),
    ("@phpstan-ignore", Scope::NextLine, true),
];

/// Bare directives (no `-line`/`-next-line`/`-file` suffix) resolve their scope
/// from where the comment sits: a trailing comment annotates its own line, a
/// standalone comment annotates the statement that follows it.
const BARE_KEYWORDS: &[&str] = &[
    "@mir-ignore",
    "@mir-suppress",
    "@psalm-suppress",
    "@suppress",
    "@phpstan-ignore",
];

/// Like `parse_directive` (which is parse_directive_with_tracking discarding the tracking flag),
/// but also returns whether named suppression tracking
/// should be applied (true for `@psalm-suppress`, `@mir-suppress`, `@suppress`
/// and `@mir-ignore` forms; false for `@phpstan-*` which are blanket suppressors
/// not tied to specific issue kinds).
fn parse_directive_with_tracking(raw: &str) -> Option<(Directive, bool)> {
    let comment = extract_comment(raw)?;

    // A comment can carry more than one directive-shaped substring (e.g. a
    // user's own `@mir-ignore-line Foo` followed later by an unrelated
    // `@phpstan-ignore-next-line`) — pick whichever keyword actually appears
    // FIRST in the text, not the first entry `KEYWORDS` happens to define,
    // so an earlier table entry never shadows a later-defined keyword that
    // the author actually wrote earlier in the comment.
    let mut best: Option<(usize, &str, Scope, bool)> = None;
    for &(keyword, scope, force_all) in KEYWORDS {
        let Some(pos) = find_ci(comment.content, keyword) else {
            continue;
        };
        // Reject keyword matches that are really a prefix of a longer token
        // (e.g. `@mir-ignore` inside `@mir-ignore-line`).
        let after = &comment.content[pos + keyword.len()..];
        if after
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '-')
        {
            continue;
        }
        let is_leftmost = match best {
            None => true,
            Some((best_pos, ..)) => pos < best_pos,
        };
        if is_leftmost {
            best = Some((pos, keyword, scope, force_all));
        }
    }
    let (pos, keyword, scope, force_all) = best?;
    let after = &comment.content[pos + keyword.len()..];

    let is_bare = BARE_KEYWORDS.contains(&keyword);

    // Bare forms: a trailing comment suppresses its own line.
    let scope = if is_bare && comment.has_code_before {
        Scope::SameLine
    } else {
        scope
    };

    // The "documents the following element" forms (bare `@psalm-suppress`,
    // `@mir-ignore`, …) skip past intervening comment lines — e.g. the
    // closing `*/` of a multi-line docblock — to reach the declaration.
    // PHPStan's explicit `*-next-line` and bare `@phpstan-ignore` keep their
    // literal next-non-blank-line semantics.
    let skip_comments = scope == Scope::NextLine && is_bare && !force_all;

    let kinds = if force_all {
        KindSet::All
    } else {
        parse_kinds(after)
    };

    // Track named suppressions only for non-phpstan forms (phpstan forms
    // always suppress all kinds, so they can never be "unused for a specific kind").
    let track_named = !keyword.starts_with("@phpstan");

    Some((
        Directive {
            scope,
            kinds,
            skip_comments,
        },
        track_named,
    ))
}

/// Case-insensitive `str::find` for an ASCII directive keyword. Kind names
/// are already matched case-insensitively (`KindSet::matches`); the keyword
/// itself was still exact-case, so `@MIR-IGNORE`/`@Psalm-Suppress` silently
/// matched nothing. `to_ascii_lowercase` never changes a string's byte
/// length (only ASCII bytes are touched), so the returned index stays valid
/// against the original, non-lowercased `haystack`.
fn find_ci(haystack: &str, needle: &str) -> Option<usize> {
    haystack
        .to_ascii_lowercase()
        .find(&needle.to_ascii_lowercase())
}

struct Comment<'a> {
    /// Text from the comment introducer onward (still includes `*/`, `*`, etc.).
    content: &'a str,
    /// Whether non-whitespace code precedes the comment on the same line.
    has_code_before: bool,
}

/// Isolate the comment portion of a physical line, if any. Handles `//`, `#`
/// and `/* … */` introducers, block-comment continuation lines (` * …`) and
/// bare directive lines inside block comments (`@psalm-suppress …`).
fn extract_comment(raw: &str) -> Option<Comment<'_>> {
    let trimmed = raw.trim_start();

    // Block-comment continuation or a bare directive line: no code precedes it.
    if trimmed.starts_with('*') {
        return Some(Comment {
            content: trimmed.trim_start_matches('*'),
            has_code_before: false,
        });
    }
    if trimmed.starts_with('@') {
        return Some(Comment {
            content: trimmed,
            has_code_before: false,
        });
    }

    // Earliest single-line / block introducer on the line, skipping any
    // that fall inside a quoted string literal — `$x = "// not a
    // comment";` previously matched `raw.find("//")` regardless, wrongly
    // treating a plain string-literal statement as carrying a trailing
    // suppression comment. Only a same-line string is handled here (a
    // bounded, quote-toggle scan); a heredoc/multi-line string body stays
    // unrecognized, same as before — that needs cross-line state this
    // line-at-a-time scanner doesn't have.
    let pos = find_comment_introducer(raw)?;
    let has_code_before = !raw[..pos].trim().is_empty();
    Some(Comment {
        content: &raw[pos..],
        has_code_before,
    })
}

/// Byte offset of the earliest `//`, `#`, or `/*` comment introducer in
/// `raw`, ignoring any that fall inside a single- or double-quoted string
/// literal (with backslash-escape awareness). Returns `None` if the line
/// has no real comment introducer at all.
fn find_comment_introducer(raw: &str) -> Option<usize> {
    let bytes = raw.as_bytes();
    let mut in_squote = false;
    let mut in_dquote = false;
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        if in_squote {
            i += if c == b'\\' && i + 1 < bytes.len() {
                2
            } else {
                if c == b'\'' {
                    in_squote = false;
                }
                1
            };
            continue;
        }
        if in_dquote {
            i += if c == b'\\' && i + 1 < bytes.len() {
                2
            } else {
                if c == b'"' {
                    in_dquote = false;
                }
                1
            };
            continue;
        }
        match c {
            b'\'' => in_squote = true,
            b'"' => in_dquote = true,
            b'/' if bytes.get(i + 1) == Some(&b'/') || bytes.get(i + 1) == Some(&b'*') => {
                return Some(i);
            }
            // `#[` is a PHP 8 attribute opener, not a `#` line comment (see
            // `is_comment_only`'s identical carve-out) — keep scanning past
            // it instead of stopping here, so a REAL trailing comment after
            // the attribute (`#[Attr] // note`) is still found.
            b'#' if bytes.get(i + 1) == Some(&b'[') => {}
            b'#' => return Some(i),
            _ => {}
        }
        i += 1;
    }
    None
}

/// Collect issue kind names/codes following a directive keyword. Kinds are
/// comma-separated (`Foo, Bar`); only the FIRST whitespace-delimited word of
/// each comma-separated segment can be a kind name — every further word in
/// that same segment is treated as free-text prose (e.g. a trailing
/// explanation like `UndefinedClass because of a vendor stub`), not another
/// kind, since a real multi-kind list always uses a comma to continue. Once a
/// segment has trailing words after its kind name, everything from there on
/// — including later comma-separated segments — is that same free-text
/// prose, so a comma inside the prose (`Foo because of X, not fully typed`)
/// must not be mistaken for the start of another kind. Stops entirely at the
/// block-comment terminator. An empty result means "all kinds".
fn parse_kinds(rest: &str) -> KindSet {
    let mut set = FxHashSet::default();
    'segments: for segment in rest.split(',') {
        let mut tokens = segment
            .split([' ', '\t'])
            .map(str::trim)
            .filter(|t| !t.is_empty());
        for token in tokens.by_ref() {
            // End of the comment / docblock — stop scanning entirely.
            if token.starts_with("*/") || token.starts_with('*') {
                break 'segments;
            }
            // A kind name is alphanumeric (plus `_`); anything else is
            // skipped, keeping the next token as the segment's candidate.
            if token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
                set.insert(token.to_string());
                if tokens.next().is_some() {
                    // Trailing prose follows in this segment — the rest of
                    // the comment, comma or not, is that same free text.
                    break 'segments;
                }
                continue 'segments;
            }
        }
    }
    if set.is_empty() {
        KindSet::All
    } else {
        KindSet::Named(set)
    }
}

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

    fn map(src: &str) -> SuppressionMap {
        SuppressionMap::from_source(src)
    }

    #[test]
    fn line_comment_above_statement_suppresses_next_line() {
        // line 2 comment → suppress line 3
        let m = map("<?php\n// @psalm-suppress UndefinedClass\nnew NoSuchClass();\n");
        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
        assert!(!m.is_suppressed(2, "UndefinedClass", "MIR0000"));
    }

    #[test]
    fn trailing_comment_suppresses_own_line() {
        let m = map("<?php\nnew NoSuchClass(); // @mir-ignore UndefinedClass\n");
        assert!(m.is_suppressed(2, "UndefinedClass", "MIR0000"));
    }

    #[test]
    fn single_line_docblock_above_statement() {
        let m = map("<?php\n/** @psalm-suppress UndefinedClass */\nnew NoSuchClass();\n");
        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
    }

    #[test]
    fn phpstan_ignore_next_line_suppresses_all() {
        let m = map("<?php\n// @phpstan-ignore-next-line\nnew NoSuchClass();\n");
        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
        assert!(m.is_suppressed(3, "AnyOtherKind", "MIR9999"));
    }

    #[test]
    fn ignore_line_targets_own_line() {
        let m = map("<?php\nnew NoSuchClass(); // @mir-ignore-line\n");
        assert!(m.is_suppressed(2, "UndefinedClass", "MIR0000"));
    }

    #[test]
    fn next_line_skips_blank_lines() {
        let m = map("<?php\n/** @psalm-suppress UndefinedClass */\n\n\nnew NoSuchClass();\n");
        assert!(m.is_suppressed(5, "UndefinedClass", "MIR0000"));
    }

    #[test]
    fn multiline_docblock_skips_to_declaration() {
        // line 2: /**, line 3: * @psalm-suppress, line 4: */, line 5: declaration.
        let src =
            "<?php\n/**\n * @psalm-suppress UnusedMethod\n */\nprivate function a(): void {}\n";
        let m = map(src);
        assert!(m.is_suppressed(5, "UnusedMethod", "MIR0000"));
    }

    #[test]
    fn phpstan_next_line_is_literal_not_comment_skipping() {
        // PHPStan's -next-line targets the next non-blank line even if it's a
        // comment; it does not hunt for the next code line.
        let m = map("<?php\n// @phpstan-ignore-next-line\n// unrelated comment\nfoo();\n");
        assert!(m.is_suppressed(3, "X", "MIR0000"));
        assert!(!m.is_suppressed(4, "X", "MIR0000"));
    }

    #[test]
    fn named_kind_does_not_suppress_other_kinds() {
        let m = map("<?php\n// @mir-ignore UndefinedClass\nfoo();\n");
        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
        assert!(!m.is_suppressed(3, "UndefinedFunction", "MIR0001"));
    }

    #[test]
    fn match_by_code() {
        let m = map("<?php\n// @mir-ignore MIR1400\nfoo();\n");
        assert!(m.is_suppressed(3, "ParseError", "MIR1400"));
    }

    #[test]
    fn file_scope_suppresses_every_line() {
        let m = map("<?php // @mir-ignore-file UndefinedClass\nfoo();\nbar();\n");
        assert!(m.is_suppressed(2, "UndefinedClass", "MIR0000"));
        assert!(m.is_suppressed(99, "UndefinedClass", "MIR0000"));
        assert!(!m.is_suppressed(2, "UndefinedFunction", "MIR0001"));
    }

    #[test]
    fn multiple_kinds_one_directive() {
        let m = map("<?php\n// @psalm-suppress UndefinedClass, NullMethodCall\nfoo();\n");
        assert!(m.is_suppressed(3, "UndefinedClass", "MIR0000"));
        assert!(m.is_suppressed(3, "NullMethodCall", "MIR0001"));
    }

    #[test]
    fn no_directive_is_empty() {
        let m = map("<?php\n$x = \"@psalm-suppress not a comment\";\nfoo();\n");
        // It's inside a string but after `//`? No `//` here, so not detected.
        assert!(m.is_empty());
    }

    #[test]
    fn prefix_is_not_confused_with_longer_keyword() {
        // `@mir-ignore-next-line` must be parsed as next-line, not bare same-line.
        let m = map("<?php\nfoo(); // @mir-ignore-next-line\nbar();\n");
        assert!(m.is_suppressed(3, "AnyKind", "MIR0000"));
        assert!(!m.is_suppressed(2, "AnyKind", "MIR0000"));
    }
}