Skip to content

Truly independent web browser

LibJS: Add a parser that analyzes scopes as it goes

Andreas Kling01754a6a2d47
diff --git a/Libraries/LibJS/Rust/src/parser/base.rs b/Libraries/LibJS/Rust/src/parser/base.rs
new file mode 100644
index 00000000000..3483b6fb312
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/parser/base.rs
@@ -0,0 +1,2326 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Parser state, scope analysis and the function boundary.
+//!
+//! Scope analysis keeps no map per scope. Each name has one row of state, and scopes are numbered in opening order, so
+//! a scope's subtree is every scope id at or above its own once it closes:
+//!
+//! - A use pushes a row on the `uses` stack, linked to the name's previous use. Repeated uses in one scope are free.
+//! - When a scope closes, each of its bindings pops the name's uses from that subtree. A popped use from another
+//! function means the binding is captured. The work is proportional to bindings, not to references.
+//! - When a function closes, what is left of its uses are its free names. They collapse to one row each, which is what
+//! the function index keeps, and which is all an enclosing scope ever needs to know about the function.
+//!
+//! Errors do not unwind. The first one is recorded and the token stream ends, so every loop in the parser finishes on
+//! its own, and no parse function has to return a Result.
+
+use super::columns::*;
+use super::intern::Interner;
+use super::token::*;
+use super::unit::Unit;
+
+pub const USE_DEAD: u32 = u32::MAX;
+/// On the function of a use: the use is inside a `with`.
+pub const USE_IN_WITH: u32 = 1 << 31;
+
+/// What the lexer finds past the end of a source without padding once a parse has given up on it.
+static NO_MORE_SOURCE: [u16; 64] = [0; 64];
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Mode {
+ /// Only keep the tree of top-level code and of functions that are likely called right away.
+ Lazy,
+ /// Keep the tree of everything.
+ Full,
+}
+
+#[derive(Clone, Copy, Default)]
+#[repr(C)]
+pub(crate) struct NameState {
+ use_head: u32,
+ use_scope: u32,
+ decl_head: u32,
+ stamp: u32,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct UseRow {
+ name: u32,
+ scope: u32,
+ func: u32,
+ prev: u32,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct DeclRow {
+ name: u32,
+ scope: u32,
+ flags: u32,
+ next_same_name: u32,
+ next_in_scope: u32,
+ /// The innermost scope a `var` of this name was written in, on the row in the function. Scopes are numbered in
+ /// opening order, so that an open scope contains such a `var` exactly when this is at or above its id.
+ last_var_scope: u32,
+ /// The row in the tree that this binding got.
+ out_binding: u32,
+ /// Where this binding is in the summary of its function, or NONE, or what is known of one that comes up early.
+ summary_slot: u32,
+}
+
+/// Stands for the row of the top level in what goes into summaries, which sorts after all functions.
+const PROGRAM_SUMMARY_ROW: u32 = 0x7FFF_FFFE;
+/// The `summary_slot` of a binding that comes up before its declaration.
+const SUMMARY_SLOT_EARLY: u32 = 1 << 31;
+/// The `summary_slot` of a binding of a scope inside a function, which has no place in the bitmap.
+const SUMMARY_SLOT_INNER: u32 = 1 << 30;
+
+pub mod decl {
+ pub const LEXICAL: u32 = 1 << 0;
+ pub const FUNCTION: u32 = 1 << 1;
+ pub const VAR: u32 = 1 << 2;
+ pub const SIMPLE_CATCH: u32 = 1 << 3;
+ pub const PARAMETER: u32 = 1 << 4;
+ pub const FUNCTION_NAME: u32 = 1 << 5;
+ pub const ANNEX_B: u32 = 1 << 6;
+ pub const CAPTURED: u32 = 1 << 7;
+ /// The inner binding of a class's own name.
+ pub const CLASS_NAME: u32 = 1 << 8;
+ /// A function in a block whose name Annex B.3.3 also makes a `var`.
+ pub const HOISTED: u32 = 1 << 9;
+ /// A name bound by a catch parameter pattern, which no `var` may redeclare.
+ pub const CATCH_PATTERN: u32 = 1 << 10;
+ /// A `var` of a function body that a parameter expression refers to the name of.
+ pub const REFERENCED_IN_PARAMETERS: u32 = 1 << 11;
+ pub const DECLARED_LET: u32 = 1 << 12;
+ pub const DECLARED_CONST: u32 = 1 << 13;
+ pub const DECLARED_VAR: u32 = 1 << 14;
+ /// A sloppy function declared in a block that may get hoisted.
+ pub const HOISTABLE: u32 = 1 << 15;
+ /// The name of a function that Annex B.3.3 makes a `var` here.
+ pub const ANNEX_B_NAME: u32 = 1 << 16;
+ /// Something in a `with` uses the name, so that the name may mean a property of the object.
+ pub const USED_IN_WITH: u32 = 1 << 17;
+}
+
+pub mod scope_flag {
+ pub const TOP: u16 = 1 << 0;
+ pub const FUNCTION: u16 = 1 << 1;
+ pub const STATIC_BLOCK: u16 = 1 << 2;
+ pub const ARROW: u16 = 1 << 3;
+ pub const BODY_OF_PARAMETERS: u16 = 1 << 4;
+ pub const SWITCH: u16 = 1 << 5;
+ pub const VAR_SCOPE: u16 = TOP | FUNCTION | STATIC_BLOCK | BODY_OF_PARAMETERS;
+ pub const CATCH: u16 = 1 << 6;
+ pub const CLASS: u16 = 1 << 7;
+ pub const WITH: u16 = 1 << 8;
+ pub const CLASS_FIELD: u16 = 1 << 9;
+ pub const CATCH_BODY: u16 = 1 << 10;
+}
+
+/// Bits of a scope's row in the tree, above its scope flags.
+pub const SCOPE_ROW_EVAL_IN_FUNCTION: u32 = 1 << 16;
+pub const SCOPE_ROW_POISONED: u32 = 1 << 17;
+
+#[derive(Clone, Copy)]
+pub(crate) struct Scope {
+ pub id: u32,
+ pub flags: u16,
+ pub func: u32,
+ /// Where the summary of the function finds the scope.
+ pub start: u32,
+ pub decl_head: u32,
+ /// Whether this scope or anything nested in it calls eval directly.
+ pub has_eval: bool,
+ /// Whether this scope or a scope of the same function nested in it calls eval directly.
+ pub eval_in_function: bool,
+ /// Whether code directly in this scope calls eval.
+ pub eval_here: bool,
+ /// The index of the scope that a `var` here belongs to.
+ pub var_scope: u32,
+ /// Whether code directly in this scope reads `arguments` in sloppy mode.
+ pub arguments_access: bool,
+ /// Whether a scope nested in this one does, which a parameter can not turn out to explain.
+ pub nested_arguments_access: bool,
+ pub use_mark: u32,
+ pub hoist_mark: u32,
+}
+
+/// A sloppy function declaration on its way up to the scope that Annex B.3.3 hoists it to.
+#[derive(Clone, Copy)]
+pub(crate) struct Hoist {
+ pub name: u32,
+ /// Its declaration, whose binding row in the tree says what to mark.
+ pub declaration: u32,
+ pub own_scope: u32,
+}
+
+pub mod ctx {
+ pub const GENERATOR: u32 = 1 << 0;
+ pub const ASYNC: u32 = 1 << 1;
+ pub const CAN_AWAIT: u32 = 1 << 2;
+ pub const SUPER_PROPERTY: u32 = 1 << 3;
+ pub const SUPER_CALL: u32 = 1 << 4;
+ pub const NEW_TARGET: u32 = 1 << 5;
+ pub const STATIC_BLOCK: u32 = 1 << 6;
+ pub const NO_ARGUMENTS: u32 = 1 << 7;
+ pub const RETURN: u32 = 1 << 8;
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct Label {
+ /// 0 for a plain label, 1 for a loop, 2 for a switch.
+ pub kind: u8,
+ pub statement_start: u32,
+}
+
+/// What a function saves of its surroundings while it parses.
+pub(crate) struct FunctionState {
+ pub marks: AstMarks,
+ pub row: u32,
+ pub ctx: u32,
+ pub strict: bool,
+ pub labels_base: u32,
+ pub yield_pos: u32,
+ pub await_pos: u32,
+ pub await_ident_pos: u32,
+ pub cover_error: u32,
+ pub retain: bool,
+ pub duplicate_parameter: u32,
+ pub start: u32,
+ pub flags: u32,
+ pub has_body_scope: bool,
+ pub body_start: u32,
+ /// The first row of the body.
+ pub first_body_row: u32,
+ pub uses_this: bool,
+ pub uses_this_from_environment: bool,
+ pub might_need_arguments: bool,
+ pub in_class_of_sloppy_function: bool,
+ pub is_arrow: bool,
+ pub summary_ordinal: u32,
+}
+
+/// The first syntax error, at a source offset.
+pub struct PendingError {
+ pub pos: u32,
+ pub message: String,
+}
+
+/// What the first parse of a top level went by, which parsing it again has to go by too.
+#[derive(Clone, Copy)]
+pub(crate) struct ProgramContext {
+ pub(crate) context: u32,
+ pub(crate) starts_in_strict_mode: bool,
+ pub(crate) initiated_by_eval: bool,
+ /// Whether no name means a global binding.
+ pub(crate) has_no_globals: bool,
+}
+
+pub struct Parser<'a, U: Unit> {
+ /// Where in `rows_by_params_start` the last lookup ended up.
+ row_cursor: core::cell::Cell<usize>,
+ /// Whether the tree is one for a sweep: rows get marks, and change their tag where a mark is about them.
+ pub(crate) marks: bool,
+ /// The row in the index of the code of a class that was parsed last, and what it knows of that code by now.
+ pub(crate) pseudo_function_row: u32,
+ pub(crate) pseudo_function_flags: u32,
+ /// The mark of the block being parsed, for the functions it declares, and the function that it declared last.
+ pub(crate) block_mark: u32,
+ pub(crate) last_function_of_block: u32,
+ /// Whether the list of arguments that was parsed last has a spread element.
+ pub(crate) arguments_have_spread: bool,
+ /// Whether anything uses what scopes declare and what code refers to, which a sweep with a summary does not.
+ pub(crate) tracks_scopes: bool,
+ /// Whether the first parse leaves a summary of the bindings of each function.
+ records_summaries: bool,
+ /// How many bindings of the function being parsed have a place in its summary.
+ pub(crate) summary_ordinal: u32,
+ pub(crate) src: *const U,
+ pub len: u32,
+ pub(crate) pos: u32,
+ pub(crate) tok: T,
+ pub(crate) tok_start: u32,
+ pub(crate) tok_end: u32,
+ pub(crate) tok_name: u32,
+ pub(crate) nl_before: bool,
+ pub(crate) tok_escaped: bool,
+ /// A legacy octal number or a string with a legacy octal escape, both of which strict mode rejects.
+ pub(crate) tok_legacy: bool,
+ pub(crate) prev_end: u32,
+ pub(crate) prev_start: u32,
+ pub(crate) regex_body_end: u32,
+ pub(crate) name_buffer: Vec<u8>,
+ pub interner: Interner,
+
+ pub ast: Ast,
+ pub index: FunctionIndex,
+ pub(crate) scratch: Vec<u32>,
+ pub(crate) mode: Mode,
+ pub(crate) retain: bool,
+
+ pub module: bool,
+ pub strict: bool,
+ pub(crate) ctx: u32,
+ pub(crate) labels: Vec<Label>,
+ pub(crate) labels_base: u32,
+ pub(crate) stack_limit: usize,
+ recursion_depth: u32,
+ pub(crate) potential_arrow_at: u32,
+ pub(crate) cover_error: u32,
+ pub(crate) yield_pos: u32,
+ pub(crate) await_pos: u32,
+ pub(crate) await_ident_pos: u32,
+ pub(crate) duplicate_parameter: u32,
+ /// The node of the last arrow function, which no operator may follow.
+ pub(crate) last_arrow: u32,
+ /// Whether the function expression about to be parsed follows `(` or `!`.
+ /// Where the expression in the parentheses opened last starts. A function there is likely to be called, but not one
+ /// that starts after the `(` of a list of arguments, which an arrow function usually is.
+ pub(crate) parenthesized_expression_start: u32,
+ /// Whether this is the left side of `for await`, where `async of` is no arrow function.
+ pub(crate) for_await_head: bool,
+
+ pub(crate) names: Vec<NameState>,
+ pub(crate) uses: Vec<UseRow>,
+ pub(crate) decls: Vec<DeclRow>,
+ pub(crate) scopes: Vec<Scope>,
+ pub(crate) cur_scope: u32,
+ pub(crate) cur_func: u32,
+ pub(crate) next_scope: u32,
+ pub(crate) next_func: u32,
+ /// The index row of each function id, or NONE for what only counts as a function.
+ pub(crate) function_rows: Vec<u32>,
+ /// The row whose summary tells of the scopes of each function id, which is that of the function around a `with`.
+ pub(crate) summary_rows: Vec<u32>,
+ pub(crate) stamp: u32,
+
+ pub has_top_level_await: bool,
+ pub first_token_start: u32,
+ pub(crate) last_pseudo_function_row: u32,
+ pub(crate) class_start: u32,
+ pub(crate) if_start: u32,
+ pub(crate) retain_next_function: bool,
+ /// While reparsing: what the first parse found out about the functions of the source.
+ first_pass_index: *const FunctionIndex,
+ /// While reparsing: where the function being reparsed starts over.
+ pub(crate) reparse_target: u32,
+ pub(crate) with_depth: u32,
+ pub(crate) names_used_in_with: Vec<u32>,
+ pub(crate) free_names_scratch: Vec<u32>,
+ /// The innermost label of each name, as its index in `labels`.
+ pub(crate) label_indices: std::collections::HashMap<u32, u32>,
+ /// The undeclared names that something in a `with` uses, which are not simply globals.
+ pub global_names_used_in_with: Vec<u32>,
+ pub(crate) hoists: Vec<Hoist>,
+ pub(crate) uses_this: bool,
+ pub(crate) uses_this_from_environment: bool,
+ pub(crate) might_need_arguments: bool,
+ /// Whether the code being parsed is in a class in a function that is not strict. The code of a class is strict, but
+ /// `arguments` in its heritage and computed keys is the arguments object of that function.
+ pub(crate) in_class_of_sloppy_function: bool,
+ /// Whether the closest function, counting static blocks, is an arrow function.
+ pub(crate) in_arrow: bool,
+
+ /// The private names of each open class, created when a class first declares one.
+ pub(crate) private_declared: Vec<std::collections::HashMap<u32, u8>>,
+ pub(crate) private_used: Vec<(u32, u32)>,
+ pub(crate) class_marks: Vec<(u32, u32)>,
+ pub(crate) export_names: std::collections::HashSet<u32>,
+ pub(crate) export_locals: Vec<(u32, u32)>,
+
+ pub err: Option<PendingError>,
+ /// Whether this is the code of an eval, whose private names the code around it may declare.
+ pub initiated_by_eval: bool,
+ /// The private names that no class in this code declares, for an eval.
+ pub eval_referenced_private_names: Vec<u32>,
+ _marker: core::marker::PhantomData<&'a [U]>,
+}
+
+/// How much native stack parsing may use by default. Nesting past this is a syntax error rather than a crash.
+pub const DEFAULT_STACK_BUDGET: usize = 4 << 20;
+
+/// How deeply statements and expressions may nest.
+const MAX_RECURSION_DEPTH: u32 = 2000;
+
+pub(crate) const RECURSION_LIMIT_MESSAGE: &str = "Maximum parser recursion depth exceeded";
+
+impl<'a, U: Unit> Parser<'a, U> {
+ /// # Safety
+ /// `source` must be followed by at least 64 units of zeros within the same allocation.
+ pub unsafe fn new(source: &'a [U], module: bool, mode: Mode) -> Self {
+ let estimated_nodes = match mode {
+ Mode::Lazy => (source.len() / 3 + 1024).min(1 << 16),
+ Mode::Full => source.len() / 3 + 1024,
+ };
+ let estimated_functions = source.len() / 128 + 16;
+ let mut parser = Self::with_capacities(
+ source.as_ptr(),
+ source.len(),
+ module,
+ mode,
+ Interner::new(source.len()),
+ estimated_nodes,
+ estimated_functions,
+ 1 << 16,
+ );
+ if source.len() >= u32::MAX as usize - 64 {
+ parser.len = 0;
+ parser.fail(0, "Source too long");
+ }
+ parser.skip_hashbang();
+ parser
+ }
+
+ fn skip_hashbang(&mut self) {
+ if self.at(0) == 0x23 && self.at(1) == 0x21 {
+ // Hashbang comment.
+ let mut p = 2;
+ while p < self.len as usize && !matches!(self.at(p), 0x0A | 0x0D | 0x2028 | 0x2029) {
+ p += 1;
+ }
+ self.pos = p as u32;
+ }
+ }
+
+ /// A parser that only parses functions again, one at a time, knowing what the first parse of their source found.
+ /// Its source comes with each function.
+ ///
+ /// # Safety
+ /// `first_pass_index` must stay valid and unchanged for as long as the parser reparses functions.
+ pub(crate) unsafe fn for_reparsing(
+ module: bool,
+ interner: Interner,
+ first_pass_index: &FunctionIndex,
+ source_length: u32,
+ ) -> Self {
+ let mut parser = Self::with_capacities(
+ core::ptr::null(),
+ source_length as usize,
+ module,
+ Mode::Lazy,
+ interner,
+ 256,
+ 0,
+ 256,
+ );
+ parser.first_pass_index = first_pass_index;
+ parser
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn with_capacities(
+ source: *const U,
+ length: usize,
+ module: bool,
+ mode: Mode,
+ interner: Interner,
+ estimated_nodes: usize,
+ estimated_functions: usize,
+ estimated_uses: usize,
+ ) -> Self {
+ let estimated_names = if estimated_uses < 1 << 16 {
+ interner.len().next_power_of_two()
+ } else {
+ 1 << 12
+ };
+ let mut parser = Self {
+ row_cursor: core::cell::Cell::new(0),
+ marks: false,
+ pseudo_function_row: NONE,
+ pseudo_function_flags: 0,
+ block_mark: NONE,
+ last_function_of_block: 0,
+ arguments_have_spread: false,
+ tracks_scopes: true,
+ records_summaries: true,
+ summary_ordinal: 0,
+ src: source,
+ len: length as u32,
+ pos: 0,
+ tok: T::Eof,
+ tok_start: 0,
+ tok_end: 0,
+ tok_name: 0,
+ nl_before: false,
+ tok_escaped: false,
+ tok_legacy: false,
+ prev_end: 0,
+ prev_start: 0,
+ regex_body_end: 0,
+ name_buffer: Vec::with_capacity(256),
+ interner,
+ ast: Ast::with_capacity(estimated_nodes),
+ index: FunctionIndex {
+ start: Vec::with_capacity(estimated_functions),
+ params_start: Vec::with_capacity(estimated_functions),
+ end: Vec::with_capacity(estimated_functions),
+ flags: Vec::with_capacity(estimated_functions),
+ length: Vec::with_capacity(estimated_functions),
+ parameter_count: Vec::with_capacity(estimated_functions),
+ ctx: Vec::with_capacity(estimated_functions),
+ name: Vec::with_capacity(estimated_functions),
+ capture_start: Vec::with_capacity(estimated_functions),
+ capture_count: Vec::with_capacity(estimated_functions),
+ capture_names: Vec::new(),
+ pending_captures: Vec::with_capacity(estimated_functions * 2),
+ summaries: Vec::new(),
+ declared_names: Vec::new(),
+ summary_start: Vec::new(),
+ pending_summaries: Vec::new(),
+ pending_scope_bindings: Vec::new(),
+ program_summary_end: 0,
+ program_has_direct_eval: false,
+ ..FunctionIndex::default()
+ },
+ scratch: Vec::with_capacity(estimated_uses.min(4096)),
+ mode,
+ retain: true,
+ module,
+ strict: module,
+ ctx: if module { ctx::CAN_AWAIT } else { 0 },
+ labels: Vec::with_capacity(64),
+ labels_base: 0,
+ stack_limit: 0,
+ recursion_depth: 0,
+ potential_arrow_at: NONE,
+ cover_error: NONE,
+ yield_pos: 0,
+ await_pos: 0,
+ await_ident_pos: 0,
+ duplicate_parameter: NONE,
+ last_arrow: 0,
+ parenthesized_expression_start: NONE,
+ for_await_head: false,
+ names: vec![
+ NameState {
+ use_head: NONE,
+ use_scope: NONE,
+ decl_head: NONE,
+ stamp: 0
+ };
+ estimated_names
+ ],
+ uses: Vec::with_capacity(estimated_uses),
+ decls: Vec::with_capacity(estimated_uses / 16),
+ scopes: Vec::with_capacity(256),
+ cur_scope: 0,
+ cur_func: 0,
+ next_scope: 1,
+ next_func: 1,
+ function_rows: vec![NONE],
+ summary_rows: vec![PROGRAM_SUMMARY_ROW],
+ stamp: 0,
+ has_top_level_await: false,
+ first_token_start: 0,
+ last_pseudo_function_row: NONE,
+ class_start: 0,
+ if_start: 0,
+ retain_next_function: false,
+ first_pass_index: core::ptr::null(),
+ reparse_target: NONE,
+ with_depth: 0,
+ names_used_in_with: Vec::new(),
+ free_names_scratch: Vec::new(),
+ label_indices: std::collections::HashMap::new(),
+ global_names_used_in_with: Vec::new(),
+ hoists: Vec::new(),
+ uses_this: false,
+ uses_this_from_environment: false,
+ might_need_arguments: false,
+ in_class_of_sloppy_function: false,
+ in_arrow: false,
+
+ private_declared: Vec::new(),
+ private_used: Vec::new(),
+ class_marks: Vec::new(),
+ export_names: std::collections::HashSet::new(),
+ export_locals: Vec::new(),
+ err: None,
+ initiated_by_eval: false,
+ eval_referenced_private_names: Vec::new(),
+ _marker: core::marker::PhantomData,
+ };
+ // NB: Code can start parsing with less stack left than the budget, as eval near the end of the stack does.
+ parser.stack_limit = super::stack_limit_for_budget(DEFAULT_STACK_BUDGET)
+ .max(super::vm_stack_limit_of_this_thread().unwrap_or(0));
+ parser
+ }
+
+ /// Allows what `context` allows from the start of the program.
+ pub fn add_context(&mut self, context: u32) {
+ self.ctx |= context;
+ }
+
+ pub fn parse_program(&mut self) -> u32 {
+ self.open_scope_with(scope_flag::TOP, 0);
+ if !self.strict {
+ self.strict = self.has_use_strict_directive(self.pos as usize);
+ }
+ self.lex();
+ self.first_token_start = self.tok_start;
+ let mark = self.scratch.len();
+ while self.tok != T::Eof {
+ let statement = self.parse_statement_list_item(true);
+ self.scratch.push(statement);
+ }
+ let list = self.finish_list(mark);
+ if self.is_reparsing() {
+ let scope_row = self.close_scope();
+ return self.ast.push(tag::PROGRAM, 0, list, scope_row);
+ }
+ if self.module {
+ self.check_exported_locals();
+ }
+ self.check_unresolved_private_names();
+ self.index.program_has_direct_eval = self.scopes.last().unwrap().eval_in_function;
+ let scope_row = self.close_scope();
+ for row in &self.uses {
+ if row.name != USE_DEAD && row.func & USE_IN_WITH != 0 {
+ self.global_names_used_in_with.push(row.name);
+ }
+ }
+ self.group_captures();
+ self.group_summaries();
+ self.ast.push(tag::PROGRAM, 0, list, scope_row)
+ }
+
+ /// Goes through the top level once more with marks for a sweep, past all functions, after a parse that went well.
+ pub(crate) fn parse_top_level_rows(&mut self, context: ProgramContext) -> Result<(Ast, u32), super::OutOfStack> {
+ let tree = std::mem::replace(&mut self.ast, Ast::with_capacity(256));
+ let private_names = std::mem::take(&mut self.eval_referenced_private_names);
+ let (first_token_start, strict, has_top_level_await) =
+ (self.first_token_start, self.strict, self.has_top_level_await);
+ self.finish_reparse();
+ self.export_names.clear();
+ self.first_pass_index = &raw const self.index;
+ self.tracks_scopes = false;
+ self.marks = true;
+ let node = self.reparse_program(context);
+ self.first_pass_index = core::ptr::null();
+ let error = self.err.take();
+ let rows = std::mem::replace(&mut self.ast, tree);
+ self.eval_referenced_private_names = private_names;
+ self.first_token_start = first_token_start;
+ self.strict = strict;
+ self.has_top_level_await = has_top_level_await;
+ match error {
+ None => Ok((rows, node)),
+ Some(error) => {
+ assert_eq!(
+ error.message, RECURSION_LIMIT_MESSAGE,
+ "the first parse found no errors"
+ );
+ Err(super::OutOfStack)
+ }
+ }
+ }
+
+ /// Gets ready to go through the top level again, past all functions, like the first parse did.
+ pub(crate) fn reparse_program(&mut self, context: ProgramContext) -> u32 {
+ self.reparse_target = NONE;
+ self.strict = context.starts_in_strict_mode;
+ self.initiated_by_eval = context.initiated_by_eval;
+ self.ctx = if self.module { ctx::CAN_AWAIT } else { 0 } | context.context;
+ self.retain = true;
+ self.retain_next_function = false;
+ self.uses_this = false;
+ self.uses_this_from_environment = false;
+ self.might_need_arguments = false;
+ self.in_arrow = false;
+ self.cover_error = NONE;
+ self.potential_arrow_at = NONE;
+ self.last_arrow = 0;
+ self.pos = 0;
+ self.tok_end = 0;
+ self.prev_end = 0;
+ self.prev_start = 0;
+ self.skip_hashbang();
+ let node = self.parse_program();
+ self.initiated_by_eval = false;
+ node
+ }
+
+ /// Groups the captures by function, now that all of them are known.
+ fn group_captures(&mut self) {
+ let index = &mut self.index;
+ let pending = std::mem::take(&mut index.pending_captures);
+ for &(row, _) in &pending {
+ index.capture_count[row as usize] += 1;
+ }
+ let mut next = 0;
+ for row in 0..index.capture_start.len() {
+ index.capture_start[row] = next;
+ next += index.capture_count[row];
+ }
+ index.capture_names.resize(next as usize, 0);
+ let mut filled = vec![0u32; index.capture_start.len()];
+ for (row, name) in pending {
+ let slot = index.capture_start[row as usize] + filled[row as usize];
+ filled[row as usize] += 1;
+ index.capture_names[slot as usize] = name;
+ }
+ }
+
+ /// Writes out the summaries of all functions, now that all of their scopes closed.
+ fn group_summaries(&mut self) {
+ fn write_varint(bytes: &mut Vec<u8>, mut value: u32) {
+ while value >= 0x80 {
+ bytes.push(value as u8 | 0x80);
+ value >>= 7;
+ }
+ bytes.push(value as u8);
+ }
+ fn write_scope_bindings(bytes: &mut Vec<u8>, bindings: &[(u32, u32, u32)]) {
+ let scope_count = bindings.chunk_by(|a, b| a.1 == b.1).count();
+ write_varint(bytes, scope_count as u32);
+ let mut last_position = 0;
+ for scope in bindings.chunk_by(|a, b| a.1 == b.1) {
+ write_varint(bytes, scope[0].1 - last_position);
+ last_position = scope[0].1;
+ write_varint(bytes, scope.len() as u32);
+ for binding in scope {
+ write_varint(bytes, binding.2);
+ }
+ }
+ }
+ let index = &mut self.index;
+ let mut pending = std::mem::take(&mut index.pending_summaries);
+ pending.sort_unstable();
+ // NB: Rows with bit 31 set sort after all the others, so that each kind is a run of its own.
+ let captured_start = pending.partition_point(|&(row, _)| row & SUMMARY_SLOT_EARLY == 0);
+ let (mut early, mut captured) = (0, captured_start);
+ let mut scope_bindings = std::mem::take(&mut index.pending_scope_bindings);
+ scope_bindings.sort_unstable();
+ let mut scope_binding = 0;
+ let mut bitmap = Vec::new();
+ // NB: The top level has no row of its own, so its summary comes first, and it has only scopes in it.
+ let of_program = scope_bindings.partition_point(|binding| binding.0 != PROGRAM_SUMMARY_ROW);
+ write_varint(&mut index.summaries, 0);
+ write_scope_bindings(&mut index.summaries, &scope_bindings[of_program..]);
+ index.program_summary_end = index.summaries.len() as u32;
+ scope_bindings.truncate(of_program);
+ for row in 0..index.summary_start.len() as u32 {
+ index.summary_start[row as usize] = index.summaries.len() as u32;
+ let early_start = early;
+ while early < captured_start && pending[early].0 == row {
+ early += 1;
+ }
+ bitmap.clear();
+ while captured < pending.len() && pending[captured].0 & !SUMMARY_SLOT_EARLY == row {
+ let ordinal = pending[captured].1 as usize;
+ if ordinal / 8 >= bitmap.len() {
+ bitmap.resize(ordinal / 8 + 1, 0u8);
+ }
+ bitmap[ordinal / 8] |= 1 << (ordinal % 8);
+ captured += 1;
+ }
+ let scope_bindings_start = scope_binding;
+ while scope_binding < scope_bindings.len() && scope_bindings[scope_binding].0 == row {
+ scope_binding += 1;
+ }
+ let bindings_of_scopes = &scope_bindings[scope_bindings_start..scope_binding];
+ if early == early_start && bitmap.is_empty() && bindings_of_scopes.is_empty() {
+ continue;
+ }
+ write_varint(&mut index.summaries, (early - early_start) as u32);
+ for entry in &pending[early_start..early] {
+ write_varint(&mut index.summaries, entry.1);
+ }
+ write_scope_bindings(&mut index.summaries, bindings_of_scopes);
+ index.summaries.extend_from_slice(&bitmap);
+ }
+ }
+
+ /// A declaration of something that was only the name of a function expression makes that a binding like any other.
+ #[inline(always)]
+ fn note_redeclared_function_name(&mut self, declaration: u32, name: u32, scope_index: usize, bind: Bind) {
+ if self.decls[declaration as usize].flags & !decl::FUNCTION_NAME == 0 {
+ self.note_new_binding_of(declaration as usize, name, scope_index, bind);
+ }
+ }
+
+ /// A new binding of the function being parsed came up.
+ #[inline(always)]
+ fn note_new_binding(&mut self, name: u32, scope_index: usize, bind: Bind) {
+ self.note_new_binding_of(self.decls.len() - 1, name, scope_index, bind);
+ }
+
+ #[inline(always)]
+ fn note_new_binding_of(&mut self, d: usize, name: u32, scope_index: usize, bind: Bind) {
+ if !self.records_summaries {
+ return;
+ }
+ let scope = &self.scopes[scope_index];
+ let head = self.names[name as usize].use_head;
+ let is_function_level = scope.flags & scope_flag::VAR_SCOPE != 0;
+ let kind = match bind {
+ Bind::Let | Bind::Lexical | Bind::CatchPattern => 1,
+ Bind::Const => 2,
+ _ => 0,
+ };
+ // NB: A declaration of the name `arguments` has a say in the arguments object, which comes before all else.
+ let is_of_arguments = name == N_ARGUMENTS && is_function_level;
+ let is_early = bind != Bind::Parameter
+ && (is_of_arguments || (head != NONE && self.uses[head as usize].scope >= scope.id));
+ self.decls[d].summary_slot = if is_early {
+ SUMMARY_SLOT_EARLY | kind
+ } else if is_function_level {
+ self.summary_ordinal += 1;
+ self.summary_ordinal - 1
+ } else {
+ SUMMARY_SLOT_INNER | kind
+ };
+ }
+
+ /// What the summary of its function says of a binding whose scope closes.
+ #[inline(always)]
+ fn note_closed_binding(&mut self, summary_slot: u32, name: u32, is_captured: bool, scope: Scope) {
+ if summary_slot == NONE {
+ return;
+ }
+ let index_row = self.summary_rows[scope.func as usize];
+ if index_row == NONE {
+ return;
+ }
+ // NB: What the top level itself declares is no business of a summary, that is declaration instantiation.
+ if index_row == PROGRAM_SUMMARY_ROW && scope.flags & scope_flag::VAR_SCOPE != 0 {
+ return;
+ }
+ let is_early = summary_slot & SUMMARY_SLOT_EARLY != 0;
+ let entry = name << 3 | (summary_slot & 3) << 1 | u32::from(is_captured);
+ if scope.flags & scope_flag::VAR_SCOPE == 0 {
+ // NB: A `case` can be skipped, so that a declaration in a switch is no sign of having been initialized.
+ if is_early || is_captured || scope.flags & scope_flag::SWITCH != 0 {
+ self.index.pending_scope_bindings.push((index_row, scope.start, entry));
+ }
+ } else if is_early {
+ self.index.pending_summaries.push((index_row, entry));
+ } else if is_captured {
+ self.index
+ .pending_summaries
+ .push((index_row | SUMMARY_SLOT_EARLY, summary_slot));
+ }
+ }
+
+ #[cold]
+ #[inline(never)]
+ pub(crate) fn fail(&mut self, pos: u32, message: &'static str) {
+ self.fail_with(pos, message.to_string());
+ }
+
+ #[cold]
+ #[inline(never)]
+ pub(crate) fn fail_with(&mut self, pos: u32, message: String) {
+ if self.err.is_none() {
+ self.err = Some(PendingError { pos, message });
+ }
+ if self.is_reparsing() {
+ // The end of the source may have no padding, and the lexer is about to read it.
+ self.src = NO_MORE_SOURCE.as_ptr().cast::<U>().wrapping_sub(self.len as usize);
+ }
+ self.tok = T::Eof;
+ self.tok_start = self.len;
+ self.tok_end = self.len;
+ self.pos = self.len;
+ }
+
+ #[cold]
+ #[inline(never)]
+ pub(crate) fn unexpected(&mut self) {
+ let message = self.unexpected_token_message();
+ self.fail_with(self.tok_start, message);
+ }
+
+ #[cold]
+ #[inline(never)]
+ pub(crate) fn expected(&mut self, what: &str) {
+ let message = format!("{}. Expected {what}", self.unexpected_token_message());
+ self.fail_with(self.tok_start, message);
+ }
+
+ /// Fails for a token where a list goes on with a comma or ends.
+ #[cold]
+ #[inline(never)]
+ fn expected_comma_or(&mut self, close: T) {
+ self.expected(&format!("',' or {}", close.spelling()));
+ }
+
+ /// What a list expects after an item: a comma, or the token that ends the list, which the caller looks for.
+ #[inline(always)]
+ pub(crate) fn expect_comma_or(&mut self, close: T) {
+ if self.tok == T::Comma {
+ self.next();
+ } else {
+ self.expected_comma_or(close);
+ }
+ }
+
+ /// Calls the current token what the source calls it.
+ fn unexpected_token_message(&self) -> String {
+ const LONGEST_TOKEN_SHOWN: u32 = 40;
+ if self.tok == T::Eof {
+ return "Unexpected end of input".to_string();
+ }
+ let end = self.tok_end.min(self.tok_start + LONGEST_TOKEN_SHOWN);
+ let units: Vec<u16> = (self.tok_start..end)
+ .map(|index| self.at(index as usize) as u16)
+ .collect();
+ let ellipsis = if end < self.tok_end { "..." } else { "" };
+ format!("Unexpected token '{}{ellipsis}'", String::from_utf16_lossy(&units))
+ }
+
+ #[inline(always)]
+ pub(crate) fn eat(&mut self, kind: T) -> bool {
+ if self.tok == kind {
+ self.next();
+ true
+ } else {
+ false
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn expect(&mut self, kind: T) {
+ if self.tok == kind {
+ self.next();
+ } else {
+ self.expected(kind.spelling());
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn is_contextual(&self, name: u32) -> bool {
+ self.tok == T::Name && self.tok_name == name && !self.tok_escaped
+ }
+
+ #[inline(always)]
+ pub(crate) fn eat_contextual(&mut self, name: u32) -> bool {
+ if self.is_contextual(name) {
+ self.next();
+ true
+ } else {
+ false
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn can_insert_semicolon(&self) -> bool {
+ self.tok == T::Eof || self.tok == T::RBrace || self.nl_before
+ }
+
+ #[inline(always)]
+ pub(crate) fn semicolon(&mut self) {
+ if !self.eat(T::Semi) && !self.can_insert_semicolon() {
+ self.expected("';'");
+ }
+ }
+
+ /// Runs `look` on the token stream and puts it back. An error it runs into comes up again if the parser gets there.
+ pub(crate) fn look_ahead<R>(&mut self, look: impl FnOnce(&mut Self) -> R) -> R {
+ let saved = (
+ self.pos,
+ self.tok,
+ self.tok_start,
+ self.tok_end,
+ self.tok_name,
+ self.nl_before,
+ self.tok_escaped,
+ self.tok_legacy,
+ self.prev_end,
+ self.prev_start,
+ );
+ let had_error = self.err.is_some();
+ let result = look(self);
+ if !had_error {
+ self.err = None;
+ }
+ (
+ self.pos,
+ self.tok,
+ self.tok_start,
+ self.tok_end,
+ self.tok_name,
+ self.nl_before,
+ self.tok_escaped,
+ self.tok_legacy,
+ self.prev_end,
+ self.prev_start,
+ ) = saved;
+ result
+ }
+
+ /// The kind and name of the token after the current one, and whether a newline comes before it.
+ pub(crate) fn peek(&mut self) -> (T, u32, bool) {
+ self.look_ahead(|parser| {
+ parser.lex();
+ (parser.tok, parser.tok_name, parser.nl_before)
+ })
+ }
+
+ #[inline(always)]
+ pub(crate) fn finish_list(&mut self, mark: usize) -> u32 {
+ let start = self.ast.extra.len() as u32;
+ let count = self.scratch.len() - mark;
+ self.ast.extra.push(count as u32);
+ self.ast.extra.extend_from_slice(&self.scratch[mark..]);
+ self.scratch.truncate(mark);
+ start
+ }
+
+ #[inline(always)]
+ pub fn list(&self, start: u32) -> &[u32] {
+ let count = self.ast.extra[start as usize] as usize;
+ &self.ast.extra[start as usize + 1..start as usize + 1 + count]
+ }
+
+ /// Leaves a mark in the rows, for a sweep over them.
+ #[inline(always)]
+ pub(crate) fn mark(&mut self, mark: u8, a: u32) {
+ self.mark_at(mark, a, self.tok_start);
+ }
+
+ /// Leaves a mark in the rows. What it makes of a reference goes by `position` from then on, which is where whatever the
+ /// reference is for is in the source.
+ #[inline(always)]
+ pub(crate) fn mark_at(&mut self, mark: u8, a: u32, position: u32) {
+ if !self.marks {
+ return;
+ }
+ if (tag::MARK_CALLEE..=tag::MARK_KEY).contains(&mark) {
+ let mut node = self.ast.tag.len() - 1;
+ while self.ast.tag[node] == tag::PAREN {
+ node = self.ast.a[node] as usize;
+ }
+ // NB: What `delete` of an optional chain is about is the end of the chain.
+ if mark == tag::MARK_DELETE && self.ast.tag[node] == tag::CHAIN {
+ node = self.ast.a[node] as usize;
+ self.ast.tag[node] = match self.ast.tag[node] {
+ tag::MEMBER | tag::OPT_MEMBER => tag::MEMBER_DELETE,
+ tag::INDEX | tag::OPT_INDEX => tag::INDEX_DELETE,
+ other => other,
+ };
+ return;
+ }
+ // NB: What gets called on what comes from the end of the chain too, through the parentheses around it.
+ if mark == tag::MARK_CALLEE && self.ast.tag[node] == tag::CHAIN {
+ node = self.ast.a[node] as usize;
+ self.ast.tag[node] = match self.ast.tag[node] {
+ tag::MEMBER | tag::OPT_MEMBER => tag::MEMBER_CALLEE,
+ tag::INDEX | tag::OPT_INDEX => tag::INDEX_CALLEE,
+ tag::PRIVATE_MEMBER | tag::OPT_PRIVATE_MEMBER => tag::PRIVATE_MEMBER_CALLEE,
+ tag::SUPER_MEMBER => tag::SUPER_MEMBER_CALLEE,
+ tag::SUPER_INDEX => tag::SUPER_INDEX_CALLEE,
+ other => other,
+ };
+ return;
+ }
+ let offset = mark - tag::MARK_CALLEE;
+ let marked = match self.ast.tag[node] {
+ tag::IDENT => tag::IDENT_MARKED + offset,
+ tag::MEMBER if mark != tag::MARK_KEY && mark != tag::MARK_DECLARATION && mark != tag::MARK_TYPEOF => {
+ tag::MEMBER_MARKED + offset
+ }
+ tag::INDEX if mark != tag::MARK_KEY && mark != tag::MARK_DECLARATION && mark != tag::MARK_TYPEOF => {
+ tag::INDEX_MARKED + offset
+ }
+ tag::SUPER if mark == tag::MARK_CALLEE => tag::SUPER_CALLEE,
+ tag::SUPER_MEMBER
+ if mark != tag::MARK_KEY && mark != tag::MARK_DECLARATION && mark != tag::MARK_TYPEOF =>
+ {
+ tag::SUPER_MEMBER_MARKED + offset
+ }
+ tag::SUPER_INDEX
+ if mark != tag::MARK_KEY && mark != tag::MARK_DECLARATION && mark != tag::MARK_TYPEOF =>
+ {
+ tag::SUPER_INDEX_MARKED + offset
+ }
+ tag::PRIVATE_MEMBER
+ if mark != tag::MARK_KEY && mark != tag::MARK_DECLARATION && mark != tag::MARK_TYPEOF =>
+ {
+ tag::PRIVATE_MEMBER_MARKED + offset
+ }
+ tag::OPT_MEMBER if mark == tag::MARK_CALLEE => tag::OPT_MEMBER_CALLEE,
+ tag::OPT_INDEX if mark == tag::MARK_CALLEE => tag::OPT_INDEX_CALLEE,
+ tag::OPT_PRIVATE_MEMBER if mark == tag::MARK_CALLEE => tag::PRIVATE_MEMBER_CALLEE,
+ tag::STR if mark == tag::MARK_KEY => tag::STR_KEY,
+ tag::NUM if mark == tag::MARK_KEY => tag::NUM_KEY,
+ _ => 0,
+ };
+ if marked != 0 {
+ self.ast.tag[node] = marked;
+ if mark == tag::MARK_DECLARATION {
+ self.ast.b[node] = a;
+ } else if mark == tag::MARK_TYPEOF || (mark == tag::MARK_CALLEE && marked == tag::IDENT_CALLEE) {
+ // NB: A name is where it is until it takes more than reading it.
+ self.ast.b[node] = position;
+ } else if mark != tag::MARK_KEY {
+ self.ast.pos[node] = position;
+ }
+ return;
+ }
+ }
+ self.ast.push(mark, self.prev_start, a, 0);
+ }
+
+ /// Leaves a mark at the start of a construct that does not go through the rows in order, for `end_subtree()`.
+ #[inline(always)]
+ pub(crate) fn begin_subtree(&mut self) -> u32 {
+ if !self.marks {
+ return NONE;
+ }
+ self.ast.push(tag::MARK_SUBTREE, self.tok_start, 0, 0)
+ }
+
+ /// A list starts to have spread elements in it, after `count` others, in something that is at `position`.
+ #[inline(always)]
+ pub(crate) fn mark_spread_start(&mut self, count: usize, position: u32) {
+ if self.marks {
+ self.ast.push(tag::MARK_SPREAD_START, position, count as u32, 0);
+ }
+ }
+
+ /// The construct that `begin_subtree()` left `mark` for ended with the row `root`.
+ #[inline(always)]
+ pub(crate) fn end_subtree(&mut self, mark: u32, root: u32) -> u32 {
+ if mark != NONE {
+ self.ast.a[mark as usize] = root;
+ }
+ root
+ }
+
+ /// Whether the row is that of a plain identifier, marked or not.
+ #[inline(always)]
+ pub(crate) fn is_identifier_row(&self, node: u32) -> bool {
+ let row_tag = self.ast.tag[node as usize];
+ row_tag == tag::IDENT || (tag::IDENT_MARKED..tag::MEMBER_MARKED).contains(&row_tag)
+ }
+
+ // === Scopes ===
+
+ #[inline(always)]
+ fn name_state(&mut self, name: u32) -> &mut NameState {
+ if name as usize >= self.names.len() {
+ self.grow_names(name);
+ }
+ // SAFETY: The table covers the name now.
+ unsafe { self.names.get_unchecked_mut(name as usize) }
+ }
+
+ #[cold]
+ #[inline(never)]
+ fn grow_names(&mut self, name: u32) {
+ let new_len = ((name as usize + 1) * 2).next_power_of_two();
+ self.names.resize(
+ new_len,
+ NameState {
+ use_head: NONE,
+ use_scope: NONE,
+ decl_head: NONE,
+ stamp: 0,
+ },
+ );
+ }
+
+ #[inline(always)]
+ pub(crate) fn note_use(&mut self, name: u32) {
+ if !self.tracks_scopes {
+ return;
+ }
+ let scope = self.cur_scope;
+ let func = self.cur_func;
+ let next = self.uses.len() as u32;
+ let state = self.name_state(name);
+ if state.use_scope == scope {
+ return;
+ }
+ let prev = state.use_head;
+ state.use_head = next;
+ state.use_scope = scope;
+ self.uses.push(UseRow {
+ name,
+ scope,
+ func,
+ prev,
+ });
+ }
+
+ #[inline(always)]
+ pub(crate) fn open_scope(&mut self, flags: u16) {
+ self.open_scope_with(flags, self.cur_func);
+ }
+
+ #[inline(always)]
+ pub(crate) fn open_scope_with(&mut self, flags: u16, func: u32) {
+ let id = self.next_scope;
+ self.next_scope += 1;
+ let index = self.scopes.len() as u32;
+ let var_scope = if flags & scope_flag::VAR_SCOPE != 0 {
+ index
+ } else {
+ self.scopes.last().map_or(0, |scope| scope.var_scope)
+ };
+ self.scopes.push(Scope {
+ id,
+ flags,
+ func,
+ start: self.tok_start,
+ decl_head: NONE,
+ has_eval: false,
+ eval_in_function: false,
+ eval_here: false,
+ var_scope,
+ arguments_access: false,
+ nested_arguments_access: false,
+ use_mark: self.uses.len() as u32,
+ hoist_mark: self.hoists.len() as u32,
+ });
+ self.cur_scope = id;
+ self.cur_func = func;
+ }
+
+ /// Records uses of a name in nested functions that do not resolve here, for a name that matters here anyway, since a
+ /// reparse would not see them otherwise.
+ fn record_uses_as_captures(&mut self, name: u32, head: u32, scope_id: u32, func: u32) {
+ let mut use_row = head;
+ while use_row != NONE {
+ let row = self.uses[use_row as usize];
+ if row.scope < scope_id {
+ break;
+ }
+ let use_func = row.func & !USE_IN_WITH;
+ if use_func != func {
+ let index_row = self.function_rows[use_func as usize];
+ if index_row != NONE {
+ self.index
+ .pending_captures
+ .push((index_row, name | (row.func & USE_IN_WITH)));
+ }
+ }
+ use_row = row.prev;
+ }
+ }
+
+ /// Annex B.3.3, for the hoists that reached the innermost scope, which is about to close.
+ fn process_hoists(&mut self, scope: Scope, top: usize) {
+ if self.hoists.len() <= scope.hoist_mark as usize {
+ return;
+ }
+ let mut kept = scope.hoist_mark as usize;
+ let is_var_scope = scope.flags & scope_flag::VAR_SCOPE != 0;
+ for i in scope.hoist_mark as usize..self.hoists.len() {
+ let hoist = self.hoists[i];
+ let row = self.find_declaration(hoist.name, scope.id);
+ let flags = if row == NONE { 0 } else { self.decls[row as usize].flags };
+ let is_own = hoist.own_scope == scope.id;
+ if !is_var_scope && row != NONE && flags & (decl::SIMPLE_CATCH | decl::CATCH_PATTERN) != 0 {
+ // The name now also means the function, so it has to stay reachable by name.
+ self.decls[row as usize].flags |= decl::HOISTABLE;
+ }
+ let lexical = flags & decl::LEXICAL != 0 && flags & decl::SIMPLE_CATCH == 0;
+ if lexical && self.decls[row as usize].summary_slot & SUMMARY_SLOT_INNER != 0 {
+ // NB: This binding may come after the function, which has to see it to know that it does not hoist.
+ self.decls[row as usize].summary_slot |= SUMMARY_SLOT_EARLY;
+ }
+ if lexical || flags & decl::CATCH_PATTERN != 0 || (!is_own && flags & decl::HOISTABLE != 0) {
+ continue;
+ }
+ if !is_var_scope {
+ self.hoists[kept] = hoist;
+ kept += 1;
+ continue;
+ }
+ // That a hoist got here at all keeps the name out of registers, whether or not it makes a binding.
+ let mut is_parameter = flags & decl::PARAMETER != 0;
+ if scope.flags & scope_flag::BODY_OF_PARAMETERS != 0 {
+ let outer = self.find_declaration(hoist.name, self.scopes[top - 1].id);
+ if outer != NONE && self.decls[outer as usize].flags & decl::PARAMETER != 0 {
+ is_parameter = true;
+ self.decls[outer as usize].flags |= decl::ANNEX_B;
+ }
+ }
+ if row == NONE {
+ self.add_declaration(hoist.name, top, decl::ANNEX_B);
+ if self.records_summaries {
+ let d = self.decls.len() - 1;
+ self.decls[d].summary_slot = SUMMARY_SLOT_EARLY;
+ }
+ } else {
+ self.decls[row as usize].flags |= decl::ANNEX_B;
+ }
+ let row = self.find_declaration(hoist.name, scope.id);
+ if is_parameter {
+ continue;
+ }
+ let reads_arguments = hoist.name == N_ARGUMENTS
+ && (scope.arguments_access
+ || (scope.flags & scope_flag::FUNCTION != 0
+ && scope.flags & scope_flag::ARROW == 0
+ && scope.eval_in_function));
+ if !reads_arguments {
+ self.decls[row as usize].flags |= decl::ANNEX_B_NAME;
+ }
+ let binding = if hoist.declaration == NONE {
+ NONE
+ } else {
+ self.decls[hoist.declaration as usize].out_binding
+ };
+ if binding != NONE {
+ self.ast.binding_flags[binding as usize] |= decl::HOISTED;
+ }
+ }
+ self.hoists.truncate(kept);
+ }
+
+ /// Resolves the bindings of the innermost scope against the uses in its subtree, and returns its row in the tree.
+ pub(crate) fn close_scope(&mut self) -> u32 {
+ if !self.tracks_scopes {
+ self.scopes.pop();
+ if let Some(parent) = self.scopes.last() {
+ self.cur_scope = parent.id;
+ self.cur_func = parent.func;
+ }
+ return NONE;
+ }
+ let top = self.scopes.len() - 1;
+ let current = self.scopes[top];
+ self.process_hoists(current, top);
+ let scope = self.scopes.pop().unwrap();
+ let mut row = NONE;
+ let keep = self.retain;
+ if keep && (scope.decl_head != NONE || scope.eval_in_function || scope.has_eval) {
+ row = self.ast.scope_flags.len() as u32;
+ self.ast.scope_first_binding.push(self.ast.binding_name.len() as u32);
+ let mut flags = scope.flags as u32;
+ if scope.eval_in_function {
+ flags |= SCOPE_ROW_EVAL_IN_FUNCTION;
+ }
+ if scope.has_eval {
+ flags |= SCOPE_ROW_POISONED;
+ }
+ self.ast.scope_flags.push(flags);
+ }
+ let parent_id = self.scopes.last().map_or(NONE, |parent| parent.id);
+ let mut d = scope.decl_head;
+ while d != NONE {
+ // SAFETY: Declaration links stay within the table.
+ let declaration = unsafe { *self.decls.get_unchecked(d as usize) };
+ let name = declaration.name;
+ let mut flags = declaration.flags;
+ let state = self.names[name as usize];
+ // A function expression's own name resolves through the environment, so its uses stay free.
+ let name_only = flags & !(decl::FUNCTION_NAME) == 0;
+ if name_only {
+ self.record_uses_as_captures(name, state.use_head, scope.id, scope.func);
+ }
+ // A `var` only passes through the scopes between it and its function, which is where it binds.
+ let passing_through = scope.flags & scope_flag::VAR_SCOPE == 0
+ && flags & (decl::LEXICAL | decl::FUNCTION | decl::PARAMETER | decl::CLASS_NAME) == 0;
+ if !name_only && !passing_through {
+ let mut captured = scope.has_eval;
+ let mut used_in_with = false;
+ let mut head = state.use_head;
+ while head != NONE {
+ // SAFETY: Use links stay within the table.
+ let row = unsafe { self.uses.get_unchecked_mut(head as usize) };
+ if row.scope < scope.id {
+ break;
+ }
+ captured |= row.func != scope.func;
+ used_in_with |= row.func & USE_IN_WITH != 0;
+ let func = row.func & !USE_IN_WITH;
+ let in_with = row.func & USE_IN_WITH;
+ row.name = USE_DEAD;
+ if func != scope.func {
+ // SAFETY: Every function id has a row here.
+ let index_row = unsafe { *self.function_rows.get_unchecked(func as usize) };
+ if index_row != NONE {
+ self.index.pending_captures.push((index_row, name | in_with));
+ }
+ }
+ head = row.prev;
+ }
+ let new_scope = if head == NONE {
+ NONE
+ } else {
+ self.uses[head as usize].scope
+ };
+ if scope.flags & scope_flag::BODY_OF_PARAMETERS != 0
+ && new_scope != NONE
+ && new_scope >= parent_id
+ && flags & decl::VAR != 0
+ {
+ flags |= decl::REFERENCED_IN_PARAMETERS;
+ self.record_uses_as_captures(name, head, parent_id, scope.func);
+ }
+ let state = &mut self.names[name as usize];
+ state.use_head = head;
+ state.use_scope = new_scope;
+ if captured {
+ flags |= decl::CAPTURED;
+ }
+ if used_in_with {
+ flags |= decl::USED_IN_WITH;
+ }
+ if self.records_summaries {
+ let summary_slot = self.decls[d as usize].summary_slot;
+ self.note_closed_binding(summary_slot, name, captured || used_in_with, scope);
+ }
+ }
+ self.names[name as usize].decl_head = declaration.next_same_name;
+ if keep {
+ // A function directly in a switch stays out of this: it gets its binding through the case it is in.
+ if scope.flags & scope_flag::SWITCH == 0 {
+ self.decls[d as usize].out_binding = self.ast.binding_name.len() as u32;
+ }
+ self.ast.binding_name.push(name);
+ self.ast.binding_flags.push(flags);
+ }
+ d = declaration.next_in_scope;
+ }
+ if scope.flags & scope_flag::WITH != 0 {
+ for row in &mut self.uses[scope.use_mark as usize..] {
+ if row.name != USE_DEAD {
+ row.func |= USE_IN_WITH;
+ }
+ }
+ }
+ if let Some(parent) = self.scopes.last_mut() {
+ parent.has_eval |= scope.has_eval;
+ if scope.flags & scope_flag::FUNCTION == 0 {
+ parent.eval_in_function |= scope.eval_in_function;
+ parent.eval_here |= scope.eval_here;
+ parent.arguments_access |= scope.arguments_access;
+ parent.nested_arguments_access |= scope.arguments_access;
+ } else if scope.flags & scope_flag::ARROW != 0 && (scope.arguments_access || scope.eval_here) {
+ // An arrow function has no arguments object of its own, so the function around it provides it, which a
+ // direct eval in the arrow function can reach as well.
+ parent.arguments_access = true;
+ parent.nested_arguments_access = true;
+ }
+ self.cur_scope = parent.id;
+ self.cur_func = parent.func;
+ }
+ row
+ }
+
+ /// Whether the name is declared so far in the current function, as far as code that reads `arguments` can tell.
+ pub(crate) fn is_declared_in_current_function(&self, name: u32) -> bool {
+ let mut d = self.names.get(name as usize).map_or(NONE, |state| state.decl_head);
+ let mut function_scope = 0;
+ for scope in self.scopes.iter().rev() {
+ if scope.flags & (scope_flag::FUNCTION | scope_flag::STATIC_BLOCK) != 0 {
+ function_scope = scope.id;
+ break;
+ }
+ }
+ while d != NONE {
+ let row = &self.decls[d as usize];
+ if row.scope < function_scope {
+ break;
+ }
+ if row.flags & (decl::LEXICAL | decl::VAR | decl::PARAMETER | decl::HOISTABLE) != 0 {
+ return true;
+ }
+ d = row.next_same_name;
+ }
+ false
+ }
+
+ /// Pops the uses of a name that a function binds implicitly, and returns whether there were any, and whether one
+ /// of them came from a nested function.
+ pub(crate) fn resolve_implicit(&mut self, name: u32, scope_id: u32, func: u32) -> (bool, bool) {
+ let mut used = false;
+ let mut captured = false;
+ let mut head = self.names[name as usize].use_head;
+ while head != NONE {
+ let row = &mut self.uses[head as usize];
+ if row.scope < scope_id {
+ break;
+ }
+ used = true;
+ captured |= row.func != func;
+ let use_func = row.func & !USE_IN_WITH;
+ let in_with = row.func & USE_IN_WITH;
+ row.name = USE_DEAD;
+ head = row.prev;
+ if use_func != func {
+ let index_row = self.function_rows[use_func as usize];
+ if index_row != NONE {
+ self.index.pending_captures.push((index_row, name | in_with));
+ }
+ }
+ }
+ if used {
+ let new_scope = if head == NONE {
+ NONE
+ } else {
+ self.uses[head as usize].scope
+ };
+ let state = &mut self.names[name as usize];
+ state.use_head = head;
+ state.use_scope = new_scope;
+ }
+ (used, captured)
+ }
+
+ /// Whether a name has a declaration in the scope with the given id, and which.
+ #[inline(always)]
+ fn find_declaration(&self, name: u32, scope_id: u32) -> u32 {
+ let mut d = self.names[name as usize].decl_head;
+ while d != NONE {
+ let row = &self.decls[d as usize];
+ if row.scope <= scope_id {
+ return if row.scope == scope_id { d } else { NONE };
+ }
+ d = row.next_same_name;
+ }
+ NONE
+ }
+
+ fn add_declaration(&mut self, name: u32, scope_index: usize, flags: u32) {
+ if self.records_summaries {
+ let word = name as usize / 64;
+ if word >= self.index.declared_names.len() {
+ self.index.declared_names.resize(word + 1, 0);
+ }
+ self.index.declared_names[word] |= 1 << (name % 64);
+ }
+ let scope_id = self.scopes[scope_index].id;
+ let d = self.decls.len() as u32;
+ // Keep the name's chain ordered from the innermost scope out.
+ let mut previous = NONE;
+ let mut next = self.names[name as usize].decl_head;
+ while next != NONE && self.decls[next as usize].scope > scope_id {
+ previous = next;
+ next = self.decls[next as usize].next_same_name;
+ }
+ self.decls.push(DeclRow {
+ name,
+ scope: scope_id,
+ flags,
+ next_same_name: next,
+ next_in_scope: self.scopes[scope_index].decl_head,
+ last_var_scope: 0,
+ out_binding: NONE,
+ summary_slot: NONE,
+ });
+ self.scopes[scope_index].decl_head = d;
+ if previous == NONE {
+ self.names[name as usize].decl_head = d;
+ } else {
+ self.decls[previous as usize].next_same_name = d;
+ }
+ }
+
+ fn treats_functions_as_var(&self, flags: u16) -> bool {
+ flags & (scope_flag::FUNCTION | scope_flag::BODY_OF_PARAMETERS | scope_flag::STATIC_BLOCK) != 0
+ || (!self.module && flags & scope_flag::TOP != 0)
+ }
+
+ pub(crate) fn treat_functions_as_var(&self) -> bool {
+ self.treats_functions_as_var(self.scopes.last().unwrap().flags)
+ }
+
+ /// Whether a `var` of the name was written in the scope at `top` or a scope nested in it.
+ fn contains_var_named(&self, name: u32, top: usize) -> bool {
+ let var_scope = &self.scopes[self.scopes[top].var_scope as usize];
+ let row = self.find_declaration(name, var_scope.id);
+ row != NONE && self.decls[row as usize].last_var_scope >= self.scopes[top].id
+ }
+
+ /// The body of a catch clause may not lexically redeclare what the clause's parameter binds.
+ fn conflicts_with_catch_parameter(&self, name: u32, flags: u16, top: usize) -> bool {
+ if flags & scope_flag::CATCH_BODY == 0 {
+ return false;
+ }
+ let parameter = self.find_declaration(name, self.scopes[top - 1].id);
+ parameter != NONE && self.decls[parameter as usize].flags & decl::LEXICAL != 0
+ }
+
+ fn fail_redeclaration(&mut self, name: u32, pos: u32) {
+ let name = String::from_utf8_lossy(self.interner.text(name)).into_owned();
+ self.fail_with(pos, format!("Identifier '{name}' already declared"));
+ }
+
+ pub(crate) fn declare(&mut self, name: u32, bind: Bind, pos: u32) {
+ if !self.tracks_scopes {
+ return;
+ }
+ self.name_state(name).stamp |= DECLARED_BIT;
+ let top = self.scopes.len() - 1;
+ let flags = self.scopes[top].flags;
+ let scope_id = self.scopes[top].id;
+ let existing = self.find_declaration(name, scope_id);
+ let existing_flags = if existing == NONE {
+ 0
+ } else {
+ self.decls[existing as usize].flags
+ };
+ let new_flags = match bind {
+ Bind::None => return,
+ Bind::Lexical | Bind::Let | Bind::Const => {
+ let mut redeclared =
+ existing_flags & (decl::LEXICAL | decl::FUNCTION | decl::VAR | decl::PARAMETER) != 0;
+ if flags & scope_flag::BODY_OF_PARAMETERS != 0 {
+ let parameters = self.find_declaration(name, self.scopes[top - 1].id);
+ redeclared |= parameters != NONE && self.decls[parameters as usize].flags & decl::PARAMETER != 0;
+ }
+ redeclared |= self.conflicts_with_catch_parameter(name, flags, top);
+ redeclared |= self.contains_var_named(name, top);
+ if redeclared {
+ self.fail_redeclaration(name, pos);
+ return;
+ }
+ decl::LEXICAL
+ | match bind {
+ Bind::Let => decl::DECLARED_LET,
+ Bind::Const => decl::DECLARED_CONST,
+ _ => 0,
+ }
+ }
+ Bind::SimpleCatch => decl::LEXICAL | decl::SIMPLE_CATCH,
+ Bind::CatchPattern => {
+ if existing_flags & decl::LEXICAL != 0 {
+ self.fail_redeclaration(name, pos);
+ return;
+ }
+ decl::LEXICAL | decl::CATCH_PATTERN
+ }
+ Bind::Function => {
+ let mask = if self.treats_functions_as_var(flags) {
+ decl::LEXICAL
+ } else {
+ decl::LEXICAL | decl::VAR
+ };
+ let var_inside = !self.treats_functions_as_var(flags) && self.contains_var_named(name, top);
+ if existing_flags & mask != 0 || var_inside || self.conflicts_with_catch_parameter(name, flags, top) {
+ self.fail_redeclaration(name, pos);
+ return;
+ }
+ if self.treats_functions_as_var(flags) {
+ decl::FUNCTION | decl::VAR
+ } else {
+ decl::FUNCTION | decl::HOISTABLE
+ }
+ }
+ Bind::Parameter => {
+ if existing_flags & decl::PARAMETER != 0 && self.duplicate_parameter == NONE {
+ self.duplicate_parameter = pos;
+ }
+ decl::PARAMETER
+ }
+ Bind::Var => {
+ if self.with_depth != 0 {
+ // The declaration's initializer may assign to a property of the object instead.
+ self.note_use(name);
+ }
+ let var_index = self.scopes[top].var_scope as usize;
+ let var_scope = self.scopes[var_index];
+ // Only declarations of this very name can be in the way, and those are linked from the name.
+ let mut d = self.names[name as usize].decl_head;
+ let mut row = NONE;
+ while d != NONE {
+ let declaration = self.decls[d as usize];
+ if declaration.scope < var_scope.id {
+ break;
+ }
+ if declaration.scope == var_scope.id {
+ row = d;
+ }
+ let lexical_conflict =
+ declaration.flags & decl::LEXICAL != 0 && declaration.flags & decl::SIMPLE_CATCH == 0;
+ let is_block_function = declaration.flags & decl::FUNCTION != 0
+ && (declaration.scope != var_scope.id || !self.treats_functions_as_var(var_scope.flags));
+ if lexical_conflict || is_block_function {
+ self.fail_redeclaration(name, pos);
+ return;
+ }
+ if declaration.flags & decl::SIMPLE_CATCH != 0 {
+ self.decls[d as usize].flags |= decl::VAR | decl::DECLARED_VAR;
+ }
+ d = declaration.next_same_name;
+ }
+ if row == NONE {
+ self.add_declaration(name, var_index, decl::VAR | decl::DECLARED_VAR);
+ self.note_new_binding(name, var_index, bind);
+ row = self.decls.len() as u32 - 1;
+ } else {
+ self.note_redeclared_function_name(row, name, var_index, bind);
+ self.decls[row as usize].flags |= decl::VAR | decl::DECLARED_VAR;
+ }
+ self.decls[row as usize].last_var_scope = scope_id;
+ return;
+ }
+ };
+ if existing == NONE {
+ self.add_declaration(name, top, new_flags);
+ self.note_new_binding(name, top, bind);
+ } else {
+ self.note_redeclared_function_name(existing, name, top, bind);
+ self.decls[existing as usize].flags |= new_flags;
+ }
+ }
+
+ /// Annex B.3.3: a sloppy function in a block may also make a `var` in the enclosing function. That is only known
+ /// once the scopes in between have closed, since a later `let` can rule it out.
+ pub(crate) fn queue_annex_b_hoist(&mut self, name: u32) {
+ let scope = self.scopes.last().unwrap();
+ if scope.flags & scope_flag::VAR_SCOPE == 0 {
+ let own_scope = scope.id;
+ let declaration = self.find_declaration(name, own_scope);
+ self.hoists.push(Hoist {
+ name,
+ declaration,
+ own_scope,
+ });
+ }
+ }
+
+ pub(crate) fn declare_function_name(&mut self, name: u32) {
+ self.name_state(name).stamp |= DECLARED_BIT;
+ let top = self.scopes.len() - 1;
+ self.add_declaration(name, top, decl::FUNCTION_NAME);
+ }
+
+ /// The inner binding of a class's name, in the scope the class opened.
+ pub(crate) fn declare_class_name(&mut self, name: u32) {
+ self.name_state(name).stamp |= DECLARED_BIT;
+ let top = self.scopes.len() - 1;
+ self.add_declaration(name, top, decl::CLASS_NAME | decl::LEXICAL);
+ }
+
+ pub(crate) fn has_declaration_at_top_of_scope(&self, name: u32) -> bool {
+ (name as usize) < self.names.len() && self.find_declaration(name, self.cur_scope) != NONE
+ }
+
+ pub(crate) fn is_declared_at_top(&self, name: u32) -> bool {
+ let id = self.scopes[0].id;
+ (name as usize) < self.names.len() && self.find_declaration(name, id) != NONE
+ }
+
+ // === Functions ===
+
+ /// Where a function of the first parse starts and ends, its name and its flags.
+ pub(crate) fn function_row_summary(&self, row: u32) -> (u32, u32, u32, u32) {
+ let index = self.first_pass_index();
+ let row = row as usize;
+ (index.start[row], index.end[row], index.name[row], index.flags[row])
+ }
+
+ #[inline(always)]
+ pub(crate) fn open_index_row(&mut self, start: u32) -> u32 {
+ let index = &mut self.index;
+ let row = index.start.len() as u32;
+ index.start.push(start);
+ index.params_start.push(0);
+ index.end.push(0);
+ index.flags.push(0);
+ index.length.push(0);
+ index.parameter_count.push(0);
+ index.ctx.push(0);
+ index.name.push(NONE);
+ index.capture_start.push(0);
+ index.capture_count.push(0);
+ index.summary_start.push(0);
+ row
+ }
+
+ /// A new function id, for a function with a row in the index or for what only counts as one.
+ pub(crate) fn new_function_id(&mut self, row: u32) -> u32 {
+ let func = self.next_func;
+ self.next_func += 1;
+ self.function_rows.push(row);
+ self.summary_rows.push(row);
+ func
+ }
+
+ pub(crate) fn begin_function(&mut self, start: u32, new_ctx: u32, flags: u32) -> FunctionState {
+ let state = self.save_function_state(start, new_ctx, flags);
+ let func = self.new_function_id(state.row);
+ self.open_scope_with(scope_flag::FUNCTION, func);
+ state
+ }
+
+ fn save_function_state(&mut self, start: u32, new_ctx: u32, flags: u32) -> FunctionState {
+ // NB: A function that is parsed again already has its row, which is for the caller to find.
+ let row = if self.is_reparsing() {
+ NONE
+ } else {
+ let row = self.open_index_row(start);
+ self.index.ctx[row as usize] = new_ctx as u16;
+ row
+ };
+ let state = FunctionState {
+ marks: self.ast.marks(),
+ row,
+ ctx: self.ctx,
+ strict: self.strict,
+ labels_base: self.labels_base,
+ yield_pos: self.yield_pos,
+ await_pos: self.await_pos,
+ await_ident_pos: self.await_ident_pos,
+ cover_error: self.cover_error,
+ retain: self.retain,
+ duplicate_parameter: self.duplicate_parameter,
+ start,
+ flags,
+ has_body_scope: false,
+ body_start: 0,
+ first_body_row: 0,
+ uses_this: self.uses_this,
+ uses_this_from_environment: self.uses_this_from_environment,
+ might_need_arguments: self.might_need_arguments,
+ in_class_of_sloppy_function: self.in_class_of_sloppy_function,
+ is_arrow: self.in_arrow,
+ summary_ordinal: self.summary_ordinal,
+ };
+ self.summary_ordinal = 0;
+ self.uses_this = false;
+ self.uses_this_from_environment = false;
+ self.might_need_arguments = false;
+ self.in_arrow = flags & function_flag::ARROW != 0;
+ self.in_class_of_sloppy_function &= self.in_arrow;
+ self.ctx = new_ctx;
+ self.labels_base = self.labels.len() as u32;
+ self.yield_pos = 0;
+ self.await_pos = 0;
+ self.await_ident_pos = 0;
+ self.cover_error = NONE;
+ self.duplicate_parameter = NONE;
+ self.retain = self.mode == Mode::Full || core::mem::take(&mut self.retain_next_function);
+ state
+ }
+
+ /// Turns the cover scope that the parenthesized expression before `=>` opened into the scope of the arrow function.
+ pub(crate) fn begin_arrow_from_cover(
+ &mut self,
+ start: u32,
+ marks: AstMarks,
+ new_ctx: u32,
+ flags: u32,
+ ) -> FunctionState {
+ let mut state = self.save_function_state(start, new_ctx, flags);
+ let func = self.new_function_id(state.row);
+ state.marks = marks;
+ let outer = self.cur_func;
+ let index = self.scopes.len() as u32 - 1;
+ let scope = self.scopes.last_mut().unwrap();
+ scope.flags = scope_flag::FUNCTION | scope_flag::ARROW;
+ scope.func = func;
+ scope.var_scope = index;
+ let mark = scope.use_mark as usize;
+ self.cur_func = func;
+ // Uses in the parameters happen when the arrow function is called, not where it is written.
+ let mut parameters_use_this = false;
+ for row in &mut self.uses[mark..] {
+ if row.func == outer {
+ row.func = func;
+ }
+ parameters_use_this |= row.name == N_DOT_THIS || row.name == N_DOT_NEW_TARGET;
+ }
+ if parameters_use_this || self.scopes.last().unwrap().eval_here {
+ self.uses_this = true;
+ self.uses_this_from_environment = true;
+ }
+ state
+ }
+
+ pub(crate) fn open_function_body_scope(&mut self, state: &mut FunctionState) {
+ state.has_body_scope = true;
+ let eval_in_parameters = self.scopes.last().unwrap().has_eval;
+ self.open_scope(scope_flag::BODY_OF_PARAMETERS);
+ // Scope analysis treats the parameters and the body as one scope, so an eval in either reaches both.
+ self.scopes.last_mut().unwrap().has_eval = eval_in_parameters;
+ }
+
+ /// Closes the function: resolves its scopes, collapses its free names, fills in its index row unless it has one
+ /// from the first parse, and drops its tree unless it is retained. Returns the function's node.
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn end_function(
+ &mut self,
+ state: FunctionState,
+ end: u32,
+ parameter_count: u32,
+ length: u32,
+ params_start: u32,
+ parameters: u32,
+ body: u32,
+ name: u32,
+ is_expression_body: bool,
+ ) -> u32 {
+ let retained = self.retain;
+ let mut flags = state.flags;
+ let mut body_scope_row = NONE;
+ let mut name_is_alone_in_its_scopes = true;
+ if state.has_body_scope {
+ let body_scope = self.scopes.last().unwrap();
+ flags |= if body_scope.arguments_access {
+ function_flag::ARGUMENTS_ACCESS
+ } else {
+ 0
+ };
+ flags |= if body_scope.eval_here {
+ function_flag::DIRECT_EVAL
+ } else {
+ 0
+ };
+ if flags & function_flag::NAMED_EXPRESSION != 0 {
+ let current = *body_scope;
+ let top = self.scopes.len() - 1;
+ self.process_hoists(current, top);
+ name_is_alone_in_its_scopes = self.find_declaration(name, current.id) == NONE;
+ }
+ body_scope_row = self.close_scope();
+ }
+ let scope = *self.scopes.last().unwrap();
+ if scope.arguments_access {
+ flags |= function_flag::ARGUMENTS_ACCESS;
+ }
+ // Whether anything in the function could refer to its own name.
+ let name_used = self.names.get(name as usize).is_some_and(|name_state| {
+ name_state.use_head != NONE && self.uses[name_state.use_head as usize].scope >= scope.id
+ });
+ let name_declaration = if flags & function_flag::NAMED_EXPRESSION != 0 {
+ self.find_declaration(name, scope.id)
+ } else {
+ NONE
+ };
+ let scope_row = self.close_scope();
+ if self.strict {
+ flags |= function_flag::STRICT;
+ }
+ if scope.has_eval {
+ flags |= function_flag::CONTAINS_EVAL;
+ }
+ if scope.eval_here {
+ flags |= function_flag::DIRECT_EVAL;
+ }
+ if !name_used
+ && !scope.has_eval
+ && name_is_alone_in_its_scopes
+ && name_declaration != NONE
+ && self.decls[name_declaration as usize].flags & !decl::FUNCTION_NAME == 0
+ {
+ flags |= function_flag::NAME_UNUSED;
+ }
+ if state.flags & function_flag::ARROW == 0 {
+ let (used, captured) = self.resolve_implicit(N_DOT_THIS, scope.id, scope.func);
+ if used {
+ flags |= function_flag::USES_THIS;
+ }
+ if captured {
+ flags |= function_flag::CAPTURES_THIS;
+ }
+ let (used, captured) = self.resolve_implicit(N_ARGUMENTS, scope.id, scope.func);
+ if used {
+ flags |= function_flag::USES_ARGUMENTS;
+ }
+ if captured {
+ flags |= function_flag::CAPTURES_ARGUMENTS;
+ }
+ self.resolve_implicit(N_DOT_NEW_TARGET, scope.id, scope.func);
+ self.resolve_implicit(N_DOT_SUPER, scope.id, scope.func);
+ }
+ self.collapse_uses(scope.use_mark, scope.func);
+ let is_arrow = state.flags & function_flag::ARROW != 0;
+ if self.uses_this {
+ flags |= function_flag::SCOPE_USES_THIS;
+ }
+ if self.uses_this && !(is_arrow && is_expression_body) {
+ flags |= function_flag::INSIGHT_USES_THIS;
+ }
+ if self.uses_this_from_environment {
+ flags |= function_flag::INSIGHT_THIS_FROM_ENVIRONMENT | function_flag::SCOPE_THIS_FROM_ENVIRONMENT;
+ }
+ if self.might_need_arguments && !is_arrow {
+ flags |= function_flag::MIGHT_NEED_ARGUMENTS;
+ }
+ if self.might_need_arguments {
+ flags |= function_flag::MENTIONS_ARGUMENTS;
+ }
+ self.summary_ordinal = state.summary_ordinal;
+ if !self.is_reparsing() {
+ if self.tok_end as usize + super::SOURCE_PADDING > self.len as usize {
+ flags |= function_flag::REACHES_SOURCE_END;
+ }
+ let row = state.row as usize;
+ let index = &mut self.index;
+ index.params_start[row] = params_start;
+ index.end[row] = end;
+ index.flags[row] = flags;
+ index.length[row] = length;
+ index.parameter_count[row] = parameter_count;
+ index.name[row] = name;
+ }
+
+ self.ctx = state.ctx;
+ self.strict = state.strict;
+ self.labels_base = state.labels_base;
+ self.yield_pos = state.yield_pos;
+ self.await_pos = state.await_pos;
+ self.await_ident_pos = state.await_ident_pos;
+ self.cover_error = state.cover_error;
+ self.retain = state.retain;
+ self.duplicate_parameter = state.duplicate_parameter;
+ self.uses_this |= state.uses_this;
+ self.uses_this_from_environment |= state.uses_this_from_environment;
+ // An arrow function has no arguments object, so that what it mentions counts for the function around it.
+ self.might_need_arguments = state.might_need_arguments || (is_arrow && self.might_need_arguments);
+ self.in_class_of_sloppy_function = state.in_class_of_sloppy_function;
+ self.in_arrow = state.is_arrow;
+
+ if retained {
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.extend_from_slice(&[
+ parameters,
+ body,
+ name,
+ scope_row,
+ body_scope_row,
+ state.body_start,
+ is_expression_body as u32,
+ state.first_body_row,
+ ]);
+ self.ast.push(tag::FUNCTION, state.start, extra, state.row)
+ } else {
+ self.ast.truncate(&state.marks);
+ // Node indices get reused from here on.
+ if self.last_arrow >= state.marks.nodes {
+ self.last_arrow = 0;
+ }
+ self.ast.push(tag::FUNCTION, state.start, 0, state.row)
+ }
+ }
+
+ // === Reparsing ===
+
+ #[inline(always)]
+ pub(crate) fn is_reparsing(&self) -> bool {
+ !self.first_pass_index.is_null()
+ }
+
+ fn first_pass_index(&self) -> &'a FunctionIndex {
+ // SAFETY: A parser that reparses functions has an index, which for_reparsing() requires to stay valid.
+ unsafe { &*self.first_pass_index }
+ }
+
+ /// Reads from `source` from now on, where offset `offset` is at the first unit, and `length` is that of the whole
+ /// source.
+ ///
+ /// # Safety
+ /// What the lexer may read of the source, up to `length` and the padding after it if it gets that far, must stay
+ /// valid for as long as the parser reads it.
+ pub(crate) unsafe fn set_reparse_source(&mut self, source: *const U, offset: u32, length: u32) {
+ self.src = source.wrapping_sub(offset as usize);
+ self.len = length;
+ }
+
+ /// Gets ready for the next function, whether this one went well or not.
+ pub(crate) fn finish_reparse(&mut self) {
+ for row in &self.uses {
+ if row.name != USE_DEAD {
+ let state = &mut self.names[row.name as usize];
+ state.use_head = NONE;
+ state.use_scope = NONE;
+ }
+ }
+ self.uses.clear();
+ for row in &self.decls {
+ self.names[row.name as usize].decl_head = NONE;
+ }
+ self.decls.clear();
+ self.scopes.clear();
+ self.hoists.clear();
+ self.labels.clear();
+ self.labels_base = 0;
+ self.label_indices.clear();
+ self.scratch.clear();
+ self.class_marks.clear();
+ self.private_declared.clear();
+ self.private_used.clear();
+ self.names_used_in_with.clear();
+ self.function_rows.truncate(1);
+ self.summary_rows.truncate(1);
+ self.next_func = 1;
+ self.next_scope = 1;
+ self.cur_scope = 0;
+ self.cur_func = 0;
+ self.with_depth = 0;
+ self.recursion_depth = 0;
+ self.reparse_target = NONE;
+ self.err = None;
+ }
+
+ /// Parses one function again, on its own, from where the first parse found it. The functions nested in it get
+ /// skipped by what the first parse recorded about them, so that nothing is parsed further than one level down.
+ /// Returns the function's node, or the element of its class if the function is the code of a class.
+ pub(crate) fn reparse_function(&mut self, row: u32) -> u32 {
+ use function_flag::*;
+ let index = self.first_pass_index();
+ let row_index = row as usize;
+ let (start, params_start) = (index.start[row_index], index.params_start[row_index]);
+ let (flags, name) = (index.flags[row_index], index.name[row_index]);
+ self.reparse_target = params_start;
+ self.strict = flags & STRICT != 0;
+ self.ctx = index.ctx[row_index] as u32;
+ self.retain = flags & (FIELD_INITIALIZER | STATIC_BLOCK) != 0;
+ self.retain_next_function = !self.retain;
+ self.uses_this = false;
+ self.uses_this_from_environment = false;
+ self.might_need_arguments = false;
+ self.in_arrow = false;
+ self.cover_error = NONE;
+ self.potential_arrow_at = NONE;
+ self.last_arrow = 0;
+ if flags & DEFAULT_CONSTRUCTOR != 0 {
+ return self.default_constructor_class_node(row);
+ }
+ self.open_scope_with(0, 0);
+ // The class around the function, if any, already checked its private names.
+ self.class_marks.push((0, 0));
+ self.private_declared.push(std::collections::HashMap::new());
+ self.pos = params_start;
+ self.tok_end = params_start;
+ self.prev_end = params_start;
+ self.prev_start = params_start;
+ self.lex();
+ if flags & (FIELD_INITIALIZER | STATIC_BLOCK) != 0 {
+ self.class_start = start;
+ return self.reparse_class_element();
+ }
+ let new_ctx = self.ctx;
+ let own_flags = flags & (ARROW | ASYNC | GENERATOR | METHOD | NAMED_EXPRESSION);
+ let node = if flags & ARROW != 0 {
+ self.reparse_arrow_function(start, params_start, flags)
+ } else {
+ let mut state = self.begin_function(start, new_ctx, own_flags);
+ let own_name = (name != NONE).then_some((name, start));
+ if flags & NAMED_EXPRESSION != 0 {
+ self.declare_function_name(name);
+ }
+ if name == N_ARGUMENTS || name == N_EVAL {
+ self.might_need_arguments = true;
+ }
+ self.parse_function_tail(&mut state, own_name, flags & METHOD != 0)
+ };
+ self.ast.b[node as usize] = row;
+ node
+ }
+
+ /// The row of a function about to be parsed, from where it starts over, if that can be skipped.
+ #[inline(always)]
+ pub(crate) fn skippable_row(&self, params_start: u32) -> Option<u32> {
+ if !self.is_reparsing() || params_start == self.reparse_target {
+ return None;
+ }
+ self.first_pass_row_at(params_start)
+ }
+
+ /// The row of an arrow function, whose parameters can be mistaken for code.
+ #[inline(always)]
+ pub(crate) fn skippable_arrow_row(&self, params_start: u32) -> Option<u32> {
+ if !self.is_reparsing() {
+ return None;
+ }
+ self.skippable_row(params_start)
+ .filter(|&row| self.first_pass_index().flags[row as usize] & function_flag::ARROW != 0)
+ }
+
+ pub(crate) fn first_pass_row_at(&self, params_start: u32) -> Option<u32> {
+ self.first_pass_index()
+ .row_at_params_start(params_start, &self.row_cursor)
+ }
+
+ /// Goes past a nested function as if it had been parsed, from where it starts over: what it uses of the scopes
+ /// around it comes from the first parse. Returns the function's node.
+ pub(crate) fn skip_function(&mut self, mut state: FunctionState, row: u32) -> u32 {
+ use function_flag::*;
+ let index = self.first_pass_index();
+ let index_row = row as usize;
+ let flags = index.flags[index_row];
+ let captures = index.capture_start[index_row] as usize;
+ if !self.tracks_scopes {
+ return self.skip_function_without_scopes(state, row);
+ }
+ let capture_count = index.capture_count[index_row] as usize;
+ for i in captures..captures + capture_count {
+ let capture = index.capture_names[i];
+ let name = capture & !USE_IN_WITH;
+ self.note_use(name);
+ if capture & USE_IN_WITH != 0 {
+ let head = self.names[name as usize].use_head;
+ self.uses[head as usize].func |= USE_IN_WITH;
+ }
+ }
+ self.uses_this |= flags & SCOPE_USES_THIS != 0;
+ self.uses_this_from_environment |= flags & SCOPE_THIS_FROM_ENVIRONMENT != 0;
+ self.might_need_arguments |= flags & MENTIONS_ARGUMENTS != 0;
+ let scope = self.scopes.last_mut().unwrap();
+ scope.has_eval |= flags & CONTAINS_EVAL != 0;
+ scope.eval_here |= flags & DIRECT_EVAL != 0;
+ scope.arguments_access |= flags & ARGUMENTS_ACCESS != 0;
+ state.row = row;
+ self.retain = false;
+ let end = index.end[index_row];
+ self.tok_start = end - 1;
+ self.tok_end = end;
+ self.pos = end;
+ self.next();
+ self.end_function(state, end, 0, 0, 0, 0, 0, index.name[index_row], false)
+ }
+
+ /// Goes past a nested function when nothing keeps track of scopes, so that only the state of the parser matters.
+ fn skip_function_without_scopes(&mut self, state: FunctionState, row: u32) -> u32 {
+ let end = self.first_pass_index().end[row as usize];
+ self.scopes.pop();
+ if let Some(parent) = self.scopes.last() {
+ self.cur_scope = parent.id;
+ self.cur_func = parent.func;
+ }
+ self.retain = false;
+ self.tok_start = end - 1;
+ self.tok_end = end;
+ self.pos = end;
+ self.next();
+ self.ctx = state.ctx;
+ self.strict = state.strict;
+ self.labels_base = state.labels_base;
+ self.yield_pos = state.yield_pos;
+ self.await_pos = state.await_pos;
+ self.await_ident_pos = state.await_ident_pos;
+ self.cover_error = state.cover_error;
+ self.retain = state.retain;
+ self.duplicate_parameter = state.duplicate_parameter;
+ self.uses_this = state.uses_this;
+ self.uses_this_from_environment = state.uses_this_from_environment;
+ self.might_need_arguments = state.might_need_arguments;
+ self.in_arrow = state.is_arrow;
+ self.ast.push(tag::FUNCTION, state.start, 0, row)
+ }
+
+ /// Code of a class that runs as a function captures what the functions in it capture. Their uses stay, since each
+ /// of those functions has to capture the name as well.
+ pub(crate) fn note_uses_of_nested_functions(&mut self, mark: u32, func: u32) {
+ self.stamp += 1;
+ let stamp = self.stamp;
+ let mut nested_names = std::mem::take(&mut self.free_names_scratch);
+ nested_names.clear();
+ for row in &self.uses[mark as usize..] {
+ if row.name == USE_DEAD || row.func & !USE_IN_WITH == func {
+ continue;
+ }
+ let state = &mut self.names[row.name as usize];
+ if state.stamp & !DECLARED_BIT != stamp {
+ state.stamp = stamp | (state.stamp & DECLARED_BIT);
+ nested_names.push(row.name);
+ }
+ if row.func & USE_IN_WITH != 0 {
+ self.names_used_in_with.push(row.name);
+ }
+ }
+ let scope = self.cur_scope;
+ for &name in &nested_names {
+ let next = self.uses.len() as u32;
+ let state = &mut self.names[name as usize];
+ let prev = state.use_head;
+ state.use_head = next;
+ state.use_scope = scope;
+ self.uses.push(UseRow {
+ name,
+ scope,
+ func,
+ prev,
+ });
+ }
+ self.free_names_scratch = nested_names;
+ while let Some(name) = self.names_used_in_with.pop() {
+ let head = self.names[name as usize].use_head;
+ self.uses[head as usize].func |= USE_IN_WITH;
+ }
+ }
+
+ /// Replaces every use above `mark` by one row per name, as seen from the enclosing scope.
+ fn collapse_uses(&mut self, mark: u32, func: u32) {
+ self.stamp += 1;
+ let stamp = self.stamp;
+ let mut free_names = std::mem::take(&mut self.free_names_scratch);
+ free_names.clear();
+ let mut i = self.uses.len();
+ while i > mark as usize {
+ i -= 1;
+ // SAFETY: The index is within the table.
+ let row = unsafe { *self.uses.get_unchecked(i) };
+ if row.name == USE_DEAD {
+ continue;
+ }
+ // SAFETY: A live use's name has a state row.
+ let state = unsafe { self.names.get_unchecked_mut(row.name as usize) };
+ state.use_head = row.prev;
+ if state.stamp & !DECLARED_BIT != stamp {
+ state.stamp = stamp | (state.stamp & DECLARED_BIT);
+ free_names.push(row.name);
+ }
+ if row.func & USE_IN_WITH != 0 {
+ self.names_used_in_with.push(row.name);
+ }
+ }
+ self.uses.truncate(mark as usize);
+ let scope = self.cur_scope;
+ for &name in &free_names {
+ let next = self.uses.len() as u32;
+ let state = &mut self.names[name as usize];
+ let prev = state.use_head;
+ state.use_head = next;
+ state.use_scope = scope;
+ self.uses.push(UseRow {
+ name,
+ scope,
+ func,
+ prev,
+ });
+ }
+ self.free_names_scratch = free_names;
+ while let Some(name) = self.names_used_in_with.pop() {
+ let head = self.names[name as usize].use_head;
+ self.uses[head as usize].func |= USE_IN_WITH;
+ }
+ }
+
+ /// Every recursive path of the parser goes through this, and through leave() on the way back. The limit on the
+ /// depth also protects what walks the tree later, which recursion here reaches as deep as it reached here.
+ #[inline(always)]
+ pub(crate) fn enter(&mut self) -> bool {
+ let marker = 0u8;
+ if self.recursion_depth >= MAX_RECURSION_DEPTH || (&raw const marker as usize) < self.stack_limit {
+ self.fail(self.tok_start, RECURSION_LIMIT_MESSAGE);
+ return false;
+ }
+ self.recursion_depth += 1;
+ true
+ }
+
+ #[inline(always)]
+ pub(crate) fn leave(&mut self) {
+ self.recursion_depth -= 1;
+ }
+}
+
+const DECLARED_BIT: u32 = 1 << 31;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Bind {
+ None,
+ Var,
+ Let,
+ Const,
+ /// A lexical binding with no declaration keyword of its own, such as a class or an import.
+ Lexical,
+ Function,
+ SimpleCatch,
+ CatchPattern,
+ Parameter,
+}
diff --git a/Libraries/LibJS/Rust/src/parser/expr.rs b/Libraries/LibJS/Rust/src/parser/expr.rs
new file mode 100644
index 00000000000..7d2d0e3ada4
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/parser/expr.rs
@@ -0,0 +1,1653 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Expressions. Arrow function parameters and destructuring assignment targets are parsed as expressions, and a tag
+//! rewrite in place turns them into patterns once `=>` or `=` shows what they were, without going back over them.
+
+use super::base::*;
+use super::columns::*;
+use super::token::*;
+use super::unit::Unit;
+
+pub(crate) const fn starts_expression(kind: T) -> bool {
+ matches!(
+ kind,
+ T::Name
+ | T::PrivateName
+ | T::Num
+ | T::BigInt
+ | T::Str
+ | T::Backtick
+ | T::LBrace
+ | T::LParen
+ | T::LBracket
+ | T::Inc
+ | T::Dec
+ | T::Not
+ | T::Tilde
+ | T::Plus
+ | T::Minus
+ | T::Slash
+ | T::DivAssign
+ | T::KClass
+ | T::KDelete
+ | T::KFalse
+ | T::KFunction
+ | T::KImport
+ | T::KNew
+ | T::KNull
+ | T::KSuper
+ | T::KThis
+ | T::KTrue
+ | T::KTypeof
+ | T::KVoid
+ )
+}
+
+#[inline(always)]
+pub(crate) fn is_name_like(kind: T) -> bool {
+ kind == T::Name || kind == T::EscapedKeyword || kind as u8 >= T::KIn as u8
+}
+
+impl<U: Unit> Parser<'_, U> {
+ pub(crate) fn parse_expression(&mut self, no_in: bool, cover_ok: bool) -> u32 {
+ let start = self.tok_start;
+ let first = self.parse_assign(no_in, cover_ok);
+ if self.tok != T::Comma {
+ return first;
+ }
+ let mark = self.scratch.len();
+ self.scratch.push(first);
+ while self.eat(T::Comma) {
+ let next = self.parse_assign(no_in, cover_ok);
+ self.scratch.push(next);
+ }
+ let list = self.finish_list(mark);
+ self.ast.push(tag::SEQUENCE, start, list, 0)
+ }
+
+ pub(crate) fn parse_assign(&mut self, no_in: bool, cover_ok: bool) -> u32 {
+ if !self.enter() {
+ return 0;
+ }
+ let expression = self.parse_assign_inner(no_in, cover_ok);
+ self.leave();
+ expression
+ }
+
+ fn parse_assign_inner(&mut self, no_in: bool, cover_ok: bool) -> u32 {
+ if self.tok == T::Name && self.tok_name == N_YIELD && self.ctx & ctx::GENERATOR != 0 && !self.tok_escaped {
+ return self.parse_yield(no_in);
+ }
+ let saved_cover_error = self.cover_error;
+ self.cover_error = NONE;
+ let start = self.tok_start;
+ if self.tok == T::LParen || self.tok == T::Name {
+ self.potential_arrow_at = start;
+ }
+ let mut left = self.parse_conditional(no_in);
+ let kind = self.tok as u8;
+ let operator_pos = self.tok_start;
+ if kind >= T::Assign as u8 && kind <= T::NullishAssign as u8 {
+ if self.tok == T::Assign {
+ self.convert_assignment_target(left);
+ self.cover_error = NONE;
+ self.mark(tag::MARK_TARGET, 0);
+ } else {
+ let allow_call =
+ self.tok != T::LogAndAssign && self.tok != T::LogOrAssign && self.tok != T::NullishAssign;
+ self.check_simple_target(left, allow_call, "Invalid left-hand side in assignment");
+ self.mark(tag::MARK_READ_TARGET, 0);
+ if !allow_call {
+ self.mark(tag::MARK_LOGICAL_ASSIGNMENT, u32::from(kind));
+ }
+ }
+ self.next();
+ let right = self.parse_assign(no_in, false);
+ let target = left;
+ left = self
+ .ast
+ .push(tag::ASSIGN_BASE + (kind - T::Assign as u8), operator_pos, left, right);
+ if self.marks && matches!(self.ast.tag[target as usize], tag::ARRAY_PATTERN | tag::OBJECT_PATTERN) {
+ // NB: The rows of a pattern run after what comes behind them, which a sweep finds out at their start.
+ let mark = self.ast.b[target as usize];
+ self.ast.tag[mark as usize] = tag::MARK_SUBTREE;
+ self.ast.a[mark as usize] = left;
+ }
+ }
+ if self.cover_error != NONE {
+ if !cover_ok {
+ self.fail(
+ self.cover_error,
+ "Shorthand property initializers are only valid in patterns",
+ );
+ }
+ } else {
+ self.cover_error = saved_cover_error;
+ }
+ left
+ }
+
+ fn parse_yield(&mut self, no_in: bool) -> u32 {
+ if self.yield_pos == 0 {
+ self.yield_pos = self.tok_start;
+ }
+ let start = self.tok_start;
+ self.next();
+ if self.tok == T::Semi || self.can_insert_semicolon() || (self.tok != T::Star && !starts_expression(self.tok)) {
+ return self.ast.push(tag::YIELD, start, 0, 0);
+ }
+ let delegate = self.eat(T::Star);
+ let argument = self.parse_assign(no_in, false);
+ self.ast
+ .push(if delegate { tag::YIELD_STAR } else { tag::YIELD }, start, argument, 0)
+ }
+
+ #[inline(always)]
+ fn parse_conditional(&mut self, no_in: bool) -> u32 {
+ let start = self.tok_start;
+ let test = self.parse_binary_expression(no_in);
+ if self.tok != T::Question || test == self.last_arrow {
+ return test;
+ }
+ let operator_pos = self.tok_start;
+ self.mark(tag::MARK_CONDITIONAL_TEST, 0);
+ self.next();
+ let consequent = self.parse_assign(false, false);
+ self.mark(tag::MARK_CONDITIONAL_ELSE, 0);
+ self.expect(T::Colon);
+ let alternate = self.parse_assign(no_in, false);
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(consequent);
+ self.ast.extra.push(alternate);
+ let _ = start;
+ self.ast.push(tag::CONDITIONAL, operator_pos, test, extra)
+ }
+
+ #[inline(always)]
+ fn parse_binary_expression(&mut self, no_in: bool) -> u32 {
+ let start = self.tok_start;
+ let left = self.parse_unary(false, false, no_in);
+ if PRECEDENCE[self.tok as usize] == 0 || left == self.last_arrow {
+ return left;
+ }
+ self.parse_binary_operators(left, start, 0, no_in)
+ }
+
+ fn parse_binary_operators(&mut self, mut left: u32, left_start: u32, min_precedence: u8, no_in: bool) -> u32 {
+ loop {
+ let kind = self.tok;
+ let operator_pos = self.tok_start;
+ let precedence = PRECEDENCE[kind as usize];
+ if precedence <= min_precedence || (kind == T::KIn && no_in) {
+ return left;
+ }
+ let logical = kind == T::LogOr || kind == T::LogAnd;
+ let coalesce = kind == T::Nullish;
+ let right_precedence = if coalesce {
+ PRECEDENCE[T::LogAnd as usize]
+ } else {
+ precedence
+ };
+ if logical || coalesce {
+ self.mark(
+ tag::MARK_LOGICAL,
+ u32::from(tag::BINARY_BASE + (kind as u8 - T::Nullish as u8)),
+ );
+ }
+ self.next();
+ let right_start = self.tok_start;
+ let operand = self.parse_unary(false, false, no_in);
+ let right = self.parse_binary_operators(operand, right_start, right_precedence, no_in);
+ if self.ast.tag[right as usize] == tag::PRIVATE_NAME {
+ self.fail(right_start, "A private name can only be the left side of `in`");
+ }
+ let _ = left_start;
+ left = self.ast.push(
+ tag::BINARY_BASE + (kind as u8 - T::Nullish as u8),
+ operator_pos,
+ left,
+ right,
+ );
+ if (logical && self.tok == T::Nullish) || (coalesce && (self.tok == T::LogOr || self.tok == T::LogAnd)) {
+ self.fail(
+ self.tok_start,
+ "`??` cannot be mixed with `||` or `&&` without parentheses",
+ );
+ }
+ }
+ }
+
+ fn is_local_variable_access(&self, node: u32) -> bool {
+ match self.ast.tag[node as usize] {
+ tag::IDENT => true,
+ tag::PAREN => self.is_local_variable_access(self.ast.a[node as usize]),
+ _ => false,
+ }
+ }
+
+ fn is_private_field_access(&self, node: u32) -> bool {
+ match self.ast.tag[node as usize] {
+ tag::PRIVATE_MEMBER | tag::OPT_PRIVATE_MEMBER => true,
+ tag::PAREN | tag::CHAIN => self.is_private_field_access(self.ast.a[node as usize]),
+ _ => false,
+ }
+ }
+
+ /// The operand of a unary operator, which can nest without anything else in between.
+ fn parse_operand(&mut self, saw_unary: bool, inc_dec: bool, no_in: bool) -> u32 {
+ if !self.enter() {
+ return 0;
+ }
+ let operand = self.parse_unary(saw_unary, inc_dec, no_in);
+ self.leave();
+ operand
+ }
+
+ fn parse_unary(&mut self, mut saw_unary: bool, inc_dec: bool, no_in: bool) -> u32 {
+ let start = self.tok_start;
+ let mut expression;
+ match self.tok {
+ T::Name if self.tok_name == N_AWAIT && self.ctx & ctx::CAN_AWAIT != 0 && !self.tok_escaped => {
+ if self.await_pos == 0 {
+ self.await_pos = start;
+ }
+ if self.ctx & ctx::ASYNC == 0 {
+ self.has_top_level_await = true;
+ }
+ self.next();
+ let argument = self.parse_operand(true, false, no_in);
+ expression = self.ast.push(tag::AWAIT, start, argument, 0);
+ saw_unary = true;
+ }
+ T::Not | T::Tilde | T::Plus | T::Minus | T::KTypeof | T::KVoid | T::KDelete | T::Inc | T::Dec => {
+ let kind = self.tok;
+ let update = kind == T::Inc || kind == T::Dec;
+ self.next();
+ let argument = self.parse_operand(true, update, no_in);
+ if update {
+ self.check_simple_target(argument, true, "Invalid left-hand side in prefix operation");
+ self.mark_at(tag::MARK_READ_TARGET, 0, start);
+ } else {
+ if kind == T::KTypeof {
+ self.mark_at(tag::MARK_TYPEOF, 0, start);
+ }
+ if kind == T::KDelete {
+ self.mark_at(tag::MARK_DELETE, 0, start);
+ if self.strict && self.is_local_variable_access(argument) {
+ self.fail(start, "Deleting a local variable in strict mode");
+ } else if self.is_private_field_access(argument) {
+ self.fail(start, "Private fields cannot be deleted");
+ }
+ }
+ saw_unary = true;
+ }
+ let t = if update { tag::PREFIX_UPDATE } else { tag::UNARY };
+ expression = self.ast.push(t, start, argument, kind as u32);
+ }
+ T::PrivateName if !saw_unary => {
+ if no_in || (self.class_marks.is_empty() && !self.initiated_by_eval) {
+ self.unexpected();
+ return 0;
+ }
+ expression = self.parse_private_name();
+ if self.tok != T::KIn {
+ self.fail(start, "Private identifier must be followed by 'in'");
+ }
+ }
+ _ => {
+ expression = self.parse_left_hand_side(no_in);
+ if (self.tok == T::Inc || self.tok == T::Dec) && !self.nl_before {
+ while (self.tok == T::Inc || self.tok == T::Dec) && !self.nl_before {
+ let kind = self.tok;
+ let operator_pos = self.tok_start;
+ self.check_simple_target(expression, true, "Invalid left-hand side in postfix operation");
+ self.mark(tag::MARK_READ_TARGET, 0);
+ self.next();
+ expression = self
+ .ast
+ .push(tag::POSTFIX_UPDATE, operator_pos, expression, kind as u32);
+ }
+ }
+ }
+ }
+ if !inc_dec && self.tok == T::StarStar {
+ if saw_unary {
+ self.unexpected();
+ return 0;
+ }
+ let operator_pos = self.tok_start;
+ self.next();
+ let right = self.parse_operand(false, false, no_in);
+ return self.ast.push(
+ tag::BINARY_BASE + (T::StarStar as u8 - T::Nullish as u8),
+ operator_pos,
+ expression,
+ right,
+ );
+ }
+ expression
+ }
+
+ pub(crate) fn parse_private_name(&mut self) -> u32 {
+ let name = self.tok_name;
+ let pos = self.tok_start;
+ self.private_used.push((name, pos));
+ self.next();
+ self.ast.push(tag::PRIVATE_NAME, pos, name, 0)
+ }
+
+ #[inline(always)]
+ pub(crate) fn parse_left_hand_side(&mut self, no_in: bool) -> u32 {
+ let start = self.tok_start;
+ let atom = self.parse_atom(no_in, false);
+ if atom == self.last_arrow && atom != 0 && self.at(self.prev_start as usize) != 0x29 {
+ return atom;
+ }
+ match self.tok {
+ T::Dot | T::LBracket | T::LParen | T::Backtick | T::QDot => {
+ self.parse_subscripts(atom, start, false, no_in)
+ }
+ _ => atom,
+ }
+ }
+
+ fn parse_subscripts(&mut self, mut base: u32, start: u32, no_calls: bool, no_in: bool) -> u32 {
+ let base_tag = self.ast.tag[base as usize];
+ if (base_tag == tag::OBJECT || base_tag == tag::ARRAY) && self.cover_error != NONE {
+ self.fail(
+ self.cover_error,
+ "Shorthand property initializers are only valid in patterns",
+ );
+ return base;
+ }
+ let maybe_async_arrow = base_tag == tag::IDENT
+ && self.ast.a[base as usize] == N_ASYNC
+ && self.prev_end == start + 5
+ && !self.nl_before
+ && self.potential_arrow_at == start;
+ let mut optional_chained = false;
+ let mut chain_pos = start;
+ loop {
+ // NB: All of an optional chain is where it starts.
+ if optional_chained && self.marks {
+ self.ast.pos[base as usize] = chain_pos;
+ }
+ match self.tok {
+ T::Dot => {
+ let operator_pos = self.tok_start;
+ self.next();
+ base = self.parse_member_name(base, operator_pos, false);
+ }
+ T::LBracket => {
+ let operator_pos = self.tok_start;
+ self.next();
+ let property = self.parse_expression(false, false);
+ self.expect(T::RBracket);
+ let index_tag = if self.marks && self.ast.tag[base as usize] == tag::SUPER {
+ tag::SUPER_INDEX
+ } else {
+ tag::INDEX
+ };
+ base = self.ast.push(index_tag, operator_pos, base, property);
+ }
+ T::LParen if !no_calls => {
+ if maybe_async_arrow && base == self.async_candidate(base) {
+ let result = self.parse_async_call_or_arrow(base, start, no_in);
+ if result == self.last_arrow && result != 0 {
+ if self.marks {
+ // NB: This turned out not to be a reference, and nothing is to evaluate it.
+ self.ast.tag[base as usize] = tag::EMPTY;
+ }
+ return result;
+ }
+ base = result;
+ continue;
+ }
+ let operator_pos = self.tok_start;
+ let mut callee = base;
+ while self.ast.tag[callee as usize] == tag::PAREN {
+ callee = self.ast.a[callee as usize];
+ }
+ let is_eval = self.ast.tag[callee as usize] == tag::IDENT && self.ast.a[callee as usize] == N_EVAL;
+ let position = if optional_chained { chain_pos } else { operator_pos };
+ self.mark_at(tag::MARK_CALLEE, 0, position);
+ let arguments = self.parse_arguments(position);
+ if is_eval {
+ let scope = self.scopes.last_mut().unwrap();
+ scope.has_eval = true;
+ scope.eval_in_function = true;
+ scope.eval_here = true;
+ self.uses_this = true;
+ self.uses_this_from_environment |= self.in_arrow;
+ }
+ let call_tag = if self.ast.tag[callee as usize] == tag::SUPER_CALLEE {
+ tag::SUPER_CALL
+ } else if self.marks && is_eval {
+ if self.arguments_have_spread {
+ tag::CALL_DIRECT_EVAL_SPREAD
+ } else {
+ tag::CALL_DIRECT_EVAL
+ }
+ } else {
+ self.call_tag(tag::CALL)
+ };
+ base = self.ast.push(call_tag, operator_pos, base, arguments);
+ }
+ T::Backtick => {
+ if optional_chained {
+ self.fail(self.tok_start, "Tagged template in an optional chain");
+ return base;
+ }
+ self.mark_at(tag::MARK_CALLEE, 0, start);
+ let subtree = self.begin_subtree();
+ let quasi = self.parse_template(true);
+ self.end_subtree(subtree, quasi);
+ base = self.ast.push(tag::TAGGED_TEMPLATE, start, base, quasi);
+ }
+ T::QDot => {
+ if no_calls {
+ self.fail(self.tok_start, "Optional chain in the callee of new");
+ return base;
+ }
+ let operator_pos = self.tok_start;
+ if !optional_chained {
+ chain_pos = operator_pos;
+ }
+ optional_chained = true;
+ self.next();
+ if self.tok == T::LParen {
+ self.mark_at(tag::MARK_CALLEE, 0, chain_pos);
+ }
+ self.mark(tag::MARK_OPTIONAL, u32::from(chain_pos == operator_pos));
+ match self.tok {
+ T::LParen => {
+ let arguments = self.parse_arguments(chain_pos);
+ base = self
+ .ast
+ .push(self.call_tag(tag::OPT_CALL), operator_pos, base, arguments);
+ }
+ T::LBracket => {
+ self.next();
+ let property = self.parse_expression(false, false);
+ self.expect(T::RBracket);
+ base = self.ast.push(tag::OPT_INDEX, operator_pos, base, property);
+ }
+ T::Backtick => {
+ self.fail(self.tok_start, "Tagged template in an optional chain");
+ return base;
+ }
+ _ => base = self.parse_member_name(base, operator_pos, true),
+ }
+ }
+ _ => break,
+ }
+ }
+ if optional_chained {
+ if self.marks {
+ self.ast.pos[base as usize] = chain_pos;
+ }
+ base = self.ast.push(tag::CHAIN, chain_pos, base, 0);
+ }
+ base
+ }
+
+ #[inline(always)]
+ fn async_candidate(&self, base: u32) -> u32 {
+ if self.ast.tag[base as usize] == tag::IDENT {
+ base
+ } else {
+ 0
+ }
+ }
+
+ #[inline(always)]
+ fn parse_member_name(&mut self, base: u32, start: u32, optional: bool) -> u32 {
+ if self.tok == T::PrivateName {
+ if self.ast.tag[base as usize] == tag::SUPER {
+ self.unexpected();
+ return base;
+ }
+ let name = self.tok_name;
+ self.private_used.push((name, self.tok_start));
+ self.next();
+ let t = if optional {
+ tag::OPT_PRIVATE_MEMBER
+ } else {
+ tag::PRIVATE_MEMBER
+ };
+ return self.ast.push(t, start, base, name);
+ }
+ if !is_name_like(self.tok) {
+ self.unexpected();
+ return base;
+ }
+ let name = self.tok_name;
+ if optional && self.tok == T::Name && (name == N_ARGUMENTS || name == N_EVAL) {
+ self.might_need_arguments = true;
+ }
+ self.next();
+ let member_tag = if optional {
+ tag::OPT_MEMBER
+ } else if self.marks && self.ast.tag[base as usize] == tag::SUPER {
+ tag::SUPER_MEMBER
+ } else {
+ tag::MEMBER
+ };
+ self.ast.push(member_tag, start, base, name)
+ }
+
+ /// What a call with the list of arguments that was parsed last is, of a tree for a sweep too.
+ #[inline(always)]
+ fn call_tag(&self, plain: u8) -> u8 {
+ if self.marks && self.arguments_have_spread {
+ tag::CALL_SPREAD
+ } else {
+ plain
+ }
+ }
+
+ /// The arguments of a call, from the `(`, of a call that is at `position`.
+ fn parse_arguments(&mut self, position: u32) -> u32 {
+ self.next();
+ let mark = self.scratch.len();
+ let mut has_spread = false;
+ while self.tok != T::RParen && self.tok != T::Eof {
+ let item = if self.tok == T::Ellipsis {
+ let start = self.tok_start;
+ if !has_spread {
+ self.mark_spread_start(self.scratch.len() - mark, position);
+ has_spread = true;
+ }
+ self.next();
+ let argument = self.parse_assign(false, false);
+ self.ast.push(tag::SPREAD, start, argument, 0)
+ } else {
+ let argument = self.parse_assign(false, false);
+ if has_spread {
+ self.mark(tag::MARK_APPEND, 0);
+ }
+ argument
+ };
+ self.scratch.push(item);
+ if self.tok != T::RParen {
+ self.expect_comma_or(T::RParen);
+ }
+ }
+ self.expect(T::RParen);
+ self.arguments_have_spread = has_spread;
+ self.finish_list(mark)
+ }
+
+ /// `async(...)`, which is a call unless `=>` follows.
+ fn parse_async_call_or_arrow(&mut self, base: u32, start: u32, no_in: bool) -> u32 {
+ if let Some(arrow) = self.skip_arrow_function(start, self.tok_start) {
+ return arrow;
+ }
+ let marks = self.ast.marks();
+ let (old_yield, old_await, old_await_ident) = (self.yield_pos, self.await_pos, self.await_ident_pos);
+ self.yield_pos = 0;
+ self.await_pos = 0;
+ self.await_ident_pos = 0;
+ let saved_cover_error = self.cover_error;
+ self.cover_error = NONE;
+ self.open_scope(0);
+ self.next();
+ let mark = self.scratch.len();
+ let params_start = self.prev_start;
+ let mut has_spread = false;
+ while self.tok != T::RParen && self.tok != T::Eof {
+ let item = if self.tok == T::Ellipsis {
+ let item_start = self.tok_start;
+ if !has_spread {
+ self.mark_spread_start(self.scratch.len() - mark, params_start);
+ has_spread = true;
+ }
+ self.next();
+ let argument = self.parse_assign(false, true);
+ let trailing = (self.tok == T::Comma) as u32;
+ self.ast.push(tag::SPREAD, item_start, argument, trailing)
+ } else {
+ let argument = self.parse_assign(false, true);
+ if has_spread {
+ self.mark(tag::MARK_APPEND, 0);
+ }
+ argument
+ };
+ self.scratch.push(item);
+ if self.tok != T::RParen {
+ self.expect_comma_or(T::RParen);
+ }
+ }
+ self.expect(T::RParen);
+ if self.tok == T::Arrow && !self.nl_before {
+ if self.yield_pos != 0 || self.await_pos != 0 {
+ self.fail(start, "Yield or await expression in arrow function parameters");
+ }
+ if self.await_ident_pos != 0 {
+ self.fail(
+ self.await_ident_pos,
+ "Cannot use 'await' as identifier inside an async function",
+ );
+ }
+ self.yield_pos = old_yield;
+ self.await_pos = old_await;
+ self.await_ident_pos = old_await_ident;
+ self.cover_error = NONE;
+ let list = self.finish_list(mark);
+ return self.parse_arrow_from_cover(start, params_start, marks, list, true, no_in, saved_cover_error);
+ }
+ if self.cover_error != NONE {
+ self.fail(
+ self.cover_error,
+ "Shorthand property initializers are only valid in patterns",
+ );
+ }
+ self.cover_error = saved_cover_error;
+ if old_yield != 0 {
+ self.yield_pos = old_yield;
+ }
+ if old_await != 0 {
+ self.await_pos = old_await;
+ }
+ if old_await_ident != 0 {
+ self.await_ident_pos = old_await_ident;
+ }
+ self.close_scope();
+ let list = self.finish_list(mark);
+ self.note_use(N_ASYNC);
+ let call_tag = if self.marks && has_spread {
+ tag::CALL_SPREAD
+ } else {
+ tag::CALL
+ };
+ self.ast.push(call_tag, params_start, base, list)
+ }
+
+ fn check_identifier_reserved(&mut self, name: u32, pos: u32) {
+ match name {
+ N_YIELD => {
+ if self.ctx & ctx::GENERATOR != 0 || self.strict {
+ self.fail(pos, "'yield' is not allowed as an identifier in this context");
+ }
+ }
+ N_AWAIT => {
+ if self.ctx & (ctx::ASYNC | ctx::STATIC_BLOCK) != 0 || self.module {
+ self.fail(pos, "'await' is not allowed as an identifier in this context");
+ }
+ if self.await_ident_pos == 0 {
+ self.await_ident_pos = pos;
+ }
+ }
+ N_ARGUMENTS => {
+ if self.ctx & ctx::STATIC_BLOCK != 0 {
+ self.fail(pos, "'arguments' is not allowed in class static initialization blocks");
+ } else if self.ctx & ctx::NO_ARGUMENTS != 0 {
+ self.fail(pos, "'arguments' is not allowed in class field initializer");
+ }
+ }
+ _ => {
+ if self.strict && (N_IMPLEMENTS..N_YIELD).contains(&name) {
+ self.fail(pos, "Identifier must not be a reserved word in strict mode");
+ }
+ }
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn check_identifier(&mut self, name: u32, pos: u32) {
+ if name < FIRST_PLAIN_NAME {
+ self.check_identifier_reserved(name, pos);
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn check_binding_name(&mut self, name: u32, pos: u32) {
+ if name < FIRST_PLAIN_NAME {
+ self.check_identifier_reserved(name, pos);
+ if self.strict && (name == N_EVAL || name == N_ARGUMENTS) {
+ self.fail(
+ pos,
+ "Binding pattern target may not be called 'arguments' or 'eval' in strict mode",
+ );
+ }
+ }
+ }
+
+ /// What a binding name has to pass once a function turns out to be strict, on top of what it passed when parsed.
+ pub(crate) fn check_strict_binding_name(&mut self, name: u32, pos: u32) {
+ if name == N_EVAL || name == N_ARGUMENTS || (N_IMPLEMENTS..=N_YIELD).contains(&name) {
+ self.fail(
+ pos,
+ "Binding pattern target may not be called 'arguments' or 'eval' in strict mode",
+ );
+ }
+ }
+
+ /// An identifier in a place that is no reference, which still has to be a valid one.
+ pub(crate) fn parse_ident(&mut self) -> (u32, u32) {
+ let (name, pos) = (self.tok_name, self.tok_start);
+ if self.tok != T::Name {
+ self.unexpected();
+ return (0, pos);
+ }
+ self.check_identifier(name, pos);
+ self.next();
+ (name, pos)
+ }
+
+ fn parse_atom(&mut self, no_in: bool, for_new: bool) -> u32 {
+ let start = self.tok_start;
+ match self.tok {
+ T::Name => {
+ let name = self.tok_name;
+ let escaped = self.tok_escaped;
+ let can_be_arrow = self.potential_arrow_at == start;
+ self.check_identifier(name, start);
+ if name == N_ARGUMENTS || name == N_EVAL {
+ self.might_need_arguments = true;
+ if name == N_ARGUMENTS
+ && (!self.strict || self.in_class_of_sloppy_function)
+ && !self.is_declared_in_current_function(name)
+ {
+ self.scopes.last_mut().unwrap().arguments_access = true;
+ }
+ }
+ self.next();
+ if name == N_ASYNC && !escaped && !self.nl_before {
+ if self.tok == T::KFunction {
+ self.next();
+ return self.parse_function_expression(start, true);
+ }
+ if can_be_arrow && self.tok == T::Name {
+ let param = self.tok_name;
+ let param_pos = self.tok_start;
+ if let Some(arrow) = self.skip_arrow_function(start, param_pos) {
+ return arrow;
+ }
+ if !(self.for_await_head && param == N_OF && !self.tok_escaped) {
+ self.next();
+ if self.tok != T::Arrow || self.nl_before {
+ self.unexpected();
+ return 0;
+ }
+ return self.parse_arrow_single(start, param, param_pos, true, no_in);
+ }
+ }
+ }
+ if self.tok == T::Arrow && can_be_arrow && !self.nl_before {
+ if let Some(arrow) = self.skip_arrow_function(start, start) {
+ return arrow;
+ }
+ return self.parse_arrow_single(start, name, start, false, no_in);
+ }
+ self.note_use(name);
+ self.ast.push(tag::IDENT, start, name, 0)
+ }
+ T::Num | T::BigInt | T::Str => self.parse_literal(),
+ T::KThis => {
+ self.note_use(N_DOT_THIS);
+ self.uses_this = true;
+ self.uses_this_from_environment |= self.in_arrow;
+ self.next();
+ self.ast.push(tag::THIS, start, 0, 0)
+ }
+ T::LParen => self.parse_paren(no_in),
+ T::LBracket => self.parse_array(),
+ T::LBrace => self.parse_object(),
+ T::KFunction => {
+ self.next();
+ self.parse_function_expression(start, false)
+ }
+ T::KTrue | T::KFalse | T::KNull => {
+ let t = match self.tok {
+ T::KTrue => tag::TRUE,
+ T::KFalse => tag::FALSE,
+ _ => tag::NULL,
+ };
+ self.next();
+ self.ast.push(t, start, 0, 0)
+ }
+ T::Slash | T::DivAssign => {
+ self.rescan_regex();
+ if self.tok != T::Regex {
+ return 0;
+ }
+ let (body_end, end) = (self.regex_body_end, self.tok_end);
+ self.next();
+ self.ast.push(tag::REGEX, start, body_end, end)
+ }
+ T::Backtick => {
+ let subtree = self.begin_subtree();
+ let template = self.parse_template(false);
+ self.end_subtree(subtree, template)
+ }
+ T::KNew => self.parse_new(),
+ T::KClass => self.parse_class(false),
+ T::KSuper => self.parse_super(),
+ T::KImport => self.parse_import_expression(for_new),
+ _ => {
+ self.expected("primary expression");
+ 0
+ }
+ }
+ }
+
+ fn parse_super(&mut self) -> u32 {
+ let start = self.tok_start;
+ if self.ctx & ctx::SUPER_PROPERTY == 0 {
+ self.fail(start, "'super' keyword unexpected here");
+ return 0;
+ }
+ self.next();
+ if self.tok == T::LParen && self.ctx & ctx::SUPER_CALL == 0 {
+ self.fail(start, "'super' keyword unexpected here");
+ return 0;
+ }
+ if self.tok != T::Dot && self.tok != T::LBracket && self.tok != T::LParen {
+ self.fail(start, "'super' keyword unexpected here");
+ return 0;
+ }
+ self.note_use(N_DOT_THIS);
+ self.note_use(N_DOT_SUPER);
+ self.uses_this = true;
+ self.uses_this_from_environment = true;
+ self.ast.push(tag::SUPER, start, 0, 0)
+ }
+
+ fn parse_literal(&mut self) -> u32 {
+ let start = self.tok_start;
+ let t = match self.tok {
+ T::Num => tag::NUM,
+ T::BigInt => tag::BIGINT,
+ _ => tag::STR,
+ };
+ if t != tag::BIGINT && self.tok_legacy && self.strict {
+ self.fail(
+ start,
+ if t == tag::NUM {
+ "Unprefixed octal number not allowed in strict mode"
+ } else {
+ "Octal escape sequence in string literal not allowed in strict mode"
+ },
+ );
+ return 0;
+ }
+ let end = self.tok_end;
+ self.next();
+ // The AST places a string where the next token starts.
+ self.ast.push(t, start, end, self.tok_start)
+ }
+
+ fn parse_import_expression(&mut self, for_new: bool) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ if self.tok == T::Dot {
+ self.next();
+ if !self.is_contextual(N_META) {
+ self.fail(self.tok_start, "Expected 'meta' after 'import.'");
+ return 0;
+ }
+ if !self.module {
+ self.fail(start, "import.meta outside a module");
+ return 0;
+ }
+ self.next();
+ return self.ast.push(tag::IMPORT_META, start, 0, 0);
+ }
+ if self.tok != T::LParen || for_new {
+ self.unexpected();
+ return 0;
+ }
+ self.next();
+ let specifier = self.parse_assign(false, false);
+ let mut options = 0;
+ if self.eat(T::Comma) && self.tok != T::RParen {
+ options = self.parse_assign(false, false);
+ self.eat(T::Comma);
+ }
+ self.expect(T::RParen);
+ self.ast.push(tag::IMPORT_CALL, start, specifier, options)
+ }
+
+ fn parse_new(&mut self) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ if self.tok == T::Dot {
+ self.next();
+ if !self.is_contextual(N_TARGET) {
+ self.fail(self.tok_start, "The only valid meta property for new is new.target");
+ return 0;
+ }
+ if self.ctx & ctx::NEW_TARGET == 0 {
+ self.fail(start, "'new.target' not allowed outside of a function");
+ return 0;
+ }
+ self.note_use(N_DOT_NEW_TARGET);
+ self.uses_this = true;
+ self.uses_this_from_environment = true;
+ self.next();
+ return self.ast.push(tag::NEW_TARGET, start, 0, 0);
+ }
+ if !self.enter() {
+ return 0;
+ }
+ let callee_start = self.tok_start;
+ let atom = self.parse_atom(false, true);
+ let callee = self.parse_subscripts(atom, callee_start, true, false);
+ self.leave();
+ let has_arguments = self.tok == T::LParen;
+ let arguments = if has_arguments {
+ self.parse_arguments(start)
+ } else {
+ self.finish_list(self.scratch.len())
+ };
+ let new_tag = if self.marks && has_arguments && self.arguments_have_spread {
+ tag::NEW_SPREAD
+ } else {
+ tag::NEW
+ };
+ self.ast.push(new_tag, start, callee, arguments)
+ }
+
+ fn parse_template(&mut self, tagged: bool) -> u32 {
+ let start = self.tok_start;
+ let mark = self.scratch.len();
+ loop {
+ let chunk = self.pos;
+ let (tail, invalid) = self.read_template_chunk();
+ if invalid && !tagged {
+ self.fail(chunk, "Invalid escape in template");
+ }
+ if self.err.is_some() {
+ self.scratch.truncate(mark);
+ return 0;
+ }
+ let chunk_end = self.pos - if tail { 1 } else { 2 };
+ // An empty chunk has no token to take a position from.
+ let shown_pos = if chunk_end == chunk { start } else { chunk_end };
+ let quasi = self.ast.push(
+ tag::TEMPLATE_CHUNK,
+ shown_pos,
+ chunk,
+ invalid as u32 | (chunk_end - chunk) << 1,
+ );
+ self.scratch.push(quasi);
+ if tail {
+ self.tok_end = self.pos;
+ self.next();
+ break;
+ }
+ self.tok_end = self.pos;
+ self.next();
+ let expression = self.parse_expression(false, false);
+ self.scratch.push(expression);
+ if self.tok != T::RBrace {
+ self.unexpected();
+ self.scratch.truncate(mark);
+ return 0;
+ }
+ }
+ let list = self.finish_list(mark);
+ self.ast.push(tag::TEMPLATE, start, list, 0)
+ }
+
+ fn parse_array(&mut self) -> u32 {
+ let start = self.tok_start;
+ let subtree = self.begin_subtree();
+ self.next();
+ let mark = self.scratch.len();
+ let mut has_spread = false;
+ while self.tok != T::RBracket && self.tok != T::Eof {
+ let is_spread = self.tok == T::Ellipsis;
+ if is_spread && !has_spread {
+ self.mark_spread_start(self.scratch.len() - mark, start);
+ has_spread = true;
+ }
+ let item = match self.tok {
+ T::Comma => self.ast.push(tag::HOLE, self.tok_start, 0, 0),
+ T::Ellipsis => {
+ let item_start = self.tok_start;
+ self.next();
+ let argument = self.parse_assign(false, true);
+ let trailing = (self.tok == T::Comma) as u32;
+ self.ast.push(tag::SPREAD, item_start, argument, trailing)
+ }
+ _ => self.parse_assign(false, true),
+ };
+ if has_spread && !is_spread {
+ self.mark(tag::MARK_APPEND, 0);
+ }
+ self.scratch.push(item);
+ if self.tok != T::RBracket {
+ self.expect_comma_or(T::RBracket);
+ }
+ }
+ self.expect(T::RBracket);
+ let list = self.finish_list(mark);
+ let array_tag = if self.marks && has_spread {
+ tag::ARRAY_SPREAD
+ } else {
+ tag::ARRAY
+ };
+ self.ast
+ .push(array_tag, start, list, if self.marks { subtree } else { 0 })
+ }
+
+ pub(crate) fn parse_property_name(&mut self) -> (u32, bool) {
+ let start = self.tok_start;
+ match self.tok {
+ T::LBracket => {
+ self.next();
+ let key = self.parse_assign(false, false);
+ self.expect(T::RBracket);
+ self.mark(tag::MARK_COMPUTED_KEY, 0);
+ (key, true)
+ }
+ T::Str | T::Num | T::BigInt => {
+ let key = self.parse_literal();
+ self.mark(tag::MARK_KEY, 0);
+ (key, false)
+ }
+ kind if is_name_like(kind) => {
+ let name = self.tok_name;
+ self.next();
+ let key = self.ast.push(tag::IDENT, start, name, 0);
+ self.mark(tag::MARK_KEY, 0);
+ (key, false)
+ }
+ _ => {
+ self.unexpected();
+ (0, false)
+ }
+ }
+ }
+
+ fn is_proto_key(&self, key: u32, key_kind: T, key_name: u32, key_end: u32) -> bool {
+ match key_kind {
+ T::Name => key_name == N_PROTO,
+ T::Str => {
+ let start = self.ast.pos[key as usize] as usize;
+ key_end as usize - start == 11 && (0..9).all(|i| self.at(start + 1 + i) == b"__proto__"[i] as u32)
+ }
+ _ => false,
+ }
+ }
+
+ fn parse_object(&mut self) -> u32 {
+ let start = self.tok_start;
+ let object_mark = self.ast.tag.len();
+ self.mark(tag::MARK_OBJECT, 0);
+ self.next();
+ let mark = self.scratch.len();
+ let mut has_proto = false;
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let property = self.parse_property(start, &mut has_proto);
+ self.scratch.push(property);
+ if self.tok != T::RBrace {
+ self.expect_comma_or(T::RBrace);
+ }
+ }
+ self.expect(T::RBrace);
+ if self.marks {
+ // NB: A literal of nothing but plain properties can cache its shape.
+ let is_simple = self.scratch.len() > mark
+ && !has_proto
+ && self.scratch[mark..].iter().all(|&property| {
+ let property = property as usize;
+ match self.ast.tag[property] {
+ tag::SHORTHAND => true,
+ tag::PROPERTY => {
+ let key = self.ast.a[property] as usize;
+ match self.ast.tag[key] {
+ tag::IDENT | tag::IDENT_KEY => true,
+ tag::STR | tag::STR_KEY => {
+ let first = self.at(self.ast.pos[key] as usize + 1);
+ !(0x30..=0x39).contains(&first) && first != 0x5C
+ }
+ _ => false,
+ }
+ }
+ _ => false,
+ }
+ });
+ self.ast.a[object_mark] = u32::from(is_simple);
+ }
+ let list = self.finish_list(mark);
+ self.ast.push(
+ tag::OBJECT,
+ start,
+ list,
+ if self.marks { object_mark as u32 } else { 0 },
+ )
+ }
+
+ fn parse_property(&mut self, object_start: u32, has_proto: &mut bool) -> u32 {
+ let start = self.tok_start;
+ if self.tok == T::Ellipsis {
+ self.next();
+ let argument = self.parse_assign(false, true);
+ let trailing = (self.tok == T::Comma) as u32;
+ if self.marks {
+ return self.ast.push(tag::OBJECT_SPREAD, object_start, argument, trailing);
+ }
+ return self.ast.push(tag::SPREAD, start, argument, trailing);
+ }
+ let mut is_generator = self.eat(T::Star);
+ let mut is_async = false;
+ let mut key_kind = self.tok;
+ let mut key_name = self.tok_name;
+ let mut key_escaped = key_kind == T::Name && self.tok_escaped;
+ let mut key_end = self.tok_end;
+ let (mut key, mut computed) = self.parse_property_name();
+ if !is_generator
+ && !computed
+ && key_kind == T::Name
+ && key_name == N_ASYNC
+ && !key_escaped
+ && !self.nl_before
+ && (is_name_like(self.tok) || matches!(self.tok, T::Num | T::BigInt | T::Str | T::LBracket | T::Star))
+ {
+ is_async = true;
+ is_generator = self.eat(T::Star);
+ key_kind = self.tok;
+ key_name = self.tok_name;
+ key_escaped = key_kind == T::Name && self.tok_escaped;
+ key_end = self.tok_end;
+ (key, computed) = self.parse_property_name();
+ }
+ if self.tok == T::Colon {
+ if is_generator || is_async {
+ self.unexpected();
+ return 0;
+ }
+ self.next();
+ let value = self.parse_assign(false, true);
+ if !computed && self.is_proto_key(key, key_kind, key_name, key_end) {
+ if *has_proto {
+ self.cover_error = start;
+ }
+ *has_proto = true;
+ }
+ let t = if computed {
+ tag::COMPUTED_PROPERTY
+ } else {
+ tag::PROPERTY
+ };
+ return self.ast.push(t, start, key, value);
+ }
+ if self.tok == T::LParen {
+ let function = self.parse_method(start, is_generator, is_async, false).0;
+ let t = if computed { tag::COMPUTED_METHOD } else { tag::METHOD };
+ return self.ast.push(t, start, key, function);
+ }
+ if !computed
+ && key_kind == T::Name
+ && (key_name == N_GET || key_name == N_SET)
+ && !key_escaped
+ && !matches!(self.tok, T::Comma | T::RBrace | T::Assign)
+ {
+ if is_generator || is_async {
+ self.unexpected();
+ return 0;
+ }
+ let (accessor_key, accessor_computed) = self.parse_property_name();
+ let (function, count, has_rest) = self.parse_method(start, false, false, false);
+ self.check_accessor_parameters(start, key_name == N_GET, count, has_rest);
+ let t = match (key_name == N_GET, accessor_computed) {
+ (true, false) => tag::GETTER,
+ (true, true) => tag::COMPUTED_GETTER,
+ (false, false) => tag::SETTER,
+ (false, true) => tag::COMPUTED_SETTER,
+ };
+ return self.ast.push(t, start, accessor_key, function);
+ }
+ if computed || key_kind != T::Name || is_generator || is_async {
+ self.unexpected();
+ return 0;
+ }
+ self.check_identifier(key_name, start);
+ self.note_use(key_name);
+ let mut value = self.ast.push(tag::IDENT, start, key_name, 0);
+ if self.tok == T::Assign {
+ self.cover_error = self.tok_start;
+ self.next();
+ let default = self.parse_nested_default();
+ value = self.ast.push(tag::ASSIGN_PATTERN, start, value, default);
+ }
+ self.ast.push(tag::SHORTHAND, start, key_name, value)
+ }
+
+ /// An initializer inside a cover grammar, whose own cover errors do not concern the pattern around it.
+ fn parse_nested_default(&mut self) -> u32 {
+ let saved = self.cover_error;
+ let value = self.parse_assign(false, false);
+ self.cover_error = saved;
+ value
+ }
+
+ pub(crate) fn check_accessor_parameters(&mut self, pos: u32, getter: bool, count: u32, has_rest: bool) {
+ if !self.is_reparsing() && (count != if getter { 0 } else { 1 } || has_rest) {
+ self.fail(pos, "Wrong number of accessor parameters");
+ }
+ }
+
+ // === Parenthesized expressions and arrow functions ===
+
+ fn parse_paren(&mut self, no_in: bool) -> u32 {
+ let start = self.tok_start;
+ let is_parenthesized = self.parenthesized_expression_start == start;
+ let can_be_arrow = self.potential_arrow_at == start;
+ if can_be_arrow && let Some(arrow) = self.skip_arrow_function(start, start) {
+ return arrow;
+ }
+ if !can_be_arrow {
+ self.next();
+ self.parenthesized_expression_start = self.tok_start;
+ let inner = self.parse_expression(false, false);
+ self.expect(T::RParen);
+ return self.ast.push(tag::PAREN, start, inner, self.prev_start);
+ }
+ let marks = self.ast.marks();
+ let (old_yield, old_await) = (self.yield_pos, self.await_pos);
+ self.yield_pos = 0;
+ self.await_pos = 0;
+ let saved_cover_error = self.cover_error;
+ self.cover_error = NONE;
+ self.open_scope(0);
+ self.next();
+ let pos_after_paren = self.tok_start;
+ self.parenthesized_expression_start = pos_after_paren;
+ let mark = self.scratch.len();
+ let mut last_is_comma = false;
+ let mut spread_at = NONE;
+ let mut first = true;
+ while self.tok != T::RParen && self.tok != T::Eof {
+ if !first {
+ self.expect_comma_or(T::RParen);
+ if self.tok == T::RParen {
+ last_is_comma = true;
+ break;
+ }
+ }
+ first = false;
+ if self.tok == T::Ellipsis {
+ spread_at = self.tok_start;
+ self.next();
+ let target = self.parse_binding_atom(Bind::None);
+ let rest = self.ast.push(tag::REST, spread_at, target, 0);
+ self.scratch.push(rest);
+ if self.tok == T::Comma {
+ self.fail(self.tok_start, "Comma is not permitted after the rest element");
+ }
+ break;
+ }
+ let item = self.parse_assign(false, true);
+ self.scratch.push(item);
+ }
+ let empty = self.scratch.len() == mark;
+ self.expect(T::RParen);
+ if self.tok == T::Arrow && !self.nl_before {
+ if self.yield_pos != 0 || self.await_pos != 0 {
+ self.fail(start, "Yield or await expression in arrow function parameters");
+ }
+ self.yield_pos = old_yield;
+ self.await_pos = old_await;
+ self.cover_error = NONE;
+ let list = self.finish_list(mark);
+ self.parenthesized_expression_start = if is_parenthesized { start } else { NONE };
+ return self.parse_arrow_from_cover(start, start, marks, list, false, no_in, saved_cover_error);
+ }
+ if empty || last_is_comma {
+ self.unexpected();
+ self.scratch.truncate(mark);
+ return 0;
+ }
+ if spread_at != NONE {
+ self.fail(spread_at, "Unexpected rest element");
+ self.scratch.truncate(mark);
+ return 0;
+ }
+ if self.cover_error != NONE {
+ self.fail(
+ self.cover_error,
+ "Shorthand property initializers are only valid in patterns",
+ );
+ }
+ self.cover_error = saved_cover_error;
+ if old_yield != 0 {
+ self.yield_pos = old_yield;
+ }
+ if old_await != 0 {
+ self.await_pos = old_await;
+ }
+ self.close_scope();
+ let inner = if self.scratch.len() - mark == 1 {
+ self.scratch.pop().unwrap()
+ } else {
+ let first_item = pos_after_paren;
+ let list = self.finish_list(mark);
+ self.ast.push(tag::SEQUENCE, first_item, list, 0)
+ };
+ self.ast.push(tag::PAREN, start, inner, self.prev_start)
+ }
+
+ /// An arrow function on its own: its parameters are known to be parameters by now, so no cover grammar is needed.
+ pub(crate) fn reparse_arrow_function(&mut self, start: u32, params_start: u32, flags: u32) -> u32 {
+ let is_async = flags & function_flag::ASYNC != 0;
+ let no_in = flags & function_flag::NO_IN != 0;
+ if self.tok == T::Name {
+ let (name, name_pos) = (self.tok_name, self.tok_start);
+ self.next();
+ return self.parse_arrow_single(start, name, name_pos, is_async, no_in);
+ }
+ let new_ctx = self.ctx;
+ let own_flags = function_flag::ARROW | if is_async { function_flag::ASYNC } else { 0 };
+ let mut state = self.begin_function(start, new_ctx, own_flags);
+ self.scopes.last_mut().unwrap().flags |= scope_flag::ARROW;
+ let (list, count, length, simple, _) = self.parse_parameter_list(&mut state);
+ self.parse_arrow_body(&mut state, list, count, length, simple, params_start, no_in, start)
+ }
+
+ /// In a reparse: goes past the arrow function that the code at `params_start` turns out to be, if it is one.
+ fn skip_arrow_function(&mut self, start: u32, params_start: u32) -> Option<u32> {
+ let row = self.skippable_arrow_row(params_start)?;
+ let state = self.begin_function(start, self.ctx, function_flag::ARROW);
+ self.scopes.last_mut().unwrap().flags |= scope_flag::ARROW;
+ let node = self.skip_function(state, row);
+ self.last_arrow = node;
+ Some(node)
+ }
+
+ fn arrow_ctx(&self, is_async: bool) -> u32 {
+ let inherited = self.ctx & (ctx::SUPER_PROPERTY | ctx::SUPER_CALL | ctx::NEW_TARGET | ctx::NO_ARGUMENTS);
+ inherited | ctx::RETURN | if is_async { ctx::ASYNC | ctx::CAN_AWAIT } else { 0 }
+ }
+
+ fn parse_arrow_single(&mut self, start: u32, name: u32, name_pos: u32, is_async: bool, no_in: bool) -> u32 {
+ let new_ctx = self.arrow_ctx(is_async);
+ let flags =
+ function_flag::ARROW | function_flag::SIMPLE_PARAMETERS | if is_async { function_flag::ASYNC } else { 0 };
+ let mut state = self.begin_function(start, new_ctx, flags);
+ self.scopes.last_mut().unwrap().flags |= scope_flag::ARROW;
+ self.check_binding_name(name, name_pos);
+ self.declare(name, Bind::Parameter, name_pos);
+ let param = self.ast.push(tag::IDENT, start, name, 0);
+ self.scratch.push(param);
+ let list = self.finish_list(self.scratch.len() - 1);
+ self.parse_arrow_body(&mut state, list, 1, 1, true, name_pos, no_in, start)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn parse_arrow_from_cover(
+ &mut self,
+ start: u32,
+ params_start: u32,
+ marks: AstMarks,
+ list: u32,
+ is_async: bool,
+ no_in: bool,
+ saved_cover_error: u32,
+ ) -> u32 {
+ let new_ctx = self.arrow_ctx(is_async);
+ let flags = function_flag::ARROW | if is_async { function_flag::ASYNC } else { 0 };
+ let mut state = self.begin_arrow_from_cover(start, marks, new_ctx, flags);
+ state.cover_error = saved_cover_error;
+ let count = self.ast.extra[list as usize];
+ let mut simple = true;
+ let mut length = 0;
+ let mut counting = true;
+ for i in 0..count {
+ let item = self.ast.extra[(list + 1 + i) as usize];
+ if self.ast.tag[item as usize] == tag::SPREAD {
+ // `async(...rest) =>` was parsed as the arguments of a call.
+ if i + 1 != count || self.ast.b[item as usize] != 0 {
+ self.fail(self.ast.pos[item as usize], "Rest parameter must be last");
+ }
+ let argument = self.ast.a[item as usize];
+ if self.is_assignment(argument) {
+ self.fail(
+ self.ast.pos[argument as usize],
+ "Rest parameter may not have an initializer",
+ );
+ }
+ self.ast.tag[item as usize] = tag::REST;
+ }
+ self.convert_to_assignable(item, Bind::Parameter);
+ let t = self.ast.tag[item as usize];
+ simple &= t == tag::IDENT;
+ counting &= t != tag::ASSIGN_PATTERN && t != tag::REST;
+ if counting {
+ length += 1;
+ }
+ }
+ if simple {
+ state.flags |= function_flag::SIMPLE_PARAMETERS;
+ }
+ if self.duplicate_parameter != NONE {
+ self.fail(self.duplicate_parameter, "Duplicate parameter name");
+ }
+ // A parameter named `arguments` looked like a read of it until the `=>`.
+ let declares_arguments = self.has_declaration_at_top_of_scope(N_ARGUMENTS);
+ if declares_arguments {
+ let scope = self.scopes.last_mut().unwrap();
+ scope.arguments_access = scope.nested_arguments_access;
+ }
+ self.parse_arrow_body(&mut state, list, count, length, simple, params_start, no_in, start)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn parse_arrow_body(
+ &mut self,
+ state: &mut FunctionState,
+ list: u32,
+ count: u32,
+ length: u32,
+ simple: bool,
+ params_start: u32,
+ no_in: bool,
+ start: u32,
+ ) -> u32 {
+ self.next();
+ state.body_start = self.tok_start;
+ state.first_body_row = self.ast.tag.len() as u32;
+ if no_in {
+ state.flags |= function_flag::NO_IN;
+ }
+ let (body, is_expression) = if self.tok == T::LBrace {
+ (self.parse_function_body(state, None, list, simple, true, false), false)
+ } else {
+ if !simple {
+ self.open_function_body_scope(state);
+ }
+ (self.parse_assign(no_in, false), true)
+ };
+ let end = self.prev_end;
+ let moved_state = core::mem::replace(state, self.empty_function_state());
+ let node = self.end_function(
+ moved_state,
+ end,
+ count,
+ length,
+ params_start,
+ list,
+ body,
+ NONE,
+ is_expression,
+ );
+ self.last_arrow = node;
+ let _ = start;
+ node
+ }
+
+ // === Patterns ===
+
+ /// The target of an assignment, which unlike a target inside a pattern may also be a call in sloppy mode.
+ pub(crate) fn convert_assignment_target(&mut self, node: u32) {
+ let mut inner = node;
+ while self.ast.tag[inner as usize] == tag::PAREN {
+ inner = self.ast.a[inner as usize];
+ }
+ if self.ast.tag[inner as usize] == tag::CALL && !self.strict {
+ return;
+ }
+ self.convert_to_assignable(node, Bind::None);
+ }
+
+ /// Rewrites an expression into the pattern it covers, and validates it. With a binding kind, this also declares the
+ /// pattern's names.
+ pub(crate) fn convert_to_assignable(&mut self, node: u32, bind: Bind) {
+ let binding = bind != Bind::None;
+ // An inner assignment already converted and checked its target, and a binding walks it only once.
+ if !binding && matches!(self.ast.tag[node as usize], tag::OBJECT_PATTERN | tag::ARRAY_PATTERN) {
+ return;
+ }
+ let pos = self.ast.pos[node as usize];
+ match self.ast.tag[node as usize] {
+ tag::IDENT => {
+ let name = self.ast.a[node as usize];
+ if binding {
+ self.check_binding_name(name, pos);
+ self.declare(name, bind, pos);
+ } else if self.strict && (name == N_EVAL || name == N_ARGUMENTS) {
+ self.fail(
+ pos,
+ "Binding pattern target may not be called 'arguments' or 'eval' in strict mode",
+ );
+ }
+ }
+ tag::MEMBER | tag::INDEX | tag::PRIVATE_MEMBER => {
+ if binding {
+ self.fail(pos, "Binding member expression");
+ }
+ }
+ tag::PAREN => {
+ if binding {
+ self.fail(pos, "Binding parenthesized expression");
+ return;
+ }
+ let mut inner = self.ast.a[node as usize];
+ while self.ast.tag[inner as usize] == tag::PAREN {
+ inner = self.ast.a[inner as usize];
+ }
+ match self.ast.tag[inner as usize] {
+ tag::IDENT | tag::MEMBER | tag::INDEX | tag::PRIVATE_MEMBER => {
+ self.convert_to_assignable(inner, bind);
+ }
+ // NB: This went through the first parse, and rows may have changed by now.
+ _ if self.marks => {}
+ _ => self.fail(pos, "Invalid left-hand side in assignment"),
+ }
+ }
+ tag::OBJECT | tag::OBJECT_PATTERN => {
+ self.ast.tag[node as usize] = tag::OBJECT_PATTERN;
+ let list = self.ast.a[node as usize];
+ let count = self.ast.extra[list as usize];
+ for i in 0..count {
+ let property = self.ast.extra[(list + 1 + i) as usize];
+ match self.ast.tag[property as usize] {
+ tag::PROPERTY | tag::COMPUTED_PROPERTY | tag::SHORTHAND => {
+ self.convert_to_assignable(self.ast.b[property as usize], bind);
+ }
+ tag::SPREAD | tag::OBJECT_SPREAD | tag::REST => {
+ if i + 1 != count || self.ast.b[property as usize] != 0 {
+ self.fail(self.ast.pos[property as usize], "Rest element must be last");
+ return;
+ }
+ self.ast.tag[property as usize] = tag::REST;
+ let argument = self.ast.a[property as usize];
+ let t = self.ast.tag[argument as usize];
+ let valid = self.marks
+ || t == tag::IDENT
+ || (!binding
+ && matches!(t, tag::MEMBER | tag::INDEX | tag::PRIVATE_MEMBER | tag::PAREN));
+ if !valid {
+ self.fail(self.ast.pos[argument as usize], "Invalid rest element");
+ return;
+ }
+ self.convert_to_assignable(argument, bind);
+ }
+ _ => {
+ self.fail(
+ self.ast.pos[property as usize],
+ "Invalid destructuring assignment target",
+ );
+ return;
+ }
+ }
+ }
+ }
+ tag::ARRAY | tag::ARRAY_SPREAD | tag::ARRAY_PATTERN => {
+ self.ast.tag[node as usize] = tag::ARRAY_PATTERN;
+ let list = self.ast.a[node as usize];
+ let count = self.ast.extra[list as usize];
+ for i in 0..count {
+ let element = self.ast.extra[(list + 1 + i) as usize];
+ match self.ast.tag[element as usize] {
+ tag::HOLE => {}
+ tag::SPREAD | tag::REST => {
+ if i + 1 != count || self.ast.b[element as usize] != 0 {
+ self.fail(self.ast.pos[element as usize], "Rest element must be last");
+ return;
+ }
+ self.ast.tag[element as usize] = tag::REST;
+ let argument = self.ast.a[element as usize];
+ if self.is_assignment(argument) || self.ast.tag[argument as usize] == tag::ASSIGN_PATTERN {
+ self.fail(
+ self.ast.pos[argument as usize],
+ "Rest element may not have an initializer",
+ );
+ return;
+ }
+ self.convert_to_assignable(argument, bind);
+ }
+ _ => self.convert_to_assignable(element, bind),
+ }
+ }
+ }
+ tag::REST => self.convert_to_assignable(self.ast.a[node as usize], bind),
+ tag::ASSIGN_PATTERN => {
+ self.convert_to_assignable(self.ast.a[node as usize], bind);
+ }
+ t if t == tag::ASSIGN_BASE => {
+ self.ast.tag[node as usize] = tag::ASSIGN_PATTERN;
+ self.convert_to_assignable(self.ast.a[node as usize], bind);
+ }
+ // NB: This went through the first parse, and rows may have changed by now.
+ _ if self.marks => {}
+ _ => self.fail(pos, "Invalid left-hand side in assignment"),
+ }
+ }
+
+ #[inline(always)]
+ fn is_assignment(&self, node: u32) -> bool {
+ self.ast.tag[node as usize] == tag::ASSIGN_BASE
+ }
+
+ /// The target of an update or a compound assignment.
+ fn check_simple_target(&mut self, node: u32, allow_call: bool, message: &'static str) {
+ let mut inner = node;
+ while self.ast.tag[inner as usize] == tag::PAREN {
+ inner = self.ast.a[inner as usize];
+ }
+ let pos = self.ast.pos[inner as usize];
+ match self.ast.tag[inner as usize] {
+ tag::IDENT => {
+ let name = self.ast.a[inner as usize];
+ if self.strict && (name == N_EVAL || name == N_ARGUMENTS) {
+ self.fail(
+ pos,
+ "Binding pattern target may not be called 'arguments' or 'eval' in strict mode",
+ );
+ }
+ }
+ tag::MEMBER | tag::INDEX | tag::PRIVATE_MEMBER => {}
+ tag::CALL if !self.strict && allow_call => {}
+ _ if self.marks => {}
+ _ => self.fail(pos, message),
+ }
+ }
+}
diff --git a/Libraries/LibJS/Rust/src/parser/stmt.rs b/Libraries/LibJS/Rust/src/parser/stmt.rs
new file mode 100644
index 00000000000..18619763284
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/parser/stmt.rs
@@ -0,0 +1,2147 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Statements, functions, classes and modules.
+
+use super::base::*;
+use super::columns::*;
+use super::expr::is_name_like;
+use super::expr::starts_expression;
+use super::token::*;
+use super::unit::Unit;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Context {
+ /// In a statement list, where declarations are allowed.
+ List,
+ If,
+ Label,
+ /// Any other single-statement position.
+ Single,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum VarKind {
+ Var,
+ Let,
+ Const,
+ Using,
+ AwaitUsing,
+}
+
+impl VarKind {
+ fn tag(self) -> u8 {
+ match self {
+ VarKind::Var => tag::VAR,
+ VarKind::Let => tag::LET,
+ VarKind::Const => tag::CONST,
+ VarKind::Using => tag::USING,
+ VarKind::AwaitUsing => tag::AWAIT_USING,
+ }
+ }
+
+ fn bind(self) -> Bind {
+ match self {
+ VarKind::Var => Bind::Var,
+ VarKind::Let => Bind::Let,
+ _ => Bind::Const,
+ }
+ }
+}
+
+impl<U: Unit> Parser<'_, U> {
+ pub(crate) fn parse_statement_list_item(&mut self, top_level: bool) -> u32 {
+ self.parse_statement(Context::List, top_level)
+ }
+
+ fn is_let(&mut self, context: Context) -> bool {
+ if !self.is_contextual(N_LET) {
+ return false;
+ }
+ let (kind, _, _) = self.peek();
+ if kind == T::LBracket {
+ return true;
+ }
+ if context != Context::List {
+ return false;
+ }
+ if kind == T::LBrace || kind == T::Name || kind == T::EscapedKeyword {
+ return true;
+ }
+ kind as u8 >= T::KBreak as u8
+ }
+
+ fn is_async_function(&mut self) -> bool {
+ if !self.is_contextual(N_ASYNC) {
+ return false;
+ }
+ let (kind, _, newline) = self.peek();
+ kind == T::KFunction && !newline
+ }
+
+ fn is_using(&mut self, in_for: bool) -> bool {
+ if !self.is_contextual(N_USING) {
+ return false;
+ }
+ let (kind, name, newline) = self.peek();
+ if newline || kind != T::Name {
+ return false;
+ }
+ if !(in_for && name == N_OF) {
+ return true;
+ }
+ // `for (using of x)` iterates over a variable named `using`, and `for (using of = 1;;)` declares `of`.
+ let after = self.look_ahead(|parser| {
+ parser.lex();
+ parser.peek().0
+ });
+ matches!(after, T::Assign | T::Semi | T::Comma)
+ }
+
+ fn is_await_using(&mut self) -> bool {
+ if !self.is_contextual(N_AWAIT) || self.ctx & ctx::CAN_AWAIT == 0 {
+ return false;
+ }
+ self.look_ahead(|parser| {
+ parser.lex();
+ !parser.nl_before && parser.is_using(false)
+ })
+ }
+
+ pub(crate) fn parse_statement(&mut self, context: Context, top_level: bool) -> u32 {
+ if !self.enter() {
+ return 0;
+ }
+ let statement = self.parse_statement_inner(context, top_level);
+ self.leave();
+ statement
+ }
+
+ fn parse_statement_inner(&mut self, context: Context, top_level: bool) -> u32 {
+ let start = self.tok_start;
+ match self.tok {
+ T::KVar => {
+ self.next();
+ self.parse_var_statement(start, VarKind::Var)
+ }
+ T::KIf => {
+ self.next();
+ self.expect(T::LParen);
+ let test = self.parse_expression(false, false);
+ self.expect(T::RParen);
+ self.mark(tag::MARK_IF_TEST, 0);
+ self.if_start = start;
+ let consequent = self.parse_statement(Context::If, false);
+ let alternate = if self.eat(T::KElse) {
+ self.mark(tag::MARK_ELSE, 0);
+ self.if_start = start;
+ self.parse_statement(Context::If, false)
+ } else {
+ 0
+ };
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(consequent);
+ self.ast.extra.push(alternate);
+ self.ast.push(tag::IF, start, test, extra)
+ }
+ T::KReturn => {
+ if self.ctx & ctx::RETURN == 0 {
+ self.fail(start, "'return' not allowed outside of a function");
+ }
+ self.next();
+ if self.can_insert_semicolon() {
+ return self.ast.push(tag::RETURN, start, 0, 0);
+ }
+ let argument = if self.tok == T::Semi {
+ 0
+ } else {
+ self.parse_expression(false, false)
+ };
+ self.semicolon();
+ self.ast.push(tag::RETURN, start, argument, 0)
+ }
+ T::LBrace => self.parse_block(),
+ T::Semi => {
+ self.next();
+ self.ast.push(tag::EMPTY, start, 0, 0)
+ }
+ T::KFunction => {
+ if context != Context::List && (self.strict || (context != Context::If && context != Context::Label)) {
+ self.unexpected();
+ return 0;
+ }
+ self.next();
+ if context == Context::If {
+ // Annex B.3.4: as if it were in a block of its own.
+ let if_start = self.if_start;
+ let saved_block_mark = (self.block_mark, self.last_function_of_block);
+ self.block_mark = if self.marks { self.ast.tag.len() as u32 } else { NONE };
+ self.last_function_of_block = 0;
+ self.mark(tag::MARK_BLOCK, self.tok_start);
+ self.open_scope(0);
+ let node = self.parse_function_declaration(start, false, true);
+ (self.block_mark, self.last_function_of_block) = saved_block_mark;
+ let scope = self.close_scope();
+ return self.ast.push(tag::IF_FUNCTION_BLOCK, if_start, node, scope);
+ }
+ self.parse_function_declaration(start, false, context != Context::List)
+ }
+ T::KClass => {
+ if context != Context::List {
+ self.unexpected();
+ return 0;
+ }
+ self.parse_class(true)
+ }
+ T::KConst => {
+ if context != Context::List {
+ self.unexpected();
+ return 0;
+ }
+ self.next();
+ self.parse_var_statement(start, VarKind::Const)
+ }
+ T::KFor => self.parse_for(),
+ T::KWhile => {
+ self.next();
+ self.expect(T::LParen);
+ self.mark(tag::MARK_LOOP_HEAD, 0);
+ let test = self.parse_expression(false, false);
+ self.expect(T::RParen);
+ self.mark(tag::MARK_WHILE_TEST, 0);
+ self.push_loop_label();
+ let body = self.parse_statement(Context::Single, false);
+ self.labels.pop();
+ self.ast.push(tag::WHILE, start, test, body)
+ }
+ T::KDo => {
+ self.next();
+ self.mark(tag::MARK_DO_HEAD, 0);
+ self.push_loop_label();
+ let body = self.parse_statement(Context::Single, false);
+ self.labels.pop();
+ self.expect(T::KWhile);
+ self.expect(T::LParen);
+ self.mark(tag::MARK_DO_TEST, 0);
+ let test = self.parse_expression(false, false);
+ self.expect(T::RParen);
+ self.eat(T::Semi);
+ self.ast.push(tag::DO_WHILE, start, body, test)
+ }
+ T::KBreak | T::KContinue => self.parse_break_continue(),
+ T::KThrow => {
+ self.next();
+ if self.nl_before {
+ self.fail(self.prev_end, "Illegal newline after throw");
+ return 0;
+ }
+ let argument = self.parse_expression(false, false);
+ self.semicolon();
+ self.ast.push(tag::THROW, start, argument, 0)
+ }
+ T::KTry => {
+ let subtree = self.begin_subtree();
+ let statement = self.parse_try(subtree);
+ self.end_subtree(subtree, statement)
+ }
+ T::KSwitch => {
+ let subtree = self.begin_subtree();
+ let statement = self.parse_switch(subtree);
+ self.end_subtree(subtree, statement)
+ }
+ T::KWith => {
+ if self.strict {
+ self.fail(start, "'with' statement not allowed in strict mode");
+ return 0;
+ }
+ let subtree = self.begin_subtree();
+ self.next();
+ self.expect(T::LParen);
+ let object = self.parse_expression(false, false);
+ self.expect(T::RParen);
+ // A name used in the body may not be what it looks like, so that the body counts as a function of its
+ // own: whatever it uses has to stay reachable by name.
+ let summary_row = self.summary_rows[self.cur_func as usize];
+ let func = self.new_function_id(NONE);
+ self.summary_rows[func as usize] = summary_row;
+ self.open_scope_with(scope_flag::WITH, func);
+ self.with_depth += 1;
+ let body = self.parse_statement(Context::Single, false);
+ self.with_depth -= 1;
+ let scope = self.close_scope();
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(body);
+ self.ast.extra.push(scope);
+ let statement = self.ast.push(tag::WITH, start, object, extra);
+ self.end_subtree(subtree, statement)
+ }
+ T::KDebugger => {
+ self.next();
+ self.semicolon();
+ self.ast.push(tag::DEBUGGER, start, 0, 0)
+ }
+ T::KImport | T::KExport => {
+ if self.tok == T::KImport {
+ let (kind, _, _) = self.peek();
+ if kind == T::LParen || kind == T::Dot {
+ let expression = self.parse_expression(false, false);
+ self.semicolon();
+ return self.ast.push(tag::EXPR_STMT, start, expression, 0);
+ }
+ }
+ if !top_level || !self.module {
+ self.fail(
+ start,
+ "'import' and 'export' may only appear at the top level of a module",
+ );
+ return 0;
+ }
+ let subtree = self.begin_subtree();
+ let statement = if self.tok == T::KImport {
+ self.parse_import()
+ } else {
+ self.parse_export()
+ };
+ self.end_subtree(subtree, statement)
+ }
+ T::Name => self.parse_name_statement(context),
+ kind => {
+ if !starts_expression(kind) {
+ self.expected(match (context, top_level) {
+ (Context::List, true) if self.ctx & ctx::RETURN == 0 => "statement or declaration",
+ (Context::List, _) => "'}'",
+ _ => "statement",
+ });
+ return 0;
+ }
+ let expression = self.parse_expression(false, false);
+ self.semicolon();
+ self.ast.push(tag::EXPR_STMT, start, expression, 0)
+ }
+ }
+ }
+
+ fn parse_name_statement(&mut self, context: Context) -> u32 {
+ let start = self.tok_start;
+ if self.tok_name < FIRST_PLAIN_NAME {
+ if self.is_let(context) {
+ if context != Context::List {
+ self.unexpected();
+ return 0;
+ }
+ self.next();
+ return self.parse_var_statement(start, VarKind::Let);
+ }
+ if self.is_async_function() {
+ if context != Context::List {
+ self.unexpected();
+ return 0;
+ }
+ self.next();
+ self.next();
+ return self.parse_function_declaration(start, true, false);
+ }
+ if self.is_using(false) {
+ let flags = self.scopes.last().unwrap().flags;
+ let at_script_top_level = flags & scope_flag::TOP != 0 && !self.module && self.ctx & ctx::RETURN == 0;
+ if context != Context::List || at_script_top_level || flags & scope_flag::SWITCH != 0 {
+ self.fail(start, "'using' is not allowed here");
+ return 0;
+ }
+ self.next();
+ return self.parse_var_statement(start, VarKind::Using);
+ }
+ if self.is_await_using() {
+ let flags = self.scopes.last().unwrap().flags;
+ let at_script_top_level = flags & scope_flag::TOP != 0 && !self.module && self.ctx & ctx::RETURN == 0;
+ if context != Context::List || at_script_top_level || flags & scope_flag::SWITCH != 0 {
+ self.fail(start, "'await using' is not allowed here");
+ return 0;
+ }
+ if self.ctx & ctx::ASYNC == 0 {
+ self.has_top_level_await = true;
+ }
+ self.next();
+ self.next();
+ return self.parse_var_statement(start, VarKind::AwaitUsing);
+ }
+ }
+ let name = self.tok_name;
+ // A label is no use of a variable of that name, so it must not get parsed as one.
+ let next = self.at(self.pos as usize);
+ if next == 0x3A || ((next <= 0x20 || next == 0x2F) && self.peek().0 == T::Colon) {
+ self.check_identifier(name, start);
+ self.next();
+ self.next();
+ return self.parse_labeled(start, name, context);
+ }
+ let expression = self.parse_expression(false, false);
+ self.semicolon();
+ self.ast.push(tag::EXPR_STMT, start, expression, 0)
+ }
+
+ fn parse_labeled(&mut self, start: u32, name: u32, context: Context) -> u32 {
+ let subtree = self.begin_subtree();
+ let base = self.labels_base as usize;
+ let shadowed = self.label_indices.get(&name).copied();
+ if shadowed.is_some_and(|index| index as usize >= base) {
+ let label = String::from_utf8_lossy(self.interner.text(name)).into_owned();
+ self.fail_with(start, format!("Label '{label}' has already been declared"));
+ return 0;
+ }
+ let kind = match self.tok {
+ T::KFor | T::KWhile | T::KDo => 1,
+ T::KSwitch => 2,
+ _ => 0,
+ };
+ for i in (base..self.labels.len()).rev() {
+ let label = &mut self.labels[i];
+ if label.statement_start == start {
+ label.statement_start = self.tok_start;
+ label.kind = kind;
+ } else {
+ break;
+ }
+ }
+ self.label_indices.insert(name, self.labels.len() as u32);
+ self.labels.push(Label {
+ kind,
+ statement_start: self.tok_start,
+ });
+ let body_context = match context {
+ Context::If | Context::Single => Context::Single,
+ _ => Context::Label,
+ };
+ let body = self.parse_statement(body_context, false);
+ self.labels.pop();
+ match shadowed {
+ Some(index) => self.label_indices.insert(name, index),
+ None => self.label_indices.remove(&name),
+ };
+ let statement = self.ast.push(tag::LABELED, start, name, body);
+ self.end_subtree(subtree, statement)
+ }
+
+ #[inline(always)]
+ fn push_loop_label(&mut self) {
+ self.labels.push(Label {
+ kind: 1,
+ statement_start: NONE,
+ });
+ }
+
+ fn parse_break_continue(&mut self) -> u32 {
+ let start = self.tok_start;
+ let is_break = self.tok == T::KBreak;
+ self.next();
+ let mut name = NONE;
+ let mut name_pos = start;
+ if !self.eat(T::Semi) && !self.can_insert_semicolon() {
+ if self.tok != T::Name {
+ self.unexpected();
+ return 0;
+ }
+ (name, name_pos) = self.parse_ident();
+ self.semicolon();
+ }
+ let base = self.labels_base as usize;
+ let found = if name == NONE {
+ self.labels[base..]
+ .iter()
+ .rev()
+ .any(|label| label.kind != 0 && (is_break || label.kind == 1))
+ } else {
+ self.label_indices.get(&name).is_some_and(|&index| {
+ let label = &self.labels[index as usize];
+ index as usize >= base && (is_break || label.kind == 1)
+ })
+ };
+ if !found {
+ let message = if name == NONE {
+ if is_break {
+ "Unlabeled 'break' not allowed outside of a loop or switch statement".to_string()
+ } else {
+ "'continue' not allowed outside of a loop".to_string()
+ }
+ } else {
+ let label = String::from_utf8_lossy(self.interner.text(name)).into_owned();
+ let is_in_scope = self
+ .label_indices
+ .get(&name)
+ .is_some_and(|&index| index as usize >= base);
+ if is_in_scope {
+ "labelled continue statement cannot use non iterating statement".to_string()
+ } else {
+ format!("Label '{label}' not found")
+ }
+ };
+ self.fail_with(name_pos, message);
+ }
+ self.ast
+ .push(if is_break { tag::BREAK } else { tag::CONTINUE }, start, name, 0)
+ }
+
+ fn parse_block(&mut self) -> u32 {
+ let start = self.tok_start;
+ let saved_block_mark = (self.block_mark, self.last_function_of_block);
+ self.block_mark = if self.marks { self.ast.tag.len() as u32 } else { NONE };
+ self.last_function_of_block = 0;
+ self.mark(tag::MARK_BLOCK, start);
+ self.open_scope(0);
+ let list = self.parse_block_statements();
+ (self.block_mark, self.last_function_of_block) = saved_block_mark;
+ let scope = self.close_scope();
+ self.ast.push(tag::BLOCK, start, list, scope)
+ }
+
+ /// The statements from the `{` through the `}`.
+ fn parse_block_statements(&mut self) -> u32 {
+ self.next();
+ let mark = self.scratch.len();
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let statement = self.parse_statement(Context::List, false);
+ self.scratch.push(statement);
+ }
+ self.expect(T::RBrace);
+ let list = self.finish_list(mark);
+ // A block's list is followed by where the code after the block starts.
+ self.ast.extra.push(self.tok_start);
+ list
+ }
+
+ fn parse_var_statement(&mut self, start: u32, kind: VarKind) -> u32 {
+ let list = self.parse_var_declarators(kind, false, start);
+ self.semicolon();
+ self.ast.push(kind.tag(), start, list, 0)
+ }
+
+ fn parse_var_declarators(&mut self, kind: VarKind, is_for: bool, statement_start: u32) -> u32 {
+ let mark = self.scratch.len();
+ loop {
+ let start = self.tok_start;
+ if (kind == VarKind::Using || kind == VarKind::AwaitUsing) && self.tok != T::Name {
+ self.unexpected();
+ break;
+ }
+ let bind = kind.bind();
+ let is_pattern = matches!(self.tok, T::LBracket | T::LBrace);
+ let subtree = if is_pattern { self.begin_subtree() } else { NONE };
+ if subtree != NONE {
+ self.ast.b[subtree as usize] = u32::from(kind.tag());
+ self.ast.pos[subtree as usize] = statement_start;
+ }
+ let target = self.parse_binding_atom(bind);
+ if !is_pattern {
+ self.mark(tag::MARK_DECLARATION, u32::from(kind.tag()));
+ }
+ let mut init = 0;
+ if self.eat(T::Assign) {
+ init = self.parse_assign(is_for, false);
+ } else {
+ let in_for_head = is_for && (self.tok == T::KIn || self.is_contextual(N_OF));
+ let needs_init = kind == VarKind::Const
+ || kind == VarKind::Using
+ || kind == VarKind::AwaitUsing
+ || !self.is_identifier_row(target);
+ if needs_init && !in_for_head {
+ self.fail(self.prev_end, "Missing initializer in declaration");
+ break;
+ }
+ }
+ let declarator = self.ast.push(tag::DECLARATOR, start, target, init);
+ self.end_subtree(subtree, declarator);
+ self.scratch.push(declarator);
+ if !self.eat(T::Comma) {
+ break;
+ }
+ }
+ self.finish_list(mark)
+ }
+
+ /// A binding identifier or pattern, whose names get declared as `bind`.
+ pub(crate) fn parse_binding_atom(&mut self, bind: Bind) -> u32 {
+ if self.tok != T::LBracket && self.tok != T::LBrace {
+ return self.parse_binding_atom_inner(bind);
+ }
+ if !self.enter() {
+ return 0;
+ }
+ let atom = self.parse_binding_atom_inner(bind);
+ self.leave();
+ atom
+ }
+
+ fn parse_binding_atom_inner(&mut self, bind: Bind) -> u32 {
+ let start = self.tok_start;
+ match self.tok {
+ T::Name => {
+ let name = self.tok_name;
+ if name == N_LET && matches!(bind, Bind::Let | Bind::Const | Bind::Lexical) {
+ self.fail(start, "'let' is disallowed as a lexically bound name");
+ return 0;
+ }
+ self.check_binding_name(name, start);
+ if name == N_ARGUMENTS || name == N_EVAL {
+ self.might_need_arguments = true;
+ }
+ self.declare(name, bind, start);
+ self.next();
+ self.ast.push(tag::IDENT, start, name, 0)
+ }
+ T::LBracket => {
+ self.next();
+ let mark = self.scratch.len();
+ while self.tok != T::RBracket && self.tok != T::Eof {
+ let item = match self.tok {
+ T::Comma => self.ast.push(tag::HOLE, self.tok_start, 0, 0),
+ T::Ellipsis => {
+ let item_start = self.tok_start;
+ self.next();
+ let target = self.parse_binding_atom(bind);
+ if self.tok != T::RBracket {
+ self.fail(self.tok_start, "Rest element may not be followed by a comma");
+ }
+ self.ast.push(tag::REST, item_start, target, 0)
+ }
+ _ => self.parse_binding_element(bind),
+ };
+ self.scratch.push(item);
+ if self.tok != T::RBracket {
+ self.expect_comma_or(T::RBracket);
+ }
+ }
+ self.expect(T::RBracket);
+ let list = self.finish_list(mark);
+ self.ast.push(tag::ARRAY_PATTERN, start, list, 0)
+ }
+ T::LBrace => {
+ self.next();
+ let mark = self.scratch.len();
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let property = self.parse_binding_property(bind);
+ self.scratch.push(property);
+ if self.tok != T::RBrace {
+ self.expect_comma_or(T::RBrace);
+ }
+ }
+ self.expect(T::RBrace);
+ let list = self.finish_list(mark);
+ self.ast.push(tag::OBJECT_PATTERN, start, list, 0)
+ }
+ _ => {
+ self.unexpected();
+ 0
+ }
+ }
+ }
+
+ fn parse_binding_property(&mut self, bind: Bind) -> u32 {
+ let start = self.tok_start;
+ if self.tok == T::Ellipsis {
+ self.next();
+ if self.tok != T::Name {
+ self.unexpected();
+ return 0;
+ }
+ let target = self.parse_binding_atom(bind);
+ if self.tok != T::RBrace {
+ self.fail(self.tok_start, "Rest element may not be followed by a comma");
+ }
+ return self.ast.push(tag::REST, start, target, 0);
+ }
+ let key_kind = self.tok;
+ let key_name = self.tok_name;
+ let (key, computed) = self.parse_property_name();
+ if self.eat(T::Colon) {
+ let value = self.parse_binding_element(bind);
+ let t = if computed {
+ tag::COMPUTED_PROPERTY
+ } else {
+ tag::PROPERTY
+ };
+ return self.ast.push(t, start, key, value);
+ }
+ if computed || key_kind != T::Name {
+ self.unexpected();
+ return 0;
+ }
+ if key_name == N_LET && matches!(bind, Bind::Let | Bind::Const | Bind::Lexical) {
+ self.fail(start, "'let' is disallowed as a lexically bound name");
+ return 0;
+ }
+ self.check_binding_name(key_name, start);
+ self.declare(key_name, bind, start);
+ let mut value = key;
+ if self.eat(T::Assign) {
+ let default = self.parse_assign(false, false);
+ value = self.ast.push(tag::ASSIGN_PATTERN, start, value, default);
+ }
+ self.ast.push(tag::SHORTHAND, start, key_name, value)
+ }
+
+ fn parse_binding_element(&mut self, bind: Bind) -> u32 {
+ let start = self.tok_start;
+ let target = self.parse_binding_atom(bind);
+ if self.eat(T::Assign) {
+ let default = self.parse_assign(false, false);
+ return self.ast.push(tag::ASSIGN_PATTERN, start, target, default);
+ }
+ target
+ }
+
+ fn parse_for(&mut self) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ let mut await_at = NONE;
+ if self.ctx & ctx::CAN_AWAIT != 0 && self.is_contextual(N_AWAIT) {
+ await_at = self.tok_start;
+ if self.ctx & ctx::ASYNC == 0 {
+ self.has_top_level_await = true;
+ }
+ self.next();
+ }
+ self.push_loop_label();
+ let subtree = self.begin_subtree();
+ self.open_scope(0);
+ self.expect(T::LParen);
+ let node = self.parse_for_head(start, await_at);
+ let scope = self.close_scope();
+ self.labels.pop();
+ let statement = self.ast.push(tag::SCOPED, start, node, scope);
+ self.end_subtree(subtree, statement)
+ }
+
+ fn parse_for_head(&mut self, start: u32, await_at: u32) -> u32 {
+ if self.tok == T::Semi {
+ if await_at != NONE {
+ self.fail(await_at, "Unexpected await");
+ }
+ return self.parse_plain_for(start, 0);
+ }
+ let is_let = self.is_let(Context::List);
+ let is_using = self.is_using(true);
+ let is_await_using = !is_let && !is_using && self.is_await_using();
+ if self.tok == T::KVar || self.tok == T::KConst || is_let || is_using || is_await_using {
+ let kind = if is_let {
+ VarKind::Let
+ } else if is_using {
+ VarKind::Using
+ } else if is_await_using {
+ VarKind::AwaitUsing
+ } else if self.tok == T::KVar {
+ VarKind::Var
+ } else {
+ VarKind::Const
+ };
+ let init_start = self.tok_start;
+ self.next();
+ if is_await_using {
+ if self.ctx & ctx::ASYNC == 0 {
+ self.has_top_level_await = true;
+ }
+ self.next();
+ }
+ let list = self.parse_var_declarators(kind, true, init_start);
+ let init = self.ast.push(kind.tag(), init_start, list, 0);
+ if (self.tok == T::KIn || self.is_contextual(N_OF)) && self.list(list).len() == 1 {
+ let is_in = self.tok == T::KIn;
+ if is_in && (await_at != NONE || kind == VarKind::Using || kind == VarKind::AwaitUsing) {
+ self.unexpected();
+ return 0;
+ }
+ let declarator = self.list(list)[0];
+ let has_init = self.ast.b[declarator as usize] != 0;
+ if has_init {
+ let target = self.ast.a[declarator as usize];
+ let allowed = is_in && !self.strict && kind == VarKind::Var && self.is_identifier_row(target);
+ if !allowed {
+ self.fail(init_start, "Variable initializer not allowed in for..in/of");
+ return 0;
+ }
+ }
+ return self.parse_for_in(start, init, await_at);
+ }
+ if await_at != NONE {
+ self.fail(await_at, "Unexpected await");
+ }
+ if kind != VarKind::Var {
+ // The initializer check waits until here, since `const x` is fine before `of`.
+ }
+ return self.parse_plain_for(start, init);
+ }
+ let starts_with_let = self.is_contextual(N_LET);
+ let starts_with_async = self.is_contextual(N_ASYNC);
+ let init_start = self.tok_start;
+ let saved_cover_error = self.cover_error;
+ self.cover_error = NONE;
+ self.for_await_head = await_at != NONE;
+ let init = if await_at != NONE {
+ self.parse_left_hand_side(false)
+ } else {
+ self.parse_expression(true, true)
+ };
+ self.for_await_head = false;
+ let is_of = self.is_contextual(N_OF);
+ if self.tok == T::KIn || is_of {
+ if await_at != NONE && !is_of {
+ self.unexpected();
+ return 0;
+ }
+ if is_of && await_at == NONE && starts_with_async {
+ let is_plain_async =
+ self.ast.tag[init as usize] == tag::IDENT && self.ast.pos[init as usize] == init_start;
+ if is_plain_async {
+ self.unexpected();
+ return 0;
+ }
+ }
+ if starts_with_let && is_of {
+ self.fail(init_start, "The left-hand side of a for-of loop may not be 'let'");
+ return 0;
+ }
+ if self.ast.tag[init as usize] >= tag::ASSIGN_BASE && self.ast.tag[init as usize] < tag::BINARY_BASE {
+ self.fail(init_start, "Invalid left-hand side in for loop");
+ return 0;
+ }
+ self.convert_assignment_target(init);
+ self.cover_error = saved_cover_error;
+ return self.parse_for_in(start, init, await_at);
+ }
+ if self.cover_error != NONE {
+ self.fail(
+ self.cover_error,
+ "Shorthand property initializers are only valid in patterns",
+ );
+ }
+ self.cover_error = saved_cover_error;
+ if await_at != NONE {
+ self.fail(await_at, "Unexpected await");
+ }
+ self.parse_plain_for(start, init)
+ }
+
+ fn parse_plain_for(&mut self, start: u32, init: u32) -> u32 {
+ // A `const` or pattern without an initializer got past the declarator only for a for-in or for-of head.
+ if init != 0
+ && matches!(
+ self.ast.tag[init as usize],
+ tag::CONST | tag::USING | tag::AWAIT_USING | tag::LET | tag::VAR
+ )
+ {
+ let list = self.ast.a[init as usize];
+ let kind = self.ast.tag[init as usize];
+ for i in 0..self.ast.extra[list as usize] {
+ let declarator = self.ast.extra[(list + 1 + i) as usize];
+ let missing = self.ast.b[declarator as usize] == 0;
+ let pattern = !self.is_identifier_row(self.ast.a[declarator as usize]);
+ if missing && (pattern || (kind != tag::LET && kind != tag::VAR)) {
+ self.fail(start, "Missing initializer in declaration");
+ }
+ }
+ }
+ self.expect(T::Semi);
+ let test = if self.tok == T::Semi {
+ 0
+ } else {
+ self.parse_expression(false, false)
+ };
+ self.expect(T::Semi);
+ let update = if self.tok == T::RParen {
+ 0
+ } else {
+ self.parse_expression(false, false)
+ };
+ self.expect(T::RParen);
+ let body = self.parse_statement(Context::Single, false);
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(test);
+ self.ast.extra.push(update);
+ self.ast.extra.push(body);
+ self.ast.push(tag::FOR, start, init, extra)
+ }
+
+ fn parse_for_in(&mut self, _start: u32, left: u32, await_at: u32) -> u32 {
+ let is_in = self.tok == T::KIn;
+ let start = self.tok_start;
+ self.next();
+ let right = if is_in {
+ self.parse_expression(false, false)
+ } else {
+ self.parse_assign(false, false)
+ };
+ self.expect(T::RParen);
+ let body = self.parse_statement(Context::Single, false);
+ let t = if is_in {
+ tag::FOR_IN
+ } else if await_at != NONE {
+ tag::FOR_AWAIT_OF
+ } else {
+ tag::FOR_OF
+ };
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(right);
+ self.ast.extra.push(body);
+ self.ast.push(t, start, left, extra)
+ }
+
+ fn parse_try(&mut self, subtree: u32) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ if self.tok != T::LBrace {
+ self.unexpected();
+ return 0;
+ }
+ let block = self.parse_block();
+ let mut parameter = 0;
+ let mut handler = 0;
+ let mut catch_scope = NONE;
+ let catch_pos = self.tok_start;
+ if self.tok == T::KCatch {
+ self.next();
+ self.open_scope(scope_flag::CATCH);
+ self.scopes.last_mut().expect("the scope just opened").start = catch_pos;
+ if self.eat(T::LParen) {
+ let simple = self.tok == T::Name;
+ parameter = self.parse_binding_atom(if simple { Bind::SimpleCatch } else { Bind::CatchPattern });
+ self.expect(T::RParen);
+ }
+ if self.tok != T::LBrace {
+ self.unexpected();
+ self.close_scope();
+ return 0;
+ }
+ let handler_start = self.tok_start;
+ self.open_scope(scope_flag::CATCH_BODY);
+ let saved_block_mark = (self.block_mark, self.last_function_of_block);
+ self.block_mark = subtree;
+ self.last_function_of_block = 0;
+ let list = self.parse_block_statements();
+ (self.block_mark, self.last_function_of_block) = saved_block_mark;
+ let body_scope = self.close_scope();
+ catch_scope = self.close_scope();
+ handler = self.ast.push(tag::BLOCK, handler_start, list, body_scope);
+ }
+ let finalizer = if self.tok == T::KFinally {
+ self.next();
+ if self.tok != T::LBrace {
+ self.unexpected();
+ return 0;
+ }
+ self.parse_block()
+ } else {
+ 0
+ };
+ if handler == 0 && finalizer == 0 {
+ self.fail(start, "Missing catch or finally clause");
+ }
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(parameter);
+ self.ast.extra.push(handler);
+ self.ast.extra.push(finalizer);
+ self.ast.extra.push(catch_pos);
+ self.ast.extra.push(catch_scope);
+ self.ast.push(tag::TRY, start, block, extra)
+ }
+
+ fn parse_switch(&mut self, subtree: u32) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ self.expect(T::LParen);
+ let discriminant = self.parse_expression(false, false);
+ self.expect(T::RParen);
+ self.expect(T::LBrace);
+ self.labels.push(Label {
+ kind: 2,
+ statement_start: NONE,
+ });
+ self.open_scope(scope_flag::SWITCH);
+ self.scopes.last_mut().expect("the scope just opened").start = start;
+ let saved_block_mark = (self.block_mark, self.last_function_of_block);
+ self.block_mark = subtree;
+ self.last_function_of_block = 0;
+ let mark = self.scratch.len();
+ let mut saw_default = false;
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let case_start = self.tok_start;
+ let test = if self.eat(T::KCase) {
+ self.parse_expression(false, false)
+ } else if self.tok == T::KDefault {
+ if saw_default {
+ self.fail(case_start, "Multiple default clauses");
+ }
+ saw_default = true;
+ self.next();
+ 0
+ } else {
+ self.unexpected();
+ 0
+ };
+ self.expect(T::Colon);
+ let statements_mark = self.scratch.len();
+ while !matches!(self.tok, T::KCase | T::KDefault | T::RBrace | T::Eof) {
+ let statement = self.parse_statement(Context::List, false);
+ self.scratch.push(statement);
+ }
+ let statements = self.finish_list(statements_mark);
+ let case = self.ast.push(tag::CASE, case_start, test, statements);
+ self.scratch.push(case);
+ }
+ self.expect(T::RBrace);
+ (self.block_mark, self.last_function_of_block) = saved_block_mark;
+ let scope = self.close_scope();
+ self.labels.pop();
+ let list = self.finish_list(mark);
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(list);
+ self.ast.extra.push(scope);
+ self.ast.push(tag::SWITCH, start, discriminant, extra)
+ }
+
+ // === Functions ===
+
+ pub(crate) fn empty_function_state(&self) -> FunctionState {
+ FunctionState {
+ marks: self.ast.marks(),
+ row: 0,
+ ctx: 0,
+ strict: false,
+ labels_base: 0,
+ yield_pos: 0,
+ await_pos: 0,
+ await_ident_pos: 0,
+ cover_error: 0,
+ retain: false,
+ duplicate_parameter: 0,
+ start: 0,
+ flags: 0,
+ has_body_scope: false,
+ body_start: 0,
+ first_body_row: 0,
+ uses_this: false,
+ uses_this_from_environment: false,
+ might_need_arguments: false,
+ in_class_of_sloppy_function: self.in_class_of_sloppy_function,
+ is_arrow: false,
+ summary_ordinal: 0,
+ }
+ }
+
+ fn function_ctx(is_generator: bool, is_async: bool) -> u32 {
+ let mut c = ctx::RETURN | ctx::NEW_TARGET;
+ if is_generator {
+ c |= ctx::GENERATOR;
+ }
+ if is_async {
+ c |= ctx::ASYNC | ctx::CAN_AWAIT;
+ }
+ c
+ }
+
+ fn function_flags(is_generator: bool, is_async: bool) -> u32 {
+ (if is_generator { function_flag::GENERATOR } else { 0 }) | (if is_async { function_flag::ASYNC } else { 0 })
+ }
+
+ /// From after `function`.
+ fn parse_function_declaration(&mut self, start: u32, is_async: bool, hanging: bool) -> u32 {
+ if self.tok == T::Star && hanging {
+ self.unexpected();
+ return 0;
+ }
+ let is_generator = self.eat(T::Star);
+ let (name, name_pos) = self.parse_ident();
+ if is_generator && is_async && (name == N_AWAIT || name == N_YIELD) {
+ let text = String::from_utf8_lossy(self.interner.text(name)).into_owned();
+ self.fail_with(
+ name_pos,
+ format!("async generator function is not allowed to be called '{text}'"),
+ );
+ }
+ if !hanging {
+ let bind = if self.strict || is_generator || is_async {
+ if self.treat_functions_as_var() {
+ Bind::Var
+ } else {
+ Bind::Lexical
+ }
+ } else {
+ Bind::Function
+ };
+ self.declare(name, bind, name_pos);
+ if bind == Bind::Function {
+ self.queue_annex_b_hoist(name);
+ }
+ } else {
+ self.declare(name, Bind::Function, name_pos);
+ self.queue_annex_b_hoist(name);
+ }
+ let node = self.parse_function_rest(start, Some((name, name_pos)), is_generator, is_async);
+ if self.marks && self.block_mark != NONE {
+ // NB: These run when the block starts, which a sweep gets to from the mark of the block.
+ if self.last_function_of_block == 0 {
+ self.ast.b[self.block_mark as usize] = node;
+ } else {
+ self.ast.a[self.last_function_of_block as usize] = node;
+ }
+ self.last_function_of_block = node;
+ }
+ self.ast.push(tag::FUNCTION_DECL, start, node, name)
+ }
+
+ /// From after `function`.
+ pub(crate) fn parse_function_expression(&mut self, start: u32, is_async: bool) -> u32 {
+ let is_generator = self.eat(T::Star);
+ let new_ctx = Self::function_ctx(is_generator, is_async);
+ let flags = Self::function_flags(is_generator, is_async);
+ let mut state = self.begin_function(start, new_ctx, flags);
+ let mut name = None;
+ if self.tok == T::Name {
+ state.flags |= function_flag::NAMED_EXPRESSION;
+ let parsed = self.parse_ident();
+ if parsed.0 == N_ARGUMENTS || parsed.0 == N_EVAL {
+ self.might_need_arguments = true;
+ }
+ self.declare_function_name(parsed.0);
+ name = Some(parsed);
+ }
+ self.parse_function_tail(&mut state, name, false)
+ }
+
+ fn parse_function_rest(&mut self, start: u32, name: Option<(u32, u32)>, is_generator: bool, is_async: bool) -> u32 {
+ let new_ctx = Self::function_ctx(is_generator, is_async);
+ let flags = Self::function_flags(is_generator, is_async);
+ let mut state = self.begin_function(start, new_ctx, flags);
+ if let Some((name, _)) = name
+ && (name == N_ARGUMENTS || name == N_EVAL)
+ {
+ self.might_need_arguments = true;
+ }
+ self.parse_function_tail(&mut state, name, false)
+ }
+
+ /// The parameter list, from the `(`.
+ pub(crate) fn parse_parameter_list(&mut self, state: &mut FunctionState) -> (u32, u32, u32, bool, bool) {
+ let params_start = self.tok_start;
+ self.expect(T::LParen);
+ let mark = self.scratch.len();
+ let mut simple = true;
+ let mut has_rest = false;
+ let mut length = 0;
+ let mut counting = true;
+ while self.tok != T::RParen && self.tok != T::Eof {
+ let item_start = self.tok_start;
+ let item = if self.tok == T::Ellipsis {
+ self.next();
+ let target = self.parse_binding_atom(Bind::Parameter);
+ has_rest = true;
+ simple = false;
+ counting = false;
+ if self.tok != T::RParen {
+ self.fail(self.tok_start, "Rest parameter must be last");
+ }
+ self.ast.push(tag::REST, item_start, target, 0)
+ } else {
+ let item = self.parse_binding_element(Bind::Parameter);
+ let t = self.ast.tag[item as usize];
+ simple &= t == tag::IDENT;
+ counting &= t != tag::ASSIGN_PATTERN;
+ if counting {
+ length += 1;
+ }
+ item
+ };
+ self.scratch.push(item);
+ if self.tok != T::RParen {
+ self.expect_comma_or(T::RParen);
+ }
+ }
+ self.expect(T::RParen);
+ let count = (self.scratch.len() - mark) as u32;
+ let list = self.finish_list(mark);
+ if self.yield_pos != 0 || self.await_pos != 0 {
+ self.fail(params_start, "Yield or await expression in function parameters");
+ }
+ if simple {
+ state.flags |= function_flag::SIMPLE_PARAMETERS;
+ }
+ (list, count, length, simple, has_rest)
+ }
+
+ pub(crate) fn parse_function_tail(
+ &mut self,
+ state: &mut FunctionState,
+ name: Option<(u32, u32)>,
+ is_method: bool,
+ ) -> u32 {
+ self.parse_function_tail_with_info(state, name, is_method).0
+ }
+
+ /// The parameters and the body, from the `(`. Returns the node, the parameter count and whether there is a rest
+ /// parameter.
+ fn parse_function_tail_with_info(
+ &mut self,
+ state: &mut FunctionState,
+ name: Option<(u32, u32)>,
+ is_method: bool,
+ ) -> (u32, u32, bool) {
+ let params_start = self.tok_start;
+ if let Some(row) = self.skippable_row(params_start) {
+ let moved_state = core::mem::replace(state, self.empty_function_state());
+ let node = self.skip_function(moved_state, row);
+ return (node, 0, false);
+ }
+ let (list, count, length, simple, has_rest) = self.parse_parameter_list(state);
+ if self.tok != T::LBrace {
+ self.unexpected();
+ }
+ state.body_start = self.pos;
+ let body = self.parse_function_body(state, name, list, simple, false, is_method);
+ let end = self.prev_end;
+ let moved_state = core::mem::replace(state, self.empty_function_state());
+ let name = name.map_or(NONE, |(name, _)| name);
+ let node = self.end_function(moved_state, end, count, length, params_start, list, body, name, false);
+ (node, count, has_rest)
+ }
+
+ /// The statements of a function, from the `{` through the `}`.
+ pub(crate) fn parse_function_body(
+ &mut self,
+ state: &mut FunctionState,
+ name: Option<(u32, u32)>,
+ parameters: u32,
+ simple: bool,
+ is_arrow: bool,
+ is_method: bool,
+ ) -> u32 {
+ let old_strict = self.strict;
+ let mut use_strict = false;
+ if !old_strict || !simple {
+ use_strict = self.has_use_strict_directive(self.tok_end as usize);
+ if use_strict && !simple {
+ self.fail(
+ self.tok_start,
+ "Illegal 'use strict' directive in function with non-simple parameter list",
+ );
+ }
+ }
+ if use_strict {
+ self.strict = true;
+ }
+ if self.duplicate_parameter != NONE && (self.strict || !simple || is_arrow || is_method) {
+ self.fail(self.duplicate_parameter, "Duplicate parameter names not allowed");
+ }
+ if self.strict {
+ if let Some((name, pos)) = name {
+ self.check_strict_binding_name(name, pos);
+ }
+ if !old_strict {
+ let count = self.ast.extra[parameters as usize];
+ for i in 0..count {
+ let parameter = self.ast.extra[(parameters + 1 + i) as usize];
+ if self.ast.tag[parameter as usize] == tag::IDENT {
+ let (name, pos) = (self.ast.a[parameter as usize], self.ast.pos[parameter as usize]);
+ self.check_strict_binding_name(name, pos);
+ }
+ }
+ }
+ }
+ if !simple {
+ self.open_function_body_scope(state);
+ }
+ self.next();
+ state.body_start = self.tok_start;
+ state.first_body_row = self.ast.tag.len() as u32;
+ let mark = self.scratch.len();
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let statement = self.parse_statement(Context::List, false);
+ self.scratch.push(statement);
+ }
+ self.expect(T::RBrace);
+ self.finish_list(mark)
+ }
+
+ /// A method's function, from the `(`. Returns its node, its parameter count and whether it has a rest parameter.
+ pub(crate) fn parse_method(
+ &mut self,
+ start: u32,
+ is_generator: bool,
+ is_async: bool,
+ super_call: bool,
+ ) -> (u32, u32, bool) {
+ let mut new_ctx = Self::function_ctx(is_generator, is_async) | ctx::SUPER_PROPERTY;
+ if super_call {
+ new_ctx |= ctx::SUPER_CALL;
+ }
+ let flags = Self::function_flags(is_generator, is_async) | function_flag::METHOD;
+ let mut state = self.begin_function(start, new_ctx, flags);
+ self.parse_function_tail_with_info(&mut state, None, true)
+ }
+
+ // === Classes ===
+
+ pub(crate) fn parse_class(&mut self, is_statement: bool) -> u32 {
+ let subtree = self.begin_subtree();
+ let class = self.parse_class_with_its_rows(is_statement);
+ self.end_subtree(subtree, class)
+ }
+
+ fn parse_class_with_its_rows(&mut self, is_statement: bool) -> u32 {
+ if !self.enter() {
+ return 0;
+ }
+ let class = self.parse_class_inner(is_statement);
+ self.leave();
+ class
+ }
+
+ fn parse_class_inner(&mut self, is_statement: bool) -> u32 {
+ let start = self.tok_start;
+ let saved_class_start = core::mem::replace(&mut self.class_start, start);
+ self.next();
+ let old_strict = self.strict;
+ let was_in_class_of_sloppy_function = self.in_class_of_sloppy_function;
+ self.in_class_of_sloppy_function |= !old_strict;
+ self.strict = true;
+ let mut name = NONE;
+ if self.tok == T::Name && !(self.is_contextual(N_IMPLEMENTS)) {
+ let (parsed, pos) = self.parse_ident();
+ self.check_binding_name(parsed, pos);
+ if parsed == N_LET {
+ self.fail(pos, "'let' is disallowed as a lexically bound name");
+ }
+ name = parsed;
+ if is_statement {
+ self.declare(name, Bind::Lexical, pos);
+ }
+ } else if is_statement {
+ self.unexpected();
+ }
+ self.open_scope(scope_flag::CLASS);
+ if name != NONE {
+ self.declare_class_name(name);
+ }
+ let mut super_class = 0;
+ if self.eat(T::KExtends) {
+ super_class = self.parse_left_hand_side(false);
+ }
+ self.class_marks
+ .push((self.private_declared.len() as u32, self.private_used.len() as u32));
+ self.private_declared.push(std::collections::HashMap::new());
+ self.expect(T::LBrace);
+ let mark = self.scratch.len();
+ let mut had_constructor = false;
+ let mut constructor = 0;
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ if self.eat(T::Semi) {
+ continue;
+ }
+ let was_constructor = had_constructor;
+ let element = self.parse_class_element(super_class != 0, &mut had_constructor);
+ if had_constructor && !was_constructor {
+ constructor = self.ast.b[element as usize];
+ }
+ // The constructor stays in the list, so that the list keeps the elements in source order.
+ self.scratch.push(element);
+ }
+ self.strict = old_strict;
+ self.in_class_of_sloppy_function = was_in_class_of_sloppy_function;
+ self.class_start = saved_class_start;
+ self.expect(T::RBrace);
+ self.exit_class_body();
+ let list = self.finish_list(mark);
+ let scope = self.close_scope();
+ let default_constructor_row = if had_constructor {
+ NONE
+ } else {
+ let derived = if super_class != 0 {
+ function_flag::DERIVED_CONSTRUCTOR
+ } else {
+ 0
+ };
+ self.class_function_row(start, start, function_flag::DEFAULT_CONSTRUCTOR | derived, name, NONE)
+ };
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(super_class);
+ self.ast.extra.push(list);
+ self.ast.extra.push(scope);
+ self.ast.extra.push(constructor);
+ self.ast.extra.push(self.prev_end);
+ self.ast.extra.push(default_constructor_row);
+ let node = self.ast.push(tag::CLASS, start, name, extra);
+ if is_statement {
+ return self.ast.push(tag::CLASS_DECL, start, node, 0);
+ }
+ node
+ }
+
+ fn exit_class_body(&mut self) {
+ let (_, used_mark) = self.class_marks.pop().unwrap();
+ let declared = self.private_declared.pop().unwrap();
+ let mut kept = used_mark as usize;
+ let is_outermost = self.class_marks.is_empty();
+ for i in used_mark as usize..self.private_used.len() {
+ let (name, pos) = self.private_used[i];
+ if declared.contains_key(&name) {
+ continue;
+ }
+ if is_outermost {
+ self.report_undeclared_private_name(name, pos);
+ continue;
+ }
+ self.private_used[kept] = (name, pos);
+ kept += 1;
+ }
+ self.private_used.truncate(kept);
+ }
+
+ pub(crate) fn check_unresolved_private_names(&mut self) {
+ for (name, pos) in std::mem::take(&mut self.private_used) {
+ self.report_undeclared_private_name(name, pos);
+ }
+ }
+
+ /// The code around an eval may declare the name, which the eval's caller finds out.
+ fn report_undeclared_private_name(&mut self, name: u32, pos: u32) {
+ if self.initiated_by_eval {
+ if !self.eval_referenced_private_names.contains(&name) {
+ self.eval_referenced_private_names.push(name);
+ }
+ return;
+ }
+ let name = String::from_utf8_lossy(self.interner.text(name)).into_owned();
+ self.fail_with(
+ pos,
+ format!("Reference to undeclared private field or method '#{name}'"),
+ );
+ }
+
+ /// `kind` is 0 for a field or a method, 1 and 2 for instance accessors, 3 and 4 for static ones.
+ fn declare_private_name(&mut self, name: u32, kind: u8, pos: u32) {
+ let declared = self.private_declared.last_mut().unwrap();
+ match declared.get_mut(&name) {
+ Some(previous) => {
+ let pair = (*previous == 1 && kind == 2)
+ || (*previous == 2 && kind == 1)
+ || (*previous == 3 && kind == 4)
+ || (*previous == 4 && kind == 3);
+ if pair {
+ *previous = 0;
+ } else {
+ self.fail(pos, "Duplicate private field or method");
+ }
+ }
+ None => {
+ declared.insert(name, kind);
+ }
+ }
+ }
+
+ fn is_class_element_name_start(&self) -> bool {
+ is_name_like(self.tok) || matches!(self.tok, T::PrivateName | T::Num | T::BigInt | T::Str | T::LBracket)
+ }
+
+ fn key_is(&self, key: u32, computed: bool, word: u32, text: &[u8]) -> bool {
+ if computed {
+ return false;
+ }
+ match self.ast.tag[key as usize] {
+ tag::IDENT | tag::IDENT_KEY => self.ast.a[key as usize] == word,
+ tag::STR | tag::STR_KEY => {
+ let start = self.ast.pos[key as usize] as usize;
+ self.ast.a[key as usize] as usize - start == text.len() + 2
+ && (0..text.len()).all(|i| self.at(start + 1 + i) == text[i] as u32)
+ }
+ _ => false,
+ }
+ }
+
+ fn parse_class_element(&mut self, has_super_class: bool, had_constructor: &mut bool) -> u32 {
+ let start = self.tok_start;
+ let mut key_name = NONE;
+ let mut is_static = false;
+ let mut is_async = false;
+ let mut is_generator = false;
+ let mut accessor = 0; // 1 for a getter, 2 for a setter.
+ let mut method_start = start;
+
+ if self.is_contextual(N_STATIC) {
+ self.next();
+ method_start = self.tok_start;
+ if self.tok == T::LBrace {
+ return self.parse_class_static_block(self.tok_start, start);
+ }
+ if self.is_class_element_name_start() || self.tok == T::Star {
+ is_static = true;
+ } else {
+ key_name = N_STATIC;
+ }
+ }
+ if key_name == NONE && self.is_contextual(N_ASYNC) {
+ self.next();
+ if (self.is_class_element_name_start() || self.tok == T::Star) && !self.nl_before {
+ is_async = true;
+ } else {
+ key_name = N_ASYNC;
+ }
+ }
+ if key_name == NONE && self.eat(T::Star) {
+ is_generator = true;
+ }
+ if key_name == NONE && !is_async && !is_generator && (self.is_contextual(N_GET) || self.is_contextual(N_SET)) {
+ let word = self.tok_name;
+ self.next();
+ if self.is_class_element_name_start() {
+ accessor = if word == N_GET { 1 } else { 2 };
+ } else {
+ key_name = word;
+ }
+ }
+
+ let key_start = self.tok_start;
+ let mut private_name = NONE;
+ let (key, computed) = if key_name != NONE {
+ let key_pos = if key_name == N_STATIC {
+ self.class_start
+ } else {
+ self.prev_start
+ };
+ (self.ast.push(tag::IDENT, key_pos, key_name, 0), false)
+ } else if self.tok == T::PrivateName {
+ private_name = self.tok_name;
+ if self.interner.text(private_name) == b"constructor" {
+ self.fail(key_start, "Private property with name '#constructor' is not allowed");
+ }
+ self.next();
+ (self.ast.push(tag::PRIVATE_NAME, key_start, private_name, 0), false)
+ } else {
+ self.parse_property_name()
+ };
+
+ if self.tok == T::LParen || accessor != 0 || is_generator || is_async {
+ let is_constructor =
+ !is_static && private_name == NONE && self.key_is(key, computed, N_CONSTRUCTOR, b"constructor");
+ if is_constructor {
+ if accessor != 0 {
+ self.fail(key_start, "Constructor can't have a get or set modifier");
+ }
+ if is_generator || is_async {
+ self.fail(key_start, "Constructor can't be a generator or async");
+ }
+ if *had_constructor {
+ self.fail(key_start, "Duplicate constructor in the same class");
+ }
+ *had_constructor = true;
+ } else if is_static && private_name == NONE && self.key_is(key, computed, N_PROTOTYPE, b"prototype") {
+ self.fail(key_start, "Classes may not have a static property named 'prototype'");
+ }
+ if private_name != NONE {
+ let kind = if accessor == 0 {
+ 0
+ } else {
+ accessor + if is_static { 2 } else { 0 }
+ };
+ self.declare_private_name(private_name, kind, key_start);
+ }
+ let (function, count, has_rest) =
+ self.parse_method(method_start, is_generator, is_async, is_constructor && has_super_class);
+ if is_constructor && !self.is_reparsing() {
+ let row = self.ast.b[function as usize] as usize;
+ self.index.flags[row] |= function_flag::INSIGHT_USES_THIS;
+ if has_super_class {
+ self.index.flags[row] |= function_flag::INSIGHT_THIS_FROM_ENVIRONMENT;
+ }
+ }
+ if accessor != 0 {
+ self.check_accessor_parameters(start, accessor == 1, count, has_rest);
+ }
+ let t = match (accessor, computed) {
+ (0, false) => tag::METHOD,
+ (0, true) => tag::COMPUTED_METHOD,
+ (1, false) => tag::GETTER,
+ (1, true) => tag::COMPUTED_GETTER,
+ (_, false) => tag::SETTER,
+ (_, true) => tag::COMPUTED_SETTER,
+ };
+ let element = self.ast.push(t, start, key, function);
+ return if is_static {
+ self.ast.push(tag::STATIC_ELEMENT, start, element, 0)
+ } else {
+ element
+ };
+ }
+
+ if self.key_is(key, computed, N_CONSTRUCTOR, b"constructor") {
+ self.fail(key_start, "Classes can't have a field named 'constructor'");
+ } else if is_static && self.key_is(key, computed, N_PROTOTYPE, b"prototype") {
+ self.fail(key_start, "Classes can't have a static field named 'prototype'");
+ }
+ if private_name != NONE {
+ self.declare_private_name(private_name, 0, key_start);
+ }
+ let mut value = 0;
+ if self.eat(T::Assign) {
+ value = self.parse_in_pseudo_function(
+ ctx::SUPER_PROPERTY | ctx::NEW_TARGET | ctx::NO_ARGUMENTS,
+ scope_flag::CLASS_FIELD,
+ |parser| parser.parse_assign(false, false),
+ );
+ // A parenthesized expression ends at its innermost closing parenthesis.
+ let mut inner = value;
+ let mut end = self.tok_start;
+ while self.ast.tag[inner as usize] == tag::PAREN {
+ end = self.ast.b[inner as usize];
+ inner = self.ast.a[inner as usize];
+ }
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(self.last_pseudo_function_row);
+ self.ast.extra.push(NONE);
+ value = self.ast.push(tag::FIELD_INITIALIZER, end, value, extra);
+ }
+ self.semicolon();
+ if value != 0 {
+ let extra = self.ast.b[value as usize];
+ let row = self.class_function_row(
+ start,
+ self.class_start,
+ function_flag::FIELD_INITIALIZER | self.pseudo_function_flags,
+ NONE,
+ self.pseudo_function_row,
+ );
+ self.ast.extra[extra as usize + 1] = row;
+ }
+ let element = self.ast.push(
+ if computed {
+ tag::COMPUTED_CLASS_FIELD
+ } else {
+ tag::CLASS_FIELD
+ },
+ start,
+ key,
+ value,
+ );
+ if is_static {
+ self.ast.push(tag::STATIC_ELEMENT, start, element, 0)
+ } else {
+ element
+ }
+ }
+
+ /// Parses code that runs as a function of its own, but is part of the class's tree.
+ fn parse_in_pseudo_function(
+ &mut self,
+ new_ctx: u32,
+ scope_flags: u16,
+ parse: impl FnOnce(&mut Self) -> u32,
+ ) -> u32 {
+ // NB: What the code captures goes by its row, which it needs to have from the start for that.
+ let row = if self.is_reparsing() {
+ NONE
+ } else {
+ self.open_index_row(self.class_start)
+ };
+ let func = self.new_function_id(row);
+ let saved_summary_ordinal = core::mem::replace(&mut self.summary_ordinal, 0);
+ let saved_ctx = core::mem::replace(&mut self.ctx, new_ctx);
+ let saved_labels_base = self.labels_base;
+ self.labels_base = self.labels.len() as u32;
+ let (saved_yield, saved_await, saved_await_ident) = (self.yield_pos, self.await_pos, self.await_ident_pos);
+ let saved_in_arrow = self.in_arrow;
+ if scope_flags & scope_flag::STATIC_BLOCK != 0 {
+ self.in_arrow = false;
+ }
+ self.open_scope_with(scope_flags, func);
+ let id = self.cur_scope;
+ let node = parse(self);
+ let scope = *self.scopes.last().expect("the scope is still there");
+ let has_eval = scope.has_eval;
+ self.last_pseudo_function_row = self.close_scope();
+ self.summary_ordinal = saved_summary_ordinal;
+ self.pseudo_function_flags = if has_eval { function_flag::CONTAINS_EVAL } else { 0 };
+ self.resolve_implicit(N_DOT_THIS, id, func);
+ self.resolve_implicit(N_DOT_NEW_TARGET, id, func);
+ self.resolve_implicit(N_DOT_SUPER, id, func);
+ if row != NONE {
+ self.note_uses_of_nested_functions(scope.use_mark, func);
+ }
+ self.pseudo_function_row = row;
+ self.ctx = saved_ctx;
+ self.in_arrow = saved_in_arrow;
+ self.labels_base = saved_labels_base;
+ (self.yield_pos, self.await_pos, self.await_ident_pos) = (saved_yield, saved_await, saved_await_ident);
+ node
+ }
+
+ fn parse_class_static_block(&mut self, start: u32, element_start: u32) -> u32 {
+ let new_ctx = ctx::SUPER_PROPERTY | ctx::NEW_TARGET | ctx::STATIC_BLOCK | ctx::NO_ARGUMENTS;
+ let list = self.parse_in_pseudo_function(new_ctx, scope_flag::STATIC_BLOCK, |parser| {
+ parser.parse_block_statements()
+ });
+ let row = self.class_function_row(
+ element_start,
+ self.class_start,
+ function_flag::STATIC_BLOCK | self.pseudo_function_flags,
+ NONE,
+ self.pseudo_function_row,
+ );
+ let extra = self.ast.extra.len() as u32;
+ self.ast.extra.push(self.last_pseudo_function_row);
+ self.ast.extra.push(row);
+ self.ast.push(tag::CLASS_STATIC_BLOCK, start, list, extra)
+ }
+
+ /// The row of the code of a class that runs as a function: the initializer of a field, a static block or a default
+ /// constructor, which is known by the offset of the class element or of the class. The code stays part of the tree
+ /// of the class, so that nothing else ever reads the row but the compilation of the function.
+ fn class_function_row(&mut self, key: u32, start: u32, flags: u32, name: u32, reserved_row: u32) -> u32 {
+ if self.is_reparsing() {
+ return self
+ .first_pass_row_at(key)
+ .expect("the first parse made a row for the code of a class");
+ }
+ let row = if reserved_row == NONE {
+ self.open_index_row(start)
+ } else {
+ reserved_row
+ };
+ let reaches_source_end = self.tok_end as usize + super::SOURCE_PADDING > self.len as usize;
+ let index = &mut self.index;
+ index.params_start[row as usize] = key;
+ index.end[row as usize] = self.prev_end;
+ index.flags[row as usize] = flags
+ | function_flag::STRICT
+ | if reaches_source_end {
+ function_flag::REACHES_SOURCE_END
+ } else {
+ 0
+ };
+ index.ctx[row as usize] = self.ctx as u16;
+ index.name[row as usize] = name;
+ row
+ }
+
+ /// Parses a class element on its own, for the function that the element is. Returns the element without its
+ /// `static`.
+ pub(crate) fn reparse_class_element(&mut self) -> u32 {
+ self.open_scope(scope_flag::CLASS);
+ self.strict = true;
+ let mut had_constructor = false;
+ let element = self.parse_class_element(false, &mut had_constructor);
+ if self.ast.tag[element as usize] == tag::STATIC_ELEMENT {
+ self.ast.a[element as usize]
+ } else {
+ element
+ }
+ }
+
+ /// A class node of nothing but what the default constructor at `row` reads of its class.
+ pub(crate) fn default_constructor_class_node(&mut self, row: u32) -> u32 {
+ let (start, end, name, flags) = self.function_row_summary(row);
+ let extra = self.ast.extra.len() as u32;
+ self.ast
+ .extra
+ .push(u32::from(flags & function_flag::DERIVED_CONSTRUCTOR != 0));
+ self.ast.extra.push(0);
+ self.ast.extra.push(NONE);
+ self.ast.extra.push(0);
+ self.ast.extra.push(end);
+ self.ast.extra.push(row);
+ self.ast.push(tag::CLASS, start, name, extra)
+ }
+
+ // === Modules ===
+
+ fn parse_module_export_name(&mut self) -> u32 {
+ let start = self.tok_start;
+ if self.tok == T::Str {
+ let name = self.intern_string_literal();
+ self.next();
+ return self.ast.push(tag::STR, start, name, 0);
+ }
+ if !is_name_like(self.tok) {
+ self.unexpected();
+ return 0;
+ }
+ let name = self.tok_name;
+ self.next();
+ self.ast.push(tag::IDENT, start, name, 0)
+ }
+
+ /// The name a string literal spells. Module export names are the only strings that need one, and they must be well
+ /// formed, which also rules out lone surrogates written as escapes.
+ fn intern_string_literal(&mut self) -> u32 {
+ let (start, end) = (self.tok_start as usize + 1, self.tok_end as usize - 1);
+ let mut buffer = Vec::with_capacity(end - start);
+ let mut p = start;
+ while p < end {
+ let mut c = self.at(p);
+ p += 1;
+ if c == 0x5C {
+ if self.at(p) == 0x75 {
+ let mut value = 0;
+ if self.at(p + 1) == 0x7B {
+ let mut q = p + 2;
+ while self.at(q) != 0x7D {
+ value = value * 16 + char::from_u32(self.at(q)).and_then(|d| d.to_digit(16)).unwrap_or(0);
+ q += 1;
+ }
+ p = q + 1;
+ } else {
+ for i in 1..=4 {
+ value =
+ value * 16 + char::from_u32(self.at(p + i)).and_then(|d| d.to_digit(16)).unwrap_or(0);
+ }
+ p += 5;
+ }
+ c = value;
+ } else {
+ c = self.at(p);
+ p += 1;
+ }
+ }
+ if (0xD800..0xDC00).contains(&c) {
+ let (mut low, mut after) = (self.at(p), p + 1);
+ if low == 0x5C && self.at(p + 1) == 0x75 {
+ low = 0;
+ for i in 2..=5 {
+ low = low * 16 + char::from_u32(self.at(p + i)).and_then(|d| d.to_digit(16)).unwrap_or(0);
+ }
+ after = p + 6;
+ }
+ if (0xDC00..0xE000).contains(&low) {
+ c = 0x10000 + ((c - 0xD800) << 10) + (low - 0xDC00);
+ p = after;
+ }
+ }
+ match char::from_u32(c) {
+ Some(ch) => {
+ let mut encoded = [0u8; 4];
+ buffer.extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());
+ }
+ None => {
+ self.fail(self.tok_start, "Export name is not well formed");
+ break;
+ }
+ }
+ }
+ self.interner.intern_bytes(&buffer)
+ }
+
+ /// Returns the list of keys and values, as interned names, or zero if there are none.
+ fn parse_import_attributes(&mut self) -> u32 {
+ if self.tok != T::KWith {
+ return 0;
+ }
+ self.next();
+ self.expect(T::LBrace);
+ let mark = self.scratch.len();
+ let mut seen = std::collections::HashSet::new();
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let key = if self.tok == T::Str {
+ self.intern_string_literal()
+ } else if is_name_like(self.tok) {
+ self.tok_name
+ } else {
+ self.unexpected();
+ self.scratch.truncate(mark);
+ return 0;
+ };
+ if !seen.insert(key) {
+ self.fail(self.tok_start, "Duplicate import attribute key");
+ }
+ self.next();
+ self.expect(T::Colon);
+ if self.tok != T::Str {
+ self.unexpected();
+ self.scratch.truncate(mark);
+ return 0;
+ }
+ let value = self.intern_string_literal();
+ self.scratch.push(key);
+ self.scratch.push(value);
+ self.next();
+ if self.tok != T::RBrace {
+ self.expect_comma_or(T::RBrace);
+ }
+ }
+ self.expect(T::RBrace);
+ self.finish_list(mark)
+ }
+
+ fn parse_import(&mut self) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ let mark = self.scratch.len();
+ if self.tok == T::Str {
+ let source = self.parse_module_source();
+ let attributes = self.parse_import_attributes();
+ self.ast.b[source as usize] = attributes;
+ self.semicolon();
+ let list = self.finish_list(mark);
+ return self.ast.push(tag::IMPORT, start, list, source);
+ }
+ let mut more = true;
+ if self.tok == T::Name {
+ let specifier = self.parse_import_binding(0);
+ self.scratch.push(specifier);
+ more = self.eat(T::Comma);
+ }
+ if more {
+ if self.eat(T::Star) {
+ if !self.eat_contextual(N_AS) {
+ self.unexpected();
+ }
+ let specifier = self.parse_import_binding(NONE);
+ self.scratch.push(specifier);
+ } else {
+ self.expect(T::LBrace);
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let was_string = self.tok == T::Str;
+ let keyword = self.tok != T::Name;
+ let imported_start = self.tok_start;
+ let imported_name = self.tok_name;
+ let imported = self.parse_module_export_name();
+ let specifier = if self.eat_contextual(N_AS) {
+ self.parse_import_binding(imported)
+ } else {
+ if was_string || keyword {
+ self.fail(imported_start, "Import specifier needs a local name");
+ }
+ self.check_binding_name(imported_name, imported_start);
+ self.declare(imported_name, Bind::Lexical, imported_start);
+ self.ast.push(tag::SPECIFIER, imported_start, imported, imported_name)
+ };
+ self.scratch.push(specifier);
+ if self.tok != T::RBrace {
+ self.expect_comma_or(T::RBrace);
+ }
+ }
+ self.expect(T::RBrace);
+ }
+ }
+ if !self.eat_contextual(N_FROM) {
+ self.unexpected();
+ }
+ let source = self.parse_module_source();
+ let attributes = self.parse_import_attributes();
+ self.ast.b[source as usize] = attributes;
+ self.semicolon();
+ let list = self.finish_list(mark);
+ self.ast.push(tag::IMPORT, start, list, source)
+ }
+
+ fn parse_import_binding(&mut self, imported: u32) -> u32 {
+ let start = self.tok_start;
+ let (name, pos) = self.parse_ident();
+ self.check_binding_name(name, pos);
+ if name == N_LET {
+ self.fail(pos, "'let' is disallowed as a lexically bound name");
+ }
+ self.declare(name, Bind::Lexical, pos);
+ self.ast.push(tag::SPECIFIER, start, imported, name)
+ }
+
+ fn parse_module_source(&mut self) -> u32 {
+ let start = self.tok_start;
+ if self.tok != T::Str {
+ self.unexpected();
+ return 0;
+ }
+ let end = self.tok_end;
+ self.next();
+ self.ast.push(tag::STR, start, end, 0)
+ }
+
+ fn add_export_name(&mut self, name: u32, pos: u32) {
+ if !self.export_names.insert(name) {
+ self.fail(pos, "Duplicate export");
+ }
+ }
+
+ fn export_pattern_names(&mut self, node: u32) {
+ match self.ast.tag[node as usize] {
+ tag::IDENT => self.add_export_name(self.ast.a[node as usize], self.ast.pos[node as usize]),
+ tag::ARRAY_PATTERN | tag::OBJECT_PATTERN => {
+ let list = self.ast.a[node as usize];
+ for i in 0..self.ast.extra[list as usize] {
+ let item = self.ast.extra[(list + 1 + i) as usize];
+ self.export_pattern_names(item);
+ }
+ }
+ tag::PROPERTY | tag::COMPUTED_PROPERTY | tag::SHORTHAND => {
+ self.export_pattern_names(self.ast.b[node as usize]);
+ }
+ tag::REST | tag::ASSIGN_PATTERN => self.export_pattern_names(self.ast.a[node as usize]),
+ _ => {}
+ }
+ }
+
+ fn parse_export(&mut self) -> u32 {
+ let start = self.tok_start;
+ self.next();
+ if self.eat(T::Star) {
+ let mut exported = 0;
+ if self.eat_contextual(N_AS) {
+ let name_start = self.tok_start;
+ let name = if self.tok == T::Str {
+ self.intern_string_literal()
+ } else {
+ self.tok_name
+ };
+ exported = self.parse_module_export_name();
+ self.add_export_name(name, name_start);
+ }
+ if !self.eat_contextual(N_FROM) {
+ self.unexpected();
+ }
+ let source = self.parse_module_source();
+ let attributes = self.parse_import_attributes();
+ self.ast.b[source as usize] = attributes;
+ self.semicolon();
+ return self.ast.push(tag::EXPORT_ALL, start, exported, source);
+ }
+ if self.tok == T::KDefault {
+ let default_pos = self.tok_start;
+ self.add_export_name(
+ KEYWORDS.iter().position(|(word, _)| *word == "default").unwrap() as u32,
+ default_pos,
+ );
+ self.next();
+ let value_start = self.tok_start;
+ let is_async_function = self.is_async_function();
+ let declaration = if self.tok == T::KFunction || is_async_function {
+ if is_async_function {
+ self.next();
+ }
+ self.next();
+ let is_generator = self.eat(T::Star);
+ if self.tok == T::Name {
+ let (name, pos) = self.parse_ident();
+ self.declare(name, Bind::Lexical, pos);
+ self.parse_function_rest(value_start, Some((name, pos)), is_generator, is_async_function)
+ } else {
+ self.parse_function_rest(value_start, None, is_generator, is_async_function)
+ }
+ } else if self.tok == T::KClass {
+ let (next_kind, _, _) = self.peek();
+ let named = next_kind == T::Name && !(self.peek().1 == N_IMPLEMENTS);
+ self.parse_class(named)
+ } else {
+ let expression = self.parse_assign(false, false);
+ self.semicolon();
+ expression
+ };
+ let is_declaration = matches!(
+ self.ast.tag[declaration as usize],
+ tag::FUNCTION | tag::CLASS_DECL | tag::CLASS
+ ) && (self.tok_is_declaration_export(value_start));
+ return self
+ .ast
+ .push(tag::EXPORT_DEFAULT, start, declaration, is_declaration as u32);
+ }
+ if self.tok == T::LBrace {
+ self.next();
+ let mark = self.scratch.len();
+ let mut had_string_local = false;
+ let locals_mark = self.export_locals.len();
+ let mut pending: Vec<(u32, u32)> = Vec::new();
+ while self.tok != T::RBrace && self.tok != T::Eof {
+ let local_start = self.tok_start;
+ let local_kind = self.tok;
+ let local_name = if local_kind == T::Str {
+ self.intern_string_literal()
+ } else {
+ self.tok_name
+ };
+ let local = self.parse_module_export_name();
+ had_string_local |= local_kind == T::Str;
+ let mut exported_name = local_name;
+ let mut exported_pos = local_start;
+ let mut exported = local;
+ if self.eat_contextual(N_AS) {
+ exported_pos = self.tok_start;
+ exported_name = if self.tok == T::Str {
+ self.intern_string_literal()
+ } else {
+ self.tok_name
+ };
+ exported = self.parse_module_export_name();
+ }
+ pending.push((exported_name, exported_pos));
+ self.export_locals
+ .push((local_name, local_start | ((local_kind != T::Name) as u32) << 31));
+ let specifier = self.ast.push(tag::SPECIFIER, local_start, local, exported);
+ self.scratch.push(specifier);
+ if self.tok != T::RBrace {
+ self.expect_comma_or(T::RBrace);
+ }
+ }
+ self.expect(T::RBrace);
+ for (name, pos) in pending {
+ self.add_export_name(name, pos);
+ }
+ let mut source = 0;
+ if self.eat_contextual(N_FROM) {
+ source = self.parse_module_source();
+ let attributes = self.parse_import_attributes();
+ self.ast.b[source as usize] = attributes;
+ self.export_locals.truncate(locals_mark);
+ } else {
+ if had_string_local {
+ self.fail(start, "A string cannot be a local export name");
+ }
+ for i in locals_mark..self.export_locals.len() {
+ let (name, pos) = self.export_locals[i];
+ if pos >> 31 != 0 {
+ self.fail(pos & 0x7FFF_FFFF, "Keyword as a local export name");
+ }
+ self.check_identifier(name, pos);
+ self.note_use(name);
+ }
+ }
+ self.semicolon();
+ let list = self.finish_list(mark);
+ return self.ast.push(tag::EXPORT_NAMED, start, list, source);
+ }
+ // `export` of a declaration.
+ let is_var = matches!(self.tok, T::KVar | T::KConst) || self.is_let(Context::List);
+ if is_var {
+ let statement = self.parse_statement(Context::List, false);
+ let list = self.ast.a[statement as usize];
+ for i in 0..self.ast.extra[list as usize] {
+ let declarator = self.ast.extra[(list + 1 + i) as usize];
+ self.export_pattern_names(self.ast.a[declarator as usize]);
+ }
+ return self.ast.push(tag::EXPORT_NAMED, start, 0, statement);
+ }
+ if !matches!(self.tok, T::KFunction | T::KClass) && !self.is_async_function() {
+ self.unexpected();
+ return 0;
+ }
+ let name_pos = self.tok_start;
+ let statement = self.parse_statement(Context::List, false);
+ let name = match self.ast.tag[statement as usize] {
+ tag::FUNCTION_DECL => self.ast.b[statement as usize],
+ tag::CLASS_DECL => self.ast.a[self.ast.a[statement as usize] as usize],
+ _ => 0,
+ };
+ self.add_export_name(name, name_pos);
+ self.ast.push(tag::EXPORT_NAMED, start, 0, statement)
+ }
+
+ fn tok_is_declaration_export(&self, value_start: u32) -> bool {
+ // `export default` of a function or class declaration rather than of an expression that happens to be one.
+ matches!(self.at(value_start as usize), 0x66 | 0x63 | 0x61)
+ }
+
+ pub(crate) fn check_exported_locals(&mut self) {
+ for i in 0..self.export_locals.len() {
+ let (name, pos) = self.export_locals[i];
+ if !self.is_declared_at_top(name) {
+ self.fail(pos & 0x7FFF_FFFF, "Export of an undeclared name");
+ return;
+ }
+ }
+ }
+}