Skip to main content

relate_parser/
error.rs

1use std::fmt;
2
3/// A parser error with source position information.
4#[derive(Debug, Clone, PartialEq)]
5pub struct ParseError {
6    pub message: String,
7    pub line: usize,
8    pub col: usize,
9    /// Optional source line text for caret display.
10    pub source_line: Option<String>,
11    /// Optional symbolic openCypher-TCK error-*detail* name for this parse
12    /// failure (e.g. `"IntegerOverflow"`, `"FloatingPointOverflow"`).
13    ///
14    /// A parse failure always renders as a `SyntaxError` *class*, but the TCK
15    /// error grammar also carries a finer detail (`a SyntaxError should be
16    /// raised at compile time: IntegerOverflow`). This tag lets
17    /// `EngineError::kind()` surface that detail for the TCK harness
18    /// matcher without depending on `relate-error` (the dependency runs the
19    /// other way): the consumer maps the string through `ErrorKind::from_name`.
20    /// It is **never** rendered by `Display`, so tagging a `ParseError`
21    /// preserves the byte-for-byte error string (the prime invariant).
22    pub detail: Option<&'static str>,
23}
24
25impl ParseError {
26    pub fn new(message: impl Into<String>, line: usize, col: usize) -> Self {
27        ParseError {
28            message: message.into(),
29            line,
30            col,
31            source_line: None,
32            detail: None,
33        }
34    }
35
36    pub fn with_source(mut self, source: &str) -> Self {
37        let lines: Vec<&str> = source.split('\n').collect();
38        if self.line >= 1 && self.line <= lines.len() {
39            self.source_line = Some(lines[self.line - 1].to_string());
40        }
41        self
42    }
43
44    /// Tags this error with a symbolic TCK error-detail name (see
45    /// [`ParseError::detail`]). Does not affect `Display`.
46    pub fn with_detail(mut self, detail: &'static str) -> Self {
47        self.detail = Some(detail);
48        self
49    }
50}
51
52/// Maximum source chars echoed on each side of the error column.
53///
54/// Bounds the `Display` rendering (and its cost) for pathological
55/// single-line inputs: without a window, a 100 KB one-line query would echo
56/// ~200 KB into the error string and into logs / wire failure messages.
57const ECHO_SIDE_CHARS: usize = 120;
58/// Marker prepended/appended when the echoed source line is truncated.
59const ELLIPSIS: char = '…';
60
61/// Converts a 1-based byte column (as tracked by the lexer) into a 0-based
62/// char index into `line`. Boundary-safe: a column landing mid-character
63/// resolves to the char containing that byte, and a column past the end of
64/// the line resolves to `line.chars().count()`.
65fn byte_col_to_char_idx(line: &str, col: usize) -> usize {
66    let byte_idx = col.saturating_sub(1);
67    line.char_indices()
68        .take_while(|(b, _)| *b < byte_idx)
69        .count()
70}
71
72/// Windows `line` around the 1-based byte `col`, returning the excerpt plus
73/// the 1-based caret column within that excerpt. Lexer columns are
74/// byte-based, so `col` is first converted to a char index — otherwise
75/// multi-byte chars before the error shift the caret right and can push the
76/// true error character outside the excerpt entirely. Lines that fit the
77/// window are returned unchanged so short-line rendering is byte-for-byte
78/// identical to the unwindowed behavior.
79fn window_source_excerpt(line: &str, col: usize) -> (String, usize) {
80    let chars: Vec<char> = line.chars().collect();
81    let len = chars.len();
82    let char_idx = byte_col_to_char_idx(line, col);
83    let caret_idx = char_idx.min(len.saturating_sub(1));
84    let start = caret_idx.saturating_sub(ECHO_SIDE_CHARS);
85    let end = (caret_idx + ECHO_SIDE_CHARS + 1).min(len);
86    if start == 0 && end == len {
87        // Untruncated lines keep the legacy byte-for-byte rendering: the
88        // raw column for out-of-range columns (historical fallback), the
89        // char column otherwise (identical to the raw column on ASCII).
90        let caret_col = if col.saturating_sub(1) >= line.len() {
91            col
92        } else {
93            char_idx + 1
94        };
95        return (line.to_string(), caret_col);
96    }
97    let mut excerpt = String::with_capacity(end - start + 2);
98    let mut caret_col = caret_idx - start + 1;
99    if start > 0 {
100        excerpt.push(ELLIPSIS);
101        caret_col += 1;
102    }
103    excerpt.extend(chars[start..end].iter());
104    if end < len {
105        excerpt.push(ELLIPSIS);
106    }
107    (excerpt, caret_col)
108}
109
110impl fmt::Display for ParseError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        if let Some(ref src_line) = self.source_line {
113            if self.col > 0 {
114                let (excerpt, caret_col) = window_source_excerpt(src_line, self.col);
115                let caret = " ".repeat(caret_col - 1) + "^";
116                return write!(
117                    f,
118                    "parse error: {}\n  {}\n  {}",
119                    self.message, excerpt, caret
120                );
121            }
122        }
123        write!(
124            f,
125            "parse error: {} at line {}, col {}",
126            self.message, self.line, self.col
127        )
128    }
129}
130
131impl std::error::Error for ParseError {}
132
133pub type ParseResult<T> = Result<T, ParseError>;
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    /// Builds a `ParseError` at (line 1, `col`) whose source echo is
140    /// `line_text`.
141    fn error_at(col: usize, line_text: &str) -> ParseError {
142        ParseError::new("boom", 1, col).with_source(line_text)
143    }
144
145    /// Splits a rendered error into (source excerpt, caret line), both
146    /// without the two-space indent.
147    fn rendered_excerpt_and_caret(rendered: &str) -> (&str, &str) {
148        let mut lines = rendered.lines();
149        assert!(lines.next().is_some_and(|l| l.starts_with("parse error:")));
150        let excerpt = lines.next().expect("excerpt line");
151        let caret = lines.next().expect("caret line");
152        (
153            excerpt.strip_prefix("  ").expect("excerpt indent"),
154            caret.strip_prefix("  ").expect("caret indent"),
155        )
156    }
157
158    #[test]
159    fn long_single_line_error_renders_bounded_excerpt() {
160        let line = "a".repeat(100 * 1024);
161        let rendered = error_at(50 * 1024, &line).to_string();
162        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
163        // 2 * 120 window chars + at most 2 ellipsis markers.
164        assert!(
165            excerpt.chars().count() < 400,
166            "excerpt must be bounded, got {} chars",
167            excerpt.chars().count()
168        );
169        assert!(caret.chars().count() < 400);
170        assert!(excerpt.starts_with(ELLIPSIS) && excerpt.ends_with(ELLIPSIS));
171    }
172
173    #[test]
174    fn caret_points_at_true_column_within_window() {
175        // Distinct marker char mid-line in a very long line.
176        let mut line = "a".repeat(50_000);
177        line.push('X');
178        line.push_str(&"a".repeat(50_000));
179        let col = 50_001; // 1-based column of 'X'
180        let rendered = error_at(col, &line).to_string();
181        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
182
183        let x_pos = excerpt
184            .chars()
185            .position(|c| c == 'X')
186            .expect("marker char must survive windowing");
187        let caret_pos = caret
188            .chars()
189            .position(|c| c == '^')
190            .expect("caret must be present");
191        assert_eq!(
192            x_pos, caret_pos,
193            "caret must point at the true error column within the excerpt"
194        );
195    }
196
197    #[test]
198    fn short_line_renders_exactly_as_before() {
199        let rendered = error_at(7, "CREATE (n)").to_string();
200        assert_eq!(rendered, "parse error: boom\n  CREATE (n)\n        ^");
201    }
202
203    #[test]
204    fn col_beyond_line_length_keeps_legacy_caret_position() {
205        // Untruncated lines must keep the old byte-for-byte rendering even
206        // when the column overshoots the line length.
207        let rendered = error_at(30, "MATCH (n)").to_string();
208        let expected = format!("parse error: boom\n  MATCH (n)\n  {}^", " ".repeat(29));
209        assert_eq!(rendered, expected);
210    }
211
212    #[test]
213    fn caret_aligns_after_cjk_chars_on_long_line() {
214        // 500 CJK chars (3 bytes each), a marker, then 500 more: the byte
215        // column of the marker (1501) is far outside the char window around
216        // its char index (500), so without byte→char conversion the marker
217        // falls outside the excerpt entirely.
218        let mut line = "漢".repeat(500);
219        line.push('X');
220        line.push_str(&"漢".repeat(500));
221        let byte_col = 500 * 3 + 1; // 1-based byte column of 'X'
222        let rendered = error_at(byte_col, &line).to_string();
223        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
224
225        let x_pos = excerpt
226            .chars()
227            .position(|c| c == 'X')
228            .expect("marker char must survive windowing");
229        let caret_pos = caret
230            .chars()
231            .position(|c| c == '^')
232            .expect("caret must be present");
233        assert_eq!(
234            x_pos, caret_pos,
235            "caret must point at the true error character within the excerpt"
236        );
237    }
238
239    #[test]
240    fn caret_aligns_after_emoji_on_long_line() {
241        // A 4-byte emoji before the error must not shift the caret.
242        let mut line = "a".repeat(300);
243        line.push('🦀');
244        line.push_str(&"a".repeat(300));
245        line.push('X');
246        line.push_str(&"a".repeat(300));
247        let byte_col = 300 + 4 + 300 + 1; // 1-based byte column of 'X'
248        let rendered = error_at(byte_col, &line).to_string();
249        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
250
251        let x_pos = excerpt
252            .chars()
253            .position(|c| c == 'X')
254            .expect("marker char must survive windowing");
255        let caret_pos = caret
256            .chars()
257            .position(|c| c == '^')
258            .expect("caret must be present");
259        assert_eq!(x_pos, caret_pos);
260    }
261
262    #[test]
263    fn caret_aligns_at_window_boundary_with_mixed_width_chars() {
264        // Alternating ASCII and 2-byte chars; the marker sits at the first
265        // char index where the window starts sliding (start becomes 1).
266        let mut line = String::new();
267        for i in 0..=ECHO_SIDE_CHARS {
268            line.push(if i % 2 == 0 { 'a' } else { 'é' });
269        }
270        let byte_col = line.len() + 1; // 1-based byte column of the marker
271        line.push('X');
272        line.push_str(&"ab".repeat(500));
273        let rendered = error_at(byte_col, &line).to_string();
274        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
275
276        assert!(excerpt.starts_with(ELLIPSIS));
277        let x_pos = excerpt
278            .chars()
279            .position(|c| c == 'X')
280            .expect("marker char must survive windowing");
281        let caret_pos = caret
282            .chars()
283            .position(|c| c == '^')
284            .expect("caret must be present");
285        assert_eq!(x_pos, caret_pos);
286    }
287
288    #[test]
289    fn short_multibyte_line_caret_uses_char_column() {
290        // 'é' is 2 bytes: the lexer column of 'b' is 4, its char column 3.
291        let rendered = error_at(4, "éab").to_string();
292        assert_eq!(rendered, "parse error: boom\n  éab\n    ^");
293    }
294
295    #[test]
296    fn error_near_line_start_truncates_only_at_end() {
297        let line = "b".repeat(1_000);
298        let rendered = error_at(3, &line).to_string();
299        let (excerpt, _) = rendered_excerpt_and_caret(&rendered);
300        assert!(!excerpt.starts_with(ELLIPSIS));
301        assert!(excerpt.ends_with(ELLIPSIS));
302        // 2 chars before the caret char + caret char + 120 window chars
303        // after + 1 trailing ellipsis.
304        assert_eq!(excerpt.chars().count(), 2 + 1 + ECHO_SIDE_CHARS + 1);
305    }
306}