Skip to main content

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    /// Whether the reference reports this error *without* a position.
18    ///
19    /// Almost every syntax error is printed as `SyntaxError: <message>` followed by
20    /// `    at <file>:<line>:<column>`. A handful are not, and the difference is not
21    /// cosmetic: the reference raises them from `js_resolve_module`, after parsing has
22    /// succeeded, so there is no position to give —
23    /// `export {a}` with no `a` prints a bare `SyntaxError: exported variable 'a' does
24    /// not exist`. Our parser makes that check itself (it has the declared names in
25    /// hand), so it has to say "report me like a link error" explicitly.
26    pub positionless: bool,
27}
28
29impl LexError {
30    /// Build an error at `span`.
31    pub fn new(message: impl Into<String>, span: Span) -> LexError {
32        LexError {
33            message: message.into(),
34            span,
35            positionless: false,
36        }
37    }
38
39    /// Mark this error as one the reference reports without a position.
40    ///
41    /// See [`SyntaxError::positionless`].
42    pub fn positionless(mut self) -> LexError {
43        self.positionless = true;
44        self
45    }
46
47    /// 1-based line of the error.
48    pub fn line(&self) -> u32 {
49        self.span.start.line
50    }
51
52    /// 1-based column of the error.
53    pub fn column(&self) -> u32 {
54        self.span.start.column
55    }
56}
57
58/// Lexical errors share the syntax error type: the engine reports both as
59/// `SyntaxError`.
60pub type LexError = SyntaxError;
61
62/// Parser errors share the syntax error type.
63pub type ParseError = SyntaxError;
64
65impl fmt::Display for SyntaxError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "{}:{}: {}", self.line(), self.column(), self.message)
68    }
69}
70
71impl std::error::Error for SyntaxError {}
72
73/// Result type used by the lexer and the parser.
74pub type Result<T> = std::result::Result<T, SyntaxError>;