htl_core/diagnostic.rs
1//! What a check reported, as a value rather than as a line of text.
2//!
3//! The checker formats its findings as `"<file>:<line>:<col>: <message>"`, and a lint
4//! adds ` [htl <rule>]`. Every reader that wants the position back — `--format json`,
5//! `htl fix`, and whatever comes next (an LSP, `--watch`, a `build.rs` that fails on a
6//! lint) — used to take that string apart for itself. [`Diagnostic::parse`] is the one
7//! place that does it now, and it lives here, beside the fix and the severity it hands
8//! over, rather than in each caller.
9//!
10//! The text is still what the checker produces and what the run cache stores, so it is
11//! parsed here rather than reconstructed: a report and a replay of it print the string
12//! the checker wrote, and only readers that ask for the parts pay for the split.
13
14use crate::Fix;
15use serde::Serialize;
16use std::path::{Component, Path, PathBuf};
17
18/// How loud a diagnostic is. `error` fails a check; `warning` and `lint` do not unless
19/// the caller promotes them (`htl check --strict`, `include_tl!`).
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
21#[serde(rename_all = "lowercase")]
22pub enum Severity {
23 /// The file did not type-check. From the Teal checker, and the only severity that
24 /// fails a run on its own.
25 Error,
26 /// A kind the Teal compiler reports for itself — an unused local, a redeclaration —
27 /// which htl surfaces under the rule name of its kind (`tl:unused`, ...) rather than
28 /// inventing one.
29 Warning,
30 /// A finding of one of htl's own rules. The only severity whose diagnostics carry a
31 /// [`rule`](Diagnostic::rule), because a rule is what a project sets a level for.
32 Lint,
33}
34
35impl Severity {
36 /// The lowercase word this severity is written as: in the `<severity>:` a report
37 /// prints, in `--format json`, and in the run cache. [`parse`](Self::parse) reads it
38 /// back, so the two are the one spelling that crosses between a run and a replay of it.
39 pub fn as_str(self) -> &'static str {
40 match self {
41 Severity::Error => "error",
42 Severity::Warning => "warning",
43 Severity::Lint => "lint",
44 }
45 }
46
47 /// The inverse of [`as_str`](Self::as_str). `None` for anything else, which is the
48 /// answer a reader of stored diagnostics wants: an entry written by a build that
49 /// knew a fourth severity is refused rather than guessed at.
50 pub fn parse(s: &str) -> Option<Self> {
51 match s {
52 "error" => Some(Severity::Error),
53 "warning" => Some(Severity::Warning),
54 "lint" => Some(Severity::Lint),
55 _ => None,
56 }
57 }
58}
59
60impl std::fmt::Display for Severity {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 f.write_str(self.as_str())
63 }
64}
65
66/// One `error:` / `warning:` / `lint:` finding, split into its parts.
67///
68/// The serialized form is what `htl check --format json` prints. Field names are stable;
69/// new fields may be added, existing ones are not renamed.
70#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
71pub struct Diagnostic {
72 /// Which of the three this is, and so whether a run that reported it fails — the
73 /// caller's to decide for a `warning` or a `lint`, settled for an `error`.
74 pub severity: Severity,
75 /// The file the diagnostic is in, as the report spells it. Empty when the text
76 /// carried no position (a failure that is about a file rather than a place in one).
77 pub file: String,
78 /// The line, counted from 1 as the checker counts it. `0` alongside an empty
79 /// [`file`](Self::file): the text carried no position, rather than pointing at a
80 /// first line.
81 pub line: usize,
82 /// The column, counted from 1, and `0` under the same condition as
83 /// [`line`](Self::line).
84 pub col: usize,
85 /// The lint rule (`nil-index`, `contract`, ...) for `lint` diagnostics, or a Teal
86 /// warning's kind (`tl:unused`, ...) for a `warning`, kept apart from the message. On
87 /// an error the checker raised it is the class `htl fix` files that error's fix under
88 /// (`forward-ref`, `tl:error`), the same name `htl fix --format json` gives it.
89 #[serde(skip_serializing_if = "Option::is_none")]
90 pub rule: Option<String>,
91 /// What the finding says, with the position prefix and the ` [htl <rule>]` suffix
92 /// taken off — the sentence alone, so a reader that formats its own line does not
93 /// have to unpick one.
94 pub message: String,
95 /// A mechanical rewrite `htl fix` may apply, when the diagnostic has one.
96 #[serde(skip_serializing_if = "Option::is_none")]
97 pub fix: Option<Fix>,
98 /// For an error in a module the check reached through `require`: the file whose
99 /// require pulled it in. Absent on the project's own diagnostics.
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub required_by: Option<String>,
102 /// Where such a file lives: `dependency` (installed under `.htl/modules`, a vendored
103 /// copy, or the declarations a crate ships under `types/<crate>/`) or `external` (a
104 /// `[check] paths` or contract directory). Absent for a file of the project's own, a
105 /// patched dependency included, and on the project's own diagnostics. Decided by the
106 /// module whose directory holds the file ([`crate::model::Owner::origin`]), the same
107 /// module `htl resolve` names a file's origin from.
108 #[serde(skip_serializing_if = "Option::is_none")]
109 pub origin: Option<String>,
110}
111
112/// The text form, and the only place it is made: `<file>:<line>:<col>: <message>`, the
113/// position left out when there is none, and ` [htl <rule>]` after a warning's or a lint's
114/// message. An error's rule is the class its fix is filed under and is not printed: the
115/// text of an error has never carried one.
116///
117/// Every line htl prints about a finding comes from here, whether the finding was just made
118/// or read back from the store, so the two cannot drift apart.
119impl std::fmt::Display for Diagnostic {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 if !self.file.is_empty() || self.line != 0 {
122 write!(f, "{}:{}:{}: ", self.file, self.line, self.col)?;
123 }
124 f.write_str(&self.message)?;
125 if self.severity != Severity::Error
126 && let Some(rule) = &self.rule
127 {
128 write!(f, " [htl {rule}]")?;
129 }
130 Ok(())
131 }
132}
133
134impl Diagnostic {
135 /// A finding made by htl rather than read from the checker: `file` as the report
136 /// should spell it, the 1-based position, the sentence alone, and the rule it is said
137 /// under (`None` for an error that is not a lint's). `fix`, `required_by` and `origin`
138 /// start empty.
139 pub fn new(
140 severity: Severity,
141 file: impl Into<String>,
142 line: usize,
143 col: usize,
144 message: impl Into<String>,
145 rule: Option<&str>,
146 ) -> Self {
147 Self {
148 severity,
149 file: file.into(),
150 line,
151 col,
152 rule: rule.map(str::to_string),
153 message: message.into(),
154 fix: None,
155 required_by: None,
156 origin: None,
157 }
158 }
159
160 /// The same finding with its paths — [`file`](Self::file) and
161 /// [`required_by`](Self::required_by) — spelled as every report spells a path
162 /// ([`display_path`]). The checker names a file as it was handed it (`./src/a.tl`, or
163 /// absolute from a search path); a reader that prints a diagnostic takes it through
164 /// here first, so a failed `include_tl!`, a junit body and `htl check` name one file
165 /// one way.
166 pub fn spelled(mut self) -> Self {
167 if !self.file.is_empty() {
168 self.file = display_path(Path::new(&self.file));
169 }
170 if let Some(by) = &self.required_by {
171 self.required_by = Some(display_path(Path::new(by)));
172 }
173 self
174 }
175
176 /// `"<file>:<line>:<col>: <message>"` — what the checker formats — into its parts.
177 /// Text that is not in that shape keeps the whole of itself as the message, with no
178 /// file and no position.
179 ///
180 /// `fix`, `required_by` and `origin` are the caller's to fill in: they are not in the
181 /// text, they travel beside it.
182 pub fn parse(severity: Severity, text: &str) -> Self {
183 let Some((file, line, col, msg)) = position(text) else {
184 let (message, rule) = split_rule(text);
185 return Self {
186 severity,
187 file: String::new(),
188 line: 0,
189 col: 0,
190 rule,
191 message,
192 fix: None,
193 required_by: None,
194 origin: None,
195 };
196 };
197 let (message, rule) = split_rule(msg.trim_start());
198 Self {
199 severity,
200 file: file.to_string(),
201 line,
202 col,
203 rule,
204 message,
205 fix: None,
206 required_by: None,
207 origin: None,
208 }
209 }
210}
211
212/// The `<file>`, `<line>`, `<col>` and the rest of `"<file>:<line>:<col>: <message>"`.
213/// `None` when the text is not in that shape.
214///
215/// The only place a diagnostic's text is taken apart. `file` is a prefix of `text`, so a
216/// caller that wants to rewrite the file and keep the rest can slice by its length.
217pub fn position(text: &str) -> Option<(&str, usize, usize, &str)> {
218 let (file, rest) = text.split_once(':')?;
219 let (line, rest) = rest.split_once(':')?;
220 let (col, message) = rest.split_once(':')?;
221 Some((
222 file,
223 line.trim().parse().ok()?,
224 col.trim().parse().ok()?,
225 message,
226 ))
227}
228
229/// The rule name a finding's text ends with (` [htl <rule>]`), borrowed from it.
230///
231/// For a caller that has the text and wants only the name: which rule a run reported
232/// under, so its level can be asked for. Reading the whole diagnostic is
233/// [`Diagnostic::parse`], and both take the suffix apart here.
234pub fn rule_of(text: &str) -> Option<&str> {
235 if !text.ends_with(']') {
236 return None;
237 }
238 let start = text.rfind(" [htl ")?;
239 let rule = &text[start + " [htl ".len()..text.len() - 1];
240 (!rule.is_empty() && !rule.contains(' ')).then_some(rule)
241}
242
243/// Lint messages end with ` [htl <rule>]`. Splitting it off leaves the message reading
244/// as a sentence and the rule available as a name to filter on.
245fn split_rule(msg: &str) -> (String, Option<String>) {
246 match rule_of(msg) {
247 // The suffix is ` [htl ` + the name + `]`: seven characters around it.
248 Some(rule) => (
249 msg[..msg.len() - rule.len() - 7].to_string(),
250 Some(rule.to_string()),
251 ),
252 None => (msg.to_string(), None),
253 }
254}
255
256/// Relative to the directory the command ran in when it is under it, normalised absolute
257/// when it is not — a dependency outside the project reads better that way than as a stack
258/// of `..`.
259///
260/// Public because it is how *a* path reads in this tool's output, not how a diagnostic's
261/// does: `crate::unused` reports files the walk found rather than diagnostics, and the
262/// two must spell one file the same way.
263pub fn display_path(p: &Path) -> String {
264 let Ok(cwd) = std::env::current_dir() else {
265 return lexical(p).display().to_string();
266 };
267 // Against the working directory first: a relative path's leading `..` says where it
268 // is from here, and folding it without that — `../src/a.tl` to `src/a.tl` — names a
269 // different file.
270 let norm = lexical(&cwd.join(p));
271 match norm.strip_prefix(&cwd) {
272 Ok(rel) => rel.display().to_string(),
273 Err(_) => norm.display().to_string(),
274 }
275}
276
277/// Fold `.` and `..` without touching the filesystem.
278///
279/// [`std::fs::canonicalize`] would resolve symlinks too, and `.htl/modules/entries/<dep>`
280/// is one: following it names mlua-pkg's cache directory rather than the dependency, which
281/// is the opposite of what a report wants to say.
282fn lexical(p: &Path) -> PathBuf {
283 let mut out = PathBuf::new();
284 for c in p.components() {
285 match c {
286 Component::ParentDir => {
287 out.pop();
288 }
289 Component::CurDir => {}
290 c => out.push(c.as_os_str()),
291 }
292 }
293 out
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 #[test]
301 fn parses_position_and_message() {
302 let d = Diagnostic::parse(
303 Severity::Error,
304 "src/a.tl:12:3: expected string, got integer",
305 );
306 assert_eq!(d.file, "src/a.tl");
307 assert_eq!((d.line, d.col), (12, 3));
308 assert_eq!(d.message, "expected string, got integer");
309 assert_eq!(d.rule, None);
310 }
311
312 #[test]
313 fn splits_the_lint_rule_off_the_message() {
314 let d = Diagnostic::parse(
315 Severity::Lint,
316 "src/a.tl:4:1: t.x may be nil [htl nil-index]",
317 );
318 assert_eq!(d.rule.as_deref(), Some("nil-index"));
319 assert_eq!(d.message, "t.x may be nil");
320 }
321
322 #[test]
323 fn text_without_a_position_keeps_all_of_itself() {
324 let d = Diagnostic::parse(Severity::Error, "src/a.tl: generate failed: boom");
325 assert_eq!(d.file, "");
326 assert_eq!((d.line, d.col), (0, 0));
327 assert_eq!(d.message, "src/a.tl: generate failed: boom");
328 }
329
330 #[test]
331 fn a_bracket_that_is_not_a_rule_stays_in_the_message() {
332 let d = Diagnostic::parse(Severity::Lint, "src/a.tl:1:1: see [htl two words]");
333 assert_eq!(d.rule, None);
334 assert_eq!(d.message, "see [htl two words]");
335 }
336
337 #[test]
338 fn severity_round_trips_through_its_name() {
339 for s in [Severity::Error, Severity::Warning, Severity::Lint] {
340 assert_eq!(Severity::parse(s.as_str()), Some(s));
341 }
342 assert_eq!(Severity::parse("fatal"), None);
343 }
344
345 #[test]
346 fn spelled_folds_the_file_and_the_requirer_and_leaves_a_positionless_one_alone() {
347 let cwd = std::env::current_dir().unwrap();
348 let mut d = Diagnostic::new(Severity::Error, "./src/x/../a.tl", 1, 2, "boom", None);
349 d.required_by = Some(cwd.join("src/b.tl").display().to_string());
350 let d = d.spelled();
351 assert_eq!(d.file, "src/a.tl");
352 assert_eq!(d.required_by.as_deref(), Some("src/b.tl"));
353 assert_eq!(d.to_string(), "src/a.tl:1:2: boom");
354
355 let bare = Diagnostic::new(Severity::Error, "", 0, 0, "a.tl: generate failed", None);
356 assert_eq!(bare.clone().spelled(), bare);
357 }
358}