1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq)]
5pub struct ParseError {
6 pub message: String,
7 pub line: usize,
8 pub col: usize,
9 pub source_line: Option<String>,
11 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 pub fn with_detail(mut self, detail: &'static str) -> Self {
47 self.detail = Some(detail);
48 self
49 }
50}
51
52const ECHO_SIDE_CHARS: usize = 120;
58const ELLIPSIS: char = '…';
60
61fn 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
72fn 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 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
135pub const SUPPORTED_CYPHER_VERSION: u32 = 25;
143
144pub 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 fn error_at(col: usize, line_text: &str) -> ParseError {
171 ParseError::new("boom", 1, col).with_source(line_text)
172 }
173
174 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 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 let mut line = "a".repeat(50_000);
206 line.push('X');
207 line.push_str(&"a".repeat(50_000));
208 let col = 50_001; 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 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 let mut line = "漢".repeat(500);
248 line.push('X');
249 line.push_str(&"漢".repeat(500));
250 let byte_col = 500 * 3 + 1; 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 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; 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 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; 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 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 assert_eq!(excerpt.chars().count(), 2 + 1 + ECHO_SIDE_CHARS + 1);
334 }
335}