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/// ADR-0584: the one admitted Cypher version — the value the statement
136/// preamble accepts as a no-op and `ALTER DATABASE … SET DEFAULT LANGUAGE`
137/// admits, and the one spelling [`unsupported_cypher_version_message`]
138/// names. Every version decision consults this constant. The type is the
139/// admin command's `default_language`; the preamble compares the version
140/// token's canonical decimal text against it, so a radix spelling
141/// (`CYPHER 0x19`) stays the unsupported-version rejection.
142pub const SUPPORTED_CYPHER_VERSION: u32 = 25;
143
144/// ADR-0584: the one authored unsupported-version rejection — the settled
145/// text both version-bearing surfaces raise, `requested` the integer the
146/// statement asked for. The statement preamble raises it at parse
147/// (`Parser::parse_preamble`); `ALTER DATABASE … SET DEFAULT LANGUAGE`
148/// raises it at command execution (`catalog_alter_database`), so the two
149/// spellings cannot drift apart.
150///
151/// The wording mirrors the server's own version-option rejection, which
152/// names the options it accepts (`4 is not a valid option for cypher
153/// version. Valid options are: 25, 5`). That sentence is the remedy, and it
154/// reads correctly on both surfaces — unlike advice phrased around the
155/// preamble (`omit the CYPHER clause`), for which the `ALTER DATABASE`
156/// spelling has no equivalent.
157pub fn unsupported_cypher_version_message(requested: impl fmt::Display) -> String {
158    format!(
159        "UnsupportedCypherVersion: {requested} is not a valid option for cypher \
160         version. Valid options are: {SUPPORTED_CYPHER_VERSION}"
161    )
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    /// Builds a `ParseError` at (line 1, `col`) whose source echo is
169    /// `line_text`.
170    fn error_at(col: usize, line_text: &str) -> ParseError {
171        ParseError::new("boom", 1, col).with_source(line_text)
172    }
173
174    /// Splits a rendered error into (source excerpt, caret line), both
175    /// without the two-space indent.
176    fn rendered_excerpt_and_caret(rendered: &str) -> (&str, &str) {
177        let mut lines = rendered.lines();
178        assert!(lines.next().is_some_and(|l| l.starts_with("parse error:")));
179        let excerpt = lines.next().expect("excerpt line");
180        let caret = lines.next().expect("caret line");
181        (
182            excerpt.strip_prefix("  ").expect("excerpt indent"),
183            caret.strip_prefix("  ").expect("caret indent"),
184        )
185    }
186
187    #[test]
188    fn long_single_line_error_renders_bounded_excerpt() {
189        let line = "a".repeat(100 * 1024);
190        let rendered = error_at(50 * 1024, &line).to_string();
191        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
192        // 2 * 120 window chars + at most 2 ellipsis markers.
193        assert!(
194            excerpt.chars().count() < 400,
195            "excerpt must be bounded, got {} chars",
196            excerpt.chars().count()
197        );
198        assert!(caret.chars().count() < 400);
199        assert!(excerpt.starts_with(ELLIPSIS) && excerpt.ends_with(ELLIPSIS));
200    }
201
202    #[test]
203    fn caret_points_at_true_column_within_window() {
204        // Distinct marker char mid-line in a very long line.
205        let mut line = "a".repeat(50_000);
206        line.push('X');
207        line.push_str(&"a".repeat(50_000));
208        let col = 50_001; // 1-based column of 'X'
209        let rendered = error_at(col, &line).to_string();
210        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
211
212        let x_pos = excerpt
213            .chars()
214            .position(|c| c == 'X')
215            .expect("marker char must survive windowing");
216        let caret_pos = caret
217            .chars()
218            .position(|c| c == '^')
219            .expect("caret must be present");
220        assert_eq!(
221            x_pos, caret_pos,
222            "caret must point at the true error column within the excerpt"
223        );
224    }
225
226    #[test]
227    fn short_line_renders_exactly_as_before() {
228        let rendered = error_at(7, "CREATE (n)").to_string();
229        assert_eq!(rendered, "parse error: boom\n  CREATE (n)\n        ^");
230    }
231
232    #[test]
233    fn col_beyond_line_length_keeps_legacy_caret_position() {
234        // Untruncated lines must keep the old byte-for-byte rendering even
235        // when the column overshoots the line length.
236        let rendered = error_at(30, "MATCH (n)").to_string();
237        let expected = format!("parse error: boom\n  MATCH (n)\n  {}^", " ".repeat(29));
238        assert_eq!(rendered, expected);
239    }
240
241    #[test]
242    fn caret_aligns_after_cjk_chars_on_long_line() {
243        // 500 CJK chars (3 bytes each), a marker, then 500 more: the byte
244        // column of the marker (1501) is far outside the char window around
245        // its char index (500), so without byte→char conversion the marker
246        // falls outside the excerpt entirely.
247        let mut line = "漢".repeat(500);
248        line.push('X');
249        line.push_str(&"漢".repeat(500));
250        let byte_col = 500 * 3 + 1; // 1-based byte column of 'X'
251        let rendered = error_at(byte_col, &line).to_string();
252        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
253
254        let x_pos = excerpt
255            .chars()
256            .position(|c| c == 'X')
257            .expect("marker char must survive windowing");
258        let caret_pos = caret
259            .chars()
260            .position(|c| c == '^')
261            .expect("caret must be present");
262        assert_eq!(
263            x_pos, caret_pos,
264            "caret must point at the true error character within the excerpt"
265        );
266    }
267
268    #[test]
269    fn caret_aligns_after_emoji_on_long_line() {
270        // A 4-byte emoji before the error must not shift the caret.
271        let mut line = "a".repeat(300);
272        line.push('🦀');
273        line.push_str(&"a".repeat(300));
274        line.push('X');
275        line.push_str(&"a".repeat(300));
276        let byte_col = 300 + 4 + 300 + 1; // 1-based byte column of 'X'
277        let rendered = error_at(byte_col, &line).to_string();
278        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
279
280        let x_pos = excerpt
281            .chars()
282            .position(|c| c == 'X')
283            .expect("marker char must survive windowing");
284        let caret_pos = caret
285            .chars()
286            .position(|c| c == '^')
287            .expect("caret must be present");
288        assert_eq!(x_pos, caret_pos);
289    }
290
291    #[test]
292    fn caret_aligns_at_window_boundary_with_mixed_width_chars() {
293        // Alternating ASCII and 2-byte chars; the marker sits at the first
294        // char index where the window starts sliding (start becomes 1).
295        let mut line = String::new();
296        for i in 0..=ECHO_SIDE_CHARS {
297            line.push(if i % 2 == 0 { 'a' } else { 'é' });
298        }
299        let byte_col = line.len() + 1; // 1-based byte column of the marker
300        line.push('X');
301        line.push_str(&"ab".repeat(500));
302        let rendered = error_at(byte_col, &line).to_string();
303        let (excerpt, caret) = rendered_excerpt_and_caret(&rendered);
304
305        assert!(excerpt.starts_with(ELLIPSIS));
306        let x_pos = excerpt
307            .chars()
308            .position(|c| c == 'X')
309            .expect("marker char must survive windowing");
310        let caret_pos = caret
311            .chars()
312            .position(|c| c == '^')
313            .expect("caret must be present");
314        assert_eq!(x_pos, caret_pos);
315    }
316
317    #[test]
318    fn short_multibyte_line_caret_uses_char_column() {
319        // 'é' is 2 bytes: the lexer column of 'b' is 4, its char column 3.
320        let rendered = error_at(4, "éab").to_string();
321        assert_eq!(rendered, "parse error: boom\n  éab\n    ^");
322    }
323
324    #[test]
325    fn error_near_line_start_truncates_only_at_end() {
326        let line = "b".repeat(1_000);
327        let rendered = error_at(3, &line).to_string();
328        let (excerpt, _) = rendered_excerpt_and_caret(&rendered);
329        assert!(!excerpt.starts_with(ELLIPSIS));
330        assert!(excerpt.ends_with(ELLIPSIS));
331        // 2 chars before the caret char + caret char + 120 window chars
332        // after + 1 trailing ellipsis.
333        assert_eq!(excerpt.chars().count(), 2 + 1 + ECHO_SIDE_CHARS + 1);
334    }
335}