Skip to main content

dive_syntax/
diagnostics.rs

1//! Syntax diagnostics and their stable codes.
2//!
3//! Codes have the form `DIVE-Snnnn` and never change meaning once
4//! published. Add new codes at the end of the table; never reuse one.
5
6use rowan::{TextRange, TextSize};
7
8/// How serious a diagnostic is.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub enum Severity {
11    /// The module is rejected, as SANY's parser would reject it.
12    Error,
13    /// Accepted, but worth pointing out.
14    Warning,
15}
16
17/// A stable diagnostic code.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum Code {
20    /// `DIVE-S0001`: a character that cannot start any token.
21    UnexpectedCharacter,
22    /// `DIVE-S0002`: a string literal with a bad escape or no closing quote.
23    BadString,
24    /// `DIVE-S0003`: a block comment still open at end of input.
25    UnterminatedComment,
26    /// `DIVE-S0004`: no `---- MODULE` header in the input.
27    NoModule,
28    /// `DIVE-S0005`: end of input before the module's closing `====`.
29    MissingModuleEnd,
30    /// `DIVE-S0010`: a token the grammar does not allow here.
31    UnexpectedToken,
32    /// `DIVE-S0011`: an expression was expected but is missing.
33    MissingExpression,
34    /// `DIVE-S0012`: operators of overlapping precedence without parentheses.
35    PrecedenceConflict,
36    /// `DIVE-S0013`: two expressions with no operator between them.
37    MissingOperator,
38    /// `DIVE-S0014`: a prefix, infix or postfix operator in a position it cannot take.
39    MisplacedOperator,
40    /// `DIVE-S0015`: a token inside a `/\` or `\/` list item is not right of its bullet.
41    JunctionIndentation,
42    /// `DIVE-S0020`: a proof step number has the wrong level.
43    StepLevel,
44    /// `DIVE-S0021`: a step number used outside a proof, or `<+>` in an expression.
45    StepNumberMisuse,
46    /// `DIVE-S0022`: a proof attached to a step that cannot take one.
47    UnexpectedProof,
48    /// `DIVE-S0023`: proofs nested more than 100 levels (SANY's limit).
49    ProofTooDeep,
50    /// `DIVE-S0030`: `::` that does not follow a label.
51    BadLabel,
52    /// `DIVE-S0031`: a label whose removal would change how the expression parses.
53    LabelChangesParse,
54    /// `DIVE-S0032`: `\X` (or `\times`) used as an operator argument.
55    TimesAsArgument,
56    /// `DIVE-S0033`: the form `{a \in b : c \in d}`.
57    SetMapWithIn,
58    /// `DIVE-S0034`: `@` used as a field name in `!.@`.
59    AtInExcept,
60    /// `DIVE-S0035`: an ill-structured `WF_`/`SF_` expression.
61    BadFairness,
62    /// `DIVE-S0036`: `NEW` declares a symbol with arguments before `\in`.
63    NewWithArguments,
64    /// `DIVE-S0037`: a decimal number used as a structural selector (`Op!1.2`).
65    BadStructuralSelector,
66    /// `DIVE-S0040`: nesting deeper than this parser supports.
67    NestingTooDeep,
68    /// `DIVE-S0041`: input larger than 4 GiB.
69    InputTooLarge,
70    /// `DIVE-S0006`: the top-level module's name differs from the file name.
71    ModuleNameMismatch,
72    /// `DIVE-S0007` (warning): the file is not valid UTF-8; invalid bytes were
73    /// read as U+FFFD, as SANY's UTF-8 reader does.
74    InvalidUtf8,
75}
76
77impl Code {
78    /// The stable string form, e.g. `DIVE-S0012`.
79    #[must_use]
80    pub fn as_str(self) -> &'static str {
81        match self {
82            Self::UnexpectedCharacter => "DIVE-S0001",
83            Self::BadString => "DIVE-S0002",
84            Self::UnterminatedComment => "DIVE-S0003",
85            Self::NoModule => "DIVE-S0004",
86            Self::MissingModuleEnd => "DIVE-S0005",
87            Self::UnexpectedToken => "DIVE-S0010",
88            Self::MissingExpression => "DIVE-S0011",
89            Self::PrecedenceConflict => "DIVE-S0012",
90            Self::MissingOperator => "DIVE-S0013",
91            Self::MisplacedOperator => "DIVE-S0014",
92            Self::JunctionIndentation => "DIVE-S0015",
93            Self::StepLevel => "DIVE-S0020",
94            Self::StepNumberMisuse => "DIVE-S0021",
95            Self::UnexpectedProof => "DIVE-S0022",
96            Self::ProofTooDeep => "DIVE-S0023",
97            Self::BadLabel => "DIVE-S0030",
98            Self::LabelChangesParse => "DIVE-S0031",
99            Self::TimesAsArgument => "DIVE-S0032",
100            Self::SetMapWithIn => "DIVE-S0033",
101            Self::AtInExcept => "DIVE-S0034",
102            Self::BadFairness => "DIVE-S0035",
103            Self::NewWithArguments => "DIVE-S0036",
104            Self::BadStructuralSelector => "DIVE-S0037",
105            Self::NestingTooDeep => "DIVE-S0040",
106            Self::InputTooLarge => "DIVE-S0041",
107            Self::ModuleNameMismatch => "DIVE-S0006",
108            Self::InvalidUtf8 => "DIVE-S0007",
109        }
110    }
111}
112
113impl std::fmt::Display for Code {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.write_str(self.as_str())
116    }
117}
118
119/// One diagnostic about the source text.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Diagnostic {
122    /// Stable code.
123    pub code: Code,
124    /// Severity.
125    pub severity: Severity,
126    /// What is wrong, naming the construct.
127    pub message: String,
128    /// The primary source span, in bytes.
129    pub range: TextRange,
130    /// A likely fix, when one can be suggested.
131    pub help: Option<String>,
132}
133
134impl Diagnostic {
135    pub(crate) fn error(code: Code, range: TextRange, message: impl Into<String>) -> Self {
136        Self {
137            code,
138            severity: Severity::Error,
139            message: message.into(),
140            range,
141            help: None,
142        }
143    }
144
145    pub(crate) fn with_help(mut self, help: impl Into<String>) -> Self {
146        self.help = Some(help.into());
147        self
148    }
149
150    /// Whether this diagnostic rejects the module.
151    #[must_use]
152    pub fn is_error(&self) -> bool {
153        self.severity == Severity::Error
154    }
155}
156
157/// 1-based line and column (in Unicode scalar values) of a byte offset.
158#[must_use]
159pub fn line_col(src: &str, offset: TextSize) -> (u32, u32) {
160    let offset = usize::from(offset).min(src.len());
161    let mut line = 1u32;
162    let mut col = 1u32;
163    for (i, c) in src.char_indices() {
164        if i >= offset {
165            break;
166        }
167        if c == '\n' {
168            line += 1;
169            col = 1;
170        } else {
171            col += 1;
172        }
173    }
174    (line, col)
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn codes_are_unique() {
183        let all = [
184            Code::UnexpectedCharacter,
185            Code::BadString,
186            Code::UnterminatedComment,
187            Code::NoModule,
188            Code::MissingModuleEnd,
189            Code::UnexpectedToken,
190            Code::MissingExpression,
191            Code::PrecedenceConflict,
192            Code::MissingOperator,
193            Code::MisplacedOperator,
194            Code::JunctionIndentation,
195            Code::StepLevel,
196            Code::StepNumberMisuse,
197            Code::UnexpectedProof,
198            Code::ProofTooDeep,
199            Code::BadLabel,
200            Code::LabelChangesParse,
201            Code::TimesAsArgument,
202            Code::SetMapWithIn,
203            Code::AtInExcept,
204            Code::BadFairness,
205            Code::NewWithArguments,
206            Code::BadStructuralSelector,
207            Code::NestingTooDeep,
208            Code::InputTooLarge,
209            Code::ModuleNameMismatch,
210            Code::InvalidUtf8,
211        ];
212        let mut seen = std::collections::BTreeSet::new();
213        for c in all {
214            assert!(seen.insert(c.as_str()), "{c}");
215            assert!(c.as_str().starts_with("DIVE-S"));
216        }
217    }
218
219    #[test]
220    fn line_col_counts_chars() {
221        assert_eq!(line_col("ab\ncd", TextSize::from(4)), (2, 2));
222        assert_eq!(line_col("∧x", TextSize::from(3)), (1, 2));
223    }
224}