Truly independent web browser
LibJS: Remove the old frontend and the bytecode cache
Andreas Kling45f78fb36a59
diff --git a/Libraries/LibJS/DecodedBytecodeCache.cpp b/Libraries/LibJS/DecodedBytecodeCache.cppdeleted file mode 100644index d7e8b187b1a..00000000000--- a/Libraries/LibJS/DecodedBytecodeCache.cpp+++ /dev/null@@ -1,39 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibJS/DecodedBytecodeCache.h>-#include <LibJS/ScriptAndModuleABIConversions.h>--namespace JS::RustIntegration {--using namespace EmbeddingABI;--static_assert(to_underlying(ProgramType::Script) == JS_PROGRAM_TYPE_SCRIPT);-static_assert(to_underlying(ProgramType::Module) == JS_PROGRAM_TYPE_MODULE);--RefPtr<DecodedBytecodeCache> DecodedBytecodeCache::create(Core::ImmutableBytes bytes, ProgramType program_type, ReadonlyBytes source_hash)-{- // The runtime runs the bytecode in place in the blob's bytes, which stay alive until it releases their owner.- auto* bytes_owner = new Core::ImmutableBytes(move(bytes));- JSBytecodeCacheBlobOwner owner {- .owner = bytes_owner,- .release = [](void* owner) { delete static_cast<Core::ImmutableBytes*>(owner); },- };- auto blob = bytes_owner->bytes();- return adopt_decoded_bytecode_cache_from_abi(js_bytecode_cache_decode(blob.data(), blob.size(), program_type_to_abi(program_type), source_hash.data(), source_hash.size(), owner));-}--void DecodedBytecodeCache::ref() const-{- js_bytecode_cache_retain(decoded_bytecode_cache_to_abi(*this));-}--void DecodedBytecodeCache::unref() const-{- js_bytecode_cache_release(decoded_bytecode_cache_to_abi(*this));-}--}diff --git a/Libraries/LibJS/DecodedBytecodeCache.h b/Libraries/LibJS/DecodedBytecodeCache.hdeleted file mode 100644index 9afc37c2723..00000000000--- a/Libraries/LibJS/DecodedBytecodeCache.h+++ /dev/null@@ -1,46 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Noncopyable.h>-#include <AK/NonnullRefPtr.h>-#include <AK/RefPtr.h>-#include <AK/Span.h>-#include <AK/Types.h>-#include <LibCore/ImmutableBytes.h>-#include <LibJS/Export.h>--namespace JS::RustIntegration {--enum class ProgramType : u8 {- Script = 0,- Module = 1,-};--// A bytecode cache blob, decoded and checked against the program type and the source hash it was written for. A-// pointer to it is the Rust runtime's decoded cache itself, which is reference counted: the thread that decoded it may-// hand it to the VM's thread while nothing else references it, and from then on only the VM's thread may reference or-// release it.-class JS_API DecodedBytecodeCache {- AK_MAKE_NONCOPYABLE(DecodedBytecodeCache);- AK_MAKE_NONMOVABLE(DecodedBytecodeCache);--public:- // Null for a blob of another format version, runtime, program type or source hash, and for a malformed one.- static RefPtr<DecodedBytecodeCache> create(Core::ImmutableBytes, ProgramType, ReadonlyBytes source_hash);-- void ref() const;- void unref() const;-- DecodedBytecodeCache() = delete;- ~DecodedBytecodeCache() = delete;-};--}--template<>-inline constexpr bool AllocatedWithCustomAllocator<JS::RustIntegration::DecodedBytecodeCache> = true;diff --git a/Libraries/LibJS/Rust/src/bytecode/basic_block.rs b/Libraries/LibJS/Rust/src/bytecode/basic_block.rsdeleted file mode 100644index 73c86ceebe7..00000000000--- a/Libraries/LibJS/Rust/src/bytecode/basic_block.rs+++ /dev/null@@ -1,53 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use super::instruction::Instruction;-use super::operand::Label;--/// A source map entry mapping a bytecode offset to a source position.-#[derive(Debug, Clone, Copy)]-pub struct SourceMapEntry {- pub bytecode_offset: u32,- pub line: u32,- pub column: u32,-}--/// A basic block in the bytecode generator.-///-/// During codegen, instructions are appended as typed `Instruction` enum-/// variants. During flattening (compile/assemble), instructions are-/// serialized into the final byte stream.-pub struct BasicBlock {- pub index: u32,- pub instructions: Vec<(Instruction, SourceMapEntry, bool)>,- pub handler: Option<Label>,- pub terminated: bool,- pub resolved_this: bool,-}--impl BasicBlock {- pub fn new(index: u32) -> Self {- Self {- index,- instructions: Vec::new(),- handler: None,- terminated: false,- resolved_this: false,- }- }-- pub fn append(&mut self, instruction: Instruction, source_map: SourceMapEntry, strict: bool) {- let is_terminator = instruction.is_terminator();- self.instructions.push((instruction, source_map, strict));- if is_terminator {- self.terminated = true;- }- }-- pub fn is_empty(&self) -> bool {- self.instructions.is_empty()- }-}diff --git a/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rsdeleted file mode 100644index 597d8075efa..00000000000--- a/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rs+++ /dev/null@@ -1,357 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Bytecode cache blobs on this runtime's types: Script and Source Text Module Records materialized from a decoded-//! blob, and blobs installed into records that already run.-//!-//! The executables made from a blob run their bytecode in place in it and keep it alive. A function's executable stays-//! in the blob until the function is first called. Installing a blob into a running record matches every function the-//! record has created to a function of the blob, then gives each one that ran an executable from the blob, which takes-//! over the inline caches, feedback and tier of the one it replaces, and each one that did not its executable in the-//! blob. A function whose executable has JIT code keeps it.--use core::cell::{Ref, RefCell};-use std::collections::{HashMap, HashSet};-use std::rc::Rc;--use crate::bytecode::executable::Executable;-use crate::bytecode::generator::FunctionSfdMetadata;-use crate::bytecode_cache::{- DecodedCacheBlob, DecodedCachedExecutableRecord, DecodedExecutableRecord, DecodedFunctionRecord,-};-use crate::gc::root::MarkedVec;-use crate::interpreter::vm::Vm;-use crate::layout::cell::Gc;-use crate::parser_error::ParserError;-use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;-use crate::source_code::SourceCode;--/// RustIntegration::DecodedBytecodeCache: a decoded blob, which the records materialized from it share, and which is-/// validated against the source code once.-pub struct DecodedBytecodeCache {- blob: RefCell<DecodedCacheBlob>,-}--impl DecodedBytecodeCache {- pub fn new(blob: DecodedCacheBlob) -> Self {- Self {- blob: RefCell::new(blob),- }- }-- /// Validates the blob for source code of `source_length_in_code_units` code units, and checks nothing else after- /// that succeeded once.- pub fn validate(&self, source_length_in_code_units: usize) -> bool {- self.blob- .borrow_mut()- .validate_for_materialization(source_length_in_code_units)- .is_ok()- }-- /// The blob, if it passed validation for source code of `source_length_in_code_units` code units.- pub fn validated_blob(&self, source_length_in_code_units: usize) -> Option<Ref<'_, DecodedCacheBlob>> {- self.validate(source_length_in_code_units).then(|| self.blob.borrow())- }-}--/// The error a record that cannot be materialized from a bytecode cache blob reports.-pub fn failed_to_materialize_bytecode_cache() -> Vec<ParserError> {- vec![ParserError {- message: "Failed to materialize bytecode cache".to_string(),- line: 0,- column: 0,- }]-}--/// ExecutableBacking: what the executables of a Script or Source Text Module Record were made from, and how that-/// changes while a bytecode cache is generated for the record and installed into it.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum ExecutableBacking {- /// Compiled from source code on the VM's thread.- Source,- /// Compiled on another thread.- HeapBytecode,- GeneratingFreshCacheFromSource,- GeneratingFreshCacheFromHeapBytecode,- /// Materialized from a bytecode cache blob, or with one installed.- MappedBytecodeCache,-}--impl ExecutableBacking {- pub fn is_source(self) -> bool {- matches!(self, Self::Source | Self::GeneratingFreshCacheFromSource)- }-- pub fn is_heap_bytecode(self) -> bool {- matches!(self, Self::HeapBytecode | Self::GeneratingFreshCacheFromHeapBytecode)- }-- pub fn is_mapped_bytecode_cache(self) -> bool {- self == Self::MappedBytecodeCache- }-- pub fn can_generate_bytecode_cache(self) -> bool {- matches!(self, Self::Source | Self::HeapBytecode)- }-- pub fn can_install_generated_bytecode_cache(self) -> bool {- matches!(- self,- Self::GeneratingFreshCacheFromSource | Self::GeneratingFreshCacheFromHeapBytecode- )- }-- /// The backing once the generation of a bytecode cache began.- pub fn with_bytecode_cache_generation_begun(self) -> Self {- match self {- Self::Source => Self::GeneratingFreshCacheFromSource,- Self::HeapBytecode => Self::GeneratingFreshCacheFromHeapBytecode,- _ => panic!("a bytecode cache is only generated for a record that has none, once at a time"),- }- }-- /// The backing once the generation of a bytecode cache ended without installing it.- pub fn with_bytecode_cache_generation_finished_without_install(self) -> Self {- match self {- Self::GeneratingFreshCacheFromSource => Self::Source,- Self::GeneratingFreshCacheFromHeapBytecode => Self::HeapBytecode,- _ => panic!("only the generation of a bytecode cache that began can finish"),- }- }-}--/// Every function a record has created so far: those it declares, those its executables create, and so on for the-/// executables of the functions that ran.-pub fn functions_created_by(- vm: &Vm,- declared_functions: impl IntoIterator<Item = Gc<SharedFunctionInstanceData>>,- executable: Option<Gc<Executable>>,-) -> MarkedVec<'_, Gc<SharedFunctionInstanceData>> {- let functions = MarkedVec::new(vm);- let mut seen = HashSet::new();- let executables_to_visit = MarkedVec::new(vm);- if let Some(executable) = executable {- executables_to_visit.push(executable);- }- let mut add_function = |function: Gc<SharedFunctionInstanceData>| {- if seen.insert(function.as_ptr().addr()) {- functions.push(function);- if let Some(executable) = function.executable() {- executables_to_visit.push(executable);- }- }- };- for function in declared_functions {- add_function(function);- }- while let Some(executable) = executables_to_visit.pop() {- for index in 0..executable.shared_function_data_count() {- add_function(executable.shared_function_data(u32::try_from(index).expect("the index fits in u32")));- }- }- functions-}--/// Whether none of `functions` still has an AST or bytecode compiled ahead of its first call, which a record with a-/// bytecode cache installed only compiles from the blob.-pub fn have_only_bytecode_cache_compile_inputs(functions: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>) -> bool {- functions- .to_vec()- .iter()- .all(|function| !function.has_function_ast() && !function.has_precompiled_bytecode())-}--/// Creates the executable of a cached record together with the functions its bytecode creates, whose own executables-/// stay in the blob. Returns `None` if the record turns out to be malformed.-pub fn create_executable_and_its_functions(- vm: &Vm,- record: &DecodedExecutableRecord,- source_code: &Rc<SourceCode>,-) -> Option<Gc<Executable>> {- let functions = MarkedVec::new(vm);- for function in record.functions()? {- functions.push(SharedFunctionInstanceData::create_from_bytecode_cache(- vm,- &function,- record.is_strict(),- source_code,- ));- }- Executable::create_from_bytecode_cache(vm, record, &functions, source_code, None)-}--/// The executable of a function whose executable stayed in a bytecode cache blob until its first call, as-/// rust_materialize_bytecode_cache_function makes it.-pub fn materialize_cached_function_executable(- vm: &Vm,- cached_executable: &DecodedCachedExecutableRecord,- source_code: &Rc<SourceCode>,-) -> Option<Gc<Executable>> {- create_executable_and_its_functions(vm, &cached_executable.decode_executable()?, source_code)-}--enum Replacement {- CachedExecutable(DecodedCachedExecutableRecord),- /// The executable at this index of `new_executables`.- Executable(usize),- /// The function keeps the executable it has, which has JIT code, or a compile on its way.- KeepExecutable,-}--/// What installing a blob gives one function, once every function turned out to have its counterpart in the blob.-struct PendingFunctionInstall {- /// The index of the function among the existing functions.- function: usize,- replacement: Replacement,- metadata: FunctionSfdMetadata,-}--/// Installing a bytecode cache blob into a running record: the functions the record has created, each of which must-/// match one function of the blob, and what each one gets once they all did.-pub struct BytecodeCacheInstall<'vm, 'source> {- vm: &'vm Vm,- source_code: &'source Rc<SourceCode>,- existing_functions: &'source MarkedVec<'vm, Gc<SharedFunctionInstanceData>>,- /// The indices of the existing functions by the source text range a blob identifies them by, in their order.- existing_functions_by_source_text_range: HashMap<(usize, usize), Vec<usize>, foldhash::fast::RandomState>,- matched: Vec<bool>,- pending_installs: Vec<PendingFunctionInstall>,- /// The executables made for functions that ran, which nothing else holds until the install commits.- new_executables: MarkedVec<'vm, Gc<Executable>>,-}--impl<'vm, 'source> BytecodeCacheInstall<'vm, 'source> {- pub fn new(- vm: &'vm Vm,- source_code: &'source Rc<SourceCode>,- existing_functions: &'source MarkedVec<'vm, Gc<SharedFunctionInstanceData>>,- ) -> Self {- let mut existing_functions_by_source_text_range: HashMap<_, Vec<_>, _> = HashMap::default();- for (index, function) in existing_functions.values().iter().enumerate() {- existing_functions_by_source_text_range- .entry(function.bytecode_cache_source_text_range())- .or_default()- .push(index);- }- Self {- vm,- source_code,- matched: vec![false; existing_functions.len()],- existing_functions,- existing_functions_by_source_text_range,- pending_installs: Vec::new(),- new_executables: MarkedVec::new(vm),- }- }-- fn take_matching_function(&mut self, function: &DecodedFunctionRecord, outer_strict: bool) -> Option<usize> {- let source_text_range = function.source_text_range();- let index = self- .existing_functions_by_source_text_range- .get(&(- source_text_range.start,- source_text_range.end.saturating_sub(source_text_range.start),- ))?- .iter()- .copied()- .find(|&index| {- !self.matched[index]- && self- .existing_function(index)- .matches_bytecode_cache_function(function, outer_strict)- })?;- self.matched[index] = true;- Some(index)- }-- fn existing_function(&self, index: usize) -> Gc<SharedFunctionInstanceData> {- self.existing_functions- .get(index)- .expect("the index is that of an existing function")- }-- /// Matches a function of the blob, nested in code that is strict if `outer_strict` is, to one the record created,- /// and prepares what that one gets: an executable from the blob if it ran, which recursively matches the functions- /// it creates, and its executable in the blob otherwise. Returns `None` if no function matches or the blob turns- /// out to be malformed.- pub fn prepare_function(- &mut self,- function: &DecodedFunctionRecord,- outer_strict: bool,- ) -> Option<Gc<SharedFunctionInstanceData>> {- let existing_function_index = self.take_matching_function(function, outer_strict)?;- let existing_function = self.existing_function(existing_function_index);- let replacement = match existing_function.executable() {- None => Replacement::CachedExecutable(function.cached_executable()),- // NB: JIT code is tied to the executable it was compiled for, and an executable from the blob would compile- // again from scratch, so a function with code keeps its executable. The functions it creates still- // match functions of the blob, and get what they would otherwise.- Some(existing_executable) if existing_executable.has_jit_code_or_compile() => {- let record = function.cached_executable().decode_executable()?;- for nested_function in record.functions()? {- self.prepare_function(&nested_function, record.is_strict())?;- }- Replacement::KeepExecutable- }- Some(existing_executable) => {- let record = function.cached_executable().decode_executable()?;- self.prepare_executable(&record, Some(existing_executable))?;- // NB: prepare_executable() pushes the executable it makes last.- Replacement::Executable(self.new_executables.len() - 1)- }- };- self.pending_installs.push(PendingFunctionInstall {- function: existing_function_index,- replacement,- metadata: function.scope_metadata().clone(),- });- Some(existing_function)- }-- /// The executable of a record of the blob, whose functions match functions the record created, and which takes over- /// the inline caches of `replaced_executable`.- pub fn prepare_executable(- &mut self,- record: &DecodedExecutableRecord,- replaced_executable: Option<Gc<Executable>>,- ) -> Option<Gc<Executable>> {- let functions = MarkedVec::new(self.vm);- for function in record.functions()? {- functions.push(self.prepare_function(&function, record.is_strict())?);- }- let executable =- Executable::create_from_bytecode_cache(self.vm, record, &functions, self.source_code, replaced_executable)?;- self.new_executables.push(executable);- Some(executable)- }-- /// Gives every function what was prepared for it, if every function the record created found its counterpart in- /// the blob. Otherwise nothing changes and this returns false.- pub fn commit(self) -> bool {- if !self.matched.iter().all(|matched| *matched) {- return false;- }- for install in self.pending_installs {- let function = self- .existing_functions- .get(install.function)- .expect("the index is that of an existing function");- match install.replacement {- Replacement::CachedExecutable(cached_executable) => {- function.install_cached_bytecode_executable(cached_executable, &install.metadata);- }- Replacement::Executable(index) => function.install_bytecode_cache_executable(- self.new_executables- .get(index)- .expect("the index is that of a new executable"),- &install.metadata,- ),- Replacement::KeepExecutable => function.clear_compile_inputs(),- }- }- true- }-}diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rsdeleted file mode 100644index 52c5275960e..00000000000--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs+++ /dev/null@@ -1,10824 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Bytecode generation from AST.-//!-//! This is the largest module in the parser -- it walks the AST-//! and emits bytecode instructions via the `Generator`.-//!-//! ## Conventions-//!-//! Each AST node's codegen returns `Option<ScopedOperand>`:-//! - `Some(op)` if the node produces a value (expressions)-//! - `None` for statements that don't produce values-//!-//! The `preferred_dst` parameter is a register hint: when the caller-//! already has a destination register (e.g. the LHS of an assignment),-//! codegen writes directly there instead of allocating a temporary.-//!-//! ## File organization-//!-//! The file is organized by AST node type, with section headers:-//!-//! - **Top-level entry points**: `generate_expression`, `generate_statement`-//! - **Literals and identifiers**: numeric, string, boolean, regexp, identifier-//! - **Await/yield**: async/generator control flow helpers-//! - **Operators**: binary, logical, conditional, update, assignment-//! - **Control flow**: if, while, do-while, for, for-in/of, switch, labelled-//! - **Blocks and scopes**: block statements, function bodies, scope children-//! - **Declarations**: variable declarations, using declarations-//! - **Calls**: regular calls, super calls, optional chains, builtin detection-//! - **Templates**: template literals, tagged templates-//! - **Objects and classes**: object expressions, class expressions-//! - **Patterns**: binding pattern destructuring (array and object)-//! - **Try/catch/finally**: try statement codegen-//! - **Functions**: `emit_new_function`, `emit_function_declaration_instantiation`-//! - **Helpers**: constant folding, NaN-boxing, error message utilities--use std::collections::HashSet;--use num_bigint::BigInt;-use num_traits::FromPrimitive;-use num_traits::One;-use num_traits::Signed;-use num_traits::ToPrimitive;-use num_traits::Zero;--use libjs_abi::ArgumentsKind;-use libjs_abi::ClassElementKind;-use libjs_abi::CompletionType;-use libjs_abi::EnvironmentMode;-use libjs_abi::FunctionNamePrefix;-use libjs_abi::IteratorHint;-use libjs_abi::PutKind;-use libjs_abi::value as nan_box;--use crate::ast::*;-use crate::lexer::ch;-use crate::u32_from_usize;--use super::constant::AbstractOperationKind;-use super::constant::WellKnownSymbolKind;-use super::generator::BindingLocation;-use super::generator::BlockBoundaryType;-use super::generator::ConstantValue;-use super::generator::DisposableResourceKind;-use super::generator::FinallyContext;-use super::generator::Generator;-use super::generator::PendingClassBlueprint;-use super::generator::PendingClassElement;-use super::generator::PendingLiteralValueKind;-use super::generator::PendingSharedFunctionData;-use super::generator::ScopedOperand;-use super::generator::choose_dst;-use super::generator::constant_to_boolean;-use super::generator::parse_bigint;-use super::instruction::Instruction;-use super::operand::*;--/// Generate bytecode for an expression.-pub fn generate_expression(- expression: &Expression,- generator: &mut Generator,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let saved_source_start = generator.current_source_start;- let saved_source_end = generator.current_source_end;- generator.current_source_start = expression.range.start;- generator.current_source_end = expression.range.end;-- let result = generate_expression_inner(expression, generator, preferred_dst);-- generator.current_source_start = saved_source_start;- generator.current_source_end = saved_source_end;- result-}--fn generate_class_part_expression(- expression: &Expression,- generator: &mut Generator,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // https://tc39.es/ecma262/#sec-strict-mode-code- // All parts of a |ClassDeclaration| or a |ClassExpression| are strict mode code.- let saved_strict = generator.strict;- generator.strict = true;- let result = generate_expression(expression, generator, preferred_dst);- generator.strict = saved_strict;- result-}--fn emit_get_binding(- generator: &mut Generator,- dst: Operand,- identifier: IdentifierTableIndex,- known_initialized: bool,-) {- // Prefer an eagerly-computed coordinate when the generator can prove that- // the binding lives in a known declarative environment. The dynamic forms- // remain necessary for script and eval code, eval-poisoned scopes, and- // `with`.- match (generator.binding_location_for_identifier(identifier), known_initialized) {- (Some(BindingLocation::Import(import_index)), _) => generator.emit(Instruction::GetImport {- dst,- identifier,- import_index,- }),- (Some(BindingLocation::Environment(cache)), true) => {- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetInitializedBinding {- value_feedback,- dst,- identifier,- cache,- });- }- (Some(BindingLocation::Environment(cache)), false) => {- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetBinding {- value_feedback,- dst,- identifier,- cache,- });- }- (None, true) => {- let cache = generator.next_environment_coordinate_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::DynamicGetInitializedBinding {- value_feedback,- dst,- identifier,- cache,- });- }- (None, false) => {- let cache = generator.next_environment_coordinate_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::DynamicGetBinding {- value_feedback,- dst,- identifier,- cache,- });- }- }-}--fn emit_get_callee_and_this_from_environment(- generator: &mut Generator,- callee: Operand,- this_value: Operand,- identifier: IdentifierTableIndex,-) {- match generator.binding_location_for_identifier(identifier) {- Some(BindingLocation::Environment(cache)) => {- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetCalleeAndThisFromEnvironment {- value_feedback,- callee,- this_value,- identifier,- cache,- });- }- Some(BindingLocation::Import(import_index)) => {- generator.emit(Instruction::GetImport {- dst: callee,- identifier,- import_index,- });- let undefined = generator.add_constant_undefined();- generator.emit(Instruction::Mov {- dst: this_value,- src: undefined.operand(),- });- }- None => {- let cache = generator.next_environment_coordinate_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::DynamicGetCalleeAndThisFromEnvironment {- value_feedback,- callee,- this_value,- identifier,- cache,- });- }- }-}--fn emit_initialize_lexical_binding(generator: &mut Generator, identifier: IdentifierTableIndex, src: Operand) {- if let Some(cache) = generator.environment_coordinate_for_identifier(identifier) {- generator.emit(Instruction::InitializeLexicalBinding { identifier, src, cache });- } else {- let cache = generator.next_environment_coordinate_cache();- generator.emit(Instruction::DynamicInitializeLexicalBinding { identifier, src, cache });- }-}--fn emit_initialize_variable_binding(generator: &mut Generator, identifier: IdentifierTableIndex, src: Operand) {- // Var bindings are resolved from vm.variable_environment(), not from the- // current lexical environment. Use the generator's variable-environment- // anchor so nested lexical scopes do not affect the coordinate hops.- if let Some(cache) = generator.variable_environment_coordinate_for_identifier(identifier) {- generator.emit(Instruction::InitializeVariableBinding { identifier, src, cache });- } else {- let cache = generator.next_environment_coordinate_cache();- generator.emit(Instruction::DynamicInitializeVariableBinding { identifier, src, cache });- }-}--fn emit_set_lexical_binding(generator: &mut Generator, identifier: IdentifierTableIndex, src: Operand) {- if let Some(cache) = generator.environment_coordinate_for_identifier(identifier) {- generator.emit(Instruction::SetLexicalBinding { identifier, src, cache });- } else {- let cache = generator.next_environment_coordinate_cache();- generator.emit(Instruction::DynamicSetLexicalBinding { identifier, src, cache });- }-}--fn emit_set_variable_binding(generator: &mut Generator, identifier: IdentifierTableIndex, src: Operand) {- // See emit_initialize_variable_binding for why var coordinates use a- // different lookup anchor than ordinary lexical operations.- if let Some(cache) = generator.variable_environment_coordinate_for_identifier(identifier) {- generator.emit(Instruction::SetVariableBinding { identifier, src, cache });- } else {- let cache = generator.next_environment_coordinate_cache();- generator.emit(Instruction::DynamicSetVariableBinding { identifier, src, cache });- }-}--fn emit_typeof_binding(generator: &mut Generator, dst: Operand, identifier: IdentifierTableIndex) {- match generator.binding_location_for_identifier(identifier) {- Some(BindingLocation::Environment(cache)) => {- generator.emit(Instruction::TypeofBinding { dst, identifier, cache });- }- Some(BindingLocation::Import(import_index)) => {- generator.emit(Instruction::GetImport {- dst,- identifier,- import_index,- });- generator.emit(Instruction::Typeof { dst, src: dst });- }- None => {- let cache = generator.next_environment_coordinate_cache();- generator.emit(Instruction::DynamicTypeofBinding { dst, identifier, cache });- }- }-}--fn set_pending_lhs_name_for_identifier_assignment(- generator: &mut Generator,- identifier: StringId,- lhs_is_parenthesized: bool,-) {- // https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation- // If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of- // |LeftHandSideExpression| is *true*, then- // A parenthesized identifier can be a simple assignment target, but it is not an IdentifierRef.- generator.pending_lhs_name = if lhs_is_parenthesized {- None- } else {- Some(generator.intern_identifier_id(identifier))- };-}--fn generate_expression_inner(- expression: &Expression,- generator: &mut Generator,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // NamedEvaluation: only function/class expressions consume pending_lhs_name.- // Clear it for all other expression types so it doesn't leak through to- // nested function expressions (e.g. IIFEs: `let x = (function() { ... })()`).- if !matches!(expression.inner, ExpressionKind::Function(_) | ExpressionKind::Class(_)) {- generator.pending_lhs_name = None;- }- if !matches!(expression.inner, ExpressionKind::Class(_)) {- generator.pending_computed_class_name = None;- }-- match &expression.inner {- // === Literals ===- ExpressionKind::NumericLiteral(value) => Some(generator.add_constant_number(*value)),-- ExpressionKind::BooleanLiteral(value) => Some(generator.add_constant_boolean(*value)),-- ExpressionKind::NullLiteral => Some(generator.add_constant_null()),-- ExpressionKind::StringLiteral(value) => Some(generator.add_constant_string((**value).clone())),-- ExpressionKind::BigIntLiteral(value) => {- let digits = bigint_literal_digits(value);- Some(generator.add_constant_bigint(ascii_code_units_to_string(digits)?))- }-- ExpressionKind::RegExpLiteral(data) => {- let source_index = generator.intern_string(&data.pattern);- let flags_index = generator.intern_string(&data.flags);- let dst = choose_dst(generator, preferred_dst);- generator.emit(Instruction::NewRegExp {- dst: dst.operand(),- source_index,- flags_index,- });- Some(dst)- }-- // === Identifiers ===- ExpressionKind::Identifier(ident) => Some(generate_identifier(*ident, generator, preferred_dst)),-- // === This ===- ExpressionKind::This => {- // OPTIMIZATION: When this_value_needs_environment_resolution is false,- // `this` is already cached in the function's this register.- if generator.this_value_needs_environment_resolution {- emit_resolve_this_if_needed(generator);- }- Some(generator.this_value())- }-- // === Unary ===- ExpressionKind::Unary { op, operand } => generate_unary_expression(generator, *op, operand, preferred_dst),-- // === Binary ===- ExpressionKind::Binary(data) => {- generate_binary_expression(generator, data.op, &data.lhs, &data.rhs, preferred_dst)- }-- // === Logical (short-circuit) ===- ExpressionKind::Logical(data) => generate_logical(generator, data.op, &data.lhs, &data.rhs, preferred_dst),-- // === Conditional (ternary) ===- ExpressionKind::Conditional(data) => {- generate_conditional(generator, &data.test, &data.consequent, &data.alternate, preferred_dst)- }-- // === Sequence ===- ExpressionKind::Sequence(expressions) => {- let mut last = None;- for expression in expressions.iter() {- last = generate_expression(expression, generator, None);- if generator.is_current_block_terminated() {- break;- }- }- last- }-- // === Function expressions ===- ExpressionKind::Function(function_id) => {- Some(generate_function_expression(generator, *function_id, preferred_dst))- }-- // === Array ===- ExpressionKind::Array(elements) => Some(generate_array_expression(generator, elements, preferred_dst)),-- // === Member access ===- ExpressionKind::Member(data) => {- generate_member_expression(generator, &data.object, &data.property, data.computed, preferred_dst)- }-- // === Call ===- ExpressionKind::Call(data) => generate_call_expression(generator, data, preferred_dst, false),-- // === New ===- ExpressionKind::New(data) => generate_call_expression(generator, data, preferred_dst, true),-- // === Spread ===- ExpressionKind::Spread(inner) => {- // Spread is handled by the caller (Call, Array, Object)- Some(generate_expression_or_undefined(inner, generator, preferred_dst))- }-- // === Yield ===- ExpressionKind::Yield(data) => Some(generate_yield_expression(- generator,- data.argument.as_deref(),- data.is_yield_from,- )),-- // === Await ===- ExpressionKind::Await(inner) => {- let value = generate_expression_or_undefined(inner, generator, None);- // Allocate received_completion registers before the await.- let received_completion = generator.allocate_register();- let received_completion_type = generator.allocate_register();- let received_completion_value = generator.allocate_register();- let acc = generator.accumulator();- generator.emit_mov(&received_completion, &acc);- Some(generate_await_with_completions(- generator,- &value,- &received_completion,- &received_completion_type,- &received_completion_value,- ))- }-- // === MetaProperty ===- ExpressionKind::MetaProperty(MetaPropertyType::NewTarget) => {- let dst = choose_dst(generator, preferred_dst);- generator.emit(Instruction::GetNewTarget { dst: dst.operand() });- Some(dst)- }-- ExpressionKind::MetaProperty(MetaPropertyType::ImportMeta) => {- let dst = choose_dst(generator, preferred_dst);- generator.emit(Instruction::GetImportMeta { dst: dst.operand() });- Some(dst)- }-- // === ImportCall ===- ExpressionKind::ImportCall(ic_data) => {- let spec = generate_expression(&ic_data.specifier, generator, None)?;- let spec = copy_if_reassignable_by(generator, spec, ic_data.options.as_deref());- let opts = match &ic_data.options {- Some(o) => generate_expression(o, generator, None)?,- None => generator.add_constant_undefined(),- };- let dst = choose_dst(generator, preferred_dst);- generator.emit(Instruction::ImportCall {- dst: dst.operand(),- specifier: spec.operand(),- options: opts.operand(),- });- Some(dst)- }-- // === Update (++/--) ===- ExpressionKind::Update(data) => generate_update_expression(generator, data.op, &data.argument, data.prefixed),-- // === Assignment ===- ExpressionKind::Assignment(data) => generate_assignment_expression(- generator,- data.op,- &data.lhs,- &data.rhs,- data.lhs_is_parenthesized,- preferred_dst,- ),-- // === Template literals ===- ExpressionKind::TemplateLiteral(data) => generate_template_literal(generator, data, preferred_dst),-- // === Tagged template literals ===- ExpressionKind::TaggedTemplateLiteral(data) => Some(generate_tagged_template_literal(- generator,- &data.tag,- &data.template_literal,- preferred_dst,- )),-- // === Object ===- ExpressionKind::Object(data) => Some(generate_object_expression(generator, data, preferred_dst)),-- // === OptionalChain ===- ExpressionKind::OptionalChain(oc_data) => {- // Allocate current_base first, current_value second.- let current_base = generator.allocate_register();- let current_value = choose_dst(generator, preferred_dst);- let undef = generator.add_constant_undefined();- generator.emit_mov(¤t_base, &undef);- generate_optional_chain_inner(- generator,- &oc_data.base,- &oc_data.references,- ¤t_value,- ¤t_base,- )?;- Some(current_value)- }-- // === SuperCall ===- ExpressionKind::SuperCall(data) => {- // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation- // 3. Let _superConstructor_ be GetSuperConstructor().- // 4. Let _argList_ be ? ArgumentListEvaluation of |Arguments|.- let super_constructor = generator.allocate_register();- generator.emit(Instruction::GetSuperConstructor {- dst: super_constructor.operand(),- });-- let arguments = if data.is_synthetic {- // Synthetic constructor: super(...arguments) — single spread argument,- // don't call @@iterator on %Array.prototype%.- assert!(data.arguments.len() == 1 && data.arguments[0].is_spread);- generate_expression_or_undefined(&data.arguments[0].value, generator, None)- } else {- generate_arguments_array(generator, &data.arguments)- };-- let dst = choose_dst(generator, preferred_dst);- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::SuperCallWithArgumentArray {- value_feedback,- call_feedback,- dst: dst.operand(),- super_constructor: super_constructor.operand(),- arguments: arguments.operand(),- is_synthetic: data.is_synthetic,- });- Some(dst)- }-- ExpressionKind::Super => {- // super keyword as an expression (for super.foo, super[foo])- // Returns the home object's prototype- let dst = choose_dst(generator, preferred_dst);- generator.emit(Instruction::ResolveSuperBase { dst: dst.operand() });- Some(dst)- }-- ExpressionKind::Class(data) => Some(generate_class_expression(generator, data, preferred_dst)),-- ExpressionKind::PrivateIdentifier(_) => {- // Private identifiers are handled by member access codegen- None- }-- ExpressionKind::Error => None,- }-}--fn generate_unary_expression(- generator: &mut Generator,- op: UnaryOp,- operand: &Expression,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // typeof and delete on identifiers need special handling BEFORE- // evaluating the operand to avoid throwing on unresolvable references.- // Allocate dst before evaluating typeof/not operands.- if op == UnaryOp::Typeof {- let arena = generator.arena.clone();- if let ExpressionKind::Identifier(ident) = &operand.inner- && !arena.identifiers[*ident].is_local()- {- let dst = choose_dst(generator, preferred_dst);- let id = generator.intern_identifier_id(arena.identifiers[*ident].name);- if arena.identifiers[*ident].is_global {- let cache = generator.next_global_variable_cache();- generator.emit(Instruction::TypeofGlobal {- dst: dst.operand(),- identifier: id,- cache,- });- } else {- emit_typeof_binding(generator, dst.operand(), id);- }- return Some(dst);- }- let dst = choose_dst(generator, preferred_dst);- let value = generate_expression(operand, generator, None)?;- generator.emit(Instruction::Typeof {- dst: dst.operand(),- src: value.operand(),- });- return Some(dst);- }- if op == UnaryOp::Delete {- return Some(emit_delete_reference(generator, operand));- }-- // Allocate dst before operand.- // Also optimize !!x -> ToBoolean(x).- if op == UnaryOp::Not {- let dst = choose_dst(generator, preferred_dst);- if let ExpressionKind::Unary {- op: UnaryOp::Not,- operand: inner,- } = &operand.inner- {- let value = generate_expression(inner, generator, None)?;- if let Some(folded) = try_constant_fold_to_boolean(generator, &value) {- return Some(folded);- }- generator.emit(Instruction::ToBoolean {- dst: dst.operand(),- value: value.operand(),- });- return Some(dst);- }- let value = generate_expression(operand, generator, None)?;- if let Some(folded) = try_constant_fold_unary(generator, op, &value) {- return Some(folded);- }- generator.emit(Instruction::Not {- dst: dst.operand(),- src: value.operand(),- });- return Some(dst);- }-- let value = generate_expression(operand, generator, None)?;-- // OPTIMIZATION: constant fold unary operations on constants.- if let Some(folded) = try_constant_fold_unary(generator, op, &value) {- return Some(folded);- }-- let dst = choose_dst(generator, preferred_dst);- match op {- UnaryOp::BitwiseNot => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseNot {- arith_feedback,- dst: dst.operand(),- src: value.operand(),- });- }- UnaryOp::Not => unreachable!("Not is handled by early return above"),- UnaryOp::Plus => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::UnaryPlus {- arith_feedback,- dst: dst.operand(),- src: value.operand(),- });- }- UnaryOp::Minus => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::UnaryMinus {- arith_feedback,- dst: dst.operand(),- src: value.operand(),- });- }- UnaryOp::Typeof => unreachable!("Typeof is handled by early return above"),- UnaryOp::Void => {- return Some(generator.add_constant_undefined());- }- UnaryOp::Delete => unreachable!("Delete is handled by early return above"),- }- Some(dst)-}--fn might_contain_assignment_expression(expression: &Expression) -> bool {- match &expression.inner {- ExpressionKind::NumericLiteral(_)- | ExpressionKind::StringLiteral(_)- | ExpressionKind::BooleanLiteral(_)- | ExpressionKind::NullLiteral- | ExpressionKind::Identifier(_)- | ExpressionKind::PrivateIdentifier(_) => false,- ExpressionKind::Unary { op: _, operand } => might_contain_assignment_expression(operand),- ExpressionKind::Binary(data) => {- might_contain_assignment_expression(&data.lhs) || might_contain_assignment_expression(&data.rhs)- }- ExpressionKind::Member(data) => {- might_contain_assignment_expression(&data.object) || might_contain_assignment_expression(&data.property)- }- // Conservatively consider everything else, including assignments themselves as potentially- // assigning.- _ => true,- }-}--/// Copy a local operand that evaluating any of the later expressions might reassign.-fn copy_if_reassignable_by<'a>(- generator: &mut Generator,- operand: ScopedOperand,- later: impl IntoIterator<Item = &'a Expression>,-) -> ScopedOperand {- if later.into_iter().any(might_contain_assignment_expression) {- generator.copy_if_needed_to_preserve_evaluation_order(&operand)- } else {- operand- }-}--fn generate_binary_expression(- generator: &mut Generator,- op: BinaryOp,- lhs: &Expression,- rhs: &Expression,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // Special case: `#privateId in obj` uses HasPrivateId instead of In.- if op == BinaryOp::In- && let ExpressionKind::PrivateIdentifier(priv_ident) = &lhs.inner- {- let base = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- let id = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::HasPrivateId {- dst: dst.operand(),- base: base.operand(),- property: id,- });- return Some(dst);- }- // OPTIMIZATION: Pre-convert numeric literal operands of bitwise- // operations to i32/u32 to avoid runtime conversion.- let lhs_val = match op {- BinaryOp::BitwiseAnd- | BinaryOp::BitwiseOr- | BinaryOp::BitwiseXor- | BinaryOp::LeftShift- | BinaryOp::RightShift- | BinaryOp::UnsignedRightShift => {- if let ExpressionKind::NumericLiteral(n) = &lhs.inner {- generator.add_constant_number(to_int32(*n) as f64)- } else {- generate_expression(lhs, generator, None)?- }- }- _ => generate_expression(lhs, generator, None)?,- };-- // OPTIMIZATION: We do need to make a copy of the LHS here in case evaluation of the RHS- // reassigns it. However, binary expressions are a pretty common thing, so doing the copy- // unconditionally is a noticable performance hit, especially because in practice, the copy is- // almost never needed. We add a small heuristic here that detects the most common cases.- // FIXME: This is a pretty narrow optimization. Maybe instead, it would make sense to have a- // more general "remove unnecessary mov-operations" as part of a bytecode optimization pass.- let lhs_val = if might_contain_assignment_expression(rhs) {- generator.copy_if_needed_to_preserve_evaluation_order(&lhs_val)- } else {- lhs_val- };-- let rhs_val = match op {- BinaryOp::BitwiseAnd | BinaryOp::BitwiseOr | BinaryOp::BitwiseXor => {- if let ExpressionKind::NumericLiteral(n) = &rhs.inner {- generator.add_constant_number(to_int32(*n) as f64)- } else {- generate_expression(rhs, generator, None)?- }- }- BinaryOp::LeftShift | BinaryOp::RightShift | BinaryOp::UnsignedRightShift => {- if let ExpressionKind::NumericLiteral(n) = &rhs.inner {- generator.add_constant_number(to_u32(*n) as f64)- } else {- generate_expression(rhs, generator, None)?- }- }- _ => generate_expression(rhs, generator, None)?,- };- // OPTIMIZATION: constant folding for binary operations on constants.- if let Some(folded) = try_constant_fold_binary(generator, op, &lhs_val, &rhs_val) {- return Some(folded);- }- let dst = choose_dst(generator, preferred_dst);- emit_binary_op(generator, op, &dst, &lhs_val, &rhs_val);- Some(dst)-}--fn generate_function_expression(- generator: &mut Generator,- function_id: FunctionId,- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- let should_eager_compile = generator.eager_compile_function_ids.contains(&function_id);- let data = generator.function_table.take(function_id);- let has_name = data.name.is_some();- // OPTIMIZATION: Nothing observes the scope of a name the function never looks up.- let binds_name = has_name- && match &data.body.inner {- StatementKind::FunctionBody { scope, .. } => !generator.arena.scopes[*scope].function_name_is_unused,- _ => true,- };-- // Named function expressions get an intermediate scope so the name- // is visible inside the function body but not outside.- let name_id = if binds_name {- let parent = generator- .lexical_environment_register_stack- .last()- .cloned()- .unwrap_or_else(|| generator.add_constant_undefined());- let new_env = generator.allocate_register();- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- let shape_cache = generator.next_environment_shape_cache();- generator.emit(Instruction::CreateLexicalEnvironment {- dst: new_env.operand(),- parent: parent.operand(),- capacity: 1,- shape_cache,- is_catch_environment: false,- });- generator.push_static_lexical_environment(new_env);-- let name_id = data.name.expect("function declaration must have a name");- let arena = generator.arena.clone();- let id = generator.intern_identifier_id(arena.identifiers[name_id].name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: true,- is_global: false,- is_strict: false,- });- Some(id)- } else {- None- };-- let dst = choose_dst(generator, preferred_dst);- // For anonymous function expressions, use the pending LHS name- // as the function's .name property.- let lhs_name = if !has_name {- generator.pending_lhs_name.take()- } else {- None- };- let lhs_name_str: Option<Utf16String> =- lhs_name.map(|index| Utf16String::from(generator.identifier_table[index.0 as usize].to_utf16().as_ref()));- let name_override = if !has_name { lhs_name_str.as_deref() } else { None };- let shared_function_data_index = emit_new_function(generator, data, name_override);- if should_eager_compile- && let Some(pending) = generator- .shared_function_data- .get_mut(shared_function_data_index as usize)- {- pending.should_eager_compile = true;- }- let home_object = generator.home_objects.last().map(|ho| ho.operand());- generator.emit(Instruction::NewFunction {- dst: dst.operand(),- shared_function_data_index,- lhs_name,- home_object,- });-- if let Some(name_id) = name_id {- emit_initialize_lexical_binding(generator, name_id, dst.operand());-- generator.end_variable_scope();- }- dst-}--fn generate_array_expression(- generator: &mut Generator,- elements: &[Option<Expression>],- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- // If all elements are constant primitives, emit NewPrimitiveArray.- if !elements.is_empty()- && elements.iter().all(|e| match e {- None => true, // holes- Some(e) => matches!(- e.inner,- ExpressionKind::NumericLiteral(_) | ExpressionKind::BooleanLiteral(_) | ExpressionKind::NullLiteral- ),- })- {- let values: Vec<u64> = elements- .iter()- .map(|e| match e {- None => nanboxed_empty(),- Some(e) => match &e.inner {- ExpressionKind::NumericLiteral(n) => nanboxed_number(*n),- ExpressionKind::BooleanLiteral(b) => nanboxed_boolean(*b),- ExpressionKind::NullLiteral => nanboxed_null(),- _ => unreachable!("all elements verified as primitive literals above"),- },- })- .collect();- let dst = choose_dst(generator, preferred_dst);- generator.emit(Instruction::NewPrimitiveArray {- dst: dst.operand(),- element_count: u32_from_usize(values.len()),- elements: values,- });- return dst;- }-- // Find the first spread element.- let first_spread = elements- .iter()- .position(|e| matches!(e, Some(element) if matches!(element.inner, ExpressionKind::Spread(_))));-- // Collect elements before the first spread into a NewArray.- let pre_spread_count = first_spread.unwrap_or(elements.len());- let mut scoped_arguments: Vec<ScopedOperand> = Vec::with_capacity(pre_spread_count);- for element in &elements[..pre_spread_count] {- match element {- Some(e) => {- let val = generate_expression_or_undefined(e, generator, None);- scoped_arguments.push(generator.copy_if_needed_to_preserve_evaluation_order(&val));- }- None => {- scoped_arguments.push(generator.add_constant_empty());- }- }- }- let dst = choose_dst(generator, preferred_dst);- let arguments: Vec<Operand> = scoped_arguments.iter().map(|s| s.operand()).collect();- generator.emit(Instruction::NewArray {- dst: dst.operand(),- element_count: u32_from_usize(arguments.len()),- elements: arguments,- });-- // NB: Keep scoped_arguments alive until the end of the expression- // so their registers aren't reused during spread evaluation.-- // Append elements after the first spread using ArrayAppend.- if let Some(spread_index) = first_spread {- for element in &elements[spread_index..] {- match element {- None => {- let empty = generator.add_constant_empty();- generator.emit(Instruction::ArrayAppend {- dst: dst.operand(),- src: empty.operand(),- is_spread: false,- });- }- Some(e) => {- let is_spread = matches!(e.inner, ExpressionKind::Spread(_));- let val = generate_expression_or_undefined(e, generator, None);- generator.emit(Instruction::ArrayAppend {- dst: dst.operand(),- src: val.operand(),- is_spread,- });- }- }- }- }-- dst-}--fn generate_member_expression(- generator: &mut Generator,- object: &Expression,- property: &Expression,- computed: bool,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let is_super = matches!(object.inner, ExpressionKind::Super);- if is_super {- // Per spec, evaluation order for super property access is:- // 1. Resolve this binding- // 2. Evaluate computed property (if any)- // 3. Resolve super base- // 4. Property lookup with this- let this_value = emit_resolve_this_binding(generator);- let computed_key = if computed {- Some(generate_expression(property, generator, None)?)- } else {- None- };- let super_base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase {- dst: super_base.operand(),- });- let dst = choose_dst(generator, preferred_dst);- if let Some(key) = computed_key {- emit_get_by_value_with_this(generator, &dst, &super_base, &key, &this_value);- } else if let ExpressionKind::Identifier(ident) = &property.inner {- let arena = generator.arena.clone();- emit_get_by_id_with_this(generator, &dst, &super_base, arena.name_slice(*ident), &this_value);- }- return Some(dst);- }- let obj = generate_expression(object, generator, None)?;- let obj = copy_if_reassignable_by(generator, obj, [property]);- let base_id = intern_base_identifier(generator, object);- if computed {- let property = generate_expression(property, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- emit_get_by_value(generator, &dst, &obj, &property, base_id);- return Some(dst);- }- // Non-computed: property must be an Identifier- let dst = choose_dst(generator, preferred_dst);- if let ExpressionKind::Identifier(ident) = &property.inner {- let arena = generator.arena.clone();- emit_get_by_id(generator, &dst, &obj, arena.name_slice(*ident), base_id);- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &property.inner {- let id = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::GetPrivateById {- dst: dst.operand(),- base: obj.operand(),- property: id,- });- }- Some(dst)-}--fn generate_yield_expression(- generator: &mut Generator,- argument: Option<&Expression>,- is_yield_from: bool,-) -> ScopedOperand {- // Allocate completion registers before evaluating the argument.- let received_completion = generator.allocate_register();- let received_completion_type = generator.allocate_register();- let received_completion_value = generator.allocate_register();-- let value = if let Some(argument) = argument {- generate_expression_or_undefined(argument, generator, None)- } else {- generator.add_constant_undefined()- };-- if is_yield_from {- return generate_yield_from(- generator,- value,- &received_completion,- &received_completion_type,- &received_completion_value,- );- }-- // Create continuation block, call generate_yield, then handle- // completion checking.- let continuation_block = generator.make_block();- let is_in_finalizer = generator.is_in_finalizer();-- // Save exception register before yielding if in a finalizer,- // as the act of yielding clears scheduled exceptions.- let saved_exception = if is_in_finalizer {- let reg = generator.allocate_register();- generator.emit_mov_raw(reg.operand(), generator.exception_operand());- Some(reg)- } else {- None- };-- generate_yield(- generator,- continuation_block,- &value,- &received_completion,- &received_completion_type,- &received_completion_value,- if generator.is_in_async_generator_function() {- YieldBehavior::AwaitValue- } else {- YieldBehavior::Normal- },- );-- generator.switch_to_basic_block(continuation_block);-- // Restore exception register after resuming.- if let Some(ref saved) = saved_exception {- generator.emit_mov_raw(generator.exception_operand(), saved.operand());- }-- let acc = generator.accumulator();- generator.emit_mov(&received_completion, &acc);- generator.emit(Instruction::GetCompletionFields {- type_dst: received_completion_type.operand(),- value_dst: received_completion_value.operand(),- completion: received_completion.operand(),- });-- let normal_block = generator.make_block();- let throw_cont = generator.make_block();- let type_is_normal = generator.allocate_register();- let normal_type = generator.add_constant_number(f64::from(CompletionType::Normal as u32));- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: type_is_normal.operand(),- lhs: received_completion_type.operand(),- rhs: normal_type.operand(),- });- generator.emit_jump_if(&type_is_normal, normal_block, throw_cont);-- let throw_value_block = generator.make_block();- let return_value_block = generator.make_block();-- generator.switch_to_basic_block(throw_cont);- let type_is_throw = generator.allocate_register();- let throw_type = generator.add_constant_number(f64::from(CompletionType::Throw as u32));- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: type_is_throw.operand(),- lhs: received_completion_type.operand(),- rhs: throw_type.operand(),- });- generator.emit_jump_if(&type_is_throw, throw_value_block, return_value_block);-- generator.switch_to_basic_block(throw_value_block);- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw {- src: received_completion_value.operand(),- });-- generator.switch_to_basic_block(return_value_block);- generator.generate_return(&received_completion_value);-- generator.switch_to_basic_block(normal_block);- received_completion_value-}--/// Generate bytecode for an expression, returning `undefined` if the-/// expression produces no value (e.g. the block was already terminated).-fn generate_expression_or_undefined(- expression: &Expression,- generator: &mut Generator,- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- generate_expression(expression, generator, preferred_dst).unwrap_or_else(|| generator.add_constant_undefined())-}--/// Generate bytecode for a statement.-pub fn generate_statement(- statement: &Statement,- generator: &mut Generator,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let saved_source_start = generator.current_source_start;- let saved_source_end = generator.current_source_end;- generator.current_source_start = statement.range.start;- generator.current_source_end = statement.range.end;-- let result = match &statement.inner {- StatementKind::Empty | StatementKind::Error | StatementKind::ErrorDeclaration => None,- StatementKind::Debugger => {- generator.emit(Instruction::Debugger {});- None- }-- // === ExpressionStatement ===- StatementKind::Expression(expression) => generate_expression(expression, generator, None),-- // === Block ===- StatementKind::Block(scope) => {- let arena = generator.arena.clone();- generate_block_statement(generator, &arena.scopes[*scope], preferred_dst)- }-- // === FunctionBody ===- StatementKind::FunctionBody { scope, .. } => {- let arena = generator.arena.clone();- generate_scope_children_with_disposal(generator, &arena.scopes[*scope], preferred_dst)- }-- // === Program ===- // Note: GlobalDeclarationInstantiation (GDI) runs before this bytecode- // executes. GDI hoists top-level function declarations and var bindings- // to the global scope, including Annex B function-in-block hoisting.- StatementKind::Program(data) => {- // Populate annexb_function_names so switch codegen can emit- // GetBinding + SetVariableBinding for AnnexB-hoisted functions- // (Annex B requires switch cases to copy the block-scoped binding- // into the var-scoped binding on each case entry).- let arena = generator.arena.clone();- let scope = &arena.scopes[data.scope];- for name in &scope.annexb_function_names {- generator.annexb_function_names.insert(name.clone());- }- generate_scope_children_with_disposal(generator, scope, preferred_dst)- }-- // === If ===- StatementKind::If(data) => generate_if_statement(- generator,- &data.test,- &data.consequent,- data.alternate.as_deref(),- preferred_dst,- ),-- // === While ===- StatementKind::While(data) => generate_while_statement(generator, &data.test, &data.body, preferred_dst),-- // === DoWhile ===- StatementKind::DoWhile(data) => generate_do_while_statement(generator, &data.test, &data.body, preferred_dst),-- // === For ===- StatementKind::For(data) => generate_for_statement(- generator,- data.init.as_ref(),- data.test.as_deref(),- data.update.as_deref(),- &data.body,- preferred_dst,- ),-- // === Return ===- StatementKind::Return(value) => {- let val = match value {- Some(expression) => {- let v = generate_expression_or_undefined(expression, generator, None);- if generator.is_in_async_generator_function() {- let received_completion = generator.allocate_register();- let received_completion_type = generator.allocate_register();- let received_completion_value = generator.allocate_register();- generate_await_with_completions(- generator,- &v,- &received_completion,- &received_completion_type,- &received_completion_value,- )- } else {- v- }- }- None => generator.add_constant_undefined(),- };- generator.generate_return(&val);- None- }-- // === Throw ===- StatementKind::Throw(expression) => {- let val = generate_expression(expression, generator, None)?;- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw { src: val.operand() });- None- }-- // === Variable declarations ===- StatementKind::VariableDeclaration(data) => {- generate_variable_declaration(generator, data.kind, &data.declarations);- None- }-- // === Break ===- StatementKind::Break { target_label } => {- generator.generate_break(target_label.as_deref());- None- }-- // === Continue ===- StatementKind::Continue { target_label } => {- generator.generate_continue(target_label.as_deref());- None- }-- // === Labelled ===- StatementKind::Labelled(data) => generate_labelled_statement(generator, &data.label, &data.item, preferred_dst),-- // === Switch ===- StatementKind::Switch(data) => generate_switch_statement(generator, data, preferred_dst),-- // === Try ===- StatementKind::Try(data) => generate_try_statement(generator, data, preferred_dst),-- // === FunctionDeclaration ===- StatementKind::FunctionDeclaration(fd) => {- if fd.is_hoisted {- // Annex B.3.3: Copy the function from the lexical (block) scope- // to the var scope.- if let Some(name_ident) = fd.name {- let arena = generator.arena.clone();- let id = generator.intern_identifier_id(arena.identifiers[name_ident].name);- let value = generator.allocate_register();- emit_get_binding(generator, value.operand(), id, false);- emit_set_variable_binding(generator, id, value.operand());- }- }- None- }-- // === With ===- StatementKind::With(data) => {- let obj = generate_expression(&data.object, generator, None)?;- let object_environment = generator.allocate_register();- generator.emit(Instruction::EnterObjectEnvironment {- dst: object_environment.operand(),- object: obj.operand(),- });- generator.push_dynamic_lexical_environment(object_environment);- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);-- let with_completion = generator.allocate_completion_register();- let result = generate_with_completion(- &data.body,- generator,- with_completion.as_ref(),- with_completion.as_ref().or(preferred_dst),- );-- generator.end_variable_scope();-- // Return ? UpdateEmpty(_stmtCompletion_, *undefined*).- Some(with_completion.unwrap_or_else(|| result.unwrap_or_else(|| generator.add_constant_undefined())))- }-- // === ForIn / ForOf / ForAwaitOf ===- StatementKind::ForInOf(data) => {- generate_for_in_of_statement(generator, data.kind, &data.lhs, &data.rhs, &data.body, preferred_dst)- }-- // === UsingDeclaration / AwaitUsingDeclaration ===- StatementKind::UsingDeclaration(data) => {- generate_using_declaration(generator, data);- None- }-- // === ClassDeclaration ===- StatementKind::ClassDeclaration(data) => {- let value = generate_class_expression(generator, data, None);- // Bind the class name in the outer scope (classes are lexically scoped).- // Use InitializeLexicalBinding since the name starts in the TDZ- // (temporal dead zone) until this point, matching `let` semantics.- // NB: We do NOT mark the local as initialized here, preserving- // TDZ checks for subsequent uses of the class name.- if let Some(name_ident_id) = data.name {- let arena = generator.arena.clone();- let name_ident = &arena.identifiers[name_ident_id];- if name_ident.is_local() {- let local = generator.resolve_local(name_ident.local_index, name_ident.local_type.unwrap());- generator.emit_mov(&local, &value);- } else {- let id = generator.intern_identifier_id(name_ident.name);- emit_initialize_lexical_binding(generator, id, value.operand());- }- }- None- }-- // === Import/Export ===- StatementKind::Import(_) => None, // Handled by module loading- StatementKind::Export(export_data) => {- if !export_data.is_default_export {- // Non-default export: generate code for the wrapped statement.- if let Some(ref child_statement) = export_data.statement {- generate_statement(child_statement, generator, None)- } else {- None- }- } else if let Some(ref child_statement) = export_data.statement {- match &child_statement.inner {- StatementKind::FunctionDeclaration(_) | StatementKind::ClassDeclaration(_) => {- generate_statement(child_statement, generator, None)- }- _ => {- // export default <expression>- // The child_statement wraps an Expression via StatementKind::Expression.- let default_name: Utf16String = Utf16String::from(utf16!("default"));- generator.pending_lhs_name = Some(generator.intern_identifier(&default_name));- let value = generate_statement(child_statement, generator, None);- generator.pending_lhs_name = None;- if let Some(value) = value {- let local_name = generator.intern_identifier(utf16!("*default*"));- emit_initialize_lexical_binding(generator, local_name, value.operand());- Some(value)- } else {- None- }- }- }- } else {- None- }- }-- // === ClassFieldInitializer ===- StatementKind::ClassFieldInitializer(data) => {- // https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody- // Initializer : = AssignmentExpression- // 3. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then- // a. Let value be ? NamedEvaluation of Initializer with argument func.[[ClassFieldInitializerName]].- // 4. Else,- // a. Let rhs be ? Evaluation of AssignmentExpression.- // b. Let value be ? GetValue(rhs).- let value = if let Some(field_name) = &data.field_name {- generator.pending_lhs_name = Some(generator.intern_identifier(field_name));- let value = generate_expression_or_undefined(&data.expression, generator, None);- generator.pending_lhs_name = None;- value- } else if is_anonymous_function_definition(generator, &data.expression) {- // NB: A computed key is only known once the class is defined, so the function reads it.- let name = generator.allocate_register();- generator.emit(Instruction::GetClassFieldInitializerName { dst: name.operand() });- if matches!(data.expression.inner, ExpressionKind::Class(_)) {- generator.pending_computed_class_name = Some(name);- generate_expression_or_undefined(&data.expression, generator, None)- } else {- let value = generate_expression_or_undefined(&data.expression, generator, None);- emit_set_function_name(generator, &value, &name, FunctionNamePrefix::None);- value- }- } else {- generate_expression_or_undefined(&data.expression, generator, None)- };- // 5. Return ReturnCompletion(value).- generator.emit(Instruction::Return { value: value.operand() });- None- }- };-- generator.current_source_start = saved_source_start;- generator.current_source_end = saved_source_end;- result-}--// =============================================================================-// Await helper-// =============================================================================--#[derive(Clone, Copy, PartialEq, Eq)]-enum YieldBehavior {- Normal,- AwaitValue,- IteratorResult,-}--/// Like generate_await but uses caller-provided completion registers.-///-/// Returns the received_completion_value on the normal path.-/// Emits a Throw on the throw path.-fn generate_await_with_completions(- generator: &mut Generator,- argument: &ScopedOperand,- received_completion: &ScopedOperand,- received_completion_type: &ScopedOperand,- received_completion_value: &ScopedOperand,-) -> ScopedOperand {- let continuation = generator.make_block();- generator.emit(Instruction::Await {- continuation_label: continuation,- argument: argument.operand(),- });- generator.switch_to_basic_block(continuation);-- let acc = generator.accumulator();- generator.emit_mov(received_completion, &acc);- generator.emit(Instruction::GetCompletionFields {- type_dst: received_completion_type.operand(),- value_dst: received_completion_value.operand(),- completion: received_completion.operand(),- });-- let normal_block = generator.make_block();- let throw_block = generator.make_block();- let is_normal = generator.allocate_register();- let normal_type = generator.add_constant_number(f64::from(CompletionType::Normal as u32));- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: is_normal.operand(),- lhs: received_completion_type.operand(),- rhs: normal_type.operand(),- });- generator.emit_jump_if(&is_normal, normal_block, throw_block);-- generator.switch_to_basic_block(throw_block);- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw {- src: received_completion_value.operand(),- });-- generator.switch_to_basic_block(normal_block);- received_completion_value.clone()-}--/// Yield* (yield from) delegation.-///-/// Implements the iterator delegation protocol from-/// https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation-///-/// The delegating generator forwards next/throw/return to the inner iterator.-fn generate_yield_from(- generator: &mut Generator,- value: ScopedOperand,- received_completion: &ScopedOperand,- received_completion_type: &ScopedOperand,- received_completion_value: &ScopedOperand,-) -> ScopedOperand {- let is_async = generator.is_in_async_generator_function();-- // 4. Let iteratorRecord be ? GetIterator(value, generatorKind).- let iterator = generator.allocate_register();- let next_method = generator.allocate_register();- let iterator_done_property = generator.allocate_register();- let hint = if is_async {- IteratorHint::Async- } else {- IteratorHint::Sync- } as u32;- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetIterator {- dst_iterator_object: iterator.operand(),- dst_iterator_next: next_method.operand(),- dst_iterator_done: iterator_done_property.operand(),- iterable: value.operand(),- hint,- // NB: yield* passes the iterator to calls of its methods.- fast_array_mode_allowed: false,- cache,- });-- // 6. Let received be NormalCompletion(undefined).- let normal_const = generator.add_constant_number(f64::from(CompletionType::Normal as u32));- generator.emit_mov(received_completion_type, &normal_const);- let undef = generator.add_constant_undefined();- generator.emit_mov(received_completion_value, &undef);-- // 7. Repeat,- let loop_block = generator.make_block();- let continuation_block = generator.make_block();- let loop_end_block = generator.make_block();- generator.emit(Instruction::Jump { target: loop_block });- generator.switch_to_basic_block(loop_block);-- // Branch on received.[[Type]].- let type_is_normal_block = generator.make_block();- let is_type_throw_block = generator.make_block();- let is_normal = generator.allocate_register();- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: is_normal.operand(),- lhs: received_completion_type.operand(),- rhs: normal_const.operand(),- });- generator.emit_jump_if(&is_normal, type_is_normal_block, is_type_throw_block);-- // =========================================================================- // a. If received.[[Type]] is normal, then- // =========================================================================- generator.switch_to_basic_block(type_is_normal_block);-- // i. Let _innerResult_ be ? Call(_next_, _iterator_, « _received_.[[Value]] »).- let inner_result = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: inner_result.operand(),- callee: next_method.operand(),- this_value: iterator.operand(),- argument_count: 1,- expression_string: None,- arguments: vec![received_completion_value.operand()],- });-- // ii. If _generatorKind_ is ~async~, set _innerResult_ to ? Await(_innerResult_).- if is_async {- let awaited = generate_await_with_completions(- generator,- &inner_result,- received_completion,- received_completion_type,- received_completion_value,- );- generator.emit_mov(&inner_result, &awaited);- }-- // iii. If _innerResult_ is not an Object, throw a *TypeError* exception.- generator.emit(Instruction::ThrowIfNotObject {- src: inner_result.operand(),- });-- // iv. Let _done_ be ? IteratorComplete(_innerResult_).- let done = generator.allocate_register();- emit_get_by_id(generator, &done, &inner_result, utf16!("done"), None);-- // v. If _done_ is *true*, then return ? IteratorValue(_innerResult_).- let type_is_normal_done_block = generator.make_block();- let type_is_normal_not_done_block = generator.make_block();- generator.emit_jump_if(&done, type_is_normal_done_block, type_is_normal_not_done_block);-- generator.switch_to_basic_block(type_is_normal_done_block);- let return_value = generator.allocate_register();- emit_get_by_id(generator, &return_value, &inner_result, utf16!("value"), None);- generator.emit(Instruction::Jump { target: loop_end_block });-- // vi. If _generatorKind_ is ~async~, set _received_ to Completion(AsyncGeneratorYield(? IteratorValue(_innerResult_))).- // vii. Else, set _received_ to Completion(GeneratorYield(_innerResult_)).- generator.switch_to_basic_block(type_is_normal_not_done_block);- {- let (yield_value, yield_behavior) = if is_async {- let current_value = generator.allocate_register();- emit_get_by_id(generator, ¤t_value, &inner_result, utf16!("value"), None);- (current_value, YieldBehavior::Normal)- } else {- (inner_result.clone(), YieldBehavior::IteratorResult)- };-- generate_yield(- generator,- continuation_block,- &yield_value,- received_completion,- received_completion_type,- received_completion_value,- yield_behavior,- );- }-- // =========================================================================- // b. Else if received.[[Type]] is throw, then- // =========================================================================- generator.switch_to_basic_block(is_type_throw_block);- let type_is_throw_block = generator.make_block();- let type_is_return_block = generator.make_block();- let throw_const = generator.add_constant_number(f64::from(CompletionType::Throw as u32));- let is_throw = generator.allocate_register();- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: is_throw.operand(),- lhs: received_completion_type.operand(),- rhs: throw_const.operand(),- });- generator.emit_jump_if(&is_throw, type_is_throw_block, type_is_return_block);-- generator.switch_to_basic_block(type_is_throw_block);-- // i. Let _throw_ be ? GetMethod(_iterator_, *"throw"*).- let throw_method = generator.allocate_register();- let throw_key = generator.intern_property_key(utf16!("throw"));- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetMethod {- dst: throw_method.operand(),- object: iterator.operand(),- property: throw_key,- cache,- });-- // ii. If _throw_ is not *undefined*, then- let throw_method_defined_block = generator.make_block();- let throw_method_undefined_block = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: throw_method.operand(),- true_target: throw_method_undefined_block,- false_target: throw_method_defined_block,- });-- generator.switch_to_basic_block(throw_method_defined_block);-- // 1. Let _innerResult_ be ? Call(_throw_, _iterator_, « _received_.[[Value]] »).- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: inner_result.operand(),- callee: throw_method.operand(),- this_value: iterator.operand(),- argument_count: 1,- expression_string: None,- arguments: vec![received_completion_value.operand()],- });-- // 2. If _generatorKind_ is ~async~, set _innerResult_ to ? Await(_innerResult_).- if is_async {- let awaited = generate_await_with_completions(- generator,- &inner_result,- received_completion,- received_completion_type,- received_completion_value,- );- generator.emit_mov(&inner_result, &awaited);- }-- // 4. If _innerResult_ is not an Object, throw a *TypeError* exception.- generator.emit(Instruction::ThrowIfNotObject {- src: inner_result.operand(),- });-- // 5. Let _done_ be ? IteratorComplete(_innerResult_).- emit_get_by_id(generator, &done, &inner_result, utf16!("done"), None);-- // 6. If _done_ is *true*, return ? IteratorValue(_innerResult_).- let type_is_throw_done_block = generator.make_block();- let type_is_throw_not_done_block = generator.make_block();- generator.emit_jump_if(&done, type_is_throw_done_block, type_is_throw_not_done_block);-- generator.switch_to_basic_block(type_is_throw_done_block);- emit_get_by_id(generator, &return_value, &inner_result, utf16!("value"), None);- generator.emit(Instruction::Jump { target: loop_end_block });-- // 7. If _generatorKind_ is ~async~, set _received_ to Completion(AsyncGeneratorYield(? IteratorValue(_innerResult_))).- // 8. Else, set _received_ to Completion(GeneratorYield(_innerResult_)).- generator.switch_to_basic_block(type_is_throw_not_done_block);- {- let (yield_value, yield_behavior) = if is_async {- let current_value = generator.allocate_register();- emit_get_by_id(generator, ¤t_value, &inner_result, utf16!("value"), None);- (current_value, YieldBehavior::Normal)- } else {- (inner_result.clone(), YieldBehavior::IteratorResult)- };- generate_yield(- generator,- continuation_block,- &yield_value,- received_completion,- received_completion_type,- received_completion_value,- yield_behavior,- );- }-- // throw is undefined: close iterator, throw TypeError.- generator.switch_to_basic_block(throw_method_undefined_block);-- if is_async {- // AsyncIteratorClose: get return method, call it, await, check object.- let return_method = generator.allocate_register();- let return_key = generator.intern_property_key(utf16!("return"));- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetMethod {- dst: return_method.operand(),- object: iterator.operand(),- property: return_key,- cache,- });-- let call_return_block = generator.make_block();- let after_close = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: return_method.operand(),- true_target: after_close,- false_target: call_return_block,- });- generator.switch_to_basic_block(call_return_block);-- let close_result = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: close_result.operand(),- callee: return_method.operand(),- this_value: iterator.operand(),- argument_count: 0,- expression_string: None,- arguments: vec![],- });-- let awaited = generate_await_with_completions(- generator,- &close_result,- received_completion,- received_completion_type,- received_completion_value,- );- generator.emit(Instruction::ThrowIfNotObject { src: awaited.operand() });-- generator.emit(Instruction::Jump { target: after_close });- generator.switch_to_basic_block(after_close);- } else {- // Sync: IteratorClose with Normal completion.- let undef = generator.add_constant_undefined();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::IteratorClose {- iterator_object: iterator.operand(),- iterator_next: next_method.operand(),- iterator_done: iterator_done_property.operand(),- completion_type: CompletionType::Normal as u32,- completion_value: undef.operand(),- cache,- });- }-- // Throw a TypeError: iterator does not have a throw method.- let exception = generator.allocate_register();- let error_string = generator.intern_string(utf16!("yield* protocol violation: iterator must have a throw method"));- generator.emit(Instruction::NewTypeError {- dst: exception.operand(),- error_string,- });- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw {- src: exception.operand(),- });-- // =========================================================================- // c. Else (received.[[Type]] is return)- // =========================================================================- generator.switch_to_basic_block(type_is_return_block);-- // ii. Let _return_ be ? GetMethod(_iterator_, *"return"*).- let return_method = generator.allocate_register();- let return_key = generator.intern_property_key(utf16!("return"));- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetMethod {- dst: return_method.operand(),- object: iterator.operand(),- property: return_key,- cache,- });-- // iii. If _return_ is *undefined*, then- let return_is_undefined_block = generator.make_block();- let return_is_defined_block = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: return_method.operand(),- true_target: return_is_undefined_block,- false_target: return_is_defined_block,- });-- generator.switch_to_basic_block(return_is_undefined_block);- // 1. If _generatorKind_ is ~async~, set _received_.[[Value]] to ? Await(_received_.[[Value]]).- if is_async {- generate_await_with_completions(- generator,- received_completion_value,- received_completion,- received_completion_type,- received_completion_value,- );- }- // 2. Return _received_.- generator.generate_return(received_completion_value);-- generator.switch_to_basic_block(return_is_defined_block);-- // iv. Let _innerReturnResult_ be ? Call(_return_, _iterator_, « _received_.[[Value]] »).- let inner_return_result = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: inner_return_result.operand(),- callee: return_method.operand(),- this_value: iterator.operand(),- argument_count: 1,- expression_string: None,- arguments: vec![received_completion_value.operand()],- });-- // v. If _generatorKind_ is ~async~, set _innerReturnResult_ to ? Await(_innerReturnResult_).- if is_async {- let awaited = generate_await_with_completions(- generator,- &inner_return_result,- received_completion,- received_completion_type,- received_completion_value,- );- generator.emit_mov(&inner_return_result, &awaited);- }-- // vi. If _innerReturnResult_ is not an Object, throw a *TypeError* exception.- generator.emit(Instruction::ThrowIfNotObject {- src: inner_return_result.operand(),- });-- // vii. Let _done_ be ? IteratorComplete(_innerReturnResult_).- emit_get_by_id(generator, &done, &inner_return_result, utf16!("done"), None);-- // viii. If _done_ is *true*, then- let type_is_return_done_block = generator.make_block();- let type_is_return_not_done_block = generator.make_block();- generator.emit_jump_if(&done, type_is_return_done_block, type_is_return_not_done_block);-- generator.switch_to_basic_block(type_is_return_done_block);- let inner_return_result_value = generator.allocate_register();- emit_get_by_id(- generator,- &inner_return_result_value,- &inner_return_result,- utf16!("value"),- None,- );- generator.generate_return(&inner_return_result_value);-- // ix. If _generatorKind_ is ~async~, set _received_ to Completion(AsyncGeneratorYield(? IteratorValue(_innerReturnResult_))).- // x. Else, set _received_ to Completion(GeneratorYield(_innerReturnResult_)).- generator.switch_to_basic_block(type_is_return_not_done_block);- let (received, yield_behavior) = if is_async {- let current_value = generator.allocate_register();- emit_get_by_id(generator, ¤t_value, &inner_return_result, utf16!("value"), None);- (current_value, YieldBehavior::Normal)- } else {- (inner_return_result.clone(), YieldBehavior::IteratorResult)- };- generate_yield(- generator,- continuation_block,- &received,- received_completion,- received_completion_type,- received_completion_value,- yield_behavior,- );-- // =========================================================================- // Continuation block: resume after any yield, extract completion, loop back.- // =========================================================================- generator.switch_to_basic_block(continuation_block);- let acc = generator.accumulator();- generator.emit_mov(received_completion, &acc);- generator.emit(Instruction::GetCompletionFields {- type_dst: received_completion_type.operand(),- value_dst: received_completion_value.operand(),- completion: received_completion.operand(),- });- generator.emit(Instruction::Jump { target: loop_block });-- // =========================================================================- // Loop end: return the accumulated return_value.- // =========================================================================- generator.switch_to_basic_block(loop_end_block);- return_value-}--/// Unified yield function.-///-/// For non-async generators: just emits a Yield instruction.-/// For async generators: optionally awaits the argument first, then yields,-/// then handles AsyncGeneratorUnwrapYieldResumption (check return type,-/// await return value, re-classify).-/// Jumps to continuation_label for the "not return" and "throw after await" paths.-fn generate_yield(- generator: &mut Generator,- continuation_label: Label,- argument: &ScopedOperand,- received_completion: &ScopedOperand,- received_completion_type: &ScopedOperand,- received_completion_value: &ScopedOperand,- yield_behavior: YieldBehavior,-) {- if !generator.is_in_async_generator_function() {- if yield_behavior == YieldBehavior::IteratorResult {- generator.emit(Instruction::YieldIteratorResult {- continuation_label,- value: argument.operand(),- });- } else {- generator.emit(Instruction::Yield {- continuation_label: Some(continuation_label),- value: argument.operand(),- });- }- return;- }-- let argument = if yield_behavior == YieldBehavior::AwaitValue {- generate_await_with_completions(- generator,- argument,- received_completion,- received_completion_type,- received_completion_value,- )- } else {- argument.clone()- };-- // Yield, then UnwrapYieldResumption.- let unwrap_block = generator.make_block();- generator.emit(Instruction::Yield {- continuation_label: Some(unwrap_block),- value: argument.operand(),- });- generator.switch_to_basic_block(unwrap_block);-- let acc = generator.accumulator();- generator.emit_mov(received_completion, &acc);- generator.emit(Instruction::GetCompletionFields {- type_dst: received_completion_type.operand(),- value_dst: received_completion_value.operand(),- completion: received_completion.operand(),- });-- // If resumptionValue.[[Type]] is not return, jump to continuation.- let return_block = generator.make_block();- let is_not_return = generator.allocate_register();- let return_type = generator.add_constant_number(f64::from(CompletionType::Return as u32));- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyInequals {- arith_feedback,- dst: is_not_return.operand(),- lhs: received_completion_type.operand(),- rhs: return_type.operand(),- });- generator.emit_jump_if(&is_not_return, continuation_label, return_block);-- // Return path: Await(resumptionValue.[[Value]]).- generator.switch_to_basic_block(return_block);- generate_await_with_completions(- generator,- received_completion_value,- received_completion,- received_completion_type,- received_completion_value,- );-- // If awaited.[[Type]] is throw, jump to continuation.- let awaited_normal_block = generator.make_block();- let is_throw = generator.allocate_register();- let throw_type = generator.add_constant_number(f64::from(CompletionType::Throw as u32));- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: is_throw.operand(),- lhs: received_completion_type.operand(),- rhs: throw_type.operand(),- });- generator.emit_jump_if(&is_throw, continuation_label, awaited_normal_block);-- // awaited.[[Type]] is normal: set type to Return and jump to continuation.- generator.switch_to_basic_block(awaited_normal_block);- generator.emit(Instruction::SetCompletionType {- completion: received_completion.operand(),- completion_type: CompletionType::Return as u32,- });- generator.emit(Instruction::Jump {- target: continuation_label,- });-}--// =============================================================================-// Identifier codegen-// =============================================================================--/// Generate bytecode for an identifier reference.-///-/// Scope analysis determines how the identifier is resolved:-/// - **Local**: direct register/local access (with TDZ check for let/const)-/// - **Global**: GetGlobal instruction (with inline cache)-/// - **Environment**: GetBinding/GetInitializedBinding (with environment coordinate cache)-fn generate_identifier(- id: crate::ast::IdentifierId,- generator: &mut Generator,- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if ident.is_local() {- emit_tdz_check_if_needed(generator, id);- return generator.resolve_local(ident.local_index, ident.local_type.unwrap());- }-- // OPTIMIZATION: Generate builtin constants (undefined, NaN, Infinity) directly.- if ident.is_global- && let Some(constant) = maybe_generate_builtin_constant(generator, arena.name_slice(id))- {- return constant;- }-- let dst = choose_dst(generator, preferred_dst);- if ident.is_global {- let id = generator.intern_identifier_id(ident.name);- let cache = generator.next_global_variable_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetGlobal {- value_feedback,- dst: dst.operand(),- identifier: id,- cache,- });- } else if ident.declaration_kind == Some(DeclarationKind::Var) {- let id = generator.intern_identifier_id(ident.name);- emit_get_binding(generator, dst.operand(), id, true);- } else {- let id = generator.intern_identifier_id(ident.name);- emit_get_binding(generator, dst.operand(), id, false);- }- dst-}--fn maybe_generate_builtin_constant(generator: &mut Generator, name: &[u16]) -> Option<ScopedOperand> {- if name == utf16!("undefined") {- return Some(generator.add_constant_undefined());- }- if name == utf16!("NaN") {- return Some(generator.add_constant_number(f64::NAN));- }- if name == utf16!("Infinity") {- return Some(generator.add_constant_number(f64::INFINITY));- }- if let Some(op) = try_generate_builtin_constant(generator, &name.into()) {- return Some(op);- }- None-}--// =============================================================================-// Binary operator emission-// =============================================================================--fn emit_binary_op(- generator: &mut Generator,- op: BinaryOp,- dst: &ScopedOperand,- lhs: &ScopedOperand,- rhs: &ScopedOperand,-) {- let dst_op = dst.operand();- let lhs_op = lhs.operand();- let rhs_op = rhs.operand();- match op {- BinaryOp::Addition => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Add {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::Subtraction => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Sub {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::Multiplication => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Mul {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::Division => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Div {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::Modulo => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Mod {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::Exponentiation => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Exp {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::StrictlyEquals => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::StrictlyInequals => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyInequals {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::LooselyEquals => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::LooselyEquals {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::LooselyInequals => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::LooselyInequals {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::GreaterThan => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::GreaterThan {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::GreaterThanEquals => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::GreaterThanEquals {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::LessThan => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::LessThan {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::LessThanEquals => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::LessThanEquals {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::BitwiseAnd => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseAnd {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::BitwiseOr => {- // OPTIMIZATION: x | 0 == ToInt32(x)- if let Some(ConstantValue::Number(n)) = generator.get_constant(rhs) {- if *n == 0.0 && n.is_sign_positive() {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::ToInt32 {- arith_feedback,- dst: dst_op,- value: lhs_op,- });- } else {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseOr {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- } else {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseOr {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- }- BinaryOp::BitwiseXor => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseXor {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::LeftShift => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::LeftShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::RightShift => {- // OPTIMIZATION: x >> 0 == ToInt32(x) (matches C++)- if let Some(ConstantValue::Number(n)) = generator.get_constant(rhs) {- if *n == 0.0 && n.is_sign_positive() {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::ToInt32 {- arith_feedback,- dst: dst_op,- value: lhs_op,- });- } else {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::RightShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- } else {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::RightShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- }- BinaryOp::UnsignedRightShift => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::UnsignedRightShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- BinaryOp::In => generator.emit(Instruction::In {- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- }),- BinaryOp::InstanceOf => generator.emit(Instruction::InstanceOf {- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- }),- }-}--// =============================================================================-// Logical expression (short-circuit)-// =============================================================================--fn generate_logical(- generator: &mut Generator,- op: LogicalOp,- lhs: &Expression,- rhs: &Expression,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let lhs_val = generate_expression(lhs, generator, preferred_dst)?;-- // Constant-fold: if LHS is a constant, we can statically determine the branch.- if let Some(constant) = generator.get_constant(&lhs_val) {- let is_nullish = matches!(constant, ConstantValue::Null | ConstantValue::Undefined);- if let Some(is_truthy) = constant_to_boolean(constant) {- let take_rhs = match op {- LogicalOp::And => is_truthy,- LogicalOp::Or => !is_truthy,- LogicalOp::NullishCoalescing => is_nullish,- };- if take_rhs {- let dst = choose_dst(generator, preferred_dst);- let rhs_val = generate_expression(rhs, generator, Some(&dst))?;- if rhs_val.operand().is_constant() {- return Some(rhs_val);- }- generator.emit_mov(&dst, &rhs_val);- return Some(dst);- }- return Some(lhs_val);- }- }-- let dst = choose_dst(generator, preferred_dst);- generator.emit_mov(&dst, &lhs_val);-- let rhs_block = generator.make_block();- let end_block = generator.make_block();-- match op {- LogicalOp::And => {- // If lhs is falsy, short-circuit to end- generator.emit_jump_if(&lhs_val, rhs_block, end_block);- }- LogicalOp::Or => {- // If lhs is truthy, short-circuit to end- generator.emit_jump_if(&lhs_val, end_block, rhs_block);- }- LogicalOp::NullishCoalescing => {- generator.emit(Instruction::JumpNullish {- condition: lhs_val.operand(),- true_target: rhs_block,- false_target: end_block,- });- }- }-- generator.switch_to_basic_block(rhs_block);- let rhs_val = generate_expression(rhs, generator, Some(&dst));- if let Some(rhs_val) = &rhs_val {- generator.emit_mov(&dst, rhs_val);- }- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: end_block });- }-- generator.switch_to_basic_block(end_block);- Some(dst)-}--// =============================================================================-// Conditional expression (ternary)-// =============================================================================--fn generate_conditional(- generator: &mut Generator,- test: &Expression,- consequent: &Expression,- alternate: &Expression,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let predicate = generate_expression(test, generator, None)?;-- // OPTIMIZATION: if the predicate is always true/false, only generate the taken expression.- if let Some(constant) = generator.get_constant(&predicate)- && let Some(is_truthy) = constant_to_boolean(constant)- {- if is_truthy {- return generate_expression(consequent, generator, preferred_dst);- }- return generate_expression(alternate, generator, preferred_dst);- }-- let true_block = generator.make_block();- let false_block = generator.make_block();- let end_block = generator.make_block();-- generator.emit_jump_if(&predicate, true_block, false_block);-- let dst = choose_dst(generator, preferred_dst);-- generator.switch_to_basic_block(true_block);- let cons_val = generate_expression(consequent, generator, None);- if let Some(val) = &cons_val {- generator.emit_mov(&dst, val);- }- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: end_block });- }-- generator.switch_to_basic_block(false_block);- let alt_val = generate_expression(alternate, generator, None);- if let Some(val) = &alt_val {- generator.emit_mov(&dst, val);- }- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: end_block });- }-- generator.switch_to_basic_block(end_block);- Some(dst)-}--/// Generate a statement while propagating the completion register.-///-/// Saves and restores `gen.current_completion_register`, and emits a mov-/// from the statement's result to the completion register when appropriate.-fn generate_with_completion(- body: &Statement,- generator: &mut Generator,- completion: Option<&ScopedOperand>,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let saved = generator.current_completion_register.clone();- if let Some(c) = completion {- generator.current_completion_register = Some(c.clone());- }- let result = generate_statement(body, generator, preferred_dst);- if !generator.is_current_block_terminated()- && let (Some(c), Some(val)) = (completion, &result)- {- generator.emit_mov(c, val);- }- generator.current_completion_register = saved;- result-}--// =============================================================================-// If statement-// =============================================================================--fn generate_if_statement(- generator: &mut Generator,- test: &Expression,- consequent: &Statement,- alternate: Option<&Statement>,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let pred = generate_expression_or_undefined(test, generator, None);-- let completion = if generator.must_propagate_completion {- let reg = choose_dst(generator, preferred_dst);- let undef = generator.add_constant_undefined();- generator.emit_mov(®, &undef);- Some(reg)- } else {- None- };-- // OPTIMIZATION: if the predicate is always true/false, only build the taken branch.- if let Some(constant) = generator.get_constant(&pred)- && let Some(is_truthy) = constant_to_boolean(constant)- {- // Pass the completion register as preferred_dst so nested- // if-statements reuse the same register.- let child_dst = completion.as_ref().or(preferred_dst);- if is_truthy {- generate_with_completion(consequent, generator, completion.as_ref(), child_dst);- } else if let Some(alt) = alternate {- generate_with_completion(alt, generator, completion.as_ref(), child_dst);- }- return completion;- }-- let true_block = generator.make_block();- let false_block = generator.make_block();- let has_alternate = alternate.is_some();- let end_block = if has_alternate {- generator.make_block()- } else {- false_block- };-- generator.emit_jump_if(&pred, true_block, false_block);-- // Pass completion as preferred_dst to children so nested if-else chains- // reuse the same completion register.- let child_preferred_dst = completion.as_ref();-- // Consequent- let saved_completion = generator.current_completion_register.clone();- {- generator.switch_to_basic_block(true_block);- if let Some(ref c) = completion {- generator.current_completion_register = Some(c.clone());- }- let cons_result = generate_statement(consequent, generator, child_preferred_dst);- if !generator.is_current_block_terminated() {- if let (Some(c), Some(val)) = (&completion, &cons_result) {- generator.emit_mov(c, val);- }- generator.emit(Instruction::Jump { target: end_block });- }- }- generator.current_completion_register = saved_completion.clone();-- // Alternate- if let Some(alt) = alternate {- generator.switch_to_basic_block(false_block);- if let Some(ref c) = completion {- generator.current_completion_register = Some(c.clone());- }- let alt_result = generate_statement(alt, generator, child_preferred_dst);- if !generator.is_current_block_terminated() {- if let (Some(c), Some(val)) = (&completion, &alt_result) {- generator.emit_mov(c, val);- }- generator.emit(Instruction::Jump { target: end_block });- }- generator.current_completion_register = saved_completion;- }-- generator.switch_to_basic_block(end_block);- completion-}--// =============================================================================-// While statement-// =============================================================================--fn generate_while_statement(- generator: &mut Generator,- test: &Expression,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let test_block = generator.make_block();-- let completion = generator.allocate_completion_register();-- generator.emit(Instruction::Jump { target: test_block });-- generator.switch_to_basic_block(test_block);- let test_val = generate_expression_or_undefined(test, generator, None);-- // OPTIMIZATION: If predicate is always false, ignore body and exit early.- if let Some(constant) = generator.get_constant(&test_val)- && constant_to_boolean(constant) == Some(false)- {- return completion;- }-- let body_block = generator.make_block();- let end_block = generator.make_block();-- generator.emit_jump_if(&test_val, body_block, end_block);-- generator.switch_to_basic_block(body_block);- let labels = std::mem::take(&mut generator.pending_labels);- generator.begin_continuable_scope(test_block, labels.clone(), completion.clone());- generator.begin_breakable_scope(end_block, labels, completion.clone());-- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);-- generator.end_breakable_scope();- generator.end_continuable_scope();- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: test_block });- }-- generator.switch_to_basic_block(end_block);- completion-}--// =============================================================================-// DoWhile statement-// =============================================================================--fn generate_do_while_statement(- generator: &mut Generator,- test: &Expression,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let body_block = generator.make_block();- let test_block = generator.make_block();- let load_result_and_jump_to_end_block = generator.make_block();- let end_block = generator.make_block();-- let completion = generator.allocate_completion_register();-- generator.emit(Instruction::Jump { target: body_block });-- // Generate test FIRST, keeping the test ScopedOperand alive during- // body generation, consuming a register from the free pool.- generator.switch_to_basic_block(test_block);- let test_val = generate_expression_or_undefined(test, generator, None);- generator.emit_jump_if(&test_val, body_block, load_result_and_jump_to_end_block);-- // Generate body SECOND (test_val still alive).- generator.switch_to_basic_block(body_block);- let labels = std::mem::take(&mut generator.pending_labels);- generator.begin_continuable_scope(test_block, labels.clone(), completion.clone());- generator.begin_breakable_scope(end_block, labels, completion.clone());-- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);-- generator.end_breakable_scope();- generator.end_continuable_scope();- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: test_block });- }-- generator.switch_to_basic_block(load_result_and_jump_to_end_block);- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(end_block);- completion-}--// =============================================================================-// For statement-// =============================================================================--fn generate_for_statement(- generator: &mut Generator,- init: Option<&ForInit>,- test: Option<&Expression>,- update: Option<&Expression>,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // ForStatement : `for` `(` LexicalDeclaration Expression? `;` Expression? `)` Statement- // NB: The resources of a `using` or `await using` declaration in the head are disposed of when the loop ends,- // including when its declaration is abrupt.- if let Some(ForInit::Declaration(declaration)) = init- && let Some(kind) = disposal_kind_of_statements(core::iter::once(declaration.as_ref()))- {- return generate_with_disposable_resource_stack(generator, kind, |generator| {- generate_for_statement_without_disposal(generator, init, test, update, body, preferred_dst)- });- }- generate_for_statement_without_disposal(generator, init, test, update, body, preferred_dst)-}--/// The declarators of a lexical declaration (`let`, `const`, `using` or `await using`), and whether it is a constant-/// declaration.-fn lexical_declarators(statement: &Statement) -> Option<(&[VariableDeclarator], bool)> {- match &statement.inner {- StatementKind::VariableDeclaration(vd)- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>- {- Some((&vd.declarations, vd.kind == DeclarationKind::Const))- }- StatementKind::UsingDeclaration(data) => Some((&data.declarations, true)),- _ => None,- }-}--fn generate_for_statement_without_disposal(- generator: &mut Generator,- init: Option<&ForInit>,- test: Option<&Expression>,- update: Option<&Expression>,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // Check if init is a lexical declaration (let/const/using) with non-local variables.- // If so, we need to create a lexical environment for the loop variables and- // implement per-iteration copy semantics (CreatePerIterationEnvironment).- let mut has_lexical_environment = false;- let mut per_iteration_binding_names: Vec<Utf16String> = Vec::new();-- if let Some(ForInit::Declaration(init)) = init- && let Some((declarations, is_const)) = lexical_declarators(init)- {- let mut non_local_names: Vec<(Utf16String, bool)> = Vec::new();- for declaration in declarations {- collect_target_names(&declaration.target, &mut non_local_names, &generator.arena);- }- if !non_local_names.is_empty() {- has_lexical_environment = true;-- // begin_variable_scope: CreateLexicalEnvironment + boundary- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.push_new_lexical_environment(u32_from_usize(non_local_names.len()));-- for (name, _) in &non_local_names {- let id = generator.intern_identifier(name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: is_const,- is_global: false,- is_strict: false,- });- if !is_const {- per_iteration_binding_names.push(name.clone());- }- }- }- }-- // Init- match init {- Some(ForInit::Declaration(decl)) => {- generate_statement(decl, generator, None);- }- Some(ForInit::Expression(expr)) => {- generate_expression(expr, generator, None);- }- None => {}- }-- // CreatePerIterationEnvironment after init (first iteration setup).- emit_per_iteration_bindings(generator, &per_iteration_binding_names);-- // Block creation order: body → per-iteration (if needed) → update (if exists) → test (if exists) → end.- // If 'test' is missing, fuse 'test' and 'body' blocks.- // If 'update' is missing, fuse 'body' and 'update' blocks.- let body_block = generator.make_block();- // `continue` targets this block too, so CreatePerIterationEnvironment runs before every update.- let per_iteration_block = if per_iteration_binding_names.is_empty() {- None- } else {- Some(generator.make_block())- };- let update_block = if update.is_some() {- generator.make_block()- } else {- body_block- };- let test_block = if test.is_some() {- generator.make_block()- } else {- body_block- };- let end_block = generator.make_block();-- let completion = generator.allocate_completion_register();-- generator.emit(Instruction::Jump { target: test_block });-- // Test- if let Some(test_expression) = test {- generator.switch_to_basic_block(test_block);- let test_val = generate_expression_or_undefined(test_expression, generator, None);-- // OPTIMIZATION: test value is always falsey, skip body entirely.- if let Some(constant) = generator.get_constant(&test_val)- && constant_to_boolean(constant) == Some(false)- {- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(end_block);- if has_lexical_environment {- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();- if !generator.is_current_block_terminated() {- let parent = generator.current_lexical_environment();- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });- }- }- return completion;- }-- generator.emit_jump_if(&test_val, body_block, end_block);- }-- // Update- if let Some(update_expression) = update {- generator.switch_to_basic_block(update_block);- generate_expression(update_expression, generator, None);- generator.emit(Instruction::Jump { target: test_block });- }-- // Body- generator.switch_to_basic_block(body_block);- let labels = std::mem::take(&mut generator.pending_labels);- let next_iteration_block = if update.is_some() { update_block } else { test_block };- let continue_block = per_iteration_block.unwrap_or(next_iteration_block);- generator.begin_continuable_scope(continue_block, labels.clone(), completion.clone());- generator.begin_breakable_scope(end_block, labels, completion.clone());-- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);-- generator.end_breakable_scope();- generator.end_continuable_scope();- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: continue_block });- }-- if let Some(per_iteration_block) = per_iteration_block {- generator.switch_to_basic_block(per_iteration_block);- emit_per_iteration_bindings(generator, &per_iteration_binding_names);- generator.emit(Instruction::Jump {- target: next_iteration_block,- });- }-- generator.switch_to_basic_block(end_block);-- // end_variable_scope: restore parent environment- if has_lexical_environment {- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();- if !generator.is_current_block_terminated() {- let parent = generator.current_lexical_environment();- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });- }- }-- completion-}--/// Emit CreatePerIterationEnvironment: save current binding values, pop env,-/// push new env, re-create variables, and re-initialize from saved values.-/// This implements per-iteration lexical scoping for `for (let ...)` loops.-fn emit_per_iteration_bindings(generator: &mut Generator, bindings: &[Utf16String]) {- if bindings.is_empty() {- return;- }-- // Save current values into registers.- let mut saved: Vec<(ScopedOperand, IdentifierTableIndex)> = Vec::with_capacity(bindings.len());- for name in bindings {- let id = generator.intern_identifier(name);- let reg = generator.allocate_register();- emit_get_binding(generator, reg.operand(), id, false);- saved.push((reg, id));- }-- // Pop current environment (end_variable_scope).- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();- let parent = generator.current_lexical_environment();- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });-- // Push new environment (begin_variable_scope).- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.push_new_lexical_environment(u32_from_usize(saved.len()));-- // Re-create variables and initialize from saved values.- for (reg, id) in &saved {- generator.emit(Instruction::CreateVariable {- identifier: *id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- emit_initialize_lexical_binding(generator, *id, reg.operand());- }-}--// =============================================================================-// Scope children (Block, FunctionBody, Program)-// =============================================================================--fn generate_scope_children(- generator: &mut Generator,- scope: &ScopeData,- _preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // A labelled statement that completes empty keeps the running value, so it needs that value in a register.- let running_completion = if generator.must_propagate_completion- && generator.current_completion_register.is_none()- && reaches_labelled_statement(&scope.children, &generator.arena)- {- generator.allocate_completion_register()- } else {- None- };- if running_completion.is_some() {- generator.current_completion_register = running_completion.clone();- }-- let mut last_result = None;- for child in &scope.children {- let result = generate_statement(child, generator, None);- if generator.must_propagate_completion- && let Some(ref val) = result- {- // A later statement that completes empty can still reassign a local the value is read from.- let val = &generator.copy_if_needed_to_preserve_evaluation_order(val);- last_result = Some(val.clone());- if !generator.is_current_block_terminated()- && let Some(ref completion_reg) = generator.current_completion_register.clone()- {- generator.emit_mov(completion_reg, val);- }- }- // NB: When must_propagate_completion is false, we intentionally do NOT- // accumulate results into last_result. `result` goes out of scope at- // the end of each loop iteration, freeing any temporary registers- // immediately.- if generator.is_current_block_terminated() {- break;- }- }-- if running_completion.is_some() {- generator.current_completion_register = None;- }- running_completion.or(last_result)-}--fn reaches_labelled_statement(statements: &[Statement], arena: &AstArena) -> bool {- statements.iter().any(|statement| match &statement.inner {- StatementKind::Labelled(_) => true,- StatementKind::Block(scope) => reaches_labelled_statement(&arena.scopes[*scope].children, arena),- _ => false,- })-}--/// Generate bytecode for a block statement, creating a lexical environment-/// if the block has non-local lexical declarations (let/const/class).-fn generate_block_statement(- generator: &mut Generator,- scope: &ScopeData,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let did_create_env = emit_block_declaration_instantiation(generator, scope);- if did_create_env {- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- }-- // The parser wraps for-loop statements in a Block for scope tracking- // (via close_for_loop_scope). When the block doesn't create a lexical- // environment and its only child is a for-loop variant, skip- // generate_scope_children and generate the child directly to avoid- // emitting a redundant completion Mov.- emit_tdz_reset_of_declared_locals(generator, scope.children.iter());- let result = if !did_create_env && scope.children.len() == 1 && is_for_loop(&scope.children[0]) {- generate_statement(&scope.children[0], generator, preferred_dst)- } else {- generate_scope_children_with_disposal(generator, scope, preferred_dst)- };-- if did_create_env {- generator.end_variable_scope();- }- result-}--/// Empty the locals that a scope declares lexically where the scope starts, so that entering it again (as a loop does)-/// starts them uninitialized. The generator drops the store for a local that no TDZ check reads.-fn emit_tdz_reset_of_declared_locals<'a>(generator: &mut Generator, statements: impl Iterator<Item = &'a Statement>) {- let arena = generator.arena.clone();- let mut locals = Vec::new();- for statement in statements {- collect_lexically_declared_locals(statement, &arena, &mut locals);- }- for index in locals {- generator.emit_tdz_reset(index);- }-}--/// Collect the locals that a statement directly in a scope declares lexically, including in a loop head.-fn collect_lexically_declared_locals(statement: &Statement, arena: &AstArena, locals: &mut Vec<u32>) {- if let Some((declarations, _)) = lexical_declarators(statement) {- for declaration in declarations {- match &declaration.target {- VariableDeclaratorTarget::Identifier(id) => collect_local(*id, arena, locals),- VariableDeclaratorTarget::BindingPattern(pattern) => {- collect_pattern_locals(pattern, arena, locals);- }- }- }- return;- }- match &statement.inner {- StatementKind::ClassDeclaration(data) => {- if let Some(id) = data.name {- collect_local(id, arena, locals);- }- }- StatementKind::For(data) => {- if let Some(ForInit::Declaration(declaration)) = &data.init {- collect_lexically_declared_locals(declaration, arena, locals);- }- }- StatementKind::ForInOf(data) => {- if let ForInOfLhs::Declaration(declaration) = &data.lhs {- collect_lexically_declared_locals(declaration, arena, locals);- }- }- _ => {}- }-}--fn collect_pattern_locals(pattern: &BindingPattern, arena: &AstArena, locals: &mut Vec<u32>) {- for entry in &pattern.entries {- match &entry.alias {- Some(BindingEntryAlias::Identifier(id)) => collect_local(*id, arena, locals),- Some(BindingEntryAlias::BindingPattern(sub_pattern)) => collect_pattern_locals(sub_pattern, arena, locals),- Some(BindingEntryAlias::MemberExpression(_)) => {}- None => {- if let Some(BindingEntryName::Identifier(id)) = &entry.name {- collect_local(*id, arena, locals);- }- }- }- }-}--fn collect_local(id: IdentifierId, arena: &AstArena, locals: &mut Vec<u32>) {- let identifier = &arena.identifiers[id];- if identifier.is_local() && identifier.local_type == Some(LocalType::Variable) {- locals.push(identifier.local_index);- }-}--/// How the resources of a scope are disposed of, if the scope has `using` or `await using` declarations.-#[derive(Clone, Copy, PartialEq, Eq)]-enum DisposalKind {- Sync,- Async,-}--/// The disposal kind of a statement list, from the `using` and `await using` declarations directly in it.-fn disposal_kind_of_statements<'a>(statements: impl Iterator<Item = &'a Statement>) -> Option<DisposalKind> {- let mut kind = None;- for statement in statements {- if let StatementKind::UsingDeclaration(data) = &statement.inner {- if data.is_await {- return Some(DisposalKind::Async);- }- kind = Some(DisposalKind::Sync);- }- }- kind-}--/// Generate the children of a scope, disposing of the resources of the `using` and `await using` declarations in-/// it when control leaves it. Scopes without such declarations are generated exactly like generate_scope_children.-fn generate_scope_children_with_disposal(- generator: &mut Generator,- scope: &ScopeData,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- match disposal_kind_of_statements(scope.children.iter()) {- None => generate_scope_children(generator, scope, preferred_dst),- Some(kind) => generate_with_disposable_resource_stack(generator, kind, |generator| {- generate_scope_children(generator, scope, preferred_dst)- }),- }-}--/// Generate code that has a new [[DisposableResourceStack]], whose resources are disposed of however control leaves-/// the code, like a try statement whose finally block performs DisposeResources.-// https://tc39.es/ecma262/#sec-disposeresources-fn generate_with_disposable_resource_stack(- generator: &mut Generator,- kind: DisposalKind,- body: impl FnOnce(&mut Generator) -> Option<ScopedOperand>,-) -> Option<ScopedOperand> {- let stack = generator.allocate_register();- generator.emit(Instruction::NewDisposableResourceStack { dst: stack.operand() });- let saved_stack = generator.current_disposable_resource_stack.replace(stack.clone());-- let old_handler = generator.current_unwind_handler;- let saved_block = generator.current_block_index();- let saved_env = generator.current_lexical_environment();-- let completion_type = generator.allocate_register();- let completion_value = generator.allocate_register();- let exception_preamble_block = generator.make_block();- let dispose_block = generator.make_block();-- let parent_index = generator.current_finally_context;- let ctx_index = generator.push_finally_context(FinallyContext {- completion_type: completion_type.clone(),- completion_value: completion_value.clone(),- finally_body: dispose_block,- exception_preamble: exception_preamble_block,- parent_index,- registered_jumps: Vec::new(),- next_jump_index: FinallyContext::FIRST_JUMP_INDEX,- lexical_environment_at_entry: Some(saved_env.clone()),- saved_unwind_handler: None,- });-- // Exception preamble: record the throw completion and dispose of the resources.- generator.switch_to_basic_block(exception_preamble_block);- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::Catch {- value_feedback,- dst: completion_value.operand(),- });- generator.emit(Instruction::SetLexicalEnvironment {- environment: saved_env.operand(),- });- let throw_const = generator.add_constant_i32(FinallyContext::THROW);- generator.emit_mov(&completion_type, &throw_const);- generator.emit(Instruction::Jump { target: dispose_block });-- // Body.- generator.current_unwind_handler = Some(exception_preamble_block);- let body_block = generator.make_block();- generator.switch_to_basic_block(saved_block);- generator.emit(Instruction::Jump { target: body_block });- generator.start_boundary(BlockBoundaryType::ReturnToFinally);- generator.switch_to_basic_block(body_block);-- let result = body(generator);-- if !generator.is_current_block_terminated() {- let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);- generator.emit_mov(&completion_type, &normal_const);- generator.emit(Instruction::Jump { target: dispose_block });- }- generator.end_boundary(BlockBoundaryType::ReturnToFinally);-- generator.current_unwind_handler = old_handler;- generator.current_finally_context = parent_index;- generator.current_disposable_resource_stack = saved_stack;-- // Dispose of the resources, which replaces the completion with a throw completion if a dispose method throws.- generator.switch_to_basic_block(dispose_block);- match kind {- DisposalKind::Sync => {- generator.emit(Instruction::DisposeResources {- stack: stack.operand(),- completion_type: completion_type.operand(),- completion_value: completion_value.operand(),- });- }- DisposalKind::Async => {- // NB: DisposeResources awaits between some of its steps here, so the bytecode performs it one step at a- // time, with an Await after each step that asks for one.- let await_completion = generator.allocate_register();- let await_completion_type = generator.allocate_register();- let await_completion_value = generator.allocate_register();- let done = generator.allocate_register();- let awaited_value = generator.allocate_register();- let normal_type = generator.add_constant_number(f64::from(CompletionType::Normal as u32));- let undefined = generator.add_constant_undefined();- generator.emit_mov(&await_completion_type, &normal_type);- generator.emit_mov(&await_completion_value, &undefined);-- let step_block = generator.make_block();- let await_block = generator.make_block();- let continuation_block = generator.make_block();- let done_block = generator.make_block();- generator.emit(Instruction::Jump { target: step_block });-- generator.switch_to_basic_block(step_block);- generator.emit(Instruction::AsyncDisposeResourcesStep {- done: done.operand(),- awaited_value: awaited_value.operand(),- stack: stack.operand(),- completion_type: completion_type.operand(),- completion_value: completion_value.operand(),- await_completion_type: await_completion_type.operand(),- await_completion_value: await_completion_value.operand(),- });- generator.emit_jump_if(&done, done_block, await_block);-- generator.switch_to_basic_block(await_block);- let acc = generator.accumulator();- generator.emit_mov(&await_completion, &acc);- generator.emit(Instruction::Await {- continuation_label: continuation_block,- argument: awaited_value.operand(),- });-- generator.switch_to_basic_block(continuation_block);- let acc = generator.accumulator();- generator.emit_mov(&await_completion, &acc);- generator.emit(Instruction::GetCompletionFields {- type_dst: await_completion_type.operand(),- value_dst: await_completion_value.operand(),- completion: await_completion.operand(),- });- generator.emit(Instruction::Jump { target: step_block });-- generator.switch_to_basic_block(done_block);- }- }-- let next_block = generator.make_block();- emit_finally_dispatch(generator, ctx_index, &completion_type, &completion_value, next_block);-- let dummy = generator.add_constant_undefined();- generator.finally_contexts[ctx_index].lexical_environment_at_entry = None;- generator.finally_contexts[ctx_index].completion_value = dummy.clone();- generator.finally_contexts[ctx_index].completion_type = dummy;-- generator.switch_to_basic_block(next_block);- result-}--// https://tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation-// UsingDeclaration : `using` BindingList `;`-// AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList `;`-fn generate_using_declaration(generator: &mut Generator, data: &UsingDeclarationData) {- // UsingDeclaration:- // 1. Perform ? BindingEvaluation of BindingList with argument sync-dispose.- // AwaitUsingDeclaration:- // 1. Perform ? BindingEvaluation of BindingList with argument async-dispose.- let kind = if data.is_await {- DisposableResourceKind::AsyncDispose- } else {- DisposableResourceKind::SyncDispose- };- for declaration in &data.declarations {- let VariableDeclaratorTarget::Identifier(id) = &declaration.target else {- unreachable!("using declarations only bind identifiers");- };- let value = generate_expression_or_undefined_with_lhs_name(generator, *id, declaration.init.as_ref());- emit_add_disposable_resource_and_initialize_binding(generator, *id, &value, kind);- }- // 2. Return empty.-}--/// Evaluates the Initializer of a LexicalBinding, as NamedEvaluation with the name of the binding if it is an-/// anonymous function definition.-fn generate_expression_or_undefined_with_lhs_name(- generator: &mut Generator,- id: IdentifierId,- init: Option<&Expression>,-) -> ScopedOperand {- let arena = generator.arena.clone();- generator.pending_lhs_name = Some(generator.intern_identifier_id(arena.identifiers[id].name));- let value = init.and_then(|init| generate_expression(init, generator, None));- generator.pending_lhs_name = None;- value.unwrap_or_else(|| generator.add_constant_undefined())-}--// https://tc39.es/ecma262/#sec-bindingevaluation-// LexicalBinding : BindingIdentifier Initializer-fn emit_add_disposable_resource_and_initialize_binding(- generator: &mut Generator,- id: IdentifierId,- value: &ScopedOperand,- kind: DisposableResourceKind,-) {- // 5. If kind is not normal, then- // a. Assert: IsUnresolvableReference(lhs) is false.- // b. Let base be lhs.[[Base]].- // c. Assert: base is a Declarative Environment Record.- // d. Perform ? AddDisposableResource(base.[[DisposableResourceStack]], value, kind).- let stack = generator- .current_disposable_resource_stack- .clone()- .expect("a using declaration is in a scope with a disposable resource stack");- generator.emit(Instruction::AddDisposableResource {- stack: stack.operand(),- value: value.operand(),- hint: kind as u32,- });-- // 6. Perform ? InitializeReferencedBinding(lhs, value).- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if ident.is_local() {- let local_index = ident.local_index;- let local = generator.resolve_local(local_index, ident.local_type.unwrap());- generator.emit_mov(&local, value);- generator.mark_local_initialized(local_index);- } else {- let identifier = generator.intern_identifier_id(ident.name);- emit_initialize_lexical_binding(generator, identifier, value.operand());- }-}--/// Create lexical bindings and instantiate function declarations for a block.-/// All bindings are created before any function is instantiated, so every-/// function closes over the complete binding layout of the block.-fn emit_lexical_declarations_for_block<'a>(- generator: &mut Generator,- environment: &ScopedOperand,- children: impl Iterator<Item = &'a Statement>,-) {- let arena = generator.arena.clone();- let mut function_declarations = Vec::new();- let mut function_names = HashSet::new();- for child in children {- if let Some(fd) = child.inner.function_declaration_for_labelled_item()- && let Some(name_ident_id) = fd.name- {- let name_ident = &arena.identifiers[name_ident_id];- let is_first_declaration = function_names.insert(name_ident.name);- if is_first_declaration && !name_ident.is_local() {- let id = generator.intern_identifier_id(name_ident.name);- generator.emit(Instruction::CreateMutableBinding {- environment: environment.operand(),- identifier: id,- can_be_deleted: false,- });- }- function_declarations.push((fd, is_first_declaration));- continue;- }-- match &child.inner {- StatementKind::VariableDeclaration(vd)- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>- {- let is_constant = vd.kind == DeclarationKind::Const;- for declaration in &vd.declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, &generator.arena);- for (name, _) in &names {- let id = generator.intern_identifier(name);- if is_constant {- generator.emit(Instruction::CreateImmutableBinding {- environment: environment.operand(),- identifier: id,- strict_binding: true,- });- } else {- generator.emit(Instruction::CreateMutableBinding {- environment: environment.operand(),- identifier: id,- can_be_deleted: false,- });- }- }- }- }- StatementKind::UsingDeclaration(declarations) => {- for declaration in &declarations.declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, &generator.arena);- for (name, _) in &names {- let id = generator.intern_identifier(name);- generator.emit(Instruction::CreateImmutableBinding {- environment: environment.operand(),- identifier: id,- strict_binding: true,- });- }- }- }- StatementKind::ClassDeclaration(class_data) => {- if let Some(name_ident_id) = class_data.name {- let name_ident = &arena.identifiers[name_ident_id];- if !name_ident.is_local() {- let id = generator.intern_identifier_id(name_ident.name);- generator.emit(Instruction::CreateMutableBinding {- environment: environment.operand(),- identifier: id,- can_be_deleted: false,- });- }- }- }- _ => {}- }- }-- for (fd, is_first_declaration) in function_declarations {- emit_lexical_function_declaration_for_block(generator, fd, is_first_declaration);- }-}--fn emit_lexical_function_declaration_for_block(- generator: &mut Generator,- fd: &FunctionDeclarationData,- is_first_declaration: bool,-) {- let name_ident_id = fd.name.unwrap();- let arena = generator.arena.clone();- let name_ident = &arena.identifiers[name_ident_id];- let function_data = generator.function_table.take(fd.function_id);- let sfd_index = emit_new_function(generator, function_data, None);- let fo = generator.allocate_register();- generator.emit(Instruction::NewFunction {- dst: fo.operand(),- shared_function_data_index: sfd_index,- home_object: None,- lhs_name: None,- });- if name_ident.is_local() {- let local_index = name_ident.local_index;- let local = generator.local(local_index);- generator.emit_mov(&local, &fo);- generator.mark_local_initialized(local_index);- } else {- let id = generator.intern_identifier_id(name_ident.name);- if is_first_declaration {- emit_initialize_lexical_binding(generator, id, fo.operand());- } else {- emit_set_lexical_binding(generator, id, fo.operand());- }- }-}--fn emit_block_declaration_instantiation(generator: &mut Generator, scope: &ScopeData) -> bool {- if !needs_block_declaration_instantiation(scope, &generator.arena) {- return false;- }-- let capacity = count_lexical_declarations_for_block(scope.children.iter(), &generator.arena);- let new_env = generator.push_new_lexical_environment(capacity);-- emit_lexical_declarations_for_block(generator, &new_env, scope.children.iter());-- true-}--// =============================================================================-// Variable declaration-// =============================================================================--enum ResolvedBinding {- /// The environment ResolveBinding found the binding in, or null if the reference is unresolvable.- Environment {- environment: ScopedOperand,- identifier: IdentifierTableIndex,- },- /// Whether ResolveGlobalBinding found the binding of an identifier the compiler found no binding of before the- /// global environment, in which case it is stored with SetGlobal.- Global {- is_resolvable: ScopedOperand,- identifier: IdentifierTableIndex,- cache: u32,- },-}--fn emit_resolve_binding_for_identifier_assignment(- generator: &mut Generator,- id: crate::ast::IdentifierId,-) -> Option<ResolvedBinding> {- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if ident.is_local() || (ident.is_global && !generator.strict) {- return None;- }-- // In strict mode, a global-looking identifier may still be unresolvable. Preserve that reference across RHS- // evaluation so PutValue throws even if the RHS creates a global property with the same name.- let identifier = generator.intern_identifier_id(ident.name);- if generator.environment_coordinate_for_identifier(identifier).is_some() {- return None;- }-- // OPTIMIZATION: Only the global environment can have the binding of a global-looking identifier, so whether it has- // one is checked with the cache of the SetGlobal that stores the value if so.- if ident.is_global {- let is_resolvable = generator.allocate_register();- let cache = generator.next_global_variable_cache();- generator.emit(Instruction::ResolveGlobalBinding {- dst: is_resolvable.operand(),- identifier,- cache,- });- return Some(ResolvedBinding::Global {- is_resolvable,- identifier,- cache,- });- }-- let environment = generator.allocate_register();- generator.emit(Instruction::ResolveBinding {- dst: environment.operand(),- identifier,- });- Some(ResolvedBinding::Environment {- environment,- identifier,- })-}--fn generate_identifier_with_resolved_binding(- generator: &mut Generator,- id: crate::ast::IdentifierId,- resolved_binding: Option<&ResolvedBinding>,-) -> ScopedOperand {- if let Some(ResolvedBinding::Environment {- environment,- identifier,- }) = resolved_binding- {- let value = generator.allocate_register();- generator.emit(Instruction::GetResolvedBinding {- dst: value.operand(),- environment: environment.operand(),- identifier: *identifier,- });- value- } else {- generate_identifier(id, generator, None)- }-}--fn emit_set_resolved_binding(generator: &mut Generator, resolved_binding: &ResolvedBinding, value: &ScopedOperand) {- match resolved_binding {- ResolvedBinding::Environment {- environment,- identifier,- } => {- generator.emit(Instruction::SetResolvedBinding {- environment: environment.operand(),- identifier: *identifier,- src: value.operand(),- });- }- ResolvedBinding::Global {- is_resolvable,- identifier,- cache,- } => {- let set_block = generator.make_block();- let unresolvable_block = generator.make_block();- let end_block = generator.make_block();- generator.emit_jump_if(is_resolvable, set_block, unresolvable_block);-- generator.switch_to_basic_block(set_block);- generator.emit(Instruction::SetGlobal {- identifier: *identifier,- src: value.operand(),- cache: *cache,- });- generator.emit(Instruction::Jump { target: end_block });-- // NB: PutValue of an unresolvable reference throws a ReferenceError in strict mode code.- generator.switch_to_basic_block(unresolvable_block);- let null = generator.add_constant_null();- generator.emit(Instruction::SetResolvedBinding {- environment: null.operand(),- identifier: *identifier,- src: value.operand(),- });- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(end_block);- }- }-}--fn emit_set_variable_or_resolved_binding(- generator: &mut Generator,- id: crate::ast::IdentifierId,- value: &ScopedOperand,- resolved_binding: Option<&ResolvedBinding>,-) {- if let Some(resolved_binding) = resolved_binding {- emit_set_resolved_binding(generator, resolved_binding, value);- } else {- emit_set_variable(generator, id, value);- }-}--/// Reports whether evaluating `expression` can read or write the local variable at `local_index`.-///-/// A binding only becomes a local when no nested function captures it, no `with` statement covers it-/// and no direct eval can see it. Code that runs from inside this expression therefore has no way to-/// name the binding, and a textual reference in the expression itself is the only way to reach it.-/// That makes this a plain search for such references. The match is exhaustive on purpose: a new-/// kind of expression must be classified here rather than silently defaulting to one answer.-fn expression_may_reach_local(arena: &AstArena, expression: &Expression, local_index: u32) -> bool {- let reaches = |expression: &Expression| expression_may_reach_local(arena, expression, local_index);- let arguments_reach = |arguments: &Vec<CallArgument>| arguments.iter().any(|argument| reaches(&argument.value));- match &expression.inner {- ExpressionKind::NumericLiteral(_)- | ExpressionKind::StringLiteral(_)- | ExpressionKind::BooleanLiteral(_)- | ExpressionKind::NullLiteral- | ExpressionKind::BigIntLiteral(_)- | ExpressionKind::RegExpLiteral(_)- | ExpressionKind::This- | ExpressionKind::Super- | ExpressionKind::MetaProperty(_)- | ExpressionKind::Error => false,-- // A function body that referred to the binding would have captured it, and a captured- // binding never becomes a local. The same holds for its default parameter expressions.- ExpressionKind::Function(_) => false,-- ExpressionKind::Identifier(id) => {- let ident = &arena.identifiers[*id];- ident.local_type == Some(LocalType::Variable) && ident.local_index == local_index- }-- ExpressionKind::Unary { operand, .. } => reaches(operand),- ExpressionKind::Spread(operand) | ExpressionKind::Await(operand) => reaches(operand),- ExpressionKind::Binary(data) => reaches(&data.lhs) || reaches(&data.rhs),- ExpressionKind::Logical(data) => reaches(&data.lhs) || reaches(&data.rhs),- ExpressionKind::Conditional(data) => {- reaches(&data.test) || reaches(&data.consequent) || reaches(&data.alternate)- }- ExpressionKind::Sequence(expressions) => expressions.iter().any(reaches),- ExpressionKind::TemplateLiteral(data) => data.expressions.iter().any(reaches),- ExpressionKind::Array(elements) => elements.iter().flatten().any(reaches),-- ExpressionKind::Object(properties) => properties- .iter()- .any(|property| reaches(&property.key) || property.value.as_ref().is_some_and(|value| reaches(value))),-- ExpressionKind::Update(data) => reaches(&data.argument),- ExpressionKind::Assignment(data) => {- let lhs_reaches = match &data.lhs {- AssignmentLhs::Expression(lhs) => reaches(lhs),- // Destructuring patterns can bind the local, and their shape is not walked here.- AssignmentLhs::Pattern(_) => true,- };- lhs_reaches || reaches(&data.rhs)- }-- // A non-computed member name is a plain property name, not a reference.- ExpressionKind::Member(data) => reaches(&data.object) || (data.computed && reaches(&data.property)),-- ExpressionKind::Call(data) | ExpressionKind::New(data) => {- reaches(&data.callee) || arguments_reach(&data.arguments)- }- ExpressionKind::SuperCall(data) => arguments_reach(&data.arguments),- ExpressionKind::TaggedTemplateLiteral(data) => reaches(&data.tag) || reaches(&data.template_literal),- ExpressionKind::ImportCall(data) => {- reaches(&data.specifier) || data.options.as_ref().is_some_and(|options| reaches(options))- }- ExpressionKind::Yield(data) => data.argument.as_ref().is_some_and(|argument| reaches(argument)),-- ExpressionKind::OptionalChain(data) => {- reaches(&data.base)- || data.references.iter().any(|reference| match reference {- OptionalChainReference::Call { arguments, .. } => arguments_reach(arguments),- OptionalChainReference::ComputedReference { expression, .. } => reaches(expression),- OptionalChainReference::MemberReference { .. }- | OptionalChainReference::PrivateMemberReference { .. } => false,- })- }-- // The superclass and the element keys are evaluated in the enclosing scope. Method bodies,- // field initializers and static blocks belong to the class scope, so a binding they refer to- // counts as captured and never becomes a local.- ExpressionKind::Class(data) => {- data.super_class- .as_ref()- .is_some_and(|super_class| reaches(super_class))- || data.elements.iter().any(|element| match &element.inner {- ClassElement::Method { key, .. } | ClassElement::Field { key, .. } => reaches(key),- ClassElement::StaticInitializer { .. } => false,- })- }-- ExpressionKind::PrivateIdentifier(_) => false,- }-}--fn generate_variable_declaration(- generator: &mut Generator,- kind: DeclarationKind,- declarations: &[VariableDeclarator],-) {- for declaration in declarations {- let arena = generator.arena.clone();- // OPTIMIZATION: For let/const declarations where the target is a local identifier,- // pass the local as preferred_dst to the initializer. This allows NewArray, NewFunction,- // Add, etc. to write directly to the local instead of temp+Mov.- // NB: Not safe for `var` since var declarations can have duplicates, meaning the- // preferred_dst could be used as input in the initializer.- // NB: Also not safe when the initializer can reach the binding itself. Until the- // declaration finishes, the local must keep holding the Empty sentinel that marks the- // binding uninitialized, and generators like NewObject write their destination before- // they are done with it.- let init_dst = if kind != DeclarationKind::Var {- if let VariableDeclaratorTarget::Identifier(id) = &declaration.target {- let ident = &arena.identifiers[*id];- let local_index = ident.local_index;- let initializer_is_self_referential = declaration- .init- .as_ref()- .is_some_and(|init| expression_may_reach_local(&arena, init, local_index));- if ident.is_local() && ident.local_type == Some(LocalType::Variable) && !initializer_is_self_referential- {- Some(generator.local(local_index))- } else {- None- }- } else {- None- }- } else {- None- };-- // https://tc39.es/ecma262/#sec-variable-statement-runtime-semantics-evaluation- // VariableDeclaration : BindingIdentifier Initializer- //- // 1. Let _bindingId_ be the StringValue of |BindingIdentifier|.- // 2. Let _lhs_ be ? ResolveBinding(_bindingId_).- let resolved_binding = if kind == DeclarationKind::Var && declaration.init.is_some() {- if let VariableDeclaratorTarget::Identifier(id) = &declaration.target {- emit_resolve_binding_for_identifier_assignment(generator, *id)- } else {- None- }- } else {- None- };-- // Set pending LHS name for function name inference.- if let VariableDeclaratorTarget::Identifier(id) = &declaration.target {- let ident = &arena.identifiers[*id];- generator.pending_lhs_name = Some(generator.intern_identifier_id(ident.name));- }- let init_value = declaration- .init- .as_ref()- .and_then(|init| generate_expression(init, generator, init_dst.as_ref()));- generator.pending_lhs_name = None;-- match &declaration.target {- VariableDeclaratorTarget::Identifier(id) => {- let ident = &arena.identifiers[*id];- // var declarations without initializer don't need to assign undefined.- // The FDI already handles initialization for var bindings.- if init_value.is_none() && kind == DeclarationKind::Var {- if ident.is_local() {- generator.mark_local_initialized(ident.local_index);- }- continue;- }- let value = init_value.unwrap_or_else(|| generator.add_constant_undefined());- if ident.is_local() {- let local_index = ident.local_index;- let local = generator.resolve_local(local_index, ident.local_type.unwrap());- generator.emit_mov(&local, &value);- generator.mark_local_initialized(local_index);- } else {- let id = generator.intern_identifier_id(ident.name);- match kind {- DeclarationKind::Var => {- if let Some(resolved_binding) = &resolved_binding {- emit_set_resolved_binding(generator, resolved_binding, &value);- } else if ident.is_global {- let cache = generator.next_global_variable_cache();- generator.emit(Instruction::SetGlobal {- identifier: id,- src: value.operand(),- cache,- });- } else {- emit_set_lexical_binding(generator, id, value.operand());- }- }- DeclarationKind::Let | DeclarationKind::Const => {- emit_initialize_lexical_binding(generator, id, value.operand());- }- }- }- }- VariableDeclaratorTarget::BindingPattern(pattern) => {- if let Some(value) = init_value {- let mode = match kind {- DeclarationKind::Var => BindingMode::Set,- DeclarationKind::Let | DeclarationKind::Const => BindingMode::InitializeLexical,- };- generate_binding_pattern_bytecode(generator, pattern, mode, &value);- }- }- }- }-}--// =============================================================================-// Call expression-// =============================================================================--fn try_generate_builtin_abstract_operation(- generator: &mut Generator,- data: &CallExpressionData,- preferred_dst: Option<&ScopedOperand>,-) -> Option<Option<ScopedOperand>> {- if !generator.builtin_abstract_operations_enabled {- return None;- }- let arena = generator.arena.clone();- let name = match &data.callee.inner {- ExpressionKind::Identifier(ident)- if arena.identifiers[*ident].is_global && arena.identifiers[*ident].declaration_kind.is_none() =>- {- arena.name_slice(*ident)- }- _ => return None,- };- if data.arguments.iter().any(|a| a.is_spread) {- return None;- }-- let dst = choose_dst(generator, preferred_dst);-- // Operations that map to dedicated bytecode instructions.- if name == utf16!("IsCallable") {- let [value] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::IsCallable {- dst: dst.operand(),- value: value.operand(),- });- return Some(Some(dst));- }- if name == utf16!("IsConstructor") {- let [value] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::IsConstructor {- dst: dst.operand(),- value: value.operand(),- });- return Some(Some(dst));- }- if name == utf16!("ToBoolean") {- let [value] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::ToBoolean {- dst: dst.operand(),- value: value.operand(),- });- return Some(Some(dst));- }- if name == utf16!("ToObject") {- let [value] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::ToObject {- dst: dst.operand(),- value: value.operand(),- });- return Some(Some(dst));- }- if name == utf16!("ToLength") {- let [value] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::ToLength {- dst: dst.operand(),- value: value.operand(),- });- return Some(Some(dst));- }- if name == utf16!("ThrowIfNotObject") {- let [src] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::ThrowIfNotObject { src: src.operand() });- return Some(Some(dst));- }- if name == utf16!("ThrowNotAFunction") {- let [src] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::ThrowNotAFunction { src: src.operand() });- return Some(Some(dst));- }- if name == utf16!("ArgumentCount") {- let [] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::GetArgumentCount { dst: dst.operand() });- return Some(Some(dst));- }- if name == utf16!("ThrowTypeError") {- expect_builtin_argument_count(data, name, 1);- if let ExpressionKind::StringLiteral(ref s) = data.arguments[0].value.inner {- let message_string = generator.intern_string(s);- let type_error_register = generator.allocate_register();- generator.emit(Instruction::NewTypeError {- dst: type_error_register.operand(),- error_string: message_string,- });- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw {- src: type_error_register.operand(),- });- return Some(Some(dst));- }- return None;- }- if name == utf16!("NewTypeError") {- expect_builtin_argument_count(data, name, 1);- if let ExpressionKind::StringLiteral(ref s) = data.arguments[0].value.inner {- let message_string = generator.intern_string(s);- generator.emit(Instruction::NewTypeError {- dst: dst.operand(),- error_string: message_string,- });- return Some(Some(dst));- }- return None;- }- if name == utf16!("NewObjectWithNoPrototype") {- let [] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::NewObjectWithNoPrototype { dst: dst.operand() });- return Some(Some(dst));- }- if name == utf16!("NewArrayWithLength") {- let [length] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::NewArrayWithLength {- dst: dst.operand(),- array_length: length.operand(),- });- return Some(Some(dst));- }- if name == utf16!("CreateAsyncFromSyncIterator") {- let [iterator, next_method, done] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::CreateAsyncFromSyncIterator {- dst: dst.operand(),- iterator: iterator.operand(),- next_method: next_method.operand(),- done: done.operand(),- });- return Some(Some(dst));- }- if name == utf16!("CreateDataPropertyOrThrow") {- let [object, property, value] = generate_builtin_call_arguments(generator, data, name);- generator.emit(Instruction::CreateDataPropertyOrThrow {- object: object.operand(),- property: property.operand(),- value: value.operand(),- });- return Some(Some(dst));- }- if name == utf16!("Call") {- assert!(- data.arguments.len() >= 2,- "builtin Call takes a callee and a this value"- );- let mut arguments = generate_builtin_call_argument_list(generator, &data.arguments).into_iter();- let callee = arguments.next().unwrap();- let this_value = arguments.next().unwrap();- let argument_holders: Vec<ScopedOperand> = arguments.collect();- let arena_clone = generator.arena.clone();- let callee_name = expression_string_approximation(&data.arguments[0].value, &arena_clone)- .map(|s| generator.intern_string(&s));- let arguments: Vec<Operand> = argument_holders.iter().map(|a| a.operand()).collect();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: this_value.operand(),- argument_count: u32_from_usize(arguments.len()),- expression_string: callee_name,- arguments,- });- return Some(Some(dst));- }-- // Operations that map to intrinsic function calls.- let known_operations: &[(&[u16], AbstractOperationKind)] = &[- (utf16!("ArraySpeciesCreate"), AbstractOperationKind::ArraySpeciesCreate),- (utf16!("AsyncIteratorClose"), AbstractOperationKind::AsyncIteratorClose),- (utf16!("GetMethod"), AbstractOperationKind::GetMethod),- (utf16!("GetIteratorDirect"), AbstractOperationKind::GetIteratorDirect),- (- utf16!("GetIteratorFromMethod"),- AbstractOperationKind::GetIteratorFromMethod,- ),- (utf16!("IteratorComplete"), AbstractOperationKind::IteratorComplete),- ];- for &(op_name, operation) in known_operations {- if name == op_name {- let callee = generator.add_constant_abstract_operation(operation);- let undefined = generator.add_constant_undefined();- let expression_string = generator.intern_string(name);- let argument_holders = generate_builtin_call_argument_list(generator, &data.arguments);- let arguments: Vec<Operand> = argument_holders.iter().map(|a| a.operand()).collect();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: undefined.operand(),- argument_count: u32_from_usize(arguments.len()),- expression_string: Some(expression_string),- arguments,- });- return Some(Some(dst));- }- }-- None-}--fn expect_builtin_argument_count(data: &CallExpressionData, name: &[u16], count: usize) {- assert_eq!(- data.arguments.len(),- count,- "builtin {} takes {count} argument(s)",- String::from_utf16_lossy(name)- );-}--fn generate_builtin_call_arguments<const N: usize>(- generator: &mut Generator,- data: &CallExpressionData,- name: &[u16],-) -> [ScopedOperand; N] {- expect_builtin_argument_count(data, name, N);- let arguments = generate_builtin_call_argument_list(generator, &data.arguments);- arguments- .try_into()- .unwrap_or_else(|_| unreachable!("argument count was checked"))-}--/// Evaluate builtin call arguments in order, snapshotting any that a later argument might reassign.-fn generate_builtin_call_argument_list(generator: &mut Generator, arguments: &[CallArgument]) -> Vec<ScopedOperand> {- (0..arguments.len())- .map(|index| {- let value = generate_expression_or_undefined(&arguments[index].value, generator, None);- let later = arguments[index + 1..].iter().map(|later| &later.value);- copy_if_reassignable_by(generator, value, later)- })- .collect()-}--/// Try to generate a builtin constant (e.g. SYMBOL_ITERATOR).-/// Returns Some(operand) if the identifier is a known builtin constant.-fn try_generate_builtin_constant(generator: &mut Generator, name: &Utf16String) -> Option<ScopedOperand> {- if !generator.builtin_abstract_operations_enabled {- return None;- }- if *name == utf16!("SYMBOL_ITERATOR") {- return Some(generator.add_constant_well_known_symbol(WellKnownSymbolKind::SymbolIterator));- }- if *name == utf16!("SYMBOL_ASYNC_ITERATOR") {- return Some(generator.add_constant_well_known_symbol(WellKnownSymbolKind::SymbolAsyncIterator));- }- if *name == utf16!("MAX_ARRAY_LIKE_INDEX") {- return Some(generator.add_constant_number(9007199254740991.0));- }- None-}--/// Generate bytecode for a call expression (`f()`) or new expression (`new C()`).-///-/// Handles several special forms:-/// - Direct `eval()` calls (CallWithArgumentArray with IsDirectEval flag)-/// - Member calls (`obj.f()`) that need to pass `this`-/// - Super calls (`super()`)-/// - Spread arguments (CallWithArgumentArray)-/// - Builtin abstract operation detection for built-in JS files-fn generate_call_expression(- generator: &mut Generator,- data: &CallExpressionData,- preferred_dst: Option<&ScopedOperand>,- is_new: bool,-) -> Option<ScopedOperand> {- if generator.eager_compile_direct_iifes- && !is_new- && let ExpressionKind::Function(function_id) = &data.callee.inner- {- generator.eager_compile_function_ids.insert(*function_id);- }-- // Check for builtin abstract operations before anything else.- if !is_new && let Some(result) = try_generate_builtin_abstract_operation(generator, data, preferred_dst) {- return result;- }-- let dst = choose_dst(generator, preferred_dst);-- // Compute expression_string for error messages (e.g. "true is not a function (evaluated from 'a')").- let arena = generator.arena.clone();- let expression_string: Option<StringTableIndex> =- expression_string_approximation(&data.callee, &arena).map(|s| generator.intern_string(&s));-- // Detect direct eval calls: bare identifier "eval" as callee.- let is_direct_eval = !is_new- && matches!(&data.callee.inner, ExpressionKind::Identifier(ident) if arena.name_slice(*ident) == utf16!("eval"));-- // For method calls (obj.method()), we need to use the object as `this`.- let (callee, this_value) = if !is_new {- match &data.callee.inner {- ExpressionKind::Member(data) if matches!(data.object.inner, ExpressionKind::Super) => {- // Super member call: super.method() or super[expr]()- // Spec evaluation order:- // 1. ResolveThisBinding- // 2. Evaluate computed property (if any)- // 3. ResolveSuperBase- // 4. GetByIdWithThis / GetByValueWithThis- let this_value = emit_resolve_this_binding(generator);- let computed_key = if data.computed {- Some(generate_expression_or_undefined(&data.property, generator, None))- } else {- None- };- let super_base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase {- dst: super_base.operand(),- });- let method = generator.allocate_register();- if let Some(key) = computed_key {- emit_get_by_value_with_this(generator, &method, &super_base, &key, &this_value);- } else if let ExpressionKind::Identifier(ident) = &data.property.inner {- emit_get_by_id_with_this(generator, &method, &super_base, arena.name_slice(*ident), &this_value);- }- (method, Some(this_value))- }- ExpressionKind::Member(data) => {- let obj = generate_expression_or_undefined(&data.object, generator, None);- let obj = copy_if_reassignable_by(generator, obj, [&*data.property]);- let base_id = intern_base_identifier(generator, &data.object);- let method = generator.allocate_register();- if data.computed {- let property = generate_expression_or_undefined(&data.property, generator, None);- emit_get_by_value(generator, &method, &obj, &property, None);- } else if let ExpressionKind::Identifier(ident) = &data.property.inner {- emit_get_by_id(generator, &method, &obj, arena.name_slice(*ident), base_id);- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &data.property.inner {- let id = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::GetPrivateById {- dst: method.operand(),- base: obj.operand(),- property: id,- });- }- (method, Some(obj))- }- ExpressionKind::Identifier(ident) if arena.identifiers[*ident].is_local() => {- (generate_identifier(*ident, generator, None), None)- }- ExpressionKind::Identifier(ident) if !arena.identifiers[*ident].is_global => {- // Non-local, non-global identifier: use GetCalleeAndThisFromEnvironment- // to properly handle with-statement bindings and eval.- let callee_reg = generator.allocate_register();- let this_reg = generator.allocate_register();- let id = generator.intern_identifier_id(arena.identifiers[*ident].name);- emit_get_callee_and_this_from_environment(generator, callee_reg.operand(), this_reg.operand(), id);- (callee_reg, Some(this_reg))- }- ExpressionKind::OptionalChain(oc_data) => {- // Allocate callee (current_value) first, this_value- // (current_base) second.- let callee = generator.allocate_register();- let this_value = generator.allocate_register();- generate_optional_chain_inner(generator, &oc_data.base, &oc_data.references, &callee, &this_value)?;- (callee, Some(this_value))- }- _ => {- let callee = generate_expression_or_undefined(&data.callee, generator, None);- (callee, None)- }- }- } else {- let callee = generate_expression_or_undefined(&data.callee, generator, None);- (callee, None)- };-- // Copy callee/this into fresh registers so argument evaluation- // cannot mutate them (e.g. `foo.bar(foo = null)`).- // Zero-argument calls do not evaluate anything after the callee/this.- let this_value = if data.arguments.is_empty() {- this_value- } else {- this_value.map(|tv| generator.copy_if_needed_to_preserve_evaluation_order(&tv))- };- let callee = if data.arguments.is_empty() {- callee- } else {- generator.copy_if_needed_to_preserve_evaluation_order(&callee)- };-- // Unwrap this_value at function scope so its register lifetime outlives argument temporaries.- let this_value = this_value.unwrap_or_else(|| generator.add_constant_undefined());-- let has_spread = data.arguments.iter().any(|a| a.is_spread);-- if has_spread {- // Build an arguments array using NewArray + ArrayAppend for spread elements.- let arguments_array = generator.allocate_register();- let first_spread = data.arguments.iter().position(|a| a.is_spread).unwrap_or(0);-- let mut pre_holders = Vec::with_capacity(first_spread);- for argument in &data.arguments[..first_spread] {- let reg = generator.allocate_register();- let val = generate_expression_or_undefined(&argument.value, generator, None);- generator.emit_mov(®, &val);- pre_holders.push(reg);- }- let pre_arguments: Vec<Operand> = pre_holders.iter().map(|a| a.operand()).collect();- generator.emit(Instruction::NewArray {- dst: arguments_array.operand(),- element_count: u32_from_usize(pre_arguments.len()),- elements: pre_arguments,- });-- for argument in &data.arguments[first_spread..] {- let val = generate_expression_or_undefined(&argument.value, generator, None);- generator.emit(Instruction::ArrayAppend {- dst: arguments_array.operand(),- src: val.operand(),- is_spread: argument.is_spread,- });- }- if is_new {- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallConstructWithArgumentArray {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: this_value.operand(),- arguments: arguments_array.operand(),- expression_string,- });- } else if is_direct_eval {- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallDirectEvalWithArgumentArray {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: this_value.operand(),- arguments: arguments_array.operand(),- expression_string,- });- } else {- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallWithArgumentArray {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: this_value.operand(),- arguments: arguments_array.operand(),- expression_string,- });- }- } else {- // Copy local variables into fresh registers so that evaluating- // later arguments cannot mutate earlier argument values (e.g.- // `bar(i, i++)` — the first argument must be the pre-increment value).- let mut argument_holders = Vec::with_capacity(data.arguments.len());- for argument in &data.arguments {- let val = generate_expression_or_undefined(&argument.value, generator, None);- argument_holders.push(generator.copy_if_needed_to_preserve_evaluation_order(&val));- }- let arguments: Vec<Operand> = argument_holders.iter().map(|a| a.operand()).collect();-- if is_new {- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallConstruct {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- argument_count: u32_from_usize(arguments.len()),- expression_string,- arguments,- });- } else if is_direct_eval {- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallDirectEval {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: this_value.operand(),- argument_count: u32_from_usize(arguments.len()),- expression_string,- arguments,- });- } else {- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: callee.operand(),- this_value: this_value.operand(),- argument_count: u32_from_usize(arguments.len()),- expression_string,- arguments,- });- }- }-- Some(dst)-}--// =============================================================================-// Update expression (++/--)-// =============================================================================--/// Emit the increment/decrement operation for an update expression.-/// Returns the result operand: `value` for prefix, a new `dst` for postfix.-fn emit_update_op(generator: &mut Generator, op: UpdateOp, prefixed: bool, value: &ScopedOperand) -> ScopedOperand {- if prefixed {- match op {- UpdateOp::Increment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Increment {- arith_feedback,- dst: value.operand(),- });- }- UpdateOp::Decrement => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Decrement {- arith_feedback,- dst: value.operand(),- });- }- }- value.clone()- } else {- // Always allocate a fresh register for the old value.- let dst = generator.allocate_register();- match op {- UpdateOp::Increment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::PostfixIncrement {- arith_feedback,- dst: dst.operand(),- src: value.operand(),- });- }- UpdateOp::Decrement => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::PostfixDecrement {- arith_feedback,- dst: dst.operand(),- src: value.operand(),- });- }- }- dst- }-}--/// Convert a property name to the primitive that ToPropertyKey turns into a property key without observable effects,-/// in a register of its own unless it is a constant, which is a primitive already.-fn emit_to_primitive_property_key(generator: &mut Generator, property_name: &ScopedOperand) -> ScopedOperand {- if property_name.operand().is_constant() {- return property_name.clone();- }- // NB: The name can be the operand of a variable or of `this`, which converting it in place would change.- let property_key = generator.allocate_register();- generator.emit(Instruction::ToPrimitiveWithStringHint {- dst: property_key.operand(),- value: property_name.operand(),- });- property_key-}--/// Preserve the primitive key produced by GetValue so PutValue does not convert it again.-fn emit_read_modify_write_property_key(- generator: &mut Generator,- property: &ScopedOperand,- base: &ScopedOperand,-) -> ScopedOperand {- if property.operand().is_constant() {- return property.clone();- }- // GetValue converts the base to an object before converting the property key.- generator.emit(Instruction::ThrowIfNullish { src: base.operand() });- let key = generator.allocate_register();- generator.emit(Instruction::ToPrimitiveWithStringHint {- dst: key.operand(),- value: property.operand(),- });- key-}--fn generate_update_expression(- generator: &mut Generator,- op: UpdateOp,- argument: &Expression,- prefixed: bool,-) -> Option<ScopedOperand> {- // Load the value, keeping track of the base for member expressions- // so we can store back without re-evaluating.- match &argument.inner {- ExpressionKind::Identifier(ident) => {- let resolved_binding = emit_resolve_binding_for_identifier_assignment(generator, *ident);- let mut value = generate_identifier_with_resolved_binding(generator, *ident, resolved_binding.as_ref());- // The update is made in place, but storing to a constant throws, which must leave it unchanged.- if is_constant_local(generator, *ident) {- value = generator.copy_if_needed_to_preserve_evaluation_order(&value);- }- let result = emit_update_op(generator, op, prefixed, &value);- emit_set_variable_or_resolved_binding(generator, *ident, &value, resolved_binding.as_ref());- Some(result)- }- ExpressionKind::Member(data) => {- let is_super = matches!(data.object.inner, ExpressionKind::Super);-- if is_super {- // Per spec, evaluation order for super property access is:- // 1. ResolveThisBinding- // 2. Evaluate computed property (if any)- // 3. ResolveSuperBase- // 4. Property lookup with this- let this_value = emit_resolve_this_binding(generator);- let computed_key = if data.computed {- Some(generate_expression_or_undefined(&data.property, generator, None))- } else {- None- };- let base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase { dst: base.operand() });- let computed_key = computed_key.map(|key| emit_read_modify_write_property_key(generator, &key, &base));- let value = generator.allocate_register();- if let Some(ref key) = computed_key {- emit_get_by_value_with_this(generator, &value, &base, key, &this_value);- } else if let ExpressionKind::Identifier(ident) = &data.property.inner {- let arena = generator.arena.clone();- emit_get_by_id_with_this(generator, &value, &base, arena.name_slice(*ident), &this_value);- }- let result = emit_update_op(generator, op, prefixed, &value);- emit_super_put(- generator,- &base,- &data.property,- data.computed,- &this_value,- &value,- computed_key.as_ref(),- );- Some(result)- } else {- // Non-super member update expression.- let base = generate_expression(&data.object, generator, None)?;- let base = generator.copy_if_needed_to_preserve_evaluation_order(&base);- let base_id = intern_base_identifier(generator, &data.object);- if data.computed {- let property = generate_expression(&data.property, generator, None)?;- let property = emit_read_modify_write_property_key(generator, &property, &base);- let value = generator.allocate_register();- emit_get_by_value(generator, &value, &base, &property, base_id);- let result = emit_update_op(generator, op, prefixed, &value);- emit_put_normal_by_value(generator, &base, &property, &value, None);- Some(result)- } else if let ExpressionKind::Identifier(property_ident) = &data.property.inner {- let value = generator.allocate_register();- let arena = generator.arena.clone();- let property_name = arena.name_slice(*property_ident);- emit_get_by_id(generator, &value, &base, property_name, base_id);- let key = generator.intern_property_key(property_name);- let result = emit_update_op(generator, op, prefixed, &value);- let cache2 = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: base.operand(),- property: key,- src: value.operand(),- cache: cache2,- base_identifier: None,- kind: PutKind::Normal as u32,- });- Some(result)- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &data.property.inner {- let id = generator.intern_identifier(&priv_ident.name);- let value = generator.allocate_register();- generator.emit(Instruction::GetPrivateById {- dst: value.operand(),- base: base.operand(),- property: id,- });- let result = emit_update_op(generator, op, prefixed, &value);- generator.emit(Instruction::PutPrivateById {- base: base.operand(),- property: id,- src: value.operand(),- });- Some(result)- } else {- // Fallback: just evaluate, no store-back- let value = generator.allocate_register();- Some(value)- }- }- }- _ => {- // Invalid update target (e.g. foo()++). Per spec, evaluate the- // expression first, then throw ReferenceError.- generate_expression(argument, generator, None);- emit_invalid_lhs_error(generator);- Some(generator.add_constant_undefined())- }- }-}--// =============================================================================-// Assignment expression-// =============================================================================--/// Generate bytecode for all forms of assignment: simple (`=`), compound-/// (`+=`, `-=`, etc.), and logical (`&&=`, `||=`, `??=`).-///-/// Handles identifiers (local, global, environment), member expressions-/// (by-id, by-value, super, private), and destructuring patterns.-fn generate_assignment_expression(- generator: &mut Generator,- op: AssignmentOp,- lhs: &AssignmentLhs,- rhs: &Expression,- lhs_is_parenthesized: bool,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- match lhs {- AssignmentLhs::Expression(lhs_expression) => {- // Simple assignment to identifier- if let ExpressionKind::Identifier(id) = &lhs_expression.inner {- let id = *id;- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if op == AssignmentOp::Assignment {- // https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation- // AssignmentExpression : LeftHandSideExpression `=` AssignmentExpression- //- // 1. If |LeftHandSideExpression| is neither an |ObjectLiteral| nor an |ArrayLiteral|, then- // a. Let _lRef_ be ? Evaluation of |LeftHandSideExpression|.- // b. If the AssignmentTargetType of |LeftHandSideExpression| is ~web-compat~, throw a- // *ReferenceError* exception.- // c. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of- // |LeftHandSideExpression| is *true*, then- // i. Let _lhs_ be the StringValue of |LeftHandSideExpression|.- // ii. Let _rVal_ be ? NamedEvaluation of |AssignmentExpression| with argument _lhs_.- // d. Else,- // i. Let _rRef_ be ? Evaluation of |AssignmentExpression|.- // ii. Let _rVal_ be ? GetValue(_rRef_).- let resolved_binding = emit_resolve_binding_for_identifier_assignment(generator, id);- set_pending_lhs_name_for_identifier_assignment(generator, ident.name, lhs_is_parenthesized);- let rhs_val = generate_expression(rhs, generator, None)?;- generator.pending_lhs_name = None;- if ident.is_local() {- emit_tdz_check_if_needed(generator, id);- }- emit_set_variable_or_resolved_binding(generator, id, &rhs_val, resolved_binding.as_ref());- return Some(rhs_val);- }-- // Load LHS value first (needed for both compound and logical assignments).- let resolved_binding = emit_resolve_binding_for_identifier_assignment(generator, id);- let lhs_val = generate_identifier_with_resolved_binding(generator, id, resolved_binding.as_ref());- let lhs_val = generator.copy_if_needed_to_preserve_evaluation_order(&lhs_val);-- let is_logical = matches!(- op,- AssignmentOp::AndAssignment | AssignmentOp::OrAssignment | AssignmentOp::NullishAssignment- );- if is_logical {- // Logical assignments short-circuit: evaluate RHS only if condition met.- let rhs_block = generator.make_block();- let lhs_block = generator.make_block();- let end_block = generator.make_block();- match op {- AssignmentOp::AndAssignment => {- generator.emit_jump_if(&lhs_val, rhs_block, lhs_block);- }- AssignmentOp::OrAssignment => {- generator.emit_jump_if(&lhs_val, lhs_block, rhs_block);- }- AssignmentOp::NullishAssignment => {- generator.emit(Instruction::JumpNullish {- condition: lhs_val.operand(),- true_target: rhs_block,- false_target: lhs_block,- });- }- _ => unreachable!("only logical assignment ops reach this branch"),- }- // RHS block: evaluate RHS, assign, jump to end.- generator.switch_to_basic_block(rhs_block);- set_pending_lhs_name_for_identifier_assignment(- generator,- arena.identifiers[id].name,- lhs_is_parenthesized,- );- let rhs_val = generate_expression(rhs, generator, None)?;- generator.pending_lhs_name = None;- // Allocate dst after RHS evaluation.- let dst = choose_dst(generator, preferred_dst);- generator.emit_mov(&dst, &rhs_val);- emit_set_variable_or_resolved_binding(generator, id, &dst, resolved_binding.as_ref());- generator.emit(Instruction::Jump { target: end_block });- // LHS block: keep original value.- generator.switch_to_basic_block(lhs_block);- generator.emit_mov(&dst, &lhs_val);- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(end_block);- return Some(dst);- }-- // Regular compound assignment (+=, -=, etc.)- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- emit_compound_assignment(generator, op, &dst, &lhs_val, &rhs_val);- emit_set_variable_or_resolved_binding(generator, id, &dst, resolved_binding.as_ref());- return Some(dst);- }- // Member expression LHS (e.g., obj.foo = x, obj[key] = x)- if let ExpressionKind::Member(member_data) = &lhs_expression.inner {- let is_super = matches!(member_data.object.inner, ExpressionKind::Super);-- if is_super {- // Per spec, evaluation order for super property reference is:- // 1. ResolveThisBinding- // 2. Evaluate computed property (if any)- // 3. ResolveSuperBase- let super_this = emit_resolve_this_binding(generator);-- if op == AssignmentOp::Assignment {- let computed_key = if member_data.computed {- let key = generate_expression_or_undefined(&member_data.property, generator, None);- Some(copy_if_reassignable_by(generator, key, [rhs]))- } else {- None- };- let base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase { dst: base.operand() });- let rhs_val = generate_expression(rhs, generator, None)?;- emit_super_put(- generator,- &base,- &member_data.property,- member_data.computed,- &super_this,- &rhs_val,- computed_key.as_ref(),- );- return Some(rhs_val);- }-- // Compound/logical assignment: evaluate property, resolve- // super base, then get old value.- let computed_key = if member_data.computed {- Some(generate_expression_or_undefined(&member_data.property, generator, None))- } else {- None- };- let base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase { dst: base.operand() });- let computed_key =- computed_key.map(|key| emit_read_modify_write_property_key(generator, &key, &base));- let old_val = generator.allocate_register();- if let Some(ref key) = computed_key {- emit_get_by_value_with_this(generator, &old_val, &base, key, &super_this);- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let arena = generator.arena.clone();- emit_get_by_id_with_this(generator, &old_val, &base, arena.name_slice(*ident), &super_this);- }- let is_logical = matches!(- op,- AssignmentOp::AndAssignment | AssignmentOp::OrAssignment | AssignmentOp::NullishAssignment- );- if is_logical {- let rhs_block = generator.make_block();- let lhs_block = generator.make_block();- let end_block = generator.make_block();- emit_logical_jump(generator, op, &old_val, rhs_block, lhs_block);- generator.switch_to_basic_block(rhs_block);- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- generator.emit_mov(&dst, &rhs_val);- emit_super_put(- generator,- &base,- &member_data.property,- member_data.computed,- &super_this,- &dst,- computed_key.as_ref(),- );- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(lhs_block);- generator.emit_mov(&dst, &old_val);- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(end_block);- return Some(dst);- }- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- emit_compound_assignment(generator, op, &dst, &old_val, &rhs_val);- emit_super_put(- generator,- &base,- &member_data.property,- member_data.computed,- &super_this,- &dst,- computed_key.as_ref(),- );- return Some(dst);- }-- // Non-super member assignment.- let base_raw = generate_expression(&member_data.object, generator, None)?;-- if op == AssignmentOp::Assignment {- let base = generator.copy_if_needed_to_preserve_evaluation_order(&base_raw);- let precomputed_key = if member_data.computed {- let key_val = generate_expression_or_undefined(&member_data.property, generator, None);- Some(generator.copy_if_needed_to_preserve_evaluation_order(&key_val))- } else {- None- };- let rhs_val = generate_expression(rhs, generator, None)?;- if let Some(key) = precomputed_key {- let base_id = intern_base_identifier(generator, &member_data.object);- emit_put_normal_by_value(generator, &base, &key, &rhs_val, base_id);- } else {- emit_put_to_member(- generator,- &base,- &member_data.property,- false,- &rhs_val,- Some(&member_data.object),- );- }- return Some(rhs_val);- }-- // Compound/logical member assignment.- let base = generator.copy_if_needed_to_preserve_evaluation_order(&base_raw);- let base_id = intern_base_identifier(generator, &member_data.object);- let is_logical = matches!(- op,- AssignmentOp::AndAssignment | AssignmentOp::OrAssignment | AssignmentOp::NullishAssignment- );-- if member_data.computed {- let property = generate_expression(&member_data.property, generator, None)?;- let property = emit_read_modify_write_property_key(generator, &property, &base);- let old_val = generator.allocate_register();- emit_get_by_value(generator, &old_val, &base, &property, base_id);- if is_logical {- let rhs_block = generator.make_block();- let lhs_block = generator.make_block();- let end_block = generator.make_block();- emit_logical_jump(generator, op, &old_val, rhs_block, lhs_block);- generator.switch_to_basic_block(rhs_block);- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- generator.emit_mov(&dst, &rhs_val);- emit_put_normal_by_value(generator, &base, &property, &dst, None);- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(lhs_block);- generator.emit_mov(&dst, &old_val);- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(end_block);- return Some(dst);- }- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- emit_compound_assignment(generator, op, &dst, &old_val, &rhs_val);- emit_put_normal_by_value(generator, &base, &property, &dst, None);- return Some(dst);- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let old_val = generator.allocate_register();- let arena = generator.arena.clone();- let property_name = arena.name_slice(*ident);- emit_get_by_id(generator, &old_val, &base, property_name, base_id);- if is_logical {- let rhs_block = generator.make_block();- let lhs_block = generator.make_block();- let end_block = generator.make_block();- emit_logical_jump(generator, op, &old_val, rhs_block, lhs_block);- generator.switch_to_basic_block(rhs_block);- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- generator.emit_mov(&dst, &rhs_val);- let key = generator.intern_property_key(property_name);- let cache2 = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: base.operand(),- property: key,- src: dst.operand(),- cache: cache2,- base_identifier: None,- kind: PutKind::Normal as u32,- });- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(lhs_block);- generator.emit_mov(&dst, &old_val);- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(end_block);- return Some(dst);- }- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- emit_compound_assignment(generator, op, &dst, &old_val, &rhs_val);- let key = generator.intern_property_key(property_name);- let cache2 = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: base.operand(),- property: key,- src: dst.operand(),- cache: cache2,- base_identifier: None,- kind: PutKind::Normal as u32,- });- return Some(dst);- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &member_data.property.inner {- let old_val = generator.allocate_register();- let id = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::GetPrivateById {- dst: old_val.operand(),- base: base.operand(),- property: id,- });- if is_logical {- let rhs_block = generator.make_block();- let lhs_block = generator.make_block();- let end_block = generator.make_block();- emit_logical_jump(generator, op, &old_val, rhs_block, lhs_block);- generator.switch_to_basic_block(rhs_block);- let rhs_val = generate_expression(rhs, generator, None)?;- // Allocate dst after RHS evaluation.- let dst = choose_dst(generator, preferred_dst);- generator.emit_mov(&dst, &rhs_val);- let id2 = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::PutPrivateById {- base: base.operand(),- property: id2,- src: dst.operand(),- });- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(lhs_block);- generator.emit_mov(&dst, &old_val);- generator.emit(Instruction::Jump { target: end_block });- generator.switch_to_basic_block(end_block);- return Some(dst);- }- let rhs_val = generate_expression(rhs, generator, None)?;- let dst = choose_dst(generator, preferred_dst);- emit_compound_assignment(generator, op, &dst, &old_val, &rhs_val);- let id2 = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::PutPrivateById {- base: base.operand(),- property: id2,- src: dst.operand(),- });- return Some(dst);- }- }- // LHS is not an identifier or member expression (e.g. a function call).- // Per spec 13.15.2 step 1b, evaluate the LHS, then throw ReferenceError- // before evaluating the RHS.- generate_expression(lhs_expression, generator, None);- emit_invalid_lhs_error(generator);- Some(generator.add_constant_undefined())- }- AssignmentLhs::Pattern(pattern) => {- let rhs_val = generate_expression(rhs, generator, None)?;- generate_binding_pattern_bytecode(generator, pattern, BindingMode::Set, &rhs_val);- Some(rhs_val)- }- }-}--/// Emit ResolveThisBinding (if not already resolved in current block) and return-/// the this value register.-fn emit_resolve_this_binding(generator: &mut Generator) -> ScopedOperand {- emit_resolve_this_if_needed(generator);- generator.this_value()-}--/// Emit ResolveThisBinding only if not already resolved in the current or entry block.-fn emit_resolve_this_if_needed(generator: &mut Generator) {- let index = generator.current_block_index().basic_block_index();- if generator.basic_blocks[index].resolved_this {- return;- }- if generator.basic_blocks[0].resolved_this {- generator.basic_blocks[index].resolved_this = true;- return;- }- generator.emit(Instruction::ResolveThisBinding);- let index = generator.current_block_index().basic_block_index();- generator.basic_blocks[index].resolved_this = true;-}--/// Emit a super property put (uses WithThis variants), to the computed key the caller evaluated for computed access.-fn emit_super_put(- generator: &mut Generator,- base: &ScopedOperand,- property: &Expression,- computed: bool,- this_value: &ScopedOperand,- value: &ScopedOperand,- computed_key: Option<&ScopedOperand>,-) {- if computed {- let property = computed_key.expect("a computed super property put has its evaluated key");- emit_put_normal_by_value_with_this(generator, base, property, this_value, value);- } else if let ExpressionKind::Identifier(ident) = &property.inner {- let arena = generator.arena.clone();- let key = generator.intern_property_key_id(arena.identifiers[*ident].name);- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByIdWithThis {- base: base.operand(),- this_value: this_value.operand(),- property: key,- src: value.operand(),- cache,- kind: PutKind::Normal as u32,- });- }-}--/// Emit a property access by name, using GetLength for the "length" property.-fn emit_get_by_id(- generator: &mut Generator,- dst: &ScopedOperand,- base: &ScopedOperand,- property_name: &[u16],- base_identifier: Option<IdentifierTableIndex>,-) {- let key = generator.intern_property_key(property_name);- if property_name == utf16!("length") {- generator.length_identifier = Some(key);- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- let keyed_feedback = generator.next_keyed_feedback();- generator.emit(Instruction::GetLength {- value_feedback,- keyed_feedback,- dst: dst.operand(),- base: base.operand(),- base_identifier,- cache,- });- } else {- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetById {- value_feedback,- dst: dst.operand(),- base: base.operand(),- property: key,- base_identifier,- cache,- });- }-}--/// Emit a property access by name with a this value, using GetLengthWithThis-/// for the "length" property.-fn emit_get_by_id_with_this(- generator: &mut Generator,- dst: &ScopedOperand,- base: &ScopedOperand,- property_name: &[u16],- this_value: &ScopedOperand,-) {- let key = generator.intern_property_key(property_name);- if property_name == utf16!("length") {- generator.length_identifier = Some(key);- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetLengthWithThis {- value_feedback,- dst: dst.operand(),- base: base.operand(),- this_value: this_value.operand(),- cache,- });- } else {- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetByIdWithThis {- value_feedback,- dst: dst.operand(),- base: base.operand(),- property: key,- this_value: this_value.operand(),- cache,- });- }-}--/// Emit a "Invalid left-hand side in assignment" ReferenceError followed by Throw.-fn emit_invalid_lhs_error(generator: &mut Generator) {- let exception = generator.allocate_register();- let error_string = generator.intern_string(utf16!("Invalid left-hand side in assignment"));- generator.emit(Instruction::NewReferenceError {- dst: exception.operand(),- error_string,- });- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw {- src: exception.operand(),- });-}--/// Check if a UTF-16 string is a canonical array index (non-negative integer < 2^32 - 1).-/// These strings become integer PropertyKeys,-/// not string PropertyKeys, so they must NOT be optimized to GetById/PutById.-pub(crate) fn is_array_index(s: &[u16]) -> bool {- if s.is_empty() || s.len() > 10 {- return false;- }- // Must not have leading zeros (except "0" itself)- if s.len() > 1 && s[0] == ch(b'0') {- return false;- }- let mut value: u64 = 0;- for &c in s {- if c < ch(b'0') || c > ch(b'9') {- return false;- }- value = value * 10 + (c - ch(b'0')) as u64;- }- value <= 0xFFFF_FFFE-}--/// Emit a property read by value, optimizing constant string properties to GetById.-fn emit_get_by_value(- generator: &mut Generator,- dst: &ScopedOperand,- base: &ScopedOperand,- property: &ScopedOperand,- base_identifier: Option<IdentifierTableIndex>,-) {- if let Some(key) = generator.try_constant_string_to_property_key(property) {- if generator.property_key_table[key.0 as usize] == ak::Utf16FlyString::from_utf8("length") {- generator.length_identifier = Some(key);- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- let keyed_feedback = generator.next_keyed_feedback();- generator.emit(Instruction::GetLength {- value_feedback,- keyed_feedback,- dst: dst.operand(),- base: base.operand(),- base_identifier,- cache,- });- } else {- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetById {- value_feedback,- dst: dst.operand(),- base: base.operand(),- property: key,- base_identifier,- cache,- });- }- return;- }- let value_feedback = generator.next_value_feedback();- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetByValue {- value_feedback,- keyed_feedback,- dst: dst.operand(),- base: base.operand(),- property: property.operand(),- base_identifier,- cache,- });-}--/// Emit a property read by value with explicit this, optimizing constant string properties.-fn emit_get_by_value_with_this(- generator: &mut Generator,- dst: &ScopedOperand,- base: &ScopedOperand,- property: &ScopedOperand,- this_value: &ScopedOperand,-) {- if let Some(key) = generator.try_constant_string_to_property_key(property) {- if generator.property_key_table[key.0 as usize] == ak::Utf16FlyString::from_utf8("length") {- generator.length_identifier = Some(key);- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetLengthWithThis {- value_feedback,- dst: dst.operand(),- base: base.operand(),- this_value: this_value.operand(),- cache,- });- } else {- let cache = generator.next_property_lookup_cache();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetByIdWithThis {- value_feedback,- dst: dst.operand(),- base: base.operand(),- property: key,- this_value: this_value.operand(),- cache,- });- }- return;- }- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::GetByValueWithThis {- value_feedback,- dst: dst.operand(),- base: base.operand(),- property: property.operand(),- this_value: this_value.operand(),- });-}--/// Emit a normal property write by value, optimizing constant string properties to PutNormalById.-fn emit_put_normal_by_value(- generator: &mut Generator,- base: &ScopedOperand,- property: &ScopedOperand,- src: &ScopedOperand,- base_identifier: Option<IdentifierTableIndex>,-) {- if let Some(key) = generator.try_constant_string_to_property_key(property) {- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: base.operand(),- property: key,- src: src.operand(),- cache,- base_identifier,- kind: PutKind::Normal as u32,- });- return;- }- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: base.operand(),- property: property.operand(),- src: src.operand(),- base_identifier,- kind: PutKind::Normal as u32,- cache,- });-}--/// Emit a normal property write by value with explicit this, optimizing constant string properties.-fn emit_put_normal_by_value_with_this(- generator: &mut Generator,- base: &ScopedOperand,- property: &ScopedOperand,- this_value: &ScopedOperand,- src: &ScopedOperand,-) {- if let Some(key) = generator.try_constant_string_to_property_key(property) {- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByIdWithThis {- base: base.operand(),- this_value: this_value.operand(),- property: key,- src: src.operand(),- cache,- kind: PutKind::Normal as u32,- });- return;- }- generator.emit(Instruction::PutByValueWithThis {- base: base.operand(),- property: property.operand(),- this_value: this_value.operand(),- src: src.operand(),- kind: PutKind::Normal as u32,- });-}--/// Emit a property write by value, optimizing constant string properties to the ById variant.-fn emit_put_by_value(- generator: &mut Generator,- base: &ScopedOperand,- property: &ScopedOperand,- src: &ScopedOperand,- kind: PutKind,-) {- if let Some(key) = generator.try_constant_string_to_property_key(property) {- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: base.operand(),- property: key,- src: src.operand(),- cache,- base_identifier: None,- kind: kind as u32,- });- return;- }- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: base.operand(),- property: property.operand(),- src: src.operand(),- base_identifier: None,- kind: kind as u32,- cache,- });-}--/// Emit a ThrowIfTDZ check of a local identifier that is not known to be initialized here.-fn emit_tdz_check_if_needed(generator: &mut Generator, id: crate::ast::IdentifierId) {- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if !ident.is_local() {- return;- }- let local_index = ident.local_index;- let needs_tdz_check = if ident.local_type == Some(LocalType::Argument) {- !generator.is_argument_initialized(local_index)- } else {- generator.is_local_lexically_declared(local_index) && !generator.is_local_initialized(local_index)- };- if needs_tdz_check {- let local = generator.resolve_local(local_index, ident.local_type.unwrap());- if ident.local_type == Some(LocalType::Argument) {- let empty = generator.add_constant_empty();- generator.emit_mov(&local, &empty);- } else {- generator.mark_local_tdz_checked(local_index);- }- generator.emit(Instruction::ThrowIfTDZ { src: local.operand() });- }-}--fn is_constant_local(generator: &Generator, id: crate::ast::IdentifierId) -> bool {- let ident = &generator.arena.identifiers[id];- ident.is_local() && ident.declaration_kind == Some(DeclarationKind::Const)-}--fn emit_set_variable(generator: &mut Generator, id: crate::ast::IdentifierId, value: &ScopedOperand) {- if is_constant_local(generator, id) {- // The caller is responsible for emitting ThrowIfTDZ before calling- // emit_set_variable().- generator.emit(Instruction::ThrowConstAssignment {});- return;- }- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if ident.is_local() {- let local_index = ident.local_index;- let local = generator.resolve_local(local_index, ident.local_type.unwrap());- // Skip self-move entirely, of variables and arguments alike.- if local.operand() == value.operand() {- return;- }- // No TDZ check here: the caller is responsible for checking TDZ- // before calling emit_set_variable().- generator.emit(Instruction::Mov {- dst: local.operand(),- src: value.operand(),- });- } else if ident.is_global {- let id = generator.intern_identifier_id(ident.name);- let cache = generator.next_global_variable_cache();- generator.emit(Instruction::SetGlobal {- identifier: id,- src: value.operand(),- cache,- });- } else {- // Non-local, non-global: use SetLexicalBinding which searches- // the lexical environment chain (important for with-statement support).- let id = generator.intern_identifier_id(ident.name);- emit_set_lexical_binding(generator, id, value.operand());- }-}--fn emit_put_to_member(- generator: &mut Generator,- base: &ScopedOperand,- property: &Expression,- computed: bool,- value: &ScopedOperand,- base_object: Option<&Expression>,-) {- let base_id = base_object.and_then(|obj| intern_base_identifier(generator, obj));- if computed {- let property = generate_expression_or_undefined(property, generator, None);- emit_put_normal_by_value(generator, base, &property, value, base_id);- } else if let ExpressionKind::Identifier(ident) = &property.inner {- let arena = generator.arena.clone();- let key = generator.intern_property_key_id(arena.identifiers[*ident].name);- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: base.operand(),- property: key,- src: value.operand(),- cache,- base_identifier: base_id,- kind: PutKind::Normal as u32,- });- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &property.inner {- let id = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::PutPrivateById {- base: base.operand(),- property: id,- src: value.operand(),- });- }-}--/// Emit bytecode for `delete <expression>`.-fn emit_delete_reference(generator: &mut Generator, operand: &Expression) -> ScopedOperand {- match &operand.inner {- ExpressionKind::Identifier(ident) => {- let arena = generator.arena.clone();- let identifier = &arena.identifiers[*ident];- if identifier.is_local() {- return generator.add_constant_boolean(false);- }- let dst = generator.allocate_register();- let id = generator.intern_identifier_id(identifier.name);- generator.emit(Instruction::DeleteVariable {- dst: dst.operand(),- identifier: id,- });- dst- }- ExpressionKind::Member(data) => {- // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation- // Deleting a super property is always a ReferenceError.- if matches!(data.object.inner, ExpressionKind::Super) {- let this_value = emit_resolve_this_binding(generator);- // Evaluate computed property for side effects before throwing.- // Per spec, property key evaluation precedes ResolveSuperBase.- let _computed_key = if data.computed {- Some(generate_expression_or_undefined(&data.property, generator, None))- } else {- None- };- let super_base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase {- dst: super_base.operand(),- });- let exception = generator.allocate_register();- let error_string = generator.intern_string(utf16!("Can't delete a property on 'super'"));- generator.emit(Instruction::NewReferenceError {- dst: exception.operand(),- error_string,- });- generator.perform_needed_unwinds();- generator.emit(Instruction::Throw {- src: exception.operand(),- });- let dead_block = generator.make_block();- generator.switch_to_basic_block(dead_block);- let _ = (this_value, _computed_key);- return generator.add_constant_undefined();- }- let base = generate_expression_or_undefined(&data.object, generator, None);- let base = copy_if_reassignable_by(generator, base, [&*data.property]);- let dst = generator.allocate_register();- if data.computed {- let key = generate_expression_or_undefined(&data.property, generator, None);- generator.emit(Instruction::DeleteByValue {- dst: dst.operand(),- base: base.operand(),- property: key.operand(),- });- } else if let ExpressionKind::Identifier(property_ident) = &data.property.inner {- let arena = generator.arena.clone();- let key = generator.intern_property_key_id(arena.identifiers[*property_ident].name);- generator.emit(Instruction::DeleteById {- dst: dst.operand(),- base: base.operand(),- property: key,- });- } else {- return generator.add_constant_boolean(true);- }- dst- }- ExpressionKind::OptionalChain(data) => emit_delete_optional_chain_reference(generator, data),- _ => {- // delete on non-reference: evaluate for side effects, return true- generate_expression(operand, generator, None);- generator.add_constant_boolean(true)- }- }-}--/// Pre-evaluated reference operands for deferred store.-/// Used when the spec requires evaluating the assignment target reference-/// before performing some other operation (like iterating a spread element).-enum EvaluatedReference {- Binding(ResolvedBinding),- Member {- base: ScopedOperand,- property: ScopedOperand,- base_identifier: Option<IdentifierTableIndex>,- },- MemberId {- base: ScopedOperand,- property: PropertyKeyTableIndex,- cache: u32,- base_identifier: Option<IdentifierTableIndex>,- },- PrivateMember {- base: ScopedOperand,- property: IdentifierTableIndex,- },- SuperMember {- base: ScopedOperand,- property: ScopedOperand,- this_value: ScopedOperand,- },- SuperMemberId {- base: ScopedOperand,- property: PropertyKeyTableIndex,- cache: u32,- this_value: ScopedOperand,- },-}--/// Evaluate a member expression target to get pre-computed reference operands-/// without performing a load. This implements the "Let lref be ? Evaluation of-/// DestructuringAssignmentTarget" step from the spec.-fn emit_evaluate_member_reference(generator: &mut Generator, target: &Expression) -> EvaluatedReference {- if let ExpressionKind::Member(member_data) = &target.inner {- let is_super = matches!(member_data.object.inner, ExpressionKind::Super);-- if is_super {- // ResolveThisBinding first, then the computed property, then ResolveSuperBase.- let this_value = emit_resolve_this_binding(generator);- let computed_property = member_data- .computed- .then(|| generate_expression_or_undefined(&member_data.property, generator, None));- let base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase { dst: base.operand() });- if let Some(property) = computed_property {- // If the computed property is a constant string (e.g. super["minutes"]),- // optimize to SuperMemberId.- if let Some(key) = generator.try_constant_string_to_property_key(&property) {- let cache = generator.next_property_lookup_cache();- EvaluatedReference::SuperMemberId {- base,- property: key,- cache,- this_value,- }- } else {- let saved_property = generator.allocate_register();- generator.emit_mov(&saved_property, &property);- EvaluatedReference::SuperMember {- base,- property: saved_property,- this_value,- }- }- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let arena = generator.arena.clone();- let key = generator.intern_property_key_id(arena.identifiers[*ident].name);- let cache = generator.next_property_lookup_cache();- EvaluatedReference::SuperMemberId {- base,- property: key,- cache,- this_value,- }- } else {- unreachable!("non-computed super member property must be an identifier")- }- } else {- let base = generate_expression_or_undefined(&member_data.object, generator, None);- let base = generator.copy_if_needed_to_preserve_evaluation_order(&base);- if member_data.computed {- let property = generate_expression_or_undefined(&member_data.property, generator, None);- // If the computed property is a constant string (e.g. obj["key"]),- // optimize to MemberId.- if let Some(key) = generator.try_constant_string_to_property_key(&property) {- let cache = generator.next_property_lookup_cache();- EvaluatedReference::MemberId {- base,- property: key,- cache,- base_identifier: None,- }- } else {- let saved_property = generator.allocate_register();- generator.emit_mov(&saved_property, &property);- EvaluatedReference::Member {- base,- property: saved_property,- base_identifier: None,- }- }- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let arena = generator.arena.clone();- let key = generator.intern_property_key_id(arena.identifiers[*ident].name);- let cache = generator.next_property_lookup_cache();- EvaluatedReference::MemberId {- base,- property: key,- cache,- base_identifier: None,- }- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &member_data.property.inner {- let id = generator.intern_identifier(&priv_ident.name);- EvaluatedReference::PrivateMember { base, property: id }- } else {- unreachable!("non-computed member property must be an identifier or private identifier")- }- }- } else {- unreachable!("emit_evaluate_member_reference called on non-member expression")- }-}--/// Store a value to a pre-evaluated reference.-fn emit_store_to_evaluated_reference(generator: &mut Generator, reference: &EvaluatedReference, value: &ScopedOperand) {- match reference {- EvaluatedReference::Binding(binding) => emit_set_resolved_binding(generator, binding, value),- EvaluatedReference::Member {- base,- property,- base_identifier,- } => {- emit_put_normal_by_value(generator, base, property, value, *base_identifier);- }- EvaluatedReference::MemberId {- base,- property,- cache,- base_identifier,- } => {- generator.emit(Instruction::PutById {- base: base.operand(),- property: *property,- src: value.operand(),- cache: *cache,- base_identifier: *base_identifier,- kind: PutKind::Normal as u32,- });- }- EvaluatedReference::PrivateMember { base, property } => {- generator.emit(Instruction::PutPrivateById {- base: base.operand(),- property: *property,- src: value.operand(),- });- }- EvaluatedReference::SuperMember {- base,- property,- this_value,- } => {- emit_put_normal_by_value_with_this(generator, base, property, this_value, value);- }- EvaluatedReference::SuperMemberId {- base,- property,- cache,- this_value,- } => {- generator.emit(Instruction::PutByIdWithThis {- base: base.operand(),- this_value: this_value.operand(),- property: *property,- src: value.operand(),- cache: *cache,- kind: PutKind::Normal as u32,- });- }- }-}--fn emit_store_to_reference(generator: &mut Generator, target: &Expression, value: &ScopedOperand) {- match &target.inner {- ExpressionKind::Identifier(ident) => {- emit_tdz_check_if_needed(generator, *ident);- emit_set_variable(generator, *ident, value);- }- ExpressionKind::Member(data) => {- if matches!(data.object.inner, ExpressionKind::Super) {- // ResolveThisBinding first, then the computed property, then ResolveSuperBase.- let this_value = emit_resolve_this_binding(generator);- let computed_key = data- .computed- .then(|| generate_expression_or_undefined(&data.property, generator, None));- let base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase { dst: base.operand() });- emit_super_put(- generator,- &base,- &data.property,- data.computed,- &this_value,- value,- computed_key.as_ref(),- );- } else {- let base = generate_expression_or_undefined(&data.object, generator, None);- let base = copy_if_reassignable_by(generator, base, [&*data.property]);- emit_put_to_member(generator, &base, &data.property, data.computed, value, None);- }- }- _ => {- // Evaluate the expression for side effects, then throw ReferenceError.- generate_expression(target, generator, None);- emit_invalid_lhs_error(generator);- }- }-}--/// Emit the conditional jump for a logical assignment (&&=, ||=, ??=).-fn emit_logical_jump(- generator: &mut Generator,- op: AssignmentOp,- condition: &ScopedOperand,- rhs_block: Label,- lhs_block: Label,-) {- match op {- AssignmentOp::AndAssignment => {- generator.emit_jump_if(condition, rhs_block, lhs_block);- }- AssignmentOp::OrAssignment => {- generator.emit_jump_if(condition, lhs_block, rhs_block);- }- AssignmentOp::NullishAssignment => {- generator.emit(Instruction::JumpNullish {- condition: condition.operand(),- true_target: rhs_block,- false_target: lhs_block,- });- }- _ => unreachable!("only logical assignment ops are passed to emit_logical_jump"),- }-}--fn emit_compound_assignment(- generator: &mut Generator,- op: AssignmentOp,- dst: &ScopedOperand,- lhs: &ScopedOperand,- rhs: &ScopedOperand,-) {- let dst_op = dst.operand();- let lhs_op = lhs.operand();- let rhs_op = rhs.operand();- match op {- AssignmentOp::AdditionAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Add {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::SubtractionAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Sub {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::MultiplicationAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Mul {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::DivisionAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Div {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::ModuloAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Mod {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::ExponentiationAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::Exp {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::BitwiseAndAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseAnd {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::BitwiseOrAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseOr {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::BitwiseXorAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::BitwiseXor {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::LeftShiftAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::LeftShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::RightShiftAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::RightShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::UnsignedRightShiftAssignment => {- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::UnsignedRightShift {- arith_feedback,- dst: dst_op,- lhs: lhs_op,- rhs: rhs_op,- });- }- AssignmentOp::AndAssignment | AssignmentOp::OrAssignment | AssignmentOp::NullishAssignment => {- unreachable!("logical assignment in compound path")- }- AssignmentOp::Assignment => unreachable!("plain assignment in compound path"),- }-}--// =============================================================================-// Template literal-// =============================================================================--fn generate_template_literal(- generator: &mut Generator,- data: &TemplateLiteralData,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // The parser stores ALL parts (string segments AND interpolated expressions)- // in data.expressions. raw_strings is only populated for tagged templates.-- // OPTIMIZATION: Filter out empty string segments.- let segments: Vec<&Expression> = data- .expressions- .iter()- .filter(|e| !matches!(&e.inner, ExpressionKind::StringLiteral(s) if s.is_empty()))- .collect();-- if segments.is_empty() {- return Some(generator.add_constant_string(Utf16String::new()));- }-- // Allocate dst before generating expressions.- let dst = choose_dst(generator, preferred_dst);-- if segments.len() == 1 {- let val = generate_expression(segments[0], generator, None)?;- // OPTIMIZATION: Convert a constant at compile time.- if let Some(string) = generator.get_constant(&val).and_then(constant_to_string) {- return Some(generator.add_constant_string(string));- }- // Otherwise, emit ToString.- generator.emit(Instruction::ToString {- dst: dst.operand(),- value: val.operand(),- });- return Some(dst);- }-- for (index, expression) in segments.iter().enumerate() {- let val = generate_expression_or_undefined(expression, generator, None);- if index == 0 {- if matches!(&expression.inner, ExpressionKind::StringLiteral(_)) {- generator.emit_mov(&dst, &val);- } else {- generator.emit(Instruction::ToString {- dst: dst.operand(),- value: val.operand(),- });- }- } else {- generator.emit(Instruction::ConcatString {- dst: dst.operand(),- src: val.operand(),- });- }- }-- Some(dst)-}--// =============================================================================-// Tagged template literal-// =============================================================================--fn generate_tagged_template_literal(- generator: &mut Generator,- tag: &Expression,- template_literal: &Expression,- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- // Resolve tag and this_value based on the tag expression type.- let (tag_reg, this_value) = match &tag.inner {- ExpressionKind::Member(member_data) if matches!(member_data.object.inner, ExpressionKind::Super) => {- // super.func`` or super["func"]``- // Per spec, evaluation order: ResolveThisBinding, evaluate- // computed property, then ResolveSuperBase.- let this_value = emit_resolve_this_binding(generator);- let computed_key = if member_data.computed {- Some(generate_expression_or_undefined(&member_data.property, generator, None))- } else {- None- };- let super_base = generator.allocate_register();- generator.emit(Instruction::ResolveSuperBase {- dst: super_base.operand(),- });- let method = generator.allocate_register();- let arena = generator.arena.clone();- if let Some(key) = computed_key {- emit_get_by_value_with_this(generator, &method, &super_base, &key, &this_value);- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- emit_get_by_id_with_this(generator, &method, &super_base, arena.name_slice(*ident), &this_value);- }- (method, Some(this_value))- }- ExpressionKind::Member(member_data) => {- let arena = generator.arena.clone();- let obj = generate_expression_or_undefined(&member_data.object, generator, None);- let obj = copy_if_reassignable_by(generator, obj, [&*member_data.property]);- let method = generator.allocate_register();- if member_data.computed {- let property = generate_expression_or_undefined(&member_data.property, generator, None);- emit_get_by_value(generator, &method, &obj, &property, None);- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let base_id = intern_base_identifier(generator, &member_data.object);- emit_get_by_id(generator, &method, &obj, arena.name_slice(*ident), base_id);- } else if let ExpressionKind::PrivateIdentifier(priv_ident) = &member_data.property.inner {- let id = generator.intern_identifier(&priv_ident.name);- generator.emit(Instruction::GetPrivateById {- dst: method.operand(),- base: obj.operand(),- property: id,- });- }- (method, Some(obj))- }- ExpressionKind::Identifier(ident)- if generator.arena.identifiers[*ident].is_local() || generator.arena.identifiers[*ident].is_global =>- {- let tag_val = generate_expression_or_undefined(tag, generator, None);- (tag_val, None)- }- ExpressionKind::Identifier(ident) => {- // Non-local, non-global identifier: use GetCalleeAndThisFromEnvironment- // to properly handle with-statement bindings.- let callee_reg = generator.allocate_register();- let this_reg = generator.allocate_register();- let arena = generator.arena.clone();- let id = generator.intern_identifier_id(arena.identifiers[*ident].name);- emit_get_callee_and_this_from_environment(generator, callee_reg.operand(), this_reg.operand(), id);- (callee_reg, Some(this_reg))- }- _ => {- let tag_val = generate_expression_or_undefined(tag, generator, None);- (tag_val, None)- }- };-- // Build template strings for GetTemplateObject.- // expressions has alternating: string_0, expression_0, string_1, expression_1, ..., string_n- let ExpressionKind::TemplateLiteral(data) = &template_literal.inner else {- unreachable!("TaggedTemplateLiteral template must be TemplateLiteral");- };-- // Substitutions are evaluated after the tag, so snapshot whatever a later substitution might reassign.- let tag_reg = copy_if_reassignable_by(generator, tag_reg, &data.expressions);- let this_value = this_value.map(|value| copy_if_reassignable_by(generator, value, &data.expressions));-- // Collect cooked strings (even indices). NullLiteral means invalid escape → undefined.- let mut string_regs = Vec::new();- for i in (0..data.expressions.len()).step_by(2) {- if matches!(&data.expressions[i].inner, ExpressionKind::NullLiteral) {- string_regs.push(generator.add_constant_undefined());- } else {- let val = generate_expression_or_undefined(&data.expressions[i], generator, None);- string_regs.push(val);- }- }-- // Append raw strings.- for raw in &data.raw_strings {- let val = generator.add_constant_string(raw.clone());- string_regs.push(val);- }-- // Emit GetTemplateObject.- let strings_array = generator.allocate_register();- let string_ops: Vec<Operand> = string_regs.iter().map(|s| s.operand()).collect();- let cache_index = generator.next_template_object_cache();- generator.emit(Instruction::GetTemplateObject {- dst: strings_array.operand(),- strings_count: u32_from_usize(string_ops.len()),- cache: cache_index,- strings: string_ops,- });-- // Build arguments: [template_object, ...interpolated_expressions]- let mut argument_regs = vec![strings_array];- for i in (1..data.expressions.len()).step_by(2) {- let val = generate_expression_or_undefined(&data.expressions[i], generator, None);- argument_regs.push(copy_if_reassignable_by(generator, val, &data.expressions[i + 1..]));- }-- let dst = choose_dst(generator, preferred_dst);- let this_op = this_value.unwrap_or_else(|| generator.add_constant_undefined());- let arguments: Vec<Operand> = argument_regs.iter().map(|a| a.operand()).collect();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: dst.operand(),- callee: tag_reg.operand(),- this_value: this_op.operand(),- argument_count: u32_from_usize(arguments.len()),- expression_string: None,- arguments,- });-- dst-}--// =============================================================================-// Switch statement-// =============================================================================--fn generate_switch_statement(- generator: &mut Generator,- data: &SwitchStatementData,- _preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let completion = generator.allocate_completion_register();-- let discriminant = generate_expression(&data.discriminant, generator, None)?;-- // A case test may reassign the local or argument the discriminant was read from.- let discriminant = if data- .cases- .iter()- .any(|case| case.test.as_ref().is_some_and(might_contain_assignment_expression))- {- generator.copy_if_needed_to_preserve_evaluation_order(&discriminant)- } else {- discriminant- };-- // Block declaration instantiation: create lexical environment for- // function declarations and let/const across all switch cases.- let did_create_env = emit_switch_block_declaration_instantiation(generator, data);- if did_create_env {- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- }-- let initialized_locals_at_entry = generator.initialized_locals.clone();- let arena = generator.arena.clone();- emit_tdz_reset_of_declared_locals(- generator,- data.cases- .iter()- .flat_map(|case| arena.scopes[case.scope].children.iter()),- );-- // Create first test block and jump to it.- let first_test_block = generator.make_block();- generator.emit(Instruction::Jump {- target: first_test_block,- });-- // Pre-allocate test blocks for each case with a test expression.- let mut test_blocks: Vec<Label> = Vec::with_capacity(data.cases.len());- for case in &data.cases {- if case.test.is_some() {- test_blocks.push(generator.make_block());- }- }-- // Emit comparison chain: for each case, create the case body block,- // switch to the test block, evaluate the test, and emit comparison.- // Test blocks are interleaved with case body blocks.- let mut next_test_block = first_test_block;- let mut case_blocks: Vec<Label> = Vec::with_capacity(data.cases.len());- let mut default_block = None;- let mut test_block_index = 0;-- for case in &data.cases {- let case_block = generator.make_block();- if let Some(test) = &case.test {- generator.switch_to_basic_block(next_test_block);- let test_val = generate_expression(test, generator, None)?;- let cmp = generator.allocate_register();- // NB: test_value is LHS, discriminant is RHS.- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::StrictlyEquals {- arith_feedback,- dst: cmp.operand(),- lhs: test_val.operand(),- rhs: discriminant.operand(),- });- next_test_block = test_blocks[test_block_index];- test_block_index += 1;- generator.emit_jump_if(&cmp, case_block, next_test_block);- } else {- default_block = Some(case_block);- }- case_blocks.push(case_block);- }-- // Switch to the last test block and create end block.- generator.switch_to_basic_block(next_test_block);- let end_block = generator.make_block();- let labels = std::mem::take(&mut generator.pending_labels);-- // Jump to default case or end block.- let fallthrough_target = default_block.unwrap_or(end_block);- generator.emit(Instruction::Jump {- target: fallthrough_target,- });-- generator.begin_breakable_scope(end_block, labels, completion.clone());-- // Emit case bodies (fall-through by default).- for (i, case) in data.cases.iter().enumerate() {- generator.switch_to_basic_block(case_blocks[i]);- generator.initialized_locals.clone_from(&initialized_locals_at_entry);-- let saved_completion = generator.current_completion_register.clone();- if let Some(ref c) = completion {- generator.current_completion_register = Some(c.clone());- }-- let arena = generator.arena.clone();- let case_scope = &arena.scopes[case.scope];- for child in &case_scope.children {- // For function declarations in switch cases: emit AnnexB hoisting- // only if the scope collector approved it (name is in annexb_function_names).- if did_create_env- && let Some(fd) = child.inner.function_declaration_for_labelled_item()- && let Some(name_ident_id) = fd.name- && generator- .annexb_function_names- .contains(generator.arena.name_slice(name_ident_id))- {- let arena = generator.arena.clone();- let id = generator.intern_identifier_id(arena.identifiers[name_ident_id].name);- let value = generator.allocate_register();- emit_get_binding(generator, value.operand(), id, false);- emit_set_variable_binding(generator, id, value.operand());- }- let result = generate_statement(child, generator, None);- if generator.is_current_block_terminated() {- break;- }- if generator.must_propagate_completion- && let (Some(c), Some(val)) = (&completion, &result)- {- generator.emit_mov(c, val);- }- }-- generator.current_completion_register = saved_completion;-- // Fall through to next case- if !generator.is_current_block_terminated() && i + 1 < case_blocks.len() {- generator.emit(Instruction::Jump {- target: case_blocks[i + 1],- });- } else if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: end_block });- }- }-- generator.end_breakable_scope();- generator.switch_to_basic_block(end_block);- generator.initialized_locals = initialized_locals_at_entry;-- if did_create_env {- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();- if !generator.is_current_block_terminated() {- let parent = generator.current_lexical_environment();- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });- }- }- completion-}--/// Create block declaration instantiation for switch statements.-/// Function declarations and let/const declarations across all cases-/// share a single lexical environment.-fn emit_switch_block_declaration_instantiation(generator: &mut Generator, data: &SwitchStatementData) -> bool {- // Collect all statements across all cases.- let arena = generator.arena.clone();- let all_children: Vec<&Statement> = data- .cases- .iter()- .flat_map(|c| arena.scopes[c.scope].children.iter())- .collect();-- // Check if we need a lexical environment.- // Only needed if there are non-local lexical declarations.- let needs_env = all_children.iter().any(|child| match &child.inner {- _ if child.inner.function_declaration_for_labelled_item().is_some() => true,- StatementKind::VariableDeclaration(vd)- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>- {- vd.declarations.iter().any(|declaration| {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, &generator.arena);- !names.is_empty()- })- }- StatementKind::VariableDeclaration(_) => false,- StatementKind::ClassDeclaration(class_data) => class_data- .name- .is_some_and(|n| !generator.arena.identifiers[n].is_local()),- _ => false,- });-- if !needs_env {- return false;- }-- let capacity = count_lexical_declarations_for_block(all_children.iter().copied(), &generator.arena);- let new_env = generator.push_new_lexical_environment(capacity);-- emit_lexical_declarations_for_block(generator, &new_env, all_children.iter().copied());-- true-}--// =============================================================================-// Object expression-// =============================================================================--fn is_anonymous_function_definition(generator: &Generator, expression: &Expression) -> bool {- match &expression.inner {- ExpressionKind::Function(function_id) => generator.function_table.get(*function_id).name.is_none(),- ExpressionKind::Class(data) => data.name.is_none(),- _ => false,- }-}--fn emit_set_function_name(- generator: &mut Generator,- function: &ScopedOperand,- name: &ScopedOperand,- prefix: FunctionNamePrefix,-) {- generator.emit(Instruction::SetFunctionName {- function: function.operand(),- name: name.operand(),- prefix: prefix as u32,- });-}--/// Generate bytecode for an object literal expression.-///-/// Objects whose shape can be determined at compile time (only simple-/// key-value properties with identifier or non-numeric string keys)-/// get shape caching for faster allocation.-fn generate_object_expression(- generator: &mut Generator,- properties: &[ObjectProperty],- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- let dst = choose_dst(generator, preferred_dst);-- // Determine if this is a simple object literal (all KeyValue with non-computed- // string/identifier keys that are not numeric indices). Simple literals can- // benefit from shape caching. Numeric string keys like "0" are stored in- // indexed storage rather than shape-based storage, so they can't use the fast path.- //- // NB: The parser treats {["x"]: 1} identically to {"x": 1} at the AST level- // (both produce a StringLiteral key with is_computed=false). The parser keeps- // is_computed=true for bracket-enclosed keys. We normalize here by treating- // StringLiteral keys as non-computed regardless of is_computed.- let is_simple = !properties.is_empty()- && properties.iter().all(|p| {- if p.property_type != ObjectPropertyType::KeyValue {- return false;- }- match &p.key.inner {- ExpressionKind::Identifier(_) if !p.is_computed => true,- ExpressionKind::StringLiteral(s) => !is_numeric_index_key(s),- _ => false,- }- });-- let cache_index = if is_simple {- generator.next_object_shape_cache()- } else {- u32::MAX- };- generator.emit(Instruction::NewObject {- dst: dst.operand(),- cache: cache_index,- });-- if properties.is_empty() {- return dst;- }-- for (slot, property) in properties.iter().enumerate() {- if property.property_type == ObjectPropertyType::Spread {- // For spread, the source expression is in `key`, not `value`.- let src = generate_expression_or_undefined(&property.key, generator, None);- generator.emit(Instruction::PutBySpread {- base: dst.operand(),- src: src.operand(),- });- continue;- }-- // For non-string keys (computed, numeric, etc.), evaluate key before value- // (spec evaluation order). All non-StringLiteral keys are treated the same:- // generate key → ToPrimitiveWithStringHint → generate value → PutByValue.- //- // NB: StringLiteral keys are always treated as non-computed (see is_simple comment).- let is_string_literal_key = matches!(&property.key.inner, ExpressionKind::StringLiteral(_));- let is_string_key = is_string_literal_key || matches!(&property.key.inner, ExpressionKind::Identifier(_));- let effectively_computed = property.is_computed && !is_string_literal_key;- let computed_key = if effectively_computed || !is_string_key {- let key = generate_expression_or_undefined(&property.key, generator, None);- Some(emit_to_primitive_property_key(generator, &key))- } else {- None- };-- let is_method_like = property.is_method- || property.property_type == ObjectPropertyType::Getter- || property.property_type == ObjectPropertyType::Setter;- let function_name_prefix = match property.property_type {- ObjectPropertyType::Getter => FunctionNamePrefix::Get,- ObjectPropertyType::Setter => FunctionNamePrefix::Set,- _ => FunctionNamePrefix::None,- };- // PropertyDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydefinitionevaluation- // If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and _isProtoSetter_ is *false*, then- // Let _propValue_ be ? NamedEvaluation of |AssignmentExpression| with argument _propertyKey_.- let should_set_runtime_function_name = computed_key.is_some()- && property.property_type != ObjectPropertyType::ProtoSetter- && (is_method_like- || property- .value- .as_ref()- .is_some_and(|value| is_anonymous_function_definition(generator, value)));- // NB: A class has its name before its static elements are evaluated, so NewClass is given it.- let names_class = should_set_runtime_function_name- && property- .value- .as_ref()- .is_some_and(|value| matches!(value.inner, ExpressionKind::Class(_)));-- // Set pending LHS name for function name inference on non-computed properties.- // ProtoSetter (__proto__) skips NamedEvaluation per spec.- if !effectively_computed && property.property_type != ObjectPropertyType::ProtoSetter {- let base_name: Option<Utf16String> = match &property.key.inner {- ExpressionKind::StringLiteral(s) => Some((**s).clone()),- ExpressionKind::Identifier(ident) => Some(generator.arena.name_of(*ident).clone()),- _ => None,- };- if let Some(name) = base_name {- let full_name: Utf16String = match property.property_type {- ObjectPropertyType::Getter => {- let mut prefixed = Utf16String(utf16!("get ").to_vec());- prefixed.0.extend_from_slice(&name);- prefixed- }- ObjectPropertyType::Setter => {- let mut prefixed = Utf16String(utf16!("set ").to_vec());- prefixed.0.extend_from_slice(&name);- prefixed- }- _ => name,- };- generator.pending_lhs_name = Some(generator.intern_identifier(&full_name));- } else {- generator.pending_lhs_name = None;- }- } else {- generator.pending_lhs_name = None;- }- // Methods, getters, and setters need the object as their [[HomeObject]]- // so that super property lookups work.- if is_method_like {- generator.home_objects.push(dst.clone());- }- if names_class {- generator.pending_computed_class_name = computed_key.clone();- }- let value = property- .value- .as_ref()- .and_then(|v| generate_expression(v, generator, None))- .unwrap_or_else(|| generator.add_constant_undefined());- if is_method_like {- generator.home_objects.pop();- }- generator.pending_lhs_name = None;- if should_set_runtime_function_name && !names_class {- emit_set_function_name(- generator,- &value,- computed_key- .as_ref()- .expect("runtime function names require a runtime property key"),- function_name_prefix,- );- }-- match property.property_type {- ObjectPropertyType::Spread => {- unreachable!("spread properties are handled before this point")- }- ObjectPropertyType::KeyValue => {- if let Some(key_val) = &computed_key {- emit_put_by_value(generator, &dst, key_val, &value, PutKind::Own);- } else if is_simple {- emit_object_property_set_by_key(- generator,- &dst,- &property.key,- &value,- u32_from_usize(slot),- cache_index,- false,- );- } else {- // Non-simple object: use PutOwnById instead of InitObjectLiteralProperty- let arena = generator.arena.clone();- let property_key = match &property.key.inner {- ExpressionKind::Identifier(ident) => {- generator.intern_property_key_id(arena.identifiers[*ident].name)- }- ExpressionKind::StringLiteral(s) => generator.intern_property_key(s),- _ => {- emit_object_property_set_by_key(- generator,- &dst,- &property.key,- &value,- u32_from_usize(slot),- cache_index,- false,- );- continue;- }- };- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: dst.operand(),- property: property_key,- src: value.operand(),- cache,- base_identifier: None,- kind: PutKind::Own as u32,- });- }- }- ObjectPropertyType::Getter => {- if let Some(key_val) = &computed_key {- emit_put_by_value(generator, &dst, key_val, &value, PutKind::Getter);- } else {- emit_object_accessor_by_key(generator, &dst, &property.key, &value, true, false);- }- }- ObjectPropertyType::Setter => {- if let Some(key_val) = &computed_key {- emit_put_by_value(generator, &dst, key_val, &value, PutKind::Setter);- } else {- emit_object_accessor_by_key(generator, &dst, &property.key, &value, false, false);- }- }- ObjectPropertyType::ProtoSetter => {- let key = generator.intern_property_key(utf16!("__proto__"));- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutById {- base: dst.operand(),- property: key,- src: value.operand(),- cache,- base_identifier: None,- kind: PutKind::Prototype as u32,- });- }- }- }-- if is_simple {- generator.emit(Instruction::CacheObjectShape {- object: dst.operand(),- cache: cache_index,- });- }-- dst-}--/// Emit a property set for an object literal key (static or computed).-fn emit_object_property_set_by_key(- generator: &mut Generator,- object: &ScopedOperand,- key: &Expression,- value: &ScopedOperand,- slot: u32,- cache_index: u32,- is_computed: bool,-) {- if is_computed {- let key_val = generate_expression_or_undefined(key, generator, None);- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: object.operand(),- property: key_val.operand(),- src: value.operand(),- base_identifier: None,- kind: PutKind::Own as u32,- cache,- });- return;- }- match &key.inner {- ExpressionKind::Identifier(ident) => {- let arena = generator.arena.clone();- let property_key = generator.intern_property_key_id(arena.identifiers[*ident].name);- generator.emit(Instruction::InitObjectLiteralProperty {- object: object.operand(),- property: property_key,- src: value.operand(),- shape_cache_index: cache_index,- property_slot: slot,- });- }- ExpressionKind::StringLiteral(s) => {- let property_key = generator.intern_property_key(s);- generator.emit(Instruction::InitObjectLiteralProperty {- object: object.operand(),- property: property_key,- src: value.operand(),- shape_cache_index: cache_index,- property_slot: slot,- });- }- ExpressionKind::NumericLiteral(n) => {- let key_val = generator.add_constant_number(*n);- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: object.operand(),- property: key_val.operand(),- src: value.operand(),- base_identifier: None,- kind: PutKind::Own as u32,- cache,- });- }- _ => {- // Computed key- let key_val = generate_expression_or_undefined(key, generator, None);- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: object.operand(),- property: key_val.operand(),- src: value.operand(),- base_identifier: None,- kind: PutKind::Own as u32,- cache,- });- }- }-}--/// Emit a getter/setter for an object literal key.-fn emit_object_accessor_by_key(- generator: &mut Generator,- object: &ScopedOperand,- key: &Expression,- value: &ScopedOperand,- is_getter: bool,- is_computed: bool,-) {- let emit_by_id = |generator: &mut Generator, name: &[u16]| {- let property_key = generator.intern_property_key(name);- let cache = generator.next_property_lookup_cache();- if is_getter {- generator.emit(Instruction::PutById {- base: object.operand(),- property: property_key,- src: value.operand(),- cache,- base_identifier: None,- kind: PutKind::Getter as u32,- });- } else {- generator.emit(Instruction::PutById {- base: object.operand(),- property: property_key,- src: value.operand(),- cache,- base_identifier: None,- kind: PutKind::Setter as u32,- });- }- };-- let emit_by_value = |generator: &mut Generator, key: &Expression| {- let key_val = generate_expression_or_undefined(key, generator, None);- if is_getter {- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: object.operand(),- property: key_val.operand(),- src: value.operand(),- base_identifier: None,- kind: PutKind::Getter as u32,- cache,- });- } else {- let keyed_feedback = generator.next_keyed_feedback();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::PutByValue {- keyed_feedback,- base: object.operand(),- property: key_val.operand(),- src: value.operand(),- base_identifier: None,- kind: PutKind::Setter as u32,- cache,- });- }- };-- if is_computed {- emit_by_value(generator, key);- return;- }-- match &key.inner {- ExpressionKind::Identifier(ident) => {- let arena = generator.arena.clone();- let name = arena.name_slice(*ident);- emit_by_id(generator, name);- }- ExpressionKind::StringLiteral(s) => emit_by_id(generator, s),- _ => emit_by_value(generator, key),- }-}--// =============================================================================-// Optional chain-// =============================================================================--/// Generate an optional chain, writing results into pre-allocated current_value-/// and current_base registers.-fn generate_optional_chain_inner(- generator: &mut Generator,- base: &Expression,- references: &[OptionalChainReference],- current_value: &ScopedOperand,- current_base: &ScopedOperand,-) -> Option<()> {- // Evaluate base expression.- let new_current_value = match &base.inner {- ExpressionKind::Member(member_data) if matches!(member_data.object.inner, ExpressionKind::Super) => {- let this_value = emit_resolve_this_binding(generator);- let value = generate_member_expression(- generator,- &member_data.object,- &member_data.property,- member_data.computed,- None,- )?;- generator.emit_mov(current_base, &this_value);- value- }- ExpressionKind::Member(member_data) => {- let obj = generate_expression(&member_data.object, generator, None)?;- let val = generator.allocate_register();- if member_data.computed {- let obj = copy_if_reassignable_by(generator, obj, [&*member_data.property]);- let property = generate_expression(&member_data.property, generator, None)?;- emit_get_by_value(generator, &val, &obj, &property, None);- generator.emit_mov(current_base, &obj);- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let base_id = intern_base_identifier(generator, &member_data.object);- let arena = generator.arena.clone();- emit_get_by_id(generator, &val, &obj, arena.name_slice(*ident), base_id);- generator.emit_mov(current_base, &obj);- } else if let ExpressionKind::PrivateIdentifier(name) = &member_data.property.inner {- let id = generator.intern_identifier(&name.name);- generator.emit(Instruction::GetPrivateById {- dst: val.operand(),- base: obj.operand(),- property: id,- });- generator.emit_mov(current_base, &obj);- } else {- let property = generate_expression(&member_data.property, generator, None)?;- emit_get_by_value(generator, &val, &obj, &property, None);- generator.emit_mov(current_base, &obj);- }- val- }- ExpressionKind::OptionalChain(oc_data) => {- generate_optional_chain_inner(- generator,- &oc_data.base,- &oc_data.references,- current_value,- current_base,- )?;- current_value.clone()- }- _ => generate_expression(base, generator, None)?,- };-- generator.emit_mov(current_value, &new_current_value);-- // Create shared blocks: load_undefined_block is reused for all optional- // short-circuits.- let load_undefined_block = generator.make_block();- let end_block = generator.make_block();-- for reference in references {- let is_optional = match reference {- OptionalChainReference::Call { mode, .. }- | OptionalChainReference::ComputedReference { mode, .. }- | OptionalChainReference::MemberReference { mode, .. }- | OptionalChainReference::PrivateMemberReference { mode, .. } => *mode == OptionalChainMode::Optional,- };-- if is_optional {- let not_nullish_block = generator.make_block();- generator.emit(Instruction::JumpNullish {- condition: current_value.operand(),- true_target: load_undefined_block,- false_target: not_nullish_block,- });- generator.switch_to_basic_block(not_nullish_block);- }-- match reference {- OptionalChainReference::MemberReference { identifier, .. } => {- generator.emit_mov(current_base, current_value);- let arena = generator.arena.clone();- emit_get_by_id(- generator,- current_value,- current_value,- arena.name_slice(*identifier),- None,- );- }- OptionalChainReference::ComputedReference { expression, .. } => {- generator.emit_mov(current_base, current_value);- let property = generate_expression(expression, generator, None)?;- emit_get_by_value(generator, current_value, current_value, &property, None);- }- OptionalChainReference::Call { arguments, .. } => {- let arguments_array = generate_arguments_array(generator, arguments);- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallWithArgumentArray {- value_feedback,- call_feedback,- dst: current_value.operand(),- callee: current_value.operand(),- this_value: current_base.operand(),- arguments: arguments_array.operand(),- expression_string: None,- });- let undef = generator.add_constant_undefined();- generator.emit_mov(current_base, &undef);- }- OptionalChainReference::PrivateMemberReference { private_identifier, .. } => {- generator.emit_mov(current_base, current_value);- let id = generator.intern_identifier(&private_identifier.name);- generator.emit(Instruction::GetPrivateById {- dst: current_value.operand(),- base: current_value.operand(),- property: id,- });- }- }- }-- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(load_undefined_block);- let undef = generator.add_constant_undefined();- generator.emit_mov(current_value, &undef);- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(end_block);- Some(())-}--fn generate_optional_chain_start(- generator: &mut Generator,- base: &Expression,- current_value: &ScopedOperand,- current_base: &ScopedOperand,-) -> Option<()> {- let new_current_value = match &base.inner {- ExpressionKind::Member(member_data) if matches!(member_data.object.inner, ExpressionKind::Super) => {- let this_value = emit_resolve_this_binding(generator);- let value = generate_member_expression(- generator,- &member_data.object,- &member_data.property,- member_data.computed,- None,- )?;- generator.emit_mov(current_base, &this_value);- value- }- ExpressionKind::Member(member_data) => {- let obj = generate_expression(&member_data.object, generator, None)?;- let val = generator.allocate_register();- if member_data.computed {- let obj = copy_if_reassignable_by(generator, obj, [&*member_data.property]);- let property = generate_expression(&member_data.property, generator, None)?;- emit_get_by_value(generator, &val, &obj, &property, None);- generator.emit_mov(current_base, &obj);- } else if let ExpressionKind::Identifier(ident) = &member_data.property.inner {- let base_id = intern_base_identifier(generator, &member_data.object);- let arena = generator.arena.clone();- emit_get_by_id(generator, &val, &obj, arena.name_slice(*ident), base_id);- generator.emit_mov(current_base, &obj);- } else if let ExpressionKind::PrivateIdentifier(name) = &member_data.property.inner {- let id = generator.intern_identifier(&name.name);- generator.emit(Instruction::GetPrivateById {- dst: val.operand(),- base: obj.operand(),- property: id,- });- generator.emit_mov(current_base, &obj);- } else {- let property = generate_expression(&member_data.property, generator, None)?;- emit_get_by_value(generator, &val, &obj, &property, None);- generator.emit_mov(current_base, &obj);- }- val- }- ExpressionKind::OptionalChain(oc_data) => {- generate_optional_chain_inner(- generator,- &oc_data.base,- &oc_data.references,- current_value,- current_base,- )?;- current_value.clone()- }- _ => generate_expression(base, generator, None)?,- };-- generator.emit_mov(current_value, &new_current_value);- Some(())-}--fn is_optional_chain_reference_optional(reference: &OptionalChainReference) -> bool {- match reference {- OptionalChainReference::Call { mode, .. }- | OptionalChainReference::ComputedReference { mode, .. }- | OptionalChainReference::MemberReference { mode, .. }- | OptionalChainReference::PrivateMemberReference { mode, .. } => *mode == OptionalChainMode::Optional,- }-}--fn generate_optional_chain_reference(- generator: &mut Generator,- reference: &OptionalChainReference,- current_value: &ScopedOperand,- current_base: &ScopedOperand,-) -> Option<()> {- match reference {- OptionalChainReference::MemberReference { identifier, .. } => {- generator.emit_mov(current_base, current_value);- let arena = generator.arena.clone();- emit_get_by_id(- generator,- current_value,- current_value,- arena.name_slice(*identifier),- None,- );- }- OptionalChainReference::ComputedReference { expression, .. } => {- generator.emit_mov(current_base, current_value);- let property = generate_expression(expression, generator, None)?;- emit_get_by_value(generator, current_value, current_value, &property, None);- }- OptionalChainReference::Call { arguments, .. } => {- let arguments_array = generate_arguments_array(generator, arguments);- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::CallWithArgumentArray {- value_feedback,- call_feedback,- dst: current_value.operand(),- callee: current_value.operand(),- this_value: current_base.operand(),- arguments: arguments_array.operand(),- expression_string: None,- });- let undef = generator.add_constant_undefined();- generator.emit_mov(current_base, &undef);- }- OptionalChainReference::PrivateMemberReference { private_identifier, .. } => {- generator.emit_mov(current_base, current_value);- let id = generator.intern_identifier(&private_identifier.name);- generator.emit(Instruction::GetPrivateById {- dst: current_value.operand(),- base: current_value.operand(),- property: id,- });- }- }-- Some(())-}--fn emit_delete_optional_chain_reference(generator: &mut Generator, data: &OptionalChainData) -> ScopedOperand {- // https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation- // `delete` needs the final optional-chain property reference so it can perform [[Delete]]. If an optional hop- // short-circuits, the operand evaluates to a non-reference value and `delete` returns true.- let Some((last_reference, prefix_references)) = data.references.split_last() else {- generate_expression(&data.base, generator, None);- return generator.add_constant_boolean(true);- };-- if !matches!(- last_reference,- OptionalChainReference::MemberReference { .. } | OptionalChainReference::ComputedReference { .. }- ) {- let current_base = generator.allocate_register();- let current_value = generator.allocate_register();- let undef = generator.add_constant_undefined();- generator.emit_mov(¤t_base, &undef);- generate_optional_chain_inner(generator, &data.base, &data.references, ¤t_value, ¤t_base);- return generator.add_constant_boolean(true);- }-- let dst = generator.allocate_register();- let current_base = generator.allocate_register();- let current_value = generator.allocate_register();- let undef = generator.add_constant_undefined();- generator.emit_mov(¤t_base, &undef);-- let short_circuit_block = generator.make_block();- let end_block = generator.make_block();-- generate_optional_chain_start(generator, &data.base, ¤t_value, ¤t_base);-- for reference in prefix_references {- if is_optional_chain_reference_optional(reference) {- let not_nullish_block = generator.make_block();- generator.emit(Instruction::JumpNullish {- condition: current_value.operand(),- true_target: short_circuit_block,- false_target: not_nullish_block,- });- generator.switch_to_basic_block(not_nullish_block);- }-- generate_optional_chain_reference(generator, reference, ¤t_value, ¤t_base);- }-- if is_optional_chain_reference_optional(last_reference) {- let not_nullish_block = generator.make_block();- generator.emit(Instruction::JumpNullish {- condition: current_value.operand(),- true_target: short_circuit_block,- false_target: not_nullish_block,- });- generator.switch_to_basic_block(not_nullish_block);- }-- match last_reference {- OptionalChainReference::MemberReference { identifier, .. } => {- let arena = generator.arena.clone();- let key = generator.intern_property_key_id(arena.identifiers[*identifier].name);- generator.emit(Instruction::DeleteById {- dst: dst.operand(),- base: current_value.operand(),- property: key,- });- }- OptionalChainReference::ComputedReference { expression, .. } => {- let property = generate_expression_or_undefined(expression, generator, None);- generator.emit(Instruction::DeleteByValue {- dst: dst.operand(),- base: current_value.operand(),- property: property.operand(),- });- }- _ => unreachable!("non-property optional chain references were handled above"),- }- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(short_circuit_block);- let true_value = generator.add_constant_boolean(true);- generator.emit_mov(&dst, &true_value);- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(end_block);- dst-}--/// Convert arguments to an array for CallWithArgumentArray.-fn generate_arguments_array(generator: &mut Generator, arguments: &[CallArgument]) -> ScopedOperand {- let dst = generator.allocate_register();- if arguments.is_empty() {- generator.emit(Instruction::NewArray {- dst: dst.operand(),- element_count: 0,- elements: vec![],- });- return dst;- }-- let first_spread = arguments.iter().position(|a| a.is_spread).unwrap_or(arguments.len());-- let mut arg_holders = Vec::with_capacity(first_spread);- for argument in &arguments[..first_spread] {- let reg = generator.allocate_register();- let val = generate_expression_or_undefined(&argument.value, generator, None);- generator.emit_mov(®, &val);- arg_holders.push(reg);- }-- let arg_ops: Vec<Operand> = arg_holders.iter().map(|a| a.operand()).collect();- generator.emit(Instruction::NewArray {- dst: dst.operand(),- element_count: u32_from_usize(arg_ops.len()),- elements: arg_ops,- });- // NB: arg_holders stays alive until function return so their registers- // aren't reused during the spread arguments loop.-- for argument in &arguments[first_spread..] {- let val = generate_expression_or_undefined(&argument.value, generator, None);- generator.emit(Instruction::ArrayAppend {- dst: dst.operand(),- src: val.operand(),- is_spread: argument.is_spread,- });- }-- drop(arg_holders);- dst-}--// =============================================================================-// Class expression-// =============================================================================--/// Generate bytecode for a class expression or declaration.-///-/// Creates a ClassBlueprint via FFI containing the constructor SFD,-/// class elements (methods, fields, accessors, static initializers),-/// and then emits a NewClass instruction that creates the class at runtime.-fn generate_class_expression(- generator: &mut Generator,- data: &ClassData,- preferred_dst: Option<&ScopedOperand>,-) -> ScopedOperand {- let has_super = data.super_class.is_some();- // Always consume the pending names. Named classes don't use them, but we- // must clear them to prevent them from leaking to nested expressions.- let lhs_name = generator.pending_lhs_name.take().filter(|_| data.name.is_none());- let computed_name = generator- .pending_computed_class_name- .take()- .filter(|_| data.name.is_none());-- // Step 2: Save parent environment, create class lexical environment.- let has_class_binding = data.name.is_some() || (lhs_name.is_none() && computed_name.is_none());- let parent_env = generator.current_lexical_environment();- let class_env = generator.allocate_register();- let shape_cache = generator.next_environment_shape_cache();- // An anonymous class binds an empty name, which an environment shape cannot hold.- generator.emit(Instruction::CreateLexicalEnvironment {- dst: class_env.operand(),- parent: parent_env.operand(),- capacity: if data.name.is_some() { 1 } else { 0 },- shape_cache,- is_catch_environment: false,- });- generator.push_static_lexical_environment(class_env.clone());- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);-- // https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation- // If _classBinding_ is not *undefined*, then- // Perform ! _classEnv_.CreateImmutableBinding(_classBinding_, *true*).- // Only emit when the class has a name, or when there's no lhs_name- // (skip this for anonymous classes with lhs_name).- if has_class_binding {- let name = if let Some(name_ident_id) = data.name {- generator.arena.name_of(name_ident_id).clone()- } else {- Utf16String::new()- };- let name_id = generator.intern_identifier(&name);- generator.emit(Instruction::CreateVariable {- identifier: name_id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: true,- is_global: false,- is_strict: true,- });- }-- // Evaluate super class if present- // NB: NewClass reads the superclass after the class elements, which can reassign the local it was read from.- let super_class = if let Some(super_expression) = &data.super_class {- generate_class_part_expression(super_expression, generator, None)- .map(|super_class| generator.copy_if_needed_to_preserve_evaluation_order(&super_class))- } else {- None- };- // NB: The heritage is checked before any class element is evaluated.- let proto_parent = super_class.as_ref().map(|super_class| {- let proto_parent = generator.allocate_register();- generator.emit(Instruction::GetClassProtoParent {- dst: proto_parent.operand(),- super_class: super_class.operand(),- });- proto_parent- });-- // Create private environment for private class elements.- let mut has_private_env = false;- for element_node in &data.elements {- let priv_name = match &element_node.inner {- ClassElement::Method { key, .. } | ClassElement::Field { key, .. } => {- if let ExpressionKind::PrivateIdentifier(ident) = &key.inner {- Some(ident.name.clone())- } else {- None- }- }- ClassElement::StaticInitializer { .. } => None,- };- if let Some(name) = priv_name {- if !has_private_env {- generator.emit(Instruction::CreatePrivateEnvironment);- has_private_env = true;- }- let name_id = generator.intern_identifier(&name);- generator.emit(Instruction::AddPrivateName { name: name_id });- }- }-- // First pass: evaluate all computed property keys.- // This must happen before registering the constructor and method SFDs,- // using a two-pass structure.- let mut element_keys: Vec<Option<ScopedOperand>> = Vec::with_capacity(data.elements.len());- for element_node in &data.elements {- match &element_node.inner {- ClassElement::Method { key, .. } | ClassElement::Field { key, .. } if !is_private_key(key) => {- element_keys.push(generate_class_element_key(generator, key));- }- ClassElement::Method { .. } | ClassElement::Field { .. } | ClassElement::StaticInitializer { .. } => {- element_keys.push(None);- }- }- }-- // Create SharedFunctionInstanceData for constructor- let constructor_sfd_index = if let Some(ctor_expression) = &data.constructor {- // Explicit constructor — extract FunctionData from the expression- if let ExpressionKind::Function(function_id) = &ctor_expression.inner {- let function_data = generator.function_table.take(*function_id);- emit_new_function(generator, function_data, None)- } else {- // Fallback: synthesize a default constructor- emit_default_constructor(generator, has_super)- }- } else {- // No explicit constructor — synthesize a default one- emit_default_constructor(generator, has_super)- };-- // Second pass: register method/field SFDs and build element descriptors.- let mut class_elements = Vec::with_capacity(data.elements.len());-- for element_node in &data.elements {- match &element_node.inner {- ClassElement::Method {- key,- function,- kind,- is_static,- } => {- let ffi_kind = match kind {- ClassMethodKind::Method => ClassElementKind::Method as u8,- ClassMethodKind::Getter => ClassElementKind::Getter as u8,- ClassMethodKind::Setter => ClassElementKind::Setter as u8,- };-- // Create SFD for the method function.- // Don't set the method name here — the runtime's update_function_name- // in construct_class sets it from the evaluated property key, which- // correctly handles computed keys (Symbols, etc).- let sfd_index = if let ExpressionKind::Function(function_id) = &function.inner {- let function_data = generator.function_table.take(*function_id);- Some(emit_new_function(generator, function_data, None))- } else {- None- };-- // Handle computed vs static keys- let is_private = is_private_key(key);-- class_elements.push(PendingClassElement {- kind: ffi_kind,- is_static: *is_static,- is_private,- private_identifier: get_private_identifier_name(key),- shared_function_data_index: sfd_index,- has_initializer: false,- literal_value_kind: PendingLiteralValueKind::None,- literal_value_number: 0.0,- literal_value_string: None,- });- }- ClassElement::Field {- key,- initializer,- is_static,- } => {- // Detect literal initializers and store the value directly,- // avoiding function creation for simple cases like x = 0.- // This avoids function creation for simple cases.- let mut literal_value_kind = PendingLiteralValueKind::None;- let mut literal_value_number: f64 = 0.0;- let mut literal_value_string = None;- let mut sfd_index = None;-- if let Some(init_expression) = initializer {- let is_literal = match &init_expression.inner {- ExpressionKind::NumericLiteral(n) => {- literal_value_kind = PendingLiteralValueKind::Number;- literal_value_number = *n;- true- }- ExpressionKind::BooleanLiteral(b) => {- literal_value_kind = if *b {- PendingLiteralValueKind::BooleanTrue- } else {- PendingLiteralValueKind::BooleanFalse- };- true- }- ExpressionKind::NullLiteral => {- literal_value_kind = PendingLiteralValueKind::Null;- true- }- ExpressionKind::StringLiteral(s) => {- literal_value_kind = PendingLiteralValueKind::String;- literal_value_string = Some((**s).clone());- true- }- ExpressionKind::Unary { op, operand } if *op == UnaryOp::Minus => {- if let ExpressionKind::NumericLiteral(n) = &operand.inner {- literal_value_kind = PendingLiteralValueKind::Number;- literal_value_number = -n;- true- } else {- false- }- }- _ => false,- };-- if !is_literal {- let field_name = class_field_literal_name(key);-- // Use the ClassFieldInitializer statement directly as the- // synthetic function's body. compile_function_payload tolerates- // a non-Block body (body_scope = None for the wrapper).- let body_statement = Statement::new(- init_expression.range,- StatementKind::ClassFieldInitializer(Box::new(ClassFieldInitializerData {- expression: Box::new(init_expression.as_ref().clone()),- field_name: field_name.clone(),- })),- );-- // Class bodies are always strict mode.- let function_data = Box::new(FunctionData {- name: None,- source_text_start: init_expression.range.start.offset,- source_text_end: init_expression.range.end.offset,- body: Box::new(body_statement),- parameters: Vec::new(),- function_length: 0,- kind: FunctionKind::Normal,- is_strict_mode: true,- is_arrow_function: false,- parsing_insights: FunctionParsingInsights {- uses_this: true,- uses_this_from_environment: true,- ..Default::default()- },- // This wrapper is synthesized after parsing, so it- // asks FunctionTable to discover nested functions- // from the wrapped initializer expression.- nested_function_ids: None,- });- let index = emit_new_function(generator, function_data, Some(utf16!("field")));-- if let Some(field_name) = field_name {- generator.set_class_field_initializer_name(index, field_name, is_private_key(key));- }-- sfd_index = Some(index);- }- }-- let is_private = is_private_key(key);-- class_elements.push(PendingClassElement {- kind: ClassElementKind::Field as u8,- is_static: *is_static,- is_private,- private_identifier: get_private_identifier_name(key),- shared_function_data_index: sfd_index,- has_initializer: initializer.is_some(),- literal_value_kind,- literal_value_number,- literal_value_string,- });- }- ClassElement::StaticInitializer { body } => {- // Wrap the static block body in a function.- // Class bodies are always strict mode.- let function_data = Box::new(FunctionData {- name: None,- source_text_start: body.range.start.offset,- source_text_end: body.range.end.offset,- body: body.clone(),- parameters: Vec::new(),- function_length: 0,- kind: FunctionKind::Normal,- is_strict_mode: true,- is_arrow_function: false,- parsing_insights: FunctionParsingInsights {- uses_this: true,- uses_this_from_environment: true,- ..Default::default()- },- // Static initializer wrappers are synthesized after parsing;- // keep the structural fallback for nested functions inside- // the wrapped block.- nested_function_ids: None,- });- let sfd_index = Some(emit_new_function(generator, function_data, None));-- class_elements.push(PendingClassElement {- kind: ClassElementKind::StaticInitializer as u8,- is_static: true,- is_private: false,- private_identifier: None,- shared_function_data_index: sfd_index,- has_initializer: false,- literal_value_kind: PendingLiteralValueKind::None,- literal_value_number: 0.0,- literal_value_string: None,- });- }- }- }-- // Get class name and source text- let has_name = data.name.is_some();-- let source_start = data.source_text_start as usize;- let source_end = data.source_text_end as usize;- let source_text_len = source_end - source_start;-- let class_name = data.name.map(|n| generator.arena.name_of(n).clone());- let blueprint_index = generator.register_class_blueprint(PendingClassBlueprint {- name: class_name,- source_text_offset: source_start,- source_text_length: source_text_len,- constructor_sfd_index,- has_super_class: has_super,- has_name,- elements: class_elements,- });-- // Build element_keys operands for the NewClass instruction- let element_key_ops: Vec<Option<Operand>> = element_keys.iter().map(|k| k.as_ref().map(|s| s.operand())).collect();-- // Restore parent environment before emitting NewClass.- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent_env.operand(),- });- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();-- // Allocate dst after element keys.- let dst = choose_dst(generator, preferred_dst);-- // Emit NewClass instruction- generator.emit(Instruction::NewClass {- dst: dst.operand(),- super_class: super_class.as_ref().map(|s| s.operand()),- proto_parent: proto_parent.as_ref().map(|p| p.operand()),- class_environment: class_env.operand(),- class_blueprint_index: blueprint_index,- lhs_name,- computed_name: computed_name.as_ref().map(|name| name.operand()),- element_keys_count: u32_from_usize(element_key_ops.len()),- element_keys: element_key_ops,- });-- if has_private_env {- generator.emit(Instruction::LeavePrivateEnvironment);- }-- dst-}--// https://tc39.es/ecma262/#sec-object-initializer-runtime-semantics-evaluation-// ComputedPropertyName : [ AssignmentExpression ]-fn generate_class_element_key(generator: &mut Generator, key: &Expression) -> Option<ScopedOperand> {- // 1. Let exprValue be ? Evaluation of AssignmentExpression.- // 2. Let propertyName be ? GetValue(exprValue).- let property_name = generate_class_part_expression(key, generator, None)?;- // 3. Return ? ToPropertyKey(propertyName).- // NB: NewClass converts the primitive this leaves to a property key, which a later key cannot observe.- Some(emit_to_primitive_property_key(generator, &property_name))-}--/// The name of a class field whose key is a literal, which a computed key gets only when the class is defined.-// https://tc39.es/ecma262/#sec-static-semantics-propname-fn class_field_literal_name(key: &Expression) -> Option<Utf16String> {- match &key.inner {- ExpressionKind::StringLiteral(string) => Some((**string).clone()),- ExpressionKind::PrivateIdentifier(identifier) => Some(identifier.name.clone()),- ExpressionKind::NumericLiteral(number) => Some(crate::host::js_number_to_utf16(*number)),- ExpressionKind::BigIntLiteral(literal) => {- let digits = String::from_utf16_lossy(bigint_literal_digits(literal));- let value = parse_bigint(&digits).expect("the lexer only produces valid BigInt literals");- Some(Utf16String(value.to_string().encode_utf16().collect()))- }- _ => None,- }-}--/// Synthesize a default constructor SharedFunctionInstanceData.-fn emit_default_constructor(generator: &mut Generator, has_super: bool) -> u32 {- use crate::parser::Parser;- use crate::parser::ProgramType;-- // Wrap in "function" keyword so it parses as a FunctionDeclaration.- let source: Utf16String = if has_super {- Utf16String::from(utf16!("function constructor(...arguments) { super(...arguments); }"))- } else {- Utf16String::from(utf16!("function constructor() {}"))- };-- let mut parser = Parser::new(&source, ProgramType::Script);- if has_super {- parser.flags.allow_super_constructor_call = true;- }- let program = parser.parse_program(false);- parser.scope_collector.analyze(- false,- &mut parser.arena.identifiers,- &parser.arena.strings,- &mut parser.arena.scopes,- );-- assert!(!parser.has_errors(), "default constructor parse failed");-- // Extract FunctionData from the parsed program.- let function_id = if let StatementKind::Program(ref data) = program.inner {- let scope = &parser.arena.scopes[data.scope];- scope.children.iter().find_map(|child| {- if let StatementKind::FunctionDeclaration(fd) = &child.inner {- Some(fd.function_id)- } else {- None- }- })- } else {- None- };-- let function_id = function_id.expect("default constructor: no FunctionDeclaration found");- let mut function_data = parser.function_table.take(function_id);-- // Zero out source text range since this is synthetic source,- // not part of the original source code buffer.- function_data.source_text_start = 0;- function_data.source_text_end = 0;-- let subtable = parser- .function_table- .extract_reachable(&function_data, &parser.arena.scopes);- let arena = std::sync::Arc::new(std::mem::take(&mut parser.arena));- generator.register_shared_function_data(PendingSharedFunctionData {- function_data: Some(function_data),- subtable: Some(subtable),- arena: Some(arena),- name_override: None,- class_field_initializer_name: None,- should_eager_compile: false,- precompiled_function: None,- enclosing_environment_scope: None,- })-}--/// Check if a key expression is a private identifier, return (is_private, private_name).-fn is_private_key(key: &Expression) -> bool {- matches!(&key.inner, ExpressionKind::PrivateIdentifier(_))-}--/// Get a pointer directly into the AST's PrivateIdentifier name.-/// The pointer remains valid as long as the AST is alive.-fn get_private_identifier_name(key: &Expression) -> Option<Utf16String> {- if let ExpressionKind::PrivateIdentifier(ident) = &key.inner {- Some(ident.name.clone())- } else {- None- }-}--/// Check if a for-in/for-of LHS is a `let`/`const` declaration with non-local identifiers,-/// meaning we need a per-iteration lexical environment.-fn for_in_of_needs_lexical_env(lhs: &ForInOfLhs, arena: &crate::ast::AstArena) -> bool {- if let ForInOfLhs::Declaration(statement) = lhs- && let Some((declarations, _)) = lexical_declarators(statement)- {- let mut names = Vec::new();- for declaration in declarations {- collect_target_names(&declaration.target, &mut names, arena);- }- return !names.is_empty();- }- false-}--/// Collect all non-local binding names from a variable declarator target.-fn collect_target_names(- target: &VariableDeclaratorTarget,- names: &mut Vec<(Utf16String, bool)>,- arena: &crate::ast::AstArena,-) {- match target {- VariableDeclaratorTarget::Identifier(id) => {- let ident = &arena.identifiers[*id];- if !ident.is_local() {- names.push((arena.strings[ident.name].clone(), false));- }- }- VariableDeclaratorTarget::BindingPattern(pattern) => {- collect_pattern_binding_names(pattern, names, arena);- }- }-}--/// Collect all non-local binding names from a binding pattern (recursive).-fn collect_pattern_binding_names(- pattern: &BindingPattern,- names: &mut Vec<(Utf16String, bool)>,- arena: &crate::ast::AstArena,-) {- for entry in &pattern.entries {- match &entry.alias {- Some(BindingEntryAlias::Identifier(id)) => {- let ident = &arena.identifiers[*id];- if !ident.is_local() {- names.push((arena.strings[ident.name].clone(), false));- }- }- Some(BindingEntryAlias::BindingPattern(sub)) => {- collect_pattern_binding_names(sub, names, arena);- }- None => {- if let Some(BindingEntryName::Identifier(id)) = &entry.name {- let ident = &arena.identifiers[*id];- if !ident.is_local() {- names.push((arena.strings[ident.name].clone(), false));- }- }- }- Some(BindingEntryAlias::MemberExpression(_)) => {}- }- }-}--/// Create a per-iteration lexical environment for for-in/for-of `let`/`const` declarations.-/// Returns the parent environment register so we can restore it later.-fn create_for_in_of_lexical_env(generator: &mut Generator, lhs: &ForInOfLhs) -> ScopedOperand {- let parent = generator.current_lexical_environment();-- // Collect all binding names to determine capacity.- let mut binding_names: Vec<(Utf16String, bool)> = Vec::new();- let mut is_constant = false;- if let ForInOfLhs::Declaration(statement) = lhs- && let Some((declarations, is_constant_declaration)) = lexical_declarators(statement)- {- is_constant = is_constant_declaration;- for declaration in declarations {- collect_target_names(&declaration.target, &mut binding_names, &generator.arena);- }- }-- generator.push_new_lexical_environment(u32_from_usize(binding_names.len()));-- // Create variable bindings in the new environment.- for (name, _) in &binding_names {- let id = generator.intern_identifier(name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: is_constant,- is_global: false,- is_strict: is_constant,- });- }-- parent-}--// =============================================================================-// For-in statement-// =============================================================================--/// Create a TDZ environment for lexical declarations in for-in/for-of heads.-/// Returns true if a TDZ scope was entered (must call leave_for_in_of_head_tdz after RHS eval).-fn enter_for_in_of_head_tdz(generator: &mut Generator, lhs: &ForInOfLhs) -> bool {- if let ForInOfLhs::Declaration(statement) = lhs- && let Some((declarations, _)) = lexical_declarators(statement)- {- let mut names = Vec::new();- for declaration in declarations {- collect_target_names(&declaration.target, &mut names, &generator.arena);- }- if !names.is_empty() {- generator.push_new_lexical_environment(u32_from_usize(names.len()));- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- for (name, _) in &names {- let id = generator.intern_identifier(name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- }- return true;- }- }- false-}--/// Tear down the TDZ environment after RHS evaluation.-fn leave_for_in_of_head_tdz(generator: &mut Generator) {- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();- if !generator.is_current_block_terminated() {- let parent = generator.current_lexical_environment();- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });- }-}--fn generate_for_in_of_statement(- generator: &mut Generator,- kind: ForInOfKind,- lhs: &ForInOfLhs,- rhs: &Expression,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- match kind {- ForInOfKind::ForIn => generate_for_in_statement(generator, lhs, rhs, body, preferred_dst),- ForInOfKind::ForOf => generate_for_of_statement_inner(generator, lhs, rhs, body, preferred_dst, false),- ForInOfKind::ForAwaitOf => generate_for_of_statement_inner(generator, lhs, rhs, body, preferred_dst, true),- }-}--fn generate_for_in_statement(- generator: &mut Generator,- lhs: &ForInOfLhs,- rhs: &Expression,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads- // ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement- if let ForInOfLhs::Declaration(statement) = lhs- && let StatementKind::VariableDeclaration(vd) = &statement.inner- && vd.kind == DeclarationKind::Var- && let Some(declaration) = vd.declarations.first()- && let (VariableDeclaratorTarget::Identifier(ident_id), Some(init)) = (&declaration.target, &declaration.init)- {- // 1. Let name be the StringValue of BindingIdentifier.- // 2. Let lhs be ? ResolveBinding(name).- let resolved_binding = emit_resolve_binding_for_identifier_assignment(generator, *ident_id);- // 3. If IsAnonymousFunctionDefinition(Initializer) is true, then- // a. Let value be ? NamedEvaluation of Initializer with argument name.- // 4. Else,- // a. Let rhs be ? Evaluation of Initializer.- // b. Let value be ? GetValue(rhs).- let arena = generator.arena.clone();- generator.pending_lhs_name = Some(generator.intern_identifier_id(arena.identifiers[*ident_id].name));- let value = generate_expression_or_undefined(init, generator, None);- generator.pending_lhs_name = None;- // 5. Perform ? PutValue(lhs, value).- emit_set_variable_or_resolved_binding(generator, *ident_id, &value, resolved_binding.as_ref());- }-- // Create end_block and update_block first, then nullish_block and- // continuation_block during head evaluation.- let end_block = generator.make_block();- let update_block = generator.make_block();- let needs_lexical_env = for_in_of_needs_lexical_env(lhs, &generator.arena);-- // B.3.5 Initializers in ForIn Statement Heads: evaluate initializer before RHS.- // Create TDZ for lexical declarations before evaluating the RHS expression.- let entered_tdz = enter_for_in_of_head_tdz(generator, lhs);-- // Evaluate RHS into `receiver`. The receiver, its flattened key snapshot, and the cursor all- // outlive the loop body: the next op revalidates against the live receiver and advances the- // cursor in place. Keeping this state in registers instead of a heap iterator object means- // nothing enumeration-internal can be observed as a script value.- let source = generate_expression_or_undefined(rhs, generator, None);- if entered_tdz {- leave_for_in_of_head_tdz(generator);- }-- let receiver = generator.allocate_register();- let keys = generator.allocate_register();- let cursor = generator.allocate_register();-- // NB: The completion register starts out as undefined, which is also the completion value of a- // loop whose iteration is skipped below, so it has to be initialized before the null check.- let completion = generator.allocate_completion_register();-- // https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation- // 6. If iterationKind is enumerate, then- // a. If exprValue is either undefined or null, then- // i. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.- // NB: LabelledEvaluation turns this break completion into NormalCompletion(undefined).- let nullish_block = generator.make_block();- let continue_block = generator.make_block();- generator.emit(Instruction::JumpNullish {- condition: source.operand(),- true_target: nullish_block,- false_target: continue_block,- });-- generator.switch_to_basic_block(nullish_block);- generator.emit(Instruction::Jump { target: end_block });-- generator.switch_to_basic_block(continue_block);-- // Snapshot the enumerable keys and start the cursor at the first one. GetObjectPropertyIterator- // also writes back the ToObject'd receiver, which is what the next op enumerates against.- let cache = generator.next_object_property_iterator_cache();- generator.emit(Instruction::GetObjectPropertyIterator {- dst_keys: keys.operand(),- dst_receiver: receiver.operand(),- object: source.operand(),- cache,- });- let zero = generator.add_constant_i32(0);- generator.emit_mov(&cursor, &zero);-- generator.emit(Instruction::Jump { target: update_block });-- // Update: get next value- generator.switch_to_basic_block(update_block);- let next_value = generator.allocate_register();- let done = generator.allocate_register();- generator.emit(Instruction::ObjectPropertyIteratorNext {- dst_value: next_value.operand(),- dst_done: done.operand(),- receiver: receiver.operand(),- keys: keys.operand(),- cursor: cursor.operand(),- });-- let loop_continue_block = generator.make_block();- generator.emit_jump_if(&done, end_block, loop_continue_block);- generator.switch_to_basic_block(loop_continue_block);-- // Create per-iteration lexical environment for let/const declarations.- if needs_lexical_env {- create_for_in_of_lexical_env(generator, lhs);- }-- // Body — break/continue handle environment restoration via LeaveLexicalEnvironment boundary.- let labels = std::mem::take(&mut generator.pending_labels);- generator.begin_continuable_scope(update_block, labels.clone(), completion.clone());- generator.begin_breakable_scope(end_block, labels, completion.clone());- if needs_lexical_env {- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- }-- // Assign to LHS- assign_to_for_in_of_lhs(generator, lhs, &next_value);-- if !generator.is_current_block_terminated() {- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);- }-- if needs_lexical_env {- generator.end_variable_scope();- }-- generator.end_breakable_scope();- generator.end_continuable_scope();-- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: update_block });- }-- generator.switch_to_basic_block(end_block);- completion-}--// =============================================================================-// Labelled statement-// =============================================================================--fn generate_labelled_statement(- generator: &mut Generator,- label: &Utf16String,- item: &Statement,- preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- // Collect all labels from nested Labelled statements.- let mut labels = vec![label.clone()];- let mut inner = item;- while let StatementKind::Labelled(labelled_data) = &inner.inner {- labels.push(labelled_data.label.clone());- inner = &labelled_data.item;- }-- // For iteration/switch statements, set pending_labels so that- // begin_breakable_scope/begin_continuable_scope pick them up.- // NB: The parser wraps for/for-in/for-of loops in a Block for scope- // management, so we look through single-child Block wrappers.- let block_arena;- let effective_inner = if let StatementKind::Block(scope) = inner.inner {- block_arena = generator.arena.clone();- let children = &block_arena.scopes[scope].children;- if children.len() == 1 { &children[0] } else { inner }- } else {- inner- };- let is_iteration_or_switch = matches!(- &effective_inner.inner,- StatementKind::For(_)- | StatementKind::ForInOf(_)- | StatementKind::While(_)- | StatementKind::DoWhile(_)- | StatementKind::Switch(_)- );-- if is_iteration_or_switch {- let previous_labels = std::mem::replace(&mut generator.pending_labels, labels);- let result = generate_statement(inner, generator, preferred_dst);- generator.pending_labels = previous_labels;- result- } else {- // Non-iteration: wrap in a breakable scope so `break label;` works. When completion- // propagation is on, the breakable scope shares the running completion register of the- // enclosing statement list, so a body that completes empty, or `break label;` with an empty- // value, leaves the running value in place.- let end_block = generator.make_block();- let completion = generator- .current_completion_register- .clone()- .or_else(|| generator.allocate_completion_register());- generator.begin_breakable_scope(end_block, labels, completion.clone());- let result = generate_with_completion(inner, generator, completion.as_ref(), preferred_dst);- generator.end_breakable_scope();- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump { target: end_block });- }- generator.switch_to_basic_block(end_block);- if completion.is_some() { completion } else { result }- }-}--// =============================================================================-// For-of statement-// =============================================================================--/// Shared implementation for for-of and for-await-of with iterator close.-fn generate_for_of_statement_inner(- generator: &mut Generator,- lhs: &ForInOfLhs,- rhs: &Expression,- body: &Statement,- preferred_dst: Option<&ScopedOperand>,- is_await: bool,-) -> Option<ScopedOperand> {- // Create end_block and update_block before evaluating the RHS expression.- // This ensures loop blocks get lower block numbers than any blocks created- // during RHS evaluation (e.g. conditional expressions).- let end_block = generator.make_block();- let update_block = generator.make_block();-- // Create TDZ for lexical declarations before evaluating the RHS expression.- let entered_tdz = enter_for_in_of_head_tdz(generator, lhs);- let needs_lexical_env = for_in_of_needs_lexical_env(lhs, &generator.arena);- let old_handler = generator.current_unwind_handler;-- // Evaluate RHS into `object`, allocate iterator registers, and emit- // GetIterator. The block scopes `object` so its register is freed- // before the loop body.- let (iterator_object, iterator_next_method, iterator_done) = {- let object = generate_expression_or_undefined(rhs, generator, None);- if entered_tdz {- leave_for_in_of_head_tdz(generator);- }-- let iterator_object = generator.allocate_register();- let iterator_next_method = generator.allocate_register();- let iterator_done = generator.allocate_register();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetIterator {- dst_iterator_object: iterator_object.operand(),- dst_iterator_next: iterator_next_method.operand(),- dst_iterator_done: iterator_done.operand(),- iterable: object.operand(),- hint: if is_await {- IteratorHint::Async- } else {- IteratorHint::Sync- } as u32,- fast_array_mode_allowed: !is_await,- cache,- });-- (iterator_object, iterator_next_method, iterator_done)- };-- let completion = generator.allocate_completion_register();-- // Set up iterator close via synthetic FinallyContext.- let close_completion_type = generator.allocate_register();- let close_completion_value = generator.allocate_register();- let exception_preamble_block = generator.make_block();- let iterator_close_body_block = generator.make_block();- let lexical_env_at_entry = generator.lexical_environment_register_stack.last().cloned();-- let parent_index = generator.current_finally_context;- generator.push_finally_context(FinallyContext {- completion_type: close_completion_type.clone(),- completion_value: close_completion_value.clone(),- finally_body: iterator_close_body_block,- exception_preamble: exception_preamble_block,- parent_index,- registered_jumps: Vec::new(),- next_jump_index: FinallyContext::FIRST_JUMP_INDEX,- lexical_environment_at_entry: lexical_env_at_entry.clone(),- saved_unwind_handler: None,- });-- // Break scope wraps the ReturnToFinally so break hits ReturnToFinally first.- let labels = std::mem::take(&mut generator.pending_labels);- generator.begin_breakable_scope(end_block, labels.clone(), completion.clone());- generator.start_boundary(BlockBoundaryType::ReturnToFinally);-- generator.emit(Instruction::Jump { target: update_block });-- // Update: get next value- generator.switch_to_basic_block(update_block);- let next_value = generator.allocate_register();- let done = generator.allocate_register();-- if is_await {- // For-await-of: Call iterator.next(), await the result, then unpack.- let next_result = generator.allocate_register();- generator.emit(Instruction::IteratorNext {- dst: next_result.operand(),- iterator_object: iterator_object.operand(),- iterator_next: iterator_next_method.operand(),- iterator_done: iterator_done.operand(),- });- // Await the next result. Pre-allocate completion registers and emit- // Mov(received_completion, accumulator) before Await.- let received_completion = generator.allocate_register();- let received_completion_type = generator.allocate_register();- let received_completion_value = generator.allocate_register();- let acc = generator.accumulator();- generator.emit_mov(&received_completion, &acc);- let awaited = generate_await_with_completions(- generator,- &next_result,- &received_completion,- &received_completion_type,- &received_completion_value,- );- generator.emit_mov(&next_result, &awaited);- // Type check- generator.emit(Instruction::ThrowIfNotObject {- src: next_result.operand(),- });- // IteratorComplete — get .done property- emit_get_by_id(generator, &done, &next_result, utf16!("done"), None);-- let loop_continue_block = generator.make_block();- generator.emit_jump_if(&done, end_block, loop_continue_block);- generator.switch_to_basic_block(loop_continue_block);-- // IteratorValue — get .value property- emit_get_by_id(generator, &next_value, &next_result, utf16!("value"), None);- } else {- generator.emit(Instruction::IteratorNextUnpack {- dst_value: next_value.operand(),- dst_done: done.operand(),- iterator_object: iterator_object.operand(),- iterator_next: iterator_next_method.operand(),- iterator_done: iterator_done.operand(),- });-- let loop_continue_block = generator.make_block();- generator.emit_jump_if(&done, end_block, loop_continue_block);- generator.switch_to_basic_block(loop_continue_block);- }-- // Set up exception handler AFTER iterator-next section.- // Per spec, exceptions from IteratorNext/Await/IteratorComplete/IteratorValue- // propagate directly; only LHS assignment and body exceptions trigger close.- generator.current_unwind_handler = Some(exception_preamble_block);- let loop_body_block = generator.make_block();- generator.emit(Instruction::Jump {- target: loop_body_block,- });- generator.switch_to_basic_block(loop_body_block);-- // Create per-iteration lexical environment for let/const declarations.- let parent_env = if needs_lexical_env {- Some(create_for_in_of_lexical_env(generator, lhs))- } else {- None- };-- let disposal_kind = match lhs {- ForInOfLhs::Declaration(statement) => disposal_kind_of_statements(core::iter::once(statement.as_ref())),- _ => None,- };-- generator.begin_continuable_scope(update_block, labels, completion.clone());- if needs_lexical_env {- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- }-- if let Some(disposal_kind) = disposal_kind {- // NB: The resource of a `using` or `await using` declaration is disposed of at the end of each iteration,- // including when the declaration is abrupt, and before the iterator is closed.- generate_with_disposable_resource_stack(generator, disposal_kind, |generator| {- assign_to_for_in_of_lhs(generator, lhs, &next_value);- if !generator.is_current_block_terminated() {- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);- }- None- });- } else {- // Assign to LHS- assign_to_for_in_of_lhs(generator, lhs, &next_value);-- // Body- if !generator.is_current_block_terminated() {- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);- }- }-- // Restore lexical env before continuing- if needs_lexical_env {- generator.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- generator.pop_tracked_lexical_environment();- }- generator.end_continuable_scope();-- generator.end_boundary(BlockBoundaryType::ReturnToFinally);- generator.end_breakable_scope();-- // Pop the FinallyContext.- let finally_ctx_index = generator.current_finally_context.expect("no active finally context");- generator.current_finally_context = generator.finally_contexts[finally_ctx_index].parent_index;-- // Restore unwind handler- generator.current_unwind_handler = old_handler;-- if !generator.is_current_block_terminated() {- if needs_lexical_env {- let parent = parent_env- .as_ref()- .expect("parent_env must be set when restoring lexical environment");- generator.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });- }- generator.emit(Instruction::Jump { target: update_block });- }-- // --- Exception preamble: catch thrown exception, route to iterator close ---- generator.switch_to_basic_block(exception_preamble_block);- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::Catch {- value_feedback,- dst: close_completion_value.operand(),- });- if let Some(env) = &lexical_env_at_entry {- generator.emit(Instruction::SetLexicalEnvironment {- environment: env.operand(),- });- }- let throw_const = generator.add_constant_i32(FinallyContext::THROW);- generator.emit_mov(&close_completion_type, &throw_const);- generator.emit(Instruction::Jump {- target: iterator_close_body_block,- });-- // --- Iterator close body: dispatch based on completion type ---- generator.switch_to_basic_block(iterator_close_body_block);-- // THROW path- let throw_close_block = generator.make_block();- let non_throw_close_block = generator.make_block();- let throw_check_const = generator.add_constant_i32(FinallyContext::THROW);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: close_completion_type.operand(),- rhs: throw_check_const.operand(),- true_target: throw_close_block,- false_target: non_throw_close_block,- });-- // Non-throw close: close the iterator with Normal completion, then dispatch.- generator.switch_to_basic_block(non_throw_close_block);-- if is_await {- // For async iterators, inline AsyncIteratorClose using GetMethod+Call+Await- // instead of the synchronous IteratorClose instruction. This avoids spinning- // the event loop inside bytecode execution.- let after_close = generator.make_block();- let return_method = generator.allocate_register();- let return_key = generator.intern_property_key(utf16!("return"));- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetMethod {- dst: return_method.operand(),- object: iterator_object.operand(),- property: return_key,- cache,- });- let call_return_block = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: return_method.operand(),- true_target: after_close,- false_target: call_return_block,- });- generator.switch_to_basic_block(call_return_block);-- let inner_result = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: inner_result.operand(),- callee: return_method.operand(),- this_value: iterator_object.operand(),- expression_string: None,- argument_count: 0,- arguments: vec![],- });-- // Pre-allocate completion registers in this scope so they're freed- // together with return_method and inner_result.- let rc = generator.allocate_register();- let rct = generator.allocate_register();- let rcv = generator.allocate_register();- let awaited = generate_await_with_completions(generator, &inner_result, &rc, &rct, &rcv);- generator.emit(Instruction::ThrowIfNotObject { src: awaited.operand() });- generator.emit(Instruction::Jump { target: after_close });- generator.switch_to_basic_block(after_close);- } else {- let undef = generator.add_constant_undefined();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::IteratorClose {- iterator_object: iterator_object.operand(),- iterator_next: iterator_next_method.operand(),- iterator_done: iterator_done.operand(),- completion_type: CompletionType::Normal as u32,- completion_value: undef.operand(),- cache,- });- }-- // Dispatch registered jumps (break/continue targets).- let registered_jumps = std::mem::take(&mut generator.finally_contexts[finally_ctx_index].registered_jumps);- for jump in ®istered_jumps {- let after_check = generator.make_block();- let jump_const = generator.add_constant_i32(jump.index);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: close_completion_type.operand(),- rhs: jump_const.operand(),- true_target: jump.target,- false_target: after_check,- });- generator.switch_to_basic_block(after_check);- }-- // RETURN path- let return_block = generator.make_block();- let unreachable_block = generator.make_block();- let return_const = generator.add_constant_i32(FinallyContext::RETURN);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: close_completion_type.operand(),- rhs: return_const.operand(),- true_target: return_block,- false_target: unreachable_block,- });-- generator.switch_to_basic_block(return_block);- if let Some(outer_index) = generator.current_finally_context {- generator.forward_completion_to_outer_finally(outer_index, &close_completion_type, &close_completion_value);- } else if generator.is_in_generator_function() {- generator.emit(Instruction::Yield {- continuation_label: None,- value: close_completion_value.operand(),- });- } else {- generator.emit(Instruction::Return {- value: close_completion_value.operand(),- });- }-- // Unreachable default: throw the value.- generator.switch_to_basic_block(unreachable_block);- generator.emit(Instruction::Throw {- src: close_completion_value.operand(),- });-- // Throw close: close iterator then rethrow original exception.- generator.switch_to_basic_block(throw_close_block);-- if is_await {- // Inline AsyncIteratorClose with exception handler: any error from the close- // steps is discarded and the original exception is rethrown.- let rethrow_block = generator.make_block();- let close_catch_block = generator.make_block();-- // Set up an exception handler that catches errors from the close and rethrows original.- let old_close_handler = generator.current_unwind_handler;- generator.current_unwind_handler = Some(close_catch_block);-- // Jump to a block created inside the unwind context so that- // GetMethod/Call/Await all have the exception handler set.- let close_try_block = generator.make_block();- generator.emit(Instruction::Jump {- target: close_try_block,- });- generator.switch_to_basic_block(close_try_block);-- {- let return_method = generator.allocate_register();- let return_key = generator.intern_property_key(utf16!("return"));- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetMethod {- dst: return_method.operand(),- object: iterator_object.operand(),- property: return_key,- cache,- });-- let call_return_block = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: return_method.operand(),- true_target: rethrow_block,- false_target: call_return_block,- });- generator.switch_to_basic_block(call_return_block);-- let inner_result = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- let call_feedback = generator.next_call_feedback();- generator.emit(Instruction::Call {- value_feedback,- call_feedback,- dst: inner_result.operand(),- callee: return_method.operand(),- this_value: iterator_object.operand(),- expression_string: None,- argument_count: 0,- arguments: vec![],- });-- let rc = generator.allocate_register();- let rct = generator.allocate_register();- let rcv = generator.allocate_register();- generate_await_with_completions(generator, &inner_result, &rc, &rct, &rcv);-- // Even if close succeeded, rethrow original (spec step 5).- generator.emit(Instruction::Jump { target: rethrow_block });- }-- // Exception handler: discard close error, rethrow original.- generator.current_unwind_handler = old_close_handler;- generator.switch_to_basic_block(close_catch_block);- let discarded = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::Catch {- value_feedback,- dst: discarded.operand(),- });- generator.emit(Instruction::Jump { target: rethrow_block });-- generator.switch_to_basic_block(rethrow_block);- generator.emit(Instruction::Throw {- src: close_completion_value.operand(),- });- } else {- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::IteratorClose {- iterator_object: iterator_object.operand(),- iterator_next: iterator_next_method.operand(),- iterator_done: iterator_done.operand(),- completion_type: CompletionType::Throw as u32,- completion_value: close_completion_value.operand(),- cache,- });- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Throw {- src: close_completion_value.operand(),- });- }- }-- // Release the FinallyContext's ScopedOperands so their registers- // can be reused.- let dummy = generator.add_constant_undefined();- generator.finally_contexts[finally_ctx_index].completion_type = dummy.clone();- generator.finally_contexts[finally_ctx_index].completion_value = dummy;- generator.finally_contexts[finally_ctx_index].lexical_environment_at_entry = None;-- generator.switch_to_basic_block(end_block);- completion-}--fn assign_to_for_in_of_lhs(generator: &mut Generator, lhs: &ForInOfLhs, value: &ScopedOperand) {- match lhs {- ForInOfLhs::Declaration(statement) => {- // NB: For a `using` or `await using` declaration, these are steps 8.h.vii.4 and 8.h.vii.6 of- // ForIn/OfBodyEvaluation.- if let StatementKind::UsingDeclaration(data) = &statement.inner {- // 4. If declKind is not normal, then- // a. Assert: IsUnresolvableReference(lhsRef) is false.- // b. Let base be lhsRef.[[Base]].- // c. Assert: base is a Declarative Environment Record.- // d. Let status be Completion(AddDisposableResource(base.[[DisposableResourceStack]], nextValue, declKind)).- // 6. If status is a normal completion, then- // a. Set status to Completion(InitializeReferencedBinding(lhsRef, nextValue)).- let VariableDeclaratorTarget::Identifier(id) = &data.declarations[0].target else {- unreachable!("using declarations only bind identifiers");- };- let kind = if data.is_await {- DisposableResourceKind::AsyncDispose- } else {- DisposableResourceKind::SyncDispose- };- emit_add_disposable_resource_and_initialize_binding(generator, *id, value, kind);- return;- }- // The declaration is a VariableDeclaration with a single declarator- if let StatementKind::VariableDeclaration(vd) = &statement.inner- && let Some(declaration) = vd.declarations.first()- {- // For var: FDI already initialized the binding, so use Set.- // For let/const: per-iteration env created new bindings needing Initialize.- let mode = match vd.kind {- DeclarationKind::Var => BindingMode::Set,- DeclarationKind::Let | DeclarationKind::Const => BindingMode::InitializeLexical,- };- match &declaration.target {- VariableDeclaratorTarget::Identifier(ident) => {- emit_set_variable_with_mode(generator, *ident, value, mode);- }- VariableDeclaratorTarget::BindingPattern(pattern) => {- generate_binding_pattern_bytecode(generator, pattern, mode, value);- }- }- }- }- ForInOfLhs::Expression(expression) => {- emit_store_to_reference(generator, expression, value);- }- ForInOfLhs::Pattern(pattern) => {- generate_binding_pattern_bytecode(generator, pattern, BindingMode::Set, value);- }- }-}--// =============================================================================-// Binding pattern destructuring-// =============================================================================--/// Whether we are initializing a new binding or setting an existing one.-// https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization-// https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation-// Binding patterns initialize lexical declarations, while assignment patterns perform PutValue.-#[derive(Clone, Copy)]-enum BindingMode {- /// `const` or `let` declarations: emit InitializeLexicalBinding.- InitializeLexical,- /// Assignment expressions / var iteration: emit SetLexicalBinding or SetGlobal.- Set,-}--fn set_pending_lhs_name_for_entry(generator: &mut Generator, entry: &BindingEntry) {- let arena = generator.arena.clone();- let name = match &entry.alias {- Some(BindingEntryAlias::Identifier(id)) => Some(arena.identifiers[*id].name),- None => {- if let Some(BindingEntryName::Identifier(id)) = &entry.name {- Some(arena.identifiers[*id].name)- } else {- None- }- }- _ => None,- };- if let Some(name) = name {- generator.pending_lhs_name = Some(generator.intern_identifier_id(name));- }-}--fn generate_binding_pattern_bytecode(- generator: &mut Generator,- pattern: &BindingPattern,- mode: BindingMode,- input_value: &ScopedOperand,-) {- match pattern.kind {- BindingPatternKind::Array => {- generate_array_binding_pattern(generator, pattern, mode, input_value);- }- BindingPatternKind::Object => {- generate_object_binding_pattern(generator, pattern, mode, input_value);- }- }-}--fn emit_set_variable_with_mode(- generator: &mut Generator,- id: crate::ast::IdentifierId,- value: &ScopedOperand,- mode: BindingMode,-) {- let arena = generator.arena.clone();- let ident = &arena.identifiers[id];- if ident.is_local() {- match mode {- BindingMode::InitializeLexical => {- let local = generator.resolve_local(ident.local_index, ident.local_type.unwrap());- generator.emit_mov(&local, value);- generator.mark_local_initialized(ident.local_index);- }- BindingMode::Set => {- emit_tdz_check_if_needed(generator, id);- emit_set_variable(generator, id, value);- }- }- } else {- let id = generator.intern_identifier_id(ident.name);- match mode {- BindingMode::InitializeLexical => {- emit_initialize_lexical_binding(generator, id, value.operand());- }- BindingMode::Set => {- if ident.is_global {- let cache = generator.next_global_variable_cache();- generator.emit(Instruction::SetGlobal {- identifier: id,- src: value.operand(),- cache,- });- } else {- emit_set_lexical_binding(generator, id, value.operand());- }- }- }- }-}--fn emit_evaluate_binding_reference(- generator: &mut Generator,- entry: &BindingEntry,- mode: BindingMode,-) -> Option<EvaluatedReference> {- if let Some(BindingEntryAlias::MemberExpression(expression)) = &entry.alias {- return Some(emit_evaluate_member_reference(generator, expression));- }- if !matches!(mode, BindingMode::Set) {- return None;- }- let identifier = match (&entry.alias, &entry.name) {- (Some(BindingEntryAlias::Identifier(identifier)), _)- | (None, Some(BindingEntryName::Identifier(identifier))) => *identifier,- _ => return None,- };- emit_resolve_binding_for_identifier_assignment(generator, identifier).map(EvaluatedReference::Binding)-}--fn assign_binding_entry_alias(- generator: &mut Generator,- entry: &BindingEntry,- value: &ScopedOperand,- mode: BindingMode,-) {- match &entry.alias {- None => {- // Name IS the binding target (e.g., `{ x }` or array element).- if let Some(BindingEntryName::Identifier(ident)) = &entry.name {- emit_set_variable_with_mode(generator, *ident, value, mode);- }- }- Some(BindingEntryAlias::Identifier(ident)) => {- emit_set_variable_with_mode(generator, *ident, value, mode);- }- Some(BindingEntryAlias::BindingPattern(sub_pattern)) => {- generate_binding_pattern_bytecode(generator, sub_pattern, mode, value);- }- Some(BindingEntryAlias::MemberExpression(expression)) => {- emit_store_to_reference(generator, expression, value);- }- }-}--fn make_block_with_unwind_handler(generator: &mut Generator, unwind_handler: Option<Label>) -> Label {- let saved_unwind_handler = generator.current_unwind_handler;- generator.current_unwind_handler = unwind_handler;- let block = generator.make_block();- generator.current_unwind_handler = saved_unwind_handler;- block-}--fn generate_array_binding_pattern(- generator: &mut Generator,- pattern: &BindingPattern,- mode: BindingMode,- input_array: &ScopedOperand,-) {- let is_exhausted = generator.allocate_register();- let false_val = generator.add_constant_boolean(false);- generator.emit_mov(&is_exhausted, &false_val);-- let iterator_object = generator.allocate_register();- let iterator_next = generator.allocate_register();- let iterator_done = generator.allocate_register();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::GetIterator {- dst_iterator_object: iterator_object.operand(),- dst_iterator_next: iterator_next.operand(),- dst_iterator_done: iterator_done.operand(),- iterable: input_array.operand(),- hint: IteratorHint::Sync as u32,- fast_array_mode_allowed: true,- cache,- });-- // 13.15.5.1 Runtime Semantics: DestructuringAssignmentEvaluation,- // https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation- //- // ArrayAssignmentPattern : `[` AssignmentElementList `]`- // 1. Let _iteratorRecord_ be ? GetIterator(_value_, ~sync~).- // 2. Let _result_ be Completion(IteratorDestructuringAssignmentEvaluation of |AssignmentElementList| with argument- // _iteratorRecord_).- // 3. If _iteratorRecord_.[[Done]] is *false*, return ? IteratorClose(_iteratorRecord_, _result_).- // 4. Return _result_.- let old_handler = generator.current_unwind_handler;- let close_completion_type = generator.allocate_register();- let close_completion_value = generator.allocate_register();- let exception_preamble_block = generator.make_block();- let iterator_close_body_block = generator.make_block();- let after_pattern_block = generator.make_block();- let lexical_env_at_entry = generator.lexical_environment_register_stack.last().cloned();- let parent_index = generator.current_finally_context;- generator.push_finally_context(FinallyContext {- completion_type: close_completion_type.clone(),- completion_value: close_completion_value.clone(),- finally_body: iterator_close_body_block,- exception_preamble: exception_preamble_block,- parent_index,- registered_jumps: Vec::new(),- next_jump_index: FinallyContext::FIRST_JUMP_INDEX,- lexical_environment_at_entry: lexical_env_at_entry.clone(),- saved_unwind_handler: None,- });- generator.start_boundary(BlockBoundaryType::ReturnToFinally);-- generator.current_unwind_handler = Some(exception_preamble_block);- let pattern_body_block = generator.make_block();- generator.emit(Instruction::Jump {- target: pattern_body_block,- });- generator.switch_to_basic_block(pattern_body_block);-- for (index, entry) in pattern.entries.iter().enumerate() {- if entry.is_rest {- // 13.15.5.3 AssignmentRestElement: ... DestructuringAssignmentTarget- // Step 1: Evaluate the reference BEFORE iterating remaining elements.- let evaluated_ref = emit_evaluate_binding_reference(generator, entry, mode);-- // Rest element: collect remaining into array.- // NB: Allocate register unconditionally, then re-allocate in the- // else branch.- let mut value = generator.allocate_register();- if index == 0 {- let iterator_to_array_block = make_block_with_unwind_handler(generator, old_handler);- let continuation = make_block_with_unwind_handler(generator, Some(exception_preamble_block));- generator.emit(Instruction::Jump {- target: iterator_to_array_block,- });- generator.switch_to_basic_block(iterator_to_array_block);- generator.emit(Instruction::IteratorToArray {- dst: value.operand(),- iterator_object: iterator_object.operand(),- iterator_next_method: iterator_next.operand(),- iterator_done_property: iterator_done.operand(),- });- generator.emit(Instruction::Jump { target: continuation });- generator.switch_to_basic_block(continuation);- } else {- let if_exhausted = make_block_with_unwind_handler(generator, Some(exception_preamble_block));- let if_not_exhausted = make_block_with_unwind_handler(generator, old_handler);- let continuation = make_block_with_unwind_handler(generator, Some(exception_preamble_block));-- generator.emit_jump_if(&is_exhausted, if_exhausted, if_not_exhausted);-- value = generator.allocate_register();-- generator.switch_to_basic_block(if_exhausted);- generator.emit(Instruction::NewArray {- dst: value.operand(),- element_count: 0,- elements: Vec::new(),- });- generator.emit(Instruction::Jump { target: continuation });-- generator.switch_to_basic_block(if_not_exhausted);- generator.emit(Instruction::IteratorToArray {- dst: value.operand(),- iterator_object: iterator_object.operand(),- iterator_next_method: iterator_next.operand(),- iterator_done_property: iterator_done.operand(),- });- generator.emit(Instruction::Jump { target: continuation });-- generator.switch_to_basic_block(continuation);- }-- if let Some(ref eref) = evaluated_ref {- emit_store_to_evaluated_reference(generator, eref, &value);- } else {- assign_binding_entry_alias(generator, entry, &value, mode);- }- break; // rest consumes the iterator- }-- // 13.15.5.5 AssignmentElement: DestructuringAssignmentTarget Initializer(opt)- // Step 1: Evaluate the reference BEFORE calling IteratorStepValue.- let evaluated_ref = emit_evaluate_binding_reference(generator, entry, mode);-- // For elisions (name is None), we still advance the iterator- // but don't bind anything.- let is_elision = entry.name.is_none() && entry.alias.is_none();-- let exhausted_block = make_block_with_unwind_handler(generator, Some(exception_preamble_block));-- if index != 0 {- let not_exhausted_block = make_block_with_unwind_handler(generator, Some(exception_preamble_block));- generator.emit_jump_if(&is_exhausted, exhausted_block, not_exhausted_block);- generator.switch_to_basic_block(not_exhausted_block);- }-- let iterator_next_block = make_block_with_unwind_handler(generator, old_handler);- generator.emit(Instruction::Jump {- target: iterator_next_block,- });- generator.switch_to_basic_block(iterator_next_block);-- let value = generator.allocate_register();- generator.emit(Instruction::IteratorNextUnpack {- dst_value: value.operand(),- dst_done: is_exhausted.operand(),- iterator_object: iterator_object.operand(),- iterator_next: iterator_next.operand(),- iterator_done: iterator_done.operand(),- });-- // Check if iterator got exhausted by this step.- let no_bail_block = make_block_with_unwind_handler(generator, Some(exception_preamble_block));- generator.emit_jump_if(&is_exhausted, exhausted_block, no_bail_block);-- generator.switch_to_basic_block(no_bail_block);- let create_binding_block = make_block_with_unwind_handler(generator, Some(exception_preamble_block));- generator.emit(Instruction::Jump {- target: create_binding_block,- });-- // Exhausted: load undefined.- generator.switch_to_basic_block(exhausted_block);- let undef = generator.add_constant_undefined();- generator.emit_mov(&value, &undef);- generator.emit(Instruction::Jump {- target: create_binding_block,- });-- generator.switch_to_basic_block(create_binding_block);-- // Handle default initializer.- if let Some(ref initializer) = entry.initializer {- let if_undefined = generator.make_block();- let if_not_undefined = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: value.operand(),- true_target: if_undefined,- false_target: if_not_undefined,- });- generator.switch_to_basic_block(if_undefined);- set_pending_lhs_name_for_entry(generator, entry);- if let Some(default_value) = generate_expression(initializer, generator, None) {- generator.emit_mov(&value, &default_value);- }- generator.emit(Instruction::Jump {- target: if_not_undefined,- });- generator.switch_to_basic_block(if_not_undefined);- }-- if !is_elision {- if let Some(ref eref) = evaluated_ref {- emit_store_to_evaluated_reference(generator, eref, &value);- } else {- assign_binding_entry_alias(generator, entry, &value, mode);- }- }- }-- generator.end_boundary(BlockBoundaryType::ReturnToFinally);- let finally_ctx_index = generator.current_finally_context.expect("no active finally context");- generator.current_finally_context = generator.finally_contexts[finally_ctx_index].parent_index;- generator.current_unwind_handler = old_handler;-- let normal_close_check_block = make_block_with_unwind_handler(generator, old_handler);- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Jump {- target: normal_close_check_block,- });- }-- // Close iterator if it is not done.- generator.switch_to_basic_block(normal_close_check_block);- let done_block = make_block_with_unwind_handler(generator, old_handler);- let not_done_block = make_block_with_unwind_handler(generator, old_handler);- generator.emit_jump_if(&iterator_done, done_block, not_done_block);- generator.switch_to_basic_block(not_done_block);- let undef = generator.add_constant_undefined();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::IteratorClose {- iterator_object: iterator_object.operand(),- iterator_next: iterator_next.operand(),- iterator_done: iterator_done.operand(),- completion_type: CompletionType::Normal as u32,- completion_value: undef.operand(),- cache,- });- generator.emit(Instruction::Jump { target: done_block });- generator.switch_to_basic_block(done_block);- generator.emit(Instruction::Jump {- target: after_pattern_block,- });-- generator.switch_to_basic_block(exception_preamble_block);- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::Catch {- value_feedback,- dst: close_completion_value.operand(),- });- if let Some(env) = &lexical_env_at_entry {- generator.emit(Instruction::SetLexicalEnvironment {- environment: env.operand(),- });- }- let throw_const = generator.add_constant_i32(FinallyContext::THROW);- generator.emit_mov(&close_completion_type, &throw_const);- generator.emit(Instruction::Jump {- target: iterator_close_body_block,- });-- generator.switch_to_basic_block(iterator_close_body_block);- let close_iterator_block = make_block_with_unwind_handler(generator, old_handler);- let dispatch_completion_block = make_block_with_unwind_handler(generator, old_handler);- generator.emit_jump_if(&iterator_done, dispatch_completion_block, close_iterator_block);-- generator.switch_to_basic_block(close_iterator_block);- let throw_close_block = make_block_with_unwind_handler(generator, old_handler);- let non_throw_close_block = make_block_with_unwind_handler(generator, old_handler);- let throw_check_const = generator.add_constant_i32(FinallyContext::THROW);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: close_completion_type.operand(),- rhs: throw_check_const.operand(),- true_target: throw_close_block,- false_target: non_throw_close_block,- });-- generator.switch_to_basic_block(non_throw_close_block);- let undef = generator.add_constant_undefined();- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::IteratorClose {- iterator_object: iterator_object.operand(),- iterator_next: iterator_next.operand(),- iterator_done: iterator_done.operand(),- completion_type: CompletionType::Normal as u32,- completion_value: undef.operand(),- cache,- });- generator.emit(Instruction::Jump {- target: dispatch_completion_block,- });-- generator.switch_to_basic_block(throw_close_block);- let cache = generator.next_property_lookup_cache();- generator.emit(Instruction::IteratorClose {- iterator_object: iterator_object.operand(),- iterator_next: iterator_next.operand(),- iterator_done: iterator_done.operand(),- completion_type: CompletionType::Throw as u32,- completion_value: close_completion_value.operand(),- cache,- });- if !generator.is_current_block_terminated() {- generator.emit(Instruction::Throw {- src: close_completion_value.operand(),- });- }-- generator.switch_to_basic_block(dispatch_completion_block);- let registered_jumps = std::mem::take(&mut generator.finally_contexts[finally_ctx_index].registered_jumps);- for jump in ®istered_jumps {- let after_check = make_block_with_unwind_handler(generator, old_handler);- let jump_const = generator.add_constant_i32(jump.index);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: close_completion_type.operand(),- rhs: jump_const.operand(),- true_target: jump.target,- false_target: after_check,- });- generator.switch_to_basic_block(after_check);- }-- let return_block = make_block_with_unwind_handler(generator, old_handler);- let throw_block = make_block_with_unwind_handler(generator, old_handler);- let return_const = generator.add_constant_i32(FinallyContext::RETURN);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: close_completion_type.operand(),- rhs: return_const.operand(),- true_target: return_block,- false_target: throw_block,- });-- generator.switch_to_basic_block(return_block);- if let Some(outer_index) = generator.current_finally_context {- generator.forward_completion_to_outer_finally(outer_index, &close_completion_type, &close_completion_value);- } else if generator.is_in_generator_function() {- generator.emit(Instruction::Yield {- continuation_label: None,- value: close_completion_value.operand(),- });- } else {- generator.emit(Instruction::Return {- value: close_completion_value.operand(),- });- }-- generator.switch_to_basic_block(throw_block);- generator.emit(Instruction::Throw {- src: close_completion_value.operand(),- });-- let dummy = generator.add_constant_undefined();- generator.finally_contexts[finally_ctx_index].completion_type = dummy.clone();- generator.finally_contexts[finally_ctx_index].completion_value = dummy;- generator.finally_contexts[finally_ctx_index].lexical_environment_at_entry = None;-- generator.switch_to_basic_block(after_pattern_block);-}--fn generate_object_binding_pattern(- generator: &mut Generator,- pattern: &BindingPattern,- mode: BindingMode,- object: &ScopedOperand,-) {- generator.emit(Instruction::ThrowIfNullish { src: object.operand() });-- // Every property is read from the value the pattern started with, even after an earlier entry- // has assigned the variable that value came from (`var { a, b: e } = e`).- let object = &generator.copy_if_needed_to_preserve_evaluation_order(object);-- let mut excluded_names: Vec<ScopedOperand> = Vec::new();- let has_rest = pattern.entries.last().is_some_and(|e| e.is_rest);-- for entry in &pattern.entries {- if entry.is_rest {- // AssignmentRestProperty : `...` DestructuringAssignmentTarget- // 1. Let _lRef_ be ? Evaluation of |DestructuringAssignmentTarget|.- let evaluated_ref = emit_evaluate_binding_reference(generator, entry, mode);-- // Rest element: copy object excluding already-destructured properties.- let copy = generator.allocate_register();- generator.emit(Instruction::CopyObjectExcludingProperties {- dst: copy.operand(),- from_object: object.operand(),- excluded_names_count: u32_from_usize(excluded_names.len()),- excluded_names: excluded_names.iter().map(|o| o.operand()).collect(),- });- if let Some(ref eref) = evaluated_ref {- emit_store_to_evaluated_reference(generator, eref, ©);- } else {- assign_binding_entry_alias(generator, entry, ©, mode);- }- return;- }-- let value = generator.allocate_register();- let evaluated_ref;-- match &entry.name {- Some(BindingEntryName::Identifier(ident)) => {- let arena = generator.arena.clone();- let name = arena.name_slice(*ident);- // AssignmentElement : DestructuringAssignmentTarget Initializer?- // 1. If |DestructuringAssignmentTarget| is neither an |ObjectLiteral| nor an |ArrayLiteral|, then- // a. Let _lRef_ be ? Evaluation of |DestructuringAssignmentTarget|.- // 2. Let _v_ be ? GetV(_value_, _propertyName_).- evaluated_ref = emit_evaluate_binding_reference(generator, entry, mode);- emit_get_by_id(generator, &value, object, name, None);- if has_rest {- let name_val = generator.add_constant_string(arena.name_of(*ident).clone());- excluded_names.push(name_val);- }- }- Some(BindingEntryName::Expression(expression)) => {- let property_name = generate_expression_or_undefined(expression, generator, None);- let property_name = emit_to_primitive_property_key(generator, &property_name);- if has_rest {- excluded_names.push(property_name.clone());- }- // AssignmentElement : DestructuringAssignmentTarget Initializer?- // 1. If |DestructuringAssignmentTarget| is neither an |ObjectLiteral| nor an |ArrayLiteral|, then- // a. Let _lRef_ be ? Evaluation of |DestructuringAssignmentTarget|.- // 2. Let _v_ be ? GetV(_value_, _propertyName_).- evaluated_ref = emit_evaluate_binding_reference(generator, entry, mode);- emit_get_by_value(generator, &value, object, &property_name, None);- }- None => {- // Should not happen for object patterns- continue;- }- }-- // Handle default initializer.- if let Some(ref initializer) = entry.initializer {- let if_undefined = generator.make_block();- let if_not_undefined = generator.make_block();- generator.emit(Instruction::JumpUndefined {- condition: value.operand(),- true_target: if_undefined,- false_target: if_not_undefined,- });- generator.switch_to_basic_block(if_undefined);- set_pending_lhs_name_for_entry(generator, entry);- if let Some(default_value) = generate_expression(initializer, generator, None) {- generator.emit_mov(&value, &default_value);- }- generator.emit(Instruction::Jump {- target: if_not_undefined,- });- generator.switch_to_basic_block(if_not_undefined);- }-- if let Some(ref eref) = evaluated_ref {- emit_store_to_evaluated_reference(generator, eref, &value);- } else {- assign_binding_entry_alias(generator, entry, &value, mode);- }- }-}--// =============================================================================-// Try statement-// =============================================================================--/// Generate bytecode for a try/catch/finally statement.-///-/// The structure is:-/// 1. Set up FinallyContext (if finally block exists)-/// 2. Set up exception handler pointing to catch/exception preamble-/// 3. Generate try body-/// 4. Generate catch block (if present)-/// 5. Generate finally block (if present) with LeaveFinally dispatch-fn generate_try_statement(- generator: &mut Generator,- data: &TryStatementData,- _preferred_dst: Option<&ScopedOperand>,-) -> Option<ScopedOperand> {- let old_handler = generator.current_unwind_handler;- let saved_block = generator.current_block_index();-- // Save lexical environment for restoration in catch/exception handler.- let saved_env = generator.current_lexical_environment();-- let mut next_block: Option<Label> = None;- let completion = generator.allocate_completion_register();-- // --- Set up FinallyContext if we have a finalizer ---- let has_finally = data.finalizer.is_some();- let mut finally_body_block: Option<Label> = None;-- if has_finally {- let completion_type = generator.allocate_register();- let completion_value = generator.allocate_register();-- let exception_preamble_block = generator.make_block();- let fb_block = generator.make_block();- finally_body_block = Some(fb_block);-- // Save the parent FinallyContext and install new one.- let parent_index = generator.current_finally_context;- generator.push_finally_context(FinallyContext {- completion_type,- completion_value,- finally_body: fb_block,- exception_preamble: exception_preamble_block,- parent_index,- registered_jumps: Vec::new(),- next_jump_index: FinallyContext::FIRST_JUMP_INDEX,- lexical_environment_at_entry: Some(saved_env.clone()),- saved_unwind_handler: None,- });-- // Generate exception preamble block:- // Catch → completion_value- // SetLexicalEnvironment (restore to entry)- // completion_type = THROW- // Jump → finally_body- generator.switch_to_basic_block(exception_preamble_block);- let ctx_index = generator.current_finally_context.expect("no active finally context");- let cv = generator.finally_contexts[ctx_index].completion_value.clone();- let ct = generator.finally_contexts[ctx_index].completion_type.clone();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::Catch {- value_feedback,- dst: cv.operand(),- });- generator.emit(Instruction::SetLexicalEnvironment {- environment: saved_env.operand(),- });- let throw_const = generator.add_constant_i32(FinallyContext::THROW);- generator.emit_mov(&ct, &throw_const);- generator.emit(Instruction::Jump { target: fb_block });-- // Set exception_preamble as default handler for blocks created below.- // The catch body gets this as its handler (exceptions in catch → finally).- generator.current_unwind_handler = Some(exception_preamble_block);- generator.start_boundary(BlockBoundaryType::ReturnToFinally);- }-- // --- Generate catch handler block (if present) ---- let mut handler_block: Option<Label> = None;- if let Some(catch) = &data.handler {- let hb = generator.make_block();- generator.catch_handler_labels.insert(hb.0);- handler_block = Some(hb);- generator.switch_to_basic_block(hb);-- let caught_value = generator.allocate_register();- let value_feedback = generator.next_value_feedback();- generator.emit(Instruction::Catch {- value_feedback,- dst: caught_value.operand(),- });- generator.emit(Instruction::SetLexicalEnvironment {- environment: saved_env.operand(),- });-- // Bind the catch parameter.- let mut created_catch_scope = false;- if let Some(parameter) = &catch.parameter {- match parameter {- CatchBinding::Identifier(ident_id) => {- let arena = generator.arena.clone();- let ident = &arena.identifiers[*ident_id];- if ident.is_local() {- let local = generator.local(ident.local_index);- generator.emit_mov(&local, &caught_value);- generator.mark_local_initialized(ident.local_index);- } else {- generator.push_new_catch_lexical_environment(0);- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- created_catch_scope = true;-- let id = generator.intern_identifier_id(ident.name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- emit_initialize_lexical_binding(generator, id, caught_value.operand());- }- }- CatchBinding::BindingPattern(pattern) => {- let mut names: Vec<(Utf16String, bool)> = Vec::new();- collect_pattern_binding_names(pattern, &mut names, &generator.arena);-- if !names.is_empty() {- generator.push_new_catch_lexical_environment(0);- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- created_catch_scope = true;-- for (name, _) in &names {- let id = generator.intern_identifier(name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- }- }-- generate_binding_pattern_bytecode(- generator,- pattern,- BindingMode::InitializeLexical,- &caught_value,- );- }- }- }-- // Catch body gets its own completion register to prevent- // break/continue inside catch from leaking values.- let mut catch_completion: Option<ScopedOperand> = None;- {- let saved_completion = generator.current_completion_register.clone();- if generator.must_propagate_completion {- let reg = generator.allocate_register();- let undef = generator.add_constant_undefined();- generator.emit_mov(®, &undef);- generator.current_completion_register = Some(reg.clone());- catch_completion = Some(reg);- }- generate_statement(&catch.body, generator, None);- generator.current_completion_register = saved_completion;- }-- // Save catch completion BEFORE restoring the lexical environment- // from the catch scope.- if let Some(ref completion) = completion- && let Some(ref cc) = catch_completion- && !generator.is_current_block_terminated()- {- generator.emit_mov(completion, cc);- }-- if created_catch_scope {- generator.end_variable_scope();- }-- if !generator.is_current_block_terminated() {- if has_finally {- // Normal exit from catch → completion_type = NORMAL, jump to finally.- let ctx_index = generator.current_finally_context.expect("no active finally context");- let ct = generator.finally_contexts[ctx_index].completion_type.clone();- let fb = generator.finally_contexts[ctx_index].finally_body;- let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);- generator.emit_mov(&ct, &normal_const);- generator.emit(Instruction::Jump { target: fb });- } else {- if next_block.is_none() {- next_block = Some(generator.make_block());- }- generator.emit(Instruction::Jump {- target: next_block.expect("next_block must be set"),- });- }- }- }-- if has_finally {- generator.end_boundary(BlockBoundaryType::ReturnToFinally);- }-- // --- Generate try body ----- // Set handler BEFORE creating the try body block, so make_block()- // captures the correct handler for exception routing.- // For try-catch-finally: catch handler is inner (exceptions → catch → exception_preamble → finally).- // For try-catch: catch handler.- // For try-finally: exception_preamble.- if let Some(hb) = handler_block {- generator.current_unwind_handler = Some(hb);- } else if has_finally && let Some(ctx_index) = generator.current_finally_context {- let ep = generator.finally_contexts[ctx_index].exception_preamble;- generator.current_unwind_handler = Some(ep);- }-- let try_body_block = generator.make_block();- generator.switch_to_basic_block(saved_block);- generator.emit(Instruction::Jump { target: try_body_block });-- if has_finally {- generator.start_boundary(BlockBoundaryType::ReturnToFinally);- }-- generator.switch_to_basic_block(try_body_block);-- // Try body gets its own completion register to prevent- // break/continue inside try from leaking values.- // NB: try_completion must be declared outside the inner scope so its- // register stays alive during finally body generation.- let mut try_completion: Option<ScopedOperand> = None;- {- let saved_completion = generator.current_completion_register.clone();- if generator.must_propagate_completion {- let reg = generator.allocate_register();- let undef = generator.add_constant_undefined();- generator.emit_mov(®, &undef);- generator.current_completion_register = Some(reg.clone());- try_completion = Some(reg);- }- generate_statement(&data.block, generator, None);- generator.current_completion_register = saved_completion;-- if !generator.is_current_block_terminated()- && let Some(ref completion) = completion- && let Some(ref tc) = try_completion- {- generator.emit_mov(completion, tc);- }- }-- if !generator.is_current_block_terminated() {- if has_finally {- // Normal exit from try → completion_type = NORMAL, jump to finally.- let ctx_index = generator.current_finally_context.expect("no active finally context");- let ct = generator.finally_contexts[ctx_index].completion_type.clone();- let fb = generator.finally_contexts[ctx_index].finally_body;- let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);- generator.emit_mov(&ct, &normal_const);- generator.emit(Instruction::Jump { target: fb });- } else {- generator.current_unwind_handler = old_handler;- if next_block.is_none() {- next_block = Some(generator.make_block());- }- generator.emit(Instruction::Jump {- target: next_block.expect("next_block must be set"),- });- }- }-- if has_finally {- generator.end_boundary(BlockBoundaryType::ReturnToFinally);- }-- // Restore old unwind handler.- generator.current_unwind_handler = old_handler;-- // --- Generate finally body and after-finally dispatch ---- if let Some(fb_block) = finally_body_block {- // Pop FinallyContext.- let ctx_index = generator.current_finally_context.expect("no active finally context");- generator.current_finally_context = generator.finally_contexts[ctx_index].parent_index;-- // Extract fields needed for dispatch (to avoid borrow conflicts).- let ctx_ct = generator.finally_contexts[ctx_index].completion_type.clone();- let ctx_cv = generator.finally_contexts[ctx_index].completion_value.clone();-- generator.switch_to_basic_block(fb_block);- generator.start_boundary(BlockBoundaryType::LeaveFinally);-- // Generate the finally body with a throwaway completion register- // to prevent break/continue in finally from leaking the try/catch- // completion value.- if let Some(finalizer) = &data.finalizer {- let saved_completion = generator.current_completion_register.clone();- if generator.must_propagate_completion {- let finally_completion = generator.allocate_register();- let undef = generator.add_constant_undefined();- generator.emit_mov(&finally_completion, &undef);- generator.current_completion_register = Some(finally_completion);- }- generate_statement(finalizer, generator, None);- generator.current_completion_register = saved_completion;- }-- generator.end_boundary(BlockBoundaryType::LeaveFinally);-- if !generator.is_current_block_terminated() {- if next_block.is_none() {- next_block = Some(generator.make_block());- }- let nb = next_block.expect("next_block must be set");-- emit_finally_dispatch(generator, ctx_index, &ctx_ct, &ctx_cv, nb);- }-- generator.finally_contexts[ctx_index].lexical_environment_at_entry = None;- let dummy = generator.add_constant_undefined();- generator.finally_contexts[ctx_index].completion_value = dummy.clone();- generator.finally_contexts[ctx_index].completion_type = dummy;- }-- // Switch to the next block for code after the try statement.- // When next_block is None, all paths are terminated; switch back to- // saved_block (which is already terminated) so no dead block is emitted.- generator.switch_to_basic_block(next_block.unwrap_or(saved_block));-- completion-}--/// Emit the jumps that continue after the body of a finally context, according to the type of the completion it-/// recorded: to the next block, to a registered break or continue target, to a return, or to a rethrow.-fn emit_finally_dispatch(- generator: &mut Generator,- ctx_index: usize,- ctx_ct: &ScopedOperand,- ctx_cv: &ScopedOperand,- nb: Label,-) {- // After-finally dispatch chain:- // 1. NORMAL → next block- let after_normal_check = generator.make_block();- let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: ctx_ct.operand(),- rhs: normal_const.operand(),- true_target: nb,- false_target: after_normal_check,- });- generator.switch_to_basic_block(after_normal_check);-- // 2. Registered break/continue jumps- let registered_jumps = std::mem::take(&mut generator.finally_contexts[ctx_index].registered_jumps);- for jump in ®istered_jumps {- let after_jump_check = generator.make_block();- let jump_const = generator.add_constant_i32(jump.index);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: ctx_ct.operand(),- rhs: jump_const.operand(),- true_target: jump.target,- false_target: after_jump_check,- });- generator.switch_to_basic_block(after_jump_check);- }-- // 3. RETURN → actually return the completion_value- let return_block = generator.make_block();- let rethrow_block = generator.make_block();- let return_const = generator.add_constant_i32(FinallyContext::RETURN);- let arith_feedback = generator.next_arith_feedback();- generator.emit(Instruction::JumpStrictlyEquals {- arith_feedback,- lhs: ctx_ct.operand(),- rhs: return_const.operand(),- true_target: return_block,- false_target: rethrow_block,- });-- // Generate return block.- generator.switch_to_basic_block(return_block);- if let Some(outer_index) = generator.current_finally_context {- // Nested finally: copy completion record to outer and jump to outer finally.- generator.forward_completion_to_outer_finally(outer_index, ctx_ct, ctx_cv);- } else if generator.is_in_generator_function() {- generator.emit(Instruction::Yield {- continuation_label: None,- value: ctx_cv.operand(),- });- } else {- generator.emit(Instruction::Return {- value: ctx_cv.operand(),- });- }-- // 4. Default → rethrow the exception.- generator.switch_to_basic_block(rethrow_block);- generator.emit(Instruction::Throw { src: ctx_cv.operand() });-}--/// Create a SharedFunctionInstanceData for a function expression/declaration-/// and register it with the generator.-///-/// Returns the shared_function_data_index for use in NewFunction instructions.-fn emit_new_function(generator: &mut Generator, data: Box<FunctionData>, name_override: Option<&[u16]>) -> u32 {- assert!(- data.source_text_end as usize <= generator.source_len,- "Function source range out of bounds: {}..{} (source len {})",- data.source_text_start,- data.source_text_end,- generator.source_len- );-- let arena_clone = generator.arena.clone();- let subtable = generator.function_table.extract_reachable(&data, &arena_clone.scopes);- generator.register_shared_function_data(PendingSharedFunctionData {- function_data: Some(data),- subtable: Some(subtable),- arena: None,- name_override: name_override.map(Utf16String::from),- class_field_initializer_name: None,- should_eager_compile: false,- precompiled_function: None,- enclosing_environment_scope: None,- })-}--// =============================================================================-// FunctionDeclarationInstantiation (FDI)-// =============================================================================--/// Emit FDI bytecode for a function body.-///-/// Creates environment bindings, initializes parameters, creates arguments-/// objects, and hoists function declarations.-pub fn emit_function_declaration_instantiation(- generator: &mut Generator,- function_data: &FunctionData,- body_scope: &ScopeData,- var_environment_bindings_count: usize,-) {- let strict = function_data.is_strict_mode || generator.strict;- let is_arrow = function_data.is_arrow_function;-- // --- Compute FDI metadata ----- // Check for parameter expressions (default values or binding patterns with expressions).- let has_parameter_expressions = function_data.parameters.iter().any(|p| {- p.default_value.is_some()- || matches!(- p.binding,- FunctionParameterBinding::BindingPattern(ref pat) if pat.contains_expression()- )- });-- // Build parameter_names map and check for duplicates.- let mut parameter_names: Vec<FdiParameterName> = Vec::new();- let mut seen_names: HashSet<Utf16String> = HashSet::new();- let mut has_duplicates = false;-- let arena = generator.arena.clone();- for parameter in &function_data.parameters {- match ¶meter.binding {- FunctionParameterBinding::Identifier(ident_id) => {- let ident = &arena.identifiers[*ident_id];- let name = arena.strings[ident.name].clone();- let is_local = ident.is_local();- if !seen_names.insert(name.clone()) {- has_duplicates = true;- } else {- parameter_names.push(FdiParameterName { name, is_local });- }- }- FunctionParameterBinding::BindingPattern(pattern) => {- collect_binding_pattern_names(- pattern,- &mut parameter_names,- &mut seen_names,- &mut has_duplicates,- &arena,- );- }- }- }-- // Determine if arguments object is needed. The parser's- // `might_need_arguments_object` flag is set when an `arguments` or- // `eval` Identifier is consumed as a free reference, but it misses- // references created without going through consume(), like shorthand- // `{ arguments }`. Fall back to checking whether scope analysis- // allocated a non-lexical `arguments` local (an ArgumentsObject- // binding). Skip the fallback when a function declaration named- // `arguments` claims the same local: that local belongs to the- // function, not a real arguments-object reference.- let function_scope_data = body_scope.function_scope_data.as_ref();- let has_function_named_arguments = function_scope_data.is_some_and(|fsd| fsd.has_function_named_arguments);- let arguments_local_index = body_scope- .local_variables- .iter()- .position(|lv| lv.kind == LocalVarKind::ArgumentsObject);- let has_arguments_local = arguments_local_index.is_some();- let mut arguments_object_needed = if is_arrow || parameter_names.iter().any(|p| p.name == utf16!("arguments")) {- false- } else {- function_data.parsing_insights.might_need_arguments_object- || (has_arguments_local && !has_function_named_arguments)- };-- if let Some(fsd) = function_scope_data {- if !has_parameter_expressions && fsd.has_function_named_arguments {- arguments_object_needed = false;- }- if !has_parameter_expressions && arguments_object_needed && fsd.has_lexically_declared_arguments {- arguments_object_needed = false;- }- }-- // --- Step 1: Parameter scope for parameter expressions ----- if has_parameter_expressions {- let non_local_parameter_count = parameter_names.iter().filter(|p| !p.is_local).count();- if non_local_parameter_count > 0 {- // NB: The arguments binding goes here too, and so do the lexical declarations of strict code without a- // separate var environment for non-local vars (see Step 5 and Step 7).- let arguments_binding = arguments_object_needed && !has_arguments_local;- let has_non_local_vars =- function_scope_data.is_some_and(|fsd| fsd.vars_to_initialize.iter().any(|v| v.local.is_none()));- let lexical_bindings = if strict && !has_non_local_vars {- count_non_local_lexical_bindings(body_scope, &generator.arena)- } else {- 0- };- let capacity = u32_from_usize(non_local_parameter_count) + u32::from(arguments_binding) + lexical_bindings;- generator.push_new_lexical_environment(capacity);- }- }-- // NB: A mapped arguments object aliases bindings of the parameters, which CreateArguments then creates in the- // function environment itself, in the same order as the CreateVariables below would.- let arguments_object_is_mapped = arguments_object_needed- && !strict- && function_data.parameters.iter().all(|p| {- !p.is_rest && p.default_value.is_none() && matches!(p.binding, FunctionParameterBinding::Identifier(_))- });- // NB: When the arguments object is not used after all, the parameters may be locals, and have no bindings to make.- // Without parameters, there are none to make either.- let arguments_object_creates_parameter_bindings = arguments_object_is_mapped- && !parameter_names.is_empty()- && parameter_names.iter().all(|param| !param.is_local);-- // --- Step 2: Create bindings for non-local parameters ----- for param in ¶meter_names {- if arguments_object_creates_parameter_bindings {- let id = generator.intern_identifier(¶m.name);- generator.record_environment_binding_created_elsewhere(id);- continue;- }- if !param.is_local {- let id = generator.intern_identifier(¶m.name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- if has_duplicates {- let undef = generator.add_constant_undefined();- emit_initialize_lexical_binding(generator, id, undef.operand());- }- }- }-- // --- Step 3: Create arguments object ----- if arguments_object_needed {- let dst = arguments_local_index.map(|index| Operand::local(u32_from_usize(index)));-- let kind = if arguments_object_is_mapped {- ArgumentsKind::Mapped as u32- } else {- ArgumentsKind::Unmapped as u32- };-- generator.emit(Instruction::CreateArguments {- dst,- kind,- is_immutable: strict,- creates_parameter_bindings: arguments_object_creates_parameter_bindings,- });-- if arguments_object_creates_parameter_bindings && has_duplicates {- for param in ¶meter_names {- let id = generator.intern_identifier(¶m.name);- let undef = generator.add_constant_undefined();- emit_initialize_lexical_binding(generator, id, undef.operand());- }- }-- if let Some(index) = arguments_local_index {- generator.mark_local_initialized(u32_from_usize(index));- }- }-- // --- Step 4: Bind formal parameters ----- for (parameter_index, parameter) in function_data.parameters.iter().enumerate() {- let parameter_index = u32_from_usize(parameter_index);-- if parameter.is_rest {- let dst = generator.scoped_operand(Operand::argument(parameter_index));- generator.emit(Instruction::CreateRestParams {- dst: dst.operand(),- rest_index: parameter_index,- });- } else if parameter.default_value.is_some() {- let if_undefined_block = generator.make_block();- let if_not_undefined_block = generator.make_block();-- generator.emit(Instruction::JumpUndefined {- condition: Operand::argument(parameter_index),- true_target: if_undefined_block,- false_target: if_not_undefined_block,- });-- generator.switch_to_basic_block(if_undefined_block);- if let FunctionParameterBinding::Identifier(ident_id) = ¶meter.binding {- // https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization- // If |Initializer| is present and _v_ is *undefined*, then- // If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then- // Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_.- let arena = generator.arena.clone();- generator.pending_lhs_name = Some(generator.intern_identifier_id(arena.identifiers[*ident_id].name));- }- if let Some(value) = generate_expression(- parameter- .default_value- .as_ref()- .expect("guarded by has_default_value check"),- generator,- None,- ) {- generator.emit_mov_raw(Operand::argument(parameter_index), value.operand());- }- generator.pending_lhs_name = None;- generator.emit(Instruction::Jump {- target: if_not_undefined_block,- });-- generator.switch_to_basic_block(if_not_undefined_block);- }-- match ¶meter.binding {- FunctionParameterBinding::Identifier(ident_id) => {- let arena = generator.arena.clone();- let ident = &arena.identifiers[*ident_id];- if ident.is_local() {- let local_index = ident.local_index;- match ident.local_type {- Some(LocalType::Variable) => generator.mark_local_initialized(local_index),- Some(LocalType::Argument) => {- generator.mark_argument_initialized(local_index);- }- None => {}- }- } else {- let id = generator.intern_identifier_id(ident.name);- if has_duplicates {- emit_set_lexical_binding(generator, id, Operand::argument(parameter_index));- } else {- emit_initialize_lexical_binding(generator, id, Operand::argument(parameter_index));- }- }- }- FunctionParameterBinding::BindingPattern(pattern) => {- let argument = generator.scoped_operand(Operand::argument(parameter_index));- let mode = if has_duplicates {- BindingMode::Set- } else {- BindingMode::InitializeLexical- };- generate_binding_pattern_bytecode(generator, pattern, mode, &argument);- }- }- }-- // --- Step 5: Initialize var bindings ----- if let Some(fsd) = function_scope_data {- if !has_parameter_expressions {- // Simple case: vars share the parameter environment.- for var in &fsd.vars_to_initialize {- if var.is_parameter {- continue;- }- if arguments_object_needed && var.name == utf16!("arguments") {- continue;- }-- if let Some(local_binding) = var.local {- let undef = generator.add_constant_undefined();- let local = var_local_operand(generator, local_binding.local_type, local_binding.index);- generator.emit_mov(&local, &undef);- } else {- let id = generator.intern_identifier(&var.name);- let undef = generator.add_constant_undefined();- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Var as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- emit_initialize_variable_binding(generator, id, undef.operand());- }- }- } else {- // Parameter expressions: vars get a separate environment.- let has_non_local_vars = fsd.vars_to_initialize.iter().any(|v| v.local.is_none());-- if has_non_local_vars {- generator.emit(Instruction::CreateVariableEnvironment {- capacity: u32_from_usize(var_environment_bindings_count),- });- // After CreateVariableEnvironment, re-read the lexical environment- // (which was also updated) and push it onto the register stack.- // This ensures subsequent CreateLexicalEnvironment instructions- // (e.g. Step 7) use the var environment as their parent, not the- // parameter scope.- let var_env = generator.allocate_register();- generator.emit(Instruction::GetLexicalEnvironment { dst: var_env.operand() });- generator.push_static_variable_environment(var_env);- }-- for var in &fsd.vars_to_initialize {- let is_in_parameter_bindings =- var.is_parameter || (arguments_object_needed && var.name == utf16!("arguments"));-- let initial_value = if !is_in_parameter_bindings || var.is_function_name {- let value = generator.allocate_register();- let undef = generator.add_constant_undefined();- generator.emit_mov(&value, &undef);- value- } else if let Some(local_binding) = var.local {- let local = var_local_operand(generator, local_binding.local_type, local_binding.index);- let value = generator.allocate_register();- generator.emit_mov(&value, &local);- value- } else {- let id = generator.intern_identifier(&var.name);- let value = generator.allocate_register();- emit_get_binding(generator, value.operand(), id, false);- value- };-- if let Some(local_binding) = var.local {- let local = var_local_operand(generator, local_binding.local_type, local_binding.index);- generator.emit_mov(&local, &initial_value);- } else {- let id = generator.intern_identifier(&var.name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Var as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- emit_initialize_variable_binding(generator, id, initial_value.operand());- }- }- }- }-- // --- Step 6: AnnexB function name bindings (non-strict only) ---- if !strict {- let var_names = function_scope_data.map(|fsd| &fsd.var_names);- for name in &body_scope.annexb_function_names {- generator.annexb_function_names.insert(name.clone());- // Skip creating a var binding if this name is already declared as a var.- if var_names.is_some_and(|names| names.contains(name)) {- continue;- }- let id = generator.intern_identifier(name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Var as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- let undef = generator.add_constant_undefined();- emit_initialize_variable_binding(generator, id, undef.operand());- }- }-- // --- Step 7: Lexical environment for non-local declarations ---- // Note: this counts only let/const/class declarations (not function declarations,- // which are var-hoisted in function bodies).- let lex_bindings_count = count_non_local_lexical_bindings(body_scope, &generator.arena);-- if !strict && lex_bindings_count > 0 {- generator.push_new_lexical_environment(lex_bindings_count);- }-- // --- Step 8: Create lexical bindings ----- for child in &body_scope.children {- if let Some((declarations, is_constant)) = lexical_declarators(child) {- for declaration in declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, &generator.arena);- for (name, _) in names {- let id = generator.intern_identifier(&name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: is_constant,- is_global: false,- is_strict: is_constant,- });- }- }- continue;- }- if let StatementKind::ClassDeclaration(class_data) = &child.inner {- // Class declarations are lexically scoped (like const).- if let Some(name_ident_id) = class_data.name {- let arena = generator.arena.clone();- let name_ident = &arena.identifiers[name_ident_id];- if !name_ident.is_local() {- let id = generator.intern_identifier_id(name_ident.name);- generator.emit(Instruction::CreateVariable {- identifier: id,- mode: EnvironmentMode::Lexical as u32,- is_immutable: false,- is_global: false,- is_strict: false,- });- }- }- }- }-- // --- Step 9: Initialize hoisted function declarations ----- if let Some(fsd) = function_scope_data {- for function_to_init in &fsd.functions_to_initialize {- let child = &body_scope.children[function_to_init.child_index];- if let Some(fd) = child.inner.function_declaration_for_labelled_item() {- let inner_function_data = generator.function_table.take(fd.function_id);- let sfd_index = emit_new_function(generator, inner_function_data, None);-- // Check if the function name identifier is local.- if let Some(name_ident_id) = fd.name {- let arena = generator.arena.clone();- let name_ident = &arena.identifiers[name_ident_id];- if name_ident.is_local() {- let local_index = name_ident.local_index;- let local = generator.local(local_index);- generator.emit(Instruction::NewFunction {- dst: local.operand(),- shared_function_data_index: sfd_index,- home_object: None,- lhs_name: None,- });- generator.mark_local_initialized(local_index);- } else {- let function_reg = generator.allocate_register();- generator.emit(Instruction::NewFunction {- dst: function_reg.operand(),- shared_function_data_index: sfd_index,- home_object: None,- lhs_name: None,- });- let id = generator.intern_identifier_id(name_ident.name);- emit_set_variable_binding(generator, id, function_reg.operand());- }- }- }- }- }-}--/// Check if a statement is a for-loop variant (for, for-in, for-of, for-await-of).-fn is_for_loop(statement: &Statement) -> bool {- matches!(statement.inner, StatementKind::For(_) | StatementKind::ForInOf(_))-}--/// Check if a block needs block declaration instantiation.-/// True when the block has function declarations or non-local let/const/class.-fn needs_block_declaration_instantiation(scope: &ScopeData, arena: &crate::ast::AstArena) -> bool {- for child in &scope.children {- match &child.inner {- _ if child.inner.function_declaration_for_labelled_item().is_some() => {- return true;- }- StatementKind::VariableDeclaration(vd)- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>- {- for declaration in &vd.declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, arena);- if !names.is_empty() {- return true;- }- }- }- StatementKind::ClassDeclaration(class_data) => {- if let Some(name_ident) = class_data.name- && !arena.identifiers[name_ident].is_local()- {- return true;- }- }- StatementKind::UsingDeclaration(declarations) => {- for declaration in &declarations.declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, arena);- if !names.is_empty() {- return true;- }- }- }- _ => {}- }- }- false-}--/// Count the bindings a block or switch declaration instantiation creates.-fn count_lexical_declarations_for_block<'a>(- children: impl Iterator<Item = &'a Statement>,- arena: &crate::ast::AstArena,-) -> u32 {- let mut count = 0u32;- let mut function_names = HashSet::new();- for child in children {- if let Some(fd) = child.inner.function_declaration_for_labelled_item()- && let Some(name_ident_id) = fd.name- {- let name_ident = &arena.identifiers[name_ident_id];- if function_names.insert(name_ident.name) && !name_ident.is_local() {- count += 1;- }- continue;- }-- match &child.inner {- StatementKind::VariableDeclaration(vd)- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>- {- for declaration in &vd.declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, arena);- count += u32_from_usize(names.len());- }- }- StatementKind::UsingDeclaration(declarations) => {- for declaration in &declarations.declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, arena);- count += u32_from_usize(names.len());- }- }- StatementKind::ClassDeclaration(class_data)- if class_data.name.is_some_and(|n| !arena.identifiers[n].is_local()) =>- {- count += 1;- }- _ => {}- }- }- count-}--/// Count non-local lexical bindings in a function body scope.-fn count_non_local_lexical_bindings(scope: &ScopeData, arena: &crate::ast::AstArena) -> u32 {- let mut count = 0u32;- for child in &scope.children {- if let Some((declarations, _)) = lexical_declarators(child) {- for declaration in declarations {- let mut names = Vec::new();- collect_target_names(&declaration.target, &mut names, arena);- count += u32_from_usize(names.len());- }- continue;- }- match &child.inner {- StatementKind::ClassDeclaration(class_data)- if class_data.name.is_some_and(|n| !arena.identifiers[n].is_local()) =>- {- count += 1;- }- _ => {}- }- }- count-}--/// Create a ScopedOperand for a VarToInit's local variable (argument or variable).-fn var_local_operand(generator: &mut Generator, local_type: LocalType, index: u32) -> ScopedOperand {- generator.resolve_local(index, local_type)-}--/// Collect bound names from a binding pattern into the parameter_names list.-fn collect_binding_pattern_names(- pattern: &BindingPattern,- parameter_names: &mut Vec<FdiParameterName>,- seen_names: &mut HashSet<Utf16String>,- has_duplicates: &mut bool,- arena: &crate::ast::AstArena,-) {- for entry in &pattern.entries {- // The bound name can be in the alias (for object patterns) or name (for array patterns).- match &entry.alias {- Some(BindingEntryAlias::Identifier(ident_id)) => {- let ident = &arena.identifiers[*ident_id];- let name = arena.strings[ident.name].clone();- let is_local = ident.is_local();- if !seen_names.insert(name.clone()) {- *has_duplicates = true;- } else {- parameter_names.push(FdiParameterName { name, is_local });- }- }- Some(BindingEntryAlias::BindingPattern(sub_pattern)) => {- collect_binding_pattern_names(sub_pattern, parameter_names, seen_names, has_duplicates, arena);- }- None => {- // No alias — the name itself is the binding.- if let Some(BindingEntryName::Identifier(ident_id)) = &entry.name {- let ident = &arena.identifiers[*ident_id];- let name = arena.strings[ident.name].clone();- let is_local = ident.is_local();- if !seen_names.insert(name.clone()) {- *has_duplicates = true;- } else {- parameter_names.push(FdiParameterName { name, is_local });- }- }- }- Some(BindingEntryAlias::MemberExpression(_)) => {}- }- }-}--/// A parameter name with its locality (used during FDI).-struct FdiParameterName {- name: Utf16String,- is_local: bool,-}--/// JS ToInt32 conversion (ECMA-262 7.1.6).-fn to_int32(n: f64) -> i32 {- if n.is_nan() || n.is_infinite() || n == 0.0 {- return 0;- }- let int_val = n.signum() * n.abs().floor();- let int32bit = int_val % 4294967296.0; // 2^32- let int32bit = if int32bit < 0.0 {- int32bit + 4294967296.0- } else {- int32bit- };- if int32bit >= 2147483648.0 {- (int32bit - 4294967296.0) as i32- } else {- int32bit as i32- }-}--/// JS ToUint32 conversion (ECMA-262 7.1.7).-fn to_u32(n: f64) -> u32 {- if n.is_nan() || n.is_infinite() || n == 0.0 {- return 0;- }- let int_val = n.signum() * n.abs().floor();- let int32bit = int_val % 4294967296.0; // 2^32- if int32bit < 0.0 {- (int32bit + 4294967296.0) as u32- } else {- int32bit as u32- }-}--/// Check if a string key is a numeric index (valid u32 < u32::MAX).-/// Numeric indices are stored in indexed storage rather than shape-based storage.-fn is_numeric_index_key(key: &[u16]) -> bool {- if key.is_empty() {- return false;- }- // Exclude leading zeros in multi-digit strings (e.g., "01")- if key[0] == ch(b'0') && key.len() > 1 {- return false;- }- // Must be all ASCII digits- if !key.iter().all(|&c| c >= ch(b'0') && c <= ch(b'9')) {- return false;- }- // Parse as u64 first to avoid overflow, then check < u32::MAX- let mut n: u64 = 0;- for &c in key {- n = n * 10 + (c - ch(b'0')) as u64;- if n > u32::MAX as u64 {- return false;- }- }- (n as u32) < u32::MAX-}--// =============================================================================-// Constant folding-// =============================================================================--/// Try to constant-fold a unary operation when the operand is a constant.-fn try_constant_fold_unary(generator: &mut Generator, op: UnaryOp, operand: &ScopedOperand) -> Option<ScopedOperand> {- let constant = generator.get_constant(operand)?;- match op {- UnaryOp::Minus => {- let n = constant_to_number(constant)?;- Some(generator.add_constant_number(-n))- }- UnaryOp::Plus => {- let n = constant_to_number(constant)?;- Some(generator.add_constant_number(n))- }- UnaryOp::BitwiseNot => {- if let ConstantValue::BigInt(s) = constant {- let n = parse_bigint(&s.clone())?;- return Some(generator.add_constant_bigint((-(n + BigInt::one())).to_string()));- }- let n = constant_to_number(constant)?;- Some(generator.add_constant_number((!to_int32(n)) as f64))- }- UnaryOp::Not => {- let as_bool = constant_to_boolean(constant)?;- Some(generator.add_constant_boolean(!as_bool))- }- _ => None,- }-}--/// Constant-fold !!x when x is a constant, returning Boolean(x).-fn try_constant_fold_to_boolean(generator: &mut Generator, operand: &ScopedOperand) -> Option<ScopedOperand> {- let constant = generator.get_constant(operand)?;- let as_bool = constant_to_boolean(constant)?;- Some(generator.add_constant_boolean(as_bool))-}--/// Implement IsLooselyEqual for constant values.-/// https://tc39.es/ecma262/#sec-islooselyequal-fn try_constant_loosely_equals(lhs: &ConstantValue, rhs: &ConstantValue) -> Option<bool> {- // Same type: use strict equality rules.- match (lhs, rhs) {- (ConstantValue::Null | ConstantValue::Undefined, ConstantValue::Null | ConstantValue::Undefined) => {- return Some(true);- }- (ConstantValue::Null | ConstantValue::Undefined, _) | (_, ConstantValue::Null | ConstantValue::Undefined) => {- return Some(false);- }- (ConstantValue::Number(a), ConstantValue::Number(b)) => return Some(a == b),- (ConstantValue::String(a), ConstantValue::String(b)) => return Some(a == b),- (ConstantValue::Boolean(a), ConstantValue::Boolean(b)) => return Some(a == b),- (ConstantValue::BigInt(a), ConstantValue::BigInt(b)) => return Some(a == b),- _ => {}- }- // Cross-type comparisons: Boolean → Number first, then retry.- match (lhs, rhs) {- (ConstantValue::Boolean(b), _) => {- let coerced = ConstantValue::Number(if *b { 1.0 } else { 0.0 });- return try_constant_loosely_equals(&coerced, rhs);- }- (_, ConstantValue::Boolean(b)) => {- let coerced = ConstantValue::Number(if *b { 1.0 } else { 0.0 });- return try_constant_loosely_equals(lhs, &coerced);- }- _ => {}- }- // Number == String → compare ToNumber(string) to number.- // String == Number → compare number to ToNumber(string).- match (lhs, rhs) {- (ConstantValue::Number(n), ConstantValue::String(s)) | (ConstantValue::String(s), ConstantValue::Number(n)) => {- Some(*n == crate::host::string_to_number(&s.0))- }- // BigInt == Number or Number == BigInt: compare mathematical values.- (ConstantValue::BigInt(b), ConstantValue::Number(n)) | (ConstantValue::Number(n), ConstantValue::BigInt(b)) => {- if n.is_nan() || n.is_infinite() {- return Some(false);- }- if n.fract() != 0.0 {- return Some(false);- }- let bi = parse_bigint(b)?;- Some(BigInt::from_f64(*n)? == bi)- }- // BigInt == String or String == BigInt: parse string as BigInt per StringToBigInt.- // If the string cannot be parsed, the result is false (not equal).- (ConstantValue::BigInt(b), ConstantValue::String(s)) | (ConstantValue::String(s), ConstantValue::BigInt(b)) => {- match crate::host::string_to_bigint(&s.0) {- Some(s_bi) => {- let bi = parse_bigint(b)?;- Some(bi == s_bi)- }- None => Some(false),- }- }- _ => None,- }-}--fn ascii_code_units_to_string(text: &[u16]) -> Option<String> {- text.iter()- .map(|&code_unit| {- u8::try_from(code_unit)- .ok()- .and_then(|byte| byte.is_ascii().then_some(char::from(byte)))- })- .collect()-}--fn bigint_literal_digits(literal: &Utf16String) -> &[u16] {- literal.0.strip_suffix(&[b'n'.into()]).unwrap_or(literal.0.as_slice())-}--/// Constant-fold a binary operation on two BigInt operands.-fn try_constant_fold_bigint_binary(- generator: &mut Generator,- op: BinaryOp,- a_str: &str,- b_str: &str,-) -> Option<ScopedOperand> {- let a = parse_bigint(a_str)?;- let b = parse_bigint(b_str)?;- match op {- // Arithmetic operations: produce a BigInt result.- BinaryOp::Addition => Some(generator.add_constant_bigint((&a + &b).to_string())),- BinaryOp::Subtraction => Some(generator.add_constant_bigint((&a - &b).to_string())),- BinaryOp::Multiplication => Some(generator.add_constant_bigint((&a * &b).to_string())),- BinaryOp::Division => {- if b.is_zero() {- return None; // Division by zero throws at runtime.- }- use num_integer::Integer;- let (quotient, _) = a.div_rem(&b);- Some(generator.add_constant_bigint(quotient.to_string()))- }- BinaryOp::Modulo => {- if b.is_zero() {- return None; // Modulo by zero throws at runtime.- }- // JS BigInt remainder has the sign of the dividend (truncated division).- Some(generator.add_constant_bigint((&a % &b).to_string()))- }- BinaryOp::Exponentiation => {- if b.is_negative() {- return None; // Negative exponent throws at runtime.- }- let exp = b.to_u32()?;- // Only fold small exponents to avoid huge results.- if exp > 1000 {- return None;- }- Some(generator.add_constant_bigint(num_traits::pow::pow(a, exp as usize).to_string()))- }- // Comparison operations: produce a Boolean result.- BinaryOp::StrictlyEquals | BinaryOp::LooselyEquals => Some(generator.add_constant_boolean(a == b)),- BinaryOp::StrictlyInequals | BinaryOp::LooselyInequals => Some(generator.add_constant_boolean(a != b)),- BinaryOp::LessThan => Some(generator.add_constant_boolean(a < b)),- BinaryOp::LessThanEquals => Some(generator.add_constant_boolean(a <= b)),- BinaryOp::GreaterThan => Some(generator.add_constant_boolean(a > b)),- BinaryOp::GreaterThanEquals => Some(generator.add_constant_boolean(a >= b)),- // Bitwise operations on BigInt.- BinaryOp::BitwiseAnd => Some(generator.add_constant_bigint((&a & &b).to_string())),- BinaryOp::BitwiseOr => Some(generator.add_constant_bigint((&a | &b).to_string())),- BinaryOp::BitwiseXor => Some(generator.add_constant_bigint((&a ^ &b).to_string())),- BinaryOp::LeftShift => {- let shift = b.to_u64()?;- if shift > 512 {- return None;- }- Some(generator.add_constant_bigint((&a << shift as usize).to_string()))- }- BinaryOp::RightShift => {- let shift = b.to_u64()?;- // BigInt right shift for negative numbers floors toward negative infinity.- Some(generator.add_constant_bigint((&a >> shift).to_string()))- }- // UnsignedRightShift throws TypeError for BigInt.- _ => None,- }-}--/// Convert a constant value to a JS number for constant folding purposes.-fn constant_to_number(val: &ConstantValue) -> Option<f64> {- match val {- ConstantValue::Number(n) => Some(*n),- ConstantValue::Boolean(b) => Some(if *b { 1.0 } else { 0.0 }),- ConstantValue::Null => Some(0.0),- ConstantValue::Undefined => Some(f64::NAN),- ConstantValue::String(s) => Some(crate::host::string_to_number(&s.0)),- _ => None,- }-}--/// Convert a constant value to a JS string (ToString) for string concatenation.-/// Returns None for types where ToString requires runtime (e.g. objects).-fn constant_to_string(val: &ConstantValue) -> Option<Utf16String> {- match val {- ConstantValue::String(s) => Some(s.clone()),- ConstantValue::Number(n) => Some(crate::host::js_number_to_utf16(*n)),- ConstantValue::Boolean(b) => Some(if *b {- Utf16String(utf16!("true").to_vec())- } else {- Utf16String(utf16!("false").to_vec())- }),- ConstantValue::Null => Some(Utf16String(utf16!("null").to_vec())),- ConstantValue::Undefined => Some(Utf16String(utf16!("undefined").to_vec())),- ConstantValue::BigInt(s) => {- // BigInt.prototype.toString() returns the decimal string representation.- Some(Utf16String(parse_bigint(s)?.to_string().encode_utf16().collect()))- }- _ => None,- }-}--/// Compare a BigInt and a Number using Abstract Relational Comparison semantics.-/// Returns None if comparison cannot be folded (non-safe integer, etc).-/// Returns Some(None) for NaN (undefined result - all comparisons return false).-/// Returns Some(Some(Ordering)) for the BigInt relative to the Number.-fn compare_bigint_and_number(bigint_str: &str, number: f64) -> Option<Option<std::cmp::Ordering>> {- use std::cmp::Ordering;- if number.is_nan() {- return Some(None); // Comparisons with NaN return undefined → false.- }- if number == f64::INFINITY {- return Some(Some(Ordering::Less)); // Any BigInt < +Infinity- }- if number == f64::NEG_INFINITY {- return Some(Some(Ordering::Greater)); // Any BigInt > -Infinity- }- let bigint = parse_bigint(bigint_str)?;- if number.fract() != 0.0 {- // The number has a fractional part, so we can still compare:- // floor(number) < bigint means bigint > number, etc.- let floored = number.floor();- let floored_bigint = BigInt::from_f64(floored)?;- if bigint <= floored_bigint {- // bigint <= floor(number) means bigint < number- return Some(Some(Ordering::Less));- } else {- // bigint > floor(number) means bigint > number (since number = floor + fract where fract > 0)- return Some(Some(Ordering::Greater));- }- }- let number_bigint = BigInt::from_f64(number)?;- Some(Some(bigint.cmp(&number_bigint)))-}--/// Try to constant-fold a binary operation when both operands are constants.-fn try_constant_fold_binary(- generator: &mut Generator,- op: BinaryOp,- lhs: &ScopedOperand,- rhs: &ScopedOperand,-) -> Option<ScopedOperand> {- let lhs_const = generator.get_constant(lhs)?;- let rhs_const = generator.get_constant(rhs)?;-- // BigInt constant folding: if both operands are BigInt, handle separately.- // Clone strings to release the immutable borrow on gen before the mutable call.- if let (ConstantValue::BigInt(a), ConstantValue::BigInt(b)) = (lhs_const, rhs_const) {- let a = a.clone();- let b = b.clone();- return try_constant_fold_bigint_binary(generator, op, &a, &b);- }-- match op {- BinaryOp::Addition => {- // If either operand is a string, do string concatenation using ToString.- if matches!(lhs_const, ConstantValue::String(_)) || matches!(rhs_const, ConstantValue::String(_)) {- let a = constant_to_string(lhs_const)?;- let b = constant_to_string(rhs_const)?;- let mut result = a;- result.0.extend_from_slice(&b);- return Some(generator.add_constant_string(result));- }- // Numeric addition: both operands coerced to number- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number(a + b))- }- BinaryOp::Subtraction => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number(a - b))- }- BinaryOp::Multiplication => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number(a * b))- }- BinaryOp::Division => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number(a / b))- }- BinaryOp::Modulo => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number(a % b))- }- BinaryOp::Exponentiation => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number(crate::host::exponentiate(a, b)))- }- BinaryOp::StrictlyEquals | BinaryOp::StrictlyInequals => {- let equal = match (lhs_const, rhs_const) {- (ConstantValue::Number(a), ConstantValue::Number(b)) => a == b,- (ConstantValue::String(a), ConstantValue::String(b)) => a == b,- (ConstantValue::Boolean(a), ConstantValue::Boolean(b)) => a == b,- (ConstantValue::Null, ConstantValue::Null) => true,- (ConstantValue::Undefined, ConstantValue::Undefined) => true,- (ConstantValue::WellKnownSymbol(a), ConstantValue::WellKnownSymbol(b)) => a == b,- // Different types are never strictly equal.- _ => false,- };- let result = if op == BinaryOp::StrictlyInequals {- !equal- } else {- equal- };- Some(generator.add_constant_boolean(result))- }- BinaryOp::GreaterThan | BinaryOp::GreaterThanEquals | BinaryOp::LessThan | BinaryOp::LessThanEquals => {- // String-string comparison is lexicographic (by UTF-16 code units).- if let (ConstantValue::String(a), ConstantValue::String(b)) = (lhs_const, rhs_const) {- let result = match op {- BinaryOp::GreaterThan => a.0 > b.0,- BinaryOp::GreaterThanEquals => a.0 >= b.0,- BinaryOp::LessThan => a.0 < b.0,- BinaryOp::LessThanEquals => a.0 <= b.0,- _ => unreachable!("outer match arm only matches comparison operators"),- };- return Some(generator.add_constant_boolean(result));- }- // BigInt-Number/Boolean cross-type comparison.- // Per spec, Booleans are converted to Number first.- let lhs_for_cmp = match lhs_const {- ConstantValue::Boolean(b) => &ConstantValue::Number(if *b { 1.0 } else { 0.0 }),- other => other,- };- let rhs_for_cmp = match rhs_const {- ConstantValue::Boolean(b) => &ConstantValue::Number(if *b { 1.0 } else { 0.0 }),- other => other,- };- // BigInt vs Number comparison using Abstract Relational Comparison.- let bigint_ord = match (lhs_for_cmp, rhs_for_cmp) {- (ConstantValue::BigInt(b), ConstantValue::Number(n)) => compare_bigint_and_number(b, *n),- (ConstantValue::Number(n), ConstantValue::BigInt(b)) => {- compare_bigint_and_number(b, *n).map(|o| o.map(|o| o.reverse()))- }- // BigInt vs String: per spec, parse the string as a BigInt- // using StringToBigInt, then compare the two BigInts.- // If the string is not a valid StringIntegerLiteral,- // the result is undefined (= false for all comparisons).- (ConstantValue::BigInt(b), ConstantValue::String(s)) => match crate::host::string_to_bigint(&s.0) {- Some(rhs_bi) => {- let lhs_bi = parse_bigint(b)?;- Some(Some(lhs_bi.cmp(&rhs_bi)))- }- None => Some(None),- },- (ConstantValue::String(s), ConstantValue::BigInt(b)) => match crate::host::string_to_bigint(&s.0) {- Some(lhs_bi) => {- let rhs_bi = parse_bigint(b)?;- Some(Some(lhs_bi.cmp(&rhs_bi)))- }- None => Some(None),- },- _ => None,- };- if let Some(ord) = bigint_ord {- let result = match op {- BinaryOp::GreaterThan => matches!(ord, Some(std::cmp::Ordering::Greater)),- BinaryOp::GreaterThanEquals => {- matches!(ord, Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal))- }- BinaryOp::LessThan => matches!(ord, Some(std::cmp::Ordering::Less)),- BinaryOp::LessThanEquals => {- matches!(ord, Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal))- }- _ => unreachable!("outer match arm only matches comparison operators"),- };- return Some(generator.add_constant_boolean(result));- }- let a = constant_to_number(lhs_for_cmp)?;- let b = constant_to_number(rhs_for_cmp)?;- let result = match op {- BinaryOp::GreaterThan => a > b,- BinaryOp::GreaterThanEquals => a >= b,- BinaryOp::LessThan => a < b,- BinaryOp::LessThanEquals => a <= b,- _ => unreachable!("outer match arm only matches comparison operators"),- };- Some(generator.add_constant_boolean(result))- }- BinaryOp::LooselyEquals => {- let result = try_constant_loosely_equals(lhs_const, rhs_const)?;- Some(generator.add_constant_boolean(result))- }- BinaryOp::LooselyInequals => {- let result = try_constant_loosely_equals(lhs_const, rhs_const)?;- Some(generator.add_constant_boolean(!result))- }- BinaryOp::BitwiseAnd => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number((to_int32(a) & to_int32(b)) as f64))- }- BinaryOp::BitwiseOr => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number((to_int32(a) | to_int32(b)) as f64))- }- BinaryOp::BitwiseXor => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number((to_int32(a) ^ to_int32(b)) as f64))- }- BinaryOp::LeftShift => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number((to_int32(a) << (to_u32(b) & 0x1f)) as f64))- }- BinaryOp::RightShift => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number((to_int32(a) >> (to_u32(b) & 0x1f)) as f64))- }- BinaryOp::UnsignedRightShift => {- let a = constant_to_number(lhs_const)?;- let b = constant_to_number(rhs_const)?;- Some(generator.add_constant_number((to_u32(a) >> (to_u32(b) & 0x1f)) as f64))- }- _ => None,- }-}--// =============================================================================-// NaN-boxing helpers-// =============================================================================--// NanBoxed Value encoding helpers (ABI-compatible with GC::NanBoxedValue).-// Used by NewPrimitiveArray to encode constant primitive values inline.--fn nanboxed_number(value: f64) -> u64 {- let is_negative_zero = value.to_bits() == nan_box::NEGATIVE_ZERO_BITS;- if value >= i32::MIN as f64 && value <= i32::MAX as f64 && value.trunc() == value && !is_negative_zero {- nan_box::SHIFTED_INT32_TAG | ((value as i32 as u32) as u64)- } else if value.is_nan() {- nan_box::CANON_NAN_BITS- } else {- value.to_bits()- }-}--fn nanboxed_boolean(value: bool) -> u64 {- nan_box::SHIFTED_BOOLEAN_TAG | u64::from(value)-}--fn nanboxed_null() -> u64 {- nan_box::NULL_VALUE-}--fn nanboxed_empty() -> u64 {- nan_box::EMPTY_VALUE-}--#[cfg(test)]-mod tests {- use super::*;-- fn parse_builtin_expression(source: &str, statement_index: usize) -> (crate::compile::ParsedProgram, Expression) {- let source: Vec<u16> = source.encode_utf16().collect();- let parsed = crate::compile::parse_builtin_file(&source);- let scope = match &parsed.program.inner {- StatementKind::Program(data) => data.scope,- _ => unreachable!(),- };- let statement = &parsed.arena.scopes[scope].children[statement_index];- let StatementKind::Expression(expression) = &statement.inner else {- panic!("expected expression statement at index {statement_index}");- };- let expression = *expression.clone();- (parsed, expression)- }-- fn builtin_generator(arena: std::sync::Arc<AstArena>) -> Generator {- let mut generator = Generator::new();- generator.arena = arena;- generator.builtin_abstract_operations_enabled = true;- let block = generator.make_block();- generator.switch_to_basic_block(block);- generator- }-- #[test]- fn constant_fold_compares_well_known_symbols_by_identity() {- let mut generator = Generator::new();- let lhs = generator.add_constant_well_known_symbol(WellKnownSymbolKind::SymbolIterator);- let rhs = generator.add_constant_well_known_symbol(WellKnownSymbolKind::SymbolIterator);-- let result = try_constant_fold_binary(&mut generator, BinaryOp::StrictlyEquals, &lhs, &rhs)- .expect("well-known symbol equality should fold");-- assert!(matches!(- generator.get_constant(&result),- Some(ConstantValue::Boolean(true))- ));- }-- #[test]- fn builtin_intrinsic_lowering_respects_declared_global_shadows() {- let (parsed, expression) = parse_builtin_expression("let ToBoolean; ToBoolean(0);", 1);- let mut generator = builtin_generator(parsed.arena.clone());-- generate_expression(&expression, &mut generator, None).expect("call expression should produce a value");-- let instructions = &generator.basic_blocks[0].instructions;- assert!(- instructions- .iter()- .any(|(instruction, _, _)| matches!(instruction, Instruction::Call { .. }))- );- assert!(- !instructions- .iter()- .any(|(instruction, _, _)| matches!(instruction, Instruction::ToBoolean { .. }))- );- }-- #[test]- #[should_panic(expected = "builtin ToBoolean takes 1 argument(s)")]- fn builtin_intrinsic_lowering_rejects_wrong_argument_count() {- let (parsed, expression) = parse_builtin_expression("ToBoolean(true, false);", 0);- let mut generator = builtin_generator(parsed.arena.clone());-- generate_expression(&expression, &mut generator, None);- }-- #[test]- fn builtin_call_snapshots_callee_before_evaluating_later_arguments() {- let (mut parsed, expression) =- parse_builtin_expression("var target; Call(target, undefined, (target = 2));", 1);- let call = match &expression.inner {- ExpressionKind::Call(call) => call,- _ => unreachable!(),- };- let ExpressionKind::Identifier(target_argument) = call.arguments[0].value.inner else {- unreachable!();- };- let ExpressionKind::Assignment(assignment) = &call.arguments[2].value.inner else {- unreachable!();- };- let AssignmentLhs::Expression(lhs) = &assignment.lhs else {- unreachable!();- };- let ExpressionKind::Identifier(target_assignment) = lhs.inner else {- unreachable!();- };-- let arena = std::sync::Arc::get_mut(&mut parsed.arena).expect("parsed arena should be uniquely owned");- for identifier in [target_argument, target_assignment] {- let identifier = &mut arena.identifiers[identifier];- identifier.local_type = Some(LocalType::Variable);- identifier.local_index = 0;- identifier.is_global = false;- identifier.declaration_kind = None;- }-- let mut generator = builtin_generator(parsed.arena.clone());- generator- .local_variables- .push(crate::bytecode::generator::LocalVariable {- name: ak::Utf16FlyString::from_utf8("target"),- is_lexically_declared: false,- is_initialized_during_declaration_instantiation: true,- is_mutable: true,- scope_range: None,- });- generator.initialized_locals.push(true);-- generate_expression(&expression, &mut generator, None).expect("call expression should produce a value");-- let callee = generator.basic_blocks[0]- .instructions- .iter()- .find_map(|(instruction, _, _)| match instruction {- Instruction::Call { callee, .. } => Some(*callee),- _ => None,- })- .expect("builtin Call should lower to a Call instruction");- assert!(- callee.is_register(),- "callee value must be captured before later arguments run"- );- }-}--// =============================================================================-// Error message utilities-// =============================================================================--/// Intern the base expression as an identifier for error messages like-/// "Cannot access property X on null object Y".-fn intern_base_identifier(generator: &mut Generator, base: &Expression) -> Option<IdentifierTableIndex> {- let arena = generator.arena.clone();- expression_identifier(base, &arena).map(|s| generator.intern_identifier(&s))-}--/// Try to produce a human-readable name for an expression (for error messages).-/// Returns None for expressions that have no meaningful name.-fn expression_identifier(expression: &Expression, arena: &crate::ast::AstArena) -> Option<Utf16String> {- match &expression.inner {- ExpressionKind::Identifier(ident) => Some(arena.name_of(*ident).clone()),- ExpressionKind::StringLiteral(s) => {- let mut result = Utf16String(utf16!("'").to_vec());- result.0.extend_from_slice(s);- result.0.extend_from_slice(utf16!("'"));- Some(result)- }- ExpressionKind::NumericLiteral(n) => Some(crate::host::js_number_to_utf16(*n)),- ExpressionKind::This => Some(Utf16String(utf16!("this").to_vec())),- ExpressionKind::Member(data) => {- let mut s = Utf16String::new();- if let Some(obj_id) = expression_identifier(&data.object, arena) {- s.0.extend_from_slice(&obj_id);- }- if let Some(property_id) = expression_identifier(&data.property, arena) {- if data.computed {- s.0.extend_from_slice(utf16!("["));- s.0.extend_from_slice(&property_id);- s.0.extend_from_slice(utf16!("]"));- } else {- s.0.extend_from_slice(utf16!("."));- s.0.extend_from_slice(&property_id);- }- }- Some(s)- }- _ => None,- }-}--/// Produce a human-readable string for call expression error messages.-/// Unlike expression_identifier, this always produces output for known types-/// (using "<object>" for unrecognized sub-expressions).-fn expression_string_approximation(expression: &Expression, arena: &crate::ast::AstArena) -> Option<Utf16String> {- match &expression.inner {- ExpressionKind::Identifier(ident) => Some(arena.name_of(*ident).clone()),- ExpressionKind::Member(_) => Some(member_to_string_approximation(expression, arena)),- _ => None,- }-}--fn member_to_string_approximation(expression: &Expression, arena: &crate::ast::AstArena) -> Utf16String {- match &expression.inner {- ExpressionKind::Identifier(ident) => arena.name_of(*ident).clone(),- ExpressionKind::Member(data) => {- let mut s = member_to_string_approximation(&data.object, arena);- let property_str = member_to_string_approximation(&data.property, arena);- if data.computed {- s.0.extend_from_slice(utf16!("["));- s.0.extend_from_slice(&property_str);- s.0.extend_from_slice(utf16!("]"));- } else {- s.0.extend_from_slice(utf16!("."));- s.0.extend_from_slice(&property_str);- }- s- }- ExpressionKind::StringLiteral(s) => {- let mut result = Utf16String(utf16!("'").to_vec());- result.0.extend_from_slice(s);- result.0.extend_from_slice(utf16!("'"));- result- }- ExpressionKind::NumericLiteral(n) => crate::host::js_number_to_utf16(*n),- ExpressionKind::This => Utf16String(utf16!("this").to_vec()),- ExpressionKind::PrivateIdentifier(ident) => ident.name.clone(),- _ => Utf16String(utf16!("<object>").to_vec()),- }-}diff --git a/Libraries/LibJS/Rust/src/bytecode/generator.rs b/Libraries/LibJS/Rust/src/bytecode/generator.rsdeleted file mode 100644index f827fbdc98c..00000000000--- a/Libraries/LibJS/Rust/src/bytecode/generator.rs+++ /dev/null@@ -1,2758 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Bytecode generator.-//!-//! This module contains the `Generator` struct which manages all state-//! needed for bytecode generation from the AST.--use std::cell::RefCell;-use std::collections::HashMap;-use std::collections::HashSet;-use std::rc::Rc;--use super::basic_block::BasicBlock;-use super::basic_block::SourceMapEntry;-use super::constant::AbstractOperationKind;-use super::constant::WellKnownSymbolKind;-use super::executable_data::ExecutableData;-use super::instruction::{Instruction, specialize_instruction_sequence};-use super::operand::*;-use crate::ast::AstArena;-use crate::ast::FunctionData;-use crate::ast::FunctionId;-use crate::ast::FunctionTable;-use crate::ast::IdentifierId;-use crate::ast::LocalType;-use crate::ast::Position;-use crate::ast::Utf16String;-use crate::u32_from_usize;-use std::sync::Arc;-use std::sync::atomic::AtomicBool;-use std::sync::atomic::Ordering;--/// Identifies an operand that auto-frees its register when the last-/// clone is dropped.-///-/// Wraps `Rc<ScopedOperandInner>`. When the last `Rc` clone drops-/// and the operand is a non-reserved register, the `Drop` impl-/// returns it to the generator's register pool for reuse.-#[derive(Debug, Clone)]-pub struct ScopedOperand {- pub(crate) inner: std::rc::Rc<ScopedOperandInner>,-}--pub(crate) struct ScopedOperandInner {- operand: Operand,- free_register_pool: Rc<RefCell<Vec<Register>>>,-}--pub struct PendingSharedFunctionData {- pub function_data: Option<Box<FunctionData>>,- pub subtable: Option<FunctionTable>,- pub arena: Option<Arc<AstArena>>,- pub name_override: Option<Utf16String>,- pub class_field_initializer_name: Option<(Utf16String, bool)>,- pub should_eager_compile: bool,- pub precompiled_function: Option<Box<PrecompiledFunction>>,- pub enclosing_environment_scope: Option<Arc<EnclosingEnvironmentScope>>,-}--/// Metadata computed from scope analysis for a SharedFunctionInstanceData.-#[derive(Clone)]-pub struct FunctionSfdMetadata {- pub uses_this: bool,- pub this_value_needs_environment_resolution: bool,- pub function_environment_needed: bool,- pub function_environment_bindings_count: usize,- pub var_environment_bindings_count: usize,- pub might_need_arguments: bool,- pub contains_eval: bool,-}--/// GC-free compiled bytecode for a function that top-level code will immediately invoke.-pub struct PrecompiledFunction {- pub executable: ExecutableData,- pub metadata: FunctionSfdMetadata,-}--#[derive(Clone, Copy)]-pub enum PendingLiteralValueKind {- None,- Number,- BooleanTrue,- BooleanFalse,- Null,- String,-}--pub struct PendingClassElement {- pub kind: u8,- pub is_static: bool,- pub is_private: bool,- pub private_identifier: Option<Utf16String>,- pub shared_function_data_index: Option<u32>,- pub has_initializer: bool,- pub literal_value_kind: PendingLiteralValueKind,- pub literal_value_number: f64,- pub literal_value_string: Option<Utf16String>,-}--pub struct PendingClassBlueprint {- pub name: Option<Utf16String>,- pub source_text_offset: usize,- pub source_text_length: usize,- pub constructor_sfd_index: u32,- pub has_super_class: bool,- pub has_name: bool,- pub elements: Vec<PendingClassElement>,-}--struct EnvironmentCoordinateScope {- bindings: HashMap<ak::Utf16FlyString, u32>,- next_binding_index: u32,- kind: EnvironmentCoordinateScopeKind,- stops_unresolved_lookups: bool,- captured_scope: Option<Arc<EnclosingEnvironmentScope>>,-}--pub struct EnclosingEnvironmentScope {- bindings: HashMap<ak::Utf16FlyString, u32>,- imports: HashMap<ak::Utf16FlyString, u32>,- kind: EnvironmentCoordinateScopeKind,- stops_unresolved_lookups: AtomicBool,- parent: Option<Arc<EnclosingEnvironmentScope>>,-}--impl EnclosingEnvironmentScope {- pub fn for_module_environment(- binding_names: Vec<ak::Utf16FlyString>,- import_names: Vec<ak::Utf16FlyString>,- ) -> Arc<Self> {- fn index_names(names: Vec<ak::Utf16FlyString>) -> HashMap<ak::Utf16FlyString, u32> {- let mut indices = HashMap::with_capacity(names.len());- for name in names {- let index = u32_from_usize(indices.len());- let previous_index = indices.insert(name, index);- debug_assert!(previous_index.is_none());- }- indices- }- Arc::new(Self {- bindings: index_names(binding_names),- imports: index_names(import_names),- kind: EnvironmentCoordinateScopeKind::Static,- stops_unresolved_lookups: AtomicBool::new(false),- parent: None,- })- }-}--pub enum BindingLocation {- Environment(EnvironmentCoordinate),- Import(u32),-}--enum ScopeLookup {- Found(u32),- NotFound,- Unresolvable,-}--fn look_up_in_scope(- name: &ak::Utf16FlyString,- bindings: &HashMap<ak::Utf16FlyString, u32>,- kind: EnvironmentCoordinateScopeKind,- stops_unresolved_lookups: bool,-) -> ScopeLookup {- // Coordinates are only safe through fully-known declarative scopes. If- // any dynamic scope is crossed, preserve the runtime lookup semantics.- if kind == EnvironmentCoordinateScopeKind::Dynamic {- return ScopeLookup::Unresolvable;- }- if let Some(index) = bindings.get(name) {- return ScopeLookup::Found(*index);- }- if stops_unresolved_lookups {- return ScopeLookup::Unresolvable;- }- ScopeLookup::NotFound-}--#[derive(Clone, Copy, PartialEq)]-enum EnvironmentCoordinateScopeKind {- // A declarative environment whose bindings are created by bytecode we emit,- // or by module linking in an order we mirror. The binding indexes are- // therefore known while generating the instruction stream and can be- // embedded in EnvironmentCoordinate operands.- Static,- // An object environment, such as `with`, can intercept any name. Once one- // is between the current point and a binding, resolution must stay dynamic.- Dynamic,-}--const ENVIRONMENT_MODE_LEXICAL: u32 = libjs_abi::EnvironmentMode::Lexical as u32;-const ENVIRONMENT_MODE_VAR: u32 = libjs_abi::EnvironmentMode::Var as u32;--fn should_verify_environment_coordinates() -> bool {- static SHOULD_VERIFY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *SHOULD_VERIFY.get_or_init(|| {- std::env::var_os("LADYBIRD_JS_VERIFY_ENVIRONMENT_COORDINATES").is_some_and(|value| value == "1")- })-}--fn environment_coordinate_to_verify(- instruction: &Instruction,-) -> Option<(IdentifierTableIndex, EnvironmentCoordinate, u32)> {- match instruction {- Instruction::GetBinding { identifier, cache, .. }- | Instruction::GetInitializedBinding { identifier, cache, .. }- | Instruction::GetCalleeAndThisFromEnvironment { identifier, cache, .. }- | Instruction::InitializeLexicalBinding { identifier, cache, .. }- | Instruction::SetLexicalBinding { identifier, cache, .. }- | Instruction::TypeofBinding { identifier, cache, .. } => Some((*identifier, *cache, ENVIRONMENT_MODE_LEXICAL)),- Instruction::InitializeVariableBinding { identifier, cache, .. }- | Instruction::SetVariableBinding { identifier, cache, .. } => {- Some((*identifier, *cache, ENVIRONMENT_MODE_VAR))- }- _ => None,- }-}--impl std::fmt::Debug for ScopedOperandInner {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(f, "ScopedOperandInner({:?})", self.operand)- }-}--impl Drop for ScopedOperandInner {- fn drop(&mut self) {- if self.operand.is_register() && self.operand.index() >= Register::RESERVED_COUNT {- self.free_register_pool- .borrow_mut()- .push(Register(self.operand.index()));- }- }-}--impl ScopedOperand {- pub fn operand(&self) -> Operand {- self.inner.operand- }-}--impl PartialEq for ScopedOperand {- fn eq(&self, other: &Self) -> bool {- self.inner.operand == other.inner.operand- }-}--pub use crate::ast::FunctionKind;--/// Block boundary types for unwind tracking.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum BlockBoundaryType {- Break,- Continue,- ReturnToFinally,- LeaveFinally,- LeaveLexicalEnvironment,-}--/// A break/continue scope with its target label and language labels.-pub struct LabelableScope {- pub bytecode_target: Label,- pub language_label_set: Vec<Utf16String>,- pub completion_register: Option<ScopedOperand>,-}--/// Codegen-time state for a try/finally scope.-///-/// Stored in `Generator::finally_contexts` Vec, referenced by index.-/// This avoids the deep-clone issues of an owned `Box` parent chain.-pub struct FinallyContext {- pub completion_type: ScopedOperand,- pub completion_value: ScopedOperand,- pub finally_body: Label,- pub exception_preamble: Label,- pub parent_index: Option<usize>,- pub registered_jumps: Vec<FinallyJump>,- pub next_jump_index: i32,- pub lexical_environment_at_entry: Option<ScopedOperand>,- pub saved_unwind_handler: Option<Label>,-}--impl FinallyContext {- pub const NORMAL: i32 = 0;- pub const THROW: i32 = 1;- pub const RETURN: i32 = 2;- pub const FIRST_JUMP_INDEX: i32 = 3;-}--/// The kind of a disposable resource, as the hint operand of AddDisposableResource encodes it.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u32)]-pub enum DisposableResourceKind {- SyncDispose = 0,- AsyncDispose = 1,-}--/// A break/continue target registered with a FinallyContext.-pub struct FinallyJump {- pub index: i32,- pub target: Label,-}--/// A local variable name with metadata.-pub struct LocalVariable {- pub name: ak::Utf16FlyString,- pub is_lexically_declared: bool,- pub is_initialized_during_declaration_instantiation: bool,- pub is_mutable: bool,- pub scope_range: Option<crate::ast::SourceRange>,-}--/// The bytecode generator.-///-/// Manages all state needed for compiling an AST into bytecode.-pub struct Generator {- // --- Basic block management ---- pub basic_blocks: Vec<BasicBlock>,- current_block_index: Label,-- // --- Register allocation ---- next_register: u32,- free_register_pool: Rc<RefCell<Vec<Register>>>,-- // --- Constant pool ---- pub constants: Vec<ConstantValue>,-- // Cached constants for deduplication- true_constant: Option<ScopedOperand>,- false_constant: Option<ScopedOperand>,- null_constant: Option<ScopedOperand>,- undefined_constant: Option<ScopedOperand>,- empty_constant: Option<ScopedOperand>,- int32_constants: HashMap<i32, ScopedOperand>,- double_constants: HashMap<u64, ScopedOperand>,- string_constants: HashMap<Utf16String, ScopedOperand>,-- // --- String/identifier/property tables (with deduplication) ---- pub string_table: Vec<ak::Utf16FlyString>,- string_table_index: HashMap<ak::Utf16FlyString, StringTableIndex>,- pub identifier_table: Vec<ak::Utf16FlyString>,- identifier_table_index: HashMap<ak::Utf16FlyString, IdentifierTableIndex>,- pub property_key_table: Vec<ak::Utf16FlyString>,- property_key_table_index: HashMap<ak::Utf16FlyString, PropertyKeyTableIndex>,-- // --- Scope/unwind state ---- pub boundaries: Vec<BlockBoundaryType>,- pub continuable_scopes: Vec<LabelableScope>,- pub breakable_scopes: Vec<LabelableScope>,- pub pending_labels: Vec<Utf16String>,- pub lexical_environment_register_stack: Vec<ScopedOperand>,- // Mirrors lexical_environment_register_stack for environments whose binding- // layout is known to codegen. This lets us emit immutable coordinates- // instead of runtime-updated caches in common lexical lookup instructions.- environment_coordinate_scope_stack: Vec<EnvironmentCoordinateScope>,- // `var` binding instructions start from vm.variable_environment(), not the- // current lexical environment. Keep a separate anchor so a var write inside- // a nested block does not accidentally count the block as a hop.- variable_environment_coordinate_scope_index: Option<usize>,- // A non-strict direct eval can add `var` bindings to the variable- // environment at runtime, so a name it lacks cannot resolve to any outer- // environment.- pub contains_direct_call_to_eval_in_non_strict_mode: bool,- pub enclosing_environment_scope: Option<Arc<EnclosingEnvironmentScope>>,- verify_environment_coordinates: bool,- pub home_objects: Vec<ScopedOperand>,-- // --- Finally context ---- // FinallyContext objects are stored in this Vec and referenced by index.- // This avoids the deep-clone issues of an owned Box parent chain.- pub finally_contexts: Vec<FinallyContext>,- pub current_finally_context: Option<usize>,- /// The [[DisposableResourceStack]] of the innermost scope that has `using` or `await using` declarations.- pub current_disposable_resource_stack: Option<ScopedOperand>,-- // --- Various counters ---- pub next_property_lookup_cache: u32,- pub next_global_variable_cache: u32,- pub next_environment_coordinate_cache: u32,- pub next_template_object_cache: u32,- pub next_object_shape_cache: u32,- pub next_object_property_iterator_cache: u32,- pub next_environment_shape_cache: u32,- pub next_arith_feedback: u32,- pub next_value_feedback: u32,- pub next_call_feedback: u32,- pub next_keyed_feedback: u32,-- // --- Codegen state ---- pub strict: bool,- pub this_value_needs_environment_resolution: bool,- pub enclosing_function_kind: FunctionKind,- pub local_variables: Vec<LocalVariable>,- pub argument_variable_names: Vec<ak::Utf16FlyString>,- pub initialized_locals: Vec<bool>,- pub initialized_arguments: Vec<bool>,- /// Lexically declared locals with a TDZ check, for which the store that empties them where their scope starts is- /// kept.- pub tdz_checked_locals: Vec<bool>,-- /// When set, function/class expressions will use this as their `.name`.- /// Set by assignment/declaration codegen, consumed by function expression codegen.- pub pending_lhs_name: Option<IdentifierTableIndex>,- /// A property key that the next anonymous class expression is named with, as NamedEvaluation of a value whose- /// property name is computed.- pub pending_computed_class_name: Option<ScopedOperand>,-- // Source location tracking- pub current_source_start: Position,- pub current_source_end: Position,-- // --- Completion register ---- pub current_completion_register: Option<ScopedOperand>,- pub must_propagate_completion: bool,-- // --- Accumulator and this ---- accumulator: ScopedOperand,- this_value: ScopedOperand,-- // --- Shared function data ---- // Pending descriptors for SharedFunctionInstanceData objects. These are- // materialized by the runtime so bytecode generation can run without- // allocating GC cells.- pub shared_function_data: Vec<PendingSharedFunctionData>,- pub eager_compile_function_ids: HashSet<FunctionId>,- pub eager_compile_direct_iifes: bool,-- // --- Class blueprints ---- // Pending descriptors for ClassBlueprint objects. Ownership transfers to- // the Executable after materialization.- pub class_blueprints: Vec<PendingClassBlueprint>,-- // --- Length identifier cache ---- pub length_identifier: Option<PropertyKeyTableIndex>,-- // --- Unwind context ---- // When set, newly created basic blocks inherit this handler index.- pub current_unwind_handler: Option<Label>,- pub catch_handler_labels: HashSet<u32>,-- // --- AnnexB function names ---- // Names approved for AnnexB.3.3 hoisting by the scope collector.- // Populated during FDI, checked in switch case codegen.- pub annexb_function_names: HashSet<Utf16String>,-- // --- Builtin abstract operations ---- // When true, calls to known abstract operations (e.g. IsCallable, GetMethod)- // are compiled to specialized bytecode instructions rather than normal calls.- // Used for builtin JS files.- pub builtin_abstract_operations_enabled: bool,-- // --- Source ---- pub source_len: usize,-- // --- Function table ---- // Side table owning all FunctionData from the parser. Codegen- // takes ownership of individual entries via `take()`.- pub function_table: crate::ast::FunctionTable,-- // --- AST arena ---- // Shared (read-only post-parse) storage for identifiers, scopes, and- // interned strings. Cloning is a refcount bump — multiple generators- // (top-level + nested IIFE + lazy children) share the same arena.- pub arena: Arc<AstArena>,-}--impl Generator {- /// Convenience: look up an identifier by ID in this generator's arena.- #[inline]- pub fn identifier(&self, id: IdentifierId) -> &crate::ast::Identifier {- &self.arena.identifiers[id]- }-}--macro_rules! singleton_constant {- ($self:expr_2021, $field:ident, $value:expr_2021) => {{- if let Some(op) = &$self.$field {- return op.clone();- }- let op = $self.append_constant($value);- $self.$field = Some(op.clone());- op- }};-}--macro_rules! next_cache_method {- ($method:ident, $field:ident) => {- pub fn $method(&mut self) -> u32 {- let index = self.$field;- self.$field += 1;- index- }- };-}--/// Feedback slot indices are encoded as u16. Sites beyond the last index share-/// it, which only merges their feedback.-pub const MAX_FEEDBACK_SLOT_COUNT: u32 = u16::MAX as u32 + 1;--macro_rules! next_feedback_slot_method {- ($method:ident, $field:ident) => {- pub fn $method(&mut self) -> u16 {- let index = u16::try_from(self.$field).unwrap_or(u16::MAX);- self.$field = (self.$field + 1).min(MAX_FEEDBACK_SLOT_COUNT);- index- }- };-}--macro_rules! define_intern_method {- ($method_name:ident, $index_type:ident, $table:ident, $cache:ident) => {- pub fn $method_name(&mut self, s: &[u16]) -> $index_type {- let key = ak::Utf16FlyString::from_utf16(s);- if let Some(&index) = self.$cache.get(&key) {- return index;- }- let index = $index_type(u32_from_usize(self.$table.len()));- self.$table.push(key.clone());- self.$cache.insert(key, index);- index- }- };-}--impl Default for Generator {- fn default() -> Self {- Self::new()- }-}--impl Generator {- /// Create a new bytecode generator.- pub fn new() -> Self {- let free_register_pool = Rc::new(RefCell::new(Vec::new()));-- Self {- basic_blocks: Vec::new(),- current_block_index: Label(0),- next_register: Register::RESERVED_COUNT,- constants: Vec::new(),- true_constant: None,- false_constant: None,- null_constant: None,- undefined_constant: None,- empty_constant: None,- int32_constants: HashMap::new(),- double_constants: HashMap::new(),- string_constants: HashMap::new(),- string_table: Vec::new(),- string_table_index: HashMap::new(),- identifier_table: Vec::new(),- identifier_table_index: HashMap::new(),- property_key_table: Vec::new(),- property_key_table_index: HashMap::new(),- boundaries: Vec::new(),- continuable_scopes: Vec::new(),- breakable_scopes: Vec::new(),- pending_labels: Vec::new(),- lexical_environment_register_stack: Vec::new(),- environment_coordinate_scope_stack: Vec::new(),- variable_environment_coordinate_scope_index: None,- contains_direct_call_to_eval_in_non_strict_mode: false,- enclosing_environment_scope: None,- verify_environment_coordinates: should_verify_environment_coordinates(),- home_objects: Vec::new(),- finally_contexts: Vec::new(),- current_finally_context: None,- current_disposable_resource_stack: None,- next_property_lookup_cache: 0,- next_global_variable_cache: 0,- next_environment_coordinate_cache: 0,- next_template_object_cache: 0,- next_object_shape_cache: 0,- next_object_property_iterator_cache: 0,- next_environment_shape_cache: 0,- next_arith_feedback: 0,- next_value_feedback: 0,- next_call_feedback: 0,- next_keyed_feedback: 0,- strict: false,- this_value_needs_environment_resolution: true,- enclosing_function_kind: FunctionKind::Normal,- local_variables: Vec::new(),- argument_variable_names: Vec::new(),- initialized_locals: Vec::new(),- initialized_arguments: Vec::new(),- tdz_checked_locals: Vec::new(),- pending_lhs_name: None,- pending_computed_class_name: None,- current_source_start: Position {- line: 0,- column: 0,- offset: 0,- },- current_source_end: Position {- line: 0,- column: 0,- offset: 0,- },- current_completion_register: None,- must_propagate_completion: false,- accumulator: ScopedOperand {- inner: Rc::new(ScopedOperandInner {- operand: Operand::register(Register::ACCUMULATOR),- free_register_pool: free_register_pool.clone(),- }),- },- this_value: ScopedOperand {- inner: Rc::new(ScopedOperandInner {- operand: Operand::register(Register::THIS_VALUE),- free_register_pool: free_register_pool.clone(),- }),- },- shared_function_data: Vec::new(),- eager_compile_function_ids: HashSet::new(),- eager_compile_direct_iifes: false,- class_blueprints: Vec::new(),- length_identifier: None,- current_unwind_handler: None,- catch_handler_labels: HashSet::new(),- annexb_function_names: HashSet::new(),- builtin_abstract_operations_enabled: false,- source_len: 0,- function_table: crate::ast::FunctionTable::new(),- arena: Arc::new(AstArena::new()),- free_register_pool,- }- }-- // --- Function kind queries ----- pub fn is_in_generator_function(&self) -> bool {- matches!(- self.enclosing_function_kind,- FunctionKind::Generator | FunctionKind::AsyncGenerator- )- }-- pub fn is_in_async_function(&self) -> bool {- matches!(- self.enclosing_function_kind,- FunctionKind::Async | FunctionKind::AsyncGenerator- )- }-- pub fn is_in_async_generator_function(&self) -> bool {- self.enclosing_function_kind == FunctionKind::AsyncGenerator- }-- pub fn is_in_generator_or_async_function(&self) -> bool {- self.enclosing_function_kind != FunctionKind::Normal- }-- pub fn is_in_finalizer(&self) -> bool {- self.boundaries.contains(&BlockBoundaryType::LeaveFinally)- }-- // --- Register management ----- /// Allocate a new register (or reuse a freed one).- pub fn allocate_register(&mut self) -> ScopedOperand {- let reg = {- let mut pool = self.free_register_pool.borrow_mut();- match pool.pop() {- Some(r) => r,- None => {- let r = Register(self.next_register);- self.next_register += 1;- r- }- }- };- self.scoped_operand(Operand::register(reg))- }-- /// Get a ScopedOperand for a local variable.- pub fn local(&mut self, index: u32) -> ScopedOperand {- self.scoped_operand(Operand::local(index))- }-- /// Resolve a local binding (argument or variable) to a ScopedOperand.- pub fn resolve_local(&mut self, index: u32, local_type: LocalType) -> ScopedOperand {- match local_type {- LocalType::Argument => self.scoped_operand(Operand::argument(index)),- LocalType::Variable => self.local(index),- }- }-- /// Get the accumulator register.- pub fn accumulator(&self) -> ScopedOperand {- self.accumulator.clone()- }-- /// Get the this_value register.- pub fn this_value(&self) -> ScopedOperand {- self.this_value.clone()- }-- /// Get the exception register as a raw Operand (not ScopedOperand since- /// it's a fixed register that should not be freed).- pub fn exception_operand(&self) -> Operand {- Operand::register(Register::EXCEPTION)- }-- /// Copy a local variable into a fresh register to prevent later- /// side effects from changing its value. Returns the operand unchanged- /// if it is not a local.- pub fn copy_if_needed_to_preserve_evaluation_order(&mut self, operand: &ScopedOperand) -> ScopedOperand {- match operand.operand().operand_type() {- OperandType::Register | OperandType::Constant => operand.clone(),- OperandType::Local | OperandType::Argument => {- let reg = self.allocate_register();- self.emit_mov(®, operand);- reg- }- }- }-- pub fn scoped_operand(&mut self, operand: Operand) -> ScopedOperand {- ScopedOperand {- inner: Rc::new(ScopedOperandInner {- operand,- free_register_pool: self.free_register_pool.clone(),- }),- }- }-- // --- Constant pool ----- fn append_constant(&mut self, value: ConstantValue) -> ScopedOperand {- let index = u32_from_usize(self.constants.len());- self.constants.push(value);- self.scoped_operand(Operand::constant(index))- }-- pub fn add_constant_number(&mut self, value: f64) -> ScopedOperand {- // Deduplicate i32 values (but not -0.0, which has distinct semantics from +0.0)- if value.fract() == 0.0- && value >= i32::MIN as f64- && value <= i32::MAX as f64- && value.to_bits() != (-0.0_f64).to_bits()- {- let as_i32 = value as i32;- if let Some(op) = self.int32_constants.get(&as_i32) {- return op.clone();- }- let op = self.append_constant(ConstantValue::Number(value));- self.int32_constants.insert(as_i32, op.clone());- return op;- }- // Deduplicate double values by their bit representation- let as_bits = value.to_bits();- if let Some(op) = self.double_constants.get(&as_bits) {- return op.clone();- }- let op = self.append_constant(ConstantValue::Number(value));- self.double_constants.insert(as_bits, op.clone());- op- }-- pub fn add_constant_boolean(&mut self, value: bool) -> ScopedOperand {- if value {- singleton_constant!(self, true_constant, ConstantValue::Boolean(true))- } else {- singleton_constant!(self, false_constant, ConstantValue::Boolean(false))- }- }-- pub fn add_constant_null(&mut self) -> ScopedOperand {- singleton_constant!(self, null_constant, ConstantValue::Null)- }-- pub fn add_constant_undefined(&mut self) -> ScopedOperand {- singleton_constant!(self, undefined_constant, ConstantValue::Undefined)- }-- pub fn add_constant_empty(&mut self) -> ScopedOperand {- singleton_constant!(self, empty_constant, ConstantValue::Empty)- }-- pub fn add_constant_string(&mut self, value: Utf16String) -> ScopedOperand {- if let Some(op) = self.string_constants.get(&value) {- return op.clone();- }- let op = self.append_constant(ConstantValue::String(value.clone()));- self.string_constants.insert(value, op.clone());- op- }-- pub fn add_constant_bigint(&mut self, value: String) -> ScopedOperand {- self.append_constant(ConstantValue::BigInt(value))- }-- pub fn add_constant_well_known_symbol(&mut self, symbol: WellKnownSymbolKind) -> ScopedOperand {- self.append_constant(ConstantValue::WellKnownSymbol(symbol))- }-- pub fn add_constant_abstract_operation(&mut self, operation: AbstractOperationKind) -> ScopedOperand {- self.append_constant(ConstantValue::AbstractOperation(operation))- }-- /// Get the constant value for a constant operand.- pub fn get_constant(&self, operand: &ScopedOperand) -> Option<&ConstantValue> {- if operand.operand().is_constant() {- self.constants.get(operand.operand().index() as usize)- } else {- None- }- }-- // --- Table interning ----- define_intern_method!(intern_string, StringTableIndex, string_table, string_table_index);- define_intern_method!(- intern_identifier,- IdentifierTableIndex,- identifier_table,- identifier_table_index- );- define_intern_method!(- intern_property_key,- PropertyKeyTableIndex,- property_key_table,- property_key_table_index- );-- /// Convenience: look up a `StringId` in the AST interner and intern the- /// resulting slice into the bytecode identifier table.- pub fn intern_identifier_id(&mut self, id: crate::ast::StringId) -> IdentifierTableIndex {- let arena = self.arena.clone();- let slice = arena.strings[id].as_slice();- self.intern_identifier(slice)- }-- /// Convenience: look up a `StringId` in the AST interner and intern the- /// resulting slice into the bytecode property key table.- pub fn intern_property_key_id(&mut self, id: crate::ast::StringId) -> PropertyKeyTableIndex {- let arena = self.arena.clone();- let slice = arena.strings[id].as_slice();- self.intern_property_key(slice)- }-- /// Convenience: look up a `StringId` in the AST interner and intern the- /// resulting slice into the bytecode string table.- pub fn intern_string_id(&mut self, id: crate::ast::StringId) -> StringTableIndex {- let arena = self.arena.clone();- let slice = arena.strings[id].as_slice();- self.intern_string(slice)- }-- /// If `operand` is a constant string that is not an array index, intern it- /// as a property key and return the index.- pub fn try_constant_string_to_property_key(&mut self, operand: &ScopedOperand) -> Option<PropertyKeyTableIndex> {- if !operand.operand().is_constant() {- return None;- }- let idx = operand.operand().index() as usize;- let s: &[u16] = match self.constants.get(idx) {- Some(ConstantValue::String(s)) if !super::codegen::is_array_index(&s.0) => &s.0,- _ => return None,- };- let owned = ak::Utf16FlyString::from_utf16(s);- if let Some(&key_index) = self.property_key_table_index.get(&owned) {- return Some(key_index);- }- let key_index = PropertyKeyTableIndex(u32_from_usize(self.property_key_table.len()));- self.property_key_table.push(owned.clone());- self.property_key_table_index.insert(owned, key_index);- Some(key_index)- }-- /// Register a pending SharedFunctionInstanceData descriptor and return its index.- pub fn register_shared_function_data(&mut self, mut data: PendingSharedFunctionData) -> u32 {- data.enclosing_environment_scope = self.capture_environment_coordinate_scopes();- let index = u32_from_usize(self.shared_function_data.len());- self.shared_function_data.push(data);- index- }-- pub fn set_class_field_initializer_name(&mut self, index: u32, name: Utf16String, is_private: bool) {- if let Some(data) = self.shared_function_data.get_mut(index as usize) {- data.class_field_initializer_name = Some((name, is_private));- }- }-- /// Register a pending ClassBlueprint descriptor and return its index.- pub fn register_class_blueprint(&mut self, data: PendingClassBlueprint) -> u32 {- let index = u32_from_usize(self.class_blueprints.len());- self.class_blueprints.push(data);- index- }-- // --- Basic block management ----- /// Create a new basic block and return its label.- pub fn make_block(&mut self) -> Label {- let index = self.basic_blocks.len();- let mut block = BasicBlock::new(u32_from_usize(index));-- // Propagate exception handler from active unwind context.- if let Some(handler) = self.current_unwind_handler {- block.handler = Some(handler);- }-- self.basic_blocks.push(block);- Label(u32_from_usize(index))- }-- /// Switch emission to the given basic block.- pub fn switch_to_basic_block(&mut self, label: Label) {- self.current_block_index = label;- }-- /// Get the current basic block's label.- pub fn current_block_index(&self) -> Label {- self.current_block_index- }-- /// Is the current block terminated?- pub fn is_current_block_terminated(&self) -> bool {- self.basic_blocks[self.current_block_index.basic_block_index()].terminated- }-- /// Number of basic blocks.- pub fn basic_block_count(&self) -> usize {- self.basic_blocks.len()- }-- /// Terminate all unterminated blocks with Yield (no continuation).- /// Used for generator and async functions.- pub fn terminate_unterminated_blocks_with_yield(&mut self) {- let block_count = self.basic_block_count();- for i in 0..block_count {- let label = Label(u32_from_usize(i));- if self.is_block_terminated(label) {- continue;- }- self.switch_to_basic_block(label);- let undef = self.add_constant_undefined();- self.emit(Instruction::Yield {- continuation_label: None,- value: undef.operand(),- });- }- }-- /// Is a specific block terminated?- pub fn is_block_terminated(&self, label: Label) -> bool {- self.basic_blocks[label.basic_block_index()].terminated- }-- // --- Instruction emission ----- /// Emit the store that empties a lexically declared local where a scope declaring it starts. Until the code is- /// assembled, it is a move of the local to itself, which nothing else emits (see resolve_tdz_resets).- pub fn emit_tdz_reset(&mut self, index: u32) {- let local = Operand::local(index);- self.emit(Instruction::Mov { dst: local, src: local });- }-- /// Make each TDZ reset of a local that a TDZ check reads store the empty value, and remove the others, which a- /// local only read once it is initialized does not need.- fn resolve_tdz_resets(&mut self) {- let mut empty = None;- for block_index in 0..self.basic_blocks.len() {- let mut instructions = core::mem::take(&mut self.basic_blocks[block_index].instructions);- instructions.retain_mut(|(instruction, _, _)| {- let Instruction::Mov { dst, src } = instruction else {- return true;- };- if dst.operand_type() != OperandType::Local || dst != src {- return true;- }- if !self- .tdz_checked_locals- .get(dst.index() as usize)- .copied()- .unwrap_or(false)- {- return false;- }- *src = *empty.get_or_insert_with(|| self.add_constant_empty().operand());- true- });- self.basic_blocks[block_index].instructions = instructions;- }- }-- /// Emit an instruction to the current basic block.- pub fn emit(&mut self, instruction: Instruction) {- if self.is_current_block_terminated() {- return;- }- if self.verify_environment_coordinates- && let Some((identifier, coordinate, mode)) = environment_coordinate_to_verify(&instruction)- {- self.emit(Instruction::VerifyEnvironmentCoordinate {- identifier,- coordinate,- mode,- });- }- // Keep coordinate scopes in lockstep with the actual declarative- // environment shape. Most bindings are created explicitly, while- // CreateArguments can implicitly create an `arguments` binding.- if let Instruction::CreateVariable {- identifier,- mode,- is_global,- ..- } = &instruction- && !is_global- {- let name = self.identifier_table[identifier.0 as usize].clone();- if *mode == ENVIRONMENT_MODE_LEXICAL {- self.record_environment_binding(name);- } else {- self.record_variable_environment_binding(name);- }- }- if let Instruction::CreateMutableBinding { identifier, .. }- | Instruction::CreateImmutableBinding { identifier, .. } = &instruction- {- let name = self.identifier_table[identifier.0 as usize].clone();- self.record_environment_binding(name);- }- if let Instruction::CreateArguments { dst: None, .. } = &instruction {- self.record_environment_binding(ak::Utf16FlyString::from_utf8("arguments"));- }- let source_map = SourceMapEntry {- bytecode_offset: 0, // filled during flattening- line: self.current_source_start.line,- column: self.current_source_start.column,- };- let block = &mut self.basic_blocks[self.current_block_index.basic_block_index()];- block.append(instruction, source_map, self.strict);- }-- /// Emit a Mov instruction (optimized away if src == dst).- pub fn emit_mov(&mut self, dst: &ScopedOperand, src: &ScopedOperand) {- if dst != src {- self.emit(Instruction::Mov {- dst: dst.operand(),- src: src.operand(),- });- }- }-- pub fn emit_mov_raw(&mut self, dst: Operand, src: Operand) {- // NB: Unlike emit_mov (ScopedOperand version), this does NOT skip- // self-moves and emits unconditionally.- self.emit(Instruction::Mov { dst, src });- }-- /// Emit a conditional jump, with comparison fusion and constant folding.- pub fn emit_jump_if(&mut self, condition: &ScopedOperand, true_target: Label, false_target: Label) {- // OPTIMIZATION: If condition is a constant, emit an unconditional jump.- if let Some(constant) = self.get_constant(condition)- && let Some(is_truthy) = constant_to_boolean(constant)- {- self.emit(Instruction::Jump {- target: if is_truthy { true_target } else { false_target },- });- return;- }-- // OPTIMIZATION: If the condition is a register with ref_count == 1 and the last- // instruction is a comparison whose dst matches condition, fuse into a JumpXxx.- if condition.operand().is_register() && std::rc::Rc::strong_count(&condition.inner) == 1 {- let block = &mut self.basic_blocks[self.current_block_index.basic_block_index()];- if let Some((last_instruction, _, _)) = block.instructions.last() {- let fused = match last_instruction {- Instruction::LessThan {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpLessThan {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::LessThanEquals {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpLessThanEquals {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::GreaterThan {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpGreaterThan {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::GreaterThanEquals {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpGreaterThanEquals {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::LooselyEquals {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpLooselyEquals {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::LooselyInequals {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpLooselyInequals {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::StrictlyEquals {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpStrictlyEquals {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- Instruction::StrictlyInequals {- arith_feedback,- dst,- lhs,- rhs,- } if *dst == condition.operand() => Some(Instruction::JumpStrictlyInequals {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target,- false_target,- }),- _ => None,- };- if let Some(fused_instruction) = fused {- // Remove the comparison instruction and emit the fused jump.- block.instructions.pop();- self.emit(fused_instruction);- return;- }- }- }-- self.emit(Instruction::JumpIf {- condition: condition.operand(),- true_target,- false_target,- });- }-- // --- Cache index allocation ----- next_cache_method!(next_property_lookup_cache, next_property_lookup_cache);- next_cache_method!(next_global_variable_cache, next_global_variable_cache);- next_cache_method!(next_environment_coordinate_cache, next_environment_coordinate_cache);- next_cache_method!(next_template_object_cache, next_template_object_cache);- next_cache_method!(next_object_shape_cache, next_object_shape_cache);- next_cache_method!(next_object_property_iterator_cache, next_object_property_iterator_cache);- next_cache_method!(next_environment_shape_cache, next_environment_shape_cache);- next_feedback_slot_method!(next_arith_feedback, next_arith_feedback);- next_feedback_slot_method!(next_value_feedback, next_value_feedback);- next_feedback_slot_method!(next_call_feedback, next_call_feedback);- next_feedback_slot_method!(next_keyed_feedback, next_keyed_feedback);-- // --- Lexical environment helpers ----- pub fn current_lexical_environment(&mut self) -> ScopedOperand {- self.lexical_environment_register_stack- .last()- .cloned()- .unwrap_or_else(|| self.scoped_operand(Operand::register(Register::SAVED_LEXICAL_ENVIRONMENT)))- }-- pub fn capture_saved_lexical_environment(&mut self) {- let env_reg = self.scoped_operand(Operand::register(Register::SAVED_LEXICAL_ENVIRONMENT));- self.emit(Instruction::GetLexicalEnvironment { dst: env_reg.operand() });- self.push_untracked_lexical_environment(env_reg);- }-- pub fn capture_saved_lexical_environment_with_coordinates(&mut self, has_function_environment: bool) {- let env_reg = self.scoped_operand(Operand::register(Register::SAVED_LEXICAL_ENVIRONMENT));- self.emit(Instruction::GetLexicalEnvironment { dst: env_reg.operand() });- if !has_function_environment {- self.push_untracked_lexical_environment(env_reg);- return;- }- self.push_static_variable_environment(env_reg);- }-- pub fn end_variable_scope(&mut self) {- self.end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);- self.pop_tracked_lexical_environment();- if !self.is_current_block_terminated() {- let parent = self.current_lexical_environment();- self.emit(Instruction::SetLexicalEnvironment {- environment: parent.operand(),- });- }- }-- pub fn allocate_completion_register(&mut self) -> Option<ScopedOperand> {- if self.must_propagate_completion {- let reg = self.allocate_register();- let undef = self.add_constant_undefined();- self.emit_mov(®, &undef);- Some(reg)- } else {- None- }- }-- pub fn push_new_lexical_environment(&mut self, capacity: u32) -> ScopedOperand {- self.push_new_lexical_environment_impl(capacity, false)- }-- pub fn push_new_catch_lexical_environment(&mut self, capacity: u32) -> ScopedOperand {- self.push_new_lexical_environment_impl(capacity, true)- }-- fn push_new_lexical_environment_impl(&mut self, capacity: u32, is_catch_environment: bool) -> ScopedOperand {- let parent = self.current_lexical_environment();- let new_env = self.allocate_register();- let shape_cache = self.next_environment_shape_cache();- self.emit(Instruction::CreateLexicalEnvironment {- dst: new_env.operand(),- parent: parent.operand(),- capacity,- shape_cache,- is_catch_environment,- });- self.push_static_lexical_environment(new_env.clone());- new_env- }-- pub fn push_untracked_lexical_environment(&mut self, environment: ScopedOperand) {- self.lexical_environment_register_stack.push(environment);- }-- pub fn push_static_lexical_environment(&mut self, environment: ScopedOperand) {- self.push_untracked_lexical_environment(environment);- self.push_environment_coordinate_scope(EnvironmentCoordinateScopeKind::Static);- }-- pub fn push_dynamic_lexical_environment(&mut self, environment: ScopedOperand) {- self.push_untracked_lexical_environment(environment);- self.push_environment_coordinate_scope(EnvironmentCoordinateScopeKind::Dynamic);- }-- pub fn push_static_variable_environment(&mut self, environment: ScopedOperand) {- self.push_static_lexical_environment(environment);- let scope_index = self.environment_coordinate_scope_stack.len() - 1;- self.environment_coordinate_scope_stack[scope_index].stops_unresolved_lookups =- self.contains_direct_call_to_eval_in_non_strict_mode;- self.variable_environment_coordinate_scope_index = Some(scope_index);- }-- pub fn pop_untracked_lexical_environment(&mut self) -> Option<ScopedOperand> {- self.lexical_environment_register_stack.pop()- }-- pub fn pop_tracked_lexical_environment(&mut self) -> Option<ScopedOperand> {- self.pop_environment_coordinate_scope();- self.pop_untracked_lexical_environment()- }-- fn push_environment_coordinate_scope(&mut self, kind: EnvironmentCoordinateScopeKind) {- self.environment_coordinate_scope_stack- .push(EnvironmentCoordinateScope {- bindings: HashMap::new(),- next_binding_index: 0,- kind,- stops_unresolved_lookups: false,- captured_scope: None,- });- }-- fn capture_environment_coordinate_scopes(&mut self) -> Option<Arc<EnclosingEnvironmentScope>> {- let mut parent = self.enclosing_environment_scope.clone();- let mut parent_was_captured_again = false;- for scope in &mut self.environment_coordinate_scope_stack {- if parent_was_captured_again || scope.captured_scope.is_none() {- scope.captured_scope = Some(Arc::new(EnclosingEnvironmentScope {- bindings: scope.bindings.clone(),- imports: HashMap::new(),- kind: scope.kind,- stops_unresolved_lookups: AtomicBool::new(scope.stops_unresolved_lookups),- parent,- }));- parent_was_captured_again = true;- }- parent = scope.captured_scope.clone();- }- parent- }-- fn pop_environment_coordinate_scope(&mut self) {- self.environment_coordinate_scope_stack.pop();- }-- /// Records a binding of the innermost environment that an instruction other than CreateVariable creates.- pub fn record_environment_binding_created_elsewhere(&mut self, identifier: IdentifierTableIndex) {- let name = self.identifier_table[identifier.0 as usize].clone();- self.record_environment_binding(name);- }-- fn record_environment_binding(&mut self, name: ak::Utf16FlyString) {- let Some(scope_index) = self.environment_coordinate_scope_stack.len().checked_sub(1) else {- return;- };- self.record_environment_binding_at_scope_index(name, scope_index);- }-- fn record_variable_environment_binding(&mut self, name: ak::Utf16FlyString) {- let Some(scope_index) = self.variable_environment_coordinate_scope_index else {- return;- };- self.record_environment_binding_at_scope_index(name, scope_index);- }-- fn record_environment_binding_at_scope_index(&mut self, name: ak::Utf16FlyString, scope_index: usize) {- let Some(scope) = self.environment_coordinate_scope_stack.get_mut(scope_index) else {- return;- };- if scope.kind == EnvironmentCoordinateScopeKind::Dynamic {- return;- }- debug_assert!(!scope.bindings.contains_key(&name));- scope.bindings.insert(name, scope.next_binding_index);- scope.next_binding_index += 1;- if let Some(captured_scope) = scope.captured_scope.take() {- captured_scope.stops_unresolved_lookups.store(true, Ordering::Relaxed);- }- }-- pub fn environment_coordinate_for(&self, name: &[u16]) -> Option<EnvironmentCoordinate> {- self.environment_coordinate_for_from_scope_index(- &ak::Utf16FlyString::from_utf16(name),- self.environment_coordinate_scope_stack.len().checked_sub(1),- )- }-- fn environment_coordinate_for_from_scope_index(- &self,- name: &ak::Utf16FlyString,- scope_index: Option<usize>,- ) -> Option<EnvironmentCoordinate> {- match self.binding_location_for_from_scope_index(name, scope_index)? {- BindingLocation::Environment(coordinate) => Some(coordinate),- BindingLocation::Import(_) => None,- }- }-- fn binding_location_for_from_scope_index(- &self,- name: &ak::Utf16FlyString,- scope_index: Option<usize>,- ) -> Option<BindingLocation> {- let local_scopes = match scope_index {- Some(scope_index) => &self.environment_coordinate_scope_stack[..=scope_index],- None => &[],- };- let mut hops = 0;- for scope in local_scopes.iter().rev() {- match look_up_in_scope(name, &scope.bindings, scope.kind, scope.stops_unresolved_lookups) {- ScopeLookup::Found(index) => {- return Some(BindingLocation::Environment(EnvironmentCoordinate { hops, index }));- }- ScopeLookup::NotFound => hops += 1,- ScopeLookup::Unresolvable => return None,- }- }- let mut enclosing_scope = self.enclosing_environment_scope.as_deref();- while let Some(scope) = enclosing_scope {- let stops_unresolved_lookups = scope.stops_unresolved_lookups.load(Ordering::Relaxed);- match look_up_in_scope(name, &scope.bindings, scope.kind, stops_unresolved_lookups) {- ScopeLookup::Found(index) => {- return Some(BindingLocation::Environment(EnvironmentCoordinate { hops, index }));- }- ScopeLookup::NotFound => hops += 1,- ScopeLookup::Unresolvable => return None,- }- if let Some(import_index) = scope.imports.get(name) {- return Some(BindingLocation::Import(*import_index));- }- enclosing_scope = scope.parent.as_deref();- }- None- }-- pub fn environment_coordinate_for_identifier(- &self,- identifier: IdentifierTableIndex,- ) -> Option<EnvironmentCoordinate> {- let name = &self.identifier_table[identifier.0 as usize];- self.environment_coordinate_for_from_scope_index(- name,- self.environment_coordinate_scope_stack.len().checked_sub(1),- )- }-- pub fn binding_location_for_identifier(&self, identifier: IdentifierTableIndex) -> Option<BindingLocation> {- let name = &self.identifier_table[identifier.0 as usize];- self.binding_location_for_from_scope_index(name, self.environment_coordinate_scope_stack.len().checked_sub(1))- }-- pub fn variable_environment_coordinate_for_identifier(- &self,- identifier: IdentifierTableIndex,- ) -> Option<EnvironmentCoordinate> {- let name = &self.identifier_table[identifier.0 as usize];- self.environment_coordinate_for_from_scope_index(name, Some(self.variable_environment_coordinate_scope_index?))- }-- // --- Boundary management ----- pub fn start_boundary(&mut self, ty: BlockBoundaryType) {- self.boundaries.push(ty);- }-- pub fn end_boundary(&mut self, ty: BlockBoundaryType) {- assert_eq!(self.boundaries.last(), Some(&ty));- self.boundaries.pop();- }-- // --- Break/continue scope management ----- pub fn begin_breakable_scope(- &mut self,- target: Label,- label_set: Vec<Utf16String>,- completion: Option<ScopedOperand>,- ) {- self.breakable_scopes.push(LabelableScope {- bytecode_target: target,- language_label_set: label_set,- completion_register: completion,- });- self.start_boundary(BlockBoundaryType::Break);- }-- pub fn end_breakable_scope(&mut self) {- self.end_boundary(BlockBoundaryType::Break);- self.breakable_scopes.pop();- }-- pub fn begin_continuable_scope(- &mut self,- target: Label,- label_set: Vec<Utf16String>,- completion: Option<ScopedOperand>,- ) {- self.continuable_scopes.push(LabelableScope {- bytecode_target: target,- language_label_set: label_set,- completion_register: completion,- });- self.start_boundary(BlockBoundaryType::Continue);- }-- pub fn end_continuable_scope(&mut self) {- self.end_boundary(BlockBoundaryType::Continue);- self.continuable_scopes.pop();- }-- pub fn set_current_breakable_scope_completion_register(&mut self, completion: ScopedOperand) {- self.breakable_scopes- .last_mut()- .expect("no active breakable scope")- .completion_register = Some(completion);- }-- pub fn find_breakable_scope(&self, label: Option<&[u16]>) -> Option<&LabelableScope> {- if let Some(label) = label {- self.breakable_scopes- .iter()- .rev()- .find(|s| s.language_label_set.iter().any(|l| l == label))- } else {- self.breakable_scopes.last()- }- }-- pub fn find_continuable_scope(&self, label: Option<&[u16]>) -> Option<&LabelableScope> {- if let Some(label) = label {- self.continuable_scopes- .iter()- .rev()- .find(|s| s.language_label_set.iter().any(|l| l == label))- } else {- self.continuable_scopes.last()- }- }-- // --- FinallyContext support ----- /// Push a new FinallyContext and set it as current. Returns its index.- pub fn push_finally_context(&mut self, mut ctx: FinallyContext) -> usize {- let index = self.finally_contexts.len();- ctx.saved_unwind_handler = self.current_unwind_handler;- self.finally_contexts.push(ctx);- self.current_finally_context = Some(index);- index- }-- /// Check if there is an outer ReturnToFinally boundary between `boundary_index`- /// and the matching break/continue boundary.- fn has_outer_finally_before_target(&self, is_break: bool, boundary_index: usize) -> bool {- for j in (0..boundary_index.saturating_sub(1)).rev() {- let inner = self.boundaries[j];- if (is_break && inner == BlockBoundaryType::Break) || (!is_break && inner == BlockBoundaryType::Continue) {- return false;- }- if inner == BlockBoundaryType::ReturnToFinally {- return true;- }- }- false- }-- /// Register a jump target with the current FinallyContext.- /// Assigns a unique completion_type index and emits code to set it and jump to finally.- pub fn register_jump_in_finally_context(&mut self, target: Label) {- let index = self.current_finally_context.expect("no active finally context");- let ctx = &mut self.finally_contexts[index];- let jump_index = ctx.next_jump_index;- ctx.next_jump_index += 1;- ctx.registered_jumps.push(FinallyJump {- index: jump_index,- target,- });- let completion_type = ctx.completion_type.clone();- let finally_body = ctx.finally_body;- let index_const = self.add_constant_i32(jump_index);- self.emit_mov(&completion_type, &index_const);- self.emit(Instruction::Jump { target: finally_body });- }-- /// For break/continue through nested finally: create a trampoline block.- fn emit_trampoline_through_finally(&mut self) {- let trampoline_block = self.make_block();- self.register_jump_in_finally_context(trampoline_block);- self.switch_to_basic_block(trampoline_block);- // Pop to the parent FinallyContext (simulating the inner finally completing).- let index = self.current_finally_context.expect("no active finally context");- self.current_unwind_handler = self.finally_contexts[index].saved_unwind_handler;- self.current_finally_context = self.finally_contexts[index].parent_index;- }-- /// Generate a break, walking boundaries and handling FinallyContext.- pub fn generate_break(&mut self, label: Option<&[u16]>) {- if let Some(label) = label {- self.generate_labelled_jump(true, label);- } else {- self.generate_scoped_jump(true);- }- }-- /// Generate a continue, walking boundaries and handling FinallyContext.- pub fn generate_continue(&mut self, label: Option<&[u16]>) {- if let Some(label) = label {- self.generate_labelled_jump(false, label);- } else {- self.generate_scoped_jump(false);- }- }-- /// Walk boundaries for unlabelled break/continue.- fn generate_scoped_jump(&mut self, is_break: bool) {- let saved_ctx = self.current_finally_context;- let env_stack_len = self.lexical_environment_register_stack.len();- let mut env_offset = env_stack_len;-- let mut i = self.boundaries.len();- while i > 0 {- i -= 1;- let boundary = self.boundaries[i];- match boundary {- BlockBoundaryType::Break if is_break => {- let target_scope = self.breakable_scopes.last().expect("no active breakable scope");- let target = target_scope.bytecode_target;- let completion = target_scope.completion_register.clone();- if let (Some(cur), Some(tgt)) = (self.current_completion_register.clone(), completion)- && cur != tgt- {- self.emit_mov(&tgt, &cur);- }- self.emit(Instruction::Jump { target });- self.current_finally_context = saved_ctx;- return;- }- BlockBoundaryType::Continue if !is_break => {- let target_scope = self.continuable_scopes.last().expect("no active continuable scope");- let target = target_scope.bytecode_target;- let completion = target_scope.completion_register.clone();- if let (Some(cur), Some(tgt)) = (self.current_completion_register.clone(), completion)- && cur != tgt- {- self.emit_mov(&tgt, &cur);- }- self.emit(Instruction::Jump { target });- self.current_finally_context = saved_ctx;- return;- }- BlockBoundaryType::LeaveLexicalEnvironment => {- env_offset -= 1;- let env = self.lexical_environment_register_stack[env_offset - 1].clone();- self.emit(Instruction::SetLexicalEnvironment {- environment: env.operand(),- });- }- BlockBoundaryType::ReturnToFinally => {- if !self.has_outer_finally_before_target(is_break, i + 1) {- let target_scope = if is_break {- self.breakable_scopes.last().expect("no active breakable scope")- } else {- self.continuable_scopes.last().expect("no active continuable scope")- };- let target = target_scope.bytecode_target;- let completion = target_scope.completion_register.clone();- if let (Some(cur), Some(tgt)) = (self.current_completion_register.clone(), completion)- && cur != tgt- {- self.emit_mov(&tgt, &cur);- }- let mut needs_trampoline = false;- {- let mut j = i;- while j > 0 {- j -= 1;- match self.boundaries[j] {- BlockBoundaryType::LeaveLexicalEnvironment => {- needs_trampoline = true;- }- b if (!is_break && b == BlockBoundaryType::Continue)- || (is_break && b == BlockBoundaryType::Break) =>- {- break;- }- _ => {}- }- }- }- if !needs_trampoline {- self.register_jump_in_finally_context(target);- self.current_finally_context = saved_ctx;- return;- }- let trampoline = self.make_block();- self.register_jump_in_finally_context(trampoline);- self.current_finally_context = saved_ctx;- self.switch_to_basic_block(trampoline);- let mut restore_env_offset = env_offset;- {- let mut j = i;- while j > 0 {- j -= 1;- match self.boundaries[j] {- BlockBoundaryType::LeaveLexicalEnvironment => {- restore_env_offset -= 1;- let env =- self.lexical_environment_register_stack[restore_env_offset - 1].clone();- self.emit(Instruction::SetLexicalEnvironment {- environment: env.operand(),- });- }- b if (!is_break && b == BlockBoundaryType::Continue)- || (is_break && b == BlockBoundaryType::Break) =>- {- break;- }- _ => {}- }- }- }- self.emit(Instruction::Jump { target });- return;- }- self.emit_trampoline_through_finally();- }- _ => {}- }- }- self.current_finally_context = saved_ctx;- }-- /// Walk boundaries for labelled break/continue.- fn generate_labelled_jump(&mut self, is_break: bool, label: &[u16]) {- let saved_ctx = self.current_finally_context;- let env_stack_len = self.lexical_environment_register_stack.len();- let mut env_offset = env_stack_len;-- let jumpable_scopes: Vec<(Label, Vec<Utf16String>, Option<ScopedOperand>)> = if is_break {- self.breakable_scopes- .iter()- .rev()- .map(|s| {- (- s.bytecode_target,- s.language_label_set.clone(),- s.completion_register.clone(),- )- })- .collect()- } else {- self.continuable_scopes- .iter()- .rev()- .map(|s| {- (- s.bytecode_target,- s.language_label_set.clone(),- s.completion_register.clone(),- )- })- .collect()- };-- let mut current_boundary = self.boundaries.len();-- for (target, label_set, completion) in &jumpable_scopes {- while current_boundary > 0 {- current_boundary -= 1;- let boundary = self.boundaries[current_boundary];- match boundary {- BlockBoundaryType::LeaveLexicalEnvironment => {- env_offset -= 1;- let env = self.lexical_environment_register_stack[env_offset - 1].clone();- self.emit(Instruction::SetLexicalEnvironment {- environment: env.operand(),- });- }- BlockBoundaryType::ReturnToFinally => {- if !self.has_outer_finally_before_target(is_break, current_boundary + 1)- && label_set.iter().any(|l| l == label)- {- if let (Some(cur), Some(tgt)) =- (self.current_completion_register.clone(), completion.clone())- && cur != tgt- {- self.emit_mov(&tgt, &cur);- }- let mut needs_trampoline = false;- {- let mut j = current_boundary;- while j > 0 {- j -= 1;- match self.boundaries[j] {- BlockBoundaryType::LeaveLexicalEnvironment => {- needs_trampoline = true;- }- b if (!is_break && b == BlockBoundaryType::Continue)- || (is_break && b == BlockBoundaryType::Break) =>- {- break;- }- _ => {}- }- }- }- if !needs_trampoline {- self.register_jump_in_finally_context(*target);- self.current_finally_context = saved_ctx;- return;- }- let trampoline = self.make_block();- self.register_jump_in_finally_context(trampoline);- self.current_finally_context = saved_ctx;- self.switch_to_basic_block(trampoline);- let mut restore_env_offset = env_offset;- {- let mut j = current_boundary;- while j > 0 {- j -= 1;- match self.boundaries[j] {- BlockBoundaryType::LeaveLexicalEnvironment => {- restore_env_offset -= 1;- let env =- self.lexical_environment_register_stack[restore_env_offset - 1].clone();- self.emit(Instruction::SetLexicalEnvironment {- environment: env.operand(),- });- }- b if (!is_break && b == BlockBoundaryType::Continue)- || (is_break && b == BlockBoundaryType::Break) =>- {- break;- }- _ => {}- }- }- }- self.emit(Instruction::Jump { target: *target });- return;- }- self.emit_trampoline_through_finally();- }- b if (is_break && b == BlockBoundaryType::Break)- || (!is_break && b == BlockBoundaryType::Continue) =>- {- break;- }- _ => {}- }- }-- if label_set.iter().any(|l| l == label) {- if let (Some(cur), Some(tgt)) = (self.current_completion_register.clone(), completion.clone())- && cur != tgt- {- self.emit_mov(&tgt, &cur);- }- self.emit(Instruction::Jump { target: *target });- self.current_finally_context = saved_ctx;- return;- }- }- self.current_finally_context = saved_ctx;- }-- /// Walk the boundary stack and emit SetLexicalEnvironment instructions- /// for each LeaveLexicalEnvironment boundary, restoring the parent- /// environment. Stops at ReturnToFinally since the finally handler- /// takes care of further unwinding.- pub fn perform_needed_unwinds(&mut self) {- let mut env_stack_offset = self.lexical_environment_register_stack.len();- for i in (0..self.boundaries.len()).rev() {- match self.boundaries[i] {- BlockBoundaryType::LeaveLexicalEnvironment => {- env_stack_offset -= 1;- let parent_env = self.lexical_environment_register_stack[env_stack_offset - 1].clone();- self.emit(Instruction::SetLexicalEnvironment {- environment: parent_env.operand(),- });- }- BlockBoundaryType::ReturnToFinally => {- debug_assert_eq!(- self.current_finally_context- .and_then(|index| self.finally_contexts[index].lexical_environment_at_entry.as_ref()),- Some(&self.lexical_environment_register_stack[env_stack_offset - 1])- );- return;- }- _ => {}- }- }- }-- /// Generate a return, routing through FinallyContext if needed.- pub fn generate_return(&mut self, value: &ScopedOperand) {- self.perform_needed_unwinds();- if let Some(index) = self.current_finally_context {- let ctx = &self.finally_contexts[index];- let completion_value = ctx.completion_value.clone();- let completion_type = ctx.completion_type.clone();- let finally_body = ctx.finally_body;- self.emit_mov(&completion_value, value);- let ret_const = self.add_constant_i32(FinallyContext::RETURN);- self.emit_mov(&completion_type, &ret_const);- self.emit(Instruction::Jump { target: finally_body });- } else if self.is_in_generator_or_async_function() {- self.emit(Instruction::Yield {- continuation_label: None,- value: value.operand(),- });- } else {- self.emit(Instruction::Return { value: value.operand() });- }- }-- pub fn forward_completion_to_outer_finally(- &mut self,- outer_index: usize,- completion_type: &ScopedOperand,- completion_value: &ScopedOperand,- ) {- let outer = &self.finally_contexts[outer_index];- let outer_completion_type = outer.completion_type.clone();- let outer_completion_value = outer.completion_value.clone();- let outer_finally_body = outer.finally_body;- let outer_environment = outer.lexical_environment_at_entry.clone();- self.emit_mov(&outer_completion_type, completion_type);- self.emit_mov(&outer_completion_value, completion_value);- if let Some(environment) = outer_environment {- self.emit(Instruction::SetLexicalEnvironment {- environment: environment.operand(),- });- }- self.emit(Instruction::Jump {- target: outer_finally_body,- });- }-- pub fn add_constant_i32(&mut self, val: i32) -> ScopedOperand {- self.add_constant_number(val as f64)- }-- // --- Local variable initialization tracking ----- pub fn is_local_initialized(&self, index: u32) -> bool {- self.initialized_locals.get(index as usize).copied().unwrap_or(false)- }-- pub fn is_local_lexically_declared(&self, index: u32) -> bool {- self.local_variables- .get(index as usize)- .is_some_and(|v| v.is_lexically_declared)- }-- pub fn mark_local_tdz_checked(&mut self, index: u32) {- let index = index as usize;- if index >= self.tdz_checked_locals.len() {- self.tdz_checked_locals.resize(index + 1, false);- }- self.tdz_checked_locals[index] = true;- }-- pub fn mark_local_initialized(&mut self, index: u32) {- let index = index as usize;- if index >= self.initialized_locals.len() {- self.initialized_locals.resize(index + 1, false);- }- self.initialized_locals[index] = true;- }-- pub fn is_argument_initialized(&self, index: u32) -> bool {- self.initialized_arguments.get(index as usize).copied().unwrap_or(false)- }-- pub fn mark_argument_initialized(&mut self, index: u32) {- let index = index as usize;- if index >= self.initialized_arguments.len() {- self.initialized_arguments.resize(index + 1, false);- }- self.initialized_arguments[index] = true;- }-- // --- Compile/assemble/link pipeline ----- /// Compile all basic blocks into a flat bytecode buffer.- ///- /// This performs:- /// 1. Operand rewriting (offset indices for the runtime layout)- /// 2. Compute block byte offsets using encoded_size()- /// 3. Patch labels in typed instructions (block index → byte offset)- /// 4. Encode to bytes and build source map + exception handlers- pub fn assemble(&mut self) -> AssembledBytecode {- let saved_environment = Operand::register(Register::SAVED_LEXICAL_ENVIRONMENT);- let synthetic_load = self.basic_blocks.iter().enumerate().find_map(|(block_index, block)| {- let (instruction_index, (instruction, _, _)) = block- .instructions- .iter()- .enumerate()- .find(|(_, (instruction, _, _))| !matches!(instruction, Instruction::Enter))?;- matches!(- instruction,- Instruction::GetLexicalEnvironment { dst } if *dst == saved_environment- )- .then_some((block_index, instruction_index))- });-- if let Some((load_block_index, load_instruction_index)) = synthetic_load {- let is_restore_of_saved_environment = |instruction: &Instruction| {- matches!(- instruction,- Instruction::SetLexicalEnvironment { environment } if *environment == saved_environment- )- };- let mut saved_environment_is_only_restored = true;- let mut has_restores_of_saved_environment = false;- let mut changes_running_lexical_environment = false;- for (block_index, block) in self.basic_blocks.iter().enumerate() {- for (instruction_index, (instruction, _, _)) in block.instructions.iter().enumerate() {- if block_index == load_block_index && instruction_index == load_instruction_index {- continue;- }- if is_restore_of_saved_environment(instruction) {- has_restores_of_saved_environment = true;- continue;- }- // NB: These are the instructions whose interpreter handlers change the running lexical environment:- // SetLexicalEnvironment in interpreter.flap, and the slow paths in slow_paths/bindings.rs.- // Exception unwinding and generator resumption do not change it.- changes_running_lexical_environment |= matches!(- instruction,- Instruction::SetLexicalEnvironment { .. }- | Instruction::CreateLexicalEnvironment { .. }- | Instruction::CreateVariableEnvironment { .. }- | Instruction::EnterObjectEnvironment { .. }- );- let mut instruction = instruction.clone();- instruction.visit_operands(&mut |operand: &mut Operand| {- if *operand == saved_environment {- saved_environment_is_only_restored = false;- }- });- }- }-- // NB: Restoring an environment that no instruction changes does nothing.- if saved_environment_is_only_restored- && (!has_restores_of_saved_environment || !changes_running_lexical_environment)- {- self.basic_blocks[load_block_index]- .instructions- .remove(load_instruction_index);- for block in &mut self.basic_blocks {- block- .instructions- .retain(|(instruction, _, _)| !is_restore_of_saved_environment(instruction));- }- }- }-- self.resolve_tdz_resets();-- // If any block is unterminated, ensure the undefined constant exists- // for the assembly-time End(undefined) fallthrough. This must happen- // before computing number_of_constants so operand rewriting accounts- // for it.- let has_unterminated = self.basic_blocks.iter().any(|b| !b.terminated);- let undefined_constant_operand = if has_unterminated {- Some(self.add_constant_undefined().operand())- } else {- None- };-- // Select declarative single-instruction specializations and fused- // sequences before operand indices are rewritten away from the- // generator's constant table.- for (block_index, block) in self.basic_blocks.iter_mut().enumerate() {- remove_redundant_movs(&mut block.instructions);-- mark_loop_back_edge(block_index, &mut block.instructions);-- specialize_instructions(&mut block.instructions, &self.constants);- }-- let number_of_registers = self.next_register;- let number_of_locals = u32_from_usize(self.local_variables.len());- let number_of_constants = u32_from_usize(self.constants.len());-- // Phase 1: Operand rewriting- let mut max_argument_index: Option<u32> = None;- for block in &mut self.basic_blocks {- for (instruction, _, _) in &mut block.instructions {- instruction.visit_operands(&mut |op: &mut Operand| {- match op.operand_type() {- OperandType::Register => {} // stays as-is- OperandType::Local => op.offset_index_by(number_of_registers),- OperandType::Constant => {- op.offset_index_by(number_of_registers + number_of_locals);- }- OperandType::Argument => {- let index = op.index();- max_argument_index = Some(max_argument_index.map_or(index, |m| m.max(index)));- op.offset_index_by(number_of_registers + number_of_locals + number_of_constants);- }- }- });- }- }- let number_of_arguments = max_argument_index.map_or(0, |m| m + 1);-- // Phase 2: Compute block byte offsets, applying assembly-time optimizations:- // - Skip Jump-to-next-block- // - Replace Jump-to-Return/End-only-block with inline Return/End- // - Replace JumpIf-where-one-target-is-next-block with JumpTrue/JumpFalse- let num_blocks = self.basic_blocks.len();- let mut block_offsets: Vec<usize> = Vec::with_capacity(num_blocks);- // Per-instruction skip flags: skip_flags[block_index][instruction_index] = replacement action- #[derive(Clone, Copy)]- enum InstAction {- Emit,- Skip,- JumpToReturn(Operand),- JumpToEnd(Operand),- EmitJumpTrue {- condition: Operand,- target: Label,- loop_back_edge: bool,- },- EmitJumpFalse {- condition: Operand,- target: Label,- loop_back_edge: bool,- },- }- let mut actions: Vec<Vec<InstAction>> = Vec::with_capacity(num_blocks);- let mut offset: usize = 0;-- for block_index in 0..num_blocks {- block_offsets.push(offset);- let block = &self.basic_blocks[block_index];- let mut block_actions = Vec::with_capacity(block.instructions.len());- for (instruction, _, _) in &block.instructions {- match instruction {- Instruction::Jump { target } | Instruction::JumpLoop { target } => {- let target_block = target.0 as usize;- // OPTIMIZATION: Don't emit jumps that just jump to the next block.- if target_block == block_index + 1 {- // If this block would become empty, we handle it by- // not advancing offset.- block_actions.push(InstAction::Skip);- continue;- }- // OPTIMIZATION: For jumps to a return-or-end-only block, inline- // the Return/End instead of emitting the Jump.- let target_blk = &self.basic_blocks[target_block];- if target_blk.terminated && target_blk.instructions.len() == 1 {- match &target_blk.instructions[0].0 {- Instruction::Return { value } => {- let replacement = Instruction::Return { value: *value };- block_actions.push(InstAction::JumpToReturn(*value));- offset += replacement.encoded_size();- continue;- }- Instruction::End { value } => {- let replacement = Instruction::End { value: *value };- block_actions.push(InstAction::JumpToEnd(*value));- offset += replacement.encoded_size();- continue;- }- _ => {}- }- }- block_actions.push(InstAction::Emit);- offset += instruction.encoded_size();- }- Instruction::JumpIf {- condition,- true_target,- false_target,- }- | Instruction::JumpIfLoop {- condition,- true_target,- false_target,- } => {- let true_block = true_target.0 as usize;- let false_block = false_target.0 as usize;- let loop_back_edge = matches!(instruction, Instruction::JumpIfLoop { .. });- // OPTIMIZATION: Replace JumpIf where one target is next block- // with JumpTrue or JumpFalse.- if true_block == block_index + 1 {- block_actions.push(InstAction::EmitJumpFalse {- condition: *condition,- target: *false_target,- loop_back_edge,- });- let replacement = Instruction::JumpFalse {- condition: *condition,- target: *false_target,- };- offset += replacement.encoded_size();- continue;- }- if false_block == block_index + 1 {- block_actions.push(InstAction::EmitJumpTrue {- condition: *condition,- target: *true_target,- loop_back_edge,- });- let replacement = Instruction::JumpTrue {- condition: *condition,- target: *true_target,- };- offset += replacement.encoded_size();- continue;- }- block_actions.push(InstAction::Emit);- offset += instruction.encoded_size();- }- _ => {- block_actions.push(InstAction::Emit);- offset += instruction.encoded_size();- }- }- }- // Unterminated blocks get an implicit End(undefined) appended.- if !block.terminated {- let dummy_end = Instruction::End {- value: Operand::constant(0),- };- offset += dummy_end.encoded_size();- }- actions.push(block_actions);- }-- // NB: Empty blocks (from skipped jumps) have the same byte offset as- // the next block, so labels referencing them resolve correctly.-- // Phase 3: Patch labels (block index → byte offset)- for block in &mut self.basic_blocks {- for (instruction, _, _) in &mut block.instructions {- instruction.visit_labels(&mut |label: &mut Label| {- let block_index = label.0 as usize;- label.0 = u32_from_usize(block_offsets[block_index]);- });- }- }-- // Phase 4: Encode to bytes with optimizations applied- let mut bytecode: Vec<u8> = Vec::with_capacity(offset);- let mut source_map: Vec<SourceMapEntry> = Vec::new();- let mut exception_handlers: Vec<ExceptionHandler> = Vec::new();- fn push_source_map_entry(source_map: &mut Vec<SourceMapEntry>, entry: SourceMapEntry) {- let should_push = source_map- .last()- .is_none_or(|previous| previous.line != entry.line || previous.column != entry.column);- if should_push {- source_map.push(entry);- }- }-- // Track which blocks actually produced instructions.- let mut basic_block_start_offsets: Vec<usize> = Vec::with_capacity(num_blocks);-- for (block_index, block) in self.basic_blocks.iter().enumerate() {- basic_block_start_offsets.push(bytecode.len());- let block_start = bytecode.len();- let handler = block.handler;- let block_actions = &actions[block_index];-- for (instruction_index, (instruction, sm, strict)) in block.instructions.iter().enumerate() {- let action = block_actions[instruction_index];- match action {- InstAction::Skip => {- // If this skip makes the block empty, remove it from- // basic_block_start_offsets.- if basic_block_start_offsets.last() == Some(&bytecode.len()) {- basic_block_start_offsets.pop();- }- }- InstAction::Emit => {- let instruction_offset = bytecode.len();- push_source_map_entry(- &mut source_map,- SourceMapEntry {- bytecode_offset: u32_from_usize(instruction_offset),- line: sm.line,- column: sm.column,- },- );- instruction.encode(*strict, &mut bytecode);- }- InstAction::JumpToReturn(value) => {- let instruction_offset = bytecode.len();- push_source_map_entry(- &mut source_map,- SourceMapEntry {- bytecode_offset: u32_from_usize(instruction_offset),- line: sm.line,- column: sm.column,- },- );- let replacement = Instruction::Return { value };- replacement.encode(*strict, &mut bytecode);- }- InstAction::JumpToEnd(value) => {- let instruction_offset = bytecode.len();- push_source_map_entry(- &mut source_map,- SourceMapEntry {- bytecode_offset: u32_from_usize(instruction_offset),- line: sm.line,- column: sm.column,- },- );- let replacement = Instruction::End { value };- replacement.encode(*strict, &mut bytecode);- }- InstAction::EmitJumpFalse {- condition,- mut target,- loop_back_edge,- } => {- // Patch label for the target- let target_block = target.0 as usize;- target.0 = u32_from_usize(block_offsets[target_block]);- let instruction_offset = bytecode.len();- push_source_map_entry(- &mut source_map,- SourceMapEntry {- bytecode_offset: u32_from_usize(instruction_offset),- line: sm.line,- column: sm.column,- },- );- let replacement = if loop_back_edge {- Instruction::JumpFalseLoop { condition, target }- } else {- Instruction::JumpFalse { condition, target }- };- replacement.encode(*strict, &mut bytecode);- }- InstAction::EmitJumpTrue {- condition,- mut target,- loop_back_edge,- } => {- let target_block = target.0 as usize;- target.0 = u32_from_usize(block_offsets[target_block]);- let instruction_offset = bytecode.len();- push_source_map_entry(- &mut source_map,- SourceMapEntry {- bytecode_offset: u32_from_usize(instruction_offset),- line: sm.line,- column: sm.column,- },- );- let replacement = if loop_back_edge {- Instruction::JumpTrueLoop { condition, target }- } else {- Instruction::JumpTrue { condition, target }- };- replacement.encode(*strict, &mut bytecode);- }- }- }-- // Unterminated blocks get an implicit End(undefined).- if !block.terminated {- let mut undef_rewritten = undefined_constant_operand.expect("undefined constant must exist");- undef_rewritten.offset_index_by(number_of_registers + number_of_locals);- let end_instruction = Instruction::End { value: undef_rewritten };- let instruction_offset = bytecode.len();- push_source_map_entry(- &mut source_map,- SourceMapEntry {- bytecode_offset: u32_from_usize(instruction_offset),- line: 0,- column: 0,- },- );- end_instruction.encode(self.strict, &mut bytecode);- }-- // Close exception handler range- if let Some(handler_label) = handler {- exception_handlers.push(ExceptionHandler {- start_offset: u32_from_usize(block_start),- end_offset: u32_from_usize(bytecode.len()),- handler_offset: u32_from_usize(block_offsets[handler_label.basic_block_index()]),- catches_exception: self.catch_handler_labels.contains(&handler_label.0),- });- }- }-- // Merge adjacent exception handlers with the same handler offset.- let mut merged_handlers: Vec<ExceptionHandler> = Vec::new();- for handler in &exception_handlers {- if let Some(last) = merged_handlers.last_mut()- && last.end_offset == handler.start_offset- && last.handler_offset == handler.handler_offset- && last.catches_exception == handler.catches_exception- {- last.end_offset = handler.end_offset;- continue;- }- merged_handlers.push(handler.clone());- }- merged_handlers.sort_by_key(|h| h.start_offset);-- AssembledBytecode {- bytecode,- source_map,- exception_handlers: merged_handlers,- basic_block_start_offsets,- number_of_registers,- number_of_arguments,- }- }-}--/// Result of assembling bytecode from basic blocks.-pub struct AssembledBytecode {- pub bytecode: Vec<u8>,- pub source_map: Vec<SourceMapEntry>,- pub exception_handlers: Vec<ExceptionHandler>,- pub basic_block_start_offsets: Vec<usize>,- pub number_of_registers: u32,- /// One past the highest `Operand::argument` index referenced by any- /// instruction, or 0 if the bytecode never reads an argument. Used by- /// the validator as the upper bound for argument operands.- pub number_of_arguments: u32,-}--/// Exception handler range (with byte offsets, post-linking).-#[derive(Debug, Clone)]-pub struct ExceptionHandler {- pub start_offset: u32,- pub end_offset: u32,- pub handler_offset: u32,- pub catches_exception: bool,-}--/// A typed constant value stored in the constant pool.-///-/// The actual NaN-boxed encoding happens at the FFI boundary when-/// creating the `Bytecode::Executable`.-#[derive(Debug, Clone)]-pub enum ConstantValue {- Number(f64),- Boolean(bool),- Null,- Undefined,- Empty,- String(Utf16String),- BigInt(String),- /// A VM-specific well-known symbol resolved when the Executable is materialized.- WellKnownSymbol(WellKnownSymbolKind),- /// A NativeJavaScriptBackedFunction intrinsic resolved when the Executable is materialized.- AbstractOperation(AbstractOperationKind),-}--/// Convert a constant value to a boolean, matching JS `ToBoolean`.-/// Returns `None` for VM-specific constants whose truthiness cannot be-/// determined until the Executable is materialized.-pub fn constant_to_boolean(value: &ConstantValue) -> Option<bool> {- match value {- ConstantValue::Boolean(b) => Some(*b),- ConstantValue::Null | ConstantValue::Undefined | ConstantValue::Empty => Some(false),- ConstantValue::Number(n) => Some(*n != 0.0 && !n.is_nan()),- ConstantValue::String(s) => Some(!s.is_empty()),- ConstantValue::BigInt(s) => parse_bigint(s).map(|bi| bi != num_bigint::BigInt::ZERO),- ConstantValue::WellKnownSymbol(_) | ConstantValue::AbstractOperation(_) => None,- }-}--/// Parse a BigInt string to an arbitrary-precision BigInt.-/// Handles decimal, 0b binary, 0o octal, and 0x hex prefixes.-pub fn parse_bigint(s: &str) -> Option<num_bigint::BigInt> {- use num_bigint::BigInt;- if s.len() > 2 {- let (prefix, rest) = s.split_at(2);- match prefix {- "0b" | "0B" => return BigInt::parse_bytes(rest.as_bytes(), 2),- "0o" | "0O" => return BigInt::parse_bytes(rest.as_bytes(), 8),- "0x" | "0X" => return BigInt::parse_bytes(rest.as_bytes(), 16),- _ => {}- }- }- s.parse::<BigInt>().ok()-}--/// Use `preferred_dst` if available, otherwise allocate a fresh register.-pub fn choose_dst(generator: &mut Generator, preferred_dst: Option<&ScopedOperand>) -> ScopedOperand {- match preferred_dst {- Some(dst) => dst.clone(),- None => generator.allocate_register(),- }-}--fn specialize_instructions(instructions: &mut Vec<(Instruction, SourceMapEntry, bool)>, constants: &[ConstantValue]) {- let mut read_index = 0;- let mut write_index = 0;- while read_index < instructions.len() {- let mut consumed = 1;- if let Some((specialized, component_count)) = specialize_instruction_sequence(- instructions[read_index..].iter().map(|(instruction, _, _)| instruction),- constants,- ) {- let strict = instructions[read_index].2;- if instructions[read_index..read_index + component_count]- .iter()- .all(|(_, _, component_strict)| *component_strict == strict)- {- instructions[read_index].0 = specialized;- consumed = component_count;- }- }- // Compact once instead of shifting the entire tail after each fused sequence.- instructions.swap(write_index, read_index);- write_index += 1;- read_index += consumed;- }- instructions.truncate(write_index);-}--/// A jump to the same or an earlier block is a loop back edge. Back edges use-/// the loop variants of the jump instructions, which count loop iterations-/// towards the executable's tier-up budget, so that ordinary jumps do not-/// have to check their direction.-fn mark_loop_back_edge(block_index: usize, instructions: &mut [(Instruction, SourceMapEntry, bool)]) {- let Some((instruction, _, _)) = instructions.last_mut() else {- return;- };- let mut is_back_edge = false;- instruction.visit_labels(&mut |label: &mut Label| {- if label.0 as usize <= block_index {- is_back_edge = true;- }- });- if !is_back_edge {- return;- }-- macro_rules! compare_jump_loop {- ($from:ident, $to:ident, $instruction:expr) => {- if let Instruction::$from {- arith_feedback,- lhs,- rhs,- true_target,- false_target,- } = $instruction- {- return Some(Instruction::$to {- arith_feedback: *arith_feedback,- lhs: *lhs,- rhs: *rhs,- true_target: *true_target,- false_target: *false_target,- });- }- };- }-- let loop_variant = |instruction: &Instruction| -> Option<Instruction> {- match instruction {- Instruction::Jump { target } => return Some(Instruction::JumpLoop { target: *target }),- Instruction::JumpIf {- condition,- true_target,- false_target,- } => {- return Some(Instruction::JumpIfLoop {- condition: *condition,- true_target: *true_target,- false_target: *false_target,- });- }- Instruction::JumpTrue { condition, target } => {- return Some(Instruction::JumpTrueLoop {- condition: *condition,- target: *target,- });- }- Instruction::JumpFalse { condition, target } => {- return Some(Instruction::JumpFalseLoop {- condition: *condition,- target: *target,- });- }- _ => {}- }- compare_jump_loop!(JumpLessThan, JumpLessThanLoop, instruction);- compare_jump_loop!(JumpGreaterThan, JumpGreaterThanLoop, instruction);- compare_jump_loop!(JumpLessThanEquals, JumpLessThanEqualsLoop, instruction);- compare_jump_loop!(JumpGreaterThanEquals, JumpGreaterThanEqualsLoop, instruction);- compare_jump_loop!(JumpLooselyEquals, JumpLooselyEqualsLoop, instruction);- compare_jump_loop!(JumpLooselyInequals, JumpLooselyInequalsLoop, instruction);- compare_jump_loop!(JumpStrictlyEquals, JumpStrictlyEqualsLoop, instruction);- compare_jump_loop!(JumpStrictlyInequals, JumpStrictlyInequalsLoop, instruction);- None- };-- if let Some(replacement) = loop_variant(instruction) {- *instruction = replacement;- }-}--fn remove_redundant_movs(instructions: &mut Vec<(Instruction, SourceMapEntry, bool)>) {- let mut write_index = 0;- for read_index in 0..instructions.len() {- if let Instruction::Mov { dst, src } = instructions[read_index].0 {- let same_move = |index: usize| {- matches!(- instructions[index].0,- Instruction::Mov { dst: d, src: s } if d == dst && s == src- )- };- let redundant = (write_index > 0 && same_move(write_index - 1))- || (write_index > 1- && same_move(write_index - 2)- && matches!(- instructions[write_index - 1].0,- Instruction::Mov { dst: middle_dst, .. } if middle_dst != dst && middle_dst != src- ));- if redundant {- continue;- }- }- instructions.swap(write_index, read_index);- write_index += 1;- }- instructions.truncate(write_index);-}--#[cfg(test)]-mod tests {- use super::*;-- fn mov(dst: Operand, src: Operand) -> (Instruction, SourceMapEntry, bool) {- (- Instruction::Mov { dst, src },- SourceMapEntry {- bytecode_offset: 0,- line: 0,- column: 0,- },- false,- )- }-- fn register(index: u32) -> Operand {- Operand::register(Register(index))- }-- #[test]- fn compacts_fused_sequences_with_their_original_source_locations() {- let mut instructions: Vec<_> = (0..3000)- .map(|index| {- let mut instruction = mov(register(index), Operand::constant(0));- instruction.1.line = index;- instruction- })- .collect();- specialize_instructions(&mut instructions, &[ConstantValue::Undefined]);- assert_eq!(instructions.len(), 1000);- for (index, (instruction, source, strict)) in instructions.iter().enumerate() {- assert!(matches!(instruction, Instruction::MovUndefined3 { .. }));- assert_eq!(source.line, index as u32 * 3);- assert!(!strict);- }- }-- #[test]- fn preserves_strict_mode_boundaries_when_compacting_fused_sequences() {- let mut instructions: Vec<_> = (0..7)- .map(|index| {- let mut instruction = mov(register(index), Operand::constant(0));- instruction.1.line = index;- instruction.2 = index >= 3;- instruction- })- .collect();- specialize_instructions(&mut instructions, &[ConstantValue::Undefined]);- assert_eq!(instructions.len(), 3);- assert!(matches!(instructions[0].0, Instruction::MovUndefined3 { .. }));- assert!(matches!(instructions[1].0, Instruction::MovUndefined3 { .. }));- assert!(matches!(instructions[2].0, Instruction::MovSrcUndefined { .. }));- assert_eq!(- instructions- .iter()- .map(|(_, source, strict)| (source.line, *strict))- .collect::<Vec<_>>(),- vec![(0, false), (3, true), (6, true)]- );- }-- #[test]- fn does_not_fuse_a_sequence_that_crosses_strict_mode_boundaries() {- let mut instructions = vec![- mov(register(0), Operand::constant(0)),- mov(register(1), Operand::constant(0)),- mov(register(2), Operand::constant(0)),- ];- instructions[1].2 = true;- specialize_instructions(&mut instructions, &[ConstantValue::Undefined]);- assert_eq!(instructions.len(), 3);- assert!(matches!(instructions[0].0, Instruction::Mov { .. }));- assert!(matches!(instructions[1].0, Instruction::Mov { .. }));- assert!(matches!(instructions[2].0, Instruction::MovSrcUndefined { .. }));- assert_eq!(- instructions.iter().map(|(_, _, strict)| *strict).collect::<Vec<_>>(),- vec![false, true, false]- );- }-- #[test]- fn keeps_a_repeated_mov_after_either_operand_is_clobbered() {- let dst = register(Register::RESERVED_COUNT);- let src = register(Register::RESERVED_COUNT + 1);- let other = register(Register::RESERVED_COUNT + 2);-- for clobbered in [src, dst] {- let mut instructions = vec![mov(dst, src), mov(clobbered, other), mov(dst, src)];-- remove_redundant_movs(&mut instructions);-- assert_eq!(instructions.len(), 3);- }- }-- #[test]- fn removes_a_repeated_mov_after_an_unrelated_mov() {- let dst = register(Register::RESERVED_COUNT);- let src = register(Register::RESERVED_COUNT + 1);- let other_dst = register(Register::RESERVED_COUNT + 2);- let other_src = register(Register::RESERVED_COUNT + 3);- let mut instructions = vec![mov(dst, src), mov(other_dst, other_src), mov(dst, src)];-- remove_redundant_movs(&mut instructions);-- assert_eq!(instructions.len(), 2);- }-- #[test]- fn removes_a_repeated_mov_exposed_by_an_earlier_removal() {- let dst = register(Register::RESERVED_COUNT);- let src = register(Register::RESERVED_COUNT + 1);- let other_dst = register(Register::RESERVED_COUNT + 2);- let other_src = register(Register::RESERVED_COUNT + 3);- let mut instructions = vec![- mov(dst, src),- mov(other_dst, other_src),- mov(other_dst, other_src),- mov(dst, src),- ];-- remove_redundant_movs(&mut instructions);-- assert_eq!(instructions.len(), 2);- }-}diff --git a/Libraries/LibJS/Rust/src/bytecode/mod.rs b/Libraries/LibJS/Rust/src/bytecode/mod.rsindex 9748969870d..f7091e200e5 100644--- a/Libraries/LibJS/Rust/src/bytecode/mod.rs+++ b/Libraries/LibJS/Rust/src/bytecode/mod.rs@@ -29,7 +29,6 @@#[cfg(not(test))]pub mod class_blueprint;-#[path = "codegen/mod.rs"]pub mod codegen;pub mod constant;pub mod constant_fold;diff --git a/Libraries/LibJS/Rust/src/bytecode/validator.rs b/Libraries/LibJS/Rust/src/bytecode/validator.rsdeleted file mode 100644index 630d9177b94..00000000000--- a/Libraries/LibJS/Rust/src/bytecode/validator.rs+++ /dev/null@@ -1,821 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Bytecode validator.-//!-//! Walks a packed bytecode buffer and verifies its structural integrity-//! against a set of bounds (table sizes, register/local/constant/argument-//! counts, cache-array sizes). Intended for two purposes:-//! 1. A debug/sanitizer-build sanity check that runs after every successful-//! bytecode compilation.-//! 2. A safety net for loading bytecode from on-disk caches.-//!-//! Operates on the wire-format bytes only, without round-tripping through-//! the Rust `Instruction` enum, so it works on freshly-encoded as well as-//! freshly-deserialized bytecode.--use super::instruction::NUM_OPCODES;-use super::instruction::instruction_length_from_bytes;-use super::instruction::validate_instruction;--/// Sentinel u32 used by `Operand::INVALID` and by `Optional<*TableIndex>` for-/// "no value".-const INVALID_INDEX_U32: u32 = 0xFFFF_FFFF;--/// Sentinel u32 written into cache fields by the bytecode encoder when no-/// cache slot was reserved.-const NO_CACHE_INDEX: u32 = u32::MAX;--/// Bounds against which bytecode references are checked.-#[repr(C)]-pub struct FFIValidatorBounds {- pub number_of_registers: u32,- pub number_of_locals: u32,- pub number_of_constants: u32,- pub number_of_arguments: u32,- pub identifier_table_size: u32,- pub string_table_size: u32,- pub property_key_table_size: u32,- pub regex_table_size: u32,- pub property_lookup_cache_count: u32,- pub global_variable_cache_count: u32,- pub environment_coordinate_cache_count: u32,- pub template_object_cache_count: u32,- pub object_shape_cache_count: u32,- pub object_property_iterator_cache_count: u32,- pub environment_shape_cache_count: u32,- pub arith_feedback_count: u32,- pub value_feedback_count: u32,- pub call_feedback_count: u32,- pub keyed_feedback_count: u32,- pub class_blueprint_count: u32,- pub shared_function_data_count: u32,- /// Variant counts for the enum types referenced by bytecode declarations- /// fields.- pub completion_type_variant_count: u32,- pub iterator_hint_variant_count: u32,- pub environment_mode_variant_count: u32,- pub put_kind_variant_count: u32,- pub arguments_kind_variant_count: u32,- pub function_name_prefix_variant_count: u32,-}--/// Categorization of validation failures.-#[repr(u32)]-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum ValidationErrorKind {- Ok = 0,- BufferNotAligned = 1,- InstructionMisaligned = 2,- UnknownOpcode = 3,- TruncatedInstruction = 4,- InvalidLength = 5,- OperandOutOfRange = 6,- OperandInvalid = 7,- LabelNotAtInstructionBoundary = 8,- IdentifierIndexOutOfRange = 9,- StringIndexOutOfRange = 10,- PropertyKeyIndexOutOfRange = 11,- RegexIndexOutOfRange = 12,- PropertyLookupCacheIndexOutOfRange = 13,- GlobalVariableCacheIndexOutOfRange = 14,- TemplateObjectCacheIndexOutOfRange = 15,- ObjectShapeCacheIndexOutOfRange = 16,- ObjectPropertyIteratorCacheIndexOutOfRange = 17,- SharedFunctionDataIndexOutOfRange = 18,- ClassBlueprintIndexOutOfRange = 19,- EnumOutOfRange = 20,- BasicBlockOffsetInvalid = 21,- ExceptionHandlerStartInvalid = 22,- ExceptionHandlerEndInvalid = 23,- ExceptionHandlerHandlerInvalid = 24,- ExceptionHandlerRangeInvalid = 25,- SourceMapOffsetInvalid = 26,- EnvironmentCoordinateCacheIndexOutOfRange = 27,- EnvironmentShapeCacheIndexOutOfRange = 28,- ArithFeedbackIndexOutOfRange = 29,- ValueFeedbackIndexOutOfRange = 30,- CallFeedbackIndexOutOfRange = 31,- KeyedFeedbackIndexOutOfRange = 32,-}--/// Detail returned to the caller on validation failure.-#[repr(C)]-#[derive(Debug, Clone, Copy)]-pub struct FFIValidationError {- pub kind: ValidationErrorKind,- pub offset: u32,- pub opcode: u32,-}--/// Layout-compatible mirror of `Bytecode::Executable::ExceptionHandlers`,-/// flattened to plain offsets for FFI.-#[repr(C)]-pub struct FFIExceptionHandlerOffsets {- pub start: u32,- pub end: u32,- pub handler: u32,-}--/// Structural metadata that lives on `Executable` alongside the bytecode-/// itself. Every offset must point at an instruction boundary; some endpoints-/// (handler ranges, source map entries) may also be one-past-the-last-/// instruction so that "end of bytecode" is representable.-#[repr(C)]-pub struct FFIValidatorExtras {- pub basic_block_offsets: *const u32,- pub basic_block_count: usize,- pub exception_handlers: *const FFIExceptionHandlerOffsets,- pub exception_handler_count: usize,- pub source_map_offsets: *const u32,- pub source_map_count: usize,-}--impl FFIValidationError {- pub const fn new(kind: ValidationErrorKind, offset: usize, opcode: u8) -> Self {- Self {- kind,- offset: offset as u32,- opcode: opcode as u32,- }- }-}--/// Borrowed state passed to the generated per-instruction validator.-pub struct ValidationContext<'a> {- pub bounds: &'a FFIValidatorBounds,- pub bytes: &'a [u8],- /// Sorted byte offsets of valid instruction starts, populated by Pass 1.- pub valid_offsets: &'a [u32],-}--#[inline]-pub fn read_u16(bytes: &[u8], at: usize) -> u16 {- u16::from_ne_bytes(bytes[at..at + 2].try_into().unwrap())-}--#[inline]-pub fn read_u32(bytes: &[u8], at: usize) -> u32 {- u32::from_ne_bytes(bytes[at..at + 4].try_into().unwrap())-}--#[inline]-pub fn read_u64(bytes: &[u8], at: usize) -> u64 {- u64::from_ne_bytes(bytes[at..at + 8].try_into().unwrap())-}--#[inline]-pub fn validate_operand(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- // After the assembler runs, operands in the encoded instruction stream- // are flat indices into the runtime [registers | locals | constants |- // arguments] array; the original 3-bit type tag has been zeroed out by- // Operand::offset_index_by. The runtime indexes the combined array- // directly with raw, so the validator just needs to keep raw inside that- // array's bounds.- if raw == INVALID_INDEX_U32 {- return Err(ValidationErrorKind::OperandInvalid);- }- let max = ctx- .bounds- .number_of_registers- .saturating_add(ctx.bounds.number_of_locals)- .saturating_add(ctx.bounds.number_of_constants)- .saturating_add(ctx.bounds.number_of_arguments);- if raw >= max {- return Err(ValidationErrorKind::OperandOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_optional_operand(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == INVALID_INDEX_U32 {- return Ok(());- }- validate_operand(raw, ctx)-}--#[inline]-pub fn validate_label(addr: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if ctx.valid_offsets.binary_search(&addr).is_err() {- return Err(ValidationErrorKind::LabelNotAtInstructionBoundary);- }- Ok(())-}--#[inline]-pub fn validate_identifier_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == INVALID_INDEX_U32 || raw >= ctx.bounds.identifier_table_size {- return Err(ValidationErrorKind::IdentifierIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_optional_identifier_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == INVALID_INDEX_U32 {- return Ok(());- }- if raw >= ctx.bounds.identifier_table_size {- return Err(ValidationErrorKind::IdentifierIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_string_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == INVALID_INDEX_U32 || raw >= ctx.bounds.string_table_size {- return Err(ValidationErrorKind::StringIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_optional_string_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == INVALID_INDEX_U32 {- return Ok(());- }- if raw >= ctx.bounds.string_table_size {- return Err(ValidationErrorKind::StringIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_property_key_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == INVALID_INDEX_U32 || raw >= ctx.bounds.property_key_table_size {- return Err(ValidationErrorKind::PropertyKeyIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_property_lookup_cache_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == NO_CACHE_INDEX {- return Ok(());- }- if raw >= ctx.bounds.property_lookup_cache_count {- return Err(ValidationErrorKind::PropertyLookupCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_global_variable_cache_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == NO_CACHE_INDEX {- return Ok(());- }- if raw >= ctx.bounds.global_variable_cache_count {- return Err(ValidationErrorKind::GlobalVariableCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_environment_coordinate_cache_index(- raw: u32,- ctx: &ValidationContext,-) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.environment_coordinate_cache_count {- return Err(ValidationErrorKind::EnvironmentCoordinateCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_template_object_cache_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == NO_CACHE_INDEX {- return Ok(());- }- if raw >= ctx.bounds.template_object_cache_count {- return Err(ValidationErrorKind::TemplateObjectCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_object_shape_cache_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw == NO_CACHE_INDEX {- return Ok(());- }- if raw >= ctx.bounds.object_shape_cache_count {- return Err(ValidationErrorKind::ObjectShapeCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_object_property_iterator_cache_index(- raw: u32,- ctx: &ValidationContext,-) -> Result<(), ValidationErrorKind> {- if raw == NO_CACHE_INDEX {- return Ok(());- }- if raw >= ctx.bounds.object_property_iterator_cache_count {- return Err(ValidationErrorKind::ObjectPropertyIteratorCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_environment_shape_cache_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.environment_shape_cache_count {- return Err(ValidationErrorKind::EnvironmentShapeCacheIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_arith_feedback_index(raw: u16, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if u32::from(raw) >= ctx.bounds.arith_feedback_count {- return Err(ValidationErrorKind::ArithFeedbackIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_value_feedback_index(raw: u16, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if u32::from(raw) >= ctx.bounds.value_feedback_count {- return Err(ValidationErrorKind::ValueFeedbackIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_call_feedback_index(raw: u16, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if u32::from(raw) >= ctx.bounds.call_feedback_count {- return Err(ValidationErrorKind::CallFeedbackIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_keyed_feedback_index(raw: u16, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if u32::from(raw) >= ctx.bounds.keyed_feedback_count {- return Err(ValidationErrorKind::KeyedFeedbackIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_shared_function_data_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.shared_function_data_count {- return Err(ValidationErrorKind::SharedFunctionDataIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_class_blueprint_index(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.class_blueprint_count {- return Err(ValidationErrorKind::ClassBlueprintIndexOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_completion_type(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.completion_type_variant_count {- return Err(ValidationErrorKind::EnumOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_iterator_hint(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.iterator_hint_variant_count {- return Err(ValidationErrorKind::EnumOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_environment_mode(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.environment_mode_variant_count {- return Err(ValidationErrorKind::EnumOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_put_kind(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.put_kind_variant_count {- return Err(ValidationErrorKind::EnumOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_arguments_kind(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.arguments_kind_variant_count {- return Err(ValidationErrorKind::EnumOutOfRange);- }- Ok(())-}--#[inline]-pub fn validate_function_name_prefix(raw: u32, ctx: &ValidationContext) -> Result<(), ValidationErrorKind> {- if raw >= ctx.bounds.function_name_prefix_variant_count {- return Err(ValidationErrorKind::EnumOutOfRange);- }- Ok(())-}--/// Walk `bytes` and verify the structural integrity of every instruction.-///-/// Pass 1 verifies that the buffer is a tight sequence of well-formed-/// instructions: each opcode is in range, each instruction is properly-/// aligned, the reported length is sane, and the buffer ends exactly on-/// an instruction boundary. The set of valid instruction-start offsets-/// is collected for use in Pass 2.-///-/// Pass 2 dispatches per-opcode field validation.-///-/// Pass 3 validates the structural metadata that travels alongside the-/// bytecode buffer in `Executable` (basic block start offsets, exception-/// handler ranges, source map entries) against the offset set.-pub fn validate_bytecode(- bytes: &[u8],- bounds: &FFIValidatorBounds,- basic_block_offsets: &[u32],- exception_handlers: &[FFIExceptionHandlerOffsets],- source_map_offsets: &[u32],-) -> Result<(), FFIValidationError> {- let mut valid_offsets: Vec<u32> = Vec::with_capacity(bytes.len() / 16);-- let mut at: usize = 0;- while at < bytes.len() {- if !at.is_multiple_of(8) {- return Err(FFIValidationError::new(- ValidationErrorKind::InstructionMisaligned,- at,- 0,- ));- }-- let opcode = bytes[at];- if (opcode as u32) >= NUM_OPCODES {- return Err(FFIValidationError::new(ValidationErrorKind::UnknownOpcode, at, opcode));- }-- let size = instruction_length_from_bytes(opcode, bytes, at)- .map_err(|kind| FFIValidationError::new(kind, at, opcode))?;-- if size == 0 || !size.is_multiple_of(8) {- return Err(FFIValidationError::new(ValidationErrorKind::InvalidLength, at, opcode));- }-- let end = at- .checked_add(size)- .ok_or_else(|| FFIValidationError::new(ValidationErrorKind::InvalidLength, at, opcode))?;- if end > bytes.len() {- return Err(FFIValidationError::new(- ValidationErrorKind::TruncatedInstruction,- at,- opcode,- ));- }-- valid_offsets.push(at as u32);- at = end;- }-- let ctx = ValidationContext {- bounds,- bytes,- valid_offsets: &valid_offsets,- };- for &off_u32 in &valid_offsets {- let off = off_u32 as usize;- let opcode = bytes[off];- validate_instruction(opcode, &ctx, off).map_err(|kind| FFIValidationError::new(kind, off, opcode))?;- }-- // Pass 3: structural metadata.- let bytecode_end = bytes.len() as u32;- let is_instruction_boundary = |offset: u32| -> bool { valid_offsets.binary_search(&offset).is_ok() };- let is_instruction_or_end = |offset: u32| -> bool { offset == bytecode_end || is_instruction_boundary(offset) };-- for &off in basic_block_offsets {- if !is_instruction_boundary(off) {- return Err(FFIValidationError::new(- ValidationErrorKind::BasicBlockOffsetInvalid,- off as usize,- 0,- ));- }- }-- for handler in exception_handlers {- if !is_instruction_or_end(handler.start) {- return Err(FFIValidationError::new(- ValidationErrorKind::ExceptionHandlerStartInvalid,- handler.start as usize,- 0,- ));- }- if !is_instruction_or_end(handler.end) {- return Err(FFIValidationError::new(- ValidationErrorKind::ExceptionHandlerEndInvalid,- handler.end as usize,- 0,- ));- }- if handler.start > handler.end {- return Err(FFIValidationError::new(- ValidationErrorKind::ExceptionHandlerRangeInvalid,- handler.start as usize,- 0,- ));- }- if !is_instruction_boundary(handler.handler) {- return Err(FFIValidationError::new(- ValidationErrorKind::ExceptionHandlerHandlerInvalid,- handler.handler as usize,- 0,- ));- }- }-- for &off in source_map_offsets {- if !is_instruction_or_end(off) {- return Err(FFIValidationError::new(- ValidationErrorKind::SourceMapOffsetInvalid,- off as usize,- 0,- ));- }- }-- Ok(())-}--#[cfg(test)]-mod tests {- use super::super::instruction::OpCode;- use super::*;-- fn permissive_bounds() -> FFIValidatorBounds {- FFIValidatorBounds {- number_of_registers: 8,- number_of_locals: 4,- number_of_constants: 4,- number_of_arguments: 4,- identifier_table_size: 4,- string_table_size: 4,- property_key_table_size: 4,- regex_table_size: 0,- property_lookup_cache_count: 4,- global_variable_cache_count: 4,- environment_coordinate_cache_count: 4,- template_object_cache_count: 4,- object_shape_cache_count: 4,- object_property_iterator_cache_count: 4,- environment_shape_cache_count: 4,- arith_feedback_count: 4,- value_feedback_count: 4,- call_feedback_count: 4,- keyed_feedback_count: 4,- class_blueprint_count: 4,- shared_function_data_count: 4,- completion_type_variant_count: 6,- iterator_hint_variant_count: 2,- environment_mode_variant_count: 2,- put_kind_variant_count: 5,- arguments_kind_variant_count: 2,- function_name_prefix_variant_count: 3,- }- }-- fn validate(bytes: &[u8], bounds: &FFIValidatorBounds) -> Result<(), FFIValidationError> {- validate_bytecode(bytes, bounds, &[], &[], &[])- }-- fn put_u32(bytes: &mut [u8], at: usize, v: u32) {- bytes[at..at + 4].copy_from_slice(&v.to_ne_bytes());- }-- /// Build the smallest possible valid bytecode buffer: a single `End` with- /// `m_value` set to register 0. Useful as a baseline that callers can then- /// corrupt to trigger a specific error.- fn minimal_end_buffer() -> [u8; 8] {- let mut bytes = [0u8; 8];- bytes[0] = OpCode::End as u8;- // m_value at offset 4 stays as 0, which encodes register 0.- bytes- }-- #[test]- fn accepts_minimal_valid_buffer() {- let bytes = minimal_end_buffer();- validate(&bytes, &permissive_bounds()).expect("valid buffer should pass");- }-- #[test]- fn rejects_unknown_opcode() {- let mut bytes = minimal_end_buffer();- bytes[0] = 0xFF;- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::UnknownOpcode);- }-- #[test]- fn rejects_truncated_instruction() {- // End is 8 bytes; lop one off so the walker can't fit the trailing- // operand inside the buffer.- let bytes = &minimal_end_buffer()[..7];- let err = validate(bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::TruncatedInstruction);- }-- #[test]- fn rejects_misaligned_second_instruction() {- // First instruction is End (8 bytes), but we trail a 1-byte payload that- // can't possibly start an instruction at an 8-aligned offset.- let mut bytes = [0u8; 9];- bytes[..8].copy_from_slice(&minimal_end_buffer());- bytes[8] = OpCode::End as u8;- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- // The walker stops when it can't fit a whole 8-byte End at offset 8.- assert_eq!(err.kind, ValidationErrorKind::TruncatedInstruction);- }-- #[test]- fn rejects_undersized_variable_length_instruction() {- // NewArray's fixed prefix is 16 bytes. A shorter m_length must be- // rejected before pass 2 reads fixed fields beyond the buffer.- let mut bytes = [0u8; 8];- bytes[0] = OpCode::NewArray as u8;- put_u32(&mut bytes, 4, 8);-- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::InvalidLength);- }-- #[test]- fn rejects_operand_invalid() {- let mut bytes = minimal_end_buffer();- put_u32(&mut bytes, 4, 0xFFFF_FFFF);- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::OperandInvalid);- }-- #[test]- fn rejects_operand_out_of_range() {- let mut bytes = minimal_end_buffer();- // Bounds total = 8+4+4+4 = 20, so flat index 20 is out of range.- put_u32(&mut bytes, 4, 20);- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::OperandOutOfRange);- }-- #[test]- fn rejects_label_not_at_instruction_boundary() {- // Build [Jump @4, End]: the Jump's target points into the middle of- // its own instruction, which is not an instruction-start offset.- let mut bytes = [0u8; 16];- bytes[0] = OpCode::Jump as u8;- // m_target at offset 4 (the only field on Jump after the header).- put_u32(&mut bytes, 4, 4);- bytes[8] = OpCode::End as u8;- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::LabelNotAtInstructionBoundary);- }-- #[test]- fn accepts_label_at_instruction_boundary() {- let mut bytes = [0u8; 16];- bytes[0] = OpCode::Jump as u8;- put_u32(&mut bytes, 4, 8); // points at the End below- bytes[8] = OpCode::End as u8;- validate(&bytes, &permissive_bounds()).expect("forward jump to End should pass");- }-- #[test]- fn rejects_basic_block_offset_invalid() {- let bytes = minimal_end_buffer();- let bad_basic_blocks: [u32; 1] = [4]; // mid-instruction- let err = validate_bytecode(&bytes, &permissive_bounds(), &bad_basic_blocks, &[], &[]).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::BasicBlockOffsetInvalid);- }-- #[test]- fn rejects_exception_handler_handler_invalid() {- let bytes = minimal_end_buffer();- let handlers = [FFIExceptionHandlerOffsets {- start: 0,- end: 8,- handler: 4, // mid-instruction- }];- let err = validate_bytecode(&bytes, &permissive_bounds(), &[], &handlers, &[]).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::ExceptionHandlerHandlerInvalid);- }-- #[test]- fn rejects_exception_handler_range_invalid() {- let bytes = minimal_end_buffer();- let handlers = [FFIExceptionHandlerOffsets {- start: 8,- end: 0,- handler: 0,- }];- let err = validate_bytecode(&bytes, &permissive_bounds(), &[], &handlers, &[]).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::ExceptionHandlerRangeInvalid);- }-- #[test]- fn accepts_exception_handler_at_end_of_buffer() {- let bytes = minimal_end_buffer();- let handlers = [FFIExceptionHandlerOffsets {- start: 0,- end: 8, // one-past-last is OK for end- handler: 0,- }];- validate_bytecode(&bytes, &permissive_bounds(), &[], &handlers, &[])- .expect("end-of-buffer handler end should pass");- }-- #[test]- fn rejects_source_map_offset_invalid() {- let bytes = minimal_end_buffer();- let bad_source_map: [u32; 1] = [4];- let err = validate_bytecode(&bytes, &permissive_bounds(), &[], &[], &bad_source_map).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::SourceMapOffsetInvalid);- }-- #[test]- fn rejects_cache_index_out_of_range() {- // NewObject layout: header(2) + pad(2) + m_dst(4) + m_cache(4) -> 16 bytes.- let mut bytes = [0u8; 16];- bytes[0] = OpCode::NewObject as u8;- // m_dst at offset 4 stays 0 (register 0).- // m_cache at offset 8: an index well past object_shape_cache_count.- put_u32(&mut bytes, 8, 999_999);-- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::ObjectShapeCacheIndexOutOfRange);- }-- #[test]- fn rejects_object_literal_shape_cache_index_out_of_range() {- // InitObjectLiteralProperty layout: header(2) + pad(2) + m_object(4)- // + m_property(4) + m_src(4) + m_shape_cache_index(4)- // + m_property_slot(4) = 24 bytes.- let mut bytes = [0u8; 24];- bytes[0] = OpCode::InitObjectLiteralProperty as u8;- // m_object, m_property, and m_src stay at 0.- // m_shape_cache_index at offset 16: an index well past- // object_shape_cache_count.- put_u32(&mut bytes, 16, 999_999);-- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::ObjectShapeCacheIndexOutOfRange);- }-- #[test]- fn rejects_environment_coordinate_cache_sentinel() {- // DynamicGetBinding layout: header(2) + pad(2) + m_dst(4)- // + m_identifier(4) + m_cache(4) = 16 bytes.- let mut bytes = [0u8; 16];- bytes[0] = OpCode::DynamicGetBinding as u8;- // m_dst and m_identifier stay at 0.- // m_cache at offset 12: dynamic environment opcodes always index this- // cache, so the no-cache sentinel must not validate.- put_u32(&mut bytes, 12, NO_CACHE_INDEX);-- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::EnvironmentCoordinateCacheIndexOutOfRange);- }-- #[test]- fn rejects_environment_shape_cache_sentinel() {- // CreateLexicalEnvironment layout: header(2) + pad(2) + m_dst(4)- // + m_parent(4) + m_capacity(4) + m_shape_cache(4)- // + m_is_catch_environment(1) + pad(3) = 24 bytes.- let mut bytes = [0u8; 24];- bytes[0] = OpCode::CreateLexicalEnvironment as u8;- // m_dst, m_parent and m_capacity stay at 0.- // m_shape_cache at offset 16: every lexical environment creation site- // owns a cache slot, so the no-cache sentinel must not validate.- put_u32(&mut bytes, 16, NO_CACHE_INDEX);-- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::EnvironmentShapeCacheIndexOutOfRange);- }-- #[test]- fn rejects_enum_out_of_range() {- // SetCompletionType layout: header(2) + pad(2) + m_completion(4) + m_completion_type(4) = 12, padded to 16.- let mut bytes = [0u8; 16];- bytes[0] = OpCode::SetCompletionType as u8;- // m_completion at offset 4 stays as register 0.- // m_completion_type at offset 8: 99 is well past the 6 valid variants.- put_u32(&mut bytes, 8, 99);- let err = validate(&bytes, &permissive_bounds()).unwrap_err();- assert_eq!(err.kind, ValidationErrorKind::EnumOutOfRange);- }-}diff --git a/Libraries/LibJS/Rust/src/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode_cache.rsdeleted file mode 100644index 6542337dc98..00000000000--- a/Libraries/LibJS/Rust/src/bytecode_cache.rs+++ /dev/null@@ -1,3357 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Versioned serialization for fully compiled JavaScript bytecode cache blobs.-//!-//! [`serialize_compiled_program()`] writes a program that was compiled with-//! [`FunctionPrecompileMode::All`](crate::compile::FunctionPrecompileMode::All), and [`decode_blob()`] reads it back-//! into views that borrow strings and bytecode from the blob. A runtime builds its executables from those views once-//! [`DecodedCacheBlob::validate_for_materialization()`] has accepted them.-//!-//! Every blob names the [`BytecodeCacheRuntime`] it was written for, and decoding it for the other one fails, so a-//! profile that a build of either runtime filled is safe to use with the other: its blobs only miss.-//!-//! The format is expressed as small record types with `Encode`-//! implementations. The matching decoder should mirror these records instead-//! of growing a separate procedural parser.--use std::borrow::Cow;-use std::collections::HashMap;-use std::ffi::c_void;-use std::ops::Range;-use std::rc::Rc;--use crate::ast;-use crate::bytecode::basic_block::SourceMapEntry;-use crate::bytecode::constant::AbstractOperationKind;-use crate::bytecode::constant::ConstantTag;-use crate::bytecode::constant::WellKnownSymbolKind;-use crate::bytecode::executable_data::ExecutableCacheCounts;-use crate::bytecode::executable_data::ExecutableData;-use crate::bytecode::generator::ConstantValue;-use crate::bytecode::generator::ExceptionHandler;-use crate::bytecode::generator::FunctionSfdMetadata;-use crate::bytecode::generator::LocalVariable;-use crate::bytecode::generator::MAX_FEEDBACK_SLOT_COUNT;-use crate::bytecode::generator::PendingClassBlueprint;-use crate::bytecode::generator::PendingClassElement;-use crate::bytecode::generator::PendingLiteralValueKind;-use crate::bytecode::generator::PendingSharedFunctionData;-use crate::bytecode::generator::PrecompiledFunction;-use crate::bytecode::validator::FFIExceptionHandlerOffsets;-use crate::bytecode::validator::FFIValidatorBounds;-use crate::bytecode::validator::ValidationErrorKind;-use crate::bytecode::validator::validate_bytecode;-use crate::compile::CompiledProgram;-use crate::compile::CompiledProgramBytecode;-use crate::u32_from_usize;--const MAGIC: &[u8; 8] = b"LBJSBC\0\0";-const FORMAT_VERSION: u32 = 31;-// A blob's instructions are only good for the instruction set they were encoded with; see build.rs.-include!(concat!(env!("OUT_DIR"), "/instruction_set_fingerprint.rs"));-/// The size of the source hash a blob is keyed by.-pub(crate) const SOURCE_HASH_SIZE: usize = 32;-const BYTECODE_ALIGNMENT: usize = 8;-const COMPLETION_TYPE_VARIANT_COUNT: u32 = 6;-const ITERATOR_HINT_VARIANT_COUNT: u32 = 2;-const ENVIRONMENT_MODE_VARIANT_COUNT: u32 = 2;-const PUT_KIND_VARIANT_COUNT: u32 = 5;-const ARGUMENTS_KIND_VARIANT_COUNT: u32 = 2;-const FUNCTION_NAME_PREFIX_VARIANT_COUNT: u32 = 3;--fn source_span_is_valid(start: u32, end: u32, source_len: usize) -> bool {- let start = start as usize;- let end = end as usize;- start <= end && end <= source_len-}--fn source_range_is_valid(offset: usize, length: usize, source_len: usize) -> bool {- offset <= source_len && length <= source_len - offset-}--/// The runtime that materializes the executables of a blob. Both runtimes run the frontend's bytecode, but each turns-/// a blob into executables of its own, so a blob is only accepted by the runtime it was written for.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum BytecodeCacheRuntime {- Cpp,- Rust,-}--impl BytecodeCacheRuntime {- fn tag(self) -> u8 {- match self {- Self::Cpp => b'C',- Self::Rust => b'R',- }- }-}--/// Serializes, for `runtime`, a program compiled with-/// [`FunctionPrecompileMode::All`](crate::compile::FunctionPrecompileMode::All) from source that hashes to-/// `source_hash`.-///-/// # Panics-/// Panics if a function of the program was not precompiled.-pub fn serialize_compiled_program(- compiled: &CompiledProgram,- program_type: ast::ProgramType,- source_hash: &[u8; SOURCE_HASH_SIZE],- runtime: BytecodeCacheRuntime,-) -> Vec<u8> {- let mut encoder = Encoder::new();- CacheBlob {- compiled,- program_type,- source_hash,- runtime,- }- .encode(&mut encoder);- encoder.finish()-}--pub type FreeBytecodeCacheBlobOwner = unsafe extern "C" fn(*mut c_void);--/// What keeps the bytes of a bytecode cache blob alive.-pub enum BytecodeCacheBlobOwner {- /// An embedder's handle on the bytes, which `free_owner` releases once nothing decoded from them needs them- /// anymore.- Foreign {- owner: *mut c_void,- free_owner: FreeBytecodeCacheBlobOwner,- },- /// A copy of bytes that were not aligned for running in place. A Vec, unlike a Box, can be moved while the bytes- /// are borrowed.- Aligned(Vec<u64>),-}--impl Drop for BytecodeCacheBlobOwner {- fn drop(&mut self) {- if let Self::Foreign { owner, free_owner } = self {- // SAFETY: The embedder's release function takes the owner it handed over, once.- unsafe { free_owner(*owner) };- }- }-}--/// Decodes a blob that [`serialize_compiled_program()`] wrote for `expected_runtime` and a program of-/// `expected_program_type`, from source that hashes to `expected_source_hash`.-///-/// Strings and bytecode stay in `bytes`, which `owner` keeps alive for as long as anything decoded from them does.-/// `owner` is released when the blob is rejected as well. Returns `None` for a blob of another format version, runtime,-/// program type or source, and for a malformed one.-///-/// # Safety-/// `bytes` must stay alive and unchanged until `owner` is dropped.-pub unsafe fn decode_blob(- bytes: &[u8],- expected_program_type: ast::ProgramType,- expected_source_hash: &[u8; SOURCE_HASH_SIZE],- expected_runtime: BytecodeCacheRuntime,- owner: BytecodeCacheBlobOwner,-) -> Option<DecodedCacheBlob> {- let mut decoder = Decoder::new(bytes, Some(owner));- let blob = CacheBlob::decode(- &mut decoder,- expected_program_type,- expected_source_hash,- expected_runtime,- )?;- decoder.is_empty().then_some(blob)-}--struct Encoder {- bytes: Vec<u8>,-}--impl Encoder {- fn new() -> Self {- Self { bytes: Vec::new() }- }-- fn finish(self) -> Vec<u8> {- self.bytes- }-- fn byte(&mut self, value: u8) {- self.bytes.push(value);- }-- fn bytes(&mut self, bytes: &[u8]) {- self.bytes.extend_from_slice(bytes);- }-- fn align_to(&mut self, alignment: usize) {- let padding = self.bytes.len().next_multiple_of(alignment) - self.bytes.len();- self.bytes.extend(std::iter::repeat_n(0, padding));- }-- fn align_bytes_payload_to(&mut self, alignment: usize) {- let payload_offset = self.bytes.len() + size_of::<u32>();- let padding = payload_offset.next_multiple_of(alignment) - payload_offset;- self.bytes.extend(std::iter::repeat_n(0, padding));- }-- fn sequence<T>(&mut self, items: &[T], mut encode_item: impl FnMut(&T, &mut Self)) {- u32_from_usize(items.len()).encode(self);- for item in items {- encode_item(item, self);- }- }-}--struct ForeignBytecodeCacheBlob {- data: *const u8,- length: usize,- _owner: BytecodeCacheBlobOwner,-}--struct Decoder<'a> {- bytes: &'a [u8],- offset: usize,- foreign_blob: Option<Rc<ForeignBytecodeCacheBlob>>,-}--impl<'a> Decoder<'a> {- fn new(bytes: &'a [u8], owner: Option<BytecodeCacheBlobOwner>) -> Self {- let foreign_blob = owner.map(|owner| {- Rc::new(ForeignBytecodeCacheBlob {- data: bytes.as_ptr(),- length: bytes.len(),- _owner: owner,- })- });- Self {- bytes,- offset: 0,- foreign_blob,- }- }-- fn is_empty(&self) -> bool {- self.bytes.is_empty()- }-- fn bytes(&mut self, length: usize) -> Option<&'a [u8]> {- if self.bytes.len() < length {- return None;- }-- let (bytes, rest) = self.bytes.split_at(length);- self.bytes = rest;- self.offset = self.offset.checked_add(length)?;- Some(bytes)- }-- fn align_to(&mut self, alignment: usize) -> Option<()> {- let padding = self.offset.next_multiple_of(alignment) - self.offset;- self.bytes(padding)?;- Some(())- }-- fn align_bytes_payload_to(&mut self, alignment: usize) -> Option<()> {- let payload_offset = self.offset.checked_add(size_of::<u32>())?;- let padding = payload_offset.next_multiple_of(alignment) - payload_offset;- self.bytes(padding)?;- Some(())- }-- fn bytecode_bytes(&mut self, length: usize) -> Option<DecodedBytecodeBytes> {- let offset = self.offset;- self.bytes(length)?;- let foreign_blob = self.foreign_blob.as_ref()?;- Some(DecodedBytecodeBytes {- blob: foreign_blob.clone(),- range: offset..offset + length,- })- }-- fn expect_bytes(&mut self, expected: &[u8]) -> Option<()> {- (self.bytes(expected.len())? == expected).then_some(())- }-- fn sequence_values<T>(&mut self, mut decode_item: impl FnMut(&mut Self) -> Option<T>) -> Option<Vec<T>> {- let length: usize = u32::decode(self)?.try_into().ok()?;- // Reject lengths that cannot fit in the remaining blob even for one-byte items, so a- // malformed sidecar with a four-billion element header cannot drag the allocator down.- if length > self.bytes.len() {- return None;- }-- let mut values = Vec::with_capacity(length);- for _ in 0..length {- values.push(decode_item(self)?);- }- Some(values)- }-}--trait Encode {- fn encode(&self, encoder: &mut Encoder);-}--trait Decode: Sized {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self>;-}--impl Encode for bool {- fn encode(&self, encoder: &mut Encoder) {- encoder.byte(*self as u8);- }-}--impl Decode for bool {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(false),- 1 => Some(true),- _ => None,- }- }-}--impl Encode for u8 {- fn encode(&self, encoder: &mut Encoder) {- encoder.byte(*self);- }-}--impl Decode for u8 {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- decoder.bytes(1)?.first().copied()- }-}--impl Encode for u32 {- fn encode(&self, encoder: &mut Encoder) {- encoder.bytes(&self.to_le_bytes());- }-}--impl Decode for u32 {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(u32::from_le_bytes(decoder.bytes(4)?.try_into().ok()?))- }-}--impl Encode for i32 {- fn encode(&self, encoder: &mut Encoder) {- encoder.bytes(&self.to_le_bytes());- }-}--impl Decode for i32 {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(i32::from_le_bytes(decoder.bytes(4)?.try_into().ok()?))- }-}--impl Encode for u64 {- fn encode(&self, encoder: &mut Encoder) {- encoder.bytes(&self.to_le_bytes());- }-}--impl Decode for u64 {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(u64::from_le_bytes(decoder.bytes(8)?.try_into().ok()?))- }-}--impl Encode for usize {- fn encode(&self, encoder: &mut Encoder) {- u64::try_from(*self).expect("usize does not fit in u64").encode(encoder);- }-}--impl Decode for usize {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- u64::decode(decoder)?.try_into().ok()- }-}--impl Encode for f64 {- fn encode(&self, encoder: &mut Encoder) {- encoder.bytes(&self.to_le_bytes());- }-}--impl Decode for f64 {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(f64::from_le_bytes(decoder.bytes(8)?.try_into().ok()?))- }-}--impl Decode for ast::Position {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(Self {- line: u32::decode(decoder)?,- column: u32::decode(decoder)?,- offset: u32::decode(decoder)?,- })- }-}--impl<T: Encode> Encode for Option<T> {- fn encode(&self, encoder: &mut Encoder) {- self.is_some().encode(encoder);- if let Some(value) = self {- value.encode(encoder);- }- }-}--impl<T: Decode> Decode for Option<T> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- if bool::decode(decoder)? {- Some(Some(T::decode(decoder)?))- } else {- Some(None)- }- }-}--impl Decode for ast::Utf16String {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- decoder.align_to(align_of::<u16>())?;- let length: usize = u32::decode(decoder)?.try_into().ok()?;- let bytes = decoder.bytes(length.checked_mul(size_of::<u16>())?)?;- let mut code_units = Vec::with_capacity(length);- for chunk in bytes.as_chunks::<{ size_of::<u16>() }>().0 {- code_units.push(u16::from_le_bytes(*chunk));- }- Some(code_units.into())- }-}--pub(crate) enum DecodedUtf16String {- Owned(ast::Utf16String),- // The surrounding decoded executable keeps the mapped blob alive through its- // DecodedBytecodeBytes. Store only the payload pointer here so large string- // tables do not clone an owner handle for every string.- Foreign { data: *const u16, length: usize },-}--impl Decode for DecodedUtf16String {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- decoder.align_to(align_of::<u16>())?;- let length: usize = u32::decode(decoder)?.try_into().ok()?;- let byte_length = length.checked_mul(size_of::<u16>())?;- let bytes = decoder.bytes(byte_length)?;- if decoder.foreign_blob.is_some() {- debug_assert_eq!((bytes.as_ptr() as usize) % align_of::<u16>(), 0);- return Some(Self::Foreign {- data: bytes.as_ptr().cast(),- length,- });- }-- let mut code_units = Vec::with_capacity(length);- for chunk in bytes.as_chunks::<{ size_of::<u16>() }>().0 {- code_units.push(u16::from_le_bytes(*chunk));- }- Some(Self::Owned(code_units.into()))- }-}--impl From<ast::Utf16String> for DecodedUtf16String {- fn from(value: ast::Utf16String) -> Self {- Self::Owned(value)- }-}--impl DecodedUtf16String {- pub(crate) fn to_vec(&self) -> Vec<u16> {- self.code_units().into_owned()- }-- /// The code units, in place where the blob stores them in the native byte order. A foreign string is only valid- /// while its blob is, so callers only reach one through a record that keeps the blob alive.- fn code_units(&self) -> Cow<'_, [u16]> {- match self {- Self::Owned(value) => Cow::Borrowed(value.as_slice()),- #[cfg(target_endian = "little")]- // SAFETY: The record this string was reached through keeps the blob alive, and the decoder checked that- // the code units lie within it and are aligned.- Self::Foreign { data, length } => Cow::Borrowed(unsafe { ak::slice_from_raw_parts(*data, *length) }),- #[cfg(not(target_endian = "little"))]- // SAFETY: As above.- Self::Foreign { data, length } => Cow::Owned(unsafe {- ak::slice_from_raw_parts(*data, *length)- .iter()- .map(|code_unit| u16::from_le(*code_unit))- .collect()- }),- }- }-- fn to_utf16_string(&self) -> ast::Utf16String {- self.to_vec().into()- }-- fn to_fly_string(&self) -> ak::Utf16FlyString {- ak::Utf16FlyString::from_utf16(&self.code_units())- }-}--struct Bytes<'a>(&'a [u8]);--impl Encode for Bytes<'_> {- fn encode(&self, encoder: &mut Encoder) {- u32_from_usize(self.0.len()).encode(encoder);- encoder.bytes(self.0);- }-}--struct ByteVector;--impl ByteVector {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<u8>> {- let length: usize = u32::decode(decoder)?.try_into().ok()?;- Some(decoder.bytes(length)?.to_vec())- }-}--/// Bytes of a decoded blob, in place, which keep the whole blob alive.-#[derive(Clone)]-pub struct DecodedBytecodeBytes {- blob: Rc<ForeignBytecodeCacheBlob>,- range: Range<usize>,-}--impl DecodedBytecodeBytes {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- let length: usize = u32::decode(decoder)?.try_into().ok()?;- decoder.bytecode_bytes(length)- }-- pub fn as_slice(&self) -> &[u8] {- debug_assert!(self.range.end <= self.blob.length);- // SAFETY: The decoder checked that the range lies within the blob, which the Rc keeps alive.- unsafe { ak::slice_from_raw_parts(self.blob.data.add(self.range.start), self.range.len()) }- }-- fn decoder(&self) -> Decoder<'_> {- Decoder {- bytes: self.as_slice(),- offset: self.range.start,- foreign_blob: Some(self.blob.clone()),- }- }-}--struct DecodedRecordSequence {- count: usize,- bytes: DecodedBytecodeBytes,-}--impl DecodedRecordSequence {- fn encode<T>(encoder: &mut Encoder, items: &[T], mut encode_item: impl FnMut(&T, &mut Encoder)) {- Self::encode_with_alignment(encoder, items, align_of::<u16>(), |item, encoder| {- encode_item(item, encoder);- });- }-- fn encode_with_alignment<T>(- encoder: &mut Encoder,- items: &[T],- alignment: usize,- mut encode_item: impl FnMut(&T, &mut Encoder),- ) {- u32_from_usize(items.len()).encode(encoder);-- let mut payload_encoder = Encoder::new();- for item in items {- encode_item(item, &mut payload_encoder);- }-- encoder.align_bytes_payload_to(alignment);- Bytes(&payload_encoder.finish()).encode(encoder);- }-- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Self::decode_with_alignment(decoder, align_of::<u16>())- }-- fn decode_with_alignment(decoder: &mut Decoder<'_>, alignment: usize) -> Option<Self> {- let count: usize = u32::decode(decoder)?.try_into().ok()?;- decoder.align_bytes_payload_to(alignment)?;- let byte_length: usize = u32::decode(decoder)?.try_into().ok()?;- // Every record currently has at least one byte in the payload. Reject- // impossible counts up front so corrupt cache files cannot ask later- // materialization to reserve huge vectors for tiny payloads.- if count > byte_length {- return None;- }- Some(Self {- count,- bytes: decoder.bytecode_bytes(byte_length)?,- })- }-- fn len(&self) -> usize {- self.count- }-- fn decoder(&self) -> Decoder<'_> {- self.bytes.decoder()- }-}--struct Utf16<'a>(&'a [u16]);--impl Encode for Utf16<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.align_to(align_of::<u16>());- u32_from_usize(self.0.len()).encode(encoder);- for code_unit in self.0 {- encoder.bytes(&code_unit.to_le_bytes());- }- }-}--struct CacheBlob<'a> {- compiled: &'a CompiledProgram,- program_type: ast::ProgramType,- // Fingerprint of the encoded source bytes the blob was generated from. Cache writes happen asynchronously after the- // HTTP response has been served, so the entry on disk may have been replaced for the same (URL, vary key) by the- // time we go to attach the sidecar. Embedding the source hash makes a stale write harmless: a later read whose- // source no longer matches will reject the blob and fall through to source compilation.- source_hash: &'a [u8; SOURCE_HASH_SIZE],- runtime: BytecodeCacheRuntime,-}--impl Encode for CacheBlob<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.bytes(MAGIC);- FORMAT_VERSION.encode(encoder);- INSTRUCTION_SET_FINGERPRINT.encode(encoder);- self.runtime.tag().encode(encoder);- self.program_type.encode(encoder);- encoder.bytes(self.source_hash);- u32_from_usize(self.compiled.source_len).encode(encoder);- self.compiled.parsed.has_top_level_await.encode(encoder);- self.compiled.parsed.is_strict_mode.encode(encoder);- DeclarationMetadataRecord {- compiled: self.compiled,- program_type: self.program_type,- }- .encode(encoder);- ProgramRecord::from(self.compiled).encode(encoder);- }-}--impl CacheBlob<'_> {- fn decode(- decoder: &mut Decoder<'_>,- expected_program_type: ast::ProgramType,- expected_source_hash: &[u8; SOURCE_HASH_SIZE],- expected_runtime: BytecodeCacheRuntime,- ) -> Option<DecodedCacheBlob> {- decoder.expect_bytes(MAGIC)?;- (u32::decode(decoder)? == FORMAT_VERSION).then_some(())?;- (u64::decode(decoder)? == INSTRUCTION_SET_FINGERPRINT).then_some(())?;- (u8::decode(decoder)? == expected_runtime.tag()).then_some(())?;- let program_type = ast::ProgramType::decode(decoder)?;- (program_type == expected_program_type).then_some(())?;- (decoder.bytes(SOURCE_HASH_SIZE)? == expected_source_hash).then_some(())?;- let source_len = u32::decode(decoder)? as usize;- Some(DecodedCacheBlob {- program_type,- source_len,- has_top_level_await: bool::decode(decoder)?,- is_strict_mode: bool::decode(decoder)?,- metadata: DeclarationMetadataRecord::decode(decoder)?,- program: ProgramRecord::decode(decoder)?,- has_been_validated_for_materialization: false,- })- }-}--/// A decoded bytecode cache blob, whose strings and bytecode stay in the blob.-pub struct DecodedCacheBlob {- pub(crate) program_type: ast::ProgramType,- pub(crate) source_len: usize,- pub(crate) has_top_level_await: bool,- pub(crate) is_strict_mode: bool,- pub(crate) metadata: DecodedDeclarationMetadata,- pub(crate) program: DecodedProgramRecord,- has_been_validated_for_materialization: bool,-}--/// Witnesses that the blob a cached executable came from passed validation for materialization.-#[derive(Clone, Copy)]-pub(crate) enum CachedBytecodeValidation {- Validated,-}--impl DecodedCacheBlob {- pub fn program_type(&self) -> ast::ProgramType {- self.program_type- }-- pub fn has_top_level_await(&self) -> bool {- self.has_top_level_await- }-- pub fn is_strict_mode(&self) -> bool {- self.is_strict_mode- }-- /// Checks everything that bytecode built from this blob may rely on for source code of `source_len` code units:- /// source ranges, the tables and the indices into them, and the bytecode of every executable, including those of- /// nested functions.- pub fn validate_for_materialization(&mut self, source_len: usize) -> Result<(), ValidationErrorKind> {- if self.source_len != source_len {- return Err(ValidationErrorKind::InvalidLength);- }- if self.has_been_validated_for_materialization {- return Ok(());- }- self.metadata.validate_for_materialization(source_len)?;- self.program.validate_for_materialization(source_len)?;- self.has_been_validated_for_materialization = true;- Ok(())- }-- pub(crate) fn verify_has_been_validated_for_materialization(&self) {- assert!(- self.has_been_validated_for_materialization,- "decoded bytecode cache blob must be validated before materialization"- );- }-- /// What declaration instantiation of the program needs. Every record reached from here passed validation.- ///- /// # Panics- /// Panics if the blob has not passed [`DecodedCacheBlob::validate_for_materialization()`].- pub fn declaration_metadata(&self) -> &DecodedDeclarationMetadata {- self.verify_has_been_validated_for_materialization();- &self.metadata- }-- /// The program's body. Every record reached from here passed validation.- ///- /// # Panics- /// Panics if the blob has not passed [`DecodedCacheBlob::validate_for_materialization()`].- pub fn program(&self) -> &DecodedProgramRecord {- self.verify_has_been_validated_for_materialization();- &self.program- }-}--impl Encode for ast::ProgramType {- fn encode(&self, encoder: &mut Encoder) {- (*self as u8).encode(encoder);- }-}--impl Decode for ast::ProgramType {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(Self::Script),- 1 => Some(Self::Module),- _ => None,- }- }-}--impl Decode for ast::ExportEntryKind {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(Self::NamedExport),- 1 => Some(Self::ModuleRequestAll),- 2 => Some(Self::ModuleRequestAllButDefault),- _ => None,- }- }-}--impl Decode for ast::FunctionKind {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(Self::Normal),- 1 => Some(Self::Generator),- 2 => Some(Self::Async),- 3 => Some(Self::AsyncGenerator),- _ => None,- }- }-}--struct DeclarationMetadataRecord<'a> {- compiled: &'a CompiledProgram,- program_type: ast::ProgramType,-}--impl Encode for DeclarationMetadataRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- let ast::StatementKind::Program(program) = &self.compiled.parsed.program.inner else {- unreachable!("bytecode cache expects a parsed program root");- };- let arena = &self.compiled.parsed.arena;- let scope = &arena.scopes[program.scope];- match self.program_type {- ast::ProgramType::Script => ScriptDeclarationMetadata::from_scope(scope, arena).encode(encoder),- ast::ProgramType::Module => ModuleDeclarationMetadata::from_scope(scope, arena).encode(encoder),- }- DeclarationFunctionTable(&self.compiled.declaration_functions).encode(encoder);- }-}--impl DeclarationMetadataRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedDeclarationMetadata> {- match MetadataKind::decode(decoder)? {- MetadataKind::Script => Some(DecodedDeclarationMetadata::Script {- metadata: ScriptDeclarationMetadata::decode_payload(decoder)?,- declaration_functions: DeclarationFunctionTable::decode(decoder)?,- }),- MetadataKind::Module => Some(DecodedDeclarationMetadata::Module {- metadata: ModuleDeclarationMetadata::decode_payload(decoder)?,- declaration_functions: DeclarationFunctionTable::decode(decoder)?,- }),- }- }-}--/// What declaration instantiation of a cached script or module needs, with the functions it declares.-pub enum DecodedDeclarationMetadata {- Script {- metadata: ScriptDeclarationMetadata,- declaration_functions: Vec<DecodedFunctionRecord>,- },- Module {- metadata: ModuleDeclarationMetadata,- declaration_functions: Vec<DecodedFunctionRecord>,- },-}--impl DecodedDeclarationMetadata {- fn validate_for_materialization(&self, source_len: usize) -> Result<(), ValidationErrorKind> {- match self {- Self::Script {- declaration_functions, ..- } => {- for function in declaration_functions {- function.validate_for_materialization(source_len)?;- }- Ok(())- }- Self::Module {- metadata,- declaration_functions,- } => {- if declaration_functions.len() != metadata.function_names.len()- || metadata.lexical_bindings.iter().any(|binding| {- binding.function_index >= 0- && !usize::try_from(binding.function_index)- .is_ok_and(|index| index < declaration_functions.len())- })- {- return Err(ValidationErrorKind::InvalidLength);- }-- for function in declaration_functions {- function.validate_for_materialization(source_len)?;- }- Ok(())- }- }- }-}--#[repr(u8)]-#[derive(Clone, Copy)]-enum MetadataKind {- Script = 0,- Module = 1,-}--impl Encode for MetadataKind {- fn encode(&self, encoder: &mut Encoder) {- (*self as u8).encode(encoder);- }-}--impl Decode for MetadataKind {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(Self::Script),- 1 => Some(Self::Module),- _ => None,- }- }-}--pub struct ScriptDeclarationMetadata {- pub lexical_names: Vec<ast::Utf16String>,- pub var_names: Vec<ast::Utf16String>,- pub function_names: Vec<ast::Utf16String>,- pub var_scoped_names: Vec<ast::Utf16String>,- pub annex_b_candidate_names: Vec<ast::Utf16String>,- pub lexical_bindings: Vec<LexicalBindingRecord>,-}--impl ScriptDeclarationMetadata {- fn from_scope(scope: &ast::ScopeData, arena: &ast::AstArena) -> Self {- let mut metadata = Self {- lexical_names: Vec::new(),- var_names: Vec::new(),- function_names: script_function_names(scope, arena),- var_scoped_names: Vec::new(),- annex_b_candidate_names: scope.annexb_function_names.to_vec(),- lexical_bindings: Vec::new(),- };-- for child in &scope.children {- collect_var_names_recursive(&child.inner, arena, &mut metadata.var_names);- if let Some(function) = child.inner.function_declaration_for_labelled_item()- && let Some(name) = function.name- {- metadata.var_names.push(arena.name_of(name).clone());- }- collect_script_lexical_names(&child.inner, arena, &mut metadata.lexical_names);- collect_script_lexical_bindings(&child.inner, arena, &mut metadata.lexical_bindings);- collect_var_names_recursive(&child.inner, arena, &mut metadata.var_scoped_names);- }-- metadata- }-- fn decode_payload(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(Self {- lexical_names: Utf16Vector::decode(decoder)?,- var_names: Utf16Vector::decode(decoder)?,- function_names: Utf16Vector::decode(decoder)?,- var_scoped_names: Utf16Vector::decode(decoder)?,- annex_b_candidate_names: Utf16Vector::decode(decoder)?,- lexical_bindings: LexicalBindingTable::decode(decoder)?,- })- }-}--impl Encode for ScriptDeclarationMetadata {- fn encode(&self, encoder: &mut Encoder) {- MetadataKind::Script.encode(encoder);- Utf16Vector(&self.lexical_names).encode(encoder);- Utf16Vector(&self.var_names).encode(encoder);- Utf16Vector(&self.function_names).encode(encoder);- Utf16Vector(&self.var_scoped_names).encode(encoder);- Utf16Vector(&self.annex_b_candidate_names).encode(encoder);- LexicalBindingTable(&self.lexical_bindings).encode(encoder);- }-}--pub struct ModuleDeclarationMetadata {- pub import_entries: Vec<ModuleImportEntryRecord>,- pub local_exports: Vec<ModuleExportEntryRecord>,- pub indirect_exports: Vec<ModuleExportEntryRecord>,- pub star_exports: Vec<ModuleExportEntryRecord>,- pub requested_modules: Vec<ModuleRequestRecord>,- pub default_export_binding_name: Option<ast::Utf16String>,- pub var_declared_names: Vec<ast::Utf16String>,- pub function_names: Vec<ast::Utf16String>,- pub lexical_bindings: Vec<ModuleLexicalBindingRecord>,-}--impl ModuleDeclarationMetadata {- fn from_scope(scope: &ast::ScopeData, arena: &ast::AstArena) -> Self {- let mut metadata = Self {- import_entries: Vec::new(),- local_exports: Vec::new(),- indirect_exports: Vec::new(),- star_exports: Vec::new(),- requested_modules: requested_modules(scope),- default_export_binding_name: None,- var_declared_names: Vec::new(),- function_names: Vec::new(),- lexical_bindings: Vec::new(),- };-- collect_module_imports_and_exports(scope, &mut metadata);-- let mut function_index = 0;- for child in &scope.children {- collect_module_var_names(&child.inner, arena, &mut metadata.var_declared_names);-- let (declaration, is_exported) = match &child.inner {- ast::StatementKind::Export(export_data) => {- if let Some(ref statement) = export_data.statement {- (&statement.inner, true)- } else {- continue;- }- }- other => (other, false),- };- collect_module_declaration(declaration, is_exported, function_index, arena, &mut metadata);- if matches!(declaration, ast::StatementKind::FunctionDeclaration(_)) {- function_index += 1;- }- }-- metadata- }-- fn decode_payload(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(Self {- import_entries: ModuleImportEntryTable::decode(decoder)?,- local_exports: ModuleExportEntryTable::decode(decoder)?,- indirect_exports: ModuleExportEntryTable::decode(decoder)?,- star_exports: ModuleExportEntryTable::decode(decoder)?,- requested_modules: ModuleRequestTable::decode(decoder)?,- default_export_binding_name: Option::<ast::Utf16String>::decode(decoder)?,- var_declared_names: Utf16Vector::decode(decoder)?,- function_names: Utf16Vector::decode(decoder)?,- lexical_bindings: ModuleLexicalBindingTable::decode(decoder)?,- })- }-}--impl Encode for ModuleDeclarationMetadata {- fn encode(&self, encoder: &mut Encoder) {- MetadataKind::Module.encode(encoder);- ModuleImportEntryTable(&self.import_entries).encode(encoder);- ModuleExportEntryTable(&self.local_exports).encode(encoder);- ModuleExportEntryTable(&self.indirect_exports).encode(encoder);- ModuleExportEntryTable(&self.star_exports).encode(encoder);- ModuleRequestTable(&self.requested_modules).encode(encoder);- self.default_export_binding_name- .as_ref()- .map(|name| Utf16(name))- .encode(encoder);- Utf16Vector(&self.var_declared_names).encode(encoder);- Utf16Vector(&self.function_names).encode(encoder);- ModuleLexicalBindingTable(&self.lexical_bindings).encode(encoder);- }-}--struct Utf16Vector<'a>(&'a [ast::Utf16String]);--impl Encode for Utf16Vector<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |value, encoder| Utf16(value).encode(encoder));- }-}--impl Utf16Vector<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<ast::Utf16String>> {- decoder.sequence_values(ast::Utf16String::decode)- }-}--pub struct LexicalBindingRecord {- pub name: ast::Utf16String,- pub is_constant: bool,-}--impl Encode for LexicalBindingRecord {- fn encode(&self, encoder: &mut Encoder) {- Utf16(&self.name).encode(encoder);- self.is_constant.encode(encoder);- }-}--struct LexicalBindingTable<'a>(&'a [LexicalBindingRecord]);--impl Encode for LexicalBindingTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |binding, encoder| binding.encode(encoder));- }-}--impl LexicalBindingTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<LexicalBindingRecord>> {- decoder.sequence_values(|decoder| {- Some(LexicalBindingRecord {- name: ast::Utf16String::decode(decoder)?,- is_constant: bool::decode(decoder)?,- })- })- }-}--/// A lexical binding of a module, which the declared function at `function_index` initializes, unless that is -1.-pub struct ModuleLexicalBindingRecord {- pub name: ast::Utf16String,- pub is_constant: bool,- pub function_index: i32,-}--impl Encode for ModuleLexicalBindingRecord {- fn encode(&self, encoder: &mut Encoder) {- Utf16(&self.name).encode(encoder);- self.is_constant.encode(encoder);- self.function_index.encode(encoder);- }-}--struct ModuleLexicalBindingTable<'a>(&'a [ModuleLexicalBindingRecord]);--impl Encode for ModuleLexicalBindingTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |binding, encoder| binding.encode(encoder));- }-}--impl ModuleLexicalBindingTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<ModuleLexicalBindingRecord>> {- decoder.sequence_values(|decoder| {- Some(ModuleLexicalBindingRecord {- name: ast::Utf16String::decode(decoder)?,- is_constant: bool::decode(decoder)?,- function_index: i32::decode(decoder)?,- })- })- }-}--#[derive(Clone)]-pub struct ModuleRequestRecord {- pub specifier: ast::Utf16String,- pub attributes: Vec<ast::ImportAttribute>,-}--impl From<&ast::ModuleRequest> for ModuleRequestRecord {- fn from(request: &ast::ModuleRequest) -> Self {- Self {- specifier: request.module_specifier.clone(),- attributes: request.attributes.clone(),- }- }-}--impl Encode for ModuleRequestRecord {- fn encode(&self, encoder: &mut Encoder) {- Utf16(&self.specifier).encode(encoder);- ImportAttributeTable(&self.attributes).encode(encoder);- }-}--impl Decode for ModuleRequestRecord {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(Self {- specifier: ast::Utf16String::decode(decoder)?,- attributes: ImportAttributeTable::decode(decoder)?,- })- }-}--impl From<&ModuleRequestRecord> for ast::ModuleRequest {- fn from(record: &ModuleRequestRecord) -> Self {- Self {- module_specifier: record.specifier.clone(),- attributes: record.attributes.clone(),- }- }-}--struct ModuleRequestTable<'a>(&'a [ModuleRequestRecord]);--impl Encode for ModuleRequestTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |request, encoder| request.encode(encoder));- }-}--impl ModuleRequestTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<ModuleRequestRecord>> {- decoder.sequence_values(ModuleRequestRecord::decode)- }-}--struct ImportAttributeTable<'a>(&'a [ast::ImportAttribute]);--impl Encode for ImportAttributeTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |attribute, encoder| {- Utf16(&attribute.key).encode(encoder);- Utf16(&attribute.value).encode(encoder);- });- }-}--impl ImportAttributeTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<ast::ImportAttribute>> {- decoder.sequence_values(|decoder| {- Some(ast::ImportAttribute {- key: ast::Utf16String::decode(decoder)?,- value: ast::Utf16String::decode(decoder)?,- })- })- }-}--pub struct ModuleImportEntryRecord {- pub import_name: Option<ast::Utf16String>,- pub local_name: ast::Utf16String,- pub module_request: ModuleRequestRecord,-}--impl Encode for ModuleImportEntryRecord {- fn encode(&self, encoder: &mut Encoder) {- self.import_name.as_ref().map(|name| Utf16(name)).encode(encoder);- Utf16(&self.local_name).encode(encoder);- self.module_request.encode(encoder);- }-}--struct ModuleImportEntryTable<'a>(&'a [ModuleImportEntryRecord]);--impl Encode for ModuleImportEntryTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |entry, encoder| entry.encode(encoder));- }-}--impl ModuleImportEntryTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<ModuleImportEntryRecord>> {- decoder.sequence_values(|decoder| {- Some(ModuleImportEntryRecord {- import_name: Option::<ast::Utf16String>::decode(decoder)?,- local_name: ast::Utf16String::decode(decoder)?,- module_request: ModuleRequestRecord::decode(decoder)?,- })- })- }-}--pub struct ModuleExportEntryRecord {- pub kind: ast::ExportEntryKind,- pub export_name: Option<ast::Utf16String>,- pub local_or_import_name: Option<ast::Utf16String>,- pub module_request: Option<ModuleRequestRecord>,-}--impl Encode for ModuleExportEntryRecord {- fn encode(&self, encoder: &mut Encoder) {- (self.kind as u8).encode(encoder);- self.export_name.as_ref().map(|name| Utf16(name)).encode(encoder);- self.local_or_import_name- .as_ref()- .map(|name| Utf16(name))- .encode(encoder);- self.module_request.encode(encoder);- }-}--struct ModuleExportEntryTable<'a>(&'a [ModuleExportEntryRecord]);--impl Encode for ModuleExportEntryTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- encoder.sequence(self.0, |entry, encoder| entry.encode(encoder));- }-}--impl ModuleExportEntryTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<ModuleExportEntryRecord>> {- decoder.sequence_values(|decoder| {- Some(ModuleExportEntryRecord {- kind: ast::ExportEntryKind::decode(decoder)?,- export_name: Option::<ast::Utf16String>::decode(decoder)?,- local_or_import_name: Option::<ast::Utf16String>::decode(decoder)?,- module_request: Option::<ModuleRequestRecord>::decode(decoder)?,- })- })- }-}--fn collect_script_lexical_names(- statement: &ast::StatementKind,- arena: &ast::AstArena,- names: &mut Vec<ast::Utf16String>,-) {- match statement {- ast::StatementKind::VariableDeclaration(declaration) if declaration.kind != ast::DeclarationKind::Var => {- for declarator in &declaration.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| names.push(name.to_vec().into()));- }- }- ast::StatementKind::UsingDeclaration(declarations) => {- for declarator in &declarations.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| names.push(name.to_vec().into()));- }- }- ast::StatementKind::ClassDeclaration(class_data) => {- if let Some(name) = class_data.name {- names.push(arena.name_of(name).clone());- }- }- _ => {}- }-}--fn collect_script_lexical_bindings(- statement: &ast::StatementKind,- arena: &ast::AstArena,- bindings: &mut Vec<LexicalBindingRecord>,-) {- match statement {- ast::StatementKind::VariableDeclaration(declaration) if declaration.kind != ast::DeclarationKind::Var => {- let is_constant = declaration.kind == ast::DeclarationKind::Const;- for declarator in &declaration.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| {- bindings.push(LexicalBindingRecord {- name: name.to_vec().into(),- is_constant,- });- });- }- }- ast::StatementKind::UsingDeclaration(declarations) => {- for declarator in &declarations.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| {- bindings.push(LexicalBindingRecord {- name: name.to_vec().into(),- is_constant: true,- });- });- }- }- ast::StatementKind::ClassDeclaration(class_data) => {- if let Some(name) = class_data.name {- bindings.push(LexicalBindingRecord {- name: arena.name_of(name).clone(),- is_constant: false,- });- }- }- _ => {}- }-}--fn script_function_names(scope: &ast::ScopeData, arena: &ast::AstArena) -> Vec<ast::Utf16String> {- let mut last_position = HashMap::new();- for (index, child) in scope.children.iter().enumerate() {- if let Some(function) = child.inner.function_declaration_for_labelled_item()- && let Some(name) = function.name- {- last_position.insert(arena.identifiers[name].name, index);- }- }-- let mut names = Vec::new();- for (index, child) in scope.children.iter().enumerate() {- if let Some(function) = child.inner.function_declaration_for_labelled_item()- && let Some(name) = function.name- && last_position.get(&arena.identifiers[name].name).copied() == Some(index)- {- names.push(arena.name_of(name).clone());- }- }- names-}--fn collect_module_imports_and_exports(scope: &ast::ScopeData, metadata: &mut ModuleDeclarationMetadata) {- struct ImportEntryWithRequest {- import_name: Option<ast::Utf16String>,- local_name: ast::Utf16String,- module_request: ModuleRequestRecord,- }-- let mut all_import_entries = Vec::new();-- for child in &scope.children {- if let ast::StatementKind::Import(import_data) = &child.inner {- for entry in &import_data.entries {- let module_request = ModuleRequestRecord::from(&import_data.module_request);- metadata.import_entries.push(ModuleImportEntryRecord {- import_name: entry.import_name.clone(),- local_name: entry.local_name.clone(),- module_request: module_request.clone(),- });- all_import_entries.push(ImportEntryWithRequest {- import_name: entry.import_name.clone(),- local_name: entry.local_name.clone(),- module_request,- });- }- }- }-- for child in &scope.children {- let ast::StatementKind::Export(export_data) = &child.inner else {- continue;- };-- if export_data.is_default_export && export_data.entries.len() == 1 {- let entry = &export_data.entries[0];- let is_declaration = export_data.statement.as_ref().is_some_and(|statement| {- matches!(- statement.inner,- ast::StatementKind::FunctionDeclaration(_) | ast::StatementKind::ClassDeclaration(_)- )- });- let is_specific_import_export = all_import_entries.iter().any(|import| {- entry.local_or_import_name.as_ref() == Some(&import.local_name) && import.import_name.is_some()- });- if !is_declaration && !is_specific_import_export {- metadata.default_export_binding_name = entry.local_or_import_name.clone();- }- }-- for entry in &export_data.entries {- if entry.kind == ast::ExportEntryKind::EmptyNamedExport {- break;- }-- let has_module_request = export_data.module_request.is_some();- if !has_module_request {- let matching_import = all_import_entries- .iter()- .find(|import| entry.local_or_import_name.as_ref() == Some(&import.local_name));- if let Some(import_entry) = matching_import {- if import_entry.import_name.is_none() {- metadata.indirect_exports.push(ModuleExportEntryRecord {- kind: ast::ExportEntryKind::ModuleRequestAll,- export_name: entry.export_name.clone(),- local_or_import_name: None,- module_request: Some(import_entry.module_request.clone()),- });- } else {- metadata.indirect_exports.push(ModuleExportEntryRecord {- kind: entry.kind,- export_name: entry.export_name.clone(),- local_or_import_name: import_entry.import_name.clone(),- module_request: Some(import_entry.module_request.clone()),- });- }- } else {- metadata.local_exports.push(export_record(entry, None));- }- } else if entry.kind == ast::ExportEntryKind::ModuleRequestAllButDefault {- let module_request = export_data.module_request.as_ref().map(ModuleRequestRecord::from);- metadata- .star_exports- .push(export_record(entry, module_request.as_ref()));- } else {- let module_request = export_data.module_request.as_ref().map(ModuleRequestRecord::from);- metadata- .indirect_exports- .push(export_record(entry, module_request.as_ref()));- }- }- }-}--fn export_record(entry: &ast::ExportEntry, module_request: Option<&ModuleRequestRecord>) -> ModuleExportEntryRecord {- ModuleExportEntryRecord {- kind: entry.kind,- export_name: entry.export_name.clone(),- local_or_import_name: entry.local_or_import_name.clone(),- module_request: module_request.cloned(),- }-}--fn requested_modules(scope: &ast::ScopeData) -> Vec<ModuleRequestRecord> {- let mut modules = Vec::new();- for child in &scope.children {- match &child.inner {- ast::StatementKind::Import(import_data) => {- modules.push((- child.range.start.offset,- ModuleRequestRecord::from(&import_data.module_request),- ));- }- ast::StatementKind::Export(export_data) => {- if let Some(module_request) = &export_data.module_request {- modules.push((child.range.start.offset, ModuleRequestRecord::from(module_request)));- }- }- _ => {}- }- }- modules.sort_by_key(|(source_offset, _)| *source_offset);- modules.into_iter().map(|(_, module_request)| module_request).collect()-}--fn collect_module_declaration(- declaration: &ast::StatementKind,- is_exported: bool,- function_index: i32,- arena: &ast::AstArena,- metadata: &mut ModuleDeclarationMetadata,-) {- let default_name: ast::Utf16String = utf16!("*default*").into();- match declaration {- ast::StatementKind::FunctionDeclaration(function) => {- let Some(name) = function.name else {- return;- };- let is_default = is_exported && arena.name_slice(name) == default_name.as_slice();- let function_name = if is_default {- utf16!("default").into()- } else {- arena.name_of(name).clone()- };- metadata.function_names.push(function_name);- metadata.lexical_bindings.push(ModuleLexicalBindingRecord {- name: arena.name_of(name).clone(),- is_constant: false,- function_index,- });- }- ast::StatementKind::ClassDeclaration(class_data) => {- if let Some(name) = class_data.name {- metadata.lexical_bindings.push(ModuleLexicalBindingRecord {- name: arena.name_of(name).clone(),- is_constant: false,- function_index: -1,- });- }- }- ast::StatementKind::VariableDeclaration(declaration) if declaration.kind != ast::DeclarationKind::Var => {- let is_constant = declaration.kind == ast::DeclarationKind::Const;- for declarator in &declaration.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| {- metadata.lexical_bindings.push(ModuleLexicalBindingRecord {- name: name.to_vec().into(),- is_constant,- function_index: -1,- });- });- }- }- ast::StatementKind::UsingDeclaration(declarations) => {- for declarator in &declarations.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| {- metadata.lexical_bindings.push(ModuleLexicalBindingRecord {- name: name.to_vec().into(),- is_constant: true,- function_index: -1,- });- });- }- }- _ => {}- }-}--fn collect_var_names_recursive(- statement: &ast::StatementKind,- arena: &ast::AstArena,- names: &mut Vec<ast::Utf16String>,-) {- match statement {- ast::StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {- for declarator in &declaration.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| names.push(name.to_vec().into()));- }- }- _ => {- for_each_child_statement(statement, arena, &mut |child| {- collect_var_names_recursive(child, arena, names);- });- }- }-}--fn collect_module_var_names(statement: &ast::StatementKind, arena: &ast::AstArena, names: &mut Vec<ast::Utf16String>) {- match statement {- ast::StatementKind::VariableDeclaration(declaration) if declaration.kind == ast::DeclarationKind::Var => {- for declarator in &declaration.declarations {- for_each_bound_name(&declarator.target, arena, &mut |name| names.push(name.to_vec().into()));- }- }- ast::StatementKind::Export(export_data) => {- if let Some(ref statement) = export_data.statement {- collect_module_var_names(&statement.inner, arena, names);- }- }- _ => {- for_each_child_statement(statement, arena, &mut |child| {- collect_module_var_names(child, arena, names);- });- }- }-}--fn for_each_bound_name(- target: &ast::VariableDeclaratorTarget,- arena: &ast::AstArena,- callback: &mut dyn FnMut(&[u16]),-) {- match target {- ast::VariableDeclaratorTarget::Identifier(identifier) => callback(arena.name_slice(*identifier)),- ast::VariableDeclaratorTarget::BindingPattern(pattern) => {- for_each_bound_name_in_pattern(pattern, arena, callback);- }- }-}--fn for_each_bound_name_in_pattern(- pattern: &ast::BindingPattern,- arena: &ast::AstArena,- callback: &mut dyn FnMut(&[u16]),-) {- for entry in &pattern.entries {- match &entry.alias {- Some(ast::BindingEntryAlias::Identifier(identifier)) => callback(arena.name_slice(*identifier)),- Some(ast::BindingEntryAlias::BindingPattern(pattern)) => {- for_each_bound_name_in_pattern(pattern, arena, callback);- }- Some(ast::BindingEntryAlias::MemberExpression(_)) => {}- None => {- if let Some(ast::BindingEntryName::Identifier(identifier)) = &entry.name {- callback(arena.name_slice(*identifier));- }- }- }- }-}--fn for_each_child_statement(- statement: &ast::StatementKind,- arena: &ast::AstArena,- callback: &mut dyn FnMut(&ast::StatementKind),-) {- match statement {- ast::StatementKind::Block(scope) => {- for child in &arena.scopes[*scope].children {- callback(&child.inner);- }- }- ast::StatementKind::If(data) => {- callback(&data.consequent.inner);- if let Some(alternate) = &data.alternate {- callback(&alternate.inner);- }- }- ast::StatementKind::While(data) | ast::StatementKind::DoWhile(data) => {- callback(&data.body.inner);- }- ast::StatementKind::With(data) => callback(&data.body.inner),- ast::StatementKind::For(data) => {- if let Some(ast::ForInit::Declaration(declaration)) = &data.init {- callback(&declaration.inner);- }- callback(&data.body.inner);- }- ast::StatementKind::ForInOf(data) => {- if let ast::ForInOfLhs::Declaration(declaration) = &data.lhs {- callback(&declaration.inner);- }- callback(&data.body.inner);- }- ast::StatementKind::Switch(data) => {- for case in &data.cases {- for child in &arena.scopes[case.scope].children {- callback(&child.inner);- }- }- }- ast::StatementKind::Labelled(data) => callback(&data.item.inner),- ast::StatementKind::Try(data) => {- callback(&data.block.inner);- if let Some(catch) = &data.handler {- callback(&catch.body.inner);- }- if let Some(finalizer) = &data.finalizer {- callback(&finalizer.inner);- }- }- ast::StatementKind::Export(export_data) => {- if let Some(statement) = &export_data.statement {- callback(&statement.inner);- }- }- _ => {}- }-}--struct ProgramRecord<'a> {- kind: ProgramKind,- executable: ExecutableRecord<'a>,-}--impl<'a> From<&'a CompiledProgram> for ProgramRecord<'a> {- fn from(compiled: &'a CompiledProgram) -> Self {- match &compiled.bytecode {- CompiledProgramBytecode::Program(executable) => Self {- kind: ProgramKind::ScriptOrModule,- executable: ExecutableRecord(executable),- },- CompiledProgramBytecode::AsyncModule(executable) => Self {- kind: ProgramKind::AsyncModule,- executable: ExecutableRecord(executable),- },- }- }-}--impl Encode for ProgramRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- self.kind.encode(encoder);- self.executable.encode(encoder);- }-}--impl ProgramRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedProgramRecord> {- Some(DecodedProgramRecord {- kind: ProgramKind::decode(decoder)?,- executable: ExecutableRecord::decode(decoder)?,- })- }-}--/// The body of a cached script or module.-pub struct DecodedProgramRecord {- pub(crate) kind: ProgramKind,- pub(crate) executable: DecodedExecutableRecord,-}--impl DecodedProgramRecord {- fn validate_for_materialization(&self, source_len: usize) -> Result<(), ValidationErrorKind> {- self.executable.validate_for_materialization(source_len)- }-- /// Whether this is the body of a module with top-level await, which is compiled as that of an async function.- pub fn is_async_module(&self) -> bool {- matches!(self.kind, ProgramKind::AsyncModule)- }-- pub fn executable(&self) -> &DecodedExecutableRecord {- &self.executable- }-}--#[repr(u8)]-#[derive(Clone, Copy)]-pub(crate) enum ProgramKind {- ScriptOrModule = 0,- AsyncModule = 1,-}--impl Encode for ProgramKind {- fn encode(&self, encoder: &mut Encoder) {- (*self as u8).encode(encoder);- }-}--impl Decode for ProgramKind {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(Self::ScriptOrModule),- 1 => Some(Self::AsyncModule),- _ => None,- }- }-}--struct ExecutableRecord<'a>(&'a ExecutableData);--impl Encode for ExecutableRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- self.0.is_strict.encode(encoder);- self.0.number_of_registers.encode(encoder);- self.0.number_of_arguments.encode(encoder);- CacheCounters(&self.0.cache_counts).encode(encoder);- self.0.this_value_needs_environment_resolution.encode(encoder);- self.0.length_identifier.map(|index| index.0).encode(encoder);-- encoder.align_bytes_payload_to(BYTECODE_ALIGNMENT);- Bytes(&self.0.bytecode).encode(encoder);- for table in [- &self.0.identifier_table,- &self.0.property_key_table,- &self.0.string_table,- ] {- DecodedRecordSequence::encode(encoder, table, |value, encoder| {- Utf16(&value.to_utf16()).encode(encoder);- });- }- ConstantTable(&self.0.constants).encode(encoder);- ExceptionHandlerTable(&self.0.exception_handlers).encode(encoder);- SourceMapTable(&self.0.source_map).encode(encoder);- LocalVariableTable(&self.0.local_variables).encode(encoder);- DecodedRecordSequence::encode(encoder, &self.0.argument_variable_names, |value, encoder| {- Utf16(&value.to_utf16()).encode(encoder);- });- SharedFunctionTable(&self.0.shared_function_data).encode(encoder);- ClassBlueprintTable(&self.0.class_blueprints).encode(encoder);- }-}--impl ExecutableRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedExecutableRecord> {- Some(DecodedExecutableRecord {- strict: bool::decode(decoder)?,- number_of_registers: u32::decode(decoder)?,- number_of_arguments: u32::decode(decoder)?,- cache_counters: CacheCounters::decode(decoder)?,- length_identifier: {- // this_value_needs_environment_resolution, which the runtime takes from the metadata of the function- // that owns the executable instead.- bool::decode(decoder)?;- Option::<u32>::decode(decoder)?- },- bytecode: {- decoder.align_bytes_payload_to(BYTECODE_ALIGNMENT)?;- DecodedBytecodeBytes::decode(decoder)?- },- identifier_table: Utf16Table::decode(decoder)?,- property_key_table: Utf16Table::decode(decoder)?,- string_table: Utf16Table::decode(decoder)?,- constants: ConstantTable::decode(decoder)?,- exception_handlers: ExceptionHandlerTable::decode(decoder)?,- source_map: SourceMapTable::decode(decoder)?,- local_variables: LocalVariableTable::decode(decoder)?,- argument_variable_names: Utf16Table::decode(decoder)?,- shared_functions: SharedFunctionTable::decode(decoder)?,- class_blueprints: ClassBlueprintTable::decode(decoder)?,- })- }-}--/// One cached executable, whose bytecode stays in the blob. Its tables are decoded on request, into what a runtime-/// creates an executable from; each returns `None` if the blob turns out to be malformed there.-pub struct DecodedExecutableRecord {- pub(crate) strict: bool,- pub(crate) number_of_registers: u32,- pub(crate) number_of_arguments: u32,- pub(crate) cache_counters: DecodedCacheCounters,- pub(crate) length_identifier: Option<u32>,- pub(crate) bytecode: DecodedBytecodeBytes,- pub(crate) identifier_table: DecodedUtf16Table,- pub(crate) property_key_table: DecodedUtf16Table,- pub(crate) string_table: DecodedUtf16Table,- pub(crate) constants: DecodedConstantTable,- pub(crate) exception_handlers: DecodedExceptionHandlerTable,- pub(crate) source_map: DecodedSourceMapTable,- pub(crate) local_variables: DecodedLocalVariableTable,- pub(crate) argument_variable_names: DecodedUtf16Table,- pub(crate) shared_functions: DecodedFunctionTable,- pub(crate) class_blueprints: DecodedClassBlueprintTable,-}--impl DecodedExecutableRecord {- fn validate_for_materialization(&self, source_len: usize) -> Result<(), ValidationErrorKind> {- if self- .length_identifier- .is_some_and(|index| (index as usize) >= self.property_key_table.len())- {- return Err(ValidationErrorKind::InvalidLength);- }- if !self.tables_are_well_formed() {- return Err(ValidationErrorKind::InvalidLength);- }- self.shared_functions.validate_for_materialization(source_len)?;- self.class_blueprints- .validate_for_materialization(source_len, self.shared_functions.len())?;-- let bounds = FFIValidatorBounds {- number_of_registers: self.number_of_registers,- number_of_locals: self.local_variables.len() as u32,- number_of_constants: self.constants.len() as u32,- number_of_arguments: self.number_of_arguments,- identifier_table_size: self.identifier_table.len() as u32,- string_table_size: self.string_table.len() as u32,- property_key_table_size: self.property_key_table.len() as u32,- regex_table_size: 0,- property_lookup_cache_count: self.cache_counters.property_lookup_cache_count,- global_variable_cache_count: self.cache_counters.global_variable_cache_count,- environment_coordinate_cache_count: self.cache_counters.environment_coordinate_cache_count,- template_object_cache_count: self.cache_counters.template_object_cache_count,- object_shape_cache_count: self.cache_counters.object_shape_cache_count,- object_property_iterator_cache_count: self.cache_counters.object_property_iterator_cache_count,- environment_shape_cache_count: self.cache_counters.environment_shape_cache_count,- arith_feedback_count: self.cache_counters.arith_feedback_count,- value_feedback_count: self.cache_counters.value_feedback_count,- call_feedback_count: self.cache_counters.call_feedback_count,- keyed_feedback_count: self.cache_counters.keyed_feedback_count,- class_blueprint_count: self.class_blueprints.len() as u32,- shared_function_data_count: self.shared_functions.len() as u32,- completion_type_variant_count: COMPLETION_TYPE_VARIANT_COUNT,- iterator_hint_variant_count: ITERATOR_HINT_VARIANT_COUNT,- environment_mode_variant_count: ENVIRONMENT_MODE_VARIANT_COUNT,- put_kind_variant_count: PUT_KIND_VARIANT_COUNT,- arguments_kind_variant_count: ARGUMENTS_KIND_VARIANT_COUNT,- function_name_prefix_variant_count: FUNCTION_NAME_PREFIX_VARIANT_COUNT,- };-- let exception_handlers = self- .exception_handlers- .values()- .ok_or(ValidationErrorKind::InvalidLength)?;- let exception_handlers: Vec<FFIExceptionHandlerOffsets> = exception_handlers- .iter()- .map(|handler| FFIExceptionHandlerOffsets {- start: handler.start_offset,- end: handler.end_offset,- handler: handler.handler_offset,- })- .collect();- let source_map = self.source_map.values().ok_or(ValidationErrorKind::InvalidLength)?;- let source_map_offsets: Vec<u32> = source_map.iter().map(|entry| entry.bytecode_offset).collect();-- validate_bytecode(- self.bytecode.as_slice(),- &bounds,- &[],- &exception_handlers,- &source_map_offsets,- )- .map_err(|error| error.kind)?;-- Ok(())- }-- /// Whether every table that an executable is created from decodes. A function's executable is only created on its- /// first call, when a malformed table can no longer make the host compile the source instead.- fn tables_are_well_formed(&self) -> bool {- self.identifier_table.is_well_formed()- && self.property_key_table.is_well_formed()- && self.string_table.is_well_formed()- && self.argument_variable_names.is_well_formed()- && self.constants.is_well_formed()- && self.local_variables.values().is_some()- }-- pub fn is_strict(&self) -> bool {- self.strict- }-- pub fn number_of_registers(&self) -> u32 {- self.number_of_registers- }-- pub fn number_of_arguments(&self) -> u32 {- self.number_of_arguments- }-- pub fn cache_counts(&self) -> ExecutableCacheCounts {- let counters = &self.cache_counters;- ExecutableCacheCounts {- property_lookup: counters.property_lookup_cache_count,- global_variable: counters.global_variable_cache_count,- environment_coordinate: counters.environment_coordinate_cache_count,- template_object: counters.template_object_cache_count,- object_shape: counters.object_shape_cache_count,- object_property_iterator: counters.object_property_iterator_cache_count,- environment_shape: counters.environment_shape_cache_count,- arith_feedback: counters.arith_feedback_count,- value_feedback: counters.value_feedback_count,- call_feedback: counters.call_feedback_count,- keyed_feedback: counters.keyed_feedback_count,- }- }-- /// The index in the property key table of the name the bytecode reads a length through, if any.- pub fn length_identifier(&self) -> Option<u32> {- self.length_identifier- }-- /// The bytecode, in the blob, which these bytes keep alive.- pub fn bytecode(&self) -> &DecodedBytecodeBytes {- &self.bytecode- }-- pub fn identifiers(&self) -> Option<Vec<ak::Utf16FlyString>> {- self.identifier_table.fly_strings()- }-- pub fn property_keys(&self) -> Option<Vec<ak::Utf16FlyString>> {- self.property_key_table.fly_strings()- }-- pub fn strings(&self) -> Option<Vec<ak::Utf16FlyString>> {- self.string_table.fly_strings()- }-- pub fn argument_names(&self) -> Option<Vec<ak::Utf16FlyString>> {- self.argument_variable_names.fly_strings()- }-- pub fn constant_values(&self) -> Option<Vec<ConstantValue>> {- self.constants.values()- }-- pub fn exception_handler_entries(&self) -> Option<Vec<ExceptionHandler>> {- self.exception_handlers.values()- }-- pub fn source_map_entries(&self) -> Option<Vec<SourceMapEntry>> {- self.source_map.values()- }-- pub fn locals(&self) -> Option<Vec<LocalVariable>> {- self.local_variables.local_variables()- }-- /// The functions the bytecode creates, which refer to it by index.- pub fn functions(&self) -> Option<Vec<DecodedFunctionRecord>> {- self.shared_functions.values()- }-- pub fn classes(&self) -> Option<Vec<PendingClassBlueprint>> {- Some(- self.class_blueprints- .values()?- .iter()- .map(PendingClassBlueprint::from)- .collect(),- )- }-}--/// The executable of a cached function, kept in the blob until the function is first called.-pub struct DecodedCachedExecutableRecord {- bytes: DecodedBytecodeBytes,- has_been_validated_for_materialization: bool,-}--impl DecodedCachedExecutableRecord {- /// The executable, decoded.- ///- /// # Panics- /// Panics unless the record came from a blob that passed validation.- pub fn decode_executable(&self) -> Option<DecodedExecutableRecord> {- self.verify_has_been_validated_for_materialization();- self.decode_validated_executable(CachedBytecodeValidation::Validated)- }-- pub(crate) fn decode_validated_executable(&self, _: CachedBytecodeValidation) -> Option<DecodedExecutableRecord> {- let mut decoder = self.bytes.decoder();- let executable = ExecutableRecord::decode(&mut decoder)?;- decoder.is_empty().then_some(executable)- }-- pub(crate) fn validated_copy(&self, _: CachedBytecodeValidation) -> Self {- Self {- bytes: self.bytes.clone(),- has_been_validated_for_materialization: true,- }- }-- pub(crate) fn verify_has_been_validated_for_materialization(&self) {- assert!(- self.has_been_validated_for_materialization,- "cached bytecode executable must be validated before materialization"- );- }-- fn validate_for_materialization(&self, source_len: usize) -> Result<(), ValidationErrorKind> {- let mut decoder = self.bytes.decoder();- let executable = ExecutableRecord::decode(&mut decoder).ok_or(ValidationErrorKind::InvalidLength)?;- if !decoder.is_empty() {- return Err(ValidationErrorKind::InvalidLength);- }- executable.validate_for_materialization(source_len)- }-}--struct CacheCounters<'a>(&'a ExecutableCacheCounts);--impl Encode for CacheCounters<'_> {- fn encode(&self, encoder: &mut Encoder) {- self.0.property_lookup.encode(encoder);- self.0.global_variable.encode(encoder);- self.0.environment_coordinate.encode(encoder);- self.0.template_object.encode(encoder);- self.0.object_shape.encode(encoder);- self.0.object_property_iterator.encode(encoder);- self.0.environment_shape.encode(encoder);- self.0.arith_feedback.encode(encoder);- self.0.value_feedback.encode(encoder);- self.0.call_feedback.encode(encoder);- self.0.keyed_feedback.encode(encoder);- }-}--impl CacheCounters<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedCacheCounters> {- Some(DecodedCacheCounters {- property_lookup_cache_count: u32::decode(decoder)?,- global_variable_cache_count: u32::decode(decoder)?,- environment_coordinate_cache_count: u32::decode(decoder)?,- template_object_cache_count: u32::decode(decoder)?,- object_shape_cache_count: u32::decode(decoder)?,- object_property_iterator_cache_count: u32::decode(decoder)?,- environment_shape_cache_count: u32::decode(decoder)?,- arith_feedback_count: decode_feedback_slot_count(decoder)?,- value_feedback_count: decode_feedback_slot_count(decoder)?,- call_feedback_count: decode_feedback_slot_count(decoder)?,- keyed_feedback_count: decode_feedback_slot_count(decoder)?,- })- }-}--pub(crate) struct DecodedCacheCounters {- pub(crate) property_lookup_cache_count: u32,- pub(crate) global_variable_cache_count: u32,- pub(crate) environment_coordinate_cache_count: u32,- pub(crate) template_object_cache_count: u32,- pub(crate) object_shape_cache_count: u32,- pub(crate) object_property_iterator_cache_count: u32,- pub(crate) environment_shape_cache_count: u32,- pub(crate) arith_feedback_count: u32,- pub(crate) value_feedback_count: u32,- pub(crate) call_feedback_count: u32,- pub(crate) keyed_feedback_count: u32,-}--fn decode_feedback_slot_count(decoder: &mut Decoder<'_>) -> Option<u32> {- let count = u32::decode(decoder)?;- (count <= MAX_FEEDBACK_SLOT_COUNT).then_some(count)-}--struct Utf16Table<'a>(&'a [ast::Utf16String]);--impl Encode for Utf16Table<'_> {- fn encode(&self, encoder: &mut Encoder) {- DecodedRecordSequence::encode(encoder, self.0, |value, encoder| Utf16(value).encode(encoder));- }-}--impl Utf16Table<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedUtf16Table> {- Some(DecodedUtf16Table {- sequence: DecodedRecordSequence::decode(decoder)?,- })- }-}--pub(crate) struct DecodedUtf16Table {- sequence: DecodedRecordSequence,-}--impl DecodedUtf16Table {- fn len(&self) -> usize {- self.sequence.len()- }-- pub(crate) fn values(&self) -> Option<Vec<DecodedUtf16String>> {- let mut decoder = self.sequence.decoder();- let mut values = Vec::with_capacity(self.sequence.len());- for _ in 0..self.sequence.len() {- values.push(DecodedUtf16String::decode(&mut decoder)?);- }- decoder.is_empty().then_some(values)- }-- fn is_well_formed(&self) -> bool {- let mut decoder = self.sequence.decoder();- (0..self.sequence.len()).all(|_| DecodedUtf16String::decode(&mut decoder).is_some()) && decoder.is_empty()- }-- fn fly_strings(&self) -> Option<Vec<ak::Utf16FlyString>> {- // The strings point into the bytes of this table, which keep the blob alive while they are converted.- Some(self.values()?.iter().map(DecodedUtf16String::to_fly_string).collect())- }-}--struct ConstantTable<'a>(&'a [ConstantValue]);--impl Encode for ConstantTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- u32_from_usize(self.0.len()).encode(encoder);-- let mut constant_encoder = Encoder::new();- for constant in self.0 {- constant.encode(&mut constant_encoder);- }- Bytes(&constant_encoder.finish()).encode(encoder);- }-}--impl ConstantTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedConstantTable> {- let count: usize = u32::decode(decoder)?.try_into().ok()?;- let byte_length: usize = u32::decode(decoder)?.try_into().ok()?;- // Constants are encoded as at least their one-byte tag.- if count > byte_length {- return None;- }- Some(DecodedConstantTable {- count,- bytes: decoder.bytecode_bytes(byte_length)?,- })- }-}--pub(crate) struct DecodedConstantTable {- count: usize,- bytes: DecodedBytecodeBytes,-}--impl DecodedConstantTable {- fn len(&self) -> usize {- self.count- }-- /// Whether every constant is one that the runtime creates a value from.- fn is_well_formed(&self) -> bool {- let mut decoder = Decoder::new(self.bytes.as_slice(), None);- (0..self.count).all(|_| validate_constant_value(&mut decoder).is_some()) && decoder.is_empty()- }-- fn values(&self) -> Option<Vec<ConstantValue>> {- let mut decoder = Decoder::new(self.bytes.as_slice(), None);- let mut values = Vec::with_capacity(self.count);- for _ in 0..self.count {- values.push(ConstantValue::decode(&mut decoder)?);- }- decoder.is_empty().then_some(values)- }-}--fn validate_constant_value(decoder: &mut Decoder<'_>) -> Option<()> {- match u8::decode(decoder)? {- tag if tag == ConstantTag::Number as u8 => {- f64::decode(decoder)?;- }- tag if tag == ConstantTag::BooleanTrue as u8 => {}- tag if tag == ConstantTag::BooleanFalse as u8 => {}- tag if tag == ConstantTag::Null as u8 => {}- tag if tag == ConstantTag::Undefined as u8 => {}- tag if tag == ConstantTag::Empty as u8 => {}- tag if tag == ConstantTag::String as u8 => {- decoder.align_to(align_of::<u16>())?;- let length: usize = u32::decode(decoder)?.try_into().ok()?;- decoder.bytes(length.checked_mul(size_of::<u16>())?)?;- }- tag if tag == ConstantTag::BigInt as u8 => {- let length: usize = u32::decode(decoder)?.try_into().ok()?;- is_big_int_constant(decoder.bytes(length)?).then_some(())?;- }- tag if tag == ConstantTag::WellKnownSymbol as u8 => match u8::decode(decoder)? {- 0 | 1 => {}- _ => return None,- },- tag if tag == ConstantTag::AbstractOperation as u8 => match u8::decode(decoder)? {- 0..=5 => {}- _ => return None,- },- _ => return None,- }-- Some(())-}--/// Whether `literal` is a BigInt as the frontend writes one into a constant table, which the runtime parses: the-/// digits of a literal, after its 0x, 0o or 0b prefix and with the numeric separators of its source text, or the-/// decimal digits of a folded value, which may be negative.-fn is_big_int_constant(literal: &[u8]) -> bool {- let (radix, digits) = match literal {- [b'0', b'x' | b'X', digits @ ..] if !digits.is_empty() => (16, digits),- [b'0', b'o' | b'O', digits @ ..] if !digits.is_empty() => (8, digits),- [b'0', b'b' | b'B', digits @ ..] if !digits.is_empty() => (2, digits),- [b'-', digits @ ..] => (10, digits),- digits => (10, digits),- };- let is_digit = |byte: &u8| char::from(*byte).is_digit(radix);- digits.first().is_some_and(is_digit)- && digits.last().is_some_and(is_digit)- && digits.windows(2).all(|pair| pair != b"__")- && digits.iter().all(|byte| *byte == b'_' || is_digit(byte))-}--impl Encode for ConstantValue {- fn encode(&self, encoder: &mut Encoder) {- match self {- ConstantValue::Number(value) => {- (ConstantTag::Number as u8).encode(encoder);- value.encode(encoder);- }- ConstantValue::Boolean(true) => (ConstantTag::BooleanTrue as u8).encode(encoder),- ConstantValue::Boolean(false) => (ConstantTag::BooleanFalse as u8).encode(encoder),- ConstantValue::Null => (ConstantTag::Null as u8).encode(encoder),- ConstantValue::Undefined => (ConstantTag::Undefined as u8).encode(encoder),- ConstantValue::Empty => (ConstantTag::Empty as u8).encode(encoder),- ConstantValue::String(value) => {- (ConstantTag::String as u8).encode(encoder);- Utf16(value).encode(encoder);- }- ConstantValue::BigInt(value) => {- (ConstantTag::BigInt as u8).encode(encoder);- Bytes(value.as_bytes()).encode(encoder);- }- ConstantValue::WellKnownSymbol(symbol) => {- (ConstantTag::WellKnownSymbol as u8).encode(encoder);- (*symbol as u8).encode(encoder);- }- ConstantValue::AbstractOperation(operation) => {- (ConstantTag::AbstractOperation as u8).encode(encoder);- (*operation as u8).encode(encoder);- }- }- }-}--impl Decode for ConstantValue {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- tag if tag == ConstantTag::Number as u8 => Some(Self::Number(f64::decode(decoder)?)),- tag if tag == ConstantTag::BooleanTrue as u8 => Some(Self::Boolean(true)),- tag if tag == ConstantTag::BooleanFalse as u8 => Some(Self::Boolean(false)),- tag if tag == ConstantTag::Null as u8 => Some(Self::Null),- tag if tag == ConstantTag::Undefined as u8 => Some(Self::Undefined),- tag if tag == ConstantTag::Empty as u8 => Some(Self::Empty),- tag if tag == ConstantTag::String as u8 => Some(Self::String(ast::Utf16String::decode(decoder)?)),- tag if tag == ConstantTag::BigInt as u8 => {- let bytes = ByteVector::decode(decoder)?;- bytes.is_ascii().then_some(())?;- Some(Self::BigInt(bytes.into_iter().map(char::from).collect()))- }- tag if tag == ConstantTag::WellKnownSymbol as u8 => match u8::decode(decoder)? {- 0 => Some(Self::WellKnownSymbol(WellKnownSymbolKind::SymbolIterator)),- 1 => Some(Self::WellKnownSymbol(WellKnownSymbolKind::SymbolAsyncIterator)),- _ => None,- },- tag if tag == ConstantTag::AbstractOperation as u8 => match u8::decode(decoder)? {- 0 => Some(Self::AbstractOperation(AbstractOperationKind::AsyncIteratorClose)),- 1 => Some(Self::AbstractOperation(AbstractOperationKind::GetMethod)),- 2 => Some(Self::AbstractOperation(AbstractOperationKind::GetIteratorDirect)),- 3 => Some(Self::AbstractOperation(AbstractOperationKind::GetIteratorFromMethod)),- 4 => Some(Self::AbstractOperation(AbstractOperationKind::IteratorComplete)),- 5 => Some(Self::AbstractOperation(AbstractOperationKind::ArraySpeciesCreate)),- _ => None,- },- _ => None,- }- }-}--struct ExceptionHandlerTable<'a>(&'a [ExceptionHandler]);--impl Encode for ExceptionHandlerTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- DecodedRecordSequence::encode(encoder, self.0, |handler, encoder| {- handler.start_offset.encode(encoder);- handler.end_offset.encode(encoder);- handler.handler_offset.encode(encoder);- handler.catches_exception.encode(encoder);- });- }-}--impl ExceptionHandlerTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedExceptionHandlerTable> {- Some(DecodedExceptionHandlerTable {- sequence: DecodedRecordSequence::decode(decoder)?,- })- }-}--pub(crate) struct DecodedExceptionHandlerTable {- sequence: DecodedRecordSequence,-}--impl DecodedExceptionHandlerTable {- pub(crate) fn values(&self) -> Option<Vec<ExceptionHandler>> {- let mut decoder = self.sequence.decoder();- let mut values = Vec::with_capacity(self.sequence.len());- for _ in 0..self.sequence.len() {- values.push(ExceptionHandler {- start_offset: u32::decode(&mut decoder)?,- end_offset: u32::decode(&mut decoder)?,- handler_offset: u32::decode(&mut decoder)?,- catches_exception: bool::decode(&mut decoder)?,- });- }- decoder.is_empty().then_some(values)- }-}--struct SourceMapTable<'a>(&'a [SourceMapEntry]);--impl Encode for SourceMapTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- DecodedRecordSequence::encode(encoder, self.0, |entry, encoder| {- entry.bytecode_offset.encode(encoder);- entry.line.encode(encoder);- entry.column.encode(encoder);- });- }-}--impl SourceMapTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedSourceMapTable> {- Some(DecodedSourceMapTable {- sequence: DecodedRecordSequence::decode(decoder)?,- })- }-}--pub(crate) struct DecodedSourceMapTable {- sequence: DecodedRecordSequence,-}--impl DecodedSourceMapTable {- pub(crate) fn values(&self) -> Option<Vec<SourceMapEntry>> {- let mut decoder = self.sequence.decoder();- let mut values = Vec::with_capacity(self.sequence.len());- for _ in 0..self.sequence.len() {- values.push(SourceMapEntry {- bytecode_offset: u32::decode(&mut decoder)?,- line: u32::decode(&mut decoder)?,- column: u32::decode(&mut decoder)?,- });- }- decoder.is_empty().then_some(values)- }-}--struct LocalVariableTable<'a>(&'a [LocalVariable]);--impl Encode for LocalVariableTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- DecodedRecordSequence::encode(encoder, self.0, |local_variable, encoder| {- Utf16(&local_variable.name.to_utf16()).encode(encoder);- local_variable.is_lexically_declared.encode(encoder);- local_variable- .is_initialized_during_declaration_instantiation- .encode(encoder);- local_variable.is_mutable.encode(encoder);- local_variable.scope_range.is_some().encode(encoder);- if let Some(range) = local_variable.scope_range {- range.start.line.encode(encoder);- range.start.column.encode(encoder);- range.end.line.encode(encoder);- range.end.column.encode(encoder);- }- });- }-}--impl LocalVariableTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedLocalVariableTable> {- Some(DecodedLocalVariableTable {- sequence: DecodedRecordSequence::decode(decoder)?,- })- }-}--pub(crate) struct DecodedLocalVariableTable {- sequence: DecodedRecordSequence,-}--impl DecodedLocalVariableTable {- fn len(&self) -> usize {- self.sequence.len()- }-- pub(crate) fn values(&self) -> Option<Vec<DecodedLocalVariable>> {- let mut decoder = self.sequence.decoder();- let mut values = Vec::with_capacity(self.sequence.len());- for _ in 0..self.sequence.len() {- values.push(DecodedLocalVariable {- name: DecodedUtf16String::decode(&mut decoder)?,- is_lexically_declared: bool::decode(&mut decoder)?,- is_initialized_during_declaration_instantiation: bool::decode(&mut decoder)?,- is_mutable: bool::decode(&mut decoder)?,- scope_range: if bool::decode(&mut decoder)? {- Some(crate::ast::SourceRange {- start: crate::ast::Position {- line: u32::decode(&mut decoder)?,- column: u32::decode(&mut decoder)?,- offset: 0,- },- end: crate::ast::Position {- line: u32::decode(&mut decoder)?,- column: u32::decode(&mut decoder)?,- offset: 0,- },- })- } else {- None- },- });- }- decoder.is_empty().then_some(values)- }-- fn local_variables(&self) -> Option<Vec<LocalVariable>> {- // The names point into the bytes of this table, which keep the blob alive while they are converted.- Some(- self.values()?- .into_iter()- .map(|local_variable| LocalVariable {- name: local_variable.name.to_fly_string(),- is_lexically_declared: local_variable.is_lexically_declared,- is_initialized_during_declaration_instantiation: local_variable- .is_initialized_during_declaration_instantiation,- is_mutable: local_variable.is_mutable,- scope_range: local_variable.scope_range,- })- .collect(),- )- }-}--pub(crate) struct DecodedLocalVariable {- pub(crate) name: DecodedUtf16String,- pub(crate) is_lexically_declared: bool,- pub(crate) is_initialized_during_declaration_instantiation: bool,- pub(crate) is_mutable: bool,- pub(crate) scope_range: Option<crate::ast::SourceRange>,-}--struct SharedFunctionTable<'a>(&'a [PendingSharedFunctionData]);--impl Encode for SharedFunctionTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- DecodedRecordSequence::encode_with_alignment(encoder, self.0, BYTECODE_ALIGNMENT, |shared_data, encoder| {- FunctionRecord(shared_data).encode(encoder);- });- }-}--impl SharedFunctionTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedFunctionTable> {- Some(DecodedFunctionTable {- sequence: DecodedRecordSequence::decode_with_alignment(decoder, BYTECODE_ALIGNMENT)?,- })- }-}--pub(crate) struct DecodedFunctionTable {- sequence: DecodedRecordSequence,-}--impl DecodedFunctionTable {- fn len(&self) -> usize {- self.sequence.len()- }-- pub(crate) fn values(&self) -> Option<Vec<DecodedFunctionRecord>> {- let mut decoder = self.sequence.decoder();- let mut values = Vec::with_capacity(self.sequence.len());- for _ in 0..self.sequence.len() {- values.push(FunctionRecord::decode(&mut decoder)?);- }- decoder.is_empty().then_some(values)- }-- fn validate_for_materialization(&self, source_len: usize) -> Result<(), ValidationErrorKind> {- let mut decoder = self.sequence.decoder();- for _ in 0..self.sequence.len() {- let function = FunctionRecord::decode(&mut decoder).ok_or(ValidationErrorKind::InvalidLength)?;- function.validate_for_materialization(source_len)?;- }- decoder- .is_empty()- .then_some(())- .ok_or(ValidationErrorKind::InvalidLength)- }-}--struct DeclarationFunctionTable<'a>(&'a [PendingSharedFunctionData]);--impl Encode for DeclarationFunctionTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- u32_from_usize(self.0.len()).encode(encoder);- let mut payload_encoder = Encoder::new();- for shared_data in self.0 {- FunctionRecord(shared_data).encode(&mut payload_encoder);- }- encoder.align_bytes_payload_to(BYTECODE_ALIGNMENT);- Bytes(&payload_encoder.finish()).encode(encoder);- }-}--impl DeclarationFunctionTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Vec<DecodedFunctionRecord>> {- let count: usize = u32::decode(decoder)?.try_into().ok()?;- decoder.align_bytes_payload_to(BYTECODE_ALIGNMENT)?;- let byte_length: usize = u32::decode(decoder)?.try_into().ok()?;- if count > byte_length {- return None;- }- let bytes = decoder.bytecode_bytes(byte_length)?;- let mut decoder = bytes.decoder();- let mut values = Vec::with_capacity(count);- for _ in 0..count {- values.push(FunctionRecord::decode(&mut decoder)?);- }- decoder.is_empty().then_some(values)- }-}--struct FunctionRecord<'a>(&'a PendingSharedFunctionData);--impl Encode for FunctionRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- let function_data = self- .0- .function_data- .as_ref()- .expect("bytecode cache requires function data to be retained until serialization");- let precompiled = self- .0- .precompiled_function- .as_ref()- .expect("fully compiled bytecode cache entry is missing nested function bytecode");-- self.function_name(function_data).encode(encoder);- function_data.source_text_start.encode(encoder);- function_data.source_text_end.encode(encoder);- function_data.function_length.encode(encoder);- u32_from_usize(function_data.parameters.len()).encode(encoder);- (function_data.kind as u8).encode(encoder);- function_data.is_strict_mode.encode(encoder);- function_data.is_arrow_function.encode(encoder);- SimpleParameterList {- function_data,- arena: self.function_arena(),- }- .encode(encoder);- function_data.parsing_insights.uses_this.encode(encoder);- function_data- .parsing_insights- .uses_this_from_environment- .encode(encoder);- ClassFieldInitializerName(self.0).encode(encoder);- precompiled.metadata.encode(encoder);- PrecompiledFunctionRecord(precompiled).encode(encoder);- }-}--impl FunctionRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedFunctionRecord> {- Some(DecodedFunctionRecord {- name: Option::<DecodedUtf16String>::decode(decoder)?,- source_text_start: u32::decode(decoder)?,- source_text_end: u32::decode(decoder)?,- function_length: i32::decode(decoder)?,- formal_parameter_count: u32::decode(decoder)?,- kind: ast::FunctionKind::decode(decoder)?,- is_strict_mode: bool::decode(decoder)?,- is_arrow_function: bool::decode(decoder)?,- parameter_names: SimpleParameterList::decode(decoder)?,- uses_this: bool::decode(decoder)?,- uses_this_from_environment: bool::decode(decoder)?,- class_field_initializer_name: ClassFieldInitializerName::decode(decoder)?,- metadata: FunctionSfdMetadata::decode(decoder)?,- precompiled: PrecompiledFunctionRecord::decode(decoder)?,- })- }-}--/// One function a cached executable creates or a cached program declares. The strings it returns stay in the blob.-pub struct DecodedFunctionRecord {- pub(crate) name: Option<DecodedUtf16String>,- pub(crate) source_text_start: u32,- pub(crate) source_text_end: u32,- pub(crate) function_length: i32,- pub(crate) formal_parameter_count: u32,- pub(crate) kind: ast::FunctionKind,- pub(crate) is_strict_mode: bool,- pub(crate) is_arrow_function: bool,- pub(crate) parameter_names: Option<Vec<DecodedUtf16String>>,- pub(crate) uses_this: bool,- pub(crate) uses_this_from_environment: bool,- pub(crate) class_field_initializer_name: Option<(DecodedUtf16String, bool)>,- pub(crate) metadata: FunctionSfdMetadata,- pub(crate) precompiled: DecodedCachedExecutableRecord,-}--impl DecodedFunctionRecord {- fn validate_for_materialization(&self, source_len: usize) -> Result<(), ValidationErrorKind> {- if !source_span_is_valid(self.source_text_start, self.source_text_end, source_len) {- return Err(ValidationErrorKind::InvalidLength);- }- self.precompiled.validate_for_materialization(source_len)- }-- // NB: The strings of a record point into the blob, which the record's own bytecode keeps alive.- pub fn function_name(&self) -> Option<Cow<'_, [u16]>> {- self.name.as_ref().map(DecodedUtf16String::code_units)- }-- /// Where the function's source text starts and ends in the source code, in code units.- pub fn source_text_range(&self) -> Range<usize> {- self.source_text_start as usize..self.source_text_end as usize- }-- pub fn length(&self) -> i32 {- self.function_length- }-- pub fn parameter_count(&self) -> u32 {- self.formal_parameter_count- }-- pub fn function_kind(&self) -> ast::FunctionKind {- self.kind- }-- /// Whether the function's own code is strict, which does not count code it is nested in.- pub fn has_strict_code(&self) -> bool {- self.is_strict_mode- }-- pub fn is_arrow(&self) -> bool {- self.is_arrow_function- }-- /// The names of the parameters if the parameter list is simple, and `None` otherwise.- pub fn simple_parameter_names(&self) -> Option<Vec<ak::Utf16FlyString>> {- Some(- self.parameter_names- .as_ref()?- .iter()- .map(DecodedUtf16String::to_fly_string)- .collect(),- )- }-- /// What parsing found out about the function's use of `this`: whether it does, and whether it resolves `this`- /// through its environment.- pub fn parsing_insights_about_this(&self) -> (bool, bool) {- (self.uses_this, self.uses_this_from_environment)- }-- /// The name of the field whose initializer the function is, and whether that field is private.- pub fn field_initializer_name(&self) -> Option<(Cow<'_, [u16]>, bool)> {- self.class_field_initializer_name- .as_ref()- .map(|(name, is_private)| (name.code_units(), *is_private))- }-- pub fn scope_metadata(&self) -> &FunctionSfdMetadata {- &self.metadata- }-- /// The function's own executable, which stays in the blob until the function is first called.- pub fn cached_executable(&self) -> DecodedCachedExecutableRecord {- // Records are only reachable from outside this module through a blob that passed validation.- self.precompiled.validated_copy(CachedBytecodeValidation::Validated)- }-}--impl<'a> FunctionRecord<'a> {- fn function_name(&self, function_data: &'a ast::FunctionData) -> Option<Utf16<'a>> {- self.0- .name_override- .as_deref()- .or_else(|| function_data.name.map(|name| self.function_arena().name_slice(name)))- .map(Utf16)- }-- fn function_arena(&self) -> &'a ast::AstArena {- self.0- .arena- .as_deref()- .expect("bytecode cache function is missing its AST arena")- }-}--struct SimpleParameterList<'a> {- function_data: &'a ast::FunctionData,- arena: &'a ast::AstArena,-}--impl Encode for SimpleParameterList<'_> {- fn encode(&self, encoder: &mut Encoder) {- let names = simple_parameter_names(self.function_data, self.arena);- names.is_some().encode(encoder);- if let Some(names) = names {- encoder.sequence(&names, |name, encoder| Utf16(name).encode(encoder));- }- }-}--impl SimpleParameterList<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Option<Vec<DecodedUtf16String>>> {- if bool::decode(decoder)? {- Some(Some(decoder.sequence_values(DecodedUtf16String::decode)?))- } else {- Some(None)- }- }-}--fn simple_parameter_names<'a>(- function_data: &'a ast::FunctionData,- arena: &'a ast::AstArena,-) -> Option<Vec<&'a [u16]>> {- let mut names = Vec::with_capacity(function_data.parameters.len());- for parameter in &function_data.parameters {- if parameter.is_rest || parameter.default_value.is_some() {- return None;- }- let ast::FunctionParameterBinding::Identifier(identifier) = ¶meter.binding else {- return None;- };- names.push(arena.name_slice(*identifier));- }- Some(names)-}--struct ClassFieldInitializerName<'a>(&'a PendingSharedFunctionData);--impl Encode for ClassFieldInitializerName<'_> {- fn encode(&self, encoder: &mut Encoder) {- self.0- .class_field_initializer_name- .as_ref()- .map(|(name, is_private)| (Utf16(name.as_slice()), *is_private))- .encode(encoder);- }-}--impl ClassFieldInitializerName<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<Option<(DecodedUtf16String, bool)>> {- Option::<(DecodedUtf16String, bool)>::decode(decoder)- }-}--impl Encode for (Utf16<'_>, bool) {- fn encode(&self, encoder: &mut Encoder) {- self.0.encode(encoder);- self.1.encode(encoder);- }-}--impl Decode for (DecodedUtf16String, bool) {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some((DecodedUtf16String::decode(decoder)?, bool::decode(decoder)?))- }-}--impl Encode for FunctionSfdMetadata {- fn encode(&self, encoder: &mut Encoder) {- self.uses_this.encode(encoder);- self.this_value_needs_environment_resolution.encode(encoder);- self.function_environment_needed.encode(encoder);- self.function_environment_bindings_count.encode(encoder);- self.var_environment_bindings_count.encode(encoder);- self.might_need_arguments.encode(encoder);- self.contains_eval.encode(encoder);- }-}--impl FunctionSfdMetadata {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- Some(Self {- uses_this: bool::decode(decoder)?,- this_value_needs_environment_resolution: bool::decode(decoder)?,- function_environment_needed: bool::decode(decoder)?,- function_environment_bindings_count: usize::decode(decoder)?,- var_environment_bindings_count: usize::decode(decoder)?,- might_need_arguments: bool::decode(decoder)?,- contains_eval: bool::decode(decoder)?,- })- }-}--struct PrecompiledFunctionRecord<'a>(&'a PrecompiledFunction);--impl Encode for PrecompiledFunctionRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- let mut payload_encoder = Encoder::new();- ExecutableRecord(&self.0.executable).encode(&mut payload_encoder);- encoder.align_bytes_payload_to(BYTECODE_ALIGNMENT);- Bytes(&payload_encoder.finish()).encode(encoder);- }-}--impl PrecompiledFunctionRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedCachedExecutableRecord> {- decoder.align_bytes_payload_to(BYTECODE_ALIGNMENT)?;- Some(DecodedCachedExecutableRecord {- bytes: DecodedBytecodeBytes::decode(decoder)?,- has_been_validated_for_materialization: false,- })- }-}--struct ClassBlueprintTable<'a>(&'a [PendingClassBlueprint]);--impl Encode for ClassBlueprintTable<'_> {- fn encode(&self, encoder: &mut Encoder) {- DecodedRecordSequence::encode(encoder, self.0, |blueprint, encoder| {- ClassBlueprintRecord(blueprint).encode(encoder);- });- }-}--impl ClassBlueprintTable<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedClassBlueprintTable> {- Some(DecodedClassBlueprintTable {- sequence: DecodedRecordSequence::decode(decoder)?,- })- }-}--pub(crate) struct DecodedClassBlueprintTable {- sequence: DecodedRecordSequence,-}--impl DecodedClassBlueprintTable {- fn len(&self) -> usize {- self.sequence.len()- }-- pub(crate) fn values(&self) -> Option<Vec<DecodedClassBlueprintRecord>> {- let mut decoder = self.sequence.decoder();- let mut values = Vec::with_capacity(self.sequence.len());- for _ in 0..self.sequence.len() {- values.push(ClassBlueprintRecord::decode(&mut decoder)?);- }- decoder.is_empty().then_some(values)- }-- fn for_each(&self, mut callback: impl FnMut(DecodedClassBlueprintRecord) -> Option<()>) -> Option<()> {- let mut decoder = self.sequence.decoder();- for _ in 0..self.sequence.len() {- callback(ClassBlueprintRecord::decode(&mut decoder)?)?;- }- decoder.is_empty().then_some(())- }-- fn validate_for_materialization(- &self,- source_len: usize,- shared_function_count: usize,- ) -> Result<(), ValidationErrorKind> {- self.for_each(|blueprint| {- (blueprint.source_range_is_valid(source_len) && blueprint.indices_are_valid(shared_function_count))- .then_some(())- })- .ok_or(ValidationErrorKind::InvalidLength)- }-}--struct ClassBlueprintRecord<'a>(&'a PendingClassBlueprint);--impl Encode for ClassBlueprintRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- self.0.name.as_deref().map(Utf16).encode(encoder);- self.0.source_text_offset.encode(encoder);- self.0.source_text_length.encode(encoder);- self.0.constructor_sfd_index.encode(encoder);- self.0.has_super_class.encode(encoder);- self.0.has_name.encode(encoder);- encoder.sequence(&self.0.elements, |element, encoder| {- ClassElementRecord(element).encode(encoder);- });- }-}--impl ClassBlueprintRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedClassBlueprintRecord> {- Some(DecodedClassBlueprintRecord {- name: Option::<DecodedUtf16String>::decode(decoder)?,- source_text_offset: usize::decode(decoder)?,- source_text_length: usize::decode(decoder)?,- constructor_sfd_index: u32::decode(decoder)?,- has_super_class: bool::decode(decoder)?,- has_name: bool::decode(decoder)?,- elements: decoder.sequence_values(ClassElementRecord::decode)?,- })- }-}--pub(crate) struct DecodedClassBlueprintRecord {- name: Option<DecodedUtf16String>,- source_text_offset: usize,- source_text_length: usize,- constructor_sfd_index: u32,- has_super_class: bool,- has_name: bool,- elements: Vec<DecodedClassElementRecord>,-}--impl DecodedClassBlueprintRecord {- fn source_range_is_valid(&self, source_len: usize) -> bool {- source_range_is_valid(self.source_text_offset, self.source_text_length, source_len)- }-- fn indices_are_valid(&self, shared_function_count: usize) -> bool {- (self.constructor_sfd_index as usize) < shared_function_count- && self- .elements- .iter()- .all(|element| element.indices_are_valid(shared_function_count))- }-}--impl From<&DecodedClassBlueprintRecord> for PendingClassBlueprint {- fn from(record: &DecodedClassBlueprintRecord) -> Self {- Self {- name: record.name.as_ref().map(DecodedUtf16String::to_utf16_string),- source_text_offset: record.source_text_offset,- source_text_length: record.source_text_length,- constructor_sfd_index: record.constructor_sfd_index,- has_super_class: record.has_super_class,- has_name: record.has_name,- elements: record.elements.iter().map(PendingClassElement::from).collect(),- }- }-}--struct ClassElementRecord<'a>(&'a PendingClassElement);--impl Encode for ClassElementRecord<'_> {- fn encode(&self, encoder: &mut Encoder) {- self.0.kind.encode(encoder);- self.0.is_static.encode(encoder);- self.0.is_private.encode(encoder);- self.0.private_identifier.as_deref().map(Utf16).encode(encoder);- self.0.shared_function_data_index.encode(encoder);- self.0.has_initializer.encode(encoder);- literal_value_kind_tag(self.0.literal_value_kind).encode(encoder);- self.0.literal_value_number.encode(encoder);- self.0.literal_value_string.as_deref().map(Utf16).encode(encoder);- }-}--impl ClassElementRecord<'_> {- fn decode(decoder: &mut Decoder<'_>) -> Option<DecodedClassElementRecord> {- Some(DecodedClassElementRecord {- kind: u8::decode(decoder)?,- is_static: bool::decode(decoder)?,- is_private: bool::decode(decoder)?,- private_identifier: Option::<DecodedUtf16String>::decode(decoder)?,- shared_function_data_index: Option::<u32>::decode(decoder)?,- has_initializer: bool::decode(decoder)?,- literal_value_kind: PendingLiteralValueKind::decode(decoder)?,- literal_value_number: f64::decode(decoder)?,- literal_value_string: Option::<DecodedUtf16String>::decode(decoder)?,- })- }-}--pub(crate) struct DecodedClassElementRecord {- kind: u8,- is_static: bool,- is_private: bool,- private_identifier: Option<DecodedUtf16String>,- shared_function_data_index: Option<u32>,- has_initializer: bool,- literal_value_kind: PendingLiteralValueKind,- literal_value_number: f64,- literal_value_string: Option<DecodedUtf16String>,-}--impl DecodedClassElementRecord {- fn indices_are_valid(&self, shared_function_count: usize) -> bool {- let shared_function_data_index_is_valid = || {- self.shared_function_data_index- .is_some_and(|index| (index as usize) < shared_function_count)- };-- match self.kind {- 0 | 1 | 2 | 4 => shared_function_data_index_is_valid(),- 3 => {- if self.has_initializer && matches!(self.literal_value_kind, PendingLiteralValueKind::None) {- shared_function_data_index_is_valid()- } else {- self.shared_function_data_index- .is_none_or(|index| (index as usize) < shared_function_count)- }- }- _ => false,- }- }-}--impl From<&DecodedClassElementRecord> for PendingClassElement {- fn from(record: &DecodedClassElementRecord) -> Self {- Self {- kind: record.kind,- is_static: record.is_static,- is_private: record.is_private,- private_identifier: record- .private_identifier- .as_ref()- .map(DecodedUtf16String::to_utf16_string),- shared_function_data_index: record.shared_function_data_index,- has_initializer: record.has_initializer,- literal_value_kind: record.literal_value_kind,- literal_value_number: record.literal_value_number,- literal_value_string: record- .literal_value_string- .as_ref()- .map(DecodedUtf16String::to_utf16_string),- }- }-}--impl Decode for PendingLiteralValueKind {- fn decode(decoder: &mut Decoder<'_>) -> Option<Self> {- match u8::decode(decoder)? {- 0 => Some(Self::None),- 1 => Some(Self::Number),- 2 => Some(Self::BooleanTrue),- 3 => Some(Self::BooleanFalse),- 4 => Some(Self::Null),- 5 => Some(Self::String),- _ => None,- }- }-}--fn literal_value_kind_tag(kind: PendingLiteralValueKind) -> u8 {- match kind {- PendingLiteralValueKind::None => 0,- PendingLiteralValueKind::Number => 1,- PendingLiteralValueKind::BooleanTrue => 2,- PendingLiteralValueKind::BooleanFalse => 3,- PendingLiteralValueKind::Null => 4,- PendingLiteralValueKind::String => 5,- }-}--#[cfg(test)]-mod tests {- use std::cell::Cell;-- use super::*;-- /// Blob bytes as an embedder owns them: aligned the way an embedder's blob is, and counting their releases.- struct TestBlobStorage {- words: Vec<u64>,- releases: Rc<Cell<usize>>,- }-- unsafe extern "C" fn release_test_blob(owner: *mut c_void) {- let storage = unsafe { Box::from_raw(owner.cast::<TestBlobStorage>()) };- storage.releases.set(storage.releases.get() + 1);- }-- /// Copies `bytes` into storage of the returned owner, which adds one to `releases` when it is released.- fn test_blob(bytes: &[u8], releases: &Rc<Cell<usize>>) -> (&'static [u8], BytecodeCacheBlobOwner) {- let mut storage = Box::new(TestBlobStorage {- words: vec![0u64; bytes.len().div_ceil(size_of::<u64>())],- releases: releases.clone(),- });- // SAFETY: The words have room for every byte.- unsafe {- std::ptr::copy_nonoverlapping(bytes.as_ptr(), storage.words.as_mut_ptr().cast::<u8>(), bytes.len());- }- // SAFETY: The owner keeps the words alive until the decoded blob releases it.- let view = unsafe { ak::slice_from_raw_parts(storage.words.as_ptr().cast::<u8>(), bytes.len()) };- let owner = BytecodeCacheBlobOwner::Foreign {- owner: Box::into_raw(storage).cast(),- free_owner: release_test_blob,- };- (view, owner)- }-- fn decode_test_blob(- bytes: &[u8],- expected_program_type: ast::ProgramType,- expected_source_hash: &[u8; SOURCE_HASH_SIZE],- releases: &Rc<Cell<usize>>,- ) -> Option<DecodedCacheBlob> {- decode_test_blob_for_runtime(- bytes,- expected_program_type,- expected_source_hash,- BytecodeCacheRuntime::Rust,- releases,- )- }-- fn decode_test_blob_for_runtime(- bytes: &[u8],- expected_program_type: ast::ProgramType,- expected_source_hash: &[u8; SOURCE_HASH_SIZE],- expected_runtime: BytecodeCacheRuntime,- releases: &Rc<Cell<usize>>,- ) -> Option<DecodedCacheBlob> {- let (view, owner) = test_blob(bytes, releases);- // SAFETY: The owner keeps the view alive.- unsafe {- decode_blob(- view,- expected_program_type,- expected_source_hash,- expected_runtime,- owner,- )- }- }-- fn empty_record_sequence(encoder: &mut Encoder) {- DecodedRecordSequence::encode::<u8>(encoder, &[], |_, _| {});- }-- fn executable_record_with_shared_function(function_payload: Option<Vec<u8>>) -> Vec<u8> {- let mut encoder = Encoder::new();-- false.encode(&mut encoder); // Strict.- 0u32.encode(&mut encoder); // Number of registers.- 0u32.encode(&mut encoder); // Number of arguments.- for _ in 0..11 {- 0u32.encode(&mut encoder); // Cache and feedback slot counters.- }- false.encode(&mut encoder); // This value needs environment resolution.- Option::<u32>::None.encode(&mut encoder); // Length identifier.-- encoder.align_bytes_payload_to(BYTECODE_ALIGNMENT);- Bytes(&[]).encode(&mut encoder); // Bytecode.- empty_record_sequence(&mut encoder); // Identifier table.- empty_record_sequence(&mut encoder); // Property key table.- empty_record_sequence(&mut encoder); // String table.- 0u32.encode(&mut encoder); // Constant count.- Bytes(&[]).encode(&mut encoder);- empty_record_sequence(&mut encoder); // Exception handlers.- empty_record_sequence(&mut encoder); // Source map.- empty_record_sequence(&mut encoder); // Local variables.- empty_record_sequence(&mut encoder); // Argument variable names.-- match function_payload {- Some(payload) => {- 1u32.encode(&mut encoder); // Shared function count.- encoder.align_bytes_payload_to(BYTECODE_ALIGNMENT);- Bytes(&payload).encode(&mut encoder);- }- None => {- DecodedRecordSequence::encode_with_alignment::<u8>(&mut encoder, &[], BYTECODE_ALIGNMENT, |_, _| {});- }- }-- empty_record_sequence(&mut encoder); // Class blueprints.- encoder.finish()- }-- fn function_payload(source_text_start: u32, source_text_end: u32) -> Vec<u8> {- let mut encoder = Encoder::new();-- Option::<Utf16<'_>>::None.encode(&mut encoder); // Function name.- source_text_start.encode(&mut encoder);- source_text_end.encode(&mut encoder);- 0i32.encode(&mut encoder); // Function length.- 0u32.encode(&mut encoder); // Formal parameter count.- (ast::FunctionKind::Normal as u8).encode(&mut encoder);- false.encode(&mut encoder); // Strict mode.- false.encode(&mut encoder); // Arrow function.- false.encode(&mut encoder); // Simple parameter list.- false.encode(&mut encoder); // Uses this.- false.encode(&mut encoder); // Uses this from environment.- Option::<(Utf16<'_>, bool)>::None.encode(&mut encoder); // Class field initializer name.- FunctionSfdMetadata {- uses_this: false,- this_value_needs_environment_resolution: false,- function_environment_needed: false,- function_environment_bindings_count: 0,- var_environment_bindings_count: 0,- might_need_arguments: false,- contains_eval: false,- }- .encode(&mut encoder);-- encoder.align_bytes_payload_to(BYTECODE_ALIGNMENT);- Bytes(&executable_record_with_shared_function(None)).encode(&mut encoder);-- encoder.finish()- }-- fn cached_executable(bytes: &[u8]) -> DecodedCachedExecutableRecord {- let (view, owner) = test_blob(bytes, &Rc::default());- let mut decoder = Decoder::new(view, Some(owner));- DecodedCachedExecutableRecord {- bytes: decoder.bytecode_bytes(view.len()).expect("the record fits in its blob"),- has_been_validated_for_materialization: false,- }- }-- #[test]- fn sequence_decode_rejects_lengths_larger_than_remaining_bytes() {- let bytes = u32::MAX.to_le_bytes();-- let mut decoder = Decoder::new(&bytes, None);- assert!(decoder.sequence_values(u8::decode).is_none());- }-- #[test]- fn sequence_decode_rejects_truncated_items_without_large_allocation() {- let mut bytes = Vec::new();- bytes.extend_from_slice(&4u32.to_le_bytes());- bytes.extend_from_slice(&[1, 2, 3]);-- let mut decoder = Decoder::new(&bytes, None);- assert!(decoder.sequence_values(u8::decode).is_none());- }-- #[test]- fn record_sequence_decode_rejects_impossible_count_without_large_allocation() {- let mut bytes = Vec::new();- bytes.extend_from_slice(&4u32.to_le_bytes());- bytes.extend_from_slice(&1u32.to_le_bytes());- bytes.push(0);-- let mut decoder = Decoder::new(&bytes, None);- assert!(DecodedRecordSequence::decode(&mut decoder).is_none());- }-- #[test]- fn constant_table_decode_rejects_impossible_count_without_large_allocation() {- let mut bytes = Vec::new();- bytes.extend_from_slice(&4u32.to_le_bytes());- bytes.extend_from_slice(&1u32.to_le_bytes());- bytes.push(0);-- let mut decoder = Decoder::new(&bytes, None);- assert!(ConstantTable::decode(&mut decoder).is_none());- }-- #[test]- fn decode_rejects_mismatched_source_hash_before_payload() {- let stored_source_hash = [1u8; SOURCE_HASH_SIZE];- let expected_source_hash = [2u8; SOURCE_HASH_SIZE];-- let mut bytes = Vec::new();- bytes.extend_from_slice(MAGIC);- bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());- bytes.extend_from_slice(&INSTRUCTION_SET_FINGERPRINT.to_le_bytes());- bytes.push(BytecodeCacheRuntime::Rust.tag());- bytes.push(ast::ProgramType::Script as u8);- bytes.extend_from_slice(&stored_source_hash);-- let releases = Rc::default();- assert!(decode_test_blob(&bytes, ast::ProgramType::Script, &expected_source_hash, &releases).is_none());- assert_eq!(releases.get(), 1);- }-- #[test]- fn decode_rejects_another_instruction_set() {- let source_hash = [1u8; SOURCE_HASH_SIZE];-- let mut bytes = Vec::new();- bytes.extend_from_slice(MAGIC);- bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());- bytes.extend_from_slice(&(INSTRUCTION_SET_FINGERPRINT ^ 1).to_le_bytes());- bytes.push(BytecodeCacheRuntime::Rust.tag());- bytes.push(ast::ProgramType::Script as u8);- bytes.extend_from_slice(&source_hash);-- let releases = Rc::default();- assert!(decode_test_blob(&bytes, ast::ProgramType::Script, &source_hash, &releases).is_none());- assert_eq!(releases.get(), 1);- }-- #[test]- fn utf16_decode_borrows_from_foreign_blob() {- let mut bytes = Vec::new();- bytes.extend_from_slice(&3u32.to_le_bytes());- bytes.extend_from_slice(&0x41u16.to_le_bytes());- bytes.extend_from_slice(&0x2262u16.to_le_bytes());- bytes.extend_from_slice(&0x0391u16.to_le_bytes());-- let (view, owner) = test_blob(&bytes, &Rc::default());- let mut decoder = Decoder::new(view, Some(owner));- let decoded = DecodedUtf16String::decode(&mut decoder).unwrap();- assert!(matches!(decoded, DecodedUtf16String::Foreign { .. }));- assert_eq!(decoded.to_vec(), vec![0x41, 0x2262, 0x0391]);- }-- #[test]- fn cached_function_validation_includes_nested_source_ranges() {- let executable = cached_executable(&executable_record_with_shared_function(Some(function_payload(20, 21))));-- assert_eq!(- executable.validate_for_materialization(10),- Err(ValidationErrorKind::InvalidLength)- );- assert_eq!(executable.validate_for_materialization(30), Ok(()));- }-}diff --git a/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rs b/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rsdeleted file mode 100644index 9e5edb73e60..00000000000--- a/Libraries/LibJS/Rust/src/embedding/bytecode_cache.rs+++ /dev/null@@ -1,460 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! The bytecode cache: blobs of programs compiled with all their functions, which an embedder stores keyed by a hash-//! of the source and loads again instead of compiling, as C++ LibJS/ScriptCompilation.h, JS::DecodedBytecodeCache and-//! the bytecode cache methods of JS::Script and JS::SourceTextModule offer it.-//!-//! Serializing, decoding and validating need no VM, so any thread may do them. A decoded cache is reference counted-//! without atomics, like JS::DecodedBytecodeCache: the thread that decoded it may hand it to the VM's thread while-//! nothing else holds a reference to it, and from then on only the VM's thread may use it.-//!-//! Scripts and modules materialized from a cache run their bytecode in place in the blob's bytes, which stay alive as-//! long as any of them, or the cache, does. A blob whose tag names another runtime is rejected like a corrupt one.--use core::ffi::c_void;-use std::rc::Rc;--use crate::bytecode::bytecode_cache::DecodedBytecodeCache;-use crate::bytecode_cache::{BytecodeCacheBlobOwner, BytecodeCacheRuntime, decode_blob, serialize_compiled_program};-use crate::compile::FunctionPrecompileMode;-use crate::embedding::abi_types::{- JSByteSink, JSRealm, JSSourceCode, JSUtf16View, cell_from_abi, cell_into_abi, vm_from_abi,-};-use crate::embedding::compile::{- JSCompiledProgram, JSProgramType, compiled_program_from_abi, program_type_from_abi, source_text_module_from_abi,-};-use crate::embedding::script::{JSParserErrorSink, JSScript, append_to_parser_error_sink, host_defined_slot_from_abi};-use crate::embedding::source_code::shared_source_code_from_abi;-use crate::layout::host_class::{JSModule, JSVM};-use crate::runtime::module::Module;-use crate::runtime::source_text_module::SourceTextModule;-use crate::script::Script;--/// A decoded bytecode cache blob: LibJS's JS::DecodedBytecodeCache.-pub struct JSDecodedBytecodeCache {- _opaque: [u8; 0],-}--/// The size of the hash of the source that keys a blob.-pub const JS_BYTECODE_CACHE_SOURCE_HASH_SIZE: usize = 32;--/// The alignment that the bytes of a blob need for the runtime to run them in place. The runtime copies the bytes of a-/// blob that is not aligned this way.-pub const JS_BYTECODE_CACHE_BLOB_ALIGNMENT: usize = 8;--/// The embedder's handle on the bytes of a blob, such as a Core::ImmutableBytes. The runtime calls `release` with-/// `owner` once, when nothing decoded from the bytes needs them anymore: on the decoding thread when it rejects the-/// blob, and on the VM's thread otherwise, possibly while the heap sweeps the last executable that ran from the-/// bytes, so `release` must not use the VM or its heap.-#[repr(C)]-pub struct JSBytecodeCacheBlobOwner {- pub owner: *mut c_void,- pub release: Option<unsafe extern "C" fn(owner: *mut c_void)>,-}--/// # Safety-///-/// `source_hash` must point to `source_hash_length` readable bytes.-unsafe fn source_hash_from_abi<'a>(- source_hash: *const u8,- source_hash_length: usize,-) -> Option<&'a [u8; JS_BYTECODE_CACHE_SOURCE_HASH_SIZE]> {- if source_hash.is_null() || source_hash_length != JS_BYTECODE_CACHE_SOURCE_HASH_SIZE {- return None;- }- // SAFETY: The caller passes readable bytes, which are as many as a hash has.- unsafe { ak::slice_from_raw_parts(source_hash, source_hash_length) }- .try_into()- .ok()-}--fn cache_into_abi(cache: DecodedBytecodeCache) -> *const JSDecodedBytecodeCache {- Rc::into_raw(Rc::new(cache)).cast()-}--/// # Safety-///-/// `cache` must be a live decoded cache, which stays alive for `'a`.-unsafe fn cache_from_abi<'a>(cache: *const JSDecodedBytecodeCache) -> &'a DecodedBytecodeCache {- assert!(!cache.is_null(), "the embedder passes a decoded bytecode cache");- // SAFETY: The caller passes a live cache, which is the contents of an Rc.- unsafe { &*cache.cast::<DecodedBytecodeCache>() }-}--/// CompiledProgram::serialize_for_bytecode_cache(type, source_hash): writes the blob of a program that-/// js_compile_parsed_program_with_all_functions() compiled, for a program of `program_type` whose source hashes to the-/// `source_hash_length` bytes of `source_hash`, to `sink`. Returns false, having written nothing or part of the blob,-/// for a program compiled without all its functions or of another type, for a hash of the wrong size, and when the-/// sink stops taking bytes. Borrows the program. Any thread may call this.-///-/// # Safety-///-/// `compiled` must be a live compiled program, `source_hash` must point to `source_hash_length` readable bytes, and-/// `sink` must be a valid sink.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_serialize(- compiled: *const JSCompiledProgram,- program_type: JSProgramType,- source_hash: *const u8,- source_hash_length: usize,- sink: *const JSByteSink,-) -> bool {- // SAFETY: The caller passes a live program, readable hash bytes and a valid sink.- let (compiled, source_hash, sink) = unsafe {- (- compiled_program_from_abi(compiled),- source_hash_from_abi(source_hash, source_hash_length),- sink.as_ref().expect("the embedder passes a sink"),- )- };- let program_type = program_type_from_abi(program_type);- let Some(source_hash) = source_hash else {- return false;- };- if compiled.function_precompile_mode() != FunctionPrecompileMode::All || compiled.program_type() != program_type {- return false;- }- let blob = serialize_compiled_program(compiled, program_type, source_hash, BytecodeCacheRuntime::Rust);- let append = sink.append.expect("a byte sink has an append function");- // SAFETY: The embedder's sink takes the bytes with the context it came with, and copies them.- unsafe { append(sink.context, blob.as_ptr(), blob.len()) }-}--const _: () = assert!(align_of::<u64>() == JS_BYTECODE_CACHE_BLOB_ALIGNMENT);--/// Decodes the blob in `bytes`, whose owner it takes over, releasing the owner if it rejects the blob.-///-/// # Safety-///-/// `bytes` must point to `length` bytes that stay alive and unchanged until the owner is released, and `source_hash`-/// must point to `source_hash_length` readable bytes.-unsafe fn decode(- bytes: *const u8,- length: usize,- program_type: JSProgramType,- source_hash: *const u8,- source_hash_length: usize,- owner: JSBytecodeCacheBlobOwner,-) -> Option<DecodedBytecodeCache> {- let release = owner.release.expect("the owner of a blob has a release function");- let release_owner = || {- // SAFETY: The embedder's release function takes the owner it handed over, once.- unsafe { release(owner.owner) };- };- // SAFETY: The caller passes readable hash bytes.- let Some(source_hash) = (unsafe { source_hash_from_abi(source_hash, source_hash_length) }) else {- release_owner();- return None;- };- if bytes.is_null() {- release_owner();- return None;- }- let program_type = program_type_from_abi(program_type);- // SAFETY: The caller passes bytes that stay alive and unchanged until the owner is released.- let bytes = unsafe { ak::slice_from_raw_parts(bytes, length) };-- let (bytes, owner) = if bytes.as_ptr().addr().is_multiple_of(JS_BYTECODE_CACHE_BLOB_ALIGNMENT) {- let owner = BytecodeCacheBlobOwner::Foreign {- owner: owner.owner,- free_owner: release,- };- (bytes, owner)- } else {- let mut words = vec![0; length.div_ceil(size_of::<u64>())];- for (word, chunk) in words.iter_mut().zip(bytes.chunks(size_of::<u64>())) {- let mut word_bytes = [0; size_of::<u64>()];- word_bytes[..chunk.len()].copy_from_slice(chunk);- *word = u64::from_ne_bytes(word_bytes);- }- release_owner();- // SAFETY: The words, which the owner below keeps, stay alive and unchanged.- let bytes = unsafe { ak::slice_from_raw_parts(words.as_ptr().cast::<u8>(), length) };- (bytes, BytecodeCacheBlobOwner::Aligned(words))- };- // SAFETY: The owner keeps the bytes alive and unchanged until it is released.- let blob = unsafe { decode_blob(bytes, program_type, source_hash, BytecodeCacheRuntime::Rust, owner) }?;- Some(DecodedBytecodeCache::new(blob))-}--/// DecodedBytecodeCache::create(bytes, type, source_hash): decodes the `length` bytes of a blob that-/// js_bytecode_cache_serialize() wrote for a program of `program_type` whose source hashes to the `source_hash_length`-/// bytes of `source_hash`. Validation against the source code happens when a script or module is created from it or-/// installs it. Returns the cache, whose one reference the caller owns, or null for a blob of another format version,-/// runtime, program type or source, and for a malformed one. Takes over `owner` either way. Any thread may call this.-///-/// # Safety-///-/// `bytes` must point to `length` bytes that stay alive and unchanged until the owner is released, `source_hash` must-/// point to `source_hash_length` readable bytes, and the owner's release function must accept the owner.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_decode(- bytes: *const u8,- length: usize,- program_type: JSProgramType,- source_hash: *const u8,- source_hash_length: usize,- owner: JSBytecodeCacheBlobOwner,-) -> *const JSDecodedBytecodeCache {- // SAFETY: The caller's guarantees are decode()'s.- unsafe { decode(bytes, length, program_type, source_hash, source_hash_length, owner) }- .map_or(core::ptr::null(), cache_into_abi)-}--/// decode_and_validate_bytecode_cache(bytes, type, source_hash, source_length_in_code_units): decodes a blob like-/// js_bytecode_cache_decode(), then validates it against source code of `source_length_in_code_units` code units:-/// every source range, table index and the bytecode of every executable. Returns null for a blob that does not pass,-/// having released its owner. Any thread may call this.-///-/// # Safety-///-/// As for js_bytecode_cache_decode().-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_decode_and_validate(- bytes: *const u8,- length: usize,- program_type: JSProgramType,- source_hash: *const u8,- source_hash_length: usize,- source_length_in_code_units: usize,- owner: JSBytecodeCacheBlobOwner,-) -> *const JSDecodedBytecodeCache {- // SAFETY: The caller's guarantees are decode()'s.- let Some(cache) = (unsafe { decode(bytes, length, program_type, source_hash, source_hash_length, owner) }) else {- return core::ptr::null();- };- if !cache.validate(source_length_in_code_units) {- return core::ptr::null();- }- cache_into_abi(cache)-}--/// Adds a reference to the cache, which the caller gives up with js_bytecode_cache_release(). Only the VM's thread may-/// call this.-///-/// # Safety-///-/// `cache` must be a live decoded cache.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_retain(cache: *const JSDecodedBytecodeCache) {- assert!(!cache.is_null(), "the embedder passes a decoded bytecode cache");- // SAFETY: The caller passes the contents of a live Rc.- unsafe { Rc::increment_strong_count(cache.cast::<DecodedBytecodeCache>()) };-}--/// Gives up a reference to the cache. The blob's bytes stay alive while a script or module made from them does. Only-/// the thread that owns the cache, which is the VM's thread once a record was made from it, may call this.-///-/// # Safety-///-/// `cache` must be a live decoded cache, whose reference the caller gives up.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_release(cache: *const JSDecodedBytecodeCache) {- assert!(!cache.is_null(), "the embedder passes a decoded bytecode cache");- // SAFETY: The caller gives up a reference to the contents of a live Rc.- unsafe { Rc::decrement_strong_count(cache.cast::<DecodedBytecodeCache>()) };-}--/// Script::create_from_bytecode_cache(cache, source_code, realm, filename, host_defined): the Script Record of a-/// classic script whose blob, decoded in `cache`, was compiled from the code of `source_code`, which reports the-/// filename of the source code. Its dynamic imports resolve against `filename`, and `host_defined` (null for none) is-/// its [[HostDefined]]. Returns the script, which the caller keeps alive, or null after appending one error to `errors`-/// (which may be null) if the blob does not match the source code or turns out to be malformed. Borrows the cache.-/// Only the VM's thread may call this.-///-/// # Safety-///-/// `vm`, `cache`, `source_code` and `realm` must be live, `filename` a valid view, `host_defined` null or a live cell,-/// and `errors` null or a valid sink.-#[unsafe(no_mangle)]-#[allow(- clippy::too_many_arguments,- reason = "C++ Script::create_from_bytecode_cache takes all of these"-)]-pub unsafe extern "C" fn js_bytecode_cache_create_script(- vm: *mut JSVM,- cache: *const JSDecodedBytecodeCache,- source_code: *const JSSourceCode,- realm: *mut JSRealm,- filename: JSUtf16View,- host_defined: *mut c_void,- errors: *const JSParserErrorSink,-) -> *mut JSScript {- // SAFETY: The caller passes a live VM, cache, source code, realm and host-defined cell, and a valid view.- let (vm, cache, source_code, realm, filename, host_defined) = unsafe {- (- vm_from_abi(vm),- cache_from_abi(cache),- shared_source_code_from_abi(source_code),- cell_from_abi(realm),- filename.as_view().to_utf8(),- host_defined_slot_from_abi(host_defined),- )- };- match Script::create_from_bytecode_cache(vm, realm, cache, source_code, &filename, host_defined) {- Ok(script) => cell_into_abi(script),- Err(parser_errors) => {- // SAFETY: The caller passes null or a valid sink.- unsafe { append_to_parser_error_sink(errors, &parser_errors) };- core::ptr::null_mut()- }- }-}--/// SourceTextModule::parse_from_bytecode_cache(cache, source_code, realm, filename, host_defined): like-/// js_bytecode_cache_create_script(), but for a module, whose imports resolve against `filename`. Returns the Source-/// Text Module Record, or null after appending one error to `errors`. Only the VM's thread may call this.-///-/// # Safety-///-/// As for js_bytecode_cache_create_script().-#[unsafe(no_mangle)]-#[allow(- clippy::too_many_arguments,- reason = "C++ SourceTextModule::parse_from_bytecode_cache takes all of these"-)]-pub unsafe extern "C" fn js_bytecode_cache_create_module(- vm: *mut JSVM,- cache: *const JSDecodedBytecodeCache,- source_code: *const JSSourceCode,- realm: *mut JSRealm,- filename: JSUtf16View,- host_defined: *mut c_void,- errors: *const JSParserErrorSink,-) -> *mut JSModule {- // SAFETY: The caller passes a live VM, cache, source code, realm and host-defined cell, and a valid view.- let (vm, cache, source_code, realm, filename, host_defined) = unsafe {- (- vm_from_abi(vm),- cache_from_abi(cache),- shared_source_code_from_abi(source_code),- cell_from_abi(realm),- filename.as_view().to_utf8(),- host_defined_slot_from_abi(host_defined),- )- };- match SourceTextModule::create_from_bytecode_cache(vm, realm, &filename, cache, source_code, host_defined) {- Ok(module) => cell_into_abi(module.upcast::<Module>()),- Err(parser_errors) => {- // SAFETY: The caller passes null or a valid sink.- unsafe { append_to_parser_error_sink(errors, &parser_errors) };- core::ptr::null_mut()- }- }-}--/// Script::begin_bytecode_cache_generation(): marks the script as one whose bytecode cache is being generated, until-/// js_bytecode_cache_script_install_generated() installs it or js_bytecode_cache_script_finish_generation_without_install()-/// gives up. Panics unless the script is in the SOURCE or HEAP_BYTECODE state. Only the VM's thread may call this.-///-/// # Safety-///-/// `vm` and `script` must be live.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_script_begin_generation(vm: *mut JSVM, script: *mut JSScript) {- // SAFETY: The caller passes a live VM and script.- let (vm, script) = unsafe { (vm_from_abi(vm), cell_from_abi(script)) };- script.begin_bytecode_cache_generation(vm);-}--/// Script::finish_bytecode_cache_generation_without_install(). Panics unless a bytecode cache is being generated for-/// the script. Only the VM's thread may call this.-///-/// # Safety-///-/// `vm` and `script` must be live.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_script_finish_generation_without_install(- vm: *mut JSVM,- script: *mut JSScript,-) {- // SAFETY: The caller passes a live VM and script.- let (vm, script) = unsafe { (vm_from_abi(vm), cell_from_abi(script)) };- script.finish_bytecode_cache_generation_without_install(vm);-}--/// Script::install_generated_bytecode_cache(cache, source_code): installs the cache that was generated for the script,-/// so that from now on the script and its functions run from the blob, compiled from the code of `source_code`.-/// Functions that already ran get executables from the blob, which take over their inline caches; the others compile-/// from the blob on their first call. Panics unless a bytecode cache is being generated for the script, and if the-/// blob does not match it. Only the VM's thread may call this.-///-/// # Safety-///-/// `vm`, `script`, `cache` and `source_code` must be live.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_script_install_generated(- vm: *mut JSVM,- script: *mut JSScript,- cache: *const JSDecodedBytecodeCache,- source_code: *const JSSourceCode,-) {- // SAFETY: The caller passes a live VM, script, cache and source code.- let (vm, script, cache, source_code) = unsafe {- (- vm_from_abi(vm),- cell_from_abi(script),- cache_from_abi(cache),- shared_source_code_from_abi(source_code),- )- };- script.install_generated_bytecode_cache(vm, cache, &source_code);-}--/// SourceTextModule::begin_bytecode_cache_generation(): like js_bytecode_cache_script_begin_generation(). Only the VM's-/// thread may call this.-///-/// # Safety-///-/// `vm` must be live, and `module` a live Source Text Module Record.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_module_begin_generation(vm: *mut JSVM, module: *mut JSModule) {- // SAFETY: The caller passes a live VM and Source Text Module Record.- let (vm, module) = unsafe { (vm_from_abi(vm), source_text_module_from_abi(module)) };- module.begin_bytecode_cache_generation(vm);-}--/// SourceTextModule::finish_bytecode_cache_generation_without_install(): like-/// js_bytecode_cache_script_finish_generation_without_install(). Only the VM's thread may call this.-///-/// # Safety-///-/// `vm` must be live, and `module` a live Source Text Module Record.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_module_finish_generation_without_install(- vm: *mut JSVM,- module: *mut JSModule,-) {- // SAFETY: The caller passes a live VM and Source Text Module Record.- let (vm, module) = unsafe { (vm_from_abi(vm), source_text_module_from_abi(module)) };- module.finish_bytecode_cache_generation_without_install(vm);-}--/// SourceTextModule::install_generated_bytecode_cache(cache, source_code): like-/// js_bytecode_cache_script_install_generated(), for a module. Only the VM's thread may call this.-///-/// # Safety-///-/// `vm`, `cache` and `source_code` must be live, and `module` a live Source Text Module Record.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn js_bytecode_cache_module_install_generated(- vm: *mut JSVM,- module: *mut JSModule,- cache: *const JSDecodedBytecodeCache,- source_code: *const JSSourceCode,-) {- // SAFETY: The caller passes a live VM, Source Text Module Record, cache and source code.- let (vm, module, cache, source_code) = unsafe {- (- vm_from_abi(vm),- source_text_module_from_abi(module),- cache_from_abi(cache),- shared_source_code_from_abi(source_code),- )- };- module.install_generated_bytecode_cache(vm, cache, &source_code);-}diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rsindex 78f50573139..cf9a4bf629f 100644--- a/Libraries/LibJS/Rust/src/lib.rs+++ b/Libraries/LibJS/Rust/src/lib.rs@@ -133,7 +133,6 @@ mod layout_forward;pub mod lexer;#[cfg(not(test))]pub mod lexical_path;-#[path = "parser/mod.rs"]pub mod parser;pub mod parser_error;#[cfg(not(test))]diff --git a/Libraries/LibJS/Rust/src/parser.rs b/Libraries/LibJS/Rust/src/parser.rsdeleted file mode 100644index 1cbe28b6760..00000000000--- a/Libraries/LibJS/Rust/src/parser.rs+++ /dev/null@@ -1,1732 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! JavaScript parser: recursive descent with precedence climbing.-//!-//! This is the core parser module. It contains the `Parser` struct (parser-//! state + helpers) and delegates actual parsing to submodules:-//!-//! - `expressions` — `parse_expression()`, primary/secondary expressions-//! - `statements` — `parse_statement()`, control flow-//! - `declarations` — functions, classes, variables, import/export-//!-//! ## How parsing works-//!-//! The parser is a single-pass, recursive-descent parser. Expression parsing-//! uses precedence climbing (Pratt-style): `parse_expression(min_precedence)`-//! parses a primary expression, then loops consuming binary/postfix operators-//! whose precedence is >= `min_precedence`.-//!-//! The parser reads tokens one at a time from the Lexer. The "current token"-//! is always available via `self.current_token`. Calling `consume()` returns-//! the current token and advances to the next one.-//!-//! ## Backtracking-//!-//! Some constructs require speculative parsing (e.g., arrow functions:-//! `(a, b) =>` looks like a parenthesized expression until `=>` is seen).-//! The parser supports this via `save_state()` / `load_state()`, which-//! save and restore the full parser state including lexer position, current-//! token, error list, and all boolean flags.--use crate::fast_hash::HashMap;-use crate::fast_hash::HashSet;--use crate::ast::AstArena;-use crate::ast::BindingPattern;-use crate::ast::Expression;-use crate::ast::ExpressionKind;-use crate::ast::FunctionData;-use crate::ast::FunctionId;-use crate::ast::FunctionParameter;-use crate::ast::FunctionTable;-use crate::ast::Identifier;-use crate::ast::IdentifierId;-use crate::ast::PrivateIdentifier;-use crate::ast::ProgramData;-use crate::ast::ScopeData;-use crate::ast::ScopeId;-use crate::ast::SourceRange;-use crate::ast::Statement;-use crate::ast::StatementKind;-use crate::ast::StringId;-use crate::ast::Utf16String;-use crate::lexer::Lexer;-use crate::lexer::ch;-use crate::scope_collector::ScopeCollector;-use crate::scope_collector::ScopeCollectorState;-use crate::token::Token;-use crate::token::TokenType;--mod declarations;-mod expressions;-mod statements;--pub use crate::ast::DeclarationKind;-pub use crate::ast::FunctionKind;-pub use crate::ast::FunctionParsingInsights;-pub use crate::ast::Position;-pub use crate::ast::ProgramType;--// Named precedence levels for parse_expression().-// These correspond to the operator precedence table in ECMA-262.-pub(crate) const PRECEDENCE_COMMA: i32 = 0;-pub(crate) const PRECEDENCE_ASSIGNMENT: i32 = 2;-pub(crate) const PRECEDENCE_UNARY: i32 = 17;-pub(crate) const PRECEDENCE_MEMBER: i32 = 19;--/// Result of parsing a function's formal parameter list.-pub struct ParsedParameters {- pub parameters: Vec<FunctionParameter>,- pub function_length: i32,- pub parameter_info: Vec<ParamInfo>,- pub is_simple: bool,-}--/// Information about a single parameter name binding.-pub struct ParamInfo {- pub name: Utf16String,- pub is_rest: bool,- pub is_from_pattern: bool,- pub identifier: Option<IdentifierId>,-}--/// Result of parsing a property key (object literal or class element).-pub(crate) struct PropertyKey {- pub expression: Expression,- pub name: Option<Utf16String>,- pub is_proto: bool,- pub is_computed: bool,- pub is_identifier: bool,-}--/// Method kind for parse_method_definition.-#[derive(Clone, Copy, PartialEq, Eq)]-pub enum MethodKind {- Normal,- Getter,- Setter,- Constructor,-}--/// Associativity for operator precedence.-#[derive(Clone, Copy, PartialEq, Eq)]-pub enum Associativity {- Left,- Right,-}--/// Tracks which tokens are forbidden in the current expression context.-///-/// This is threaded through `parse_expression()` to prevent ambiguity:-/// - `forbid_in`: in for-loop init position (`for (x in ...)` is for-in, not comparison)-/// - `forbid_logical/forbid_coalesce`: `&&`/`||` and `??` cannot be mixed without parens-/// - `forbid_paren_open`: prevents consuming `(` as call in `new Foo()` callee position-/// - `forbid_question_mark_period`: prevents `?.` in `new Foo?.bar`-/// - `forbid_equals`: prevents `=` from being consumed as assignment in certain contexts-#[derive(Clone, Copy, Default)]-pub struct ForbiddenTokens {- pub forbid_in: bool,- pub forbid_logical: bool,- pub forbid_coalesce: bool,- pub forbid_paren_open: bool,- pub forbid_question_mark_period: bool,- pub forbid_equals: bool,-}--impl ForbiddenTokens {- pub fn none() -> Self {- Self::default()- }-- pub fn with_in() -> Self {- Self {- forbid_in: true,- ..Self::default()- }- }-- pub fn allows(&self, token: TokenType) -> bool {- match token {- TokenType::In => !self.forbid_in,- TokenType::DoubleAmpersand | TokenType::DoublePipe => !self.forbid_logical,- TokenType::DoubleQuestionMark => !self.forbid_coalesce,- TokenType::ParenOpen => !self.forbid_paren_open,- TokenType::QuestionMarkPeriod => !self.forbid_question_mark_period,- TokenType::Equals => !self.forbid_equals,- _ => true,- }- }-- pub fn merge(&self, other: ForbiddenTokens) -> ForbiddenTokens {- ForbiddenTokens {- forbid_in: self.forbid_in || other.forbid_in,- forbid_logical: self.forbid_logical || other.forbid_logical,- forbid_coalesce: self.forbid_coalesce || other.forbid_coalesce,- forbid_paren_open: self.forbid_paren_open || other.forbid_paren_open,- forbid_question_mark_period: self.forbid_question_mark_period || other.forbid_question_mark_period,- forbid_equals: self.forbid_equals || other.forbid_equals,- }- }-- pub fn forbid(&self, tokens: &[TokenType]) -> ForbiddenTokens {- let mut result = *self;- for &t in tokens {- match t {- TokenType::In => result.forbid_in = true,- TokenType::DoubleAmpersand | TokenType::DoublePipe => result.forbid_logical = true,- TokenType::DoubleQuestionMark => result.forbid_coalesce = true,- TokenType::ParenOpen => result.forbid_paren_open = true,- TokenType::QuestionMarkPeriod => result.forbid_question_mark_period = true,- TokenType::Equals => result.forbid_equals = true,- _ => {}- }- }- result- }-}--pub struct ParseError {- pub message: String,- pub line: u32,- pub column: u32,-}--/// Boolean flags that are saved/restored during speculative parsing.-#[derive(Clone, Copy, Default)]-pub(crate) struct ParserFlags {- pub strict_mode: bool,- pub allow_super_property_lookup: bool,- pub allow_super_constructor_call: bool,- pub in_function_context: bool,- pub in_formal_parameter_context: bool,- pub in_generator_function_context: bool,- pub await_expression_is_valid: bool,- pub in_break_context: bool,- pub in_continue_context: bool,- pub string_legacy_octal_escape_sequence_in_scope: bool,- pub in_class_field_initializer: bool,- pub in_class_static_init_block: bool,- /// True inside non-arrow function bodies and class static init blocks.- /// Arrow functions inherit this flag rather than setting it, since they- /// don't have their own `new.target` binding.- pub new_target_is_valid: bool,- pub function_might_need_arguments_object: bool,- pub previous_token_was_period: bool,-}--/// Snapshot of parser state for speculative parsing (backtracking).-struct SavedState {- token: Token,- errors_len: usize,- flags: ParserFlags,- scope_collector_state: ScopeCollectorState,- function_context_stack_lengths: Vec<usize>,- referenced_private_names_stack: Vec<HashSet<Utf16String>>,- eval_referenced_private_names: Vec<Utf16String>,-}--/// The main JavaScript parser.-///-/// Produces an AST. Parsing methods live in the `expressions`,-/// `statements`, and `declarations` submodules (all `impl Parser`).-pub struct Parser<'a> {- lexer: Lexer<'a>,- /// `consume()` returns this and advances to the next token.- current_token: Token,- errors: Vec<ParseError>,- saved_states: Vec<SavedState>,- program_type: ProgramType,- /// UTF-16 source text.- source: &'a [u16],-- // --- Parser state flags (saved/restored during speculative parsing) ---- pub(crate) flags: ParserFlags,-- // --- Flags NOT saved/restored during speculative parsing ---- pub(crate) initiated_by_eval: bool,- pub(crate) in_eval_function_context: bool,-- /// Labels currently in scope. Value is Some(line, col) if a `continue`- /// statement referenced this label, None otherwise.- labels_in_scope: HashMap<Utf16String, Option<(u32, u32)>>,-- /// Set by try_parse_labelled_statement to propagate iteration-ness- /// through nested labels (e.g., `a: b: for(...)`).- last_inner_label_is_iteration: bool,-- /// Set by parse_primary_expression when it parses a parenthesized expression.- /// Consumed by parse_secondary_expression to prevent treating (obj) as destructuring.- pub(crate) last_primary_was_parenthesized: bool,-- last_function_name: Utf16String,- last_function_kind: FunctionKind,- last_class_name: Utf16String,-- /// Bound names collected during parse_binding_pattern.- /// Caller drains this after calling parse_binding_pattern.- /// Each entry is (name, identifier) — allows scope analysis to annotate- /// binding pattern identifiers with local variable info.- pub(crate) pattern_bound_names: Vec<(StringId, IdentifierId)>,-- /// Set during synthesize_binding_pattern to allow MemberExpressions as binding targets.- allow_member_expressions: bool,-- /// True while parsing a class body that has an `extends` clause.- pub(crate) class_has_super_class: bool,- /// Depth counter for class bodies — used to reject `#name` outside classes.- pub(crate) class_scope_depth: u32,- /// Current expression-parser recursion depth, used to guard against native- /// stack exhaustion from pathologically-nested expressions (see #5749).- recursion_depth: u32,- /// Native stack address at the outermost recursion level.- recursion_stack_base: usize,- /// Set once the recursion-depth limit is hit — so parsing loops stop- /// spinning on unconsumed input after a placeholder node is returned.- recursion_limit_reached: bool,- pub(crate) has_default_export_name: bool,-- /// Stack of sets tracking private names referenced inside class bodies.- /// Each class body pushes a new set. At the end of the class, any names- /// not found in the class's declared private names are bubbled up to the- /// outer class, recorded for eval validation, or reported as errors.- referenced_private_names_stack: Vec<HashSet<Utf16String>>,- eval_referenced_private_names: Vec<Utf16String>,-- /// Communication channel from `parse_variable_declaration` back to- /// `parse_for_statement` when parsing `for (let/const/var ... ; ...)`.- /// These are set when `is_for_loop` is true and read by the for-loop- /// parser to validate for-in/of restrictions.- pub(crate) for_loop_declaration_count: usize,- pub(crate) for_loop_declaration_has_init: bool,- pub(crate) for_loop_declaration_is_var: bool,- pub(crate) for_loop_declaration_is_pattern: bool,-- pub scope_collector: ScopeCollector,-- /// Track exported names for duplicate detection in modules.- exported_names: HashSet<Utf16String>,-- /// Side table owning all FunctionData produced during parsing.- pub function_table: FunctionTable,-- /// Bulk storage for identifiers, scopes, and interned strings. Replaces- /// the old per-node `Rc<Identifier>` heap allocations.- pub arena: AstArena,-- /// Stack of nested function ids discovered while parsing each active function.- ///- /// When the parser finishes a function, the top list becomes that- /// FunctionData's child list. This lets lazy-compile payload extraction move- /// a known function subtree instead of walking the function body again.- function_context_stack: Vec<Vec<FunctionId>>,-- /// Memoization: offsets where arrow function parsing has already failed.- /// Prevents exponential re-processing of nested expressions like- /// `(a=(b=(c=0)))` where each failed arrow attempt would otherwise- /// re-attempt inner positions during grouping expression re-parse.- arrow_function_failed_positions: HashSet<usize>,-}--impl<'a> Parser<'a> {- pub fn new(source: &'a [u16], program_type: ProgramType) -> Self {- Self::new_with_line_offset(source, program_type, 1)- }-- pub fn new_with_line_offset(source: &'a [u16], program_type: ProgramType, initial_line_number: u32) -> Self {- let mut lexer = Lexer::new(source, initial_line_number, 0);- if program_type == ProgramType::Module {- lexer.disallow_html_comments();- }- let first_token = lexer.next();- Self {- lexer,- current_token: first_token,- errors: Vec::new(),- saved_states: Vec::new(),- program_type,- source,- flags: ParserFlags::default(),- initiated_by_eval: false,- in_eval_function_context: false,- labels_in_scope: HashMap::default(),- last_inner_label_is_iteration: false,- last_primary_was_parenthesized: false,- last_function_name: Utf16String::default(),- last_function_kind: FunctionKind::Normal,- last_class_name: Utf16String::default(),- pattern_bound_names: Vec::new(),- allow_member_expressions: false,- class_has_super_class: false,- class_scope_depth: 0,- recursion_depth: 0,- recursion_stack_base: 0,- recursion_limit_reached: false,- has_default_export_name: false,- referenced_private_names_stack: Vec::new(),- eval_referenced_private_names: Vec::new(),- for_loop_declaration_count: 0,- for_loop_declaration_has_init: false,- for_loop_declaration_is_var: false,- for_loop_declaration_is_pattern: false,- scope_collector: ScopeCollector::new(),- exported_names: HashSet::default(),- function_table: FunctionTable::new(),- arena: AstArena::new(),- function_context_stack: Vec::new(),- arrow_function_failed_positions: HashSet::default(),- }- }-- // === AST construction helpers ===-- pub(crate) fn range_from(&self, start: Position) -> SourceRange {- SourceRange {- start,- end: self.position(),- }- }-- pub(crate) fn expression(&self, start: Position, expression: ExpressionKind) -> Expression {- Expression::new(self.range_from(start), expression)- }-- pub(crate) fn statement(&self, start: Position, statement: StatementKind) -> Statement {- Statement::new(self.range_from(start), statement)- }-- pub(crate) fn push_function_context(&mut self) {- self.function_context_stack.push(Vec::new());- }-- pub(crate) fn pop_function_context(&mut self) -> Vec<FunctionId> {- self.function_context_stack- .pop()- .expect("Parser::pop_function_context: no active function context")- }-- pub(crate) fn insert_function_data(&mut self, data: FunctionData) -> FunctionId {- let function_id = self.function_table.insert(data);- if let Some(context) = self.function_context_stack.last_mut() {- // The newly parsed function belongs to the innermost function- // context. Top-level functions have no parent and remain reachable- // through their AST node, as before.- context.push(function_id);- }- function_id- }-- pub(crate) fn make_identifier(&mut self, start: Position, name: StringId) -> IdentifierId {- let identifier = Identifier::new(self.range_from(start), name);- self.arena.identifiers.insert(identifier)- }-- pub(crate) fn make_identifier_from_slice(&mut self, start: Position, name: &[u16]) -> IdentifierId {- let id = self.arena.strings.intern(name);- self.make_identifier(start, id)- }-- pub(crate) fn make_scope(&mut self, children: Vec<Statement>) -> ScopeId {- self.arena.scopes.insert(ScopeData {- children,- ..ScopeData::default()- })- }-- pub(crate) fn make_empty_scope(&mut self) -> ScopeId {- self.arena.scopes.insert(ScopeData::default())- }-- pub(crate) fn token_identifier_name(&mut self, token: &Token) -> StringId {- if let Some(value) = &token.identifier_value {- // Cheap-clone via Vec slicing because intern needs a slice but- // self.arena is borrowed.- let owned = value.clone();- return self.arena.strings.intern_owned(owned);- }- let start = token.value_start as usize;- let end = start + token.value_len as usize;- let slice = &self.source[start..end];- self.arena.strings.intern(slice)- }-- pub(crate) fn register_function_parameters_with_scope(- &mut self,- parameters: &[FunctionParameter],- parameter_info: &[ParamInfo],- ) {- use crate::ast::FunctionParameterBinding;- use crate::scope_collector::ParameterEntry;- let mut entries: Vec<ParameterEntry> = Vec::new();- let mut has_parameter_expressions = false;- let mut info_index = 0;- for parameter in parameters {- if parameter.default_value.is_some() {- has_parameter_expressions = true;- }- match ¶meter.binding {- FunctionParameterBinding::Identifier(id) => {- let (name, is_rest, is_from_pattern) = if info_index < parameter_info.len() {- let pi = ¶meter_info[info_index];- info_index += 1;- (pi.name.clone(), pi.is_rest, pi.is_from_pattern)- } else {- (self.arena.name_of(*id).clone(), parameter.is_rest, false)- };- entries.push(ParameterEntry {- name,- identifier: Some(*id),- is_rest,- is_from_pattern,- is_first_from_pattern: false,- });- }- FunctionParameterBinding::BindingPattern(pattern) => {- if pattern.contains_expression() {- has_parameter_expressions = true;- }- // Push a placeholder entry for the pattern parameter itself- // so subsequent parameters get correct positional indices.- entries.push(ParameterEntry {- name: Utf16String::default(),- identifier: None,- is_rest: false,- is_from_pattern: true,- is_first_from_pattern: true,- });- // Then push bound names from this pattern.- while info_index < parameter_info.len() && parameter_info[info_index].is_from_pattern {- let pi = ¶meter_info[info_index];- entries.push(ParameterEntry {- name: pi.name.clone(),- identifier: pi.identifier,- is_rest: pi.is_rest,- is_from_pattern: true,- is_first_from_pattern: false,- });- info_index += 1;- }- }- }- }- let Self {- scope_collector, arena, ..- } = self;- scope_collector.set_function_parameters(- &entries,- has_parameter_expressions,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }-- // === Token access ===-- pub(crate) fn current_token(&self) -> &Token {- &self.current_token- }-- pub(crate) fn current_token_type(&self) -> TokenType {- self.current_token.token_type- }-- pub(crate) fn match_token(&self, tt: TokenType) -> bool {- self.current_token.token_type == tt- }-- pub(crate) fn done(&self) -> bool {- self.recursion_limit_reached || self.match_token(TokenType::Eof)- }-- // === Token consumption ===-- pub(crate) fn consume(&mut self) -> Token {- let old = std::mem::replace(&mut self.current_token, self.lexer.next());- self.check_arguments_or_eval(&old);- self.flags.previous_token_was_period = old.token_type == TokenType::Period;- old- }-- /// Like `consume()` but skips the `arguments`/`eval` reference check.- /// Use this when consuming a token that is syntactically a property key- /// rather than an identifier reference (e.g. `{ arguments: 1 }`).- pub(crate) fn consume_property_key_token(&mut self) -> Token {- let old = std::mem::replace(&mut self.current_token, self.lexer.next());- self.flags.previous_token_was_period = old.token_type == TokenType::Period;- old- }-- pub(crate) fn consume_and_check_identifier(&mut self) -> Token {- let token = self.consume();- if self.flags.strict_mode && token.token_type == TokenType::Identifier {- let value = self.token_value(&token);- if is_strict_reserved_word(value) {- let name = String::from_utf16_lossy(value);- self.syntax_error(&format!(- "Identifier must not be a reserved word in strict mode ('{name}')"- ));- }- }- token- }-- pub(crate) fn consume_token(&mut self, expected: TokenType) -> Token {- if self.current_token.token_type != expected {- self.expected(expected.name());- }- self.consume()- }-- pub(crate) fn eat(&mut self, tt: TokenType) -> bool {- if self.match_token(tt) {- self.consume();- true- } else {- false- }- }-- fn check_arguments_or_eval(&mut self, token: &Token) {- if token.token_type == TokenType::Identifier && !self.flags.previous_token_was_period {- let value: &[u16] = if let Some(ref v) = token.identifier_value {- v- } else {- let start = token.value_start as usize;- let end = start + token.value_len as usize;- if end <= self.source.len() {- &self.source[start..end]- } else {- &[]- }- };- if value == utf16!("arguments") {- if self.flags.in_class_field_initializer {- self.syntax_error("'arguments' is not allowed in class field initializer");- }- self.flags.function_might_need_arguments_object = true;- } else if value == utf16!("eval") {- self.flags.function_might_need_arguments_object = true;- }- }- }-- pub(crate) fn consume_identifier(&mut self) -> Token {- if self.match_identifier() {- return self.consume_and_check_identifier();- }- self.expected("identifier");- self.consume()- }-- // https://tc39.es/ecma262/#sec-numeric-literals-early-errors- // It is a Syntax Error if IsStringWellFormedUnicode of the source text matched- // by NumericLiteral is not true.- // The source character immediately following a NumericLiteral must not be an- // IdentifierStart or DecimalDigit.- pub(crate) fn consume_and_validate_numeric_literal(&mut self) -> Token {- let token = self.consume();- if self.flags.strict_mode {- // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals- // In strict mode, legacy octal literals (0-prefixed) are not permitted.- let value = self.token_value(&token);- if value.len() > 1 && value[0] == ch(b'0') && value[1] >= ch(b'0') && value[1] <= ch(b'9') {- self.syntax_error("Unprefixed octal number not allowed in strict mode");- }- }- if self.match_identifier_name() && self.current_token.trivia_len == 0 {- self.syntax_error("Numeric literal must not be immediately followed by identifier");- }- token- }-- // https://tc39.es/ecma262/#sec-automatic-semicolon-insertion- // A semicolon is automatically inserted when:- // 1. The offending token is separated from the previous token by at least- // one LineTerminator.- // 2. The offending token is `}`.- // 3. The previous token is `)` and the inserted semicolon would then be- // parsed as the terminating semicolon of a do-while statement.- // 4. The end of the input stream of tokens is reached.- pub(crate) fn consume_or_insert_semicolon(&mut self) {- if self.match_token(TokenType::Semicolon) {- self.consume();- return;- }- if self.current_token.trivia_has_line_terminator || self.match_token(TokenType::CurlyClose) || self.done() {- return;- }- self.expected("Semicolon");- }-- // === Lookahead ===-- pub(crate) fn next_token(&mut self) -> Token {- self.lexer.save_state();- let token = self.lexer.next();- self.lexer.load_state();- token- }-- pub(crate) fn next_two_tokens(&mut self) -> (Token, Token) {- self.lexer.save_state();- let first = self.lexer.next();- let second = self.lexer.next();- self.lexer.load_state();- (first, second)- }-- // === Position ===-- pub(crate) fn position(&self) -> Position {- Position {- line: self.current_token.line_number,- column: self.current_token.line_column,- offset: self.current_token.offset,- }- }-- pub(crate) fn source_text_end_offset(&self) -> u32 {- self.current_token.offset - self.current_token.trivia_len- }-- // === Error reporting ===-- /// Maximum parser recursion depth. Beyond this, the parser reports a syntax- /// error — rather than exhausting the native stack, which would crash the- /// process on pathologically-nested input (see #5749).- const MAX_RECURSION_DEPTH: u32 = 2000;-- /// Maximum native stack the parser's recursion may use. A level takes under- /// 1 KiB of stack in optimized builds but up to 7 KiB in unoptimized ones, where- /// MAX_RECURSION_DEPTH levels would overflow the 8 MiB stacks scripts are parsed on.- const MAX_RECURSION_STACK_BYTES: usize = 4 * 1024 * 1024;-- /// Enters a nested-parse recursion level. Returns false if the maximum depth- /// or stack use would be exceeded — in which case a syntax error is recorded,- /// and the caller must return a placeholder node instead of recursing further.- #[must_use]- fn enter_recursion(&mut self) -> bool {- let stack_marker = 0u8;- let stack_address = std::hint::black_box(&stack_marker) as *const u8 as usize;- if self.recursion_depth == 0 {- self.recursion_stack_base = stack_address;- }- self.recursion_depth += 1;- if self.recursion_depth > Self::MAX_RECURSION_DEPTH- || self.recursion_stack_base.abs_diff(stack_address) > Self::MAX_RECURSION_STACK_BYTES- {- self.recursion_depth -= 1;- self.recursion_limit_reached = true;- self.syntax_error("Maximum parser recursion depth exceeded");- return false;- }- true- }-- /// Leaves a recursion level previously entered via enter_recursion.- fn leave_recursion(&mut self) {- self.recursion_depth -= 1;- }-- pub(crate) fn syntax_error(&mut self, message: &str) {- self.errors.push(ParseError {- message: message.to_string(),- line: self.current_token.line_number,- column: self.current_token.line_column,- });- }-- pub(crate) fn syntax_error_at(&mut self, message: &str, line: u32, column: u32) {- self.errors.push(ParseError {- message: message.to_string(),- line,- column,- });- }-- pub(crate) fn syntax_error_at_position(&mut self, message: &str, pos: Position) {- self.syntax_error_at(message, pos.line, pos.column);- }-- /// Register a referenced private name. Returns true if the reference can be- /// checked later by class parsing or EvalDeclarationInstantiation.- pub(crate) fn register_referenced_private_name(&mut self, name: &[u16]) -> bool {- if let Some(set) = self.referenced_private_names_stack.last_mut() {- set.insert(Utf16String::from(name));- true- } else if self.initiated_by_eval {- self.register_eval_referenced_private_name(name);- true- } else {- false- }- }-- pub(crate) fn register_eval_referenced_private_name(&mut self, name: &[u16]) {- let name = Utf16String::from(name);- if !self.eval_referenced_private_names.contains(&name) {- self.eval_referenced_private_names.push(name);- }- }-- pub fn eval_referenced_private_names(&self) -> &[Utf16String] {- &self.eval_referenced_private_names- }-- /// Parse and validate a private identifier token.- /// Registers the private name reference and emits an error if it cannot be validated later.- /// The current token must be a PrivateIdentifier.- pub(crate) fn parse_private_identifier(&mut self, range_start: Position) -> PrivateIdentifier {- let value = self.token_value(&self.current_token).to_vec();- if !self.register_referenced_private_name(&value) {- let name = String::from_utf16_lossy(&value);- self.syntax_error(&format!("Reference to undeclared private field or method '{name}'"));- }- let token = self.consume();- let value = self.token_value(&token).to_vec();- PrivateIdentifier {- range: self.range_from(range_start),- name: value.into(),- }- }-- pub(crate) fn expected(&mut self, what: &str) {- let msg = if let Some(ref message) = self.current_token.message {- message.clone()- } else {- format!(- "Unexpected token {}. Expected {}",- self.current_token.token_type.name(),- what- )- };- self.syntax_error(&msg);- }-- pub(crate) fn validate_regex_flags(&mut self, flags: &[u16]) {- let valid_flags: &[u16] = &[- ch(b'd'),- ch(b'g'),- ch(b'i'),- ch(b'm'),- ch(b's'),- ch(b'u'),- ch(b'v'),- ch(b'y'),- ];- let mut seen = [false; 128];- for &flag in flags {- if flag >= 128 || !valid_flags.contains(&flag) {- self.syntax_error(&format!(- "Invalid RegExp flag '{}'",- char::from_u32(flag as u32).unwrap_or('?')- ));- return;- }- if seen[flag as usize] {- self.syntax_error(&format!(- "Repeated RegExp flag '{}'",- char::from_u32(flag as u32).unwrap_or('?')- ));- return;- }- seen[flag as usize] = true;- }- }-- pub fn has_errors(&self) -> bool {- !self.errors.is_empty()- }-- pub fn errors(&self) -> &[ParseError] {- &self.errors- }-- pub fn take_errors(&mut self) -> Vec<ParseError> {- std::mem::take(&mut self.errors)- }-- pub fn error_messages(&self) -> Vec<String> {- self.errors- .iter()- .map(|e| format!("{}:{}: {}", e.line, e.column, e.message))- .collect()- }-- // === State save/restore for backtracking ===-- pub(crate) fn save_state(&mut self) {- self.lexer.save_state();- self.saved_states.push(SavedState {- token: self.current_token.clone(),- errors_len: self.errors.len(),- flags: self.flags,- scope_collector_state: self.scope_collector.save_state(),- function_context_stack_lengths: self.function_context_stack.iter().map(Vec::len).collect(),- referenced_private_names_stack: self.referenced_private_names_stack.clone(),- eval_referenced_private_names: self.eval_referenced_private_names.clone(),- });- }-- pub(crate) fn load_state(&mut self) {- let state = self.saved_states.pop().expect("No saved state to restore");- self.current_token = state.token;- self.errors.truncate(state.errors_len);- self.flags = state.flags;- self.scope_collector.load_state(state.scope_collector_state);- self.referenced_private_names_stack = state.referenced_private_names_stack;- self.eval_referenced_private_names = state.eval_referenced_private_names;- self.function_context_stack- .truncate(state.function_context_stack_lengths.len());- for (context, len) in self- .function_context_stack- .iter_mut()- .zip(state.function_context_stack_lengths)- {- context.truncate(len);- }- self.lexer.load_state();- }-- pub(crate) fn discard_saved_state(&mut self) {- self.saved_states.pop();- self.lexer.discard_saved_state();- }-- // === Token matching helpers ===-- pub(crate) fn match_identifier(&self) -> bool {- self.token_is_identifier(&self.current_token)- }-- pub(crate) fn token_is_identifier(&self, token: &Token) -> bool {- use TokenType::*;-- let tt = token.token_type;-- match tt {- Identifier => true,- EscapedKeyword => !self.match_invalid_escaped_keyword(),- Let => !self.flags.strict_mode,- Yield => !self.flags.strict_mode && !self.flags.in_generator_function_context,- Await => {- !self.flags.await_expression_is_valid- && self.program_type != ProgramType::Module- && !self.flags.in_class_static_init_block- }- Async => true,- _ => false,- }- }-- pub(crate) fn match_identifier_name(&self) -> bool {- self.current_token.token_type.is_identifier_name() || self.match_identifier()- }-- pub(crate) fn match_invalid_escaped_keyword(&self) -> bool {- if self.current_token.token_type != TokenType::EscapedKeyword {- return false;- }- let value = self.token_value(&self.current_token);- if value == utf16!("await") {- return self.program_type == ProgramType::Module- || self.flags.await_expression_is_valid- || self.flags.in_class_static_init_block;- }- if value == utf16!("async") {- return false;- }- if value == utf16!("yield") {- return self.flags.in_generator_function_context;- }- if self.flags.strict_mode {- return true;- }- // In non-strict mode, "let" and "static" are context-sensitive- // keywords that are valid as escaped identifiers. All other- // escaped keywords (break, for, etc.) are always invalid.- value != utf16!("let") && value != utf16!("static")- }-- pub(crate) fn check_identifier_name_for_assignment_validity(&mut self, name: &[u16], force_strict: bool) {- if self.flags.strict_mode || force_strict {- if name == utf16!("arguments") || name == utf16!("eval") {- // https://tc39.es/ecma262/#sec-identifiers-static-semantics-early-errors- // It is a Syntax Error if IsStrict(this production) is *true* and the StringValue of |Identifier| is- // either *"arguments"* or *"eval"*.- self.syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode");- } else if is_strict_reserved_word(name) {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!(- "Identifier must not be a reserved word in strict mode ('{name_str}')"- ));- }- }- // 'await' is not allowed as a binding identifier in class static- // init blocks or module code.- if name == utf16!("await")- && (self.flags.in_class_static_init_block || self.program_type == ProgramType::Module)- {- self.syntax_error("'await' is not allowed as an identifier in this context");- }- }-- /// Check for duplicate parameter names in arrow functions.- /// Arrow functions always reject duplicates, regardless of strict mode.- pub(crate) fn check_arrow_duplicate_parameters(&mut self, parameter_info: &[ParamInfo]) {- let mut seen_names: HashSet<&[u16]> = HashSet::default();- for pi in parameter_info {- let name = &pi.name;- if name.is_empty() {- continue;- }- if !seen_names.insert(&**name) {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!(- "Duplicate parameter '{name_str}' not allowed in arrow function"- ));- }- }- }-- pub(crate) fn check_unique_formal_parameters(&mut self, parameter_info: &[ParamInfo]) {- let mut seen_names: HashSet<&[u16]> = HashSet::default();- for pi in parameter_info {- let name = &pi.name;- if name.is_empty() {- continue;- }- if !seen_names.insert(&**name) {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!("Duplicate parameter '{name_str}' not allowed"));- }- }- }-- /// Check parameter names that need deferred strict-mode validation after parsing the function body.- pub(crate) fn check_parameters_post_body(- &mut self,- parameter_info: &[ParamInfo],- force_strict: bool,- _kind: FunctionKind,- ) {- let mut seen_names: HashSet<&[u16]> = HashSet::default();- for pi in parameter_info {- let name = &pi.name;- if name.is_empty() {- continue;- }- self.check_identifier_name_for_assignment_validity(name, force_strict);- if !seen_names.insert(&**name) {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!("Duplicate parameter '{name_str}' not allowed in strict mode"));- }- }- }-- pub(crate) fn token_value<'b>(&'b self, token: &'b Token) -> &'b [u16] {- if let Some(ref value) = token.identifier_value {- return value;- }- let start = token.value_start as usize;- let end = start + token.value_len as usize;- assert!(- end <= self.source.len(),- "token_value: bounds [{start}..{end}) exceed source length {}",- self.source.len()- );- &self.source[start..end]- }-- pub(crate) fn token_original_value(&self, token: &Token) -> &'a [u16] {- let start = token.value_start as usize;- let end = (token.value_start + token.value_len) as usize;- assert!(- end <= self.source.len(),- "token_original_value: bounds [{start}..{end}) exceed source length {}",- self.source.len()- );- &self.source[start..end]- }-- /// Re-parse the source range starting at `start` as a binding pattern- /// with member expressions allowed (for destructuring assignment patterns).- pub(crate) fn synthesize_binding_pattern(&mut self, start: Position) -> BindingPattern {- // Clear any syntax errors that occurred in the range of the expression- // being reinterpreted as a binding pattern. This matches C++'s behavior- // where errors like duplicate __proto__ in object literals are cleared- // when the object is reinterpreted as an assignment target.- let end_line = self.current_token.line_number;- let end_column = self.current_token.line_column;- self.errors.retain(|e| {- !(e.line > start.line || (e.line == start.line && e.column >= start.column))- || (e.line > end_line || (e.line == end_line && e.column >= end_column))- });-- let saved_lexer = std::mem::replace(- &mut self.lexer,- Lexer::new_at_offset(self.source, start.offset as usize, start.line, start.column),- );- let saved_token = std::mem::replace(&mut self.current_token, Token::new(TokenType::Eof));- let saved_allow = self.allow_member_expressions;-- self.current_token = self.lexer.next();- self.allow_member_expressions = true;-- let pattern = self.parse_binding_pattern();-- self.lexer = saved_lexer;- self.current_token = saved_token;- self.allow_member_expressions = saved_allow;-- pattern- }-- // https://tc39.es/ecma262/#sec-static-semantics-assignmenttargettype- pub(crate) fn is_simple_assignment_target(- expression: &Expression,- allow_call_expression: bool,- strict_mode: bool,- ) -> bool {- match &expression.inner {- ExpressionKind::Identifier(_) | ExpressionKind::Member(_) => true,- // CallExpression: In strict mode, call expressions are always ~invalid~ as- // assignment targets. In non-strict mode, they are ~web-compat~ (runtime error).- // NewExpression is always ~invalid~.- ExpressionKind::Call(_) if allow_call_expression && !strict_mode => true,- _ => false,- }- }-- fn is_object_expression(expression: &Expression) -> bool {- matches!(&expression.inner, ExpressionKind::Object(_))- }-- fn is_array_expression(expression: &Expression) -> bool {- matches!(&expression.inner, ExpressionKind::Array(_))- }-- fn is_object_or_array_expression(expression: &Expression) -> bool {- Self::is_object_expression(expression) || Self::is_array_expression(expression)- }-- fn is_parenthesized_object_or_array_expression(expression: &Expression, start: Position) -> bool {- Self::is_object_or_array_expression(expression) && expression.range.start.offset != start.offset- }-- fn is_identifier(expression: &Expression) -> bool {- matches!(&expression.inner, ExpressionKind::Identifier(_))- }-- fn is_member_expression(expression: &Expression) -> bool {- matches!(&expression.inner, ExpressionKind::Member(_))- }-- fn is_update_expression(expression: &Expression) -> bool {- matches!(&expression.inner, ExpressionKind::Update(_))- }-- // === Main entry point ===-- pub fn parse_program(&mut self, starts_in_strict_mode: bool) -> Statement {- let start = self.position();-- if self.program_type == ProgramType::Script {- let (children, is_strict) = self.parse_script(starts_in_strict_mode);- let scope = self.make_scope(children);- // Scope was opened in parse_script via open_program_scope.- // Now close it after children are set.- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();- self.statement(- start,- StatementKind::Program(Box::new(ProgramData {- scope,- program_type: ProgramType::Script,- is_strict_mode: is_strict,- has_top_level_await: false,- })),- )- } else {- let (children, has_top_level_await) = self.parse_module();- let scope = self.make_scope(children);- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();- self.statement(- start,- StatementKind::Program(Box::new(ProgramData {- scope,- program_type: ProgramType::Module,- is_strict_mode: true,- has_top_level_await,- })),- )- }- }-- fn parse_script(&mut self, starts_in_strict_mode: bool) -> (Vec<Statement>, bool) {- // Open program scope — will be closed in parse_program after ScopeData is created.- self.scope_collector.open_program_scope(ProgramType::Script);-- let strict_before = self.flags.strict_mode;- if starts_in_strict_mode {- self.flags.strict_mode = true;- }-- let (has_use_strict, mut children) = self.parse_directive();-- if self.flags.strict_mode || has_use_strict {- self.flags.strict_mode = true;- }-- children.extend(self.parse_statement_list(true));- if !self.done() {- if self.flags.in_function_context {- self.expected("CurlyClose");- } else {- self.expected("statement or declaration");- }- self.consume();- }-- let is_strict = self.flags.strict_mode;- self.flags.strict_mode = strict_before;- (children, is_strict)- }-- // https://tc39.es/ecma262/#sec-modules- // Module code is always strict mode code.- fn parse_module(&mut self) -> (Vec<Statement>, bool) {- // Open program scope — will be closed in parse_program after ScopeData is created.- self.scope_collector.open_program_scope(ProgramType::Module);-- let strict_before = self.flags.strict_mode;- let await_before = self.flags.await_expression_is_valid;- self.flags.strict_mode = true;- self.flags.await_expression_is_valid = true;-- let mut children = Vec::new();-- while !self.done() {- children.extend(self.parse_statement_list(true));-- if self.done() {- break;- }-- if self.match_export_or_import() {- if self.match_token(TokenType::Export) {- children.push(self.parse_export_statement());- } else {- children.push(self.parse_import_statement());- }- } else {- self.expected("statement or declaration");- self.consume();- }- }-- // Check that all exported bindings are declared in the module.- self.check_undeclared_exports(&children);-- self.flags.strict_mode = strict_before;- self.flags.await_expression_is_valid = await_before;- let has_top_level_await = self.scope_collector.contains_await_expression();- (children, has_top_level_await)- }-- fn check_undeclared_exports(&mut self, children: &[Statement]) {- use crate::ast::*;-- // Collect all declared names at module level.- let mut declared_names: HashSet<Utf16String> = HashSet::default();- for child in children {- collect_module_declared_names(child, &mut declared_names, &self.arena);- }-- // Check each export's local bindings.- for child in children {- if let StatementKind::Export(data) = &child.inner {- if data.statement.is_some() {- continue;- }- for entry in &data.entries {- if data.module_request.is_some() {- continue;- }- if entry.kind == ExportEntryKind::EmptyNamedExport {- continue;- }- if let Some(ref local_name) = entry.local_or_import_name- && !declared_names.contains(local_name.as_slice())- {- self.syntax_error_at_position(- &format!(- "'{}' in export is not declared",- String::from_utf16_lossy(local_name.as_slice())- ),- child.range.start,- );- }- }- }- }- }-- // https://tc39.es/ecma262/#sec-directive-prologues-and-the-use-strict-directive- // A Directive Prologue is a sequence of ExpressionStatements at the beginning- // of a FunctionBody, ScriptBody, or ModuleBody that each consist entirely of- // a StringLiteral followed by semicolon. A "use strict" directive causes- // subsequent code to be interpreted in strict mode.- pub(crate) fn parse_directive(&mut self) -> (bool, Vec<Statement>) {- self.flags.string_legacy_octal_escape_sequence_in_scope = false;- let mut found_use_strict = false;- let mut statements = Vec::new();- while !self.done() && self.match_token(TokenType::StringLiteral) {- let raw_value = self.token_original_value(&self.current_token);- let statement = self.parse_statement(false);- statements.push(statement);-- if is_use_strict(raw_value) {- found_use_strict = true;- if self.flags.string_legacy_octal_escape_sequence_in_scope {- self.syntax_error("Octal escape sequence in string literal not allowed in strict mode");- }- break;- }- }- self.flags.string_legacy_octal_escape_sequence_in_scope = false;- (found_use_strict, statements)- }-- pub(crate) fn parse_statement_list(&mut self, allow_labelled_functions: bool) -> Vec<Statement> {- let mut statements = Vec::new();- while !self.done() {- if self.match_export_or_import() {- break;- }- if self.match_declaration() {- statements.push(self.parse_declaration());- } else if self.match_statement() {- statements.push(self.parse_statement(allow_labelled_functions));- } else {- break;- }- }- statements- }-- pub(crate) fn match_statement(&mut self) -> bool {- matches!(- self.current_token_type(),- TokenType::CurlyOpen- | TokenType::Return- | TokenType::Var- | TokenType::For- | TokenType::If- | TokenType::Throw- | TokenType::Try- | TokenType::Break- | TokenType::Continue- | TokenType::Switch- | TokenType::Do- | TokenType::While- | TokenType::With- | TokenType::Debugger- | TokenType::Semicolon- | TokenType::Slash- | TokenType::SlashEquals- ) || self.match_expression()- }-- pub(crate) fn match_declaration(&mut self) -> bool {- match self.current_token_type() {- TokenType::Function | TokenType::Class | TokenType::Const => true,- TokenType::Let => {- if !self.flags.strict_mode {- self.try_match_let_declaration()- } else {- true- }- }- TokenType::Async => {- let next = self.next_token();- next.token_type == TokenType::Function && !next.trivia_has_line_terminator- }- TokenType::Identifier => {- let value = self.token_value(&self.current_token);- if value != utf16!("using") {- return false;- }- // UsingDeclaration : `using` [no LineTerminator here] BindingList `;`- // NB: A reserved word cannot start the BindingList, so `using in x` is an expression.- let next = self.next_token();- !next.trivia_has_line_terminator && self.token_is_identifier(&next)- }- TokenType::Await => self.match_await_using_declaration(),- _ => false,- }- }-- // AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead [no LineTerminator here] BindingList `;`- // AwaitUsingDeclarationHead : `await` [no LineTerminator here] `using`- pub(crate) fn match_await_using_declaration(&mut self) -> bool {- if !self.match_token(TokenType::Await) || !self.flags.await_expression_is_valid {- return false;- }- let (using_token, binding_token) = self.next_two_tokens();- using_token.token_type == TokenType::Identifier- && !using_token.trivia_has_line_terminator- && self.token_value(&using_token) == utf16!("using")- && !binding_token.trivia_has_line_terminator- && self.token_is_identifier(&binding_token)- }-- fn try_match_let_declaration(&mut self) -> bool {- let next = self.next_token();- if next.token_type.is_identifier_name() && self.token_value(&next) != utf16!("in") {- return true;- }- if next.token_type == TokenType::CurlyOpen || next.token_type == TokenType::BracketOpen {- return true;- }- false- }-- fn match_iteration_start(&self) -> bool {- matches!(- self.current_token_type(),- TokenType::For | TokenType::While | TokenType::Do- )- }-- pub(crate) fn match_export_or_import(&mut self) -> bool {- if self.match_token(TokenType::Export) {- return true;- }- if self.match_token(TokenType::Import) {- let next = self.next_token();- return next.token_type != TokenType::ParenOpen && next.token_type != TokenType::Period;- }- false- }-- // === Operator precedence ===-- pub(crate) fn operator_precedence(tt: TokenType) -> i32 {- match tt {- TokenType::Period | TokenType::BracketOpen | TokenType::ParenOpen | TokenType::QuestionMarkPeriod => 20,- TokenType::New => 19,- TokenType::PlusPlus | TokenType::MinusMinus => 18,- TokenType::ExclamationMark- | TokenType::Tilde- | TokenType::Typeof- | TokenType::Void- | TokenType::Delete- | TokenType::Await => 17,- TokenType::DoubleAsterisk => 16,- TokenType::Asterisk | TokenType::Slash | TokenType::Percent => 15,- TokenType::Plus | TokenType::Minus => 14,- TokenType::ShiftLeft | TokenType::ShiftRight | TokenType::UnsignedShiftRight => 13,- TokenType::LessThan- | TokenType::LessThanEquals- | TokenType::GreaterThan- | TokenType::GreaterThanEquals- | TokenType::In- | TokenType::Instanceof => 12,- TokenType::EqualsEquals- | TokenType::ExclamationMarkEquals- | TokenType::EqualsEqualsEquals- | TokenType::ExclamationMarkEqualsEquals => 11,- TokenType::Ampersand => 10,- TokenType::Caret => 9,- TokenType::Pipe => 8,- TokenType::DoubleQuestionMark => 7,- TokenType::DoubleAmpersand => 6,- TokenType::DoublePipe => 5,- TokenType::QuestionMark => 4,- TokenType::Equals- | TokenType::PlusEquals- | TokenType::MinusEquals- | TokenType::DoubleAsteriskEquals- | TokenType::AsteriskEquals- | TokenType::SlashEquals- | TokenType::PercentEquals- | TokenType::ShiftLeftEquals- | TokenType::ShiftRightEquals- | TokenType::UnsignedShiftRightEquals- | TokenType::AmpersandEquals- | TokenType::CaretEquals- | TokenType::PipeEquals- | TokenType::DoubleAmpersandEquals- | TokenType::DoublePipeEquals- | TokenType::DoubleQuestionMarkEquals => 3,- TokenType::Yield => 2,- TokenType::Comma => 1,- _ => 0,- }- }-- pub(crate) fn operator_associativity(tt: TokenType) -> Associativity {- match tt {- TokenType::Period- | TokenType::BracketOpen- | TokenType::ParenOpen- | TokenType::QuestionMarkPeriod- | TokenType::Asterisk- | TokenType::Slash- | TokenType::Percent- | TokenType::Plus- | TokenType::Minus- | TokenType::ShiftLeft- | TokenType::ShiftRight- | TokenType::UnsignedShiftRight- | TokenType::LessThan- | TokenType::LessThanEquals- | TokenType::GreaterThan- | TokenType::GreaterThanEquals- | TokenType::In- | TokenType::Instanceof- | TokenType::EqualsEquals- | TokenType::ExclamationMarkEquals- | TokenType::EqualsEqualsEquals- | TokenType::ExclamationMarkEqualsEquals- | TokenType::Typeof- | TokenType::Void- | TokenType::Delete- | TokenType::Await- | TokenType::Ampersand- | TokenType::Caret- | TokenType::Pipe- | TokenType::DoubleQuestionMark- | TokenType::DoubleAmpersand- | TokenType::DoublePipe- | TokenType::Comma => Associativity::Left,- _ => Associativity::Right,- }- }-}--// === Helpers ===--fn is_use_strict(raw: &[u16]) -> bool {- raw == utf16!("'use strict'") || raw == utf16!("\"use strict\"")-}--/// Collect all binding names introduced by a variable declarator target.-fn collect_binding_names(- target: &crate::ast::VariableDeclaratorTarget,- names: &mut HashSet<Utf16String>,- arena: &crate::ast::AstArena,-) {- match target {- crate::ast::VariableDeclaratorTarget::Identifier(identifier) => {- names.insert(arena.name_of(*identifier).clone());- }- crate::ast::VariableDeclaratorTarget::BindingPattern(pattern) => {- collect_binding_pattern_names(pattern, names, arena);- }- }-}--/// Collect all binding names from a binding pattern (object or array destructuring).-fn collect_binding_pattern_names(- pattern: &crate::ast::BindingPattern,- names: &mut HashSet<Utf16String>,- arena: &crate::ast::AstArena,-) {- for entry in &pattern.entries {- if let Some(ref alias) = entry.alias {- match alias {- crate::ast::BindingEntryAlias::Identifier(identifier) => {- names.insert(arena.name_of(*identifier).clone());- }- crate::ast::BindingEntryAlias::BindingPattern(nested) => {- collect_binding_pattern_names(nested, names, arena);- }- crate::ast::BindingEntryAlias::MemberExpression(_) => {}- }- } else if let Some(crate::ast::BindingEntryName::Identifier(identifier)) = &entry.name {- names.insert(arena.name_of(*identifier).clone());- }- }-}--/// Collect all names declared by a top-level module statement.-/// This includes lexical declarations (let/const), function/class declarations, imports,-/// and also `var` declarations which hoist to module scope even when nested inside-/// blocks, loops, if/else, etc.-fn collect_module_declared_names(- statement: &crate::ast::Statement,- names: &mut HashSet<Utf16String>,- arena: &crate::ast::AstArena,-) {- use crate::ast::*;- match &statement.inner {- StatementKind::VariableDeclaration(data) => {- // All top-level declarations (var, let, const) are module-scoped.- for decl in &data.declarations {- collect_binding_names(&decl.target, names, arena);- }- }- StatementKind::FunctionDeclaration(data) => {- if let Some(name) = data.name {- names.insert(arena.name_of(name).clone());- }- }- StatementKind::UsingDeclaration(data) => {- for decl in &data.declarations {- collect_binding_names(&decl.target, names, arena);- }- }- StatementKind::ClassDeclaration(data) => {- if let Some(name) = data.name {- names.insert(arena.name_of(name).clone());- }- }- StatementKind::Import(data) => {- for entry in &data.entries {- names.insert(entry.local_name.clone());- }- }- StatementKind::Export(data) => {- if let Some(ref stmt) = data.statement {- collect_module_declared_names(stmt, names, arena);- }- }- // For any other statement, recurse to find hoisted var declarations.- _ => {- collect_var_declared_names(statement, names, arena);- }- }-}--/// Recursively collect `var` declaration names from nested statements.-/// `var` declarations are hoisted to the enclosing function/module scope,-/// so we must walk into blocks, loops, if/else, switch, try/catch, etc.-/// We do NOT walk into function bodies since `var` does not hoist out of functions.-fn collect_var_declared_names(- statement: &crate::ast::Statement,- names: &mut HashSet<Utf16String>,- arena: &crate::ast::AstArena,-) {- use crate::ast::*;- match &statement.inner {- StatementKind::VariableDeclaration(data) if matches!(data.kind, DeclarationKind::Var) => {- for decl in &data.declarations {- collect_binding_names(&decl.target, names, arena);- }- }- StatementKind::Block(scope) => {- for child in &arena.scopes[*scope].children {- collect_var_declared_names(child, names, arena);- }- }- StatementKind::If(data) => {- collect_var_declared_names(&data.consequent, names, arena);- if let Some(ref alt) = data.alternate {- collect_var_declared_names(alt, names, arena);- }- }- StatementKind::While(data) | StatementKind::DoWhile(data) => {- collect_var_declared_names(&data.body, names, arena);- }- StatementKind::With(data) => {- collect_var_declared_names(&data.body, names, arena);- }- StatementKind::For(data) => {- if let Some(ForInit::Declaration(ref decl)) = data.init {- collect_var_declared_names(decl, names, arena);- }- collect_var_declared_names(&data.body, names, arena);- }- StatementKind::ForInOf(data) => {- if let ForInOfLhs::Declaration(ref decl) = data.lhs {- collect_var_declared_names(decl, names, arena);- }- collect_var_declared_names(&data.body, names, arena);- }- StatementKind::Switch(data) => {- for case in &data.cases {- for child in &arena.scopes[case.scope].children {- collect_var_declared_names(child, names, arena);- }- }- }- StatementKind::Try(data) => {- collect_var_declared_names(&data.block, names, arena);- if let Some(ref handler) = data.handler {- collect_var_declared_names(&handler.body, names, arena);- }- if let Some(ref finalizer) = data.finalizer {- collect_var_declared_names(finalizer, names, arena);- }- }- StatementKind::Labelled(data) => {- collect_var_declared_names(&data.item, names, arena);- }- // Don't recurse into functions (var doesn't hoist out of functions).- // Don't recurse into let/const (they are block-scoped, not hoisted).- _ => {}- }-}--// https://tc39.es/ecma262/#sec-keywords-and-reserved-words-// In strict mode code, the following tokens are also reserved:-// `implements` `interface` `let` `package` `private` `protected` `public` `static` `yield`-pub(crate) fn is_strict_reserved_word(name: &[u16]) -> bool {- name == utf16!("implements")- || name == utf16!("interface")- || name == utf16!("let")- || name == utf16!("package")- || name == utf16!("private")- || name == utf16!("protected")- || name == utf16!("public")- || name == utf16!("static")- || name == utf16!("yield")-}--// https://tc39.es/ecma262/#sec-keywords-and-reserved-words-// All tokens in the |ReservedWord| list below, except for `await` and `yield`, are unconditionally reserved.-pub(crate) fn is_unconditional_reserved_word(name: &[u16]) -> bool {- name == utf16!("break")- || name == utf16!("case")- || name == utf16!("catch")- || name == utf16!("class")- || name == utf16!("const")- || name == utf16!("continue")- || name == utf16!("debugger")- || name == utf16!("default")- || name == utf16!("delete")- || name == utf16!("do")- || name == utf16!("else")- || name == utf16!("enum")- || name == utf16!("export")- || name == utf16!("extends")- || name == utf16!("false")- || name == utf16!("finally")- || name == utf16!("for")- || name == utf16!("function")- || name == utf16!("if")- || name == utf16!("import")- || name == utf16!("in")- || name == utf16!("instanceof")- || name == utf16!("new")- || name == utf16!("null")- || name == utf16!("return")- || name == utf16!("super")- || name == utf16!("switch")- || name == utf16!("this")- || name == utf16!("throw")- || name == utf16!("true")- || name == utf16!("try")- || name == utf16!("typeof")- || name == utf16!("var")- || name == utf16!("void")- || name == utf16!("while")- || name == utf16!("with")-}diff --git a/Libraries/LibJS/Rust/src/parser/declarations.rs b/Libraries/LibJS/Rust/src/parser/declarations.rsdeleted file mode 100644index 00a86bfc111..00000000000--- a/Libraries/LibJS/Rust/src/parser/declarations.rs+++ /dev/null@@ -1,2328 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Declaration parsing: variables, functions, classes, imports, exports.--use crate::fast_hash::HashMap;-use crate::fast_hash::HashSet;--use crate::ast::*;-use crate::bytecode::generator::parse_bigint;-use crate::host::js_number_to_utf16;-use crate::lexer::ch;-use crate::parser::Associativity;-use crate::parser::DeclarationKind;-use crate::parser::ForbiddenTokens;-use crate::parser::FunctionKind;-use crate::parser::MethodKind;-use crate::parser::PRECEDENCE_ASSIGNMENT;-use crate::parser::ParamInfo;-use crate::parser::ParsedParameters;-use crate::parser::Parser;-use crate::parser::Position;-use crate::parser::ProgramType;-use crate::parser::PropertyKey;-use crate::parser::expressions::parse_numeric_value;-use crate::token::TokenType;--fn expression_into_identifier(expression: Expression) -> IdentifierId {- match expression.inner {- ExpressionKind::Identifier(id) => id,- _ => unreachable!("expected Identifier expression"),- }-}--/// Extract bound names from a declaration for export statements.-fn get_declaration_export_names(statement: &Statement, arena: &AstArena) -> Vec<Utf16String> {- match &statement.inner {- StatementKind::VariableDeclaration(vd) => {- let mut names = Vec::new();- for declaration in &vd.declarations {- collect_declarator_names(&declaration.target, &mut names, arena);- }- names- }- StatementKind::UsingDeclaration(declarations) => {- let mut names = Vec::new();- for declaration in &declarations.declarations {- if let VariableDeclaratorTarget::Identifier(id) = &declaration.target {- names.push(arena.name_of(*id).clone());- }- }- names- }- StatementKind::FunctionDeclaration(fd) => {- if let Some(name) = fd.name {- vec![arena.name_of(name).clone()]- } else {- Vec::new()- }- }- StatementKind::ClassDeclaration(class) => {- if let Some(name) = class.name {- vec![arena.name_of(name).clone()]- } else {- Vec::new()- }- }- _ => Vec::new(),- }-}--fn collect_declarator_names(target: &VariableDeclaratorTarget, names: &mut Vec<Utf16String>, arena: &AstArena) {- match target {- VariableDeclaratorTarget::Identifier(id) => names.push(arena.name_of(*id).clone()),- VariableDeclaratorTarget::BindingPattern(pat) => collect_pattern_names(pat, names, arena),- }-}--fn collect_pattern_names(pat: &BindingPattern, names: &mut Vec<Utf16String>, arena: &AstArena) {- for entry in &pat.entries {- match &entry.alias {- Some(BindingEntryAlias::Identifier(id)) => names.push(arena.name_of(*id).clone()),- Some(BindingEntryAlias::BindingPattern(nested)) => collect_pattern_names(nested, names, arena),- _ => {}- }- if entry.alias.is_none()- && let Some(BindingEntryName::Identifier(id)) = &entry.name- {- names.push(arena.name_of(*id).clone());- }- }-}--impl Parser<'_> {- fn can_have_using_declaration(&self) -> bool {- // NB: The body of a dynamic function is first checked on its own as a script that can return, and it is a- // FunctionBody, which can have using declarations.- self.scope_collector.can_have_using_declaration() || self.flags.in_function_context- }-- pub(crate) fn parse_declaration(&mut self) -> Statement {- if self.match_token(TokenType::Async) {- let next = self.next_token();- if next.token_type == TokenType::Function && !next.trivia_has_line_terminator {- return self.parse_function_declaration();- }- }-- match self.current_token_type() {- TokenType::Function => self.parse_function_declaration(),- TokenType::Class => self.parse_class_declaration(),- TokenType::Let | TokenType::Const => self.parse_variable_declaration(false),- TokenType::Identifier if self.token_value(&self.current_token) == utf16!("using") => {- if !self.can_have_using_declaration() {- self.syntax_error("'using' not allowed outside of block, for loop or function");- }- self.parse_using_declaration(false, false)- }- TokenType::Await if self.match_await_using_declaration() => {- if !self.can_have_using_declaration() {- self.syntax_error("'await using' not allowed outside of block, for loop or function");- }- self.parse_using_declaration(false, true)- }- _ => {- self.expected("declaration");- let start = self.position();- self.consume();- self.statement(start, StatementKind::Empty)- }- }- }-- // https://tc39.es/ecma262/#sec-variable-statement- // https://tc39.es/ecma262/#sec-let-and-const-declarations- // VariableStatement : `var` VariableDeclarationList `;`- // LexicalDeclaration : LetOrConst BindingList `;`- // NB: `var` declarations are hoisted to the enclosing function/script scope,- // while `let`/`const` are block-scoped (sec-declarations-and-the-variable-statement).- pub(crate) fn parse_variable_declaration(&mut self, is_for_loop: bool) -> Statement {- let start = self.position();- let declaration_line = self.current_token().line_number;- let declaration_column = self.current_token().line_column;-- let kind = match self.current_token_type() {- TokenType::Var => DeclarationKind::Var,- TokenType::Let => DeclarationKind::Let,- TokenType::Const => DeclarationKind::Const,- _ => {- self.expected("variable declaration keyword");- DeclarationKind::Var- }- };- self.consume();-- let mut declarators: Vec<VariableDeclarator> = Vec::new();- let mut any_init = false;-- loop {- let declaration_start = self.position();-- let target = if self.match_identifier() {- let token = self.consume();- let name = self.token_identifier_name(&token);- let name_str = self.arena.strings[name].clone();- self.check_identifier_name_for_assignment_validity(name_str.as_slice(), false);- if kind != DeclarationKind::Var && name_str.as_slice() == utf16!("let") {- self.syntax_error("Lexical binding may not be called 'let'");- }- let id = self.make_identifier(declaration_start, name);-- if kind == DeclarationKind::Var {- let Self {- scope_collector, arena, ..- } = self;- scope_collector.add_var_declaration(- &[(name_str.as_slice(), Some(id))],- declaration_line,- declaration_column,- Some(DeclarationKind::Var),- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- } else {- self.scope_collector.add_lexical_declaration(- &[name_str.as_slice()],- declaration_line,- declaration_column,- );- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- Some(kind),- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }-- VariableDeclaratorTarget::Identifier(id)- } else if self.match_token(TokenType::CurlyOpen) || self.match_token(TokenType::BracketOpen) {- let pat = self.parse_binding_pattern();- let bound_names = std::mem::take(&mut self.pattern_bound_names);- // Materialize slices for scope-collector calls (which key on Utf16String).- let name_strs: Vec<Utf16String> = bound_names- .iter()- .map(|(n, _)| self.arena.strings[*n].clone())- .collect();-- for name in &name_strs {- self.check_identifier_name_for_assignment_validity(name.as_slice(), false);- if kind != DeclarationKind::Var && name.as_slice() == utf16!("let") {- self.syntax_error("Lexical binding may not be called 'let'");- }- }-- if kind != DeclarationKind::Var {- let mut seen: HashSet<&[u16]> = HashSet::default();- for name in &name_strs {- if !seen.insert(name.as_slice()) {- self.syntax_error("Duplicate parameter names in bindings");- }- }- }-- // Register bound names with scope collector.- if kind == DeclarationKind::Var {- let entries: Vec<(&[u16], Option<IdentifierId>)> = name_strs- .iter()- .zip(bound_names.iter())- .map(|(n, (_, id))| (n.as_slice(), Some(*id)))- .collect();- let Self {- scope_collector, arena, ..- } = self;- scope_collector.add_var_declaration(- &entries,- declaration_line,- declaration_column,- Some(DeclarationKind::Var),- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- } else {- let refs: Vec<&[u16]> = name_strs.iter().map(|n| n.as_slice()).collect();- self.scope_collector- .add_lexical_declaration(&refs, declaration_line, declaration_column);- let Self {- scope_collector, arena, ..- } = self;- for (_name, id) in &bound_names {- scope_collector.register_identifier(- *id,- Some(kind),- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- }-- VariableDeclaratorTarget::BindingPattern(pat)- } else {- self.expected("identifier or a binding pattern");- self.consume();- let empty = self.arena.strings.intern(&[]);- let id = self.make_identifier(declaration_start, empty);- VariableDeclaratorTarget::Identifier(id)- };-- let init = if self.match_token(TokenType::Equals) {- self.consume();- any_init = true;- let forbidden = if is_for_loop {- ForbiddenTokens::with_in()- } else {- ForbiddenTokens::none()- };- Some(self.parse_expression(PRECEDENCE_ASSIGNMENT, Associativity::Right, forbidden))- } else {- None- };-- if kind == DeclarationKind::Const && init.is_none() && !is_for_loop {- self.syntax_error("Missing initializer in const declaration");- }-- declarators.push(VariableDeclarator {- range: self.range_from(start),- target,- init,- });-- if !self.match_token(TokenType::Comma) {- break;- }- self.consume();- }-- if !is_for_loop {- self.consume_or_insert_semicolon();- }-- if is_for_loop {- self.for_loop_declaration_count = declarators.len();- self.for_loop_declaration_has_init = any_init;- self.for_loop_declaration_is_var = kind == DeclarationKind::Var;- self.for_loop_declaration_is_pattern = declarators- .iter()- .any(|d| matches!(d.target, VariableDeclaratorTarget::BindingPattern(_)));- }-- self.statement(- start,- StatementKind::VariableDeclaration(Box::new(VariableDeclarationData {- kind,- declarations: declarators,- })),- )- }-- // https://tc39.es/ecma262/#sec-let-and-const-declarations- // UsingDeclaration : `using` [no LineTerminator here] BindingList `;`- // AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead [no LineTerminator here] BindingList `;`- // NB: `using` and `await using` declarations have lexical scoping like `const` and invoke- // the Symbol.dispose or Symbol.asyncDispose method when the enclosing scope exits.- pub(crate) fn parse_using_declaration(&mut self, is_for_loop: bool, is_await: bool) -> Statement {- let start = self.position();- let declaration_line = self.current_token().line_number;- let declaration_column = self.current_token().line_column;- if is_await {- self.consume(); // consume 'await'- self.scope_collector.set_contains_await_expression();- }- self.consume(); // consume 'using'-- let mut declarators: Vec<VariableDeclarator> = Vec::new();-- loop {- let declaration_start = self.position();-- if !self.match_identifier() {- // NB: The error is reported at the start of the declaration, since an error inside of what follows is- // dropped if it is reparsed as an assignment pattern, like in `using x = null, [] = null;`.- let message = format!(- "Unexpected token {}. Expected identifier",- self.current_token.token_type.name()- );- self.syntax_error_at_position(&message, start);- break;- }- let token = self.consume();- let name = self.token_identifier_name(&token);- let name_str = self.arena.strings[name].clone();-- self.check_identifier_name_for_assignment_validity(name_str.as_slice(), false);- if name_str.as_slice() == utf16!("let") {- self.syntax_error("Lexical binding may not be called 'let'");- }-- let id = self.make_identifier(declaration_start, name);-- self.scope_collector- .add_lexical_declaration(&[name_str.as_slice()], declaration_line, declaration_column);- // NB: The bindings of using declarations are constant, like those of const declarations.- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- Some(DeclarationKind::Const),- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );-- let init = if self.match_token(TokenType::Equals) {- self.consume();- if is_for_loop {- Some(self.parse_expression(PRECEDENCE_ASSIGNMENT, Associativity::Right, ForbiddenTokens::with_in()))- } else {- Some(self.parse_assignment_expression())- }- } else if !is_for_loop {- self.consume_token(TokenType::Equals);- None- } else {- None- };-- // C++ uses rule_start (using keyword position) for all VariableDeclarators.- declarators.push(VariableDeclarator {- range: self.range_from(start),- target: VariableDeclaratorTarget::Identifier(id),- init,- });-- if self.match_token(TokenType::Comma) {- self.consume();- continue;- }- break;- }-- if !is_for_loop {- self.consume_or_insert_semicolon();- }-- if is_for_loop {- let any_init = declarators.iter().any(|d| d.init.is_some());- self.for_loop_declaration_count = declarators.len();- self.for_loop_declaration_has_init = any_init;- }-- self.statement(- start,- StatementKind::UsingDeclaration(Box::new(UsingDeclarationData {- is_await,- declarations: declarators,- })),- )- }-- // https://tc39.es/ecma262/#sec-function-definitions- // FunctionDeclaration : `function` BindingIdentifier `(` FormalParameters `)` `{` FunctionBody `}`- // | [+Default] `function` `(` FormalParameters `)` `{` FunctionBody `}`- // NB: The second form (without name) is only valid in `export default` context.- pub(crate) fn parse_function_declaration(&mut self) -> Statement {- let start = self.position();- let declaration_line = self.current_token().line_number;- let declaration_column = self.current_token().line_column;-- let saved_might_need_arguments = self.flags.function_might_need_arguments_object;- self.flags.function_might_need_arguments_object = false;-- let is_async = self.eat(TokenType::Async);- self.consume_token(TokenType::Function);- let is_generator = self.eat(TokenType::Asterisk);- let kind = FunctionKind::from_async_generator(is_async, is_generator);-- // Parse function name.- let (name, fn_name) = if self.has_default_export_name && !self.match_identifier() {- let default_name = Utf16String::from(utf16!("*default*"));- self.last_function_name = default_name.clone();- (- Some(self.make_identifier_from_slice(start, default_name.as_slice())),- default_name,- )- } else if self.match_identifier() {- let token = self.consume();- let value = Utf16String::from(self.token_value(&token));- self.last_function_name = value.clone();- (Some(self.make_identifier_from_slice(start, value.as_slice())), value)- } else {- self.last_function_name.0.clear();- (None, Utf16String::default())- };- self.last_function_kind = kind;-- // Register function declaration in parent scope (before opening function scope).- let strict = self.flags.strict_mode;- let Self {- scope_collector, arena, ..- } = self;- scope_collector.add_function_declaration(- &fn_name,- name,- kind,- strict,- declaration_line,- declaration_column,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );-- let fn_name_for_scope = if fn_name.is_empty() {- None- } else {- Some(fn_name.as_slice())- };- self.scope_collector.open_function_scope(fn_name_for_scope);- self.scope_collector.set_is_function_declaration();-- let fd = self.parse_function_common(- name,- &fn_name,- kind,- is_async,- is_generator,- start,- saved_might_need_arguments,- );- let decl_name = fd.name;- let decl_kind = fd.kind;- let function_id = self.insert_function_data(fd);- self.statement(- start,- StatementKind::FunctionDeclaration(Box::new(FunctionDeclarationData {- function_id,- name: decl_name,- kind: decl_kind,- is_hoisted: false,- })),- )- }-- // https://tc39.es/ecma262/#sec-function-definitions- // FunctionExpression : `function` BindingIdentifier? `(` FormalParameters `)` `{` FunctionBody `}`- // NB: The function name, if present, is bound within the function's own scope- // (not the enclosing scope), allowing recursive self-reference.- pub(crate) fn parse_function_expression(&mut self) -> Expression {- let start = self.position();-- let saved_might_need_arguments = self.flags.function_might_need_arguments_object;- self.flags.function_might_need_arguments_object = false;-- let is_async = self.eat(TokenType::Async);- self.consume_token(TokenType::Function);- let is_generator = self.eat(TokenType::Asterisk);- let kind = FunctionKind::from_async_generator(is_async, is_generator);-- let mut fn_name_value = Utf16String::default();- let name = if self.match_identifier() {- let token = self.consume();- fn_name_value = Utf16String::from(self.token_value(&token));- Some(self.make_identifier_from_slice(start, fn_name_value.as_slice()))- } else if self.match_token(TokenType::Yield) || self.match_token(TokenType::Await) {- // C++ explicitly allows yield/await as function expression names- // even inside generator/async contexts, then validates after.- let token = self.consume();- fn_name_value = Utf16String::from(self.token_value(&token));- Some(self.make_identifier_from_slice(start, fn_name_value.as_slice()))- } else {- None- };-- // https://tc39.es/ecma262/#prod-GeneratorExpression- // GeneratorExpression : `function` `*` BindingIdentifier[+Yield, ~Await]? `(` FormalParameters[+Yield, ~Await] `)`- // `{` GeneratorBody `}`- if kind == FunctionKind::Generator && fn_name_value.as_slice() == utf16!("yield") {- self.syntax_error("'yield' is not allowed as a generator function expression name");- }-- // Register the function expression name in the outer scope, matching C++.- // This must happen before open_function_scope so that the identifier group- // exists with declaration_kind=None, preventing later var declarations- // with the same name from setting a spurious declaration_kind.- if let Some(id) = name {- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(id, None, &mut arena.identifiers, &arena.strings, &mut arena.scopes);- }-- // Open function scope (function expression name is bound within its own scope).- let fn_name_for_scope = if fn_name_value.is_empty() {- None- } else {- Some(fn_name_value.as_slice())- };- self.scope_collector.open_function_scope(fn_name_for_scope);-- let fd = self.parse_function_common(- name,- &fn_name_value,- kind,- is_async,- is_generator,- start,- saved_might_need_arguments,- );- let function_id = self.insert_function_data(fd);- self.expression(start, ExpressionKind::Function(function_id))- }-- /// Shared logic for parsing formal parameters, function body, and constructing- /// FunctionData. Called after the function scope has been opened.- #[allow(clippy::too_many_arguments)]- fn parse_function_common(- &mut self,- name: Option<IdentifierId>,- fn_name: &[u16],- kind: FunctionKind,- is_async: bool,- is_generator: bool,- start: Position,- saved_might_need_arguments: bool,- ) -> FunctionData {- // Validate name against async generator and class static init restrictions.- if name.is_some() {- if kind == FunctionKind::AsyncGenerator && (fn_name == utf16!("await") || fn_name == utf16!("yield")) {- let name_str = String::from_utf16_lossy(fn_name);- self.syntax_error(&format!(- "async generator function is not allowed to be called '{name_str}'"- ));- }- if self.flags.in_class_static_init_block && is_async && fn_name == utf16!("await") {- self.syntax_error("'await' is a reserved word");- }- }-- let in_generator_before = self.flags.in_generator_function_context;- let await_before = self.flags.await_expression_is_valid;- let saved_static_init = self.flags.in_class_static_init_block;- let saved_field_init = self.flags.in_class_field_initializer;- let saved_allow_super_call = self.flags.allow_super_constructor_call;- let saved_allow_super_lookup = self.flags.allow_super_property_lookup;- let saved_new_target = self.flags.new_target_is_valid;- self.flags.in_generator_function_context = is_generator;- self.flags.await_expression_is_valid = is_async;- self.flags.in_class_static_init_block = false;- self.flags.in_class_field_initializer = false;- self.flags.allow_super_constructor_call = false;- self.flags.allow_super_property_lookup = false;- self.flags.new_target_is_valid = true;-- // Save pattern_bound_names so that destructuring patterns in the- // function body don't steal names from an outer binding context.- let saved_pattern_bound_names = std::mem::take(&mut self.pattern_bound_names);-- self.push_function_context();- let parsed = self.parse_formal_parameters();- self.register_function_parameters_with_scope(&parsed.parameters, &parsed.parameter_info);-- self.flags.in_generator_function_context = in_generator_before;- self.flags.await_expression_is_valid = await_before;-- let (body, has_use_strict, mut insights) = self.parse_function_body(is_async, is_generator, parsed.is_simple);- self.flags.allow_super_constructor_call = saved_allow_super_call;- self.flags.allow_super_property_lookup = saved_allow_super_lookup;-- self.scope_collector.close_scope();- self.pattern_bound_names = saved_pattern_bound_names;-- if name.is_some() {- self.check_identifier_name_for_assignment_validity(fn_name, has_use_strict);- }- let parameters_are_strict = self.flags.strict_mode || has_use_strict;- if parameters_are_strict || kind != FunctionKind::Normal {- self.check_parameters_post_body(&parsed.parameter_info, parameters_are_strict, kind);- }- self.flags.in_class_static_init_block = saved_static_init;- self.flags.in_class_field_initializer = saved_field_init;- self.flags.new_target_is_valid = saved_new_target;-- insights.might_need_arguments_object = self.flags.function_might_need_arguments_object;- self.flags.function_might_need_arguments_object = saved_might_need_arguments;- let nested_function_ids = self.pop_function_context();-- FunctionData {- name,- source_text_start: start.offset,- source_text_end: self.source_text_end_offset(),- body: Box::new(body),- parameters: parsed.parameters,- function_length: parsed.function_length,- kind,- is_strict_mode: self.flags.strict_mode || has_use_strict,- is_arrow_function: false,- parsing_insights: insights,- nested_function_ids: Some(nested_function_ids),- }- }-- // https://tc39.es/ecma262/#sec-class-definitions- // ClassDeclaration : `class` BindingIdentifier ClassTail- // ClassExpression : `class` BindingIdentifier? ClassTail- // ClassTail : ClassHeritage? `{` ClassBody `}`- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // NB: All code within a ClassBody is in strict mode.- pub(crate) fn parse_class_expression(&mut self, expect_name: bool) -> Expression {- let start = self.position();-- let strict_before = self.flags.strict_mode;- self.flags.strict_mode = true;-- self.consume_token(TokenType::Class);-- let (name_id, name_value) = if expect_name || self.match_identifier() {- if self.match_identifier() {- let token = self.consume();- let value = Utf16String::from(self.token_value(&token));- self.last_class_name = value.clone();- (Some(self.make_identifier_from_slice(start, value.as_slice())), value)- } else if expect_name {- self.expected("class name");- self.last_class_name.0.clear();- (None, Utf16String::default())- } else {- self.last_class_name.0.clear();- (None, Utf16String::default())- }- } else {- self.last_class_name.0.clear();- (None, Utf16String::default())- };-- let saved_class_name = self.last_class_name.clone();-- let class_name_for_scope = if name_value.is_empty() {- None- } else {- Some(name_value.as_slice())- };- self.scope_collector.open_class_declaration_scope(class_name_for_scope);-- if name_id.is_some() {- self.check_identifier_name_for_assignment_validity(&name_value, true);- if self.flags.in_class_static_init_block && name_value == utf16!("await") {- self.syntax_error("Identifier must not be a reserved word in modules ('await')");- }- }-- let super_class = if self.match_token(TokenType::Extends) {- self.consume();- let heritage_start = self.position();- let expression = self.parse_expression_any();- // ClassHeritage[Yield, Await] : `extends` LeftHandSideExpression[?Yield, ?Await]- if expression.range.start.offset == heritage_start.offset- && let ExpressionKind::Function(function_id) = &expression.inner- && self.function_table.get(*function_id).is_arrow_function- {- self.syntax_error("Arrow function is not allowed in class heritage");- }- Some(Box::new(expression))- } else {- None- };-- self.consume_token(TokenType::CurlyOpen);- let mut elements: Vec<Node<ClassElement>> = Vec::new();- let mut constructor: Option<Expression> = None;- let mut found_private_names: HashMap<Utf16String, (Option<ClassMethodKind>, bool)> = HashMap::default();-- self.referenced_private_names_stack.push(HashSet::default());-- let saved_class_has_super = self.class_has_super_class;- self.class_has_super_class = super_class.is_some();- self.class_scope_depth += 1;-- while !self.match_token(TokenType::CurlyClose) && !self.done() {- if self.match_token(TokenType::Semicolon) {- self.consume();- continue;- }-- let (element, maybe_ctor) = self.parse_class_element(start, &mut found_private_names);- if let Some(ctor) = maybe_ctor {- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if PrototypePropertyNameList of ClassElementList- // contains more than one occurrence of "constructor".- if constructor.is_some() {- self.syntax_error("Classes may not have more than one constructor");- }- constructor = Some(ctor);- } else if let Some(element) = element {- elements.push(element);- }- }-- self.consume_token(TokenType::CurlyClose);- self.class_scope_depth -= 1;- self.class_has_super_class = saved_class_has_super;-- // AllPrivateNamesValid: check that all referenced private names were declared.- let referenced = self.referenced_private_names_stack.pop().unwrap_or_default();- for name in referenced {- if found_private_names.contains_key(&name) {- continue;- }- // Bubble up to outer class, or error if no outer class.- if let Some(outer) = self.referenced_private_names_stack.last_mut() {- outer.insert(name);- } else if self.initiated_by_eval {- self.register_eval_referenced_private_name(&name);- } else {- let name_str = String::from_utf16_lossy(&name);- self.syntax_error(&format!("Reference to undeclared private field or method '{name_str}'"));- }- }- self.flags.strict_mode = strict_before;-- self.scope_collector.close_scope();-- if constructor.is_none() {- constructor = Some(self.synthesize_default_constructor(start, &name_value, super_class.is_some()));- }-- self.last_class_name = saved_class_name;-- self.expression(- start,- ExpressionKind::Class(Box::new(ClassData {- name: name_id,- source_text_start: start.offset,- source_text_end: self.source_text_end_offset(),- constructor: constructor.map(Box::new),- super_class,- elements,- })),- )- }-- pub(crate) fn parse_class_declaration(&mut self) -> Statement {- let start = self.position();- let class_expression = self.parse_class_expression(true);- // Convert the class expression into a class declaration by extracting ClassData.- match class_expression.inner {- ExpressionKind::Class(data) => {- // Register class name as lexical declaration in the outer scope.- // The inner class scope (opened/closed inside parse_class_expression)- // binds the name for self-reference. The outer scope needs the name- // registered as a lexical declaration so it's visible to sibling code.- if let Some(name_ident) = data.name {- let name_slice = self.arena.name_of(name_ident).clone();- self.scope_collector- .add_lexical_declaration(&[name_slice.as_slice()], start.line, start.column);- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- name_ident,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- self.statement(start, StatementKind::ClassDeclaration(data))- }- _ => unreachable!("parse_class_expression must return ExpressionKind::Class"),- }- }-- // https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation- // If no constructor is present in the ClassBody:- // - Base class: constructor() {}- // - Derived class: constructor(...arguments) { super(...arguments); }- fn synthesize_default_constructor(&mut self, start: Position, class_name: &[u16], has_super: bool) -> Expression {- let ctor_name = if !class_name.is_empty() {- Some(self.make_identifier_from_slice(start, class_name))- } else {- None- };-- // Note: No scope collector calls here. The synthesized constructor AST- // is stored in the SFD and compiled lazily — scope analysis runs at that point.-- if has_super {- let arguments_name_id = self.arena.strings.intern(utf16!("args"));- let range = self.range_from(start);-- let arguments_ref = self.arena.identifiers.insert(Identifier::new(range, arguments_name_id));- let arguments_expression = self.expression(start, ExpressionKind::Identifier(arguments_ref));-- let super_call = self.expression(- start,- ExpressionKind::SuperCall(Box::new(SuperCallData {- arguments: vec![CallArgument {- value: arguments_expression,- is_spread: true,- }],- is_synthetic: true,- })),- );- let return_statement = self.statement(start, StatementKind::Return(Some(Box::new(super_call))));- let body_scope = self.make_scope(vec![return_statement]);- let body = self.statement(start, StatementKind::Block(body_scope));-- let arguments_binding = self- .arena- .identifiers- .insert(Identifier::new(self.range_from(start), arguments_name_id));- let parameters = vec![FunctionParameter {- binding: FunctionParameterBinding::Identifier(arguments_binding),- default_value: None,- is_rest: true,- }];-- let function_id = self.insert_function_data(FunctionData {- name: ctor_name,- source_text_start: start.offset,- source_text_end: self.source_text_end_offset(),- body: Box::new(body),- parameters,- function_length: 0,- kind: FunctionKind::Normal,- is_strict_mode: true,- is_arrow_function: false,- parsing_insights: FunctionParsingInsights {- uses_this: true,- uses_this_from_environment: true,- ..FunctionParsingInsights::default()- },- nested_function_ids: Some(Vec::new()),- });- self.expression(start, ExpressionKind::Function(function_id))- } else {- let body_scope = self.make_scope(Vec::new());- let body = self.statement(start, StatementKind::Block(body_scope));-- let function_id = self.insert_function_data(FunctionData {- name: ctor_name,- source_text_start: start.offset,- source_text_end: self.source_text_end_offset(),- body: Box::new(body),- parameters: Vec::new(),- function_length: 0,- kind: FunctionKind::Normal,- is_strict_mode: true,- is_arrow_function: false,- parsing_insights: FunctionParsingInsights {- uses_this: true,- uses_this_from_environment: true,- ..FunctionParsingInsights::default()- },- nested_function_ids: Some(Vec::new()),- });- self.expression(start, ExpressionKind::Function(function_id))- }- }-- // https://tc39.es/ecma262/#sec-class-definitions- // ClassElement : MethodDefinition- // | `static` MethodDefinition- // | FieldDefinition `;`- // | `static` FieldDefinition `;`- // | ClassStaticBlock- // | `;`- fn parse_class_element(- &mut self,- class_start: Position,- found_private_names: &mut HashMap<Utf16String, (Option<ClassMethodKind>, bool)>,- ) -> (Option<Node<ClassElement>>, Option<Expression>) {- // C++ lexes "static" as Identifier and checks original_value() == "static".- let mut is_static =- if self.match_identifier() && self.token_original_value(&self.current_token) == utf16!("static") {- self.consume();- // https://tc39.es/ecma262/#sec-class-static-initialization-blocks- // ClassStaticBlock : `static` `{` ClassStaticBlockBody `}`- if self.match_token(TokenType::CurlyOpen) {- // C++ captures static_start (push_start) before consuming '{'.- let static_start = self.position();- self.consume(); // consume '{'- let saved_flags = self.flags;- self.flags.in_break_context = false;- self.flags.in_continue_context = false;- self.flags.in_function_context = false;- self.flags.in_generator_function_context = false;- self.flags.await_expression_is_valid = false;- self.flags.in_class_field_initializer = true;- self.flags.in_class_static_init_block = true;- self.flags.allow_super_property_lookup = true;- self.flags.new_target_is_valid = true;- self.scope_collector.open_static_init_scope(None);- // Save pattern_bound_names so that destructuring patterns in the- // static block don't steal names from an outer binding context.- let saved_pattern_bound_names = std::mem::take(&mut self.pattern_bound_names);- let children = self.parse_statement_list(false);- self.pattern_bound_names = saved_pattern_bound_names;- self.flags = saved_flags;- self.consume_token(TokenType::CurlyClose);- let scope = self.make_scope(children);- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();- // C++ uses rule_start (class start) for FunctionBody position.- let body = self.statement(- class_start,- StatementKind::FunctionBody {- scope,- in_strict_mode: self.flags.strict_mode,- },- );- // C++ uses static_start (after '{') for StaticInitializer position.- return (- Some(Node::new(- self.range_from(static_start),- ClassElement::StaticInitializer { body: Box::new(body) },- )),- None,- );- }- true- } else {- false- };-- let mut is_async = false;- let mut is_generator = false;- let mut is_getter = false;- let mut is_setter = false;- let function_start = self.position();-- // Check modifiers (must not contain escape sequences).- if self.match_identifier_name() {- let value = self.token_original_value(&self.current_token).to_vec();- if value == utf16!("get") && self.match_property_key_ahead() {- is_getter = true;- self.consume();- } else if value == utf16!("set") && self.match_property_key_ahead() {- is_setter = true;- self.consume();- } else if value == utf16!("async") {- let next = self.next_token();- if !next.trivia_has_line_terminator- && next.token_type != TokenType::ParenOpen- && next.token_type != TokenType::Colon- && next.token_type != TokenType::Comma- && next.token_type != TokenType::CurlyClose- && next.token_type != TokenType::Semicolon- && next.token_type != TokenType::Equals- {- is_async = true;- self.consume();- }- }- }-- if self.match_token(TokenType::Asterisk) {- is_generator = true;- self.consume();- }-- // If we consumed a modifier keyword (static/async/get/set) but the next token- // is one that can't start a property key (`;`, `=`, `(`, `}`), the keyword was- // actually the field/method name, not a modifier.- let PropertyKey {- expression: key,- name: key_value,- ..- } = if (is_static || is_async || is_getter || is_setter)- && (self.match_token(TokenType::Semicolon)- || self.match_token(TokenType::Equals)- || self.match_token(TokenType::ParenOpen)- || self.match_token(TokenType::CurlyClose))- {- let name: &[u16] = if is_async {- is_async = false;- utf16!("async")- } else if is_getter {- is_getter = false;- utf16!("get")- } else if is_setter {- is_setter = false;- utf16!("set")- } else {- is_static = false;- utf16!("static")- };- let expression = self.expression(- class_start,- ExpressionKind::StringLiteral(Box::new(Utf16String(name.to_vec()))),- );- PropertyKey {- expression,- name: Some(Utf16String::from(name)),- is_proto: false,- is_computed: false,- is_identifier: false,- }- } else {- self.parse_property_key()- };-- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if PropName of ClassElement is "prototype"- // and ClassElement is `static` MethodDefinition or `static` FieldDefinition.- if is_static && key_value.as_deref() == Some(utf16!("prototype")) {- self.syntax_error("Classes may not have a static property named 'prototype'");- }-- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if PrivateBoundIdentifiers of ClassElementList contains- // any duplicate entries, unless the name is used once for a getter and once for- // a setter and in no other entries, and they are either both static or both non-static.- let is_private = key_value.as_ref().is_some_and(|v| v.first() == Some(&ch(b'#')));- if is_private {- let name = key_value.as_ref().unwrap();- let current_kind = if is_getter {- Some(ClassMethodKind::Getter)- } else if is_setter {- Some(ClassMethodKind::Setter)- } else {- None- };- let is_accessor = is_getter || is_setter;- if is_accessor {- // Getter or setter: check against existing private names- if let Some(&(existing_kind, existing_static)) = found_private_names.get(name) {- let is_error = match existing_kind {- // Existing is not a method (field/plain method) → error- None => true,- // Existing is a getter/setter- Some(ek) => {- // Different staticness → error- existing_static != is_static- // Same kind (getter+getter or setter+setter) → error- // Plain method → error- || ek == ClassMethodKind::Method- || ek == current_kind.unwrap()- }- };- if is_error {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!("Duplicate private field or method named '{name_str}'"));- }- }- found_private_names.insert(name.clone(), (current_kind, is_static));- } else if found_private_names- .insert(name.clone(), (current_kind, is_static))- .is_some()- {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!("Duplicate private field or method named '{name_str}'"));- }- }-- if self.match_token(TokenType::ParenOpen) {- let ctor_name = utf16!("constructor");- let is_constructor = !is_static && !is_getter && !is_setter && key_value.as_deref() == Some(ctor_name);-- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if SpecialMethod of MethodDefinition is true- // and PropName of MethodDefinition is "constructor".- if is_constructor {- if is_getter || is_setter {- self.syntax_error("Class constructor may not be an accessor");- }- if is_generator {- self.syntax_error("Class constructor may not be a generator");- }- if is_async {- self.syntax_error("Class constructor may not be async");- }- }-- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if PropName of MethodDefinition is "constructor"- // and SpecialMethod of MethodDefinition is true (getter/setter).- if !is_static && (is_getter || is_setter) && key_value.as_deref() == Some(ctor_name) {- self.syntax_error("Class constructor may not be an accessor");- }-- let method_kind = if is_constructor {- MethodKind::Constructor- } else if is_getter {- MethodKind::Getter- } else if is_setter {- MethodKind::Setter- } else {- MethodKind::Normal- };- let function = self.parse_method_definition(is_async, is_generator, method_kind, function_start);- let class_method_kind = if is_getter {- ClassMethodKind::Getter- } else if is_setter {- ClassMethodKind::Setter- } else {- ClassMethodKind::Method- };-- if is_constructor {- return (None, Some(function));- }-- return (- Some(Node::new(- self.range_from(class_start),- ClassElement::Method {- key: Box::new(key),- function: Box::new(function),- kind: class_method_kind,- is_static,- },- )),- None,- );- }-- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if PropName of ClassElement is "constructor"- // and ClassElement is FieldDefinition.- if key_value.as_deref() == Some(utf16!("constructor")) {- self.syntax_error("Class cannot have field named 'constructor'");- }-- let init = if self.match_token(TokenType::Equals) {- self.consume();- let saved_await = self.flags.await_expression_is_valid;- let saved_field_init = self.flags.in_class_field_initializer;- let saved_super_lookup = self.flags.allow_super_property_lookup;- self.flags.await_expression_is_valid = false;- self.flags.in_class_field_initializer = true;- self.flags.allow_super_property_lookup = true;- self.scope_collector.open_class_field_scope(None);- let expression = self.parse_assignment_expression();- self.scope_collector.close_scope();- self.flags.await_expression_is_valid = saved_await;- self.flags.in_class_field_initializer = saved_field_init;- self.flags.allow_super_property_lookup = saved_super_lookup;- Some(Box::new(expression))- } else {- None- };-- self.consume_or_insert_semicolon();- (- Some(Node::new(- self.range_from(class_start),- ClassElement::Field {- key: Box::new(key),- initializer: init,- is_static,- },- )),- None,- )- }-- // https://tc39.es/ecma262/#sec-function-definitions-static-semantics-early-errors- // It is a Syntax Error if FunctionBodyContainsUseStrict of FunctionBody is true- // and IsSimpleParameterList of FormalParameters is false.- pub(crate) fn parse_function_body(- &mut self,- is_async: bool,- is_generator: bool,- is_simple: bool,- ) -> (Statement, bool, FunctionParsingInsights) {- self.consume_token(TokenType::CurlyOpen);- // C++ captures FunctionBody position AFTER consuming `{`.- let start = self.position();-- let in_function_before = self.flags.in_function_context;- let in_generator_before = self.flags.in_generator_function_context;- let await_before = self.flags.await_expression_is_valid;- let formal_parameter_before = self.flags.in_formal_parameter_context;- let old_labels = std::mem::take(&mut self.labels_in_scope);- self.flags.in_function_context = true;- self.flags.in_generator_function_context = is_generator;- self.flags.await_expression_is_valid = is_async;- self.flags.in_formal_parameter_context = false;-- let (has_use_strict, mut children) = self.parse_directive();- let body_is_strict = has_use_strict || self.flags.strict_mode;-- let strict_before = self.flags.strict_mode;- if has_use_strict {- self.flags.strict_mode = true;- if !is_simple {- self.syntax_error("Illegal 'use strict' directive in function with non-simple parameter list");- }- }-- // https://tc39.es/ecma262/#sec-labelled-function-declarations- // That rule is then modified to suppress the Syntax Error in non-strict code if the host supports this feature.- children.extend(self.parse_statement_list(true));-- self.flags.strict_mode = strict_before;- self.flags.in_function_context = in_function_before;- self.flags.in_generator_function_context = in_generator_before;- self.flags.await_expression_is_valid = await_before;- self.flags.in_formal_parameter_context = formal_parameter_before;- self.labels_in_scope = old_labels;-- // Read scope analysis flags before the function scope is closed.- let insights = FunctionParsingInsights {- contains_direct_call_to_eval: self.scope_collector.contains_direct_call_to_eval(),- uses_this: self.scope_collector.uses_this(),- uses_this_from_environment: self.scope_collector.uses_this_from_environment(),- ..FunctionParsingInsights::default()- };-- self.consume_token(TokenType::CurlyClose);-- let scope = self.make_scope(children);- self.scope_collector.set_scope_node(scope);-- let body = self.statement(- start,- StatementKind::FunctionBody {- scope,- in_strict_mode: body_is_strict,- },- );-- (body, has_use_strict, insights)- }-- // https://tc39.es/ecma262/#sec-function-definitions- // FormalParameters : [empty]- // | FunctionRestParameter- // | FormalParameterList- // | FormalParameterList `,`- // | FormalParameterList `,` FunctionRestParameter- pub(crate) fn parse_formal_parameters(&mut self) -> ParsedParameters {- self.consume_token(TokenType::ParenOpen);- let result = self.parse_formal_parameters_impl(false);- self.consume_token(TokenType::ParenClose);- result- }-- pub(crate) fn parse_formal_parameters_impl(&mut self, is_arrow: bool) -> ParsedParameters {- let saved_formal_parameter_ctx = self.flags.in_formal_parameter_context;- self.flags.in_formal_parameter_context = true;-- // Save and clear pattern_bound_names so that nested function parsing- // (e.g. arrow functions in default values) doesn't steal binding names- // accumulated by an outer binding pattern context.- let saved_pattern_bound_names = std::mem::take(&mut self.pattern_bound_names);-- if self.match_token(TokenType::ParenClose) {- self.flags.in_formal_parameter_context = saved_formal_parameter_ctx;- self.pattern_bound_names = saved_pattern_bound_names;- return ParsedParameters {- parameters: Vec::new(),- function_length: 0,- parameter_info: Vec::new(),- is_simple: true,- };- }-- let mut parameters: Vec<FunctionParameter> = Vec::new();- let mut function_length: i32 = 0;- let mut has_seen_default = false;- let mut has_seen_rest = false;- let mut parameter_info: Vec<ParamInfo> = Vec::new();-- // C++ uses the position at the start of parse_formal_parameters for all- // parameter identifiers (i.e., the position of the first parameter).- let formal_parameters_start = self.position();-- loop {- let parameter_start = self.position();- let rest = self.eat(TokenType::TripleDot);- if rest {- has_seen_rest = true;- }-- let binding = if self.match_identifier()- || self.match_token(TokenType::Await)- || self.match_token(TokenType::Yield)- {- // Emit errors for await/yield used as parameter names in- // contexts where they are reserved.- if self.current_token_type() == TokenType::Await- && (self.program_type == ProgramType::Module- || self.flags.await_expression_is_valid- || self.flags.in_class_static_init_block)- {- self.syntax_error("'await' is not allowed as an identifier in this context");- }- if self.current_token_type() == TokenType::Yield- && (self.flags.strict_mode || self.flags.in_generator_function_context)- {- self.syntax_error("'yield' is not allowed as an identifier in this context");- }- let token = self.consume();- let value = Utf16String::from(self.token_value(&token));- // Skip validity check for arrow functions; arrow parameter- // parsing is speculative and errors would abort the parse.- // The check runs after the arrow is confirmed instead.- if !is_arrow {- self.check_identifier_name_for_assignment_validity(&value, false);- }- let name = self.token_identifier_name(&token);- let id = self- .arena- .identifiers- .insert(Identifier::new(self.range_from(formal_parameters_start), name));- parameter_info.push(ParamInfo {- name: value,- is_rest: rest,- is_from_pattern: false,- identifier: Some(id),- });- FunctionParameterBinding::Identifier(id)- } else if self.match_token(TokenType::CurlyOpen) || self.match_token(TokenType::BracketOpen) {- let pat = self.parse_binding_pattern();- let bound_names = std::mem::take(&mut self.pattern_bound_names);- for (n, id) in bound_names {- let name = self.arena.strings[n].clone();- parameter_info.push(ParamInfo {- name,- is_rest: rest,- is_from_pattern: true,- identifier: Some(id),- });- }- FunctionParameterBinding::BindingPattern(pat)- } else {- self.expected("parameter name");- self.consume();- let empty = self.arena.strings.intern(&[]);- let id = self- .arena- .identifiers- .insert(Identifier::new(self.range_from(parameter_start), empty));- FunctionParameterBinding::Identifier(id)- };-- let default_value = if !rest && self.match_token(TokenType::Equals) {- self.consume();- has_seen_default = true;- let saved_in_function = self.flags.in_function_context;- self.flags.in_function_context = true;- // https://tc39.es/ecma262/#prod-SingleNameBinding- // SingleNameBinding[Yield, Await] :- // BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]?- let expr = self.parse_assignment_expression();- self.flags.in_function_context = saved_in_function;- Some(expr)- } else {- None- };-- if !rest && !has_seen_default && default_value.is_none() {- function_length += 1;- }-- parameters.push(FunctionParameter {- binding,- default_value,- is_rest: rest,- });-- if rest || !self.match_token(TokenType::Comma) {- break;- }- self.consume();-- if self.match_token(TokenType::ParenClose) {- break;- }- }-- let is_simple = !has_seen_default- && !has_seen_rest- && !parameters- .iter()- .any(|p| matches!(&p.binding, FunctionParameterBinding::BindingPattern(_)));-- // Validate duplicates after parsing so we can use borrowed name slices- // from `parameter_info` without cloning each entry into the HashSet.- let mut seen_parameter_names: HashSet<&[u16]> = HashSet::default();- for info in ¶meter_info {- if info.name.is_empty() {- continue;- }- let is_duplicate = seen_parameter_names.contains(info.name.as_slice());- // https://tc39.es/ecma262/#sec-function-definitions-static-semantics-early-errors- // Duplicate names are tolerated only for sloppy, non-arrow functions with a fully simple parameter list.- if is_duplicate && !is_arrow && (self.flags.strict_mode || !is_simple) {- let name_str = String::from_utf16_lossy(&info.name);- self.syntax_error(&format!("Duplicate parameter '{name_str}' not allowed"));- }- seen_parameter_names.insert(info.name.as_slice());- }-- self.flags.in_formal_parameter_context = saved_formal_parameter_ctx;- self.pattern_bound_names = saved_pattern_bound_names;-- ParsedParameters {- parameters,- function_length,- parameter_info,- is_simple,- }- }-- // https://tc39.es/ecma262/#sec-destructuring-binding-patterns- // BindingPattern : ObjectBindingPattern | ArrayBindingPattern- // ObjectBindingPattern : `{` `}`- // | `{` BindingRestProperty `}`- // | `{` BindingPropertyList `}`- // | `{` BindingPropertyList `,` BindingRestProperty? `}`- // ArrayBindingPattern : `[` Elision? BindingRestElement? `]`- // | `[` BindingElementList `]`- // | `[` BindingElementList `,` Elision? BindingRestElement? `]`- pub(crate) fn parse_binding_pattern(&mut self) -> BindingPattern {- if !self.enter_recursion() {- return BindingPattern {- kind: BindingPatternKind::Object,- entries: Vec::new(),- };- }- let pattern = self.parse_binding_pattern_inner();- self.leave_recursion();- pattern- }-- fn parse_binding_pattern_inner(&mut self) -> BindingPattern {- let is_object = self.match_token(TokenType::CurlyOpen);- let is_array = self.match_token(TokenType::BracketOpen);- if !is_object && !is_array {- return BindingPattern {- kind: BindingPatternKind::Object,- entries: Vec::new(),- };- }- self.consume();-- let kind = if is_object {- BindingPatternKind::Object- } else {- BindingPatternKind::Array- };- let closing_token = if is_object {- TokenType::CurlyClose- } else {- TokenType::BracketClose- };- let mut entries: Vec<BindingEntry> = Vec::new();-- while !self.match_token(closing_token) && !self.done() {- // Array elision: bare comma.- if !is_object && self.match_token(TokenType::Comma) {- self.consume();- entries.push(BindingEntry {- name: None,- alias: None,- initializer: None,- is_rest: false,- });- continue;- }-- let is_rest = self.eat(TokenType::TripleDot);-- let mut entry_name = None;- let mut entry_alias = None;-- if is_object {- if self.allow_member_expressions && is_rest {- // Destructuring assignment: rest target can be MemberExpression or Identifier.- let expression = self.parse_expression(- PRECEDENCE_ASSIGNMENT,- Associativity::Right,- ForbiddenTokens::none().forbid(&[TokenType::Equals]),- );- if Self::is_member_expression(&expression) {- entry_alias = Some(BindingEntryAlias::MemberExpression(Box::new(expression)));- } else if Self::is_identifier(&expression) {- entry_name = Some(BindingEntryName::Identifier(expression_into_identifier(expression)));- } else {- self.syntax_error("Invalid destructuring assignment target");- break;- }- } else {- let mut needs_alias = false;- let mut entry_name_value: Option<StringId> = None;- let mut entry_is_keyword = false;-- if self.match_identifier_name()- || self.match_token(TokenType::StringLiteral)- || self.match_token(TokenType::NumericLiteral)- || self.match_token(TokenType::BigIntLiteral)- {- let entry_start = self.position();-- needs_alias = !self.match_identifier_name();-- entry_is_keyword =- self.current_token.token_type.is_identifier_name() && !self.match_identifier();-- // Property keys are name tokens, not identifier references,- // so don't run the eval/arguments check on them.- if needs_alias {- // https://tc39.es/ecma262/#sec-static-semantics-propname- let token = self.consume_property_key_token();- let value = match token.token_type {- TokenType::StringLiteral => self.parse_string_value(&token).0,- TokenType::NumericLiteral => {- js_number_to_utf16(parse_numeric_value(self.token_value(&token)))- }- TokenType::BigIntLiteral => {- let literal = String::from_utf16_lossy(self.token_value(&token));- let value = parse_bigint(literal.trim_end_matches('n'))- .expect("the lexer only produces valid BigInt literals");- Utf16String(value.to_string().encode_utf16().collect())- }- _ => unreachable!(),- };- let id = self.make_identifier_from_slice(entry_start, value.as_slice());- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- entry_name = Some(BindingEntryName::Identifier(id));- } else {- let token = self.consume_property_key_token();- let name = self.token_identifier_name(&token);- entry_name_value = Some(name);- let id = self.make_identifier(entry_start, name);- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- entry_name = Some(BindingEntryName::Identifier(id));- }- } else if self.match_token(TokenType::BracketOpen) {- self.consume();- let expression = self.parse_expression_any();- entry_name = Some(BindingEntryName::Expression(Box::new(expression)));- self.consume_token(TokenType::BracketClose);- } else {- self.expected("identifier or computed property name");- break;- }-- if !is_rest && self.match_token(TokenType::Colon) {- self.consume();- if self.allow_member_expressions {- let expression_start = self.position();- let expression = self.parse_expression(- PRECEDENCE_ASSIGNMENT,- Associativity::Right,- ForbiddenTokens::none().forbid(&[TokenType::Equals]),- );- if Self::is_parenthesized_object_or_array_expression(&expression, expression_start) {- // https://tc39.es/ecma262/#sec-destructuring-assignment-static-semantics-early-errors- // If |LeftHandSideExpression| is either an |ObjectLiteral| or an |ArrayLiteral|,- // |LeftHandSideExpression| must cover an |AssignmentPattern|.- self.syntax_error("Invalid destructuring assignment target");- break;- } else if Self::is_object_or_array_expression(&expression) {- let pattern = self.synthesize_binding_pattern(expression.range.start);- entry_alias = Some(BindingEntryAlias::BindingPattern(Box::new(pattern)));- } else if Self::is_member_expression(&expression) {- entry_alias = Some(BindingEntryAlias::MemberExpression(Box::new(expression)));- } else if Self::is_identifier(&expression) {- entry_alias =- Some(BindingEntryAlias::Identifier(expression_into_identifier(expression)));- } else {- self.syntax_error("Invalid destructuring assignment target");- break;- }- } else if self.match_token(TokenType::CurlyOpen) || self.match_token(TokenType::BracketOpen) {- let nested = self.parse_binding_pattern();- entry_alias = Some(BindingEntryAlias::BindingPattern(Box::new(nested)));- } else if self.match_identifier_name() {- let alias_start = self.position();- let token = self.consume();- let name = self.token_identifier_name(&token);- let id = self.make_identifier(alias_start, name);- self.pattern_bound_names.push((name, id));- entry_alias = Some(BindingEntryAlias::Identifier(id));- } else {- self.expected("identifier or binding pattern");- break;- }- } else if needs_alias {- self.expected("alias for string or numeric literal name");- break;- } else if let Some(name_id) = entry_name_value {- // Shorthand: name is the bound identifier.- if entry_is_keyword {- self.syntax_error("Binding pattern target may not be a reserved word");- }- if let Some(BindingEntryName::Identifier(id)) = entry_name {- self.pattern_bound_names.push((name_id, id));- }- }- }- } else if self.allow_member_expressions {- let expression_start = self.position();- let expression = self.parse_expression(- PRECEDENCE_ASSIGNMENT,- Associativity::Right,- ForbiddenTokens::none().forbid(&[TokenType::Equals]),- );- if Self::is_parenthesized_object_or_array_expression(&expression, expression_start) {- // https://tc39.es/ecma262/#sec-destructuring-assignment-static-semantics-early-errors- // If |LeftHandSideExpression| is either an |ObjectLiteral| or an |ArrayLiteral|,- // |LeftHandSideExpression| must cover an |AssignmentPattern|.- self.syntax_error("Invalid destructuring assignment target");- break;- } else if Self::is_object_or_array_expression(&expression) {- let pattern = self.synthesize_binding_pattern(expression.range.start);- entry_alias = Some(BindingEntryAlias::BindingPattern(Box::new(pattern)));- } else if Self::is_member_expression(&expression) {- entry_alias = Some(BindingEntryAlias::MemberExpression(Box::new(expression)));- } else if Self::is_identifier(&expression) {- let id = expression_into_identifier(expression);- let name = self.arena.identifiers[id].name;- self.pattern_bound_names.push((name, id));- entry_alias = Some(BindingEntryAlias::Identifier(id));- } else {- self.syntax_error("Invalid destructuring assignment target");- break;- }- } else if self.match_token(TokenType::CurlyOpen) || self.match_token(TokenType::BracketOpen) {- let nested = self.parse_binding_pattern();- entry_alias = Some(BindingEntryAlias::BindingPattern(Box::new(nested)));- } else if self.match_identifier_name() {- let alias_start = self.position();- let token = self.consume();- let name = self.token_identifier_name(&token);- let id = self.make_identifier(alias_start, name);- self.pattern_bound_names.push((name, id));- entry_alias = Some(BindingEntryAlias::Identifier(id));- } else {- self.expected("identifier or binding pattern");- break;- }-- let initializer = if self.match_token(TokenType::Equals) {- if is_rest {- self.syntax_error("Unexpected initializer after rest element");- }- self.consume();- Some(self.parse_assignment_expression())- } else {- None- };-- entries.push(BindingEntry {- name: entry_name,- alias: entry_alias,- initializer,- is_rest,- });-- if is_rest {- if self.match_token(TokenType::Comma) {- self.syntax_error("Rest element may not be followed by a comma");- self.consume();- }- break;- }-- if self.match_token(TokenType::Comma) {- self.consume();- } else if is_object && !self.match_token(closing_token) {- self.consume_token(TokenType::Comma);- }- }-- // Consume trailing commas for arrays.- if !is_object {- while self.match_token(TokenType::Comma) {- self.consume();- }- }-- self.consume_token(closing_token);- BindingPattern { kind, entries }- }-- // https://tc39.es/ecma262/#sec-imports- // ImportDeclaration : `import` ImportClause FromClause `;`- // | `import` ModuleSpecifier `;`- // ImportClause : ImportedDefaultBinding- // | NameSpaceImport- // | NamedImports- // | ImportedDefaultBinding `,` NameSpaceImport- // | ImportedDefaultBinding `,` NamedImports- pub(crate) fn parse_import_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Import);-- if self.program_type != ProgramType::Module {- self.syntax_error("Cannot use 'import' outside a module");- }-- if self.match_token(TokenType::StringLiteral) {- let module_specifier = self.consume_module_specifier();- let attributes = self.parse_with_clause();- self.consume_or_insert_semicolon();- return self.statement(- start,- StatementKind::Import(Box::new(ImportStatementData {- module_request: ModuleRequest {- module_specifier,- attributes,- },- entries: Vec::new(),- })),- );- }-- let mut entries: Vec<ImportEntry> = Vec::new();- let mut continue_parsing = true;-- if self.match_imported_binding() {- let token = self.consume();- let local_name: Utf16String = self.token_value(&token).into();- entries.push(ImportEntry {- import_name: Some(utf16!("default").into()),- local_name,- });- if self.match_token(TokenType::Comma) {- self.consume();- } else {- continue_parsing = false;- }- }-- if continue_parsing {- if self.match_token(TokenType::Asterisk) {- // NameSpaceImport: * as ImportedBinding- self.consume();- if !self.match_as() {- self.expected("'as'");- }- self.consume(); // consume 'as'- if self.match_imported_binding() {- let token = self.consume();- let namespace_name: Utf16String = self.token_value(&token).into();- entries.push(ImportEntry {- import_name: None,- local_name: namespace_name,- });- } else {- self.expected("identifier");- }- } else if self.match_token(TokenType::CurlyOpen) {- // NamedImports: { ImportSpecifier, ... }- self.consume();- while !self.done() && !self.match_token(TokenType::CurlyClose) {- if self.match_identifier_name() {- let require_as = !self.match_imported_binding();- let name_pos = self.position();- let token = self.consume();- let name = self.token_value(&token).to_vec();-- if self.match_as() {- self.consume(); // consume 'as'- let alias_token = self.consume_identifier();- let alias = self.token_value(&alias_token).to_vec();- self.check_identifier_name_for_assignment_validity(&alias, false);- entries.push(ImportEntry {- import_name: Some(name.into()),- local_name: alias.into(),- });- } else if require_as {- self.syntax_error_at_position(- &format!("Unexpected reserved word '{}'", String::from_utf16_lossy(&name)),- name_pos,- );- } else {- self.check_identifier_name_for_assignment_validity(&name, false);- let name: Utf16String = name.into();- entries.push(ImportEntry {- import_name: Some(name.clone()),- local_name: name,- });- }- } else if self.match_token(TokenType::StringLiteral) {- let token = self.consume();- let (name, _) = self.parse_string_value(&token);- if let Some(&last) = name.last()- && (0xD800..=0xDBFF).contains(&last)- {- self.syntax_error("StringValue ending with unpaired high surrogate");- }-- if !self.match_as() {- self.expected("'as'");- }- self.consume(); // consume 'as'-- let alias_token = self.consume_identifier();- let alias = self.token_value(&alias_token).to_vec();- self.check_identifier_name_for_assignment_validity(&alias, false);- entries.push(ImportEntry {- import_name: Some(name),- local_name: alias.into(),- });- } else {- self.expected("identifier");- break;- }-- if !self.match_token(TokenType::Comma) {- break;- }- self.consume();- }- self.consume_token(TokenType::CurlyClose);- } else {- self.expected("import clauses");- }- }-- if !self.match_from() {- self.expected("'from'");- }- self.consume(); // consume 'from'-- let module_specifier = self.consume_module_specifier();- let attributes = self.parse_with_clause();- self.consume_or_insert_semicolon();-- for entry in &entries {- self.scope_collector- .add_import_binding(&entry.local_name, start.line, start.column);- }-- self.statement(- start,- StatementKind::Import(Box::new(ImportStatementData {- module_request: ModuleRequest {- module_specifier,- attributes,- },- entries,- })),- )- }-- // https://tc39.es/ecma262/#sec-exports- // ExportDeclaration : `export` ExportFromClause FromClause `;`- // | `export` NamedExports `;`- // | `export` VariableStatement- // | `export` Declaration- // | `export` `default` HoistableDeclaration- // | `export` `default` ClassDeclaration- // | `export` `default` AssignmentExpression `;`- pub(crate) fn parse_export_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Export);-- if self.program_type != ProgramType::Module {- self.syntax_error("Cannot use 'export' outside a module");- }-- let mut entries: Vec<ExportEntry> = Vec::new();- let mut statement: Option<Box<Statement>> = None;- let mut is_default = false;- let mut from_specifier: Option<Utf16String> = None;-- if self.match_token(TokenType::Default) {- is_default = true;- self.consume();-- let mut local_name: Option<Utf16String> = None;-- let matches_function = self.match_function_declaration_for_export();-- if matches_function != MatchesFunctionDeclaration::No {- let has_default_name = matches_function == MatchesFunctionDeclaration::WithoutName;- let declaration = self.parse_function_declaration_for_export(has_default_name);- if !has_default_name- && let StatementKind::FunctionDeclaration(ref fd) = declaration.inner- && let Some(name_id) = fd.name- {- local_name = Some(self.arena.name_of(name_id).clone());- }- statement = Some(Box::new(declaration));- } else if self.match_token(TokenType::Class) {- let next = self.next_token();- if next.token_type != TokenType::CurlyOpen && next.token_type != TokenType::Extends {- let declaration = self.parse_class_declaration();- if let StatementKind::ClassDeclaration(ref class) = declaration.inner- && let Some(name_id) = class.name- {- local_name = Some(self.arena.name_of(name_id).clone());- }- statement = Some(Box::new(declaration));- } else {- // Unnamed class declaration - don't consume semicolon,- // matching the C++ parser's special_case_declaration_without_name.- let expression = self.parse_assignment_expression();- let expression_range = expression.range;- statement = Some(Box::new(Statement::new(- expression_range,- StatementKind::Expression(Box::new(expression)),- )));- }- } else if self.match_expression() {- // Check if this is an unnamed function/class declaration that- // should NOT consume a trailing semicolon.- let special_case_declaration_without_name = self.match_token(TokenType::Class)- || self.match_token(TokenType::Function)- || (self.match_token(TokenType::Async) && {- let next = self.next_token();- next.token_type == TokenType::Function && !next.trivia_has_line_terminator- });- let expression = self.parse_assignment_expression();- if !special_case_declaration_without_name {- self.consume_or_insert_semicolon();- }- let expression_range = expression.range;- statement = Some(Box::new(Statement::new(- expression_range,- StatementKind::Expression(Box::new(expression)),- )));- } else {- self.expected("declaration or assignment expression");- }-- if local_name.is_none() {- local_name = Some(utf16!("*default*").into());- }-- entries.push(ExportEntry {- kind: ExportEntryKind::NamedExport,- export_name: Some(utf16!("default").into()),- local_or_import_name: local_name,- });- } else {- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- enum FromSpecifier {- NotAllowed,- Optional,- Required,- }- let mut check_for_from = FromSpecifier::NotAllowed;-- if self.match_token(TokenType::Asterisk) {- self.consume();- if self.match_as() {- self.consume(); // consume 'as'- let (exported_name, _) = self.parse_module_export_name();- entries.push(ExportEntry {- kind: ExportEntryKind::ModuleRequestAll,- export_name: Some(exported_name),- local_or_import_name: None,- });- } else {- entries.push(ExportEntry {- kind: ExportEntryKind::ModuleRequestAllButDefault,- export_name: None,- local_or_import_name: None,- });- }- check_for_from = FromSpecifier::Required;- } else if self.match_declaration() {- let declaration = self.parse_declaration();- // NB: ExportDeclaration does not include UsingDeclaration or AwaitUsingDeclaration.- if matches!(declaration.inner, StatementKind::UsingDeclaration(_)) {- self.syntax_error_at_position("'using' declarations cannot be exported", declaration.range.start);- }- let names = get_declaration_export_names(&declaration, &self.arena);- for name in &names {- entries.push(ExportEntry {- kind: ExportEntryKind::NamedExport,- export_name: Some(name.clone()),- local_or_import_name: Some(name.clone()),- });- }- statement = Some(Box::new(declaration));- } else if self.match_token(TokenType::Var) {- let var_declaration = self.parse_variable_declaration(false);- let names = get_declaration_export_names(&var_declaration, &self.arena);- for name in &names {- entries.push(ExportEntry {- kind: ExportEntryKind::NamedExport,- export_name: Some(name.clone()),- local_or_import_name: Some(name.clone()),- });- }- statement = Some(Box::new(var_declaration));- } else if self.match_token(TokenType::CurlyOpen) {- self.consume();- check_for_from = FromSpecifier::Optional;-- while !self.done() && !self.match_token(TokenType::CurlyClose) {- let (identifier, was_string) = self.parse_module_export_name();- if was_string {- check_for_from = FromSpecifier::Required;- }-- if self.match_as() {- self.consume(); // consume 'as'- let (export_name, _) = self.parse_module_export_name();- entries.push(ExportEntry {- kind: ExportEntryKind::NamedExport,- export_name: Some(export_name),- local_or_import_name: Some(identifier),- });- } else {- entries.push(ExportEntry {- kind: ExportEntryKind::NamedExport,- export_name: Some(identifier.clone()),- local_or_import_name: Some(identifier),- });- }-- if !self.match_token(TokenType::Comma) {- break;- }- self.consume();- }-- if entries.is_empty() {- entries.push(ExportEntry {- kind: ExportEntryKind::EmptyNamedExport,- export_name: None,- local_or_import_name: None,- });- }-- self.consume_token(TokenType::CurlyClose);- } else {- self.syntax_error("Unexpected token 'export'");- }-- if check_for_from != FromSpecifier::NotAllowed && self.match_from() {- self.consume(); // consume 'from'- from_specifier = Some(self.consume_module_specifier());- } else if check_for_from == FromSpecifier::Required {- self.expected("'from'");- }-- if from_specifier.is_none() && check_for_from != FromSpecifier::NotAllowed {- self.consume_or_insert_semicolon();- }- }-- let module_request = if let Some(specifier) = from_specifier {- let attributes = self.parse_with_clause();- self.consume_or_insert_semicolon();- Some(ModuleRequest {- module_specifier: specifier,- attributes,- })- } else {- None- };-- // Check for duplicate exported names.- for entry in &entries {- if let Some(ref name) = entry.export_name- && !self.exported_names.insert(name.clone())- {- self.syntax_error_at_position(- &format!(- "Duplicate export with name: '{}'",- String::from_utf16_lossy(name.as_slice())- ),- start,- );- }- }-- self.statement(- start,- StatementKind::Export(Box::new(ExportStatementData {- statement,- entries,- is_default_export: is_default,- module_request,- })),- )- }-- fn match_imported_binding(&self) -> bool {- self.match_identifier() || self.match_token(TokenType::Yield) || self.match_token(TokenType::Await)- }-- fn match_as(&self) -> bool {- self.match_token(TokenType::Identifier) && self.token_original_value(&self.current_token) == utf16!("as")- }-- fn match_from(&self) -> bool {- self.match_token(TokenType::Identifier) && self.token_original_value(&self.current_token) == utf16!("from")- }-- fn consume_module_specifier(&mut self) -> Utf16String {- if !self.match_token(TokenType::StringLiteral) {- self.expected("module specifier (string)");- return utf16!("!!invalid!!").into();- }- let token = self.consume();- let (value, _) = self.parse_string_value(&token);- value- }-- fn parse_module_export_name(&mut self) -> (Utf16String, bool) {- if self.match_identifier_name() {- let token = self.consume();- (self.token_value(&token).into(), false)- } else if self.match_token(TokenType::StringLiteral) {- let token = self.consume();- let (value, _) = self.parse_string_value(&token);- // https://tc39.es/ecma262/#sec-module-semantics-static-semantics-early-errors- // It is a Syntax Error if IsStringWellFormedUnicode of the StringValue- // of StringLiteral is false.- if let Some(&last) = value.last()- && (0xD800..=0xDBFF).contains(&last)- {- self.syntax_error("StringValue ending with unpaired high surrogate");- }- (value, true)- } else {- self.expected("export specifier (string or identifier)");- (Utf16String::default(), false)- }- }-- // https://tc39.es/ecma262/#sec-imports- // WithClause : `with` `{` WithEntries `}`- // WithEntries : AttributeKey `:` StringLiteral- fn parse_with_clause(&mut self) -> Vec<ImportAttribute> {- if !self.match_token(TokenType::With) {- return Vec::new();- }- self.consume();- self.consume_token(TokenType::CurlyOpen);-- let mut attributes: Vec<ImportAttribute> = Vec::new();- while !self.done() && !self.match_token(TokenType::CurlyClose) {- let key: Utf16String = if self.match_token(TokenType::StringLiteral) {- let token = self.consume();- let (value, _) = self.parse_string_value(&token);- value- } else if self.match_identifier_name() {- let token = self.consume();- self.token_value(&token).into()- } else {- self.expected("identifier or string as attribute key");- self.consume();- continue;- };-- self.consume_token(TokenType::Colon);-- if self.match_token(TokenType::StringLiteral) {- let token = self.consume();- let (value, _) = self.parse_string_value(&token);-- // https://tc39.es/ecma262/#sec-imports-static-semantics-early-errors- // It is a Syntax Error if WithClauseToAttributes of WithClause has two different entries a and b such- // that a.[[Key]] is b.[[Key]].- if attributes.iter().any(|attribute| attribute.key == key) {- self.syntax_error("Duplicate import attribute key");- }-- attributes.push(ImportAttribute { key, value });- } else {- self.expected("string as attribute value");- self.consume();- }-- if self.match_token(TokenType::Comma) {- self.consume();- } else {- break;- }- }- self.consume_token(TokenType::CurlyClose);- attributes- }-- fn match_function_declaration_for_export(&mut self) -> MatchesFunctionDeclaration {- if self.match_token(TokenType::Function) {- let next = self.next_token();- if next.token_type == TokenType::Asterisk {- self.save_state();- self.consume(); // function- self.consume(); // *- let result = if self.match_token(TokenType::ParenOpen) {- MatchesFunctionDeclaration::WithoutName- } else {- MatchesFunctionDeclaration::Yes- };- self.load_state();- return result;- }- return if next.token_type == TokenType::ParenOpen {- MatchesFunctionDeclaration::WithoutName- } else {- MatchesFunctionDeclaration::Yes- };- }-- if self.match_token(TokenType::Async) {- let next = self.next_token();- if next.token_type != TokenType::Function || next.trivia_has_line_terminator {- return MatchesFunctionDeclaration::No;- }- self.save_state();- self.consume(); // async- self.consume(); // function- if self.match_token(TokenType::Asterisk) {- self.consume(); // *- }- let result = if self.match_token(TokenType::ParenOpen) {- MatchesFunctionDeclaration::WithoutName- } else {- MatchesFunctionDeclaration::Yes- };- self.load_state();- return result;- }-- MatchesFunctionDeclaration::No- }-- fn parse_function_declaration_for_export(&mut self, has_default_name: bool) -> Statement {- if has_default_name {- self.has_default_export_name = true;- let result = self.parse_function_declaration();- self.has_default_export_name = false;- result- } else {- self.parse_function_declaration()- }- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum MatchesFunctionDeclaration {- No,- Yes,- WithoutName,-}diff --git a/Libraries/LibJS/Rust/src/parser/expressions.rs b/Libraries/LibJS/Rust/src/parser/expressions.rsdeleted file mode 100644index bba21e0bb22..00000000000--- a/Libraries/LibJS/Rust/src/parser/expressions.rs+++ /dev/null@@ -1,2775 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Expression parsing: primary, secondary (binary/postfix), unary, and-//! precedence climbing.--use crate::ast::*;-use crate::lexer::ch;-use crate::parser::Associativity;-use crate::parser::ForbiddenTokens;-use crate::parser::FunctionKind;-use crate::parser::MethodKind;-use crate::parser::PRECEDENCE_ASSIGNMENT;-use crate::parser::PRECEDENCE_COMMA;-use crate::parser::PRECEDENCE_MEMBER;-use crate::parser::PRECEDENCE_UNARY;-use crate::parser::ParamInfo;-use crate::parser::ParsedParameters;-use crate::parser::Parser;-use crate::parser::Position;-use crate::parser::PropertyKey;-use crate::parser::is_strict_reserved_word;-use crate::token::Token;-use crate::token::TokenType;--#[derive(PartialEq, Eq)]-enum EscapeMode {- /// Tagged template literals: invalid escapes produce `undefined` cooked value.- TaggedTemplate,- /// String literals: invalid escapes emit syntax errors, legacy octals are tracked.- StringLiteral,-}--impl Parser<'_> {- pub(crate) fn match_expression(&mut self) -> bool {- match self.current_token_type() {- TokenType::BoolLiteral- | TokenType::NumericLiteral- | TokenType::BigIntLiteral- | TokenType::StringLiteral- | TokenType::NullLiteral- | TokenType::RegexLiteral- | TokenType::TemplateLiteralStart- | TokenType::This- | TokenType::Super- | TokenType::New- | TokenType::Class- | TokenType::Function- | TokenType::ParenOpen- | TokenType::CurlyOpen- | TokenType::BracketOpen- | TokenType::PrivateIdentifier- | TokenType::Slash- | TokenType::SlashEquals => true,-- TokenType::Async => true,- TokenType::Yield => true,- TokenType::Await => true,-- // https://tc39.es/ecma262/#sec-import-calls- // https://tc39.es/ecma262/#sec-import-meta- // `import` is only a valid expression start if followed by `(` or `.`.- TokenType::Import => {- let next = self.next_token();- next.token_type == TokenType::ParenOpen || next.token_type == TokenType::Period- }-- _ => {- if self.match_identifier() {- return true;- }- self.match_unary_prefixed_expression()- }- }- }-- pub(crate) fn match_unary_prefixed_expression(&self) -> bool {- matches!(- self.current_token_type(),- TokenType::PlusPlus- | TokenType::MinusMinus- | TokenType::ExclamationMark- | TokenType::Tilde- | TokenType::Plus- | TokenType::Minus- | TokenType::Typeof- | TokenType::Void- | TokenType::Delete- ) || (self.flags.await_expression_is_valid && self.current_token_type() == TokenType::Await)- }-- pub(crate) fn match_secondary_expression(&self, forbidden: &ForbiddenTokens) -> bool {- let tt = self.current_token_type();- if !forbidden.allows(tt) {- return false;- }- match tt {- TokenType::Period | TokenType::BracketOpen | TokenType::ParenOpen | TokenType::QuestionMarkPeriod => true,- TokenType::PlusPlus | TokenType::MinusMinus => !self.current_token.trivia_has_line_terminator,- TokenType::DoubleAsterisk- | TokenType::Asterisk- | TokenType::Slash- | TokenType::Percent- | TokenType::Plus- | TokenType::Minus- | TokenType::ShiftLeft- | TokenType::ShiftRight- | TokenType::UnsignedShiftRight- | TokenType::LessThan- | TokenType::LessThanEquals- | TokenType::GreaterThan- | TokenType::GreaterThanEquals- | TokenType::In- | TokenType::Instanceof- | TokenType::EqualsEquals- | TokenType::ExclamationMarkEquals- | TokenType::EqualsEqualsEquals- | TokenType::ExclamationMarkEqualsEquals- | TokenType::Ampersand- | TokenType::Caret- | TokenType::Pipe- | TokenType::DoubleQuestionMark- | TokenType::DoubleAmpersand- | TokenType::DoublePipe => true,- TokenType::QuestionMark => true,- TokenType::Equals- | TokenType::PlusEquals- | TokenType::MinusEquals- | TokenType::DoubleAsteriskEquals- | TokenType::AsteriskEquals- | TokenType::SlashEquals- | TokenType::PercentEquals- | TokenType::ShiftLeftEquals- | TokenType::ShiftRightEquals- | TokenType::UnsignedShiftRightEquals- | TokenType::AmpersandEquals- | TokenType::CaretEquals- | TokenType::PipeEquals- | TokenType::DoubleAmpersandEquals- | TokenType::DoublePipeEquals- | TokenType::DoubleQuestionMarkEquals => true,- _ => false,- }- }-- pub(crate) fn parse_expression_any(&mut self) -> Expression {- self.parse_expression(PRECEDENCE_COMMA, Associativity::Right, ForbiddenTokens::none())- }-- pub(crate) fn parse_assignment_expression(&mut self) -> Expression {- self.parse_expression(PRECEDENCE_ASSIGNMENT, Associativity::Right, ForbiddenTokens::none())- }-- pub(crate) fn parse_expression(- &mut self,- min_precedence: i32,- associativity: Associativity,- forbidden: ForbiddenTokens,- ) -> Expression {- if !self.enter_recursion() {- let start = self.position();- return self.expression(start, ExpressionKind::Error);- }- let expression = self.parse_expression_inner(min_precedence, associativity, forbidden);- self.leave_recursion();- expression- }-- fn parse_expression_inner(- &mut self,- min_precedence: i32,- associativity: Associativity,- forbidden: ForbiddenTokens,- ) -> Expression {- if self.match_unary_prefixed_expression() {- let start = self.position();- let expression = self.parse_unary_prefixed_expression();-- // https://tc39.es/ecma262/#sec-exp-operator- // ExponentiationExpression :- // UnaryExpression- // UpdateExpression `**` ExponentiationExpression- // NB: UnaryExpression cannot be the base of `**`, only UpdateExpression can.- // This prevents ambiguity like `-x ** y` (is it `(-x) ** y` or `-(x ** y)`?).- // ++x ** y and --x ** y are valid (they're UpdateExpressions, not UnaryExpressions).- if self.match_token(TokenType::DoubleAsterisk) && !Self::is_update_expression(&expression) {- self.syntax_error("Unparenthesized unary expression can't appear on the left-hand side of '**'");- }-- return self.continue_parse_expression(start, expression, min_precedence, associativity, forbidden);- }-- let lhs_start = self.position();- self.last_primary_was_parenthesized = false;- let (expression, should_continue) = self.parse_primary_expression(min_precedence, forbidden);-- // C++ checks for freestanding `arguments` references here (after- // parse_primary_expression), NOT during consume(). This avoids- // falsely flagging parameter names like `function f(arguments)`.- if let ExpressionKind::Identifier(id) = expression.inner- && self.arena.name_of(id).as_slice() == utf16!("arguments")- {- // https://tc39.es/ecma262/#sec-class-static-initialization-blocks- // It is a Syntax Error if ContainsArguments of ClassStaticBlockBody is true.- if self.flags.in_class_static_init_block {- self.syntax_error("'arguments' is not allowed in class static initialization blocks");- } else {- let name = self.arena.name_of(id).clone();- if !self.flags.strict_mode && !self.scope_collector.has_declaration_in_current_function(&name) {- self.scope_collector- .set_contains_access_to_arguments_object_in_non_strict_mode();- }- }- }-- if !should_continue {- // Yield/Await expressions don't participate in secondary expression- // parsing (e.g. member access), but they DO participate in comma- // expressions (e.g. `yield 1, yield 2`). Check for comma here.- let expression = self.parse_comma_expression(lhs_start, expression, min_precedence, forbidden);- self.report_invalid_private_identifier_usage(&expression);- return expression;- }-- let expression = self.parse_tagged_template_literals(lhs_start, expression);-- self.continue_parse_expression(lhs_start, expression, min_precedence, associativity, forbidden)- }-- fn continue_parse_expression(- &mut self,- lhs_start: Position,- mut expression: Expression,- min_precedence: i32,- associativity: Associativity,- mut forbidden: ForbiddenTokens,- ) -> Expression {- let original_forbidden = forbidden;- let mut lhs_is_parenthesized = self.last_primary_was_parenthesized;- self.last_primary_was_parenthesized = false;- while !self.recursion_limit_reached && self.match_secondary_expression(&forbidden) {- let new_precedence = Self::operator_precedence(self.current_token_type());- if new_precedence < min_precedence {- break;- }- if new_precedence == min_precedence && associativity == Associativity::Left {- break;- }-- let result = self.parse_secondary_expression(- lhs_start,- expression,- new_precedence,- original_forbidden,- lhs_is_parenthesized,- );- lhs_is_parenthesized = false;- expression = result.0;- forbidden = forbidden.merge(result.1);-- // Tagged template literals bind tighter than any operator, so we- // consume them eagerly after each secondary expression — but NOT- // after update expressions (x++`template` is not valid).- if !Self::is_update_expression(&expression) {- expression = self.parse_tagged_template_literals(lhs_start, expression);- }- }-- let expression = self.parse_comma_expression(lhs_start, expression, min_precedence, forbidden);- self.report_invalid_private_identifier_usage(&expression);- expression- }-- fn parse_comma_expression(- &mut self,- start: Position,- expression: Expression,- min_precedence: i32,- forbidden: ForbiddenTokens,- ) -> Expression {- if min_precedence <= 1 && self.match_token(TokenType::Comma) && forbidden.allows(TokenType::Comma) {- self.report_invalid_private_identifier_usage(&expression);- let mut expressions = vec![expression];- while self.match_token(TokenType::Comma) {- self.consume();- let expression = self.parse_assignment_expression();- self.report_invalid_private_identifier_usage(&expression);- expressions.push(expression);- }- return self.expression(start, ExpressionKind::Sequence(Box::new(expressions)));- }- expression- }-- fn report_invalid_private_identifier_usage(&mut self, expression: &Expression) {- if matches!(expression.inner, ExpressionKind::PrivateIdentifier(_)) {- self.syntax_error("Private identifier must be followed by 'in'");- }- }-- /// Parse a primary expression (literal, identifier, `this`, etc.).- /// Returns `(expression, should_continue)` — `false` means the caller- /// should not attempt to parse a secondary expression (e.g. arrow).- fn parse_primary_expression(&mut self, min_precedence: i32, forbidden: ForbiddenTokens) -> (Expression, bool) {- let start = self.position();- let token = self.current_token().clone();-- match token.token_type {- TokenType::ParenOpen => {- let paren_start = self.position();- self.consume_token(TokenType::ParenOpen);- if let Some(arrow) = self.try_parse_arrow_function_expression(true, false, Some(paren_start), forbidden)- {- return (arrow, false);- }- if self.match_token(TokenType::ParenClose) {- self.syntax_error("Unexpected token )");- self.consume();- return (self.expression(start, ExpressionKind::Error), true);- }- let mut expression = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);- if let ExpressionKind::New(ref mut new_expression) = expression.inner {- // Mirrors C++ Parser: `(new Foo)` sets "inside grouping parens".- new_expression.is_inside_parens = true;- }- self.last_primary_was_parenthesized = true;- (expression, true)- }-- TokenType::This => {- self.consume();- self.scope_collector.set_uses_this();- (self.expression(start, ExpressionKind::This), true)- }-- TokenType::Class => {- let expression = self.parse_class_expression(false);- (expression, true)- }-- // https://tc39.es/ecma262/#sec-super-keyword- // SuperProperty : `super` `.` IdentifierName- // | `super` `[` Expression `]`- // SuperCall : `super` Arguments- // NB: `super` must be followed by `.`, `[`, or `(`; bare `super` is invalid.- TokenType::Super => {- self.consume();- // C++ creates SuperCall in parse_call_expression which does- // push_start() after `super` is consumed, so position is at `(`.- let after_super = self.position();- if self.scope_collector.has_current_scope() {- self.scope_collector.set_uses_new_target();- }- if self.match_token(TokenType::ParenOpen) {- if !self.flags.allow_super_constructor_call {- self.syntax_error("'super' keyword unexpected here");- }- let arguments = self.parse_arguments();- (- self.expression(- after_super,- ExpressionKind::SuperCall(Box::new(SuperCallData {- arguments,- is_synthetic: false,- })),- ),- true,- )- } else if self.match_token(TokenType::Period) || self.match_token(TokenType::BracketOpen) {- if !self.flags.allow_super_property_lookup {- self.syntax_error("'super' keyword unexpected here");- }- (self.expression(start, ExpressionKind::Super), true)- } else {- self.syntax_error("'super' keyword unexpected here");- (self.expression(start, ExpressionKind::Super), true)- }- }-- TokenType::NumericLiteral => {- let token = self.consume_and_validate_numeric_literal();- let value_str = self.token_value(&token);- let value = parse_numeric_value(value_str);- (self.expression(start, ExpressionKind::NumericLiteral(value)), true)- }-- TokenType::BigIntLiteral => {- let token = self.consume();- let value = self.token_value(&token);- // Store the raw value including the 'n' suffix, matching C++.- let value = Utf16String(value.to_vec());- (- self.expression(start, ExpressionKind::BigIntLiteral(Box::new(value))),- true,- )- }-- TokenType::BoolLiteral => {- let token = self.consume();- let value = self.token_value(&token);- let is_true = value == utf16!("true");- (self.expression(start, ExpressionKind::BooleanLiteral(is_true)), true)- }-- TokenType::StringLiteral => {- let token = self.consume();- // C++ calls consume() before push_start() for StringLiteral,- // so its position is the token AFTER the string.- let after_string = self.position();- let (value, has_octal) = self.parse_string_value(&token);- if has_octal {- if self.flags.strict_mode {- self.syntax_error("Octal escape sequence in string literal not allowed in strict mode");- } else {- self.flags.string_legacy_octal_escape_sequence_in_scope = true;- }- }- (- self.expression(after_string, ExpressionKind::StringLiteral(Box::new(value))),- true,- )- }-- TokenType::NullLiteral => {- self.consume();- (self.expression(start, ExpressionKind::NullLiteral), true)- }-- TokenType::CurlyOpen => {- let expression = self.parse_object_expression();- (expression, true)- }-- TokenType::BracketOpen => {- let expression = self.parse_array_expression();- (expression, true)- }-- TokenType::Function => {- let expression = self.parse_function_expression();- (expression, true)- }-- // https://tc39.es/ecma262/#sec-async-function-definitions- // `async` [no LineTerminator here] `function` starts an async function expression.- // `async` [no LineTerminator here] ArrowParameters `=>` starts an async arrow.- // Otherwise, `async` is just an identifier reference.- TokenType::Async => {- let next = self.next_token();- if next.token_type == TokenType::Function && !next.trivia_has_line_terminator {- let expression = self.parse_function_expression();- return (expression, true);- }- if let Some(arrow) = self.try_parse_arrow_function_expression(- next.token_type == TokenType::ParenOpen,- true,- None,- forbidden,- ) {- return (arrow, false);- }- self.arrow_function_failed_positions.remove(&(start.offset as usize));- // `async => ...` is a regular arrow function with parameter name `async`- // (not an async arrow function).- if let Some(arrow) = self.try_parse_arrow_function_expression(false, false, None, forbidden) {- return (arrow, false);- }- let token = self.consume_and_check_identifier();- let name = self.token_identifier_name(&token);- let id = self.make_identifier(start, name);- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- (self.expression(start, ExpressionKind::Identifier(id)), true)- }-- TokenType::TemplateLiteralStart => {- let expression = self.parse_template_literal(false);- (expression, true)- }-- TokenType::New => {- let expression = self.parse_new_expression();- (expression, true)- }-- // https://tc39.es/ecma262/#sec-import-calls- // ImportCall : `import` `(` AssignmentExpression `,`? `)- // | `import` `(` AssignmentExpression `,` AssignmentExpression `,`? `)`- // https://tc39.es/ecma262/#sec-import-meta- // `import.meta` is only valid in module code.- TokenType::Import => {- self.consume();- if self.match_token(TokenType::Period) {- self.consume();- let meta_token = self.current_token.clone();- self.consume_token(TokenType::Identifier);- let meta_utf16: [u16; 4] = [ch(b'm'), ch(b'e'), ch(b't'), ch(b'a')];- if self.token_original_value(&meta_token) != meta_utf16 {- self.syntax_error("Expected 'meta' after 'import.'");- }- if self.program_type != ProgramType::Module {- self.syntax_error("import.meta is only allowed in modules");- }- (- self.expression(start, ExpressionKind::MetaProperty(MetaPropertyType::ImportMeta)),- true,- )- } else if self.match_token(TokenType::ParenOpen) {- self.consume();- let specifier = self.parse_assignment_expression();- let options = if self.match_token(TokenType::Comma) {- self.consume();- if self.match_token(TokenType::ParenClose) {- None- } else {- let opts = self.parse_assignment_expression();- if self.match_token(TokenType::Comma) {- self.consume();- }- Some(Box::new(opts))- }- } else {- None- };- self.consume_token(TokenType::ParenClose);- (- self.expression(- start,- ExpressionKind::ImportCall(Box::new(ImportCallData {- specifier: Box::new(specifier),- options,- })),- ),- true,- )- } else {- self.expected("'.' or '('");- (self.expression(start, ExpressionKind::Error), true)- }- }-- // https://tc39.es/ecma262/#sec-generator-function-definitions- // YieldExpression : `yield`- // | `yield` [no LineTerminator here] AssignmentExpression- // | `yield` [no LineTerminator here] `*` AssignmentExpression- // YieldExpression is at AssignmentExpression level (precedence 3).- // When min_precedence is higher (e.g. void/typeof at 17), yield must- // be treated as an identifier, not a yield expression.- TokenType::Yield if self.flags.in_generator_function_context && min_precedence <= 3 => {- let expression = self.parse_yield_expression(forbidden);- (expression, false)- }-- TokenType::PrivateIdentifier => {- let id = self.parse_private_identifier(start);- (- self.expression(start, ExpressionKind::PrivateIdentifier(Box::new(id))),- true,- )- }-- TokenType::RegexLiteral => {- let token = self.consume();- (self.parse_regex_literal(start, &token), true)- }-- TokenType::Slash | TokenType::SlashEquals => {- let token = self.lexer.force_slash_as_regex();- self.current_token = token;- let token = self.consume();- (self.parse_regex_literal(start, &token), true)- }-- _ => {- // NB: When Await/Yield guards above don't match, those tokens fall- // through here. match_identifier() may return false for Await in- // class static init blocks, but we still need to try arrow function- // parsing and identifier consumption (with appropriate errors).- // This matches C++'s "goto read_as_identifier" pattern.- if self.match_identifier() || self.match_token(TokenType::Await) || self.match_token(TokenType::Yield) {- if let Some(arrow) = self.try_parse_arrow_function_expression(false, false, None, forbidden) {- return (arrow, false);- }- if self.match_token(TokenType::Await)- && (self.program_type == ProgramType::Module- || self.flags.await_expression_is_valid- || self.flags.in_class_static_init_block)- {- self.syntax_error("'await' is not allowed as an identifier in this context");- }- if self.match_token(TokenType::Yield)- && (self.flags.strict_mode || self.flags.in_generator_function_context)- {- self.syntax_error("'yield' is not allowed as an identifier in this context");- }- let token = self.consume_and_check_identifier();- let name = self.token_identifier_name(&token);- let id = self.make_identifier(start, name);- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- (self.expression(start, ExpressionKind::Identifier(id)), true)- } else if self.match_token(TokenType::EscapedKeyword) {- self.syntax_error("Keyword must not contain escaped characters");- let token = self.consume_and_check_identifier();- let name = self.token_identifier_name(&token);- let id = self.make_identifier(start, name);- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- (self.expression(start, ExpressionKind::Identifier(id)), true)- } else {- self.expected("primary expression");- self.consume();- (self.expression(start, ExpressionKind::Error), true)- }- }- }- }-- fn parse_regex_literal(&mut self, start: Position, token: &Token) -> Expression {- let value = self.token_value(token);- let pattern = if value.len() >= 2 {- value[1..value.len() - 1].to_vec()- } else {- value.to_vec()- };- let flags = if self.match_token(TokenType::RegexFlags) {- let ftok = self.consume();- self.token_value(&ftok).to_vec()- } else {- Vec::new()- };- self.validate_regex_flags(&flags);- if let Err(msg) = crate::host::validate_regex(&pattern, &flags) {- self.syntax_error_at_position(&String::from_utf16_lossy(&msg), start);- }- self.expression(- start,- ExpressionKind::RegExpLiteral(Box::new(RegExpLiteralData {- pattern: pattern.into(),- flags: flags.into(),- })),- )- }-- fn parse_secondary_expression(- &mut self,- _lhs_start: Position,- lhs: Expression,- min_precedence: i32,- forbidden: ForbiddenTokens,- lhs_is_parenthesized: bool,- ) -> (Expression, ForbiddenTokens) {- let start = self.position();- let tt = self.current_token_type();-- if matches!(lhs.inner, ExpressionKind::PrivateIdentifier(_)) && tt != TokenType::In {- self.syntax_error("Private identifier must be followed by 'in'");- }-- match tt {- // === Binary operators ===- TokenType::Plus- | TokenType::Minus- | TokenType::Asterisk- | TokenType::Slash- | TokenType::Percent- | TokenType::DoubleAsterisk- | TokenType::ShiftLeft- | TokenType::ShiftRight- | TokenType::UnsignedShiftRight- | TokenType::Ampersand- | TokenType::Caret- | TokenType::Pipe- | TokenType::LessThan- | TokenType::LessThanEquals- | TokenType::GreaterThan- | TokenType::GreaterThanEquals- | TokenType::EqualsEquals- | TokenType::ExclamationMarkEquals- | TokenType::EqualsEqualsEquals- | TokenType::ExclamationMarkEqualsEquals- | TokenType::Instanceof => {- let op = token_to_binary_op(tt);- self.consume();- let rhs = self.parse_expression(min_precedence, Self::operator_associativity(tt), forbidden);- (- self.expression(- start,- ExpressionKind::Binary(Box::new(BinaryExprData {- op,- lhs: Box::new(lhs),- rhs: Box::new(rhs),- })),- ),- ForbiddenTokens::none(),- )- }-- TokenType::In => {- let is_private_in = matches!(&lhs.inner, ExpressionKind::PrivateIdentifier(_));- self.consume();- let rhs = self.parse_expression(min_precedence, Self::operator_associativity(tt), forbidden);- if is_private_in- && let ExpressionKind::Function(fn_id) = &rhs.inner- && self.function_table.get(*fn_id).is_arrow_function- {- self.syntax_error(- "Arrow function is not allowed as the right-hand side of a private 'in' expression",- );- }-- (- self.expression(- start,- ExpressionKind::Binary(Box::new(BinaryExprData {- op: BinaryOp::In,- lhs: Box::new(lhs),- rhs: Box::new(rhs),- })),- ),- ForbiddenTokens::none(),- )- }-- // === Logical operators ===- // https://tc39.es/ecma262/#sec-binary-logical-operators- // It is a Syntax Error if ShortCircuitExpression includes both- // LogicalORExpression (||/&&) and CoalesceExpression (??), since- // their precedence is ambiguous without explicit parentheses.- TokenType::DoubleAmpersand => {- self.consume();- let new_forbidden = forbidden.forbid(&[TokenType::DoubleQuestionMark]);- let rhs = self.parse_expression(min_precedence, Associativity::Left, new_forbidden);- (- self.expression(- start,- ExpressionKind::Logical(Box::new(LogicalExprData {- op: LogicalOp::And,- lhs: Box::new(lhs),- rhs: Box::new(rhs),- })),- ),- new_forbidden,- )- }- TokenType::DoublePipe => {- self.consume();- let new_forbidden = forbidden.forbid(&[TokenType::DoubleQuestionMark]);- let rhs = self.parse_expression(min_precedence, Associativity::Left, new_forbidden);- (- self.expression(- start,- ExpressionKind::Logical(Box::new(LogicalExprData {- op: LogicalOp::Or,- lhs: Box::new(lhs),- rhs: Box::new(rhs),- })),- ),- new_forbidden,- )- }- TokenType::DoubleQuestionMark => {- self.consume();- let new_forbidden = forbidden.forbid(&[TokenType::DoubleAmpersand, TokenType::DoublePipe]);- let rhs = self.parse_expression(min_precedence, Associativity::Left, new_forbidden);- (- self.expression(- start,- ExpressionKind::Logical(Box::new(LogicalExprData {- op: LogicalOp::NullishCoalescing,- lhs: Box::new(lhs),- rhs: Box::new(rhs),- })),- ),- new_forbidden,- )- }-- // === Assignment ===- TokenType::Equals- | TokenType::PlusEquals- | TokenType::MinusEquals- | TokenType::DoubleAsteriskEquals- | TokenType::AsteriskEquals- | TokenType::SlashEquals- | TokenType::PercentEquals- | TokenType::ShiftLeftEquals- | TokenType::ShiftRightEquals- | TokenType::UnsignedShiftRightEquals- | TokenType::AmpersandEquals- | TokenType::CaretEquals- | TokenType::PipeEquals- | TokenType::DoubleAmpersandEquals- | TokenType::DoublePipeEquals- | TokenType::DoubleQuestionMarkEquals => {- let op = token_to_assignment_op(tt);- if op == AssignmentOp::Assignment- && !lhs_is_parenthesized- && (Self::is_object_expression(&lhs) || Self::is_array_expression(&lhs))- {- // Save pattern_bound_names so that an outer binding- // pattern parse in progress doesn't lose its entries.- let saved_bound_names = std::mem::take(&mut self.pattern_bound_names);- // Use the expression's own range start, not the outer- // lhs_start. When the expression is parenthesized (e.g.- // `([a,b]) = ...`), lhs_start points to `(` but we need- // to re-lex from `[` to correctly synthesize the pattern.-- let binding_pattern = self.synthesize_binding_pattern(lhs.range.start);-- // Register synthesized identifiers with the scope collector so- // they get resolved as locals during analyze().- let bound_names = std::mem::take(&mut self.pattern_bound_names);- for (name, _id) in &bound_names {- let name_str = self.arena.strings[*name].clone();- self.check_identifier_name_for_assignment_validity(name_str.as_slice(), false);- }- let Self {- scope_collector, arena, ..- } = self;- for (_name, id) in &bound_names {- scope_collector.register_identifier(- *id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- self.pattern_bound_names = saved_bound_names;- self.consume();- let rhs = self.parse_expression(min_precedence, Associativity::Right, forbidden);- return (- self.expression(- start,- ExpressionKind::Assignment(Box::new(AssignmentExprData {- op,- lhs: AssignmentLhs::Pattern(binding_pattern),- rhs: Box::new(rhs),- lhs_is_parenthesized,- })),- ),- ForbiddenTokens::none(),- );- }- let allow_call = !matches!(- tt,- TokenType::DoubleAmpersandEquals- | TokenType::DoublePipeEquals- | TokenType::DoubleQuestionMarkEquals- );- if !Self::is_simple_assignment_target(&lhs, allow_call, self.flags.strict_mode) {- self.syntax_error("Invalid left-hand side in assignment");- }- if let ExpressionKind::Identifier(id) = lhs.inner {- let name = self.arena.name_of(id).clone();- self.check_identifier_name_for_assignment_validity(&name, false);- }- self.consume();- let rhs = self.parse_expression(min_precedence, Associativity::Right, forbidden);- (- self.expression(- start,- ExpressionKind::Assignment(Box::new(AssignmentExprData {- op,- lhs: AssignmentLhs::Expression(Box::new(lhs)),- rhs: Box::new(rhs),- lhs_is_parenthesized,- })),- ),- ForbiddenTokens::none(),- )- }-- // === Ternary ===- TokenType::QuestionMark => {- self.consume();- let consequent = self.parse_assignment_expression();- self.consume_token(TokenType::Colon);- let alternate = self.parse_expression(PRECEDENCE_ASSIGNMENT, Associativity::Right, forbidden);- (- self.expression(- start,- ExpressionKind::Conditional(Box::new(ConditionalExprData {- test: Box::new(lhs),- consequent: Box::new(consequent),- alternate: Box::new(alternate),- })),- ),- ForbiddenTokens::none(),- )- }-- // === Member access ===- TokenType::Period => {- self.consume();- if self.match_token(TokenType::PrivateIdentifier) {- // https://tc39.es/ecma262/#sec-static-semantics-early-errors- // It is a Syntax Error if MemberExpression is SuperProperty- // and the PrivateIdentifier is present.- if matches!(lhs.inner, ExpressionKind::Super) {- self.syntax_error("Cannot access private field or method via 'super'");- }- let property_start = self.position();- let id = self.parse_private_identifier(property_start);- let property = self.expression(property_start, ExpressionKind::PrivateIdentifier(Box::new(id)));- (- self.expression(- start,- ExpressionKind::Member(Box::new(MemberExprData {- object: Box::new(lhs),- property: Box::new(property),- computed: false,- })),- ),- ForbiddenTokens::none(),- )- } else if self.match_identifier_name() {- let property_start = self.position();- let token = self.consume();- let property_name = self.token_identifier_name(&token);- let property_identifier = self.make_identifier(property_start, property_name);- let property = self.expression(property_start, ExpressionKind::Identifier(property_identifier));- (- self.expression(- start,- ExpressionKind::Member(Box::new(MemberExprData {- object: Box::new(lhs),- property: Box::new(property),- computed: false,- })),- ),- ForbiddenTokens::none(),- )- } else {- self.expected("property name");- (lhs, ForbiddenTokens::none())- }- }-- // === Computed member access ===- TokenType::BracketOpen => {- self.consume();- let property = self.parse_expression_any();- self.consume_token(TokenType::BracketClose);- (- self.expression(- start,- ExpressionKind::Member(Box::new(MemberExprData {- object: Box::new(lhs),- property: Box::new(property),- computed: true,- })),- ),- ForbiddenTokens::none(),- )- }-- // === Call ===- TokenType::ParenOpen => {- let expression = self.parse_call_expression(lhs);- (expression, ForbiddenTokens::none())- }-- // === Optional chaining ===- TokenType::QuestionMarkPeriod => {- // https://tc39.es/ecma262/#prod-OptionalExpression- // Optional chaining directly on an unparenthesized `new` expression is invalid:- // `new Foo?.bar` // SyntaxError- // while parenthesized/new-call forms remain valid:- // `(new Foo)?.bar`- // `new Foo()?.bar`- if let ExpressionKind::New(ref new_expression) = lhs.inner- && !new_expression.is_parenthesized- && !new_expression.is_inside_parens- {- self.syntax_error("'new' cannot be used with optional chaining");- self.consume();- return (lhs, ForbiddenTokens::none());- }- let chain = self.parse_optional_chain(start, lhs);- (chain, ForbiddenTokens::none())- }-- // === Postfix ===- // https://tc39.es/ecma262/#sec-update-expressions- // UpdateExpression : LeftHandSideExpression [no LineTerminator here] `++`- // | LeftHandSideExpression [no LineTerminator here] `--`- // NB: The [no LineTerminator here] is enforced by match_secondary_expression- // which checks trivia_has_line_terminator for PlusPlus/MinusMinus.- TokenType::PlusPlus => {- if !Self::is_simple_assignment_target(&lhs, true, self.flags.strict_mode) {- self.syntax_error("Invalid left-hand side in postfix operation");- }- if let ExpressionKind::Identifier(id) = lhs.inner {- let name = self.arena.name_of(id).clone();- self.check_identifier_name_for_assignment_validity(&name, false);- }- self.consume();- (- self.expression(- start,- ExpressionKind::Update(Box::new(UpdateExprData {- op: UpdateOp::Increment,- argument: Box::new(lhs),- prefixed: false,- })),- ),- ForbiddenTokens::none(),- )- }- TokenType::MinusMinus => {- if !Self::is_simple_assignment_target(&lhs, true, self.flags.strict_mode) {- self.syntax_error("Invalid left-hand side in postfix operation");- }- if let ExpressionKind::Identifier(id) = lhs.inner {- let name = self.arena.name_of(id).clone();- self.check_identifier_name_for_assignment_validity(&name, false);- }- self.consume();- (- self.expression(- start,- ExpressionKind::Update(Box::new(UpdateExprData {- op: UpdateOp::Decrement,- argument: Box::new(lhs),- prefixed: false,- })),- ),- ForbiddenTokens::none(),- )- }-- _ => {- self.expected("secondary expression");- (lhs, ForbiddenTokens::none())- }- }- }-- fn parse_unary_prefixed_expression(&mut self) -> Expression {- let start = self.position();- let tt = self.current_token_type();-- match tt {- TokenType::Await if self.flags.await_expression_is_valid => self.parse_await_expression(),- TokenType::PlusPlus => {- self.consume();- let expression = self.parse_expression(PRECEDENCE_UNARY, Associativity::Right, ForbiddenTokens::none());- if !Self::is_simple_assignment_target(&expression, true, self.flags.strict_mode) {- self.syntax_error("Invalid left-hand side in prefix operation");- }- if let ExpressionKind::Identifier(id) = expression.inner {- let name = self.arena.name_of(id).clone();- self.check_identifier_name_for_assignment_validity(&name, false);- }- self.expression(- start,- ExpressionKind::Update(Box::new(UpdateExprData {- op: UpdateOp::Increment,- argument: Box::new(expression),- prefixed: true,- })),- )- }- TokenType::MinusMinus => {- self.consume();- let expression = self.parse_expression(PRECEDENCE_UNARY, Associativity::Right, ForbiddenTokens::none());- if !Self::is_simple_assignment_target(&expression, true, self.flags.strict_mode) {- self.syntax_error("Invalid left-hand side in prefix operation");- }- if let ExpressionKind::Identifier(id) = expression.inner {- let name = self.arena.name_of(id).clone();- self.check_identifier_name_for_assignment_validity(&name, false);- }- self.expression(- start,- ExpressionKind::Update(Box::new(UpdateExprData {- op: UpdateOp::Decrement,- argument: Box::new(expression),- prefixed: true,- })),- )- }- TokenType::ExclamationMark- | TokenType::Tilde- | TokenType::Plus- | TokenType::Minus- | TokenType::Typeof- | TokenType::Void => {- let op = match tt {- TokenType::ExclamationMark => UnaryOp::Not,- TokenType::Tilde => UnaryOp::BitwiseNot,- TokenType::Plus => UnaryOp::Plus,- TokenType::Minus => UnaryOp::Minus,- TokenType::Typeof => UnaryOp::Typeof,- _ => UnaryOp::Void,- };- self.consume();- let expression = self.parse_expression(PRECEDENCE_UNARY, Associativity::Right, ForbiddenTokens::none());- self.report_invalid_private_identifier_usage(&expression);- self.expression(- start,- ExpressionKind::Unary {- op,- operand: Box::new(expression),- },- )- }- // https://tc39.es/ecma262/#sec-delete-operator-static-semantics-early-errors- // It is a Syntax Error if the UnaryExpression is an IdentifierReference- // and the source text matched by the enclosing Script or Module is strict mode code.- TokenType::Delete => {- self.consume();- let rhs_start = self.position();- let expression = self.parse_expression(PRECEDENCE_UNARY, Associativity::Right, ForbiddenTokens::none());- self.report_invalid_private_identifier_usage(&expression);- if self.flags.strict_mode && Self::is_identifier(&expression) {- self.syntax_error_at(- "Delete of an unqualified identifier in strict mode.",- rhs_start.line,- rhs_start.column,- );- }- if let ExpressionKind::Member(ref data) = expression.inner- && matches!(data.property.inner, ExpressionKind::PrivateIdentifier(_))- {- self.syntax_error("Private fields cannot be deleted");- }- self.expression(- start,- ExpressionKind::Unary {- op: UnaryOp::Delete,- operand: Box::new(expression),- },- )- }- _ => {- self.expected("unary expression");- self.consume();- self.expression(start, ExpressionKind::Error)- }- }- }-- /// Parse a `new` expression, handling `new.target` and nested `new` calls.- // https://tc39.es/ecma262/#sec-new-operator- // MemberExpression : `new` MemberExpression Arguments- // NewExpression : `new` NewExpression- // https://tc39.es/ecma262/#sec-meta-properties- // NewTarget : `new` `.` `target`- fn parse_new_expression(&mut self) -> Expression {- let start = self.position();- self.consume_token(TokenType::New);-- if self.match_token(TokenType::Period) {- self.consume();- let target_token = self.current_token.clone();- self.consume_token(TokenType::Identifier);- if self.token_original_value(&target_token) != utf16!("target") {- self.syntax_error("Expected 'target' after 'new.'");- }- // https://tc39.es/ecma262/#sec-new.target- // It is a Syntax Error if NewTarget is not enclosed, directly or indirectly- // (but not crossing function or class static initialization block boundaries),- // within a FunctionBody, ConciseBody, ClassStaticBlock, or ClassBody.- if !self.flags.new_target_is_valid && !self.in_eval_function_context {- self.syntax_error("'new.target' not allowed outside of a function");- }- if self.scope_collector.has_current_scope() {- self.scope_collector.set_uses_new_target();- }- return self.expression(start, ExpressionKind::MetaProperty(MetaPropertyType::NewTarget));- }-- let callee_starts_with_grouping_paren = self.match_token(TokenType::ParenOpen);- let callee = if self.match_token(TokenType::New) {- self.parse_new_expression()- } else {- let forbidden = ForbiddenTokens::none().forbid(&[TokenType::ParenOpen, TokenType::QuestionMarkPeriod]);- self.parse_expression(PRECEDENCE_MEMBER, Associativity::Right, forbidden)- };-- // NB: An ImportCall is a CallExpression, not a MemberExpression, so neither it nor a member access or tagged- // template on it can be the operand of `new` unless it is parenthesized.- if !callee_starts_with_grouping_paren {- let mut base = &callee;- loop {- match &base.inner {- ExpressionKind::Member(member) => base = &member.object,- ExpressionKind::TaggedTemplateLiteral(tagged_template) => base = &tagged_template.tag,- _ => break,- }- }- if matches!(base.inner, ExpressionKind::ImportCall(_)) {- self.syntax_error("Cannot call new on dynamic import");- }- }-- if self.match_token(TokenType::ParenOpen) {- let arguments = self.parse_arguments();- self.expression(- start,- ExpressionKind::New(Box::new(CallExpressionData {- callee: Box::new(callee),- arguments,- // Mirrors C++ InvocationStyle::Parenthesized for `new Foo(...)`.- is_parenthesized: true,- is_inside_parens: false,- })),- )- } else {- self.expression(- start,- ExpressionKind::New(Box::new(CallExpressionData {- callee: Box::new(callee),- arguments: Vec::new(),- is_parenthesized: false,- is_inside_parens: false,- })),- )- }- }-- /// Parse a call expression `callee(arguments...)`.- // https://tc39.es/ecma262/#sec-function-calls- // https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation- // NB: A direct call to `eval` (bare identifier `eval` as callee) uses the- // running execution context's variable environment, not a fresh one.- pub(crate) fn parse_call_expression(&mut self, callee: Expression) -> Expression {- let start = self.position();- let arguments = self.parse_arguments();- // Check the actual callee expression kind, matching C++ which does- // is<Identifier>(callee) && callee.string() == "eval".- if let ExpressionKind::Identifier(id) = callee.inner- && self.arena.name_of(id).as_slice() == utf16!("eval")- {- self.scope_collector.set_contains_direct_call_to_eval();- self.scope_collector.set_uses_this();- }- self.expression(- start,- ExpressionKind::Call(Box::new(CallExpressionData {- callee: Box::new(callee),- arguments,- is_parenthesized: false,- is_inside_parens: false,- })),- )- }-- pub(crate) fn parse_arguments(&mut self) -> Vec<CallArgument> {- self.consume_token(TokenType::ParenOpen);- let mut arguments = Vec::new();-- while !self.match_token(TokenType::ParenClose) && !self.done() {- let is_spread = self.eat(TokenType::TripleDot);- let value = self.parse_assignment_expression();- arguments.push(CallArgument { value, is_spread });- if !self.match_token(TokenType::Comma) {- break;- }- self.consume();- }-- self.consume_token(TokenType::ParenClose);- arguments- }-- /// Parse an optional chaining expression (`a?.b`, `a?.[x]`, `a?.()`).- // https://tc39.es/ecma262/#sec-optional-chains- // OptionalExpression : MemberExpression OptionalChain- // OptionalChain : `?.` Arguments- // | `?.` `[` Expression `]`- // | `?.` IdentifierName- // | `?.` TemplateLiteral -- NOTE: this is a syntax error (see below)- // | OptionalChain Arguments- // | OptionalChain `[` Expression `]`- // | OptionalChain `.` IdentifierName- // | OptionalChain TemplateLiteral -- also a syntax error- fn parse_optional_chain(&mut self, start: Position, base: Expression) -> Expression {- let mut references = Vec::new();-- loop {- if self.match_token(TokenType::QuestionMarkPeriod) {- self.consume();- match self.current_token_type() {- TokenType::ParenOpen => {- let arguments = self.parse_arguments();- references.push(OptionalChainReference::Call {- arguments,- mode: OptionalChainMode::Optional,- });- }- TokenType::BracketOpen => {- self.consume();- let expression = self.parse_expression_any();- self.consume_token(TokenType::BracketClose);- references.push(OptionalChainReference::ComputedReference {- expression: Box::new(expression),- mode: OptionalChainMode::Optional,- });- }- TokenType::PrivateIdentifier => {- let property_start = self.position();- let id = self.parse_private_identifier(property_start);- references.push(OptionalChainReference::PrivateMemberReference {- private_identifier: id,- mode: OptionalChainMode::Optional,- });- }- // https://tc39.es/ecma262/#sec-optional-chaining-chain-production- // It is a Syntax Error if any code matches this production:- // OptionalChain : `?.` TemplateLiteral- // Tagged templates cannot be used with optional chaining.- TokenType::TemplateLiteralStart => {- self.syntax_error("Invalid tagged template literal after ?.");- break;- }- _ => {- if self.match_identifier_name() {- let property_start = self.position();- let token = self.consume();- let name = self.token_identifier_name(&token);- references.push(OptionalChainReference::MemberReference {- identifier: self.make_identifier(property_start, name),- mode: OptionalChainMode::Optional,- });- } else {- self.syntax_error("Invalid optional chain reference after ?.");- break;- }- }- }- } else if self.match_token(TokenType::ParenOpen) {- let arguments = self.parse_arguments();- references.push(OptionalChainReference::Call {- arguments,- mode: OptionalChainMode::NotOptional,- });- } else if self.match_token(TokenType::Period) {- self.consume();- if self.match_token(TokenType::PrivateIdentifier) {- let property_start = self.position();- let id = self.parse_private_identifier(property_start);- references.push(OptionalChainReference::PrivateMemberReference {- private_identifier: id,- mode: OptionalChainMode::NotOptional,- });- } else if self.match_identifier_name() {- let property_start = self.position();- let token = self.consume();- let name = self.token_identifier_name(&token);- references.push(OptionalChainReference::MemberReference {- identifier: self.make_identifier(property_start, name),- mode: OptionalChainMode::NotOptional,- });- } else {- self.expected("an identifier");- break;- }- } else if self.match_token(TokenType::TemplateLiteralStart) {- self.syntax_error("Invalid tagged template literal after optional chain");- break;- } else if self.match_token(TokenType::BracketOpen) {- self.consume();- let expression = self.parse_expression_any();- self.consume_token(TokenType::BracketClose);- references.push(OptionalChainReference::ComputedReference {- expression: Box::new(expression),- mode: OptionalChainMode::NotOptional,- });- } else {- break;- }-- if self.done() {- break;- }- }-- self.expression(- start,- ExpressionKind::OptionalChain(Box::new(OptionalChainData {- base: Box::new(base),- references,- })),- )- }-- /// Parse a `yield` or `yield*` expression.- // https://tc39.es/ecma262/#sec-generator-function-definitions- // YieldExpression : `yield`- // | `yield` [no LineTerminator here] AssignmentExpression- // | `yield` [no LineTerminator here] `*` AssignmentExpression- // https://tc39.es/ecma262/#sec-generator-function-definitions-static-semantics-early-errors- // It is a Syntax Error if YieldExpression appears within FormalParameters.- fn parse_yield_expression(&mut self, forbidden: ForbiddenTokens) -> Expression {- let start = self.position();-- if self.flags.in_formal_parameter_context {- self.syntax_error("'Yield' expression is not allowed in formal parameters of generator function");- }-- self.consume_token(TokenType::Yield);-- if self.current_token.trivia_has_line_terminator {- return self.expression(- start,- ExpressionKind::Yield(Box::new(YieldExprData {- argument: None,- is_yield_from: false,- })),- );- }-- let is_yield_from = self.match_token(TokenType::Asterisk);- if is_yield_from {- self.consume();- }-- if is_yield_from || self.match_expression() || self.match_token(TokenType::Class) {- // https://tc39.es/ecma262/#prod-YieldExpression- // YieldExpression[In, Await] :- // `yield` [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await]- // `yield` [no LineTerminator here] `*` AssignmentExpression[?In, +Yield, ?Await]- let argument = self.parse_expression(PRECEDENCE_ASSIGNMENT, Associativity::Right, forbidden);- self.expression(- start,- ExpressionKind::Yield(Box::new(YieldExprData {- argument: Some(Box::new(argument)),- is_yield_from,- })),- )- } else {- self.expression(- start,- ExpressionKind::Yield(Box::new(YieldExprData {- argument: None,- is_yield_from: false,- })),- )- }- }-- /// Parse an `await` expression.- // https://tc39.es/ecma262/#sec-async-function-definitions- // AwaitExpression : `await` UnaryExpression- // https://tc39.es/ecma262/#sec-async-function-definitions-static-semantics-early-errors- // It is a Syntax Error if AwaitExpression appears within FormalParameters.- fn parse_await_expression(&mut self) -> Expression {- let start = self.position();-- if self.flags.in_formal_parameter_context {- self.syntax_error("'Await' expression is not allowed in formal parameters of an async function");- }-- self.consume_token(TokenType::Await);- let argument = self.parse_expression(PRECEDENCE_UNARY, Associativity::Right, ForbiddenTokens::none());- self.scope_collector.set_contains_await_expression();- self.expression(start, ExpressionKind::Await(Box::new(argument)))- }-- fn parse_object_expression(&mut self) -> Expression {- let start = self.position();- self.consume_token(TokenType::CurlyOpen);-- let mut properties = Vec::new();- let mut has_proto_setter = false;- while !self.match_token(TokenType::CurlyClose) && !self.done() {- if self.match_token(TokenType::TripleDot) {- let spread_start = self.position();- self.consume();- let expression = self.parse_assignment_expression();- properties.push(ObjectProperty {- range: self.range_from(spread_start),- property_type: ObjectPropertyType::Spread,- key: Box::new(expression),- is_computed: false,- value: None,- is_method: false,- });- } else {- let property = self.parse_object_property(start);- // https://tc39.es/ecma262/#sec-object-initializer-static-semantics-early-errors- // It is a Syntax Error if PropertyNameList of PropertyDefinitionList- // contains any duplicate entries for "__proto__" and at least two of- // those entries were obtained from productions of the form- // PropertyDefinition : PropertyName `:` AssignmentExpression.- if property.property_type == ObjectPropertyType::ProtoSetter {- if has_proto_setter {- self.syntax_error("Duplicate __proto__ fields are not allowed in object expressions");- }- has_proto_setter = true;- }- properties.push(property);- }-- if !self.match_token(TokenType::Comma) {- break;- }- self.consume();- }-- self.consume_token(TokenType::CurlyClose);- self.expression(start, ExpressionKind::Object(Box::new(properties)))- }-- fn parse_object_property(&mut self, obj_start: Position) -> ObjectProperty {- let start = self.position();- let mut is_getter = false;- let mut is_setter = false;- let mut is_async = false;- let mut is_generator = false;-- if self.match_identifier_name() {- let value = self.token_original_value(&self.current_token).to_vec();- if value == utf16!("get") && self.match_property_key_ahead() {- is_getter = true;- self.consume();- } else if value == utf16!("set") && self.match_property_key_ahead() {- is_setter = true;- self.consume();- } else if value == utf16!("async") {- let next = self.next_token();- if !next.trivia_has_line_terminator- && next.token_type != TokenType::ParenOpen- && next.token_type != TokenType::Colon- && next.token_type != TokenType::Comma- && next.token_type != TokenType::CurlyClose- {- is_async = true;- self.consume();- if self.match_token(TokenType::Asterisk) {- is_generator = true;- self.consume();- }- }- }- }-- if !is_getter && !is_setter && !is_async && self.match_token(TokenType::Asterisk) {- is_generator = true;- self.consume();- }-- let PropertyKey {- expression: key,- name: key_value,- is_proto,- is_computed,- is_identifier,- } = self.parse_property_key();-- // https://tc39.es/ecma262/#sec-object-initializer- // Private names are not allowed in object literals, even inside class bodies.- if let ExpressionKind::PrivateIdentifier(_) = key.inner {- self.syntax_error("Private field or method is not allowed in object literal");- }-- if self.match_token(TokenType::ParenOpen) {- let method_kind = if is_getter {- MethodKind::Getter- } else if is_setter {- MethodKind::Setter- } else {- MethodKind::Normal- };- let function = self.parse_method_definition(is_async, is_generator, method_kind, start);- let property_type = if is_getter {- ObjectPropertyType::Getter- } else if is_setter {- ObjectPropertyType::Setter- } else {- ObjectPropertyType::KeyValue- };- return ObjectProperty {- range: self.range_from(obj_start),- property_type,- key: Box::new(key),- value: Some(Box::new(function)),- is_method: true,- is_computed,- };- }-- // async modifier requires a method (must have parens)- if is_async {- self.syntax_error("Expected function after async keyword");- }- // Generator shorthand requires a method body.- if is_generator {- self.syntax_error("Expected method after generator star");- }-- if is_getter || is_setter {- let method_kind = if is_getter {- MethodKind::Getter- } else {- MethodKind::Setter- };- let function = self.parse_method_definition(false, false, method_kind, start);- let property_type = if is_getter {- ObjectPropertyType::Getter- } else {- ObjectPropertyType::Setter- };- return ObjectProperty {- range: self.range_from(obj_start),- property_type,- key: Box::new(key),- value: Some(Box::new(function)),- is_method: true,- is_computed,- };- }-- if self.match_token(TokenType::Colon) {- self.consume();- let value = self.parse_assignment_expression();- let property_type = if is_proto {- ObjectPropertyType::ProtoSetter- } else {- ObjectPropertyType::KeyValue- };- return ObjectProperty {- range: self.range_from(obj_start),- property_type,- key: Box::new(key),- value: Some(Box::new(value)),- is_method: false,- is_computed,- };- }-- // https://tc39.es/ecma262/#sec-object-initializer- // CoverInitializedName : IdentifierReference Initializer- // https://tc39.es/ecma262/#sec-object-initializer-static-semantics-early-errors- // It is a Syntax Error if PropertyDefinitionList contains any CoverInitializedName.- // NB: This is not a valid object literal, but is a valid destructuring assignment- // target. We parse the initializer to advance the lexer, but roll back scope records- // since this expression is discarded. synthesize_binding_pattern will- // re-parse from source and create the real scope records.- if self.match_token(TokenType::Equals)- && is_identifier- && let Some(kv) = &key_value- {- let id = self.make_identifier_from_slice(obj_start, kv.as_slice());- {- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- let value = self.expression(obj_start, ExpressionKind::Identifier(id));- self.consume(); // consume '='- // NB: Add a syntax error for CoverInitializedName. This error will- // be cleared by synthesize_binding_pattern if the containing object- // is reinterpreted as a destructuring pattern, but will persist if- // the object is used in expression context (e.g. as a member base).- self.syntax_error("Invalid property in object literal");- let saved_scope_state = self.scope_collector.save_state();- let _initializer = self.parse_assignment_expression();- self.scope_collector.load_state(saved_scope_state);- return ObjectProperty {- range: self.range_from(obj_start),- property_type: ObjectPropertyType::KeyValue,- key: Box::new(key),- value: Some(Box::new(value)),- is_method: false,- is_computed: false,- };- }-- // Shorthand property: { x }- // Only identifiers can be shorthand properties, not string/numeric literals.- if let Some(kv) = key_value.filter(|_| is_identifier) {- // https://tc39.es/ecma262/#sec-object-initializer-static-semantics-early-errors- // Strict-mode reserved words cannot be used as shorthand properties.- if self.flags.strict_mode && is_strict_reserved_word(&kv) {- let name_str = String::from_utf16_lossy(&kv);- self.syntax_error(&format!("'{name_str}' is a reserved keyword"));- }- let id = self.make_identifier_from_slice(obj_start, kv.as_slice());- {- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- let value = self.expression(obj_start, ExpressionKind::Identifier(id));- return ObjectProperty {- range: self.range_from(obj_start),- property_type: ObjectPropertyType::KeyValue,- key: Box::new(key),- value: Some(Box::new(value)),- is_method: false,- is_computed: false,- };- }-- self.expected("':' or '('");- ObjectProperty {- range: self.range_from(obj_start),- property_type: ObjectPropertyType::KeyValue,- key: Box::new(key),- value: None,- is_method: false,- is_computed,- }- }-- pub(crate) fn match_property_key_ahead(&mut self) -> bool {- let next = self.next_token();- matches!(- next.token_type,- TokenType::BracketOpen- | TokenType::StringLiteral- | TokenType::NumericLiteral- | TokenType::BigIntLiteral- | TokenType::PrivateIdentifier- ) || next.token_type.is_identifier_name()- }-- pub(crate) fn parse_property_key(&mut self) -> PropertyKey {- let proto_name = utf16!("__proto__");- let start = self.position();- match self.current_token_type() {- TokenType::BracketOpen => {- self.consume();- let expression = self.parse_assignment_expression();- self.consume_token(TokenType::BracketClose);- PropertyKey {- expression,- name: None,- is_proto: false,- is_computed: true,- is_identifier: false,- }- }- TokenType::StringLiteral => {- let token = self.consume_property_key_token();- // C++ calls consume() before push_start() for StringLiteral,- // so its position is the token AFTER the string.- let after_string = self.position();- let (value, has_octal) = self.parse_string_value(&token);- if has_octal {- if self.flags.strict_mode {- self.syntax_error("Octal escape sequence in string literal not allowed in strict mode");- } else {- self.flags.string_legacy_octal_escape_sequence_in_scope = true;- }- }- let is_proto = value == proto_name;- let expression = self.expression(after_string, ExpressionKind::StringLiteral(Box::new(value.clone())));- PropertyKey {- expression,- name: Some(value),- is_proto,- is_computed: false,- is_identifier: false,- }- }- TokenType::NumericLiteral => {- let token = self.consume_and_validate_numeric_literal();- let value_str = self.token_value(&token);- let value = parse_numeric_value(value_str);- let expression = self.expression(start, ExpressionKind::NumericLiteral(value));- PropertyKey {- expression,- name: None,- is_proto: false,- is_computed: false,- is_identifier: false,- }- }- TokenType::BigIntLiteral => {- let token = self.consume();- let value = self.token_value(&token);- // Store the raw value including the 'n' suffix, matching C++.- let value = Utf16String(value.to_vec());- let expression = self.expression(start, ExpressionKind::BigIntLiteral(Box::new(value)));- PropertyKey {- expression,- name: None,- is_proto: false,- is_computed: false,- is_identifier: false,- }- }- // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors- // It is a Syntax Error if the StringValue of PrivateIdentifier is "#constructor".- TokenType::PrivateIdentifier => {- let token = self.consume();- let value = Utf16String::from(self.token_value(&token));- if value == utf16!("#constructor") {- self.syntax_error("Private property with name '#constructor' is not allowed");- }- let expression = self.expression(- start,- ExpressionKind::PrivateIdentifier(Box::new(PrivateIdentifier {- range: self.range_from(start),- name: value.clone(),- })),- );- PropertyKey {- expression,- name: Some(value),- is_proto: false,- is_computed: false,- is_identifier: false,- }- }- _ => {- if self.match_identifier_name() {- // is_identifier is true only for valid identifier references (not just- // identifier names). This matters for shorthand properties: { await }- // is not valid in class static blocks since await is not an identifier there.- let is_ident = self.match_identifier();- let token = self.consume_property_key_token();- let value = Utf16String::from(self.token_value(&token));- let is_proto = value == proto_name;- let expression = self.expression(start, ExpressionKind::StringLiteral(Box::new(value.clone())));- PropertyKey {- expression,- name: Some(value),- is_proto,- is_computed: false,- is_identifier: is_ident,- }- } else {- self.expected("property key");- self.consume_property_key_token();- let expression =- self.expression(start, ExpressionKind::StringLiteral(Box::new(Utf16String::new())));- PropertyKey {- expression,- name: None,- is_proto: false,- is_computed: false,- is_identifier: false,- }- }- }- }- }-- fn parse_array_expression(&mut self) -> Expression {- let start = self.position();- self.consume_token(TokenType::BracketOpen);-- let mut elements: Vec<Option<Expression>> = Vec::new();- while !self.match_token(TokenType::BracketClose) && !self.done() {- if self.match_token(TokenType::Comma) {- elements.push(None);- self.consume();- continue;- }- if self.match_token(TokenType::TripleDot) {- let spread_start = self.position();- self.consume();- let expression = self.parse_assignment_expression();- elements.push(Some(- self.expression(spread_start, ExpressionKind::Spread(Box::new(expression))),- ));- } else {- elements.push(Some(self.parse_assignment_expression()));- }- if !self.match_token(TokenType::Comma) {- break;- }- self.consume();- }-- self.consume_token(TokenType::BracketClose);- self.expression(start, ExpressionKind::Array(Box::new(elements)))- }-- /// Parse a template literal (`` `...${expression}...` ``).- // https://tc39.es/ecma262/#sec-template-literals- // TemplateLiteral : NoSubstitutionTemplate- // | SubstitutionTemplate- // SubstitutionTemplate : TemplateHead Expression TemplateSpans- // NB: In tagged templates, invalid escape sequences produce `undefined` for the- // cooked value instead of a syntax error (sec-template-literals-static-semantics-early-errors).- /// Consume any tagged template literals following an expression.- /// Tagged templates bind tighter than any binary operator, so they- /// are handled outside the normal precedence loop.- fn parse_tagged_template_literals(&mut self, tag_start: Position, mut expression: Expression) -> Expression {- while self.match_token(TokenType::TemplateLiteralStart) {- let template = self.parse_template_literal(true);- expression = self.expression(- tag_start,- ExpressionKind::TaggedTemplateLiteral(Box::new(TaggedTemplateData {- tag: Box::new(expression),- template_literal: Box::new(template),- })),- );- }- expression- }-- pub(crate) fn parse_template_literal(&mut self, is_tagged: bool) -> Expression {- let start = self.position();- self.consume_token(TokenType::TemplateLiteralStart);-- let mut expressions = Vec::new();- let mut raw_strings = Vec::new();-- let needs_leading_empty = !self.match_token(TokenType::TemplateLiteralString);- if needs_leading_empty {- if is_tagged {- raw_strings.push(Utf16String::new());- }- expressions.push(self.expression(start, ExpressionKind::StringLiteral(Box::new(Utf16String::new()))));- }-- // For non-tagged templates, we collect parts as expressions (alternating- // string parts and interpolation expressions). For tagged templates, we- // also collect raw strings separately.-- loop {- if self.match_token(TokenType::TemplateLiteralEnd) {- self.consume();- break;- }- if self.match_token(TokenType::TemplateLiteralString) {- let token = self.consume();- // C++ calls parse_string_literal after consume(), so its position- // is after the template string token. Match that behavior.- let string_pos = self.position();- let raw = self.token_value(&token).to_vec();- if is_tagged {- let raw_value = raw_template_value(&raw);- raw_strings.push(raw_value);- match self.process_template_escape_sequences(&raw) {- Some(cooked) => expressions- .push(self.expression(string_pos, ExpressionKind::StringLiteral(Box::new(cooked)))),- // C++ uses rule_start (template literal start) for NullLiteral.- None => {- expressions.push(self.expression(start, ExpressionKind::NullLiteral));- }- }- } else {- let (value, has_octal) = self.process_escape_sequences(&raw);- if has_octal {- self.syntax_error("Octal escape sequence not allowed in template literal");- }- expressions.push(self.expression(string_pos, ExpressionKind::StringLiteral(Box::new(value))));- }- } else if self.match_token(TokenType::TemplateLiteralExprStart) {- self.consume();- let expression = self.parse_expression_any();- expressions.push(expression);- self.consume_token(TokenType::TemplateLiteralExprEnd);- // After an expression, if no template string follows, insert empty.- if !self.match_token(TokenType::TemplateLiteralString) {- expressions- .push(self.expression(start, ExpressionKind::StringLiteral(Box::new(Utf16String::new()))));- if is_tagged {- raw_strings.push(Utf16String::new());- }- }- } else if self.done() {- self.expected("template literal end");- break;- } else {- self.consume();- }- }-- self.expression(- start,- ExpressionKind::TemplateLiteral(Box::new(TemplateLiteralData {- expressions,- raw_strings,- })),- )- }-- fn process_template_escape_sequences(&self, raw: &[u16]) -> Option<Utf16String> {- let result = process_escape_sequences_impl(raw, EscapeMode::TaggedTemplate);- if result.failed { None } else { Some(result.value) }- }-- /// Parse a string literal token's value, processing escape sequences.- /// Returns `(value, has_legacy_octal)`.- pub(crate) fn parse_string_value(&mut self, token: &Token) -> (Utf16String, bool) {- let raw = self.token_value(token).to_vec();- if raw.len() < 2 {- return (Utf16String::default(), false);- }- self.process_escape_sequences(&raw[1..raw.len() - 1])- }-- pub(crate) fn process_escape_sequences(&mut self, inner: &[u16]) -> (Utf16String, bool) {- let result = process_escape_sequences_impl(inner, EscapeMode::StringLiteral);- if result.malformed_hex {- self.syntax_error("Malformed hexadecimal escape sequence");- }- if result.malformed_unicode {- self.syntax_error("Malformed unicode escape sequence");- }- (result.value, result.has_legacy_octal)- }-}--struct EscapeResult {- value: Utf16String,- has_legacy_octal: bool,- /// Tagged template encountered an invalid escape.- failed: bool,- malformed_hex: bool,- malformed_unicode: bool,-}--/// Unified escape sequence processor for both string and template literals.-///-/// In `TaggedTemplate` mode, `failed` is true when an invalid escape is-/// encountered (the cooked value becomes `undefined`).-fn process_escape_sequences_impl(input: &[u16], mode: EscapeMode) -> EscapeResult {- let mut result = Utf16String(Vec::with_capacity(input.len()));- let mut has_legacy_octal = false;- let mut malformed_hex = false;- let mut malformed_unicode = false;- let mut i = 0;-- const N: u16 = ch(b'n');- const R: u16 = ch(b'r');- const T: u16 = ch(b't');- const B: u16 = ch(b'b');- const F: u16 = ch(b'f');- const V: u16 = ch(b'v');- const ZERO: u16 = ch(b'0');- const ONE: u16 = ch(b'1');- const SEVEN: u16 = ch(b'7');- const EIGHT: u16 = ch(b'8');- const NINE: u16 = ch(b'9');- const X: u16 = ch(b'x');- const U: u16 = ch(b'u');- const LF: u16 = ch(b'\n');- const CR: u16 = ch(b'\r');- const LS: u16 = 0x2028;- const PS: u16 = 0x2029;-- while i < input.len() {- if input[i] == b'\\' as u16 && i + 1 < input.len() {- i += 1;- match input[i] {- N => result.0.push(ch(b'\n')),- R => result.0.push(ch(b'\r')),- T => result.0.push(ch(b'\t')),- B => result.0.push(8),- F => result.0.push(12),- V => result.0.push(11),- ZERO => {- if mode == EscapeMode::TaggedTemplate {- if i + 1 < input.len()- && (is_octal_char(input[i + 1]) || input[i + 1] == EIGHT || input[i + 1] == NINE)- {- return EscapeResult {- value: result,- has_legacy_octal: false,- failed: true,- malformed_hex: false,- malformed_unicode: false,- };- }- result.0.push(0);- } else if i + 1 < input.len() && is_octal_char(input[i + 1]) {- has_legacy_octal = true;- let (val, consumed) = parse_octal_escape(input, i);- result.0.push(val);- i += consumed;- } else if i + 1 < input.len() && (input[i + 1] == EIGHT || input[i + 1] == NINE) {- has_legacy_octal = true;- result.0.push(0);- } else {- result.0.push(0);- }- }- ONE..=SEVEN => {- if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: result,- has_legacy_octal: false,- failed: true,- malformed_hex: false,- malformed_unicode: false,- };- }- has_legacy_octal = true;- let (val, consumed) = parse_octal_escape(input, i);- result.0.push(val);- i += consumed;- }- EIGHT | NINE => {- if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: result,- has_legacy_octal: false,- failed: true,- malformed_hex: false,- malformed_unicode: false,- };- }- has_legacy_octal = true;- result.0.push(input[i]);- }- X => {- if let Some((advance, ch)) = parse_hex_escape(input, i) {- result.0.push(ch);- i += advance;- } else if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: result,- has_legacy_octal: false,- failed: true,- malformed_hex: false,- malformed_unicode: false,- };- } else {- malformed_hex = true;- result.0.push(input[i]);- }- }- U => {- if let Some((advance, code_point)) = parse_unicode_escape(input, i) {- push_code_point(&mut result.0, code_point);- i += advance;- } else if mode == EscapeMode::TaggedTemplate {- return EscapeResult {- value: result,- has_legacy_octal: false,- failed: true,- malformed_hex: false,- malformed_unicode: false,- };- } else {- malformed_unicode = true;- result.0.push(input[i]);- }- }- LF => { /* line continuation */ }- CR => {- if i + 1 < input.len() && input[i + 1] == LF {- i += 1;- }- }- LS | PS => { /* skip LS/PS */ }- c => result.0.push(c),- }- } else if input[i] == ch(b'\r') {- // Normalize \r\n and bare \r to \n per spec (12.9.6).- result.0.push(ch(b'\n'));- if i + 1 < input.len() && input[i + 1] == ch(b'\n') {- i += 1;- }- } else {- result.0.push(input[i]);- }- i += 1;- }- EscapeResult {- value: result,- has_legacy_octal,- failed: false,- malformed_hex,- malformed_unicode,- }-}--impl Parser<'_> {- /// Try to parse an arrow function expression, with memoization.- /// If a previous attempt at this position already failed, returns `None`- /// immediately. Otherwise attempts the parse and caches the failure.- /// This prevents exponential re-processing of nested expressions like- /// `(a=(b=(c=0)))` where each outer failed arrow attempt would re-trigger- /// inner attempts during grouping expression re-parse.- // https://tc39.es/ecma262/#sec-arrow-function-definitions- // ArrowFunction : ArrowParameters [no LineTerminator here] `=>` ConciseBody- // ConciseBody : [lookahead != `{`] ExpressionBody- // | `{` FunctionBody `}`- pub(crate) fn try_parse_arrow_function_expression(- &mut self,- expect_parens: bool,- is_async: bool,- source_start_override: Option<Position>,- forbidden: ForbiddenTokens,- ) -> Option<Expression> {- let offset = source_start_override.map_or(self.current_token.offset, |p| p.offset) as usize;- if self.arrow_function_failed_positions.contains(&offset) {- return None;- }- let result =- self.try_parse_arrow_function_expression_impl(expect_parens, is_async, source_start_override, forbidden);- if result.is_none() {- self.arrow_function_failed_positions.insert(offset);- }- result- }-- fn try_parse_arrow_function_expression_impl(- &mut self,- expect_parens: bool,- is_async: bool,- source_start_override: Option<Position>,- forbidden: ForbiddenTokens,- ) -> Option<Expression> {- let start = source_start_override.unwrap_or_else(|| self.position());-- if !expect_parens && !is_async {- if !self.match_identifier() && !self.match_token(TokenType::Await) && !self.match_token(TokenType::Yield) {- return None;- }- let next = self.next_token();- if next.token_type != TokenType::Arrow || next.trivia_has_line_terminator {- return None;- }- }-- // Save and clear pattern_bound_names so that parameter and body- // parsing inside this arrow function doesn't steal binding names- // accumulated by an outer binding pattern context.- let saved_pattern_bound_names = std::mem::take(&mut self.pattern_bound_names);-- self.save_state();-- // Reset in_formal_parameter_context so that yield/await inside- // arrow function bodies nested in parameter defaults are not- // rejected. (load_state restores flags on error paths.)- let saved_formal_parameter_ctx = self.flags.in_formal_parameter_context;- self.flags.in_formal_parameter_context = false;-- if is_async {- self.consume(); // consume 'async'- if self.current_token.trivia_has_line_terminator {- self.pattern_bound_names = saved_pattern_bound_names;- self.load_state();- return None;- }- if expect_parens {- self.consume_token(TokenType::ParenOpen);- }- }-- // Open function scope before parsing parameters so that default- // value expressions are resolved inside the function scope.- // save_state() above captured scope collector state, so any- // load_state() rollback will undo this.- self.scope_collector.open_function_scope(None);- self.scope_collector.set_is_arrow_function();- self.push_function_context();-- // Set await_expression_is_valid during parameter parsing so that- // 'await' is rejected as an identifier in async arrow parameters.- let saved_await = self.flags.await_expression_is_valid;- let saved_static_init = self.flags.in_class_static_init_block;- if is_async {- self.flags.await_expression_is_valid = true;- }- // NB: Do NOT clear in_class_static_init_block here. Arrow functions don't- // create a new `await` boundary, so `await` in parameter defaults must still- // be rejected inside class static initializer blocks. The flag is cleared- // below, after parameter parsing, for the arrow body only.-- let parsed;-- if expect_parens {- let previous_errors = self.errors.len();- parsed = self.parse_formal_parameters_impl(true);- if self.errors.len() > previous_errors {- self.pattern_bound_names = saved_pattern_bound_names;- self.load_state();- return None;- }- if !self.match_token(TokenType::ParenClose) {- self.pattern_bound_names = saved_pattern_bound_names;- self.load_state();- return None;- }- self.consume(); // consume ')'- } else if self.match_identifier() || self.match_token(TokenType::Await) {- let token = self.consume();- let value = self.token_value(&token).to_vec();- if value == utf16!("await")- && (is_async || self.program_type == ProgramType::Module || self.flags.in_class_static_init_block)- {- self.syntax_error("'await' is not allowed as an identifier in this context");- }- // C++ uses rule_start (arrow function start, which is `async` for async arrows).- let value_id = self.arena.strings.intern(&value);- let binding = self- .arena- .identifiers- .insert(Identifier::new(self.range_from(start), value_id));- parsed = ParsedParameters {- parameters: vec![FunctionParameter {- binding: FunctionParameterBinding::Identifier(binding),- default_value: None,- is_rest: false,- }],- function_length: 1,- parameter_info: vec![ParamInfo {- name: value.into(),- is_rest: false,- is_from_pattern: false,- identifier: Some(binding),- }],- is_simple: true,- };- } else {- self.flags.await_expression_is_valid = saved_await;- self.pattern_bound_names = saved_pattern_bound_names;- self.load_state();- return None;- }-- // Restore await flag during arrow-check; it will be set- // again for the body below.- self.flags.await_expression_is_valid = saved_await;-- // [no LineTerminator here] before `=>`- if !self.match_token(TokenType::Arrow) || self.current_token.trivia_has_line_terminator {- self.pattern_bound_names = saved_pattern_bound_names;- self.load_state();- return None;- }- self.consume(); // consume =>-- self.discard_saved_state();-- let ParsedParameters {- parameters,- function_length,- parameter_info,- is_simple,- } = parsed;-- // Arrow functions always reject duplicate parameter names.- self.check_arrow_duplicate_parameters(¶meter_info);-- self.register_function_parameters_with_scope(¶meters, ¶meter_info);-- let fn_kind = if is_async {- FunctionKind::Async- } else {- FunctionKind::Normal- };- let src_start = source_start_override.unwrap_or(start).offset;-- // Set context flags for the arrow body.- let saved_await_body = self.flags.await_expression_is_valid;- self.flags.await_expression_is_valid = is_async;- self.flags.in_class_static_init_block = false;-- if self.match_token(TokenType::CurlyOpen) {- let (body, has_use_strict, insights) = self.parse_function_body(is_async, false, is_simple);-- self.scope_collector.close_scope();- self.pattern_bound_names = saved_pattern_bound_names;-- if has_use_strict || fn_kind != FunctionKind::Normal || self.flags.strict_mode {- self.check_parameters_post_body(¶meter_info, has_use_strict || self.flags.strict_mode, fn_kind);- }-- self.flags.await_expression_is_valid = saved_await_body;- self.flags.in_class_static_init_block = saved_static_init;- self.flags.in_formal_parameter_context = saved_formal_parameter_ctx;- let nested_function_ids = self.pop_function_context();- let function_id = self.insert_function_data(FunctionData {- name: None,- source_text_start: src_start,- source_text_end: self.source_text_end_offset(),- body: Box::new(body),- parameters,- function_length,- kind: fn_kind,- is_strict_mode: self.flags.strict_mode || has_use_strict,- is_arrow_function: true,- parsing_insights: insights,- nested_function_ids: Some(nested_function_ids),- });- Some(self.expression(start, ExpressionKind::Function(function_id)))- } else {- // https://tc39.es/ecma262/#prod-ArrowFunction- // ArrowFunction[In, Yield, Await] :- // ArrowParameters[?Yield, ?Await] [no LineTerminator here] `=>` ConciseBody[?In]- let expression = self.parse_expression(PRECEDENCE_ASSIGNMENT, Associativity::Right, forbidden);- // C++ uses rule_start (function start) for ReturnStatement and FunctionBody.- let return_statement = Statement::new(- self.range_from(start),- StatementKind::Return(Some(Box::new(expression))),- );- let scope = self.make_scope(vec![return_statement]);- self.scope_collector.set_scope_node(scope);- let body = Statement::new(- self.range_from(start),- StatementKind::FunctionBody {- scope,- in_strict_mode: self.flags.strict_mode,- },- );-- // C++ only sets contains_direct_call_to_eval and uses_this_from_environment- // for expression-body arrows (not uses_this).- let insights = FunctionParsingInsights {- contains_direct_call_to_eval: self.scope_collector.contains_direct_call_to_eval(),- uses_this_from_environment: self.scope_collector.uses_this_from_environment(),- ..FunctionParsingInsights::default()- };-- self.scope_collector.close_scope();- self.pattern_bound_names = saved_pattern_bound_names;-- if self.flags.strict_mode || fn_kind != FunctionKind::Normal {- self.check_parameters_post_body(¶meter_info, self.flags.strict_mode, fn_kind);- }-- self.flags.await_expression_is_valid = saved_await_body;- self.flags.in_class_static_init_block = saved_static_init;- self.flags.in_formal_parameter_context = saved_formal_parameter_ctx;- let nested_function_ids = self.pop_function_context();- let function_id = self.insert_function_data(FunctionData {- name: None,- source_text_start: src_start,- source_text_end: self.source_text_end_offset(),- body: Box::new(body),- parameters,- function_length,- kind: fn_kind,- is_strict_mode: self.flags.strict_mode,- is_arrow_function: true,- parsing_insights: insights,- nested_function_ids: Some(nested_function_ids),- });- Some(self.expression(start, ExpressionKind::Function(function_id)))- }- }-- pub(crate) fn parse_method_definition(- &mut self,- is_async: bool,- is_generator: bool,- method_kind: MethodKind,- function_start: Position,- ) -> Expression {- let start = function_start;-- let saved_might_need_arguments = self.flags.function_might_need_arguments_object;- self.flags.function_might_need_arguments_object = false;-- let fn_kind = FunctionKind::from_async_generator(is_async, is_generator);-- // Open function scope for method.- self.scope_collector.open_function_scope(None);-- let in_generator_before = self.flags.in_generator_function_context;- let await_before = self.flags.await_expression_is_valid;- let saved_static_init = self.flags.in_class_static_init_block;- let saved_field_init = self.flags.in_class_field_initializer;- let saved_allow_super_call = self.flags.allow_super_constructor_call;- let saved_allow_super_lookup = self.flags.allow_super_property_lookup;- let saved_new_target = self.flags.new_target_is_valid;- self.flags.in_generator_function_context = is_generator;- self.flags.await_expression_is_valid = is_async;- self.flags.in_class_static_init_block = false;- self.flags.in_class_field_initializer = false;- self.flags.allow_super_constructor_call = method_kind == MethodKind::Constructor && self.class_has_super_class;- self.flags.allow_super_property_lookup = true;- self.flags.new_target_is_valid = true;-- // Save pattern_bound_names so that destructuring patterns in the- // method body don't steal names from an outer binding context.- let saved_pattern_bound_names = std::mem::take(&mut self.pattern_bound_names);-- self.push_function_context();- let parsed = self.parse_formal_parameters();-- // UniqueFormalParameters : FormalParameters- // It is a Syntax Error if the BoundNames of |FormalParameters| contains any duplicate elements.- self.check_unique_formal_parameters(&parsed.parameter_info);-- self.register_function_parameters_with_scope(&parsed.parameters, &parsed.parameter_info);-- if method_kind == MethodKind::Getter && !parsed.parameters.is_empty() {- self.syntax_error("Getter function must have no arguments");- }- if method_kind == MethodKind::Setter- && (parsed.parameters.len() != 1 || parsed.parameters.first().is_some_and(|p| p.is_rest))- {- self.syntax_error("Setter function must have one argument");- }-- self.flags.in_generator_function_context = in_generator_before;- self.flags.await_expression_is_valid = await_before;-- let (body, has_use_strict, mut insights) = self.parse_function_body(is_async, is_generator, parsed.is_simple);- self.flags.allow_super_constructor_call = saved_allow_super_call;- self.flags.allow_super_property_lookup = saved_allow_super_lookup;-- self.scope_collector.close_scope();- self.pattern_bound_names = saved_pattern_bound_names;-- // Check parameters before restoring flags so that the method's- // context is used (e.g. in_class_static_init_block must remain- // false to allow `await` as a parameter name in generators).- let parameters_are_strict = self.flags.strict_mode || has_use_strict;- if parameters_are_strict || fn_kind != FunctionKind::Normal {- self.check_parameters_post_body(&parsed.parameter_info, parameters_are_strict, fn_kind);- }-- self.flags.in_class_static_init_block = saved_static_init;- self.flags.in_class_field_initializer = saved_field_init;- self.flags.new_target_is_valid = saved_new_target;-- insights.might_need_arguments_object = self.flags.function_might_need_arguments_object;- self.flags.function_might_need_arguments_object = saved_might_need_arguments;-- // Class constructors always bind `this`. Derived constructors need a function- // environment for it, since super() binds it there; base constructors bind it like- // other functions do (OrdinaryCallBindThis), and only need one if something in them- // does.- if method_kind == MethodKind::Constructor {- insights.uses_this = true;- if self.class_has_super_class {- insights.uses_this_from_environment = true;- }- }-- let nested_function_ids = self.pop_function_context();- let function_id = self.insert_function_data(FunctionData {- name: None,- source_text_start: function_start.offset,- source_text_end: self.source_text_end_offset(),- body: Box::new(body),- parameters: parsed.parameters,- function_length: parsed.function_length,- kind: fn_kind,- is_strict_mode: self.flags.strict_mode || has_use_strict,- is_arrow_function: false,- parsing_insights: insights,- nested_function_ids: Some(nested_function_ids),- });- self.expression(start, ExpressionKind::Function(function_id))- }-}--fn hex_digit(c: u16) -> Option<u16> {- match c {- 0x30..=0x39 => Some(c - 0x30),- 0x41..=0x46 => Some(c - 0x41 + 10),- 0x61..=0x66 => Some(c - 0x61 + 10),- _ => None,- }-}--fn is_octal_char(c: u16) -> bool {- c >= ch(b'0') && c <= ch(b'7')-}--fn parse_octal_escape(inner: &[u16], i: usize) -> (u16, usize) {- let first = (inner[i] - ch(b'0')) as u32;- let mut value = first;- let mut consumed = 0;-- if i + 1 < inner.len() && is_octal_char(inner[i + 1]) {- value = value * 8 + (inner[i + 1] - ch(b'0')) as u32;- consumed = 1;-- if i + 2 < inner.len() && is_octal_char(inner[i + 2]) && first <= 3 {- value = value * 8 + (inner[i + 2] - ch(b'0')) as u32;- consumed = 2;- }- }- (value as u16, consumed)-}--fn parse_hex_escape(raw: &[u16], i: usize) -> Option<(usize, u16)> {- if i + 2 >= raw.len() {- return None;- }- let high = hex_digit(raw[i + 1])?;- let low = hex_digit(raw[i + 2])?;- Some((2, high * 16 + low))-}--fn parse_unicode_escape(raw: &[u16], i: usize) -> Option<(usize, u32)> {- if i + 1 >= raw.len() {- return None;- }- if raw[i + 1] == ch(b'{') {- let mut j = i + 2;- let mut value: u32 = 0;- let mut digits = 0;- while j < raw.len() && raw[j] != ch(b'}') {- let d = hex_digit(raw[j])? as u32;- value = value * 16 + d;- if value > 0x10FFFF {- return None;- }- digits += 1;- j += 1;- }- if j >= raw.len() || digits == 0 {- return None;- }- Some((j - i, value))- } else {- if i + 4 >= raw.len() {- return None;- }- let d0 = hex_digit(raw[i + 1])? as u32;- let d1 = hex_digit(raw[i + 2])? as u32;- let d2 = hex_digit(raw[i + 3])? as u32;- let d3 = hex_digit(raw[i + 4])? as u32;- Some((4, (d0 << 12) | (d1 << 8) | (d2 << 4) | d3))- }-}--fn push_code_point(result: &mut Vec<u16>, code_point: u32) {- if code_point > 0xFFFF {- let adjusted = code_point - 0x10000;- result.push((0xD800 | ((adjusted >> 10) & 0x3FF)) as u16);- result.push((0xDC00 | (adjusted & 0x3FF)) as u16);- } else {- result.push(code_point as u16);- }-}--fn raw_template_value(raw: &[u16]) -> Utf16String {- let mut result = Utf16String(Vec::with_capacity(raw.len()));- let mut i = 0;- while i < raw.len() {- if raw[i] == ch(b'\r') {- result.0.push(ch(b'\n'));- if i + 1 < raw.len() && raw[i + 1] == ch(b'\n') {- i += 1;- }- } else {- result.0.push(raw[i]);- }- i += 1;- }- result-}--fn token_to_binary_op(tt: TokenType) -> BinaryOp {- match tt {- TokenType::Plus => BinaryOp::Addition,- TokenType::Minus => BinaryOp::Subtraction,- TokenType::Asterisk => BinaryOp::Multiplication,- TokenType::Slash => BinaryOp::Division,- TokenType::Percent => BinaryOp::Modulo,- TokenType::DoubleAsterisk => BinaryOp::Exponentiation,- TokenType::EqualsEqualsEquals => BinaryOp::StrictlyEquals,- TokenType::ExclamationMarkEqualsEquals => BinaryOp::StrictlyInequals,- TokenType::EqualsEquals => BinaryOp::LooselyEquals,- TokenType::ExclamationMarkEquals => BinaryOp::LooselyInequals,- TokenType::GreaterThan => BinaryOp::GreaterThan,- TokenType::GreaterThanEquals => BinaryOp::GreaterThanEquals,- TokenType::LessThan => BinaryOp::LessThan,- TokenType::LessThanEquals => BinaryOp::LessThanEquals,- TokenType::Ampersand => BinaryOp::BitwiseAnd,- TokenType::Pipe => BinaryOp::BitwiseOr,- TokenType::Caret => BinaryOp::BitwiseXor,- TokenType::ShiftLeft => BinaryOp::LeftShift,- TokenType::ShiftRight => BinaryOp::RightShift,- TokenType::UnsignedShiftRight => BinaryOp::UnsignedRightShift,- TokenType::In => BinaryOp::In,- TokenType::Instanceof => BinaryOp::InstanceOf,- _ => unreachable!("unexpected token {:?} in binary expression", tt),- }-}--fn token_to_assignment_op(tt: TokenType) -> AssignmentOp {- match tt {- TokenType::Equals => AssignmentOp::Assignment,- TokenType::PlusEquals => AssignmentOp::AdditionAssignment,- TokenType::MinusEquals => AssignmentOp::SubtractionAssignment,- TokenType::AsteriskEquals => AssignmentOp::MultiplicationAssignment,- TokenType::SlashEquals => AssignmentOp::DivisionAssignment,- TokenType::PercentEquals => AssignmentOp::ModuloAssignment,- TokenType::DoubleAsteriskEquals => AssignmentOp::ExponentiationAssignment,- TokenType::AmpersandEquals => AssignmentOp::BitwiseAndAssignment,- TokenType::PipeEquals => AssignmentOp::BitwiseOrAssignment,- TokenType::CaretEquals => AssignmentOp::BitwiseXorAssignment,- TokenType::ShiftLeftEquals => AssignmentOp::LeftShiftAssignment,- TokenType::ShiftRightEquals => AssignmentOp::RightShiftAssignment,- TokenType::UnsignedShiftRightEquals => AssignmentOp::UnsignedRightShiftAssignment,- TokenType::DoubleAmpersandEquals => AssignmentOp::AndAssignment,- TokenType::DoublePipeEquals => AssignmentOp::OrAssignment,- TokenType::DoubleQuestionMarkEquals => AssignmentOp::NullishAssignment,- _ => unreachable!("unexpected token {:?} in assignment expression", tt),- }-}--pub(crate) fn parse_numeric_value(value: &[u16]) -> f64 {- let s: String = value- .iter()- .filter(|&&c| c != '_' as u16)- .map(|&c| c as u8 as char)- .collect();-- if s.starts_with("0x") || s.starts_with("0X") {- parse_integer_with_radix(&s[2..], 16)- } else if s.starts_with("0o") || s.starts_with("0O") {- parse_integer_with_radix(&s[2..], 8)- } else if s.starts_with("0b") || s.starts_with("0B") {- parse_integer_with_radix(&s[2..], 2)- } else if s.starts_with('0') && s.len() > 1 && s.as_bytes()[1].is_ascii_digit() {- let digits = &s[1..];- if digits.bytes().all(|b| (b'0'..=b'7').contains(&b)) {- parse_integer_with_radix(digits, 8)- } else {- s.parse::<f64>().unwrap_or(f64::NAN)- }- } else {- s.parse::<f64>().unwrap_or(f64::NAN)- }-}--fn parse_integer_with_radix(digits: &str, radix: u32) -> f64 {- if let Ok(v) = u64::from_str_radix(digits, radix) {- return v as f64;- }- let mut result: f64 = 0.0;- for ch in digits.chars() {- let digit = ch.to_digit(radix);- if let Some(d) = digit {- result = result * (radix as f64) + (d as f64);- }- }- result-}diff --git a/Libraries/LibJS/Rust/src/parser/statements.rs b/Libraries/LibJS/Rust/src/parser/statements.rsdeleted file mode 100644index adb6d34bdec..00000000000--- a/Libraries/LibJS/Rust/src/parser/statements.rs+++ /dev/null@@ -1,1085 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Statement parsing: if, for, while, switch, try, etc.--use crate::fast_hash::HashSet;--use crate::ast::*;-use crate::parser::Associativity;-use crate::parser::ForbiddenTokens;-use crate::parser::PRECEDENCE_COMMA;-use crate::parser::Parser;-use crate::parser::Position;-use crate::parser::collect_binding_names;-use crate::parser::is_strict_reserved_word;-use crate::parser::is_unconditional_reserved_word;-use crate::token::TokenType;--/// Used locally during for-statement parsing before converting to `ast::ForInit`.-enum LocalForInit {- Declaration(Statement),- Expression(Expression),-}--impl Parser<'_> {- pub(crate) fn parse_statement(&mut self, allow_labelled_function: bool) -> Statement {- if !self.enter_recursion() {- let start = self.position();- return self.statement(start, StatementKind::Error);- }- let statement = self.parse_statement_inner(allow_labelled_function);- self.leave_recursion();- statement- }-- fn parse_statement_inner(&mut self, allow_labelled_function: bool) -> Statement {- let start = self.position();- let tt = self.current_token_type();-- match tt {- TokenType::CurlyOpen => self.parse_block_statement(),- TokenType::Return => self.parse_return_statement(),- TokenType::Var => self.parse_variable_declaration(false),- TokenType::For => self.parse_for_statement(),- TokenType::If => self.parse_if_statement(),- TokenType::Throw => self.parse_throw_statement(),- TokenType::Try => self.parse_try_statement(),- TokenType::Break => self.parse_break_statement(),- TokenType::Continue => self.parse_continue_statement(),- TokenType::Switch => self.parse_switch_statement(),- TokenType::Do => self.parse_do_while_statement(),- TokenType::While => self.parse_while_statement(),- TokenType::With => {- if self.flags.strict_mode {- self.syntax_error("'with' statement not allowed in strict mode");- }- self.parse_with_statement()- }- TokenType::Debugger => self.parse_debugger_statement(),- TokenType::Semicolon => {- self.consume();- self.statement(start, StatementKind::Empty)- }- TokenType::Slash | TokenType::SlashEquals => {- let token = self.lexer.force_slash_as_regex();- self.current_token = token;- self.parse_expression_statement()- }- _ => {- if self.match_invalid_escaped_keyword() {- self.syntax_error("Keyword must not contain escaped characters");- }- if self.match_identifier_name()- && let Some(labelled) = self.try_parse_labelled_statement(allow_labelled_function)- {- return labelled;- }- if self.match_expression() {- self.parse_expression_statement()- } else {- self.expected("statement");- self.consume();- self.statement(start, StatementKind::Empty)- }- }- }- }-- pub(crate) fn parse_block_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::CurlyOpen);-- self.scope_collector.open_block_scope(None);-- let mut children = Vec::new();-- while !self.match_token(TokenType::CurlyClose) && !self.done() {- if self.match_declaration() {- children.push(self.parse_declaration());- } else {- children.push(self.parse_statement(true));- }- }-- self.consume_token(TokenType::CurlyClose);- let scope = self.make_scope(children);- let range = self.range_from(start);- self.arena.scopes[scope].source_range = Some(range);- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();- Statement::new(range, StatementKind::Block(scope))- }-- fn parse_expression_statement(&mut self) -> Statement {- let start = self.position();-- if self.match_token(TokenType::Async) {- let lookahead = self.next_token();- if lookahead.token_type == TokenType::Function && !lookahead.trivia_has_line_terminator {- self.syntax_error("Async function declaration not allowed in single-statement context");- }- } else if self.match_token(TokenType::Function) || self.match_token(TokenType::Class) {- let name = self.current_token.token_type.name();- self.syntax_error(&format!("{name} declaration not allowed in single-statement context"));- } else if self.match_token(TokenType::Let) && self.next_token().token_type == TokenType::BracketOpen {- self.syntax_error("let followed by [ is not allowed in single-statement context");- }-- let expression = self.parse_expression_any();- self.consume_or_insert_semicolon();- self.statement(start, StatementKind::Expression(Box::new(expression)))- }-- // https://tc39.es/ecma262/#sec-return-statement- // ReturnStatement : `return` [no LineTerminator here] Expression? `;`- fn parse_return_statement(&mut self) -> Statement {- let start = self.position();- if !self.flags.in_function_context {- self.syntax_error("'return' not allowed outside of a function");- }- self.consume_token(TokenType::Return);-- // [no LineTerminator here]: if a line terminator follows `return`,- // ASI inserts a semicolon and the return has no argument.- // NB: Don't consume the next token — it may be `;` which should- // become an EmptyStatement, not be swallowed by the return.- if self.current_token.trivia_has_line_terminator {- return self.statement(start, StatementKind::Return(None));- }- if self.match_token(TokenType::Semicolon) || self.match_token(TokenType::CurlyClose) || self.done() {- self.consume_or_insert_semicolon();- return self.statement(start, StatementKind::Return(None));- }-- let argument = self.parse_expression_any();- self.consume_or_insert_semicolon();- self.statement(start, StatementKind::Return(Some(Box::new(argument))))- }-- // https://tc39.es/ecma262/#sec-throw-statement- // ThrowStatement : `throw` [no LineTerminator here] Expression `;`- fn parse_throw_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Throw);-- // [no LineTerminator here]: unlike `return`, a line terminator after- // `throw` is always an error because `throw;` is never valid.- if self.current_token.trivia_has_line_terminator {- self.syntax_error("No line break is allowed between 'throw' and its expression");- }-- let argument = self.parse_expression_any();- self.consume_or_insert_semicolon();- self.statement(start, StatementKind::Throw(Box::new(argument)))- }-- // https://tc39.es/ecma262/#sec-break-statement- // BreakStatement : `break` [no LineTerminator here] LabelIdentifier? `;`- fn parse_break_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Break);-- let label = if self.match_token(TokenType::Semicolon) {- self.consume();- None- } else if !self.current_token.trivia_has_line_terminator- && !self.match_token(TokenType::CurlyClose)- && !self.done()- && self.match_identifier()- {- let token = self.consume();- let label_value = Utf16String::from(self.token_value(&token));-- if !self.labels_in_scope.contains_key(label_value.as_slice()) {- let label_str = String::from_utf16_lossy(&label_value);- self.syntax_error(&format!("Label '{label_str}' not found"));- }-- self.consume_or_insert_semicolon();- Some(label_value)- } else {- self.consume_or_insert_semicolon();- None- };-- if label.is_none() && !self.flags.in_break_context {- self.syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");- }-- self.statement(start, StatementKind::Break { target_label: label })- }-- // https://tc39.es/ecma262/#sec-continue-statement- // ContinueStatement : `continue` [no LineTerminator here] LabelIdentifier? `;`- fn parse_continue_statement(&mut self) -> Statement {- let start = self.position();- if !self.flags.in_continue_context {- self.syntax_error("'continue' not allowed outside of a loop");- }- self.consume_token(TokenType::Continue);-- let label = if self.match_token(TokenType::Semicolon) {- None- } else if !self.current_token.trivia_has_line_terminator- && !self.match_token(TokenType::CurlyClose)- && !self.done()- && self.match_identifier()- {- let label_line = self.current_token.line_number;- let label_col = self.current_token.line_column;- let token = self.consume();- let label_value = Utf16String::from(self.token_value(&token));-- if let Some(entry) = self.labels_in_scope.get_mut(label_value.as_slice()) {- *entry = Some((label_line, label_col));- } else {- let label_str = String::from_utf16_lossy(&label_value);- self.syntax_error(&format!("Label '{label_str}' not found or invalid"));- }-- Some(label_value)- } else {- None- };-- self.consume_or_insert_semicolon();-- self.statement(start, StatementKind::Continue { target_label: label })- }-- fn parse_debugger_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Debugger);- self.consume_or_insert_semicolon();- self.statement(start, StatementKind::Debugger)- }-- fn parse_if_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::If);- self.consume_token(TokenType::ParenOpen);- let predicate = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);-- // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses- // Annex B allows FunctionDeclarations (but NOT GeneratorDeclarations) in- // IfStatement bodies in sloppy mode.- let consequent = if !self.flags.strict_mode- && self.match_token(TokenType::Function)- && self.next_token().token_type != TokenType::Asterisk- {- self.parse_function_declaration_as_block_statement(start)- } else {- self.parse_statement(false)- };-- let alternate = if self.match_token(TokenType::Else) {- self.consume();- if !self.flags.strict_mode- && self.match_token(TokenType::Function)- && self.next_token().token_type != TokenType::Asterisk- {- Some(Box::new(self.parse_function_declaration_as_block_statement(start)))- } else {- Some(Box::new(self.parse_statement(false)))- }- } else {- None- };-- self.statement(- start,- StatementKind::If(Box::new(IfStatementData {- test: Box::new(predicate),- consequent: Box::new(consequent),- alternate,- })),- )- }-- /// Annex B: Parse a function declaration as if wrapped in a synthetic block.- /// See https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses- fn parse_function_declaration_as_block_statement(&mut self, if_start: Position) -> Statement {- // C++ uses rule_start from the enclosing if-statement for the block position.- let start = if_start;- self.scope_collector.open_block_scope(None);- let declaration = self.parse_function_declaration();- let scope = self.make_scope(vec![declaration]);- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();- self.statement(start, StatementKind::Block(scope))- }-- /// Parse a statement in a loop body context (break and continue allowed).- fn parse_loop_body(&mut self) -> Statement {- let break_before = self.flags.in_break_context;- let continue_before = self.flags.in_continue_context;- self.flags.in_break_context = true;- self.flags.in_continue_context = true;- let body = self.parse_statement(false);- self.flags.in_break_context = break_before;- self.flags.in_continue_context = continue_before;- body- }-- fn parse_while_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::While);- self.consume_token(TokenType::ParenOpen);- let test = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);-- let body = self.parse_loop_body();-- self.statement(- start,- StatementKind::While(Box::new(WhileStatementData {- test: Box::new(test),- body: Box::new(body),- })),- )- }-- fn parse_do_while_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Do);-- let body = self.parse_loop_body();-- self.consume_token(TokenType::While);- self.consume_token(TokenType::ParenOpen);- let test = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);-- // Since ES 2015 a missing semicolon is inserted here, despite- // the regular ASI rules not applying.- self.eat(TokenType::Semicolon);-- self.statement(- start,- StatementKind::DoWhile(Box::new(WhileStatementData {- test: Box::new(test),- body: Box::new(body),- })),- )- }-- // https://tc39.es/ecma262/#sec-for-statement- // https://tc39.es/ecma262/#sec-for-in-and-for-of-statements- fn parse_for_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::For);-- // Open for-loop scope (for let/const/using declarations).- // scope_data set after the for-loop body is parsed.- self.scope_collector.open_for_loop_scope(None);-- let is_await = if self.match_token(TokenType::Await) {- if !self.flags.await_expression_is_valid {- self.syntax_error("for-await-of not allowed outside of async context");- }- self.consume();- self.scope_collector.set_contains_await_expression();- true- } else {- false- };-- self.consume_token(TokenType::ParenOpen);-- if self.match_token(TokenType::Semicolon) && !is_await {- self.consume();- let result = self.parse_standard_for_loop(start, None);- return self.close_for_loop_scope(start, result);- }-- let init_start = self.position();- let init_starts_with_async_keyword = self.match_token(TokenType::Async);- let is_var_init = self.match_token(TokenType::Var);- let is_await_using = self.match_await_using_declaration();- let is_using = is_await_using || self.match_for_using_declaration();- let is_let = self.match_token(TokenType::Let) && (self.flags.strict_mode || self.try_match_let_declaration());- let is_declaration = is_var_init || is_using || is_let || self.match_token(TokenType::Const);- let init = if is_using {- LocalForInit::Declaration(self.parse_using_declaration(true, is_await_using))- } else if is_declaration {- LocalForInit::Declaration(self.parse_variable_declaration(true))- } else {- let forbidden = ForbiddenTokens::with_in();- LocalForInit::Expression(self.parse_expression(PRECEDENCE_COMMA, Associativity::Right, forbidden))- };-- // Check for in- // https://tc39.es/ecma262/#sec-for-in-and-for-of-statements- // It is a Syntax Error if IsDestructuring of ForBinding is false and- // Initializer is present. (Only a single, non-initialized ForBinding- // is allowed; except in Annex B sloppy var with one declarator.)- if self.match_token(TokenType::In) && !is_await {- // C++ captures ForInStatement position at the `in` keyword.- let forin_start = self.position();- if is_using {- self.syntax_error("Using declaration not allowed in for-in loop");- } else if is_declaration {- if self.for_loop_declaration_count > 1 {- self.syntax_error("Multiple declarations not allowed in for..in/of");- }- if self.for_loop_declaration_has_init {- // https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads- // Annex B: In sloppy mode, a single `var` with a simple- // BindingIdentifier and an initializer is permitted.- // Binding patterns with initializers are never allowed.- if !self.for_loop_declaration_is_var- || self.for_loop_declaration_count != 1- || self.flags.strict_mode- || self.for_loop_declaration_is_pattern- {- self.syntax_error("Variable initializer not allowed in for..in/of");- }- }- } else {- self.validate_for_in_of_lhs(&init);- }- self.consume();- let rhs = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);-- let body = self.parse_loop_body();-- let lhs = self.synthesize_for_in_of_lhs(init, init_start);- let result = self.statement(- forin_start,- StatementKind::ForInOf(Box::new(ForInOfStatementData {- kind: ForInOfKind::ForIn,- lhs,- rhs: Box::new(rhs),- body: Box::new(body),- })),- );- return self.close_for_loop_scope(start, result);- }-- // Check for of (keyword must not contain escapes)- if self.match_identifier_name() {- let value = self.token_original_value(&self.current_token);- if value == utf16!("of") {- // C++ captures ForOfStatement position at the `of` keyword.- let forof_start = self.position();- if is_declaration {- if self.for_loop_declaration_count > 1 {- self.syntax_error("Multiple declarations not allowed in for..in/of");- }- if self.for_loop_declaration_has_init {- self.syntax_error("Variable initializer not allowed in for..of");- }- } else {- self.validate_for_in_of_lhs(&init);- // https://tc39.es/ecma262/#sec-for-in-and-for-of-statements- // The ordinary for-of grammar excludes `async of`, while the for-await-of grammar only excludes- // `let`, so escaped identifiers (e.g. `\u0061sync`) and `for await (async of ...)` are valid here.- if !is_await- && init_starts_with_async_keyword- && let LocalForInit::Expression(ref expression) = init- && let ExpressionKind::Identifier(ident) = expression.inner- && self.arena.name_of(ident).as_slice() == utf16!("async")- {- self.syntax_error("for-of statement may not use 'async' as the left-hand side");- }- // https://tc39.es/ecma262/#sec-for-in-and-for-of-statements- if let LocalForInit::Expression(ref expression) = init- && let ExpressionKind::Member(ref data) = expression.inner- && let ExpressionKind::Identifier(ident) = data.object.inner- && self.arena.name_of(ident).as_slice() == utf16!("let")- {- self.syntax_error("For of statement may not start with let.");- }- }- self.consume();- let rhs = self.parse_assignment_expression();- self.consume_token(TokenType::ParenClose);-- let body = self.parse_loop_body();-- let lhs = self.synthesize_for_in_of_lhs(init, init_start);- let for_of_kind = if is_await {- ForInOfKind::ForAwaitOf- } else {- ForInOfKind::ForOf- };- let result = self.statement(- forof_start,- StatementKind::ForInOf(Box::new(ForInOfStatementData {- kind: for_of_kind,- lhs,- rhs: Box::new(rhs),- body: Box::new(body),- })),- );- return self.close_for_loop_scope(start, result);- }- }-- // Standard for loop — const requires initializer.- if let LocalForInit::Declaration(ref declaration) = init- && let StatementKind::VariableDeclaration(ref vd) = declaration.inner- && vd.kind == DeclarationKind::Const- {- for d in &vd.declarations {- if d.init.is_none() {- self.syntax_error("Missing initializer in const declaration");- }- }- }- if let LocalForInit::Declaration(ref declaration) = init- && let StatementKind::UsingDeclaration(ref using_declaration) = declaration.inner- && using_declaration.declarations.iter().any(|d| d.init.is_none())- {- self.syntax_error("Missing initializer in using declaration");- }- if is_await {- // https://tc39.es/ecma262/#prod-ForInOfStatement- // `for await` only has `of` productions.- self.syntax_error("for-await-of statement must use 'of'");- }- self.consume_token(TokenType::Semicolon);- let for_init = match init {- LocalForInit::Declaration(declaration) => Some(ForInit::Declaration(Box::new(declaration))),- LocalForInit::Expression(expression) => Some(ForInit::Expression(Box::new(expression))),- };- let result = self.parse_standard_for_loop(start, for_init);- self.close_for_loop_scope(start, result)- }-- /// Close the for-loop scope and wrap the for-loop statement in a Block- /// with scope data.- fn close_for_loop_scope(&mut self, start: Position, inner: Statement) -> Statement {- let scope = self.make_scope(vec![inner]);- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();- self.statement(start, StatementKind::Block(scope))- }-- fn parse_standard_for_loop(&mut self, start: Position, init: Option<ForInit>) -> Statement {- let test = if self.match_token(TokenType::Semicolon) {- None- } else {- Some(Box::new(self.parse_expression_any()))- };- self.consume_token(TokenType::Semicolon);-- let update = if self.match_token(TokenType::ParenClose) {- None- } else {- Some(Box::new(self.parse_expression_any()))- };- self.consume_token(TokenType::ParenClose);-- let body = self.parse_loop_body();-- self.statement(- start,- StatementKind::For(Box::new(ForStatementData {- init,- test,- update,- body: Box::new(body),- })),- )- }-- // https://tc39.es/ecma262/#sec-with-statement- // NOTE: The with statement is forbidden in strict mode code.- fn parse_with_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::With);- self.consume_token(TokenType::ParenOpen);- let object = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);- self.scope_collector.open_with_scope(None);- let body = self.parse_statement(false);- self.scope_collector.close_scope();- self.statement(- start,- StatementKind::With(Box::new(WithStatementData {- object: Box::new(object),- body: Box::new(body),- })),- )- }-- // https://tc39.es/ecma262/#sec-switch-statement- // All case clauses in a switch statement share a single block scope.- fn parse_switch_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Switch);- self.consume_token(TokenType::ParenOpen);- let discriminant = self.parse_expression_any();- self.consume_token(TokenType::ParenClose);-- self.consume_token(TokenType::CurlyOpen);-- self.scope_collector.open_block_scope(None);-- let break_before = self.flags.in_break_context;- self.flags.in_break_context = true;-- let mut cases = Vec::new();- let mut has_default = false;- while !self.match_token(TokenType::CurlyClose) && !self.done() {- let case = self.parse_switch_case();- if case.test.is_none() {- if has_default {- self.syntax_error("Multiple 'default' clauses in switch statement");- }- has_default = true;- }- cases.push(case);- }-- self.flags.in_break_context = break_before;-- self.consume_token(TokenType::CurlyClose);-- let scope = self.make_empty_scope();- self.scope_collector.set_scope_node(scope);- self.scope_collector.close_scope();-- self.statement(- start,- StatementKind::Switch(Box::new(SwitchStatementData {- scope,- discriminant: Box::new(discriminant),- cases,- })),- )- }-- fn parse_switch_case(&mut self) -> SwitchCase {- let start = self.position();- let test = if self.match_token(TokenType::Case) {- self.consume();- Some(self.parse_expression_any())- } else if self.match_token(TokenType::Default) {- self.consume();- None- } else {- self.expected("'case' or 'default'");- None- };-- self.consume_token(TokenType::Colon);-- let mut children = Vec::new();- while !self.match_token(TokenType::CurlyClose)- && !self.match_token(TokenType::Case)- && !self.match_token(TokenType::Default)- && !self.done()- {- if self.match_declaration() {- let declaration = self.parse_declaration();- // https://tc39.es/ecma262/#sec-switch-statement-static-semantics-early-errors- // CaseClause : `case` Expression `:` StatementList- // DefaultClause : `default` `:` StatementList- // - It is a Syntax Error if ContainsUsing of StatementList is true.- if matches!(declaration.inner, StatementKind::UsingDeclaration(_)) {- self.syntax_error_at_position(- "'using' declarations are not allowed directly in a case or default clause",- declaration.range.start,- );- }- children.push(declaration);- } else {- children.push(self.parse_statement(true));- }- }-- SwitchCase {- range: self.range_from(start),- scope: self.make_scope(children),- test,- }- }-- // https://tc39.es/ecma262/#sec-try-statement- // TryStatement :- // `try` Block Catch- // `try` Block Finally- // `try` Block Catch Finally- fn parse_try_statement(&mut self) -> Statement {- let start = self.position();- self.consume_token(TokenType::Try);-- let block = self.parse_block_statement();-- let handler = if self.match_token(TokenType::Catch) {- Some(self.parse_catch_clause())- } else {- None- };-- let finalizer = if self.match_token(TokenType::Finally) {- self.consume();- Some(Box::new(self.parse_block_statement()))- } else {- None- };-- if handler.is_none() && finalizer.is_none() {- self.syntax_error("try statement must have a catch or finally clause");- }-- self.statement(- start,- StatementKind::Try(Box::new(TryStatementData {- block: Box::new(block),- handler,- finalizer,- })),- )- }-- // https://tc39.es/ecma262/#sec-try-statement- // Catch : `catch` `(` CatchParameter `)` Block- // | `catch` Block- // The catch parameter creates its own scope that wraps the block body.- fn parse_catch_clause(&mut self) -> CatchClause {- let start = self.position();- self.consume_token(TokenType::Catch);-- self.scope_collector.open_catch_scope();-- let mut catch_pattern_names: Vec<StringId> = Vec::new();- let parameter = if self.match_token(TokenType::ParenOpen) {- self.consume();- let parameter = if self.match_token(TokenType::CurlyOpen) || self.match_token(TokenType::BracketOpen) {- let pattern = self.parse_binding_pattern();- let pattern_bound_names = std::mem::take(&mut self.pattern_bound_names);- // Materialize Utf16Strings for slice-based scope-collector calls.- let names_to_check: Vec<Utf16String> = pattern_bound_names- .iter()- .map(|(n, _)| self.arena.strings[*n].clone())- .collect();- // https://tc39.es/ecma262/#sec-try-statement-static-semantics-early-errors- // It is a Syntax Error if BoundNames of CatchParameter- // contains any duplicate elements.- {- let mut seen: HashSet<&[u16]> = HashSet::default();- for name in &names_to_check {- if !seen.insert(name.as_slice()) {- let name_str = String::from_utf16_lossy(name);- self.syntax_error(&format!("Duplicate binding '{name_str}' in catch parameter"));- }- }- }- for name in &names_to_check {- self.check_identifier_name_for_assignment_validity(name.as_slice(), false);- }- let bound_names: Vec<&[u16]> = names_to_check.iter().map(|n| n.as_slice()).collect();- self.scope_collector.add_catch_parameter_pattern(&bound_names);- // Register each binding pattern identifier for scope analysis- // so they get is_local() annotations (matching variable declarations).- let pattern_bound_ids: Vec<IdentifierId> = pattern_bound_names.iter().map(|(_, id)| *id).collect();- catch_pattern_names = pattern_bound_names.iter().map(|(n, _)| *n).collect();- let Self {- scope_collector, arena, ..- } = self;- for id in pattern_bound_ids {- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- Some(CatchBinding::BindingPattern(pattern))- } else if self.match_identifier() {- let parameter_start = self.position();- let token = self.consume();- let value = self.token_value(&token).to_vec();- self.check_identifier_name_for_assignment_validity(&value, false);- let name = self.token_identifier_name(&token);- let id = self- .arena- .identifiers- .insert(Identifier::new(self.range_from(parameter_start), name));- let Self {- scope_collector, arena, ..- } = self;- scope_collector.register_identifier(- id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- scope_collector.add_catch_parameter_identifier(&value);- Some(CatchBinding::Identifier(id))- } else {- self.expected("catch parameter");- None- };- self.consume_token(TokenType::ParenClose);- parameter- } else {- None- };-- // Collect catch parameter names (as StringIds) for post-body validation.- let catch_names: Vec<StringId> = match ¶meter {- Some(CatchBinding::Identifier(id)) => vec![self.arena.identifiers[*id].name],- Some(CatchBinding::BindingPattern(_)) => catch_pattern_names,- None => Vec::new(),- };-- let body = self.parse_block_statement();-- // https://tc39.es/ecma262/#sec-try-statement-static-semantics-early-errors- // It is a Syntax Error if any element of the BoundNames of- // CatchParameter also occurs in the LexicallyDeclaredNames of Block.- if !catch_names.is_empty()- && let StatementKind::Block(scope_id) = body.inner- {- let mut lexically_declared_names: HashSet<Utf16String> = HashSet::default();- for child in &self.arena.scopes[scope_id].children {- match &child.inner {- StatementKind::VariableDeclaration(vd) if vd.kind != DeclarationKind::Var => {- for decl in &vd.declarations {- collect_binding_names(&decl.target, &mut lexically_declared_names, &self.arena);- }- }- StatementKind::UsingDeclaration(data) => {- for decl in &data.declarations {- collect_binding_names(&decl.target, &mut lexically_declared_names, &self.arena);- }- }- StatementKind::FunctionDeclaration(fd) => {- if let Some(id) = fd.name {- lexically_declared_names.insert(self.arena.name_of(id).clone());- }- }- StatementKind::ClassDeclaration(data) => {- if let Some(id) = data.name {- lexically_declared_names.insert(self.arena.name_of(id).clone());- }- }- _ => {}- }- }- for cn in &catch_names {- let name = &self.arena.strings[*cn];- if lexically_declared_names.contains(name) {- let n = String::from_utf16_lossy(name.as_slice());- self.syntax_error(&format!("Identifier '{n}' already declared as catch parameter"));- }- }- }-- self.scope_collector.close_scope();-- CatchClause {- range: self.range_from(start),- parameter,- body: Box::new(body),- }- }-- // https://tc39.es/ecma262/#sec-labelled-statements- // It is a Syntax Error if any source text is matched by this production- // and a `continue` statement with label targets that production.- // (i.e., `continue` with a label can only target an iteration statement.)- fn try_parse_labelled_statement(&mut self, allow_labelled_function: bool) -> Option<Statement> {- let start = self.position();-- if !self.match_identifier_name() {- return None;- }-- self.save_state();- let token = self.consume();- let label = Utf16String::from(self.token_value(&token));-- if !self.match_token(TokenType::Colon) {- self.load_state();- return None;- }- self.discard_saved_state();- self.consume(); // consume :-- // https://tc39.es/ecma262/#sec-identifiers- // LabelIdentifier[Yield, Await] : Identifier- // Identifier : IdentifierName but not ReservedWord- if is_unconditional_reserved_word(&label) {- self.syntax_error("Reserved word cannot be used as a label");- }-- if self.flags.strict_mode && (label == utf16!("let") || is_strict_reserved_word(&label)) {- self.syntax_error("Strict mode reserved word is not allowed in label");- }- if self.flags.in_generator_function_context && label == utf16!("yield") {- self.syntax_error("'yield' label is not allowed in generator function context");- }- if (self.flags.await_expression_is_valid- || self.flags.in_class_static_init_block- || self.program_type == crate::parser::ProgramType::Module)- && label == utf16!("await")- {- self.syntax_error("'await' is not allowed as a label in this context");- }-- if self.labels_in_scope.contains_key(label.as_slice()) {- let label_str = String::from_utf16_lossy(&label);- self.syntax_error(&format!("Label '{label_str}' has already been declared"));- }-- if self.match_token(TokenType::Function) && (!allow_labelled_function || self.flags.strict_mode) {- self.syntax_error("Not allowed to declare a function here");- }- if self.match_token(TokenType::Async) {- let next = self.next_token();- if next.token_type == TokenType::Function && !next.trivia_has_line_terminator {- self.syntax_error("Async functions cannot be defined in labelled statements");- }- }-- self.labels_in_scope.insert(label.clone(), None);-- let break_before = self.flags.in_break_context;- self.flags.in_break_context = true;-- let body_starts_iteration = self.match_iteration_start();- self.last_inner_label_is_iteration = false;- let body = if self.match_token(TokenType::Function) {- let function_start = self.position();- let fn_decl = self.parse_function_declaration();- if let StatementKind::FunctionDeclaration(ref fd) = fn_decl.inner {- if let Some(name) = fd.name {- let name = self.arena.name_of(name).clone();- self.scope_collector.check_labelled_function_declaration(- name.as_slice(),- function_start.line,- function_start.column,- );- }- match fd.kind {- FunctionKind::Generator | FunctionKind::AsyncGenerator => {- self.syntax_error("Generator functions cannot be defined in labelled statements");- }- FunctionKind::Async => {- self.syntax_error("Async functions cannot be defined in labelled statements");- }- _ => {}- }- }- fn_decl- } else {- self.parse_statement(allow_labelled_function)- };-- let is_iteration = body_starts_iteration || self.last_inner_label_is_iteration;- if !is_iteration && let Some(Some((line, col))) = self.labels_in_scope.get(label.as_slice()) {- self.syntax_error_at(- "labelled continue statement cannot use non iterating statement",- *line,- *col,- );- }-- self.labels_in_scope.remove(label.as_slice());- self.flags.in_break_context = break_before;- self.last_inner_label_is_iteration = is_iteration;-- Some(self.statement(- start,- StatementKind::Labelled(Box::new(LabelledStatementData {- label,- item: Box::new(body),- })),- ))- }-- fn match_for_using_declaration(&mut self) -> bool {- if !self.match_token(TokenType::Identifier) {- return false;- }- if self.token_value(&self.current_token) != utf16!("using") {- return false;- }- let (next, after_next) = self.next_two_tokens();- if next.trivia_has_line_terminator {- return false;- }- if next.token_type == TokenType::Identifier {- let next_val = self.token_original_value(&next);- // NB: The `using of` lookahead restriction only applies to for-of and for-await-of, so `for (using of =- // null;;)` declares a binding named `of`.- if next_val == utf16!("of") {- return after_next.token_type == TokenType::Equals;- }- }- // Must be an actual identifier, not just an identifier-name keyword- // like `in`. This matches C++ token_is_identifier().- self.token_is_identifier(&next)- }-- /// Validate that an expression-form LHS is valid for for-in/for-of.- fn validate_for_in_of_lhs(&mut self, init: &LocalForInit) {- if let LocalForInit::Expression(ref expression) = *init {- match &expression.inner {- // NewExpression is never a valid assignment target.- ExpressionKind::New(_) => {- self.syntax_error("Invalid left-hand side in for-loop");- }- // CallExpression is a valid assignment target only in non-strict mode (web compat).- ExpressionKind::Call(_) if self.flags.strict_mode => {- self.syntax_error("Invalid left-hand side in for-loop");- }- ExpressionKind::Identifier(_)- | ExpressionKind::Member(_)- | ExpressionKind::Call(_)- | ExpressionKind::Object(_)- | ExpressionKind::Array(_) => {}- _ => {- self.syntax_error("Invalid left-hand side in for-loop");- }- }- }- }-- /// Convert a `LocalForInit` into a `ForInOfLhs`, synthesizing a binding- /// pattern when the LHS is an array or object expression.- fn synthesize_for_in_of_lhs(&mut self, init: LocalForInit, init_start: Position) -> ForInOfLhs {- match init {- LocalForInit::Declaration(declaration) => ForInOfLhs::Declaration(Box::new(declaration)),- LocalForInit::Expression(expression) => {- if Self::is_array_expression(&expression) || Self::is_object_expression(&expression) {- let pattern = self.synthesize_binding_pattern(init_start);-- let bound_names = std::mem::take(&mut self.pattern_bound_names);- for (name, _id) in &bound_names {- let name_str = self.arena.strings[*name].clone();- self.check_identifier_name_for_assignment_validity(name_str.as_slice(), false);- }- let Self {- scope_collector, arena, ..- } = self;- for (_name, id) in &bound_names {- scope_collector.register_identifier(- *id,- None,- &mut arena.identifiers,- &arena.strings,- &mut arena.scopes,- );- }- ForInOfLhs::Pattern(pattern)- } else {- ForInOfLhs::Expression(Box::new(expression))- }- }- }- }-}diff --git a/Libraries/LibJS/Rust/src/scope_collector.rs b/Libraries/LibJS/Rust/src/scope_collector.rsdeleted file mode 100644index b6831ab321a..00000000000--- a/Libraries/LibJS/Rust/src/scope_collector.rs+++ /dev/null@@ -1,1548 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Scope analysis for the parser.-//!-//! This is a two-phase system:-//!-//! ## Phase 1: Build scope tree (during parsing)-//!-//! As the parser encounters scopes (functions, blocks, for-loops, etc.),-//! it calls `open_*_scope()` to push a `ScopeRecord` onto the tree, and-//! the scope is closed when parsing of the construct finishes. During-//! parsing, declarations and identifier references are registered:-//!-//! - `add_var_declaration()` — `var` bindings (hoist to function scope)-//! - `add_lexical_declaration()` — `let`/`const` (block-scoped)-//! - `add_function_declaration()` — function declarations (may Annex-B hoist)-//! - `register_identifier()` — any identifier reference-//!-//! ## Phase 2: Analyze (after parsing)-//!-//! `analyze()` walks the scope tree bottom-up and for each scope:-//!-//! 1. **Resolves identifiers**: matches identifier references to their-//! declarations (var, let/const, function, parameter, catch binding).-//! Unresolved identifiers are marked as global.-//!-//! 2. **Propagates eval poisoning**: if a scope contains a direct call-//! to `eval()`, all ancestor scopes must know (they can't optimize-//! away their environment records).-//!-//! 3. **Hoists functions (Annex B)**: in non-strict sloppy mode,-//! function declarations inside blocks can create `var` bindings-//! in the enclosing function scope.-//!-//! 4. **Builds local variable lists**: populates `FunctionScopeData`-//! on AST ScopeData nodes, enabling the bytecode generator-//! to use indexed locals.-//!-//! ## Key data structures-//!-//! - `ScopeRecord` — one scope (function, block, etc.) with its-//! variables, identifiers, and child scopes-//! - `ScopeVariable` — a declared name within a scope (flags track-//! whether it's var/lexical/function/catch/parameter)-//! - `IdentifierGroup` — a set of identifier references with the same-//! name within one scope (multiple `foo` refs are grouped together)--use crate::fast_hash::HashMap;-use crate::fast_hash::IndexMap;--use crate::ast::FunctionScopeData;-use crate::ast::IdentifierArena;-use crate::ast::IdentifierId;-use crate::ast::LocalBinding;-use crate::ast::LocalVarKind;-use crate::ast::LocalVariable;-use crate::ast::ScopeId;-use crate::ast::Statement;-use crate::ast::StringId;-use crate::ast::Utf16String;-use crate::ast::VarToInit;-use crate::parser::DeclarationKind;-use crate::parser::FunctionKind;-use crate::parser::ParseError;-use crate::parser::ProgramType;-use crate::u32_from_usize;--// === Enums ===--#[derive(Clone, Copy, PartialEq, Eq, Debug)]-pub enum ScopeType {- Function,- Program,- Block,- ForLoop,- With,- Catch,- ClassStaticInit,- ClassField,- ClassDeclaration,-}--#[derive(Clone, Copy, PartialEq, Eq, Debug)]-pub enum ScopeLevel {- NotTopLevel,- ScriptTopLevel,- ModuleTopLevel,- FunctionTopLevel,- StaticInitTopLevel,-}--impl ScopeLevel {- fn is_top_level(self) -> bool {- self != ScopeLevel::NotTopLevel- }-}--// === Variable flags ===-// Bit flags on ScopeVariable that track how a name was declared.-// A single name can accumulate multiple flags (e.g., a `var` that-// shadows a parameter gets both VAR and FORBIDDEN_LEXICAL).--#[derive(Clone, Copy, Debug, Default)]-struct VarFlags(u16);--impl VarFlags {- const EMPTY: Self = Self(0);- const VAR: Self = Self(1 << 0);- const LEXICAL: Self = Self(1 << 1);- const FUNCTION: Self = Self(1 << 2);- const CATCH_PARAMETER: Self = Self(1 << 3);- const FORBIDDEN_LEXICAL: Self = Self(1 << 4);- const FORBIDDEN_VAR: Self = Self(1 << 5);- const BOUND: Self = Self(1 << 6);- const PARAMETER_CANDIDATE: Self = Self(1 << 7);- const REFERENCED_IN_FORMAL_PARAMETERS: Self = Self(1 << 8);- const IMPORT: Self = Self(1 << 9);-- const fn intersects(self, other: Self) -> bool {- self.0 & other.0 != 0- }-}--impl std::ops::BitOr for VarFlags {- type Output = Self;- fn bitor(self, rhs: Self) -> Self {- Self(self.0 | rhs.0)- }-}--impl std::ops::BitOrAssign for VarFlags {- fn bitor_assign(&mut self, rhs: Self) {- self.0 |= rhs.0;- }-}--// === Data structures ===--/// A declared name within a scope. Multiple declaration forms can share-/// the same name (e.g., `var x` and `function x`), so flags are ORed together.-#[derive(Debug, Default)]-struct ScopeVariable {- /// Bit flags describing how this name was declared.- flags: VarFlags,- /// The local that references to this name in this scope resolve to (used to- /// build FunctionScopeData). None if not a local.- local: Option<LocalBinding>,-}--/// Groups all Identifier AST nodes that share the same name within a scope.-/// During analysis, the group is resolved to a local variable, parameter,-/// or propagated to the parent scope if unresolved.-#[derive(Debug)]-struct IdentifierGroup {- /// True if any identifier in this group is referenced from a nested- /// function (prevents local variable optimization).- captured_by_nested_function: bool,- /// True if any identifier in this group is inside a `with` block- /// (prevents local variable optimization since `with` can shadow anything).- used_inside_with_statement: bool,- /// All Identifier AST nodes with this name in this scope.- identifiers: Vec<IdentifierId>,- /// If this name was declared (var/let/const), tracks the declaration kind- /// so we can annotate each Identifier AST node.- declaration_kind: Option<DeclarationKind>,-}--/// A function to hoist via Annex B.3.3.-#[derive(Debug)]-struct HoistableFunction {- name: Utf16String,- /// Reference to the block ScopeData that contains the function declaration.- /// Used to set `is_hoisted = true` on the FunctionData when it's hoisted.- block_scope_data: Option<ScopeId>,-}--#[derive(Debug)]-struct ParameterName {- name: Utf16String,- is_rest: bool,-}--/// Entry describing a single parameter binding for scope analysis.-pub struct ParameterEntry {- pub name: Utf16String,- pub identifier: Option<IdentifierId>,- pub is_rest: bool,- pub is_from_pattern: bool,- pub is_first_from_pattern: bool,-}--#[derive(Debug)]-struct ScopeRecord {- scope_type: ScopeType,- scope_level: ScopeLevel,- scope_data: Option<ScopeId>,-- variables: IndexMap<Utf16String, ScopeVariable>,- identifier_groups: IndexMap<Utf16String, IdentifierGroup>,- functions_to_hoist: Vec<HoistableFunction>,-- // Parameter tracking- has_function_parameters: bool,- parameter_names: Vec<ParameterName>,-- // Flags- contains_access_to_arguments_object_in_non_strict_mode: bool,- contains_direct_call_to_eval: bool,- contains_await_expression: bool,- poisoned_by_eval_in_scope_chain: bool,- eval_in_current_function: bool,- uses_this_from_environment: bool,- uses_this: bool,- is_arrow_function: bool,- is_function_declaration: bool,- has_parameter_expressions: bool,-- // Tree (indices into ScopeCollector::records)- parent: Option<usize>,- top_level: Option<usize>,- children: Vec<usize>,-}--impl ScopeRecord {- fn new(scope_type: ScopeType, scope_level: ScopeLevel, scope_data: Option<ScopeId>) -> Self {- Self {- scope_type,- scope_level,- scope_data,- variables: IndexMap::default(),- identifier_groups: IndexMap::default(),- functions_to_hoist: Vec::new(),- has_function_parameters: false,- parameter_names: Vec::new(),- contains_access_to_arguments_object_in_non_strict_mode: false,- contains_direct_call_to_eval: false,- contains_await_expression: false,- poisoned_by_eval_in_scope_chain: false,- eval_in_current_function: false,- uses_this_from_environment: false,- uses_this: false,- is_arrow_function: false,- is_function_declaration: false,- has_parameter_expressions: false,- parent: None,- top_level: None,- children: Vec::new(),- }- }-- fn is_top_level(&self) -> bool {- self.scope_level.is_top_level()- }-- fn variable(&mut self, name: &[u16]) -> &mut ScopeVariable {- if !self.variables.contains_key(name) {- self.variables.insert(Utf16String::from(name), ScopeVariable::default());- }- self.variables.get_mut(name).unwrap()- }-- fn has_flag(&self, name: &[u16], flags: VarFlags) -> bool {- self.variables.get(name).is_some_and(|v| v.flags.intersects(flags))- }-- fn get_parameter_index(&self, name: &[u16]) -> Option<u32> {- // Iterate backwards to return the last parameter with the same name,- // matching the semantics of duplicate parameter names in non-strict mode.- for (i, param) in self.parameter_names.iter().enumerate().rev() {- if param.name == name {- return Some(u32_from_usize(i));- }- }- None- }-- fn has_rest_parameter_with_name(&self, name: &[u16]) -> bool {- self.parameter_names- .iter()- .any(|param| param.is_rest && param.name == name)- }-- fn has_hoistable_function_named(&self, name: &[u16]) -> bool {- self.functions_to_hoist.iter().any(|f| f.name == name)- }-}--/// Walk ancestor scopes starting from `start` (inclusive), following parent links.-fn ancestor_scopes(start: usize, records: &[ScopeRecord]) -> impl Iterator<Item = usize> + '_ {- std::iter::successors(Some(start), move |&i| records[i].parent)-}--fn last_function_scope(index: usize, records: &[ScopeRecord]) -> Option<usize> {- ancestor_scopes(index, records)- .find(|&i| records[i].scope_type == ScopeType::Function || records[i].scope_type == ScopeType::ClassStaticInit)-}--fn mark_hoisted_function_declarations(- statement: &mut Statement,- name: &[u16],- identifiers: &IdentifierArena,- strings: &crate::ast::StringInterner,-) {- if let Some(fd) = statement.inner.function_declaration_for_labelled_item_mut()- && fd.name.is_some_and(|n| strings[identifiers[n].name].as_slice() == name)- {- fd.is_hoisted = true;- }-}--// === ScopeCollector ===--/// Saved flags for a scope record, used to restore state after-/// speculative parsing (e.g. failed arrow function attempts).-struct SavedScopeFlags {- index: usize,- uses_this: bool,- uses_this_from_environment: bool,-}--pub struct ScopeCollectorState {- records_len: usize,- current: Option<usize>,- errors_len: usize,- /// Snapshot of propagatable flags on existing scope records.- /// During speculative parsing, set_uses_this() and set_uses_new_target()- /// propagate flags to ancestor function scopes. These changes must be- /// undone if the speculative parse fails.- saved_flags: Vec<SavedScopeFlags>,-}--pub struct ScopeCollector {- records: Vec<ScopeRecord>,- current: Option<usize>,- errors: Vec<ParseError>,-}--impl Default for ScopeCollector {- fn default() -> Self {- Self::new()- }-}--impl ScopeCollector {- pub fn new() -> Self {- Self {- records: Vec::new(),- current: None,- errors: Vec::new(),- }- }-- pub fn drain_errors(&mut self) -> Vec<ParseError> {- std::mem::take(&mut self.errors)- }-- fn already_declared_error(&mut self, name: &[u16], line: u32, column: u32) {- self.errors.push(ParseError {- message: format!("Identifier '{}' already declared", String::from_utf16_lossy(name)),- line,- column,- });- }-- pub fn has_errors(&self) -> bool {- !self.errors.is_empty()- }-- pub fn has_current_scope(&self) -> bool {- self.current.is_some()- }-- pub fn save_state(&self) -> ScopeCollectorState {- // Snapshot flags on ancestor function scopes that set_uses_this()- // and set_uses_new_target() might modify during speculative parsing.- let mut saved_flags = Vec::new();- if let Some(start) = self.current {- for index in ancestor_scopes(start, &self.records) {- if self.records[index].scope_type == ScopeType::Function {- saved_flags.push(SavedScopeFlags {- index,- uses_this: self.records[index].uses_this,- uses_this_from_environment: self.records[index].uses_this_from_environment,- });- }- }- }- ScopeCollectorState {- records_len: self.records.len(),- current: self.current,- errors_len: self.errors.len(),- saved_flags,- }- }-- pub fn load_state(&mut self, state: ScopeCollectorState) {- let saved_len = state.records_len;- self.records.truncate(saved_len);- self.current = state.current;- self.errors.truncate(state.errors_len);- // Remove any child indices that pointed to now-truncated records.- if let Some(current_index) = self.current {- self.records[current_index].children.retain(|&c| c < saved_len);- }- // Restore flags on ancestor function scopes that may have been- // modified by set_uses_this() or set_uses_new_target() during- // the speculative parse.- for saved in &state.saved_flags {- if saved.index < self.records.len() {- self.records[saved.index].uses_this = saved.uses_this;- self.records[saved.index].uses_this_from_environment = saved.uses_this_from_environment;- }- }- }-- // === Open/close scopes ===-- fn open_scope(&mut self, scope_type: ScopeType, scope_data: Option<ScopeId>, scope_level: ScopeLevel) {- let index = self.records.len();- let mut record = ScopeRecord::new(scope_type, scope_level, scope_data);- record.parent = self.current;-- if scope_type != ScopeType::Function- && record.scope_data.is_none()- && let Some(parent_index) = self.current- {- record.scope_data = self.records[parent_index].scope_data;- }-- if scope_level == ScopeLevel::NotTopLevel {- if let Some(parent_index) = self.current {- record.top_level = self.records[parent_index].top_level;- }- } else {- record.top_level = Some(index);- }-- self.records.push(record);- if let Some(parent_index) = self.current {- self.records[parent_index].children.push(index);- }- self.current = Some(index);- }-- pub fn close_scope(&mut self) {- let index = self.current.expect("close_scope with no current scope");-- if let Some(parent_index) = self.records[index].parent- && !self.records[index].has_function_parameters- {- let c = &self.records[index];- let arguments = c.contains_access_to_arguments_object_in_non_strict_mode;- let eval = c.contains_direct_call_to_eval;- let contains_await = c.contains_await_expression;- self.records[parent_index].contains_access_to_arguments_object_in_non_strict_mode |= arguments;- self.records[parent_index].contains_direct_call_to_eval |= eval;- self.records[parent_index].contains_await_expression |= contains_await;- }- // NB: An arrow function has no arguments object of its own, so the function it is in provides the one it uses.- // A direct eval in the arrow function can also reach it.- else if let Some(parent_index) = self.records[index].parent- && self.records[index].is_arrow_function- && (self.records[index].contains_access_to_arguments_object_in_non_strict_mode- || self.records[index].contains_direct_call_to_eval)- {- self.records[parent_index].contains_access_to_arguments_object_in_non_strict_mode = true;- }-- self.current = self.records[index].parent;- }-- pub fn open_program_scope(&mut self, program_type: ProgramType) {- let level = if program_type == ProgramType::Script {- ScopeLevel::ScriptTopLevel- } else {- ScopeLevel::ModuleTopLevel- };- self.open_scope(ScopeType::Program, None, level);- }-- pub fn open_function_scope(&mut self, function_name: Option<&[u16]>) {- self.open_scope(ScopeType::Function, None, ScopeLevel::FunctionTopLevel);- if let Some(name) = function_name {- let index = self.current.expect("no current scope");- self.records[index].variable(name).flags |= VarFlags::BOUND;- }- }-- pub fn open_block_scope(&mut self, scope_data: Option<ScopeId>) {- self.open_scope(ScopeType::Block, scope_data, ScopeLevel::NotTopLevel);- }-- pub fn open_for_loop_scope(&mut self, scope_data: Option<ScopeId>) {- self.open_scope(ScopeType::ForLoop, scope_data, ScopeLevel::NotTopLevel);- }-- // https://tc39.es/ecma262/#sec-with-statement- // The `with` statement creates an object environment record that intercepts- // identifier lookups, preventing any local variable optimization for- // identifiers used within its scope.- pub fn open_with_scope(&mut self, scope_data: Option<ScopeId>) {- self.open_scope(ScopeType::With, scope_data, ScopeLevel::NotTopLevel);- }-- pub fn open_catch_scope(&mut self) {- self.open_scope(ScopeType::Catch, None, ScopeLevel::NotTopLevel);- }-- pub fn open_static_init_scope(&mut self, scope_data: Option<ScopeId>) {- self.open_scope(ScopeType::ClassStaticInit, scope_data, ScopeLevel::StaticInitTopLevel);- }-- pub fn open_class_field_scope(&mut self, scope_data: Option<ScopeId>) {- self.open_scope(ScopeType::ClassField, scope_data, ScopeLevel::NotTopLevel);- }-- pub fn open_class_declaration_scope(&mut self, class_name: Option<&[u16]>) {- self.open_scope(ScopeType::ClassDeclaration, None, ScopeLevel::NotTopLevel);- if let Some(name) = class_name {- let index = self.current.expect("no current scope");- self.records[index].variable(name).flags |= VarFlags::BOUND;- }- }-- // === Declaration registration ===-- // https://tc39.es/ecma262/#sec-let-and-const-declarations- // https://tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics- // Lexical declarations (let/const) are block-scoped and must not collide- // with any existing var, function, or lexical binding in the same scope.- pub fn add_lexical_declaration(&mut self, bound_names: &[&[u16]], declaration_line: u32, declaration_column: u32) {- let index = self.current.expect("no current scope");-- for name in bound_names {- let flags = self.records[index].variable(name).flags;- if flags.intersects(- VarFlags::VAR | VarFlags::FORBIDDEN_LEXICAL | VarFlags::FUNCTION | VarFlags::LEXICAL | VarFlags::IMPORT,- ) {- self.already_declared_error(name, declaration_line, declaration_column);- }- self.records[index].variable(name).flags |= VarFlags::LEXICAL;- }- }-- // https://tc39.es/ecma262/#sec-variable-statement- // `var` declarations hoist to the enclosing function or script scope.- // They walk the scope chain upward, registering in every scope along- // the way until reaching a top-level scope (function, program, or- // class static initializer).- #[allow(clippy::too_many_arguments)]- pub fn add_var_declaration(- &mut self,- bound_names: &[(&[u16], Option<IdentifierId>)],- declaration_line: u32,- declaration_column: u32,- declaration_kind: Option<DeclarationKind>,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- let index = self.current.expect("no current scope");-- for (name, identifier) in bound_names {- // Register the declaration identifier so it participates in scope analysis.- if let Some(id) = identifier {- self.register_identifier(*id, declaration_kind, identifiers, strings, scopes);- }-- let mut scope_index = index;- loop {- let existing_flags = self.records[scope_index].variable(name).flags;- if existing_flags- .intersects(VarFlags::LEXICAL | VarFlags::FUNCTION | VarFlags::FORBIDDEN_VAR | VarFlags::IMPORT)- {- self.already_declared_error(name, declaration_line, declaration_column);- }- self.records[scope_index].variable(name).flags |= VarFlags::VAR;- if self.records[scope_index].is_top_level() {- break;- }- scope_index = self.records[scope_index].parent.expect("scope has no parent");- }- }- }-- // https://tc39.es/ecma262/#sec-function-definitions- // https://tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics- // At top level (function/script scope), function declarations act like `var`.- // At block level in sloppy mode, Annex B.3.3 allows hoisting the name as- // a `var` binding to the enclosing function scope.- // In strict mode (or for async/generator functions), block-scoped function- // declarations are treated as lexical bindings and are NOT Annex-B hoisted.- #[allow(clippy::too_many_arguments)]- pub fn add_function_declaration(- &mut self,- name: &[u16],- name_identifier: Option<IdentifierId>,- function_kind: FunctionKind,- strict_mode: bool,- declaration_line: u32,- declaration_column: u32,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- let index = self.current.expect("no current scope");- let scope_level = self.records[index].scope_level;-- // Register the name identifier so it participates in scope analysis.- if let Some(id) = name_identifier {- self.register_identifier(id, None, identifiers, strings, scopes);- }-- if scope_level != ScopeLevel::NotTopLevel && scope_level != ScopeLevel::ModuleTopLevel {- self.records[index].variable(name).flags |= VarFlags::VAR;- } else {- // Check flags first, then modify. This avoids borrow checker issues- // since we need to access both variables and functions_to_hoist.- let existing_flags = self.records[index]- .variables- .get(name)- .map_or(VarFlags::EMPTY, |v| v.flags);-- if existing_flags.intersects(VarFlags::VAR | VarFlags::LEXICAL | VarFlags::IMPORT) {- self.already_declared_error(name, declaration_line, declaration_column);- }-- if function_kind != FunctionKind::Normal || strict_mode {- if existing_flags.intersects(VarFlags::FUNCTION) {- self.already_declared_error(name, declaration_line, declaration_column);- }- self.records[index].variable(name).flags |= VarFlags::LEXICAL;- return;- }-- if !existing_flags.intersects(VarFlags::LEXICAL) {- let block_scope = self.records[index].scope_data;- self.records[index].functions_to_hoist.push(HoistableFunction {- name: Utf16String::from(name),- block_scope_data: block_scope,- });- }-- let var = self.records[index].variable(name);- var.flags |= VarFlags::FUNCTION;- }- }-- pub fn check_labelled_function_declaration(- &mut self,- name: &[u16],- declaration_line: u32,- declaration_column: u32,- ) {- let index = self.current.expect("no current scope");-- if self.records[index].has_flag(name, VarFlags::LEXICAL) {- self.already_declared_error(name, declaration_line, declaration_column);- }- }-- // https://tc39.es/ecma262/#sec-try-statement- // Catch clause parameters create a new scope. The bound names in a- // catch pattern forbid `var` declarations with the same name in the- // catch block (unlike regular block-scoped variables).- pub fn add_catch_parameter_pattern(&mut self, bound_names: &[&[u16]]) {- let index = self.current.expect("no current scope");- for name in bound_names {- let var = self.records[index].variable(name);- var.flags |= VarFlags::FORBIDDEN_VAR | VarFlags::BOUND | VarFlags::CATCH_PARAMETER;- }- }-- // https://tc39.es/ecma262/#sec-imports- // Imported bindings live in the module environment, next to the module's own declarations.- // https://tc39.es/ecma262/#sec-module-semantics-static-semantics-early-errors- // They are lexically declared names of the module, so they must not collide with any other- // import, var, function, or lexical binding of the module.- pub fn add_import_binding(&mut self, name: &[u16], declaration_line: u32, declaration_column: u32) {- let index = self.current.expect("no current scope");- let flags = self.records[index].variable(name).flags;- if flags.intersects(VarFlags::VAR | VarFlags::FUNCTION | VarFlags::LEXICAL | VarFlags::IMPORT) {- self.already_declared_error(name, declaration_line, declaration_column);- }- self.records[index].variable(name).flags |= VarFlags::IMPORT;- }-- pub fn add_catch_parameter_identifier(&mut self, name: &[u16]) {- let index = self.current.expect("no current scope");- self.records[index].variable(name).flags |= VarFlags::VAR | VarFlags::BOUND | VarFlags::CATCH_PARAMETER;- }-- // === Identifier registration ===-- pub fn register_identifier(- &mut self,- id: IdentifierId,- declaration_kind: Option<DeclarationKind>,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- _scopes: &mut crate::ast::ScopeArena,- ) {- let index = self.current.expect("no current scope");- let name = strings[identifiers[id].name].clone();- self.records[index]- .identifier_groups- .entry(name)- .and_modify(|group| {- group.identifiers.push(id);- if declaration_kind.is_some() && group.declaration_kind.is_none() {- group.declaration_kind = declaration_kind;- }- })- .or_insert_with(|| IdentifierGroup {- captured_by_nested_function: false,- used_inside_with_statement: false,- identifiers: vec![id],- declaration_kind,- });- }-- // === Function parameters ===-- pub fn set_function_parameters(- &mut self,- entries: &[ParameterEntry],- has_parameter_expressions: bool,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- let index = self.current.expect("no current scope");- self.records[index].has_function_parameters = true;- self.records[index].has_parameter_expressions = has_parameter_expressions;-- for entry in entries {- if entry.is_from_pattern {- if entry.is_first_from_pattern {- // Placeholder for a pattern parameter — push an empty- // entry so subsequent parameters get the correct- // positional index. Don't register anything else.- self.records[index].parameter_names.push(ParameterName {- name: Utf16String::default(),- is_rest: false,- });- continue;- }- } else {- self.records[index].parameter_names.push(ParameterName {- name: entry.name.clone(),- is_rest: entry.is_rest,- });- }- if let Some(id) = entry.identifier {- self.register_identifier(id, None, identifiers, strings, scopes);- }- let var = self.records[index].variables.entry(entry.name.clone()).or_default();- var.flags |= VarFlags::PARAMETER_CANDIDATE | VarFlags::FORBIDDEN_LEXICAL;- }-- // Mark non-parameter names that were referenced during formal parameter- // parsing (i.e. in default value expressions). If a body var later- // declares the same name, it must not be optimized to a local, since the- // default expression needs to resolve it from the outer scope.- if has_parameter_expressions {- let names_to_mark: Vec<Utf16String> = self.records[index]- .identifier_groups- .keys()- .filter(|name| !self.records[index].has_flag(name.as_slice(), VarFlags::FORBIDDEN_LEXICAL))- .cloned()- .collect();- for name in names_to_mark {- self.records[index].variable(name.as_slice()).flags |= VarFlags::REFERENCED_IN_FORMAL_PARAMETERS;- }- }- }-- // === Scope node ===-- pub fn set_scope_node(&mut self, scope_data: ScopeId) {- let index = self.current.expect("no current scope");- self.records[index].scope_data = Some(scope_data);- // Update block_scope_data for any pending functions_to_hoist that- // were registered before the ScopeData was created.- for function in &mut self.records[index].functions_to_hoist {- if function.block_scope_data.is_none() {- function.block_scope_data = Some(scope_data);- }- }- }-- // === Flag setters ===-- // https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation- // A direct call to eval (identifier `eval` as callee) can introduce new- // bindings at runtime, so the entire scope chain must retain its environment- // records (no local variable optimization through eval-poisoned scopes).- pub fn set_contains_direct_call_to_eval(&mut self) {- let index = self.current.expect("no current scope");- self.records[index].contains_direct_call_to_eval = true;- self.records[index].poisoned_by_eval_in_scope_chain = true;- self.records[index].eval_in_current_function = true;- }-- pub fn set_contains_access_to_arguments_object_in_non_strict_mode(&mut self) {- let index = self.current.expect("no current scope");- self.records[index].contains_access_to_arguments_object_in_non_strict_mode = true;- }-- pub fn set_contains_await_expression(&mut self) {- let index = self.current.expect("no current scope");- self.records[index].contains_await_expression = true;- }-- // https://tc39.es/ecma262/#sec-arrow-function-definitions-runtime-semantics-evaluation- // Arrow functions don't have their own `this`; they inherit it from the- // enclosing lexical environment (uses_this_from_environment).- pub fn set_uses_this(&mut self) {- let index = self.current.expect("no current scope");- let closest_fn = last_function_scope(index, &self.records);- let this_from_env = closest_fn.is_some_and(|fi| self.records[fi].is_arrow_function);-- // NB: collect() is needed because ancestor_scopes borrows self.records- // immutably, but the loop body needs mutable access.- for si in ancestor_scopes(index, &self.records).collect::<Vec<_>>() {- if self.records[si].scope_type == ScopeType::Function {- self.records[si].uses_this = true;- if this_from_env {- self.records[si].uses_this_from_environment = true;- }- }- }- }-- pub fn set_uses_new_target(&mut self) {- let index = self.current.expect("no current scope");- // NB: collect() for the same reason as set_uses_this above.- for si in ancestor_scopes(index, &self.records).collect::<Vec<_>>() {- if self.records[si].scope_type == ScopeType::Function {- self.records[si].uses_this = true;- self.records[si].uses_this_from_environment = true;- }- }- }-- pub fn set_is_arrow_function(&mut self) {- let index = self.current.expect("no current scope");- self.records[index].is_arrow_function = true;- }-- pub fn set_is_function_declaration(&mut self) {- let index = self.current.expect("no current scope");- self.records[index].is_function_declaration = true;- }-- // === Getters ===-- pub fn contains_direct_call_to_eval(&self) -> bool {- self.current- .is_some_and(|index| self.records[index].contains_direct_call_to_eval)- }-- pub fn uses_this_from_environment(&self) -> bool {- self.current- .is_some_and(|index| self.records[index].uses_this_from_environment)- }-- pub fn uses_this(&self) -> bool {- self.current.is_some_and(|index| self.records[index].uses_this)- }-- pub fn contains_await_expression(&self) -> bool {- self.current- .is_some_and(|index| self.records[index].contains_await_expression)- }-- pub fn scope_type(&self) -> Option<ScopeType> {- self.current.map(|index| self.records[index].scope_type)- }-- pub fn can_have_using_declaration(&self) -> bool {- self.current- .is_some_and(|index| self.records[index].scope_level != ScopeLevel::ScriptTopLevel)- }-- pub fn has_declaration(&self, name: &[u16]) -> bool {- if let Some(index) = self.current {- if self.records[index].has_flag(name, VarFlags::LEXICAL | VarFlags::VAR) {- return true;- }- return self.records[index].has_hoistable_function_named(name);- }- false- }-- pub fn has_declaration_in_current_function(&self, name: &[u16]) -> bool {- let Some(index) = self.current else {- return false;- };- let fn_scope = last_function_scope(index, &self.records);- let stop = fn_scope.and_then(|fi| self.records[fi].parent);- for si in ancestor_scopes(index, &self.records) {- if Some(si) == stop {- break;- }- if self.records[si].has_flag(name, VarFlags::LEXICAL | VarFlags::VAR | VarFlags::PARAMETER_CANDIDATE) {- return true;- }- if self.records[si].has_hoistable_function_named(name) {- return true;- }- }- false- }-- // === Post-parse analysis ===-- pub fn analyze(- &mut self,- initiated_by_eval: bool,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- self.analyze_inner(initiated_by_eval, false, identifiers, strings, scopes);- }-- /// Like analyze(), but suppresses marking identifiers as global.- /// Used for dynamic functions (new Function(...)) where the source is- /// parsed as a Script but identifiers must not use GetGlobal/SetGlobal,- /// matching the C++ path which parses as a FunctionExpression.- pub fn analyze_as_dynamic_function(- &mut self,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- self.analyze_inner(false, true, identifiers, strings, scopes);- }-- fn analyze_inner(- &mut self,- initiated_by_eval: bool,- suppress_globals: bool,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- if !self.records.is_empty() {- self.analyze_recursive(0, initiated_by_eval, suppress_globals, identifiers, strings, scopes);- }- }-- /// Analyze a scope and all its descendants, bottom-up.- /// Children are analyzed first so that unresolved identifiers bubble up- /// to their parent, and eval poisoning propagates outward.- fn analyze_recursive(- &mut self,- index: usize,- initiated_by_eval: bool,- suppress_globals: bool,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- // Process children first (bottom-up traversal).- let children = std::mem::take(&mut self.records[index].children);- for child_index in children {- self.analyze_recursive(- child_index,- initiated_by_eval,- suppress_globals,- identifiers,- strings,- scopes,- );- }-- // Steps 1-3 must run even for scopes without scope_data (e.g. catch- // scopes), so that identifier groups propagate through the scope chain.- // Without this, captured variables inside catch blocks are invisible- // to enclosing scopes and get incorrectly optimized as locals.-- // 1. Propagate eval() flags from children to parent.- Self::propagate_eval_poisoning(&mut self.records, index);- Self::note_unused_function_name(&self.records, index, scopes);- // 2. Match identifier references to declarations; optimize as locals.- Self::resolve_identifiers(- &mut self.records,- index,- initiated_by_eval,- suppress_globals,- identifiers,- strings,- scopes,- );- // 3. Annex B: hoist block-scoped functions to enclosing function scope.- Self::hoist_functions(&mut self.records, index, identifiers, strings, scopes);-- // 4. For function-like scopes, build the var declaration list that- // the bytecode generator uses to initialize function-scoped variables.- if self.records[index].scope_data.is_some() {- let st = self.records[index].scope_type;- let needs_fsd = (st == ScopeType::Function && self.records[index].has_function_parameters)- || st == ScopeType::ClassStaticInit- || st == ScopeType::ClassField;- if needs_fsd {- Self::build_function_scope_data(&self.records, index, identifiers, strings, scopes);- }- }- }-- /// Propagate eval-related flags from a child scope to its parent.- ///- /// Three separate flags track eval impact:- /// - `contains_direct_call_to_eval`: this scope itself has `eval()`- /// - `poisoned_by_eval_in_scope_chain`: some descendant has eval, so- /// this scope can't optimize away its environment record- /// - `eval_in_current_function`: eval exists somewhere in the current- /// function (propagates through blocks but stops at function boundaries)- fn propagate_eval_poisoning(records: &mut [ScopeRecord], index: usize) {- if let Some(parent_index) = records[index].parent {- if records[index].contains_direct_call_to_eval || records[index].poisoned_by_eval_in_scope_chain {- records[parent_index].poisoned_by_eval_in_scope_chain = true;- }- // eval_in_current_function propagates upward through blocks but- // stops at function boundaries (each function is independent).- if records[index].eval_in_current_function && records[index].scope_type != ScopeType::Function {- records[parent_index].eval_in_current_function = true;- }- }- }-- /// Notes in the body of a named function expression whether the function's own name is unused: nothing in the- /// function or the functions nested in it refers to it, and no direct eval could. References are still in the- /// scope's identifier groups here, where the nested scopes left the ones they did not resolve.- fn note_unused_function_name(records: &[ScopeRecord], index: usize, scopes: &mut crate::ast::ScopeArena) {- let record = &records[index];- if record.scope_type != ScopeType::Function- || record.is_function_declaration- || record.is_arrow_function- || record.contains_direct_call_to_eval- || record.poisoned_by_eval_in_scope_chain- {- return;- }- let Some(scope_id) = record.scope_data else {- return;- };- let Some((name, _)) = record- .variables- .iter()- .find(|(_, variable)| variable.flags.intersects(VarFlags::BOUND))- else {- return;- };- if !record.identifier_groups.contains_key(name) {- scopes[scope_id].function_name_is_unused = true;- }- }-- /// Try to resolve each identifier group in this scope to a local variable.- ///- /// For each named group, this function:- /// 1. Annotates identifiers with their declaration kind (var/let/const)- /// 2. Determines if the name can be optimized to a local variable index- /// 3. If not resolvable here, propagates the group to the parent scope- ///- /// An identifier is optimized to a local when:- /// - It's declared in this scope (var, let/const, function, parameter, catch)- /// - It's NOT captured by a nested function- /// - It's NOT used inside a `with` statement- /// - The scope chain is NOT poisoned by `eval()`- fn resolve_identifiers(- records: &mut [ScopeRecord],- index: usize,- initiated_by_eval: bool,- suppress_globals: bool,- identifiers: &mut IdentifierArena,- _strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- // identifier_groups is an IndexMap, so iteration is in source order- // of first reference. Local variable indices follow that order.- let groups = std::mem::take(&mut records[index].identifier_groups);- let mut propagate_to_parent: Vec<(Utf16String, IdentifierGroup)> = Vec::new();- for (name, mut group) in groups {- // Annotate each Identifier AST node with its declaration kind,- // so the bytecode generator knows how to handle TDZ checks, etc.- if let Some(dk) = group.declaration_kind {- for id in &group.identifiers {- identifiers[*id].declaration_kind = Some(dk);- }- }-- let var_flags = records[index]- .variables- .get(name.as_slice())- .map_or(VarFlags::EMPTY, |v| v.flags);-- // Determine what kind of local variable this is (if any).- // Priority: var (at top-level) > let/const > function declaration.- let mut local_var_kind: Option<LocalVarKind> = None;- if records[index].is_top_level() && var_flags.intersects(VarFlags::VAR) {- local_var_kind = Some(LocalVarKind::Var);- } else if var_flags.intersects(VarFlags::LEXICAL) {- local_var_kind = Some(LocalVarKind::LetOrConst);- } else if var_flags.intersects(VarFlags::FUNCTION) {- local_var_kind = Some(LocalVarKind::Function);- }-- // https://tc39.es/ecma262/#sec-functiondeclarationinstantiation- // Non-arrow functions implicitly declare `arguments` as a local- // (an Arguments exotic object or a mapped arguments object).- // https://tc39.es/ecma262/#sec-arrow-function-definitions-runtime-semantics-evaluation- // Arrow functions do NOT have their own `arguments` binding;- // references to `arguments` resolve to the enclosing function's.- if records[index].scope_type == ScopeType::Function- && !records[index].is_arrow_function- && name == utf16!("arguments")- {- local_var_kind = Some(LocalVarKind::ArgumentsObject);- }-- if records[index].scope_type == ScopeType::Catch && var_flags.intersects(VarFlags::CATCH_PARAMETER) {- local_var_kind = Some(LocalVarKind::CatchClauseParameter);- }-- // When a function has parameter expressions (default values, etc.), body- // var declarations live in a separate Variable Environment from the- // parameter scope. If the same name is also referenced in a default- // parameter expression, it must not be a local: the default expression- // needs to resolve it from the outer scope via the environment chain,- // not read the (uninitialized) local.- // We also mark the name as captured in the parent scope, so that the- // outer binding is not optimized to a local register either.- if var_flags.intersects(VarFlags::REFERENCED_IN_FORMAL_PARAMETERS)- && var_flags.intersects(VarFlags::VAR)- && !var_flags.intersects(VarFlags::FORBIDDEN_LEXICAL)- {- if let Some(parent_index) = records[index].parent {- records[parent_index]- .identifier_groups- .entry(name.clone())- .or_insert_with(|| IdentifierGroup {- captured_by_nested_function: false,- used_inside_with_statement: false,- identifiers: Vec::new(),- declaration_kind: None,- })- .captured_by_nested_function = true;- }- continue;- }-- let hoistable = records[index].has_hoistable_function_named(&name);-- // ClassDeclaration with IsBound: skip entirely.- if records[index].scope_type == ScopeType::ClassDeclaration && var_flags.intersects(VarFlags::BOUND) {- continue;- }-- // Function expression name binding.- if records[index].scope_type == ScopeType::Function- && !records[index].is_function_declaration- && var_flags.intersects(VarFlags::BOUND)- {- for id in &group.identifiers {- identifiers[*id].is_inside_scope_with_eval = true;- }- }-- if records[index].scope_type == ScopeType::ClassDeclaration {- local_var_kind = None;- }-- let mut is_function_parameter = false;- if records[index].scope_type == ScopeType::Function {- if var_flags.intersects(VarFlags::PARAMETER_CANDIDATE)- && (!records[index].contains_access_to_arguments_object_in_non_strict_mode- || records[index].has_rest_parameter_with_name(&name))- {- is_function_parameter = true;- } else if var_flags.intersects(VarFlags::FORBIDDEN_LEXICAL) {- continue;- }- }-- if records[index].scope_type == ScopeType::Function && hoistable {- continue;- }-- if records[index].scope_type == ScopeType::Program {- // Declarations and imports of a module live in its module environment, whose layout the bytecode- // generator knows, so they must not be looked up as globals.- let is_module_declaration = records[index].scope_level == ScopeLevel::ModuleTopLevel- && var_flags.intersects(VarFlags::VAR | VarFlags::LEXICAL | VarFlags::FUNCTION | VarFlags::IMPORT);- let can_use_global = !(suppress_globals- || group.used_inside_with_statement- || initiated_by_eval- || is_module_declaration);- if can_use_global {- for id in &group.identifiers {- let identifier = &mut identifiers[*id];- if !identifier.is_inside_scope_with_eval {- identifier.is_global = true;- }- }- }- } else if local_var_kind.is_some() || is_function_parameter {- if hoistable {- continue;- }-- // When a function has parameter expressions and a nested function in a- // default expression captures a name that is also a body var, propagate- // the capture to the parent scope so the outer binding stays in the- // environment (not optimized to a local register).- if records[index].has_parameter_expressions- && group.captured_by_nested_function- && var_flags.intersects(VarFlags::VAR)- && !var_flags.intersects(VarFlags::FORBIDDEN_LEXICAL)- && let Some(parent_index) = records[index].parent- {- records[parent_index]- .identifier_groups- .entry(name.clone())- .or_insert_with(|| IdentifierGroup {- captured_by_nested_function: false,- used_inside_with_statement: false,- identifiers: Vec::new(),- declaration_kind: None,- })- .captured_by_nested_function = true;- }-- if !group.captured_by_nested_function && !group.used_inside_with_statement {- if records[index].poisoned_by_eval_in_scope_chain {- continue;- }-- let mut local_scope = last_function_scope(index, records);- if local_scope.is_none() {- if group.declaration_kind == Some(DeclarationKind::Var) {- continue;- }- local_scope = records[index].top_level;- }-- if let Some(ls) = local_scope- && let Some(scope_id) = records[ls].scope_data- {- let local_scope_range = records[index]- .scope_data- .and_then(|scope_id| scopes[scope_id].source_range);- let sd = &mut scopes[scope_id];-- let local = if is_function_parameter {- let argument_index = records[ls].get_parameter_index(&name);- if let Some(ai) = argument_index {- for id in &group.identifiers {- let identifier = &mut identifiers[*id];- identifier.local_index = ai;- identifier.local_type = Some(crate::ast::LocalType::Argument);- }- LocalBinding {- local_type: crate::ast::LocalType::Argument,- index: ai,- }- } else {- let lvi = u32_from_usize(sd.local_variables.len());- sd.local_variables.push(LocalVariable {- name: name.clone(),- kind: LocalVarKind::Var,- is_mutable: true,- scope_range: None,- });- for id in &group.identifiers {- let identifier = &mut identifiers[*id];- identifier.local_index = lvi;- identifier.local_type = Some(crate::ast::LocalType::Variable);- }- LocalBinding {- local_type: crate::ast::LocalType::Variable,- index: lvi,- }- }- } else {- let kind = local_var_kind.expect("local_var_kind must be set for local variables");- let lvi = u32_from_usize(sd.local_variables.len());- sd.local_variables.push(LocalVariable {- name: name.clone(),- kind,- is_mutable: group.declaration_kind != Some(DeclarationKind::Const),- scope_range: local_scope_range,- });- for id in &group.identifiers {- let identifier = &mut identifiers[*id];- identifier.local_index = lvi;- identifier.local_type = Some(crate::ast::LocalType::Variable);- }- LocalBinding {- local_type: crate::ast::LocalType::Variable,- index: lvi,- }- };- if let Some(variable) = records[index].variables.get_mut(name.as_slice()) {- variable.local = Some(local);- }- }- }- } else {- if records[index].has_function_parameters- || records[index].scope_type == ScopeType::ClassField- || records[index].scope_type == ScopeType::ClassStaticInit- {- group.captured_by_nested_function = true;- }-- if records[index].scope_type == ScopeType::With {- group.used_inside_with_statement = true;- }-- if records[index].eval_in_current_function {- for id in &group.identifiers {- identifiers[*id].is_inside_scope_with_eval = true;- }- }-- propagate_to_parent.push((name, group));- }- }-- if let Some(parent_index) = records[index].parent {- for (name, group) in propagate_to_parent {- if let Some(parent_group) = records[parent_index].identifier_groups.get_mut(&name) {- parent_group.identifiers.extend(group.identifiers);- if group.captured_by_nested_function {- parent_group.captured_by_nested_function = true;- }- if group.used_inside_with_statement {- parent_group.used_inside_with_statement = true;- }- } else {- records[parent_index].identifier_groups.insert(name, group);- }- }- }- }-- // https://tc39.es/ecma262/#sec-functiondeclarationinstantiation- // Builds the data needed by FunctionDeclarationInstantiation at runtime:- // - vars_to_initialize: var-declared names and their local variable indices- // - functions_to_initialize: function declarations to instantiate (in reverse order)- // - arguments object metadata (has_argument_parameter, has_function_named_arguments, etc.)- fn build_function_scope_data(- records: &[ScopeRecord],- index: usize,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- let record = &records[index];- let Some(scope_id) = record.scope_data else {- return;- };-- let has_argument_parameter = record- .variables- .get(utf16!("arguments") as &[u16])- .is_some_and(|v| v.flags.intersects(VarFlags::FORBIDDEN_LEXICAL));-- let mut vars_to_initialize = Vec::new();- let mut var_names = Vec::new();- let mut has_function_named_arguments = false;- let mut has_lexically_declared_arguments = false;- let mut non_local_var_count: usize = 0;- let mut non_local_var_count_for_parameter_expressions: usize = 0;-- // Build functions_to_initialize by scanning children for FunctionDeclarations.- // ECMAScript hoisting keeps the LAST function declaration with a given name,- // but we want to emit the resulting list in SOURCE order. Two forward passes:- // record the last position for each name, then keep only the entries whose- // position matches. Keys are SharedUtf16String so each insert is a cheap- // Rc bump rather than a deep clone of the name.- let mut functions_to_initialize: Vec<crate::ast::FunctionToInit> = Vec::new();- let mut last_position: HashMap<StringId, usize> = HashMap::default();- let mut last_position_by_slice: HashMap<Utf16String, usize> = HashMap::default();- {- let sd = &scopes[scope_id];- for (i, child) in sd.children.iter().enumerate() {- if let Some(fd) = child.inner.function_declaration_for_labelled_item()- && let Some(name_ident) = fd.name- {- let name_id = identifiers[name_ident].name;- last_position.insert(name_id, i);- last_position_by_slice.insert(strings[name_id].clone(), i);- }- }- for (i, child) in sd.children.iter().enumerate() {- if let Some(fd) = child.inner.function_declaration_for_labelled_item()- && let Some(name_ident) = fd.name- && last_position.get(&identifiers[name_ident].name).copied() == Some(i)- {- functions_to_initialize.push(crate::ast::FunctionToInit { child_index: i });- }- }- }-- for (name, var) in &record.variables {- if !var.flags.intersects(VarFlags::VAR) {- continue;- }-- var_names.push(name.clone());-- let is_parameter = var.flags.intersects(VarFlags::FORBIDDEN_LEXICAL);- let is_function_name = last_position_by_slice.contains_key(name.as_slice());-- let local_info = var.local;-- if local_info.is_none() {- non_local_var_count_for_parameter_expressions += 1;- if !is_parameter {- non_local_var_count += 1;- }- }-- vars_to_initialize.push(VarToInit {- name: name.clone(),- is_parameter,- is_function_name,- local: local_info,- });- }-- // vars_to_initialize and var_names follow source order via the- // insertion order of `record.variables`, which is now an IndexMap.-- if last_position_by_slice.contains_key(utf16!("arguments") as &[u16]) {- has_function_named_arguments = true;- }-- if record- .variables- .get(utf16!("arguments") as &[u16])- .is_some_and(|v| v.flags.intersects(VarFlags::LEXICAL))- {- has_lexically_declared_arguments = true;- }-- let fsd = FunctionScopeData {- functions_to_initialize,- vars_to_initialize,- var_names,- has_function_named_arguments,- has_argument_parameter,- has_lexically_declared_arguments,- non_local_var_count,- non_local_var_count_for_parameter_expressions,- };-- {- let sd = &mut scopes[scope_id];- sd.function_scope_data = Some(Box::new(fsd));-- // Write scope analysis insights to ScopeData so they can be read- // during lazy compilation (write_sfd_metadata, FDI emission).- sd.uses_this = record.uses_this;- sd.uses_this_from_environment = record.uses_this_from_environment;- sd.contains_direct_call_to_eval =- record.contains_direct_call_to_eval || record.poisoned_by_eval_in_scope_chain;- sd.contains_access_to_arguments_object = record.contains_access_to_arguments_object_in_non_strict_mode;- }- }-- /// https://tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics- ///- /// Annex B.3.3 function hoisting: in sloppy mode, function declarations- /// inside blocks can create `var` bindings in the enclosing function scope.- ///- /// For example:- /// ```js- /// function f() {- /// if (true) { function g() {} } // g is hoisted to f's scope- /// g(); // works in sloppy mode!- /// }- /// ```- ///- /// The function propagates upward through block scopes until it reaches- /// a function/program scope (top level) or is blocked by an existing- /// lexical or function declaration with the same name.- fn hoist_functions(- records: &mut [ScopeRecord],- index: usize,- identifiers: &mut IdentifierArena,- strings: &crate::ast::StringInterner,- scopes: &mut crate::ast::ScopeArena,- ) {- let functions = std::mem::take(&mut records[index].functions_to_hoist);-- for function in functions {- // A let/const or forbidden var with the same name blocks hoisting.- if records[index].has_flag(&function.name, VarFlags::LEXICAL | VarFlags::FORBIDDEN_VAR) {- continue;- }-- if records[index].is_top_level() {- // AnnexB.3.3.1: Skip hoisting if the function name is a parameter name.- if records[index].has_flag(&function.name, VarFlags::FORBIDDEN_LEXICAL) {- continue;- }- // NB: FunctionDeclarationInstantiation creates no var binding for a hoisted function named- // "arguments". When the function declaration is evaluated, it is stored into the arguments- // object binding instead. A direct eval can reach the arguments object too.- let uses_existing_arguments_binding = function.name == utf16!("arguments")- && (records[index].contains_access_to_arguments_object_in_non_strict_mode- || (records[index].scope_type == ScopeType::Function- && !records[index].is_arrow_function- && records[index].contains_direct_call_to_eval));- // Reached function/program scope — register the hoisted function name.- if !uses_existing_arguments_binding && let Some(scope_id) = records[index].scope_data {- let sd = &mut scopes[scope_id];- if !sd.annexb_function_names.contains(&function.name) {- sd.annexb_function_names.push(function.name.clone());- }- }- // Mark all function declarations with this name in the block- // as hoisted, so they emit GetBinding + SetVariableBinding.- if let Some(block_scope_id) = function.block_scope_data {- let bs = &mut scopes[block_scope_id];- for child in &mut bs.children {- mark_hoisted_function_declarations(child, function.name.as_slice(), identifiers, strings);- }- }- } else if let Some(parent_index) = records[index].parent {- // Not yet at top level — keep propagating upward unless blocked.- if !records[parent_index].has_flag(&function.name, VarFlags::LEXICAL | VarFlags::FUNCTION) {- records[parent_index].functions_to_hoist.push(function);- }- }- }- }-}