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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! AST definitions for JavaScript expressions.
//!
//! The main struct here is [`Expression`], which wraps [`Expr`] enum.

use crate::derive_enum_from;
use crate::prelude::*;

use crate::{
    ast::Binding,
    source,
    JSValue,
    JSON,
};

use super::stmt::BlockStatement;

/// `Expression` represents an [`Expr`] together with its source span, if any.
#[derive(Debug, Clone)]
pub struct Expression {
    pub expr: Expr,
    pub loc: Option<Box<source::Location>>,
}

impl Expression {
    pub fn with_loc(self, loc: source::Location) -> Self {
        Expression {
            expr: self.expr,
            loc: Some(Box::new(loc)),
        }
    }
}

impl PartialEq for Expression {
    fn eq(&self, other: &Self) -> bool {
        self.expr == other.expr
    }
}
impl Eq for Expression {}

impl<E> From<E> for Expression
where
    Expr: From<E>,
{
    fn from(expr: E) -> Expression {
        let expr = Expr::from(expr);
        Expression { expr, loc: None }
    }
}

/// The enumeration of every possible kind of JS expressions.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    Literal(Literal),
    Identifier(Identifier),
    BinaryOp(Box<BinaryExpression>),
    LogicalOp(Box<LogicalExpression>),
    Call(Box<CallExpression>),
    Array(ArrayExpression),
    Object(ObjectExpression),
    Member(Box<MemberExpression>),
    Assign(Box<AssignmentExpression>),
    Conditional(Box<ConditionalExpression>),
    Unary(Box<UnaryExpression>),
    Update(Box<UpdateExpression>),
    Sequence(SequenceExpression),
    Function(FunctionExpression),
    This,
    New(Box<NewExpression>),
}

derive_enum_from!(Expr::Literal, T: Into<Literal>);
derive_enum_from!(Expr::Identifier);
derive_enum_from!(Expr::BinaryOp, Box<BinaryExpression>);
derive_enum_from!(Expr::Unary, Box<UnaryExpression>);
derive_enum_from!(Expr::Array, ArrayExpression);
derive_enum_from!(Expr::Object, ObjectExpression);
derive_enum_from!(Expr::Function, FunctionExpression);
derive_enum_from!(Expr::Member, Box<MemberExpression>);
derive_enum_from!(Expr::Call, Box<CallExpression>);

// NOTE: the internal JSValue must not contain references.
#[derive(Clone, Debug, PartialEq)]
pub struct Literal(JSValue);

impl Literal {
    pub const NULL: Literal = Literal(JSValue::NULL);

    pub fn to_value(&self) -> JSValue {
        self.0.clone()
    }

    pub fn to_json(&self) -> JSON {
        match &self.0 {
            JSValue::Bool(b) => JSON::from(*b),
            JSValue::Number(n) => JSON::from(*n),
            JSValue::String(s) => JSON::from(s.as_str()),
            JSValue::Undefined => JSON::Null,
            JSValue::Ref(r) if r.is_null() => JSON::Null,
            _ => unreachable!(),
        }
    }
}

impl fmt::Display for Literal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            JSValue::Undefined => write!(f, "undefined"),
            JSValue::Ref(r) if r.is_null() => write!(f, "null"),
            JSValue::Bool(b) => write!(f, "{}", *b),
            JSValue::Number(n) => write!(f, "{}", *n),
            JSValue::String(s) => {
                write!(f, "\"{}\"", s.as_str().escape_default())
            }
            _ => unreachable!(),
        }
    }
}

impl TryFrom<&JSON> for Literal {
    type Error = ();

    fn try_from(json: &JSON) -> Result<Self, Self::Error> {
        let value = if json.is_null() {
            JSValue::NULL
        } else if let Some(b) = json.as_bool() {
            JSValue::from(b)
        } else if let Some(n) = json.as_f64() {
            JSValue::from(n)
        } else if let Some(s) = json.as_str() {
            JSValue::from(s)
        } else {
            return Err(());
        };
        Ok(Literal(value))
    }
}

impl TryFrom<JSValue> for Literal {
    type Error = ();

    fn try_from(val: JSValue) -> Result<Self, Self::Error> {
        match val {
            JSValue::Ref(r) if !r.is_null() => Err(()),
            _ => Ok(Literal(val)),
        }
    }
}

impl From<bool> for Literal {
    fn from(b: bool) -> Self {
        Literal(JSValue::from(b))
    }
}
impl From<f64> for Literal {
    fn from(n: f64) -> Self {
        Literal(JSValue::from(n))
    }
}
impl From<i64> for Literal {
    fn from(n: i64) -> Self {
        Literal(JSValue::from(n))
    }
}
impl From<&str> for Literal {
    fn from(s: &str) -> Self {
        Literal(JSValue::from(s))
    }
}
impl From<JSString> for Literal {
    fn from(s: JSString) -> Self {
        Literal(JSValue::String(s))
    }
}

#[derive(Clone, Debug, PartialEq, Hash, Eq)]
pub struct Identifier(pub JSString);

impl Identifier {
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl From<&str> for Identifier {
    fn from(s: &str) -> Identifier {
        Identifier(s.into())
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BinaryExpression(pub Expression, pub BinOp, pub Expression);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LogicalExpression(pub Expression, pub BoolOp, pub Expression);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnaryExpression(pub UnOp, pub Expression);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UpdateExpression(pub UpdOp, pub bool, pub Expression);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallExpression(pub Expression, pub Vec<Expression>);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArrayExpression(pub Vec<Expression>);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ObjectExpression(pub Vec<(ObjectKey, Expression)>);

/// Describes an [`ObjectExpression`] key: `ObjectKey::Computed` or `ObjectKey::Identifier`
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ObjectKey {
    Computed(Expression),
    Identifier(JSString),
}

impl<E> From<E> for ObjectKey
where
    Expression: From<E>,
{
    fn from(expr: E) -> Self {
        let expr = Expression::from(expr);
        match expr.expr {
            Expr::Identifier(id) => ObjectKey::Identifier(id.0),
            _ => ObjectKey::Computed(expr),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MemberExpression(pub Expression, pub Expression, pub bool);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SequenceExpression(pub Vec<Expression>);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AssignmentExpression(pub Expression, pub Option<BinOp>, pub Expression);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConditionalExpression {
    pub condexpr: Expression,
    pub thenexpr: Expression,
    pub elseexpr: Expression,
}

/// `Function` describes a JS function definition (`params`, `body`, etc).
///
/// Can only be created with [`super::LexicalContext::enter_function`], to have mandatory
/// static analysis.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Function {
    pub id: Option<Identifier>,
    pub params: Vec<Pattern>, // cannot be a HashSet, needs order
    pub body: BlockStatement,
    pub(super) locals: Vec<Binding>, // the set of variables
    pub(super) free_variables: Vec<Identifier>,
    // TODO: pub is_generator: bool,
    // TODO: pub is_expression: bool,
    // TODO: pub is_async: bool,
}

impl Function {
    pub fn bindings_iter(&self) -> FuncBindings {
        FuncBindings {
            func: self,
            local_idx: 0, /*, let_idx: 0*/
        }
    }

    pub fn freevars_iter(&self) -> impl Iterator<Item = &Identifier> {
        self.free_variables.iter()
    }
}

pub struct FuncBindings<'f> {
    func: &'f Function,
    local_idx: usize,
    //let_idx: usize,
}

impl<'b> Iterator for FuncBindings<'b> {
    type Item = Binding;

    fn next(&mut self) -> Option<Binding> {
        if let Some(lb) = self.func.locals.get(self.local_idx) {
            self.local_idx += 1;
            return Some(lb.clone());
        }
        /*
        if let Some(b) = self.func.bindings.get(self.let_idx) {
            self.let_idx += 1;
            return Some(Binding::from(b.clone()));
        }
        */
        None
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FunctionExpression {
    pub func: Rc<Function>,
}

// TODO: enum { AssignmentPattern, Identifier, BindingPattern }
pub type Pattern = Identifier;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewExpression(pub Expression, pub Vec<Expression>);

/// Lists all possible binary operation for [`BinaryExpression`]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BinOp {
    Plus,
    Minus,
    Star,
    Slash,
    Percent,
    EqEq,
    NotEq,
    EqEqEq,
    NotEqEq,
    Less,
    Greater,
    LtEq,
    GtEq,
    Pipe,
    Hat,
    Ampersand,
    LtLt,
    GtGt,
    GtGtGt,
    In,
    InstanceOf,
}

/// Lists all boolean operations (`&&`, `||`) for [`LogicalExpression`]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BoolOp {
    And,
    Or,
}

/// Lists all unary operations for [`UnaryExpression`]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnOp {
    Exclamation,
    Minus,
    Plus,
    Tilde,
    Typeof,
    Void,
    Delete,
}

/// Lists all update operations (`++`, `--`) for [`UpdateExpression`]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UpdOp {
    Increment,
    Decrement,
}