boa/syntax/lexer/
error.rs

1//! This module contains the errors used by the lexer.
2//!
3//! More information:
4//!  - [ECMAScript reference][spec]
5//!
6//! [spec]: https://tc39.es/ecma262/#sec-native-error-types-used-in-this-standard
7
8use super::Position;
9use std::{error::Error as StdError, fmt, io};
10
11#[derive(Debug)]
12pub enum Error {
13    /// An IO error is raised to indicate an issue when the lexer is reading data that isn't
14    /// related to the sourcecode itself.
15    IO(io::Error),
16
17    /// Indicates a parsing error due to the presence, or lack of, one or more characters.
18    ///
19    /// More information:
20    /// - [ECMAScript reference][spec]
21    ///
22    /// [spec]: https://tc39.es/ecma262/#sec-native-error-types-used-in-this-standard-syntaxerror
23    Syntax(Box<str>, Position),
24}
25
26impl From<io::Error> for Error {
27    fn from(err: io::Error) -> Self {
28        Self::IO(err)
29    }
30}
31
32impl Error {
33    /// Creates a new syntax error.
34    pub(super) fn syntax<M, P>(err: M, pos: P) -> Self
35    where
36        M: Into<Box<str>>,
37        P: Into<Position>,
38    {
39        Self::Syntax(err.into(), pos.into())
40    }
41}
42
43impl fmt::Display for Error {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match self {
46            Self::IO(e) => write!(f, "I/O error: {}", e),
47            Self::Syntax(e, pos) => write!(f, "Syntax Error: {} at position: {}", e, pos),
48        }
49    }
50}
51
52impl StdError for Error {
53    fn source(&self) -> Option<&(dyn StdError + 'static)> {
54        match self {
55            Self::IO(err) => Some(err),
56            Self::Syntax(_, _) => None,
57        }
58    }
59}