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
mod hir;

use mun_hir::InFile;
use mun_syntax::TextRange;

///! This crate provides in-depth human-readable diagnostic information and fixes for compiler
///! errors that can be shared between the compiler and the language server.
///!
///! The processing of diagnostics into human-readable is separated from the machine-readable
///! diagnostics in for instance the HIR crate for performance reasons. This enables lazily querying
///! the system for more information only when required.

/// An annotation within the source code
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SourceAnnotation {
    /// The location in the source
    pub range: TextRange,

    /// The message
    pub message: String,
}

/// An annotation within the source code
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SecondaryAnnotation {
    /// The location in the source
    pub range: InFile<TextRange>,

    /// The message
    pub message: String,
}

/// The base trait for all diagnostics in this crate.
pub trait Diagnostic {
    /// Returns the primary message of the diagnostic.
    fn title(&self) -> String;

    /// Returns the location of this diagnostic.
    fn range(&self) -> TextRange;

    /// Returns a source annotation that acts as the primary annotation for this Diagnostic.
    fn primary_annotation(&self) -> Option<SourceAnnotation>;

    /// Returns secondary source annotation that are shown as additional references.
    fn secondary_annotations(&self) -> Vec<SecondaryAnnotation> {
        Vec::new()
    }

    /// Optional footer text
    fn footer(&self) -> Vec<String> {
        Vec::new()
    }
}

/// When implemented enables requesting `Diagnostic`s for the implementer.
pub trait DiagnosticFor {
    /// Calls the specified function `f` with an instance of a [`Diagnostic`]. This can be used
    /// to perform lazy diagnostic evaluation.
    fn with_diagnostic<R, F: FnMut(&dyn Diagnostic) -> R>(&self, f: F) -> R;
}

/// Like [`DiagnosticFor`], enables requesting `Diagnostic`s for the implementer but only if passed
/// a required object.
pub trait DiagnosticForWith<With> {
    /// Calls the specified function `f` with an instance of a [`Diagnostic`]. This can be used
    /// to perform lazy diagnostic evaluation.
    fn with_diagnostic<R, F: FnMut(&dyn Diagnostic) -> R>(&self, with: &With, f: F) -> R;
}

impl Into<SourceAnnotation> for SecondaryAnnotation {
    fn into(self) -> SourceAnnotation {
        SourceAnnotation {
            range: self.range.value,
            message: self.message,
        }
    }
}