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
//! ECMAScript expressions.
use crate::class::Class;
use crate::function::{ArrowFunction, Function};
use crate::identifier::{Identifier, PrivateIdentifier};
use crate::literal::Literal;
use crate::operator::{
AssignmentOperator, BinaryOperator, LogicalOperator, UnaryOperator, UpdateOperator,
};
use crate::span::Spanned;
/// An expression paired with its source span.
pub type Expression = Spanned<ExpressionKind>;
/// The shape of an ECMAScript expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExpressionKind {
/// The `this` keyword.
This,
/// The `super` keyword (only valid in certain method bodies).
Super,
/// A variable reference.
Identifier(Identifier),
/// A private class-field identifier (`#foo`) used as a value.
PrivateIdentifier(PrivateIdentifier),
/// A static literal value.
Literal(Literal),
/// A template literal (`` `hello ${name}` ``). The number of `quasis`
/// must satisfy `quasis.len() == expressions.len() + 1`.
Template {
/// Literal text chunks in source order.
quasis: Vec<String>,
/// Interpolated expressions, each appearing between two quasis.
expressions: Vec<Expression>,
},
/// A tagged template (`` tag`hello ${name}` ``).
TaggedTemplate {
/// The tag function expression.
tag: Box<Expression>,
/// Literal text chunks.
quasis: Vec<String>,
/// Interpolated expressions.
expressions: Vec<Expression>,
},
/// An array expression. `None` entries represent holes
/// (`[1, , 3]`), and any element may be a [`ExpressionKind::Spread`].
Array {
/// Array elements; `None` for holes.
elements: Vec<Option<Expression>>,
},
/// An object expression.
Object {
/// Object members in source order.
properties: Vec<ObjectMember>,
},
/// Property access: `object.property` or `object[property]`, optionally
/// `?.`-qualified.
Member {
/// The object expression.
object: Box<Expression>,
/// The property selector.
property: MemberProperty,
/// True when the access used `?.` (optional chaining).
optional: bool,
},
/// Function application: `callee(args)`, optionally `?.()`-qualified.
Call {
/// The callee expression.
callee: Box<Expression>,
/// The argument list (each may be a spread).
arguments: Vec<Expression>,
/// True when the call used `?.()`.
optional: bool,
},
/// `new` invocation: `new callee(args)`.
New {
/// The constructor expression.
callee: Box<Expression>,
/// The argument list.
arguments: Vec<Expression>,
},
/// `++` or `--` applied to an argument, prefix or postfix.
Update {
/// `++` or `--`.
operator: UpdateOperator,
/// The target being updated.
argument: Box<Expression>,
/// True for `++x` / `--x`, false for `x++` / `x--`.
prefix: bool,
},
/// A unary prefix operator (`!x`, `-x`, `typeof x`, ...).
Unary {
/// The operator.
operator: UnaryOperator,
/// The operand.
argument: Box<Expression>,
},
/// A binary operator without short-circuit semantics.
Binary {
/// The operator.
operator: BinaryOperator,
/// The left operand.
left: Box<Expression>,
/// The right operand.
right: Box<Expression>,
},
/// A short-circuit logical operator (`&&`, `||`, `??`).
Logical {
/// The operator.
operator: LogicalOperator,
/// The left operand.
left: Box<Expression>,
/// The right operand (evaluated lazily).
right: Box<Expression>,
},
/// The ternary conditional (`test ? consequent : alternate`).
Conditional {
/// The test expression.
test: Box<Expression>,
/// The branch when `test` is truthy.
consequent: Box<Expression>,
/// The branch when `test` is falsy.
alternate: Box<Expression>,
},
/// An assignment expression (`x = v`, `x += v`, etc.).
Assignment {
/// The assignment operator (plain `=` or compound).
operator: AssignmentOperator,
/// The target (an expression that must be a valid assignment target;
/// patterns are validated structurally rather than at the type level).
left: Box<Expression>,
/// The right-hand value.
right: Box<Expression>,
},
/// A comma expression (`a, b, c`). Evaluates all in order and yields
/// the last value.
Sequence {
/// Sub-expressions in source order.
expressions: Vec<Expression>,
},
/// A spread element (`...expr`).
Spread {
/// The expression being spread.
argument: Box<Expression>,
},
/// An arrow function expression.
ArrowFunction(Box<ArrowFunction>),
/// A `function` expression (named or anonymous).
FunctionExpression(Box<Function>),
/// A `class` expression.
ClassExpression(Box<Class>),
/// `yield` or `yield*` in a generator.
Yield {
/// Optional argument; `yield;` with no value gives `None`.
argument: Option<Box<Expression>>,
/// True for `yield*`, false for plain `yield`.
delegate: bool,
},
/// `await expr` in an async function.
Await {
/// The promise-valued expression to await.
argument: Box<Expression>,
},
/// Optional-chaining wrapper (`(obj?.a.b)`). `ESTree` wraps the chain
/// root so consumers can detect optional-chain shortcircuiting cheaply.
Chain {
/// The optional-chain expression (a `Member` or `Call` with
/// `optional: true` at some point in its descent).
expression: Box<Expression>,
},
/// Dynamic `import(source, options?)`.
ImportExpression {
/// The module specifier expression.
source: Box<Expression>,
/// Optional second-argument options bag.
options: Option<Box<Expression>>,
},
/// A meta property: `new.target` or `import.meta`.
MetaProperty {
/// The meta keyword (`new` or `import`).
meta: Identifier,
/// The property name (`target` or `meta`).
property: Identifier,
},
/// A parenthesised expression. Some tools care about whether the user
/// wrote parens; for those, this variant preserves the distinction.
Parenthesized {
/// The inner expression.
expression: Box<Expression>,
},
}
/// How a member access selects its property.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemberProperty {
/// `object.name`.
Identifier(Identifier),
/// `object[expr]`.
Computed(Box<Expression>),
/// `object.#name`.
Private(PrivateIdentifier),
}
/// A property key as used in object literals, class members, and
/// destructuring patterns.
#[derive(Debug, Clone, PartialEq)]
pub enum PropertyKey {
/// A plain identifier key.
Identifier(Identifier),
/// A string-literal key.
String(String),
/// A numeric-literal key.
Number(f64),
/// A computed key written in brackets.
Computed(Box<Expression>),
/// A private class-field key (`#name`).
Private(PrivateIdentifier),
}
impl Eq for PropertyKey {}
impl std::fmt::Display for PropertyKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Identifier(name) => write!(f, "{name}"),
Self::String(s) => write!(f, "{s:?}"),
Self::Number(n) => write!(f, "{n}"),
Self::Computed(expr) => write!(f, "[{expr}]"),
Self::Private(p) => write!(f, "{p}"),
}
}
}
/// One member of an object literal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ObjectMember {
/// A named property or method.
Property {
/// The property key.
key: PropertyKey,
/// The property value (or method definition for shorthand methods).
value: Expression,
/// Whether the member is a getter, setter, ordinary method, or
/// plain data property.
kind: ObjectPropertyKind,
/// Whether the key was a computed expression (`[k]`).
computed: bool,
/// Whether the property used shorthand (`{ x }`).
shorthand: bool,
},
/// A spread member (`{ ...other }`).
Spread {
/// The expression being spread into the object.
argument: Expression,
},
}
/// Distinguishes the kinds of object-literal members.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObjectPropertyKind {
/// A plain data property (`{ x: 1 }`).
Init,
/// A getter (`{ get x() { ... } }`).
Get,
/// A setter (`{ set x(v) { ... } }`).
Set,
/// A shorthand method (`{ x() { ... } }`).
Method,
}
impl std::fmt::Display for ExpressionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::This => f.write_str("this"),
Self::Super => f.write_str("super"),
Self::Identifier(id) => write!(f, "{id}"),
Self::PrivateIdentifier(id) => write!(f, "{id}"),
Self::Literal(lit) => write!(f, "{lit}"),
Self::Template {
quasis,
expressions,
} => write_template(f, None, quasis, expressions),
Self::TaggedTemplate {
tag,
quasis,
expressions,
} => write_template(f, Some(tag), quasis, expressions),
Self::Array { elements } => write_array(f, elements),
Self::Object { properties } => write_object(f, properties),
Self::Member {
object,
property,
optional,
} => write_member(f, object, property, *optional),
Self::Call {
callee,
arguments,
optional,
} => write_call(f, callee, arguments, *optional),
Self::New { callee, arguments } => write_new(f, callee, arguments),
Self::Update {
operator,
argument,
prefix,
} => write_update(f, *operator, argument, *prefix),
Self::Unary { operator, argument } => write!(f, "({operator} {argument})"),
Self::Binary {
operator,
left,
right,
} => write!(f, "({left} {operator} {right})"),
Self::Logical {
operator,
left,
right,
} => write!(f, "({left} {operator} {right})"),
Self::Conditional {
test,
consequent,
alternate,
} => write!(f, "({test} ? {consequent} : {alternate})"),
Self::Assignment {
operator,
left,
right,
} => write!(f, "({left} {operator} {right})"),
Self::Sequence { expressions } => write_sequence(f, expressions),
Self::Spread { argument } => write!(f, "...{argument}"),
Self::ArrowFunction(arrow) => write!(f, "{arrow}"),
Self::FunctionExpression(func) => write!(f, "{func}"),
Self::ClassExpression(class) => write!(f, "{class}"),
Self::Yield { argument, delegate } => write_yield(f, argument.as_deref(), *delegate),
Self::Await { argument } => write!(f, "(await {argument})"),
Self::Chain { expression } => write!(f, "{expression}"),
Self::ImportExpression { source, options } => {
write_import_expression(f, source, options.as_deref())
}
Self::MetaProperty { meta, property } => write!(f, "{meta}.{property}"),
Self::Parenthesized { expression } => write!(f, "({expression})"),
}
}
}
fn write_template(
f: &mut std::fmt::Formatter<'_>,
tag: Option<&Expression>,
quasis: &[String],
expressions: &[Expression],
) -> std::fmt::Result {
if let Some(tag) = tag {
write!(f, "{tag}")?;
}
f.write_str("`")?;
let pieces: String = quasis
.iter()
.enumerate()
.map(|(i, quasi)| {
expressions
.get(i)
.map_or_else(|| quasi.clone(), |expr| format!("{quasi}${{{expr}}}"))
})
.collect();
f.write_str(&pieces)?;
f.write_str("`")
}
fn write_array(
f: &mut std::fmt::Formatter<'_>,
elements: &[Option<Expression>],
) -> std::fmt::Result {
let body = elements
.iter()
.map(|e| {
e.as_ref()
.map_or_else(String::new, |expr| format!("{expr}"))
})
.collect::<Vec<_>>()
.join(", ");
write!(f, "[{body}]")
}
fn write_object(f: &mut std::fmt::Formatter<'_>, properties: &[ObjectMember]) -> std::fmt::Result {
let body = properties
.iter()
.map(|m| format!("{m}"))
.collect::<Vec<_>>()
.join(", ");
write!(f, "{{{body}}}")
}
fn write_member(
f: &mut std::fmt::Formatter<'_>,
object: &Expression,
property: &MemberProperty,
optional: bool,
) -> std::fmt::Result {
let connector = if optional { "?." } else { "" };
match property {
MemberProperty::Identifier(name) => write!(f, "{object}{connector}.{name}"),
MemberProperty::Computed(expr) => write!(f, "{object}{connector}[{expr}]"),
MemberProperty::Private(p) => write!(f, "{object}{connector}.{p}"),
}
}
fn write_call(
f: &mut std::fmt::Formatter<'_>,
callee: &Expression,
arguments: &[Expression],
optional: bool,
) -> std::fmt::Result {
let args = arguments
.iter()
.map(|a| format!("{a}"))
.collect::<Vec<_>>()
.join(", ");
let connector = if optional { "?." } else { "" };
write!(f, "{callee}{connector}({args})")
}
fn write_new(
f: &mut std::fmt::Formatter<'_>,
callee: &Expression,
arguments: &[Expression],
) -> std::fmt::Result {
let args = arguments
.iter()
.map(|a| format!("{a}"))
.collect::<Vec<_>>()
.join(", ");
write!(f, "(new {callee}({args}))")
}
fn write_update(
f: &mut std::fmt::Formatter<'_>,
operator: UpdateOperator,
argument: &Expression,
prefix: bool,
) -> std::fmt::Result {
if prefix {
write!(f, "({operator}{argument})")
} else {
write!(f, "({argument}{operator})")
}
}
fn write_sequence(f: &mut std::fmt::Formatter<'_>, expressions: &[Expression]) -> std::fmt::Result {
let body = expressions
.iter()
.map(|e| format!("{e}"))
.collect::<Vec<_>>()
.join(", ");
write!(f, "({body})")
}
fn write_yield(
f: &mut std::fmt::Formatter<'_>,
argument: Option<&Expression>,
delegate: bool,
) -> std::fmt::Result {
let star = if delegate { "*" } else { "" };
match argument {
Some(arg) => write!(f, "(yield{star} {arg})"),
None => write!(f, "(yield{star})"),
}
}
fn write_import_expression(
f: &mut std::fmt::Formatter<'_>,
source: &Expression,
options: Option<&Expression>,
) -> std::fmt::Result {
match options {
Some(opts) => write!(f, "import({source}, {opts})"),
None => write!(f, "import({source})"),
}
}
impl std::fmt::Display for ObjectMember {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Property {
key,
value,
kind,
computed,
shorthand,
} => write_object_member_property(f, key, value, *kind, *computed, *shorthand),
Self::Spread { argument } => write!(f, "...{argument}"),
}
}
}
fn write_object_member_property(
f: &mut std::fmt::Formatter<'_>,
key: &PropertyKey,
value: &Expression,
kind: ObjectPropertyKind,
computed: bool,
shorthand: bool,
) -> std::fmt::Result {
let key_repr = if computed {
format!("[{key}]")
} else {
format!("{key}")
};
match kind {
ObjectPropertyKind::Init if shorthand => write!(f, "{key_repr}"),
ObjectPropertyKind::Init => write!(f, "{key_repr}: {value}"),
ObjectPropertyKind::Get => write!(f, "get {key_repr}() {{ ... }}"),
ObjectPropertyKind::Set => write!(f, "set {key_repr}(v) {{ ... }}"),
ObjectPropertyKind::Method => write!(f, "{key_repr}() {{ ... }}"),
}
}