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
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::ops::{Index, IndexMut};

#[cfg(feature = "serialize")]
use serde::Serialize;

use crate::error::{SyntaxError, SyntaxErrorType};
use crate::num::JsNumber;
use crate::operator::OperatorName;
use crate::source::SourceRange;
use crate::symbol::ScopeId;

pub struct NodeData {
    loc: SourceRange,
    stx: Syntax,
    // For the purposes of disambiguation, the scope of a function or block is only set on its children and not itself. This is merely an arbitrary decision. For example, the scope created by a function is assigned to its signature nodes (and descendants e.g. default values), but not to the FunctionStmt itself. For a `for` loop, the scope created by it is assigned to its header nodes and descendants, but not to the ForStmt itself. For a block statement, the scope created by it is assigned to statements inside it, but not to the BlockStmt itself.
    scope: ScopeId,
}

impl NodeData {
    pub fn new(scope: ScopeId, loc: SourceRange, stx: Syntax) -> NodeData {
        NodeData {
            loc,
            stx,
            scope: scope.clone(),
        }
    }

    pub fn error(&self, typ: SyntaxErrorType) -> SyntaxError {
        SyntaxError::from_loc(self.loc(), typ, None)
    }

    pub fn loc(&self) -> &SourceRange {
        &self.loc
    }

    pub fn stx(&self) -> &Syntax {
        &self.stx
    }

    pub fn stx_mut(&mut self) -> &mut Syntax {
        &mut self.stx
    }

    pub fn stx_take(self) -> Syntax {
        self.stx
    }

    pub fn scope(&self) -> ScopeId {
        self.scope
    }
}

impl Debug for NodeData {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("{:?}", self.stx))
    }
}

// To prevent ambiguity and confusion, don't derive Eq, as two nodes could be structurally equal even if they are different nodes.
#[derive(Debug, Clone, Copy)]
pub struct NodeId(usize);

impl NodeId {
    pub fn new(id: usize) -> NodeId {
        NodeId(id)
    }

    pub fn id(&self) -> usize {
        self.0
    }
}

pub struct NodeMap {
    nodes: Vec<NodeData>,
}

impl NodeMap {
    pub fn new() -> NodeMap {
        NodeMap { nodes: Vec::new() }
    }

    pub fn create_node(&mut self, scope: ScopeId, loc: SourceRange, stx: Syntax) -> NodeId {
        let id = self.nodes.len();
        self.nodes.push(NodeData::new(scope, loc, stx));
        NodeId::new(id)
    }

    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    pub fn push(&mut self, n: NodeData) -> () {
        self.nodes.push(n);
    }
}

impl Index<NodeId> for NodeMap {
    type Output = NodeData;

    fn index(&self, index: NodeId) -> &Self::Output {
        &self.nodes[index.0]
    }
}

impl IndexMut<NodeId> for NodeMap {
    fn index_mut(&mut self, index: NodeId) -> &mut Self::Output {
        &mut self.nodes[index.0]
    }
}

// These are for readability only, and do not increase type safety or define different structures.
type Declaration = NodeId;
type Expression = NodeId;
type Pattern = NodeId;
type Statement = NodeId;

#[derive(Eq, PartialEq, Debug, Clone, Copy)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
pub enum VarDeclMode {
    Const,
    Let,
    Var,
}

#[derive(Debug, Clone)]
pub enum ArrayElement {
    Single(Expression),
    Rest(Expression),
    Empty,
}

#[derive(Clone, Debug)]
pub enum ClassOrObjectMemberKey {
    // Identifier, keyword, string, or number.
    Direct(SourceRange),
    Computed(Expression),
}

#[derive(Debug, Clone)]
pub enum ClassOrObjectMemberValue {
    Getter {
        body: Statement,
    },
    Method {
        is_async: bool,
        generator: bool,
        signature: NodeId,
        body: Statement,
    },
    Property {
        // Must be Some if object, as shorthands are covered by ObjectMemberType::Shorthand (and are initialised).
        initializer: Option<Expression>,
    },
    Setter {
        body: Statement,
        parameter: Pattern,
    },
}

#[derive(Debug, Clone)]
pub struct ClassMember {
    pub key: ClassOrObjectMemberKey,
    pub statik: bool,
    pub value: ClassOrObjectMemberValue,
}

#[derive(Debug, Clone)]
pub enum ObjectMemberType {
    Valued {
        key: ClassOrObjectMemberKey,
        value: ClassOrObjectMemberValue,
    },
    Shorthand {
        name: SourceRange,
    },
    Rest {
        value: Expression,
    },
}

#[derive(Debug, Clone)]
pub struct ArrayPatternElement {
    pub target: Pattern,
    pub default_value: Option<Expression>,
}

#[derive(Debug, Clone)]
pub struct ExportName {
    // For simplicity, we always set both fields; for shorthands, both nodes are identical.
    pub target: SourceRange,
    // IdentifierPattern.
    pub alias: Pattern,
}

#[derive(Debug, Clone)]
pub enum ExportNames {
    // `import * as name`
    // `export * from "module"`
    // `export * as name from "module"`
    // IdentifierPattern.
    All(Option<Pattern>),
    // `import {a as b, c, default as e}`
    // `export {a as default, b as c, d}`
    // `export {default, a as b, c} from "module"`
    // `default` is still a name, so we don't use an enum.
    Specific(Vec<ExportName>),
}

#[derive(Debug, Clone)]
pub struct VariableDeclarator {
    pub pattern: Pattern,
    pub initializer: Option<Expression>,
}

#[derive(Debug, Clone)]
pub enum ForThreeInit {
    None,
    Expression(Expression),
    Declaration(Declaration),
}

#[derive(Debug, Clone)]
pub enum ForInOfStmtHeaderLhs {
    Declaration(Declaration),
    Pattern(Pattern),
}

#[derive(Debug, Clone)]
pub enum ForStmtHeader {
    Three {
        init: ForThreeInit,
        condition: Option<Expression>,
        post: Option<Expression>,
    },
    InOf {
        of: bool,
        lhs: ForInOfStmtHeaderLhs,
        rhs: Expression,
    },
}

#[derive(Debug, Clone)]
pub enum LiteralTemplatePart {
    Substitution(Expression),
    String(SourceRange),
}

// We no longer derive Eq for the AST due to use of NodeId, as it's not possible to determine structural equality without the node map. Anything that contains a NodeId/Syntax must also avoid Eq.
// WARNING: .clone() is derived and available for shallow copies only. As nodes use NodeId refs to other nodes, it's impossible to actually deep clone from the .clone() method. Use it to quickly copy and make a few changes, while keeping most field values the same (including references to other existing nodes).
#[derive(Debug, Clone)]
pub enum Syntax {
    // Patterns.
    IdentifierPattern {
        name: SourceRange,
    },
    // `const fn = (a: any, b: any, ...{ length, ...c }: any[]) => void 0` is allowed.
    ArrayPattern {
        // Unnamed elements can exist.
        elements: Vec<Option<ArrayPatternElement>>,
        rest: Option<Pattern>,
    },
    // For an object pattern, `...` must be followed by an identifier.
    // `const fn = ({ a: { b = c } = d, ...e }: any) => void 0` is possible.
    ObjectPattern {
        // List of ObjectPatternProperty nodes.
        properties: Vec<NodeId>,
        // This must be IdentifierPattern, anything else is illegal.
        rest: Option<Pattern>,
    },
    // Not really a pattern but functions similarly; separated out for easy replacement when minifying.
    ClassOrFunctionName {
        name: SourceRange,
    },

    // Signatures.
    FunctionSignature {
        parameters: Vec<Declaration>,
    },

    // Declarations.
    ClassDecl {
        name: Option<NodeId>, // Name can only be omitted in a default export.
        extends: Option<Expression>,
        members: Vec<ClassMember>,
    },
    FunctionDecl {
        generator: bool,
        is_async: bool,
        name: Option<NodeId>, // Name can only be omitted in a default export.
        signature: NodeId,
        body: Statement,
    },
    ParamDecl {
        rest: bool,
        pattern: Pattern,
        default_value: Option<Expression>,
    },
    VarDecl {
        mode: VarDeclMode,
        declarators: Vec<VariableDeclarator>,
    },

    // Expressions.
    ArrowFunctionExpr {
        is_async: bool,
        signature: NodeId,
        body: NodeId,
    },
    BinaryExpr {
        parenthesised: bool,
        operator: OperatorName,
        left: Expression,
        right: Expression,
    },
    CallExpr {
        optional_chaining: bool,
        parenthesised: bool,
        callee: Expression,
        arguments: Vec<NodeId>,
    },
    ClassExpr {
        parenthesised: bool,
        name: Option<NodeId>,
        extends: Option<Expression>,
        members: Vec<ClassMember>,
    },
    ConditionalExpr {
        parenthesised: bool,
        test: Expression,
        consequent: Expression,
        alternate: Expression,
    },
    ComputedMemberExpr {
        optional_chaining: bool,
        object: Expression,
        member: Expression,
    },
    FunctionExpr {
        parenthesised: bool,
        is_async: bool,
        generator: bool,
        name: Option<NodeId>,
        signature: NodeId,
        body: Statement,
    },
    IdentifierExpr {
        name: SourceRange,
    },
    ImportExpr {
        module: Expression,
    },
    ImportMeta {},
    JsxAttribute {
        name: Expression,          // JsxName
        value: Option<Expression>, // JsxExpressionContainer or JsxText
    },
    JsxElement {
        name: Option<Expression>,    // JsxName or JsxMember; None if fragment
        attributes: Vec<Expression>, // JsxAttribute or JsxSpreadAttribute; always empty if fragment
        children: Vec<Expression>,   // JsxElement or JsxExpressionContainer or JsxText
    },
    JsxExpressionContainer {
        value: Expression,
    },
    JsxMember {
        // This is a separate property to indicate it's required and for easier pattern matching.
        base: SourceRange,
        path: Vec<SourceRange>,
    },
    JsxName {
        namespace: Option<SourceRange>,
        name: SourceRange,
    },
    JsxSpreadAttribute {
        value: Expression,
    },
    JsxText {
        value: SourceRange,
    },
    LiteralArrayExpr {
        elements: Vec<ArrayElement>,
    },
    LiteralBooleanExpr {
        value: bool,
    },
    LiteralNull {},
    LiteralNumberExpr {
        value: JsNumber,
    },
    LiteralObjectExpr {
        // List of ObjectMember nodes.
        members: Vec<NodeId>,
    },
    LiteralRegexExpr {},
    LiteralStringExpr {
        value: String,
    },
    LiteralTemplateExpr {
        parts: Vec<LiteralTemplatePart>,
    },
    LiteralUndefined {},
    // Dedicated special type to easily distinguish when analysing and minifying. Also done to avoid using IdentifierExpr as right, which is incorrect (not a variable usage).
    MemberExpr {
        parenthesised: bool,
        optional_chaining: bool,
        left: Expression,
        right: SourceRange,
    },
    SuperExpr {},
    ThisExpr {},
    UnaryExpr {
        parenthesised: bool,
        operator: OperatorName,
        argument: Expression,
    },
    UnaryPostfixExpr {
        parenthesised: bool,
        operator: OperatorName,
        argument: Expression,
    },

    // Statements.
    BlockStmt {
        body: Vec<Statement>,
    },
    BreakStmt {
        label: Option<SourceRange>,
    },
    ContinueStmt {
        label: Option<SourceRange>,
    },
    DebuggerStmt {},
    DoWhileStmt {
        condition: Expression,
        body: Statement,
    },
    EmptyStmt {},
    ExportDeclStmt {
        declaration: Declaration,
        default: bool,
    },
    ExportDefaultExprStmt {
        expression: Expression,
    },
    ExportListStmt {
        names: ExportNames,
        from: Option<String>,
    },
    ExpressionStmt {
        expression: Expression,
    },
    IfStmt {
        test: Expression,
        consequent: Statement,
        alternate: Option<Statement>,
    },
    ImportStmt {
        // IdentifierPattern.
        default: Option<Pattern>,
        names: Option<ExportNames>,
        module: String,
    },
    ForStmt {
        header: ForStmtHeader,
        body: Statement,
    },
    LabelStmt {
        name: SourceRange,
        statement: Statement,
    },
    ReturnStmt {
        value: Option<Expression>,
    },
    SwitchStmt {
        test: Expression,
        branches: Vec<NodeId>,
    },
    ThrowStmt {
        value: Expression,
    },
    TryStmt {
        wrapped: Statement,
        // One of these must be present.
        catch: Option<NodeId>,
        finally: Option<Statement>,
    },
    VarStmt {
        declaration: Declaration,
    },
    WhileStmt {
        condition: Expression,
        body: Statement,
    },

    // Others.
    TopLevel {
        body: Vec<Statement>,
    },
    CallArg {
        spread: bool,
        value: Expression,
    },
    CatchBlock {
        parameter: Option<Pattern>,
        body: Statement,
    },
    // This is a node instead of an enum so that we can replace it when minifying e.g. expanding shorthand to `key: value`.
    ObjectMember {
        typ: ObjectMemberType,
    },
    ObjectPatternProperty {
        key: ClassOrObjectMemberKey,
        // Omitted if shorthand i.e. key is Direct and target is IdentifierPattern of same name.
        // TODO Ideally for simplicity this should be duplicated from `key` if shorthand, with a `shorthand` boolean field to indicate so.
        target: Option<Pattern>,
        default_value: Option<Expression>,
    },
    SwitchBranch {
        // If None, it's `default`.
        case: Option<Expression>,
        body: Vec<Statement>,
    },
}