Skip to main content

runec/
diagnostics.rs

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