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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use crate::pat::Pat;
use crate::{AssignOp, BinaryOp, LogicalOp, PropKind, UnaryOp, UpdateOp};
use crate::{Class, Func, FuncArg, FuncBody, Ident};
use std::borrow::Cow;
/// A slightly more granular program part that a statement
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    all(feature = "serde", not(feature = "esprima")),
    derive(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "serde", feature = "esprima"), derive(Deserialize))]
#[cfg_attr(all(feature = "serde", feature = "esprima"), serde(untagged))]
pub enum Expr<'a> {
    /// `[0,,]`
    Array(ArrayExpr<'a>),
    /// An arrow function
    /// ```js
    /// () => console.log();
    /// x => {
    ///     return x;
    /// }
    /// ```
    ArrowFunc(ArrowFuncExpr<'a>),
    /// Used for resolving possible sequence expressions
    /// that are arrow parameters
    ArrowParamPlaceHolder(Vec<FuncArg<'a>>, bool),
    /// Assignment or update assignment
    /// ```js
    /// a = 0
    /// b += 1
    /// ```
    Assign(AssignExpr<'a>),
    /// The `await` keyword followed by another `Expr`
    Await(Box<Expr<'a>>),
    /// An operation that has two arguments
    Binary(BinaryExpr<'a>),
    /// A class expression see `Class`
    Class(Class<'a>),
    /// Calling a function or method
    Call(CallExpr<'a>),
    /// A ternery expression
    Conditional(ConditionalExpr<'a>),
    /// see `Function`
    Func(Func<'a>),
    /// An identifier
    Ident(Ident<'a>),
    /// A literal value, see `Literal`
    Lit(Lit<'a>),
    /// A specialized `BinaryExpr` for logical evaluation
    /// ```js
    /// true && true
    /// false || true
    /// ```
    Logical(LogicalExpr<'a>),
    /// Accessing the member of a value
    /// ```js
    /// b['thing'];
    /// c.stuff;
    /// ```
    Member(MemberExpr<'a>),
    /// currently just `new.target`
    MetaProp(MetaProp<'a>),
    /// ```js
    /// var a = true ? 'stuff' : 'things';
    /// ```
    /// `{}`
    /// Calling a constructor
    New(NewExpr<'a>),
    Obj(ObjExpr<'a>),
    /// Any sequence of expressions separated with a comma
    Sequence(SequenceExpr<'a>),
    /// `...` followed by an `Expr`
    Spread(Box<Expr<'a>>),
    /// `super`
    Super,
    /// A template literal preceded by a tag function identifier
    TaggedTemplate(TaggedTemplateExpr<'a>),
    /// `this`
    This,
    /// An operation that has one argument
    /// ```js
    /// typeof 'a';
    /// +9;
    /// ```
    Unary(UnaryExpr<'a>),
    /// Increment or decrement
    /// ```js
    /// 1++
    /// --2
    /// ```
    Update(UpdateExpr<'a>),
    /// yield a value from inside of a generator function
    Yield(YieldExpr<'a>),
}

impl<'a> Expr<'a> {
    pub fn ident_from(s: &'a str) -> Self {
        Expr::Ident(Ident::from(s))
    }
}

/// `[a, b, c]`
pub type ArrayExpr<'a> = Vec<Option<Expr<'a>>>;
/// `{a: 'b', c, ...d}`
pub type ObjExpr<'a> = Vec<ObjProp<'a>>;
/// A single part of an object literal
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
#[cfg_attr(all(feature = "serde", feature = "esprima"), serde(untagged))]
pub enum ObjProp<'a> {
    Prop(Prop<'a>),
    Spread(Expr<'a>),
}

/// A single part of an object literal or class
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    all(feature = "serde", not(feature = "esprima")),
    derive(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "serde", feature = "esprima"), derive(Deserialize))]
pub struct Prop<'a> {
    pub key: PropKey<'a>,
    pub value: PropValue<'a>,
    pub kind: PropKind,
    pub method: bool,
    pub computed: bool,
    pub short_hand: bool,
    pub is_static: bool,
}

/// An object literal or class property identifier
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
#[cfg_attr(all(feature = "serde", feature = "esprima"), serde(untagged))]
pub enum PropKey<'a> {
    Lit(Lit<'a>),
    Expr(Expr<'a>),
    Pat(Pat<'a>),
}

/// The value of an object literal or class property
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
#[cfg_attr(all(feature = "serde", feature = "esprima"), serde(untagged))]
pub enum PropValue<'a> {
    Expr(Expr<'a>),
    Pat(Pat<'a>),
    None,
}

/// An operation that takes one argument
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct UnaryExpr<'a> {
    pub operator: UnaryOp,
    pub prefix: bool,
    pub argument: Box<Expr<'a>>,
}

/// Increment or decrementing a value
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct UpdateExpr<'a> {
    pub operator: UpdateOp,
    pub argument: Box<Expr<'a>>,
    pub prefix: bool,
}

/// An operation that requires 2 arguments
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct BinaryExpr<'a> {
    pub operator: BinaryOp,
    pub left: Box<Expr<'a>>,
    pub right: Box<Expr<'a>>,
}

/// An assignment or update + assignment operation
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct AssignExpr<'a> {
    pub operator: AssignOp,
    pub left: AssignLeft<'a>,
    pub right: Box<Expr<'a>>,
}

/// The value being assigned to
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
#[cfg_attr(all(feature = "serde", feature = "esprima"), serde(untagged))]
pub enum AssignLeft<'a> {
    Pat(Pat<'a>),
    Expr(Box<Expr<'a>>),
}

/// A specialized `BinaryExpr` for logical evaluation
/// ```js
/// true && true
/// false || true
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct LogicalExpr<'a> {
    pub operator: LogicalOp,
    pub left: Box<Expr<'a>>,
    pub right: Box<Expr<'a>>,
}

/// Accessing the member of a value
/// ```js
/// b['thing'];
/// c.stuff;
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct MemberExpr<'a> {
    pub object: Box<Expr<'a>>,
    pub property: Box<Expr<'a>>,
    pub computed: bool,
}

/// A ternery expression
/// ```js
/// var a = true ? 'stuff' : 'things';
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct ConditionalExpr<'a> {
    pub test: Box<Expr<'a>>,
    pub alternate: Box<Expr<'a>>,
    pub consequent: Box<Expr<'a>>,
}

/// Calling a function or method
/// ```js
/// Math.random()
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct CallExpr<'a> {
    pub callee: Box<Expr<'a>>,
    pub arguments: Vec<Expr<'a>>,
}

/// Calling a constructor
/// ```js
/// new Uint8Array(32);
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct NewExpr<'a> {
    pub callee: Box<Expr<'a>>,
    pub arguments: Vec<Expr<'a>>,
}

/// A collection of `Exprs` separated by commas
pub type SequenceExpr<'a> = Vec<Expr<'a>>;

/// An arrow function
/// ```js
/// let x = () => y;
/// let q = x => {
///     return x + 1;
/// }
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct ArrowFuncExpr<'a> {
    pub id: Option<Ident<'a>>,
    pub params: Vec<FuncArg<'a>>,
    pub body: ArrowFuncBody<'a>,
    pub expression: bool,
    pub generator: bool,
    pub is_async: bool,
}

/// The body portion of an arrow function can be either an expression or a block of statements
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub enum ArrowFuncBody<'a> {
    FuncBody(FuncBody<'a>),
    Expr(Box<Expr<'a>>),
}

/// yield a value from inside of a generator function
/// ```js
/// function *gen() {
///     while ((new Date() / 1000) < Number.MAX_VALUE) {
///         yield new Date() / 1000;
///     }
/// }
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct YieldExpr<'a> {
    pub argument: Option<Box<Expr<'a>>>,
    pub delegate: bool,
}

/// A Template literal preceded by a function identifier
/// see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) for more details
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct TaggedTemplateExpr<'a> {
    pub tag: Box<Expr<'a>>,
    pub quasi: TemplateLit<'a>,
}

/// A template string literal
/// ```js
/// `I own ${0} birds`;
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    all(feature = "serde", not(feature = "esprima")),
    derive(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "serde", feature = "esprima"), derive(Deserialize))]
pub struct TemplateLit<'a> {
    pub quasis: Vec<TemplateElement<'a>>,
    pub expressions: Vec<Expr<'a>>,
}

/// The text part of a `TemplateLiteral`
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    all(feature = "serde", not(feature = "esprima")),
    derive(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "serde", feature = "esprima"), derive(Deserialize))]
pub struct TemplateElement<'a> {
    pub tail: bool,
    /// The non-quoted version
    pub cooked: Cow<'a, str>,
    /// The quoted version
    pub raw: Cow<'a, str>,
}

impl<'a> TemplateElement<'a> {
    pub fn from(tail: bool, cooked: &'a str, raw: &'a str) -> TemplateElement<'a> {
        Self {
            tail,
            cooked: Cow::Borrowed(cooked),
            raw: Cow::Borrowed(raw),
        }
    }
}

/// pretty much just `new.target`
/// ```js
/// function Thing(one, two) {
///     if (!new.target) {
///         return new Thing(one, two);
///     }
///     this.one = one;
///     this.two = two;
/// }
/// ```
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub struct MetaProp<'a> {
    pub meta: Ident<'a>,
    pub property: Ident<'a>,
}

/// A literal value
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    all(feature = "serde", not(feature = "esprima")),
    derive(Deserialize, Serialize)
)]
#[cfg_attr(all(feature = "serde", feature = "esprima"), derive(Deserialize))]
pub enum Lit<'a> {
    /// `null`
    Null,
    /// `"string"`
    /// `'string'`
    String(StringLit<'a>),
    /// `0`
    /// `0.0`
    /// `.0`
    /// `0.0e1`
    /// `.0E1`
    /// `0xf`
    /// `0o7`
    /// `0b1`
    Number(Cow<'a, str>),
    /// `true`
    /// `false`
    Boolean(bool),
    /// `/.+/g`
    RegEx(RegEx<'a>),
    /// ```js
    /// `I have ${0} apples`
    /// ```
    Template(TemplateLit<'a>),
}

impl<'a> Lit<'a> {
    pub fn number_from(s: &'a str) -> Self {
        Lit::Number(Cow::Borrowed(s))
    }
    pub fn single_string_from(s: &'a str) -> Self {
        Lit::String(StringLit::single_from(s))
    }
    pub fn double_string_from(s: &'a str) -> Self {
        Lit::String(StringLit::double_from(s))
    }
}

#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
pub enum StringLit<'a> {
    Double(Cow<'a, str>),
    Single(Cow<'a, str>),
}

impl<'a> StringLit<'a> {
    pub fn double_from(s: &'a str) -> StringLit<'a> {
        StringLit::Double(Cow::Borrowed(s))
    }
    pub fn single_from(s: &'a str) -> StringLit<'a> {
        StringLit::Single(Cow::Borrowed(s))
    }
    pub fn clone_inner(&self) -> Cow<'a, str> {
        match self {
            StringLit::Single(ref s) => s.clone(),
            StringLit::Double(ref s) => s.clone(),
        }
    }
    pub fn inner_matches(&self, o: &str) -> bool {
        match self {
            StringLit::Single(ref s) => s == o,
            StringLit::Double(ref d) => d == o,
        }
    }
}
/// A regular expression literal
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(all(feature = "serialization"), derive(Deserialize, Serialize))]
#[cfg_attr(all(feature = "serialization"), serde(rename_all = "camelCase"))]
pub struct RegEx<'a> {
    pub pattern: Cow<'a, str>,
    pub flags: Cow<'a, str>,
}

impl<'a> RegEx<'a> {
    pub fn from(p: &'a str, f: &'a str) -> Self {
        RegEx {
            pattern: Cow::Borrowed(p),
            flags: Cow::Borrowed(f),
        }
    }
}