js_parse/parser.rs
1//! The parser: tokens to [`crate::ast`].
2//!
3//! A recursive-descent parser with precedence climbing for expressions. It
4//! follows the specification's grammar productions closely, which keeps the
5//! early errors next to the code that can detect them.
6//!
7//! Two productions need backtracking / reinterpretation, exactly as in an
8//! engine:
9//!
10//! * **arrow functions** use the cover grammar. `(` starts either a
11//! parenthesized expression or a parameter list; the parser speculatively
12//! parses a parameter list and commits only if `=>` follows, otherwise it
13//! restores the lexer and parses an expression.
14//! * **`let`** at statement start is a declaration keyword when followed by a
15//! binding, otherwise an identifier.
16//!
17//! Automatic semicolon insertion is implemented where the grammar allows it
18//! (`Stmt` terminators, `do…while`, `return`/`throw` restricted productions,
19//! postfix `++`/`--`, `async` before arrow parameters, `yield`/`await`).
20//!
21//! Early errors implemented here (not at run time):
22//!
23//! * `with`, legacy octal literals/escapes, `delete identifier`,
24//! `eval`/`arguments` as binding or assignment target — strict mode only;
25//! * `super` outside a method, `super()` outside a derived constructor,
26//! `new.target` outside a function;
27//! * `await`/`yield` used as identifiers where they are reserved;
28//! * duplicate `__proto__` in an object literal, duplicate private names;
29//! * `break`/`continue` target validity, `return` outside a function;
30//! * `??` mixed with `&&`/`||` without parentheses, `-x ** y`, assignment to a
31//! non-assignable target, `new` on an optional chain;
32//! * duplicate parameter names (always for arrows/methods/non-simple lists).
33//!
34//! Not implemented yet (tracked for M1b.2): scope-analysis early errors such as
35//! `let x; let x;` in the same block, and parameter/`var` conflicts.
36
37use crate::ast::*;
38use crate::error::{Result, SyntaxError};
39use crate::lexer::Lexer;
40use crate::token::{Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, Token, TokenKind};
41use crate::wtf8::Wtf8;
42
43/// Everything that has to be saved to backtrack.
44struct Snapshot<'a> {
45 lexer: Lexer<'a>,
46 current: Token,
47 prev_end: Position,
48 strict: bool,
49 allow_in: bool,
50 ctx: FnCtx,
51 loop_depth: u32,
52 switch_depth: u32,
53 labels: Vec<Label>,
54 private: Vec<PrivateEnv>,
55 top_level: bool,
56 cover_inits: Vec<Span>,
57 /// Spans of array and object literals whose **last** element is a spread followed by
58 /// a trailing comma — `[...x,]`, `{...rest,}`.
59 ///
60 /// Both are valid *literals*, so the parser cannot reject them where they are written;
61 /// both are early errors once the literal turns out to be a destructuring pattern
62 /// (`[ AssignmentElementList , ]` has no room for a rest element, and
63 /// `{[AssignmentRestProperty]}` has none either). Recorded here and consulted by
64 /// `expr_to_pattern`, the same way `cover_inits` records `{a = 1}`.
65 spread_trailing_comma: Vec<Span>,
66 pending_exports: Vec<(String, Span)>,
67 current_legacy_octal: bool,
68 scopes: Vec<Scope>,
69}
70
71/// Context of the function currently being parsed.
72#[derive(Debug, Clone, Copy)]
73struct FnCtx {
74 in_function: bool,
75 in_generator: bool,
76 in_async: bool,
77 /// Inside a method (or a nested arrow in one): `super.x` is legal.
78 in_method: bool,
79 /// Inside a derived class constructor: `super()` is legal.
80 in_derived_constructor: bool,
81 /// Inside a class static block's own body. Two rules hang off it: `return` is an
82 /// early error, and `await` is a reserved word even though the block is not async.
83 ///
84 /// Deliberately *not* inherited by anything nested: a function declared in a static
85 /// block has its own `return`, and the reference stops looking for an enclosing async
86 /// function at the first frame that is not an arrow's parameter list — so `await` is
87 /// an ordinary name again one level in.
88 in_static_block: bool,
89 /// Whether the `arguments` identifier may be referenced here. False in a class field
90 /// initialiser and in a static block, and inherited by arrows, which have no
91 /// `arguments` of their own to offer.
92 arguments_allowed: bool,
93}
94
95impl Default for FnCtx {
96 fn default() -> FnCtx {
97 FnCtx {
98 in_function: false,
99 in_generator: false,
100 in_async: false,
101 in_method: false,
102 in_derived_constructor: false,
103 in_static_block: false,
104 // Outside a class body `arguments` is never the parser's business; the
105 // enclosing function decides what it means.
106 arguments_allowed: true,
107 }
108 }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112enum LabelKind {
113 /// Labels a loop.
114 Iteration,
115 /// Labels any other statement.
116 Other,
117}
118
119#[derive(Debug, Clone)]
120struct Label {
121 name: String,
122 kind: LabelKind,
123}
124
125/// Private names declared by the class currently being parsed.
126#[derive(Debug, Clone, Default)]
127struct PrivateEnv {
128 names: Vec<PrivateName>,
129 /// `#name` uses whose declaration has not been seen yet, with the use's span.
130 ///
131 /// Private names are visible throughout the class body, in **either order**:
132 /// `class D { f() { return this.#m() } #m() {} }` is legal (§15.10.2 validates
133 /// `AllPrivateIdentifiersValid` over the finished body). A one-pass parser cannot answer
134 /// at the use site, so an unresolved name is parked here and settled when the class body
135 /// closes.
136 pending: Vec<(String, Span)>,
137}
138
139#[derive(Debug, Clone)]
140struct PrivateName {
141 name: String,
142 has_get: bool,
143 has_set: bool,
144 /// Whether the first declaration of this name was an accessor.
145 ///
146 /// A field or a plain method may not be followed by anything: the pair is "one getter,
147 /// one setter and in no other entries", so `#m; get #m() {}` is a duplicate just as much
148 /// as `#m() {} #m() {}` is.
149 is_accessor: bool,
150 /// Whether the accessor half that exists is `static`.
151 ///
152 /// A getter and a setter of one name must agree on `static`; the reference rejects
153 /// `static get #x` with `set #x` (and the other three orders) with the same
154 /// "already defined" message it uses for any other duplicate.
155 accessor_is_static: bool,
156}
157
158impl PrivateEnv {
159 /// Register a private name. `get #x` + `set #x` with matching `static` is the only legal
160 /// pair; every other duplicate is an early error.
161 ///
162 /// `accessor` is `None` for a field or a plain method, which is why those can never be
163 /// followed by anything: the reference's `js_parse_class` reports
164 /// `private_field_already_defined` when the existing kind is a field or a method, and
165 /// when it is the same accessor half, and when the two halves disagree on `static`.
166 fn declare(&mut self, name: &str, accessor: Option<MethodKind>, is_static: bool) -> bool {
167 if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
168 return match accessor {
169 Some(MethodKind::Get)
170 if existing.is_accessor
171 && !existing.has_get
172 && existing.accessor_is_static == is_static =>
173 {
174 existing.has_get = true;
175 true
176 }
177 Some(MethodKind::Set)
178 if existing.is_accessor
179 && !existing.has_set
180 && existing.accessor_is_static == is_static =>
181 {
182 existing.has_set = true;
183 true
184 }
185 _ => false,
186 };
187 }
188 let mut entry = PrivateName {
189 name: name.to_string(),
190 has_get: false,
191 has_set: false,
192 is_accessor: accessor.is_some(),
193 accessor_is_static: is_static,
194 };
195 match accessor {
196 Some(MethodKind::Get) => entry.has_get = true,
197 Some(MethodKind::Set) => entry.has_set = true,
198 _ => {}
199 }
200 self.names.push(entry);
201 true
202 }
203
204 fn contains(&self, name: &str) -> bool {
205 self.names.iter().any(|n| n.name == name)
206 }
207
208 /// An environment built from names alone — for an `eval` that inherits them.
209 ///
210 /// Only [`PrivateEnv::contains`] is ever asked of this one. Whether a name is a field or
211 /// an accessor decides how it *compiles*, and that is the compiler's copy of the same
212 /// information; the parser's job is the early error, which needs nothing but the set.
213 ///
214 /// The names arrive as *bindings* (`#m`), because that is what the compiler stores; this
215 /// table is keyed on the identifier alone (`m`), because that is what `#m` parses to.
216 fn from_names(names: &[String]) -> PrivateEnv {
217 PrivateEnv {
218 names: names
219 .iter()
220 .map(|name| PrivateName {
221 name: name.strip_prefix('#').unwrap_or(name).to_string(),
222 has_get: true,
223 has_set: true,
224 is_accessor: true,
225 accessor_is_static: false,
226 })
227 .collect(),
228 pending: Vec::new(),
229 }
230 }
231}
232
233/// One lexical scope, used for the declaration-conflict early errors.
234/// Which of the reference's four "redefinition" messages a clash produces.
235///
236/// The reference picks between them in `js_parse_error_redecl` (`quickjs.c:25055` onward)
237/// from *where* the colliding binding lives, and the distinction is visible to a script
238/// author, so it is reproduced rather than collapsed into one message:
239///
240/// | colliding binding | message |
241/// |---|---|
242/// | lexical, same scope | `invalid redefinition of lexical identifier` |
243/// | `var` in the top-level scope | `invalid redefinition of global identifier` |
244/// | `var`/function inside a function | `invalid redefinition of a variable` |
245/// | a simple parameter of the same body | `invalid redefinition of parameter name` |
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247enum Redefinition {
248 Lexical,
249 Global,
250 Variable,
251 Parameter,
252}
253
254impl Redefinition {
255 fn message(self) -> &'static str {
256 match self {
257 Redefinition::Lexical => "invalid redefinition of lexical identifier",
258 Redefinition::Global => "invalid redefinition of global identifier",
259 Redefinition::Variable => "invalid redefinition of a variable",
260 Redefinition::Parameter => "invalid redefinition of parameter name",
261 }
262 }
263}
264
265#[derive(Debug, Clone)]
266struct Scope {
267 /// Whether this is a function/module scope (where `var` lands).
268 is_var_scope: bool,
269 /// `var`-declared names, including ones hoisted through this scope from a block.
270 var_names: Vec<String>,
271 /// `var`-declared names written *at this scope level*.
272 ///
273 /// `var_names` is the transitive set (`{ var a; }` puts `a` in the block *and* in the
274 /// enclosing function), which is what the lexical-conflict checks want. This one is
275 /// not transitive, because a module's function-declaration check compares scope *levels*:
276 /// a `var` written inside a block only clashes with a function in that same block, not
277 /// with one at the module's top level.
278 var_names_here: Vec<String>,
279 /// `let`/`const`/`class`/`import` names declared directly in this scope.
280 lex_names: Vec<String>,
281 /// Function-declaration names declared directly in this scope.
282 ///
283 /// Tracked apart from `var_names` because engines treat them differently:
284 /// two function declarations may share a name, a function at the top level
285 /// does not clash with an earlier `let`, and a function inside a block is
286 /// scoped to that block instead of hoisting.
287 fn_names: Vec<String>,
288 /// Names of *simple* (identifier) parameters, if this is a function body.
289 params: Vec<String>,
290 /// Names bound by a `catch` parameter, as a simple identifier.
291 ///
292 /// Kept apart from `params` because the two clash differently: a `let` colliding with a
293 /// function parameter is `invalid redefinition of parameter name`, while one colliding
294 /// with a catch binding is `invalid redefinition of lexical identifier`. Both are exempt
295 /// from the `var` check (`catch (e) { var e; }` is legal, and so is `function f(a){ var
296 /// a; }`), which is why `declare_var` looks at neither.
297 catch_names: Vec<String>,
298 /// Function-declaration names whose function is a *plain* one — not `async`, not a
299 /// generator.
300 ///
301 /// The sloppy-mode allowance for two function declarations in one block
302 /// (Annex B.3.3.4) covers only the plain kind: the reference requires
303 /// `var_def_type == JS_VAR_DEF_FUNCTION_DECL`, which an `async function` or a generator
304 /// does not use. So `{ function f(){} function f(){} }` is accepted in a sloppy script
305 /// while `{ function f(){} function* f(){} }` is not.
306 plain_fn_names: Vec<String>,
307 /// `import`-declared names.
308 ///
309 /// Recorded in `lex_names` as well, because an import *is* a lexical binding of the
310 /// module. Kept apart because a module-level function declaration conflicting with an
311 /// import is not an error in the reference — its `find_global_var` lookup does not see
312 /// imports — so the module-code check has to be able to tell the two apart.
313 import_names: Vec<String>,
314}
315
316impl Scope {
317 fn block() -> Scope {
318 Scope {
319 is_var_scope: false,
320 var_names: Vec::new(),
321 var_names_here: Vec::new(),
322 lex_names: Vec::new(),
323 fn_names: Vec::new(),
324 params: Vec::new(),
325 catch_names: Vec::new(),
326 plain_fn_names: Vec::new(),
327 import_names: Vec::new(),
328 }
329 }
330
331 fn function(params: Vec<String>) -> Scope {
332 Scope {
333 is_var_scope: true,
334 var_names: Vec::new(),
335 var_names_here: Vec::new(),
336 lex_names: Vec::new(),
337 fn_names: Vec::new(),
338 params,
339 catch_names: Vec::new(),
340 plain_fn_names: Vec::new(),
341 import_names: Vec::new(),
342 }
343 }
344}
345
346/// Which kind of target a pattern is being built for.
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348enum TargetKind {
349 /// `let x = 1`, `function f(x)`, `catch (x)` — binds new names.
350 Binding,
351 /// `x = 1`, `[a, b] = c` — assigns to existing bindings.
352 Assignment,
353}
354
355/// The arrow head produced by a successful speculative parse.
356struct ArrowHead {
357 params: Vec<Pattern>,
358 is_async: bool,
359 span: Span,
360 params_span: Span,
361}
362
363/// Default nesting limit.
364///
365/// QuickJS stops at roughly 700 nested parentheses, because it compares the real
366/// stack pointer against `--stack-size` (1 MiB by default). This port cannot do
367/// that portably, so it counts recursion depth instead; the depth a given stack
368/// can hold depends on the frame size, which differs a lot between build
369/// profiles (measured on an 8 MiB stack: ~220 levels in debug, ~1500 in release).
370/// The limit is therefore profile-dependent and deliberately leaves headroom, so
371/// that over-deep input produces a `SyntaxError: stack overflow` — exactly what
372/// QuickJS reports — instead of aborting the process.
373///
374/// [`Parser::set_max_depth`] raises it for callers that know they have a bigger
375/// stack (or a release build).
376pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
377
378/// ECMAScript 2025 parser.
379pub struct Parser<'a> {
380 lexer: Lexer<'a>,
381 current: Token,
382 prev_end: Position,
383 strict: bool,
384 module: bool,
385 allow_in: bool,
386 ctx: FnCtx,
387 loop_depth: u32,
388 switch_depth: u32,
389 labels: Vec<Label>,
390 private: Vec<PrivateEnv>,
391 top_level: bool,
392 /// Whether the token currently held by the parser contains an Annex B octal
393 /// literal or escape (checked again when strictness is switched on).
394 current_legacy_octal: bool,
395 /// Whether the statement list being parsed is a `case`/`default` clause body.
396 ///
397 /// `using` is allowed in a block, a `for` head, a function body or a class static
398 /// block, and nowhere else — in particular not *directly* in a clause's
399 /// `StatementList`, which is what this flag distinguishes from an ordinary block.
400 in_case_clause: bool,
401 /// Current recursion depth, and the limit that turns it into a
402 /// `SyntaxError` instead of a stack overflow.
403 depth: u32,
404 max_depth: u32,
405
406 /// Spans of `{a = 1}` object-literal shorthands. They are only legal when
407 /// the object is converted to a destructuring pattern, so any entry left
408 /// over at the end of a statement is a syntax error.
409 cover_inits: Vec<Span>,
410 /// The same idea for `[...x,]` / `{...rest,}`; see [`Parser::spread_trailing_comma`].
411 spread_trailing_comma: Vec<Span>,
412 /// `export {name}` clauses whose local binding still has to be checked
413 /// against the module's declared names (forward references are legal).
414 pending_exports: Vec<(String, Span)>,
415 /// Whether the tokens being consumed are a function's *formal parameters*.
416 ///
417 /// Two early errors hang off it, and both are invisible until a generator or async
418 /// function puts a `yield`/`await` there: `FormalParameters Contains YieldExpression`
419 /// is a `SyntaxError` for a generator (§15.5.1) and the same for `AwaitExpression` in
420 /// an async function (§15.8.1). The context flags `in_generator`/`in_async` are already
421 /// set by the time the parameter list is parsed — that is what makes `yield` a
422 /// reserved word there — so without this flag the expressions parse *successfully*
423 /// and `new GeneratorFunction("x = yield", "")` quietly built a function.
424 in_formal_parameters: bool,
425 /// Set once an arrow head has consumed its `=>`, so a later error is final.
426 ///
427 /// An arrow head is speculative: anything before `=>` may still turn out to be a
428 /// parenthesised expression, and the caller restores the position and tries that
429 /// instead. After `=>` there is nothing else it can be, so the error must not be
430 /// thrown away — the parameter checks run at that point and their message is the one a
431 /// reader needs (`eval => 1` in strict code said "expecting ';'" at the `=`).
432 arrow_head_committed: bool,
433 /// Open lexical scopes, innermost last.
434 scopes: Vec<Scope>,
435}
436
437/// Parse `src` as a `Script`.
438pub fn parse_script(src: &str) -> Result<Program> {
439 Parser::new(src, false)?.parse_program()
440}
441
442/// Parse `src` as a `Module`.
443pub fn parse_module(src: &str) -> Result<Program> {
444 Parser::new(src, true)?.parse_program()
445}
446
447/// Parse `src` as a `Script` whose top level is the body of an `async` function.
448///
449/// This is the reference's `JS_EVAL_FLAG_ASYNC`, which `std.evalScript` sets from
450/// `{async: true}`. The flag buys exactly one thing: top-level `await` becomes an
451/// operator, because the program's own function is an `async` one. It does *not* make the
452/// top level a function — `return` stays an error and `new.target` stays unavailable — so
453/// the compiled body still reports its completion value the way a script does, wrapped in
454/// `{value}` so that a promise is not adopted on the way out.
455pub fn parse_suspensible_script(src: &str) -> Result<Program> {
456 Parser::new_suspensible(src)?.parse_program()
457}
458
459/// Parse `src` as a `Script` whose code is strict from the first token.
460///
461/// This is what a *direct* `eval` needs: the eval'd code inherits strictness from the
462/// code that called it, so `eval("x = 1")` inside a strict function is a
463/// `ReferenceError` rather than an implicit global. Prepending a `"use strict"`
464/// directive instead would shift every column on the first line, and the positions are
465/// exactly what a stack trace has to report.
466pub fn parse_script_strict(src: &str) -> Result<Program> {
467 let mut parser = Parser::new(src, false)?;
468 parser.enter_strict()?;
469 parser.parse_program()
470}
471
472/// Parse `src` as a direct `eval` body, inheriting `new.target` from the caller.
473///
474/// `eval("new.target")` is legal inside a function because the eval'd code runs in the
475/// caller's function context, even though the source being parsed is a bare script with
476/// no function of its own. `strict` is the caller's mode, which a sloppy eval does not
477/// derive from its own text.
478pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
479 parse_eval_script_in(src, strict, EvalContext::default())
480}
481
482/// What the code that called a direct `eval` allows its body to use.
483#[derive(Debug, Clone, Default)]
484pub struct EvalContext {
485 /// The caller is a method (or a nested arrow in one), so `super.x` is legal — the
486 /// eval'd code runs with the caller's `[[HomeObject]]`.
487 pub in_method: bool,
488 /// The caller is a derived class constructor, so `super()` is legal too.
489 pub in_derived_constructor: bool,
490 /// The private names the calling code can see.
491 ///
492 /// Private names are **lexically scoped** (§15.10.2 `AllPrivateIdentifiersValid`), and a
493 /// direct `eval` runs inside the scope of its caller, so
494 /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal and answers `44`. The
495 /// source text alone cannot know that — the names come from the class surrounding the
496 /// *call site*, a different compilation unit — so the caller says which ones are live.
497 /// An indirect `eval` sees none of them, which is why this belongs to the direct-only
498 /// context rather than to the parser.
499 pub private_names: Vec<String>,
500 /// Whether `arguments` is a binding at the call site.
501 ///
502 /// A class field initializer and a static block have none (§15.7 puts them outside any
503 /// function's `arguments`), so `eval('arguments')` there is a `SyntaxError` rather than
504 /// the caller's arguments object.
505 pub arguments_allowed: bool,
506 /// Whether `new.target` is reachable from the call site.
507 ///
508 /// Legal in a direct `eval` inside any function (§15.8.1 makes it a *syntactic* form
509 /// whose target is the enclosing function's), and a `SyntaxError` in an indirect one:
510 /// there is no enclosing function to ask.
511 pub new_target_allowed: bool,
512}
513
514/// Parse `src` as a direct `eval` body with the caller's privileges.
515///
516/// An eval'd body is not a function of its own, but it runs *inside* one: `eval("super.f()")`
517/// is legal in a method, and `eval("new.target")` is legal in any function. The parser has
518/// to be told, because the source text alone has no way to know.
519pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
520 let mut parser = Parser::new(src, false)?;
521 // `in_function` is what makes `new.target` parse, so it *is* `new_target_allowed`: a
522 // direct eval inside a function inherits the form, an indirect one has no enclosing
523 // function and must reject it.
524 parser.ctx.in_function = context.new_target_allowed;
525 parser.ctx.in_method = context.in_method;
526 parser.ctx.in_derived_constructor = context.in_derived_constructor;
527 parser.ctx.arguments_allowed = context.arguments_allowed;
528 // Seeded as one environment *outside* any class the eval itself declares, so a class
529 // inside the eval body shadows an outer name of the same spelling — exactly what a
530 // nested class does in ordinary code.
531 if !context.private_names.is_empty() {
532 parser
533 .private
534 .push(PrivateEnv::from_names(&context.private_names));
535 }
536 if strict {
537 parser.enter_strict()?;
538 }
539 parser.parse_program()
540}
541
542/// Parse `src` as the suspensible (async) form of a *global* eval body.
543///
544/// Two differences from [`parse_eval_script_in`], both from the same place in the
545/// reference: a global eval is not a function body (`new_target_allowed`,
546/// `super_allowed` and `super_call_allowed` are all false), and `JS_EVAL_FLAG_ASYNC`
547/// makes the body `async`. So `new.target` and `super` stay out of reach while `await`
548/// does not.
549pub fn parse_suspensible_global_eval(src: &str, strict: bool) -> Result<Program> {
550 let mut parser = Parser::new_suspensible(src)?;
551 if strict {
552 parser.enter_strict()?;
553 }
554 parser.parse_program()
555}
556
557/// Parse `src` as a single `Expression` (used by tests and by `eval`-like entry
558/// points that need the expression grammar only).
559pub fn parse_expression(src: &str) -> Result<Expr> {
560 let mut parser = Parser::new(src, false)?;
561 let expr = parser.parse_expression(true)?;
562 if !parser.current.is_eof() {
563 return Err(parser.unexpected());
564 }
565 Ok(expr)
566}
567
568impl<'a> Parser<'a> {
569 /// Create a parser over `src`. A module is always strict.
570 ///
571 /// The program's own function is an `async` one for a module, so its top level may
572 /// `await`. That is set here rather than at each `await` site: [`Parser::ctx`]
573 /// describes the function currently being parsed, and the reference keys every
574 /// `await` rule off the same thing (`fd->func_kind & JS_FUNC_ASYNC`).
575 pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
576 Parser::with_modes(src, module, false)
577 }
578
579 /// Create a parser whose program *is* the body of an `async` function.
580 ///
581 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: a script compiled with it may use
582 /// top-level `await`, exactly as a module body may. It is not the same as being inside
583 /// a function — `return` is still an error, `new.target` is still unavailable — so
584 /// `in_function` stays false.
585 pub fn new_suspensible(src: &'a str) -> Result<Parser<'a>> {
586 Parser::with_modes(src, false, true)
587 }
588
589 fn with_modes(src: &'a str, module: bool, async_body: bool) -> Result<Parser<'a>> {
590 let mut lexer = Lexer::new(src);
591 lexer.set_strict(module);
592 let current = lexer.next_token()?;
593 let current_legacy_octal = lexer.had_legacy_octal();
594 if module && current_legacy_octal {
595 return Err(SyntaxError::new(
596 "octal literals and octal escape sequences are not allowed in strict mode",
597 current.span,
598 ));
599 }
600 Ok(Parser {
601 lexer,
602 current,
603 prev_end: Position::START,
604 strict: module,
605 module,
606 allow_in: true,
607 ctx: FnCtx {
608 in_async: module || async_body,
609 ..FnCtx::default()
610 },
611 loop_depth: 0,
612 switch_depth: 0,
613 labels: Vec::new(),
614 private: Vec::new(),
615 top_level: true,
616 current_legacy_octal,
617 in_case_clause: false,
618 depth: 0,
619 max_depth: DEFAULT_MAX_DEPTH,
620
621 cover_inits: Vec::new(),
622 spread_trailing_comma: Vec::new(),
623 pending_exports: Vec::new(),
624 in_formal_parameters: false,
625 arrow_head_committed: false,
626 scopes: vec![Scope::function(Vec::new())],
627 })
628 }
629
630 /// Raise or lower the nesting limit.
631 pub fn set_max_depth(&mut self, depth: u32) {
632 self.max_depth = depth;
633 }
634
635 /// Enter one level of recursion.
636 fn enter(&mut self) -> Result<()> {
637 self.depth += 1;
638 if self.depth > self.max_depth {
639 return Err(SyntaxError::new("stack overflow", self.current.span));
640 }
641 Ok(())
642 }
643
644 fn leave(&mut self) {
645 self.depth -= 1;
646 }
647
648 /// Parse the whole source.
649 pub fn parse_program(&mut self) -> Result<Program> {
650 let start = self.current.span.start;
651 let mut body = Vec::new();
652 let mut prologue = true;
653 while !self.current.is_eof() {
654 let stmt = self.parse_statement_list_item()?;
655 if prologue {
656 match self.directive_value(&stmt) {
657 Some(directive) if directive == "use strict" => self.enter_strict()?,
658 Some(_) => {}
659 None => prologue = false,
660 }
661 }
662 body.push(stmt);
663 }
664 if self.module {
665 self.check_module_exports(&body)?;
666 }
667 Ok(Program {
668 kind: if self.module {
669 ProgramKind::Module
670 } else {
671 ProgramKind::Script
672 },
673 body,
674 span: Span::new(start, self.prev_end),
675 strict: self.strict,
676 })
677 }
678
679 /// `export {a}` requires `a` to be declared somewhere in the module (forward
680 /// references are legal, so this can only run once the whole body is known).
681 fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
682 self.check_duplicate_exports(body)?;
683 if self.pending_exports.is_empty() {
684 return Ok(());
685 }
686 let mut declared: Vec<String> = Vec::new();
687 for stmt in body {
688 collect_module_binding(stmt, &mut declared);
689 }
690 let pending = std::mem::take(&mut self.pending_exports);
691 for (name, span) in pending {
692 if !declared.contains(&name) {
693 // The reference makes this check in `js_resolve_module`, after parsing, so
694 // it prints no position. See `SyntaxError::positionless`.
695 return Err(self
696 .error_at(format!("exported variable '{name}' does not exist"), span)
697 .positionless());
698 }
699 }
700 Ok(())
701 }
702
703 /// §16.2.3.1 step 5.c.i / 6.a: `ExportedNames` holds no duplicates.
704 ///
705 /// Every `export` clause contributes its exported names, and one name twice is a
706 /// `SyntaxError` however it is spelled — `export { x }; export { x }`,
707 /// `export { x as z }; export { y as z }`, `export default x; export { y as default }`.
708 /// The two clauses can be far apart, so this is a whole-body pass rather than a check
709 /// at each clause.
710 ///
711 /// **`export * from "m"` is the exception and it is not special-cased: it contributes
712 /// nothing here.** Its `ExportEntry` is `[[ModuleRequest]]: none`, so §16.2.1.1 starts
713 /// its `[[ExportName]]` as `null` and only `BoundNames` calls fill it in — a star
714 /// re-export is added to `ExportedNames` at *instantiation* from the resolved module,
715 /// and resolving a name that a star also provides is explicitly not a conflict
716 /// (`export { x } from "m"; export * from "m"` is legal). `export * as z` is a
717 /// different production and does contribute `z`.
718 fn check_duplicate_exports(&mut self, body: &[Stmt]) -> Result<()> {
719 // `(name, span)` per contributed name, in source order so the error blames the
720 // later clause — which is where the reference points too.
721 let mut seen: Vec<(String, Span)> = Vec::new();
722 for stmt in body {
723 let StmtKind::Export(decl) = &stmt.kind else {
724 continue;
725 };
726 match &decl.kind {
727 // No `UnicodeEscape` is allowed in a module export name, so a lone
728 // surrogate cannot be written here; `escape` is the right spelling for
729 // the rest and keeps the key comparable to the `export { x }` form.
730 ExportKind::Default(_) => seen.push(("default".to_string(), decl.span)),
731 ExportKind::Declaration(inner) => {
732 let mut names = Vec::new();
733 collect_module_binding(inner, &mut names);
734 for name in names {
735 seen.push((name, decl.span));
736 }
737 }
738 ExportKind::Named {
739 specifiers,
740 source: _,
741 attributes: _,
742 } => {
743 for specifier in specifiers {
744 seen.push((specifier.exported.as_str().to_string(), specifier.span));
745 }
746 }
747 ExportKind::All {
748 exported: Some(name),
749 ..
750 } => seen.push((name.as_str().to_string(), decl.span)),
751 // `export * from "m"` — contributes nothing, per the doc comment.
752 ExportKind::All { exported: None, .. } => {}
753 }
754 }
755 let mut reported: Vec<&str> = Vec::new();
756 for (index, (name, span)) in seen.iter().enumerate() {
757 if seen[..index].iter().any(|(earlier, _)| earlier == name) {
758 if reported.contains(&name.as_str()) {
759 continue;
760 }
761 reported.push(name);
762 return Err(self
763 .error_at(format!("duplicate export '{name}'"), *span)
764 .positionless());
765 }
766 }
767 Ok(())
768 }
769
770 // -- declaration tracking (early errors) -------------------------------
771
772 fn push_scope(&mut self, scope: Scope) {
773 self.scopes.push(scope);
774 }
775
776 fn pop_scope(&mut self) {
777 self.scopes.pop();
778 }
779
780 /// Declare a `let`/`const`/`class`/`import` name in the current scope.
781 ///
782 /// Conflicts are per scope: a lexical declaration clashes with another
783 /// lexical declaration, a `var`/function declaration or a simple parameter
784 /// *of the same scope*. `var a; { let a; }` is legal, `{ let a; { var a; } }`
785 /// is not (the `var` hoists past the `let`, which `declare_var` checks).
786 fn declare_lexical(&mut self, name: &str) -> Result<()> {
787 let Some(scope) = self.scopes.last() else {
788 return Ok(());
789 };
790 // Ordered so the most specific reason wins, matching the reference's check order:
791 // the parameter test comes before the var walk, and a lexical name before both.
792 let reason = if scope.lex_names.iter().any(|n| n == name)
793 || scope.catch_names.iter().any(|n| n == name)
794 {
795 Some(Redefinition::Lexical)
796 } else if scope.params.iter().any(|n| n == name) {
797 Some(Redefinition::Parameter)
798 } else if scope.fn_names.iter().any(|n| n == name)
799 || scope.var_names.iter().any(|n| n == name)
800 {
801 // A body-scope function declaration is recorded in both lists, and the
802 // message for either depends on whether the clash is at the global level:
803 // `function a(){} let a;` at the top of a script says "global identifier",
804 // the same two inside a function say "a variable".
805 Some(if self.at_top_level_scope() {
806 Redefinition::Global
807 } else {
808 Redefinition::Variable
809 })
810 } else {
811 None
812 };
813 if let Some(reason) = reason {
814 return Err(self.duplicate_declaration(reason));
815 }
816 if let Some(scope) = self.scopes.last_mut() {
817 scope.lex_names.push(name.to_string());
818 }
819 Ok(())
820 }
821
822 /// Declare a `var` or function-declaration name: it hoists to the nearest
823 /// function scope, but may not collide with a lexical name on the way up.
824 fn declare_var(&mut self, name: &str) -> Result<()> {
825 for scope in self.scopes.iter().rev() {
826 if scope.lex_names.iter().any(|n| n == name) {
827 return Err(self.duplicate_declaration(Redefinition::Lexical));
828 }
829 if scope.is_var_scope {
830 break;
831 }
832 }
833 let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
834 return Ok(());
835 };
836 // Record it in every scope it passes through: `{ var a; let a; }` is an
837 // early error because the block's VarDeclaredNames contain `a`.
838 for scope in &mut self.scopes[index..] {
839 if !scope.var_names.iter().any(|n| n == name) {
840 scope.var_names.push(name.to_string());
841 }
842 }
843 if let Some(scope) = self.scopes.last_mut()
844 && !scope.var_names_here.iter().any(|n| n == name)
845 {
846 scope.var_names_here.push(name.to_string());
847 }
848 Ok(())
849 }
850
851 /// Reject a parameter list that binds the same name twice.
852 ///
853 /// Two questions, answered separately and in the reference's order:
854 ///
855 /// * *Which* duplicate is reported. A name bound inside a destructuring pattern is
856 /// checked as soon as it is read (`js_parse_destructuring_var`), and so is a plain
857 /// name once the list is known to contain an `=`; a plain name in a list without one
858 /// waits for the end. So `function f([a], a, [a])` reports the *third* parameter, not
859 /// the second — the second is not checked yet when the third is.
860 /// * *Which message*. The early check says `duplicate parameter names`; the final one
861 /// says `duplicate argument names`, and carries no name.
862 /// * *Where it points*. Both checks use `s->token.ptr`, so the position follows from
863 /// when they run: the early one fires on the offending name itself, the final one
864 /// only once the body has been entered, so it points at the body's **first token**
865 /// (`}` for `function f([a], a, a){}`, `return` for `{ return 1 }`, the expression
866 /// for `(a, a) => x`). That is what `deferred_at` is.
867 ///
868 /// `plain_is_illegal` is the caller's answer to "are duplicates illegal here at all":
869 /// a sloppy `function f(a, a){}` accepts them (last wins), while a strict or
870 /// non-simple list, an arrow, or a method does not.
871 fn check_duplicate_parameters(
872 &self,
873 params: &[Pattern],
874 plain_is_illegal: bool,
875 deferred_at: Span,
876 ) -> Result<()> {
877 let has_default = params.iter().any(pattern_has_default);
878 let mut seen: Vec<String> = Vec::new();
879 let mut deferred = false;
880 for param in params {
881 for (name, span, in_pattern) in parameter_bindings(param) {
882 if seen.iter().any(|seen| seen == &name) {
883 if has_default || in_pattern {
884 return Err(self.error_at(
885 "duplicate parameter names not allowed in this context".to_string(),
886 span,
887 ));
888 }
889 deferred = true;
890 }
891 seen.push(name);
892 }
893 }
894 if deferred && plain_is_illegal {
895 return Err(self.error_at(
896 "duplicate argument names not allowed in this context".to_string(),
897 deferred_at,
898 ));
899 }
900 Ok(())
901 }
902
903 /// Declare a function declaration name in the scope that holds it.
904 ///
905 /// Split in two because the reference checks the two cases in different places, and
906 /// the reported position follows from where the check is: a block-level declaration is
907 /// checked at its *name* (`js_parse_function_decl2` calls `define_var` with the name
908 /// just consumed, before the parameters), a body-level one only once the whole function
909 /// has been parsed. So the block half runs from [`Parser::parse_function`] and this one
910 /// from the call site afterwards, and only one of the two does anything — which one
911 /// depends on the scope the declaration lands in.
912 ///
913 /// A function declaration in a function/script/module *body* behaves like a `var`:
914 /// `function a(){} var a;` and `var a; function a(){}` are both accepted, in either
915 /// mode. It is not quite a `var` though — a later `let a` reports it as "a variable"
916 /// (or "global identifier" at the top level), which is what `fn_names` records:
917 /// `find_var_in_child_scope` in the reference, consulted after the lexical check.
918 fn declare_function(&mut self, name: &str) -> Result<()> {
919 if !self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
920 return Ok(());
921 }
922 // The lexical check is skipped at the top level of a script or module, which is
923 // the reference's "avoid creating a lexical variable in the global scope" branch —
924 // so `let a; function a(){}` there is *accepted*, while the same two inside a
925 // function body are a lexical redefinition. The other order still errors, because
926 // then it is the `let` that does the checking.
927 if !self.at_top_level_scope()
928 && self
929 .scopes
930 .last()
931 .is_some_and(|scope| scope.lex_names.iter().any(|n| n == name))
932 {
933 return Err(self.duplicate_declaration(Redefinition::Lexical));
934 }
935 if let Some(scope) = self.scopes.last_mut() {
936 if !scope.var_names.iter().any(|n| n == name) {
937 scope.var_names.push(name.to_string());
938 }
939 if !scope.fn_names.iter().any(|n| n == name) {
940 scope.fn_names.push(name.to_string());
941 }
942 }
943 Ok(())
944 }
945
946 /// The at-the-name half of a function declaration: the block-scope check and the
947 /// module-code one.
948 ///
949 /// In a *block* a function declaration is a lexical binding of that block, which is why
950 /// `{ function f(){} var f }` is an early error (test262's
951 /// `block-scope/syntax/redeclaration`) while the same two declarations in a body are
952 /// not. The reference gets there by way of `define_var(JS_VAR_DEF_FUNCTION_DECL)`,
953 /// which sets `is_lexical`.
954 fn declare_block_function(&mut self, name: &str, is_plain: bool) -> Result<()> {
955 // A module is stricter about a function declaration sharing a name with anything
956 // already declared at the same level, and says so with its own message. The
957 // reference has this as a separate check (`js_parse_function_decl2`, "invalid
958 // redefinition of global identifier in module code") that runs at the name, before
959 // everything else, and matches on the *scope level* — so a `var` inside one block
960 // clashes with a function in that same block, and one at the module's top level
961 // does not.
962 if self.module
963 && self.at_top_level_scope()
964 && let Some(scope) = self.scopes.last()
965 {
966 // What can clash is only what the reference keeps in its *global* var table: a
967 // `var` written at this level (wherever that is), and — at the module's own
968 // body — the lexical declarations, which are module variables too. A `let`
969 // inside a block is not, so `{ let a; function a(){} }` in a module reports the
970 // ordinary lexical error instead.
971 let mut taken = scope.var_names_here.iter().any(|existing| existing == name);
972 if scope.is_var_scope {
973 let module_bindings = scope
974 .lex_names
975 .iter()
976 .filter(|existing| !scope.import_names.contains(existing))
977 .chain(&scope.fn_names);
978 taken |= module_bindings.into_iter().any(|existing| existing == name);
979 }
980 if taken {
981 return Err(self.error_at(
982 "invalid redefinition of global identifier in module code",
983 self.current.span,
984 ));
985 }
986 }
987 if self.scopes.last().is_none_or(|scope| scope.is_var_scope) {
988 return Ok(());
989 }
990 let Some(scope) = self.scopes.last() else {
991 return Ok(());
992 };
993 if scope.lex_names.iter().any(|n| n == name) || scope.catch_names.iter().any(|n| n == name)
994 {
995 // Annex B.3.3.4 lets a block re-declare a *function* in sloppy mode, and says
996 // nothing about a lexical binding of any other kind. A second function
997 // declaration is therefore accepted only where the first came from one too.
998 let from_plain_function = scope.plain_fn_names.iter().any(|n| n == name);
999 if !(from_plain_function && is_plain && !self.strict) {
1000 return Err(self.duplicate_declaration(Redefinition::Lexical));
1001 }
1002 } else if scope.var_names.iter().any(|n| n == name) {
1003 // A `var` in the same block clashes, and which message is right depends on
1004 // where that `var` landed: at the top level it became a global var, and the
1005 // reference checks globals separately.
1006 let reason = if self.at_top_level_scope() {
1007 Redefinition::Global
1008 } else {
1009 Redefinition::Variable
1010 };
1011 return Err(self.duplicate_declaration(reason));
1012 }
1013 if let Some(scope) = self.scopes.last_mut() {
1014 if !scope.lex_names.iter().any(|n| n == name) {
1015 scope.lex_names.push(name.to_string());
1016 }
1017 if !scope.fn_names.iter().any(|n| n == name) {
1018 scope.fn_names.push(name.to_string());
1019 }
1020 if is_plain && !scope.plain_fn_names.iter().any(|n| n == name) {
1021 scope.plain_fn_names.push(name.to_string());
1022 }
1023 }
1024 Ok(())
1025 }
1026
1027 /// A redefinition error, positioned the way the reference positions one.
1028 ///
1029 /// `js_parse_error` always uses `s->token.ptr` — the *current* token — so a
1030 /// redeclaration points at whatever follows the offending name, not at the name
1031 /// itself: `{ let a; let a = 1; }` reports the `=`, and `{ let a; let a; }` reports
1032 /// the `;`. Every call site is placed at the point the reference makes the check, so
1033 /// the current token here is the same one it would be there.
1034 ///
1035 /// Known gap: for a destructuring target the reference reports the token after the
1036 /// *inner* binding identifier (`let [a] = []` points at the `]`), while our check
1037 /// runs once the whole pattern is parsed.
1038 fn duplicate_declaration(&self, reason: Redefinition) -> SyntaxError {
1039 self.error_at(reason.message(), self.current.span)
1040 }
1041
1042 /// Whether declarations here belong to the script/module's own top-level scope.
1043 ///
1044 /// This is what splits the reference's `global identifier` message from
1045 /// `a variable`: a `var` recorded in the outermost var scope is a global var, and one
1046 /// inside a function is an ordinary variable.
1047 fn at_top_level_scope(&self) -> bool {
1048 self.scopes.iter().rposition(|scope| scope.is_var_scope) == Some(0)
1049 }
1050
1051 /// Declare every name bound by a pattern.
1052 fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
1053 let mut names = Vec::new();
1054 pattern.bound_names(&mut names);
1055 for name in names {
1056 if is_var {
1057 self.declare_var(&name.name)?;
1058 } else {
1059 self.declare_lexical(&name.name)?;
1060 }
1061 }
1062 Ok(())
1063 }
1064
1065 // -- token helpers -----------------------------------------------------
1066
1067 fn snapshot(&self) -> Snapshot<'a> {
1068 Snapshot {
1069 lexer: self.lexer.clone(),
1070 current: self.current.clone(),
1071 prev_end: self.prev_end,
1072 strict: self.strict,
1073 allow_in: self.allow_in,
1074 ctx: self.ctx,
1075 loop_depth: self.loop_depth,
1076 switch_depth: self.switch_depth,
1077 labels: self.labels.clone(),
1078 private: self.private.clone(),
1079 top_level: self.top_level,
1080 cover_inits: self.cover_inits.clone(),
1081 spread_trailing_comma: self.spread_trailing_comma.clone(),
1082 pending_exports: self.pending_exports.clone(),
1083 current_legacy_octal: self.current_legacy_octal,
1084 scopes: self.scopes.clone(),
1085 }
1086 }
1087
1088 fn restore(&mut self, snap: Snapshot<'a>) {
1089 self.lexer = snap.lexer;
1090 self.current = snap.current;
1091 self.prev_end = snap.prev_end;
1092 self.strict = snap.strict;
1093 self.allow_in = snap.allow_in;
1094 self.ctx = snap.ctx;
1095 self.loop_depth = snap.loop_depth;
1096 self.switch_depth = snap.switch_depth;
1097 self.labels = snap.labels;
1098 self.private = snap.private;
1099 self.top_level = snap.top_level;
1100 self.cover_inits = snap.cover_inits;
1101 self.spread_trailing_comma = snap.spread_trailing_comma;
1102 self.pending_exports = snap.pending_exports;
1103 self.current_legacy_octal = snap.current_legacy_octal;
1104 self.scopes = snap.scopes;
1105 }
1106
1107 fn bump(&mut self) -> Result<()> {
1108 self.prev_end = self.current.span.end;
1109 self.current = self.lexer.next_token()?;
1110 self.current_legacy_octal = self.lexer.had_legacy_octal();
1111 if self.strict && self.current_legacy_octal {
1112 return Err(SyntaxError::new(
1113 "octal literals and octal escape sequences are not allowed in strict mode",
1114 self.current.span,
1115 ));
1116 }
1117 Ok(())
1118 }
1119
1120 fn peek(&self) -> Result<Token> {
1121 let mut lexer = self.lexer.clone();
1122 lexer.next_token()
1123 }
1124
1125 fn enter_strict(&mut self) -> Result<()> {
1126 self.strict = true;
1127 self.lexer.set_strict(true);
1128 // The token after the `"use strict"` directive has already been scanned
1129 // with the old (sloppy) rules.
1130 if self.current_legacy_octal {
1131 return Err(SyntaxError::new(
1132 "octal literals and octal escape sequences are not allowed in strict mode",
1133 self.current.span,
1134 ));
1135 }
1136 Ok(())
1137 }
1138
1139 fn at_punct(&self, p: Punct) -> bool {
1140 matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
1141 }
1142
1143 fn at_keyword(&self, k: Keyword) -> bool {
1144 matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
1145 }
1146
1147 fn at_contextual(&self, name: &str) -> bool {
1148 self.at_ident(name)
1149 }
1150
1151 /// Whether the current token is the identifier `name` written without escapes.
1152 ///
1153 /// Every caller asks about a *contextual keyword* — `get`, `async`, `static`, `let`,
1154 /// and the literal `target`/`meta` of `new.target` and `import.meta`. Those words are
1155 /// only special as their own spelling, so `\u0067et` must not match here; it is an
1156 /// ordinary identifier that happens to read the same.
1157 fn at_ident(&self, name: &str) -> bool {
1158 !self.current.escaped && matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
1159 }
1160
1161 fn eat_punct(&mut self, p: Punct) -> Result<bool> {
1162 if self.at_punct(p) {
1163 self.bump()?;
1164 return Ok(true);
1165 }
1166 Ok(false)
1167 }
1168
1169 fn expect_punct(&mut self, p: Punct) -> Result<()> {
1170 if self.eat_punct(p)? {
1171 Ok(())
1172 } else {
1173 // `expecting ';'`, the reference's `js_parse_expect`. It formats the expected
1174 // token with `%c`, so only single-character punctuators can be named this way —
1175 // and every call site here passes one, which is why this is the reference's set
1176 // exactly: `( ) { } [ ] ; :`.
1177 Err(self.error(format!("expecting '{}'", p.as_str())))
1178 }
1179 }
1180
1181 fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
1182 if self.at_keyword(k) {
1183 self.bump()?;
1184 return Ok(true);
1185 }
1186 Ok(false)
1187 }
1188
1189 fn eat_contextual(&mut self, name: &str) -> Result<bool> {
1190 if self.at_ident(name) {
1191 self.bump()?;
1192 return Ok(true);
1193 }
1194 Ok(false)
1195 }
1196
1197 /// `unexpected token in expression: '<token text>'` — the reference's message when a
1198 /// primary expression was expected and the token cannot start one.
1199 ///
1200 /// The token's text is its **raw source slice**, not a description: `js_parse_error(s,
1201 /// "unexpected token in expression: '%.*s'", s->buf_ptr - s->token.ptr, s->token.ptr)`.
1202 /// That is why end of input prints as `''` and a string literal prints with its quotes.
1203 fn unexpected(&self) -> SyntaxError {
1204 let source = self.lexer.source();
1205 let start = self.current.span.start.offset as usize;
1206 let end = self.current.span.end.offset as usize;
1207 let text = source.get(start..end).unwrap_or("");
1208 SyntaxError::new(
1209 format!("unexpected token in expression: '{text}'"),
1210 self.current.span,
1211 )
1212 }
1213
1214 fn error(&self, message: impl Into<String>) -> SyntaxError {
1215 SyntaxError::new(message, self.current.span)
1216 }
1217
1218 fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
1219 SyntaxError::new(message, span)
1220 }
1221
1222 fn span_from(&self, start: Position) -> Span {
1223 Span::new(start, self.prev_end)
1224 }
1225
1226 /// Read an identifier that *binds* a name, applying the binding rules
1227 /// (`eval`/`arguments`/`let` are restricted in strict mode).
1228 fn expect_binding_ident(&mut self) -> Result<Ident> {
1229 let ident = self.expect_ident()?;
1230 self.check_binding_name(&ident.name, ident.span)?;
1231 Ok(ident)
1232 }
1233
1234 /// Read an identifier, rejecting reserved words.
1235 fn expect_ident(&mut self) -> Result<Ident> {
1236 match self.current.kind.clone() {
1237 TokenKind::Ident(name) => {
1238 // A *name* position: `await` is a token there, not an identifier, so the
1239 // reference never gets as far as complaining about it by name.
1240 if name == "await" && self.await_is_reserved() {
1241 return Err(self.error("variable name expected"));
1242 }
1243 let span = self.current.span;
1244 self.check_identifier(&name, span)?;
1245 self.bump()?;
1246 Ok(Ident { name, span })
1247 }
1248 // The reference has no "got X" suffix: `js_parse_error(s, "variable name
1249 // expected")`. The token is already the error position.
1250 _ => Err(self.error("variable name expected")),
1251 }
1252 }
1253
1254 /// Whether the current token can begin a formal parameter.
1255 ///
1256 /// A token that cannot is a *missing* parameter rather than a malformed one, which is
1257 /// the reference's `missing formal parameter`. `await` counts as missing where it is
1258 /// reserved: the reference never sees it as an identifier, so it never gets to the
1259 /// name check that would say `variable name expected`.
1260 fn at_formal_parameter(&self) -> bool {
1261 if self.at_punct(Punct::LBracket) || self.at_punct(Punct::LBrace) {
1262 return true;
1263 }
1264 match &self.current.kind {
1265 TokenKind::Ident(name) => !(name == "await" && self.await_is_reserved()),
1266 _ => false,
1267 }
1268 }
1269
1270 /// Whether `await` cannot be written as a name here.
1271 ///
1272 /// Two separate reasons, and the reference reaches them from two different places:
1273 ///
1274 /// * the enclosing function is `async`, where `await` is a keyword rather than an
1275 /// identifier (`fd->func_kind & JS_FUNC_ASYNC`);
1276 /// * the code is module code, where `await` is reserved at *every* depth — not just
1277 /// the module's own top level — so `function f(){ var await = 1 }` in a module is
1278 /// an error while the same function in a script is not.
1279 fn await_is_reserved(&self) -> bool {
1280 // A static block is not async, but `await` is still not an identifier there —
1281 // the reference spells the rule out by name (`func_has_ancestor_kind`).
1282 self.ctx.in_async || self.module || self.ctx.in_static_block
1283 }
1284
1285 /// Reject words that may not appear as an `IdentifierReference` here.
1286 fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
1287 if Keyword::lookup(name).is_some() {
1288 return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
1289 }
1290 if self.strict && Keyword::is_strict_reserved(name) {
1291 return Err(self.error_at(
1292 format!("invalid use of strict mode reserved word '{name}'"),
1293 span,
1294 ));
1295 }
1296 if self.ctx.in_generator && name == "yield" {
1297 return Err(self.error_at(
1298 "invalid use of 'yield' identifier in a generator function",
1299 span,
1300 ));
1301 }
1302 if name == "await" && self.await_is_reserved() {
1303 // `await` never reaches the identifier path where it is a keyword: in an async
1304 // function it is an operator, and in module code at *any* depth it is reserved
1305 // even inside a plain function, which is where this message comes from —
1306 // `function f(){ await 1 }` in a module is a keyword used as a name.
1307 return Err(self.error_at("unexpected 'await' keyword", span));
1308 }
1309 Ok(())
1310 }
1311
1312 /// `arguments` is not a name a class field initialiser or a static block may use.
1313 ///
1314 /// Both run in a function whose `arguments` the class never defined, so the reference
1315 /// bans the reference outright rather than letting it resolve to the enclosing one —
1316 /// `class C { x = arguments }` is a `SyntaxError`, not the caller's arguments. Only a
1317 /// *reference* is affected: a function written inside either still has its own.
1318 fn check_arguments_reference(&self, name: &str, span: Span) -> Result<()> {
1319 if name == "arguments" && !self.ctx.arguments_allowed {
1320 return Err(self.error_at(
1321 "'arguments' identifier is not allowed in class field initializer",
1322 span,
1323 ));
1324 }
1325 Ok(())
1326 }
1327
1328 /// A declarative name (`let`, `class`, `function`, parameter): stricter than
1329 /// an identifier reference because `let` is reserved in strict mode.
1330 fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
1331 self.check_identifier(name, span)?;
1332 if self.strict && (name == "eval" || name == "arguments") {
1333 // One message for both, and it names neither. Which of the two the reference
1334 // uses depends on where the name sits: `js_parse_destructuring_var` covers
1335 // every formal parameter and says "argument", while a `var`/`let`/function name
1336 // says "variable".
1337 let message = if self.in_formal_parameters {
1338 "invalid argument name in strict code"
1339 } else {
1340 "invalid variable name in strict mode"
1341 };
1342 return Err(self.error_at(message, span));
1343 }
1344 if self.strict && name == "let" {
1345 return Err(self.error_at(
1346 "invalid use of 'let' as a variable name in strict mode",
1347 span,
1348 ));
1349 }
1350 Ok(())
1351 }
1352
1353 /// The value of an expression statement that is a string literal with no
1354 /// escape sequences (a directive prologue candidate).
1355 fn directive_value(&self, stmt: &Stmt) -> Option<String> {
1356 let StmtKind::Expr(expr) = &stmt.kind else {
1357 return None;
1358 };
1359 let ExprKind::String(value) = &expr.unparen().kind else {
1360 return None;
1361 };
1362 let raw = self.slice(expr.span);
1363 if !raw.starts_with('"') && !raw.starts_with('\'') {
1364 return None;
1365 }
1366 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1367 return None;
1368 }
1369 // A directive is ASCII by construction (`"use strict"` and friends), so the lossy
1370 // conversion cannot be lossy here.
1371 Some(value.to_string_lossy().into_owned())
1372 }
1373
1374 fn slice(&self, span: Span) -> &'a str {
1375 let src = self.lexer.source();
1376 let start = span.start.offset as usize;
1377 let end = (span.end.offset as usize).min(src.len());
1378 src.get(start..end).unwrap_or("")
1379 }
1380
1381 // -- automatic semicolon insertion ------------------------------------
1382
1383 fn can_insert_semicolon(&self) -> bool {
1384 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1385 }
1386
1387 fn semicolon(&mut self) -> Result<()> {
1388 if self.eat_punct(Punct::Semicolon)? {
1389 return Ok(());
1390 }
1391 if self.can_insert_semicolon() {
1392 return Ok(());
1393 }
1394 // Not `unexpected()`: the reference's `js_parse_expect_semi` names what it wanted
1395 // (`expecting ';'`), which is why `1 2` says so rather than describing the `2`.
1396 Err(self.error("expecting ';'"))
1397 }
1398
1399 // -- statements --------------------------------------------------------
1400
1401 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1402 self.enter()?;
1403 let result = self.parse_statement_list_item_guarded();
1404 self.leave();
1405 result
1406 }
1407
1408 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1409 let cover_mark = self.cover_inits.len();
1410 let stmt = self.parse_statement_list_item_inner()?;
1411 if self.cover_inits.len() > cover_mark {
1412 let span = self.cover_inits[cover_mark];
1413 self.cover_inits.truncate(cover_mark);
1414 return Err(self.error_at("expecting '}'", span));
1415 }
1416 Ok(stmt)
1417 }
1418
1419 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1420 if self.at_keyword(Keyword::Function) {
1421 let start = self.current.span.start;
1422 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1423 if let Some(name) = &func.name {
1424 self.declare_function(&name.name)?;
1425 }
1426 return Ok(Stmt::new(
1427 StmtKind::FuncDecl(Box::new(func)),
1428 self.span_from(start),
1429 ));
1430 }
1431 if self.at_ident("async") {
1432 let peek = self.peek()?;
1433 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1434 let start = self.current.span.start;
1435 self.bump()?; // async
1436 let func = self.parse_function(FunctionForm::Declaration, true, Some(start))?;
1437 if let Some(name) = &func.name {
1438 self.declare_function(&name.name)?;
1439 }
1440 return Ok(Stmt::new(
1441 StmtKind::FuncDecl(Box::new(func)),
1442 self.span_from(start),
1443 ));
1444 }
1445 }
1446 if self.at_keyword(Keyword::Class) {
1447 let start = self.current.span.start;
1448 let class = self.parse_class(false)?;
1449 if let Some(name) = &class.name {
1450 self.declare_lexical(&name.name)?;
1451 }
1452 return Ok(Stmt::new(
1453 StmtKind::ClassDecl(Box::new(class)),
1454 self.span_from(start),
1455 ));
1456 }
1457 if self.at_keyword(Keyword::Var) {
1458 let start = self.current.span.start;
1459 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1460 self.semicolon()?;
1461 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1462 }
1463 if self.at_keyword(Keyword::Const) {
1464 let start = self.current.span.start;
1465 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1466 self.semicolon()?;
1467 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1468 }
1469 if self.at_ident("let") && self.let_starts_declaration()? {
1470 let start = self.current.span.start;
1471 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1472 self.semicolon()?;
1473 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1474 }
1475 // `await using x = …` is one declaration; `await` is only a keyword here when the
1476 // enclosing code may await at all, which is the same rule `await` expressions use.
1477 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1478 let start = self.current.span.start;
1479 // No top-level rejection here, unlike a plain `using`: the reference's check
1480 // lives on the `using` path only (`fd->is_eval && scope_level == body_scope`),
1481 // while `await using` reaches a branch that does not ask.
1482 //
1483 // The `case`-clause ban *does* apply, and for the same reason it applies to a
1484 // plain `using`: a clause is a statement list with nothing to terminate it, so
1485 // there is no point at which the resource could be disposed
1486 // (`await-using/syntax/await-using-invalid-switchstatement-caseclause`).
1487 if self.in_case_clause {
1488 return Err(self.error_at(
1489 "using declaration is not allowed in this context",
1490 self.span_from(start),
1491 ));
1492 }
1493 self.bump()?; // await
1494 let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1495 self.semicolon()?;
1496 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1497 }
1498 if self.at_ident("using") && self.using_starts_declaration()? {
1499 let start = self.current.span.start;
1500 // A script's *own* scope has no block to end, so there would be nowhere to
1501 // dispose. The reference asks `scope_level == body_scope`: the program's scope
1502 // itself, not a block nested inside it — `{ using y = 1 }` is legal there and
1503 // disposes at the closing brace. A module's top level *is* a scope, so it does
1504 // not ask at all.
1505 if self.scopes.len() == 1 && !self.module {
1506 return Err(self.error_at(
1507 "using declaration is not allowed at the top level of a script",
1508 self.span_from(start),
1509 ));
1510 }
1511 // A `case`/`default` clause is a statement list with nothing to end it, so a
1512 // `using` there has no disposal point either. This is a separate early error
1513 // from the one above: it applies inside a function too, where the scope depth
1514 // is not 1.
1515 if self.in_case_clause {
1516 return Err(self.error_at(
1517 "using declaration is not allowed in this context",
1518 self.span_from(start),
1519 ));
1520 }
1521 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1522 self.semicolon()?;
1523 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1524 }
1525 // `import`/`export` declarations belong to the module's own statement list and
1526 // nowhere else: not inside a function, not inside a block. The scope depth is what
1527 // tells the two apart — the program's scope is the only one at depth 1 — and asking
1528 // it here is what turns `class C { m() { export default 1 } }` into the parse error
1529 // the reference reports instead of letting the compiler run into an `export` with
1530 // no module tables behind it.
1531 let at_module_top_level = self.module && self.scopes.len() == 1;
1532 if at_module_top_level && self.at_keyword(Keyword::Import) {
1533 let peek = self.peek()?;
1534 // `import(` and `import.meta` are expressions, not declarations.
1535 if !matches!(
1536 peek.kind,
1537 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1538 ) {
1539 return self.parse_import_decl();
1540 }
1541 }
1542 if at_module_top_level && self.at_keyword(Keyword::Export) {
1543 return self.parse_export_decl();
1544 }
1545 self.parse_statement()
1546 }
1547
1548 /// `let` is a declaration keyword when followed by a binding or a pattern.
1549 fn let_starts_declaration(&self) -> Result<bool> {
1550 let peek = self.peek()?;
1551 Ok(matches!(
1552 peek.kind,
1553 TokenKind::Ident(_)
1554 | TokenKind::Punct(Punct::LBracket)
1555 | TokenKind::Punct(Punct::LBrace)
1556 ))
1557 }
1558
1559 /// The token after a `using` declaration head's binding name, if a head starts here.
1560 ///
1561 /// `skip` is how many words come before `using` — `1` for `await using`. Returns `None`
1562 /// when the shape is not a declaration head at all: the binding must be a plain
1563 /// identifier with no line terminator before it.
1564 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1565 let mut lexer = self.lexer.clone();
1566 // The lexer is already positioned after the current token, so the first
1567 // `next_token` yields the token that follows it. `using` itself is `skip` words in,
1568 // and the binding is the token after it.
1569 let mut binding = None;
1570 for _ in 0..=skip {
1571 binding = Some(lexer.next_token()?);
1572 }
1573 let Some(binding) = binding else {
1574 return Ok(None);
1575 };
1576 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1577 return Ok(None);
1578 }
1579 Ok(Some(lexer.next_token()?))
1580 }
1581
1582 /// Whether `await using` starts a declaration here.
1583 ///
1584 /// `await` is followed by `using`, which is in turn followed by a binding name and `=`.
1585 /// Anything else — `await using(x)` where `using` is a function — is an `await`
1586 /// expression over an ordinary call.
1587 fn await_using_follows(&self) -> Result<bool> {
1588 Ok(matches!(
1589 self.using_head_tail(1)?.map(|token| token.kind),
1590 Some(TokenKind::Punct(Punct::Eq))
1591 ))
1592 }
1593
1594 /// Whether the `using` at the current token begins a declaration.
1595 ///
1596 /// `using` is a contextual keyword, not a reserved word: `using = 1`, `using(x)` and
1597 /// `using.f` are all ordinary expressions over a variable named `using`. The spec's
1598 /// rule is `using [no LineTerminator] BindingIdentifier =`, so the binding name has to
1599 /// be followed by `=`.
1600 ///
1601 /// Patterns are excluded on purpose: `using {a} = …` is not a using declaration, and
1602 /// the grammar forbids it, so it stays an expression statement that fails to parse as
1603 /// one.
1604 fn using_starts_declaration(&self) -> Result<bool> {
1605 Ok(matches!(
1606 self.using_head_tail(0)?.map(|token| token.kind),
1607 Some(TokenKind::Punct(Punct::Eq))
1608 ))
1609 }
1610
1611 /// Whether `using x of …` starts a `for` head here.
1612 ///
1613 /// The head has no initialiser, so the token after the binding is `of` (or `in`, which
1614 /// the caller then rejects: a `using` may only iterate a `for`-`of`).
1615 fn using_starts_for_head(&self) -> Result<bool> {
1616 Ok(matches!(
1617 self.using_head_tail(0)?.map(|token| token.kind),
1618 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1619 ))
1620 }
1621
1622 /// Whether `await using x of …` starts a `for` head here.
1623 fn await_using_starts_for_head(&self) -> Result<bool> {
1624 Ok(matches!(
1625 self.using_head_tail(1)?.map(|token| token.kind),
1626 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1627 ))
1628 }
1629
1630 fn parse_statement(&mut self) -> Result<Stmt> {
1631 let start = self.current.span.start;
1632 if self.at_punct(Punct::Semicolon) {
1633 self.bump()?;
1634 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1635 }
1636 if self.at_punct(Punct::LBrace) {
1637 let body = self.parse_block()?;
1638 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1639 }
1640 if self.at_keyword(Keyword::If) {
1641 return self.parse_if();
1642 }
1643 if self.at_keyword(Keyword::Do) {
1644 return self.parse_do_while();
1645 }
1646 if self.at_keyword(Keyword::While) {
1647 return self.parse_while();
1648 }
1649 if self.at_keyword(Keyword::For) {
1650 return self.parse_for();
1651 }
1652 if self.at_keyword(Keyword::Switch) {
1653 return self.parse_switch();
1654 }
1655 if self.at_keyword(Keyword::Try) {
1656 return self.parse_try();
1657 }
1658 if self.at_keyword(Keyword::Return) {
1659 return self.parse_return();
1660 }
1661 if self.at_keyword(Keyword::Throw) {
1662 return self.parse_throw();
1663 }
1664 if self.at_keyword(Keyword::Break) {
1665 return self.parse_break_continue(true);
1666 }
1667 if self.at_keyword(Keyword::Continue) {
1668 return self.parse_break_continue(false);
1669 }
1670 // `VariableStatement` is a `Statement`, not a `Declaration`: `if (x) var y = 1;`
1671 // and `with ({}) var y = 1;` are both legal. Only `let`, `const`, `function` and
1672 // `class` are restricted to a statement *list*. Recognising `var` only in
1673 // `parse_statement_list_item` made every single-statement position reject it.
1674 if self.at_keyword(Keyword::Var) {
1675 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1676 self.semicolon()?;
1677 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1678 }
1679 if self.at_keyword(Keyword::With) {
1680 return self.parse_with();
1681 }
1682 if self.at_keyword(Keyword::Debugger) {
1683 self.bump()?;
1684 self.semicolon()?;
1685 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1686 }
1687 // `async function f(){}` is a declaration too, and Annex B never extended the
1688 // single-statement positions to cover it — only the plain form, and only in sloppy
1689 // mode. Left unhandled here it split into two statements (`async;` by ASI, then the
1690 // declaration in the enclosing list), so `with ({}) async function f(){}` was
1691 // accepted (`statements/with/decl-async-fun`).
1692 if self.at_ident("async") {
1693 let peek = self.peek()?;
1694 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1695 return Err(self
1696 .error("invalid 'async function' declaration in a single statement context"));
1697 }
1698 }
1699 if self.at_keyword(Keyword::Function) {
1700 // Annex B: function declarations in statement position are legal in
1701 // sloppy mode (`if (x) function f() {}`).
1702 if self.strict {
1703 return Err(
1704 self.error("invalid 'function' declaration in a single statement context")
1705 );
1706 }
1707 // Only the *plain* form is extended. `B.3.2` rewrites `IfStatement` to accept a
1708 // `FunctionDeclaration`, and a `GeneratorDeclaration` is a different production
1709 // — so `if (1) function* g(){}` stays a `SyntaxError`, as does the same thing
1710 // behind a label (`LabelledItem : FunctionDeclaration` has no generator form
1711 // either). `async function` is rejected just above for the same reason.
1712 if matches!(self.peek()?.kind, TokenKind::Punct(Punct::Star)) {
1713 return Err(
1714 self.error("invalid generator declaration in a single statement context")
1715 );
1716 }
1717 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1718 if let Some(name) = &func.name {
1719 self.declare_function(&name.name)?;
1720 }
1721 return Ok(Stmt::new(
1722 StmtKind::FuncDecl(Box::new(func)),
1723 self.span_from(start),
1724 ));
1725 }
1726 if self.at_keyword(Keyword::Class) {
1727 return Err(self.error("invalid 'class' declaration in a single statement context"));
1728 }
1729 if self.at_keyword(Keyword::Import) {
1730 // `import(...)` and `import.meta` are *expressions*, so they are an ordinary
1731 // expression statement here. Only a declaration is restricted to the top
1732 // level of a module.
1733 let peek = self.peek()?;
1734 let expression = matches!(
1735 peek.kind,
1736 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1737 );
1738 if !expression {
1739 return Err(self.error("'import' can only appear at the top level of a module"));
1740 }
1741 }
1742 if self.at_keyword(Keyword::Export) {
1743 return Err(self.error("'export' can only appear at the top level of a module"));
1744 }
1745 // Labelled statement.
1746 if let TokenKind::Ident(name) = &self.current.kind {
1747 // `await` is not a `LabelIdentifier` in module code, and where it is an
1748 // operator it is not an identifier at all — `await: 1` in a suspensible body
1749 // is an `await` expression whose operand is missing, not a label.
1750 if name == "await" && self.await_is_reserved() {
1751 if !self.ctx.in_async {
1752 // Reserved because this is module code, but not an operator: the
1753 // reference has a message for exactly this case.
1754 let peek = self.peek()?;
1755 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1756 return Err(self.error("unexpected 'await' keyword"));
1757 }
1758 }
1759 // Where `await` *is* an operator it is not an identifier at all, so
1760 // `await: 1` is an `await` expression with a missing operand. Falling
1761 // through leaves that to the expression parser, which says so.
1762 } else {
1763 let peek = self.peek()?;
1764 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1765 return self.parse_labeled();
1766 }
1767 }
1768 }
1769 // `ExpressionStatement` carries `[lookahead ∉ { let [ }]`: a statement may not
1770 // *begin* with `let`, so `let\n[0] = 0` is a `SyntaxError` and not a member
1771 // expression on an identifier called `let`. The newline changes nothing — the
1772 // restriction is on the first two tokens.
1773 if self.at_ident("let") {
1774 let peek = self.peek()?;
1775 if matches!(peek.kind, TokenKind::Punct(Punct::LBracket)) {
1776 return Err(self.error("unexpected 'let [' in a statement"));
1777 }
1778 }
1779 self.parse_expression_statement()
1780 }
1781
1782 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1783 self.expect_punct(Punct::LBrace)?;
1784 self.push_scope(Scope::block());
1785 // A block *inside* a `case` clause is a block, so `using` is legal there: the
1786 // early error is about a `using` sitting directly in the clause's statement list.
1787 let saved_in_case = self.in_case_clause;
1788 self.in_case_clause = false;
1789 let result = self.parse_block_body();
1790 self.in_case_clause = saved_in_case;
1791 self.pop_scope();
1792 let body = result?;
1793 self.bump()?; // }
1794 Ok(body)
1795 }
1796
1797 /// `{ … }` of a `catch` clause: parsed in the scope holding its parameter.
1798 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1799 self.expect_punct(Punct::LBrace)?;
1800 let body = self.parse_block_body()?;
1801 self.bump()?; // }
1802 Ok(body)
1803 }
1804
1805 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1806 let mut body = Vec::new();
1807 while !self.at_punct(Punct::RBrace) {
1808 if self.current.is_eof() {
1809 return Err(self.unexpected());
1810 }
1811 body.push(self.parse_statement_list_item()?);
1812 }
1813 Ok(body)
1814 }
1815
1816 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1817 let start = self.current.span.start;
1818 let expr = self.parse_expression(true)?;
1819 self.semicolon()?;
1820 Ok(Stmt::new(
1821 StmtKind::Expr(Box::new(expr)),
1822 self.span_from(start),
1823 ))
1824 }
1825
1826 fn parse_if(&mut self) -> Result<Stmt> {
1827 let start = self.current.span.start;
1828 self.bump()?; // if
1829 self.expect_punct(Punct::LParen)?;
1830 let test = self.parse_expression(true)?;
1831 self.expect_punct(Punct::RParen)?;
1832 let cons = self.parse_statement()?;
1833 let alt = if self.eat_keyword(Keyword::Else)? {
1834 Some(Box::new(self.parse_statement()?))
1835 } else {
1836 None
1837 };
1838 Ok(Stmt::new(
1839 StmtKind::If {
1840 test: Box::new(test),
1841 cons: Box::new(cons),
1842 alt,
1843 },
1844 self.span_from(start),
1845 ))
1846 }
1847
1848 fn parse_do_while(&mut self) -> Result<Stmt> {
1849 let start = self.current.span.start;
1850 self.bump()?; // do
1851 self.loop_depth += 1;
1852 let body = self.parse_single_statement();
1853 self.loop_depth -= 1;
1854 let body = body?;
1855 if !self.eat_keyword(Keyword::While)? {
1856 return Err(self.unexpected());
1857 }
1858 self.expect_punct(Punct::LParen)?;
1859 let test = self.parse_expression(true)?;
1860 self.expect_punct(Punct::RParen)?;
1861 // `do … while (x)` allows a missing semicolon even without a newline.
1862 let _ = self.eat_punct(Punct::Semicolon)?;
1863 Ok(Stmt::new(
1864 StmtKind::DoWhile {
1865 body: Box::new(body),
1866 test: Box::new(test),
1867 },
1868 self.span_from(start),
1869 ))
1870 }
1871
1872 fn parse_while(&mut self) -> Result<Stmt> {
1873 let start = self.current.span.start;
1874 self.bump()?; // while
1875 self.expect_punct(Punct::LParen)?;
1876 let test = self.parse_expression(true)?;
1877 self.expect_punct(Punct::RParen)?;
1878 self.loop_depth += 1;
1879 let body = self.parse_single_statement();
1880 self.loop_depth -= 1;
1881 Ok(Stmt::new(
1882 StmtKind::While {
1883 test: Box::new(test),
1884 body: Box::new(body?),
1885 },
1886 self.span_from(start),
1887 ))
1888 }
1889
1890 /// The right-hand side of a `for`-`in`/`for`-`of` head.
1891 ///
1892 /// The two differ, and the difference is observable: the grammar says
1893 /// `for ( x in Expression )` but `for ( x of AssignmentExpression )`. So
1894 /// `for (x in {a:1}, {})` is legal (a sequence) while `for (x of [], [])` is a
1895 /// `SyntaxError` at the `)` (`for-of/head-expr-no-expr`, `for-in/head-expr-expr`).
1896 fn parse_for_in_of_right(&mut self, is_of: bool) -> Result<Expr> {
1897 if is_of {
1898 self.parse_assignment(true)
1899 } else {
1900 self.parse_expression(true)
1901 }
1902 }
1903
1904 fn parse_for(&mut self) -> Result<Stmt> {
1905 let start = self.current.span.start;
1906 self.bump()?; // for
1907 self.push_scope(Scope::block());
1908 let result = self.parse_for_inner(start);
1909 self.pop_scope();
1910 result
1911 }
1912
1913 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1914 let mut is_await = false;
1915 if self.at_ident("await") && self.ctx.in_async {
1916 let peek = self.peek()?;
1917 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1918 is_await = true;
1919 self.bump()?;
1920 }
1921 }
1922 self.expect_punct(Punct::LParen)?;
1923
1924 // `for (;;)`
1925 if self.at_punct(Punct::Semicolon) {
1926 self.bump()?;
1927 return self.parse_for_classic(start, None);
1928 }
1929
1930 // Declaration head.
1931 let decl_kind = if self.at_keyword(Keyword::Var) {
1932 Some(VarDeclKind::Var)
1933 } else if self.at_keyword(Keyword::Const) {
1934 Some(VarDeclKind::Const)
1935 } else if self.at_ident("let") && self.let_starts_declaration()? {
1936 Some(VarDeclKind::Let)
1937 } else if self.at_ident("using") && self.using_starts_for_head()? {
1938 Some(VarDeclKind::Using)
1939 } else if self.at_ident("await")
1940 && self.ctx.in_async
1941 && self.await_using_starts_for_head()?
1942 {
1943 self.bump()?; // await, leaving `using` as the keyword
1944 Some(VarDeclKind::AwaitUsing)
1945 } else {
1946 None
1947 };
1948 if let Some(kind) = decl_kind {
1949 let decl_start = self.current.span.start;
1950 let decl = self.parse_var_decl(kind, true, false)?;
1951 if self.at_for_head_keyword() {
1952 let is_of = self.at_contextual("of");
1953 if !is_of && decl.declarators.len() != 1 {
1954 return Err(self.error_at(
1955 "only one binding allowed in a for-in loop",
1956 self.span_from(decl_start),
1957 ));
1958 }
1959 if is_of && decl.declarators.len() != 1 {
1960 return Err(self.error_at(
1961 "only one binding allowed in a for-of loop",
1962 self.span_from(decl_start),
1963 ));
1964 }
1965 if let Some(declarator) = decl.declarators.first() {
1966 if declarator.init.is_some() {
1967 // `for (var x = 1 in y)` is legacy in sloppy mode only.
1968 if is_of || kind.is_lexical() || self.strict {
1969 return Err(self.error_at(
1970 if is_of {
1971 // The reference formats `%s` with the loop kind.
1972 "a declaration in the head of a for-of loop can't have an initializer"
1973 } else {
1974 "a declaration in the head of a for-in loop can't have an initializer"
1975 },
1976 declarator.span,
1977 ));
1978 }
1979 }
1980 }
1981 if is_await && !is_of {
1982 return Err(self.error("for await is only valid with 'of'"));
1983 }
1984 self.bump()?; // in / of
1985 let right = self.parse_for_in_of_right(is_of)?;
1986 self.expect_punct(Punct::RParen)?;
1987 self.loop_depth += 1;
1988 let body = self.parse_single_statement();
1989 self.loop_depth -= 1;
1990 let head = ForHead::VarDecl(decl);
1991 let span = self.span_from(start);
1992 return Ok(Stmt::new(
1993 if is_of {
1994 StmtKind::ForOf {
1995 is_await,
1996 left: head,
1997 right: Box::new(right),
1998 body: Box::new(body?),
1999 }
2000 } else {
2001 StmtKind::ForIn {
2002 left: head,
2003 right: Box::new(right),
2004 body: Box::new(body?),
2005 }
2006 },
2007 span,
2008 ));
2009 }
2010 self.expect_punct(Punct::Semicolon)?;
2011 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
2012 }
2013
2014 // Expression head.
2015 let expr_start = self.current.span.start;
2016 let expr = self.parse_expression(false)?;
2017 if self.at_for_head_keyword() {
2018 let is_of = self.at_contextual("of");
2019 if is_await && !is_of {
2020 return Err(self.error("for await is only valid with 'of'"));
2021 }
2022 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
2023 self.bump()?; // in / of
2024 let right = self.parse_for_in_of_right(is_of)?;
2025 self.expect_punct(Punct::RParen)?;
2026 self.loop_depth += 1;
2027 let body = self.parse_single_statement();
2028 self.loop_depth -= 1;
2029 let head = ForHead::Assign(Box::new(target));
2030 let span = self.span_from(start);
2031 return Ok(Stmt::new(
2032 if is_of {
2033 StmtKind::ForOf {
2034 is_await,
2035 left: head,
2036 right: Box::new(right),
2037 body: Box::new(body?),
2038 }
2039 } else {
2040 StmtKind::ForIn {
2041 left: head,
2042 right: Box::new(right),
2043 body: Box::new(body?),
2044 }
2045 },
2046 span,
2047 ));
2048 }
2049 let _ = expr_start;
2050 self.expect_punct(Punct::Semicolon)?;
2051 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
2052 }
2053
2054 /// Whether the `for` head continues with `in` (a keyword) or `of` (a
2055 /// contextual keyword).
2056 fn at_for_head_keyword(&self) -> bool {
2057 self.at_keyword(Keyword::In) || self.at_contextual("of")
2058 }
2059
2060 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
2061 let test = if self.at_punct(Punct::Semicolon) {
2062 None
2063 } else {
2064 Some(Box::new(self.parse_expression(true)?))
2065 };
2066 self.expect_punct(Punct::Semicolon)?;
2067 let update = if self.at_punct(Punct::RParen) {
2068 None
2069 } else {
2070 Some(Box::new(self.parse_expression(true)?))
2071 };
2072 self.expect_punct(Punct::RParen)?;
2073 self.loop_depth += 1;
2074 let body = self.parse_single_statement();
2075 self.loop_depth -= 1;
2076 Ok(Stmt::new(
2077 StmtKind::For {
2078 init,
2079 test,
2080 update,
2081 body: Box::new(body?),
2082 },
2083 self.span_from(start),
2084 ))
2085 }
2086
2087 fn parse_switch(&mut self) -> Result<Stmt> {
2088 let start = self.current.span.start;
2089 self.bump()?; // switch
2090 self.expect_punct(Punct::LParen)?;
2091 let discriminant = self.parse_expression(true)?;
2092 self.expect_punct(Punct::RParen)?;
2093 self.expect_punct(Punct::LBrace)?;
2094 self.switch_depth += 1;
2095 self.push_scope(Scope::block());
2096 let mut cases = Vec::new();
2097 let mut seen_default = false;
2098 while !self.at_punct(Punct::RBrace) {
2099 if self.current.is_eof() {
2100 self.switch_depth -= 1;
2101 return Err(self.unexpected());
2102 }
2103 let case_start = self.current.span.start;
2104 let test = if self.eat_keyword(Keyword::Case)? {
2105 Some(Box::new(self.parse_expression(true)?))
2106 } else if self.eat_keyword(Keyword::Default)? {
2107 if seen_default {
2108 self.switch_depth -= 1;
2109 return Err(self.error("duplicate 'default' clause in switch statement"));
2110 }
2111 seen_default = true;
2112 None
2113 } else {
2114 self.switch_depth -= 1;
2115 return Err(self.unexpected());
2116 };
2117 self.expect_punct(Punct::Colon)?;
2118 let mut body = Vec::new();
2119 let saved_in_case = self.in_case_clause;
2120 self.in_case_clause = true;
2121 while !self.at_punct(Punct::RBrace)
2122 && !self.at_keyword(Keyword::Case)
2123 && !self.at_keyword(Keyword::Default)
2124 {
2125 if self.current.is_eof() {
2126 self.in_case_clause = saved_in_case;
2127 self.switch_depth -= 1;
2128 return Err(self.unexpected());
2129 }
2130 match self.parse_statement_list_item() {
2131 Ok(stmt) => body.push(stmt),
2132 Err(error) => {
2133 self.in_case_clause = saved_in_case;
2134 self.switch_depth -= 1;
2135 return Err(error);
2136 }
2137 }
2138 }
2139 self.in_case_clause = saved_in_case;
2140 cases.push(SwitchCase {
2141 test,
2142 body,
2143 span: self.span_from(case_start),
2144 });
2145 }
2146 self.switch_depth -= 1;
2147 self.bump()?; // }
2148 // The switch body's block scope has to be popped here. Leaving it pushed leaked one
2149 // scope per `switch` for the rest of the file, so everything after a switch was
2150 // declared into a *stale* scope: `function f(value){ switch(value){} } let value=9`
2151 // was rejected as "identifier 'value' has already been declared", and the `value`
2152 // it clashed with was the function's own parameter. That made the parser refuse
2153 // valid programs — and it never showed up on its own, only when a top-level `let`
2154 // happened to reuse a name used inside an earlier switch.
2155 self.pop_scope();
2156 Ok(Stmt::new(
2157 StmtKind::Switch {
2158 discriminant: Box::new(discriminant),
2159 cases,
2160 },
2161 self.span_from(start),
2162 ))
2163 }
2164
2165 fn parse_try(&mut self) -> Result<Stmt> {
2166 let start = self.current.span.start;
2167 self.bump()?; // try
2168 let block = self.parse_block()?;
2169 let mut handler = None;
2170 let mut finalizer = None;
2171 if self.at_keyword(Keyword::Catch) {
2172 let catch_start = self.current.span.start;
2173 self.bump()?;
2174 // The catch parameter and the body share one scope, so `catch (e) {
2175 // let e; }` is an early error. A *simple* parameter is exempt from
2176 // the `var` check (`catch (e) { var e; }` is legal), a destructured
2177 // one is not (`catch ({e}) { var e; }` is rejected) — this matches
2178 // the reference engine.
2179 let param = if self.eat_punct(Punct::LParen)? {
2180 let pattern = self.parse_binding_target()?;
2181 self.expect_punct(Punct::RParen)?;
2182 Some(pattern)
2183 } else {
2184 None
2185 };
2186 self.push_scope(Scope::block());
2187 let body = match ¶m {
2188 // A simple parameter shares the body's scope: `catch (e) { let e;
2189 // }` is an error, `catch (e) { var e; }` is not.
2190 Some(Pattern {
2191 kind: PatternKind::Ident(id),
2192 ..
2193 }) => {
2194 if let Some(scope) = self.scopes.last_mut() {
2195 scope.catch_names.push(id.name.clone());
2196 }
2197 self.parse_catch_body()
2198 }
2199 // A destructuring parameter is declared lexically in the clause's
2200 // own scope, with the body nested inside it: `catch ({e}) { var
2201 // e; }` is an error (the `var` hoists past the binding) while
2202 // `catch ({e}) { let e; }` is not.
2203 Some(pattern) => {
2204 self.declare_pattern(pattern, false)?;
2205 self.parse_block()
2206 }
2207 None => self.parse_catch_body(),
2208 };
2209 self.pop_scope();
2210 let body = body?;
2211 handler = Some(CatchClause {
2212 param,
2213 body,
2214 span: self.span_from(catch_start),
2215 });
2216 }
2217 if self.eat_keyword(Keyword::Finally)? {
2218 finalizer = Some(self.parse_block()?);
2219 }
2220 if handler.is_none() && finalizer.is_none() {
2221 return Err(self.error("expecting catch or finally"));
2222 }
2223 Ok(Stmt::new(
2224 StmtKind::Try {
2225 block,
2226 handler,
2227 finalizer,
2228 },
2229 self.span_from(start),
2230 ))
2231 }
2232
2233 fn parse_return(&mut self) -> Result<Stmt> {
2234 let start = self.current.span.start;
2235 let span = self.current.span;
2236 if !self.ctx.in_function {
2237 return Err(self.error_at("return not in a function", span));
2238 }
2239 if self.ctx.in_static_block {
2240 // A static block is written as a block, not a function: `return` has nowhere
2241 // to go. The reference checks this before it consumes the keyword, so the
2242 // error sits on `return` itself.
2243 return Err(self.error_at("return in a static initializer block", span));
2244 }
2245 self.bump()?;
2246 let argument = if self.at_punct(Punct::Semicolon)
2247 || self.at_punct(Punct::RBrace)
2248 || self.current.is_eof()
2249 || self.current.newline_before
2250 {
2251 None
2252 } else {
2253 Some(Box::new(self.parse_expression(true)?))
2254 };
2255 self.semicolon()?;
2256 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
2257 }
2258
2259 fn parse_throw(&mut self) -> Result<Stmt> {
2260 let start = self.current.span.start;
2261 self.bump()?; // throw
2262 if self.current.newline_before {
2263 return Err(self.error("line terminator not allowed after 'throw'"));
2264 }
2265 let argument = self.parse_expression(true)?;
2266 self.semicolon()?;
2267 Ok(Stmt::new(
2268 StmtKind::Throw(Box::new(argument)),
2269 self.span_from(start),
2270 ))
2271 }
2272
2273 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
2274 let start = self.current.span.start;
2275 let keyword_span = self.current.span;
2276 self.bump()?;
2277 let label = if matches!(self.current.kind, TokenKind::Ident(_))
2278 && !self.current.newline_before
2279 {
2280 let ident = self.expect_ident()?;
2281 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
2282 match found {
2283 None => {
2284 return Err(
2285 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2286 );
2287 }
2288 Some(label) => {
2289 if !is_break && label.kind != LabelKind::Iteration {
2290 return Err(self.error_at(
2291 format!("continue must be inside loop (label '{}')", ident.name),
2292 ident.span,
2293 ));
2294 }
2295 }
2296 }
2297 Some(ident)
2298 } else {
2299 if !is_break && self.loop_depth == 0 {
2300 return Err(self.error_at("continue must be inside loop", keyword_span));
2301 }
2302 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2303 {
2304 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2305 }
2306 None
2307 };
2308 self.semicolon()?;
2309 Ok(Stmt::new(
2310 if is_break {
2311 StmtKind::Break(label)
2312 } else {
2313 StmtKind::Continue(label)
2314 },
2315 self.span_from(start),
2316 ))
2317 }
2318
2319 /// A statement in a position that holds exactly one, where the grammar allows no
2320 /// declaration.
2321 ///
2322 /// `if (x) function f(){}` is the Annex B exception (`IfStatement` was extended to
2323 /// accept one) and is handled at the `if`. Everywhere else — the bodies of `with`,
2324 /// `while`, `do`, `for` — a function declaration is a `SyntaxError`, and so is one
2325 /// behind any number of labels: `with({}) label: function f(){}` is the same mistake
2326 /// spelled longer.
2327 fn parse_single_statement(&mut self) -> Result<Stmt> {
2328 let stmt = self.parse_statement()?;
2329 // A labelled function declaration is a `LabelledFunctionStatement`, which the
2330 // statement *list* accepts in sloppy mode; here it is still a declaration in a
2331 // single-statement position.
2332 let mut innermost = &stmt;
2333 while let StmtKind::Labeled { body, .. } = &innermost.kind {
2334 innermost = body;
2335 }
2336 if matches!(innermost.kind, StmtKind::FuncDecl(_)) {
2337 return Err(self.error_at(
2338 "function declarations can't appear in single-statement context",
2339 stmt.span,
2340 ));
2341 }
2342 Ok(stmt)
2343 }
2344
2345 fn parse_with(&mut self) -> Result<Stmt> {
2346 let start = self.current.span.start;
2347 let span = self.current.span;
2348 if self.strict {
2349 return Err(self.error_at("invalid keyword: with", span));
2350 }
2351 self.bump()?; // with
2352 self.expect_punct(Punct::LParen)?;
2353 let object = self.parse_expression(true)?;
2354 self.expect_punct(Punct::RParen)?;
2355 let body = self.parse_single_statement()?;
2356 Ok(Stmt::new(
2357 StmtKind::With {
2358 object: Box::new(object),
2359 body: Box::new(body),
2360 },
2361 self.span_from(start),
2362 ))
2363 }
2364
2365 fn parse_labeled(&mut self) -> Result<Stmt> {
2366 let start = self.current.span.start;
2367 let label = self.expect_ident()?;
2368 self.expect_punct(Punct::Colon)?;
2369 if self.labels.iter().any(|l| l.name == label.name) {
2370 return Err(self.error_at(
2371 format!("label '{}' already declared", label.name),
2372 label.span,
2373 ));
2374 }
2375 let kind = if self.at_keyword(Keyword::For)
2376 || self.at_keyword(Keyword::While)
2377 || self.at_keyword(Keyword::Do)
2378 {
2379 LabelKind::Iteration
2380 } else {
2381 LabelKind::Other
2382 };
2383 self.labels.push(Label {
2384 name: label.name.clone(),
2385 kind,
2386 });
2387 let body = self.parse_statement();
2388 self.labels.pop();
2389 Ok(Stmt::new(
2390 StmtKind::Labeled {
2391 label,
2392 body: Box::new(body?),
2393 },
2394 self.span_from(start),
2395 ))
2396 }
2397
2398 // -- declarations ------------------------------------------------------
2399
2400 fn parse_var_decl(
2401 &mut self,
2402 kind: VarDeclKind,
2403 in_for_head: bool,
2404 require_init: bool,
2405 ) -> Result<VarDecl> {
2406 let start = self.current.span.start;
2407 self.bump()?; // var / let / const / using
2408 self.parse_var_declarators(kind, in_for_head, require_init, start)
2409 }
2410
2411 /// A declaration whose leading keyword has already been consumed by the caller.
2412 ///
2413 /// `await using x = …` is written with two words, so the `await` is read first and only
2414 /// the `using` is left here.
2415 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2416 let start = self.current.span.start;
2417 if !self.at_ident(keyword) {
2418 return Err(self.error(format!("expected '{keyword}'")));
2419 }
2420 self.bump()?;
2421 self.parse_var_declarators(kind, false, true, start)
2422 }
2423
2424 fn parse_var_declarators(
2425 &mut self,
2426 kind: VarDeclKind,
2427 in_for_head: bool,
2428 require_init: bool,
2429 start: Position,
2430 ) -> Result<VarDecl> {
2431 let mut declarators = Vec::new();
2432 loop {
2433 let declarator_start = self.current.span.start;
2434 let target = self.parse_binding_target()?;
2435 // Declared here, before the initialiser: the reference calls `js_define_var`
2436 // from `js_parse_var`'s `set_val`, which is reached with the name just
2437 // consumed, so a redeclaration points at the `=` (or whatever follows)
2438 // rather than at the end of the statement.
2439 self.declare_pattern(&target, !kind.is_lexical())?;
2440 // `using` disposes a value, so it binds a name and nothing else: a pattern has
2441 // no single resource to dispose.
2442 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2443 return Err(self.error_at(
2444 "binding patterns are not allowed in using declarations",
2445 target.span,
2446 ));
2447 }
2448 let init = if self.eat_punct(Punct::Eq)? {
2449 // `for (var x = a in b;;)` must not parse `a in b` as the
2450 // initialiser: the head uses AssignmentExpression[~In].
2451 Some(Box::new(self.parse_assignment(!in_for_head)?))
2452 } else {
2453 None
2454 };
2455 if init.is_none() && require_init {
2456 if kind == VarDeclKind::Const {
2457 return Err(self.error("missing initializer for const variable"));
2458 }
2459 if kind.is_using() {
2460 return Err(self.error("missing initializer in using declaration"));
2461 }
2462 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2463 return Err(self.error_at(
2464 "missing initializer in destructuring declaration",
2465 target.span,
2466 ));
2467 }
2468 }
2469 if kind.is_lexical() {
2470 let mut names = Vec::new();
2471 target.bound_names(&mut names);
2472 if let Some(name) = names.iter().find(|n| n.name == "let") {
2473 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2474 }
2475 }
2476 declarators.push(Declarator {
2477 target,
2478 init,
2479 span: self.span_from(declarator_start),
2480 });
2481 if !self.eat_punct(Punct::Comma)? {
2482 break;
2483 }
2484 }
2485 Ok(VarDecl {
2486 kind,
2487 declarators,
2488 span: self.span_from(start),
2489 })
2490 }
2491
2492 /// A binding element: `target` or `target = default`. Used for parameters and
2493 /// for elements of array/object patterns.
2494 fn parse_binding_element(&mut self) -> Result<Pattern> {
2495 let pattern = self.parse_binding_target()?;
2496 if self.eat_punct(Punct::Eq)? {
2497 let start = pattern.span.start;
2498 let default = self.parse_assignment(self.allow_in)?;
2499 return Ok(Pattern::new(
2500 PatternKind::Assign {
2501 target: Box::new(pattern),
2502 default: Box::new(default),
2503 },
2504 self.span_from(start),
2505 ));
2506 }
2507 Ok(pattern)
2508 }
2509
2510 /// A binding target: `Ident`, `[ … ]` or `{ … }`, with no default value.
2511 /// Used for declarators, `catch` parameters, rest elements and `for` heads.
2512 fn parse_binding_target(&mut self) -> Result<Pattern> {
2513 self.enter()?;
2514 let result = self.parse_binding_target_unguarded();
2515 self.leave();
2516 result
2517 }
2518
2519 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2520 let start = self.current.span.start;
2521 if self.at_punct(Punct::LBracket) {
2522 return self.parse_array_pattern(start);
2523 }
2524 if self.at_punct(Punct::LBrace) {
2525 return self.parse_object_pattern(start);
2526 }
2527 let ident = self.expect_binding_ident()?;
2528 Ok(Pattern::new(
2529 PatternKind::Ident(ident),
2530 self.span_from(start),
2531 ))
2532 }
2533
2534 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2535 self.expect_punct(Punct::LBracket)?;
2536 let mut elements = Vec::new();
2537 let mut rest = None;
2538 loop {
2539 if self.at_punct(Punct::RBracket) {
2540 break;
2541 }
2542 if self.at_punct(Punct::Comma) {
2543 self.bump()?;
2544 elements.push(None);
2545 continue;
2546 }
2547 if self.at_punct(Punct::Ellipsis) {
2548 self.bump()?;
2549 let target = self.parse_binding_target()?;
2550 if self.at_punct(Punct::Comma) {
2551 return Err(self.error("rest element must be the last one"));
2552 }
2553 rest = Some(Box::new(RestElement::Pattern(target)));
2554 break;
2555 }
2556 let element_start = self.current.span.start;
2557 let element = self.parse_binding_element()?;
2558 let span = self.span_from(element_start);
2559 elements.push(Some(PatternElement::Pattern(element)));
2560 let _ = span;
2561 if !self.eat_punct(Punct::Comma)? {
2562 break;
2563 }
2564 }
2565 self.expect_punct(Punct::RBracket)?;
2566 Ok(Pattern::new(
2567 PatternKind::Array { elements, rest },
2568 self.span_from(start),
2569 ))
2570 }
2571
2572 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2573 self.expect_punct(Punct::LBrace)?;
2574 let mut properties = Vec::new();
2575 let mut rest = None;
2576 loop {
2577 if self.at_punct(Punct::RBrace) {
2578 break;
2579 }
2580 if self.at_punct(Punct::Ellipsis) {
2581 self.bump()?;
2582 let target = self.parse_binding_target()?;
2583 rest = Some(Box::new(RestElement::Pattern(target)));
2584 if self.at_punct(Punct::Comma) {
2585 return Err(self.error("rest element must be the last one"));
2586 }
2587 break;
2588 }
2589 let property_start = self.current.span.start;
2590 let key = self.parse_property_key()?;
2591 if self.eat_punct(Punct::Colon)? {
2592 let value = self.parse_binding_element()?;
2593 properties.push(Some(PatternElement::Property {
2594 key,
2595 value,
2596 shorthand: false,
2597 span: self.span_from(property_start),
2598 }));
2599 } else {
2600 let PropName::Literal(PropKey::Str(name)) = &key else {
2601 return Err(
2602 self.error("expecting ':' after a computed or numeric property key")
2603 );
2604 };
2605 let span = self.span_from(property_start);
2606 let ident = Ident {
2607 name: name.to_string_lossy().into_owned(),
2608 span,
2609 };
2610 self.check_binding_name(&ident.name, ident.span)?;
2611 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2612 if self.eat_punct(Punct::Eq)? {
2613 let default = self.parse_assignment(self.allow_in)?;
2614 value = Pattern::new(
2615 PatternKind::Assign {
2616 target: Box::new(value),
2617 default: Box::new(default),
2618 },
2619 span,
2620 );
2621 }
2622 properties.push(Some(PatternElement::Property {
2623 key,
2624 value,
2625 shorthand: true,
2626 span,
2627 }));
2628 }
2629 if !self.eat_punct(Punct::Comma)? {
2630 break;
2631 }
2632 }
2633 self.expect_punct(Punct::RBrace)?;
2634 Ok(Pattern::new(
2635 PatternKind::Object { properties, rest },
2636 self.span_from(start),
2637 ))
2638 }
2639
2640 /// A property key: identifier, string, number, computed or `#private`.
2641 fn parse_property_key(&mut self) -> Result<PropName> {
2642 match self.current.kind.clone() {
2643 TokenKind::Ident(name) => {
2644 self.bump()?;
2645 Ok(PropName::Literal(PropKey::Str(Wtf8::new(name))))
2646 }
2647 TokenKind::Keyword(kw) => {
2648 // Reserved words are valid property names (`{ if: 1 }`).
2649 self.bump()?;
2650 Ok(PropName::Literal(PropKey::Str(Wtf8::new(kw.as_str()))))
2651 }
2652 TokenKind::String(value) => {
2653 self.bump()?;
2654 Ok(PropName::Literal(PropKey::Str(value)))
2655 }
2656 TokenKind::Number(NumberLiteral::Int(v)) => {
2657 self.bump()?;
2658 Ok(PropName::Literal(PropKey::Num(v as f64)))
2659 }
2660 TokenKind::Number(NumberLiteral::Float(v)) => {
2661 self.bump()?;
2662 Ok(PropName::Literal(PropKey::Num(v)))
2663 }
2664 TokenKind::BigInt(big) => Err(self.error(format!(
2665 "BigInt property keys are not supported ('{}n')",
2666 big.digits
2667 ))),
2668 TokenKind::Punct(Punct::LBracket) => {
2669 self.bump()?;
2670 let expr = self.parse_assignment(true)?;
2671 self.expect_punct(Punct::RBracket)?;
2672 Ok(PropName::Computed(Box::new(expr)))
2673 }
2674 TokenKind::Punct(Punct::Hash) => {
2675 let ident = self.parse_private_name()?;
2676 Ok(PropName::Private(ident))
2677 }
2678 // `js_parse_property_name` in the reference: an object literal or a class
2679 // member whose name is not an identifier, string, number or computed key.
2680 _ => Err(self.error("invalid property name")),
2681 }
2682 }
2683
2684 // -- functions ---------------------------------------------------------
2685
2686 /// `function`, `function*`, `async function` or `async function*`.
2687 ///
2688 /// `start` is where the *whole* form begins, which is not where `parse_function` is
2689 /// entered for the async ones: the caller has already consumed `async`, and the
2690 /// reference keeps the position it captured before doing so
2691 /// (`js_parse_expr`'s `source_ptr`). Passing `None` means "the `function` keyword is
2692 /// the start", which is right for the synchronous forms.
2693 fn parse_function(
2694 &mut self,
2695 form: FunctionForm,
2696 is_async: bool,
2697 start: Option<Position>,
2698 ) -> Result<Function> {
2699 let start = start.unwrap_or(self.current.span.start);
2700 self.bump()?; // function
2701 let is_generator = self.eat_punct(Punct::Star)?;
2702 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2703 let ident = if form == FunctionForm::Declaration {
2704 self.expect_binding_ident()?
2705 } else {
2706 self.expect_ident()?
2707 };
2708 if is_generator && ident.name == "yield" {
2709 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2710 }
2711 if is_async && ident.name == "await" {
2712 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2713 }
2714 // §15.2.1: a `BindingIdentifier` may not be `eval` or `arguments` in strict
2715 // code — the same rule `check_binding_name` applies to a `var`/`let`, with the
2716 // function-specific wording the reference uses. A *declaration* reaches it
2717 // through `expect_binding_ident`; an expression name is read with plain
2718 // `expect_ident`, so the check has to be made here for the two to agree.
2719 // Sloppy code keeps `(function eval(){})`, which is legal.
2720 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
2721 return Err(self.error_at("invalid function name in strict code", ident.span));
2722 }
2723 Some(ident)
2724 } else {
2725 if form == FunctionForm::Declaration {
2726 return Err(self.error("function name expected"));
2727 }
2728 None
2729 };
2730 // A function declaration in a *block* is a lexical binding of that block, and the
2731 // reference checks it right here: `js_parse_function_decl2` calls
2732 // `define_var(JS_VAR_DEF_FUNCTION_DECL)` with the name just consumed, so the
2733 // reported position is the token that follows it — `(` for `function a(`. The
2734 // body-scope case is a different check and happens after the whole function, which
2735 // is why it is made at the call site instead.
2736 //
2737 // Doing it here also means a block-level conflict is found before the body is
2738 // parsed, so the body's own errors cannot mask it.
2739 if form == FunctionForm::Declaration
2740 && let Some(ident) = &name
2741 {
2742 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2743 }
2744 let saved = self.ctx;
2745 self.ctx = FnCtx {
2746 in_function: true,
2747 in_generator: is_generator,
2748 in_async: is_async,
2749 in_method: false,
2750 in_derived_constructor: false,
2751 in_static_block: false,
2752 arguments_allowed: true,
2753 };
2754 let saved_top = self.top_level;
2755 self.top_level = false;
2756 // Strictness is per function: `function f(){ "use strict"; }` must leave the
2757 // code *after* it sloppy. Without this save the directive leaked outwards, the
2758 // enclosing script was compiled as strict, and a later `function g(){}` lost its
2759 // declaration status — `typeof g` then raised instead of answering, because an
2760 // implicit global is not a declaration.
2761 let params_result = self.parse_formal_parameters();
2762 let result = match params_result {
2763 Ok(params) => self.parse_function_body(params, false),
2764 Err(err) => Err(err),
2765 };
2766 self.ctx = saved;
2767 self.top_level = saved_top;
2768 let (params, params_span, body, strict) = result?;
2769 // §15.2.1, the *other half* of the function-name rule: a name that was legal when
2770 // it was read becomes illegal if the body turns out to be strict. The check in the
2771 // `name` block above can only see the enclosing mode — `function eval(){ "use
2772 // strict" }` is read while the function is still sloppy — so the body's own mode has
2773 // to be applied afterwards. The reference makes exactly this second check
2774 // (`js_parse_function_decl2`, after the body); without it the four `name-*-strict-body`
2775 // cases in `expressions/function` accepted the declaration.
2776 if strict
2777 && let Some(ident) = &name
2778 && (ident.name == "eval" || ident.name == "arguments")
2779 {
2780 let span = ident.span;
2781 return Err(self.error_at("invalid function name in strict code", span));
2782 }
2783 Ok(Function {
2784 name,
2785 params,
2786 body,
2787 is_async,
2788 is_generator,
2789 strict,
2790 is_arrow: false,
2791 span: self.span_from(start),
2792 params_span,
2793 source_span: None,
2794 })
2795 }
2796
2797 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2798 // Every parameter list, from every entry point (function declaration/expression,
2799 // method, arrow, dynamic `new Function`): the flag makes `yield`/`await` an early
2800 // error there, and is restored on the way out so a *nested* function's body — which
2801 // is also reached from inside a default expression — is unaffected.
2802 let saved = self.in_formal_parameters;
2803 self.in_formal_parameters = true;
2804 let result = self.parse_formal_parameters_inner();
2805 self.in_formal_parameters = saved;
2806 result
2807 }
2808
2809 fn parse_formal_parameters_inner(&mut self) -> Result<Vec<Pattern>> {
2810 self.expect_punct(Punct::LParen)?;
2811 let mut params = Vec::new();
2812 loop {
2813 if self.at_punct(Punct::RParen) {
2814 break;
2815 }
2816 if self.at_punct(Punct::Ellipsis) {
2817 self.bump()?;
2818 // The rest parameter's own binding needs the same check: `function f(...)`
2819 // is a missing parameter, not a malformed one.
2820 if !self.at_formal_parameter() {
2821 return Err(self.error("missing formal parameter"));
2822 }
2823 let target = self.parse_binding_target()?;
2824 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2825 return Err(
2826 self.error_at("rest element cannot have a default value", target.span)
2827 );
2828 }
2829 params.push(Pattern::new(
2830 PatternKind::Rest(Box::new(target.clone())),
2831 target.span,
2832 ));
2833 // A rest parameter ends the list, so the only thing that may follow is
2834 // `)`. The reference simply asks for it: `js_parse_expect(s, ')')`.
2835 if self.at_punct(Punct::Comma) {
2836 return Err(self.error("expecting ')'"));
2837 }
2838 break;
2839 }
2840 if !self.at_formal_parameter() {
2841 return Err(self.error("missing formal parameter"));
2842 }
2843 let param = self.parse_binding_element()?;
2844 self.check_parameter(¶m)?;
2845 params.push(param);
2846 if !self.eat_punct(Punct::Comma)? {
2847 break;
2848 }
2849 }
2850 self.expect_punct(Punct::RParen)?;
2851 Ok(params)
2852 }
2853
2854 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2855 match ¶m.kind {
2856 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2857 PatternKind::Assign { target, .. } => self.check_parameter(target),
2858 _ => Ok(()),
2859 }
2860 }
2861
2862 fn parse_function_body(
2863 &mut self,
2864 params: Vec<Pattern>,
2865 is_method: bool,
2866 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2867 let params_span = self.prev_end;
2868 // Strictness is per function, so the body saves and restores it itself rather
2869 // than trusting every caller to do so: `function f(){ "use strict" }` must
2870 // leave the code after it sloppy, and the enclosing scope may well have been
2871 // strict too. The returned flag is the body's own mode.
2872 let saved_strict = self.strict;
2873 if !self.at_punct(Punct::LBrace) {
2874 return Err(self.unexpected());
2875 }
2876 // A function body is one of the places a `using` may live, so a function defined
2877 // inside a `case` clause starts with a clean slate for that check.
2878 let saved_in_case = self.in_case_clause;
2879 self.in_case_clause = false;
2880 let param_names = simple_parameter_names(¶ms);
2881 let simple_params = params
2882 .iter()
2883 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2884 let mut body = Vec::new();
2885 let mut prologue = true;
2886 let mut strict_seen = false;
2887 self.bump()?; // {
2888 // Where the final duplicate-parameter check points: the reference runs it with the
2889 // body's first token as `s->token`, so an empty body reports the `}` and
2890 // `{ return 1 }` reports the `return`.
2891 let body_start = self.current.span;
2892 self.push_scope(Scope::function(param_names));
2893 while !self.at_punct(Punct::RBrace) {
2894 if self.current.is_eof() {
2895 return Err(self.unexpected());
2896 }
2897 let stmt = self.parse_statement_list_item()?;
2898 if prologue {
2899 match self.directive_value(&stmt) {
2900 Some(directive) if directive == "use strict" => {
2901 strict_seen = true;
2902 self.enter_strict()?;
2903 }
2904 Some(_) => {}
2905 None => prologue = false,
2906 }
2907 }
2908 body.push(stmt);
2909 }
2910 self.pop_scope();
2911 self.bump()?; // }
2912 // The body's own mode, still in force while the early errors below are
2913 // checked; the enclosing mode is restored once they are done.
2914 let body_strict = self.strict;
2915 if strict_seen && !simple_params {
2916 return Err(self.error_at(
2917 // The reference spells the directive with double quotes inside the message.
2918 "\"use strict\" not allowed in function with default or destructuring parameter",
2919 Span::new(params_span, params_span),
2920 ));
2921 }
2922 // Duplicate parameter names. Where they are illegal at all is the reference's
2923 // condition in `js_parse_function_args`: strict mode, a non-simple list, an arrow,
2924 // or a method. A plain sloppy `function f(a, a){}` is legal (last wins), and so is
2925 // a sloppy generator or `async function` — only an async *method* is covered.
2926 //
2927 // Which of the two messages is used depends on how the duplicate was reached, and
2928 // that is a different question: at *parameter-parse* time the reference checks each
2929 // name with `duplicate parameter names`, and it only gets there when the list holds
2930 // an `=` anywhere or the name sits inside a destructuring pattern. Everything else
2931 // waits for the check above, which says `duplicate argument names`.
2932 self.check_duplicate_parameters(
2933 ¶ms,
2934 body_strict || !simple_params || is_method,
2935 body_start,
2936 )?;
2937 // A `"use strict"` directive retroactively makes the parameter list strict, and
2938 // `eval`/`arguments`/`let` may not be binding names there — the list was parsed
2939 // before the directive was seen, so the names have to be re-checked now.
2940 // `function(eval){"use strict"}` is a `SyntaxError`, and so is
2941 // `Function("eval", ""use strict";")` (`15.3.2.1-11-3-s`).
2942 if body_strict && !saved_strict {
2943 for param in ¶ms {
2944 let mut names = Vec::new();
2945 param.bound_names(&mut names);
2946 for name in names {
2947 if name.name == "eval" || name.name == "arguments" || name.name == "let" {
2948 return Err(
2949 self.error_at("invalid variable name in strict mode", name.span)
2950 );
2951 }
2952 }
2953 }
2954 }
2955 let params_span_value = Span::new(params_span, params_span);
2956 self.strict = saved_strict;
2957 self.lexer.set_strict(saved_strict);
2958 self.in_case_clause = saved_in_case;
2959 Ok((
2960 params,
2961 params_span_value,
2962 FunctionBody::Block(body),
2963 body_strict,
2964 ))
2965 }
2966
2967 // -- classes -----------------------------------------------------------
2968
2969 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2970 // "classes are parsed and executed in strict mode" — `js_parse_class` says so by
2971 // setting `JS_MODE_STRICT` before it consumes the `class` token, which makes the
2972 // *name*, the heritage and every member strict, not just the method bodies.
2973 //
2974 // Without this, a method body was parsed sloppy: `class C { m() { x = 1 } }` created
2975 // a global instead of throwing, and every method's `mode:` line in the disassembly
2976 // disagreed with the reference.
2977 let saved_strict = self.strict;
2978 let enter = self.enter_strict();
2979 let result = match enter {
2980 Ok(()) => self.parse_class_body(is_expression),
2981 Err(error) => Err(error),
2982 };
2983 self.strict = saved_strict;
2984 self.lexer.set_strict(saved_strict);
2985 result
2986 }
2987
2988 fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
2989 let start = self.current.span.start;
2990 self.bump()?; // class
2991 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2992 if is_expression {
2993 Some(self.expect_ident()?)
2994 } else {
2995 Some(self.expect_binding_ident()?)
2996 }
2997 } else {
2998 if !is_expression {
2999 return Err(self.error("class statement requires a name"));
3000 }
3001 None
3002 };
3003 let super_class = if self.eat_keyword(Keyword::Extends)? {
3004 Some(Box::new(self.parse_lhs_expression()?))
3005 } else {
3006 None
3007 };
3008 let has_super = super_class.is_some();
3009 self.private.push(PrivateEnv::default());
3010 self.expect_punct(Punct::LBrace)?;
3011 let mut elements = Vec::new();
3012 let mut seen_constructor = false;
3013 let result = (|| -> Result<()> {
3014 while !self.at_punct(Punct::RBrace) {
3015 // No end-of-input guard here: `class A {` must report `invalid property
3016 // name`, which is what falls out of asking for the element's name. An
3017 // early `unexpected()` would pre-empt that with a vaguer message.
3018 if self.eat_punct(Punct::Semicolon)? {
3019 continue;
3020 }
3021 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
3022 }
3023 Ok(())
3024 })();
3025 // Settle the forward references now that the body is complete, bubbling any the
3026 // body did not declare outward: an inner class body may name an outer class's
3027 // private field, and only the outermost body knows the full set.
3028 let settled = match self.private.pop() {
3029 Some(mut env) => {
3030 let mut carried = Vec::new();
3031 for (name, span) in std::mem::take(&mut env.pending) {
3032 if env.contains(&name) {
3033 continue;
3034 }
3035 match self.private.last_mut() {
3036 Some(outer) => outer.pending.push((name, span)),
3037 None => carried.push((name, span)),
3038 }
3039 }
3040 carried
3041 }
3042 None => Vec::new(),
3043 };
3044 if let Some((name, span)) = settled
3045 .into_iter()
3046 .min_by_key(|(_, span)| span.start.offset)
3047 {
3048 return Err(self.error_at(format!("undefined private field '#{name}'"), span));
3049 }
3050 result?;
3051 // The `}` itself, before it is consumed: a class with no written constructor gets
3052 // a synthetic one created *at* this token (see [`Class::body_end`]).
3053 let body_end = self.current.span.start;
3054 self.bump()?; // }
3055 // A class is the *constructor function object*, so `A.toString()` reports the whole
3056 // class definition, not just the `constructor(){}` member — the two are the same
3057 // object, and `Function.prototype.toString` answers with the class's own source
3058 // range (`class-declaration-explicit-ctor`). The span is widened after the body so
3059 // the closing `}` is included, while `params_span` and the line table keep pointing
3060 // at the member itself.
3061 let class_span = self.span_from(start);
3062 for element in &mut elements {
3063 if let ClassElement::Method {
3064 kind: MethodKind::Constructor,
3065 func,
3066 ..
3067 } = element
3068 {
3069 func.source_span = Some(class_span);
3070 }
3071 }
3072 Ok(Class {
3073 name,
3074 super_class,
3075 elements,
3076 span: class_span,
3077 body_end,
3078 })
3079 }
3080
3081 /// `static { … }`, with `static` already consumed and `{` the current token.
3082 ///
3083 /// The body is parsed in a context of its own. It is written as a block, but the
3084 /// reference compiles it as a function, and every early error below follows from
3085 /// that: `this` is the class, `super.x` resolves against the class's home object, but
3086 /// `super()` is not a thing a static block can do and `return` has no function to
3087 /// return from.
3088 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
3089 let saved = self.ctx;
3090 let saved_top = self.top_level;
3091 self.ctx = FnCtx {
3092 in_function: true,
3093 in_generator: false,
3094 in_async: false,
3095 // `super.x` is legal in a static block: its home object is the class.
3096 in_method: true,
3097 in_derived_constructor: false,
3098 in_static_block: true,
3099 arguments_allowed: false,
3100 };
3101 self.top_level = false;
3102 // A class body is strict, so everything in it is — including a static block. The
3103 // restore is unconditional, unlike a `"use strict"` directive's, because the block
3104 // cannot opt out of what the class already decided. `enter_strict` cannot fail
3105 // here (it only objects to an octal literal, and nothing has been scanned yet), but
3106 // it is spelled as a saved result so the context is restored either way.
3107 let saved_strict = self.strict;
3108 let enter = self.enter_strict();
3109 // A `break` or `continue` cannot escape a static block, so the label and loop
3110 // counters start empty.
3111 let saved_loop = self.loop_depth;
3112 let saved_switch = self.switch_depth;
3113 let saved_labels = std::mem::take(&mut self.labels);
3114 self.loop_depth = 0;
3115 self.switch_depth = 0;
3116 let body_start = self.current.span.start;
3117 let body = match enter {
3118 Ok(()) => self.parse_block(),
3119 Err(error) => Err(error),
3120 };
3121 self.strict = saved_strict;
3122 self.lexer.set_strict(saved_strict);
3123 self.ctx = saved;
3124 self.top_level = saved_top;
3125 self.loop_depth = saved_loop;
3126 self.switch_depth = saved_switch;
3127 self.labels = saved_labels;
3128 let body = body?;
3129 Ok(ClassElement::StaticBlock {
3130 body,
3131 body_start,
3132 span: self.span_from(start),
3133 })
3134 }
3135
3136 fn parse_class_element(
3137 &mut self,
3138 has_super: bool,
3139 seen_constructor: &mut bool,
3140 ) -> Result<ClassElement> {
3141 let start = self.current.span.start;
3142 let mut is_static = false;
3143 if self.at_ident("static") {
3144 let peek = self.peek()?;
3145 let is_modifier = !matches!(
3146 peek.kind,
3147 TokenKind::Punct(Punct::LParen)
3148 | TokenKind::Punct(Punct::Eq)
3149 | TokenKind::Punct(Punct::Semicolon)
3150 | TokenKind::Punct(Punct::RBrace)
3151 );
3152 if is_modifier {
3153 self.bump()?; // static
3154 if self.at_punct(Punct::LBrace) {
3155 return self.parse_static_block(start);
3156 }
3157 is_static = true;
3158 }
3159 }
3160 // `Function.prototype.toString` reports a method without its `static` modifier but
3161 // *with* `async`/`*`/`get`/`set`, so the recorded span starts here — the spec's
3162 // `MethodDefinition` grammar excludes exactly `static`.
3163 let reported_start = self.current.span.start;
3164
3165 // Modifiers: async, get, set, *
3166 let mut is_async = false;
3167 let mut is_generator = false;
3168 let mut accessor: Option<MethodKind> = None;
3169 if self.at_ident("async") {
3170 let peek = self.peek()?;
3171 let is_modifier = !matches!(
3172 peek.kind,
3173 TokenKind::Punct(Punct::LParen)
3174 | TokenKind::Punct(Punct::Eq)
3175 | TokenKind::Punct(Punct::Semicolon)
3176 | TokenKind::Punct(Punct::RBrace)
3177 ) && !peek.newline_before;
3178 if is_modifier {
3179 self.bump()?;
3180 is_async = true;
3181 }
3182 }
3183 if self.at_punct(Punct::Star) {
3184 self.bump()?;
3185 is_generator = true;
3186 }
3187 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
3188 let is_get = self.at_ident("get");
3189 let peek = self.peek()?;
3190 if is_property_key_start(&peek.kind) {
3191 self.bump()?;
3192 accessor = Some(if is_get {
3193 MethodKind::Get
3194 } else {
3195 MethodKind::Set
3196 });
3197 }
3198 }
3199 let key = self.parse_property_key()?;
3200
3201 // `#constructor` is not a name a private member may have, in any of its forms — a
3202 // method, an accessor or a field. Reported at the token after the name (`(`, `=`, `;`),
3203 // which is where the reference's `js_parse_error` points.
3204 if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
3205 return Err(self.error("invalid method name"));
3206 }
3207 // Nor may `constructor` carry a method modifier: `constructor` is the one member name
3208 // that has its own production, so a generator, an async method or an accessor called
3209 // `constructor` is `invalid method name`. A `static constructor` is an ordinary
3210 // method, and a field named `constructor` is rejected further down with its own
3211 // message.
3212 if !is_static
3213 && (is_generator || is_async || accessor.is_some())
3214 && matches!(&key, PropName::Literal(PropKey::Str(name)) if name.as_str() == Some("constructor"))
3215 {
3216 return Err(self.error("invalid method name"));
3217 }
3218
3219 // Private names must be registered (duplicates are early errors).
3220 if let PropName::Private(ident) = &key {
3221 if let Some(env) = self.private.last_mut() {
3222 if !env.declare(&ident.name, accessor, is_static) {
3223 return Err(self.error_at(
3224 // The reference words this without the name:
3225 // `js_parse_error(s, "private class field is already defined")`.
3226 "private class field is already defined".to_string(),
3227 ident.span,
3228 ));
3229 }
3230 }
3231 }
3232
3233 if self.at_punct(Punct::LParen) {
3234 let kind = match accessor {
3235 Some(kind) => kind,
3236 None => {
3237 let is_constructor = !is_static
3238 && !is_generator
3239 && !is_async
3240 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s.as_str() == Some("constructor"));
3241 if is_constructor {
3242 if *seen_constructor {
3243 return Err(self.error_at(
3244 "property constructor appears more than once",
3245 self.span_from(start),
3246 ));
3247 }
3248 *seen_constructor = true;
3249 MethodKind::Constructor
3250 } else {
3251 MethodKind::Method
3252 }
3253 }
3254 };
3255 if kind == MethodKind::Constructor && (is_generator || is_async) {
3256 return Err(self.error("a constructor may not be a generator or async"));
3257 }
3258 let saved = self.ctx;
3259 self.ctx = FnCtx {
3260 in_function: true,
3261 in_generator: is_generator,
3262 in_async: is_async,
3263 in_method: true,
3264 in_derived_constructor: kind == MethodKind::Constructor && has_super,
3265 in_static_block: false,
3266 arguments_allowed: true,
3267 };
3268 let saved_top = self.top_level;
3269 self.top_level = false;
3270 let result = (|| -> Result<Function> {
3271 let params = self.parse_formal_parameters()?;
3272 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
3273 Ok(Function {
3274 name: None,
3275 params,
3276 body,
3277 is_async,
3278 is_generator,
3279 strict,
3280 is_arrow: false,
3281 span: Span::new(reported_start, self.prev_end),
3282 params_span,
3283 source_span: None,
3284 })
3285 })();
3286 self.ctx = saved;
3287 self.top_level = saved_top;
3288 let func = result?;
3289 if is_static {
3290 if let PropName::Literal(PropKey::Str(name)) = &key {
3291 if name == "prototype" {
3292 return Err(self.error_at("invalid method name", func.span));
3293 }
3294 }
3295 }
3296 if kind == MethodKind::Get && !func.params.is_empty() {
3297 return Err(self.error_at(
3298 "invalid number of arguments for getter or setter",
3299 func.span,
3300 ));
3301 }
3302 if kind == MethodKind::Set && func.params.len() != 1 {
3303 return Err(self.error_at(
3304 "invalid number of arguments for getter or setter",
3305 func.span,
3306 ));
3307 }
3308 return Ok(ClassElement::Method {
3309 key,
3310 is_static,
3311 kind,
3312 func: Box::new(func),
3313 span: self.span_from(start),
3314 });
3315 }
3316
3317 // Field definition.
3318 if accessor.is_some() {
3319 return Err(self.error("expecting '(' after an accessor name"));
3320 }
3321 if let PropName::Literal(PropKey::Str(name)) = &key {
3322 // §15.7.1: a `FieldDefinition` may not be named `constructor`, and `static`
3323 // does not exempt it — `class C { static constructor; }` is as much an early
3324 // error as the instance form. Only a *method* named `constructor` is special
3325 // (the constructor), and a computed `["constructor"]` is an ordinary name.
3326 // Reading the rule as "the instance constructor's name" let the static form
3327 // through (`fields-literal-name-static-propname-constructor`).
3328 if name == "constructor" {
3329 return Err(self.error("classes may not have a field named 'constructor'"));
3330 }
3331 if name == "prototype" && is_static {
3332 return Err(self.error("classes may not have a static property named 'prototype'"));
3333 }
3334 }
3335 // The initialiser is its own function — it runs per instance, or once for a
3336 // static field, with the class's home object — so it gets its own context. That
3337 // is what makes `super.x` legal in a field but `arguments` and `super()` not.
3338 let saved = self.ctx;
3339 let saved_top = self.top_level;
3340 self.ctx = FnCtx {
3341 in_function: true,
3342 in_generator: false,
3343 in_async: false,
3344 in_method: true,
3345 in_derived_constructor: false,
3346 in_static_block: false,
3347 arguments_allowed: false,
3348 };
3349 self.top_level = false;
3350 let value = self
3351 .eat_punct(Punct::Eq)?
3352 .then(|| self.parse_assignment(true));
3353 self.ctx = saved;
3354 self.top_level = saved_top;
3355 let value = match value {
3356 Some(value) => Some(Box::new(value?)),
3357 None => None,
3358 };
3359 // Fields are terminated by `;`, `}` or a line break.
3360 self.semicolon()?;
3361 Ok(ClassElement::Field {
3362 key,
3363 is_static,
3364 value,
3365 span: self.span_from(start),
3366 })
3367 }
3368
3369 // -- modules -----------------------------------------------------------
3370
3371 fn parse_import_decl(&mut self) -> Result<Stmt> {
3372 let start = self.current.span.start;
3373 self.bump()?; // import
3374 let mut specifiers = Vec::new();
3375 if let TokenKind::String(source) = self.current.kind.clone() {
3376 let source = as_specifier(&source);
3377 self.bump()?;
3378 let attributes = self.parse_import_attributes()?;
3379 self.semicolon()?;
3380 return Ok(Stmt::new(
3381 StmtKind::Import(Box::new(ImportDecl {
3382 specifiers,
3383 source,
3384 attributes,
3385 span: self.span_from(start),
3386 })),
3387 self.span_from(start),
3388 ));
3389 }
3390 // Default import.
3391 if matches!(self.current.kind, TokenKind::Ident(_)) {
3392 let local = self.expect_ident()?;
3393 specifiers.push(ImportSpecifier::Default(local));
3394 if !self.eat_punct(Punct::Comma)? {
3395 return self.finish_import(start, specifiers);
3396 }
3397 }
3398 if self.at_punct(Punct::Star) {
3399 self.bump()?;
3400 if !self.eat_contextual("as")? {
3401 return Err(self.unexpected());
3402 }
3403 let local = self.expect_ident()?;
3404 specifiers.push(ImportSpecifier::Namespace(local));
3405 return self.finish_import(start, specifiers);
3406 }
3407 if self.at_punct(Punct::LBrace) {
3408 self.bump()?;
3409 while !self.at_punct(Punct::RBrace) {
3410 let imported = self.parse_module_name()?;
3411 let local = if self.eat_contextual("as")? {
3412 self.expect_ident()?
3413 } else {
3414 match &imported {
3415 ModuleName::Ident(id) => id.clone(),
3416 ModuleName::Str(_) => {
3417 return Err(self.error_at(
3418 "a string module name must be followed by 'as'",
3419 self.current.span,
3420 ));
3421 }
3422 }
3423 };
3424 specifiers.push(ImportSpecifier::Named { imported, local });
3425 if !self.eat_punct(Punct::Comma)? {
3426 break;
3427 }
3428 }
3429 self.expect_punct(Punct::RBrace)?;
3430 } else if !specifiers.is_empty() {
3431 return Err(self.unexpected());
3432 } else if self.at_punct(Punct::LBrace) {
3433 unreachable!("handled above");
3434 } else {
3435 return Err(self.unexpected());
3436 }
3437 self.finish_import(start, specifiers)
3438 }
3439
3440 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3441 if !self.eat_contextual("from")? {
3442 return Err(self.unexpected());
3443 }
3444 let TokenKind::String(source) = self.current.kind.clone() else {
3445 return Err(self.error("string expected"));
3446 };
3447 let source = as_specifier(&source);
3448 self.bump()?;
3449 let attributes = self.parse_import_attributes()?;
3450 self.semicolon()?;
3451 let span = self.span_from(start);
3452 for specifier in &specifiers {
3453 let local = match specifier {
3454 ImportSpecifier::Default(id) => id,
3455 ImportSpecifier::Namespace(id) => id,
3456 ImportSpecifier::Named { local, .. } => local,
3457 };
3458 // An `ImportedBinding` is a `BindingIdentifier`, and module code is always
3459 // strict, so `import { x as eval }` and `import { arguments } from "m"` are
3460 // early errors (§16.2.1.1). Only `declare_lexical` ran here, which checks for
3461 // duplicates and nothing about the name — so `as eval` was accepted outright and
3462 // the bare form failed later with "Could not find export 'eval'", a *resolution*
3463 // error where the test wants a parse-time one
3464 // (`module-code/early-import-{eval,arguments}` and the `-as-` pair).
3465 self.check_binding_name(&local.name, local.span)?;
3466 self.declare_lexical(&local.name)?;
3467 if let Some(scope) = self.scopes.last_mut()
3468 && !scope.import_names.iter().any(|n| n == &local.name)
3469 {
3470 scope.import_names.push(local.name.clone());
3471 }
3472 }
3473 Ok(Stmt::new(
3474 StmtKind::Import(Box::new(ImportDecl {
3475 specifiers,
3476 source,
3477 attributes,
3478 span,
3479 })),
3480 span,
3481 ))
3482 }
3483
3484 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3485 let mut attributes = Vec::new();
3486 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3487 if !has_with {
3488 return Ok(attributes);
3489 }
3490 let peek = self.peek()?;
3491 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3492 return Ok(attributes);
3493 }
3494 self.bump()?; // with / assert
3495 self.expect_punct(Punct::LBrace)?;
3496 while !self.at_punct(Punct::RBrace) {
3497 let attr_start = self.current.span.start;
3498 let key = match self.current.kind.clone() {
3499 TokenKind::Ident(name) => name,
3500 TokenKind::String(value) => as_specifier(&value),
3501 _ => return Err(self.error("expecting an import attribute name")),
3502 };
3503 self.bump()?;
3504 self.expect_punct(Punct::Colon)?;
3505 let TokenKind::String(value) = self.current.kind.clone() else {
3506 return Err(self.error("expecting an import attribute value string"));
3507 };
3508 let value = as_specifier(&value);
3509 self.bump()?;
3510 attributes.push(ImportAttribute {
3511 key,
3512 value,
3513 span: self.span_from(attr_start),
3514 });
3515 if !self.eat_punct(Punct::Comma)? {
3516 break;
3517 }
3518 }
3519 self.expect_punct(Punct::RBrace)?;
3520 Ok(attributes)
3521 }
3522
3523 fn parse_module_name(&mut self) -> Result<ModuleName> {
3524 match self.current.kind.clone() {
3525 TokenKind::String(value) => {
3526 self.bump()?;
3527 Ok(ModuleName::Str(as_specifier(&value)))
3528 }
3529 // `ModuleExportName : IdentifierName | StringLiteral` — an *IdentifierName*, so
3530 // every reserved word is allowed here and none of the name-position checks
3531 // apply (`export { _await as await }`, `import { if as if_ }`). Going through
3532 // `expect_ident` rejected `await`: the lexer hands it back as an identifier and
3533 // `expect_ident` refuses it in a module, which is the right answer for a
3534 // *binding* and the wrong one for a module export name
3535 // (`module-code/instn-named-id-name`).
3536 TokenKind::Ident(name) => {
3537 let span = self.current.span;
3538 self.bump()?;
3539 Ok(ModuleName::Ident(Ident { name, span }))
3540 }
3541 TokenKind::Keyword(kw) => {
3542 let span = self.current.span;
3543 self.bump()?;
3544 Ok(ModuleName::Ident(Ident {
3545 name: kw.as_str().to_string(),
3546 span,
3547 }))
3548 }
3549 // `export {a as}`: the alias may be an identifier or a string, and the
3550 // reference names both (`js_parse_error(s, "identifier or string expected")`).
3551 _ => Err(self.error("identifier or string expected")),
3552 }
3553 }
3554
3555 fn parse_export_decl(&mut self) -> Result<Stmt> {
3556 let start = self.current.span.start;
3557 self.bump()?; // export
3558 if self.at_punct(Punct::Star) {
3559 self.bump()?;
3560 let mut exported = None;
3561 if self.eat_contextual("as")? {
3562 exported = Some(self.parse_module_name()?);
3563 }
3564 if !self.eat_contextual("from")? {
3565 return Err(self.error("expecting 'from' after 'export *'"));
3566 }
3567 let TokenKind::String(source) = self.current.kind.clone() else {
3568 return Err(self.error("string expected"));
3569 };
3570 let source = as_specifier(&source);
3571 self.bump()?;
3572 let attributes = self.parse_import_attributes()?;
3573 self.semicolon()?;
3574 let span = self.span_from(start);
3575 return Ok(Stmt::new(
3576 StmtKind::Export(Box::new(ExportDecl {
3577 kind: ExportKind::All {
3578 source,
3579 exported,
3580 attributes,
3581 },
3582 span,
3583 })),
3584 span,
3585 ));
3586 }
3587 if self.eat_keyword(Keyword::Default)? {
3588 let value = if self.at_keyword(Keyword::Function) {
3589 let func = self.parse_function(FunctionForm::Expression, false, None)?;
3590 // `export default function F(){}` declares `F` — the export is anonymous but
3591 // the *name* is a binding of the module scope, so a second `F` is a
3592 // `SyntaxError` (`export-default-*-declaration-binding-exists`). It is a
3593 // lexical binding and not a hoisted function declaration: §16.2.3.1 puts a
3594 // `HoistableDeclaration` in `VarDeclaredNames` only under `export
3595 // HoistableDeclaration`, and this production is not that one.
3596 if let Some(name) = &func.name {
3597 self.check_binding_name(&name.name, name.span)?;
3598 self.declare_lexical(&name.name)?;
3599 }
3600 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3601 } else if self.at_ident("async") {
3602 let peek = self.peek()?;
3603 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3604 self.bump()?;
3605 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3606 if let Some(name) = &func.name {
3607 self.check_binding_name(&name.name, name.span)?;
3608 self.declare_lexical(&name.name)?;
3609 }
3610 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3611 } else {
3612 self.parse_assignment(true)?
3613 }
3614 } else if self.at_keyword(Keyword::Class) {
3615 let class = self.parse_class(true)?;
3616 if let Some(name) = &class.name {
3617 self.check_binding_name(&name.name, name.span)?;
3618 self.declare_lexical(&name.name)?;
3619 }
3620 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3621 } else {
3622 let expr = self.parse_assignment(true)?;
3623 self.semicolon()?;
3624 expr
3625 };
3626 let span = self.span_from(start);
3627 return Ok(Stmt::new(
3628 StmtKind::Export(Box::new(ExportDecl {
3629 kind: ExportKind::Default(Box::new(value)),
3630 span,
3631 })),
3632 span,
3633 ));
3634 }
3635 if self.at_keyword(Keyword::Var)
3636 || self.at_keyword(Keyword::Const)
3637 || self.at_keyword(Keyword::Function)
3638 || self.at_keyword(Keyword::Class)
3639 || (self.at_ident("let") && self.let_starts_declaration()?)
3640 {
3641 let decl = self.parse_statement_list_item()?;
3642 let span = self.span_from(start);
3643 return Ok(Stmt::new(
3644 StmtKind::Export(Box::new(ExportDecl {
3645 kind: ExportKind::Declaration(Box::new(decl)),
3646 span,
3647 })),
3648 span,
3649 ));
3650 }
3651 if self.at_ident("async") {
3652 let peek = self.peek()?;
3653 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3654 let decl = self.parse_statement_list_item()?;
3655 let span = self.span_from(start);
3656 return Ok(Stmt::new(
3657 StmtKind::Export(Box::new(ExportDecl {
3658 kind: ExportKind::Declaration(Box::new(decl)),
3659 span,
3660 })),
3661 span,
3662 ));
3663 }
3664 }
3665 if self.at_punct(Punct::LBrace) {
3666 self.bump()?;
3667 let mut specifiers = Vec::new();
3668 let mut candidates: Vec<(String, Span)> = Vec::new();
3669 let mut source = None;
3670 while !self.at_punct(Punct::RBrace) {
3671 let spec_start = self.current.span.start;
3672 let local = self.parse_module_name()?;
3673 let exported = if self.eat_contextual("as")? {
3674 self.parse_module_name()?
3675 } else {
3676 local.clone()
3677 };
3678 // Deferred: whether these name *local* bindings (and so have to be
3679 // checked against the module's declarations) depends on whether a
3680 // `from` follows, which is not known until the closing brace.
3681 if let ModuleName::Ident(id) = &local {
3682 candidates.push((id.name.clone(), id.span));
3683 }
3684 specifiers.push(ExportSpecifier {
3685 local,
3686 exported,
3687 span: self.span_from(spec_start),
3688 });
3689 if !self.eat_punct(Punct::Comma)? {
3690 break;
3691 }
3692 }
3693 self.expect_punct(Punct::RBrace)?;
3694 let mut attributes = Vec::new();
3695 let has_from = self.eat_contextual("from")?;
3696 if !has_from {
3697 // `export { a }` re-exports a binding of this module and must name one;
3698 // `export { a } from "m"` names an export of `m` and is checked when the
3699 // module is linked, not here.
3700 //
3701 // A **string** in the local position has no binding to name at all:
3702 // §16.2.3.1 makes `ReferencedBindings of ExportClause contains any
3703 // StringLiterals` an early error, which is how `export { "foo" as "bar" }`
3704 // is rejected while `export { "foo" as "bar" } from "m"` is fine
3705 // (`export-expname-string-binding`, `…-unpaired-surrogate`).
3706 for specifier in &specifiers {
3707 if matches!(specifier.local, ModuleName::Str(_)) {
3708 return Err(self
3709 .error_at(
3710 "a string export name must be followed by 'from'",
3711 specifier.span,
3712 )
3713 .positionless());
3714 }
3715 }
3716 self.pending_exports.extend(candidates);
3717 }
3718 if has_from {
3719 let TokenKind::String(value) = self.current.kind.clone() else {
3720 return Err(self.error("string expected"));
3721 };
3722 let value = as_specifier(&value);
3723 self.bump()?;
3724 source = Some(value);
3725 attributes = self.parse_import_attributes()?;
3726 }
3727 self.semicolon()?;
3728 let span = self.span_from(start);
3729 return Ok(Stmt::new(
3730 StmtKind::Export(Box::new(ExportDecl {
3731 kind: ExportKind::Named {
3732 specifiers,
3733 source,
3734 attributes,
3735 },
3736 span,
3737 })),
3738 span,
3739 ));
3740 }
3741 Err(self.unexpected())
3742 }
3743
3744 // -- patterns from expressions ----------------------------------------
3745
3746 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3747 self.expr_to_pattern_inner(expr, kind, false)
3748 }
3749
3750 fn expr_to_pattern_inner(
3751 &mut self,
3752 expr: Expr,
3753 kind: TargetKind,
3754 nested: bool,
3755 ) -> Result<Pattern> {
3756 let span = expr.span;
3757 match expr.kind {
3758 ExprKind::Ident(ident) => {
3759 if kind == TargetKind::Binding {
3760 self.check_binding_name(&ident.name, ident.span)?;
3761 } else {
3762 self.check_identifier(&ident.name, ident.span)?;
3763 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3764 return Err(self.error_at(
3765 format!("invalid assignment to '{}' in strict mode", ident.name),
3766 ident.span,
3767 ));
3768 }
3769 }
3770 Ok(Pattern::new(PatternKind::Ident(ident), span))
3771 }
3772 // `(a) = 1` and `(a.b) = 1` are fine — parens do not change a simple target —
3773 // but `({}) = 1` is not: `AssignmentTargetType` of a *ParenthesizedExpression*
3774 // is `simple` only when what it wraps is, and an object or array literal
3775 // becomes a pattern only where the grammar says so, which never sits behind a
3776 // parenthesis. `({} = 1)` is still valid, because there the parens wrap the
3777 // whole assignment and the literal is the direct left-hand side.
3778 ExprKind::Paren(inner) => {
3779 let pattern = self.expr_to_pattern_inner(*inner, kind, nested)?;
3780 if matches!(
3781 pattern.unparen_kind(),
3782 PatternKind::Object { .. } | PatternKind::Array { .. }
3783 ) {
3784 return Err(self.error_at("invalid assignment target", span));
3785 }
3786 Ok(pattern)
3787 }
3788 ExprKind::Array { elements } => {
3789 self.check_spread_trailing_comma(span, "rest element must be the last one")?;
3790 let mut out = Vec::new();
3791 let mut rest = None;
3792 let count = elements.len();
3793 for (index, element) in elements.into_iter().enumerate() {
3794 match element {
3795 None => out.push(None),
3796 Some(ArrayElement::Expr(expr)) => {
3797 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3798 out.push(Some(PatternElement::Pattern(pattern)));
3799 }
3800 Some(ArrayElement::Spread(expr)) => {
3801 if index + 1 != count {
3802 return Err(
3803 self.error_at("rest element must be the last one", expr.span)
3804 );
3805 }
3806 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3807 }
3808 }
3809 }
3810 Ok(Pattern::new(
3811 PatternKind::Array {
3812 elements: out,
3813 rest,
3814 },
3815 span,
3816 ))
3817 }
3818 ExprKind::Object(properties) => {
3819 self.check_spread_trailing_comma(span, "assignment rest property must be last")?;
3820 self.cover_inits
3821 .retain(|cover| !span_contains(span, *cover));
3822 let mut out = Vec::new();
3823 let mut rest = None;
3824 let count = properties.len();
3825 for (index, property) in properties.into_iter().enumerate() {
3826 match property {
3827 ObjectProperty::Spread(expr) => {
3828 if index + 1 != count {
3829 return Err(
3830 self.error_at("rest element must be the last one", expr.span)
3831 );
3832 }
3833 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3834 }
3835 ObjectProperty::Property {
3836 key,
3837 value,
3838 kind: _,
3839 shorthand,
3840 span,
3841 } => {
3842 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3843 out.push(Some(PatternElement::Property {
3844 key,
3845 value: pattern,
3846 shorthand,
3847 span,
3848 }));
3849 }
3850 }
3851 }
3852 Ok(Pattern::new(
3853 PatternKind::Object {
3854 properties: out,
3855 rest,
3856 },
3857 span,
3858 ))
3859 }
3860 ExprKind::Assign { op, target, value } if op.is_simple() => {
3861 // `{a = 1}` inside a pattern: the target must itself be a pattern.
3862 let target = match target.kind {
3863 PatternKind::Ident(ident) => {
3864 // The name checks the bare-identifier arm below runs have to run
3865 // here too, because this arm copies the identifier straight into a
3866 // pattern instead of recursing. `{ eval = 0 } = {}` is a
3867 // `SyntaxError` in strict mode for exactly that reason
3868 // (`obj-id-init-simple-strict`), and a shorthand with a default is
3869 // the only way to reach a pattern target without passing through
3870 // the other arm.
3871 self.check_target_name(&ident.name, ident.span, kind)?;
3872 Pattern::new(PatternKind::Ident(ident), target.span)
3873 }
3874 other => {
3875 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3876 self.expr_to_pattern_inner(expr, kind, nested)?
3877 }
3878 };
3879 Ok(Pattern::new(
3880 PatternKind::Assign {
3881 target: Box::new(target),
3882 default: value,
3883 },
3884 span,
3885 ))
3886 }
3887 ExprKind::Member {
3888 object,
3889 property,
3890 optional,
3891 } => {
3892 if kind == TargetKind::Binding {
3893 return Err(self.error_at("invalid binding pattern", span));
3894 }
3895 if optional {
3896 return Err(self.error_at("invalid assignment target", span));
3897 }
3898 let op_pos = expr.op_pos;
3899 Ok(Pattern::new(
3900 PatternKind::Member(Box::new(MemberPattern {
3901 object,
3902 property,
3903 span,
3904 op_pos,
3905 })),
3906 span,
3907 ))
3908 }
3909 ExprKind::OptionalChain(_) => {
3910 Err(self.error_at("invalid assignment left-hand side", span))
3911 }
3912 // QuickJS reports `a() = 1` at run time (it evaluates the callee
3913 // first, then rejects the reference) but rejects the same thing
3914 // inside a destructuring pattern at parse time. Every other
3915 // non-assignable expression is rejected here.
3916 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3917 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3918 ),
3919 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3920 // Inside an object or array literal being reinterpreted as a pattern the
3921 // reference says `invalid destructuring target`; a non-reference at the top
3922 // level of an assignment says `invalid assignment left-hand side`. `nested` is
3923 // exactly that distinction — `[1] = 2` is the first, `1 = 2` the second.
3924 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3925 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3926 }
3927 }
3928
3929 /// Reject a literal recorded as `[…spread,]` now that it has turned out to be a
3930 /// destructuring pattern.
3931 fn check_spread_trailing_comma(&mut self, span: Span, message: &str) -> Result<()> {
3932 if let Some(position) = self.spread_trailing_comma.iter().position(|s| *s == span) {
3933 self.spread_trailing_comma.remove(position);
3934 return Err(self.error_at(message, span));
3935 }
3936 // Anything nested inside is consumed by its own conversion, so a leftover can only
3937 // belong to a literal that never became a pattern; dropping those keeps the table
3938 // from growing across a whole script.
3939 self.spread_trailing_comma
3940 .retain(|candidate| !span_contains(span, *candidate));
3941 Ok(())
3942 }
3943
3944 /// The early errors on a name used as an assignment or binding target.
3945 ///
3946 /// Shared by the two paths that turn an identifier into a pattern: a bare one, and the
3947 /// target of a shorthand default (`{a = 1}`), which does not recurse.
3948 fn check_target_name(&mut self, name: &str, span: Span, kind: TargetKind) -> Result<()> {
3949 if kind == TargetKind::Binding {
3950 self.check_binding_name(name, span)?;
3951 } else {
3952 self.check_identifier(name, span)?;
3953 if self.strict && (name == "eval" || name == "arguments") {
3954 return Err(self.error_at(
3955 format!("invalid assignment to '{name}' in strict mode"),
3956 span,
3957 ));
3958 }
3959 }
3960 Ok(())
3961 }
3962
3963 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3964 // Array and object literals wrap their spread elements, so the target is
3965 // one level in.
3966 let expr = match expr.kind {
3967 ExprKind::Spread(inner) => *inner,
3968 other => Expr::new(other, expr.span),
3969 };
3970 // `[...x = 1] = []`. The literal form is a *spread of an assignment*, which is
3971 // legal, so this is where the pattern reading has to refuse it: §14.3's
3972 // `RestElement : ... BindingIdentifier` has no room for an initializer, and the
3973 // reference says the same in `js_parse_destructuring_element`.
3974 if let ExprKind::Assign { op, .. } = &expr.unparen().kind
3975 && op.is_simple()
3976 {
3977 return Err(self.error_at("rest element cannot have a default value", expr.span));
3978 }
3979 if kind == TargetKind::Binding {
3980 return Ok(RestElement::Pattern(
3981 self.expr_to_pattern_inner(expr, kind, true)?,
3982 ));
3983 }
3984 match &expr.kind {
3985 ExprKind::Member { optional, .. } => {
3986 if *optional {
3987 return Err(self.error_at("invalid assignment target", expr.span));
3988 }
3989 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3990 PatternKind::Member(member) => Ok(RestElement::Member(member)),
3991 _ => unreachable!("member expressions convert to member patterns"),
3992 }
3993 }
3994 _ => Ok(RestElement::Pattern(
3995 self.expr_to_pattern_inner(expr, kind, true)?,
3996 )),
3997 }
3998 }
3999
4000 // -- expressions -------------------------------------------------------
4001
4002 /// `Expression` (comma separated).
4003 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
4004 self.enter()?;
4005 let result = self.parse_expression_unguarded(allow_in);
4006 self.leave();
4007 result
4008 }
4009
4010 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
4011 // The flag is threaded down as an argument, but a few decisions in `parse_primary`
4012 // have no argument to read it from — `#x in o` is one. Mirroring it into the field
4013 // keeps those decisions able to see it, which is what makes `for (#f in v;;)` fail on
4014 // the `#f` instead of somewhere further along.
4015 let saved_allow_in = self.allow_in;
4016 self.allow_in = allow_in;
4017 let result = self.parse_expression_in(allow_in);
4018 self.allow_in = saved_allow_in;
4019 result
4020 }
4021
4022 fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
4023 let start = self.current.span.start;
4024 let first = self.parse_assignment(allow_in)?;
4025 if !self.at_punct(Punct::Comma) {
4026 return Ok(first);
4027 }
4028 let mut items = vec![first];
4029 while self.eat_punct(Punct::Comma)? {
4030 items.push(self.parse_assignment(allow_in)?);
4031 }
4032 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
4033 }
4034
4035 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
4036 let start = self.current.span.start;
4037
4038 // `yield` in a generator — but never in its own formal parameters
4039 // (§15.5.1: `FormalParameters Contains YieldExpression` is a `SyntaxError`).
4040 if self.ctx.in_generator && self.at_ident("yield") {
4041 if self.in_formal_parameters {
4042 return Err(self.error_at("yield in default expression", self.current.span));
4043 }
4044 return self.parse_yield(allow_in);
4045 }
4046
4047 let lhs = match self.try_parse_arrow(allow_in)? {
4048 Some(arrow) => return Ok(arrow),
4049 None => self.parse_conditional(allow_in)?,
4050 };
4051
4052 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
4053 let op_pos = self.current.span.start;
4054 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
4055 self.bump()?;
4056 let value = self.parse_assignment(allow_in)?;
4057 return Ok(Expr::at_operator(
4058 ExprKind::Assign {
4059 op,
4060 target: Box::new(target),
4061 value: Box::new(value),
4062 },
4063 self.span_from(start),
4064 op_pos,
4065 ));
4066 }
4067 let _ = start;
4068 Ok(lhs)
4069 }
4070
4071 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
4072 let start = self.current.span.start;
4073 self.bump()?; // yield
4074 let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
4075 self.bump()?;
4076 true
4077 } else {
4078 false
4079 };
4080 let argument = if delegate {
4081 Some(Box::new(self.parse_assignment(allow_in)?))
4082 } else if self.current.newline_before
4083 || self.at_punct(Punct::RParen)
4084 || self.at_punct(Punct::RBracket)
4085 || self.at_punct(Punct::RBrace)
4086 || self.at_punct(Punct::Comma)
4087 || self.at_punct(Punct::Semicolon)
4088 || self.at_punct(Punct::Colon)
4089 || self.current.is_eof()
4090 {
4091 None
4092 } else {
4093 Some(Box::new(self.parse_assignment(allow_in)?))
4094 };
4095 Ok(Expr::new(
4096 ExprKind::Yield { argument, delegate },
4097 self.span_from(start),
4098 ))
4099 }
4100
4101 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
4102 let starts_paren = self.at_punct(Punct::LParen);
4103 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
4104 if !starts_paren && !starts_ident {
4105 return Ok(None);
4106 }
4107 // `(` could be a parenthesised expression instead of a parameter list.
4108 // Scanning ahead for the matching `)` and looking for `=>` avoids the
4109 // speculative parse (and its stack cost) in the common case.
4110 if starts_paren && !self.arrow_follows_paren()? {
4111 return Ok(None);
4112 }
4113 let snapshot = self.snapshot();
4114 let head = match self.parse_arrow_head() {
4115 Ok(head) => head,
4116 Err(error) => {
4117 // `arrow_follows_paren` already saw the `=>` for the parenthesised form, and
4118 // `arrow_head_committed` says the same for both forms; either way this *is*
4119 // an arrow and the error is the real one. Restoring and reporting whatever
4120 // the expression interpretation tripped over instead gave "expecting ';'"
4121 // for `(eval) => 1` and for `eval => 1` under `"use strict"`.
4122 self.restore(snapshot);
4123 if starts_paren || self.arrow_head_committed {
4124 return Err(error);
4125 }
4126 return Ok(None);
4127 }
4128 };
4129 let Some(head) = head else {
4130 self.restore(snapshot);
4131 return Ok(None);
4132 };
4133 // Committed: `=>` has been consumed, so errors from here on are real.
4134 // Arrow parameter lists may never repeat a name, in any mode. The message is the
4135 // same one `js_parse_function_args` uses, with no name appended — an earlier
4136 // version added ` ('a')`, which the reference does not print. The position is the
4137 // body's first token: `(a, a) => x` points at the `x`, and `(a, a) => {}` at the
4138 // `}`, because the reference has already consumed the `{` by then.
4139 let body_start = if self.at_punct(Punct::LBrace) {
4140 self.peek()?.span
4141 } else {
4142 self.current.span
4143 };
4144 self.check_duplicate_parameters(&head.params, true, body_start)?;
4145 let saved_ctx = self.ctx;
4146 let saved_loop = self.loop_depth;
4147 let saved_switch = self.switch_depth;
4148 let saved_labels = std::mem::take(&mut self.labels);
4149 let saved_top = self.top_level;
4150 self.ctx = FnCtx {
4151 in_function: true,
4152 in_generator: false,
4153 in_async: head.is_async,
4154 in_method: saved_ctx.in_method,
4155 in_derived_constructor: saved_ctx.in_derived_constructor,
4156 // An arrow is not a static block, so it gets its own `return` and `await` is
4157 // an ordinary name again — but it has no `arguments` of its own, so the ban
4158 // travels with it.
4159 in_static_block: false,
4160 arguments_allowed: saved_ctx.arguments_allowed,
4161 };
4162 self.loop_depth = 0;
4163 self.switch_depth = 0;
4164 self.top_level = false;
4165 let body_start = self.current.span.start;
4166 let (body, strict) = if self.at_punct(Punct::LBrace) {
4167 let (block, strict) = self.parse_arrow_block(&head.params)?;
4168 (block, (self.prev_end, strict))
4169 } else {
4170 let expr = self.parse_assignment(allow_in)?;
4171 let end = expr.span.end;
4172 // An expression body has no directive prologue, so it inherits.
4173 let strict = self.strict;
4174 (FunctionBody::Expr(Box::new(expr)), (end, strict))
4175 };
4176 self.ctx = saved_ctx;
4177 self.loop_depth = saved_loop;
4178 self.switch_depth = saved_switch;
4179 self.labels = saved_labels;
4180 self.top_level = saved_top;
4181 let _ = body_start;
4182 let (body, (end, strict)) = (body, strict);
4183 let span = Span::new(head.span.start, end);
4184 Ok(Some(Expr::new(
4185 ExprKind::Arrow(Box::new(Function {
4186 name: None,
4187 params: head.params,
4188 body,
4189 is_async: head.is_async,
4190 is_generator: false,
4191 strict,
4192 is_arrow: true,
4193 span,
4194 params_span: head.params_span,
4195 source_span: None,
4196 })),
4197 span,
4198 )))
4199 }
4200
4201 /// Parse the `{ … }` body of an arrow, honouring a `"use strict"` prologue.
4202 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
4203 // Like a function body: the arrow's own directive governs the arrow, and the
4204 // enclosing scope's mode is restored afterwards.
4205 let saved_strict = self.strict;
4206 let params_span = self.prev_end;
4207 // §15.3.1: `"use strict"` may not appear in a function whose parameter list is not
4208 // a `SimpleParameterList`, because a non-simple list is evaluated *before* the
4209 // directive could take effect — `[a] = a` in the parameters of a strict function
4210 // would be evaluated in the wrong mode. This is the same rule
4211 // `parse_function_body` applies, and an arrow body reaches it through this
4212 // function instead, which is why `(a, ...rest) => { "use strict"; }` used to be
4213 // accepted.
4214 let simple_params = params
4215 .iter()
4216 .all(|pattern| matches!(pattern.unparen_kind(), PatternKind::Ident(_)));
4217 self.expect_punct(Punct::LBrace)?;
4218 self.push_scope(Scope::function(simple_parameter_names(params)));
4219 let mut strict_seen = false;
4220 let result = (|| -> Result<Vec<Stmt>> {
4221 let mut body = Vec::new();
4222 let mut prologue = true;
4223 while !self.at_punct(Punct::RBrace) {
4224 if self.current.is_eof() {
4225 return Err(self.unexpected());
4226 }
4227 let stmt = self.parse_statement_list_item()?;
4228 if prologue {
4229 match self.directive_value(&stmt) {
4230 Some(directive) if directive == "use strict" => {
4231 strict_seen = true;
4232 self.enter_strict()?;
4233 }
4234 Some(_) => {}
4235 None => prologue = false,
4236 }
4237 }
4238 body.push(stmt);
4239 }
4240 Ok(body)
4241 })();
4242 self.pop_scope();
4243 let body_strict = self.strict;
4244 self.strict = saved_strict;
4245 self.lexer.set_strict(saved_strict);
4246 let body = result?;
4247 if strict_seen && !simple_params {
4248 return Err(self.error_at(
4249 "\"use strict\" not allowed in function with default or destructuring parameter",
4250 Span::new(params_span, params_span),
4251 ));
4252 }
4253 self.bump()?;
4254 Ok((FunctionBody::Block(body), body_strict))
4255 }
4256
4257 /// Whether the parenthesis at the current token is the parameter list of an
4258 /// arrow function, i.e. the matching `)` is followed by `=>`.
4259 ///
4260 /// This is a plain token walk with a bracket counter: no recursion, so it
4261 /// costs a clone of the lexer and nothing else.
4262 fn arrow_follows_paren(&self) -> Result<bool> {
4263 let mut lexer = self.lexer.clone();
4264 // The opening `(` was already consumed by the caller.
4265 let mut depth = 1usize;
4266 // How many template-literal substitutions the walk is inside.
4267 let mut template_depth = 0usize;
4268 loop {
4269 let token = lexer.next_token()?;
4270 match token.kind {
4271 TokenKind::Eof => return Ok(false),
4272 // A `/` may open a regular expression literal, and this scan has to agree
4273 // with the parser about which it is. A pattern can contain `(`, `)` and `[`
4274 // without balancing them, and lexing one as division also made the
4275 // pattern's characters into tokens — `(/😀/)` was a `SyntaxError` about an
4276 // identifier, because `😀` is not one. Re-scan from the slash; if no pattern
4277 // terminates on this line there is none, and the scan carries on after the
4278 // `/` exactly as division did.
4279 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4280 if lexer.re_scan_regex(token.span.start).is_err() {
4281 lexer.reset_to(token.span.end);
4282 }
4283 }
4284 // A template literal is **not** a single token to this walk: a head chunk
4285 // ends at `${`, so the substitution's tokens follow as ordinary ones and
4286 // the `}` that closes it has to resume the template rather than close a
4287 // brace. Without this, `(function(){ let s = \`${1}\`; })` — any template
4288 // with a substitution inside a parenthesised expression — made the walk
4289 // lex the tail of the template as code and fail with
4290 // `unexpected end of string` before the caller ever got an answer.
4291 TokenKind::Template(chunk) => match chunk.kind {
4292 // `` `text` `` — one token, nothing follows it.
4293 crate::token::TemplateKind::NoSubstitution => {}
4294 // `` `text${ `` — open a substitution level.
4295 crate::token::TemplateKind::Head => template_depth += 1,
4296 // `}text${` — the `}` closed one level and opened another: no change.
4297 crate::token::TemplateKind::Middle => {}
4298 // ``}text` `` — the substitution level is closed.
4299 crate::token::TemplateKind::Tail => {
4300 template_depth = template_depth.saturating_sub(1);
4301 }
4302 },
4303 TokenKind::Punct(Punct::LParen)
4304 | TokenKind::Punct(Punct::LBracket)
4305 | TokenKind::Punct(Punct::LBrace) => depth += 1,
4306 TokenKind::Punct(Punct::RBrace) if template_depth > 0 => {
4307 // This `}` ends a substitution: re-scan it as a template continuation,
4308 // which is what the parser itself does.
4309 template_depth -= 1;
4310 let token = lexer.re_scan_template_continue(token.span.start)?;
4311 if matches!(
4312 token.kind,
4313 TokenKind::Template(crate::token::TemplateToken {
4314 kind: crate::token::TemplateKind::Head
4315 | crate::token::TemplateKind::Middle,
4316 ..
4317 })
4318 ) {
4319 template_depth += 1;
4320 }
4321 }
4322 TokenKind::Punct(Punct::RParen)
4323 | TokenKind::Punct(Punct::RBracket)
4324 | TokenKind::Punct(Punct::RBrace) => {
4325 if depth == 0 {
4326 // Unbalanced input: the caller reports it.
4327 return Ok(false);
4328 }
4329 depth -= 1;
4330 if depth == 0 {
4331 // The current token is the opening `(`, so the matching
4332 // `)` is the token that brought us back to zero.
4333 let next = lexer.next_token()?;
4334 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
4335 && !next.newline_before);
4336 }
4337 }
4338 _ => {}
4339 }
4340 }
4341 }
4342
4343 /// Speculatively parse an arrow head, consuming `=>` on success.
4344 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
4345 let start = self.current.span.start;
4346 self.arrow_head_committed = false;
4347 let mut is_async = false;
4348 if self.at_ident("async") {
4349 let peek = self.peek()?;
4350 if peek.newline_before {
4351 return Ok(None);
4352 }
4353 let plausible =
4354 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
4355 if !plausible {
4356 return Ok(None);
4357 }
4358 self.bump()?;
4359 is_async = true;
4360 }
4361 let params_start = self.current.span.start;
4362 // An async arrow's parameter list is parsed **in async mode**, which is what makes
4363 // `await` an operator there rather than a name. The reference reaches the same
4364 // place from the other direction — it detects `async (…) =>` before parsing the
4365 // parenthesis and starts a whole async function — so `async(await) => {}` and
4366 // `async(x = await) => {}` are early errors on both engines. Without the flag the
4367 // cover grammar accepted every one of them (`expressions/async-arrow-function`).
4368 //
4369 // Only the parameter list: the body's own context is built by the caller, which is
4370 // where a non-async nested arrow gets `in_async: false` again — so the `await` in
4371 // `async(a = () => await) => {}` stays an ordinary identifier.
4372 let saved_ctx = self.ctx;
4373 if is_async {
4374 self.ctx.in_async = true;
4375 self.ctx.in_generator = false;
4376 }
4377 let params = if self.at_punct(Punct::LParen) {
4378 self.parse_formal_parameters()
4379 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
4380 self.expect_ident().map(|ident| {
4381 vec![Pattern::new(
4382 PatternKind::Ident(ident),
4383 self.span_from(params_start),
4384 )]
4385 })
4386 } else {
4387 self.ctx = saved_ctx;
4388 return Ok(None);
4389 };
4390 self.ctx = saved_ctx;
4391 let params = params?;
4392 let params_span = self.span_from(params_start);
4393 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
4394 return Ok(None);
4395 }
4396 self.bump()?; // =>
4397 self.arrow_head_committed = true;
4398 // `eval => 1` is a one-parameter list, so the parameter rules apply to it exactly
4399 // as they do to `(eval) => 1`. The parenthesised form is checked inside
4400 // `parse_formal_parameters`; this covers the bare identifier, which used to skip
4401 // the check entirely (`arrowparameters-bindingidentifier-no-eval`). Done after the
4402 // `=>` because only then is the head known to be an arrow, and an error is final.
4403 //
4404 // `in_formal_parameters` again while checking, so the message is the parameter
4405 // wording ("invalid argument name in strict code") rather than the variable one.
4406 let saved_formals = self.in_formal_parameters;
4407 self.in_formal_parameters = true;
4408 let checked = params
4409 .iter()
4410 .try_for_each(|param| self.check_parameter(param));
4411 self.in_formal_parameters = saved_formals;
4412 checked?;
4413 Ok(Some(ArrowHead {
4414 params,
4415 is_async,
4416 span: self.span_from(start),
4417 params_span,
4418 }))
4419 }
4420
4421 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
4422 let start = self.current.span.start;
4423 let test = self.parse_binary(allow_in, 0)?;
4424 if !self.at_punct(Punct::Question) {
4425 return Ok(test);
4426 }
4427 self.bump()?;
4428 let consequent = self.parse_assignment(true)?;
4429 self.expect_punct(Punct::Colon)?;
4430 let alternate = self.parse_assignment(allow_in)?;
4431 Ok(Expr::new(
4432 ExprKind::Conditional {
4433 test: Box::new(test),
4434 cons: Box::new(consequent),
4435 alt: Box::new(alternate),
4436 },
4437 self.span_from(start),
4438 ))
4439 }
4440
4441 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
4442 let start = self.current.span.start;
4443 let mut lhs = self.parse_unary()?;
4444 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
4445 if prec < min_prec {
4446 break;
4447 }
4448 let op_pos = self.current.span.start;
4449 self.bump()?;
4450 let next_min = if op.is_right_associative() {
4451 prec
4452 } else {
4453 prec + 1
4454 };
4455 let rhs = self.parse_binary(allow_in, next_min)?;
4456 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
4457 }
4458 Ok(lhs)
4459 }
4460
4461 /// Unary and postfix operators. `in` is handled by the binary layer, so no
4462 /// `allow_in` flag is needed here.
4463 fn parse_unary(&mut self) -> Result<Expr> {
4464 let start = self.current.span.start;
4465 // Unary operators.
4466 let unary = match &self.current.kind {
4467 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
4468 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
4469 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
4470 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
4471 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
4472 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
4473 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
4474 _ => None,
4475 };
4476 if let Some(op) = unary {
4477 let op_pos = self.current.span.start;
4478 self.bump()?;
4479 let argument = self.parse_unary()?;
4480 if op == UnaryOp::Delete && self.strict {
4481 if let ExprKind::Ident(ident) = &argument.unparen().kind {
4482 return Err(self.error_at(
4483 "cannot delete a direct reference in strict mode",
4484 ident.span,
4485 ));
4486 }
4487 }
4488 // `delete obj.#x` is an early error in *any* mode, and so is the "covered" form:
4489 // the spec rule applies to the derived expression through any number of
4490 // parentheses, through the last element of a sequence, and to the callee of a
4491 // call. Missing the covered forms let those programs run, and `$DONOTEVALUATE()`
4492 // is what the test suite then reported instead of a `SyntaxError`.
4493 if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
4494 // Reported at the token *after* the operand, which is where the reference
4495 // reports it: `js_parse_delete` finishes parsing the expression and then calls
4496 // `js_parse_error`, whose position is `s->token`.
4497 return Err(self.error("cannot delete a private class field"));
4498 }
4499 let expr = Expr::at_operator(
4500 ExprKind::Unary {
4501 op,
4502 argument: Box::new(argument),
4503 },
4504 self.span_from(start),
4505 op_pos,
4506 );
4507 if self.at_punct(Punct::StarStar) {
4508 return Err(self.error(
4509 // The reference's wording, from `js_parse_error` in the `**` check.
4510 "unparenthesized unary expression can't appear on the left-hand side of '**'",
4511 ));
4512 }
4513 return Ok(expr);
4514 }
4515 // Prefix increment/decrement.
4516 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
4517 let op_pos = self.current.span.start;
4518 let op = if self.at_punct(Punct::PlusPlus) {
4519 UpdateOp::Increment
4520 } else {
4521 UpdateOp::Decrement
4522 };
4523 self.bump()?;
4524 let argument = self.parse_unary()?;
4525 self.check_simple_target(&argument)?;
4526 return Ok(Expr::at_operator(
4527 ExprKind::Update {
4528 op,
4529 argument: Box::new(argument),
4530 prefix: true,
4531 },
4532 self.span_from(start),
4533 op_pos,
4534 ));
4535 }
4536 // `await` wherever the enclosing function is `async`, operator or not.
4537 //
4538 // There is no "unless the next token rules it out" case: the reference reaches
4539 // `TOK_AWAIT` and consumes it unconditionally, so `await;` and `f(await)` report
4540 // the *operand* as unexpected rather than treating `await` as an identifier. That
4541 // is why this asks nothing about what follows.
4542 if self.at_ident("await") && self.ctx.in_async {
4543 // §15.8.1: `async` functions may not have an `AwaitExpression` in their own
4544 // formal parameters, so `new AsyncFunction("x = await 1", "")` is an error.
4545 if self.in_formal_parameters {
4546 return Err(self.error_at("await in default expression", self.current.span));
4547 }
4548 self.bump()?;
4549 let argument = self.parse_unary()?;
4550 return Ok(Expr::new(
4551 ExprKind::Await(Box::new(argument)),
4552 self.span_from(start),
4553 ));
4554 }
4555 let expr = self.parse_lhs_expression()?;
4556 // Postfix increment/decrement (no line break allowed before the operator).
4557 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
4558 && !self.current.newline_before
4559 {
4560 let op_pos = self.current.span.start;
4561 let op = if self.at_punct(Punct::PlusPlus) {
4562 UpdateOp::Increment
4563 } else {
4564 UpdateOp::Decrement
4565 };
4566 self.check_simple_target(&expr)?;
4567 self.bump()?;
4568 Expr::at_operator(
4569 ExprKind::Update {
4570 op,
4571 argument: Box::new(expr),
4572 prefix: false,
4573 },
4574 self.span_from(start),
4575 op_pos,
4576 )
4577 } else {
4578 expr
4579 };
4580 Ok(result)
4581 }
4582
4583 /// The operand of `++`/`--`, which must be a plain reference.
4584 ///
4585 /// Its own message, not the assignment one: the reference rejects `++1` and `1++` with
4586 /// `js_parse_error(s, "invalid increment/decrement operand")`.
4587 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
4588 match &expr.unparen().kind {
4589 // `eval++` is the same early error as `eval = 1`: §13.4 and §13.15 both fold
4590 // the operand through `AssignmentTargetType`, so the strict-mode ban covers
4591 // increment and decrement as well as assignment. Only the assignment path
4592 // checked it, which is why `"use strict"; eval++` was accepted
4593 // (`expressions/postfix-increment/eval`).
4594 ExprKind::Ident(ident) => {
4595 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
4596 return Err(self.error_at(
4597 format!("invalid assignment to '{}' in strict mode", ident.name),
4598 ident.span,
4599 ));
4600 }
4601 Ok(())
4602 }
4603 ExprKind::Member {
4604 optional: false, ..
4605 } => Ok(()),
4606 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
4607 }
4608 }
4609
4610 fn parse_lhs_expression(&mut self) -> Result<Expr> {
4611 let start = self.current.span.start;
4612 let mut expr = if self.at_keyword(Keyword::New) {
4613 self.parse_new_expression()?
4614 } else {
4615 self.parse_primary()?
4616 };
4617 let mut saw_optional = false;
4618 loop {
4619 // The position of the punctuator that follows the base expression: a
4620 // failed `.`, `[` or `(` is blamed on that token, not on the base.
4621 let op_pos = self.current.span.start;
4622 match self.current.kind.clone() {
4623 TokenKind::Punct(Punct::Dot) => {
4624 self.bump()?;
4625 let property = self.parse_member_property()?;
4626 expr = Expr::at_operator(
4627 ExprKind::Member {
4628 object: Box::new(expr),
4629 property,
4630 optional: false,
4631 },
4632 self.span_from(start),
4633 op_pos,
4634 );
4635 }
4636 TokenKind::Punct(Punct::QuestionDot) => {
4637 saw_optional = true;
4638 self.bump()?;
4639 if self.at_punct(Punct::LParen) {
4640 let arguments = self.parse_arguments()?;
4641 expr = Expr::at_operator(
4642 ExprKind::Call {
4643 callee: Box::new(expr),
4644 arguments,
4645 optional: true,
4646 },
4647 self.span_from(start),
4648 op_pos,
4649 );
4650 } else if self.at_punct(Punct::LBracket) {
4651 self.bump()?;
4652 let index = self.parse_expression(true)?;
4653 self.expect_punct(Punct::RBracket)?;
4654 expr = Expr::at_operator(
4655 ExprKind::Member {
4656 object: Box::new(expr),
4657 property: MemberProp::Computed(Box::new(index)),
4658 optional: true,
4659 },
4660 self.span_from(start),
4661 op_pos,
4662 );
4663 } else {
4664 let property = self.parse_member_property()?;
4665 expr = Expr::at_operator(
4666 ExprKind::Member {
4667 object: Box::new(expr),
4668 property,
4669 optional: true,
4670 },
4671 self.span_from(start),
4672 op_pos,
4673 );
4674 }
4675 }
4676 TokenKind::Punct(Punct::LBracket) => {
4677 self.bump()?;
4678 let index = self.parse_expression(true)?;
4679 self.expect_punct(Punct::RBracket)?;
4680 expr = Expr::at_operator(
4681 ExprKind::Member {
4682 object: Box::new(expr),
4683 property: MemberProp::Computed(Box::new(index)),
4684 optional: false,
4685 },
4686 self.span_from(start),
4687 op_pos,
4688 );
4689 }
4690 TokenKind::Punct(Punct::LParen) => {
4691 let arguments = self.parse_arguments()?;
4692 expr = Expr::at_operator(
4693 ExprKind::Call {
4694 callee: Box::new(expr),
4695 arguments,
4696 optional: false,
4697 },
4698 self.span_from(start),
4699 op_pos,
4700 );
4701 }
4702 TokenKind::Template(_) => {
4703 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4704 return Err(
4705 self.error("tagged template cannot be used in an optional chain")
4706 );
4707 }
4708 let quasi = self.parse_template()?;
4709 expr = Expr::new(
4710 ExprKind::TaggedTemplate {
4711 tag: Box::new(expr),
4712 quasi: Box::new(quasi),
4713 },
4714 self.span_from(start),
4715 );
4716 }
4717 _ => break,
4718 }
4719 }
4720 if saw_optional {
4721 expr = Expr::new(
4722 ExprKind::OptionalChain(Box::new(expr)),
4723 self.span_from(start),
4724 );
4725 }
4726 Ok(expr)
4727 }
4728
4729 /// `#name`, with `#` the current token.
4730 ///
4731 /// The `#` and the name may not be separated: `class C { # x = 1 }` is
4732 /// `invalid first character of private name`, not a field called `x`. The reference checks
4733 /// it in the lexer (`parse_ident` with `is_private`, which requires an identifier-start
4734 /// character immediately after the `#`), so the error is reported at the `#`.
4735 fn parse_private_name(&mut self) -> Result<Ident> {
4736 let hash = self.current.span;
4737 self.bump()?;
4738 let ident = self.expect_ident()?;
4739 if ident.span.start.offset != hash.end.offset {
4740 return Err(self.error_at("invalid first character of private name", hash));
4741 }
4742 Ok(ident)
4743 }
4744
4745 fn parse_member_property(&mut self) -> Result<MemberProp> {
4746 if self.at_punct(Punct::Hash) {
4747 let ident = self.parse_private_name()?;
4748 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4749 // Private names are valid throughout the class body in either order, so an
4750 // unresolved one may simply be a forward reference. Park it and settle when
4751 // the body closes; with no class body at all there is nothing to defer to,
4752 // and the reference's message is used verbatim
4753 // (`js_parse_error(s, "undefined private field '#%s'")`).
4754 let Some(innermost) = self.private.last_mut() else {
4755 return Err(self.error_at(
4756 format!("undefined private field '#{}'", ident.name),
4757 ident.span,
4758 ));
4759 };
4760 // Deferred to the *innermost* class, whose body is the one still being
4761 // parsed. If its own body never declares the name it bubbles outward — an
4762 // inner class body may legally name an outer class's private field.
4763 innermost.pending.push((ident.name.clone(), ident.span));
4764 }
4765 return Ok(MemberProp::Private(ident));
4766 }
4767 match self.current.kind.clone() {
4768 TokenKind::Ident(name) => {
4769 let span = self.current.span;
4770 self.bump()?;
4771 Ok(MemberProp::Ident(Ident { name, span }))
4772 }
4773 TokenKind::Keyword(kw) => {
4774 let span = self.current.span;
4775 self.bump()?;
4776 Ok(MemberProp::Ident(Ident {
4777 name: kw.as_str().to_string(),
4778 span,
4779 }))
4780 }
4781 // After `.` or `?.` the reference says "expecting field name", not
4782 // "invalid property name" — it is `js_parse_error(s, "expecting field name")`
4783 // at the member-access site.
4784 _ => Err(self.error("expecting field name")),
4785 }
4786 }
4787
4788 fn parse_new_expression(&mut self) -> Result<Expr> {
4789 let start = self.current.span.start;
4790 self.bump()?; // new
4791 if self.at_punct(Punct::Dot) {
4792 self.bump()?;
4793 if !self.at_ident("target") {
4794 return Err(self.error("expecting target"));
4795 }
4796 if !self.ctx.in_function {
4797 return Err(self.error("new.target only allowed within functions"));
4798 }
4799 self.bump()?;
4800 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4801 }
4802 let mut callee = if self.at_keyword(Keyword::New) {
4803 self.parse_new_expression()?
4804 } else {
4805 self.parse_primary()?
4806 };
4807 // Member accesses bind tighter than `new`, calls do not.
4808 loop {
4809 let op_pos = self.current.span.start;
4810 match self.current.kind.clone() {
4811 TokenKind::Punct(Punct::Dot) => {
4812 self.bump()?;
4813 let property = self.parse_member_property()?;
4814 callee = Expr::at_operator(
4815 ExprKind::Member {
4816 object: Box::new(callee),
4817 property,
4818 optional: false,
4819 },
4820 self.span_from(start),
4821 op_pos,
4822 );
4823 }
4824 TokenKind::Punct(Punct::LBracket) => {
4825 self.bump()?;
4826 let index = self.parse_expression(true)?;
4827 self.expect_punct(Punct::RBracket)?;
4828 callee = Expr::at_operator(
4829 ExprKind::Member {
4830 object: Box::new(callee),
4831 property: MemberProp::Computed(Box::new(index)),
4832 optional: false,
4833 },
4834 self.span_from(start),
4835 op_pos,
4836 );
4837 }
4838 TokenKind::Punct(Punct::QuestionDot) => {
4839 return Err(self.error("new keyword cannot be used with an optional chain"));
4840 }
4841 _ => break,
4842 }
4843 }
4844 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4845 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4846 }
4847 // `ImportCall` is a *CallExpression*, and `new` only reaches a `MemberExpression`
4848 // (`MemberExpression : new MemberExpression Arguments`), so `new import(x)` is a
4849 // SyntaxError. `import.meta`, by contrast, *is* a `MemberExpression`, so
4850 // `new import.meta()` parses and fails at run time for not being a constructor.
4851 //
4852 // The whole member chain has to be checked, not just its root: `new import('').p`
4853 // reaches `new` through `Member { object: ImportCall, property: p }`, and the grammar
4854 // cannot build that either — `. IdentifierName` needs a CallExpression on its left,
4855 // and a CallExpression is not a MemberExpression, so there is nothing for `new` to
4856 // take. Parentheses do change it: `new (import('')).p` is legal and throws at run
4857 // time, because a parenthesised expression *is* a PrimaryExpression.
4858 if let Some(import_call) = member_chain_import_call(&callee) {
4859 return Err(self.error_at("invalid use of 'import()'", import_call.span));
4860 }
4861 // The root check is on the callee as written, *not* through parentheses:
4862 // `new (import(''))` is legal because a parenthesised expression is a
4863 // PrimaryExpression and therefore a MemberExpression, and it fails at run time for
4864 // not being a constructor (`syntax/valid/new-covered-expression-is-valid`). The
4865 // member-chain walk above stops at a `Paren` for the same reason.
4866 if matches!(&callee.kind, ExprKind::ImportCall(..)) {
4867 return Err(self.error_at("invalid use of 'import()'", callee.span));
4868 }
4869 let arguments = if self.at_punct(Punct::LParen) {
4870 // `new C(...)`: a failure in the constructor call is blamed on the `(`.
4871 let op_pos = self.current.span.start;
4872 let arguments = Some(self.parse_arguments()?);
4873 return Ok(Expr::at_operator(
4874 ExprKind::New {
4875 callee: Box::new(callee),
4876 arguments,
4877 },
4878 self.span_from(start),
4879 op_pos,
4880 ));
4881 } else {
4882 None
4883 };
4884 // `new C` with no argument list: the reference emits its position at the token
4885 // *after* the constructor (`emit_source_pos(s, s->token.ptr)` for "new operator on
4886 // an object"), not at the `new`.
4887 Ok(Expr::at_operator(
4888 ExprKind::New {
4889 callee: Box::new(callee),
4890 arguments,
4891 },
4892 self.span_from(start),
4893 self.current.span.start,
4894 ))
4895 }
4896
4897 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4898 self.expect_punct(Punct::LParen)?;
4899 let mut arguments = Vec::new();
4900 while !self.at_punct(Punct::RParen) {
4901 if self.at_punct(Punct::Ellipsis) {
4902 let start = self.current.span.start;
4903 self.bump()?;
4904 let argument = self.parse_assignment(true)?;
4905 arguments.push(Expr::new(
4906 ExprKind::Spread(Box::new(argument)),
4907 self.span_from(start),
4908 ));
4909 } else {
4910 arguments.push(self.parse_assignment(true)?);
4911 }
4912 if !self.eat_punct(Punct::Comma)? {
4913 break;
4914 }
4915 }
4916 self.expect_punct(Punct::RParen)?;
4917 Ok(arguments)
4918 }
4919
4920 /// Primary expressions.
4921 ///
4922 /// The rarely used forms are dispatched to [`Parser::parse_primary_complex`]
4923 /// so that this function — which sits on every nesting level — keeps a small
4924 /// stack frame. That directly raises how deeply a program may nest before
4925 /// the stack limit is hit (debug builds get ~4x more depth out of it).
4926 fn parse_primary(&mut self) -> Result<Expr> {
4927 let start = self.current.span.start;
4928 match self.current.kind.clone() {
4929 TokenKind::Number(NumberLiteral::Int(value)) => {
4930 self.bump()?;
4931 Ok(Expr::new(
4932 ExprKind::Number(value as f64),
4933 self.span_from(start),
4934 ))
4935 }
4936 TokenKind::Number(NumberLiteral::Float(value)) => {
4937 self.bump()?;
4938 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4939 }
4940 TokenKind::String(value) => {
4941 self.bump()?;
4942 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4943 }
4944 // A *contextual* keyword, so only its own spelling counts: `\u0061sync
4945 // function(){}` is an identifier followed by a declaration, which is a syntax
4946 // error rather than an async function expression.
4947 TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4948 let peek = self.peek()?;
4949 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4950 && !peek.newline_before
4951 {
4952 self.bump()?; // async
4953 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4954 return Ok(Expr::new(
4955 ExprKind::Function(Box::new(func)),
4956 self.span_from(start),
4957 ));
4958 }
4959 let span = self.current.span;
4960 self.bump()?;
4961 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4962 }
4963 TokenKind::Ident(name) => {
4964 let span = self.current.span;
4965 self.check_identifier(&name, span)?;
4966 self.check_arguments_reference(&name, span)?;
4967 self.bump()?;
4968 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4969 }
4970 TokenKind::Keyword(Keyword::This) => {
4971 self.bump()?;
4972 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4973 }
4974 TokenKind::Keyword(Keyword::Null) => {
4975 self.bump()?;
4976 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4977 }
4978 TokenKind::Keyword(Keyword::True) => {
4979 self.bump()?;
4980 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4981 }
4982 TokenKind::Keyword(Keyword::False) => {
4983 self.bump()?;
4984 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4985 }
4986 TokenKind::Punct(Punct::LParen) => {
4987 self.bump()?;
4988 let inner = self.parse_expression(true)?;
4989 self.expect_punct(Punct::RParen)?;
4990 Ok(Expr::new(
4991 ExprKind::Paren(Box::new(inner)),
4992 self.span_from(start),
4993 ))
4994 }
4995 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4996 self.parse_regex_literal(start)
4997 }
4998 _ => self.parse_primary_complex(start),
4999 }
5000 }
5001
5002 /// The primary expressions that need a lot of code: literals with structure,
5003 /// functions, classes, `import`, `super`, `#x in y`.
5004 #[inline(never)]
5005 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
5006 match self.current.kind.clone() {
5007 TokenKind::BigInt(literal) => {
5008 self.bump()?;
5009 Ok(Expr::new(
5010 ExprKind::BigInt {
5011 digits: literal.digits,
5012 radix: literal.radix,
5013 },
5014 self.span_from(start),
5015 ))
5016 }
5017 TokenKind::Template(_) => {
5018 let template = self.parse_template()?;
5019 Ok(Expr::new(
5020 ExprKind::Template(Box::new(template)),
5021 self.span_from(start),
5022 ))
5023 }
5024 TokenKind::Keyword(Keyword::Function) => {
5025 let func = self.parse_function(FunctionForm::Expression, false, None)?;
5026 Ok(Expr::new(
5027 ExprKind::Function(Box::new(func)),
5028 self.span_from(start),
5029 ))
5030 }
5031 TokenKind::Keyword(Keyword::Class) => {
5032 let class = self.parse_class(true)?;
5033 Ok(Expr::new(
5034 ExprKind::Class(Box::new(class)),
5035 self.span_from(start),
5036 ))
5037 }
5038 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
5039 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
5040 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
5041 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
5042 // `#x` is only an expression as `#x in obj`, and `in` is not available where the
5043 // grammar forbids it — a `for` head, for instance. The reference parses the head
5044 // with the `[~In]` production, so `for (#f in v;;)` fails on the `#f` itself with
5045 // "unexpected token in expression: '#f'" rather than somewhere later.
5046 TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
5047 // Reached only when `in` is unavailable, so `#f` cannot start an expression here.
5048 // The message is the reference's, which quotes the whole private name rather than
5049 // the lone `#` that the token stream holds.
5050 TokenKind::Punct(Punct::Hash) => {
5051 let hash = self.current.span;
5052 let name = match self.peek()?.kind.clone() {
5053 TokenKind::Ident(name) => format!("#{name}"),
5054 _ => "#".to_string(),
5055 };
5056 Err(SyntaxError::new(
5057 format!("unexpected token in expression: '{name}'"),
5058 hash,
5059 ))
5060 }
5061 _ => Err(self.unexpected()),
5062 }
5063 }
5064
5065 /// `super` or `super(...)`.
5066 #[inline(never)]
5067 fn parse_super(&mut self) -> Result<Expr> {
5068 let start = self.current.span.start;
5069 self.bump()?;
5070 // Every error below is reported at the token *after* `super`, because the reference
5071 // consumes the keyword before it looks at what follows (`case TOK_SUPER:
5072 // next_token(s); …`) and `js_parse_error` always points at the current token. So
5073 // `super.x` reports the `.`, `super()` the `(`, and a bare `super` the token that
5074 // ends the expression.
5075 let after = self.current.span;
5076 if self.at_punct(Punct::LParen) {
5077 if !self.ctx.in_derived_constructor {
5078 return Err(self.error_at(
5079 "super() is only valid in a derived class constructor",
5080 after,
5081 ));
5082 }
5083 // A `super()` call is positioned on its `(` like any other call: the reference
5084 // reaches the same `emit_source_pos(op_token_ptr)` on the way to `apply`.
5085 let arguments = self.parse_arguments()?;
5086 return Ok(Expr::at_operator(
5087 ExprKind::SuperCall(arguments),
5088 self.span_from(start),
5089 after.start,
5090 ));
5091 }
5092 if !self.ctx.in_method {
5093 // Three messages, told apart by what follows `super`:
5094 // `super` alone -> invalid use of 'super'
5095 // `super.x`, `super[x]` -> 'super' is only valid in a method
5096 // `super()` -> handled above
5097 // A bare `super` never reaches the member-access code, so the reference names
5098 // it on its own.
5099 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
5100 "'super' is only valid in a method"
5101 } else {
5102 "invalid use of 'super'"
5103 };
5104 return Err(self.error_at(message, after));
5105 }
5106 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
5107 }
5108
5109 /// `#name in object`.
5110 #[inline(never)]
5111 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
5112 self.bump()?;
5113 let ident = self.expect_ident()?;
5114 if !self.private.iter().any(|env| env.contains(&ident.name)) {
5115 return Err(self.error_at(
5116 format!(
5117 "private field '#{}' must be declared in an enclosing class",
5118 ident.name
5119 ),
5120 ident.span,
5121 ));
5122 }
5123 if !self.at_keyword(Keyword::In) {
5124 return Err(self.error("expecting 'in' after a private name"));
5125 }
5126 self.bump()?;
5127 // `RelationalExpression : PrivateIdentifier in ShiftExpression` — the right operand is
5128 // a *shift* expression, so a second private-in cannot nest inside it. The reference
5129 // says so by rejecting `#f in #f in this` at the inner `#f`.
5130 if self.at_punct(Punct::Hash) {
5131 let hash = self.current.span;
5132 let name = match self.peek()?.kind.clone() {
5133 TokenKind::Ident(name) => format!("#{name}"),
5134 _ => "#".to_string(),
5135 };
5136 return Err(SyntaxError::new(
5137 format!("unexpected token in expression: '{name}'"),
5138 hash,
5139 ));
5140 }
5141 let object = self.parse_unary()?;
5142 Ok(Expr::new(
5143 ExprKind::PrivateIn {
5144 name: ident,
5145 object: Box::new(object),
5146 },
5147 self.span_from(start),
5148 ))
5149 }
5150
5151 /// A regular expression literal: the lexer produced `/` (or `/=`), so the
5152 /// token has to be re-scanned from that position.
5153 #[inline(never)]
5154 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
5155 let token = self.lexer.re_scan_regex(self.current.span.start)?;
5156 self.current = token;
5157 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
5158 unreachable!("re_scan_regex returns a RegExp token")
5159 };
5160 // The flags are validated **here**, at parse time, not when the opcode first runs:
5161 // a negative test262 case calls `$DONOTEVALUATE()` and then writes `/./uv`, and an
5162 // engine that compiles the literal lazily reports that `Test262Error` instead of the
5163 // `SyntaxError` the file is about (`RegExp/prototype/unicodeSets/uv-flags`).
5164 //
5165 // Only the flags are checked here. The pattern body is the regexp crate's grammar, and
5166 // the parser has no dependency on it; a malformed body still throws when the literal
5167 // is first evaluated, which is what `/a{/u` and friends rely on.
5168 let mut seen = 0u8;
5169 for flag in flags.chars() {
5170 let bit = match flag {
5171 'g' => 1 << 0,
5172 'i' => 1 << 1,
5173 'm' => 1 << 2,
5174 's' => 1 << 3,
5175 'y' => 1 << 4,
5176 'u' => 1 << 5,
5177 'd' => 1 << 6,
5178 'v' => 1 << 7,
5179 _ => {
5180 return Err(SyntaxError::new(
5181 "invalid regular expression flags",
5182 self.current.span,
5183 ));
5184 }
5185 };
5186 if seen & bit != 0 {
5187 return Err(SyntaxError::new(
5188 "duplicate regular expression flag",
5189 self.current.span,
5190 ));
5191 }
5192 seen |= bit;
5193 }
5194 // `u` and `v` are two dialects of one strict grammar, so a pattern cannot ask for both.
5195 if seen & (1 << 5) != 0 && seen & (1 << 7) != 0 {
5196 return Err(SyntaxError::new(
5197 "invalid regular expression flags",
5198 self.current.span,
5199 ));
5200 }
5201 self.bump()?;
5202 Ok(Expr::new(
5203 ExprKind::RegExp { pattern, flags },
5204 self.span_from(start),
5205 ))
5206 }
5207
5208 fn parse_import_expression(&mut self) -> Result<Expr> {
5209 let start = self.current.span.start;
5210 self.bump()?; // import
5211 if self.at_punct(Punct::Dot) {
5212 if !self.module {
5213 return Err(self.error_at(
5214 "import.meta only valid in module code",
5215 self.span_from(start),
5216 ));
5217 }
5218 self.bump()?;
5219 if !self.at_ident("meta") {
5220 return Err(self.error("expecting 'meta' after 'import.'"));
5221 }
5222 self.bump()?;
5223 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
5224 }
5225 if self.at_punct(Punct::LParen) {
5226 self.bump()?;
5227 let specifier = self.parse_assignment(true)?;
5228 // The grammar has two forms and both allow a trailing comma:
5229 //
5230 // ImportCall : import ( AssignmentExpression ,opt )
5231 // import ( AssignmentExpression , AssignmentExpression ,opt )
5232 //
5233 // The second argument is the import-attributes bag (`import(x, { with: … })`).
5234 // It stays in the tree: §13.3.10.1 step 4 says the options expression is
5235 // evaluated and its value read, so its side effects are observable even though
5236 // this loader reads no attributes. Rejecting the syntax outright is what turned
5237 // a legal `import(x,)` into a SyntaxError.
5238 let mut options = None;
5239 if self.at_punct(Punct::Comma) {
5240 self.bump()?;
5241 if !self.at_punct(Punct::RParen) {
5242 options = Some(Box::new(self.parse_assignment(true)?));
5243 if self.at_punct(Punct::Comma) {
5244 self.bump()?;
5245 }
5246 }
5247 }
5248 self.expect_punct(Punct::RParen)?;
5249 return Ok(Expr::new(
5250 ExprKind::ImportCall(Box::new(specifier), options),
5251 self.span_from(start),
5252 ));
5253 }
5254 Err(self.unexpected())
5255 }
5256
5257 fn parse_array_literal(&mut self) -> Result<Expr> {
5258 let start = self.current.span.start;
5259 self.expect_punct(Punct::LBracket)?;
5260 let mut elements = Vec::new();
5261 // Whether the comma just consumed came after a spread *and* closed the literal,
5262 // which is `[...x,]` — legal as a literal, an early error as a pattern.
5263 let mut spread_comma_closed = false;
5264 while !self.at_punct(Punct::RBracket) {
5265 if self.at_punct(Punct::Comma) {
5266 self.bump()?;
5267 elements.push(None);
5268 spread_comma_closed = false;
5269 continue;
5270 }
5271 let spread = self.at_punct(Punct::Ellipsis);
5272 if spread {
5273 let spread_start = self.current.span.start;
5274 self.bump()?;
5275 let argument = self.parse_assignment(true)?;
5276 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
5277 ExprKind::Spread(Box::new(argument)),
5278 self.span_from(spread_start),
5279 )))));
5280 } else {
5281 let expr = self.parse_assignment(true)?;
5282 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
5283 }
5284 if !self.eat_punct(Punct::Comma)? {
5285 break;
5286 }
5287 spread_comma_closed = spread && self.at_punct(Punct::RBracket);
5288 }
5289 self.expect_punct(Punct::RBracket)?;
5290 let span = self.span_from(start);
5291 if spread_comma_closed {
5292 self.spread_trailing_comma.push(span);
5293 }
5294 Ok(Expr::new(ExprKind::Array { elements }, span))
5295 }
5296
5297 fn parse_object_literal(&mut self) -> Result<Expr> {
5298 let start = self.current.span.start;
5299 self.expect_punct(Punct::LBrace)?;
5300 let mut properties: Vec<ObjectProperty> = Vec::new();
5301 let mut proto_count = 0;
5302 let mut spread_comma_closed = false;
5303 while !self.at_punct(Punct::RBrace) {
5304 let property_start = self.current.span.start;
5305 if self.at_punct(Punct::Ellipsis) {
5306 self.bump()?;
5307 let argument = self.parse_assignment(true)?;
5308 properties.push(ObjectProperty::Spread(Box::new(argument)));
5309 } else {
5310 let mut is_async = false;
5311 let mut is_generator = false;
5312 let mut accessor: Option<MethodKind> = None;
5313 if self.at_ident("async") {
5314 let peek = self.peek()?;
5315 let is_modifier = !matches!(
5316 peek.kind,
5317 TokenKind::Punct(Punct::LParen)
5318 | TokenKind::Punct(Punct::Colon)
5319 | TokenKind::Punct(Punct::Comma)
5320 | TokenKind::Punct(Punct::RBrace)
5321 | TokenKind::Punct(Punct::Eq)
5322 ) && !peek.newline_before;
5323 if is_modifier {
5324 self.bump()?;
5325 is_async = true;
5326 }
5327 }
5328 if self.at_punct(Punct::Star) {
5329 self.bump()?;
5330 is_generator = true;
5331 }
5332 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
5333 let is_get = self.at_ident("get");
5334 let peek = self.peek()?;
5335 if is_property_key_start(&peek.kind) {
5336 self.bump()?;
5337 accessor = Some(if is_get {
5338 MethodKind::Get
5339 } else {
5340 MethodKind::Set
5341 });
5342 }
5343 }
5344 let key = self.parse_property_key()?;
5345 let is_computed = matches!(key, PropName::Computed(_));
5346 if self.at_punct(Punct::LParen) {
5347 let saved = self.ctx;
5348 self.ctx = FnCtx {
5349 in_function: true,
5350 in_generator: is_generator,
5351 in_async: is_async,
5352 in_method: true,
5353 in_derived_constructor: false,
5354 in_static_block: false,
5355 arguments_allowed: true,
5356 };
5357 let saved_top = self.top_level;
5358 self.top_level = false;
5359 let func_result = (|| -> Result<Function> {
5360 let params = self.parse_formal_parameters()?;
5361 let (params, params_span, body, strict) =
5362 self.parse_function_body(params, true)?;
5363 Ok(Function {
5364 name: None,
5365 params,
5366 body,
5367 is_async,
5368 is_generator,
5369 strict,
5370 is_arrow: false,
5371 span: self.span_from(property_start),
5372 params_span,
5373 source_span: None,
5374 })
5375 })();
5376 self.ctx = saved;
5377 self.top_level = saved_top;
5378 let func = func_result?;
5379 let kind = match accessor {
5380 Some(kind) => {
5381 if is_generator || is_async {
5382 return Err(self.error_at(
5383 "accessors may not be generators or async",
5384 func.span,
5385 ));
5386 }
5387 if kind == MethodKind::Get && !func.params.is_empty() {
5388 return Err(self.error_at(
5389 "invalid number of arguments for getter or setter",
5390 func.span,
5391 ));
5392 }
5393 if kind == MethodKind::Set && func.params.len() != 1 {
5394 return Err(self.error_at(
5395 "invalid number of arguments for getter or setter",
5396 func.span,
5397 ));
5398 }
5399 match kind {
5400 MethodKind::Get => PropertyKind::Get,
5401 MethodKind::Set => PropertyKind::Set,
5402 MethodKind::Method | MethodKind::Constructor => {
5403 PropertyKind::Method
5404 }
5405 }
5406 }
5407 None => PropertyKind::Method,
5408 };
5409 let span = self.span_from(property_start);
5410 properties.push(ObjectProperty::Property {
5411 key,
5412 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
5413 kind,
5414 shorthand: false,
5415 span,
5416 });
5417 } else if self.eat_punct(Punct::Colon)? {
5418 let value = self.parse_assignment(true)?;
5419 if !is_computed
5420 && let Some(PropKeyRef::Str(name)) = key.static_name()
5421 && name == "__proto__"
5422 {
5423 proto_count += 1;
5424 if proto_count > 1 {
5425 return Err(self.error_at(
5426 "duplicate __proto__ property name",
5427 self.span_from(property_start),
5428 ));
5429 }
5430 }
5431 properties.push(ObjectProperty::Property {
5432 key,
5433 value: Box::new(value),
5434 kind: PropertyKind::Value,
5435 shorthand: false,
5436 span: self.span_from(property_start),
5437 });
5438 } else {
5439 // Shorthand `{a}` / `{a = 1}` (the latter only inside a
5440 // destructuring pattern).
5441 let PropName::Literal(PropKey::Str(name)) = &key else {
5442 return Err(self.error("expecting ':' after a property name"));
5443 };
5444 let ident_span = self.span_from(property_start);
5445 let ident = Ident {
5446 // A shorthand `{"\uD800" as a name}` is not a thing: a binding name
5447 // is an identifier, so this path is only reached for text that is
5448 // already valid; the lossy conversion cannot lose anything here.
5449 name: name.to_string_lossy().into_owned(),
5450 span: ident_span,
5451 };
5452 self.check_identifier(&ident.name, ident.span)?;
5453 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
5454 if self.at_punct(Punct::Eq) {
5455 // CoverInitializedName: only legal once the object turns
5456 // out to be a destructuring pattern.
5457 self.cover_inits.push(ident_span);
5458 self.bump()?;
5459 let default = self.parse_assignment(true)?;
5460 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
5461 value = Expr::new(
5462 ExprKind::Assign {
5463 op: AssignOp::Assign,
5464 target: Box::new(target),
5465 value: Box::new(default),
5466 },
5467 ident_span,
5468 );
5469 }
5470 properties.push(ObjectProperty::Property {
5471 key,
5472 value: Box::new(value),
5473 kind: PropertyKind::Value,
5474 shorthand: true,
5475 span: ident_span,
5476 });
5477 }
5478 }
5479 // `{…, …}` — whether the property just pushed was a spread is what decides
5480 // whether the comma that closed the literal is the illegal one.
5481 let spread = matches!(properties.last(), Some(ObjectProperty::Spread(_)));
5482 if !self.eat_punct(Punct::Comma)? {
5483 break;
5484 }
5485 spread_comma_closed = spread && self.at_punct(Punct::RBrace);
5486 }
5487 self.expect_punct(Punct::RBrace)?;
5488 let span = self.span_from(start);
5489 if spread_comma_closed {
5490 self.spread_trailing_comma.push(span);
5491 }
5492 Ok(Expr::new(ExprKind::Object(properties), span))
5493 }
5494
5495 fn parse_template(&mut self) -> Result<TemplateLiteral> {
5496 let mut quasis = Vec::new();
5497 let mut expressions = Vec::new();
5498 loop {
5499 let (cooked, raw, kind) = match self.current.kind.clone() {
5500 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
5501 _ => return Err(self.error("expecting a template literal")),
5502 };
5503 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
5504 quasis.push(TemplateChunk { cooked, raw, tail });
5505 if tail {
5506 self.bump()?;
5507 break;
5508 }
5509 self.bump()?; // move to the first token of the substitution
5510 let expr = self.parse_expression(true)?;
5511 expressions.push(expr);
5512 if !self.at_punct(Punct::RBrace) {
5513 return Err(self.error("expecting '}' in a template substitution"));
5514 }
5515 let brace = self.current.span.start;
5516 let token = self.lexer.re_scan_template_continue(brace)?;
5517 self.current = token;
5518 }
5519 Ok(TemplateLiteral {
5520 quasis,
5521 expressions,
5522 })
5523 }
5524}
5525
5526/// Which kind of function is being parsed (affects whether a name is required).
5527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5528enum FunctionForm {
5529 Declaration,
5530 Expression,
5531}
5532
5533/// Names of the parameters that participate in declaration-conflict checks.
5534///
5535/// Engines only check *simple* (identifier) parameters against the body's
5536/// lexical declarations: `function f(a) { let a; }` is an early error, but
5537/// `function f({a}) { let a; }` is not (QuickJS behaves the same way, so this
5538/// deliberately follows the reference rather than ES2025 §10.2.1).
5539/// Whether this parameter is a bare identifier, as opposed to a pattern.
5540fn is_plain_identifier(param: &Pattern) -> bool {
5541 matches!(param.unparen_kind(), PatternKind::Ident(_))
5542}
5543
5544/// Every name `param` binds, in binding order, tagged with whether it sits inside a
5545/// destructuring pattern.
5546///
5547/// A rest parameter is a pattern only when its target is: `...a` binds like a plain name,
5548/// while `...[a]` does not.
5549fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
5550 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
5551 match &pattern.kind {
5552 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
5553 PatternKind::Assign { target, default } => {
5554 walk(target, in_pattern, out);
5555 // A default's own expression can bind nothing, so only the target is walked.
5556 let _ = default;
5557 }
5558 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
5559 PatternKind::Array { .. } | PatternKind::Object { .. } => {
5560 let mut names = Vec::new();
5561 pattern.bound_names(&mut names);
5562 for name in names {
5563 out.push((name.name, name.span, true));
5564 }
5565 }
5566 _ => {}
5567 }
5568 }
5569 let mut out = Vec::new();
5570 let in_pattern = !is_plain_identifier(param);
5571 walk(param, in_pattern, &mut out);
5572 // A pattern's own walk above already flagged its names; a plain identifier or a
5573 // defaulted one goes through `walk` directly.
5574 if out.is_empty() {
5575 let mut names = Vec::new();
5576 param.bound_names(&mut names);
5577 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
5578 }
5579 out
5580}
5581
5582/// Whether any binding in `pattern` carries a default value.
5583///
5584/// This is the closest stand-in we have for the reference's lookahead: it scans the
5585/// parenthesised parameter text for an `=` (`SKIP_HAS_ASSIGNMENT`) *before* parsing it, and
5586/// that flag decides which of the two duplicate-name messages a later conflict gets.
5587fn pattern_has_default(pattern: &Pattern) -> bool {
5588 let element = |element: &Option<PatternElement>| {
5589 element.as_ref().is_some_and(|element| match element {
5590 PatternElement::Pattern(inner) => pattern_has_default(inner),
5591 PatternElement::Property { value, .. } => pattern_has_default(value),
5592 })
5593 };
5594 let rest = |rest: &Option<Box<RestElement>>| {
5595 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
5596 RestElement::Pattern(inner) => pattern_has_default(inner),
5597 RestElement::Member(_) => false,
5598 })
5599 };
5600 match &pattern.kind {
5601 PatternKind::Assign { .. } => true,
5602 PatternKind::Array {
5603 elements,
5604 rest: tail,
5605 } => elements.iter().any(element) || rest(tail),
5606 PatternKind::Object {
5607 properties,
5608 rest: tail,
5609 } => properties.iter().any(element) || rest(tail),
5610 PatternKind::Rest(target) => pattern_has_default(target),
5611 _ => false,
5612 }
5613}
5614
5615fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
5616 params
5617 .iter()
5618 .filter_map(|param| match ¶m.kind {
5619 PatternKind::Ident(id) => Some(id.name.clone()),
5620 _ => None,
5621 })
5622 .collect()
5623}
5624
5625/// Collect the names a top-level module item declares, for the exported-name
5626/// check.
5627fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
5628 match &stmt.kind {
5629 StmtKind::VarDecl(decl) => {
5630 // A `using` declaration is a lexical binding of the module's own scope but not
5631 // a *module variable*, so it cannot be exported: the reference excludes it from
5632 // `add_global_var` and `export {a}` of one reports
5633 // `exported variable 'a' does not exist`. Leaving it in this list would make
5634 // that export silently succeed.
5635 if decl.kind.is_using() {
5636 return;
5637 }
5638 for declarator in &decl.declarators {
5639 let mut names = Vec::new();
5640 declarator.target.bound_names(&mut names);
5641 out.extend(names.into_iter().map(|n| n.name));
5642 }
5643 }
5644 StmtKind::FuncDecl(func) => {
5645 if let Some(name) = &func.name {
5646 out.push(name.name.clone());
5647 }
5648 }
5649 StmtKind::ClassDecl(class) => {
5650 if let Some(name) = &class.name {
5651 out.push(name.name.clone());
5652 }
5653 }
5654 StmtKind::Import(decl) => {
5655 for specifier in &decl.specifiers {
5656 match specifier {
5657 ImportSpecifier::Default(id) => out.push(id.name.clone()),
5658 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
5659 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
5660 }
5661 }
5662 }
5663 StmtKind::Export(decl) => match &decl.kind {
5664 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
5665 ExportKind::Default(expr) => match &expr.unparen().kind {
5666 ExprKind::Function(func) => {
5667 if let Some(name) = &func.name {
5668 out.push(name.name.clone());
5669 }
5670 }
5671 ExprKind::Class(class) => {
5672 if let Some(name) = &class.name {
5673 out.push(name.name.clone());
5674 }
5675 }
5676 _ => {}
5677 },
5678 _ => {}
5679 },
5680 _ => {}
5681 }
5682}
5683
5684/// Whether `inner` is fully inside `outer` (byte offset comparison only).
5685fn span_contains(outer: Span, inner: Span) -> bool {
5686 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
5687}
5688
5689fn is_property_key_start(kind: &TokenKind) -> bool {
5690 matches!(
5691 kind,
5692 TokenKind::Ident(_)
5693 | TokenKind::Keyword(_)
5694 | TokenKind::String(_)
5695 | TokenKind::Number(_)
5696 | TokenKind::Punct(Punct::LBracket)
5697 | TokenKind::Punct(Punct::Hash)
5698 )
5699}
5700
5701/// A binary operator with its precedence, as consumed by [`Parser::parse_binary`].
5702#[derive(Debug, Clone, Copy)]
5703enum BinOp {
5704 Binary(BinaryOp),
5705 Logical(LogicalOp),
5706}
5707
5708impl BinOp {
5709 fn is_right_associative(self) -> bool {
5710 matches!(self, BinOp::Binary(BinaryOp::Pow))
5711 }
5712}
5713
5714fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
5715 use BinaryOp as B;
5716 use LogicalOp as L;
5717 let result = match kind {
5718 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
5719 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
5720 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
5721 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
5722 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
5723 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
5724 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
5725 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
5726 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
5727 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
5728 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
5729 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
5730 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
5731 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
5732 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
5733 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
5734 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
5735 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
5736 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
5737 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
5738 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5739 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5740 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5741 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5742 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5743 _ => return None,
5744 };
5745 Some(result)
5746}
5747
5748fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5749 match op {
5750 BinOp::Binary(op) => Ok(Expr::at_operator(
5751 ExprKind::Binary {
5752 op,
5753 left: Box::new(left),
5754 right: Box::new(right),
5755 },
5756 span,
5757 op_pos,
5758 )),
5759 BinOp::Logical(op) => {
5760 // `??` may not be mixed with `&&`/`||` without parentheses.
5761 // A parenthesised operand is visibly a different production, so the
5762 // check must look at the raw node, not through `Paren`.
5763 let mixes = |expr: &Expr, op: LogicalOp| {
5764 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5765 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5766 };
5767 if mixes(&left, op) || mixes(&right, op) {
5768 return Err(SyntaxError::new(
5769 // The reference has no quotes in this one; the parenthesised form is the only
5770 // way to write it, which the message states rather than implies.
5771 "cannot mix ?? with && or ||",
5772 span,
5773 ));
5774 }
5775 Ok(Expr::at_operator(
5776 ExprKind::Logical {
5777 op,
5778 left: Box::new(left),
5779 right: Box::new(right),
5780 },
5781 span,
5782 op_pos,
5783 ))
5784 }
5785 }
5786}
5787
5788/// Rebuild an expression from a pattern (used when a pattern has to go back
5789/// through [`Parser::expr_to_pattern`], e.g. `{a: [b = 1]}`).
5790fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5791 match pattern.kind {
5792 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5793 PatternKind::Assign { target, default } => Expr::new(
5794 ExprKind::Assign {
5795 op: AssignOp::Assign,
5796 target,
5797 value: default,
5798 },
5799 span,
5800 ),
5801 // A member target only ever reaches here by way of the cover grammar: `[o.p = 1]`
5802 // is parsed as an assignment whose target is already a pattern, and re-reading it
5803 // as an expression has to give the member back rather than a placeholder.
5804 PatternKind::Member(member) => {
5805 let MemberPattern {
5806 object,
5807 property,
5808 span,
5809 op_pos,
5810 } = *member;
5811 Expr {
5812 kind: ExprKind::Member {
5813 object,
5814 property,
5815 optional: false,
5816 },
5817 span,
5818 op_pos,
5819 }
5820 }
5821 PatternKind::Object { properties, rest } => {
5822 let mut out = Vec::new();
5823 for element in properties {
5824 match element {
5825 Some(PatternElement::Property {
5826 key,
5827 value,
5828 shorthand,
5829 span: _,
5830 }) => {
5831 let span = value.span;
5832 out.push(ObjectProperty::Property {
5833 key,
5834 value: Box::new(pattern_to_expr(value, span)),
5835 kind: PropertyKind::Value,
5836 shorthand,
5837 span,
5838 });
5839 }
5840 // An object pattern's elements are always properties; a bare pattern
5841 // here would be a malformed AST, and dropping it is the safe reading.
5842 None | Some(PatternElement::Pattern(_)) => {}
5843 }
5844 }
5845 if let Some(rest) = rest
5846 && let RestElement::Pattern(pattern) = *rest
5847 {
5848 let span = pattern.span;
5849 out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5850 pattern, span,
5851 ))));
5852 }
5853 Expr::new(ExprKind::Object(out), span)
5854 }
5855 PatternKind::Array { elements, rest } => {
5856 let mut out = Vec::new();
5857 for element in elements {
5858 match element {
5859 Some(PatternElement::Pattern(pattern)) => {
5860 let span = pattern.span;
5861 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5862 pattern, span,
5863 )))));
5864 }
5865 Some(PatternElement::Property { .. }) | None => out.push(None),
5866 }
5867 }
5868 if let Some(rest) = rest {
5869 let RestElement::Pattern(pattern) = *rest else {
5870 return Expr::new(ExprKind::Null, span);
5871 };
5872 let span = pattern.span;
5873 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5874 pattern, span,
5875 )))));
5876 }
5877 Expr::new(ExprKind::Array { elements: out }, span)
5878 }
5879 _ => Expr::new(ExprKind::Null, span),
5880 }
5881}
5882
5883impl Pattern {
5884 /// Pattern kind, ignoring `Paren` wrappers (patterns never have any, but
5885 /// this keeps call sites uniform with [`Expr::unparen`]).
5886 fn unparen_kind(&self) -> &PatternKind {
5887 &self.kind
5888 }
5889}
5890
5891/// Whether this `delete` operand ultimately names a private member.
5892///
5893/// Whether this `delete` operand ultimately names a private member.
5894///
5895/// §13.5.1.1: `delete` may not be applied to a `MemberExpression : MemberExpression.PrivateName`
5896/// or a `CallExpression : CallExpression.PrivateName`, and the rule re-applies to a
5897/// parenthesised phrase. So the walk goes through parentheses and through a call's callee, and
5898/// stops everywhere else — including a sequence, because `delete (0, o.#x)` parenthesises
5899/// `0, o.#x`, and that phrase in place of the operand is `delete 0, o.#x`, which is legal. The
5900/// reference agrees: it accepts that one and rejects `delete (g().#x)`.
5901/// The `import()` call an unparenthesised member chain bottoms out at, if there is one.
5902///
5903/// `new` needs a `MemberExpression`, and `import()` is a `CallExpression`, so every shape
5904/// where `new` takes an `import()` through member access is a SyntaxError — `new
5905/// import('').p` and `new import('')['p']` as much as `new import('')`. The walk stops at a
5906/// `Paren`, because `(import(''))` *is* a PrimaryExpression and therefore a MemberExpression:
5907/// `new (import('')).p` is legal and throws at run time for not being a constructor.
5908fn member_chain_import_call(expr: &Expr) -> Option<&Expr> {
5909 match &expr.kind {
5910 ExprKind::ImportCall(..) => Some(expr),
5911 ExprKind::Member { object, .. } => member_chain_import_call(object),
5912 // A parenthesised expression, a call or anything else is not a member chain.
5913 _ => None,
5914 }
5915}
5916
5917fn deletes_a_private_member(expr: &Expr) -> bool {
5918 match &expr.unparen().kind {
5919 ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5920 ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5921 _ => false,
5922 }
5923}
5924
5925/// A string that has to be a `&str` — a module specifier or an import attribute.
5926///
5927/// These reach the loader and the filesystem, neither of which can do anything with an
5928/// unpaired surrogate, so the lossy conversion is the honest one: it is what a path
5929/// encoding would do anyway. Every *other* cooked string in the tree keeps the surrogate,
5930/// because the language can observe it there.
5931fn as_specifier(value: &Wtf8) -> String {
5932 value.to_string_lossy().into_owned()
5933}