1use std::fmt;
2use std::path::{Path, PathBuf};
3use tracing::{error, info, warn};
4
5pub fn format_path(path: &Path) -> String {
7 path.to_string_lossy().replace('\\', "/")
8}
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Severity {
13 Error,
14 Warning,
15 Info,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Applicability {
22 MachineApplicable,
25 MaybeIncorrect,
29 HasPlaceholders,
32 Unspecified,
34}
35
36#[derive(Debug, Clone)]
43pub struct Suggestion {
44 pub file: PathBuf,
45 pub line_range: (usize, usize),
46 pub replacement: String,
47 pub label: Option<String>,
50}
51
52#[derive(Debug, Clone)]
55pub struct Help {
56 pub message: String,
57 pub suggestions: Vec<Suggestion>,
58 pub applicability: Applicability,
59}
60
61#[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 pub help: Vec<Help>,
73}
74
75#[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 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#[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
254fn 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}