Skip to content

Truly independent web browser

48.3 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! JS::DeclarativeEnvironment, whose bindings live where the interpreter reads them: the values in binding_values,
//! indexed like the environment coordinates the bytecode carries, and the flags either in the environment's shape,
//! shared by every environment that one piece of code creates, or in the rare data for bindings the shape does not
//! cover.

use core::cell::{Cell, RefCell};
use core::ops::Deref;
use std::collections::HashMap;

use ak::Utf16FlyString;
use libjs_runtime_macros::Trace;

use crate::gc::class::{Class, Finalize, GcCell, define_cell};
use crate::gc::class_id::ClassId;
use crate::gc::gc_ref_cell::GcRefCell;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::vm::Vm;
use crate::jit::dependencies::{CellId, Dependency};
use crate::layout::buffer::InterpreterBuffer;
use crate::layout::cell::{CellHeader, Gc};
pub use crate::layout::environment::{
    DeclarativeEnvironment, DeclarativeEnvironmentRareData, GlobalDeclarativeEnvironment,
};
use crate::layout::member::NullableMember;
use crate::layout::value::Value;
use crate::runtime::abstract_operations::{DisposeCapability, add_disposable_resource};
use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::environment::{ENVIRONMENT_METHODS, Environment, EnvironmentMethods, InitializeBindingHint};
use crate::runtime::environment_shape::{EnvironmentShape, EnvironmentShapeCache};
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::module_environment::ModuleEnvironment;
use crate::runtime::value_storage;

#[derive(Clone)]
pub struct Binding {
    pub name: Utf16FlyString,
    pub value: Value,
    pub strict: bool,
    pub mutable: bool,
    pub can_be_deleted: bool,
    pub initialized: bool,
}

/// A binding of the environment that was searched, by index, or a copy of a binding of another environment, which
/// module environments find for their indirect bindings.
pub enum BindingAndIndex {
    Index(usize),
    Temporary(Binding),
}

impl BindingAndIndex {
    /// The binding, where `environment` is the environment that found it.
    pub fn binding(&self, environment: &DeclarativeEnvironment) -> Binding {
        match self {
            Self::Index(index) => environment.binding_at(*index),
            Self::Temporary(binding) => binding.clone(),
        }
    }

    pub fn index(&self) -> Option<usize> {
        match self {
            Self::Index(index) => Some(*index),
            Self::Temporary(_) => None,
        }
    }
}

/// Mirrors AK::Bitmap, as far as the deleted bindings of an environment use it.
#[derive(Default)]
struct Bitmap {
    data: Option<Box<[u8]>>,
    size: usize,
}

impl Bitmap {
    fn create(size: usize, default_value: bool) -> Self {
        assert!(size != 0);
        let fill = if default_value { 0xff } else { 0 };
        Self {
            data: Some(vec![fill; size.div_ceil(8)].into_boxed_slice()),
            size,
        }
    }

    fn is_null(&self) -> bool {
        self.data.is_none()
    }

    fn size(&self) -> usize {
        self.size
    }

    fn get(&self, index: usize) -> bool {
        assert!(index < self.size);
        let data = self.data.as_ref().expect("a bitmap with bits has data");
        data[index / 8] & (1 << (index % 8)) != 0
    }

    fn set(&mut self, index: usize, value: bool) {
        assert!(index < self.size);
        let byte = &mut self.data.as_mut().expect("a bitmap with bits has data")[index / 8];
        if value {
            *byte |= 1 << (index % 8);
        } else {
            *byte &= !(1 << (index % 8));
        }
    }

    fn grow(&mut self, size: usize, default_value: bool) {
        assert!(size > self.size);
        let previous_size = self.size;
        let mut data = vec![0; size.div_ceil(8)].into_boxed_slice();
        if let Some(previous_data) = &self.data {
            data[..previous_data.len()].copy_from_slice(previous_data);
        }
        self.data = Some(data);
        self.size = size;
        for index in previous_size..size {
            self.set(index, default_value);
        }
    }
}

/// The part of DeclarativeEnvironment::RareData that the interpreter does not read.
#[derive(Default, Trace)]
pub struct DeclarativeEnvironmentRareDataStorage {
    #[gc(untraced)]
    binding_names: RefCell<Vec<Utf16FlyString>>,
    #[gc(untraced)]
    deleted_bindings: RefCell<Bitmap>,
    #[gc(untraced)]
    bindings_assoc: RefCell<HashMap<Utf16FlyString, usize, foldhash::fast::RandomState>>,
    dispose_capability: GcRefCell<DisposeCapability>,
    environment_shape_cache: Cell<Option<EnvironmentShapeCache>>,
    expected_binding_count: Cell<usize>,
    is_catch_environment: Cell<bool>,
    /// Whether the environment notes which bindings are assigned (see `track_binding_assignments()`).
    tracks_assignments: Cell<bool>,
    /// The bindings that were assigned since their initialization, if the environment tracks assignments.
    #[gc(untraced)]
    assigned_bindings: RefCell<Bitmap>,
    /// Whether JIT code depends on the environment getting no bindings and on its bindings staying unassigned.
    has_dependent_code: Cell<bool>,
}

impl DeclarativeEnvironmentRareData {
    fn is_empty(&self) -> bool {
        let storage = &self.storage;
        storage.binding_names.borrow().is_empty()
            && self.binding_flags.is_empty()
            && storage.deleted_bindings.borrow().is_null()
            && storage.bindings_assoc.borrow().is_empty()
            && storage.dispose_capability.borrow().disposable_resource_stack.is_none()
            && storage.environment_shape_cache.get().is_none()
            && storage.expected_binding_count.get() == 0
            && !storage.is_catch_environment.get()
            && !storage.tracks_assignments.get()
            && !storage.has_dependent_code.get()
    }
}

// SAFETY: The flags hold no cells; the storage traces the rest.
unsafe impl Trace for DeclarativeEnvironmentRareData {
    fn trace(&self, visitor: &mut Visitor) {
        self.storage.trace(visitor);
    }
}

define_cell!(DeclarativeEnvironmentRareData, Other);

impl Drop for DeclarativeEnvironmentRareData {
    fn drop(&mut self) {
        self.binding_flags.clear();
    }
}

/// Mirrors AK::Vector's growth policy.
fn padded_binding_capacity(capacity: usize) -> usize {
    4 + capacity + capacity / 4
}

/// The binding values of an environment, which it keeps in its cell or in value storage (see value_storage), which is
/// a ValueStorage cell unless there are too many values for one. A collection can rewrite the values in a cell where they
/// are, so the cells they name can move, as with the properties of objects.
struct BindingValues<'a> {
    environment: &'a DeclarativeEnvironment,
}

impl BindingValues<'_> {
    fn size(&self) -> usize {
        self.environment.binding_count.get() as usize
    }

    fn capacity(&self) -> usize {
        if self.environment.binding_values_are_inline() {
            return usize::from(self.environment.inline_binding_capacity.get());
        }
        let data = self.environment.binding_values.get();
        if data.is_null() {
            return 0;
        }
        // SAFETY: Binding values that are not in the environment's cell are value storage.
        unsafe { value_storage::capacity(data) as usize }
    }

    fn is_empty(&self) -> bool {
        self.size() == 0
    }

    fn get(&self, index: usize) -> Value {
        assert!(index < self.size(), "the binding exists");
        // SAFETY: The first `size` values are initialized.
        unsafe { self.environment.binding_values.get().add(index).read() }
    }

    fn set(&self, index: usize, value: Value) {
        assert!(index < self.size(), "the binding exists");
        // SAFETY: The value is in bounds, and nothing borrows the values.
        unsafe { self.environment.binding_values.get().add(index).write(value) };
    }

    fn append(&self, value: Value) {
        let size = self.size();
        if size == self.capacity() {
            self.reallocate(padded_binding_capacity(size + 1));
        }
        // SAFETY: There is room for one more value.
        unsafe { self.environment.binding_values.get().add(size).write(value) };
        self.environment
            .binding_count
            .set(u32::try_from(size + 1).expect("the binding count fits in u32"));
    }

    fn ensure_capacity(&self, needed_capacity: usize) {
        if needed_capacity > self.capacity() {
            self.reallocate(needed_capacity);
        }
    }

    fn shrink_to_fit(&self) {
        if self.size() != self.capacity() {
            self.reallocate(self.size());
        }
    }

    /// Removes every value and frees the storage, if it is malloc storage.
    fn clear(&self) {
        self.environment.binding_count.set(0);
        self.reallocate(0);
    }

    /// Moves the values from the cell to value storage, with room for at least `needed_capacity` values and as much more
    /// as append() would make.
    fn move_to_owned_storage(&self, needed_capacity: usize) {
        self.reallocate(needed_capacity.max(padded_binding_capacity(self.size())));
    }

    fn reallocate(&self, new_capacity: usize) {
        let size = self.size();
        assert!(new_capacity >= size);
        let old_data = self.environment.binding_values.get();
        let was_inline = self.environment.binding_values_are_inline();
        let new_data = if new_capacity == 0 {
            core::ptr::null_mut()
        } else {
            let capacity = u32::try_from(new_capacity).expect("the binding count fits in u32");
            // NB: Allocating value storage never collects garbage, so the old values stay where they are meanwhile.
            let new_data = value_storage::allocate(Vm::of_cell(self.environment).heap(), capacity, Value::UNDEFINED);
            if size != 0 {
                // SAFETY: The new storage has room for `new_capacity` values, of which `size` come from the old storage,
                //         which is other memory.
                unsafe { core::ptr::copy_nonoverlapping(old_data, new_data, size) };
            }
            new_data
        };
        if !old_data.is_null() && !was_inline {
            // SAFETY: The old storage is value storage that this method allocated, which nothing uses any more.
            unsafe { value_storage::deallocate(old_data) };
        }
        self.environment.binding_values.set(new_data);
        self.environment.inline_binding_capacity.set(0);
    }
}

define_cell!(DeclarativeEnvironment, Other, extends: [Environment], finalize: finalize);

// SAFETY: Visits the outer environment and the shape (in the Environment), the rare data's dispose capability and shape
// cache and every binding value.
unsafe impl Trace for DeclarativeEnvironment {
    fn trace(&self, visitor: &mut Visitor) {
        self.base.trace(visitor);
        self.rare_data.trace(visitor);
        let binding_values = self.binding_values.get();
        // SAFETY: The first `binding_count` values are initialized, and nothing writes them while they are visited.
        let values = unsafe { ak::slice_from_raw_parts(binding_values, self.binding_count.get() as usize) };
        if self.binding_values_are_inline() {
            visitor.visit_self_pointer(&self.binding_values);
            visitor.visit_values(values);
        } else if !binding_values.is_null() {
            // SAFETY: Binding values that are not in the environment's cell are value storage.
            match unsafe { value_storage::cell(binding_values) } {
                Some(storage) => {
                    // NB: The pointer to the storage is visited as a slot, so that a collection that moves the
                    //     environment or its storage cell keeps it pointing into it.
                    visitor.visit_interior_pointer(&self.binding_values, storage);
                    visitor.visit_values(values);
                }
                // SAFETY: Malloc storage is the environment's own, which only its own methods change, and only its
                //         finalizer frees.
                None => unsafe { visitor.visit_owned_values(values) },
            }
        }
    }
}

impl Finalize for DeclarativeEnvironment {
    fn finalize(&self) {
        if !self.binding_values_are_inline() {
            self.binding_values().clear();
        }
    }
}

/// How many binding values the size classes of an environment class have room for after the fields of the class.
/// Environments with more bindings keep them in value storage.
pub const INLINE_BINDING_CAPACITIES: [u8; 8] = [1, 2, 3, 4, 6, 8, 12, 16];

/// The cell sizes of the size classes of an environment class whose cells are `cell_size` bytes.
pub const fn inline_binding_cell_sizes(cell_size: usize) -> [u32; INLINE_BINDING_CAPACITIES.len()] {
    let mut cell_sizes = [0; INLINE_BINDING_CAPACITIES.len()];
    let mut index = 0;
    while index < cell_sizes.len() {
        cell_sizes[index] = (cell_size + INLINE_BINDING_CAPACITIES[index] as usize * size_of::<Value>()) as u32;
        index += 1;
    }
    cell_sizes
}

/// The size class (an index into INLINE_BINDING_CAPACITIES) of environments with room for `binding_capacity` binding
/// values, or None if they need none or more than any size class has.
pub fn inline_binding_size_class(binding_capacity: usize) -> Option<usize> {
    if binding_capacity == 0 {
        return None;
    }
    INLINE_BINDING_CAPACITIES
        .iter()
        .position(|&capacity| binding_capacity <= capacity as usize)
}

/// Moves `environment`, a new environment of class T without bindings, into the heap, with room for
/// `binding_capacity` binding values in its cell if a size class of T (with `cell_sizes`, from
/// inline_binding_cell_sizes()) has room for them.
pub fn allocate_environment<T: GcCell>(
    vm: &Vm,
    environment: T,
    binding_capacity: usize,
    cell_sizes: &[u32; INLINE_BINDING_CAPACITIES.len()],
    declarative: fn(&T) -> &DeclarativeEnvironment,
) -> Gc<T> {
    let heap = vm.heap();
    let Some(size_class) = inline_binding_size_class(binding_capacity) else {
        return heap.allocate(|_| environment);
    };
    let environment = heap.allocate_with_size_class(
        heap.size_classes(T::CLASS, cell_sizes)[size_class],
        |_| environment,
        Value::EMPTY,
    );
    let declarative_environment = declarative(&environment);
    // SAFETY: The cell has room for the size class's binding values after the fields of T, as long as it lives.
    let inline_values = unsafe { environment.as_ptr().cast::<u8>().add(size_of::<T>()) }.cast::<Value>();
    declarative_environment.binding_values.set(inline_values);
    declarative_environment
        .inline_binding_capacity
        .set(INLINE_BINDING_CAPACITIES[size_class]);
    environment
}

define_cell!(GlobalDeclarativeEnvironment, Other, extends: [DeclarativeEnvironment, Environment], finalize: finalize);

impl Finalize for GlobalDeclarativeEnvironment {
    fn finalize(&self) {
        self.base.finalize();
    }
}

// SAFETY: Visits what the declarative environment holds. The serial number is no cell.
unsafe impl Trace for GlobalDeclarativeEnvironment {
    fn trace(&self, visitor: &mut Visitor) {
        self.base.trace(visitor);
    }
}

impl Deref for GlobalDeclarativeEnvironment {
    type Target = DeclarativeEnvironment;

    fn deref(&self) -> &DeclarativeEnvironment {
        &self.base
    }
}

impl GlobalDeclarativeEnvironment {
    pub fn create(vm: &Vm) -> Gc<DeclarativeEnvironment> {
        vm.heap()
            .allocate(|_| Self {
                base: DeclarativeEnvironment::new(Self::CLASS, None),
                serial_number: Cell::new(0),
            })
            .upcast()
    }
}

/// The cell sizes of the size classes of declarative environments.
pub const DECLARATIVE_ENVIRONMENT_CELL_SIZES: [u32; INLINE_BINDING_CAPACITIES.len()] =
    inline_binding_cell_sizes(size_of::<DeclarativeEnvironment>());

impl Deref for DeclarativeEnvironment {
    type Target = Environment;

    fn deref(&self) -> &Environment {
        &self.base
    }
}

fn declarative(environment: &Environment) -> &DeclarativeEnvironment {
    environment
        .as_declarative_environment()
        .expect("only declarative environments have the declarative environment methods")
}

/// The methods JS::DeclarativeEnvironment overrides.
pub const DECLARATIVE_ENVIRONMENT_METHODS: EnvironmentMethods = EnvironmentMethods {
    has_binding: |environment, _, name, out_index| declarative(environment).has_binding(name, out_index),
    create_mutable_binding: |environment, vm, name, can_be_deleted| {
        declarative(environment).create_mutable_binding(vm, name, can_be_deleted)
    },
    create_immutable_binding: |environment, vm, name, strict| {
        declarative(environment).create_immutable_binding(vm, name, strict)
    },
    initialize_binding: |environment, vm, name, value, hint| {
        declarative(environment).initialize_binding(vm, name, value, hint)
    },
    set_mutable_binding: |environment, vm, name, value, strict| {
        declarative(environment).set_mutable_binding(vm, name, value, strict)
    },
    get_binding_value: |environment, vm, name, strict| declarative(environment).get_binding_value(vm, name, strict),
    delete_binding: |environment, vm, name| declarative(environment).delete_binding(vm, name),
    is_catch_environment: |environment| declarative(environment).is_catch_environment(),
    ..ENVIRONMENT_METHODS
};

impl DeclarativeEnvironment {
    const BINDING_FLAG_STRICT: u8 = EnvironmentShape::BINDING_FLAG_STRICT;
    const BINDING_FLAG_MUTABLE: u8 = EnvironmentShape::BINDING_FLAG_MUTABLE;
    const BINDING_FLAG_CAN_BE_DELETED: u8 = EnvironmentShape::BINDING_FLAG_CAN_BE_DELETED;

    /// A new environment of `class`, which is DeclarativeEnvironment or a class that extends it, with no bindings.
    pub fn new(class: &'static Class, outer_environment: Option<Gc<Environment>>) -> Self {
        Self {
            base: Environment::new(class, outer_environment, true),
            binding_values: Cell::new(core::ptr::null_mut()),
            binding_count: Cell::new(0),
            rare_data: NullableMember::null(),
        }
    }

    pub fn create(vm: &Vm, outer_environment: Option<Gc<Environment>>) -> Gc<DeclarativeEnvironment> {
        vm.heap().allocate(|_| Self::new(Self::CLASS, outer_environment))
    }

    /// A new environment with room for `binding_capacity` bindings in its cell, if a size class has that much.
    pub fn create_with_binding_capacity(
        vm: &Vm,
        outer_environment: Option<Gc<Environment>>,
        binding_capacity: usize,
    ) -> Gc<DeclarativeEnvironment> {
        allocate_environment(
            vm,
            Self::new(Self::CLASS, outer_environment),
            binding_capacity,
            &DECLARATIVE_ENVIRONMENT_CELL_SIZES,
            |environment| environment,
        )
    }

    fn rare_data(&self) -> Option<Gc<DeclarativeEnvironmentRareData>> {
        self.rare_data.get()
    }

    fn ensure_rare_data(&self) -> Gc<DeclarativeEnvironmentRareData> {
        if let Some(rare_data) = self.rare_data() {
            return rare_data;
        }
        let rare_data = Vm::of_cell(self).heap().allocate(|_| DeclarativeEnvironmentRareData {
            header: CellHeader::for_class(DeclarativeEnvironmentRareData::CLASS),
            binding_flags: InterpreterBuffer::new(),
            storage: DeclarativeEnvironmentRareDataStorage::default(),
        });
        self.rare_data.set(Some(rare_data));
        rare_data
    }

    fn drop_rare_data_if_empty(&self) {
        if self.rare_data().is_some_and(|rare_data| rare_data.is_empty()) {
            self.free_rare_data();
        }
    }

    fn free_rare_data(&self) {
        self.rare_data.set(None);
    }

    pub fn binding_values_are_inline(&self) -> bool {
        self.inline_binding_capacity.get() != 0
    }

    fn binding_values(&self) -> BindingValues<'_> {
        BindingValues { environment: self }
    }

    fn increment_environment_serial_number(&self, vm: &Vm) {
        if self.shape.get().is_some() {
            return;
        }
        if self
            .rare_data()
            .is_some_and(|rare_data| rare_data.storage.environment_shape_cache.get().is_some())
        {
            return;
        }
        let Some(global_environment) = self.downcast_ref::<GlobalDeclarativeEnvironment>() else {
            return;
        };
        let serial = global_environment.serial_number.get();
        global_environment.serial_number.set(serial + 1);
        if self.has_dependent_code() {
            crate::jit::dependencies::invalidate_dependents(
                vm,
                Dependency::GlobalDeclarations {
                    environment: CellId(core::ptr::from_ref(self) as u64),
                    serial,
                },
            );
        }
    }

    /// Makes the environment note which bindings are assigned after their initialization, which JIT code may treat
    /// as constants until then. Only the global declarative environment does, which no static environment coordinate
    /// reaches: nothing but `set_mutable_binding_direct()` and SetGlobal, which notes the bindings its caches find,
    /// assigns its bindings.
    pub fn track_binding_assignments(&self) {
        self.ensure_rare_data().storage.tracks_assignments.set(true);
    }

    /// Whether binding `index` may have been assigned since its initialization.
    pub fn binding_may_have_been_assigned(&self, index: usize) -> bool {
        let Some(rare_data) = self
            .rare_data()
            .filter(|rare_data| rare_data.storage.tracks_assignments.get())
        else {
            return true;
        };
        let assigned = rare_data.storage.assigned_bindings.borrow();
        index < assigned.size() && assigned.get(index)
    }

    /// Notes that binding `index` is assigned, or is about to be by code that does not tell the environment, which
    /// invalidates JIT code that depends on it staying unassigned.
    pub fn note_binding_assignment(&self, vm: &Vm, index: usize) {
        let Some(rare_data) = self
            .rare_data()
            .filter(|rare_data| rare_data.storage.tracks_assignments.get())
        else {
            return;
        };
        {
            let mut assigned = rare_data.storage.assigned_bindings.borrow_mut();
            if index < assigned.size() && assigned.get(index) {
                return;
            }
            if index >= assigned.size() {
                let size = (index + 1).next_power_of_two().max(64);
                assigned.grow(size, false);
            }
            assigned.set(index, true);
        }
        if rare_data.storage.has_dependent_code.get() {
            crate::jit::dependencies::invalidate_dependents(
                vm,
                Dependency::GlobalBindingUnassigned {
                    environment: CellId(core::ptr::from_ref(self) as u64),
                    index: u32::try_from(index).expect("binding indices fit in u32"),
                },
            );
        }
    }

    fn has_dependent_code(&self) -> bool {
        self.rare_data()
            .is_some_and(|rare_data| rare_data.storage.has_dependent_code.get())
    }

    /// Notes that JIT code depends on the environment getting no bindings, or on bindings of it staying unassigned.
    pub fn set_has_dependent_code(&self) {
        self.ensure_rare_data().storage.has_dependent_code.set(true);
    }

    pub fn is_catch_environment(&self) -> bool {
        self.rare_data()
            .is_some_and(|rare_data| rare_data.storage.is_catch_environment.get())
    }

    pub fn set_is_catch_environment(&self, value: bool) {
        if !value && self.rare_data().is_none() {
            return;
        }
        self.ensure_rare_data().storage.is_catch_environment.set(value);
        self.drop_rare_data_if_empty();
    }

    pub fn environment_serial_number(&self) -> u64 {
        self.downcast_ref::<GlobalDeclarativeEnvironment>()
            .expect("only global declarative environments have a serial number")
            .serial_number
            .get()
    }

    pub fn dispose_capability(&self) -> &GcRefCell<DisposeCapability> {
        let rare_data = self.ensure_rare_data();
        // SAFETY: The environment keeps its rare data alive, and only lets it go when it is empty, which having a
        //         disposable resource stack keeps it from being.
        &unsafe { &*rare_data.as_ptr() }.storage.dispose_capability
    }

    pub fn dispose_capability_if_exists(&self) -> Option<&GcRefCell<DisposeCapability>> {
        let rare_data = self.rare_data()?;
        // SAFETY: As for dispose_capability().
        let dispose_capability = &unsafe { &*rare_data.as_ptr() }.storage.dispose_capability;
        let exists = dispose_capability.borrow().disposable_resource_stack.is_some();
        exists.then_some(dispose_capability)
    }

    fn shape_binding_count(&self) -> usize {
        self.shape.get().map_or(0, |shape| shape.size())
    }

    fn binding_count(&self) -> usize {
        self.binding_values().size()
    }

    fn local_binding_index(&self, index: usize) -> usize {
        index - self.shape_binding_count()
    }

    fn append_binding(&self, binding: Binding) {
        let index = self.binding_values().size();

        let mut flags = 0;
        if binding.strict {
            flags |= Self::BINDING_FLAG_STRICT;
        }
        if binding.mutable {
            flags |= Self::BINDING_FLAG_MUTABLE;
        }
        if binding.can_be_deleted {
            flags |= Self::BINDING_FLAG_CAN_BE_DELETED;
        }

        if let Some(shape) = self.shape.get()
            && index < shape.size()
        {
            assert!(shape.binding_name(index) == &binding.name);
            assert!(shape.binding_flags(index) == flags);
        } else {
            let rare_data = self.ensure_rare_data();
            rare_data
                .storage
                .bindings_assoc
                .borrow_mut()
                .insert(binding.name.clone(), index);
            rare_data.storage.binding_names.borrow_mut().push(binding.name);
            rare_data.binding_flags.append(flags);
        }

        if self.binding_values_are_inline() && index == self.binding_values().capacity() {
            self.move_binding_values_out_of_cell(index + 1);
        }
        self.binding_values().append(if binding.initialized {
            binding.value
        } else {
            Value::EMPTY
        });
    }

    fn clear_binding(&self, name: &Utf16FlyString, index: usize) {
        if index < self.shape_binding_count() {
            self.ensure_deleted_bindings_capacity(index + 1);
            let rare_data = self
                .rare_data()
                .expect("ensure_deleted_bindings_capacity allocates the rare data");
            rare_data.storage.deleted_bindings.borrow_mut().set(index, true);
            self.binding_values().set(index, Value::EMPTY);
            return;
        }

        let rare_data = self
            .rare_data()
            .expect("bindings outside the shape are in the rare data");
        rare_data.storage.bindings_assoc.borrow_mut().remove(name);
        let local_index = self.local_binding_index(index);
        rare_data.storage.binding_names.borrow_mut()[local_index] = Utf16FlyString::default();
        self.binding_values().set(index, Value::EMPTY);
        rare_data.binding_flags.set(local_index, 0);
    }

    fn ensure_deleted_bindings_capacity(&self, needed_capacity: usize) {
        let rare_data = self.ensure_rare_data();
        let mut deleted_bindings = rare_data.storage.deleted_bindings.borrow_mut();
        if needed_capacity <= deleted_bindings.size() {
            return;
        }
        deleted_bindings.grow(needed_capacity.div_ceil(8) * 8, false);
    }

    fn binding_at(&self, index: usize) -> Binding {
        Binding {
            name: self.binding_name(index),
            value: self.binding_values().get(index),
            strict: self.binding_is_strict(index),
            mutable: self.binding_is_mutable(index),
            can_be_deleted: self.binding_can_be_deleted(index),
            initialized: self.binding_is_initialized(index),
        }
    }

    fn binding_name(&self, index: usize) -> Utf16FlyString {
        if let Some(shape) = self.shape.get()
            && index < shape.size()
        {
            return shape.binding_name(index).clone();
        }
        let rare_data = self
            .rare_data()
            .expect("bindings outside the shape are in the rare data");
        rare_data.storage.binding_names.borrow()[self.local_binding_index(index)].clone()
    }

    fn binding_flags(&self, index: usize) -> u8 {
        if let Some(shape) = self.shape.get()
            && index < shape.size()
        {
            return shape.binding_flags(index);
        }
        let rare_data = self
            .rare_data()
            .expect("bindings outside the shape are in the rare data");
        rare_data.binding_flags.get(self.local_binding_index(index))
    }

    fn binding_is_strict(&self, index: usize) -> bool {
        (self.binding_flags(index) & Self::BINDING_FLAG_STRICT) != 0
    }

    pub(crate) fn binding_is_mutable(&self, index: usize) -> bool {
        (self.binding_flags(index) & Self::BINDING_FLAG_MUTABLE) != 0
    }

    /// Whether binding `index` is one the environment's shape declares mutable and never deleted, which every
    /// environment with the shape declares the same way.
    #[cfg(feature = "jit")]
    pub(crate) fn binding_is_declared_mutable(&self, index: usize) -> bool {
        let Some(shape) = self.shape.get() else {
            return false;
        };
        if index >= shape.size() {
            return false;
        }
        let flags = shape.binding_flags(index);
        flags & Self::BINDING_FLAG_MUTABLE != 0 && flags & Self::BINDING_FLAG_CAN_BE_DELETED == 0
    }

    fn binding_can_be_deleted(&self, index: usize) -> bool {
        (self.binding_flags(index) & Self::BINDING_FLAG_CAN_BE_DELETED) != 0
    }

    fn binding_is_initialized(&self, index: usize) -> bool {
        !self.binding_values().get(index).is_empty()
    }

    fn binding_is_deleted(&self, index: usize) -> bool {
        self.rare_data().is_some_and(|rare_data| {
            let deleted_bindings = rare_data.storage.deleted_bindings.borrow();
            !deleted_bindings.is_null() && deleted_bindings.get(index)
        })
    }

    pub fn set_environment_shape_cache(&self, cache: EnvironmentShapeCache, expected_binding_count: usize) {
        if expected_binding_count == 0 {
            return;
        }

        if let Some(shape) = cache.shape() {
            assert!(shape.size() == expected_binding_count);
            self.set_environment_shape(shape);
            return;
        }

        let rare_data = self.ensure_rare_data();
        rare_data.storage.environment_shape_cache.set(Some(cache));
        rare_data.storage.expected_binding_count.set(expected_binding_count);
    }

    fn set_environment_shape(&self, shape: Gc<EnvironmentShape>) {
        assert!(self.shape.get().is_none());
        assert!(self.binding_values().size() <= shape.size());

        self.shape.set(Some(shape));
        if let Some(rare_data) = self.rare_data() {
            rare_data.storage.binding_names.replace(Vec::new());
            rare_data.binding_flags.clear();
            rare_data.storage.bindings_assoc.replace(HashMap::default());
            rare_data.storage.environment_shape_cache.set(None);
            rare_data.storage.expected_binding_count.set(0);
            self.drop_rare_data_if_empty();
        }
    }

    fn maybe_finalize_environment_shape(&self, vm: &Vm) {
        let Some(rare_data) = self.rare_data() else {
            return;
        };
        let Some(cache) = rare_data.storage.environment_shape_cache.get() else {
            return;
        };
        let expected_binding_count = rare_data.storage.expected_binding_count.get();
        if self.shape.get().is_some() || expected_binding_count == 0 || self.binding_count() != expected_binding_count {
            return;
        }

        if let Some(shape) = cache.shape() {
            assert!(shape.size() == self.binding_count());
            {
                let binding_names = rare_data.storage.binding_names.borrow();
                for (index, binding_name) in binding_names.iter().enumerate().take(self.binding_count()) {
                    assert!(shape.binding_name(index) == binding_name);
                    assert!(shape.binding_flags(index) == rare_data.binding_flags.get(index));
                }
            }
            self.set_environment_shape(shape);
            return;
        }

        // The names and flags are copied out, since creating the shape allocates.
        let binding_names = rare_data.storage.binding_names.borrow().clone();
        let binding_flags = rare_data.binding_flags.to_vec();
        let shape = EnvironmentShape::create(vm, &binding_names, &binding_flags);
        cache.set_shape(shape);
        self.set_environment_shape(shape);
    }

    /// Finds a binding the way the class of the environment does; ModuleEnvironment overrides this.
    pub(crate) fn find_binding_and_index(&self, name: &Utf16FlyString) -> Option<BindingAndIndex> {
        if self.class().id == ClassId::ModuleEnvironment {
            let module_environment = self
                .downcast_ref::<ModuleEnvironment>()
                .expect("the environment is a module environment");
            return module_environment.find_binding_and_index(name);
        }
        self.declarative_find_binding_and_index(name)
    }

    /// DeclarativeEnvironment::find_binding_and_index itself, for the classes that override it.
    pub(crate) fn declarative_find_binding_and_index(&self, name: &Utf16FlyString) -> Option<BindingAndIndex> {
        if let Some(shape) = self.shape.get()
            && let Some(index) = shape.find_binding(name)
            && index < self.binding_count()
            && !self.binding_is_deleted(index)
        {
            return Some(BindingAndIndex::Index(index));
        }

        if let Some(rare_data) = self.rare_data()
            && let Some(&index) = rare_data.storage.bindings_assoc.borrow().get(name)
        {
            return Some(BindingAndIndex::Index(index));
        }

        None
    }

    // 9.1.1.1.1 HasBinding ( N ), https://tc39.es/ecma262/#sec-declarative-environment-records-hasbinding-n
    pub fn has_binding(&self, name: &Utf16FlyString, out_index: Option<&mut Option<usize>>) -> ThrowCompletionOr<bool> {
        let Some(binding_and_index) = self.find_binding_and_index(name) else {
            return Ok(false);
        };
        if !self.is_permanently_screwed_by_eval()
            && let Some(out_index) = out_index
            && let Some(index) = binding_and_index.index()
        {
            *out_index = Some(index);
        }
        Ok(true)
    }

    // 9.1.1.1.2 CreateMutableBinding ( N, D ), https://tc39.es/ecma262/#sec-declarative-environment-records-createmutablebinding-n-d
    pub fn create_mutable_binding(
        &self,
        vm: &Vm,
        name: &Utf16FlyString,
        can_be_deleted: bool,
    ) -> ThrowCompletionOr<()> {
        // 1. Assert: envRec does not already have a binding for N.
        // NOTE: We skip this to avoid O(n) traversal of m_binding_names.

        // 2. Create a mutable binding in envRec for N and record that it is uninitialized. If D is true, record that the newly created binding may be deleted by a subsequent DeleteBinding call.
        self.append_binding(Binding {
            name: name.clone(),
            value: Value::UNDEFINED,
            strict: false,
            mutable: true,
            can_be_deleted,
            initialized: false,
        });
        self.maybe_finalize_environment_shape(vm);

        self.increment_environment_serial_number(vm);

        // 3. Return unused.
        Ok(())
    }

    // 9.1.1.1.3 CreateImmutableBinding ( N, S ), https://tc39.es/ecma262/#sec-declarative-environment-records-createimmutablebinding-n-s
    pub fn create_immutable_binding(&self, vm: &Vm, name: &Utf16FlyString, strict: bool) -> ThrowCompletionOr<()> {
        // 1. Assert: envRec does not already have a binding for N.
        // NOTE: We skip this to avoid O(n) traversal of m_binding_names.

        // 2. Create an immutable binding in envRec for N and record that it is uninitialized. If S is true, record that the newly created binding is a strict binding.
        self.append_binding(Binding {
            name: name.clone(),
            value: Value::UNDEFINED,
            strict,
            mutable: false,
            can_be_deleted: false,
            initialized: false,
        });
        self.maybe_finalize_environment_shape(vm);

        self.increment_environment_serial_number(vm);

        // 3. Return unused.
        Ok(())
    }

    // 9.1.1.1.4 InitializeBinding ( N, V ), https://tc39.es/ecma262/#sec-declarative-environment-records-initializebinding-n-v
    // 4.1.1.1.1 InitializeBinding ( N, V, hint ), https://tc39.es/proposal-explicit-resource-management/#sec-declarative-environment-records
    pub fn initialize_binding(
        &self,
        vm: &Vm,
        name: &Utf16FlyString,
        value: Value,
        hint: InitializeBindingHint,
    ) -> ThrowCompletionOr<()> {
        let index = self
            .find_binding_and_index(name)
            .and_then(|binding_and_index| binding_and_index.index())
            .expect("InitializeBinding is only performed on a binding of the environment itself");
        self.initialize_binding_direct(vm, index, value, hint)
    }

    pub fn initialize_binding_direct(
        &self,
        vm: &Vm,
        index: usize,
        value: Value,
        hint: InitializeBindingHint,
    ) -> ThrowCompletionOr<()> {
        // 1. Assert: envRec must have an uninitialized binding for N.
        assert!(!self.binding_is_initialized(index));
        assert!(!value.is_empty());

        // 2. If hint is not normal, perform ? AddDisposableResource(envRec.[[DisposeCapability]], V, hint).
        if hint != InitializeBindingHint::Normal {
            add_disposable_resource(vm, self.dispose_capability(), value, hint, None)?;
        }

        // 3. Set the bound value for N in envRec to V.
        self.binding_values().set(index, value);

        // 5. Return unused.
        Ok(())
    }

    // 9.1.1.1.5 SetMutableBinding ( N, V, S ), https://tc39.es/ecma262/#sec-declarative-environment-records-setmutablebinding-n-v-s
    pub fn set_mutable_binding(
        &self,
        vm: &Vm,
        name: &Utf16FlyString,
        value: Value,
        strict: bool,
    ) -> ThrowCompletionOr<()> {
        // 1. If envRec does not have a binding for N, then
        let Some(binding_and_index) = self.find_binding_and_index(name) else {
            // a. If S is true, throw a ReferenceError exception.
            if strict {
                return vm.throw_completion(ErrorKind::ReferenceError, ErrorType::UnknownIdentifier, &[name]);
            }

            // b. Perform ! envRec.CreateMutableBinding(N, true).
            self.create_mutable_binding(vm, name, true)
                .expect("CreateMutableBinding cannot fail");

            // c. Perform ! envRec.InitializeBinding(N, V, normal).
            self.initialize_binding(vm, name, value, InitializeBindingHint::Normal)
                .expect("a normal InitializeBinding cannot fail");

            // d. Return unused.
            return Ok(());
        };

        // 2-5. (extracted into a non-standard function below)
        if let Some(index) = binding_and_index.index() {
            self.set_mutable_binding_direct(vm, index, value, strict)?;
        } else {
            let mut binding = binding_and_index.binding(self);
            self.set_mutable_binding_of_binding(vm, &mut binding, value, strict)?;
        }

        // 6. Return unused.
        Ok(())
    }

    pub fn set_mutable_binding_direct(
        &self,
        vm: &Vm,
        index: usize,
        value: Value,
        strict: bool,
    ) -> ThrowCompletionOr<()> {
        self.note_binding_assignment(vm, index);
        let strict = strict || self.binding_is_strict(index);

        if !self.binding_is_initialized(index) {
            return vm.throw_completion(
                ErrorKind::ReferenceError,
                ErrorType::BindingNotInitialized,
                &[&self.binding_name(index)],
            );
        }

        if self.binding_is_mutable(index) {
            self.binding_values().set(index, value);
        } else if strict {
            return vm.throw_completion(ErrorKind::TypeError, ErrorType::InvalidAssignToConst, &[]);
        }

        Ok(())
    }

    /// set_mutable_binding_direct for a binding found outside the environment's own storage.
    fn set_mutable_binding_of_binding(
        &self,
        vm: &Vm,
        binding: &mut Binding,
        value: Value,
        strict: bool,
    ) -> ThrowCompletionOr<()> {
        let strict = strict || binding.strict;

        if !binding.initialized {
            return vm.throw_completion(
                ErrorKind::ReferenceError,
                ErrorType::BindingNotInitialized,
                &[&binding.name],
            );
        }

        if binding.mutable {
            binding.value = value;
        } else if strict {
            return vm.throw_completion(ErrorKind::TypeError, ErrorType::InvalidAssignToConst, &[]);
        }

        Ok(())
    }

    // 9.1.1.1.6 GetBindingValue ( N, S ), https://tc39.es/ecma262/#sec-declarative-environment-records-getbindingvalue-n-s
    pub fn get_binding_value(&self, vm: &Vm, name: &Utf16FlyString, _strict: bool) -> ThrowCompletionOr<Value> {
        // 1. Assert: envRec has a binding for N.
        let binding_and_index = self
            .find_binding_and_index(name)
            .expect("GetBindingValue is only performed on a binding the environment has");

        // 2-3. (extracted into a non-standard function below)
        if let Some(index) = binding_and_index.index() {
            return self.get_binding_value_direct(vm, index);
        }

        let binding = binding_and_index.binding(self);
        self.get_binding_value_of_binding(vm, &binding)
    }

    pub fn get_binding_value_direct(&self, vm: &Vm, index: usize) -> ThrowCompletionOr<Value> {
        if !self.binding_is_initialized(index) {
            return vm.throw_completion(
                ErrorKind::ReferenceError,
                ErrorType::BindingNotInitialized,
                &[&self.binding_name(index)],
            );
        }

        Ok(self.binding_values().get(index))
    }

    pub fn get_initialized_binding_value_direct(&self, index: usize) -> Value {
        self.binding_values().get(index)
    }

    /// get_binding_value_direct for a binding found outside the environment's own storage.
    fn get_binding_value_of_binding(&self, vm: &Vm, binding: &Binding) -> ThrowCompletionOr<Value> {
        // 2. If the binding for N in envRec is an uninitialized binding, throw a ReferenceError exception.
        if !binding.initialized {
            return vm.throw_completion(
                ErrorKind::ReferenceError,
                ErrorType::BindingNotInitialized,
                &[&binding.name],
            );
        }

        // 3. Return the value currently bound to N in envRec.
        Ok(binding.value)
    }

    // 9.1.1.1.7 DeleteBinding ( N ), https://tc39.es/ecma262/#sec-declarative-environment-records-deletebinding-n
    pub fn delete_binding(&self, vm: &Vm, name: &Utf16FlyString) -> ThrowCompletionOr<bool> {
        // 1. Assert: envRec has a binding for the name that is the value of N.
        let binding_and_index = self
            .find_binding_and_index(name)
            .expect("DeleteBinding is only performed on a binding the environment has");

        // 2. If the binding for N in envRec cannot be deleted, return false.
        let Some(index) = binding_and_index.index() else {
            if !binding_and_index.binding(self).can_be_deleted {
                return Ok(false);
            }
            unreachable!("only bindings of the environment itself can be deleted");
        };

        if !self.binding_can_be_deleted(index) {
            return Ok(false);
        }

        // 3. Remove the binding for N from envRec.
        // NOTE: We keep the entry in the parallel vectors to avoid disturbing indices.
        self.clear_binding(name, index);

        self.increment_environment_serial_number(vm);

        // 4. Return true.
        Ok(true)
    }

    /// This is not a method defined in the spec! Do not use this in any LibJS (or other spec related) code.
    pub fn bindings(&self) -> Vec<Utf16FlyString> {
        let mut names = Vec::with_capacity(self.binding_count());

        let shape_bindings_to_visit = self.shape_binding_count().min(self.binding_count());
        if let Some(shape) = self.shape.get() {
            for index in 0..shape_bindings_to_visit {
                let name = shape.binding_name(index);
                if !self.binding_is_deleted(index) && !name.is_empty() {
                    names.push(name.clone());
                }
            }
        }

        if let Some(rare_data) = self.rare_data() {
            for name in rare_data.storage.binding_names.borrow().iter() {
                if !name.is_empty() {
                    names.push(name.clone());
                }
            }
        }

        names
    }

    pub fn binding_is_mutable_by_name(&self, name: &Utf16FlyString) -> bool {
        let binding = self
            .find_binding_and_index(name)
            .expect("the environment has a binding for the name");
        binding.binding(self).mutable
    }

    pub fn binding_index(&self, name: &Utf16FlyString) -> Option<usize> {
        self.find_binding_and_index(name)?.index()
    }

    /// Creates the binding the environment's shape has next, with Value::EMPTY, if the shape names it `name` with
    /// `flags` and has no other binding of that name, and returns whether it did. The binding is then the one
    /// CreateMutableBinding or CreateImmutableBinding would create, and HasBinding(name) would have returned false
    /// before. This is how the bindings of an environment that has its final shape from the start get created.
    pub fn create_next_binding_of_shape(&self, name: &Utf16FlyString, flags: u8) -> bool {
        let Some(shape) = self.shape.get() else {
            return false;
        };
        let index = self.binding_values().size();
        if !shape.has_unique_binding_names
            || index >= shape.size()
            || shape.binding_name(index) != name
            || shape.binding_flags(index) != flags
            || self.class().id == ClassId::ModuleEnvironment
        {
            return false;
        }
        if self.binding_values_are_inline() && index == self.binding_values().capacity() {
            self.move_binding_values_out_of_cell(index + 1);
        }
        self.binding_values().append(Value::EMPTY);
        true
    }

    fn move_binding_values_out_of_cell(&self, needed_capacity: usize) {
        self.binding_values().move_to_owned_storage(needed_capacity);
    }

    pub fn ensure_capacity(&self, needed_capacity: usize) {
        if needed_capacity > self.binding_values().capacity() && self.binding_values_are_inline() {
            self.move_binding_values_out_of_cell(needed_capacity);
        }
        self.binding_values().ensure_capacity(needed_capacity);
        if self.shape.get().is_some() || needed_capacity == 0 {
            return;
        }

        let rare_data = self.ensure_rare_data();
        {
            let mut binding_names = rare_data.storage.binding_names.borrow_mut();
            let additional_capacity = needed_capacity.saturating_sub(binding_names.len());
            binding_names.reserve_exact(additional_capacity);
        }
        rare_data.binding_flags.ensure_capacity(needed_capacity);
    }

    pub fn shrink_to_fit(&self) {
        if !self.binding_values_are_inline() {
            self.binding_values().shrink_to_fit();
        }

        let Some(rare_data) = self.rare_data() else {
            return;
        };

        rare_data.storage.binding_names.borrow_mut().shrink_to_fit();
        rare_data.binding_flags.shrink_to_fit();

        if self.binding_values().is_empty() {
            rare_data.storage.deleted_bindings.replace(Bitmap::default());
            self.drop_rare_data_if_empty();
            return;
        }

        if rare_data.storage.deleted_bindings.borrow().is_null() {
            self.drop_rare_data_if_empty();
            return;
        }

        let mut deleted_bindings = Bitmap::create(self.binding_values().size(), false);
        for index in 0..self.binding_values().size() {
            deleted_bindings.set(index, self.binding_is_deleted(index));
        }
        rare_data.storage.deleted_bindings.replace(deleted_bindings);
        self.drop_rare_data_if_empty();
    }
}