neumann_parser 0.4.0

Hand-written recursive descent parser for the Neumann query language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Error types and diagnostics for the Neumann parser.
//!
//! Provides rich error messages with source context, including:
//! - Precise source locations (line and column)
//! - Error context with source snippets
//! - Helpful suggestions and expected tokens

use std::fmt;

use crate::{
    span::{get_line, line_col, Span},
    token::TokenKind,
};

/// Result type for parser operations.
pub type ParseResult<T> = Result<T, ParseError>;

/// A parse error with source location.
#[derive(Clone, Debug)]
pub struct ParseError {
    /// The kind of error.
    pub kind: ParseErrorKind,
    /// Where the error occurred.
    pub span: Span,
    /// Optional help message.
    pub help: Option<String>,
}

impl ParseError {
    /// Creates a new parse error.
    #[must_use]
    pub const fn new(kind: ParseErrorKind, span: Span) -> Self {
        Self {
            kind,
            span,
            help: None,
        }
    }

    /// Creates an "unexpected token" error.
    pub fn unexpected(found: TokenKind, span: Span, expected: impl Into<String>) -> Self {
        Self::new(
            ParseErrorKind::UnexpectedToken {
                found,
                expected: expected.into(),
            },
            span,
        )
    }

    /// Creates an "unexpected EOF" error.
    pub fn unexpected_eof(span: Span, expected: impl Into<String>) -> Self {
        Self::new(
            ParseErrorKind::UnexpectedEof {
                expected: expected.into(),
            },
            span,
        )
    }

    /// Creates an "invalid syntax" error.
    pub fn invalid(message: impl Into<String>, span: Span) -> Self {
        Self::new(ParseErrorKind::InvalidSyntax(message.into()), span)
    }

    /// Adds a help message to the error.
    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }

    /// Formats the error with source context.
    #[must_use]
    #[allow(clippy::format_push_string)]
    pub fn format_with_source(&self, source: &str) -> String {
        let (line, col) = line_col(source, self.span.start);
        let line_text = get_line(source, self.span.start);

        let kind = &self.kind;
        let mut result = format!("error: {kind}\n");
        result.push_str(&format!("  --> line {line}:{col}\n"));
        result.push_str("   |\n");
        result.push_str(&format!("{line:3} | {line_text}\n"));
        result.push_str("   | ");

        // Add carets under the error
        for _ in 0..(col - 1) {
            result.push(' ');
        }
        let len = self.span.len().max(1) as usize;
        let caret_len = len.min(line_text.len().saturating_sub(col - 1));
        for _ in 0..caret_len.max(1) {
            result.push('^');
        }
        result.push('\n');

        if let Some(help) = &self.help {
            result.push_str(&format!("   = help: {help}\n"));
        }

        result
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at {}", self.kind, self.span)
    }
}

impl std::error::Error for ParseError {}

/// Parse error kinds.
#[derive(Clone, Debug)]
pub enum ParseErrorKind {
    /// Unexpected token
    UnexpectedToken {
        /// The token that was found.
        found: TokenKind,
        /// Description of what was expected.
        expected: String,
    },
    /// Unexpected end of input
    UnexpectedEof {
        /// Description of what was expected.
        expected: String,
    },
    /// Invalid syntax
    InvalidSyntax(String),
    /// Invalid number
    InvalidNumber(String),
    /// Unterminated string
    UnterminatedString,
    /// Unknown keyword or command
    UnknownCommand(String),
    /// Duplicate column
    DuplicateColumn(String),
    /// Invalid escape sequence
    InvalidEscape(char),
    /// Expression too deeply nested
    TooDeep,
    /// Custom error
    Custom(String),
}

impl fmt::Display for ParseErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexpectedToken { found, expected } => {
                write!(f, "unexpected {found}, expected {expected}")
            },
            Self::UnexpectedEof { expected } => {
                write!(f, "unexpected end of input, expected {expected}")
            },
            Self::InvalidSyntax(msg) | Self::Custom(msg) => write!(f, "{msg}"),
            Self::InvalidNumber(msg) => write!(f, "invalid number: {msg}"),
            Self::UnterminatedString => write!(f, "unterminated string literal"),
            Self::UnknownCommand(cmd) => write!(f, "unknown command: {cmd}"),
            Self::DuplicateColumn(col) => write!(f, "duplicate column: {col}"),
            Self::InvalidEscape(c) => write!(f, "invalid escape sequence: \\{c}"),
            Self::TooDeep => write!(f, "expression nesting too deep"),
        }
    }
}

/// A collection of parse errors.
#[derive(Clone, Debug, Default)]
pub struct Errors {
    errors: Vec<ParseError>,
}

impl Errors {
    /// Creates an empty error collection.
    #[must_use]
    pub const fn new() -> Self {
        Self { errors: Vec::new() }
    }

    /// Adds an error to the collection.
    pub fn push(&mut self, error: ParseError) {
        self.errors.push(error);
    }

    /// Returns true if there are no errors.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns the number of errors.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.errors.len()
    }

    /// Returns an iterator over the errors.
    pub fn iter(&self) -> impl Iterator<Item = &ParseError> {
        self.errors.iter()
    }

    /// Consumes the collection and returns the errors.
    #[must_use]
    pub fn into_vec(self) -> Vec<ParseError> {
        self.errors
    }

    /// Formats all errors with source context.
    #[must_use]
    pub fn format_with_source(&self, source: &str) -> String {
        self.errors
            .iter()
            .map(|e| e.format_with_source(source))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

impl IntoIterator for Errors {
    type Item = ParseError;
    type IntoIter = std::vec::IntoIter<ParseError>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.into_iter()
    }
}

impl<'a> IntoIterator for &'a Errors {
    type Item = &'a ParseError;
    type IntoIter = std::slice::Iter<'a, ParseError>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.iter()
    }
}

impl Extend<ParseError> for Errors {
    fn extend<T: IntoIterator<Item = ParseError>>(&mut self, iter: T) {
        self.errors.extend(iter);
    }
}

impl FromIterator<ParseError> for Errors {
    fn from_iter<T: IntoIterator<Item = ParseError>>(iter: T) -> Self {
        Self {
            errors: iter.into_iter().collect(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_error_unexpected() {
        let err = ParseError::unexpected(
            TokenKind::Integer(42),
            Span::from_offsets(0, 2),
            "identifier",
        );
        assert!(matches!(err.kind, ParseErrorKind::UnexpectedToken { .. }));
        assert_eq!(err.span, Span::from_offsets(0, 2));
    }

    #[test]
    fn test_parse_error_unexpected_eof() {
        let err = ParseError::unexpected_eof(Span::point(crate::span::BytePos(10)), "expression");
        assert!(matches!(err.kind, ParseErrorKind::UnexpectedEof { .. }));
    }

    #[test]
    fn test_parse_error_invalid() {
        let err = ParseError::invalid("bad syntax", Span::from_offsets(5, 10));
        assert!(matches!(err.kind, ParseErrorKind::InvalidSyntax(_)));
    }

    #[test]
    fn test_parse_error_with_help() {
        let err = ParseError::invalid("missing semicolon", Span::from_offsets(0, 5))
            .with_help("add a semicolon at the end");
        assert_eq!(err.help, Some("add a semicolon at the end".to_string()));
    }

    #[test]
    fn test_parse_error_display() {
        let err =
            ParseError::unexpected(TokenKind::Comma, Span::from_offsets(10, 11), "column name");
        let s = format!("{}", err);
        assert!(s.contains("unexpected"));
        assert!(s.contains(","));
        assert!(s.contains("column name"));
    }

    #[test]
    fn test_format_with_source() {
        let source = "SELECT * FORM users";
        let err = ParseError::invalid("expected FROM, found FORM", Span::from_offsets(9, 13));
        let formatted = err.format_with_source(source);

        assert!(formatted.contains("error:"));
        assert!(formatted.contains("line 1:10"));
        assert!(formatted.contains("SELECT * FORM users"));
        assert!(formatted.contains("^^^^"));
    }

    #[test]
    fn test_format_with_source_multiline() {
        let source = "SELECT *\nFORM users\nWHERE id = 1";
        let err = ParseError::invalid("expected FROM", Span::from_offsets(9, 13));
        let formatted = err.format_with_source(source);

        assert!(formatted.contains("line 2:1"));
        assert!(formatted.contains("FORM users"));
    }

    #[test]
    fn test_format_with_help() {
        let source = "SELCT * FROM users";
        let err = ParseError::invalid("unknown keyword SELCT", Span::from_offsets(0, 5))
            .with_help("did you mean SELECT?");
        let formatted = err.format_with_source(source);

        assert!(formatted.contains("help: did you mean SELECT?"));
    }

    #[test]
    fn test_errors_collection() {
        let mut errors = Errors::new();
        assert!(errors.is_empty());
        assert_eq!(errors.len(), 0);

        errors.push(ParseError::invalid("error 1", Span::from_offsets(0, 5)));
        errors.push(ParseError::invalid("error 2", Span::from_offsets(10, 15)));

        assert!(!errors.is_empty());
        assert_eq!(errors.len(), 2);

        let mut count = 0;
        for _ in &errors {
            count += 1;
        }
        assert_eq!(count, 2);
    }

    #[test]
    fn test_errors_into_vec() {
        let mut errors = Errors::new();
        errors.push(ParseError::invalid("error 1", Span::from_offsets(0, 5)));
        errors.push(ParseError::invalid("error 2", Span::from_offsets(10, 15)));

        let vec = errors.into_vec();
        assert_eq!(vec.len(), 2);
    }

    #[test]
    fn test_errors_extend() {
        let mut errors = Errors::new();
        errors.extend(vec![
            ParseError::invalid("error 1", Span::from_offsets(0, 5)),
            ParseError::invalid("error 2", Span::from_offsets(10, 15)),
        ]);
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_errors_from_iter() {
        let errors: Errors = vec![
            ParseError::invalid("error 1", Span::from_offsets(0, 5)),
            ParseError::invalid("error 2", Span::from_offsets(10, 15)),
        ]
        .into_iter()
        .collect();
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_errors_format_with_source() {
        let source = "SELECT * FROM";
        let mut errors = Errors::new();
        errors.push(ParseError::invalid("error 1", Span::from_offsets(0, 6)));
        errors.push(ParseError::invalid("error 2", Span::from_offsets(7, 8)));

        let formatted = errors.format_with_source(source);
        assert!(formatted.contains("error 1"));
        assert!(formatted.contains("error 2"));
    }

    #[test]
    fn test_parse_error_kind_display() {
        assert!(format!("{}", ParseErrorKind::UnterminatedString).contains("unterminated"));
        assert!(format!("{}", ParseErrorKind::TooDeep).contains("deep"));
        assert!(format!("{}", ParseErrorKind::InvalidNumber("bad".to_string())).contains("bad"));
        assert!(format!("{}", ParseErrorKind::UnknownCommand("FOO".to_string())).contains("FOO"));
        assert!(format!("{}", ParseErrorKind::DuplicateColumn("id".to_string())).contains("id"));
        assert!(format!("{}", ParseErrorKind::InvalidEscape('x')).contains("\\x"));
        assert!(format!("{}", ParseErrorKind::Custom("custom".to_string())).contains("custom"));
    }

    #[test]
    fn test_errors_into_iterator() {
        let mut errors = Errors::new();
        errors.push(ParseError::invalid("error 1", Span::from_offsets(0, 5)));
        errors.push(ParseError::invalid("error 2", Span::from_offsets(10, 15)));

        let mut count = 0;
        for _ in errors {
            count += 1;
        }
        assert_eq!(count, 2);
    }

    #[test]
    fn test_zero_length_span_caret() {
        let source = "SELECT FROM";
        let err = ParseError::invalid("expected expression", Span::point(crate::span::BytePos(7)));
        let formatted = err.format_with_source(source);
        // Should still show at least one caret
        assert!(formatted.contains("^"));
    }

    #[test]
    fn test_errors_iter() {
        let mut errors = Errors::new();
        errors.push(ParseError::invalid("error 1", Span::from_offsets(0, 5)));
        errors.push(ParseError::invalid("error 2", Span::from_offsets(10, 15)));

        // Explicitly test iter() method
        let mut count = 0;
        for err in errors.iter() {
            assert!(matches!(err.kind, ParseErrorKind::InvalidSyntax(_)));
            count += 1;
        }
        assert_eq!(count, 2);
    }

    #[test]
    fn test_unexpected_eof_display() {
        let kind = ParseErrorKind::UnexpectedEof {
            expected: "identifier".to_string(),
        };
        let displayed = format!("{}", kind);
        assert!(displayed.contains("unexpected end of input"));
        assert!(displayed.contains("identifier"));
    }
}