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 // A raw `StringLiteral` is *any* literal without an escape sequence — and this
1367 // test is what decides whether a prologue ends, so it must not be confused with
1368 // "is this `use strict`". `function f(){ "\\1"; "use strict" }` is a function whose
1369 // body starts with an **OctalEscapeSequence** directive followed by the strict one,
1370 // and the second is therefore an early error; rejecting the first outright ended the
1371 // prologue instead, so the body parsed sloppy and the illegal escape was never
1372 // reported (`literals/string/legacy-*-strict-explicit-pragma`).
1373 if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
1374 // Still a directive — it just cannot *be* `use strict`: `UseStrictDirective`
1375 // requires the SV to be exactly `"use strict"`, so `"use\\u0020strict"` is an
1376 // ordinary directive. Reporting the raw text keeps the prologue going (which is
1377 // what makes a later `use strict` an early error) while making the comparison
1378 // fail for the right reason rather than by accident.
1379 return Some(raw.to_string());
1380 }
1381 // A directive is ASCII by construction (`"use strict"` and friends), so the lossy
1382 // conversion cannot be lossy here.
1383 Some(value.to_string_lossy().into_owned())
1384 }
1385
1386 fn slice(&self, span: Span) -> &'a str {
1387 let src = self.lexer.source();
1388 let start = span.start.offset as usize;
1389 let end = (span.end.offset as usize).min(src.len());
1390 src.get(start..end).unwrap_or("")
1391 }
1392
1393 // -- automatic semicolon insertion ------------------------------------
1394
1395 fn can_insert_semicolon(&self) -> bool {
1396 self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
1397 }
1398
1399 fn semicolon(&mut self) -> Result<()> {
1400 if self.eat_punct(Punct::Semicolon)? {
1401 return Ok(());
1402 }
1403 if self.can_insert_semicolon() {
1404 return Ok(());
1405 }
1406 // Not `unexpected()`: the reference's `js_parse_expect_semi` names what it wanted
1407 // (`expecting ';'`), which is why `1 2` says so rather than describing the `2`.
1408 Err(self.error("expecting ';'"))
1409 }
1410
1411 // -- statements --------------------------------------------------------
1412
1413 fn parse_statement_list_item(&mut self) -> Result<Stmt> {
1414 self.enter()?;
1415 let result = self.parse_statement_list_item_guarded();
1416 self.leave();
1417 result
1418 }
1419
1420 fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
1421 let cover_mark = self.cover_inits.len();
1422 let stmt = self.parse_statement_list_item_inner()?;
1423 if self.cover_inits.len() > cover_mark {
1424 let span = self.cover_inits[cover_mark];
1425 self.cover_inits.truncate(cover_mark);
1426 return Err(self.error_at("expecting '}'", span));
1427 }
1428 Ok(stmt)
1429 }
1430
1431 fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
1432 if self.at_keyword(Keyword::Function) {
1433 let start = self.current.span.start;
1434 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1435 if let Some(name) = &func.name {
1436 self.declare_function(&name.name)?;
1437 }
1438 return Ok(Stmt::new(
1439 StmtKind::FuncDecl(Box::new(func)),
1440 self.span_from(start),
1441 ));
1442 }
1443 if self.at_ident("async") {
1444 let peek = self.peek()?;
1445 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1446 let start = self.current.span.start;
1447 self.bump()?; // async
1448 let func = self.parse_function(FunctionForm::Declaration, true, Some(start))?;
1449 if let Some(name) = &func.name {
1450 self.declare_function(&name.name)?;
1451 }
1452 return Ok(Stmt::new(
1453 StmtKind::FuncDecl(Box::new(func)),
1454 self.span_from(start),
1455 ));
1456 }
1457 }
1458 if self.at_keyword(Keyword::Class) {
1459 let start = self.current.span.start;
1460 let class = self.parse_class(false)?;
1461 if let Some(name) = &class.name {
1462 self.declare_lexical(&name.name)?;
1463 }
1464 return Ok(Stmt::new(
1465 StmtKind::ClassDecl(Box::new(class)),
1466 self.span_from(start),
1467 ));
1468 }
1469 if self.at_keyword(Keyword::Var) {
1470 let start = self.current.span.start;
1471 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1472 self.semicolon()?;
1473 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1474 }
1475 if self.at_keyword(Keyword::Const) {
1476 let start = self.current.span.start;
1477 let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
1478 self.semicolon()?;
1479 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1480 }
1481 if self.at_ident("let") && self.let_starts_declaration()? {
1482 let start = self.current.span.start;
1483 let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
1484 self.semicolon()?;
1485 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1486 }
1487 // `await using x = …` is one declaration; `await` is only a keyword here when the
1488 // enclosing code may await at all, which is the same rule `await` expressions use.
1489 if self.at_ident("await") && self.ctx.in_async && self.await_using_follows()? {
1490 let start = self.current.span.start;
1491 // No top-level rejection here, unlike a plain `using`: the reference's check
1492 // lives on the `using` path only (`fd->is_eval && scope_level == body_scope`),
1493 // while `await using` reaches a branch that does not ask.
1494 //
1495 // The `case`-clause ban *does* apply, and for the same reason it applies to a
1496 // plain `using`: a clause is a statement list with nothing to terminate it, so
1497 // there is no point at which the resource could be disposed
1498 // (`await-using/syntax/await-using-invalid-switchstatement-caseclause`).
1499 if self.in_case_clause {
1500 return Err(self.error_at(
1501 "using declaration is not allowed in this context",
1502 self.span_from(start),
1503 ));
1504 }
1505 self.bump()?; // await
1506 let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
1507 self.semicolon()?;
1508 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1509 }
1510 if self.at_ident("using") && self.using_starts_declaration()? {
1511 let start = self.current.span.start;
1512 // A script's *own* scope has no block to end, so there would be nowhere to
1513 // dispose. The reference asks `scope_level == body_scope`: the program's scope
1514 // itself, not a block nested inside it — `{ using y = 1 }` is legal there and
1515 // disposes at the closing brace. A module's top level *is* a scope, so it does
1516 // not ask at all.
1517 if self.scopes.len() == 1 && !self.module {
1518 return Err(self.error_at(
1519 "using declaration is not allowed at the top level of a script",
1520 self.span_from(start),
1521 ));
1522 }
1523 // A `case`/`default` clause is a statement list with nothing to end it, so a
1524 // `using` there has no disposal point either. This is a separate early error
1525 // from the one above: it applies inside a function too, where the scope depth
1526 // is not 1.
1527 if self.in_case_clause {
1528 return Err(self.error_at(
1529 "using declaration is not allowed in this context",
1530 self.span_from(start),
1531 ));
1532 }
1533 let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
1534 self.semicolon()?;
1535 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1536 }
1537 // `import`/`export` declarations belong to the module's own statement list and
1538 // nowhere else: not inside a function, not inside a block. The scope depth is what
1539 // tells the two apart — the program's scope is the only one at depth 1 — and asking
1540 // it here is what turns `class C { m() { export default 1 } }` into the parse error
1541 // the reference reports instead of letting the compiler run into an `export` with
1542 // no module tables behind it.
1543 let at_module_top_level = self.module && self.scopes.len() == 1;
1544 if at_module_top_level && self.at_keyword(Keyword::Import) {
1545 let peek = self.peek()?;
1546 // `import(` and `import.meta` are expressions, not declarations.
1547 if !matches!(
1548 peek.kind,
1549 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1550 ) {
1551 return self.parse_import_decl();
1552 }
1553 }
1554 if at_module_top_level && self.at_keyword(Keyword::Export) {
1555 return self.parse_export_decl();
1556 }
1557 self.parse_statement()
1558 }
1559
1560 /// `let` is a declaration keyword when followed by a binding or a pattern.
1561 fn let_starts_declaration(&self) -> Result<bool> {
1562 let peek = self.peek()?;
1563 Ok(matches!(
1564 peek.kind,
1565 TokenKind::Ident(_)
1566 | TokenKind::Punct(Punct::LBracket)
1567 | TokenKind::Punct(Punct::LBrace)
1568 ))
1569 }
1570
1571 /// The token after a `using` declaration head's binding name, if a head starts here.
1572 ///
1573 /// `skip` is how many words come before `using` — `1` for `await using`. Returns `None`
1574 /// when the shape is not a declaration head at all: the binding must be a plain
1575 /// identifier with no line terminator before it.
1576 fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
1577 let mut lexer = self.lexer.clone();
1578 // The lexer is already positioned after the current token, so the first
1579 // `next_token` yields the token that follows it. `using` itself is `skip` words in,
1580 // and the binding is the token after it.
1581 let mut binding = None;
1582 for _ in 0..=skip {
1583 binding = Some(lexer.next_token()?);
1584 }
1585 let Some(binding) = binding else {
1586 return Ok(None);
1587 };
1588 if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
1589 return Ok(None);
1590 }
1591 Ok(Some(lexer.next_token()?))
1592 }
1593
1594 /// Whether `await using` starts a declaration here.
1595 ///
1596 /// `await` is followed by `using`, which is in turn followed by a binding name and `=`.
1597 /// Anything else — `await using(x)` where `using` is a function — is an `await`
1598 /// expression over an ordinary call.
1599 fn await_using_follows(&self) -> Result<bool> {
1600 Ok(matches!(
1601 self.using_head_tail(1)?.map(|token| token.kind),
1602 Some(TokenKind::Punct(Punct::Eq))
1603 ))
1604 }
1605
1606 /// Whether the `using` at the current token begins a declaration.
1607 ///
1608 /// `using` is a contextual keyword, not a reserved word: `using = 1`, `using(x)` and
1609 /// `using.f` are all ordinary expressions over a variable named `using`. The spec's
1610 /// rule is `using [no LineTerminator] BindingIdentifier =`, so the binding name has to
1611 /// be followed by `=`.
1612 ///
1613 /// Patterns are excluded on purpose: `using {a} = …` is not a using declaration, and
1614 /// the grammar forbids it, so it stays an expression statement that fails to parse as
1615 /// one.
1616 fn using_starts_declaration(&self) -> Result<bool> {
1617 Ok(matches!(
1618 self.using_head_tail(0)?.map(|token| token.kind),
1619 Some(TokenKind::Punct(Punct::Eq))
1620 ))
1621 }
1622
1623 /// Whether `using x of …` starts a `for` head here.
1624 ///
1625 /// The head has no initialiser, so the token after the binding is `of` (or `in`, which
1626 /// the caller then rejects: a `using` may only iterate a `for`-`of`).
1627 fn using_starts_for_head(&self) -> Result<bool> {
1628 Ok(matches!(
1629 self.using_head_tail(0)?.map(|token| token.kind),
1630 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1631 ))
1632 }
1633
1634 /// Whether `await using x of …` starts a `for` head here.
1635 fn await_using_starts_for_head(&self) -> Result<bool> {
1636 Ok(matches!(
1637 self.using_head_tail(1)?.map(|token| token.kind),
1638 Some(TokenKind::Ident(name)) if name == "of" || name == "in"
1639 ))
1640 }
1641
1642 fn parse_statement(&mut self) -> Result<Stmt> {
1643 let start = self.current.span.start;
1644 if self.at_punct(Punct::Semicolon) {
1645 self.bump()?;
1646 return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
1647 }
1648 if self.at_punct(Punct::LBrace) {
1649 let body = self.parse_block()?;
1650 return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
1651 }
1652 if self.at_keyword(Keyword::If) {
1653 return self.parse_if();
1654 }
1655 if self.at_keyword(Keyword::Do) {
1656 return self.parse_do_while();
1657 }
1658 if self.at_keyword(Keyword::While) {
1659 return self.parse_while();
1660 }
1661 if self.at_keyword(Keyword::For) {
1662 return self.parse_for();
1663 }
1664 if self.at_keyword(Keyword::Switch) {
1665 return self.parse_switch();
1666 }
1667 if self.at_keyword(Keyword::Try) {
1668 return self.parse_try();
1669 }
1670 if self.at_keyword(Keyword::Return) {
1671 return self.parse_return();
1672 }
1673 if self.at_keyword(Keyword::Throw) {
1674 return self.parse_throw();
1675 }
1676 if self.at_keyword(Keyword::Break) {
1677 return self.parse_break_continue(true);
1678 }
1679 if self.at_keyword(Keyword::Continue) {
1680 return self.parse_break_continue(false);
1681 }
1682 // `VariableStatement` is a `Statement`, not a `Declaration`: `if (x) var y = 1;`
1683 // and `with ({}) var y = 1;` are both legal. Only `let`, `const`, `function` and
1684 // `class` are restricted to a statement *list*. Recognising `var` only in
1685 // `parse_statement_list_item` made every single-statement position reject it.
1686 if self.at_keyword(Keyword::Var) {
1687 let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
1688 self.semicolon()?;
1689 return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
1690 }
1691 if self.at_keyword(Keyword::With) {
1692 return self.parse_with();
1693 }
1694 if self.at_keyword(Keyword::Debugger) {
1695 self.bump()?;
1696 self.semicolon()?;
1697 return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1698 }
1699 // `async function f(){}` is a declaration too, and Annex B never extended the
1700 // single-statement positions to cover it — only the plain form, and only in sloppy
1701 // mode. Left unhandled here it split into two statements (`async;` by ASI, then the
1702 // declaration in the enclosing list), so `with ({}) async function f(){}` was
1703 // accepted (`statements/with/decl-async-fun`).
1704 if self.at_ident("async") {
1705 let peek = self.peek()?;
1706 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
1707 return Err(self
1708 .error("invalid 'async function' declaration in a single statement context"));
1709 }
1710 }
1711 if self.at_keyword(Keyword::Function) {
1712 // Annex B: function declarations in statement position are legal in
1713 // sloppy mode (`if (x) function f() {}`).
1714 if self.strict {
1715 return Err(
1716 self.error("invalid 'function' declaration in a single statement context")
1717 );
1718 }
1719 // Only the *plain* form is extended. `B.3.2` rewrites `IfStatement` to accept a
1720 // `FunctionDeclaration`, and a `GeneratorDeclaration` is a different production
1721 // — so `if (1) function* g(){}` stays a `SyntaxError`, as does the same thing
1722 // behind a label (`LabelledItem : FunctionDeclaration` has no generator form
1723 // either). `async function` is rejected just above for the same reason.
1724 if matches!(self.peek()?.kind, TokenKind::Punct(Punct::Star)) {
1725 return Err(
1726 self.error("invalid generator declaration in a single statement context")
1727 );
1728 }
1729 let func = self.parse_function(FunctionForm::Declaration, false, None)?;
1730 if let Some(name) = &func.name {
1731 self.declare_function(&name.name)?;
1732 }
1733 return Ok(Stmt::new(
1734 StmtKind::FuncDecl(Box::new(func)),
1735 self.span_from(start),
1736 ));
1737 }
1738 if self.at_keyword(Keyword::Class) {
1739 return Err(self.error("invalid 'class' declaration in a single statement context"));
1740 }
1741 if self.at_keyword(Keyword::Import) {
1742 // `import(...)` and `import.meta` are *expressions*, so they are an ordinary
1743 // expression statement here. Only a declaration is restricted to the top
1744 // level of a module.
1745 let peek = self.peek()?;
1746 let expression = matches!(
1747 peek.kind,
1748 TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1749 );
1750 if !expression {
1751 return Err(self.error("'import' can only appear at the top level of a module"));
1752 }
1753 }
1754 if self.at_keyword(Keyword::Export) {
1755 return Err(self.error("'export' can only appear at the top level of a module"));
1756 }
1757 // Labelled statement.
1758 if let TokenKind::Ident(name) = &self.current.kind {
1759 // `await` is not a `LabelIdentifier` in module code, and where it is an
1760 // operator it is not an identifier at all — `await: 1` in a suspensible body
1761 // is an `await` expression whose operand is missing, not a label.
1762 if name == "await" && self.await_is_reserved() {
1763 if !self.ctx.in_async {
1764 // Reserved because this is module code, but not an operator: the
1765 // reference has a message for exactly this case.
1766 let peek = self.peek()?;
1767 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1768 return Err(self.error("unexpected 'await' keyword"));
1769 }
1770 }
1771 // Where `await` *is* an operator it is not an identifier at all, so
1772 // `await: 1` is an `await` expression with a missing operand. Falling
1773 // through leaves that to the expression parser, which says so.
1774 } else {
1775 let peek = self.peek()?;
1776 if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1777 return self.parse_labeled();
1778 }
1779 }
1780 }
1781 // `ExpressionStatement` carries `[lookahead ∉ { let [ }]`: a statement may not
1782 // *begin* with `let`, so `let\n[0] = 0` is a `SyntaxError` and not a member
1783 // expression on an identifier called `let`. The newline changes nothing — the
1784 // restriction is on the first two tokens.
1785 if self.at_ident("let") {
1786 let peek = self.peek()?;
1787 if matches!(peek.kind, TokenKind::Punct(Punct::LBracket)) {
1788 return Err(self.error("unexpected 'let [' in a statement"));
1789 }
1790 }
1791 self.parse_expression_statement()
1792 }
1793
1794 fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1795 self.expect_punct(Punct::LBrace)?;
1796 self.push_scope(Scope::block());
1797 // A block *inside* a `case` clause is a block, so `using` is legal there: the
1798 // early error is about a `using` sitting directly in the clause's statement list.
1799 let saved_in_case = self.in_case_clause;
1800 self.in_case_clause = false;
1801 let result = self.parse_block_body();
1802 self.in_case_clause = saved_in_case;
1803 self.pop_scope();
1804 let body = result?;
1805 self.bump()?; // }
1806 Ok(body)
1807 }
1808
1809 /// `{ … }` of a `catch` clause: parsed in the scope holding its parameter.
1810 fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1811 self.expect_punct(Punct::LBrace)?;
1812 let body = self.parse_block_body()?;
1813 self.bump()?; // }
1814 Ok(body)
1815 }
1816
1817 fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1818 let mut body = Vec::new();
1819 while !self.at_punct(Punct::RBrace) {
1820 if self.current.is_eof() {
1821 return Err(self.unexpected());
1822 }
1823 body.push(self.parse_statement_list_item()?);
1824 }
1825 Ok(body)
1826 }
1827
1828 fn parse_expression_statement(&mut self) -> Result<Stmt> {
1829 let start = self.current.span.start;
1830 let expr = self.parse_expression(true)?;
1831 self.semicolon()?;
1832 Ok(Stmt::new(
1833 StmtKind::Expr(Box::new(expr)),
1834 self.span_from(start),
1835 ))
1836 }
1837
1838 fn parse_if(&mut self) -> Result<Stmt> {
1839 let start = self.current.span.start;
1840 self.bump()?; // if
1841 self.expect_punct(Punct::LParen)?;
1842 let test = self.parse_expression(true)?;
1843 self.expect_punct(Punct::RParen)?;
1844 let cons = self.parse_statement()?;
1845 let alt = if self.eat_keyword(Keyword::Else)? {
1846 Some(Box::new(self.parse_statement()?))
1847 } else {
1848 None
1849 };
1850 Ok(Stmt::new(
1851 StmtKind::If {
1852 test: Box::new(test),
1853 cons: Box::new(cons),
1854 alt,
1855 },
1856 self.span_from(start),
1857 ))
1858 }
1859
1860 fn parse_do_while(&mut self) -> Result<Stmt> {
1861 let start = self.current.span.start;
1862 self.bump()?; // do
1863 self.loop_depth += 1;
1864 let body = self.parse_single_statement();
1865 self.loop_depth -= 1;
1866 let body = body?;
1867 if !self.eat_keyword(Keyword::While)? {
1868 return Err(self.unexpected());
1869 }
1870 self.expect_punct(Punct::LParen)?;
1871 let test = self.parse_expression(true)?;
1872 self.expect_punct(Punct::RParen)?;
1873 // `do … while (x)` allows a missing semicolon even without a newline.
1874 let _ = self.eat_punct(Punct::Semicolon)?;
1875 Ok(Stmt::new(
1876 StmtKind::DoWhile {
1877 body: Box::new(body),
1878 test: Box::new(test),
1879 },
1880 self.span_from(start),
1881 ))
1882 }
1883
1884 fn parse_while(&mut self) -> Result<Stmt> {
1885 let start = self.current.span.start;
1886 self.bump()?; // while
1887 self.expect_punct(Punct::LParen)?;
1888 let test = self.parse_expression(true)?;
1889 self.expect_punct(Punct::RParen)?;
1890 self.loop_depth += 1;
1891 let body = self.parse_single_statement();
1892 self.loop_depth -= 1;
1893 Ok(Stmt::new(
1894 StmtKind::While {
1895 test: Box::new(test),
1896 body: Box::new(body?),
1897 },
1898 self.span_from(start),
1899 ))
1900 }
1901
1902 /// The right-hand side of a `for`-`in`/`for`-`of` head.
1903 ///
1904 /// The two differ, and the difference is observable: the grammar says
1905 /// `for ( x in Expression )` but `for ( x of AssignmentExpression )`. So
1906 /// `for (x in {a:1}, {})` is legal (a sequence) while `for (x of [], [])` is a
1907 /// `SyntaxError` at the `)` (`for-of/head-expr-no-expr`, `for-in/head-expr-expr`).
1908 fn parse_for_in_of_right(&mut self, is_of: bool) -> Result<Expr> {
1909 if is_of {
1910 self.parse_assignment(true)
1911 } else {
1912 self.parse_expression(true)
1913 }
1914 }
1915
1916 fn parse_for(&mut self) -> Result<Stmt> {
1917 let start = self.current.span.start;
1918 self.bump()?; // for
1919 self.push_scope(Scope::block());
1920 let result = self.parse_for_inner(start);
1921 self.pop_scope();
1922 result
1923 }
1924
1925 fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1926 let mut is_await = false;
1927 if self.at_ident("await") && self.ctx.in_async {
1928 let peek = self.peek()?;
1929 if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1930 is_await = true;
1931 self.bump()?;
1932 }
1933 }
1934 self.expect_punct(Punct::LParen)?;
1935
1936 // `for (;;)`
1937 if self.at_punct(Punct::Semicolon) {
1938 self.bump()?;
1939 return self.parse_for_classic(start, None);
1940 }
1941
1942 // Declaration head.
1943 let decl_kind = if self.at_keyword(Keyword::Var) {
1944 Some(VarDeclKind::Var)
1945 } else if self.at_keyword(Keyword::Const) {
1946 Some(VarDeclKind::Const)
1947 } else if self.at_ident("let") && self.let_starts_declaration()? {
1948 Some(VarDeclKind::Let)
1949 } else if self.at_ident("using") && self.using_starts_for_head()? {
1950 Some(VarDeclKind::Using)
1951 } else if self.at_ident("await")
1952 && self.ctx.in_async
1953 && self.await_using_starts_for_head()?
1954 {
1955 self.bump()?; // await, leaving `using` as the keyword
1956 Some(VarDeclKind::AwaitUsing)
1957 } else {
1958 None
1959 };
1960 if let Some(kind) = decl_kind {
1961 let decl_start = self.current.span.start;
1962 let decl = self.parse_var_decl(kind, true, false)?;
1963 if self.at_for_head_keyword() {
1964 let is_of = self.at_contextual("of");
1965 if !is_of && decl.declarators.len() != 1 {
1966 return Err(self.error_at(
1967 "only one binding allowed in a for-in loop",
1968 self.span_from(decl_start),
1969 ));
1970 }
1971 if is_of && decl.declarators.len() != 1 {
1972 return Err(self.error_at(
1973 "only one binding allowed in a for-of loop",
1974 self.span_from(decl_start),
1975 ));
1976 }
1977 if let Some(declarator) = decl.declarators.first() {
1978 if declarator.init.is_some() {
1979 // `for (var x = 1 in y)` is legacy in sloppy mode only.
1980 if is_of || kind.is_lexical() || self.strict {
1981 return Err(self.error_at(
1982 if is_of {
1983 // The reference formats `%s` with the loop kind.
1984 "a declaration in the head of a for-of loop can't have an initializer"
1985 } else {
1986 "a declaration in the head of a for-in loop can't have an initializer"
1987 },
1988 declarator.span,
1989 ));
1990 }
1991 }
1992 }
1993 if is_await && !is_of {
1994 return Err(self.error("for await is only valid with 'of'"));
1995 }
1996 self.bump()?; // in / of
1997 let right = self.parse_for_in_of_right(is_of)?;
1998 self.expect_punct(Punct::RParen)?;
1999 self.loop_depth += 1;
2000 let body = self.parse_single_statement();
2001 self.loop_depth -= 1;
2002 let head = ForHead::VarDecl(decl);
2003 let span = self.span_from(start);
2004 return Ok(Stmt::new(
2005 if is_of {
2006 StmtKind::ForOf {
2007 is_await,
2008 left: head,
2009 right: Box::new(right),
2010 body: Box::new(body?),
2011 }
2012 } else {
2013 StmtKind::ForIn {
2014 left: head,
2015 right: Box::new(right),
2016 body: Box::new(body?),
2017 }
2018 },
2019 span,
2020 ));
2021 }
2022 self.expect_punct(Punct::Semicolon)?;
2023 return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
2024 }
2025
2026 // Expression head.
2027 let expr_start = self.current.span.start;
2028 let expr = self.parse_expression(false)?;
2029 if self.at_for_head_keyword() {
2030 let is_of = self.at_contextual("of");
2031 if is_await && !is_of {
2032 return Err(self.error("for await is only valid with 'of'"));
2033 }
2034 let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
2035 self.bump()?; // in / of
2036 let right = self.parse_for_in_of_right(is_of)?;
2037 self.expect_punct(Punct::RParen)?;
2038 self.loop_depth += 1;
2039 let body = self.parse_single_statement();
2040 self.loop_depth -= 1;
2041 let head = ForHead::Assign(Box::new(target));
2042 let span = self.span_from(start);
2043 return Ok(Stmt::new(
2044 if is_of {
2045 StmtKind::ForOf {
2046 is_await,
2047 left: head,
2048 right: Box::new(right),
2049 body: Box::new(body?),
2050 }
2051 } else {
2052 StmtKind::ForIn {
2053 left: head,
2054 right: Box::new(right),
2055 body: Box::new(body?),
2056 }
2057 },
2058 span,
2059 ));
2060 }
2061 let _ = expr_start;
2062 self.expect_punct(Punct::Semicolon)?;
2063 self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
2064 }
2065
2066 /// Whether the `for` head continues with `in` (a keyword) or `of` (a
2067 /// contextual keyword).
2068 fn at_for_head_keyword(&self) -> bool {
2069 self.at_keyword(Keyword::In) || self.at_contextual("of")
2070 }
2071
2072 fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
2073 let test = if self.at_punct(Punct::Semicolon) {
2074 None
2075 } else {
2076 Some(Box::new(self.parse_expression(true)?))
2077 };
2078 self.expect_punct(Punct::Semicolon)?;
2079 let update = if self.at_punct(Punct::RParen) {
2080 None
2081 } else {
2082 Some(Box::new(self.parse_expression(true)?))
2083 };
2084 self.expect_punct(Punct::RParen)?;
2085 self.loop_depth += 1;
2086 let body = self.parse_single_statement();
2087 self.loop_depth -= 1;
2088 Ok(Stmt::new(
2089 StmtKind::For {
2090 init,
2091 test,
2092 update,
2093 body: Box::new(body?),
2094 },
2095 self.span_from(start),
2096 ))
2097 }
2098
2099 fn parse_switch(&mut self) -> Result<Stmt> {
2100 let start = self.current.span.start;
2101 self.bump()?; // switch
2102 self.expect_punct(Punct::LParen)?;
2103 let discriminant = self.parse_expression(true)?;
2104 self.expect_punct(Punct::RParen)?;
2105 self.expect_punct(Punct::LBrace)?;
2106 self.switch_depth += 1;
2107 self.push_scope(Scope::block());
2108 let mut cases = Vec::new();
2109 let mut seen_default = false;
2110 while !self.at_punct(Punct::RBrace) {
2111 if self.current.is_eof() {
2112 self.switch_depth -= 1;
2113 return Err(self.unexpected());
2114 }
2115 let case_start = self.current.span.start;
2116 let test = if self.eat_keyword(Keyword::Case)? {
2117 Some(Box::new(self.parse_expression(true)?))
2118 } else if self.eat_keyword(Keyword::Default)? {
2119 if seen_default {
2120 self.switch_depth -= 1;
2121 return Err(self.error("duplicate 'default' clause in switch statement"));
2122 }
2123 seen_default = true;
2124 None
2125 } else {
2126 self.switch_depth -= 1;
2127 return Err(self.unexpected());
2128 };
2129 self.expect_punct(Punct::Colon)?;
2130 let mut body = Vec::new();
2131 let saved_in_case = self.in_case_clause;
2132 self.in_case_clause = true;
2133 while !self.at_punct(Punct::RBrace)
2134 && !self.at_keyword(Keyword::Case)
2135 && !self.at_keyword(Keyword::Default)
2136 {
2137 if self.current.is_eof() {
2138 self.in_case_clause = saved_in_case;
2139 self.switch_depth -= 1;
2140 return Err(self.unexpected());
2141 }
2142 match self.parse_statement_list_item() {
2143 Ok(stmt) => body.push(stmt),
2144 Err(error) => {
2145 self.in_case_clause = saved_in_case;
2146 self.switch_depth -= 1;
2147 return Err(error);
2148 }
2149 }
2150 }
2151 self.in_case_clause = saved_in_case;
2152 cases.push(SwitchCase {
2153 test,
2154 body,
2155 span: self.span_from(case_start),
2156 });
2157 }
2158 self.switch_depth -= 1;
2159 self.bump()?; // }
2160 // The switch body's block scope has to be popped here. Leaving it pushed leaked one
2161 // scope per `switch` for the rest of the file, so everything after a switch was
2162 // declared into a *stale* scope: `function f(value){ switch(value){} } let value=9`
2163 // was rejected as "identifier 'value' has already been declared", and the `value`
2164 // it clashed with was the function's own parameter. That made the parser refuse
2165 // valid programs — and it never showed up on its own, only when a top-level `let`
2166 // happened to reuse a name used inside an earlier switch.
2167 self.pop_scope();
2168 Ok(Stmt::new(
2169 StmtKind::Switch {
2170 discriminant: Box::new(discriminant),
2171 cases,
2172 },
2173 self.span_from(start),
2174 ))
2175 }
2176
2177 fn parse_try(&mut self) -> Result<Stmt> {
2178 let start = self.current.span.start;
2179 self.bump()?; // try
2180 let block = self.parse_block()?;
2181 let mut handler = None;
2182 let mut finalizer = None;
2183 if self.at_keyword(Keyword::Catch) {
2184 let catch_start = self.current.span.start;
2185 self.bump()?;
2186 // The catch parameter and the body share one scope, so `catch (e) {
2187 // let e; }` is an early error. A *simple* parameter is exempt from
2188 // the `var` check (`catch (e) { var e; }` is legal), a destructured
2189 // one is not (`catch ({e}) { var e; }` is rejected) — this matches
2190 // the reference engine.
2191 let param = if self.eat_punct(Punct::LParen)? {
2192 let pattern = self.parse_binding_target()?;
2193 self.expect_punct(Punct::RParen)?;
2194 Some(pattern)
2195 } else {
2196 None
2197 };
2198 self.push_scope(Scope::block());
2199 let body = match ¶m {
2200 // A simple parameter shares the body's scope: `catch (e) { let e;
2201 // }` is an error, `catch (e) { var e; }` is not.
2202 Some(Pattern {
2203 kind: PatternKind::Ident(id),
2204 ..
2205 }) => {
2206 if let Some(scope) = self.scopes.last_mut() {
2207 scope.catch_names.push(id.name.clone());
2208 }
2209 self.parse_catch_body()
2210 }
2211 // A destructuring parameter is declared lexically in the clause's
2212 // own scope, with the body nested inside it: `catch ({e}) { var
2213 // e; }` is an error (the `var` hoists past the binding) while
2214 // `catch ({e}) { let e; }` is not.
2215 Some(pattern) => {
2216 self.declare_pattern(pattern, false)?;
2217 self.parse_block()
2218 }
2219 None => self.parse_catch_body(),
2220 };
2221 self.pop_scope();
2222 let body = body?;
2223 handler = Some(CatchClause {
2224 param,
2225 body,
2226 span: self.span_from(catch_start),
2227 });
2228 }
2229 if self.eat_keyword(Keyword::Finally)? {
2230 finalizer = Some(self.parse_block()?);
2231 }
2232 if handler.is_none() && finalizer.is_none() {
2233 return Err(self.error("expecting catch or finally"));
2234 }
2235 Ok(Stmt::new(
2236 StmtKind::Try {
2237 block,
2238 handler,
2239 finalizer,
2240 },
2241 self.span_from(start),
2242 ))
2243 }
2244
2245 fn parse_return(&mut self) -> Result<Stmt> {
2246 let start = self.current.span.start;
2247 let span = self.current.span;
2248 if !self.ctx.in_function {
2249 return Err(self.error_at("return not in a function", span));
2250 }
2251 if self.ctx.in_static_block {
2252 // A static block is written as a block, not a function: `return` has nowhere
2253 // to go. The reference checks this before it consumes the keyword, so the
2254 // error sits on `return` itself.
2255 return Err(self.error_at("return in a static initializer block", span));
2256 }
2257 self.bump()?;
2258 let argument = if self.at_punct(Punct::Semicolon)
2259 || self.at_punct(Punct::RBrace)
2260 || self.current.is_eof()
2261 || self.current.newline_before
2262 {
2263 None
2264 } else {
2265 Some(Box::new(self.parse_expression(true)?))
2266 };
2267 self.semicolon()?;
2268 Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
2269 }
2270
2271 fn parse_throw(&mut self) -> Result<Stmt> {
2272 let start = self.current.span.start;
2273 self.bump()?; // throw
2274 if self.current.newline_before {
2275 return Err(self.error("line terminator not allowed after 'throw'"));
2276 }
2277 let argument = self.parse_expression(true)?;
2278 self.semicolon()?;
2279 Ok(Stmt::new(
2280 StmtKind::Throw(Box::new(argument)),
2281 self.span_from(start),
2282 ))
2283 }
2284
2285 fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
2286 let start = self.current.span.start;
2287 let keyword_span = self.current.span;
2288 self.bump()?;
2289 let label = if matches!(self.current.kind, TokenKind::Ident(_))
2290 && !self.current.newline_before
2291 {
2292 let ident = self.expect_ident()?;
2293 let found = self.labels.iter().rev().find(|l| l.name == ident.name);
2294 match found {
2295 None => {
2296 return Err(
2297 self.error_at(format!("label '{}' not found", ident.name), ident.span)
2298 );
2299 }
2300 Some(label) => {
2301 if !is_break && label.kind != LabelKind::Iteration {
2302 return Err(self.error_at(
2303 format!("continue must be inside loop (label '{}')", ident.name),
2304 ident.span,
2305 ));
2306 }
2307 }
2308 }
2309 Some(ident)
2310 } else {
2311 if !is_break && self.loop_depth == 0 {
2312 return Err(self.error_at("continue must be inside loop", keyword_span));
2313 }
2314 if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
2315 {
2316 return Err(self.error_at("break must be inside loop or switch", keyword_span));
2317 }
2318 None
2319 };
2320 self.semicolon()?;
2321 Ok(Stmt::new(
2322 if is_break {
2323 StmtKind::Break(label)
2324 } else {
2325 StmtKind::Continue(label)
2326 },
2327 self.span_from(start),
2328 ))
2329 }
2330
2331 /// A statement in a position that holds exactly one, where the grammar allows no
2332 /// declaration.
2333 ///
2334 /// `if (x) function f(){}` is the Annex B exception (`IfStatement` was extended to
2335 /// accept one) and is handled at the `if`. Everywhere else — the bodies of `with`,
2336 /// `while`, `do`, `for` — a function declaration is a `SyntaxError`, and so is one
2337 /// behind any number of labels: `with({}) label: function f(){}` is the same mistake
2338 /// spelled longer.
2339 fn parse_single_statement(&mut self) -> Result<Stmt> {
2340 let stmt = self.parse_statement()?;
2341 // A labelled function declaration is a `LabelledFunctionStatement`, which the
2342 // statement *list* accepts in sloppy mode; here it is still a declaration in a
2343 // single-statement position.
2344 let mut innermost = &stmt;
2345 while let StmtKind::Labeled { body, .. } = &innermost.kind {
2346 innermost = body;
2347 }
2348 if matches!(innermost.kind, StmtKind::FuncDecl(_)) {
2349 return Err(self.error_at(
2350 "function declarations can't appear in single-statement context",
2351 stmt.span,
2352 ));
2353 }
2354 Ok(stmt)
2355 }
2356
2357 fn parse_with(&mut self) -> Result<Stmt> {
2358 let start = self.current.span.start;
2359 let span = self.current.span;
2360 if self.strict {
2361 return Err(self.error_at("invalid keyword: with", span));
2362 }
2363 self.bump()?; // with
2364 self.expect_punct(Punct::LParen)?;
2365 let object = self.parse_expression(true)?;
2366 self.expect_punct(Punct::RParen)?;
2367 let body = self.parse_single_statement()?;
2368 Ok(Stmt::new(
2369 StmtKind::With {
2370 object: Box::new(object),
2371 body: Box::new(body),
2372 },
2373 self.span_from(start),
2374 ))
2375 }
2376
2377 fn parse_labeled(&mut self) -> Result<Stmt> {
2378 let start = self.current.span.start;
2379 let label = self.expect_ident()?;
2380 self.expect_punct(Punct::Colon)?;
2381 if self.labels.iter().any(|l| l.name == label.name) {
2382 return Err(self.error_at(
2383 format!("label '{}' already declared", label.name),
2384 label.span,
2385 ));
2386 }
2387 let kind = if self.at_keyword(Keyword::For)
2388 || self.at_keyword(Keyword::While)
2389 || self.at_keyword(Keyword::Do)
2390 {
2391 LabelKind::Iteration
2392 } else {
2393 LabelKind::Other
2394 };
2395 self.labels.push(Label {
2396 name: label.name.clone(),
2397 kind,
2398 });
2399 let body = self.parse_statement();
2400 self.labels.pop();
2401 Ok(Stmt::new(
2402 StmtKind::Labeled {
2403 label,
2404 body: Box::new(body?),
2405 },
2406 self.span_from(start),
2407 ))
2408 }
2409
2410 // -- declarations ------------------------------------------------------
2411
2412 fn parse_var_decl(
2413 &mut self,
2414 kind: VarDeclKind,
2415 in_for_head: bool,
2416 require_init: bool,
2417 ) -> Result<VarDecl> {
2418 let start = self.current.span.start;
2419 self.bump()?; // var / let / const / using
2420 self.parse_var_declarators(kind, in_for_head, require_init, start)
2421 }
2422
2423 /// A declaration whose leading keyword has already been consumed by the caller.
2424 ///
2425 /// `await using x = …` is written with two words, so the `await` is read first and only
2426 /// the `using` is left here.
2427 fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
2428 let start = self.current.span.start;
2429 if !self.at_ident(keyword) {
2430 return Err(self.error(format!("expected '{keyword}'")));
2431 }
2432 self.bump()?;
2433 self.parse_var_declarators(kind, false, true, start)
2434 }
2435
2436 fn parse_var_declarators(
2437 &mut self,
2438 kind: VarDeclKind,
2439 in_for_head: bool,
2440 require_init: bool,
2441 start: Position,
2442 ) -> Result<VarDecl> {
2443 let mut declarators = Vec::new();
2444 loop {
2445 let declarator_start = self.current.span.start;
2446 let target = self.parse_binding_target()?;
2447 // Declared here, before the initialiser: the reference calls `js_define_var`
2448 // from `js_parse_var`'s `set_val`, which is reached with the name just
2449 // consumed, so a redeclaration points at the `=` (or whatever follows)
2450 // rather than at the end of the statement.
2451 self.declare_pattern(&target, !kind.is_lexical())?;
2452 // `using` disposes a value, so it binds a name and nothing else: a pattern has
2453 // no single resource to dispose.
2454 if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
2455 return Err(self.error_at(
2456 "binding patterns are not allowed in using declarations",
2457 target.span,
2458 ));
2459 }
2460 let init = if self.eat_punct(Punct::Eq)? {
2461 // `for (var x = a in b;;)` must not parse `a in b` as the
2462 // initialiser: the head uses AssignmentExpression[~In].
2463 Some(Box::new(self.parse_assignment(!in_for_head)?))
2464 } else {
2465 None
2466 };
2467 if init.is_none() && require_init {
2468 if kind == VarDeclKind::Const {
2469 return Err(self.error("missing initializer for const variable"));
2470 }
2471 if kind.is_using() {
2472 return Err(self.error("missing initializer in using declaration"));
2473 }
2474 if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
2475 return Err(self.error_at(
2476 "missing initializer in destructuring declaration",
2477 target.span,
2478 ));
2479 }
2480 }
2481 if kind.is_lexical() {
2482 let mut names = Vec::new();
2483 target.bound_names(&mut names);
2484 if let Some(name) = names.iter().find(|n| n.name == "let") {
2485 return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
2486 }
2487 }
2488 declarators.push(Declarator {
2489 target,
2490 init,
2491 span: self.span_from(declarator_start),
2492 });
2493 if !self.eat_punct(Punct::Comma)? {
2494 break;
2495 }
2496 }
2497 Ok(VarDecl {
2498 kind,
2499 declarators,
2500 span: self.span_from(start),
2501 })
2502 }
2503
2504 /// A binding element: `target` or `target = default`. Used for parameters and
2505 /// for elements of array/object patterns.
2506 fn parse_binding_element(&mut self) -> Result<Pattern> {
2507 let pattern = self.parse_binding_target()?;
2508 if self.eat_punct(Punct::Eq)? {
2509 let start = pattern.span.start;
2510 let default = self.parse_assignment(self.allow_in)?;
2511 return Ok(Pattern::new(
2512 PatternKind::Assign {
2513 target: Box::new(pattern),
2514 default: Box::new(default),
2515 },
2516 self.span_from(start),
2517 ));
2518 }
2519 Ok(pattern)
2520 }
2521
2522 /// A binding target: `Ident`, `[ … ]` or `{ … }`, with no default value.
2523 /// Used for declarators, `catch` parameters, rest elements and `for` heads.
2524 fn parse_binding_target(&mut self) -> Result<Pattern> {
2525 self.enter()?;
2526 let result = self.parse_binding_target_unguarded();
2527 self.leave();
2528 result
2529 }
2530
2531 fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
2532 let start = self.current.span.start;
2533 if self.at_punct(Punct::LBracket) {
2534 return self.parse_array_pattern(start);
2535 }
2536 if self.at_punct(Punct::LBrace) {
2537 return self.parse_object_pattern(start);
2538 }
2539 let ident = self.expect_binding_ident()?;
2540 Ok(Pattern::new(
2541 PatternKind::Ident(ident),
2542 self.span_from(start),
2543 ))
2544 }
2545
2546 fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
2547 self.expect_punct(Punct::LBracket)?;
2548 let mut elements = Vec::new();
2549 let mut rest = None;
2550 loop {
2551 if self.at_punct(Punct::RBracket) {
2552 break;
2553 }
2554 if self.at_punct(Punct::Comma) {
2555 self.bump()?;
2556 elements.push(None);
2557 continue;
2558 }
2559 if self.at_punct(Punct::Ellipsis) {
2560 self.bump()?;
2561 let target = self.parse_binding_target()?;
2562 if self.at_punct(Punct::Comma) {
2563 return Err(self.error("rest element must be the last one"));
2564 }
2565 rest = Some(Box::new(RestElement::Pattern(target)));
2566 break;
2567 }
2568 let element_start = self.current.span.start;
2569 let element = self.parse_binding_element()?;
2570 let span = self.span_from(element_start);
2571 elements.push(Some(PatternElement::Pattern(element)));
2572 let _ = span;
2573 if !self.eat_punct(Punct::Comma)? {
2574 break;
2575 }
2576 }
2577 self.expect_punct(Punct::RBracket)?;
2578 Ok(Pattern::new(
2579 PatternKind::Array { elements, rest },
2580 self.span_from(start),
2581 ))
2582 }
2583
2584 fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
2585 self.expect_punct(Punct::LBrace)?;
2586 let mut properties = Vec::new();
2587 let mut rest = None;
2588 loop {
2589 if self.at_punct(Punct::RBrace) {
2590 break;
2591 }
2592 if self.at_punct(Punct::Ellipsis) {
2593 self.bump()?;
2594 let target = self.parse_binding_target()?;
2595 rest = Some(Box::new(RestElement::Pattern(target)));
2596 if self.at_punct(Punct::Comma) {
2597 return Err(self.error("rest element must be the last one"));
2598 }
2599 break;
2600 }
2601 let property_start = self.current.span.start;
2602 let key = self.parse_property_key()?;
2603 if self.eat_punct(Punct::Colon)? {
2604 let value = self.parse_binding_element()?;
2605 properties.push(Some(PatternElement::Property {
2606 key,
2607 value,
2608 shorthand: false,
2609 span: self.span_from(property_start),
2610 }));
2611 } else {
2612 let PropName::Literal(PropKey::Str(name)) = &key else {
2613 return Err(
2614 self.error("expecting ':' after a computed or numeric property key")
2615 );
2616 };
2617 let span = self.span_from(property_start);
2618 let ident = Ident {
2619 name: name.to_string_lossy().into_owned(),
2620 span,
2621 };
2622 self.check_binding_name(&ident.name, ident.span)?;
2623 let mut value = Pattern::new(PatternKind::Ident(ident), span);
2624 if self.eat_punct(Punct::Eq)? {
2625 let default = self.parse_assignment(self.allow_in)?;
2626 value = Pattern::new(
2627 PatternKind::Assign {
2628 target: Box::new(value),
2629 default: Box::new(default),
2630 },
2631 span,
2632 );
2633 }
2634 properties.push(Some(PatternElement::Property {
2635 key,
2636 value,
2637 shorthand: true,
2638 span,
2639 }));
2640 }
2641 if !self.eat_punct(Punct::Comma)? {
2642 break;
2643 }
2644 }
2645 self.expect_punct(Punct::RBrace)?;
2646 Ok(Pattern::new(
2647 PatternKind::Object { properties, rest },
2648 self.span_from(start),
2649 ))
2650 }
2651
2652 /// A property key: identifier, string, number, computed or `#private`.
2653 fn parse_property_key(&mut self) -> Result<PropName> {
2654 match self.current.kind.clone() {
2655 TokenKind::Ident(name) => {
2656 self.bump()?;
2657 Ok(PropName::Literal(PropKey::Str(Wtf8::new(name))))
2658 }
2659 TokenKind::Keyword(kw) => {
2660 // Reserved words are valid property names (`{ if: 1 }`).
2661 self.bump()?;
2662 Ok(PropName::Literal(PropKey::Str(Wtf8::new(kw.as_str()))))
2663 }
2664 TokenKind::String(value) => {
2665 self.bump()?;
2666 Ok(PropName::Literal(PropKey::Str(value)))
2667 }
2668 TokenKind::Number(NumberLiteral::Int(v)) => {
2669 self.bump()?;
2670 Ok(PropName::Literal(PropKey::Num(v as f64)))
2671 }
2672 TokenKind::Number(NumberLiteral::Float(v)) => {
2673 self.bump()?;
2674 Ok(PropName::Literal(PropKey::Num(v)))
2675 }
2676 TokenKind::BigInt(big) => Err(self.error(format!(
2677 "BigInt property keys are not supported ('{}n')",
2678 big.digits
2679 ))),
2680 TokenKind::Punct(Punct::LBracket) => {
2681 self.bump()?;
2682 let expr = self.parse_assignment(true)?;
2683 self.expect_punct(Punct::RBracket)?;
2684 Ok(PropName::Computed(Box::new(expr)))
2685 }
2686 TokenKind::Punct(Punct::Hash) => {
2687 let ident = self.parse_private_name()?;
2688 Ok(PropName::Private(ident))
2689 }
2690 // `js_parse_property_name` in the reference: an object literal or a class
2691 // member whose name is not an identifier, string, number or computed key.
2692 _ => Err(self.error("invalid property name")),
2693 }
2694 }
2695
2696 // -- functions ---------------------------------------------------------
2697
2698 /// `function`, `function*`, `async function` or `async function*`.
2699 ///
2700 /// `start` is where the *whole* form begins, which is not where `parse_function` is
2701 /// entered for the async ones: the caller has already consumed `async`, and the
2702 /// reference keeps the position it captured before doing so
2703 /// (`js_parse_expr`'s `source_ptr`). Passing `None` means "the `function` keyword is
2704 /// the start", which is right for the synchronous forms.
2705 fn parse_function(
2706 &mut self,
2707 form: FunctionForm,
2708 is_async: bool,
2709 start: Option<Position>,
2710 ) -> Result<Function> {
2711 let start = start.unwrap_or(self.current.span.start);
2712 self.bump()?; // function
2713 let is_generator = self.eat_punct(Punct::Star)?;
2714 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2715 let ident = if form == FunctionForm::Declaration {
2716 self.expect_binding_ident()?
2717 } else {
2718 self.expect_ident()?
2719 };
2720 if is_generator && ident.name == "yield" {
2721 return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
2722 }
2723 if is_async && ident.name == "await" {
2724 return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
2725 }
2726 // §15.2.1: a `BindingIdentifier` may not be `eval` or `arguments` in strict
2727 // code — the same rule `check_binding_name` applies to a `var`/`let`, with the
2728 // function-specific wording the reference uses. A *declaration* reaches it
2729 // through `expect_binding_ident`; an expression name is read with plain
2730 // `expect_ident`, so the check has to be made here for the two to agree.
2731 // Sloppy code keeps `(function eval(){})`, which is legal.
2732 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
2733 return Err(self.error_at("invalid function name in strict code", ident.span));
2734 }
2735 Some(ident)
2736 } else {
2737 if form == FunctionForm::Declaration {
2738 return Err(self.error("function name expected"));
2739 }
2740 None
2741 };
2742 // A function declaration in a *block* is a lexical binding of that block, and the
2743 // reference checks it right here: `js_parse_function_decl2` calls
2744 // `define_var(JS_VAR_DEF_FUNCTION_DECL)` with the name just consumed, so the
2745 // reported position is the token that follows it — `(` for `function a(`. The
2746 // body-scope case is a different check and happens after the whole function, which
2747 // is why it is made at the call site instead.
2748 //
2749 // Doing it here also means a block-level conflict is found before the body is
2750 // parsed, so the body's own errors cannot mask it.
2751 if form == FunctionForm::Declaration
2752 && let Some(ident) = &name
2753 {
2754 self.declare_block_function(&ident.name, !is_async && !is_generator)?;
2755 }
2756 let saved = self.ctx;
2757 self.ctx = FnCtx {
2758 in_function: true,
2759 in_generator: is_generator,
2760 in_async: is_async,
2761 in_method: false,
2762 in_derived_constructor: false,
2763 in_static_block: false,
2764 arguments_allowed: true,
2765 };
2766 let saved_top = self.top_level;
2767 self.top_level = false;
2768 // Strictness is per function: `function f(){ "use strict"; }` must leave the
2769 // code *after* it sloppy. Without this save the directive leaked outwards, the
2770 // enclosing script was compiled as strict, and a later `function g(){}` lost its
2771 // declaration status — `typeof g` then raised instead of answering, because an
2772 // implicit global is not a declaration.
2773 let params_result = self.parse_formal_parameters();
2774 let result = match params_result {
2775 Ok(params) => self.parse_function_body(params, false),
2776 Err(err) => Err(err),
2777 };
2778 self.ctx = saved;
2779 self.top_level = saved_top;
2780 let (params, params_span, body, strict) = result?;
2781 // §15.2.1, the *other half* of the function-name rule: a name that was legal when
2782 // it was read becomes illegal if the body turns out to be strict. The check in the
2783 // `name` block above can only see the enclosing mode — `function eval(){ "use
2784 // strict" }` is read while the function is still sloppy — so the body's own mode has
2785 // to be applied afterwards. The reference makes exactly this second check
2786 // (`js_parse_function_decl2`, after the body); without it the four `name-*-strict-body`
2787 // cases in `expressions/function` accepted the declaration.
2788 if strict
2789 && let Some(ident) = &name
2790 && (ident.name == "eval" || ident.name == "arguments")
2791 {
2792 let span = ident.span;
2793 return Err(self.error_at("invalid function name in strict code", span));
2794 }
2795 Ok(Function {
2796 name,
2797 params,
2798 body,
2799 is_async,
2800 is_generator,
2801 strict,
2802 is_arrow: false,
2803 span: self.span_from(start),
2804 params_span,
2805 source_span: None,
2806 })
2807 }
2808
2809 fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2810 // Every parameter list, from every entry point (function declaration/expression,
2811 // method, arrow, dynamic `new Function`): the flag makes `yield`/`await` an early
2812 // error there, and is restored on the way out so a *nested* function's body — which
2813 // is also reached from inside a default expression — is unaffected.
2814 let saved = self.in_formal_parameters;
2815 self.in_formal_parameters = true;
2816 let result = self.parse_formal_parameters_inner();
2817 self.in_formal_parameters = saved;
2818 result
2819 }
2820
2821 fn parse_formal_parameters_inner(&mut self) -> Result<Vec<Pattern>> {
2822 self.expect_punct(Punct::LParen)?;
2823 let mut params = Vec::new();
2824 loop {
2825 if self.at_punct(Punct::RParen) {
2826 break;
2827 }
2828 if self.at_punct(Punct::Ellipsis) {
2829 self.bump()?;
2830 // The rest parameter's own binding needs the same check: `function f(...)`
2831 // is a missing parameter, not a malformed one.
2832 if !self.at_formal_parameter() {
2833 return Err(self.error("missing formal parameter"));
2834 }
2835 let target = self.parse_binding_target()?;
2836 if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2837 return Err(
2838 self.error_at("rest element cannot have a default value", target.span)
2839 );
2840 }
2841 params.push(Pattern::new(
2842 PatternKind::Rest(Box::new(target.clone())),
2843 target.span,
2844 ));
2845 // A rest parameter ends the list, so the only thing that may follow is
2846 // `)`. The reference simply asks for it: `js_parse_expect(s, ')')`.
2847 if self.at_punct(Punct::Comma) {
2848 return Err(self.error("expecting ')'"));
2849 }
2850 break;
2851 }
2852 if !self.at_formal_parameter() {
2853 return Err(self.error("missing formal parameter"));
2854 }
2855 let param = self.parse_binding_element()?;
2856 self.check_parameter(¶m)?;
2857 params.push(param);
2858 if !self.eat_punct(Punct::Comma)? {
2859 break;
2860 }
2861 }
2862 self.expect_punct(Punct::RParen)?;
2863 Ok(params)
2864 }
2865
2866 fn check_parameter(&self, param: &Pattern) -> Result<()> {
2867 match ¶m.kind {
2868 PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2869 PatternKind::Assign { target, .. } => self.check_parameter(target),
2870 _ => Ok(()),
2871 }
2872 }
2873
2874 fn parse_function_body(
2875 &mut self,
2876 params: Vec<Pattern>,
2877 is_method: bool,
2878 ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2879 let params_span = self.prev_end;
2880 // Strictness is per function, so the body saves and restores it itself rather
2881 // than trusting every caller to do so: `function f(){ "use strict" }` must
2882 // leave the code after it sloppy, and the enclosing scope may well have been
2883 // strict too. The returned flag is the body's own mode.
2884 let saved_strict = self.strict;
2885 if !self.at_punct(Punct::LBrace) {
2886 return Err(self.unexpected());
2887 }
2888 // A function body is one of the places a `using` may live, so a function defined
2889 // inside a `case` clause starts with a clean slate for that check.
2890 let saved_in_case = self.in_case_clause;
2891 self.in_case_clause = false;
2892 let param_names = simple_parameter_names(¶ms);
2893 let simple_params = params
2894 .iter()
2895 .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2896 let mut body = Vec::new();
2897 let mut prologue = true;
2898 let mut strict_seen = false;
2899 // Any Annex B octal escape in this body makes a later `"use strict"` directive an
2900 // early error, however many tokens separate them: `function f() { "\1"; "use
2901 // strict" }` is a `SyntaxError` (Annex B B.1.2 makes the ban cover the whole
2902 // function body, not just the token after the directive). The lexer counts them so
2903 // the question can be asked once the body ends.
2904 self.lexer.reset_legacy_octal_count();
2905 self.bump()?; // {
2906 // Where the final duplicate-parameter check points: the reference runs it with the
2907 // body's first token as `s->token`, so an empty body reports the `}` and
2908 // `{ return 1 }` reports the `return`.
2909 let body_start = self.current.span;
2910 self.push_scope(Scope::function(param_names));
2911 while !self.at_punct(Punct::RBrace) {
2912 if self.current.is_eof() {
2913 return Err(self.unexpected());
2914 }
2915 let stmt = self.parse_statement_list_item()?;
2916 if prologue {
2917 match self.directive_value(&stmt) {
2918 Some(directive) if directive == "use strict" => {
2919 strict_seen = true;
2920 self.enter_strict()?;
2921 }
2922 Some(_) => {}
2923 None => prologue = false,
2924 }
2925 }
2926 body.push(stmt);
2927 }
2928 self.pop_scope();
2929 self.bump()?; // }
2930 // The body's own mode, still in force while the early errors below are
2931 // checked; the enclosing mode is restored once they are done.
2932 let body_strict = self.strict;
2933 if strict_seen && self.lexer.legacy_octal_count() > 0 {
2934 return Err(self.error_at(
2935 "octal escape sequences are not allowed in strict mode",
2936 Span::new(params_span, params_span),
2937 ));
2938 }
2939 if strict_seen && !simple_params {
2940 return Err(self.error_at(
2941 // The reference spells the directive with double quotes inside the message.
2942 "\"use strict\" not allowed in function with default or destructuring parameter",
2943 Span::new(params_span, params_span),
2944 ));
2945 }
2946 // Duplicate parameter names. Where they are illegal at all is the reference's
2947 // condition in `js_parse_function_args`: strict mode, a non-simple list, an arrow,
2948 // or a method. A plain sloppy `function f(a, a){}` is legal (last wins), and so is
2949 // a sloppy generator or `async function` — only an async *method* is covered.
2950 //
2951 // Which of the two messages is used depends on how the duplicate was reached, and
2952 // that is a different question: at *parameter-parse* time the reference checks each
2953 // name with `duplicate parameter names`, and it only gets there when the list holds
2954 // an `=` anywhere or the name sits inside a destructuring pattern. Everything else
2955 // waits for the check above, which says `duplicate argument names`.
2956 self.check_duplicate_parameters(
2957 ¶ms,
2958 body_strict || !simple_params || is_method,
2959 body_start,
2960 )?;
2961 // A `"use strict"` directive retroactively makes the parameter list strict, and
2962 // `eval`/`arguments`/`let` may not be binding names there — the list was parsed
2963 // before the directive was seen, so the names have to be re-checked now.
2964 // `function(eval){"use strict"}` is a `SyntaxError`, and so is
2965 // `Function("eval", ""use strict";")` (`15.3.2.1-11-3-s`).
2966 if body_strict && !saved_strict {
2967 for param in ¶ms {
2968 let mut names = Vec::new();
2969 param.bound_names(&mut names);
2970 for name in names {
2971 if name.name == "eval" || name.name == "arguments" || name.name == "let" {
2972 return Err(
2973 self.error_at("invalid variable name in strict mode", name.span)
2974 );
2975 }
2976 }
2977 }
2978 }
2979 let params_span_value = Span::new(params_span, params_span);
2980 self.strict = saved_strict;
2981 self.lexer.set_strict(saved_strict);
2982 self.in_case_clause = saved_in_case;
2983 Ok((
2984 params,
2985 params_span_value,
2986 FunctionBody::Block(body),
2987 body_strict,
2988 ))
2989 }
2990
2991 // -- classes -----------------------------------------------------------
2992
2993 fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2994 // "classes are parsed and executed in strict mode" — `js_parse_class` says so by
2995 // setting `JS_MODE_STRICT` before it consumes the `class` token, which makes the
2996 // *name*, the heritage and every member strict, not just the method bodies.
2997 //
2998 // Without this, a method body was parsed sloppy: `class C { m() { x = 1 } }` created
2999 // a global instead of throwing, and every method's `mode:` line in the disassembly
3000 // disagreed with the reference.
3001 let saved_strict = self.strict;
3002 let enter = self.enter_strict();
3003 let result = match enter {
3004 Ok(()) => self.parse_class_body(is_expression),
3005 Err(error) => Err(error),
3006 };
3007 self.strict = saved_strict;
3008 self.lexer.set_strict(saved_strict);
3009 result
3010 }
3011
3012 fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
3013 let start = self.current.span.start;
3014 self.bump()?; // class
3015 let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
3016 if is_expression {
3017 Some(self.expect_ident()?)
3018 } else {
3019 Some(self.expect_binding_ident()?)
3020 }
3021 } else {
3022 if !is_expression {
3023 return Err(self.error("class statement requires a name"));
3024 }
3025 None
3026 };
3027 let super_class = if self.eat_keyword(Keyword::Extends)? {
3028 Some(Box::new(self.parse_lhs_expression()?))
3029 } else {
3030 None
3031 };
3032 let has_super = super_class.is_some();
3033 self.private.push(PrivateEnv::default());
3034 self.expect_punct(Punct::LBrace)?;
3035 let mut elements = Vec::new();
3036 let mut seen_constructor = false;
3037 let result = (|| -> Result<()> {
3038 while !self.at_punct(Punct::RBrace) {
3039 // No end-of-input guard here: `class A {` must report `invalid property
3040 // name`, which is what falls out of asking for the element's name. An
3041 // early `unexpected()` would pre-empt that with a vaguer message.
3042 if self.eat_punct(Punct::Semicolon)? {
3043 continue;
3044 }
3045 elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
3046 }
3047 Ok(())
3048 })();
3049 // Settle the forward references now that the body is complete, bubbling any the
3050 // body did not declare outward: an inner class body may name an outer class's
3051 // private field, and only the outermost body knows the full set.
3052 let settled = match self.private.pop() {
3053 Some(mut env) => {
3054 let mut carried = Vec::new();
3055 for (name, span) in std::mem::take(&mut env.pending) {
3056 if env.contains(&name) {
3057 continue;
3058 }
3059 match self.private.last_mut() {
3060 Some(outer) => outer.pending.push((name, span)),
3061 None => carried.push((name, span)),
3062 }
3063 }
3064 carried
3065 }
3066 None => Vec::new(),
3067 };
3068 if let Some((name, span)) = settled
3069 .into_iter()
3070 .min_by_key(|(_, span)| span.start.offset)
3071 {
3072 return Err(self.error_at(format!("undefined private field '#{name}'"), span));
3073 }
3074 result?;
3075 // The `}` itself, before it is consumed: a class with no written constructor gets
3076 // a synthetic one created *at* this token (see [`Class::body_end`]).
3077 let body_end = self.current.span.start;
3078 self.bump()?; // }
3079 // A class is the *constructor function object*, so `A.toString()` reports the whole
3080 // class definition, not just the `constructor(){}` member — the two are the same
3081 // object, and `Function.prototype.toString` answers with the class's own source
3082 // range (`class-declaration-explicit-ctor`). The span is widened after the body so
3083 // the closing `}` is included, while `params_span` and the line table keep pointing
3084 // at the member itself.
3085 let class_span = self.span_from(start);
3086 for element in &mut elements {
3087 if let ClassElement::Method {
3088 kind: MethodKind::Constructor,
3089 func,
3090 ..
3091 } = element
3092 {
3093 func.source_span = Some(class_span);
3094 }
3095 }
3096 Ok(Class {
3097 name,
3098 super_class,
3099 elements,
3100 span: class_span,
3101 body_end,
3102 })
3103 }
3104
3105 /// `static { … }`, with `static` already consumed and `{` the current token.
3106 ///
3107 /// The body is parsed in a context of its own. It is written as a block, but the
3108 /// reference compiles it as a function, and every early error below follows from
3109 /// that: `this` is the class, `super.x` resolves against the class's home object, but
3110 /// `super()` is not a thing a static block can do and `return` has no function to
3111 /// return from.
3112 fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
3113 let saved = self.ctx;
3114 let saved_top = self.top_level;
3115 self.ctx = FnCtx {
3116 in_function: true,
3117 in_generator: false,
3118 in_async: false,
3119 // `super.x` is legal in a static block: its home object is the class.
3120 in_method: true,
3121 in_derived_constructor: false,
3122 in_static_block: true,
3123 arguments_allowed: false,
3124 };
3125 self.top_level = false;
3126 // A class body is strict, so everything in it is — including a static block. The
3127 // restore is unconditional, unlike a `"use strict"` directive's, because the block
3128 // cannot opt out of what the class already decided. `enter_strict` cannot fail
3129 // here (it only objects to an octal literal, and nothing has been scanned yet), but
3130 // it is spelled as a saved result so the context is restored either way.
3131 let saved_strict = self.strict;
3132 let enter = self.enter_strict();
3133 // A `break` or `continue` cannot escape a static block, so the label and loop
3134 // counters start empty.
3135 let saved_loop = self.loop_depth;
3136 let saved_switch = self.switch_depth;
3137 let saved_labels = std::mem::take(&mut self.labels);
3138 self.loop_depth = 0;
3139 self.switch_depth = 0;
3140 let body_start = self.current.span.start;
3141 let body = match enter {
3142 Ok(()) => self.parse_block(),
3143 Err(error) => Err(error),
3144 };
3145 self.strict = saved_strict;
3146 self.lexer.set_strict(saved_strict);
3147 self.ctx = saved;
3148 self.top_level = saved_top;
3149 self.loop_depth = saved_loop;
3150 self.switch_depth = saved_switch;
3151 self.labels = saved_labels;
3152 let body = body?;
3153 Ok(ClassElement::StaticBlock {
3154 body,
3155 body_start,
3156 span: self.span_from(start),
3157 })
3158 }
3159
3160 fn parse_class_element(
3161 &mut self,
3162 has_super: bool,
3163 seen_constructor: &mut bool,
3164 ) -> Result<ClassElement> {
3165 let start = self.current.span.start;
3166 let mut is_static = false;
3167 if self.at_ident("static") {
3168 let peek = self.peek()?;
3169 let is_modifier = !matches!(
3170 peek.kind,
3171 TokenKind::Punct(Punct::LParen)
3172 | TokenKind::Punct(Punct::Eq)
3173 | TokenKind::Punct(Punct::Semicolon)
3174 | TokenKind::Punct(Punct::RBrace)
3175 );
3176 if is_modifier {
3177 self.bump()?; // static
3178 if self.at_punct(Punct::LBrace) {
3179 return self.parse_static_block(start);
3180 }
3181 is_static = true;
3182 }
3183 }
3184 // `Function.prototype.toString` reports a method without its `static` modifier but
3185 // *with* `async`/`*`/`get`/`set`, so the recorded span starts here — the spec's
3186 // `MethodDefinition` grammar excludes exactly `static`.
3187 let reported_start = self.current.span.start;
3188
3189 // Modifiers: async, get, set, *
3190 let mut is_async = false;
3191 let mut is_generator = false;
3192 let mut accessor: Option<MethodKind> = None;
3193 if self.at_ident("async") {
3194 let peek = self.peek()?;
3195 let is_modifier = !matches!(
3196 peek.kind,
3197 TokenKind::Punct(Punct::LParen)
3198 | TokenKind::Punct(Punct::Eq)
3199 | TokenKind::Punct(Punct::Semicolon)
3200 | TokenKind::Punct(Punct::RBrace)
3201 ) && !peek.newline_before;
3202 if is_modifier {
3203 self.bump()?;
3204 is_async = true;
3205 }
3206 }
3207 if self.at_punct(Punct::Star) {
3208 self.bump()?;
3209 is_generator = true;
3210 }
3211 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
3212 let is_get = self.at_ident("get");
3213 let peek = self.peek()?;
3214 if is_property_key_start(&peek.kind) {
3215 self.bump()?;
3216 accessor = Some(if is_get {
3217 MethodKind::Get
3218 } else {
3219 MethodKind::Set
3220 });
3221 }
3222 }
3223 let key = self.parse_property_key()?;
3224
3225 // `#constructor` is not a name a private member may have, in any of its forms — a
3226 // method, an accessor or a field. Reported at the token after the name (`(`, `=`, `;`),
3227 // which is where the reference's `js_parse_error` points.
3228 if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
3229 return Err(self.error("invalid method name"));
3230 }
3231 // Nor may `constructor` carry a method modifier: `constructor` is the one member name
3232 // that has its own production, so a generator, an async method or an accessor called
3233 // `constructor` is `invalid method name`. A `static constructor` is an ordinary
3234 // method, and a field named `constructor` is rejected further down with its own
3235 // message.
3236 if !is_static
3237 && (is_generator || is_async || accessor.is_some())
3238 && matches!(&key, PropName::Literal(PropKey::Str(name)) if name.as_str() == Some("constructor"))
3239 {
3240 return Err(self.error("invalid method name"));
3241 }
3242
3243 // Private names must be registered (duplicates are early errors).
3244 if let PropName::Private(ident) = &key {
3245 if let Some(env) = self.private.last_mut() {
3246 if !env.declare(&ident.name, accessor, is_static) {
3247 return Err(self.error_at(
3248 // The reference words this without the name:
3249 // `js_parse_error(s, "private class field is already defined")`.
3250 "private class field is already defined".to_string(),
3251 ident.span,
3252 ));
3253 }
3254 }
3255 }
3256
3257 if self.at_punct(Punct::LParen) {
3258 let kind = match accessor {
3259 Some(kind) => kind,
3260 None => {
3261 let is_constructor = !is_static
3262 && !is_generator
3263 && !is_async
3264 && matches!(&key, PropName::Literal(PropKey::Str(s)) if s.as_str() == Some("constructor"));
3265 if is_constructor {
3266 if *seen_constructor {
3267 return Err(self.error_at(
3268 "property constructor appears more than once",
3269 self.span_from(start),
3270 ));
3271 }
3272 *seen_constructor = true;
3273 MethodKind::Constructor
3274 } else {
3275 MethodKind::Method
3276 }
3277 }
3278 };
3279 if kind == MethodKind::Constructor && (is_generator || is_async) {
3280 return Err(self.error("a constructor may not be a generator or async"));
3281 }
3282 let saved = self.ctx;
3283 self.ctx = FnCtx {
3284 in_function: true,
3285 in_generator: is_generator,
3286 in_async: is_async,
3287 in_method: true,
3288 in_derived_constructor: kind == MethodKind::Constructor && has_super,
3289 in_static_block: false,
3290 arguments_allowed: true,
3291 };
3292 let saved_top = self.top_level;
3293 self.top_level = false;
3294 let result = (|| -> Result<Function> {
3295 let params = self.parse_formal_parameters()?;
3296 let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
3297 Ok(Function {
3298 name: None,
3299 params,
3300 body,
3301 is_async,
3302 is_generator,
3303 strict,
3304 is_arrow: false,
3305 span: Span::new(reported_start, self.prev_end),
3306 params_span,
3307 source_span: None,
3308 })
3309 })();
3310 self.ctx = saved;
3311 self.top_level = saved_top;
3312 let func = result?;
3313 if is_static {
3314 if let PropName::Literal(PropKey::Str(name)) = &key {
3315 if name == "prototype" {
3316 return Err(self.error_at("invalid method name", func.span));
3317 }
3318 }
3319 }
3320 if kind == MethodKind::Get && !func.params.is_empty() {
3321 return Err(self.error_at(
3322 "invalid number of arguments for getter or setter",
3323 func.span,
3324 ));
3325 }
3326 if kind == MethodKind::Set && func.params.len() != 1 {
3327 return Err(self.error_at(
3328 "invalid number of arguments for getter or setter",
3329 func.span,
3330 ));
3331 }
3332 return Ok(ClassElement::Method {
3333 key,
3334 is_static,
3335 kind,
3336 func: Box::new(func),
3337 span: self.span_from(start),
3338 });
3339 }
3340
3341 // Field definition.
3342 if accessor.is_some() {
3343 return Err(self.error("expecting '(' after an accessor name"));
3344 }
3345 if let PropName::Literal(PropKey::Str(name)) = &key {
3346 // §15.7.1: a `FieldDefinition` may not be named `constructor`, and `static`
3347 // does not exempt it — `class C { static constructor; }` is as much an early
3348 // error as the instance form. Only a *method* named `constructor` is special
3349 // (the constructor), and a computed `["constructor"]` is an ordinary name.
3350 // Reading the rule as "the instance constructor's name" let the static form
3351 // through (`fields-literal-name-static-propname-constructor`).
3352 if name == "constructor" {
3353 return Err(self.error("classes may not have a field named 'constructor'"));
3354 }
3355 if name == "prototype" && is_static {
3356 return Err(self.error("classes may not have a static property named 'prototype'"));
3357 }
3358 }
3359 // The initialiser is its own function — it runs per instance, or once for a
3360 // static field, with the class's home object — so it gets its own context. That
3361 // is what makes `super.x` legal in a field but `arguments` and `super()` not.
3362 let saved = self.ctx;
3363 let saved_top = self.top_level;
3364 self.ctx = FnCtx {
3365 in_function: true,
3366 in_generator: false,
3367 in_async: false,
3368 in_method: true,
3369 in_derived_constructor: false,
3370 in_static_block: false,
3371 arguments_allowed: false,
3372 };
3373 self.top_level = false;
3374 let value = self
3375 .eat_punct(Punct::Eq)?
3376 .then(|| self.parse_assignment(true));
3377 self.ctx = saved;
3378 self.top_level = saved_top;
3379 let value = match value {
3380 Some(value) => Some(Box::new(value?)),
3381 None => None,
3382 };
3383 // Fields are terminated by `;`, `}` or a line break.
3384 self.semicolon()?;
3385 Ok(ClassElement::Field {
3386 key,
3387 is_static,
3388 value,
3389 span: self.span_from(start),
3390 })
3391 }
3392
3393 // -- modules -----------------------------------------------------------
3394
3395 fn parse_import_decl(&mut self) -> Result<Stmt> {
3396 let start = self.current.span.start;
3397 self.bump()?; // import
3398 let mut specifiers = Vec::new();
3399 if let TokenKind::String(source) = self.current.kind.clone() {
3400 let source = as_specifier(&source);
3401 self.bump()?;
3402 let attributes = self.parse_import_attributes()?;
3403 self.semicolon()?;
3404 return Ok(Stmt::new(
3405 StmtKind::Import(Box::new(ImportDecl {
3406 specifiers,
3407 source,
3408 attributes,
3409 span: self.span_from(start),
3410 })),
3411 self.span_from(start),
3412 ));
3413 }
3414 // Default import.
3415 if matches!(self.current.kind, TokenKind::Ident(_)) {
3416 let local = self.expect_ident()?;
3417 specifiers.push(ImportSpecifier::Default(local));
3418 if !self.eat_punct(Punct::Comma)? {
3419 return self.finish_import(start, specifiers);
3420 }
3421 }
3422 if self.at_punct(Punct::Star) {
3423 self.bump()?;
3424 if !self.eat_contextual("as")? {
3425 return Err(self.unexpected());
3426 }
3427 let local = self.expect_ident()?;
3428 specifiers.push(ImportSpecifier::Namespace(local));
3429 return self.finish_import(start, specifiers);
3430 }
3431 if self.at_punct(Punct::LBrace) {
3432 self.bump()?;
3433 while !self.at_punct(Punct::RBrace) {
3434 let imported = self.parse_module_name()?;
3435 let local = if self.eat_contextual("as")? {
3436 self.expect_ident()?
3437 } else {
3438 match &imported {
3439 ModuleName::Ident(id) => id.clone(),
3440 ModuleName::Str(_) => {
3441 return Err(self.error_at(
3442 "a string module name must be followed by 'as'",
3443 self.current.span,
3444 ));
3445 }
3446 }
3447 };
3448 specifiers.push(ImportSpecifier::Named { imported, local });
3449 if !self.eat_punct(Punct::Comma)? {
3450 break;
3451 }
3452 }
3453 self.expect_punct(Punct::RBrace)?;
3454 } else if !specifiers.is_empty() {
3455 return Err(self.unexpected());
3456 } else if self.at_punct(Punct::LBrace) {
3457 unreachable!("handled above");
3458 } else {
3459 return Err(self.unexpected());
3460 }
3461 self.finish_import(start, specifiers)
3462 }
3463
3464 fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3465 if !self.eat_contextual("from")? {
3466 return Err(self.unexpected());
3467 }
3468 let TokenKind::String(source) = self.current.kind.clone() else {
3469 return Err(self.error("string expected"));
3470 };
3471 let source = as_specifier(&source);
3472 self.bump()?;
3473 let attributes = self.parse_import_attributes()?;
3474 self.semicolon()?;
3475 let span = self.span_from(start);
3476 for specifier in &specifiers {
3477 let local = match specifier {
3478 ImportSpecifier::Default(id) => id,
3479 ImportSpecifier::Namespace(id) => id,
3480 ImportSpecifier::Named { local, .. } => local,
3481 };
3482 // An `ImportedBinding` is a `BindingIdentifier`, and module code is always
3483 // strict, so `import { x as eval }` and `import { arguments } from "m"` are
3484 // early errors (§16.2.1.1). Only `declare_lexical` ran here, which checks for
3485 // duplicates and nothing about the name — so `as eval` was accepted outright and
3486 // the bare form failed later with "Could not find export 'eval'", a *resolution*
3487 // error where the test wants a parse-time one
3488 // (`module-code/early-import-{eval,arguments}` and the `-as-` pair).
3489 self.check_binding_name(&local.name, local.span)?;
3490 self.declare_lexical(&local.name)?;
3491 if let Some(scope) = self.scopes.last_mut()
3492 && !scope.import_names.iter().any(|n| n == &local.name)
3493 {
3494 scope.import_names.push(local.name.clone());
3495 }
3496 }
3497 Ok(Stmt::new(
3498 StmtKind::Import(Box::new(ImportDecl {
3499 specifiers,
3500 source,
3501 attributes,
3502 span,
3503 })),
3504 span,
3505 ))
3506 }
3507
3508 fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3509 let mut attributes = Vec::new();
3510 let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3511 if !has_with {
3512 return Ok(attributes);
3513 }
3514 let peek = self.peek()?;
3515 if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3516 return Ok(attributes);
3517 }
3518 self.bump()?; // with / assert
3519 self.expect_punct(Punct::LBrace)?;
3520 while !self.at_punct(Punct::RBrace) {
3521 let attr_start = self.current.span.start;
3522 let key = match self.current.kind.clone() {
3523 TokenKind::Ident(name) => name,
3524 TokenKind::String(value) => as_specifier(&value),
3525 _ => return Err(self.error("expecting an import attribute name")),
3526 };
3527 self.bump()?;
3528 self.expect_punct(Punct::Colon)?;
3529 let TokenKind::String(value) = self.current.kind.clone() else {
3530 return Err(self.error("expecting an import attribute value string"));
3531 };
3532 let value = as_specifier(&value);
3533 self.bump()?;
3534 attributes.push(ImportAttribute {
3535 key,
3536 value,
3537 span: self.span_from(attr_start),
3538 });
3539 if !self.eat_punct(Punct::Comma)? {
3540 break;
3541 }
3542 }
3543 self.expect_punct(Punct::RBrace)?;
3544 Ok(attributes)
3545 }
3546
3547 fn parse_module_name(&mut self) -> Result<ModuleName> {
3548 match self.current.kind.clone() {
3549 TokenKind::String(value) => {
3550 self.bump()?;
3551 Ok(ModuleName::Str(as_specifier(&value)))
3552 }
3553 // `ModuleExportName : IdentifierName | StringLiteral` — an *IdentifierName*, so
3554 // every reserved word is allowed here and none of the name-position checks
3555 // apply (`export { _await as await }`, `import { if as if_ }`). Going through
3556 // `expect_ident` rejected `await`: the lexer hands it back as an identifier and
3557 // `expect_ident` refuses it in a module, which is the right answer for a
3558 // *binding* and the wrong one for a module export name
3559 // (`module-code/instn-named-id-name`).
3560 TokenKind::Ident(name) => {
3561 let span = self.current.span;
3562 self.bump()?;
3563 Ok(ModuleName::Ident(Ident { name, span }))
3564 }
3565 TokenKind::Keyword(kw) => {
3566 let span = self.current.span;
3567 self.bump()?;
3568 Ok(ModuleName::Ident(Ident {
3569 name: kw.as_str().to_string(),
3570 span,
3571 }))
3572 }
3573 // `export {a as}`: the alias may be an identifier or a string, and the
3574 // reference names both (`js_parse_error(s, "identifier or string expected")`).
3575 _ => Err(self.error("identifier or string expected")),
3576 }
3577 }
3578
3579 fn parse_export_decl(&mut self) -> Result<Stmt> {
3580 let start = self.current.span.start;
3581 self.bump()?; // export
3582 if self.at_punct(Punct::Star) {
3583 self.bump()?;
3584 let mut exported = None;
3585 if self.eat_contextual("as")? {
3586 exported = Some(self.parse_module_name()?);
3587 }
3588 if !self.eat_contextual("from")? {
3589 return Err(self.error("expecting 'from' after 'export *'"));
3590 }
3591 let TokenKind::String(source) = self.current.kind.clone() else {
3592 return Err(self.error("string expected"));
3593 };
3594 let source = as_specifier(&source);
3595 self.bump()?;
3596 let attributes = self.parse_import_attributes()?;
3597 self.semicolon()?;
3598 let span = self.span_from(start);
3599 return Ok(Stmt::new(
3600 StmtKind::Export(Box::new(ExportDecl {
3601 kind: ExportKind::All {
3602 source,
3603 exported,
3604 attributes,
3605 },
3606 span,
3607 })),
3608 span,
3609 ));
3610 }
3611 if self.eat_keyword(Keyword::Default)? {
3612 let value = if self.at_keyword(Keyword::Function) {
3613 let func = self.parse_function(FunctionForm::Expression, false, None)?;
3614 // `export default function F(){}` declares `F` — the export is anonymous but
3615 // the *name* is a binding of the module scope, so a second `F` is a
3616 // `SyntaxError` (`export-default-*-declaration-binding-exists`). It is a
3617 // lexical binding and not a hoisted function declaration: §16.2.3.1 puts a
3618 // `HoistableDeclaration` in `VarDeclaredNames` only under `export
3619 // HoistableDeclaration`, and this production is not that one.
3620 if let Some(name) = &func.name {
3621 self.check_binding_name(&name.name, name.span)?;
3622 self.declare_lexical(&name.name)?;
3623 }
3624 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3625 } else if self.at_ident("async") {
3626 let peek = self.peek()?;
3627 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3628 self.bump()?;
3629 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3630 if let Some(name) = &func.name {
3631 self.check_binding_name(&name.name, name.span)?;
3632 self.declare_lexical(&name.name)?;
3633 }
3634 Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3635 } else {
3636 self.parse_assignment(true)?
3637 }
3638 } else if self.at_keyword(Keyword::Class) {
3639 let class = self.parse_class(true)?;
3640 if let Some(name) = &class.name {
3641 self.check_binding_name(&name.name, name.span)?;
3642 self.declare_lexical(&name.name)?;
3643 }
3644 Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3645 } else {
3646 let expr = self.parse_assignment(true)?;
3647 self.semicolon()?;
3648 expr
3649 };
3650 let span = self.span_from(start);
3651 return Ok(Stmt::new(
3652 StmtKind::Export(Box::new(ExportDecl {
3653 kind: ExportKind::Default(Box::new(value)),
3654 span,
3655 })),
3656 span,
3657 ));
3658 }
3659 if self.at_keyword(Keyword::Var)
3660 || self.at_keyword(Keyword::Const)
3661 || self.at_keyword(Keyword::Function)
3662 || self.at_keyword(Keyword::Class)
3663 || (self.at_ident("let") && self.let_starts_declaration()?)
3664 {
3665 let decl = self.parse_statement_list_item()?;
3666 let span = self.span_from(start);
3667 return Ok(Stmt::new(
3668 StmtKind::Export(Box::new(ExportDecl {
3669 kind: ExportKind::Declaration(Box::new(decl)),
3670 span,
3671 })),
3672 span,
3673 ));
3674 }
3675 if self.at_ident("async") {
3676 let peek = self.peek()?;
3677 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3678 let decl = self.parse_statement_list_item()?;
3679 let span = self.span_from(start);
3680 return Ok(Stmt::new(
3681 StmtKind::Export(Box::new(ExportDecl {
3682 kind: ExportKind::Declaration(Box::new(decl)),
3683 span,
3684 })),
3685 span,
3686 ));
3687 }
3688 }
3689 if self.at_punct(Punct::LBrace) {
3690 self.bump()?;
3691 let mut specifiers = Vec::new();
3692 let mut candidates: Vec<(String, Span)> = Vec::new();
3693 let mut source = None;
3694 while !self.at_punct(Punct::RBrace) {
3695 let spec_start = self.current.span.start;
3696 let local = self.parse_module_name()?;
3697 let exported = if self.eat_contextual("as")? {
3698 self.parse_module_name()?
3699 } else {
3700 local.clone()
3701 };
3702 // Deferred: whether these name *local* bindings (and so have to be
3703 // checked against the module's declarations) depends on whether a
3704 // `from` follows, which is not known until the closing brace.
3705 if let ModuleName::Ident(id) = &local {
3706 candidates.push((id.name.clone(), id.span));
3707 }
3708 specifiers.push(ExportSpecifier {
3709 local,
3710 exported,
3711 span: self.span_from(spec_start),
3712 });
3713 if !self.eat_punct(Punct::Comma)? {
3714 break;
3715 }
3716 }
3717 self.expect_punct(Punct::RBrace)?;
3718 let mut attributes = Vec::new();
3719 let has_from = self.eat_contextual("from")?;
3720 if !has_from {
3721 // `export { a }` re-exports a binding of this module and must name one;
3722 // `export { a } from "m"` names an export of `m` and is checked when the
3723 // module is linked, not here.
3724 //
3725 // A **string** in the local position has no binding to name at all:
3726 // §16.2.3.1 makes `ReferencedBindings of ExportClause contains any
3727 // StringLiterals` an early error, which is how `export { "foo" as "bar" }`
3728 // is rejected while `export { "foo" as "bar" } from "m"` is fine
3729 // (`export-expname-string-binding`, `…-unpaired-surrogate`).
3730 for specifier in &specifiers {
3731 if matches!(specifier.local, ModuleName::Str(_)) {
3732 return Err(self
3733 .error_at(
3734 "a string export name must be followed by 'from'",
3735 specifier.span,
3736 )
3737 .positionless());
3738 }
3739 }
3740 self.pending_exports.extend(candidates);
3741 }
3742 if has_from {
3743 let TokenKind::String(value) = self.current.kind.clone() else {
3744 return Err(self.error("string expected"));
3745 };
3746 let value = as_specifier(&value);
3747 self.bump()?;
3748 source = Some(value);
3749 attributes = self.parse_import_attributes()?;
3750 }
3751 self.semicolon()?;
3752 let span = self.span_from(start);
3753 return Ok(Stmt::new(
3754 StmtKind::Export(Box::new(ExportDecl {
3755 kind: ExportKind::Named {
3756 specifiers,
3757 source,
3758 attributes,
3759 },
3760 span,
3761 })),
3762 span,
3763 ));
3764 }
3765 Err(self.unexpected())
3766 }
3767
3768 // -- patterns from expressions ----------------------------------------
3769
3770 fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3771 self.expr_to_pattern_inner(expr, kind, false)
3772 }
3773
3774 fn expr_to_pattern_inner(
3775 &mut self,
3776 expr: Expr,
3777 kind: TargetKind,
3778 nested: bool,
3779 ) -> Result<Pattern> {
3780 let span = expr.span;
3781 match expr.kind {
3782 ExprKind::Ident(ident) => {
3783 if kind == TargetKind::Binding {
3784 self.check_binding_name(&ident.name, ident.span)?;
3785 } else {
3786 self.check_identifier(&ident.name, ident.span)?;
3787 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3788 return Err(self.error_at(
3789 format!("invalid assignment to '{}' in strict mode", ident.name),
3790 ident.span,
3791 ));
3792 }
3793 }
3794 Ok(Pattern::new(PatternKind::Ident(ident), span))
3795 }
3796 // `(a) = 1` and `(a.b) = 1` are fine — parens do not change a simple target —
3797 // but `({}) = 1` is not: `AssignmentTargetType` of a *ParenthesizedExpression*
3798 // is `simple` only when what it wraps is, and an object or array literal
3799 // becomes a pattern only where the grammar says so, which never sits behind a
3800 // parenthesis. `({} = 1)` is still valid, because there the parens wrap the
3801 // whole assignment and the literal is the direct left-hand side.
3802 ExprKind::Paren(inner) => {
3803 let pattern = self.expr_to_pattern_inner(*inner, kind, nested)?;
3804 if matches!(
3805 pattern.unparen_kind(),
3806 PatternKind::Object { .. } | PatternKind::Array { .. }
3807 ) {
3808 return Err(self.error_at("invalid assignment target", span));
3809 }
3810 Ok(pattern)
3811 }
3812 ExprKind::Array { elements } => {
3813 self.check_spread_trailing_comma(span, "rest element must be the last one")?;
3814 let mut out = Vec::new();
3815 let mut rest = None;
3816 let count = elements.len();
3817 for (index, element) in elements.into_iter().enumerate() {
3818 match element {
3819 None => out.push(None),
3820 Some(ArrayElement::Expr(expr)) => {
3821 let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3822 out.push(Some(PatternElement::Pattern(pattern)));
3823 }
3824 Some(ArrayElement::Spread(expr)) => {
3825 if index + 1 != count {
3826 return Err(
3827 self.error_at("rest element must be the last one", expr.span)
3828 );
3829 }
3830 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3831 }
3832 }
3833 }
3834 Ok(Pattern::new(
3835 PatternKind::Array {
3836 elements: out,
3837 rest,
3838 },
3839 span,
3840 ))
3841 }
3842 ExprKind::Object(properties) => {
3843 self.check_spread_trailing_comma(span, "assignment rest property must be last")?;
3844 self.cover_inits
3845 .retain(|cover| !span_contains(span, *cover));
3846 let mut out = Vec::new();
3847 let mut rest = None;
3848 let count = properties.len();
3849 for (index, property) in properties.into_iter().enumerate() {
3850 match property {
3851 ObjectProperty::Spread(expr) => {
3852 if index + 1 != count {
3853 return Err(
3854 self.error_at("rest element must be the last one", expr.span)
3855 );
3856 }
3857 rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3858 }
3859 ObjectProperty::Property {
3860 key,
3861 value,
3862 kind: _,
3863 shorthand,
3864 span,
3865 } => {
3866 let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3867 out.push(Some(PatternElement::Property {
3868 key,
3869 value: pattern,
3870 shorthand,
3871 span,
3872 }));
3873 }
3874 }
3875 }
3876 Ok(Pattern::new(
3877 PatternKind::Object {
3878 properties: out,
3879 rest,
3880 },
3881 span,
3882 ))
3883 }
3884 ExprKind::Assign { op, target, value } if op.is_simple() => {
3885 // `{a = 1}` inside a pattern: the target must itself be a pattern.
3886 let target = match target.kind {
3887 PatternKind::Ident(ident) => {
3888 // The name checks the bare-identifier arm below runs have to run
3889 // here too, because this arm copies the identifier straight into a
3890 // pattern instead of recursing. `{ eval = 0 } = {}` is a
3891 // `SyntaxError` in strict mode for exactly that reason
3892 // (`obj-id-init-simple-strict`), and a shorthand with a default is
3893 // the only way to reach a pattern target without passing through
3894 // the other arm.
3895 self.check_target_name(&ident.name, ident.span, kind)?;
3896 Pattern::new(PatternKind::Ident(ident), target.span)
3897 }
3898 other => {
3899 let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3900 self.expr_to_pattern_inner(expr, kind, nested)?
3901 }
3902 };
3903 Ok(Pattern::new(
3904 PatternKind::Assign {
3905 target: Box::new(target),
3906 default: value,
3907 },
3908 span,
3909 ))
3910 }
3911 ExprKind::Member {
3912 object,
3913 property,
3914 optional,
3915 } => {
3916 if kind == TargetKind::Binding {
3917 return Err(self.error_at("invalid binding pattern", span));
3918 }
3919 if optional {
3920 return Err(self.error_at("invalid assignment target", span));
3921 }
3922 let op_pos = expr.op_pos;
3923 Ok(Pattern::new(
3924 PatternKind::Member(Box::new(MemberPattern {
3925 object,
3926 property,
3927 span,
3928 op_pos,
3929 })),
3930 span,
3931 ))
3932 }
3933 ExprKind::OptionalChain(_) => {
3934 Err(self.error_at("invalid assignment left-hand side", span))
3935 }
3936 // QuickJS reports `a() = 1` at run time (it evaluates the callee
3937 // first, then rejects the reference) but rejects the same thing
3938 // inside a destructuring pattern at parse time. Every other
3939 // non-assignable expression is rejected here.
3940 other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3941 Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3942 ),
3943 _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3944 // Inside an object or array literal being reinterpreted as a pattern the
3945 // reference says `invalid destructuring target`; a non-reference at the top
3946 // level of an assignment says `invalid assignment left-hand side`. `nested` is
3947 // exactly that distinction — `[1] = 2` is the first, `1 = 2` the second.
3948 _ if nested => Err(self.error_at("invalid destructuring target", span)),
3949 _ => Err(self.error_at("invalid assignment left-hand side", span)),
3950 }
3951 }
3952
3953 /// Reject a literal recorded as `[…spread,]` now that it has turned out to be a
3954 /// destructuring pattern.
3955 fn check_spread_trailing_comma(&mut self, span: Span, message: &str) -> Result<()> {
3956 if let Some(position) = self.spread_trailing_comma.iter().position(|s| *s == span) {
3957 self.spread_trailing_comma.remove(position);
3958 return Err(self.error_at(message, span));
3959 }
3960 // Anything nested inside is consumed by its own conversion, so a leftover can only
3961 // belong to a literal that never became a pattern; dropping those keeps the table
3962 // from growing across a whole script.
3963 self.spread_trailing_comma
3964 .retain(|candidate| !span_contains(span, *candidate));
3965 Ok(())
3966 }
3967
3968 /// The early errors on a name used as an assignment or binding target.
3969 ///
3970 /// Shared by the two paths that turn an identifier into a pattern: a bare one, and the
3971 /// target of a shorthand default (`{a = 1}`), which does not recurse.
3972 fn check_target_name(&mut self, name: &str, span: Span, kind: TargetKind) -> Result<()> {
3973 if kind == TargetKind::Binding {
3974 self.check_binding_name(name, span)?;
3975 } else {
3976 self.check_identifier(name, span)?;
3977 if self.strict && (name == "eval" || name == "arguments") {
3978 return Err(self.error_at(
3979 format!("invalid assignment to '{name}' in strict mode"),
3980 span,
3981 ));
3982 }
3983 }
3984 Ok(())
3985 }
3986
3987 fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3988 // Array and object literals wrap their spread elements, so the target is
3989 // one level in.
3990 let expr = match expr.kind {
3991 ExprKind::Spread(inner) => *inner,
3992 other => Expr::new(other, expr.span),
3993 };
3994 // `[...x = 1] = []`. The literal form is a *spread of an assignment*, which is
3995 // legal, so this is where the pattern reading has to refuse it: §14.3's
3996 // `RestElement : ... BindingIdentifier` has no room for an initializer, and the
3997 // reference says the same in `js_parse_destructuring_element`.
3998 if let ExprKind::Assign { op, .. } = &expr.unparen().kind
3999 && op.is_simple()
4000 {
4001 return Err(self.error_at("rest element cannot have a default value", expr.span));
4002 }
4003 if kind == TargetKind::Binding {
4004 return Ok(RestElement::Pattern(
4005 self.expr_to_pattern_inner(expr, kind, true)?,
4006 ));
4007 }
4008 match &expr.kind {
4009 ExprKind::Member { optional, .. } => {
4010 if *optional {
4011 return Err(self.error_at("invalid assignment target", expr.span));
4012 }
4013 match self.expr_to_pattern_inner(expr, kind, true)?.kind {
4014 PatternKind::Member(member) => Ok(RestElement::Member(member)),
4015 _ => unreachable!("member expressions convert to member patterns"),
4016 }
4017 }
4018 _ => Ok(RestElement::Pattern(
4019 self.expr_to_pattern_inner(expr, kind, true)?,
4020 )),
4021 }
4022 }
4023
4024 // -- expressions -------------------------------------------------------
4025
4026 /// `Expression` (comma separated).
4027 fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
4028 self.enter()?;
4029 let result = self.parse_expression_unguarded(allow_in);
4030 self.leave();
4031 result
4032 }
4033
4034 fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
4035 // The flag is threaded down as an argument, but a few decisions in `parse_primary`
4036 // have no argument to read it from — `#x in o` is one. Mirroring it into the field
4037 // keeps those decisions able to see it, which is what makes `for (#f in v;;)` fail on
4038 // the `#f` instead of somewhere further along.
4039 let saved_allow_in = self.allow_in;
4040 self.allow_in = allow_in;
4041 let result = self.parse_expression_in(allow_in);
4042 self.allow_in = saved_allow_in;
4043 result
4044 }
4045
4046 fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
4047 let start = self.current.span.start;
4048 let first = self.parse_assignment(allow_in)?;
4049 if !self.at_punct(Punct::Comma) {
4050 return Ok(first);
4051 }
4052 let mut items = vec![first];
4053 while self.eat_punct(Punct::Comma)? {
4054 items.push(self.parse_assignment(allow_in)?);
4055 }
4056 Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
4057 }
4058
4059 fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
4060 let start = self.current.span.start;
4061
4062 // `yield` in a generator — but never in its own formal parameters
4063 // (§15.5.1: `FormalParameters Contains YieldExpression` is a `SyntaxError`).
4064 if self.ctx.in_generator && self.at_ident("yield") {
4065 if self.in_formal_parameters {
4066 return Err(self.error_at("yield in default expression", self.current.span));
4067 }
4068 return self.parse_yield(allow_in);
4069 }
4070
4071 let lhs = match self.try_parse_arrow(allow_in)? {
4072 Some(arrow) => return Ok(arrow),
4073 None => self.parse_conditional(allow_in)?,
4074 };
4075
4076 if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
4077 let op_pos = self.current.span.start;
4078 let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
4079 self.bump()?;
4080 let value = self.parse_assignment(allow_in)?;
4081 return Ok(Expr::at_operator(
4082 ExprKind::Assign {
4083 op,
4084 target: Box::new(target),
4085 value: Box::new(value),
4086 },
4087 self.span_from(start),
4088 op_pos,
4089 ));
4090 }
4091 let _ = start;
4092 Ok(lhs)
4093 }
4094
4095 fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
4096 let start = self.current.span.start;
4097 self.bump()?; // yield
4098 let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
4099 self.bump()?;
4100 true
4101 } else {
4102 false
4103 };
4104 let argument = if delegate {
4105 Some(Box::new(self.parse_assignment(allow_in)?))
4106 } else if self.current.newline_before
4107 || self.at_punct(Punct::RParen)
4108 || self.at_punct(Punct::RBracket)
4109 || self.at_punct(Punct::RBrace)
4110 || self.at_punct(Punct::Comma)
4111 || self.at_punct(Punct::Semicolon)
4112 || self.at_punct(Punct::Colon)
4113 || self.current.is_eof()
4114 {
4115 None
4116 } else {
4117 Some(Box::new(self.parse_assignment(allow_in)?))
4118 };
4119 Ok(Expr::new(
4120 ExprKind::Yield { argument, delegate },
4121 self.span_from(start),
4122 ))
4123 }
4124
4125 fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
4126 let starts_paren = self.at_punct(Punct::LParen);
4127 let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
4128 if !starts_paren && !starts_ident {
4129 return Ok(None);
4130 }
4131 // `(` could be a parenthesised expression instead of a parameter list.
4132 // Scanning ahead for the matching `)` and looking for `=>` avoids the
4133 // speculative parse (and its stack cost) in the common case.
4134 if starts_paren && !self.arrow_follows_paren()? {
4135 return Ok(None);
4136 }
4137 let snapshot = self.snapshot();
4138 let head = match self.parse_arrow_head() {
4139 Ok(head) => head,
4140 Err(error) => {
4141 // `arrow_follows_paren` already saw the `=>` for the parenthesised form, and
4142 // `arrow_head_committed` says the same for both forms; either way this *is*
4143 // an arrow and the error is the real one. Restoring and reporting whatever
4144 // the expression interpretation tripped over instead gave "expecting ';'"
4145 // for `(eval) => 1` and for `eval => 1` under `"use strict"`.
4146 self.restore(snapshot);
4147 if starts_paren || self.arrow_head_committed {
4148 return Err(error);
4149 }
4150 return Ok(None);
4151 }
4152 };
4153 let Some(head) = head else {
4154 self.restore(snapshot);
4155 return Ok(None);
4156 };
4157 // Committed: `=>` has been consumed, so errors from here on are real.
4158 // Arrow parameter lists may never repeat a name, in any mode. The message is the
4159 // same one `js_parse_function_args` uses, with no name appended — an earlier
4160 // version added ` ('a')`, which the reference does not print. The position is the
4161 // body's first token: `(a, a) => x` points at the `x`, and `(a, a) => {}` at the
4162 // `}`, because the reference has already consumed the `{` by then.
4163 let body_start = if self.at_punct(Punct::LBrace) {
4164 self.peek()?.span
4165 } else {
4166 self.current.span
4167 };
4168 self.check_duplicate_parameters(&head.params, true, body_start)?;
4169 let saved_ctx = self.ctx;
4170 let saved_loop = self.loop_depth;
4171 let saved_switch = self.switch_depth;
4172 let saved_labels = std::mem::take(&mut self.labels);
4173 let saved_top = self.top_level;
4174 self.ctx = FnCtx {
4175 in_function: true,
4176 in_generator: false,
4177 in_async: head.is_async,
4178 in_method: saved_ctx.in_method,
4179 in_derived_constructor: saved_ctx.in_derived_constructor,
4180 // An arrow is not a static block, so it gets its own `return` and `await` is
4181 // an ordinary name again — but it has no `arguments` of its own, so the ban
4182 // travels with it.
4183 in_static_block: false,
4184 arguments_allowed: saved_ctx.arguments_allowed,
4185 };
4186 self.loop_depth = 0;
4187 self.switch_depth = 0;
4188 self.top_level = false;
4189 let body_start = self.current.span.start;
4190 let (body, strict) = if self.at_punct(Punct::LBrace) {
4191 let (block, strict) = self.parse_arrow_block(&head.params)?;
4192 (block, (self.prev_end, strict))
4193 } else {
4194 let expr = self.parse_assignment(allow_in)?;
4195 let end = expr.span.end;
4196 // An expression body has no directive prologue, so it inherits.
4197 let strict = self.strict;
4198 (FunctionBody::Expr(Box::new(expr)), (end, strict))
4199 };
4200 self.ctx = saved_ctx;
4201 self.loop_depth = saved_loop;
4202 self.switch_depth = saved_switch;
4203 self.labels = saved_labels;
4204 self.top_level = saved_top;
4205 let _ = body_start;
4206 let (body, (end, strict)) = (body, strict);
4207 let span = Span::new(head.span.start, end);
4208 Ok(Some(Expr::new(
4209 ExprKind::Arrow(Box::new(Function {
4210 name: None,
4211 params: head.params,
4212 body,
4213 is_async: head.is_async,
4214 is_generator: false,
4215 strict,
4216 is_arrow: true,
4217 span,
4218 params_span: head.params_span,
4219 source_span: None,
4220 })),
4221 span,
4222 )))
4223 }
4224
4225 /// Parse the `{ … }` body of an arrow, honouring a `"use strict"` prologue.
4226 fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
4227 // Like a function body: the arrow's own directive governs the arrow, and the
4228 // enclosing scope's mode is restored afterwards.
4229 let saved_strict = self.strict;
4230 let params_span = self.prev_end;
4231 // §15.3.1: `"use strict"` may not appear in a function whose parameter list is not
4232 // a `SimpleParameterList`, because a non-simple list is evaluated *before* the
4233 // directive could take effect — `[a] = a` in the parameters of a strict function
4234 // would be evaluated in the wrong mode. This is the same rule
4235 // `parse_function_body` applies, and an arrow body reaches it through this
4236 // function instead, which is why `(a, ...rest) => { "use strict"; }` used to be
4237 // accepted.
4238 let simple_params = params
4239 .iter()
4240 .all(|pattern| matches!(pattern.unparen_kind(), PatternKind::Ident(_)));
4241 self.expect_punct(Punct::LBrace)?;
4242 self.push_scope(Scope::function(simple_parameter_names(params)));
4243 let mut strict_seen = false;
4244 let result = (|| -> Result<Vec<Stmt>> {
4245 let mut body = Vec::new();
4246 let mut prologue = true;
4247 while !self.at_punct(Punct::RBrace) {
4248 if self.current.is_eof() {
4249 return Err(self.unexpected());
4250 }
4251 let stmt = self.parse_statement_list_item()?;
4252 if prologue {
4253 match self.directive_value(&stmt) {
4254 Some(directive) if directive == "use strict" => {
4255 strict_seen = true;
4256 self.enter_strict()?;
4257 }
4258 Some(_) => {}
4259 None => prologue = false,
4260 }
4261 }
4262 body.push(stmt);
4263 }
4264 Ok(body)
4265 })();
4266 self.pop_scope();
4267 let body_strict = self.strict;
4268 self.strict = saved_strict;
4269 self.lexer.set_strict(saved_strict);
4270 let body = result?;
4271 if strict_seen && !simple_params {
4272 return Err(self.error_at(
4273 "\"use strict\" not allowed in function with default or destructuring parameter",
4274 Span::new(params_span, params_span),
4275 ));
4276 }
4277 self.bump()?;
4278 Ok((FunctionBody::Block(body), body_strict))
4279 }
4280
4281 /// Whether the parenthesis at the current token is the parameter list of an
4282 /// arrow function, i.e. the matching `)` is followed by `=>`.
4283 ///
4284 /// This is a plain token walk with a bracket counter: no recursion, so it
4285 /// costs a clone of the lexer and nothing else.
4286 fn arrow_follows_paren(&self) -> Result<bool> {
4287 let mut lexer = self.lexer.clone();
4288 // The opening `(` was already consumed by the caller.
4289 let mut depth = 1usize;
4290 // How many template-literal substitutions the walk is inside.
4291 let mut template_depth = 0usize;
4292 loop {
4293 let token = lexer.next_token()?;
4294 match token.kind {
4295 TokenKind::Eof => return Ok(false),
4296 // A `/` may open a regular expression literal, and this scan has to agree
4297 // with the parser about which it is. A pattern can contain `(`, `)` and `[`
4298 // without balancing them, and lexing one as division also made the
4299 // pattern's characters into tokens — `(/😀/)` was a `SyntaxError` about an
4300 // identifier, because `😀` is not one. Re-scan from the slash; if no pattern
4301 // terminates on this line there is none, and the scan carries on after the
4302 // `/` exactly as division did.
4303 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4304 if lexer.re_scan_regex(token.span.start).is_err() {
4305 lexer.reset_to(token.span.end);
4306 }
4307 }
4308 // A template literal is **not** a single token to this walk: a head chunk
4309 // ends at `${`, so the substitution's tokens follow as ordinary ones and
4310 // the `}` that closes it has to resume the template rather than close a
4311 // brace. Without this, `(function(){ let s = \`${1}\`; })` — any template
4312 // with a substitution inside a parenthesised expression — made the walk
4313 // lex the tail of the template as code and fail with
4314 // `unexpected end of string` before the caller ever got an answer.
4315 TokenKind::Template(chunk) => match chunk.kind {
4316 // `` `text` `` — one token, nothing follows it.
4317 crate::token::TemplateKind::NoSubstitution => {}
4318 // `` `text${ `` — open a substitution level.
4319 crate::token::TemplateKind::Head => template_depth += 1,
4320 // `}text${` — the `}` closed one level and opened another: no change.
4321 crate::token::TemplateKind::Middle => {}
4322 // ``}text` `` — the substitution level is closed.
4323 crate::token::TemplateKind::Tail => {
4324 template_depth = template_depth.saturating_sub(1);
4325 }
4326 },
4327 TokenKind::Punct(Punct::LParen)
4328 | TokenKind::Punct(Punct::LBracket)
4329 | TokenKind::Punct(Punct::LBrace) => depth += 1,
4330 TokenKind::Punct(Punct::RBrace) if template_depth > 0 => {
4331 // This `}` ends a substitution: re-scan it as a template continuation,
4332 // which is what the parser itself does.
4333 template_depth -= 1;
4334 let token = lexer.re_scan_template_continue(token.span.start)?;
4335 if matches!(
4336 token.kind,
4337 TokenKind::Template(crate::token::TemplateToken {
4338 kind: crate::token::TemplateKind::Head
4339 | crate::token::TemplateKind::Middle,
4340 ..
4341 })
4342 ) {
4343 template_depth += 1;
4344 }
4345 }
4346 TokenKind::Punct(Punct::RParen)
4347 | TokenKind::Punct(Punct::RBracket)
4348 | TokenKind::Punct(Punct::RBrace) => {
4349 if depth == 0 {
4350 // Unbalanced input: the caller reports it.
4351 return Ok(false);
4352 }
4353 depth -= 1;
4354 if depth == 0 {
4355 // The current token is the opening `(`, so the matching
4356 // `)` is the token that brought us back to zero.
4357 let next = lexer.next_token()?;
4358 return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
4359 && !next.newline_before);
4360 }
4361 }
4362 _ => {}
4363 }
4364 }
4365 }
4366
4367 /// Speculatively parse an arrow head, consuming `=>` on success.
4368 fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
4369 let start = self.current.span.start;
4370 self.arrow_head_committed = false;
4371 let mut is_async = false;
4372 if self.at_ident("async") {
4373 let peek = self.peek()?;
4374 if peek.newline_before {
4375 return Ok(None);
4376 }
4377 let plausible =
4378 matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
4379 if !plausible {
4380 return Ok(None);
4381 }
4382 self.bump()?;
4383 is_async = true;
4384 }
4385 let params_start = self.current.span.start;
4386 // An async arrow's parameter list is parsed **in async mode**, which is what makes
4387 // `await` an operator there rather than a name. The reference reaches the same
4388 // place from the other direction — it detects `async (…) =>` before parsing the
4389 // parenthesis and starts a whole async function — so `async(await) => {}` and
4390 // `async(x = await) => {}` are early errors on both engines. Without the flag the
4391 // cover grammar accepted every one of them (`expressions/async-arrow-function`).
4392 //
4393 // Only the parameter list: the body's own context is built by the caller, which is
4394 // where a non-async nested arrow gets `in_async: false` again — so the `await` in
4395 // `async(a = () => await) => {}` stays an ordinary identifier.
4396 let saved_ctx = self.ctx;
4397 if is_async {
4398 self.ctx.in_async = true;
4399 self.ctx.in_generator = false;
4400 }
4401 let params = if self.at_punct(Punct::LParen) {
4402 self.parse_formal_parameters()
4403 } else if matches!(self.current.kind, TokenKind::Ident(_)) {
4404 self.expect_ident().map(|ident| {
4405 vec![Pattern::new(
4406 PatternKind::Ident(ident),
4407 self.span_from(params_start),
4408 )]
4409 })
4410 } else {
4411 self.ctx = saved_ctx;
4412 return Ok(None);
4413 };
4414 self.ctx = saved_ctx;
4415 let params = params?;
4416 let params_span = self.span_from(params_start);
4417 if !self.at_punct(Punct::Arrow) || self.current.newline_before {
4418 return Ok(None);
4419 }
4420 self.bump()?; // =>
4421 self.arrow_head_committed = true;
4422 // `eval => 1` is a one-parameter list, so the parameter rules apply to it exactly
4423 // as they do to `(eval) => 1`. The parenthesised form is checked inside
4424 // `parse_formal_parameters`; this covers the bare identifier, which used to skip
4425 // the check entirely (`arrowparameters-bindingidentifier-no-eval`). Done after the
4426 // `=>` because only then is the head known to be an arrow, and an error is final.
4427 //
4428 // `in_formal_parameters` again while checking, so the message is the parameter
4429 // wording ("invalid argument name in strict code") rather than the variable one.
4430 let saved_formals = self.in_formal_parameters;
4431 self.in_formal_parameters = true;
4432 let checked = params
4433 .iter()
4434 .try_for_each(|param| self.check_parameter(param));
4435 self.in_formal_parameters = saved_formals;
4436 checked?;
4437 Ok(Some(ArrowHead {
4438 params,
4439 is_async,
4440 span: self.span_from(start),
4441 params_span,
4442 }))
4443 }
4444
4445 fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
4446 let start = self.current.span.start;
4447 let test = self.parse_binary(allow_in, 0)?;
4448 if !self.at_punct(Punct::Question) {
4449 return Ok(test);
4450 }
4451 self.bump()?;
4452 let consequent = self.parse_assignment(true)?;
4453 self.expect_punct(Punct::Colon)?;
4454 let alternate = self.parse_assignment(allow_in)?;
4455 Ok(Expr::new(
4456 ExprKind::Conditional {
4457 test: Box::new(test),
4458 cons: Box::new(consequent),
4459 alt: Box::new(alternate),
4460 },
4461 self.span_from(start),
4462 ))
4463 }
4464
4465 fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
4466 let start = self.current.span.start;
4467 let mut lhs = self.parse_unary()?;
4468 while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
4469 if prec < min_prec {
4470 break;
4471 }
4472 let op_pos = self.current.span.start;
4473 self.bump()?;
4474 let next_min = if op.is_right_associative() {
4475 prec
4476 } else {
4477 prec + 1
4478 };
4479 let rhs = self.parse_binary(allow_in, next_min)?;
4480 lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
4481 }
4482 Ok(lhs)
4483 }
4484
4485 /// Unary and postfix operators. `in` is handled by the binary layer, so no
4486 /// `allow_in` flag is needed here.
4487 fn parse_unary(&mut self) -> Result<Expr> {
4488 let start = self.current.span.start;
4489 // Unary operators.
4490 let unary = match &self.current.kind {
4491 TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
4492 TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
4493 TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
4494 TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
4495 TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
4496 TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
4497 TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
4498 _ => None,
4499 };
4500 if let Some(op) = unary {
4501 let op_pos = self.current.span.start;
4502 self.bump()?;
4503 let argument = self.parse_unary()?;
4504 if op == UnaryOp::Delete && self.strict {
4505 if let ExprKind::Ident(ident) = &argument.unparen().kind {
4506 return Err(self.error_at(
4507 "cannot delete a direct reference in strict mode",
4508 ident.span,
4509 ));
4510 }
4511 }
4512 // `delete obj.#x` is an early error in *any* mode, and so is the "covered" form:
4513 // the spec rule applies to the derived expression through any number of
4514 // parentheses, through the last element of a sequence, and to the callee of a
4515 // call. Missing the covered forms let those programs run, and `$DONOTEVALUATE()`
4516 // is what the test suite then reported instead of a `SyntaxError`.
4517 if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
4518 // Reported at the token *after* the operand, which is where the reference
4519 // reports it: `js_parse_delete` finishes parsing the expression and then calls
4520 // `js_parse_error`, whose position is `s->token`.
4521 return Err(self.error("cannot delete a private class field"));
4522 }
4523 let expr = Expr::at_operator(
4524 ExprKind::Unary {
4525 op,
4526 argument: Box::new(argument),
4527 },
4528 self.span_from(start),
4529 op_pos,
4530 );
4531 if self.at_punct(Punct::StarStar) {
4532 return Err(self.error(
4533 // The reference's wording, from `js_parse_error` in the `**` check.
4534 "unparenthesized unary expression can't appear on the left-hand side of '**'",
4535 ));
4536 }
4537 return Ok(expr);
4538 }
4539 // Prefix increment/decrement.
4540 if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
4541 let op_pos = self.current.span.start;
4542 let op = if self.at_punct(Punct::PlusPlus) {
4543 UpdateOp::Increment
4544 } else {
4545 UpdateOp::Decrement
4546 };
4547 self.bump()?;
4548 let argument = self.parse_unary()?;
4549 self.check_simple_target(&argument)?;
4550 return Ok(Expr::at_operator(
4551 ExprKind::Update {
4552 op,
4553 argument: Box::new(argument),
4554 prefix: true,
4555 },
4556 self.span_from(start),
4557 op_pos,
4558 ));
4559 }
4560 // `await` wherever the enclosing function is `async`, operator or not.
4561 //
4562 // There is no "unless the next token rules it out" case: the reference reaches
4563 // `TOK_AWAIT` and consumes it unconditionally, so `await;` and `f(await)` report
4564 // the *operand* as unexpected rather than treating `await` as an identifier. That
4565 // is why this asks nothing about what follows.
4566 if self.at_ident("await") && self.ctx.in_async {
4567 // §15.8.1: `async` functions may not have an `AwaitExpression` in their own
4568 // formal parameters, so `new AsyncFunction("x = await 1", "")` is an error.
4569 if self.in_formal_parameters {
4570 return Err(self.error_at("await in default expression", self.current.span));
4571 }
4572 self.bump()?;
4573 let argument = self.parse_unary()?;
4574 return Ok(Expr::new(
4575 ExprKind::Await(Box::new(argument)),
4576 self.span_from(start),
4577 ));
4578 }
4579 let expr = self.parse_lhs_expression()?;
4580 // Postfix increment/decrement (no line break allowed before the operator).
4581 let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
4582 && !self.current.newline_before
4583 {
4584 let op_pos = self.current.span.start;
4585 let op = if self.at_punct(Punct::PlusPlus) {
4586 UpdateOp::Increment
4587 } else {
4588 UpdateOp::Decrement
4589 };
4590 self.check_simple_target(&expr)?;
4591 self.bump()?;
4592 Expr::at_operator(
4593 ExprKind::Update {
4594 op,
4595 argument: Box::new(expr),
4596 prefix: false,
4597 },
4598 self.span_from(start),
4599 op_pos,
4600 )
4601 } else {
4602 expr
4603 };
4604 Ok(result)
4605 }
4606
4607 /// The operand of `++`/`--`, which must be a plain reference.
4608 ///
4609 /// Its own message, not the assignment one: the reference rejects `++1` and `1++` with
4610 /// `js_parse_error(s, "invalid increment/decrement operand")`.
4611 fn check_simple_target(&self, expr: &Expr) -> Result<()> {
4612 match &expr.unparen().kind {
4613 // `eval++` is the same early error as `eval = 1`: §13.4 and §13.15 both fold
4614 // the operand through `AssignmentTargetType`, so the strict-mode ban covers
4615 // increment and decrement as well as assignment. Only the assignment path
4616 // checked it, which is why `"use strict"; eval++` was accepted
4617 // (`expressions/postfix-increment/eval`).
4618 ExprKind::Ident(ident) => {
4619 if self.strict && (ident.name == "eval" || ident.name == "arguments") {
4620 return Err(self.error_at(
4621 format!("invalid assignment to '{}' in strict mode", ident.name),
4622 ident.span,
4623 ));
4624 }
4625 Ok(())
4626 }
4627 ExprKind::Member {
4628 optional: false, ..
4629 } => Ok(()),
4630 _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
4631 }
4632 }
4633
4634 fn parse_lhs_expression(&mut self) -> Result<Expr> {
4635 let start = self.current.span.start;
4636 let mut expr = if self.at_keyword(Keyword::New) {
4637 self.parse_new_expression()?
4638 } else {
4639 self.parse_primary()?
4640 };
4641 let mut saw_optional = false;
4642 loop {
4643 // The position of the punctuator that follows the base expression: a
4644 // failed `.`, `[` or `(` is blamed on that token, not on the base.
4645 let op_pos = self.current.span.start;
4646 match self.current.kind.clone() {
4647 TokenKind::Punct(Punct::Dot) => {
4648 self.bump()?;
4649 let property = self.parse_member_property()?;
4650 expr = Expr::at_operator(
4651 ExprKind::Member {
4652 object: Box::new(expr),
4653 property,
4654 optional: false,
4655 },
4656 self.span_from(start),
4657 op_pos,
4658 );
4659 }
4660 TokenKind::Punct(Punct::QuestionDot) => {
4661 saw_optional = true;
4662 self.bump()?;
4663 if self.at_punct(Punct::LParen) {
4664 let arguments = self.parse_arguments()?;
4665 expr = Expr::at_operator(
4666 ExprKind::Call {
4667 callee: Box::new(expr),
4668 arguments,
4669 optional: true,
4670 },
4671 self.span_from(start),
4672 op_pos,
4673 );
4674 } else if self.at_punct(Punct::LBracket) {
4675 self.bump()?;
4676 let index = self.parse_expression(true)?;
4677 self.expect_punct(Punct::RBracket)?;
4678 expr = Expr::at_operator(
4679 ExprKind::Member {
4680 object: Box::new(expr),
4681 property: MemberProp::Computed(Box::new(index)),
4682 optional: true,
4683 },
4684 self.span_from(start),
4685 op_pos,
4686 );
4687 } else {
4688 let property = self.parse_member_property()?;
4689 expr = Expr::at_operator(
4690 ExprKind::Member {
4691 object: Box::new(expr),
4692 property,
4693 optional: true,
4694 },
4695 self.span_from(start),
4696 op_pos,
4697 );
4698 }
4699 }
4700 TokenKind::Punct(Punct::LBracket) => {
4701 self.bump()?;
4702 let index = self.parse_expression(true)?;
4703 self.expect_punct(Punct::RBracket)?;
4704 expr = Expr::at_operator(
4705 ExprKind::Member {
4706 object: Box::new(expr),
4707 property: MemberProp::Computed(Box::new(index)),
4708 optional: false,
4709 },
4710 self.span_from(start),
4711 op_pos,
4712 );
4713 }
4714 TokenKind::Punct(Punct::LParen) => {
4715 let arguments = self.parse_arguments()?;
4716 expr = Expr::at_operator(
4717 ExprKind::Call {
4718 callee: Box::new(expr),
4719 arguments,
4720 optional: false,
4721 },
4722 self.span_from(start),
4723 op_pos,
4724 );
4725 }
4726 TokenKind::Template(_) => {
4727 if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4728 return Err(
4729 self.error("tagged template cannot be used in an optional chain")
4730 );
4731 }
4732 let quasi = self.parse_template(true)?;
4733 expr = Expr::new(
4734 ExprKind::TaggedTemplate {
4735 tag: Box::new(expr),
4736 quasi: Box::new(quasi),
4737 },
4738 self.span_from(start),
4739 );
4740 }
4741 _ => break,
4742 }
4743 }
4744 if saw_optional {
4745 expr = Expr::new(
4746 ExprKind::OptionalChain(Box::new(expr)),
4747 self.span_from(start),
4748 );
4749 }
4750 Ok(expr)
4751 }
4752
4753 /// `#name`, with `#` the current token.
4754 ///
4755 /// The `#` and the name may not be separated: `class C { # x = 1 }` is
4756 /// `invalid first character of private name`, not a field called `x`. The reference checks
4757 /// it in the lexer (`parse_ident` with `is_private`, which requires an identifier-start
4758 /// character immediately after the `#`), so the error is reported at the `#`.
4759 fn parse_private_name(&mut self) -> Result<Ident> {
4760 let hash = self.current.span;
4761 self.bump()?;
4762 let ident = self.expect_ident()?;
4763 if ident.span.start.offset != hash.end.offset {
4764 return Err(self.error_at("invalid first character of private name", hash));
4765 }
4766 Ok(ident)
4767 }
4768
4769 fn parse_member_property(&mut self) -> Result<MemberProp> {
4770 if self.at_punct(Punct::Hash) {
4771 let ident = self.parse_private_name()?;
4772 if !self.private.iter().any(|env| env.contains(&ident.name)) {
4773 // Private names are valid throughout the class body in either order, so an
4774 // unresolved one may simply be a forward reference. Park it and settle when
4775 // the body closes; with no class body at all there is nothing to defer to,
4776 // and the reference's message is used verbatim
4777 // (`js_parse_error(s, "undefined private field '#%s'")`).
4778 let Some(innermost) = self.private.last_mut() else {
4779 return Err(self.error_at(
4780 format!("undefined private field '#{}'", ident.name),
4781 ident.span,
4782 ));
4783 };
4784 // Deferred to the *innermost* class, whose body is the one still being
4785 // parsed. If its own body never declares the name it bubbles outward — an
4786 // inner class body may legally name an outer class's private field.
4787 innermost.pending.push((ident.name.clone(), ident.span));
4788 }
4789 return Ok(MemberProp::Private(ident));
4790 }
4791 match self.current.kind.clone() {
4792 TokenKind::Ident(name) => {
4793 let span = self.current.span;
4794 self.bump()?;
4795 Ok(MemberProp::Ident(Ident { name, span }))
4796 }
4797 TokenKind::Keyword(kw) => {
4798 let span = self.current.span;
4799 self.bump()?;
4800 Ok(MemberProp::Ident(Ident {
4801 name: kw.as_str().to_string(),
4802 span,
4803 }))
4804 }
4805 // After `.` or `?.` the reference says "expecting field name", not
4806 // "invalid property name" — it is `js_parse_error(s, "expecting field name")`
4807 // at the member-access site.
4808 _ => Err(self.error("expecting field name")),
4809 }
4810 }
4811
4812 fn parse_new_expression(&mut self) -> Result<Expr> {
4813 let start = self.current.span.start;
4814 self.bump()?; // new
4815 if self.at_punct(Punct::Dot) {
4816 self.bump()?;
4817 if !self.at_ident("target") {
4818 return Err(self.error("expecting target"));
4819 }
4820 if !self.ctx.in_function {
4821 return Err(self.error("new.target only allowed within functions"));
4822 }
4823 self.bump()?;
4824 return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4825 }
4826 let mut callee = if self.at_keyword(Keyword::New) {
4827 self.parse_new_expression()?
4828 } else {
4829 self.parse_primary()?
4830 };
4831 // Member accesses bind tighter than `new`, calls do not.
4832 loop {
4833 let op_pos = self.current.span.start;
4834 match self.current.kind.clone() {
4835 TokenKind::Punct(Punct::Dot) => {
4836 self.bump()?;
4837 let property = self.parse_member_property()?;
4838 callee = Expr::at_operator(
4839 ExprKind::Member {
4840 object: Box::new(callee),
4841 property,
4842 optional: false,
4843 },
4844 self.span_from(start),
4845 op_pos,
4846 );
4847 }
4848 TokenKind::Punct(Punct::LBracket) => {
4849 self.bump()?;
4850 let index = self.parse_expression(true)?;
4851 self.expect_punct(Punct::RBracket)?;
4852 callee = Expr::at_operator(
4853 ExprKind::Member {
4854 object: Box::new(callee),
4855 property: MemberProp::Computed(Box::new(index)),
4856 optional: false,
4857 },
4858 self.span_from(start),
4859 op_pos,
4860 );
4861 }
4862 TokenKind::Punct(Punct::QuestionDot) => {
4863 return Err(self.error("new keyword cannot be used with an optional chain"));
4864 }
4865 _ => break,
4866 }
4867 }
4868 if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4869 return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4870 }
4871 // `ImportCall` is a *CallExpression*, and `new` only reaches a `MemberExpression`
4872 // (`MemberExpression : new MemberExpression Arguments`), so `new import(x)` is a
4873 // SyntaxError. `import.meta`, by contrast, *is* a `MemberExpression`, so
4874 // `new import.meta()` parses and fails at run time for not being a constructor.
4875 //
4876 // The whole member chain has to be checked, not just its root: `new import('').p`
4877 // reaches `new` through `Member { object: ImportCall, property: p }`, and the grammar
4878 // cannot build that either — `. IdentifierName` needs a CallExpression on its left,
4879 // and a CallExpression is not a MemberExpression, so there is nothing for `new` to
4880 // take. Parentheses do change it: `new (import('')).p` is legal and throws at run
4881 // time, because a parenthesised expression *is* a PrimaryExpression.
4882 if let Some(import_call) = member_chain_import_call(&callee) {
4883 return Err(self.error_at("invalid use of 'import()'", import_call.span));
4884 }
4885 // The root check is on the callee as written, *not* through parentheses:
4886 // `new (import(''))` is legal because a parenthesised expression is a
4887 // PrimaryExpression and therefore a MemberExpression, and it fails at run time for
4888 // not being a constructor (`syntax/valid/new-covered-expression-is-valid`). The
4889 // member-chain walk above stops at a `Paren` for the same reason.
4890 if matches!(&callee.kind, ExprKind::ImportCall(..)) {
4891 return Err(self.error_at("invalid use of 'import()'", callee.span));
4892 }
4893 let arguments = if self.at_punct(Punct::LParen) {
4894 // `new C(...)`: a failure in the constructor call is blamed on the `(`.
4895 let op_pos = self.current.span.start;
4896 let arguments = Some(self.parse_arguments()?);
4897 return Ok(Expr::at_operator(
4898 ExprKind::New {
4899 callee: Box::new(callee),
4900 arguments,
4901 },
4902 self.span_from(start),
4903 op_pos,
4904 ));
4905 } else {
4906 None
4907 };
4908 // `new C` with no argument list: the reference emits its position at the token
4909 // *after* the constructor (`emit_source_pos(s, s->token.ptr)` for "new operator on
4910 // an object"), not at the `new`.
4911 Ok(Expr::at_operator(
4912 ExprKind::New {
4913 callee: Box::new(callee),
4914 arguments,
4915 },
4916 self.span_from(start),
4917 self.current.span.start,
4918 ))
4919 }
4920
4921 fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4922 self.expect_punct(Punct::LParen)?;
4923 let mut arguments = Vec::new();
4924 while !self.at_punct(Punct::RParen) {
4925 if self.at_punct(Punct::Ellipsis) {
4926 let start = self.current.span.start;
4927 self.bump()?;
4928 let argument = self.parse_assignment(true)?;
4929 arguments.push(Expr::new(
4930 ExprKind::Spread(Box::new(argument)),
4931 self.span_from(start),
4932 ));
4933 } else {
4934 arguments.push(self.parse_assignment(true)?);
4935 }
4936 if !self.eat_punct(Punct::Comma)? {
4937 break;
4938 }
4939 }
4940 self.expect_punct(Punct::RParen)?;
4941 Ok(arguments)
4942 }
4943
4944 /// Primary expressions.
4945 ///
4946 /// The rarely used forms are dispatched to [`Parser::parse_primary_complex`]
4947 /// so that this function — which sits on every nesting level — keeps a small
4948 /// stack frame. That directly raises how deeply a program may nest before
4949 /// the stack limit is hit (debug builds get ~4x more depth out of it).
4950 fn parse_primary(&mut self) -> Result<Expr> {
4951 let start = self.current.span.start;
4952 match self.current.kind.clone() {
4953 TokenKind::Number(NumberLiteral::Int(value)) => {
4954 self.bump()?;
4955 Ok(Expr::new(
4956 ExprKind::Number(value as f64),
4957 self.span_from(start),
4958 ))
4959 }
4960 TokenKind::Number(NumberLiteral::Float(value)) => {
4961 self.bump()?;
4962 Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4963 }
4964 TokenKind::String(value) => {
4965 self.bump()?;
4966 Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4967 }
4968 // A *contextual* keyword, so only its own spelling counts: `\u0061sync
4969 // function(){}` is an identifier followed by a declaration, which is a syntax
4970 // error rather than an async function expression.
4971 TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4972 let peek = self.peek()?;
4973 if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4974 && !peek.newline_before
4975 {
4976 self.bump()?; // async
4977 let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4978 return Ok(Expr::new(
4979 ExprKind::Function(Box::new(func)),
4980 self.span_from(start),
4981 ));
4982 }
4983 let span = self.current.span;
4984 self.bump()?;
4985 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4986 }
4987 TokenKind::Ident(name) => {
4988 let span = self.current.span;
4989 self.check_identifier(&name, span)?;
4990 self.check_arguments_reference(&name, span)?;
4991 self.bump()?;
4992 Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4993 }
4994 TokenKind::Keyword(Keyword::This) => {
4995 self.bump()?;
4996 Ok(Expr::new(ExprKind::This, self.span_from(start)))
4997 }
4998 TokenKind::Keyword(Keyword::Null) => {
4999 self.bump()?;
5000 Ok(Expr::new(ExprKind::Null, self.span_from(start)))
5001 }
5002 TokenKind::Keyword(Keyword::True) => {
5003 self.bump()?;
5004 Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
5005 }
5006 TokenKind::Keyword(Keyword::False) => {
5007 self.bump()?;
5008 Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
5009 }
5010 TokenKind::Punct(Punct::LParen) => {
5011 self.bump()?;
5012 let inner = self.parse_expression(true)?;
5013 self.expect_punct(Punct::RParen)?;
5014 Ok(Expr::new(
5015 ExprKind::Paren(Box::new(inner)),
5016 self.span_from(start),
5017 ))
5018 }
5019 TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
5020 self.parse_regex_literal(start)
5021 }
5022 _ => self.parse_primary_complex(start),
5023 }
5024 }
5025
5026 /// The primary expressions that need a lot of code: literals with structure,
5027 /// functions, classes, `import`, `super`, `#x in y`.
5028 #[inline(never)]
5029 fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
5030 match self.current.kind.clone() {
5031 TokenKind::BigInt(literal) => {
5032 self.bump()?;
5033 Ok(Expr::new(
5034 ExprKind::BigInt {
5035 digits: literal.digits,
5036 radix: literal.radix,
5037 },
5038 self.span_from(start),
5039 ))
5040 }
5041 TokenKind::Template(_) => {
5042 let template = self.parse_template(false)?;
5043 Ok(Expr::new(
5044 ExprKind::Template(Box::new(template)),
5045 self.span_from(start),
5046 ))
5047 }
5048 TokenKind::Keyword(Keyword::Function) => {
5049 let func = self.parse_function(FunctionForm::Expression, false, None)?;
5050 Ok(Expr::new(
5051 ExprKind::Function(Box::new(func)),
5052 self.span_from(start),
5053 ))
5054 }
5055 TokenKind::Keyword(Keyword::Class) => {
5056 let class = self.parse_class(true)?;
5057 Ok(Expr::new(
5058 ExprKind::Class(Box::new(class)),
5059 self.span_from(start),
5060 ))
5061 }
5062 TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
5063 TokenKind::Keyword(Keyword::Super) => self.parse_super(),
5064 TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
5065 TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
5066 // `#x` is only an expression as `#x in obj`, and `in` is not available where the
5067 // grammar forbids it — a `for` head, for instance. The reference parses the head
5068 // with the `[~In]` production, so `for (#f in v;;)` fails on the `#f` itself with
5069 // "unexpected token in expression: '#f'" rather than somewhere later.
5070 TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
5071 // Reached only when `in` is unavailable, so `#f` cannot start an expression here.
5072 // The message is the reference's, which quotes the whole private name rather than
5073 // the lone `#` that the token stream holds.
5074 TokenKind::Punct(Punct::Hash) => {
5075 let hash = self.current.span;
5076 let name = match self.peek()?.kind.clone() {
5077 TokenKind::Ident(name) => format!("#{name}"),
5078 _ => "#".to_string(),
5079 };
5080 Err(SyntaxError::new(
5081 format!("unexpected token in expression: '{name}'"),
5082 hash,
5083 ))
5084 }
5085 _ => Err(self.unexpected()),
5086 }
5087 }
5088
5089 /// `super` or `super(...)`.
5090 #[inline(never)]
5091 fn parse_super(&mut self) -> Result<Expr> {
5092 let start = self.current.span.start;
5093 self.bump()?;
5094 // Every error below is reported at the token *after* `super`, because the reference
5095 // consumes the keyword before it looks at what follows (`case TOK_SUPER:
5096 // next_token(s); …`) and `js_parse_error` always points at the current token. So
5097 // `super.x` reports the `.`, `super()` the `(`, and a bare `super` the token that
5098 // ends the expression.
5099 let after = self.current.span;
5100 if self.at_punct(Punct::LParen) {
5101 if !self.ctx.in_derived_constructor {
5102 return Err(self.error_at(
5103 "super() is only valid in a derived class constructor",
5104 after,
5105 ));
5106 }
5107 // A `super()` call is positioned on its `(` like any other call: the reference
5108 // reaches the same `emit_source_pos(op_token_ptr)` on the way to `apply`.
5109 let arguments = self.parse_arguments()?;
5110 return Ok(Expr::at_operator(
5111 ExprKind::SuperCall(arguments),
5112 self.span_from(start),
5113 after.start,
5114 ));
5115 }
5116 if !self.ctx.in_method {
5117 // Three messages, told apart by what follows `super`:
5118 // `super` alone -> invalid use of 'super'
5119 // `super.x`, `super[x]` -> 'super' is only valid in a method
5120 // `super()` -> handled above
5121 // A bare `super` never reaches the member-access code, so the reference names
5122 // it on its own.
5123 let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
5124 "'super' is only valid in a method"
5125 } else {
5126 "invalid use of 'super'"
5127 };
5128 return Err(self.error_at(message, after));
5129 }
5130 Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
5131 }
5132
5133 /// `#name in object`.
5134 #[inline(never)]
5135 fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
5136 self.bump()?;
5137 let ident = self.expect_ident()?;
5138 if !self.private.iter().any(|env| env.contains(&ident.name)) {
5139 return Err(self.error_at(
5140 format!(
5141 "private field '#{}' must be declared in an enclosing class",
5142 ident.name
5143 ),
5144 ident.span,
5145 ));
5146 }
5147 if !self.at_keyword(Keyword::In) {
5148 return Err(self.error("expecting 'in' after a private name"));
5149 }
5150 self.bump()?;
5151 // `RelationalExpression : PrivateIdentifier in ShiftExpression` — the right operand is
5152 // a *shift* expression, so a second private-in cannot nest inside it. The reference
5153 // says so by rejecting `#f in #f in this` at the inner `#f`.
5154 if self.at_punct(Punct::Hash) {
5155 let hash = self.current.span;
5156 let name = match self.peek()?.kind.clone() {
5157 TokenKind::Ident(name) => format!("#{name}"),
5158 _ => "#".to_string(),
5159 };
5160 return Err(SyntaxError::new(
5161 format!("unexpected token in expression: '{name}'"),
5162 hash,
5163 ));
5164 }
5165 let object = self.parse_unary()?;
5166 Ok(Expr::new(
5167 ExprKind::PrivateIn {
5168 name: ident,
5169 object: Box::new(object),
5170 },
5171 self.span_from(start),
5172 ))
5173 }
5174
5175 /// A regular expression literal: the lexer produced `/` (or `/=`), so the
5176 /// token has to be re-scanned from that position.
5177 #[inline(never)]
5178 fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
5179 let token = self.lexer.re_scan_regex(self.current.span.start)?;
5180 self.current = token;
5181 let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
5182 unreachable!("re_scan_regex returns a RegExp token")
5183 };
5184 // The flags are validated **here**, at parse time, not when the opcode first runs:
5185 // a negative test262 case calls `$DONOTEVALUATE()` and then writes `/./uv`, and an
5186 // engine that compiles the literal lazily reports that `Test262Error` instead of the
5187 // `SyntaxError` the file is about (`RegExp/prototype/unicodeSets/uv-flags`).
5188 //
5189 // Only the flags are checked here. The pattern body is the regexp crate's grammar, and
5190 // the parser has no dependency on it; a malformed body still throws when the literal
5191 // is first evaluated, which is what `/a{/u` and friends rely on.
5192 let mut seen = 0u8;
5193 for flag in flags.chars() {
5194 let bit = match flag {
5195 'g' => 1 << 0,
5196 'i' => 1 << 1,
5197 'm' => 1 << 2,
5198 's' => 1 << 3,
5199 'y' => 1 << 4,
5200 'u' => 1 << 5,
5201 'd' => 1 << 6,
5202 'v' => 1 << 7,
5203 _ => {
5204 return Err(SyntaxError::new(
5205 "invalid regular expression flags",
5206 self.current.span,
5207 ));
5208 }
5209 };
5210 if seen & bit != 0 {
5211 return Err(SyntaxError::new(
5212 "duplicate regular expression flag",
5213 self.current.span,
5214 ));
5215 }
5216 seen |= bit;
5217 }
5218 // `u` and `v` are two dialects of one strict grammar, so a pattern cannot ask for both.
5219 if seen & (1 << 5) != 0 && seen & (1 << 7) != 0 {
5220 return Err(SyntaxError::new(
5221 "invalid regular expression flags",
5222 self.current.span,
5223 ));
5224 }
5225 self.bump()?;
5226 Ok(Expr::new(
5227 ExprKind::RegExp { pattern, flags },
5228 self.span_from(start),
5229 ))
5230 }
5231
5232 fn parse_import_expression(&mut self) -> Result<Expr> {
5233 let start = self.current.span.start;
5234 self.bump()?; // import
5235 if self.at_punct(Punct::Dot) {
5236 if !self.module {
5237 return Err(self.error_at(
5238 "import.meta only valid in module code",
5239 self.span_from(start),
5240 ));
5241 }
5242 self.bump()?;
5243 if !self.at_ident("meta") {
5244 return Err(self.error("expecting 'meta' after 'import.'"));
5245 }
5246 self.bump()?;
5247 return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
5248 }
5249 if self.at_punct(Punct::LParen) {
5250 self.bump()?;
5251 let specifier = self.parse_assignment(true)?;
5252 // The grammar has two forms and both allow a trailing comma:
5253 //
5254 // ImportCall : import ( AssignmentExpression ,opt )
5255 // import ( AssignmentExpression , AssignmentExpression ,opt )
5256 //
5257 // The second argument is the import-attributes bag (`import(x, { with: … })`).
5258 // It stays in the tree: §13.3.10.1 step 4 says the options expression is
5259 // evaluated and its value read, so its side effects are observable even though
5260 // this loader reads no attributes. Rejecting the syntax outright is what turned
5261 // a legal `import(x,)` into a SyntaxError.
5262 let mut options = None;
5263 if self.at_punct(Punct::Comma) {
5264 self.bump()?;
5265 if !self.at_punct(Punct::RParen) {
5266 options = Some(Box::new(self.parse_assignment(true)?));
5267 if self.at_punct(Punct::Comma) {
5268 self.bump()?;
5269 }
5270 }
5271 }
5272 self.expect_punct(Punct::RParen)?;
5273 return Ok(Expr::new(
5274 ExprKind::ImportCall(Box::new(specifier), options),
5275 self.span_from(start),
5276 ));
5277 }
5278 Err(self.unexpected())
5279 }
5280
5281 fn parse_array_literal(&mut self) -> Result<Expr> {
5282 let start = self.current.span.start;
5283 self.expect_punct(Punct::LBracket)?;
5284 let mut elements = Vec::new();
5285 // Whether the comma just consumed came after a spread *and* closed the literal,
5286 // which is `[...x,]` — legal as a literal, an early error as a pattern.
5287 let mut spread_comma_closed = false;
5288 while !self.at_punct(Punct::RBracket) {
5289 if self.at_punct(Punct::Comma) {
5290 self.bump()?;
5291 elements.push(None);
5292 spread_comma_closed = false;
5293 continue;
5294 }
5295 let spread = self.at_punct(Punct::Ellipsis);
5296 if spread {
5297 let spread_start = self.current.span.start;
5298 self.bump()?;
5299 let argument = self.parse_assignment(true)?;
5300 elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
5301 ExprKind::Spread(Box::new(argument)),
5302 self.span_from(spread_start),
5303 )))));
5304 } else {
5305 let expr = self.parse_assignment(true)?;
5306 elements.push(Some(ArrayElement::Expr(Box::new(expr))));
5307 }
5308 if !self.eat_punct(Punct::Comma)? {
5309 break;
5310 }
5311 spread_comma_closed = spread && self.at_punct(Punct::RBracket);
5312 }
5313 self.expect_punct(Punct::RBracket)?;
5314 let span = self.span_from(start);
5315 if spread_comma_closed {
5316 self.spread_trailing_comma.push(span);
5317 }
5318 Ok(Expr::new(ExprKind::Array { elements }, span))
5319 }
5320
5321 fn parse_object_literal(&mut self) -> Result<Expr> {
5322 let start = self.current.span.start;
5323 self.expect_punct(Punct::LBrace)?;
5324 let mut properties: Vec<ObjectProperty> = Vec::new();
5325 let mut proto_count = 0;
5326 let mut spread_comma_closed = false;
5327 while !self.at_punct(Punct::RBrace) {
5328 let property_start = self.current.span.start;
5329 if self.at_punct(Punct::Ellipsis) {
5330 self.bump()?;
5331 let argument = self.parse_assignment(true)?;
5332 properties.push(ObjectProperty::Spread(Box::new(argument)));
5333 } else {
5334 let mut is_async = false;
5335 let mut is_generator = false;
5336 let mut accessor: Option<MethodKind> = None;
5337 if self.at_ident("async") {
5338 let peek = self.peek()?;
5339 let is_modifier = !matches!(
5340 peek.kind,
5341 TokenKind::Punct(Punct::LParen)
5342 | TokenKind::Punct(Punct::Colon)
5343 | TokenKind::Punct(Punct::Comma)
5344 | TokenKind::Punct(Punct::RBrace)
5345 | TokenKind::Punct(Punct::Eq)
5346 ) && !peek.newline_before;
5347 if is_modifier {
5348 self.bump()?;
5349 is_async = true;
5350 }
5351 }
5352 if self.at_punct(Punct::Star) {
5353 self.bump()?;
5354 is_generator = true;
5355 }
5356 if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
5357 let is_get = self.at_ident("get");
5358 let peek = self.peek()?;
5359 if is_property_key_start(&peek.kind) {
5360 self.bump()?;
5361 accessor = Some(if is_get {
5362 MethodKind::Get
5363 } else {
5364 MethodKind::Set
5365 });
5366 }
5367 }
5368 let key = self.parse_property_key()?;
5369 let is_computed = matches!(key, PropName::Computed(_));
5370 if self.at_punct(Punct::LParen) {
5371 let saved = self.ctx;
5372 self.ctx = FnCtx {
5373 in_function: true,
5374 in_generator: is_generator,
5375 in_async: is_async,
5376 in_method: true,
5377 in_derived_constructor: false,
5378 in_static_block: false,
5379 arguments_allowed: true,
5380 };
5381 let saved_top = self.top_level;
5382 self.top_level = false;
5383 let func_result = (|| -> Result<Function> {
5384 let params = self.parse_formal_parameters()?;
5385 let (params, params_span, body, strict) =
5386 self.parse_function_body(params, true)?;
5387 Ok(Function {
5388 name: None,
5389 params,
5390 body,
5391 is_async,
5392 is_generator,
5393 strict,
5394 is_arrow: false,
5395 span: self.span_from(property_start),
5396 params_span,
5397 source_span: None,
5398 })
5399 })();
5400 self.ctx = saved;
5401 self.top_level = saved_top;
5402 let func = func_result?;
5403 let kind = match accessor {
5404 Some(kind) => {
5405 if is_generator || is_async {
5406 return Err(self.error_at(
5407 "accessors may not be generators or async",
5408 func.span,
5409 ));
5410 }
5411 if kind == MethodKind::Get && !func.params.is_empty() {
5412 return Err(self.error_at(
5413 "invalid number of arguments for getter or setter",
5414 func.span,
5415 ));
5416 }
5417 if kind == MethodKind::Set && func.params.len() != 1 {
5418 return Err(self.error_at(
5419 "invalid number of arguments for getter or setter",
5420 func.span,
5421 ));
5422 }
5423 match kind {
5424 MethodKind::Get => PropertyKind::Get,
5425 MethodKind::Set => PropertyKind::Set,
5426 MethodKind::Method | MethodKind::Constructor => {
5427 PropertyKind::Method
5428 }
5429 }
5430 }
5431 None => PropertyKind::Method,
5432 };
5433 let span = self.span_from(property_start);
5434 properties.push(ObjectProperty::Property {
5435 key,
5436 value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
5437 kind,
5438 shorthand: false,
5439 span,
5440 });
5441 } else if self.eat_punct(Punct::Colon)? {
5442 let value = self.parse_assignment(true)?;
5443 if !is_computed
5444 && let Some(PropKeyRef::Str(name)) = key.static_name()
5445 && name == "__proto__"
5446 {
5447 proto_count += 1;
5448 if proto_count > 1 {
5449 return Err(self.error_at(
5450 "duplicate __proto__ property name",
5451 self.span_from(property_start),
5452 ));
5453 }
5454 }
5455 properties.push(ObjectProperty::Property {
5456 key,
5457 value: Box::new(value),
5458 kind: PropertyKind::Value,
5459 shorthand: false,
5460 span: self.span_from(property_start),
5461 });
5462 } else {
5463 // Shorthand `{a}` / `{a = 1}` (the latter only inside a
5464 // destructuring pattern).
5465 let PropName::Literal(PropKey::Str(name)) = &key else {
5466 return Err(self.error("expecting ':' after a property name"));
5467 };
5468 let ident_span = self.span_from(property_start);
5469 let ident = Ident {
5470 // A shorthand `{"\uD800" as a name}` is not a thing: a binding name
5471 // is an identifier, so this path is only reached for text that is
5472 // already valid; the lossy conversion cannot lose anything here.
5473 name: name.to_string_lossy().into_owned(),
5474 span: ident_span,
5475 };
5476 self.check_identifier(&ident.name, ident.span)?;
5477 let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
5478 if self.at_punct(Punct::Eq) {
5479 // CoverInitializedName: only legal once the object turns
5480 // out to be a destructuring pattern.
5481 self.cover_inits.push(ident_span);
5482 self.bump()?;
5483 let default = self.parse_assignment(true)?;
5484 let target = Pattern::new(PatternKind::Ident(ident), ident_span);
5485 value = Expr::new(
5486 ExprKind::Assign {
5487 op: AssignOp::Assign,
5488 target: Box::new(target),
5489 value: Box::new(default),
5490 },
5491 ident_span,
5492 );
5493 }
5494 properties.push(ObjectProperty::Property {
5495 key,
5496 value: Box::new(value),
5497 kind: PropertyKind::Value,
5498 shorthand: true,
5499 span: ident_span,
5500 });
5501 }
5502 }
5503 // `{…, …}` — whether the property just pushed was a spread is what decides
5504 // whether the comma that closed the literal is the illegal one.
5505 let spread = matches!(properties.last(), Some(ObjectProperty::Spread(_)));
5506 if !self.eat_punct(Punct::Comma)? {
5507 break;
5508 }
5509 spread_comma_closed = spread && self.at_punct(Punct::RBrace);
5510 }
5511 self.expect_punct(Punct::RBrace)?;
5512 let span = self.span_from(start);
5513 if spread_comma_closed {
5514 self.spread_trailing_comma.push(span);
5515 }
5516 Ok(Expr::new(ExprKind::Object(properties), span))
5517 }
5518
5519 /// A template literal, tagged or not.
5520 ///
5521 /// The difference is the whole of the escape rules. §12.9.6.1 `TemplateCharacters`
5522 /// admits a `NotEscapeSequence`, whose `TV` is **empty** and whose `TRV` is the source
5523 /// text — so a tagged template may contain `\01`, `\8` or `\u{110000}` and reports
5524 /// `cooked` as `undefined`. Untagged, `TemplateCharacters` has no such production and
5525 /// those are `SyntaxError`s. The lexer already records `cooked: None` for exactly this
5526 /// case (it cannot know which it is scanning), so the judgement belongs here.
5527 fn parse_template(&mut self, tagged: bool) -> Result<TemplateLiteral> {
5528 let mut quasis = Vec::new();
5529 let mut expressions = Vec::new();
5530 loop {
5531 let (cooked, raw, kind) = match self.current.kind.clone() {
5532 TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
5533 _ => return Err(self.error("expecting a template literal")),
5534 };
5535 let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
5536 if cooked.is_none() && !tagged {
5537 return Err(self.error("malformed escape sequence in template literal"));
5538 }
5539 quasis.push(TemplateChunk { cooked, raw, tail });
5540 if tail {
5541 self.bump()?;
5542 break;
5543 }
5544 self.bump()?; // move to the first token of the substitution
5545 let expr = self.parse_expression(true)?;
5546 expressions.push(expr);
5547 if !self.at_punct(Punct::RBrace) {
5548 return Err(self.error("expecting '}' in a template substitution"));
5549 }
5550 let brace = self.current.span.start;
5551 let token = self.lexer.re_scan_template_continue(brace)?;
5552 self.current = token;
5553 }
5554 Ok(TemplateLiteral {
5555 quasis,
5556 expressions,
5557 })
5558 }
5559}
5560
5561/// Which kind of function is being parsed (affects whether a name is required).
5562#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5563enum FunctionForm {
5564 Declaration,
5565 Expression,
5566}
5567
5568/// Names of the parameters that participate in declaration-conflict checks.
5569///
5570/// Engines only check *simple* (identifier) parameters against the body's
5571/// lexical declarations: `function f(a) { let a; }` is an early error, but
5572/// `function f({a}) { let a; }` is not (QuickJS behaves the same way, so this
5573/// deliberately follows the reference rather than ES2025 §10.2.1).
5574/// Whether this parameter is a bare identifier, as opposed to a pattern.
5575fn is_plain_identifier(param: &Pattern) -> bool {
5576 matches!(param.unparen_kind(), PatternKind::Ident(_))
5577}
5578
5579/// Every name `param` binds, in binding order, tagged with whether it sits inside a
5580/// destructuring pattern.
5581///
5582/// A rest parameter is a pattern only when its target is: `...a` binds like a plain name,
5583/// while `...[a]` does not.
5584fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
5585 fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
5586 match &pattern.kind {
5587 PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
5588 PatternKind::Assign { target, default } => {
5589 walk(target, in_pattern, out);
5590 // A default's own expression can bind nothing, so only the target is walked.
5591 let _ = default;
5592 }
5593 PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
5594 PatternKind::Array { .. } | PatternKind::Object { .. } => {
5595 let mut names = Vec::new();
5596 pattern.bound_names(&mut names);
5597 for name in names {
5598 out.push((name.name, name.span, true));
5599 }
5600 }
5601 _ => {}
5602 }
5603 }
5604 let mut out = Vec::new();
5605 let in_pattern = !is_plain_identifier(param);
5606 walk(param, in_pattern, &mut out);
5607 // A pattern's own walk above already flagged its names; a plain identifier or a
5608 // defaulted one goes through `walk` directly.
5609 if out.is_empty() {
5610 let mut names = Vec::new();
5611 param.bound_names(&mut names);
5612 out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
5613 }
5614 out
5615}
5616
5617/// Whether any binding in `pattern` carries a default value.
5618///
5619/// This is the closest stand-in we have for the reference's lookahead: it scans the
5620/// parenthesised parameter text for an `=` (`SKIP_HAS_ASSIGNMENT`) *before* parsing it, and
5621/// that flag decides which of the two duplicate-name messages a later conflict gets.
5622fn pattern_has_default(pattern: &Pattern) -> bool {
5623 let element = |element: &Option<PatternElement>| {
5624 element.as_ref().is_some_and(|element| match element {
5625 PatternElement::Pattern(inner) => pattern_has_default(inner),
5626 PatternElement::Property { value, .. } => pattern_has_default(value),
5627 })
5628 };
5629 let rest = |rest: &Option<Box<RestElement>>| {
5630 rest.as_ref().is_some_and(|rest| match rest.as_ref() {
5631 RestElement::Pattern(inner) => pattern_has_default(inner),
5632 RestElement::Member(_) => false,
5633 })
5634 };
5635 match &pattern.kind {
5636 PatternKind::Assign { .. } => true,
5637 PatternKind::Array {
5638 elements,
5639 rest: tail,
5640 } => elements.iter().any(element) || rest(tail),
5641 PatternKind::Object {
5642 properties,
5643 rest: tail,
5644 } => properties.iter().any(element) || rest(tail),
5645 PatternKind::Rest(target) => pattern_has_default(target),
5646 _ => false,
5647 }
5648}
5649
5650fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
5651 params
5652 .iter()
5653 .filter_map(|param| match ¶m.kind {
5654 PatternKind::Ident(id) => Some(id.name.clone()),
5655 _ => None,
5656 })
5657 .collect()
5658}
5659
5660/// Collect the names a top-level module item declares, for the exported-name
5661/// check.
5662fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
5663 match &stmt.kind {
5664 StmtKind::VarDecl(decl) => {
5665 // A `using` declaration is a lexical binding of the module's own scope but not
5666 // a *module variable*, so it cannot be exported: the reference excludes it from
5667 // `add_global_var` and `export {a}` of one reports
5668 // `exported variable 'a' does not exist`. Leaving it in this list would make
5669 // that export silently succeed.
5670 if decl.kind.is_using() {
5671 return;
5672 }
5673 for declarator in &decl.declarators {
5674 let mut names = Vec::new();
5675 declarator.target.bound_names(&mut names);
5676 out.extend(names.into_iter().map(|n| n.name));
5677 }
5678 }
5679 StmtKind::FuncDecl(func) => {
5680 if let Some(name) = &func.name {
5681 out.push(name.name.clone());
5682 }
5683 }
5684 StmtKind::ClassDecl(class) => {
5685 if let Some(name) = &class.name {
5686 out.push(name.name.clone());
5687 }
5688 }
5689 StmtKind::Import(decl) => {
5690 for specifier in &decl.specifiers {
5691 match specifier {
5692 ImportSpecifier::Default(id) => out.push(id.name.clone()),
5693 ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
5694 ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
5695 }
5696 }
5697 }
5698 StmtKind::Export(decl) => match &decl.kind {
5699 ExportKind::Declaration(inner) => collect_module_binding(inner, out),
5700 ExportKind::Default(expr) => match &expr.unparen().kind {
5701 ExprKind::Function(func) => {
5702 if let Some(name) = &func.name {
5703 out.push(name.name.clone());
5704 }
5705 }
5706 ExprKind::Class(class) => {
5707 if let Some(name) = &class.name {
5708 out.push(name.name.clone());
5709 }
5710 }
5711 _ => {}
5712 },
5713 _ => {}
5714 },
5715 _ => {}
5716 }
5717}
5718
5719/// Whether `inner` is fully inside `outer` (byte offset comparison only).
5720fn span_contains(outer: Span, inner: Span) -> bool {
5721 inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
5722}
5723
5724fn is_property_key_start(kind: &TokenKind) -> bool {
5725 matches!(
5726 kind,
5727 TokenKind::Ident(_)
5728 | TokenKind::Keyword(_)
5729 | TokenKind::String(_)
5730 | TokenKind::Number(_)
5731 | TokenKind::Punct(Punct::LBracket)
5732 | TokenKind::Punct(Punct::Hash)
5733 )
5734}
5735
5736/// A binary operator with its precedence, as consumed by [`Parser::parse_binary`].
5737#[derive(Debug, Clone, Copy)]
5738enum BinOp {
5739 Binary(BinaryOp),
5740 Logical(LogicalOp),
5741}
5742
5743impl BinOp {
5744 fn is_right_associative(self) -> bool {
5745 matches!(self, BinOp::Binary(BinaryOp::Pow))
5746 }
5747}
5748
5749fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
5750 use BinaryOp as B;
5751 use LogicalOp as L;
5752 let result = match kind {
5753 TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
5754 TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
5755 TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
5756 TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
5757 TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
5758 TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
5759 TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
5760 TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
5761 TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
5762 TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
5763 TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
5764 TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
5765 TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
5766 TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
5767 TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
5768 TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
5769 TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
5770 TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
5771 TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
5772 TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
5773 TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5774 TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5775 TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5776 TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5777 TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5778 _ => return None,
5779 };
5780 Some(result)
5781}
5782
5783fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5784 match op {
5785 BinOp::Binary(op) => Ok(Expr::at_operator(
5786 ExprKind::Binary {
5787 op,
5788 left: Box::new(left),
5789 right: Box::new(right),
5790 },
5791 span,
5792 op_pos,
5793 )),
5794 BinOp::Logical(op) => {
5795 // `??` may not be mixed with `&&`/`||` without parentheses.
5796 // A parenthesised operand is visibly a different production, so the
5797 // check must look at the raw node, not through `Paren`.
5798 let mixes = |expr: &Expr, op: LogicalOp| {
5799 matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5800 if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5801 };
5802 if mixes(&left, op) || mixes(&right, op) {
5803 return Err(SyntaxError::new(
5804 // The reference has no quotes in this one; the parenthesised form is the only
5805 // way to write it, which the message states rather than implies.
5806 "cannot mix ?? with && or ||",
5807 span,
5808 ));
5809 }
5810 Ok(Expr::at_operator(
5811 ExprKind::Logical {
5812 op,
5813 left: Box::new(left),
5814 right: Box::new(right),
5815 },
5816 span,
5817 op_pos,
5818 ))
5819 }
5820 }
5821}
5822
5823/// Rebuild an expression from a pattern (used when a pattern has to go back
5824/// through [`Parser::expr_to_pattern`], e.g. `{a: [b = 1]}`).
5825fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5826 match pattern.kind {
5827 PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5828 PatternKind::Assign { target, default } => Expr::new(
5829 ExprKind::Assign {
5830 op: AssignOp::Assign,
5831 target,
5832 value: default,
5833 },
5834 span,
5835 ),
5836 // A member target only ever reaches here by way of the cover grammar: `[o.p = 1]`
5837 // is parsed as an assignment whose target is already a pattern, and re-reading it
5838 // as an expression has to give the member back rather than a placeholder.
5839 PatternKind::Member(member) => {
5840 let MemberPattern {
5841 object,
5842 property,
5843 span,
5844 op_pos,
5845 } = *member;
5846 Expr {
5847 kind: ExprKind::Member {
5848 object,
5849 property,
5850 optional: false,
5851 },
5852 span,
5853 op_pos,
5854 }
5855 }
5856 PatternKind::Object { properties, rest } => {
5857 let mut out = Vec::new();
5858 for element in properties {
5859 match element {
5860 Some(PatternElement::Property {
5861 key,
5862 value,
5863 shorthand,
5864 span: _,
5865 }) => {
5866 let span = value.span;
5867 out.push(ObjectProperty::Property {
5868 key,
5869 value: Box::new(pattern_to_expr(value, span)),
5870 kind: PropertyKind::Value,
5871 shorthand,
5872 span,
5873 });
5874 }
5875 // An object pattern's elements are always properties; a bare pattern
5876 // here would be a malformed AST, and dropping it is the safe reading.
5877 None | Some(PatternElement::Pattern(_)) => {}
5878 }
5879 }
5880 if let Some(rest) = rest
5881 && let RestElement::Pattern(pattern) = *rest
5882 {
5883 let span = pattern.span;
5884 out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5885 pattern, span,
5886 ))));
5887 }
5888 Expr::new(ExprKind::Object(out), span)
5889 }
5890 PatternKind::Array { elements, rest } => {
5891 let mut out = Vec::new();
5892 for element in elements {
5893 match element {
5894 Some(PatternElement::Pattern(pattern)) => {
5895 let span = pattern.span;
5896 out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5897 pattern, span,
5898 )))));
5899 }
5900 Some(PatternElement::Property { .. }) | None => out.push(None),
5901 }
5902 }
5903 if let Some(rest) = rest {
5904 let RestElement::Pattern(pattern) = *rest else {
5905 return Expr::new(ExprKind::Null, span);
5906 };
5907 let span = pattern.span;
5908 out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5909 pattern, span,
5910 )))));
5911 }
5912 Expr::new(ExprKind::Array { elements: out }, span)
5913 }
5914 _ => Expr::new(ExprKind::Null, span),
5915 }
5916}
5917
5918impl Pattern {
5919 /// Pattern kind, ignoring `Paren` wrappers (patterns never have any, but
5920 /// this keeps call sites uniform with [`Expr::unparen`]).
5921 fn unparen_kind(&self) -> &PatternKind {
5922 &self.kind
5923 }
5924}
5925
5926/// Whether this `delete` operand ultimately names a private member.
5927///
5928/// Whether this `delete` operand ultimately names a private member.
5929///
5930/// §13.5.1.1: `delete` may not be applied to a `MemberExpression : MemberExpression.PrivateName`
5931/// or a `CallExpression : CallExpression.PrivateName`, and the rule re-applies to a
5932/// parenthesised phrase. So the walk goes through parentheses and through a call's callee, and
5933/// stops everywhere else — including a sequence, because `delete (0, o.#x)` parenthesises
5934/// `0, o.#x`, and that phrase in place of the operand is `delete 0, o.#x`, which is legal. The
5935/// reference agrees: it accepts that one and rejects `delete (g().#x)`.
5936/// The `import()` call an unparenthesised member chain bottoms out at, if there is one.
5937///
5938/// `new` needs a `MemberExpression`, and `import()` is a `CallExpression`, so every shape
5939/// where `new` takes an `import()` through member access is a SyntaxError — `new
5940/// import('').p` and `new import('')['p']` as much as `new import('')`. The walk stops at a
5941/// `Paren`, because `(import(''))` *is* a PrimaryExpression and therefore a MemberExpression:
5942/// `new (import('')).p` is legal and throws at run time for not being a constructor.
5943fn member_chain_import_call(expr: &Expr) -> Option<&Expr> {
5944 match &expr.kind {
5945 ExprKind::ImportCall(..) => Some(expr),
5946 ExprKind::Member { object, .. } => member_chain_import_call(object),
5947 // A parenthesised expression, a call or anything else is not a member chain.
5948 _ => None,
5949 }
5950}
5951
5952fn deletes_a_private_member(expr: &Expr) -> bool {
5953 match &expr.unparen().kind {
5954 ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5955 ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5956 _ => false,
5957 }
5958}
5959
5960/// A string that has to be a `&str` — a module specifier or an import attribute.
5961///
5962/// These reach the loader and the filesystem, neither of which can do anything with an
5963/// unpaired surrogate, so the lossy conversion is the honest one: it is what a path
5964/// encoding would do anyway. Every *other* cooked string in the tree keeps the surrogate,
5965/// because the language can observe it there.
5966fn as_specifier(value: &Wtf8) -> String {
5967 value.to_string_lossy().into_owned()
5968}