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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
// Function/method parameter and destructuring-pattern parsing.
use crate::ast::*;
use crate::lexer::{KeywordKind, TokenKind};
use crate::parser::expression_assignable::AssignableContext;
use crate::parser::statement::DecoratorListKind;
use tsv_lang::{Error, Span};
use super::{Checkpoint, Parser};
impl<'a, 'arena> Parser<'a, 'arena> {
/// Parse a simple parameter: identifier with optional `?`, type annotation, and default value.
///
/// Accepts both regular identifiers and contextual keywords (`from`, `as`, etc.).
/// Does NOT handle parameter property modifiers (`public`, `private`, `readonly`).
fn parse_simple_param(&mut self) -> Result<Expression<'arena>, Error> {
let (param_start, param_end) = self.current_pos();
let name = self
.try_param_name()
.ok_or_else(|| self.error_expected("parameter name or destructuring pattern"))?;
self.advance()?;
// Check for optional marker: param? — a bare `?` extends the span.
let (optional, param_end) = self.eat_optional_marker(param_end)?;
// Check for type annotation: param: type
let (type_annotation, id_end) = if self.check(&TokenKind::Colon) {
let ta = self.parse_type_annotation()?;
let end = ta.span.end;
(Some(ta), end as usize)
} else {
(None, param_end)
};
// Build binding extra only when a type annotation is present (decorators,
// if any, are attached later by the parameter-list caller).
let extra = type_annotation.map(|ta| self.typed_extra(ta));
let mut param = Expression::from_identifier(Identifier {
escaped_name: name.escaped,
name_len: name.raw_len,
name_plain_ascii: name.plain_ascii,
optional,
extra,
span: Span::new(param_start as u32, id_end as u32),
});
// Check for default value: param = default
if self.eat(TokenKind::Equals)? {
let default_value = self.parse_assignment_expression_ref()?;
// prev_token_end covers a parenthesized default's closing `)`
let assign_end = self.prev_token_end() as u32;
param = Expression {
span: Span::new(param_start as u32, assign_end),
kind: ExpressionKind::AssignmentPattern(AssignmentPattern {
// `Bump::alloc`, always inlined, not `Parser::alloc`: an outlined call
// here grows this frame, which sits on the recursion path of every
// parameter default nested in another
left: self.arena.alloc(param),
right: default_value,
decorators: None,
}),
};
}
Ok(param)
}
/// Attach parameter decorators to a freshly-parsed parameter's **top-level
/// binding node**, matching acorn: a parameter's decorators live on the
/// `Identifier` / `AssignmentPattern` / `ObjectPattern` / `ArrayPattern` it
/// binds — reaching *inside* a `TSParameterProperty` onto its `.parameter`
/// (the property node's span still starts at the modifier). Notably the
/// default-value case (`@dec a = 1`) attaches to the `AssignmentPattern`, not
/// its `left`.
fn attach_param_decorators(
&self,
mut param: Expression<'arena>,
decorators: &'arena [Decorator<'arena>],
) -> Expression<'arena> {
let arena = self.arena;
match &mut param.kind {
// `@dec private a` — decorators ride the inner binding, not the
// property wrapper. Recurse (the inner is an Identifier or, for
// `@dec private a = 1`, an AssignmentPattern).
ExpressionKind::TSParameterProperty(pp) => {
let inner = self.attach_param_decorators((*pp.parameter).clone(), decorators);
pp.parameter = arena.alloc(inner);
param
}
ExpressionKind::Identifier(id) => {
let type_annotation = id.type_annotation().cloned();
id.extra = Some(arena.alloc(IdentifierParamExtra {
type_annotation,
decorators: Some(decorators),
}));
param
}
ExpressionKind::AssignmentPattern(ap) => {
ap.decorators = Some(decorators);
param
}
ExpressionKind::ObjectPattern(op) => {
op.decorators = Some(decorators);
param
}
ExpressionKind::ArrayPattern(arr) => {
arr.decorators = Some(decorators);
param
}
_ => param,
}
}
/// Parse a bare array/object binding pattern (no trailing `: Type`).
///
/// Current token must be `[` or `{`. The type annotation is left for the
/// caller: a destructured *parameter* / *declarator* binds the type on the
/// pattern (`parse_destructured_binding`), whereas a rest element binds it on
/// the enclosing `RestElement` (`...[a, b]: T`), matching acorn.
///
/// The pattern is read as an array/object literal and refined afterward, so the
/// grouping parens the literal parse discards are recorded while it runs
/// ([`Parser::record_grouping_parens`]): a binding pattern admits no parenthesized
/// target (`let [(a)] = x`), and the refinement cannot see a paren the internal AST
/// has dropped. The record is cut back to where this pattern found it once the
/// refinement has read it.
pub(super) fn parse_binding_pattern(&mut self) -> Result<Expression<'arena>, Error> {
let mark = self.grouping_parens.len();
let literal = self.with_context_flag(
|p| &mut p.record_grouping_parens,
true,
|p| {
Ok(if p.check(&TokenKind::BracketOpen) {
let (array, span) = p.parse_array_expression()?;
Expression {
span,
kind: ExpressionKind::ArrayExpression(array),
}
} else {
let (object, span) = p.nested(1, Self::parse_object_expression)?;
Expression {
span,
kind: ExpressionKind::ObjectExpression(object),
}
})
},
);
// Binding context: a type assertion, a member expression and a parenthesized
// target are none of them binding targets (`let [x as T] = …`, `let [a.b] = …`,
// `function f([(x)])` all reject, matching acorn).
let pattern =
literal.and_then(|expr| self.refine_assignable(expr, AssignableContext::Binding));
self.grouping_parens.truncate(mark);
pattern
}
/// Parse a destructuring binding (`[a, b]` / `{a, b}`) with an optional
/// type annotation attached to the resulting pattern.
///
/// Current token must be `[` or `{`. Shared by parameter lists and
/// variable declarators; default values are handled by the caller.
///
/// `allow_optional` permits a `?` after the pattern (`[a]?` / `{a}?`),
/// extending the span and preceding any type annotation. It is set only in
/// parameter positions: acorn accepts `[a]?` syntactically in every parameter
/// context and rejects it *semantically* outside ambient/type contexts ("A
/// binding pattern parameter cannot be optional in an implementation
/// signature") — tsv parses it everywhere, deferring that named-semantic
/// early-error (a sanctioned `canonical-fails-tsv-ok` divergence, like ambient
/// initializers). Declarator/for-loop callers pass `false`, so `const []? = x`
/// still rejects in both parsers.
pub(super) fn parse_destructured_binding(
&mut self,
allow_optional: bool,
) -> Result<Expression<'arena>, Error> {
let mut pattern = self.parse_binding_pattern()?;
// Optional marker `?` (parameter position only), between the pattern and
// any type annotation; extends the span to the `?` end (matching acorn).
if allow_optional && self.eat(TokenKind::Question)? {
let q_end = self.prev_token_end() as u32;
match &mut pattern.kind {
ExpressionKind::ArrayPattern(p) => {
p.optional = true;
pattern.span.end = q_end;
}
ExpressionKind::ObjectPattern(p) => {
p.optional = true;
pattern.span.end = q_end;
}
_ => {}
}
}
// Check for type annotation: [a, b]: Type or {a, b}: Type
if self.check(&TokenKind::Colon) {
let type_annotation = self.parse_type_annotation()?;
let end = type_annotation.span.end;
match &mut pattern.kind {
ExpressionKind::ArrayPattern(p) => {
p.type_annotation = Some(type_annotation);
pattern.span.end = end;
}
ExpressionKind::ObjectPattern(p) => {
p.type_annotation = Some(type_annotation);
pattern.span.end = end;
}
_ => {}
}
}
Ok(pattern)
}
/// Parse a rest parameter's trailing optional `?` and `: Type` (in that
/// order), after its binding argument — whose natural end is `arg_end` — has
/// been parsed. Both bind to the `RestElement`, never to the argument: the `?`
/// is invalid TypeScript (TS1047) but a deferred grammar-check tsv preserves
/// (see `RestElement`), and a rest param's annotation lives on the rest
/// element. Returns `(optional, type_annotation, end)`, `end` being the rest
/// element's end offset. Shared by the value-signature rest paths
/// (`parse_parameters`) and the function-type rest path (`types.rs`), so a new
/// rest-param position picks up the `?` handling by construction.
pub(in crate::parser) fn parse_rest_param_tail(
&mut self,
arg_end: u32,
) -> Result<(bool, Option<TSTypeAnnotation<'arena>>, u32), Error> {
let optional = self.eat(TokenKind::Question)?;
if self.check(&TokenKind::Colon) {
let ta = self.parse_type_annotation()?;
let end = ta.span.end;
Ok((optional, Some(ta), end))
} else if optional {
// The `?` is the last token consumed; it ends the rest element.
Ok((optional, None, self.prev_token_end() as u32))
} else {
Ok((optional, None, arg_end))
}
}
/// Consume the contextual keyword `kw` as a parameter-property modifier iff
/// the current token is the identifier `kw` and the next token begins a
/// parameter binding **on the same line** — otherwise `kw` is itself the
/// parameter name (`constructor(readonly)`, `f(override: T)`,
/// `f(private)`, `constructor(public readonly)`). The same-line requirement is
/// a `[no LineTerminator here]` rule mirroring tsc's `nextTokenCanFollowModifier`
/// (`nextTokenIsOnSameLineAndCanFollowModifier` → `!hasPrecedingLineBreak`) and
/// `class.rs`'s `eat_modifier_keyword` twin: a break between the modifier and
/// the binding demotes the keyword, so `constructor(readonly⏎x)` rejects (the
/// keyword becomes the binding, the next-line token is then unexpected). The
/// parameter-list analog of `eat_modifier_keyword` (which keys on a
/// class-member-name lookahead). Returns whether it was consumed.
///
/// **All five modifiers share this one rule**, accessibility included. The
/// accessibility keywords (`public`/`private`/`protected`) once skipped the
/// binding lookahead on the grounds that a strict-mode reserved word "cannot be
/// a parameter name" — but that bar is a deferred early error (the same
/// §sec-identifiers-static-semantics-early-errors bullet as `let` / `static` /
/// `package`), so `function f(private) {}` is a parameter *named* `private`,
/// which tsc parses and prettier formats. tsc draws the line with exactly this
/// lookahead (`canFollowModifier`), and only acorn rejects.
fn eat_param_modifier_keyword(&mut self, kw: &str) -> Result<bool, Error> {
if matches!(self.current_kind(), TokenKind::Identifier)
&& self.current_value() == kw
&& self.peek_starts_parameter_binding()
&& !self.peek_preceded_by_line_terminator()
{
self.advance()?; // consume the modifier keyword
Ok(true)
} else {
Ok(false)
}
}
/// Parse a parenthesized parameter list: `(a, b, c)`, **allowing** parameter
/// decorators (`@dec a`).
///
/// Used by function declarations/expressions, class methods and the
/// constructor, object-literal methods, and ambient `declare function`s —
/// every position acorn's `parseAssignableListItem` parses decorators in.
/// Consumes both opening and closing parentheses.
pub(super) fn parse_parameter_list(
&mut self,
) -> Result<bumpalo::collections::Vec<'arena, Expression<'arena>>, Error> {
self.parse_parameter_list_inner(true, 1)
}
/// Parse a parenthesized parameter list that **rejects** parameter decorators.
///
/// Used where acorn rejects a parameter decorator: arrow-function parameters (acorn
/// parses the `(…)` as a parenthesized expression first, where a leading `@` is a
/// class decorator — "Leading decorators must be attached to a class declaration")
/// and type-member signatures (interface / type-literal
/// method, call, construct, and accessor signatures — "Unexpected character
/// '@'"; those take [`Parser::parse_signature_parameter_list`]). tsc's parser
/// rejects only the non-generic arrow forms, an artifact of its arrow lookahead; it
/// accepts the generic arrows and the type-member signatures, raising "Decorators
/// are not valid here" (TS1206) from its checker. So the uniform rejection here does
/// not rest on tsc's parser, and the reject-vs-defer line (`docs/conformance_tsc.md`)
/// normally defers a checker-raised rule.
pub(super) fn parse_parameter_list_no_decorators(
&mut self,
) -> Result<bumpalo::collections::Vec<'arena, Expression<'arena>>, Error> {
self.parse_parameter_list_inner(false, 1)
}
/// [`Parser::parse_parameter_list_no_decorators`] for a type-member signature
/// (method, accessor, call and construct signatures), whose own wire level the
/// member's count already holds: the list's grouping level is the parameter's, so
/// the parameter is charged nothing beside it (the depth limit's count; an arrow's
/// grouping level is the arrow's own node instead). Whatever node the parameter is —
/// a name, a pattern, a rest element, or the default or parameter property
/// `check_signature_params` then rejects — it is that one level, and what nests below
/// it is charged where it is parsed: a pattern's own levels, a rest parameter's
/// pattern at the rest, a parameter property's binding inside the property.
pub(super) fn parse_signature_parameter_list(
&mut self,
) -> Result<bumpalo::collections::Vec<'arena, Expression<'arena>>, Error> {
self.parse_parameter_list_inner(false, 0)
}
/// Shared parameter-list body. `allow_decorators` gates whether a leading `@` on
/// a parameter is parsed as a decorator (`true`) or rejected (`false`), and
/// `parameter_levels` is what each parameter is charged beside the list's grouping
/// level (the depth limit's count, `Parser::nested`).
///
/// The list is a grouping delimiter ([`Parser::enter_grouping`]), so each
/// parameter default parses as a fresh expression frame, whatever encloses the
/// list. An arrow's list is where that shows, since no body frame encloses it:
/// - `in` is the operator even in a for header's `[~In]` region
/// (`(x = b in c) => {}`) — every default is an `Initializer[+In]` (ecma262
/// `SingleNameBinding` / `BindingElement`), and `ArrowParameters` takes no
/// `[In]` of its own;
/// - a conditional consequent's return-type bar stops at the `(`, so a default
/// may be an annotated arrow (`a ? (x = (y): T => z) => w : v`) — tsc's
/// `parseInitializer` passes `allowReturnTypeInArrowFunction` as `true`;
/// - `as` is an assertion even in a `{#each}` head (`{#each (x = y as A) => z as
/// item}`) — the host's separator cannot sit inside the list;
/// - a `<` region opened in a default ends at the `)`, which the printer always
/// prints ([`super::LtRegion`]).
fn parse_parameter_list_inner(
&mut self,
allow_decorators: bool,
parameter_levels: u32,
) -> Result<bumpalo::collections::Vec<'arena, Expression<'arena>>, Error> {
self.expect(&TokenKind::ParenOpen)?;
self.enter_grouping()?;
let mut params = self.bvec();
if !self.check(&TokenKind::ParenClose) {
// the parameters are siblings (`ListFrame`)
let mut frame = self.list_frame();
loop {
frame.element(self, params.len());
// one wire level: the parameter, over its decorators, its pattern, its
// annotation and its default (the depth limit's count) — none where the
// list's grouping level is the parameter's (`parameter_levels`)
let param = self.nested(parameter_levels, |p| {
p.parse_parameter(allow_decorators, parameter_levels)
})?;
let is_rest = matches!(param.kind, ExpressionKind::RestElement(_));
params.push(param);
// A rest parameter must be the last in the list. Per the grammar
// (`FormalParameters : FormalParameterList `,` FunctionRestParameter`)
// nothing — not even a trailing comma — may follow it. acorn:
// "Comma is not permitted after the rest element". Exception:
// in an ambient (`declare`) context acorn tolerates a single
// trailing comma (`declare function f(...a: T[], )`), consumed
// here; a following parameter or second comma still rejects
// via the `)` expectation below.
if is_rest {
if self.check(&TokenKind::Comma) {
if !self.in_ambient_context {
return Err(
self.error_msg("A rest parameter must be last in a parameter list")
);
}
self.advance()?;
}
break;
}
// Check for comma or closing paren
if !self.expect_list_separator(&TokenKind::Comma, &TokenKind::ParenClose)? {
break;
}
}
frame.close(self);
}
self.expect(&TokenKind::ParenClose)?;
self.exit_grouping();
Ok(params)
}
/// One parameter of a list ([`Parser::parse_parameter_list_inner`]): its decorators
/// (`allow_decorators`, else a `@` rejects), then the binding — an identifier, a
/// parameter property, a destructuring pattern or a rest element — with its marker,
/// annotation and default. `parameter_levels` is what the list charged the parameter
/// beside its grouping level: none in a signature list, where the grouping level is the
/// parameter's own, so a rest parameter's pattern is charged its own level here.
fn parse_parameter(
&mut self,
allow_decorators: bool,
parameter_levels: u32,
) -> Result<Expression<'arena>, Error> {
// Parameter decorators: `@dec1 @dec2 <param>`. Parsed up front so the
// parameter body below can be any binding form — a parameter property
// (`@dec private a`) or a destructuring pattern (`@dec { a }: T`), not
// just a bare identifier — and the decorators are attached afterwards.
//
// A parameter property's decorators sit on the binding inside it, one wire level
// deeper than a plain parameter's, and which one this is is known only past the
// run: a run read uncharged that turns out to be a property's is rewound and read
// again with the level charged (`Parser::decorated_parameter_properties`).
let decorators_start = self.current_pos().0 as u32;
let mut reread: Option<Checkpoint<'arena>> = None;
let decorators: &'arena [Decorator<'arena>] = if self.check(&TokenKind::At) {
// Reject decorators where the position forbids them (arrow
// parameters, type-member signatures). Checked per-parameter, so
// a mid-list decorator (`(a, @dec b)`) rejects too.
if !allow_decorators {
return Err(self.error_msg("Decorators are not valid here"));
}
// Uses the shared restricted ES decorators grammar
// (`parse_decorator_expression`), NOT a full assignment
// expression — so `@dec [a, b]` reads as a decorator on `dec`
// plus an array-pattern parameter, not the computed member
// `dec[a, b]` (matching acorn).
let decorators = if self
.decorated_parameter_properties
.binary_search(&decorators_start)
.is_ok()
{
// one wire level: the property's binding, the decorators' holder
self.nested(1, |p| p.parse_decorators(DecoratorListKind::Parameter))?
} else {
reread = Some(self.checkpoint());
self.parse_decorators(DecoratorListKind::Parameter)?
};
// Decorators are not valid on a rest parameter (acorn rejects `@d ...a`).
if self.check(&TokenKind::DotDotDot) {
return Err(self.error_msg("Decorators are not valid on a rest parameter"));
}
decorators.into_bump_slice()
} else {
&[]
};
// Parse parameter: identifier, parameter property, or destructuring pattern
let param = match self.current_kind() {
TokenKind::Identifier => {
let param_start = self.current_pos().0;
// Check for parameter property modifiers, in TS order:
// accessibility → override → readonly. Every one of the five is
// also a valid parameter NAME, so each is a modifier only when a
// binding follows it on the same line — one shared rule, see
// `eat_param_modifier_keyword`.
let accessibility = if self.eat_param_modifier_keyword("public")? {
Some(Accessibility::Public)
} else if self.eat_param_modifier_keyword("private")? {
Some(Accessibility::Private)
} else if self.eat_param_modifier_keyword("protected")? {
Some(Accessibility::Protected)
} else {
None
};
let is_override = self.eat_param_modifier_keyword("override")?;
let readonly = self.eat_param_modifier_keyword("readonly")?;
// If we have modifiers, this is a parameter property
if accessibility.is_some() || is_override || readonly {
if let Some(checkpoint) = reread {
// its decorators were read a level short: read them again, charged
if let Err(at) = self
.decorated_parameter_properties
.binary_search(&decorators_start)
{
self.decorated_parameter_properties
.insert(at, decorators_start);
}
self.rewind(checkpoint);
return self.parse_parameter(allow_decorators, parameter_levels);
}
// one wire level: the binding inside the `TSParameterProperty`
let parameter = self.nested(1, Self::parse_simple_param)?;
let param_end = parameter.span().end;
Expression {
span: Span::new(param_start as u32, param_end),
kind: ExpressionKind::TSParameterProperty(TSParameterProperty {
accessibility,
readonly,
r#override: is_override,
parameter: self.alloc(parameter),
}),
}
} else {
// Simple identifier parameter (no modifiers)
self.parse_simple_param()?
}
}
// Keywords that can be used as parameter names — the contextual
// keywords (`from`, `async`, the type keywords) plus `let`/`yield`,
// whose only bar is a deferred strict-mode early error. `await` is
// goal-dependent and gets its own arm below; `void` is a
// `ReservedWord` and stays out.
TokenKind::Keyword(kw) if kw.can_be_binding_name() => self.parse_simple_param()?,
// TypeScript `this` parameter: `function f(this: T) {}`
TokenKind::Keyword(KeywordKind::This) => self.parse_simple_param()?,
// `await` as a parameter name — a `BindingIdentifier`, so valid at
// Script goal whatever the `[Await]` context (`async function
// h(await) {}`); the `[Await]` bar is a deferred early error like
// the `[Yield]` twin, the goal bullet is enforced.
// `parse_simple_param` reads its name via `try_param_name`.
TokenKind::Keyword(KeywordKind::Await) if self.await_is_binding_name() => {
self.parse_simple_param()?
}
TokenKind::BracketOpen | TokenKind::BraceOpen => {
// Destructuring pattern: [a, b] / {a, b}, with optional `?`
// marker, type annotation and default value
let pattern = self.parse_destructured_binding(true)?;
// Check for default value
if self.eat(TokenKind::Equals)? {
let pattern_start = pattern.span().start;
let default_value = self.parse_assignment_expression_ref()?;
// prev_token_end covers a parenthesized default's closing `)`
let assign_end = self.prev_token_end() as u32;
Expression {
span: Span::new(pattern_start, assign_end),
kind: ExpressionKind::AssignmentPattern(AssignmentPattern {
left: self.alloc(pattern),
right: default_value,
decorators: None,
}),
}
} else {
pattern
}
}
TokenKind::DotDotDot => {
// Rest parameter: ...args, ...args: type, or a
// destructuring pattern (...[a, b] / ...{ a }). Per
// `BindingRestElement : ... BindingPattern`, the rest
// argument may itself be an array/object pattern.
let rest_start = self.current_pos().0;
self.advance()?; // consume '...'
if matches!(
self.current_kind(),
TokenKind::BracketOpen | TokenKind::BraceOpen
) {
// ...[a, b] / ...{ a } — the rest argument is itself a
// binding pattern. A trailing `: Type` annotates the
// *rest element* (`...[a, b]: T`), not the inner pattern,
// so parse the bare pattern and bind the type here
// (matching acorn; `parse_destructured_binding` would
// wrongly attach it to the pattern).
// one wire level: the pattern under the `RestElement` (the depth
// limit's count) — owed where the list charges the parameter nothing
// (`parse_signature_parameter_list`); a value list's grouping level
// has no wire node of its own, so there the parameter's level and the
// grouping level already hold the `RestElement` and its pattern
let pattern_levels = u32::from(parameter_levels == 0);
let pattern = self.nested(pattern_levels, Self::parse_binding_pattern)?;
// A trailing `?`/`: T` binds to the rest element (acorn's
// shape), never to the inner pattern.
let (optional, type_annotation, arg_end) =
self.parse_rest_param_tail(pattern.span().end)?;
Expression::from_rest_element(RestElement {
argument: self.alloc(pattern),
optional,
type_annotation,
span: Span::new(rest_start as u32, arg_end),
})
} else {
// ...args, ...args?, ...args: type, or ...args?: type.
// The argument span stays name-only (`id_start..id_end`);
// any `?`/`: T` binds to the rest element (acorn's shape).
// The name is a `BindingIdentifier` — the same channel the
// non-rest parameters take, so a contextual type keyword is
// legal (`function fn(...string: any[]) {}`). The FUNCTION-TYPE
// rest path already went through it.
let (id_start, id_end) = self.current_pos();
let Some(name) = self.try_binding_name() else {
return Err(self.error_expected("parameter name"));
};
self.advance()?;
let argument = Expression::from_identifier(Identifier::simple(
name,
Span::new(id_start as u32, id_end as u32),
));
let (optional, type_annotation, arg_end) =
self.parse_rest_param_tail(id_end as u32)?;
Expression::from_rest_element(RestElement {
argument: self.alloc(argument),
optional,
type_annotation,
span: Span::new(rest_start as u32, arg_end),
})
}
}
_ => {
return Err(self.error_expected_found("parameter name or destructuring pattern"));
}
};
// Attach any parameter decorators to the binding node (matching acorn).
Ok(if decorators.is_empty() {
param
} else {
self.attach_param_decorators(param, decorators)
})
}
/// Enforce accessor parameter arity: a getter takes no parameters and a
/// setter takes exactly one non-rest parameter. A faithful port of acorn's
/// getter/setter param checks (JS grammar, mode-independent) — arities are
/// productions (ecma262 §sec-method-definitions), so they reject under the
/// reject-vs-defer line (and acorn rejects too).
///
/// `allow_this_param` mirrors acorn's per-context `this`-parameter handling:
/// an object-literal accessor excludes a leading `this` pseudo-parameter
/// (`this: T`) from the count — `get x(this)` / `set x(this, v)` are valid —
/// whereas a class-member accessor counts it (acorn's class path has no such
/// exclusion), and a type-member accessor likewise counts it (so `this`
/// pushes a getter to 1 / a setter to 2 and rejects on count).
///
/// NOT enforced here: the TS-checker-only rules on the single setter
/// parameter (optional `set x(a?)` = TS1051, default `set x(a = 1)` =
/// TS1052), which acorn accepts in value positions and tsv defers to the
/// diagnostics layer — an optional/default param is an `Identifier` /
/// `AssignmentPattern`, not a `RestElement`, so it passes unchanged. (A
/// *type-member* setter's optional-param rejection, which acorn does enforce
/// at parse, lives in `check_type_member_accessor_params`.) Shared by the
/// class-member, object-literal, and type-member accessor parsers.
pub(super) fn check_accessor_param_arity(
&self,
is_getter: bool,
params: &[Expression<'arena>],
allow_this_param: bool,
) -> Result<(), Error> {
let mut expected = if is_getter { 0 } else { 1 };
if allow_this_param && params.first().is_some_and(|p| self.is_this_param(p)) {
expected += 1;
}
if params.len() != expected {
return Err(self.error_msg(if is_getter {
"getter should have no params"
} else {
"setter should have exactly one param"
}));
}
if !is_getter
&& matches!(
params.first(),
Some(Expression {
kind: ExpressionKind::RestElement(_),
..
})
)
{
return Err(self.error_msg("Setter cannot use rest params"));
}
Ok(())
}
/// Validate a **type-member accessor** signature's parameters — the
/// type-member-specific composite over `check_accessor_param_arity`, matching
/// the get/set checks in acorn's `tsParsePropertyOrMethodSignature`. Beyond
/// the shared arity rule (getter: no params; setter: exactly one non-rest
/// param; a `this` param counts toward arity here, `allow_this_param = false`),
/// a type-member **setter** also rejects — at parse, unlike a value-position
/// setter — a `this` parameter (`AccesorCannotDeclareThisParameter`; the getter
/// form is already caught by the 0-param arity check) and an optional parameter
/// (`SetAccesorCannotHaveOptionalParameter`, TS1051, which tsv otherwise defers).
pub(super) fn check_type_member_accessor_params(
&self,
kind: MethodKind,
params: &[Expression<'arena>],
) -> Result<(), Error> {
let is_getter = matches!(kind, MethodKind::Get);
self.check_accessor_param_arity(is_getter, params, false)?;
if !is_getter {
if self.is_this_param(¶ms[0]) {
return Err(
self.error_msg("'get' and 'set' accessors cannot declare 'this' parameters")
);
}
if let ExpressionKind::Identifier(id) = ¶ms[0].kind
&& id.optional
{
return Err(self.error_msg("A 'set' accessor cannot have an optional parameter"));
}
}
Ok(())
}
/// Restrict a **type-member signature**'s parameters to plain bindings —
/// `Identifier` / `RestElement` / `ObjectPattern` / `ArrayPattern` — a
/// faithful port of acorn's `tsParseBindingListForSignature`. A signature has
/// no implementation, so a default (`AssignmentPattern`, `set a(v = 1)`) or a
/// parameter property (`TSParameterProperty`, `m(public v)`) is rejected for
/// drop-in parity with acorn — a known gap against the reject-vs-defer line
/// (tsc's checker raises TS2371/TS2369). Only type-member signatures (interface /
/// type-literal method, call, construct, accessor) call this — an *implementation*, an
/// *ambient* declaration (`declare function f(v = 1)`, TS1039 deferred), and an
/// *overload* keep their defaults (all acorn-accepts). Function *types* reject
/// defaults already via their own param parser (`parse_function_type_params`).
pub(super) fn check_signature_params(
&self,
params: &[Expression<'arena>],
) -> Result<(), Error> {
for param in params {
if !matches!(
param.kind,
ExpressionKind::Identifier(_)
| ExpressionKind::RestElement(_)
| ExpressionKind::ObjectPattern(_)
| ExpressionKind::ArrayPattern(_)
) {
return Err(self.error_msg(
"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern",
));
}
}
Ok(())
}
/// Whether a parameter is the TypeScript `this` pseudo-parameter (`this: T`)
/// — a bare `this` identifier binding, matching acorn's `isThisParam`. Never
/// escaped (it's the reserved word), so a raw source-slice compare on the
/// name sub-span suffices. The node span is in **host** coordinates
/// (`base_offset` added), so it shifts back before slicing `self.source` (the
/// local, possibly Svelte-embedded slice) — same discipline as
/// `resolve_cooked`; `.get` keeps a stray span from panicking.
pub(super) fn is_this_param(&self, param: &Expression<'arena>) -> bool {
let ExpressionKind::Identifier(id) = ¶m.kind else {
return false;
};
let name = id.name_span();
let start = (name.start as usize).saturating_sub(self.base_offset);
let end = (name.end as usize).saturating_sub(self.base_offset);
self.source.get(start..end) == Some("this")
}
}