Skip to main content

strata_editor/
diagnostics.rs

1//! LSP-compatible Diagnostics model merging real-time syntax diagnostics with external validators.
2
3use serde::{Deserialize, Serialize};
4
5use crate::cursor::Position;
6use crate::syntax::SyntaxDiagnostic;
7
8/// Diagnostic severity levels aligned with the Language Server Protocol (LSP).
9#[derive(
10    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
11)]
12pub enum DiagnosticSeverity {
13    #[default]
14    Hint = 1,
15    Info = 2,
16    Warning = 3,
17    Error = 4,
18}
19
20impl DiagnosticSeverity {
21    pub const fn label(self) -> &'static str {
22        match self {
23            Self::Error => "Error",
24            Self::Warning => "Warning",
25            Self::Info => "Info",
26            Self::Hint => "Hint",
27        }
28    }
29}
30
31/// A single diagnostic annotation anchored to a document range.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct EditorDiagnostic {
34    pub start: Position,
35    pub end: Position,
36    pub severity: DiagnosticSeverity,
37    pub message: String,
38    pub code: Option<String>,
39    pub source: Option<String>,
40}
41
42impl EditorDiagnostic {
43    pub fn new(
44        start: Position,
45        end: Position,
46        severity: DiagnosticSeverity,
47        message: impl Into<String>,
48    ) -> Self {
49        Self {
50            start,
51            end,
52            severity,
53            message: message.into(),
54            code: None,
55            source: None,
56        }
57    }
58
59    pub fn error(start: Position, end: Position, message: impl Into<String>) -> Self {
60        Self::new(start, end, DiagnosticSeverity::Error, message)
61    }
62
63    pub fn warning(start: Position, end: Position, message: impl Into<String>) -> Self {
64        Self::new(start, end, DiagnosticSeverity::Warning, message)
65    }
66
67    pub fn info(start: Position, end: Position, message: impl Into<String>) -> Self {
68        Self::new(start, end, DiagnosticSeverity::Info, message)
69    }
70
71    pub fn hint(start: Position, end: Position, message: impl Into<String>) -> Self {
72        Self::new(start, end, DiagnosticSeverity::Hint, message)
73    }
74
75    pub fn with_code(mut self, code: impl Into<String>) -> Self {
76        self.code = Some(code.into());
77        self
78    }
79
80    pub fn with_source(mut self, source: impl Into<String>) -> Self {
81        self.source = Some(source.into());
82        self
83    }
84
85    pub fn from_syntax_diagnostic(diag: &SyntaxDiagnostic) -> Self {
86        Self {
87            start: diag.start,
88            end: diag.end,
89            severity: if diag.is_warning {
90                DiagnosticSeverity::Warning
91            } else {
92                DiagnosticSeverity::Error
93            },
94            message: diag.message.clone(),
95            code: None,
96            source: Some("syntax".to_string()),
97        }
98    }
99
100    /// Returns whether this diagnostic overlaps the specified 0-indexed logical line.
101    #[inline]
102    pub fn covers_line(&self, line: usize) -> bool {
103        line >= self.start.line && line <= self.end.line
104    }
105}
106
107/// Summary count of diagnostics by severity for status bars and badges.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
109pub struct DiagnosticCounts {
110    pub errors: usize,
111    pub warnings: usize,
112    pub infos: usize,
113    pub hints: usize,
114}
115
116impl DiagnosticCounts {
117    pub const fn total(&self) -> usize {
118        self.errors + self.warnings + self.infos + self.hints
119    }
120}
121
122/// Container storing live syntax diagnostics alongside user/LSP-provided diagnostics.
123#[derive(Debug, Clone, Default)]
124pub struct DiagnosticCollection {
125    syntax_diagnostics: Vec<EditorDiagnostic>,
126    external_diagnostics: Vec<EditorDiagnostic>,
127    include_syntax_diagnostics: bool,
128}
129
130impl DiagnosticCollection {
131    pub fn new() -> Self {
132        Self {
133            syntax_diagnostics: Vec::new(),
134            external_diagnostics: Vec::new(),
135            include_syntax_diagnostics: true,
136        }
137    }
138
139    /// Enables or disables automatic inclusion of real-time syntax diagnostics.
140    pub fn set_include_syntax_diagnostics(&mut self, enabled: bool) {
141        self.include_syntax_diagnostics = enabled;
142    }
143
144    /// Replaces the live syntax diagnostics produced by `SyntaxHighlighter`.
145    pub fn set_syntax_diagnostics(&mut self, diags: Vec<SyntaxDiagnostic>) {
146        self.syntax_diagnostics = diags
147            .iter()
148            .map(EditorDiagnostic::from_syntax_diagnostic)
149            .collect();
150    }
151
152    /// Replaces external/LSP diagnostics without touching live syntax diagnostics.
153    pub fn set_external(&mut self, diagnostics: Vec<EditorDiagnostic>) {
154        self.external_diagnostics = diagnostics;
155    }
156
157    /// Appends a single external diagnostic.
158    pub fn push_external(&mut self, diagnostic: EditorDiagnostic) {
159        self.external_diagnostics.push(diagnostic);
160    }
161
162    /// Clears external diagnostics.
163    pub fn clear_external(&mut self) {
164        self.external_diagnostics.clear();
165    }
166
167    /// Iterates over all active diagnostics (syntax + external).
168    pub fn iter(&self) -> impl Iterator<Item = &EditorDiagnostic> {
169        let syntax_iter = if self.include_syntax_diagnostics {
170            self.syntax_diagnostics.as_slice()
171        } else {
172            &[]
173        };
174        syntax_iter.iter().chain(self.external_diagnostics.iter())
175    }
176
177    /// Collects all active diagnostics sorted by `(start, severity desc)`.
178    pub fn all_sorted(&self) -> Vec<EditorDiagnostic> {
179        let mut out: Vec<EditorDiagnostic> = self.iter().cloned().collect();
180        out.sort_by(|a, b| a.start.cmp(&b.start).then_with(|| b.severity.cmp(&a.severity)));
181        out
182    }
183
184    /// Returns all diagnostics overlapping `line`.
185    pub fn diagnostics_on_line(&self, line: usize) -> Vec<&EditorDiagnostic> {
186        self.iter().filter(|d| d.covers_line(line)).collect()
187    }
188
189    /// Returns the highest severity present on `line`, if any.
190    pub fn max_severity_on_line(&self, line: usize) -> Option<DiagnosticSeverity> {
191        self.iter()
192            .filter(|d| d.covers_line(line))
193            .map(|d| d.severity)
194            .max()
195    }
196
197    /// Counts errors, warnings, info, and hints across the document.
198    pub fn counts(&self) -> DiagnosticCounts {
199        let mut counts = DiagnosticCounts::default();
200        for diag in self.iter() {
201            match diag.severity {
202                DiagnosticSeverity::Error => counts.errors += 1,
203                DiagnosticSeverity::Warning => counts.warnings += 1,
204                DiagnosticSeverity::Info => counts.infos += 1,
205                DiagnosticSeverity::Hint => counts.hints += 1,
206            }
207        }
208        counts
209    }
210}