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
// Object and array literal parsing (`{ ... }` and `[ ... ]`), plus the method
// body shared by object-literal method shorthand and getters/setters.
use crate::ast::*;
use crate::lexer::{KeywordKind, TokenKind};
use tsv_lang::{Error, Span};
use super::Parser;
use crate::printer::ParenContext;
impl<'a, 'arena> Parser<'a, 'arena> {
/// Parse object literal: `{ prop: value, ... }`
///
/// Supports all JS/TypeScript object literal features:
/// - Simple properties: `{ prop: value }`
/// - Shorthand properties: `{ prop }` (key equals value)
/// - Computed property names: `{ [expr]: value }`
/// - Method shorthand: `{ foo() {} }`, `{ async foo() {} }`
/// - Getter/setter: `{ get foo() {}, set foo(v) {} }`
/// - Spread properties: `{ ...obj }`
/// - String/number literal keys: `{ "key": value, 123: value }`
/// - Trailing commas: `{ a: 1, }`
/// - Empty objects: `{}`
///
/// Returns the node beside its span rather than a bare `Expression`, so the caller
/// wrapping it keeps no 72 B value in its frame (§The expression ladder's return
/// currency).
pub(super) fn parse_object_expression(
&mut self,
) -> Result<(ObjectExpression<'arena>, Span), Error> {
let arena = self.arena;
let (start, _) = self.current_pos();
self.expect(&TokenKind::BraceOpen)?; // consume '{'
self.enter_grouping()?;
let mut properties = self.bvec();
// Set when a trailing comma follows a final spread property (`{...a,}`):
// legal in a literal, rejected by `refine_assignable` in pattern context.
let mut spread_trailing_comma = false;
// Handle empty object: `{}`
if self.check(&TokenKind::BraceClose) {
let (_, end) = self.current_pos();
self.advance()?; // consume '}'
self.exit_grouping();
return Ok((
ObjectExpression {
properties: properties.into_bump_slice(),
spread_trailing_comma: false,
},
Span::new(start as u32, end as u32),
));
}
// Parse properties, siblings each (`ListFrame`)
let mut frame = self.list_frame();
loop {
frame.element(self, properties.len());
let prop_start = self.current_pos().0;
// Check for spread: { ...obj }
if self.eat(TokenKind::DotDotDot)? {
let operand_token = self.current_pos().0;
// Use assignment_expression because comma separates properties
let argument = self.parse_assignment_expression_ref()?;
// the pair the printer adds around the argument (`{...(a || b)}`), a level
// of the output's nesting
self.count_prefix_operand_pairs(
argument,
ParenContext::SpreadArgument,
operand_token,
None,
false,
)?;
// Use prev_token_end() to include the closing paren when the argument
// is parenthesized (`{...(a && b)}`), matching the array-spread and
// object-value paths (acorn includes the `)` in the SpreadElement span).
let prop_end = self.prev_token_end();
properties.push(ObjectProperty::SpreadElement(SpreadElement {
argument,
span: Span::new(prop_start as u32, prop_end as u32),
}));
// Check for comma or closing brace. A trailing comma right
// after this spread (`{...a,}`) is the rest-trailing-comma case:
// the separator is consumed before the `}`, so record it for
// `refine_assignable` (the discarded comma leaves no other trace).
let trailing_comma = self.check(&TokenKind::Comma);
if !self.expect_list_separator(&TokenKind::Comma, &TokenKind::BraceClose)? {
spread_trailing_comma = trailing_comma;
break;
}
continue;
}
// Check for async method: `async foo() {}` or `async *gen() {}`
// async is tokenized as a keyword, and is treated as method when followed by a
// property name or `*` on the same line. A line break makes `async` an ordinary
// shorthand property (ECMAScript `async [no LineTerminator here] MethodDefinition`);
// `{ async⏎m() {} }` is then a syntax error (a stray `m` with no separator), matching
// acorn/prettier — not a silently-accepted async method.
let is_async_method =
if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Async))
&& (self.peek_is_property_name() || self.peek_is(&TokenKind::Star))
&& !self.peek_preceded_by_line_terminator()
{
self.advance()?; // consume 'async'
true
} else {
false
};
// Check for generator method: `*gen() {}` or `async *gen() {}`
let is_generator = self.eat(TokenKind::Star)?;
// Check for getter/setter: `get x() {}` or `set x(v) {}`
// These are contextual keywords - only treated as get/set when followed by a property name
// Note: async getters/setters and generator getters/setters are not valid in JS
let accessor_kind = if !is_async_method
&& !is_generator
&& *self.current_kind() == TokenKind::Identifier
{
let is_get = self.current_value() == "get";
let is_set = self.current_value() == "set";
if (is_get || is_set) && self.peek_is_property_name() {
let kind = if is_get {
PropertyKind::Get
} else {
PropertyKind::Set
};
self.advance()?; // consume 'get' or 'set'
Some(kind)
} else {
None
}
} else {
None
};
// Parse property key
// Supports: identifiers, keywords (as identifiers), string literals, number literals, computed keys
// Track whether the key is ineligible as a bare shorthand / `= default`
// target: a shorthand property (and the `CoverInitializedName` `{ x = 1 }`
// form) is an `IdentifierReference`, so a string/number literal, a computed
// key, or a keyword that isn't a valid identifier reference all require the
// `PropertyName : AssignmentExpression` form (a `:` value) — ecma262
// §PropertyDefinition. acorn rejects the bare forms; tsc reports TS1005.
let (key, computed, shorthand_ineligible) = match self.current_kind() {
// Computed property: { [expr]: value } — a computed key is never a
// valid bare shorthand (`{ [e] }` requires `: value`).
TokenKind::BracketOpen => {
self.advance()?; // consume '['
(self.parse_computed_member_key()?, true, true)
}
// Both identifiers and keywords can be property keys: { foo: 1, object: 2, in: 3 }
TokenKind::Identifier => {
let (key_start, key_end) = self.current_pos();
let name = self.current_ident_name();
self.advance()?;
(
Expression::from_identifier(Identifier::simple(
name,
Span::new(key_start as u32, key_end as u32),
)),
false,
false,
)
}
TokenKind::Keyword(kw) => {
let (key_start, key_end) = self.current_pos();
let name = self.current_raw_ident_name();
// A keyword is a valid bare shorthand only when it is a valid
// `IdentifierReference`. `await` is allowed at Script `[~Await]`;
// otherwise the reference set is
// `keyword_is_expression_identifier` — the contextual/type
// keywords (`async`, `string`, …) plus the strict-reserved
// `let`/`yield`, whose bar is an early error tsv defers, minus
// `yield` inside a generator, where it is the operator (real tsc
// splits the same way). This rejects the always-reserved keywords
// (`class`, `true`, `void`, …) as shorthand — while `{ public }`
// was already deferred: `public` lexes as an identifier, not a
// `KeywordKind`.
let restricted = match kw {
KeywordKind::Await => !self.await_is_identifier(),
_ => !self.keyword_is_expression_identifier(*kw),
};
self.advance()?;
(
Expression::from_identifier(Identifier::simple(
name,
Span::new(key_start as u32, key_end as u32),
)),
false,
restricted,
)
}
// Literal keys ({"prop-name": value}, {0: value}): a `LiteralPropertyName`,
// valid only with a `:` value — never a bare shorthand (`{ '' }`, `{ 0 }`).
TokenKind::String => {
// String literal key: {"prop-name": value}
(
Expression::from_literal(self.parse_string_literal()?),
false,
true,
)
}
TokenKind::Number => {
// Number literal key: {0: value, 0xb_b: value, 1n: value} —
// shares the full numeric decode (radix, separators, bigint)
let literal = self.parse_number_or_bigint_literal()?;
self.advance()?;
(Expression::from_literal(literal), false, true)
}
_ => {
return Err(self.error_expected_found_at("property key", prop_start));
}
};
// The key is the `Property`'s by-reference slot from here on: the node
// lives in the arena and the property holds a pointer to it, so the
// 160 B element the `properties` vector moves is 32 B instead (see
// `Property`'s field docs).
let key: &'arena Expression<'arena> = arena.alloc(key);
// Determine property kind, value, shorthand, and method flags
let (kind, value, shorthand, method) = if let Some(accessor) = accessor_kind {
// Getter/setter: `get x() {}` or `set x(v) {}`
// Note: getters/setters cannot be async
// one wire level: the method's `FunctionExpression` (the depth limit's count)
let func_expr = self.nested(1, |p| p.parse_method_body(false, false))?;
// Enforce accessor arity (getter: no params; setter: exactly one
// non-rest param) — acorn rejects a violation at parse, tsv matches
// (see `check_accessor_param_arity`). An object-literal accessor
// excludes a leading `this` param from the count (`allow_this_param`).
self.check_accessor_param_arity(
accessor == PropertyKind::Get,
func_expr.params,
true,
)?;
(
accessor,
&*arena.alloc(Expression::from_function_expression(arena.alloc(func_expr))),
false,
false,
)
} else if self.check(&TokenKind::ParenOpen)
|| self.check(&TokenKind::LessThan)
|| is_async_method
|| is_generator
{
// Method shorthand: `{ foo() {} }`, `{ foo<T>() {} }`, `{ async foo() {} }`, or `{ *gen() {} }`
// one wire level: the method's `FunctionExpression` (the depth limit's count)
let func_expr =
self.nested(1, |p| p.parse_method_body(is_async_method, is_generator))?;
(
PropertyKind::Init,
&*arena.alloc(Expression::from_function_expression(arena.alloc(func_expr))),
false,
true,
)
} else if self.eat(TokenKind::Colon)? {
// Use assignment_expression because comma separates properties
(
PropertyKind::Init,
self.parse_assignment_expression_ref()?,
false,
false,
)
} else {
// Not `key: value`, a method, or an accessor — so this property is a
// bare shorthand `{ key }` or the `{ key = default }` CoverInitializedName
// (a destructuring cover, deferred here and converted to an
// AssignmentPattern by refine_assignable() in pattern context). Both forms
// are an `IdentifierReference` (ecma262 §PropertyDefinition), so a
// string/number literal, computed key, or non-reference keyword — which
// needs the `PropertyName : AssignmentExpression` (`:` value) form — is
// rejected here (acorn rejects; tsc reports TS1005). This subsumes the
// computed case, so the `= default` split below needs no `!computed`.
if shorthand_ineligible {
return Err(self.error_msg_at(
"Object literal shorthand property must be an identifier reference",
key.span().start_usize(),
));
}
if self.eat(TokenKind::Equals)? {
// `{ a = 1 }`: parsed as an AssignmentExpression. One wire level: the
// `AssignmentPattern` the pattern context refines it to, over its
// default (the depth limit's count)
let default_value = self.nested(1, Self::parse_assignment_expression_ref)?;
// prev_token_end covers a parenthesized default's closing `)`
let assign_end = self.prev_token_end() as u32;
(
PropertyKind::Init,
&*arena.alloc(Expression {
span: Span::new(key.span().start, assign_end),
kind: ExpressionKind::AssignmentExpression(AssignmentExpression {
left: arena.alloc(key.clone()),
operator: AssignmentOperator::Assign,
right: default_value,
}),
}),
true,
false,
)
} else {
// Plain shorthand `{ key }`: key is duplicated as value — a
// distinct node, not the key's own pointer, so every consumer
// that keys a node on its address (`tsv_check`'s binder) still
// sees two.
(PropertyKind::Init, &*arena.alloc(key.clone()), true, false)
}
};
// Use prev_token_end() to include closing paren when value is parenthesized
let prop_end = self.prev_token_end();
properties.push(ObjectProperty::Property(Property {
key,
value,
kind,
shorthand,
computed,
method,
span: Span::new(prop_start as u32, prop_end as u32),
}));
// Check for comma or closing brace (with trailing comma support)
if !self.expect_list_separator(&TokenKind::Comma, &TokenKind::BraceClose)? {
break;
}
}
frame.close(self);
let (_, end) = self.current_pos();
self.expect(&TokenKind::BraceClose)?; // consume '}'
self.exit_grouping();
Ok((
ObjectExpression {
properties: properties.into_bump_slice(),
spread_trailing_comma,
},
Span::new(start as u32, end as u32),
))
}
/// Parse array literal: `[elem, ...]`
///
/// Supports all JS/TypeScript array literal features:
/// - All expression types as elements
/// - Spread elements: `[...arr]`
/// - Elision (holes/sparse arrays): `[, a]`, `[1,,3]`, `[, , a]`
/// - Trailing commas: `[1, 2, 3,]`
/// - Empty arrays: `[]`
///
/// Returns the node beside its span, as `parse_object_expression` does.
pub(super) fn parse_array_expression(
&mut self,
) -> Result<(ArrayExpression<'arena>, Span), Error> {
let (start, _) = self.current_pos();
self.expect(&TokenKind::BracketOpen)?; // consume '['
self.enter_grouping()?;
let mut elements = self.bvec();
// Set when a trailing comma follows a final spread element (`[...a,]`):
// legal in a literal, rejected by `refine_assignable` in pattern context.
let mut spread_trailing_comma = false;
// Handle empty array: `[]`
if self.check(&TokenKind::BracketClose) {
let (_, end) = self.current_pos();
self.advance()?; // consume ']'
self.exit_grouping();
return Ok((
ArrayExpression {
elements: elements.into_bump_slice(),
spread_trailing_comma: false,
},
Span::new(start as u32, end as u32),
));
}
// Parse elements (including elision/holes), siblings each (`ListFrame`)
let mut frame = self.list_frame();
loop {
frame.element(self, elements.len());
// Check for elision (hole): leading comma means empty slot
if self.eat(TokenKind::Comma)? {
elements.push(None); // hole
// Check if we hit the closing bracket (trailing comma after hole)
if self.check(&TokenKind::BracketClose) {
break;
}
continue;
}
// Check for closing bracket (end of array)
if self.check(&TokenKind::BracketClose) {
break;
}
// Parse element expression (assignment_expression because comma separates
// elements); a leading `...` is a SpreadElement (ecma262 ElementList).
let elem = self.parse_spread_or_assignment_element()?;
elements.push(Some(elem));
// Check for comma or closing bracket
if self.eat(TokenKind::Comma)? {
// Check for trailing comma
if self.check(&TokenKind::BracketClose) {
// A trailing comma after a final spread (`[...a,]`) is the
// rest-trailing-comma case; record it for `refine_assignable`
// (the discarded comma leaves no other trace).
if matches!(
elements.last(),
Some(Some(Expression {
kind: ExpressionKind::SpreadElement(_),
..
}))
) {
spread_trailing_comma = true;
}
break;
}
} else if self.check(&TokenKind::BracketClose) {
break;
} else {
return Err(self.error_list_separator(&TokenKind::Comma, &TokenKind::BracketClose));
}
}
frame.close(self);
let (_, end) = self.current_pos();
self.expect(&TokenKind::BracketClose)?; // consume ']'
self.exit_grouping();
Ok((
ArrayExpression {
elements: elements.into_bump_slice(),
spread_trailing_comma,
},
Span::new(start as u32, end as u32),
))
}
/// Parse method body for method shorthand: `foo() { return 1; }`
///
/// This parses the parameter list and block body for a method definition.
/// The key has already been parsed by the caller.
fn parse_method_body(
&mut self,
is_async: bool,
is_generator: bool,
) -> Result<FunctionExpression<'arena>, Error> {
// Parse optional type parameters: <T, U>
let type_parameters = self.parse_optional_type_parameters()?;
// Capture paren position before parsing params (for comment detection)
let (params_start, _) = self.current_pos();
// Params + body in the method's `[Await]`/`[Yield]` context (async → `[+Await]`,
// generator → `[+Yield]`).
let params = self
.with_fn_context(is_async, is_generator, Self::parse_parameter_list)?
.into_bump_slice();
// Check for return type annotation: (): type or type predicate
let return_type = self.parse_optional_return_type()?;
// A body written inside an open `<` region is still inside it, and the region is
// still open past the body's `}` (`fn(a < b, { m() {} }, c > d)`): the body's
// statements start from the open regions and hand them back
// (`Parser::with_lt_region_inherited`).
let body = self.with_fn_context(is_async, is_generator, |p| {
p.with_lt_region_inherited(Self::parse_function_body)
})?;
let end = body.span.end;
Ok(FunctionExpression {
id: None, // Method shorthand has no function name
type_parameters,
params,
return_type,
body,
generator: is_generator,
r#async: is_async,
params_start: params_start as u32,
span: Span::new(params_start as u32, end),
})
}
}