js_parse/error.rs
1//! Lexical errors.
2
3use crate::token::Span;
4use std::fmt;
5
6/// A syntax error produced while scanning or parsing.
7///
8/// The message vocabulary follows the upstream QuickJS parser wherever a test
9/// observes it (`unexpected character`, `unterminated string literal`, …) so
10/// that the differential harness can compare messages once the parser lands.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct SyntaxError {
13 /// Human readable message (no position prefix).
14 pub message: String,
15 /// Where the error happened.
16 pub span: Span,
17}
18
19impl LexError {
20 /// Build an error at `span`.
21 pub fn new(message: impl Into<String>, span: Span) -> LexError {
22 LexError {
23 message: message.into(),
24 span,
25 }
26 }
27
28 /// 1-based line of the error.
29 pub fn line(&self) -> u32 {
30 self.span.start.line
31 }
32
33 /// 1-based column of the error.
34 pub fn column(&self) -> u32 {
35 self.span.start.column
36 }
37}
38
39/// Lexical errors share the syntax error type: the engine reports both as
40/// `SyntaxError`.
41pub type LexError = SyntaxError;
42
43/// Parser errors share the syntax error type.
44pub type ParseError = SyntaxError;
45
46impl fmt::Display for SyntaxError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 write!(f, "{}:{}: {}", self.line(), self.column(), self.message)
49 }
50}
51
52impl std::error::Error for SyntaxError {}
53
54/// Result type used by the lexer and the parser.
55pub type Result<T> = std::result::Result<T, SyntaxError>;