Skip to main content

runec/
diagnostics.rs

1use std::fmt;
2use std::path::{Path, PathBuf};
3use tracing::{error, info, warn};
4
5/// Render an opaque source label without consulting process state.
6pub fn format_path(path: &Path) -> String {
7    path.to_string_lossy().replace('\\', "/")
8}
9
10/// Severity level for diagnostics.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Severity {
13    Error,
14    Warning,
15    Info,
16}
17
18/// How safe it is to auto-apply a suggestion. Modelled on rustc's
19/// `Applicability`.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Applicability {
22    /// The suggestion is definitely correct; a `--fix` tool can apply it
23    /// without human review.
24    MachineApplicable,
25    /// The suggestion is likely correct but might need a minor tweak
26    /// (e.g. disambiguating an identifier). Should be reviewed before
27    /// auto-applying.
28    MaybeIncorrect,
29    /// The suggestion contains `<placeholder>` tokens that a human must
30    /// fill in before it compiles.
31    HasPlaceholders,
32    /// We don't know how confident to be.
33    Unspecified,
34}
35
36/// A single text replacement attached to a Help block.
37///
38/// Spans are inclusive line ranges (`(start_line, end_line)`) in
39/// `file`. The replacement is the full new text for that span. A
40/// "pure insertion" encodes as `start_line == end_line + 1` (insert
41/// before `start_line`) with a replacement containing the new lines.
42#[derive(Debug, Clone)]
43pub struct Suggestion {
44    pub file: PathBuf,
45    pub line_range: (usize, usize),
46    pub replacement: String,
47    /// Optional short label, e.g. "at the call site" or "at the label
48    /// header".
49    pub label: Option<String>,
50}
51
52/// A help message attached to a diagnostic. Mirrors rustc's
53/// `help:` line with an optional list of concrete suggestions.
54#[derive(Debug, Clone)]
55pub struct Help {
56    pub message: String,
57    pub suggestions: Vec<Suggestion>,
58    pub applicability: Applicability,
59}
60
61/// A single diagnostic message with source location.
62#[derive(Debug, Clone)]
63pub struct Diagnostic {
64    pub file: PathBuf,
65    pub line: usize,
66    pub column: usize,
67    pub message: String,
68    pub severity: Severity,
69    pub phase: Phase,
70    /// Optional help blocks with suggested fixes. Empty by default —
71    /// existing phases do not need to attach anything.
72    pub help: Vec<Help>,
73}
74
75/// Which compiler phase produced the diagnostic.
76///
77/// `SymbolRegistration` covers per-script validation that runs after parse
78/// but before type checking — trigger validity, redeclaration, return-type
79/// allowance, and trigger-subject resolvability. These used to claim
80/// `TypeChecking`, which lied about the source of the diagnostic.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Phase {
83    Lexing,
84    Parsing,
85    SymbolRegistration,
86    TypeChecking,
87    CodeGeneration,
88    PointerCheck,
89}
90
91impl fmt::Display for Diagnostic {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        let severity = match self.severity {
94            Severity::Error => "error",
95            Severity::Warning => "warning",
96            Severity::Info => "info",
97        };
98        // Suppress `:0` columns. Most phases (typechecker, symbol
99        // registration, pointer checker) don't carry column info — emitting
100        // `:0` falsely implies they do. Lexer/parser have real columns and
101        // still print them.
102        if self.column > 0 {
103            write!(
104                f,
105                "{}: {}\n  --> {}:{}:{}",
106                severity,
107                self.message,
108                format_path(&self.file),
109                self.line,
110                self.column,
111            )
112        } else {
113            write!(
114                f,
115                "{}: {}\n  --> {}:{}",
116                severity,
117                self.message,
118                format_path(&self.file),
119                self.line,
120            )
121        }
122    }
123}
124
125/// Collects diagnostics across all compiler phases.
126#[derive(Debug, Clone)]
127pub struct DiagnosticsCollector {
128    diagnostics: Vec<Diagnostic>,
129}
130
131impl DiagnosticsCollector {
132    pub fn new() -> Self {
133        DiagnosticsCollector {
134            diagnostics: Vec::new(),
135        }
136    }
137
138    pub fn add(&mut self, diagnostic: Diagnostic) {
139        self.diagnostics.push(diagnostic);
140    }
141
142    pub fn error(
143        &mut self,
144        file: PathBuf,
145        line: usize,
146        column: usize,
147        message: String,
148        phase: Phase,
149    ) {
150        self.add(Diagnostic {
151            file,
152            line,
153            column,
154            message,
155            severity: Severity::Error,
156            phase,
157            help: Vec::new(),
158        });
159    }
160
161    pub fn warning(
162        &mut self,
163        file: PathBuf,
164        line: usize,
165        column: usize,
166        message: String,
167        phase: Phase,
168    ) {
169        self.add(Diagnostic {
170            file,
171            line,
172            column,
173            message,
174            severity: Severity::Warning,
175            phase,
176            help: Vec::new(),
177        });
178    }
179
180    pub fn has_errors(&self) -> bool {
181        self.diagnostics
182            .iter()
183            .any(|d| d.severity == Severity::Error)
184    }
185
186    pub fn has_errors_in_phase(&self, phase: Phase) -> bool {
187        self.diagnostics
188            .iter()
189            .any(|d| d.severity == Severity::Error && d.phase == phase)
190    }
191
192    pub fn error_count(&self) -> usize {
193        self.diagnostics
194            .iter()
195            .filter(|d| d.severity == Severity::Error)
196            .count()
197    }
198
199    pub fn warning_count(&self) -> usize {
200        self.diagnostics
201            .iter()
202            .filter(|d| d.severity == Severity::Warning)
203            .count()
204    }
205
206    pub fn diagnostics(&self) -> &[Diagnostic] {
207        &self.diagnostics
208    }
209
210    pub fn errors(&self) -> Vec<&Diagnostic> {
211        self.diagnostics
212            .iter()
213            .filter(|d| d.severity == Severity::Error)
214            .collect()
215    }
216
217    pub fn print_all(&self) {
218        for diag in &self.diagnostics {
219            let msg = format!("{}", diag);
220            let help = render_help_string(diag);
221            let full = if help.is_empty() {
222                msg
223            } else {
224                format!("{}\n{}", msg, help)
225            };
226            match diag.severity {
227                Severity::Error => error!(target: "runec", "{}", full),
228                Severity::Warning => warn!(target: "runec", "{}", full),
229                Severity::Info => info!(target: "runec", "{}", full),
230            }
231        }
232        let errors = self.error_count();
233        let warnings = self.warning_count();
234        if errors > 0 || warnings > 0 {
235            info!(target: "runec", "{} error(s), {} warning(s) generated.", errors, warnings);
236        }
237    }
238
239    pub fn clear(&mut self) {
240        self.diagnostics.clear();
241    }
242
243    pub fn merge(&mut self, other: DiagnosticsCollector) {
244        self.diagnostics.extend(other.diagnostics);
245    }
246}
247
248impl Default for DiagnosticsCollector {
249    fn default() -> Self {
250        Self::new()
251    }
252}
253
254/// Render a diagnostic's attached help blocks beneath its main message,
255/// rustc-style. For each Help:
256///   - print a `help: <message>` line
257///   - for each Suggestion, print a unified-diff-ish window:
258///       -  <original line>                  (red in terminals)
259///       +  <replacement line>               (green in terminals)
260///          prefixed with the file path + line range and the suggestion label.
261///   - close with `= note: Applicability: <level>`
262///
263/// Source text is read lazily from disk; if the read fails we fall back
264/// to printing the replacement alone.
265fn render_help_string(diag: &Diagnostic) -> String {
266    if diag.help.is_empty() {
267        return String::new();
268    }
269    use std::fmt::Write;
270    let mut out = String::new();
271    for help in &diag.help {
272        let _ = writeln!(out, "help: {}", help.message);
273        for sug in &help.suggestions {
274            let path = format_path(&sug.file);
275            if let Some(label) = &sug.label {
276                let _ = writeln!(
277                    out,
278                    "  ┌─ {} {}:{}-{}",
279                    label, path, sug.line_range.0, sug.line_range.1
280                );
281            } else {
282                let _ = writeln!(
283                    out,
284                    "  ┌─ {}:{}-{}",
285                    path, sug.line_range.0, sug.line_range.1
286                );
287            }
288
289            let original = std::fs::read_to_string(&sug.file).ok().and_then(|src| {
290                let start = sug.line_range.0.saturating_sub(1);
291                let end = sug.line_range.1;
292                let lines: Vec<&str> = src.lines().collect();
293                if start < lines.len() && end <= lines.len() && start < end {
294                    Some(lines[start..end].join("\n"))
295                } else if start < lines.len() {
296                    Some(lines[start].to_string())
297                } else {
298                    None
299                }
300            });
301
302            match original {
303                Some(orig) => {
304                    for l in orig.lines() {
305                        let _ = writeln!(out, "  - {}", l);
306                    }
307                    for l in sug.replacement.lines() {
308                        let _ = writeln!(out, "  + {}", l);
309                    }
310                }
311                None => {
312                    for l in sug.replacement.lines() {
313                        let _ = writeln!(out, "  + {}", l);
314                    }
315                }
316            }
317        }
318        let appl = match help.applicability {
319            Applicability::MachineApplicable => "MachineApplicable (safe to auto-apply)",
320            Applicability::MaybeIncorrect => "MaybeIncorrect (review before applying)",
321            Applicability::HasPlaceholders => "HasPlaceholders (fill in the <…> tokens)",
322            Applicability::Unspecified => "Unspecified",
323        };
324        let _ = writeln!(out, "  = note: Applicability: {}", appl);
325    }
326    out.truncate(out.trim_end().len());
327    out
328}