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