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    /// Whether one borrowed issue matches an ignore rule.
257    #[must_use]
258    pub fn is_ignored<F>(&self, issue: &Issue, resolve_file_name: F) -> bool
259    where
260        F: Fn(FileId) -> Option<String>,
261    {
262        let mut cached_path: Option<Option<String>> = None;
263        let mut resolve_path = |issue: &Issue| -> Option<String> {
264            cached_path
265                .get_or_insert_with(|| issue.primary_span().and_then(|span| resolve_file_name(span.file_id)))
266                .clone()
267        };
268
269        for entry in &self.entries {
270            match entry {
271                CompiledIgnoreEntry::Code(ignored_code) => {
272                    if let Some(code) = &issue.code
273                        && ignored_code == code
274                    {
275                        return true;
276                    }
277                }
278                CompiledIgnoreEntry::Scoped { code: ignored_code, matcher } => {
279                    let Some(code) = &issue.code else {
280                        continue;
281                    };
282
283                    if ignored_code != code {
284                        continue;
285                    }
286
287                    if let Some(name) = resolve_path(issue)
288                        && matcher.is_match(&name)
289                    {
290                        return true;
291                    }
292                }
293                CompiledIgnoreEntry::Pattern { regex, code: ignored_code, matcher } => {
294                    if let Some(ignored_code) = ignored_code {
295                        let Some(code) = &issue.code else {
296                            continue;
297                        };
298
299                        if ignored_code != code {
300                            continue;
301                        }
302                    }
303
304                    if let Some(matcher) = matcher {
305                        let Some(name) = resolve_path(issue) else {
306                            continue;
307                        };
308
309                        if !matcher.is_match(&name) {
310                            continue;
311                        }
312                    }
313
314                    if issue_text_matches(issue, regex) {
315                        return true;
316                    }
317                }
318            }
319        }
320        false
321    }
322
323    /// Compiles the given ignore entries into a reusable matcher set.
324    ///
325    /// Bad regex/glob entries are reported via `tracing::error!` and skipped;
326    /// the returned set still contains the valid entries.
327    #[must_use]
328    pub fn compile(entries: &[IgnoreEntry], glob: GlobSettings) -> Self {
329        let mut compiled = Vec::with_capacity(entries.len());
330        for entry in entries {
331            match entry {
332                IgnoreEntry::Code(code) => compiled.push(CompiledIgnoreEntry::Code(code.clone())),
333                IgnoreEntry::Scoped { code, paths } => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
334                    Ok(matcher) => compiled.push(CompiledIgnoreEntry::Scoped { code: code.clone(), matcher }),
335                    Err(err) => {
336                        tracing::error!("Failed to compile ignore patterns for `{code}`: {err}. Entry will be skipped.")
337                    }
338                },
339                IgnoreEntry::Pattern { pattern, code, paths } => {
340                    let regex = match Regex::new(pattern) {
341                        Ok(regex) => regex,
342                        Err(err) => {
343                            tracing::error!(
344                                "Failed to compile ignore regex `{pattern}`: {err}. Entry will be skipped."
345                            );
346
347                            continue;
348                        }
349                    };
350
351                    let matcher = match paths {
352                        Some(paths) => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
353                            Ok(matcher) => Some(matcher),
354                            Err(err) => {
355                                tracing::error!(
356                                    "Failed to compile ignore paths for regex `{pattern}`: {err}. Entry will be skipped."
357                                );
358
359                                continue;
360                            }
361                        },
362                        None => None,
363                    };
364
365                    compiled.push(CompiledIgnoreEntry::Pattern { regex, code: code.clone(), matcher });
366                }
367            }
368        }
369
370        Self { entries: compiled }
371    }
372
373    #[must_use]
374    pub fn is_empty(&self) -> bool {
375        self.entries.is_empty()
376    }
377
378    #[must_use]
379    pub fn len(&self) -> usize {
380        self.entries.len()
381    }
382}
383
384impl Annotation {
385    /// Creates a new annotation with the given kind and span.
386    ///
387    /// # Examples
388    ///
389    /// ```
390    /// use mago_reporting::{Annotation, AnnotationKind};
391    /// use mago_database::file::FileId;
392    /// use mago_span::Span;
393    /// use mago_span::Position;
394    ///
395    /// let file = FileId::zero();
396    /// let start = Position::new(0);
397    /// let end = Position::new(5);
398    /// let span = Span::new(file, start, end);
399    /// let annotation = Annotation::new(AnnotationKind::Primary, span);
400    /// ```
401    #[must_use]
402    pub fn new(kind: AnnotationKind, span: Span) -> Self {
403        Self { message: None, kind, span }
404    }
405
406    /// Creates a new primary annotation with the given span.
407    ///
408    /// # Examples
409    ///
410    /// ```
411    /// use mago_reporting::{Annotation, AnnotationKind};
412    /// use mago_database::file::FileId;
413    /// use mago_span::Span;
414    /// use mago_span::Position;
415    ///
416    /// let file = FileId::zero();
417    /// let start = Position::new(0);
418    /// let end = Position::new(5);
419    /// let span = Span::new(file, start, end);
420    /// let annotation = Annotation::primary(span);
421    /// ```
422    #[must_use]
423    pub fn primary(span: Span) -> Self {
424        Self::new(AnnotationKind::Primary, span)
425    }
426
427    /// Creates a new secondary annotation with the given span.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// use mago_reporting::{Annotation, AnnotationKind};
433    /// use mago_database::file::FileId;
434    /// use mago_span::Span;
435    /// use mago_span::Position;
436    ///
437    /// let file = FileId::zero();
438    /// let start = Position::new(0);
439    /// let end = Position::new(5);
440    /// let span = Span::new(file, start, end);
441    /// let annotation = Annotation::secondary(span);
442    /// ```
443    #[must_use]
444    pub fn secondary(span: Span) -> Self {
445        Self::new(AnnotationKind::Secondary, span)
446    }
447
448    /// Sets the message of this annotation.
449    ///
450    /// # Examples
451    ///
452    /// ```
453    /// use mago_reporting::{Annotation, AnnotationKind};
454    /// use mago_database::file::FileId;
455    /// use mago_span::Span;
456    /// use mago_span::Position;
457    ///
458    /// let file = FileId::zero();
459    /// let start = Position::new(0);
460    /// let end = Position::new(5);
461    /// let span = Span::new(file, start, end);
462    /// let annotation = Annotation::primary(span).with_message("This is a primary annotation");
463    /// ```
464    #[must_use]
465    pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
466        self.message = Some(message.into());
467
468        self
469    }
470
471    /// Returns `true` if this annotation is a primary annotation.
472    #[must_use]
473    pub fn is_primary(&self) -> bool {
474        self.kind == AnnotationKind::Primary
475    }
476}
477
478impl Level {
479    /// Downgrades the level to the next lower severity.
480    ///
481    /// This function maps levels to their less severe counterparts:
482    ///
483    /// - `Error` becomes `Warning`
484    /// - `Warning` becomes `Help`
485    /// - `Help` becomes `Note`
486    /// - `Note` remains as `Note`
487    ///
488    /// # Examples
489    ///
490    /// ```
491    /// use mago_reporting::Level;
492    ///
493    /// let level = Level::Error;
494    /// assert_eq!(level.downgrade(), Level::Warning);
495    ///
496    /// let level = Level::Warning;
497    /// assert_eq!(level.downgrade(), Level::Help);
498    ///
499    /// let level = Level::Help;
500    /// assert_eq!(level.downgrade(), Level::Note);
501    ///
502    /// let level = Level::Note;
503    /// assert_eq!(level.downgrade(), Level::Note);
504    /// ```
505    #[must_use]
506    pub fn downgrade(&self) -> Self {
507        match self {
508            Level::Error => Level::Warning,
509            Level::Warning => Level::Help,
510            Level::Help | Level::Note => Level::Note,
511        }
512    }
513}
514
515impl Issue {
516    /// Creates a new issue with the given level and message.
517    ///
518    /// # Examples
519    ///
520    /// ```
521    /// use mago_reporting::{Issue, Level};
522    ///
523    /// let issue = Issue::new(Level::Error, "This is an error");
524    /// ```
525    pub fn new(level: Level, message: impl Into<Cow<'static, str>>) -> Self {
526        Self {
527            level,
528            code: None,
529            message: message.into(),
530            annotations: Vec::new(),
531            notes: Vec::new(),
532            help: None,
533            link: None,
534            edits: HashMap::default(),
535        }
536    }
537
538    /// Creates a new error issue with the given message.
539    ///
540    /// # Examples
541    ///
542    /// ```
543    /// use mago_reporting::Issue;
544    ///
545    /// let issue = Issue::error("This is an error");
546    /// ```
547    pub fn error(message: impl Into<Cow<'static, str>>) -> Self {
548        Self::new(Level::Error, message)
549    }
550
551    /// Creates a new warning issue with the given message.
552    ///
553    /// # Examples
554    ///
555    /// ```
556    /// use mago_reporting::Issue;
557    ///
558    /// let issue = Issue::warning("This is a warning");
559    /// ```
560    pub fn warning(message: impl Into<Cow<'static, str>>) -> Self {
561        Self::new(Level::Warning, message)
562    }
563
564    /// Creates a new help issue with the given message.
565    ///
566    /// # Examples
567    ///
568    /// ```
569    /// use mago_reporting::Issue;
570    ///
571    /// let issue = Issue::help("This is a help message");
572    /// ```
573    pub fn help(message: impl Into<Cow<'static, str>>) -> Self {
574        Self::new(Level::Help, message)
575    }
576
577    /// Creates a new note issue with the given message.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use mago_reporting::Issue;
583    ///
584    /// let issue = Issue::note("This is a note");
585    /// ```
586    pub fn note(message: impl Into<Cow<'static, str>>) -> Self {
587        Self::new(Level::Note, message)
588    }
589
590    /// Adds a code to this issue.
591    ///
592    /// # Examples
593    ///
594    /// ```
595    /// use mago_reporting::{Issue, Level};
596    ///
597    /// let issue = Issue::error("This is an error").with_code("E0001");
598    /// ```
599    #[must_use]
600    pub fn with_code(mut self, code: impl Into<String>) -> Self {
601        self.code = Some(code.into());
602
603        self
604    }
605
606    /// Add an annotation to this issue.
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// use mago_reporting::{Issue, Annotation, AnnotationKind};
612    /// use mago_database::file::FileId;
613    /// use mago_span::Span;
614    /// use mago_span::Position;
615    ///
616    /// let file = FileId::zero();
617    /// let start = Position::new(0);
618    /// let end = Position::new(5);
619    /// let span = Span::new(file, start, end);
620    ///
621    /// let issue = Issue::error("This is an error").with_annotation(Annotation::primary(span));
622    /// ```
623    #[must_use]
624    pub fn with_annotation(mut self, annotation: Annotation) -> Self {
625        if self.annotations.is_empty() {
626            self.annotations.reserve_exact(2);
627        }
628
629        self.annotations.push(annotation);
630
631        self
632    }
633
634    #[must_use]
635    pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
636        self.annotations.extend(annotation);
637
638        self
639    }
640
641    /// Returns the deterministic primary annotation for this issue.
642    ///
643    /// If multiple primary annotations exist, the one with the smallest span is returned.
644    #[must_use]
645    pub fn primary_annotation(&self) -> Option<&Annotation> {
646        self.annotations.iter().filter(|annotation| annotation.is_primary()).min_by_key(|annotation| annotation.span)
647    }
648
649    /// Returns the deterministic primary span for this issue.
650    #[must_use]
651    pub fn primary_span(&self) -> Option<Span> {
652        self.primary_annotation().map(|annotation| annotation.span)
653    }
654
655    /// Add a note to this issue.
656    ///
657    /// # Examples
658    ///
659    /// ```
660    /// use mago_reporting::Issue;
661    ///
662    /// let issue = Issue::error("This is an error").with_note("This is a note");
663    /// ```
664    #[must_use]
665    pub fn with_note(mut self, note: impl Into<Cow<'static, str>>) -> Self {
666        if self.notes.is_empty() {
667            self.notes.reserve_exact(1);
668        }
669
670        self.notes.push(note.into());
671
672        self
673    }
674
675    /// Add a help message to this issue.
676    ///
677    /// This is useful for providing additional context to the user on how to resolve the issue.
678    ///
679    /// # Examples
680    ///
681    /// ```
682    /// use mago_reporting::Issue;
683    ///
684    /// let issue = Issue::error("This is an error").with_help("This is a help message");
685    /// ```
686    #[must_use]
687    pub fn with_help(mut self, help: impl Into<Cow<'static, str>>) -> Self {
688        self.help = Some(help.into());
689
690        self
691    }
692
693    /// Add a link to this issue.
694    ///
695    /// # Examples
696    ///
697    /// ```
698    /// use mago_reporting::Issue;
699    ///
700    /// let issue = Issue::error("This is an error").with_link("https://example.com");
701    /// ```
702    #[must_use]
703    pub fn with_link(mut self, link: impl Into<String>) -> Self {
704        self.link = Some(link.into());
705
706        self
707    }
708
709    /// Add a single edit to this issue.
710    #[must_use]
711    pub fn with_edit(mut self, file_id: FileId, edit: TextEdit) -> Self {
712        self.edits.entry(file_id).or_default().push(edit);
713
714        self
715    }
716
717    /// Add multiple edits to this issue.
718    #[must_use]
719    pub fn with_file_edits(mut self, file_id: FileId, edits: IssueEdits) -> Self {
720        if !edits.is_empty() {
721            match self.edits.entry(file_id) {
722                Entry::Vacant(entry) => {
723                    entry.insert(edits);
724                }
725                Entry::Occupied(mut entry) => entry.get_mut().extend(edits),
726            }
727        }
728
729        self
730    }
731
732    /// Take the edits from this issue.
733    #[must_use]
734    pub fn take_edits(&mut self) -> HashMap<FileId, IssueEdits> {
735        std::mem::replace(&mut self.edits, HashMap::new())
736    }
737}
738
739impl IssueCollection {
740    #[must_use]
741    pub fn new() -> Self {
742        Self { issues: Vec::new() }
743    }
744
745    pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
746        Self { issues: issues.into_iter().collect() }
747    }
748
749    pub fn push(&mut self, issue: Issue) {
750        self.issues.push(issue);
751    }
752
753    pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
754        self.issues.extend(issues);
755    }
756
757    pub fn reserve(&mut self, additional: usize) {
758        self.issues.reserve(additional);
759    }
760
761    pub fn shrink_to_fit(&mut self) {
762        self.issues.shrink_to_fit();
763    }
764
765    #[must_use]
766    pub fn is_empty(&self) -> bool {
767        self.issues.is_empty()
768    }
769
770    #[must_use]
771    pub fn len(&self) -> usize {
772        self.issues.len()
773    }
774
775    /// Filters the issues in the collection to only include those with a severity level
776    /// lower than or equal to the given level.
777    #[must_use]
778    pub fn with_maximum_level(self, level: Level) -> Self {
779        Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
780    }
781
782    /// Filters the issues in the collection to only include those with a severity level
783    ///  higher than or equal to the given level.
784    #[must_use]
785    pub fn with_minimum_level(self, level: Level) -> Self {
786        Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
787    }
788
789    /// Returns `true` if the collection contains any issues with a severity level
790    ///  higher than or equal to the given level.
791    #[must_use]
792    pub fn has_minimum_level(&self, level: Level) -> bool {
793        self.issues.iter().any(|issue| issue.level >= level)
794    }
795
796    /// Returns the number of issues in the collection with the given severity level.
797    #[must_use]
798    pub fn get_level_count(&self, level: Level) -> usize {
799        self.issues.iter().filter(|issue| issue.level == level).count()
800    }
801
802    /// Returns the highest severity level of the issues in the collection.
803    #[must_use]
804    pub fn get_highest_level(&self) -> Option<Level> {
805        self.issues.iter().map(|issue| issue.level).max()
806    }
807
808    /// Returns the lowest severity level of the issues in the collection.
809    #[must_use]
810    pub fn get_lowest_level(&self) -> Option<Level> {
811        self.issues.iter().map(|issue| issue.level).min()
812    }
813
814    pub fn filter_out_ignored<F>(&mut self, set: &CompiledIgnoreSet, resolve_file_name: F)
815    where
816        F: Fn(FileId) -> Option<String>,
817    {
818        if !set.is_empty() {
819            self.issues.retain(|issue| !set.is_ignored(issue, &resolve_file_name));
820        }
821    }
822
823    pub fn filter_retain_codes(&mut self, retain_codes: &[String]) {
824        self.issues.retain(|issue| if let Some(code) = &issue.code { retain_codes.contains(code) } else { false });
825    }
826
827    pub fn take_edits(&mut self) -> impl Iterator<Item = (FileId, IssueEdits)> + '_ {
828        self.issues.iter_mut().flat_map(|issue| issue.take_edits().into_iter())
829    }
830
831    /// Filters the issues in the collection to only include those that have associated edits.
832    #[must_use]
833    pub fn with_edits(self) -> Self {
834        Self { issues: self.issues.into_iter().filter(|issue| !issue.edits.is_empty()).collect() }
835    }
836
837    /// Sorts the issues in the collection.
838    ///
839    /// The issues are sorted by severity level in ascending order,
840    /// then by code in ascending order, and finally by the primary annotation span.
841    #[must_use]
842    pub fn sorted(self) -> Self {
843        let mut issues = self.issues;
844
845        issues.sort_by(|a, b| match a.level.cmp(&b.level) {
846            Ordering::Greater => Ordering::Greater,
847            Ordering::Less => Ordering::Less,
848            Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
849                Ordering::Less => Ordering::Less,
850                Ordering::Greater => Ordering::Greater,
851                Ordering::Equal => {
852                    let a_span = a.primary_span();
853                    let b_span = b.primary_span();
854
855                    match (a_span, b_span) {
856                        (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
857                        (Some(_), None) => Ordering::Less,
858                        (None, Some(_)) => Ordering::Greater,
859                        (None, None) => Ordering::Equal,
860                    }
861                }
862            },
863        });
864
865        Self { issues }
866    }
867
868    pub fn iter(&self) -> impl Iterator<Item = &Issue> {
869        self.issues.iter()
870    }
871
872    /// Converts the collection into a map of edit batches grouped by file.
873    ///
874    /// Each batch contains all edits from a single issue along with the rule code.
875    /// All edits from an issue must be applied together as a batch to maintain code validity.
876    ///
877    /// Returns `HashMap<FileId, Vec<(Option<String>, IssueEdits)>>` where each tuple
878    /// is (rule_code, edits_for_that_issue).
879    #[must_use]
880    pub fn to_edit_batches(self) -> HashMap<FileId, IssueEditBatches> {
881        let mut result: HashMap<FileId, Vec<(Option<String>, IssueEdits)>> = HashMap::default();
882        for issue in self.issues.into_iter().filter(|issue| !issue.edits.is_empty()) {
883            let code = issue.code;
884            for (file_id, edit_list) in issue.edits {
885                result.entry(file_id).or_default().push((code.clone(), edit_list));
886            }
887        }
888
889        result
890    }
891}
892
893/// Returns `true` when any of the issue's textual fields matches the regex.
894///
895/// Tested in order: title, annotation messages, notes, help. The most
896/// instance-specific fields are searched first; notes and help are last
897/// because they are typically templated per rule.
898fn issue_text_matches(issue: &Issue, regex: &Regex) -> bool {
899    if regex.is_match(&issue.message) {
900        return true;
901    }
902
903    if issue
904        .annotations
905        .iter()
906        .any(|annotation| annotation.message.as_ref().is_some_and(|message| regex.is_match(message)))
907    {
908        return true;
909    }
910
911    if issue.notes.iter().any(|note| regex.is_match(note)) {
912        return true;
913    }
914
915    issue.help.as_ref().is_some_and(|help| regex.is_match(help))
916}
917
918impl IntoIterator for IssueCollection {
919    type Item = Issue;
920
921    type IntoIter = std::vec::IntoIter<Issue>;
922
923    fn into_iter(self) -> Self::IntoIter {
924        self.issues.into_iter()
925    }
926}
927
928impl<'collection> IntoIterator for &'collection IssueCollection {
929    type Item = &'collection Issue;
930
931    type IntoIter = std::slice::Iter<'collection, Issue>;
932
933    fn into_iter(self) -> Self::IntoIter {
934        self.issues.iter()
935    }
936}
937
938impl Default for IssueCollection {
939    fn default() -> Self {
940        Self::new()
941    }
942}
943
944impl IntoIterator for Issue {
945    type Item = Issue;
946    type IntoIter = Once<Issue>;
947
948    fn into_iter(self) -> Self::IntoIter {
949        std::iter::once(self)
950    }
951}
952
953impl FromIterator<Issue> for IssueCollection {
954    fn from_iter<T>(iter: T) -> Self
955    where
956        T: IntoIterator<Item = Issue>,
957    {
958        Self { issues: iter.into_iter().collect() }
959    }
960}
961
962#[cfg(test)]
963mod tests {
964    use std::collections::HashMap;
965
966    use super::*;
967
968    #[test]
969    pub fn test_highest_collection_level() {
970        let mut collection = IssueCollection::from(vec![]);
971        assert_eq!(collection.get_highest_level(), None);
972
973        collection.push(Issue::note("note"));
974        assert_eq!(collection.get_highest_level(), Some(Level::Note));
975
976        collection.push(Issue::help("help"));
977        assert_eq!(collection.get_highest_level(), Some(Level::Help));
978
979        collection.push(Issue::warning("warning"));
980        assert_eq!(collection.get_highest_level(), Some(Level::Warning));
981
982        collection.push(Issue::error("error"));
983        assert_eq!(collection.get_highest_level(), Some(Level::Error));
984    }
985
986    #[test]
987    pub fn test_level_downgrade() {
988        assert_eq!(Level::Error.downgrade(), Level::Warning);
989        assert_eq!(Level::Warning.downgrade(), Level::Help);
990        assert_eq!(Level::Help.downgrade(), Level::Note);
991        assert_eq!(Level::Note.downgrade(), Level::Note);
992    }
993
994    #[test]
995    pub fn test_issue_collection_with_maximum_level() {
996        let mut collection = IssueCollection::from(vec![
997            Issue::error("error"),
998            Issue::warning("warning"),
999            Issue::help("help"),
1000            Issue::note("note"),
1001        ]);
1002
1003        collection = collection.with_maximum_level(Level::Warning);
1004        assert_eq!(collection.len(), 3);
1005        assert_eq!(
1006            collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
1007            vec![Level::Warning, Level::Help, Level::Note]
1008        );
1009    }
1010
1011    #[test]
1012    pub fn test_issue_collection_with_minimum_level() {
1013        let mut collection = IssueCollection::from(vec![
1014            Issue::error("error"),
1015            Issue::warning("warning"),
1016            Issue::help("help"),
1017            Issue::note("note"),
1018        ]);
1019
1020        collection = collection.with_minimum_level(Level::Warning);
1021        assert_eq!(collection.len(), 2);
1022        assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
1023    }
1024
1025    #[test]
1026    pub fn test_issue_collection_has_minimum_level() {
1027        let mut collection = IssueCollection::from(vec![]);
1028
1029        assert!(!collection.has_minimum_level(Level::Error));
1030        assert!(!collection.has_minimum_level(Level::Warning));
1031        assert!(!collection.has_minimum_level(Level::Help));
1032        assert!(!collection.has_minimum_level(Level::Note));
1033
1034        collection.push(Issue::note("note"));
1035
1036        assert!(!collection.has_minimum_level(Level::Error));
1037        assert!(!collection.has_minimum_level(Level::Warning));
1038        assert!(!collection.has_minimum_level(Level::Help));
1039        assert!(collection.has_minimum_level(Level::Note));
1040
1041        collection.push(Issue::help("help"));
1042
1043        assert!(!collection.has_minimum_level(Level::Error));
1044        assert!(!collection.has_minimum_level(Level::Warning));
1045        assert!(collection.has_minimum_level(Level::Help));
1046        assert!(collection.has_minimum_level(Level::Note));
1047
1048        collection.push(Issue::warning("warning"));
1049
1050        assert!(!collection.has_minimum_level(Level::Error));
1051        assert!(collection.has_minimum_level(Level::Warning));
1052        assert!(collection.has_minimum_level(Level::Help));
1053        assert!(collection.has_minimum_level(Level::Note));
1054
1055        collection.push(Issue::error("error"));
1056
1057        assert!(collection.has_minimum_level(Level::Error));
1058        assert!(collection.has_minimum_level(Level::Warning));
1059        assert!(collection.has_minimum_level(Level::Help));
1060        assert!(collection.has_minimum_level(Level::Note));
1061    }
1062
1063    #[test]
1064    pub fn test_issue_collection_level_count() {
1065        let mut collection = IssueCollection::from(vec![]);
1066
1067        assert_eq!(collection.get_level_count(Level::Error), 0);
1068        assert_eq!(collection.get_level_count(Level::Warning), 0);
1069        assert_eq!(collection.get_level_count(Level::Help), 0);
1070        assert_eq!(collection.get_level_count(Level::Note), 0);
1071
1072        collection.push(Issue::error("error"));
1073
1074        assert_eq!(collection.get_level_count(Level::Error), 1);
1075        assert_eq!(collection.get_level_count(Level::Warning), 0);
1076        assert_eq!(collection.get_level_count(Level::Help), 0);
1077        assert_eq!(collection.get_level_count(Level::Note), 0);
1078
1079        collection.push(Issue::warning("warning"));
1080
1081        assert_eq!(collection.get_level_count(Level::Error), 1);
1082        assert_eq!(collection.get_level_count(Level::Warning), 1);
1083        assert_eq!(collection.get_level_count(Level::Help), 0);
1084        assert_eq!(collection.get_level_count(Level::Note), 0);
1085
1086        collection.push(Issue::help("help"));
1087
1088        assert_eq!(collection.get_level_count(Level::Error), 1);
1089        assert_eq!(collection.get_level_count(Level::Warning), 1);
1090        assert_eq!(collection.get_level_count(Level::Help), 1);
1091        assert_eq!(collection.get_level_count(Level::Note), 0);
1092
1093        collection.push(Issue::note("note"));
1094
1095        assert_eq!(collection.get_level_count(Level::Error), 1);
1096        assert_eq!(collection.get_level_count(Level::Warning), 1);
1097        assert_eq!(collection.get_level_count(Level::Help), 1);
1098        assert_eq!(collection.get_level_count(Level::Note), 1);
1099    }
1100
1101    #[test]
1102    pub fn test_primary_span_is_deterministic() {
1103        let file = FileId::zero();
1104        let span_later = Span::new(file, 20u32.into(), 25u32.into());
1105        let span_earlier = Span::new(file, 5u32.into(), 10u32.into());
1106
1107        let issue = Issue::error("x")
1108            .with_annotation(Annotation::primary(span_later))
1109            .with_annotation(Annotation::primary(span_earlier));
1110
1111        assert_eq!(issue.primary_span(), Some(span_earlier));
1112    }
1113
1114    fn ignore_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1115        let file_id = |name: &[u8]| FileId::new(name);
1116
1117        let paths: [&[u8]; 4] =
1118            [b"src/App.php", b"tests/Unit/FooTest.php", b"modules/auth/views/login.tpl", b"types/user/form.tpl"];
1119
1120        let mut mapping = HashMap::new();
1121        let issues: Vec<Issue> = paths
1122            .iter()
1123            .map(|p| {
1124                let id = file_id(p);
1125                mapping.insert(id, *p);
1126                Issue::error("oops").with_code("invalid-global").with_annotation(Annotation::primary(Span::new(
1127                    id,
1128                    0u32.into(),
1129                    1u32.into(),
1130                )))
1131            })
1132            .collect();
1133
1134        (IssueCollection::from(issues), mapping)
1135    }
1136
1137    fn resolve<'mapping>(
1138        mapping: &'mapping HashMap<FileId, &'static [u8]>,
1139    ) -> impl Fn(FileId) -> Option<String> + 'mapping {
1140        move |id| mapping.get(&id).map(|s| String::from_utf8_lossy(s).into_owned())
1141    }
1142
1143    fn remaining_paths(collection: &IssueCollection, mapping: &HashMap<FileId, &'static [u8]>) -> Vec<String> {
1144        collection
1145            .iter()
1146            .filter_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
1147            .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
1148            .collect()
1149    }
1150
1151    #[test]
1152    pub fn test_filter_out_ignored_with_plain_prefix() {
1153        let (mut collection, mapping) = ignore_fixture();
1154        let entries =
1155            vec![IgnoreEntry::Scoped { code: "invalid-global".to_string(), paths: vec!["tests/".to_string()] }];
1156        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1157
1158        collection.filter_out_ignored(&set, resolve(&mapping));
1159
1160        assert_eq!(
1161            remaining_paths(&collection, &mapping),
1162            vec![
1163                "src/App.php".to_string(),
1164                "modules/auth/views/login.tpl".to_string(),
1165                "types/user/form.tpl".to_string(),
1166            ]
1167        );
1168    }
1169
1170    #[test]
1171    pub fn test_filter_out_ignored_with_glob_pattern() {
1172        let (mut collection, mapping) = ignore_fixture();
1173        let entries = vec![IgnoreEntry::Scoped {
1174            code: "invalid-global".to_string(),
1175            paths: vec!["modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1176        }];
1177        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1178
1179        collection.filter_out_ignored(&set, resolve(&mapping));
1180
1181        assert_eq!(
1182            remaining_paths(&collection, &mapping),
1183            vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1184        );
1185    }
1186
1187    #[test]
1188    pub fn test_filter_out_ignored_mixes_plain_and_glob() {
1189        let (mut collection, mapping) = ignore_fixture();
1190        let entries = vec![IgnoreEntry::Scoped {
1191            code: "invalid-global".to_string(),
1192            paths: vec!["tests/".to_string(), "modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1193        }];
1194        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1195
1196        collection.filter_out_ignored(&set, resolve(&mapping));
1197
1198        assert_eq!(remaining_paths(&collection, &mapping), vec!["src/App.php".to_string()]);
1199    }
1200
1201    #[test]
1202    pub fn test_filter_out_ignored_respects_code_scope() {
1203        let (mut collection, mapping) = ignore_fixture();
1204        let entries = vec![IgnoreEntry::Scoped { code: "different-code".to_string(), paths: vec!["**/*".to_string()] }];
1205        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1206
1207        collection.filter_out_ignored(&set, resolve(&mapping));
1208
1209        assert_eq!(collection.len(), 4);
1210    }
1211
1212    fn pattern_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1213        let paths: [&[u8]; 3] = [b"src/App.php", b"src/Bridge/Symfony.php", b"tests/Unit/FooTest.php"];
1214        let mut mapping = HashMap::new();
1215        let mut issues: Vec<Issue> = Vec::new();
1216
1217        let id0 = FileId::new(blake3::hash(paths[0]).as_bytes());
1218        mapping.insert(id0, paths[0]);
1219        issues.push(
1220            Issue::error("Saw type `mixed` in Symfony bridge.")
1221                .with_code("mixed-assignment")
1222                .with_annotation(Annotation::primary(Span::new(id0, 0u32.into(), 1u32.into()))),
1223        );
1224
1225        let id1 = FileId::new(blake3::hash(paths[1]).as_bytes());
1226        mapping.insert(id1, paths[1]);
1227        issues.push(
1228            Issue::error("Could not infer a precise return type.")
1229                .with_code("mixed-assignment")
1230                .with_note("Originates from Symfony vendor stubs.")
1231                .with_annotation(Annotation::primary(Span::new(id1, 0u32.into(), 1u32.into()))),
1232        );
1233
1234        let id2 = FileId::new(blake3::hash(paths[2]).as_bytes());
1235        mapping.insert(id2, paths[2]);
1236        issues.push(
1237            Issue::error("Unused variable.")
1238                .with_code("unused-variable")
1239                .with_annotation(Annotation::primary(Span::new(id2, 0u32.into(), 1u32.into()))),
1240        );
1241
1242        (IssueCollection::from(issues), mapping)
1243    }
1244
1245    #[test]
1246    pub fn test_pattern_matches_title_and_note() {
1247        let (mut collection, mapping) = pattern_fixture();
1248        let entries = vec![IgnoreEntry::Pattern {
1249            pattern: "Symfony".to_string(),
1250            code: Some("mixed-assignment".to_string()),
1251            paths: None,
1252        }];
1253        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1254
1255        collection.filter_out_ignored(&set, resolve(&mapping));
1256
1257        assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1258    }
1259
1260    #[test]
1261    pub fn test_pattern_without_code_matches_across_codes() {
1262        let (mut collection, mapping) = pattern_fixture();
1263        let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1264        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1265
1266        collection.filter_out_ignored(&set, resolve(&mapping));
1267
1268        assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1269    }
1270
1271    #[test]
1272    pub fn test_pattern_with_path_scope() {
1273        let (mut collection, mapping) = pattern_fixture();
1274        let entries = vec![IgnoreEntry::Pattern {
1275            pattern: "Symfony".to_string(),
1276            code: None,
1277            paths: Some(vec!["src/Bridge/".to_string()]),
1278        }];
1279        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1280
1281        collection.filter_out_ignored(&set, resolve(&mapping));
1282
1283        assert_eq!(
1284            remaining_paths(&collection, &mapping),
1285            vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1286        );
1287    }
1288
1289    #[test]
1290    pub fn test_pattern_case_insensitive_with_flag() {
1291        let (mut collection, mapping) = pattern_fixture();
1292        let entries = vec![IgnoreEntry::Pattern { pattern: "(?i)symfony".to_string(), code: None, paths: None }];
1293        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1294
1295        collection.filter_out_ignored(&set, resolve(&mapping));
1296
1297        assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1298    }
1299
1300    #[test]
1301    pub fn test_pattern_invalid_regex_is_skipped() {
1302        let (mut collection, mapping) = pattern_fixture();
1303        let entries = vec![
1304            IgnoreEntry::Pattern { pattern: "[unterminated".to_string(), code: None, paths: None },
1305            IgnoreEntry::Code("unused-variable".to_string()),
1306        ];
1307        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1308
1309        assert_eq!(set.len(), 1);
1310
1311        collection.filter_out_ignored(&set, resolve(&mapping));
1312
1313        assert_eq!(
1314            remaining_paths(&collection, &mapping),
1315            vec!["src/App.php".to_string(), "src/Bridge/Symfony.php".to_string()]
1316        );
1317    }
1318
1319    #[test]
1320    pub fn test_pattern_matches_help_message() {
1321        let id = FileId::new(blake3::hash(b"src/foo.php").as_bytes());
1322        let mut mapping: HashMap<FileId, &'static [u8]> = HashMap::new();
1323        mapping.insert(id, &b"src/foo.php"[..]);
1324        let mut collection = IssueCollection::from(vec![
1325            Issue::error("Title.")
1326                .with_code("some-code")
1327                .with_help("Consider migrating off legacy Symfony bridge.")
1328                .with_annotation(Annotation::primary(Span::new(id, 0u32.into(), 1u32.into()))),
1329        ]);
1330
1331        let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1332        let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1333
1334        collection.filter_out_ignored(&set, resolve(&mapping));
1335
1336        assert!(collection.is_empty());
1337    }
1338}