mago_reporting/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::iter::Once;

use ahash::HashMap;
use serde::Deserialize;
use serde::Serialize;
use strum::Display;

use mago_fixer::FixPlan;
use mago_source::SourceIdentifier;
use mago_span::Span;

mod internal;

pub mod error;
pub mod reporter;

/// Represents the kind of annotation associated with an issue.
#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Deserialize, Serialize)]
pub enum AnnotationKind {
    /// A primary annotation, typically highlighting the main source of the issue.
    Primary,
    /// A secondary annotation, providing additional context or related information.
    Secondary,
}

/// An annotation associated with an issue, providing additional context or highlighting specific code spans.
#[derive(Debug, PartialEq, Eq, Ord, Clone, Hash, PartialOrd, Deserialize, Serialize)]
pub struct Annotation {
    /// An optional message associated with the annotation.
    pub message: Option<String>,
    /// The kind of annotation.
    pub kind: AnnotationKind,
    /// The code span that the annotation refers to.
    pub span: Span,
}

/// Represents the severity level of an issue.
#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Deserialize, Serialize, Display)]
pub enum Level {
    /// A note, providing additional information or context.
    Note,
    /// A help message, suggesting possible solutions or further actions.
    Help,
    /// A warning, indicating a potential problem that may need attention.
    Warning,
    /// An error, indicating a problem that prevents the code from functioning correctly.
    Error,
}

/// Represents an issue identified in the code.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct Issue {
    /// The severity level of the issue.
    pub level: Level,
    /// An optional code associated with the issue.
    pub code: Option<String>,
    /// The main message describing the issue.
    pub message: String,
    /// Additional notes related to the issue.
    pub notes: Vec<String>,
    /// An optional help message suggesting possible solutions or further actions.
    pub help: Option<String>,
    /// An optional link to external resources for more information about the issue.
    pub link: Option<String>,
    /// Annotations associated with the issue, providing additional context or highlighting specific code spans.
    pub annotations: Vec<Annotation>,
    /// Modification suggestions that can be applied to fix the issue.
    pub suggestions: Vec<(SourceIdentifier, FixPlan)>,
}

/// A collection of issues.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct IssueCollection {
    issues: Vec<Issue>,
}

impl Annotation {
    /// Creates a new annotation with the given kind and span.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let start = Position::dummy(0);
    /// let end = Position::dummy(5);
    /// let span = Span::new(start, end);
    /// let annotation = Annotation::new(AnnotationKind::Primary, span);
    /// ```
    pub fn new(kind: AnnotationKind, span: Span) -> Self {
        Self { message: None, kind, span }
    }

    /// Creates a new primary annotation with the given span.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let start = Position::dummy(0);
    /// let end = Position::dummy(5);
    /// let span = Span::new(start, end);
    /// let annotation = Annotation::primary(span);
    /// ```
    pub fn primary(span: Span) -> Self {
        Self::new(AnnotationKind::Primary, span)
    }

    /// Creates a new secondary annotation with the given span.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let start = Position::dummy(0);
    /// let end = Position::dummy(5);
    /// let span = Span::new(start, end);
    /// let annotation = Annotation::secondary(span);
    /// ```
    pub fn secondary(span: Span) -> Self {
        Self::new(AnnotationKind::Secondary, span)
    }

    /// Sets the message of this annotation.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let start = Position::dummy(0);
    /// let end = Position::dummy(5);
    /// let span = Span::new(start, end);
    /// let annotation = Annotation::primary(span).with_message("This is a primary annotation");
    /// ```
    #[must_use]
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());

        self
    }

    /// Returns `true` if this annotation is a primary annotation.
    pub fn is_primary(&self) -> bool {
        self.kind == AnnotationKind::Primary
    }
}

impl Level {
    /// Downgrades the level to the next lower severity.
    ///
    /// This function maps levels to their less severe counterparts:
    ///
    /// - `Error` becomes `Warning`
    /// - `Warning` becomes `Help`
    /// - `Help` becomes `Note`
    /// - `Note` remains as `Note`
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Level;
    ///
    /// let level = Level::Error;
    /// assert_eq!(level.downgrade(), Level::Warning);
    ///
    /// let level = Level::Warning;
    /// assert_eq!(level.downgrade(), Level::Help);
    ///
    /// let level = Level::Help;
    /// assert_eq!(level.downgrade(), Level::Note);
    ///
    /// let level = Level::Note;
    /// assert_eq!(level.downgrade(), Level::Note);
    /// ```
    pub fn downgrade(&self) -> Self {
        match self {
            Level::Error => Level::Warning,
            Level::Warning => Level::Help,
            Level::Help | Level::Note => Level::Note,
        }
    }
}

impl Issue {
    /// Creates a new issue with the given level and message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Issue, Level};
    ///
    /// let issue = Issue::new(Level::Error, "This is an error");
    /// ```
    pub fn new(level: Level, message: impl Into<String>) -> Self {
        Self {
            level,
            code: None,
            message: message.into(),
            annotations: Vec::new(),
            notes: Vec::new(),
            help: None,
            link: None,
            suggestions: Vec::new(),
        }
    }

    /// Creates a new error issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error");
    /// ```
    pub fn error(message: impl Into<String>) -> Self {
        Self::new(Level::Error, message)
    }

    /// Creates a new warning issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::warning("This is a warning");
    /// ```
    pub fn warning(message: impl Into<String>) -> Self {
        Self::new(Level::Warning, message)
    }

    /// Creates a new help issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::help("This is a help message");
    /// ```
    pub fn help(message: impl Into<String>) -> Self {
        Self::new(Level::Help, message)
    }

    /// Creates a new note issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::note("This is a note");
    /// ```
    pub fn note(message: impl Into<String>) -> Self {
        Self::new(Level::Note, message)
    }

    /// Adds a code to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Issue, Level};
    ///
    /// let issue = Issue::error("This is an error").with_code("E0001");
    /// ```
    #[must_use]
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());

        self
    }

    /// Add an annotation to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Issue, Annotation, AnnotationKind};
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let start = Position::dummy(0);
    /// let end = Position::dummy(5);
    /// let span = Span::new(start, end);
    ///
    /// let issue = Issue::error("This is an error").with_annotation(Annotation::primary(span));
    /// ```
    #[must_use]
    pub fn with_annotation(mut self, annotation: Annotation) -> Self {
        self.annotations.push(annotation);

        self
    }

    #[must_use]
    pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
        self.annotations.extend(annotation);

        self
    }

    /// Add a note to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error").with_note("This is a note");
    /// ```
    #[must_use]
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());

        self
    }

    /// Add a help message to this issue.
    ///
    /// This is useful for providing additional context to the user on how to resolve the issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error").with_help("This is a help message");
    /// ```
    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());

        self
    }

    /// Add a link to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error").with_link("https://example.com");
    /// ```
    #[must_use]
    pub fn with_link(mut self, link: impl Into<String>) -> Self {
        self.link = Some(link.into());

        self
    }

    /// Add a code modification suggestion to this issue.
    #[must_use]
    pub fn with_suggestion(mut self, source: SourceIdentifier, plan: FixPlan) -> Self {
        self.suggestions.push((source, plan));

        self
    }

    /// Take the code modification suggestion from this issue.
    #[must_use]
    pub fn take_suggestions(&mut self) -> Vec<(SourceIdentifier, FixPlan)> {
        self.suggestions.drain(..).collect()
    }
}

impl IssueCollection {
    pub fn new() -> Self {
        Self { issues: Vec::new() }
    }

    pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
        Self { issues: issues.into_iter().collect() }
    }

    pub fn push(&mut self, issue: Issue) {
        self.issues.push(issue);
    }

    pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
        self.issues.extend(issues);
    }

    pub fn is_empty(&self) -> bool {
        self.issues.is_empty()
    }

    pub fn len(&self) -> usize {
        self.issues.len()
    }

    /// Filters the issues in the collection to only include those with a severity level
    /// lower than or equal to the given level.
    pub fn with_maximum_level(self, level: Level) -> Self {
        Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
    }

    /// Filters the issues in the collection to only include those with a severity level
    ///  higher than or equal to the given level.
    pub fn with_minimum_level(self, level: Level) -> Self {
        Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
    }

    /// Returns `true` if the collection contains any issues with a severity level
    ///  higher than or equal to the given level.
    pub fn has_minimum_level(&self, level: Level) -> bool {
        self.issues.iter().any(|issue| issue.level >= level)
    }

    /// Returns the number of issues in the collection with the given severity level.
    pub fn get_level_count(&self, level: Level) -> usize {
        self.issues.iter().filter(|issue| issue.level == level).count()
    }

    /// Returns the highest severity level of the issues in the collection.
    pub fn get_highest_level(&self) -> Option<Level> {
        self.issues.iter().map(|issue| issue.level).max()
    }

    pub fn with_code(self, code: impl Into<String>) -> IssueCollection {
        let code = code.into();

        Self { issues: self.issues.into_iter().map(|issue| issue.with_code(&code)).collect() }
    }

    pub fn take_suggestions(&mut self) -> impl Iterator<Item = (SourceIdentifier, FixPlan)> + '_ {
        self.issues.iter_mut().flat_map(|issue| issue.take_suggestions())
    }

    pub fn only_fixable(self) -> impl Iterator<Item = Issue> {
        self.issues.into_iter().filter(|issue| !issue.suggestions.is_empty())
    }

    /// Sorts the issues in the collection.
    ///
    /// The issues are sorted by severity level in descending order,
    /// then by code in ascending order, and finally by the primary annotation span.
    pub fn sorted(self) -> Self {
        let mut issues = self.issues;

        issues.sort_by(|a, b| match a.level.cmp(&b.level) {
            Ordering::Greater => Ordering::Greater,
            Ordering::Less => Ordering::Less,
            Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
                Ordering::Less => Ordering::Less,
                Ordering::Greater => Ordering::Greater,
                Ordering::Equal => {
                    let a_span = a
                        .annotations
                        .iter()
                        .find(|annotation| annotation.is_primary())
                        .map(|annotation| annotation.span);

                    let b_span = b
                        .annotations
                        .iter()
                        .find(|annotation| annotation.is_primary())
                        .map(|annotation| annotation.span);

                    match (a_span, b_span) {
                        (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
                        (Some(_), None) => Ordering::Less,
                        (None, Some(_)) => Ordering::Greater,
                        (None, None) => Ordering::Equal,
                    }
                }
            },
        });

        Self { issues }
    }

    pub fn iter(&self) -> impl Iterator<Item = &Issue> {
        self.issues.iter()
    }

    pub fn to_fix_plans(self) -> HashMap<SourceIdentifier, FixPlan> {
        let mut plans: HashMap<SourceIdentifier, FixPlan> = HashMap::default();
        for issue in self.issues.into_iter().filter(|issue| !issue.suggestions.is_empty()) {
            for suggestion in issue.suggestions.into_iter() {
                match plans.entry(suggestion.0) {
                    Entry::Occupied(mut occupied_entry) => {
                        occupied_entry.get_mut().merge(suggestion.1);
                    }
                    Entry::Vacant(vacant_entry) => {
                        vacant_entry.insert(suggestion.1);
                    }
                }
            }
        }

        plans
    }
}

impl IntoIterator for IssueCollection {
    type Item = Issue;

    type IntoIter = std::vec::IntoIter<Issue>;

    fn into_iter(self) -> Self::IntoIter {
        self.issues.into_iter()
    }
}

impl Default for IssueCollection {
    fn default() -> Self {
        Self::new()
    }
}

impl IntoIterator for Issue {
    type Item = Issue;
    type IntoIter = Once<Issue>;

    fn into_iter(self) -> Self::IntoIter {
        std::iter::once(self)
    }
}

impl FromIterator<Issue> for IssueCollection {
    fn from_iter<T: IntoIterator<Item = Issue>>(iter: T) -> Self {
        Self { issues: iter.into_iter().collect() }
    }
}

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

    #[test]
    pub fn test_highest_collection_level() {
        let mut collection = IssueCollection::from(vec![]);
        assert_eq!(collection.get_highest_level(), None);

        collection.push(Issue::note("note"));
        assert_eq!(collection.get_highest_level(), Some(Level::Note));

        collection.push(Issue::help("help"));
        assert_eq!(collection.get_highest_level(), Some(Level::Help));

        collection.push(Issue::warning("warning"));
        assert_eq!(collection.get_highest_level(), Some(Level::Warning));

        collection.push(Issue::error("error"));
        assert_eq!(collection.get_highest_level(), Some(Level::Error));
    }

    #[test]
    pub fn test_level_downgrade() {
        assert_eq!(Level::Error.downgrade(), Level::Warning);
        assert_eq!(Level::Warning.downgrade(), Level::Help);
        assert_eq!(Level::Help.downgrade(), Level::Note);
        assert_eq!(Level::Note.downgrade(), Level::Note);
    }

    #[test]
    pub fn test_issue_collection_with_maximum_level() {
        let mut collection = IssueCollection::from(vec![
            Issue::error("error"),
            Issue::warning("warning"),
            Issue::help("help"),
            Issue::note("note"),
        ]);

        collection = collection.with_maximum_level(Level::Warning);
        assert_eq!(collection.len(), 3);
        assert_eq!(
            collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
            vec![Level::Warning, Level::Help, Level::Note]
        );
    }

    #[test]
    pub fn test_issue_collection_with_minimum_level() {
        let mut collection = IssueCollection::from(vec![
            Issue::error("error"),
            Issue::warning("warning"),
            Issue::help("help"),
            Issue::note("note"),
        ]);

        collection = collection.with_minimum_level(Level::Warning);
        assert_eq!(collection.len(), 2);
        assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
    }

    #[test]
    pub fn test_issue_collection_has_minimum_level() {
        let mut collection = IssueCollection::from(vec![]);

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(!collection.has_minimum_level(Level::Warning));
        assert!(!collection.has_minimum_level(Level::Help));
        assert!(!collection.has_minimum_level(Level::Note));

        collection.push(Issue::note("note"));

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(!collection.has_minimum_level(Level::Warning));
        assert!(!collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));

        collection.push(Issue::help("help"));

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(!collection.has_minimum_level(Level::Warning));
        assert!(collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));

        collection.push(Issue::warning("warning"));

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(collection.has_minimum_level(Level::Warning));
        assert!(collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));

        collection.push(Issue::error("error"));

        assert!(collection.has_minimum_level(Level::Error));
        assert!(collection.has_minimum_level(Level::Warning));
        assert!(collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));
    }

    #[test]
    pub fn test_issue_collection_level_count() {
        let mut collection = IssueCollection::from(vec![]);

        assert_eq!(collection.get_level_count(Level::Error), 0);
        assert_eq!(collection.get_level_count(Level::Warning), 0);
        assert_eq!(collection.get_level_count(Level::Help), 0);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::error("error"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 0);
        assert_eq!(collection.get_level_count(Level::Help), 0);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::warning("warning"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 1);
        assert_eq!(collection.get_level_count(Level::Help), 0);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::help("help"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 1);
        assert_eq!(collection.get_level_count(Level::Help), 1);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::note("note"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 1);
        assert_eq!(collection.get_level_count(Level::Help), 1);
        assert_eq!(collection.get_level_count(Level::Note), 1);
    }
}