Skip to main content

mago_reporting/
lib.rs

1#![allow(clippy::pub_use, clippy::exhaustive_enums)]
2
3//! Issue reporting and formatting for Mago.
4//!
5//! This crate provides functionality for reporting code issues identified by the linter and analyzer.
6//! It includes support for multiple output formats, baseline filtering, and rich terminal output.
7//!
8//! # Core Types
9//!
10//! - [`Issue`]: Represents a single code issue with severity level, annotations, and optional fixes
11//! - [`IssueCollection`]: A collection of issues with filtering and sorting capabilities
12//! - [`reporter::Reporter`]: Handles formatting and outputting issues in various formats
13//! - [`baseline::Baseline`]: Manages baseline files to filter out known issues
14
15use std::borrow::Cow;
16use std::cmp::Ordering;
17use std::collections::hash_map::Entry;
18use std::iter::Once;
19use std::str::FromStr;
20
21use foldhash::HashMap;
22use foldhash::HashMapExt;
23use regex::Regex;
24use schemars::JsonSchema;
25use strum::Display;
26use strum::VariantNames;
27
28use mago_database::GlobSettings;
29use mago_database::file::FileId;
30use mago_database::matcher::ExclusionMatcher;
31use mago_span::Span;
32use mago_text_edit::TextEdit;
33
34mod formatter;
35#[cfg(feature = "serde")]
36mod internal;
37
38pub mod baseline;
39pub mod color;
40pub mod error;
41pub mod output;
42pub mod reporter;
43
44pub use color::ColorChoice;
45pub use formatter::ReportingFormat;
46pub use formatter::utils::osc8_file_hyperlink;
47pub use formatter::utils::osc8_hyperlink;
48pub use output::ReportingTarget;
49
50/// Represents an entry in the analyzer's `ignore` configuration.
51///
52/// One of three shapes:
53///
54/// * A plain code string ignored everywhere: `"code1"`.
55/// * A code scoped to one or more paths/globs:
56///   `{ code = "code2", in = ["tests/", "src/**/*.php"] }`.
57/// * A regex pattern matched against the issue's textual content
58///   (title, notes, help, and annotation messages), optionally narrowed
59///   by `code` and/or `in`:
60///   `{ pattern = "Symfony", code = "mixed-assignment" }`.
61///
62/// Path entries accept both plain directory/file prefixes (e.g. `"tests/"`,
63/// `"src/Legacy.php"`) and glob patterns (e.g. `"src/**/*.php"`); entries
64/// containing any of `*`, `?`, `[`, `{` are matched with [`ExclusionMatcher`].
65///
66/// The `pattern` field is a [bare Rust regex](https://docs.rs/regex/) — use
67/// `(?i)` for case-insensitive matching. No surrounding delimiters.
68#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70#[cfg_attr(feature = "serde", serde(untagged))]
71pub enum IgnoreEntry {
72    /// Ignore a code everywhere: `"code1"`
73    Code(String),
74    /// Ignore by regex against issue text, with optional code and path scoping:
75    /// `{ pattern = "Symfony", code = "mixed-assignment", in = ["src/Bridge/"] }`.
76    Pattern {
77        /// A bare regex tested against the issue's title, annotation messages,
78        /// notes, and help message, in that order. First match short-circuits.
79        /// The most instance-specific text is searched first (title,
80        /// annotations); notes and help are tested last because they are
81        /// typically templated per rule.
82        pattern: String,
83        /// Optional code to narrow the match. When set, only issues with this
84        /// code are tested against the pattern.
85        #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
86        code: Option<String>,
87        /// Optional paths/globs to narrow the match.
88        #[cfg_attr(
89            feature = "serde",
90            serde(
91                rename = "in",
92                default,
93                skip_serializing_if = "Option::is_none",
94                deserialize_with = "opt_one_or_many"
95            )
96        )]
97        paths: Option<Vec<String>>,
98    },
99    /// Ignore a code in specific paths or glob patterns:
100    /// `{ code = "code2", in = ["tests/", "src/**/*.php"] }`
101    Scoped {
102        code: String,
103        #[cfg_attr(feature = "serde", serde(rename = "in", deserialize_with = "one_or_many"))]
104        paths: Vec<String>,
105    },
106}
107
108#[cfg(feature = "serde")]
109fn one_or_many<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
110where
111    D: serde::Deserializer<'de>,
112{
113    #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
114    #[cfg_attr(feature = "serde", serde(untagged))]
115    enum OneOrMany {
116        One(String),
117        Many(Vec<String>),
118    }
119
120    match <OneOrMany as serde::Deserialize>::deserialize(deserializer)? {
121        OneOrMany::One(s) => Ok(vec![s]),
122        OneOrMany::Many(v) => Ok(v),
123    }
124}
125
126#[cfg(feature = "serde")]
127fn opt_one_or_many<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
128where
129    D: serde::Deserializer<'de>,
130{
131    Ok(Some(one_or_many(deserializer)?))
132}
133
134/// Pre-compiled ignore entries ready for use by [`IssueCollection::filter_out_ignored`].
135///
136/// Build once per analysis (regex compilation and glob building are non-trivial),
137/// then reuse across watch-mode rebuilds and LSP analyses. Entries with invalid
138/// regex or invalid glob patterns are logged and skipped — a bad config line
139/// silently drops that entry rather than crashing the run.
140#[derive(Debug, Default)]
141pub struct CompiledIgnoreSet {
142    entries: Vec<CompiledIgnoreEntry>,
143}
144
145#[derive(Debug)]
146enum CompiledIgnoreEntry {
147    Code(String),
148    Scoped { code: String, matcher: ExclusionMatcher<String> },
149    Pattern { regex: Regex, code: Option<String>, matcher: Option<ExclusionMatcher<String>> },
150}
151
152/// Represents the kind of annotation associated with an issue.
153#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd)]
154#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
155pub enum AnnotationKind {
156    /// A primary annotation, typically highlighting the main source of the issue.
157    Primary,
158    /// A secondary annotation, providing additional context or related information.
159    Secondary,
160}
161
162/// An annotation associated with an issue, providing additional context or highlighting specific code spans.
163#[derive(Debug, PartialEq, Eq, Ord, Clone, Hash, PartialOrd)]
164#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
165pub struct Annotation {
166    /// An optional message associated with the annotation.
167    pub message: Option<Cow<'static, str>>,
168    /// The kind of annotation.
169    pub kind: AnnotationKind,
170    /// The code span that the annotation refers to.
171    pub span: Span,
172}
173
174/// Represents the severity level of an issue.
175#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Display, VariantNames, JsonSchema)]
176#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
177#[strum(serialize_all = "lowercase")]
178pub enum Level {
179    /// A note, providing additional information or context.
180    #[cfg_attr(feature = "serde", serde(alias = "note"))]
181    Note,
182    /// A help message, suggesting possible solutions or further actions.
183    #[cfg_attr(feature = "serde", serde(alias = "help"))]
184    Help,
185    /// A warning, indicating a potential problem that may need attention.
186    #[cfg_attr(feature = "serde", serde(alias = "warning", alias = "warn"))]
187    Warning,
188    /// An error, indicating a problem that prevents the code from functioning correctly.
189    #[cfg_attr(feature = "serde", serde(alias = "error", alias = "err"))]
190    Error,
191}
192
193impl FromStr for Level {
194    type Err = ();
195
196    fn from_str(s: &str) -> Result<Self, Self::Err> {
197        match s.to_lowercase().as_str() {
198            "note" => Ok(Self::Note),
199            "help" => Ok(Self::Help),
200            "warning" => Ok(Self::Warning),
201            "error" => Ok(Self::Error),
202            _ => Err(()),
203        }
204    }
205}
206
207type IssueEdits = Vec<TextEdit>;
208type IssueEditBatches = Vec<(Option<String>, IssueEdits)>;
209
210/// Represents an issue identified in the code.
211#[derive(Debug, Clone, Eq, PartialEq)]
212#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
213pub struct Issue {
214    /// The severity level of the issue.
215    pub level: Level,
216    /// An optional code associated with the issue.
217    pub code: Option<String>,
218    /// The main message describing the issue.
219    pub message: Cow<'static, str>,
220    /// Additional notes related to the issue.
221    pub notes: Vec<Cow<'static, str>>,
222    /// An optional help message suggesting possible solutions or further actions.
223    pub help: Option<Cow<'static, str>>,
224    /// An optional link to external resources for more information about the issue.
225    pub link: Option<String>,
226    /// Annotations associated with the issue, providing additional context or highlighting specific code spans.
227    pub annotations: Vec<Annotation>,
228    /// Text edits that can be applied to fix the issue, grouped by file.
229    pub edits: HashMap<FileId, IssueEdits>,
230}
231
232/// A collection of issues.
233#[derive(Debug, Clone, Eq, PartialEq)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235pub struct IssueCollection {
236    issues: Vec<Issue>,
237}
238
239impl AnnotationKind {
240    /// Returns `true` if this annotation kind is primary.
241    #[inline]
242    #[must_use]
243    pub const fn is_primary(&self) -> bool {
244        matches!(self, AnnotationKind::Primary)
245    }
246
247    /// Returns `true` if this annotation kind is secondary.
248    #[inline]
249    #[must_use]
250    pub const fn is_secondary(&self) -> bool {
251        matches!(self, AnnotationKind::Secondary)
252    }
253}
254
255impl CompiledIgnoreSet {
256    /// Compiles the given ignore entries into a reusable matcher set.
257    ///
258    /// Bad regex/glob entries are reported via `tracing::error!` and skipped;
259    /// the returned set still contains the valid entries.
260    #[must_use]
261    pub fn compile(entries: &[IgnoreEntry], glob: GlobSettings) -> Self {
262        let mut compiled = Vec::with_capacity(entries.len());
263        for entry in entries {
264            match entry {
265                IgnoreEntry::Code(code) => compiled.push(CompiledIgnoreEntry::Code(code.clone())),
266                IgnoreEntry::Scoped { code, paths } => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
267                    Ok(matcher) => compiled.push(CompiledIgnoreEntry::Scoped { code: code.clone(), matcher }),
268                    Err(err) => {
269                        tracing::error!("Failed to compile ignore patterns for `{code}`: {err}. Entry will be skipped.")
270                    }
271                },
272                IgnoreEntry::Pattern { pattern, code, paths } => {
273                    let regex = match Regex::new(pattern) {
274                        Ok(regex) => regex,
275                        Err(err) => {
276                            tracing::error!(
277                                "Failed to compile ignore regex `{pattern}`: {err}. Entry will be skipped."
278                            );
279
280                            continue;
281                        }
282                    };
283
284                    let matcher = match paths {
285                        Some(paths) => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
286                            Ok(matcher) => Some(matcher),
287                            Err(err) => {
288                                tracing::error!(
289                                    "Failed to compile ignore paths for regex `{pattern}`: {err}. Entry will be skipped."
290                                );
291
292                                continue;
293                            }
294                        },
295                        None => None,
296                    };
297
298                    compiled.push(CompiledIgnoreEntry::Pattern { regex, code: code.clone(), matcher });
299                }
300            }
301        }
302
303        Self { entries: compiled }
304    }
305
306    #[must_use]
307    pub fn is_empty(&self) -> bool {
308        self.entries.is_empty()
309    }
310
311    #[must_use]
312    pub fn len(&self) -> usize {
313        self.entries.len()
314    }
315}
316
317impl Annotation {
318    /// Creates a new annotation with the given kind and span.
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// use mago_reporting::{Annotation, AnnotationKind};
324    /// use mago_database::file::FileId;
325    /// use mago_span::Span;
326    /// use mago_span::Position;
327    ///
328    /// let file = FileId::zero();
329    /// let start = Position::new(0);
330    /// let end = Position::new(5);
331    /// let span = Span::new(file, start, end);
332    /// let annotation = Annotation::new(AnnotationKind::Primary, span);
333    /// ```
334    #[must_use]
335    pub fn new(kind: AnnotationKind, span: Span) -> Self {
336        Self { message: None, kind, span }
337    }
338
339    /// Creates a new primary annotation with the given span.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use mago_reporting::{Annotation, AnnotationKind};
345    /// use mago_database::file::FileId;
346    /// use mago_span::Span;
347    /// use mago_span::Position;
348    ///
349    /// let file = FileId::zero();
350    /// let start = Position::new(0);
351    /// let end = Position::new(5);
352    /// let span = Span::new(file, start, end);
353    /// let annotation = Annotation::primary(span);
354    /// ```
355    #[must_use]
356    pub fn primary(span: Span) -> Self {
357        Self::new(AnnotationKind::Primary, span)
358    }
359
360    /// Creates a new secondary annotation with the given span.
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// use mago_reporting::{Annotation, AnnotationKind};
366    /// use mago_database::file::FileId;
367    /// use mago_span::Span;
368    /// use mago_span::Position;
369    ///
370    /// let file = FileId::zero();
371    /// let start = Position::new(0);
372    /// let end = Position::new(5);
373    /// let span = Span::new(file, start, end);
374    /// let annotation = Annotation::secondary(span);
375    /// ```
376    #[must_use]
377    pub fn secondary(span: Span) -> Self {
378        Self::new(AnnotationKind::Secondary, span)
379    }
380
381    /// Sets the message of this annotation.
382    ///
383    /// # Examples
384    ///
385    /// ```
386    /// use mago_reporting::{Annotation, AnnotationKind};
387    /// use mago_database::file::FileId;
388    /// use mago_span::Span;
389    /// use mago_span::Position;
390    ///
391    /// let file = FileId::zero();
392    /// let start = Position::new(0);
393    /// let end = Position::new(5);
394    /// let span = Span::new(file, start, end);
395    /// let annotation = Annotation::primary(span).with_message("This is a primary annotation");
396    /// ```
397    #[must_use]
398    pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
399        self.message = Some(message.into());
400
401        self
402    }
403
404    /// Returns `true` if this annotation is a primary annotation.
405    #[must_use]
406    pub fn is_primary(&self) -> bool {
407        self.kind == AnnotationKind::Primary
408    }
409}
410
411impl Level {
412    /// Downgrades the level to the next lower severity.
413    ///
414    /// This function maps levels to their less severe counterparts:
415    ///
416    /// - `Error` becomes `Warning`
417    /// - `Warning` becomes `Help`
418    /// - `Help` becomes `Note`
419    /// - `Note` remains as `Note`
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// use mago_reporting::Level;
425    ///
426    /// let level = Level::Error;
427    /// assert_eq!(level.downgrade(), Level::Warning);
428    ///
429    /// let level = Level::Warning;
430    /// assert_eq!(level.downgrade(), Level::Help);
431    ///
432    /// let level = Level::Help;
433    /// assert_eq!(level.downgrade(), Level::Note);
434    ///
435    /// let level = Level::Note;
436    /// assert_eq!(level.downgrade(), Level::Note);
437    /// ```
438    #[must_use]
439    pub fn downgrade(&self) -> Self {
440        match self {
441            Level::Error => Level::Warning,
442            Level::Warning => Level::Help,
443            Level::Help | Level::Note => Level::Note,
444        }
445    }
446}
447
448impl Issue {
449    /// Creates a new issue with the given level and message.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// use mago_reporting::{Issue, Level};
455    ///
456    /// let issue = Issue::new(Level::Error, "This is an error");
457    /// ```
458    pub fn new(level: Level, message: impl Into<Cow<'static, str>>) -> Self {
459        Self {
460            level,
461            code: None,
462            message: message.into(),
463            annotations: Vec::new(),
464            notes: Vec::new(),
465            help: None,
466            link: None,
467            edits: HashMap::default(),
468        }
469    }
470
471    /// Creates a new error issue with the given message.
472    ///
473    /// # Examples
474    ///
475    /// ```
476    /// use mago_reporting::Issue;
477    ///
478    /// let issue = Issue::error("This is an error");
479    /// ```
480    pub fn error(message: impl Into<Cow<'static, str>>) -> Self {
481        Self::new(Level::Error, message)
482    }
483
484    /// Creates a new warning issue with the given message.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use mago_reporting::Issue;
490    ///
491    /// let issue = Issue::warning("This is a warning");
492    /// ```
493    pub fn warning(message: impl Into<Cow<'static, str>>) -> Self {
494        Self::new(Level::Warning, message)
495    }
496
497    /// Creates a new help issue with the given message.
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use mago_reporting::Issue;
503    ///
504    /// let issue = Issue::help("This is a help message");
505    /// ```
506    pub fn help(message: impl Into<Cow<'static, str>>) -> Self {
507        Self::new(Level::Help, message)
508    }
509
510    /// Creates a new note issue with the given message.
511    ///
512    /// # Examples
513    ///
514    /// ```
515    /// use mago_reporting::Issue;
516    ///
517    /// let issue = Issue::note("This is a note");
518    /// ```
519    pub fn note(message: impl Into<Cow<'static, str>>) -> Self {
520        Self::new(Level::Note, message)
521    }
522
523    /// Adds a code to this issue.
524    ///
525    /// # Examples
526    ///
527    /// ```
528    /// use mago_reporting::{Issue, Level};
529    ///
530    /// let issue = Issue::error("This is an error").with_code("E0001");
531    /// ```
532    #[must_use]
533    pub fn with_code(mut self, code: impl Into<String>) -> Self {
534        self.code = Some(code.into());
535
536        self
537    }
538
539    /// Add an annotation to this issue.
540    ///
541    /// # Examples
542    ///
543    /// ```
544    /// use mago_reporting::{Issue, Annotation, AnnotationKind};
545    /// use mago_database::file::FileId;
546    /// use mago_span::Span;
547    /// use mago_span::Position;
548    ///
549    /// let file = FileId::zero();
550    /// let start = Position::new(0);
551    /// let end = Position::new(5);
552    /// let span = Span::new(file, start, end);
553    ///
554    /// let issue = Issue::error("This is an error").with_annotation(Annotation::primary(span));
555    /// ```
556    #[must_use]
557    pub fn with_annotation(mut self, annotation: Annotation) -> Self {
558        self.annotations.push(annotation);
559
560        self
561    }
562
563    #[must_use]
564    pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
565        self.annotations.extend(annotation);
566
567        self
568    }
569
570    /// Returns the deterministic primary annotation for this issue.
571    ///
572    /// If multiple primary annotations exist, the one with the smallest span is returned.
573    #[must_use]
574    pub fn primary_annotation(&self) -> Option<&Annotation> {
575        self.annotations.iter().filter(|annotation| annotation.is_primary()).min_by_key(|annotation| annotation.span)
576    }
577
578    /// Returns the deterministic primary span for this issue.
579    #[must_use]
580    pub fn primary_span(&self) -> Option<Span> {
581        self.primary_annotation().map(|annotation| annotation.span)
582    }
583
584    /// Add a note to this issue.
585    ///
586    /// # Examples
587    ///
588    /// ```
589    /// use mago_reporting::Issue;
590    ///
591    /// let issue = Issue::error("This is an error").with_note("This is a note");
592    /// ```
593    #[must_use]
594    pub fn with_note(mut self, note: impl Into<Cow<'static, str>>) -> Self {
595        self.notes.push(note.into());
596
597        self
598    }
599
600    /// Add a help message to this issue.
601    ///
602    /// This is useful for providing additional context to the user on how to resolve the issue.
603    ///
604    /// # Examples
605    ///
606    /// ```
607    /// use mago_reporting::Issue;
608    ///
609    /// let issue = Issue::error("This is an error").with_help("This is a help message");
610    /// ```
611    #[must_use]
612    pub fn with_help(mut self, help: impl Into<Cow<'static, str>>) -> Self {
613        self.help = Some(help.into());
614
615        self
616    }
617
618    /// Add a link to this issue.
619    ///
620    /// # Examples
621    ///
622    /// ```
623    /// use mago_reporting::Issue;
624    ///
625    /// let issue = Issue::error("This is an error").with_link("https://example.com");
626    /// ```
627    #[must_use]
628    pub fn with_link(mut self, link: impl Into<String>) -> Self {
629        self.link = Some(link.into());
630
631        self
632    }
633
634    /// Add a single edit to this issue.
635    #[must_use]
636    pub fn with_edit(mut self, file_id: FileId, edit: TextEdit) -> Self {
637        self.edits.entry(file_id).or_default().push(edit);
638
639        self
640    }
641
642    /// Add multiple edits to this issue.
643    #[must_use]
644    pub fn with_file_edits(mut self, file_id: FileId, edits: IssueEdits) -> Self {
645        if !edits.is_empty() {
646            match self.edits.entry(file_id) {
647                Entry::Vacant(entry) => {
648                    entry.insert(edits);
649                }
650                Entry::Occupied(mut entry) => entry.get_mut().extend(edits),
651            }
652        }
653
654        self
655    }
656
657    /// Take the edits from this issue.
658    #[must_use]
659    pub fn take_edits(&mut self) -> HashMap<FileId, IssueEdits> {
660        std::mem::replace(&mut self.edits, HashMap::new())
661    }
662}
663
664impl IssueCollection {
665    #[must_use]
666    pub fn new() -> Self {
667        Self { issues: Vec::new() }
668    }
669
670    pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
671        Self { issues: issues.into_iter().collect() }
672    }
673
674    pub fn push(&mut self, issue: Issue) {
675        self.issues.push(issue);
676    }
677
678    pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
679        self.issues.extend(issues);
680    }
681
682    pub fn reserve(&mut self, additional: usize) {
683        self.issues.reserve(additional);
684    }
685
686    pub fn shrink_to_fit(&mut self) {
687        self.issues.shrink_to_fit();
688    }
689
690    #[must_use]
691    pub fn is_empty(&self) -> bool {
692        self.issues.is_empty()
693    }
694
695    #[must_use]
696    pub fn len(&self) -> usize {
697        self.issues.len()
698    }
699
700    /// Filters the issues in the collection to only include those with a severity level
701    /// lower than or equal to the given level.
702    #[must_use]
703    pub fn with_maximum_level(self, level: Level) -> Self {
704        Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
705    }
706
707    /// Filters the issues in the collection to only include those with a severity level
708    ///  higher than or equal to the given level.
709    #[must_use]
710    pub fn with_minimum_level(self, level: Level) -> Self {
711        Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
712    }
713
714    /// Returns `true` if the collection contains any issues with a severity level
715    ///  higher than or equal to the given level.
716    #[must_use]
717    pub fn has_minimum_level(&self, level: Level) -> bool {
718        self.issues.iter().any(|issue| issue.level >= level)
719    }
720
721    /// Returns the number of issues in the collection with the given severity level.
722    #[must_use]
723    pub fn get_level_count(&self, level: Level) -> usize {
724        self.issues.iter().filter(|issue| issue.level == level).count()
725    }
726
727    /// Returns the highest severity level of the issues in the collection.
728    #[must_use]
729    pub fn get_highest_level(&self) -> Option<Level> {
730        self.issues.iter().map(|issue| issue.level).max()
731    }
732
733    /// Returns the lowest severity level of the issues in the collection.
734    #[must_use]
735    pub fn get_lowest_level(&self) -> Option<Level> {
736        self.issues.iter().map(|issue| issue.level).min()
737    }
738
739    pub fn filter_out_ignored<F>(&mut self, set: &CompiledIgnoreSet, resolve_file_name: F)
740    where
741        F: Fn(FileId) -> Option<String>,
742    {
743        if set.is_empty() {
744            return;
745        }
746
747        self.issues.retain(|issue| {
748            let mut cached_path: Option<Option<String>> = None;
749            let mut resolve_path = |issue: &Issue| -> Option<String> {
750                cached_path
751                    .get_or_insert_with(|| issue.primary_span().and_then(|span| resolve_file_name(span.file_id)))
752                    .clone()
753            };
754
755            for entry in &set.entries {
756                match entry {
757                    CompiledIgnoreEntry::Code(ignored_code) => {
758                        if let Some(code) = &issue.code
759                            && ignored_code == code
760                        {
761                            return false;
762                        }
763                    }
764                    CompiledIgnoreEntry::Scoped { code: ignored_code, matcher } => {
765                        let Some(code) = &issue.code else {
766                            continue;
767                        };
768
769                        if ignored_code != code {
770                            continue;
771                        }
772
773                        if let Some(name) = resolve_path(issue)
774                            && matcher.is_match(&name)
775                        {
776                            return false;
777                        }
778                    }
779                    CompiledIgnoreEntry::Pattern { regex, code: ignored_code, matcher } => {
780                        if let Some(ignored_code) = ignored_code {
781                            let Some(code) = &issue.code else {
782                                continue;
783                            };
784
785                            if ignored_code != code {
786                                continue;
787                            }
788                        }
789
790                        if let Some(matcher) = matcher {
791                            let Some(name) = resolve_path(issue) else {
792                                continue;
793                            };
794
795                            if !matcher.is_match(&name) {
796                                continue;
797                            }
798                        }
799
800                        if issue_text_matches(issue, regex) {
801                            return false;
802                        }
803                    }
804                }
805            }
806
807            true
808        });
809    }
810
811    pub fn filter_retain_codes(&mut self, retain_codes: &[String]) {
812        self.issues.retain(|issue| if let Some(code) = &issue.code { retain_codes.contains(code) } else { false });
813    }
814
815    pub fn take_edits(&mut self) -> impl Iterator<Item = (FileId, IssueEdits)> + '_ {
816        self.issues.iter_mut().flat_map(|issue| issue.take_edits().into_iter())
817    }
818
819    /// Filters the issues in the collection to only include those that have associated edits.
820    #[must_use]
821    pub fn with_edits(self) -> Self {
822        Self { issues: self.issues.into_iter().filter(|issue| !issue.edits.is_empty()).collect() }
823    }
824
825    /// Sorts the issues in the collection.
826    ///
827    /// The issues are sorted by severity level in ascending order,
828    /// then by code in ascending order, and finally by the primary annotation span.
829    #[must_use]
830    pub fn sorted(self) -> Self {
831        let mut issues = self.issues;
832
833        issues.sort_by(|a, b| match a.level.cmp(&b.level) {
834            Ordering::Greater => Ordering::Greater,
835            Ordering::Less => Ordering::Less,
836            Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
837                Ordering::Less => Ordering::Less,
838                Ordering::Greater => Ordering::Greater,
839                Ordering::Equal => {
840                    let a_span = a.primary_span();
841                    let b_span = b.primary_span();
842
843                    match (a_span, b_span) {
844                        (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
845                        (Some(_), None) => Ordering::Less,
846                        (None, Some(_)) => Ordering::Greater,
847                        (None, None) => Ordering::Equal,
848                    }
849                }
850            },
851        });
852
853        Self { issues }
854    }
855
856    pub fn iter(&self) -> impl Iterator<Item = &Issue> {
857        self.issues.iter()
858    }
859
860    /// Converts the collection into a map of edit batches grouped by file.
861    ///
862    /// Each batch contains all edits from a single issue along with the rule code.
863    /// All edits from an issue must be applied together as a batch to maintain code validity.
864    ///
865    /// Returns `HashMap<FileId, Vec<(Option<String>, IssueEdits)>>` where each tuple
866    /// is (rule_code, edits_for_that_issue).
867    #[must_use]
868    pub fn to_edit_batches(self) -> HashMap<FileId, IssueEditBatches> {
869        let mut result: HashMap<FileId, Vec<(Option<String>, IssueEdits)>> = HashMap::default();
870        for issue in self.issues.into_iter().filter(|issue| !issue.edits.is_empty()) {
871            let code = issue.code;
872            for (file_id, edit_list) in issue.edits {
873                result.entry(file_id).or_default().push((code.clone(), edit_list));
874            }
875        }
876
877        result
878    }
879}
880
881/// Returns `true` when any of the issue's textual fields matches the regex.
882///
883/// Tested in order: title, annotation messages, notes, help. The most
884/// instance-specific fields are searched first; notes and help are last
885/// because they are typically templated per rule.
886fn issue_text_matches(issue: &Issue, regex: &Regex) -> bool {
887    if regex.is_match(&issue.message) {
888        return true;
889    }
890
891    if issue
892        .annotations
893        .iter()
894        .any(|annotation| annotation.message.as_ref().is_some_and(|message| regex.is_match(message)))
895    {
896        return true;
897    }
898
899    if issue.notes.iter().any(|note| regex.is_match(note)) {
900        return true;
901    }
902
903    issue.help.as_ref().is_some_and(|help| regex.is_match(help))
904}
905
906impl IntoIterator for IssueCollection {
907    type Item = Issue;
908
909    type IntoIter = std::vec::IntoIter<Issue>;
910
911    fn into_iter(self) -> Self::IntoIter {
912        self.issues.into_iter()
913    }
914}
915
916impl<'collection> IntoIterator for &'collection IssueCollection {
917    type Item = &'collection Issue;
918
919    type IntoIter = std::slice::Iter<'collection, Issue>;
920
921    fn into_iter(self) -> Self::IntoIter {
922        self.issues.iter()
923    }
924}
925
926impl Default for IssueCollection {
927    fn default() -> Self {
928        Self::new()
929    }
930}
931
932impl IntoIterator for Issue {
933    type Item = Issue;
934    type IntoIter = Once<Issue>;
935
936    fn into_iter(self) -> Self::IntoIter {
937        std::iter::once(self)
938    }
939}
940
941impl FromIterator<Issue> for IssueCollection {
942    fn from_iter<T>(iter: T) -> Self
943    where
944        T: IntoIterator<Item = Issue>,
945    {
946        Self { issues: iter.into_iter().collect() }
947    }
948}
949
950#[cfg(test)]
951mod tests {
952    use std::collections::HashMap;
953
954    use super::*;
955
956    #[test]
957    pub fn test_highest_collection_level() {
958        let mut collection = IssueCollection::from(vec![]);
959        assert_eq!(collection.get_highest_level(), None);
960
961        collection.push(Issue::note("note"));
962        assert_eq!(collection.get_highest_level(), Some(Level::Note));
963
964        collection.push(Issue::help("help"));
965        assert_eq!(collection.get_highest_level(), Some(Level::Help));
966
967        collection.push(Issue::warning("warning"));
968        assert_eq!(collection.get_highest_level(), Some(Level::Warning));
969
970        collection.push(Issue::error("error"));
971        assert_eq!(collection.get_highest_level(), Some(Level::Error));
972    }
973
974    #[test]
975    pub fn test_level_downgrade() {
976        assert_eq!(Level::Error.downgrade(), Level::Warning);
977        assert_eq!(Level::Warning.downgrade(), Level::Help);
978        assert_eq!(Level::Help.downgrade(), Level::Note);
979        assert_eq!(Level::Note.downgrade(), Level::Note);
980    }
981
982    #[test]
983    pub fn test_issue_collection_with_maximum_level() {
984        let mut collection = IssueCollection::from(vec![
985            Issue::error("error"),
986            Issue::warning("warning"),
987            Issue::help("help"),
988            Issue::note("note"),
989        ]);
990
991        collection = collection.with_maximum_level(Level::Warning);
992        assert_eq!(collection.len(), 3);
993        assert_eq!(
994            collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
995            vec![Level::Warning, Level::Help, Level::Note]
996        );
997    }
998
999    #[test]
1000    pub fn test_issue_collection_with_minimum_level() {
1001        let mut collection = IssueCollection::from(vec![
1002            Issue::error("error"),
1003            Issue::warning("warning"),
1004            Issue::help("help"),
1005            Issue::note("note"),
1006        ]);
1007
1008        collection = collection.with_minimum_level(Level::Warning);
1009        assert_eq!(collection.len(), 2);
1010        assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
1011    }
1012
1013    #[test]
1014    pub fn test_issue_collection_has_minimum_level() {
1015        let mut collection = IssueCollection::from(vec![]);
1016
1017        assert!(!collection.has_minimum_level(Level::Error));
1018        assert!(!collection.has_minimum_level(Level::Warning));
1019        assert!(!collection.has_minimum_level(Level::Help));
1020        assert!(!collection.has_minimum_level(Level::Note));
1021
1022        collection.push(Issue::note("note"));
1023
1024        assert!(!collection.has_minimum_level(Level::Error));
1025        assert!(!collection.has_minimum_level(Level::Warning));
1026        assert!(!collection.has_minimum_level(Level::Help));
1027        assert!(collection.has_minimum_level(Level::Note));
1028
1029        collection.push(Issue::help("help"));
1030
1031        assert!(!collection.has_minimum_level(Level::Error));
1032        assert!(!collection.has_minimum_level(Level::Warning));
1033        assert!(collection.has_minimum_level(Level::Help));
1034        assert!(collection.has_minimum_level(Level::Note));
1035
1036        collection.push(Issue::warning("warning"));
1037
1038        assert!(!collection.has_minimum_level(Level::Error));
1039        assert!(collection.has_minimum_level(Level::Warning));
1040        assert!(collection.has_minimum_level(Level::Help));
1041        assert!(collection.has_minimum_level(Level::Note));
1042
1043        collection.push(Issue::error("error"));
1044
1045        assert!(collection.has_minimum_level(Level::Error));
1046        assert!(collection.has_minimum_level(Level::Warning));
1047        assert!(collection.has_minimum_level(Level::Help));
1048        assert!(collection.has_minimum_level(Level::Note));
1049    }
1050
1051    #[test]
1052    pub fn test_issue_collection_level_count() {
1053        let mut collection = IssueCollection::from(vec![]);
1054
1055        assert_eq!(collection.get_level_count(Level::Error), 0);
1056        assert_eq!(collection.get_level_count(Level::Warning), 0);
1057        assert_eq!(collection.get_level_count(Level::Help), 0);
1058        assert_eq!(collection.get_level_count(Level::Note), 0);
1059
1060        collection.push(Issue::error("error"));
1061
1062        assert_eq!(collection.get_level_count(Level::Error), 1);
1063        assert_eq!(collection.get_level_count(Level::Warning), 0);
1064        assert_eq!(collection.get_level_count(Level::Help), 0);
1065        assert_eq!(collection.get_level_count(Level::Note), 0);
1066
1067        collection.push(Issue::warning("warning"));
1068
1069        assert_eq!(collection.get_level_count(Level::Error), 1);
1070        assert_eq!(collection.get_level_count(Level::Warning), 1);
1071        assert_eq!(collection.get_level_count(Level::Help), 0);
1072        assert_eq!(collection.get_level_count(Level::Note), 0);
1073
1074        collection.push(Issue::help("help"));
1075
1076        assert_eq!(collection.get_level_count(Level::Error), 1);
1077        assert_eq!(collection.get_level_count(Level::Warning), 1);
1078        assert_eq!(collection.get_level_count(Level::Help), 1);
1079        assert_eq!(collection.get_level_count(Level::Note), 0);
1080
1081        collection.push(Issue::note("note"));
1082
1083        assert_eq!(collection.get_level_count(Level::Error), 1);
1084        assert_eq!(collection.get_level_count(Level::Warning), 1);
1085        assert_eq!(collection.get_level_count(Level::Help), 1);
1086        assert_eq!(collection.get_level_count(Level::Note), 1);
1087    }
1088
1089    #[test]
1090    pub fn test_primary_span_is_deterministic() {
1091        let file = FileId::zero();
1092        let span_later = Span::new(file, 20u32.into(), 25u32.into());
1093        let span_earlier = Span::new(file, 5u32.into(), 10u32.into());
1094
1095        let issue = Issue::error("x")
1096            .with_annotation(Annotation::primary(span_later))
1097            .with_annotation(Annotation::primary(span_earlier));
1098
1099        assert_eq!(issue.primary_span(), Some(span_earlier));
1100    }
1101
1102    fn ignore_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1103        let file_id = |name: &[u8]| FileId::new(name);
1104
1105        let paths: [&[u8]; 4] =
1106            [b"src/App.php", b"tests/Unit/FooTest.php", b"modules/auth/views/login.tpl", b"types/user/form.tpl"];
1107
1108        let mut mapping = HashMap::new();
1109        let issues: Vec<Issue> = paths
1110            .iter()
1111            .map(|p| {
1112                let id = file_id(p);
1113                mapping.insert(id, *p);
1114                Issue::error("oops").with_code("invalid-global").with_annotation(Annotation::primary(Span::new(
1115                    id,
1116                    0u32.into(),
1117                    1u32.into(),
1118                )))
1119            })
1120            .collect();
1121
1122        (IssueCollection::from(issues), mapping)
1123    }
1124
1125    fn resolve<'mapping>(
1126        mapping: &'mapping HashMap<FileId, &'static [u8]>,
1127    ) -> impl Fn(FileId) -> Option<String> + 'mapping {
1128        move |id| mapping.get(&id).map(|s| String::from_utf8_lossy(s).into_owned())
1129    }
1130
1131    fn remaining_paths(collection: &IssueCollection, mapping: &HashMap<FileId, &'static [u8]>) -> Vec<String> {
1132        collection
1133            .iter()
1134            .filter_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
1135            .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
1136            .collect()
1137    }
1138
1139    #[test]
1140    pub fn test_filter_out_ignored_with_plain_prefix() {
1141        let (mut collection, mapping) = ignore_fixture();
1142        let entries =
1143            vec![IgnoreEntry::Scoped { code: "invalid-global".to_string(), paths: vec!["tests/".to_string()] }];
1144        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1145
1146        collection.filter_out_ignored(&set, resolve(&mapping));
1147
1148        assert_eq!(
1149            remaining_paths(&collection, &mapping),
1150            vec![
1151                "src/App.php".to_string(),
1152                "modules/auth/views/login.tpl".to_string(),
1153                "types/user/form.tpl".to_string(),
1154            ]
1155        );
1156    }
1157
1158    #[test]
1159    pub fn test_filter_out_ignored_with_glob_pattern() {
1160        let (mut collection, mapping) = ignore_fixture();
1161        let entries = vec![IgnoreEntry::Scoped {
1162            code: "invalid-global".to_string(),
1163            paths: vec!["modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1164        }];
1165        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1166
1167        collection.filter_out_ignored(&set, resolve(&mapping));
1168
1169        assert_eq!(
1170            remaining_paths(&collection, &mapping),
1171            vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1172        );
1173    }
1174
1175    #[test]
1176    pub fn test_filter_out_ignored_mixes_plain_and_glob() {
1177        let (mut collection, mapping) = ignore_fixture();
1178        let entries = vec![IgnoreEntry::Scoped {
1179            code: "invalid-global".to_string(),
1180            paths: vec!["tests/".to_string(), "modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1181        }];
1182        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1183
1184        collection.filter_out_ignored(&set, resolve(&mapping));
1185
1186        assert_eq!(remaining_paths(&collection, &mapping), vec!["src/App.php".to_string()]);
1187    }
1188
1189    #[test]
1190    pub fn test_filter_out_ignored_respects_code_scope() {
1191        let (mut collection, mapping) = ignore_fixture();
1192        let entries = vec![IgnoreEntry::Scoped { code: "different-code".to_string(), paths: vec!["**/*".to_string()] }];
1193        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1194
1195        collection.filter_out_ignored(&set, resolve(&mapping));
1196
1197        assert_eq!(collection.len(), 4);
1198    }
1199
1200    fn pattern_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1201        let paths: [&[u8]; 3] = [b"src/App.php", b"src/Bridge/Symfony.php", b"tests/Unit/FooTest.php"];
1202        let mut mapping = HashMap::new();
1203        let mut issues: Vec<Issue> = Vec::new();
1204
1205        let id0 = FileId::new(blake3::hash(paths[0]).as_bytes());
1206        mapping.insert(id0, paths[0]);
1207        issues.push(
1208            Issue::error("Saw type `mixed` in Symfony bridge.")
1209                .with_code("mixed-assignment")
1210                .with_annotation(Annotation::primary(Span::new(id0, 0u32.into(), 1u32.into()))),
1211        );
1212
1213        let id1 = FileId::new(blake3::hash(paths[1]).as_bytes());
1214        mapping.insert(id1, paths[1]);
1215        issues.push(
1216            Issue::error("Could not infer a precise return type.")
1217                .with_code("mixed-assignment")
1218                .with_note("Originates from Symfony vendor stubs.")
1219                .with_annotation(Annotation::primary(Span::new(id1, 0u32.into(), 1u32.into()))),
1220        );
1221
1222        let id2 = FileId::new(blake3::hash(paths[2]).as_bytes());
1223        mapping.insert(id2, paths[2]);
1224        issues.push(
1225            Issue::error("Unused variable.")
1226                .with_code("unused-variable")
1227                .with_annotation(Annotation::primary(Span::new(id2, 0u32.into(), 1u32.into()))),
1228        );
1229
1230        (IssueCollection::from(issues), mapping)
1231    }
1232
1233    #[test]
1234    pub fn test_pattern_matches_title_and_note() {
1235        let (mut collection, mapping) = pattern_fixture();
1236        let entries = vec![IgnoreEntry::Pattern {
1237            pattern: "Symfony".to_string(),
1238            code: Some("mixed-assignment".to_string()),
1239            paths: None,
1240        }];
1241        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1242
1243        collection.filter_out_ignored(&set, resolve(&mapping));
1244
1245        assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1246    }
1247
1248    #[test]
1249    pub fn test_pattern_without_code_matches_across_codes() {
1250        let (mut collection, mapping) = pattern_fixture();
1251        let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1252        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1253
1254        collection.filter_out_ignored(&set, resolve(&mapping));
1255
1256        assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1257    }
1258
1259    #[test]
1260    pub fn test_pattern_with_path_scope() {
1261        let (mut collection, mapping) = pattern_fixture();
1262        let entries = vec![IgnoreEntry::Pattern {
1263            pattern: "Symfony".to_string(),
1264            code: None,
1265            paths: Some(vec!["src/Bridge/".to_string()]),
1266        }];
1267        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1268
1269        collection.filter_out_ignored(&set, resolve(&mapping));
1270
1271        assert_eq!(
1272            remaining_paths(&collection, &mapping),
1273            vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1274        );
1275    }
1276
1277    #[test]
1278    pub fn test_pattern_case_insensitive_with_flag() {
1279        let (mut collection, mapping) = pattern_fixture();
1280        let entries = vec![IgnoreEntry::Pattern { pattern: "(?i)symfony".to_string(), code: None, paths: None }];
1281        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1282
1283        collection.filter_out_ignored(&set, resolve(&mapping));
1284
1285        assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1286    }
1287
1288    #[test]
1289    pub fn test_pattern_invalid_regex_is_skipped() {
1290        let (mut collection, mapping) = pattern_fixture();
1291        let entries = vec![
1292            IgnoreEntry::Pattern { pattern: "[unterminated".to_string(), code: None, paths: None },
1293            IgnoreEntry::Code("unused-variable".to_string()),
1294        ];
1295        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1296
1297        assert_eq!(set.len(), 1);
1298
1299        collection.filter_out_ignored(&set, resolve(&mapping));
1300
1301        assert_eq!(
1302            remaining_paths(&collection, &mapping),
1303            vec!["src/App.php".to_string(), "src/Bridge/Symfony.php".to_string()]
1304        );
1305    }
1306
1307    #[test]
1308    pub fn test_pattern_matches_help_message() {
1309        let id = FileId::new(blake3::hash(b"src/foo.php").as_bytes());
1310        let mut mapping: HashMap<FileId, &'static [u8]> = HashMap::new();
1311        mapping.insert(id, &b"src/foo.php"[..]);
1312        let mut collection = IssueCollection::from(vec![
1313            Issue::error("Title.")
1314                .with_code("some-code")
1315                .with_help("Consider migrating off legacy Symfony bridge.")
1316                .with_annotation(Annotation::primary(Span::new(id, 0u32.into(), 1u32.into()))),
1317        ]);
1318
1319        let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1320        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1321
1322        collection.filter_out_ignored(&set, resolve(&mapping));
1323
1324        assert!(collection.is_empty());
1325    }
1326}