Skip to main content

ecma_syntax_cat/
error.rs

1//! Construction-time error type.
2//!
3//! The AST itself is data; errors arise only when validating constructor
4//! input (e.g. rejecting an empty identifier).  Downstream crates (lexer,
5//! parser, evaluator) layer their own errors on top.
6
7/// All errors that arise when constructing AST nodes from raw input.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum Error {
10    /// An identifier was empty or contained an illegal character.
11    InvalidIdentifier {
12        /// The string that was attempted.
13        attempted: String,
14        /// Short description of why it is invalid.
15        reason: &'static str,
16    },
17    /// A regex literal pattern was empty.
18    EmptyRegexPattern,
19    /// A regex literal carried a flag character not recognised by ECMA-262.
20    InvalidRegexFlag {
21        /// The offending flag character.
22        flag: char,
23    },
24    /// A template literal had a different number of quasis than expressions
25    /// allow (must satisfy `quasis.len() == expressions.len() + 1`).
26    UnbalancedTemplate {
27        /// Number of literal chunks supplied.
28        quasis: usize,
29        /// Number of interpolated expressions supplied.
30        expressions: usize,
31    },
32}
33
34impl std::fmt::Display for Error {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        match self {
37            Self::InvalidIdentifier { attempted, reason } => {
38                write!(f, "invalid identifier {attempted:?}: {reason}")
39            }
40            Self::EmptyRegexPattern => f.write_str("regex literal pattern is empty"),
41            Self::InvalidRegexFlag { flag } => {
42                write!(f, "invalid regex flag {flag:?}")
43            }
44            Self::UnbalancedTemplate {
45                quasis,
46                expressions,
47            } => write!(
48                f,
49                "unbalanced template literal: {quasis} quasis and {expressions} expressions (must satisfy quasis == expressions + 1)"
50            ),
51        }
52    }
53}
54
55impl std::error::Error for Error {}