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
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 fn error_at(col: usize, line_text: &str) -> ParseError {
142 ParseError::new("boom", 1, col).with_source(line_text)
143 }
144
145 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 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 let mut line = "a".repeat(50_000);
177 line.push('X');
178 line.push_str(&"a".repeat(50_000));
179 let col = 50_001; 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 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 let mut line = "漢".repeat(500);
219 line.push('X');
220 line.push_str(&"漢".repeat(500));
221 let byte_col = 500 * 3 + 1; 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 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; 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 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; 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 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 assert_eq!(excerpt.chars().count(), 2 + 1 + ECHO_SIDE_CHARS + 1);
305 }
306}