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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! AST nodes for JS

use serde::{Serialize, Serializer};

/// A literal value.
#[derive(Debug, PartialEq, Clone, Serialize)]
#[serde(untagged)]
pub enum LiteralValue {
    String(String),
    Boolean(bool),
    Null,
    Number(f64),
    RegExp(String),
}

impl LiteralValue {
    pub fn into_node_kind<'a>(self) -> NodeKind<'a> {
        self.into()
    }
}

impl<'a> From<LiteralValue> for NodeKind<'a> {
    fn from(value: LiteralValue) -> Self {
        NodeKind::Literal { value }
    }
}

/// A function declaration or expression.
#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct Function<'a> {
    /// `type: Identifier | null`
    pub id: Box<Option<Node<'a>>>,
    /// `type: [ Pattern ]`
    pub params: Vec<Node<'a>>,
    /// `type: FunctionBody`
    pub body: Box<Node<'a>>,
    #[serde(rename = "async")]
    pub is_async: bool,
}

#[derive(Debug, PartialEq, Clone)]
pub enum VariableDeclarationKind {
    Var,
}

impl Serialize for VariableDeclarationKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            VariableDeclarationKind::Var => "var",
        };

        serializer.serialize_str(s)
    }
}

/// Ordinary property initializers have a kind value `"init"`; getters and setters have the kind values `"get"` and `"set"`, respectively.
#[derive(Debug, PartialEq, Clone)]
pub enum PropertyKind {
    Init,
    Get,
    Set,
}

impl Serialize for PropertyKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            PropertyKind::Init => "init",
            PropertyKind::Get => "get",
            PropertyKind::Set => "set",
        };

        serializer.serialize_str(s)
    }
}

/// An unary operator token.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum UnaryOperator {
    Minus,
    Plus,
    LogicalNot,
    BitwiseNot,
    Typeof,
    Void,
    Delete,
}

impl Serialize for UnaryOperator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            UnaryOperator::Minus => "-",
            UnaryOperator::Plus => "+",
            UnaryOperator::LogicalNot => "!",
            UnaryOperator::BitwiseNot => "~",
            UnaryOperator::Typeof => "typeof",
            UnaryOperator::Void => "void",
            UnaryOperator::Delete => "delete",
        };

        serializer.serialize_str(s)
    }
}

/// An update (increment or decrement) operator token.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum UpdateOperator {
    Increment,
    Decrement,
}

impl Serialize for UpdateOperator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            UpdateOperator::Increment => "++",
            UpdateOperator::Decrement => "--",
        };

        serializer.serialize_str(s)
    }
}

/// A binary operator token.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum BinaryOperator {
    EqualsEquals,
    NotEquals,
    TripleEquals,
    TripleNotEquals,
    LessThan,
    LessThanEquals,
    GreaterThan,
    GreaterThanEquals,
    /// `<<`
    ZeroFillLeftShift,
    /// `>>`
    SignedRightShift,
    /// `>>>`
    ZeroFillRightShift,
    /// `**`
    Exponentiation,
    Plus,
    Minus,
    Asterisk,
    Slash,
    Percent,
    BitwiseOr,
    BitwiseXor,
    BitwiseAnd,
    In,
    Instanceof,
}

impl Serialize for BinaryOperator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            BinaryOperator::EqualsEquals => "==",
            BinaryOperator::NotEquals => "!=",
            BinaryOperator::TripleEquals => "===",
            BinaryOperator::TripleNotEquals => "!==",
            BinaryOperator::LessThan => "<",
            BinaryOperator::LessThanEquals => "<=",
            BinaryOperator::GreaterThan => ">",
            BinaryOperator::GreaterThanEquals => ">=",
            BinaryOperator::ZeroFillLeftShift => "<<",
            BinaryOperator::SignedRightShift => ">>",
            BinaryOperator::ZeroFillRightShift => ">>>",
            BinaryOperator::Plus => "+",
            BinaryOperator::Minus => "-",
            BinaryOperator::Exponentiation => "**",
            BinaryOperator::Asterisk => "*",
            BinaryOperator::Slash => "/",
            BinaryOperator::Percent => "%",
            BinaryOperator::BitwiseOr => "|",
            BinaryOperator::BitwiseXor => "^",
            BinaryOperator::BitwiseAnd => "&",
            BinaryOperator::In => "in",
            BinaryOperator::Instanceof => "instanceof",
        };

        serializer.serialize_str(s)
    }
}

/// An assignment operator token.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum AssignmentOperator {
    Equals,
    PlusEquals,
    MinusEquals,
    ExponentEquals,
    AsteriskEquals,
    SlashEquals,
    PercentEquals,
    /// `<<=`
    ZeroFillLeftShiftEquals,
    /// `>>=`
    SignedRightShiftEquals,
    /// `>>>=`
    ZeroFillRightShiftEquals,
    /// `|=`
    BitwiseOrEquals,
    /// `^=`
    BitwiseXorEquals,
    /// `&=`
    BitwiseAndEquals,
}

impl Serialize for AssignmentOperator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            AssignmentOperator::Equals => "=",
            AssignmentOperator::PlusEquals => "+=",
            AssignmentOperator::MinusEquals => "-=",
            AssignmentOperator::ExponentEquals => "**=",
            AssignmentOperator::AsteriskEquals => "*=",
            AssignmentOperator::SlashEquals => "/=",
            AssignmentOperator::PercentEquals => "%=",
            AssignmentOperator::ZeroFillLeftShiftEquals => "<<=",
            AssignmentOperator::SignedRightShiftEquals => ">>=",
            AssignmentOperator::ZeroFillRightShiftEquals => ">>>=",
            AssignmentOperator::BitwiseOrEquals => "|=",
            AssignmentOperator::BitwiseXorEquals => "^=",
            AssignmentOperator::BitwiseAndEquals => "&=",
        };

        serializer.serialize_str(s)
    }
}

/// A logical operator token.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum LogicalOperator {
    LogicalOr,
    LogicalAnd,
}

impl Serialize for LogicalOperator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let s = match self {
            LogicalOperator::LogicalOr => "||",
            LogicalOperator::LogicalAnd => "&&",
        };

        serializer.serialize_str(s)
    }
}

/// A mega enum with ever single possible AST node.
/// Refer to https://github.com/estree/estree/blob/master/es5.md for spec on AST nodes.
#[derive(Debug, PartialEq, Clone, Serialize)]
#[serde(tag = "type")]
pub enum NodeKind<'a> {
    /// An identifier. Note that an identifier may be an expression or a destructuring pattern.
    Identifier {
        name: String,
    },
    /// A literal token. Note that a literal can be an expression.
    Literal {
        value: LiteralValue,
    },
    /// A complete program source tree.
    Program {
        /// `type: [ Directive | Statement ]`
        body: Vec<Node<'a>>,
    },
    /*
    Statements
    */
    /// An expression statement, i.e., a statement consisting of a single expression.
    ///
    /// *or:*
    ///
    /// A directive from the directive prologue of a script or function.
    /// The `directive` property is the raw string source of the directive without quotes.
    ///
    /// # Note
    /// There is no separate `Directive` case in the enum because the ESTree spec describes the `Directive` node as having a `type` field of `ExpressionStatement`.
    ExpressionStatement {
        /// `type: Expression`
        expression: Box<Node<'a>>,
        /// The raw string source of the directive without quotes. If not a directive, should be `None`.
        #[serde(skip_serializing_if = "Option::is_none")]
        directive: Option<String>,
    },
    /// A block statement, i.e., a sequence of statements surrounded by braces.
    ///
    /// *or:*
    ///
    /// The body of a function, which is a block statement that may begin with directives.
    /// # Note
    /// There is no separate `FunctionBody` case in the enum because the ESTree spec describes the `FunctionBody` node as having a `type` field of `BlockStatement`.
    BlockStatement {
        /// `type: [ Statement ]`
        body: Vec<Node<'a>>,
    },
    /// An empty statement, i.e., a solitary semicolon.
    EmptyStatement,
    /// A `debugger` statement.
    DebuggerStatement,
    /// A `with` statement.
    WithStatement {
        /// `type: Expression`
        object: Box<Node<'a>>,
        /// `type: Statement`
        body: Box<Node<'a>>,
    },
    /*
    Statements / Control Flow
    */
    /// A `return` statement.
    ReturnStatement {
        /// `type: Expression | null`
        argument: Box<Option<Node<'a>>>,
    },
    /// A labeled statement, i.e., a statement prefixed by a `break`/`continue` label.
    LabeledStatement {
        /// `type: Identifier`
        label: Box<Node<'a>>,
        /// `type: Statement`
        body: Box<Node<'a>>,
    },
    /// A `break` statement.
    BreakStatement {
        /// `type: Identifier | null`
        label: Box<Option<Node<'a>>>,
    },
    /// A `continue` statement.
    ContinueStatement {
        /// `type: Identifier | null`
        label: Box<Option<Node<'a>>>,
    },
    /*
    Statements / Choice
    */
    /// An `if` statement.
    IfStatement {
        /// `type: Expression`
        test: Box<Node<'a>>,
        /// `type: Statement`
        consequent: Box<Node<'a>>,
        /// `type: Statement | null`
        alternate: Box<Option<Node<'a>>>,
    },
    /// A `switch` statement.
    SwitchStatement {
        /// `type: Expression`
        discriminant: Box<Node<'a>>,
        /// `type: [ SwitchCase ]`
        cases: Vec<Node<'a>>,
    },
    /// A `case` (if `test` is an `Expression`) or `default` (if `test === null`) clause in the body of a `switch` statement.
    SwitchCase {
        /// `type: Expression | null`
        test: Box<Option<Node<'a>>>,
        /// `type: [ Statement ]`
        consequent: Vec<Node<'a>>,
    },
    /*
    Statements / Exceptions
    */
    /// A `throw` statement.
    ThrowStatement {
        /// `type: Expression`
        argument: Box<Node<'a>>,
    },
    /// A `try` statement. If `handler` is `null` then `finalizer` must be a `BlockStatement`.
    TryStatement {
        /// `type: BlockStatement`
        block: Box<Node<'a>>,
        /// `type: CatchClause | null`
        handler: Box<Option<Node<'a>>>,
        /// `type: BlockStatement | null`
        finalizer: Box<Option<Node<'a>>>,
    },
    CatchClause {
        /// `type: Pattern`
        param: Box<Node<'a>>,
        /// `type: BlockStatement`
        body: Box<Node<'a>>,
    },
    /*
    Statements / Loops
    */
    /// A `while` statement.
    WhileStatement {
        /// `type: Expression`
        test: Box<Node<'a>>,
        /// `type: Statement`
        body: Box<Node<'a>>,
    },
    /// A `do`/`while` statement.
    DoWhileStatement {
        /// `type: Statement`
        body: Box<Node<'a>>,
        /// `type: Expression`
        test: Box<Node<'a>>,
    },
    /// A `for` statement.
    ForStatement {
        /// `type: VariableDeclaration | Expression | null`
        init: Box<Option<Node<'a>>>,
        /// `type: Expression | null`
        test: Box<Option<Node<'a>>>,
        /// `type: Expression | null`
        update: Box<Option<Node<'a>>>,
        /// `type: Statement`
        body: Box<Node<'a>>,
    },
    /// A `for`/`in` statement.
    ForInStatement {
        /// `type: VariableDeclaration |  Pattern`
        left: Box<Node<'a>>,
        /// `type: Expression`
        right: Box<Node<'a>>,
        /// `type: Statement`
        body: Box<Node<'a>>,
    },
    /*
    Statements / Declarations
    */
    /// A function declaration.
    /// Note that unlike in the parent interface `Function`, the `id` cannot be `null`.
    FunctionDeclaration {
        /// `type: Function`
        #[serde(flatten)]
        function: Function<'a>,
    },
    /// A variable declaration.
    VariableDeclaration {
        /// `type: [ VariableDeclarator ]`
        declarations: Vec<Node<'a>>,
        kind: VariableDeclarationKind,
    },
    /// A variable declarator.
    VariableDeclarator {
        /// `type: Pattern`
        id: Box<Node<'a>>,
        /// `type: Expression | null`
        init: Box<Option<Node<'a>>>,
    },
    /*
    Expressions
    */
    /// A `this` expression.
    ThisExpression,
    /// An array expression. An element might be `null` if it represents a hole in a sparse array. E.g. `[1,,2]`.
    ArrayExpression {
        /// `type: [ Expression | null ]`
        elements: Vec<Option<Node<'a>>>,
    },
    /// An object expression.
    ObjectExpression {
        /// `type: [ Property ]`
        properties: Vec<Node<'a>>,
    },
    /// A literal property in an object expression can have either a string or number as its `value`.
    Property {
        /// `type: Literal | Identifier`
        key: Box<Node<'a>>,
        /// `type: Expression`
        value: Box<Node<'a>>,
        kind: PropertyKind,
    },
    /// A `function` expression.
    FunctionExpression {
        /// `type: Function`
        #[serde(flatten)]
        function: Function<'a>,
    },
    /*
    Expressions / Unary operations
    */
    /// An unary operator expression.
    UnaryExpression {
        operator: UnaryOperator,
        prefix: bool,
        /// `type: Expression`
        argument: Box<Node<'a>>,
    },
    /// An update (increment or decrement) operator expression.
    UpdateExpression {
        operator: UpdateOperator,
        /// `type: Expression`
        argument: Box<Node<'a>>,
        prefix: bool,
    },
    /// An await expression.
    AwaitExpression {
        /// `type: Expression`
        argument: Box<Node<'a>>,
    },
    /*
    Expressions / Binary operations
    */
    /// A binary operator expression.
    BinaryExpression {
        operator: BinaryOperator,
        /// `type: Expression`
        left: Box<Node<'a>>,
        /// `type: Expression`
        right: Box<Node<'a>>,
    },
    /// An assignment operator expression.
    AssignmentExpression {
        operator: AssignmentOperator,
        /// `type: Pattern | Expression`
        left: Box<Node<'a>>,
        /// `type: Expression`
        right: Box<Node<'a>>,
    },
    /// A logical operator expression.
    LogicalExpression {
        operator: LogicalOperator,
        /// `type: Expression`
        left: Box<Node<'a>>,
        /// `type: Expression`
        right: Box<Node<'a>>,
    },
    /// A member expression. If `computed` is `true`, the node corresponds to a computed (`a[b]`) member expression and `property` is an `Expression`.
    /// If `computed` is `false`, the node corresponds to a static (`a.b`) member expression and `property` is an `Identifier`.
    MemberExpression {
        /// `type: Expression`
        object: Box<Node<'a>>,
        /// `type: Identifier | Literal`
        property: Box<Node<'a>>,
        computed: bool,
    },
    /*
    Expressions
    */
    /// A conditional expression, i.e., a ternary `?`/`:` expression.
    ConditionalExpression {
        /// `type: Expression`
        test: Box<Node<'a>>,
        /// `type: Expression`
        consequent: Box<Node<'a>>,
        /// `type: Expression`
        alternate: Box<Node<'a>>,
    },
    /// A function or method call expression.
    CallExpression {
        /// `type: Expression`
        callee: Box<Node<'a>>,
        /// `type: [ Expression ]`
        arguments: Vec<Node<'a>>,
    },
    /// A `new` expression.
    NewExpression {
        /// `type: Expression`
        callee: Box<Node<'a>>,
        /// `type: [ Expression ]`
        arguments: Vec<Node<'a>>,
    },
    /// A sequence expression, i.e., a comma-separated sequence of expressions.
    SequenceExpression {
        /// `type: [ Expression ]`
        expressions: Vec<Node<'a>>,
    },
    /*
    Patterns
    */
    Pattern,
    /*
    Misc.
    */
    /// An error node. Should be used when source is not syntaxically correct.
    Error,
}

impl<'a> NodeKind<'a> {
    /// Creates a `Node` from `NodeKind` with specified `pos`.
    pub fn with_pos(
        self,
        start: crate::parser::Span<'a>,
        end: crate::parser::Span<'a>,
    ) -> Node<'a> {
        Node {
            kind: self,
            start,
            end,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct Node<'a> {
    #[serde(flatten)]
    pub kind: NodeKind<'a>,
    #[serde(serialize_with = "serialize_span")]
    pub start: crate::parser::Span<'a>,
    #[serde(serialize_with = "serialize_span")]
    pub end: crate::parser::Span<'a>,
}

fn serialize_span<S>(pos: &crate::parser::Span, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
{
    serializer.serialize_u64(pos.location_offset() as u64)
}

impl<'a> Node<'a> {
    /// Returns the length of the AST node in source code.
    pub fn len(&self) -> usize {
        self.end.location_offset() - self.start.location_offset()
    }
}