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
//! [`JSResult`], [`Exception`], [`ParseError`], etc.

#[cfg(feature = "std")]
use std::io;

use crate::prelude::*;
use crate::{
    ast::Identifier,
    Interpreted,
    JSValue,
    JSON,
};

pub type JSResult<T> = Result<T, Exception>;

pub type ParseResult<T> = Result<T, ParseError>;

#[derive(Debug, PartialEq, Eq)]
pub enum ParseError {
    InvalidJSON { err: String },
    ObjectWithout { attr: String, value: JSON },
    UnexpectedValue { want: &'static str, value: JSON },
    UnknownNodeType { value: JSON },
    ReferencedBeforeDeclaration {},
    BindingRedeclared { name: Identifier },
}

impl ParseError {
    pub fn no_attr(attr: &str, at: JSON) -> Self {
        ParseError::ObjectWithout {
            attr: attr.to_string(),
            value: at,
        }
    }

    pub fn want(want: &'static str, got: JSON) -> Self {
        Self::UnexpectedValue { want, value: got }
    }

    pub fn invalid_ast<E: fmt::Debug>(e: E) -> Self {
        let err = format!("{:?}", e);
        ParseError::InvalidJSON { err }
    }
}

impl From<&str> for ParseError {
    fn from(err: &str) -> Self {
        // This assumes nodejs-formatted Esprima error output.
        let mut err = unescape(err);
        if err.ends_with('}') {
            if let Some(at) = err.rfind('{') {
                // let jerr = err.split_off(at); // TODO: parse the error JSON
                err.truncate(at)
            }
        }
        Self::InvalidJSON { err }
    }
}

#[derive(Debug, PartialEq)]
pub enum Exception {
    SyntaxTreeError(ParseError),
    SyntaxErrorForInMultipleVar(),
    SyntaxErrorContinueLabelNotALoop(Identifier),

    ReferenceNotAnObject(Interpreted),
    ReferenceNotFound(Identifier),
    TypeErrorSetReadonly(Interpreted, JSString),
    TypeErrorNotConfigurable(Interpreted, JSString),
    TypeErrorGetProperty(Interpreted, JSString),
    TypeErrorCannotAssign(Interpreted),
    TypeErrorConstAssign(Interpreted),
    TypeErrorNotCallable(Interpreted),
    TypeErrorNotArraylike(Interpreted),
    TypeErrorInstanceRequired(Interpreted, JSString),
    TypeErrorInvalidDescriptor(Interpreted),
    TypeErrorInvalidPrototype(Interpreted),

    // nonlocal transfers of control, "abrupt completions"
    JumpReturn(Interpreted),
    JumpBreak(Option<Identifier>),
    JumpContinue(Option<Identifier>),

    UserThrown(JSValue),
}

// TODO: impl Display for Exception
// TODO: #[cfg(feature = "std"] impl Error for Exception
// TODO: capture JavaScript stack trace in Exception

impl Exception {
    pub fn instance_required<V>(arg: V, of: &str) -> Exception
    where
        Interpreted: From<V>,
    {
        let arg = Interpreted::from(arg);
        Exception::TypeErrorInstanceRequired(arg, of.into())
    }
}

impl From<ParseError> for Exception {
    fn from(err: ParseError) -> Self {
        Self::SyntaxTreeError(err)
    }
}

#[cfg(feature = "std")]
impl From<Exception> for io::Error {
    fn from(exc: Exception) -> io::Error {
        // TODO: impl Display for Exception
        let msg = format!("{:?}", exc);
        io::Error::new(io::ErrorKind::Other, msg)
    }
}

pub fn ignore_set_readonly(e: Exception) -> JSResult<()> {
    match e {
        Exception::TypeErrorSetReadonly(_, _) => Ok(()),
        _ => Err(e),
    }
}

pub fn unescape(input: &str) -> String {
    struct Unescape<C>(C);

    impl<C> Iterator for Unescape<C>
    where
        C: Iterator<Item = char>,
    {
        type Item = char;

        fn next(&mut self) -> Option<Self::Item> {
            match self.0.next() {
                Some('\\') => {
                    let c = self.0.next();
                    match c {
                        Some('n') => Some('\n'),
                        Some('t') => Some('\t'),
                        Some(_) => c,
                        None => Some('\\'),
                    }
                }
                other => other,
            }
        }
    }

    let input = input.trim_matches('"').trim();
    String::from_iter(Unescape(input.chars()))
}