Skip to main content

fml_syntax/
diagnostic.rs

1//! Diagnostics and source positions.
2
3use rowan::{TextRange, TextSize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
6pub enum Severity {
7    Error,
8    Warning,
9}
10
11/// A problem found in the source, located by byte range.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Diagnostic {
14    pub severity: Severity,
15    pub range: TextRange,
16    pub message: String,
17}
18
19impl Diagnostic {
20    pub fn error(range: TextRange, message: impl Into<String>) -> Self {
21        Self {
22            severity: Severity::Error,
23            range,
24            message: message.into(),
25        }
26    }
27
28    pub fn warning(range: TextRange, message: impl Into<String>) -> Self {
29        Self {
30            severity: Severity::Warning,
31            range,
32            message: message.into(),
33        }
34    }
35}
36
37/// A position in the source: zero-based line, and zero-based column counted both in UTF-8 bytes
38/// and in UTF-16 code units (the unit LSP and the Mapping Language debug trace use).
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
40pub struct LineCol {
41    pub line: u32,
42    pub col: u32,
43    pub col_utf16: u32,
44}
45
46/// Converts byte offsets to line and column.
47#[derive(Debug, Clone)]
48pub struct LineIndex {
49    line_starts: Vec<TextSize>,
50}
51
52impl LineIndex {
53    pub fn new(text: &str) -> Self {
54        let mut line_starts = vec![TextSize::from(0)];
55        let bytes = text.as_bytes();
56        let mut i = 0;
57        while i < bytes.len() {
58            match bytes[i] {
59                b'\n' => line_starts.push(TextSize::from((i + 1) as u32)),
60                b'\r' if bytes.get(i + 1) != Some(&b'\n') => {
61                    line_starts.push(TextSize::from((i + 1) as u32))
62                }
63                _ => {}
64            }
65            i += 1;
66        }
67        Self { line_starts }
68    }
69
70    /// The position of `offset` in `text`, which must be the text this index was built from.
71    pub fn line_col(&self, text: &str, offset: TextSize) -> LineCol {
72        let line = self
73            .line_starts
74            .partition_point(|&start| start <= offset)
75            .saturating_sub(1);
76        let start = self.line_starts[line];
77        let prefix = &text[usize::from(start)..usize::from(offset)];
78        LineCol {
79            line: line as u32,
80            col: prefix.len() as u32,
81            col_utf16: prefix.encode_utf16().count() as u32,
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn line_and_columns() {
92        let text = "ab\nцd\r\nx";
93        let index = LineIndex::new(text);
94        let at = |offset: u32| index.line_col(text, TextSize::from(offset));
95        assert_eq!(
96            at(0),
97            LineCol {
98                line: 0,
99                col: 0,
100                col_utf16: 0
101            }
102        );
103        assert_eq!(
104            at(5),
105            LineCol {
106                line: 1,
107                col: 2,
108                col_utf16: 1
109            }
110        );
111        assert_eq!(
112            at(8),
113            LineCol {
114                line: 2,
115                col: 0,
116                col_utf16: 0
117            }
118        );
119    }
120}