Skip to main content

constructo_runtime/
diagnostics.rs

1//! Source positions and diagnostics.
2
3use std::fmt;
4
5/// A position in a source text. Both fields are 1-based and the column counts characters.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
7pub struct Pos {
8    /// The line, from 1.
9    pub line: u32,
10    /// The column, from 1, in characters.
11    pub col: u32,
12}
13
14impl Pos {
15    /// The position of a byte offset in a text, counting characters. An offset past the end is the end.
16    pub fn at(text: &str, offset: usize) -> Pos {
17        let before = &text[..offset.min(text.len())];
18        let line = before.matches('\n').count() as u32 + 1;
19        let col = before.rsplit('\n').next().map_or(0, |last| last.chars().count()) as u32 + 1;
20        Pos { line, col }
21    }
22}
23
24impl fmt::Display for Pos {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "line {}, col {}", self.line, self.col)
27    }
28}
29
30/// How serious a diagnostic is. An error means that the inputs are wrong, and a warning that they were used but
31/// something was left out or may not be what was meant.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub enum Severity {
34    /// The inputs are wrong, and the run fails.
35    #[default]
36    Error,
37    /// The inputs were used, and the run does not fail.
38    Warning,
39}
40
41impl Severity {
42    /// The word that starts a line of this severity.
43    pub fn label(self) -> &'static str {
44        match self {
45            Severity::Error => "ERROR",
46            Severity::Warning => "WARNING",
47        }
48    }
49}
50
51/// The text with every control character written as an escape, so that text from a document that is being read cannot
52/// move the cursor, clear the screen or end the line of a diagnostic. Other characters are kept as they are.
53pub fn shown(text: &str) -> String {
54    let mut out = String::with_capacity(text.len());
55    for c in text.chars() {
56        match c {
57            '\n' => out.push_str("\\n"),
58            '\r' => out.push_str("\\r"),
59            '\t' => out.push_str("\\t"),
60            c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
61            c => out.push(c),
62        }
63    }
64    out
65}
66
67/// A problem found in a source, with the name of the file it was found in. It is an error unless it is made as a
68/// warning.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct Diagnostic {
71    /// Whether it is an error or a warning.
72    pub severity: Severity,
73    /// The name of the file, as it is shown.
74    pub file: String,
75    /// Where in the file it was found.
76    pub pos: Pos,
77    /// What the problem is.
78    pub message: String,
79    /// Extra information, such as where a duplicated name was first declared.
80    pub note: Option<String>,
81}
82
83impl Diagnostic {
84    /// A diagnostic that is an error, with no note.
85    pub fn new(file: &str, pos: Pos, message: impl Into<String>) -> Self {
86        Diagnostic {
87            severity: Severity::Error,
88            file: file.to_string(),
89            pos,
90            message: message.into(),
91            note: None,
92        }
93    }
94
95    /// A diagnostic that is a warning, which does not make a run fail.
96    pub fn warning(file: &str, pos: Pos, message: impl Into<String>) -> Self {
97        Diagnostic {
98            severity: Severity::Warning,
99            ..Diagnostic::new(file, pos, message)
100        }
101    }
102
103    /// The diagnostic with a note added.
104    pub fn with_note(mut self, note: impl Into<String>) -> Self {
105        self.note = Some(note.into());
106        self
107    }
108}
109
110impl fmt::Display for Diagnostic {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(
113            f,
114            "{}: {} ({}, {})",
115            self.severity.label(),
116            self.message,
117            self.file,
118            self.pos
119        )?;
120        if let Some(note) = &self.note {
121            write!(f, "; {}", note)?;
122        }
123        Ok(())
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    #[test]
130    fn shown_escapes_control_characters_only() {
131        assert_eq!(shown("a\u{1b}[2J\nb\r\t\u{7}"), "a\\u001b[2J\\nb\\r\\t\\u0007");
132        assert_eq!(shown("DEL\u{7f} C1\u{85}"), "DEL\\u007f C1\\u0085");
133        assert_eq!(shown("plain \"quoted\" \\ é"), "plain \"quoted\" \\ é");
134    }
135
136    use super::*;
137
138    const AT: Pos = Pos { line: 3, col: 9 };
139
140    #[test]
141    fn a_diagnostic_is_an_error_unless_it_is_made_as_a_warning() {
142        assert_eq!(Diagnostic::new("f", AT, "m").severity, Severity::Error);
143        assert_eq!(Diagnostic::warning("f", AT, "m").severity, Severity::Warning);
144    }
145
146    #[test]
147    fn an_error_starts_with_error() {
148        assert_eq!(
149            Diagnostic::new("a.values", AT, "Bad value").to_string(),
150            "ERROR: Bad value (a.values, line 3, col 9)"
151        );
152    }
153
154    #[test]
155    fn a_warning_has_the_same_form_and_starts_with_warning() {
156        assert_eq!(
157            Diagnostic::warning("a.values", AT, "More values follow").to_string(),
158            "WARNING: More values follow (a.values, line 3, col 9)"
159        );
160        assert_eq!(
161            Diagnostic::warning("a.values", AT, "More values follow")
162                .with_note("see --to-array")
163                .to_string(),
164            "WARNING: More values follow (a.values, line 3, col 9); see --to-array"
165        );
166    }
167
168    #[test]
169    fn the_labels_are_the_words_that_start_a_line() {
170        assert_eq!(Severity::Error.label(), "ERROR");
171        assert_eq!(Severity::Warning.label(), "WARNING");
172        assert_eq!(Severity::default(), Severity::Error);
173    }
174}