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