omnicoach 0.3.0

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

architecture_component!(Diagnostic);

use serde::{Deserialize, Serialize};
use std::io::{self, BufWriter, Write as _};
use std::path::{Path, PathBuf};
use strum::VariantArray;

/// A programming language analyzed by the code linter; [`Language::VARIANTS`] lists them all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, VariantArray)]
pub enum Language {
    /// Python (`.py` files).
    Python,
    /// Rust (`.rs` files).
    Rust,
}

impl Language {
    /// The lowercase identifier naming the language in configuration keys
    /// (`[rules.<name>.python]`) and Markdown code fences.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Python => "python",
            Self::Rust => "rust",
        }
    }

    /// The language of `path`, from its extension, or `None` if the code linter does not
    /// analyze it.
    #[must_use]
    pub fn from_path(path: &Path) -> Option<Self> {
        match path.extension()?.to_str()? {
            "py" => Some(Self::Python),
            "rs" => Some(Self::Rust),
            _ => None,
        }
    }
}

/// The human-readable name: `Python`, `Rust`.
impl std::fmt::Display for Language {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Python => "Python",
            Self::Rust => "Rust",
        })
    }
}

/// Strongly-typed static rule identifier name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
#[serde(transparent)]
pub struct RuleName(pub &'static str);

impl std::fmt::Display for RuleName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Detailed explanation and description of a rule violation.
#[derive(Debug, Serialize, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ViolationMessage {
    /// A short summary of the violation.
    pub summary: String,
    /// The rationale or explanation of why the rule was triggered.
    pub rationale: String,
    /// A suggestion or workaround to resolve the violation.
    pub suggestion: String,
    /// How to excuse the violation with a comment, set by the framework when the rule's
    /// enforcement mode accepts one; never part of a rule's template.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub explanation_hint: Option<String>,
}

impl ViolationMessage {
    /// Constructs a `ViolationMessage` from string-like values, without an explanation hint.
    #[must_use]
    pub fn new(
        summary: impl Into<String>,
        rationale: impl Into<String>,
        suggestion: impl Into<String>,
    ) -> Self {
        Self {
            summary: summary.into(),
            rationale: rationale.into(),
            suggestion: suggestion.into(),
            explanation_hint: None,
        }
    }
}

/// A text string with an optional language-neutral fallback and language-specific overrides.
///
/// A field that overrides every language of its rule has no fallback: it would never be shown.
/// `tests/registry.rs` checks that each rule language resolves to exactly one reachable text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LanguageText {
    /// Text used when no language-specific override matches, absent when every language of
    /// the rule is overridden.
    pub base: Option<&'static str>,
    /// Language-specific overrides.
    pub overrides: &'static [(Language, &'static str)],
}

impl LanguageText {
    /// Creates a new `LanguageText` with an optional fallback and language-specific overrides.
    #[must_use]
    pub const fn new(
        base: Option<&'static str>,
        overrides: &'static [(Language, &'static str)],
    ) -> Self {
        Self { base, overrides }
    }

    /// Creates a `LanguageText` with no language overrides.
    #[must_use]
    pub const fn from_static(base: &'static str) -> Self {
        Self {
            base: Some(base),
            overrides: &[],
        }
    }

    /// Resolves the raw static text for the given language: its override, else the fallback.
    ///
    /// Empty only for a language the rule does not declare, which `tests/registry.rs` rules out.
    #[must_use]
    pub fn resolve_for_lang(&self, lang: Language) -> &'static str {
        self.overrides
            .iter()
            .find(|&&(override_lang, _)| override_lang == lang)
            .map(|&(_, text)| text)
            .or(self.base)
            .unwrap_or_default()
    }

    /// Resolves and interpolates named `{key}` placeholders for the given language.
    #[must_use]
    pub fn render_for_lang(&self, lang: Language, params: &[(&str, &str)]) -> String {
        Self::interpolate(self.resolve_for_lang(lang), params)
    }

    /// Interpolates named `{key}` placeholders on the fallback text (for language-independent
    /// rules, which always declare one).
    #[must_use]
    pub fn render(&self, params: &[(&str, &str)]) -> String {
        Self::interpolate(self.base.unwrap_or_default(), params)
    }

    /// Replaces each known `{key}` in one left-to-right pass, so substituted values are never
    /// re-scanned; unknown placeholders and unmatched braces are kept verbatim.
    fn interpolate(template: &str, params: &[(&str, &str)]) -> String {
        let mut result = String::with_capacity(template.len());
        let mut rest = template;
        while let Some(open) = rest.find('{') {
            result.push_str(&rest[..open]);
            let after_open = &rest[open + 1..];
            let substitution = after_open.find('}').and_then(|close| {
                let key = &after_open[..close];
                params
                    .iter()
                    .find(|&&(placeholder, _)| placeholder == key)
                    .map(|&(_, replacement)| (replacement, close))
            });
            if let Some((replacement, close)) = substitution {
                result.push_str(replacement);
                rest = &after_open[close + 1..];
            } else {
                result.push('{');
                rest = after_open;
            }
        }
        result.push_str(rest);
        result
    }
}

/// A declarative template for constructing [`ViolationMessage`]s.
///
/// Each rule has exactly one template, declared with `violation_template!`. Its three
/// fields are orthogonal and never repeat each other:
/// - [`summary`](Self::summary): what was observed on the flagged construct, as a fact.
/// - [`rationale`](Self::rationale): the concrete failure mode it causes.
/// - [`suggestion`](Self::suggestion): the single canonical fix, specialized per language.
///
/// Any field may override its text per language. `{placeholder}`s are filled in when
/// the rule renders a finding ([`Self::render_for_lang`]). Why the fields are split is
/// explained in `docs/dev/rule_design_guide.md` §2; their wording and the closed
/// placeholder list are fixed by `docs/dev/naming_and_message_style_guide.md` §2–3 and
/// checked by `tests/registry.rs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ViolationTemplate {
    /// Summary template: the observed fact, e.g. ``"Test calls `{callee}()`."``.
    pub summary: LanguageText,
    /// Rationale template: the failure mode, never the matched construct or the fix.
    pub rationale: LanguageText,
    /// Suggestion template: the canonical replacement, never a restatement of the problem.
    pub suggestion: LanguageText,
}

impl ViolationTemplate {
    /// Creates a new `ViolationTemplate`.
    #[must_use]
    pub const fn new(
        summary: LanguageText,
        rationale: LanguageText,
        suggestion: LanguageText,
    ) -> Self {
        Self {
            summary,
            rationale,
            suggestion,
        }
    }

    /// Creates a template with uniform static text and no language overrides.
    #[must_use]
    pub const fn from_static(
        summary: &'static str,
        rationale: &'static str,
        suggestion: &'static str,
    ) -> Self {
        Self {
            summary: LanguageText::from_static(summary),
            rationale: LanguageText::from_static(rationale),
            suggestion: LanguageText::from_static(suggestion),
        }
    }

    /// Renders the base template into a concrete `ViolationMessage` (for command/language-independent rules).
    #[must_use]
    pub fn render(&self, params: &[(&str, &str)]) -> ViolationMessage {
        ViolationMessage {
            summary: self.summary.render(params),
            rationale: self.rationale.render(params),
            suggestion: self.suggestion.render(params),
            explanation_hint: None,
        }
    }

    /// Renders the template into a concrete `ViolationMessage` for a specific programming language.
    #[must_use]
    pub fn render_for_lang(&self, lang: Language, params: &[(&str, &str)]) -> ViolationMessage {
        ViolationMessage {
            summary: self.summary.render_for_lang(lang, params),
            rationale: self.rationale.render_for_lang(lang, params),
            suggestion: self.suggestion.render_for_lang(lang, params),
            explanation_hint: None,
        }
    }
}

/// Declaratively constructs a `const` [`ViolationTemplate`].
///
/// Fields can either be static strings or blocks with one text per language of the rule:
/// ```rust,ignore
/// violation_template! {
///     summary: "Test function `{func}` has {count} assertions...",
///     rationale: "Tests with too many assertions often verify multiple unrelated behaviors...",
///     suggestion: {
///         Python => "Use `@pytest.mark.parametrize`...",
///         Rust => "Use `#[rstest]`...",
///     },
/// }
/// ```
macro_rules! violation_template {
    // Internal arm: field overriding every language of the rule
    (@text { $($lang:ident => $text:expr),+ $(,)? }) => {
        $crate::diagnostic::LanguageText::new(
            None,
            &[$(($crate::diagnostic::Language::$lang, $text)),+],
        )
    };
    // Internal arm: static string field
    (@text $base:expr) => {
        $crate::diagnostic::LanguageText::from_static($base)
    };

    (
        summary: $summary:tt,
        rationale: $rationale:tt,
        suggestion: $suggestion:tt $(,)?
    ) => {
        $crate::diagnostic::ViolationTemplate::new(
            $crate::diagnostic::violation_template!(@text $summary),
            $crate::diagnostic::violation_template!(@text $rationale),
            $crate::diagnostic::violation_template!(@text $suggestion),
        )
    };
}

pub(crate) use violation_template;

/// The default virtual location context name for VCS changes.
pub const VCS_CONTEXT_NAME: &str = "VCS_Context";

/// Represents the file or environment context of a diagnostic.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum LocationContext {
    /// A physical file on disk.
    File(PathBuf),
    /// A virtual execution context (e.g., `VCS_Context`).
    Virtual(String),
}

impl std::fmt::Display for LocationContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::File(path) => write!(f, "{}", path.display()),
            Self::Virtual(name) => write!(f, "{name}"),
        }
    }
}

impl Serialize for LocationContext {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::File(path) => serializer.serialize_str(&path.to_string_lossy()),
            Self::Virtual(name) => serializer.serialize_str(name),
        }
    }
}

/// A byte range span (start, end) inside a source file.
#[derive(
    Debug, Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct SourceSpan {
    /// Start byte offset (inclusive).
    pub start: usize,
    /// End byte offset (exclusive).
    pub end: usize,
}

impl SourceSpan {
    /// Creates a new `SourceSpan`.
    #[must_use]
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    /// Creates a `SourceSpan` from an AST node byte range.
    #[must_use]
    pub const fn from_range(range: std::ops::Range<usize>) -> Self {
        Self {
            start: range.start,
            end: range.end,
        }
    }

    /// Returns true if `self` encloses `other` (`self.start <= other.start && other.end <= self.end`).
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.start <= other.start && other.end <= self.end
    }
}

// TODO: Should we use line-index of the line/column?
/// Represents a location span and 1-indexed coordinate inside a source file or linter context.
#[derive(Debug, Serialize, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct SourceLocation {
    /// The file path or virtual context name.
    pub context: LocationContext,
    /// The byte range span of the violation.
    pub span: SourceSpan,
    /// 1-indexed start line number.
    pub line: usize,
    /// 1-indexed start column number.
    pub column: usize,
}

impl SourceLocation {
    /// Creates a `SourceLocation` for a file path, byte span, and resolved 1-indexed coordinate.
    #[must_use]
    pub fn file_span(path: impl Into<PathBuf>, span: SourceSpan, coord: LineColumn) -> Self {
        Self {
            context: LocationContext::File(path.into()),
            span,
            line: coord.line,
            column: coord.column,
        }
    }

    /// Creates a `SourceLocation` for a virtual context, resolving `(line, column)` from `content`.
    #[must_use]
    pub fn virtual_span(name: impl Into<String>, content: &str, span: SourceSpan) -> Self {
        let coord = LineIndex::new(content).lookup(span.start);
        Self {
            context: LocationContext::Virtual(name.into()),
            span,
            line: coord.line,
            column: coord.column,
        }
    }

    /// Formats the source location into a user-friendly coordinate header (e.g. `path/to/file.rs:10:4`).
    #[must_use]
    pub fn format_header(&self) -> String {
        format!("{}:{}:{}", self.context, self.line, self.column)
    }
}

/// An alert diagnostic containing a rule violation payload and its source location.
#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    /// The rule name (e.g., "edit-of-described-commit").
    pub rule_name: RuleName,
    /// The detailed explanation and description of the rule violation.
    pub message: ViolationMessage,
    /// The source location where the violation occurred.
    pub location: SourceLocation,
}

impl Ord for Diagnostic {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.location
            .cmp(&other.location)
            .then_with(|| self.rule_name.cmp(&other.rule_name))
            .then_with(|| self.message.cmp(&other.message))
    }
}

impl PartialOrd for Diagnostic {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Diagnostic {
    /// Creates a new diagnostic.
    #[must_use]
    pub const fn new(
        rule_name: RuleName,
        message: ViolationMessage,
        location: SourceLocation,
    ) -> Self {
        Self {
            rule_name,
            message,
            location,
        }
    }
}

/// A 1-indexed line and column coordinate inside a file.
#[derive(Debug, Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq)]
pub struct LineColumn {
    /// 1-indexed line number.
    pub line: usize,
    /// 1-indexed column number.
    pub column: usize,
}

/// Optimized index for mapping flat byte offsets to 1-indexed (line, column) positions.
pub(crate) struct LineIndex {
    inner: line_index::LineIndex,
}

impl LineIndex {
    /// Creates a new `LineIndex` for the given file content.
    #[must_use]
    pub(crate) fn new(content: &str) -> Self {
        Self {
            inner: line_index::LineIndex::new(content),
        }
    }

    /// Resolves a byte offset to a 1-indexed (line, column) coordinate.
    #[must_use]
    pub(crate) fn lookup(&self, offset: usize) -> LineColumn {
        let line_col = self.inner.line_col(line_index::TextSize::from(
            u32::try_from(offset).unwrap_or(u32::MAX),
        ));
        LineColumn {
            line: line_col.line as usize + 1,
            column: line_col.col as usize + 1,
        }
    }

    /// Resolves a byte offset to a 1-indexed line number.
    #[must_use]
    pub(crate) fn line(&self, offset: usize) -> usize {
        self.lookup(offset).line
    }
}

/// Output format of diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
    /// Human-readable text
    Plain,
    /// Pretty-printed JSON array
    Json,
}

/// Formats and prints a list of diagnostics to stdout.
///
/// Supports JSON pretty-printing and plain text with pre-resolved line-column coordinates.
///
/// # Errors
///
/// Returns an error if JSON serialization or writing to stdout fails.
pub fn print_diagnostics(diagnostics: &[Diagnostic], format: OutputFormat) -> anyhow::Result<()> {
    if format == OutputFormat::Json {
        let mut sorted: Vec<&Diagnostic> = diagnostics.iter().collect();
        sorted.sort_unstable();
        println!("{}", serde_json::to_string_pretty(&sorted)?);
    } else {
        let mut stdout = BufWriter::new(io::stdout().lock());
        stdout.write_all(format_plain(diagnostics).as_bytes())?;
        stdout.flush()?;
    }
    Ok(())
}

/// Formats a slice of diagnostics into deterministic human-readable plain text.
#[must_use]
pub fn format_plain(diagnostics: &[Diagnostic]) -> String {
    use std::fmt::Write as _;

    let mut sorted: Vec<&Diagnostic> = diagnostics.iter().collect();
    sorted.sort_unstable();

    let mut output = String::new();
    for diagnostic in sorted {
        let location_header = diagnostic.location.format_header();
        let hint_line = diagnostic
            .message
            .explanation_hint
            .as_ref()
            .map(|hint| format!("  Or: {hint}\n"))
            .unwrap_or_default();

        let _ = indoc::writedoc!(
            output,
            "
            {}: [{}] {}
              Rationale: {}
              Suggestion: {}
            {}
            ",
            location_header,
            diagnostic.rule_name,
            diagnostic.message.summary,
            diagnostic.message.rationale,
            diagnostic.message.suggestion,
            hint_line
        );
    }
    output
}

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

    #[test]
    fn test_language_text_resolve_and_render() {
        const ADVICE: LanguageText = LanguageText::new(
            Some("Parameterize variations for {func}"),
            &[(Language::Python, "Use @pytest.mark.parametrize for {func}")],
        );

        assert_eq!(
            ADVICE.resolve_for_lang(Language::Python),
            "Use @pytest.mark.parametrize for {func}"
        );
        assert_eq!(
            ADVICE.render_for_lang(Language::Python, &[("func", "test_math")]),
            "Use @pytest.mark.parametrize for test_math"
        );
        assert_eq!(
            ADVICE.render_for_lang(Language::Rust, &[("func", "test_math")]),
            "Parameterize variations for test_math"
        );
        assert_eq!(
            ADVICE.render(&[("func", "test_math")]),
            "Parameterize variations for test_math"
        );
    }

    #[rstest::rstest]
    #[case::value_not_rescanned("{a} {b}", &[("a", "{b}"), ("b", "X")], "{b} X")]
    #[case::unknown_placeholder_kept("{a} {missing}", &[("a", "X")], "X {missing}")]
    #[case::unclosed_brace_kept("{a} {", &[("a", "X")], "X {")]
    fn test_language_text_interpolation(
        #[case] template: &'static str,
        #[case] params: &[(&str, &str)],
        #[case] expected: &str,
    ) {
        assert_eq!(LanguageText::from_static(template).render(params), expected);
    }

    #[test]
    fn test_violation_template_macro() {
        const TEMPLATE: ViolationTemplate = violation_template! {
            summary: "Function `{func}` too long",
            rationale: "Long functions are hard to read",
            suggestion: {
                Python => "Refactor `{func}` with helper functions",
                Rust => "Extract logic from `{func}` into sub-functions",
            },
        };

        assert_eq!(
            TEMPLATE.render_for_lang(Language::Python, &[("func", "process_data")]),
            ViolationMessage::new(
                "Function `process_data` too long",
                "Long functions are hard to read",
                "Refactor `process_data` with helper functions",
            )
        );

        assert_eq!(
            TEMPLATE.render_for_lang(Language::Rust, &[("func", "process_data")]),
            ViolationMessage::new(
                "Function `process_data` too long",
                "Long functions are hard to read",
                "Extract logic from `process_data` into sub-functions",
            )
        );
    }

    #[test]
    fn test_source_location_file_span() {
        let loc = SourceLocation::file_span(
            "src/main.rs",
            SourceSpan::new(16, 31),
            LineColumn { line: 2, column: 5 },
        );
        assert_eq!(loc.format_header(), "src/main.rs:2:5");
        assert_eq!(
            serde_json::to_value(&loc).ok(),
            Some(serde_json::json!({
                "context": "src/main.rs",
                "span": { "start": 16, "end": 31 },
                "line": 2,
                "column": 5,
            }))
        );
    }

    #[test]
    fn test_source_location_virtual_span() {
        let virtual_loc = SourceLocation::virtual_span(
            VCS_CONTEXT_NAME,
            "echo ok\njj edit main",
            SourceSpan::new(8, 20),
        );
        assert_eq!(
            virtual_loc,
            SourceLocation {
                context: LocationContext::Virtual(VCS_CONTEXT_NAME.to_string()),
                span: SourceSpan::new(8, 20),
                line: 2,
                column: 1,
            }
        );
        assert_eq!(virtual_loc.format_header(), "VCS_Context:2:1");
    }

    #[test]
    fn test_diagnostic_canonical_ordering() {
        let message_a = ViolationMessage::new("Summary A", "Rationale A", "Suggestion A");
        let message_b = ViolationMessage::new("Summary B", "Rationale B", "Suggestion B");

        let diag1 = Diagnostic::new(
            RuleName("rule-b"),
            message_a.clone(),
            SourceLocation::file_span(
                "src/b.rs",
                SourceSpan::new(10, 20),
                LineColumn { line: 2, column: 1 },
            ),
        );
        let diag2 = Diagnostic::new(
            RuleName("rule-a"),
            message_a,
            SourceLocation::file_span(
                "src/a.rs",
                SourceSpan::new(5, 15),
                LineColumn { line: 1, column: 1 },
            ),
        );
        let diag3 = Diagnostic::new(
            RuleName("rule-a"),
            message_b,
            SourceLocation::file_span(
                "src/a.rs",
                SourceSpan::new(5, 15),
                LineColumn { line: 1, column: 1 },
            ),
        );

        let mut diagnostics = vec![diag1.clone(), diag3.clone(), diag2.clone()];
        diagnostics.sort_unstable();

        assert_eq!(diagnostics, vec![diag2, diag3, diag1]);
    }
}