Files
vectorcraft/crates/js/src/interp.rs
T
dotCooCoo 1d6af09cff Scripts: a stop from end when show() fails ends the run
When show() failed (an answer that could not be read, a host call that
threw, or a handler that threw), the dialog's failure function called the
host's end and dropped its result, so an Abort from end did not stop the
run and the script could catch the error and finish. The failure function
now returns that stop, and the answer and call paths end the run with it
before the error reaches the script.
2026-11-30 17:59:40 -08:00

4841 lines
219 KiB
Rust

//! The interpreter: runs bytecode on an explicit stack of frames.
//!
//! A call to a function written in JavaScript pushes a frame and goes on in the same loop, so
//! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call
//! only where the language needs a function's result in the middle of an operation (a getter or
//! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are
//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own,
//! which `yield` moves into the generator object, operands included, and a call to its `next`,
//! `return` or `throw` pushes again ([`crate::generator`]).
//!
//! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and,
//! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap
//! limit, the frame limit, the re-entry limit and the interrupt flag each end the run with an
//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks. Source
//! compiled during a run takes a unit of fuel for each code unit before it is parsed.
//!
//! Collection runs only between instructions. An operation that may run JavaScript in the middle
//! keeps its operands on the operand stack until it is done, so everything it holds is reachable
//! from the roots when a nested run collects.
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::ast::BinaryOp;
use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source};
use crate::compiler::{CompileFail, compile_program};
use crate::heap::{
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES,
OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
};
use crate::parser::SuperRules;
use crate::string_builtins::flat_charged;
use crate::symbol::PropKey;
use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32};
use crate::{LimitKind, Limits, Options};
/// How an operation ended other than normally.
#[derive(Debug)]
pub(crate) enum Abrupt {
/// A JavaScript exception: `try` and `catch` can handle it.
Throw(Value),
/// A limit was reached; nothing handles it.
Limit(LimitKind),
/// The interpreter found itself in a state it never makes (a bug); nothing handles it.
Internal(String),
}
pub(crate) type JsResult<T> = Result<T, Abrupt>;
/// The binding that holds an arrow function's `this` in the environment it closes over, and a
/// derived class constructor's `this` in its function environment. It starts with a NUL, which no
/// identifier holds.
pub(crate) const ARROW_THIS: &[u16] = &[0, 0x74, 0x68, 0x69, 0x73];
pub(crate) fn internal<T>(message: &str) -> JsResult<T> {
Err(Abrupt::Internal(message.into()))
}
/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]).
fn description_hash(text: &str) -> u64 {
let mut h = DescriptionHash::default();
h.text(text);
h.finish()
}
/// A [`description_hash`] fed the description's code units a run at a time, so a long string is
/// hashed without being copied.
#[derive(Default)]
struct DescriptionHash(std::hash::DefaultHasher);
impl DescriptionHash {
fn units(&mut self, units: &[u16]) {
use std::hash::Hasher;
for &u in units {
self.0.write_u16(u);
}
}
fn text(&mut self, text: &str) {
use std::hash::Hasher;
for u in text.encode_utf16() {
self.0.write_u16(u);
}
}
fn finish(&self) -> u64 {
use std::hash::Hasher;
self.0.finish()
}
}
/// The kinds of error object the engine throws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ErrorType {
Error,
Eval,
Range,
Reference,
Syntax,
Type,
Uri,
}
impl ErrorType {
/// The `name` the prototype of this kind of error has before a script changes it.
pub(crate) fn name(self) -> &'static str {
match self {
ErrorType::Error => "Error",
ErrorType::Eval => "EvalError",
ErrorType::Range => "RangeError",
ErrorType::Reference => "ReferenceError",
ErrorType::Syntax => "SyntaxError",
ErrorType::Type => "TypeError",
ErrorType::Uri => "URIError",
}
}
}
/// The objects the interpreter itself refers to.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Intrinsics {
pub(crate) object_proto: ObjId,
pub(crate) function_proto: ObjId,
pub(crate) array_proto: ObjId,
pub(crate) string_proto: ObjId,
pub(crate) number_proto: ObjId,
pub(crate) boolean_proto: ObjId,
pub(crate) regexp_proto: ObjId,
pub(crate) date_proto: ObjId,
pub(crate) error_protos: [ObjId; 7],
pub(crate) eval: ObjId,
pub(crate) throw_type_error: ObjId,
/// The `XML` constructor, which holds the XML settings.
pub(crate) xml_ctor: ObjId,
pub(crate) xml_proto: ObjId,
pub(crate) xml_list_proto: ObjId,
pub(crate) namespace_proto: ObjId,
pub(crate) qname_proto: ObjId,
/// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]).
pub(crate) es2015: crate::builtins::collections::Es2015,
}
impl Intrinsics {
fn placeholder() -> Self {
let o = ObjId(0);
Self {
object_proto: o,
function_proto: o,
array_proto: o,
string_proto: o,
number_proto: o,
boolean_proto: o,
regexp_proto: o,
date_proto: o,
error_protos: [o; 7],
eval: o,
throw_type_error: o,
xml_ctor: o,
xml_proto: o,
xml_list_proto: o,
namespace_proto: o,
qname_proto: o,
es2015: crate::builtins::collections::Es2015::placeholder(),
}
}
pub(crate) fn error_proto(&self, t: ErrorType) -> ObjId {
let i = match t {
ErrorType::Error => 0,
ErrorType::Eval => 1,
ErrorType::Range => 2,
ErrorType::Reference => 3,
ErrorType::Syntax => 4,
ErrorType::Type => 5,
ErrorType::Uri => 6,
};
self.error_protos.get(i).copied().unwrap_or(self.object_proto)
}
fn all(&self) -> Vec<ObjId> {
let mut v = vec![
self.object_proto,
self.function_proto,
self.array_proto,
self.string_proto,
self.number_proto,
self.boolean_proto,
self.regexp_proto,
self.date_proto,
self.eval,
self.throw_type_error,
self.xml_ctor,
self.xml_proto,
self.xml_list_proto,
self.namespace_proto,
self.qname_proto,
];
v.extend(self.error_protos);
v.extend(self.es2015.all());
v
}
}
pub(crate) struct Frame {
pub(crate) code: Rc<Code>,
pub(crate) pc: usize,
/// Where this frame's operands start on the operand stack.
pub(crate) base: usize,
pub(crate) env: EnvId,
pub(crate) var_env: EnvId,
/// `with` and catch environments entered and not yet left.
pub(crate) env_depth: u32,
pub(crate) this: Value,
/// `this` is the binding of the environment chain that an arrow function or a derived class
/// constructor reads, not [`Self::this`]: in such code and in the direct eval code it runs.
pub(crate) this_in_env: bool,
/// The frame is running a class's heritage or computed keys, which are strict mode code
/// (ECMA-262 2015 section 10.2.1) inside code that is not.
pub(crate) strict_class: bool,
pub(crate) callee: Option<ObjId>,
/// The object `new` made, returned unless the function returns an object.
pub(crate) construct: Option<ObjId>,
/// `new.target` of a function that was constructed.
pub(crate) new_target: Option<ObjId>,
/// The environment of a derived class constructor's `this`, function object and
/// `new.target`, which `super(…)` reads.
pub(crate) this_env: Option<EnvId>,
pub(crate) completion: Value,
/// Returning from this frame returns from the Rust call that pushed it.
pub(crate) boundary: bool,
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
pub(crate) generator: Option<ObjId>,
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
pub(crate) chained: bool,
pub(crate) pending_module: bool,
}
/// Where the exception being thrown was raised: the code and the instruction.
pub(crate) type ThrowSite = (Rc<Code>, usize);
/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time.
pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given
/// `this` and the arguments, and gives the host call it makes.
pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult<Pause>;
/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the
/// answer, and gives the result of its call. One that puts another [`Pause`] in
/// [`Interp::again`] makes that host call next, and the call's result is what that pause's
/// resume function gives.
pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult<Value>;
/// What a [`Pause`] does with its kept values when its host call fails. An error it gives that is
/// not thrown (a stop, such as a host's Abort) ends the run in place of a thrown failure; a thrown
/// one gives way to the failure.
pub(crate) type FailFn = fn(&mut Interp, &[Value]) -> JsResult<()>;
/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to
/// `resume` with `keep`, at once when the host answers at once. When the host waits
/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on
/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it.
/// When the host call fails, `failed` is given `keep` before the error is thrown at the call.
pub(crate) struct Pause {
pub(crate) host: Value,
pub(crate) args: Vec<Value>,
pub(crate) keep: Vec<Value>,
pub(crate) resume: ResumeFn,
pub(crate) failed: Option<FailFn>,
}
/// A [`Pause`] whose host call waits for its answer.
pub(crate) struct Resumption {
resume: ResumeFn,
keep: Vec<Value>,
/// Runs when the answer cannot be read, so the resume function never gets it.
failed: Option<FailFn>,
}
impl Resumption {
/// The built-in does not get the host's answer: its failure function runs with its kept
/// values, which `thrown` is kept from collection with. → the stop the failure function
/// gave, which ends the run in place of `thrown`.
pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) -> JsResult<()> {
let Some(failed) = self.failed else { return Ok(()) };
let mark = interp.temp_roots.len();
interp.temp_roots.extend(self.keep.iter().cloned());
interp.temp_roots.push(thrown.clone());
let r = failed(interp, &self.keep);
interp.temp_roots.truncate(mark);
r
}
}
pub(crate) struct Interp {
pub(crate) heap: Heap,
pub(crate) stack: Vec<Value>,
pub(crate) frames: Vec<Frame>,
pending_module_frames: usize,
/// Values native code holds while it may run JavaScript.
pub(crate) temp_roots: Vec<Value>,
/// Environments native code is still building.
temp_envs: Vec<EnvId>,
/// Global and eval code whose frame is not pushed yet, counted against the heap.
temp_codes: Vec<Rc<Code>>,
pub(crate) global: ObjId,
pub(crate) global_env: EnvId,
/// The declarative environment inside `global_env` that holds the `let` and `const` names of
/// the scripts the realm runs with [`Options::es2015`]. Global code runs in it in either
/// language, so a function made by one run sees the names a later run declares.
pub(crate) global_lex: EnvId,
/// The names global code has declared with `var` or as functions on the global object, which
/// a later script's `let` or `const` cannot take (ECMA-262 2015 section 8.1.1.4, its
/// [[VarNames]]). Deleting the global object's property removes its name.
global_vars: std::collections::HashSet<Key>,
/// The [`Options::es2015`] a host set while a run was going, for the runs after it.
pub(crate) next_es2015: Option<bool>,
/// The built-in functions have the `name` and the `length` that can be redefined that
/// ECMAScript 2015 gives them ([`crate::builtins::es2015_names`]): set once the realm first
/// reads code with [`Options::es2015`], and kept after that.
pub(crate) builtin_names: bool,
/// The template objects tagged templates have made, by code and template index, each with
/// its code (ECMA-262 2015 section 12.2.9.3 keeps one object for each site).
pub(crate) template_objects: std::collections::HashMap<(usize, u32), (Rc<Code>, ObjId)>,
pub(crate) intrinsics: Intrinsics,
pub(crate) limits: Limits,
pub(crate) options: Options,
pub(crate) fuel: u64,
pub(crate) interrupt: Arc<AtomicBool>,
pub(crate) reentry: usize,
gc_threshold: usize,
/// UTF-16 code units of source parsed in this run, for [`Options::max_source_units`].
pub(crate) source_units: usize,
pub(crate) throw_site: Option<ThrowSite>,
/// The last exception a run did not catch.
pub(crate) last_thrown: Value,
/// The last `Error` object thrown in this run, caught or not, or `null` (`$.error`).
pub(crate) last_error: Value,
/// An exception passed on rather than thrown again: one a `finally` block restores, or one
/// leaving a nested run. [`Interp::unwind`] does not make it [`Interp::last_error`] again.
pub(crate) passing: Value,
/// The locale `localize` and `Object.prototype.toString` read.
pub(crate) localization: Rc<crate::builtins::extensions::Localization>,
/// The state of `Math.random`'s generator.
pub(crate) random: u64,
/// The objects `Array.prototype.join` and `toLocaleString` are joining, innermost last: a
/// cycle back to one of them joins as an empty string.
pub(crate) join_stack: Vec<ObjId>,
/// Bytes of the string buffers native functions are building outside the heap. They are
/// charged to `heap.bytes` and added back after each collection, and a native call's
/// buffers are released when it returns.
pub(crate) held_bytes: usize,
/// Why installing the built-ins failed; a realm with this set runs no script.
pub(crate) install_error: Option<String>,
/// The typed array whose element count the next array method reads as its length, set while a
/// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read.
pub(crate) typed_length: Option<ObjId>,
/// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]).
pub(crate) files: Option<crate::file_classes::Classes>,
/// `ExternalObject` and the XMP classes it loads, once a host has added them
/// ([`crate::Realm::define_external_object`]).
pub(crate) xmp: Option<crate::xmp_classes::Classes>,
/// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them.
pub(crate) host_classes: Vec<crate::host_classes::Entry>,
/// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`].
pub(crate) write_hosted: bool,
/// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of
/// the same one give the same object. It is not a root: an entry whose object was collected is
/// dropped after each collection.
pub(crate) host_objects: crate::host_classes::Made,
/// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the
/// operators take no object as a measurement.
pub(crate) unit_values: Option<crate::unit_value::Classes>,
/// The clock and time zone `Date` reads.
pub(crate) date_host: crate::date_builtins::DateHost,
/// The bytes native code holds outside the heap's cells through [`HeldBytes`].
pub(crate) held: Rc<HeldCount>,
/// Bytes of the copies [`Self::get_own_property`] made flattening the rope of a String
/// object, which the heap's total adds before the next limit check.
flattened: std::cell::Cell<usize>,
/// Fuel for the units those copies took and the rope nodes it read in place, which the next
/// step takes.
pub(crate) flattened_fuel: std::cell::Cell<u64>,
/// The global code's default XML namespace URI (ECMA-357 section 12.1).
pub(crate) xml_default_uri: Key,
/// Set by the host to end the current slice of a resumable run at the next safe point.
pub(crate) pause: Rc<std::cell::Cell<bool>>,
/// The outermost loop of a resumable run is running ([`crate::Realm::advance`]).
pub(crate) in_slice: bool,
/// True while a host function runs where it may wait ([`crate::HostError::Wait`]).
pub(crate) can_wait: Rc<std::cell::Cell<bool>>,
/// A host function's call waits for its result: the value on top of the stack stands in for it.
pub(crate) waiting: bool,
/// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its
/// answer is read as such a member's result is ([`Interp::write_hosted`]).
pub(crate) waiting_hosted: bool,
/// The answer to the call that waited could not be read as a value
/// ([`crate::Realm::answer`]): the value on top of the stack is the exception, which the next
/// step throws at that call.
pub(crate) answer_throws: bool,
/// A host class's constructor runs with `new`: it may not wait for its result.
pub(crate) constructing: bool,
/// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before
/// the next instruction runs.
pub(crate) resuming: Option<Resumption>,
/// The next host call a resume function asks for ([`ResumeFn`]).
pub(crate) again: Option<Pause>,
/// ScriptUI's `Window` and its controls, when the host added them.
pub(crate) script_ui: Option<crate::scriptui::Classes>,
/// The message of the uncatchable error a host function ended the run with.
pub(crate) host_abort: Option<String>,
/// How much a value passed to or from a host function may carry.
pub(crate) data_limits: crate::DataLimits,
/// The tag the source compiled next gets ([`crate::Realm::error_source`]).
pub(crate) source_tag: u32,
/// The sources [`crate::HostItem::Evaluator`] functions have given in this realm.
pub(crate) evaluated: u32,
/// Called with the source text given to `eval`, `Function` and evaluator functions, before it
/// is compiled ([`crate::Realm::observe_code`]).
pub(crate) code_observer: Option<CodeObserver>,
/// The tag of the source the last run's error was raised in.
pub(crate) error_tag: u32,
/// Where `$.line` and `$.stack` find the file and line of a compiled line.
pub(crate) locator: Option<crate::realm::SourceLocator>,
/// The name of the running script, which `$.stack` writes as its first line.
pub(crate) script_name: Option<String>,
/// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is
/// propagating.
pub(crate) thrown_mark: Option<u32>,
/// The marked exceptions `finally` blocks are running for, innermost last, each with its mark,
/// which the block's end throws it on with, and the stack slot that holds it while the block
/// runs. An entry whose slot no longer holds its exception belongs to a block that `break`,
/// `continue` or `return` left, and [`Self::drop_left_finally_marks`] removes it.
pub(crate) finally_marks: Vec<(ObjId, u32, usize)>,
/// Where the exceptions `finally` blocks are running for were raised, innermost last, each with
/// the stack slot that holds the exception while the block runs. The block's end throws the
/// exception on from that site. An entry whose slot is at or above the stack's length belongs to
/// a block that was left, and [`Self::drop_left_finally_sites`] removes it at each `Jump`, each
/// return and each collection. [`Self::unwind`] removes the entries at or above a handler's slot
/// before it adds one, so the slots rise and the list is never longer than the stack.
pub(crate) finally_sites: Vec<(ThrowSite, usize)>,
/// The mark of the host error the last run ended with.
pub(crate) error_mark: Option<u32>,
/// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs.
pub(crate) strict_writes: bool,
/// `Promise` and the run's promise job queue ([`crate::builtins::promise`]).
pub(crate) promises: crate::builtins::promise::Promises,
/// The well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a
/// realm with [`crate::Options::es2015`].
pub(crate) symbols: crate::symbol::Symbols,
}
/// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's
/// total still counts.
#[derive(Default)]
pub(crate) struct HeldCount {
now: std::cell::Cell<usize>,
released: std::cell::Cell<usize>,
}
/// Bytes that native code holds in Rust memory while it works (a matcher's state and stack, a
/// replacement being built, a pattern being compiled), counted against the heap limit. They are
/// in the heap's total, and in the live total of each collection, until the holder is dropped;
/// the heap's total gives them back before the next limit check.
pub(crate) struct HeldBytes {
count: Rc<HeldCount>,
bytes: usize,
}
impl HeldBytes {
pub(crate) fn new(interp: &Interp) -> Self {
Self { count: interp.held.clone(), bytes: 0 }
}
/// The bytes this holder holds.
#[cfg(test)]
pub(crate) fn bytes(&self) -> usize {
self.bytes
}
/// Holds `n` more bytes, ending the run with the heap limit when they would not fit after a
/// collection. Everything the caller still needs must be reachable from the roots.
pub(crate) fn add(&mut self, interp: &mut Interp, n: usize) -> JsResult<()> {
interp.reserve_heap(n)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(n);
self.bytes = self.bytes.saturating_add(n);
self.count.now.set(self.count.now.get().saturating_add(n));
Ok(())
}
}
impl Drop for HeldBytes {
fn drop(&mut self) {
self.count.now.set(self.count.now.get().saturating_sub(self.bytes));
self.count.released.set(self.count.released.get().saturating_add(self.bytes));
}
}
/// The least heap size a collection waits for.
const MIN_GC_BYTES: usize = 1 << 20;
/// The most arguments `Function.prototype.apply` passes.
pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16;
/// The estimated bytes of a name's entries in the list and the set `for-in` builds.
const KEY_ENTRY_BYTES: usize = 32;
/// The most units of a computed property name an error about a property of `null` or `undefined`
/// names; a longer name is left out of the message.
const NAMED_KEY_UNITS: usize = 256;
#[cfg(test)]
thread_local! {
/// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at.
pub(crate) static SITE_CHECKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// Tests: [`Interp::reserve_heap`] collects garbage each time it is called.
pub(crate) static COLLECT_ON_RESERVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// The estimated bytes of the index names `0` to `len - 1` while `for-in` lists them.
fn index_keys_bytes(len: usize) -> usize {
index_names_bytes(len, KEY_ENTRY_BYTES)
}
/// The bytes of the index names `0` to `len - 1`, each with `per_entry` bytes more, counted by
/// the number of digits without making the names.
fn index_names_bytes(len: usize, per_entry: usize) -> usize {
let mut total = 0usize;
let (mut lo, mut hi, mut digits) = (0usize, 10usize, 1usize);
while lo < len {
let count = hi.min(len) - lo;
total = total.saturating_add(count.saturating_mul(string_bytes(digits) + per_entry));
lo = hi;
hi = hi.saturating_mul(10);
digits += 1;
}
total
}
/// A seed for `Math.random` that differs from realm to realm and from run to run, from the OS
/// random source (the browser's crypto on the web), or the standard library's randomly keyed
/// hasher when that fails; never zero.
fn random_seed() -> u64 {
random_seed_from(getrandom::u64())
}
/// [`random_seed`] from what the OS random source returned.
pub(crate) fn random_seed_from(os: Result<u64, getrandom::Error>) -> u64 {
use std::hash::{BuildHasher, Hasher};
os.unwrap_or_else(|_| {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u64(0x9e37_79b9_7f4a_7c15);
h.finish()
}) | 1
}
/// The estimated bytes of a binding or property named by `len` code units.
pub(crate) fn binding_bytes(len: usize) -> usize {
PROP_BYTES + string_bytes(len)
}
/// At least the bytes that a function object made from `code` adds to the heap: the function,
/// its prototype object, their properties and the environment holding a function expression's
/// own name.
pub(crate) fn closure_bytes(code: &Code) -> usize {
let props = (if code.strict { 5 } else { 3 }) + usize::from(code.own_name.is_some());
let named = code.self_name.as_ref().map_or(0, |n| ENV_BYTES + binding_bytes(n.len()));
2 * OBJECT_BYTES + props * binding_bytes("constructor".len()) + named
}
/// At least the bytes that declaration binding instantiation (section 10.5) adds to the heap for
/// the function declarations and variables of `code`.
fn declaration_bytes(code: &Code) -> usize {
let funs = code.fun_decls.iter().fold(0usize, |total, (name, fi)| {
let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f));
total.saturating_add(binding_bytes(name.len()) + closure)
});
code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len())))
}
/// At least the bytes that [`Interp::block_env`] adds to the heap for `code.scopes[i]`: the
/// environment, its names and the closures of its function declarations.
fn scope_bytes(code: &Code, i: u32) -> usize {
let Some(scope) = code.scopes.get(i as usize) else { return ENV_BYTES };
let funcs = scope.funcs.iter().map(|(_, fi)| code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f))).sum::<usize>();
let names = scope.lets.iter().map(|(k, _)| k).chain(scope.funcs.iter().map(|(k, _)| k)).map(|k| binding_bytes(k.len())).sum::<usize>();
ENV_BYTES.saturating_add(funcs).saturating_add(names)
}
/// At least the bytes that the `arguments` object of a call with `args` arguments adds to the
/// heap: the object, its map of argument names, an element for each argument and its other
/// properties.
fn arguments_bytes(args: usize) -> usize {
let names = crate::heap::ARG_NAME_BYTES.saturating_mul(args);
OBJECT_BYTES.saturating_add(names).saturating_add(args.saturating_add(4).saturating_mul(binding_bytes(10)))
}
/// A call to a function written in JavaScript, ready to enter; `new_target` is set when it is
/// constructed.
pub(crate) struct Entry {
pub(crate) callee: ObjId,
pub(crate) code: Rc<Code>,
pub(crate) env: EnvId,
pub(crate) this: Value,
pub(crate) args: Vec<Value>,
pub(crate) new_target: Option<ObjId>,
}
/// What a call resolved to.
pub(crate) enum Prepared {
Closure(Entry),
Done(Value),
/// A generator's `next`, `return` or `throw` that goes on with its body.
Resume(Box<crate::generator::Resumed>),
}
/// A variable found in the environment chain.
enum Resolved {
Decl(EnvId),
Obj { object: ObjId, with_this: bool },
Unresolved,
}
/// A reference base as an operand: a declarative environment's index as a number, a binding
/// object as itself, and an unresolvable reference as `undefined`. The environment stays
/// reachable through the frame's environment chain while the operand is on the stack.
fn resolved_to_value(r: &Resolved) -> Value {
match r {
Resolved::Decl(e) => Value::Number(f64::from(e.0)),
Resolved::Obj { object, .. } => Value::Object(*object),
Resolved::Unresolved => Value::Undefined,
}
}
fn value_to_resolved(v: &Value) -> JsResult<Resolved> {
match v {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Value::Number(n) if *n >= 0.0 && *n <= f64::from(u32::MAX) && n.fract() == 0.0 => Ok(Resolved::Decl(EnvId(*n as u32))),
Value::Object(object) => Ok(Resolved::Obj { object: *object, with_this: false }),
Value::Undefined => Ok(Resolved::Unresolved),
_ => internal("not a reference base"),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Hint {
Default,
Number,
String,
}
fn is(k: &[u16], s: &str) -> bool {
k.len() == s.len() && k.iter().zip(s.bytes()).all(|(&a, b)| a == u16::from(b))
}
impl Interp {
pub(crate) fn new(options: Options, limits: Limits) -> Self {
let mut heap = Heap::default();
let global = heap.alloc_object(Object::new(Class::Ordinary, None));
let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None });
let global_lex = heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(global_env) });
let mut interp = Self {
heap,
stack: Vec::new(),
frames: Vec::new(),
pending_module_frames: 0,
temp_roots: Vec::new(),
temp_envs: Vec::new(),
temp_codes: Vec::new(),
global,
global_env,
global_lex,
global_vars: std::collections::HashSet::new(),
next_es2015: None,
builtin_names: false,
template_objects: std::collections::HashMap::new(),
intrinsics: Intrinsics::placeholder(),
fuel: u64::MAX,
// The built-ins are installed without limits; the realm's limits apply from the
// first run.
limits: Limits { fuel: u64::MAX, heap_bytes: usize::MAX, frames: usize::MAX, reentry: usize::MAX },
options,
interrupt: Arc::new(AtomicBool::new(false)),
reentry: 0,
gc_threshold: MIN_GC_BYTES,
source_units: 0,
throw_site: None,
last_thrown: Value::Undefined,
last_error: Value::Null,
passing: Value::Undefined,
localization: Rc::default(),
random: random_seed(),
join_stack: Vec::new(),
held_bytes: 0,
install_error: None,
typed_length: None,
files: None,
xmp: None,
host_classes: Vec::new(),
write_hosted: false,
host_objects: crate::host_classes::Made::default(),
unit_values: None,
date_host: crate::date_builtins::DateHost::default(),
held: Rc::default(),
flattened: std::cell::Cell::new(0),
flattened_fuel: std::cell::Cell::new(0),
xml_default_uri: Rc::from(Vec::new()),
pause: Rc::default(),
in_slice: false,
can_wait: Rc::default(),
waiting: false,
waiting_hosted: false,
answer_throws: false,
constructing: false,
resuming: None,
again: None,
script_ui: None,
host_abort: None,
data_limits: crate::DataLimits::default(),
source_tag: crate::realm::UNKNOWN_SOURCE,
evaluated: 0,
code_observer: None,
error_tag: crate::realm::UNKNOWN_SOURCE,
locator: None,
script_name: None,
thrown_mark: None,
finally_marks: Vec::new(),
finally_sites: Vec::new(),
error_mark: None,
strict_writes: false,
promises: crate::builtins::promise::Promises::default(),
symbols: crate::symbol::Symbols::default(),
};
// With `Options::es2015`, the first run names the built-in functions, under the limits
// the caller gives ([`crate::builtins::es2015_names`]).
crate::builtins::install(&mut interp);
interp.fuel = limits.fuel;
interp.limits = limits;
interp.gc_threshold = interp.next_threshold();
interp
}
fn next_threshold(&self) -> usize {
(self.heap.bytes.saturating_mul(2)).max(MIN_GC_BYTES).min(self.limits.heap_bytes)
}
/// Recomputes when the next collection runs, after the limits change.
pub(crate) fn reset_gc_threshold(&mut self) {
self.gc_threshold = self.next_threshold();
}
// ---- errors ----
pub(crate) fn error_object(&mut self, t: ErrorType, message: &str) -> ObjId {
let proto = self.intrinsics.error_proto(t);
let mut o = Object::new(Class::Error(None), Some(proto));
if !message.is_empty() {
o.props.insert(key("message"), Prop::Data { value: Value::str(message), flags: HIDDEN });
}
self.heap.alloc_object(o)
}
/// An error of the interpreter's or a host function's own, marked as such with a hash of the
/// description it has with its kind's own name ([`Self::thrown_by_script`]), so a name a script
/// gave the kind's prototype before the error was made counts as the script's text.
pub(crate) fn throw(&mut self, t: ErrorType, message: &str) -> Abrupt {
let o = self.error_object(t, message);
let own = if message.is_empty() { t.name().to_string() } else { format!("{}: {message}", t.name()) };
if let Some(object) = self.heap.object_mut(o) {
object.class = Class::Error(Some(description_hash(&own)));
}
Abrupt::Throw(Value::Object(o))
}
/// Is the text [`Self::describe`] gives for the thrown value `v` the script's own? It is unless
/// `v` is an error the interpreter or a host function threw, with its name and message as they
/// were then: a value the script threw, an error it made, and an error whose name or message it
/// changed all hold its own text.
pub(crate) fn thrown_by_script(&mut self, v: &Value) -> bool {
let Value::Object(o) = v else { return true };
let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true };
let hash = *hash;
self.describe_hash(*o) != hash
}
pub(crate) fn type_error(&mut self, message: &str) -> Abrupt {
self.throw(ErrorType::Type, message)
}
// ---- the operand stack ----
pub(crate) fn push(&mut self, v: Value) -> JsResult<()> {
self.stack.push(v);
Ok(())
}
pub(crate) fn frame(&self) -> JsResult<&Frame> {
self.frames.last().ok_or_else(|| Abrupt::Internal("no frame".into()))
}
pub(crate) fn frame_mut(&mut self) -> JsResult<&mut Frame> {
self.frames.last_mut().ok_or_else(|| Abrupt::Internal("no frame".into()))
}
pub(crate) fn base(&self) -> usize {
self.frames.last().map_or(0, |f| f.base)
}
pub(crate) fn pop(&mut self) -> JsResult<Value> {
if self.stack.len() <= self.base() {
return internal("operand stack underflow");
}
self.stack.pop().ok_or_else(|| Abrupt::Internal("operand stack underflow".into()))
}
/// The value `n` places below the top (0 is the top).
pub(crate) fn peek(&self, n: usize) -> JsResult<Value> {
let len = self.stack.len();
match len.checked_sub(n + 1).filter(|&i| i >= self.base()) {
Some(i) => self.stack.get(i).cloned().ok_or_else(|| Abrupt::Internal("operand stack underflow".into())),
None => internal("operand stack underflow"),
}
}
fn drop_n(&mut self, n: usize) -> JsResult<()> {
let len = self.stack.len();
match len.checked_sub(n).filter(|&i| i >= self.base()) {
Some(i) => {
self.stack.truncate(i);
Ok(())
}
None => internal("operand stack underflow"),
}
}
/// Replaces the top `n` values with `v`.
pub(crate) fn replace(&mut self, n: usize, v: Value) -> JsResult<()> {
self.drop_n(n)?;
self.push(v)
}
// ---- running ----
/// Takes a unit of fuel and checks the interrupt flag.
pub(crate) fn use_fuel(&mut self) -> JsResult<()> {
if self.fuel == 0 {
return Err(Abrupt::Limit(LimitKind::Fuel));
}
self.fuel -= 1;
if self.interrupt.load(Ordering::Relaxed) {
return Err(Abrupt::Limit(LimitKind::Interrupted));
}
Ok(())
}
fn tick(&mut self) -> JsResult<()> {
self.use_fuel()?;
crate::regexp_vm::use_fuel_n(self, self.flattened_fuel.replace(0))?;
self.settle_held();
if self.heap.bytes > self.gc_threshold {
self.collect_garbage();
if self.heap.bytes > self.limits.heap_bytes {
return Err(Abrupt::Limit(LimitKind::Heap));
}
self.gc_threshold = self.next_threshold();
}
Ok(())
}
/// Ends the run with the heap limit when `bytes` more would not fit in it after a
/// collection. Everything the caller still needs must be reachable from the roots.
pub(crate) fn reserve_heap(&mut self, bytes: usize) -> JsResult<()> {
self.settle_held();
#[cfg(test)]
if COLLECT_ON_RESERVE.with(std::cell::Cell::get) {
self.collect_garbage();
}
if self.heap.bytes.saturating_add(bytes) <= self.limits.heap_bytes {
return Ok(());
}
self.collect_garbage();
self.gc_threshold = self.next_threshold();
if self.heap.bytes.saturating_add(bytes) > self.limits.heap_bytes {
return Err(Abrupt::Limit(LimitKind::Heap));
}
Ok(())
}
/// Takes the bytes that dropped [`HeldBytes`] released off the heap's total, and adds the
/// bytes of the ropes [`Self::get_own_property`] flattened.
fn settle_held(&mut self) {
let released = self.held.released.replace(0);
let flattened = self.flattened.replace(0);
self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened);
}
/// The heap's total with the released and flattened bytes taken into account, without a
/// collection.
#[cfg(test)]
pub(crate) fn settled_heap_bytes(&mut self) -> usize {
self.settle_held();
self.heap.bytes
}
/// Collects garbage now and sets when the next collection runs.
#[cfg(test)]
pub(crate) fn collect_for_room(&mut self) {
self.collect_garbage();
self.gc_threshold = self.next_threshold();
}
/// Charges code compiled at run time to the heap, reserving its estimated size and `extra`
/// more first. The code is not reachable from the roots yet, so a collection here leaves it
/// out of the live total and the charge adds it.
pub(crate) fn charge_code(&mut self, code: &Code, extra: usize) -> JsResult<()> {
let bytes = code_bytes(code);
self.reserve_heap(bytes.saturating_add(extra))?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
Ok(())
}
/// Prepares for parsing `units` code units of source at run time: takes a unit of fuel for
/// each code unit and checks that the source text fits in the heap, before any of it is
/// flattened, parsed or compiled. Running out of fuel uses up what was left.
pub(crate) fn prepare_source(&mut self, units: usize) -> JsResult<()> {
let fuel = u64::try_from(units).unwrap_or(u64::MAX);
if fuel > self.fuel {
self.fuel = 0;
return Err(Abrupt::Limit(LimitKind::Fuel));
}
self.fuel -= fuel;
if self.interrupt.load(Ordering::Relaxed) {
return Err(Abrupt::Limit(LimitKind::Interrupted));
}
self.reserve_heap(string_bytes(units))
}
/// Removes the [`Self::finally_marks`] entries of `finally` blocks that `break`, `continue` or
/// `return` left: those whose stack slot no longer holds their exception.
fn drop_left_finally_marks(&mut self) {
let stack = &self.stack;
self.finally_marks.retain(|&(id, _, slot)| matches!(stack.get(slot), Some(Value::Object(o)) if *o == id));
}
/// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of
/// `finally` blocks that were left. The slots rise along the list, so only its end is looked at.
pub(crate) fn drop_left_finally_sites(&mut self, len: usize) {
while let Some(&(_, slot)) = self.finally_sites.last() {
#[cfg(test)]
SITE_CHECKS.with(|c| c.set(c.get() + 1));
if slot < len {
break;
}
self.finally_sites.pop();
}
}
pub(crate) fn collect_garbage(&mut self) {
self.drop_left_finally_marks();
self.drop_left_finally_sites(self.stack.len());
self.promises.forget_handled(&self.heap);
let mut roots = Roots::default();
roots.values.extend(self.stack.iter());
roots.values.extend(self.temp_roots.iter());
roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter()));
roots.values.extend(self.again.iter().flat_map(|p| p.keep.iter().chain(p.args.iter()).chain(std::iter::once(&p.host))));
roots.values.push(&self.last_thrown);
roots.values.push(&self.last_error);
roots.values.push(&self.passing);
roots.objects.extend(self.finally_marks.iter().map(|&(id, _, _)| id));
roots.codes.extend(self.finally_sites.iter().map(|((code, _), _)| &**code));
roots.codes.extend(self.temp_codes.iter().map(|code| &**code));
for f in &self.frames {
roots.values.push(&f.this);
roots.values.push(&f.completion);
roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.new_target.iter()).chain(f.generator.iter()));
roots.envs.extend(f.this_env);
roots.envs.push(f.env);
roots.envs.push(f.var_env);
roots.codes.push(&f.code);
}
roots.objects.push(self.global);
roots.objects.extend(self.intrinsics.all());
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects));
roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects));
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
roots.values.extend(self.symbols.root_values());
roots.objects.extend(self.symbols.root_objects());
roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object));
roots.envs.push(self.global_env);
roots.envs.push(self.global_lex);
roots.envs.extend(self.temp_envs.iter().copied());
for (&(code, _), &(_, object)) in &self.template_objects {
roots.template_objects.entry(code).or_default().push(object);
}
self.promises.add_roots(&mut roots);
let live_codes = self.heap.collect(&roots);
self.template_objects.retain(|(code, _), _| live_codes.contains(code));
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
// The collection counts the live total again, so bytes already released are not in it.
self.held.released.set(0);
self.flattened.set(0);
let queued = self.promises.queue_bytes();
self.heap.bytes = self
.heap
.bytes
.saturating_add(self.held_bytes)
.saturating_add(self.held.now.get())
.saturating_add(self.symbols.registry_bytes())
.saturating_add(self.xmp.as_ref().map_or(0, crate::xmp_classes::Classes::bytes))
.saturating_add(queued);
}
/// Runs frames until the boundary frame on top returns, and returns its value.
pub(crate) fn execute(&mut self) -> JsResult<Value> {
loop {
match self.step() {
Ok(Some(v)) => return Ok(v),
Ok(None) => {}
Err(Abrupt::Throw(v)) => self.unwind(v)?,
Err(other) => {
self.note_site();
self.abort_to_boundary();
return Err(other);
}
}
}
}
/// Runs the boundary frame on top until it returns (`Some` with its value) or the remaining
/// fuel falls to `pause_at`, or the host asks for a pause (`None`, with the frames left in
/// place for the next call). Only this outermost loop pauses: a nested run has native frames
/// under it and goes on until it returns.
pub(crate) fn execute_slice(&mut self, pause_at: u64) -> JsResult<Option<Value>> {
loop {
match self.step() {
Ok(Some(v)) => return Ok(Some(v)),
Ok(None) => {}
Err(Abrupt::Throw(v)) => self.unwind(v)?,
Err(other) => {
self.note_site();
self.abort_to_boundary();
return Err(other);
}
}
if self.fuel <= pause_at || self.pause.replace(false) {
return Ok(None);
}
}
}
fn step(&mut self) -> JsResult<Option<Value>> {
self.tick()?;
// An answer that could not be read is thrown at the call that waited for it.
if std::mem::take(&mut self.answer_throws) {
let thrown = self.pop()?;
return Err(Abrupt::Throw(thrown));
}
// A built-in that waited for the host takes the answer on top of the stack before the
// instruction after its call runs; what it throws is thrown at that call.
if let Some(r) = self.resuming.take() {
let answer = self.pop()?;
let v = self.resume(r, answer)?;
self.push(v)?;
return Ok(None);
}
if self.frames.last().is_some_and(|frame| frame.pending_module) {
self.pending_module_frames -= 1;
}
let frame = self.frame_mut()?;
frame.pending_module = false;
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
frame.pc += 1;
match op {
Op::Return => {
let v = self.pop()?;
self.return_value(v)
}
Op::ReturnCompletion => {
let v = self.frame()?.completion.clone();
self.return_value(v)
}
Op::GeneratorStart => self.op_generator_start(),
Op::Yield(raw) => self.op_yield(raw),
_ => self.exec(op).map(|()| None),
}
}
fn note_site(&mut self) {
if self.throw_site.is_none()
&& let Some(f) = self.frames.last()
{
self.throw_site = Some((f.code.clone(), f.pc.saturating_sub(1)));
}
}
/// Finds the handler for an exception: in the top frame, or in the frames below it up to the
/// boundary frame. Returns the exception when no handler takes it before the boundary frame.
fn unwind(&mut self, v: Value) -> JsResult<()> {
self.note_site();
let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b);
if !passed
&& let Value::Object(o) = v
&& self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error(_)))
{
self.last_error = v.clone();
}
loop {
let Some(frame) = self.frames.last_mut() else { return Err(Abrupt::Throw(v)) };
if let Some(h) = frame.code.handler(frame.pc.saturating_sub(1)) {
// A catch clause starts with `PushCatch`; every other handler is a `finally` block's.
let caught = matches!(frame.code.ops.get(h.target as usize), Some(Op::PushCatch(_)));
let target_len = frame.base + h.depth as usize;
while frame.env_depth > h.env_depth {
let outer = self.heap.env(frame.env).and_then(Env::outer);
let Some(outer) = outer else { return internal("environment chain ended early") };
frame.env = outer;
frame.env_depth -= 1;
}
frame.pc = h.target as usize;
// A handler of this frame is never inside a class's heritage or keys: they are
// expressions, and a function in them runs in a frame of its own.
frame.strict_class = false;
if self.stack.len() < target_len {
return internal("handler stack deeper than the stack");
}
self.stack.truncate(target_len);
self.drop_left_finally_marks();
self.drop_left_finally_sites(target_len);
if let (Some(mark), false, Value::Object(id)) = (self.thrown_mark.take(), caught, &v) {
self.finally_marks.push((*id, mark, target_len));
}
self.stack.push(v);
let site = self.throw_site.take();
if let (false, Some(site)) = (caught, site) {
self.finally_sites.push((site, target_len));
}
return Ok(());
}
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.chained {
// The modules under it have not started, so no handler of theirs takes it.
self.abort_to_boundary();
}
if frame.boundary || frame.chained {
self.passing = v.clone();
return Err(Abrupt::Throw(v));
}
}
}
/// Each running frame of script code, outermost first: its code, the index of its next
/// instruction, and whether it runs a function (not global or eval code).
pub(crate) fn script_frames(&self) -> impl Iterator<Item = (&Rc<Code>, usize, bool)> {
self.frames.iter().filter(|f| !f.pending_module).map(|f| (&f.code, f.pc, f.callee.is_some()))
}
pub(crate) fn clear_frames(&mut self) {
self.frames.clear();
self.pending_module_frames = 0;
}
fn pop_frame(&mut self) -> Option<Frame> {
let frame = self.frames.pop()?;
if frame.pending_module {
self.pending_module_frames -= 1;
}
Some(frame)
}
fn abort_to_boundary(&mut self) {
while let Some(frame) = self.pop_frame() {
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
break;
}
}
}
fn return_value(&mut self, mut v: Value) -> JsResult<Option<Value>> {
if let Some(env) = self.frames.last().filter(|f| f.code.derived).and_then(|f| f.this_env) {
match self.derived_result(env, v) {
Ok(result) => v = result,
Err(e) => {
// The error is thrown as the frame returns: from its last instruction, outside
// every handler of its code, and reported at the return.
self.note_site();
if let Some(f) = self.frames.last_mut() {
f.pc = f.code.ops.len();
}
return Err(e);
}
}
}
// A generator's body that returns ends it, and its caller gets `{ value, done: true }`,
// made while the frame is still there to fail in.
let v = match self.frames.last().and_then(|f| f.generator) {
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
None => v,
};
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
self.drop_left_finally_sites(frame.base);
let v = match frame.construct {
Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o),
_ => v,
};
if frame.boundary {
return Ok(Some(v));
}
if frame.chained {
return Ok(None);
}
self.push(v)?;
Ok(None)
}
pub(crate) fn jump_to(&mut self, target: u32) -> JsResult<()> {
self.frame_mut()?.pc = target as usize;
Ok(())
}
pub(crate) fn name(&self, i: u32) -> JsResult<Key> {
self.frame()?.code.names.get(i as usize).cloned().ok_or_else(|| Abrupt::Internal("name out of range".into()))
}
pub(crate) fn strict(&self) -> bool {
self.frames.last().is_some_and(|f| f.code.strict || f.strict_class)
}
/// Does a property write the running code makes throw when it cannot be made? It does in
/// strict mode code and in code from a source with [`crate::bytecode::Source::strict_writes`].
pub(crate) fn strict_writes(&self) -> bool {
self.frames.last().is_some_and(|f| f.code.strict || f.strict_class || f.code.source.strict_writes)
}
/// [`crate::bytecode::Source::strict_writes`] for source compiled now: the running code's,
/// or the realm's between runs.
pub(crate) fn writes_mode(&self) -> bool {
self.frames.last().map_or(self.strict_writes, |f| f.code.source.strict_writes)
}
fn exec(&mut self, op: Op) -> JsResult<()> {
match op {
Op::Undefined => self.push(Value::Undefined),
Op::Null => self.push(Value::Null),
Op::True => self.push(Value::Bool(true)),
Op::False => self.push(Value::Bool(false)),
Op::Number(i) => {
let n = self.frame()?.code.numbers.get(i as usize).copied();
self.push(Value::Number(n.unwrap_or(f64::NAN)))
}
Op::String(i) => {
let s = self.frame()?.code.strings.get(i as usize).cloned();
self.push(s.map_or(Value::Undefined, Value::String))
}
Op::This => {
let this = self.this_value()?;
self.push(this)
}
Op::Pop => self.pop().map(drop),
Op::PopUnder(n) => self.op_pop_under(n),
Op::Dup => self.op_dup(1),
Op::Dup2 => self.op_dup(2),
Op::Swap => self.op_swap(),
Op::Rot3 => self.op_rot3(),
Op::GetVar(n) => self.op_get_var(n, false),
Op::GetVarThis(n) => self.op_get_var(n, true),
Op::SetVar(n) => self.op_set_var(n),
Op::RefVar(n) => self.op_ref_var(n),
Op::GetRef(n) => self.op_get_ref(n),
Op::PutRef(n) => self.op_put_ref(n),
Op::TypeofVar(n) => self.op_typeof_var(n),
Op::DeleteVar(n) => self.op_delete_var(n),
Op::IncVar { name, prefix, dec } => self.op_inc_var(name, prefix, dec),
Op::GetMember(n) => self.op_get_member(n, false),
Op::GetMemberThis(n) => self.op_get_member(n, true),
Op::SetMember(n) => self.op_set_member(n),
Op::DeleteMember(n) => self.op_delete_member(n),
Op::IncMember { name, prefix, dec } => self.op_inc_member(name, prefix, dec),
Op::ToKey => self.op_to_key(),
Op::CheckObject => self.op_check_object(),
Op::GetIndex => self.op_get_index(false),
Op::GetIndexThis => self.op_get_index(true),
Op::SetIndex => self.op_set_index(),
Op::DeleteIndex => self.op_delete_index(),
Op::IncIndex { prefix, dec } => self.op_inc_index(prefix, dec),
Op::Call(n) => self.op_call(n, false),
Op::CallEval(n) => self.op_call(n, true),
Op::New(n) => self.op_new(n),
Op::Binary(b) => self.op_binary(b),
Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber => self.op_unary(op),
Op::Jump(t) => {
// `break` and `continue` leave a `finally` block by popping its exception and jumping.
self.drop_left_finally_sites(self.stack.len());
self.jump_to(t)
}
Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => self.op_branch(t, matches!(op, Op::JumpIfTrue(_)), false),
Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => self.op_branch(t, matches!(op, Op::JumpIfTrueKeep(_)), true),
Op::JumpIfNotNullishKeep(t) => {
if self.peek(0)?.is_nullish() {
self.pop().map(drop)
} else {
self.jump_to(t)
}
}
Op::JumpIfNullish { target, drop: count } => {
if self.peek(0)?.is_nullish() {
self.drop_n(count as usize)?;
self.jump_to(target)
} else {
Ok(())
}
}
Op::Throw => {
self.thrown_mark = None;
Err(Abrupt::Throw(self.pop()?))
}
Op::ThrowReferenceError(i) => self.op_throw_reference_error(i),
Op::EndFinally(t) => self.op_end_finally(t),
Op::NewObject => self.op_new_object(),
Op::NewArray => self.op_new_array(),
Op::ArrayPush => self.op_array_push(true),
Op::ArrayHole => self.op_array_push(false),
Op::InitProp(n) => self.op_init_prop(n),
Op::InitGetter(n) => self.op_init_accessor(n, true),
Op::InitSetter(n) => self.op_init_accessor(n, false),
Op::InitProto => self.op_init_proto(),
Op::SetFunctionName(n) => self.op_set_function_name(n),
Op::SetFunctionNameKey(prefix) => self.op_set_function_name_key(prefix),
Op::Closure(i) => self.op_closure(i),
Op::RegExp(i) => self.op_regexp(i),
Op::PushWith => self.op_push_with(),
Op::PushCatch(n) => self.op_push_catch(n),
Op::PopEnv => self.op_pop_env(),
Op::ForInStart => self.op_for_in_start(),
Op::ForInNext(t) => self.op_for_in_next(t),
Op::SetCompletion => {
let v = self.pop()?;
self.frame_mut()?.completion = v;
Ok(())
}
Op::GetCompletion => {
let v = self.frame()?.completion.clone();
self.push(v)
}
Op::XmlMakeName { attribute, qualified } => self.op_xml_make_name(attribute, qualified),
Op::XmlDescendants => self.op_xml_descendants(),
Op::XmlEscape(kind) => self.op_xml_escape(kind),
Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list),
Op::XmlScopeGet => self.op_xml_scope_get(),
Op::XmlScopeRef => self.op_xml_scope_ref(),
Op::XmlFilterStart => self.op_xml_filter_start(),
Op::XmlFilterNext(t) => self.op_xml_filter_next(t),
Op::XmlFilterTest => self.op_xml_filter_test(),
Op::XmlFilterEnd => self.op_xml_filter_end(),
Op::ForEachValue(n) => self.op_for_each_value(n as usize),
Op::SetDefaultNamespace => self.op_set_default_namespace(),
Op::PushBlock(i) => self.op_push_block(i),
Op::CopyEnv => self.op_copy_env(),
Op::InitVar(n) => self.op_init_var(n),
Op::LoadParam(n) => self.op_load_param(n),
Op::BodyEnv => self.op_body_env(),
Op::AnnexB(n) => self.op_annex_b(n),
Op::ArraySpread => self.op_array_spread(),
Op::CallSpread(eval) => self.op_call_spread(eval),
Op::NewSpread => self.op_new_spread(),
Op::ToStr => {
let v = self.peek(0)?;
let s = self.to_str(&v)?;
self.replace(1, Value::String(s))
}
Op::TemplateObject(i) => self.op_template_object(i),
Op::Pick(n) => {
let v = self.peek(n as usize)?;
self.push(v)
}
Op::ClassStart { ctor, heritage } => self.op_class_start(ctor, heritage),
Op::StrictClass(on) => {
self.frame_mut()?.strict_class = on;
Ok(())
}
Op::ClassMethod { func, kind, is_static } => self.op_class_method(func, kind, is_static),
Op::InitMethod { func, kind, name } => self.op_init_method(func, kind, name),
Op::InitMethodKey { func, kind } => self.op_init_method_key(func, kind),
Op::SuperRef => self.op_super_ref(),
Op::SuperGet => self.op_super_get(false),
Op::SuperGetThis => self.op_super_get(true),
Op::SuperSet => self.op_super_set(),
Op::SuperDup => self.op_dup(3),
Op::SuperInc { prefix, dec } => self.op_super_inc(prefix, dec),
Op::SuperCtor => self.op_super_ctor(),
Op::SuperCall(n) => self.op_super_call(n),
Op::SuperCallSpread => {
let n = self.unpack_args()?;
self.op_super_call(n)
}
Op::BindThis => self.op_bind_this(),
Op::NewTarget => self.op_new_target(),
Op::GetIterator => self.op_get_iterator(),
Op::IterStep(t) => self.op_iter_step(t),
Op::IterValue(n) => self.op_iter_value(n),
Op::IterSkip => self.op_iter_skip(),
Op::IterRest(n) => self.op_iter_rest(n),
Op::IterClose => self.op_iter_close(),
Op::IterCloseThrow => self.op_iter_close_throw(),
Op::RequireObjectCoercible => self.op_require_object_coercible(),
Op::PatternGet(n) => self.op_pattern_get(n),
Op::InitIndex => self.op_init_index(),
Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter),
Op::Resume(t) => self.op_resume(t),
Op::DelegateIterator => self.op_delegate_iterator(),
Op::DelegateCall(t) => self.op_delegate_call(t),
Op::DelegateResult(t) => self.op_delegate_result(t),
Op::DelegateDone(t) => self.op_delegate_done(t),
Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"),
}
}
// ---- stack operations ----
fn op_pop_under(&mut self, n: u32) -> JsResult<()> {
let top = self.pop()?;
self.drop_n(n as usize)?;
self.push(top)
}
fn op_dup(&mut self, n: usize) -> JsResult<()> {
for _ in 0..n {
let v = self.peek(n - 1)?;
self.push(v)?;
}
Ok(())
}
fn op_swap(&mut self) -> JsResult<()> {
let b = self.pop()?;
let a = self.pop()?;
self.push(b)?;
self.push(a)
}
fn op_rot3(&mut self) -> JsResult<()> {
let c = self.pop()?;
let b = self.pop()?;
let a = self.pop()?;
self.push(b)?;
self.push(c)?;
self.push(a)
}
fn op_branch(&mut self, target: u32, when: bool, keep: bool) -> JsResult<()> {
let v = self.peek(0)?;
let jump = v.truthy() == when;
if !(keep && jump) {
self.pop()?;
}
if jump { self.jump_to(target) } else { Ok(()) }
}
fn op_throw_reference_error(&mut self, i: u32) -> JsResult<()> {
let message = self.frame()?.code.strings.get(i as usize).map(Str::to_rust_string).unwrap_or_default();
Err(self.throw(ErrorType::Reference, &message))
}
/// Throws `v` again from a handler that is not a catch clause, with the stack cut back to
/// where the handler took it: the exception keeps the position and mark it was thrown with.
pub(crate) fn rethrow(&mut self, v: Value) -> Abrupt {
self.passing = v.clone();
self.throw_site = None;
self.thrown_mark = None;
let slot = self.stack.len();
if let Value::Object(o) = v
&& let Some(i) = self.finally_marks.iter().rposition(|&(id, _, s)| id == o && s == slot)
{
self.thrown_mark = self.finally_marks.get(i).map(|&(_, mark, _)| mark);
self.finally_marks.truncate(i);
}
if let Some(i) = self.finally_sites.iter().rposition(|&(_, s)| s == slot) {
self.throw_site = self.finally_sites.get(i).map(|(site, _)| site.clone());
self.finally_sites.truncate(i);
}
Abrupt::Throw(v)
}
fn op_end_finally(&mut self, table: u32) -> JsResult<()> {
let Value::Number(kind) = self.pop()? else { return internal("finally kind is not a number") };
if kind == 0.0 {
return self.pop().map(drop);
}
if kind == 1.0 {
let v = self.pop()?;
return Err(self.rethrow(v));
}
let k = (kind - 2.0) as usize;
let target = self.frame()?.code.finally_tables.get(table as usize).and_then(|t| t.get(k)).copied();
match target {
Some(t) => self.jump_to(t),
None => internal("finally exit out of range"),
}
}
// ---- variables ----
fn resolve(&mut self, name: &[u16]) -> JsResult<Resolved> {
let mut cur = Some(self.frame()?.env);
while let Some(e) = cur {
match self.heap.env(e) {
Some(Env::Decl { bindings, outer }) => {
if bindings.contains(name) {
return Ok(Resolved::Decl(e));
}
cur = *outer;
}
Some(&Env::Obj { object, with_this, outer }) => {
if self.scope_has(object, name)? {
return Ok(Resolved::Obj { object, with_this });
}
cur = outer;
}
None => return internal("environment out of range"),
}
}
Ok(Resolved::Unresolved)
}
pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult<Value> {
match self.heap.env(env) {
Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())),
_ => internal("not a declarative environment"),
}
}
fn not_defined(&mut self, name: &[u16]) -> Abrupt {
let ident = String::from_utf16_lossy(name);
self.throw(ErrorType::Reference, &format!("{ident} is not defined"))
}
/// The binding `name` of the declarative environment `env` is in its temporal dead zone.
pub(crate) fn uninitialized(&self, env: EnvId, name: &[u16]) -> bool {
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
}
/// The binding the binding `name` of the declarative environment `env` imports, when it is a
/// module's import.
fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> {
match self.heap.env(env) {
Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()),
_ => None,
}
}
fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
let ident = String::from_utf16_lossy(name);
self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
}
fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> {
let r = self.resolve(name)?;
self.get_resolved(r, name)
}
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
if let Resolved::Decl(e) = r
&& let Some((target, target_name)) = self.import_of(e, name)
{
if self.uninitialized(target, &target_name) {
return Err(self.not_initialized(name));
}
return Ok((self.binding_value(target, &target_name)?, Value::Undefined));
}
match r {
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
Resolved::Obj { object, with_this } => {
let v = self.get_value(&Value::Object(object), name)?;
Ok((v, if with_this { Value::Object(object) } else { Value::Undefined }))
}
Resolved::Unresolved => Err(self.not_defined(name)),
}
}
fn set_var(&mut self, name: &Key, v: Value) -> JsResult<()> {
let r = self.resolve(name)?;
self.set_resolved(r, name, v)
}
/// PutValue of a reference whose base was resolved earlier (section 8.7.2).
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
let strict = self.strict();
if let Resolved::Decl(e) = r
&& self.import_of(e, name).is_some()
{
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("assignment to the import '{ident}'")));
}
match r {
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
let ident = String::from_utf16_lossy(name);
Err(self.type_error(&format!("assignment to the constant '{ident}'")))
}
Resolved::Decl(e) => {
let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(e) else { return internal("not a declarative environment") };
match bindings.get_mut(name) {
Some(b) if b.mutable => {
b.value = v;
Ok(())
}
_ if strict => Err(self.type_error("assignment to a constant binding")),
_ => Ok(()),
}
}
Resolved::Obj { object, .. } if self.options.e4x && self.is_xml(&Value::Object(object)) => {
self.put_value(&Value::Object(object), name.clone(), v)
}
Resolved::Obj { object, .. } => {
let throw = self.strict_writes();
self.put(object, name.clone(), v, throw)
}
Resolved::Unresolved if strict => Err(self.not_defined(name)),
Resolved::Unresolved => {
let (global, throw) = (self.global, self.strict_writes());
self.put(global, name.clone(), v, throw)
}
}
}
fn op_get_var(&mut self, n: u32, with_this: bool) -> JsResult<()> {
let name = self.name(n)?;
if with_this
&& self.options.e4x
&& let Some((f, this)) = self.xml_scope_method(&name)?
{
self.push(f)?;
return self.push(this);
}
let (v, this) = self.get_var(&name)?;
self.push(v)?;
if with_this { self.push(this) } else { Ok(()) }
}
fn op_set_var(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.peek(0)?;
self.set_var(&name, v)
}
fn op_typeof_var(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = match self.resolve(&name)? {
Resolved::Unresolved => Value::Undefined,
_ => self.get_var(&name)?.0,
};
let t = self.type_of(&v);
self.push(Value::str(t))
}
fn op_delete_var(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let result = match self.resolve(&name)? {
Resolved::Unresolved => true,
Resolved::Decl(e) => match self.heap.env_mut(e) {
Some(Env::Decl { bindings, .. }) => {
if bindings.get(&name).is_some_and(|b| b.deletable) {
bindings.remove(&name);
true
} else {
false
}
}
_ => return internal("not a declarative environment"),
},
Resolved::Obj { object, with_this } => {
let own = self.get_own_property(object, &name)?.is_some();
let deleted = self.delete(object, &name, false)?;
// A global variable whose own property is deleted through the global environment
// no longer stops a `let` or `const` of its name (ECMA-262 2015 section 8.1.1.4.7).
// Deleting the global object's property any other way, as `delete this.x` does,
// or deleting a name it only inherits, keeps the record.
if own && deleted && !with_this && object == self.global {
self.global_vars.remove(&name);
}
deleted
}
};
self.push(Value::Bool(result))
}
fn op_inc_var(&mut self, n: u32, prefix: bool, dec: bool) -> JsResult<()> {
let name = self.name(n)?;
let r = self.resolve(&name)?;
let base = resolved_to_value(&r);
let (v, _) = self.get_resolved(r, &name)?;
// The base stays on the stack, where the collector sees it, while ToNumber runs script.
self.push(base)?;
let old = self.to_number(&v)?;
let base = self.pop()?;
let new = if dec { old - 1.0 } else { old + 1.0 };
self.set_resolved(value_to_resolved(&base)?, &name, Value::Number(new))?;
self.push(Value::Number(if prefix { new } else { old }))
}
/// Resolves a variable before the right-hand side of an assignment runs, and pushes the
/// reference's base.
fn op_ref_var(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let r = self.resolve(&name)?;
self.push(resolved_to_value(&r))
}
/// Replaces the reference base on top of the stack with the variable's value.
fn op_get_ref(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let base = self.peek(0)?;
let (v, _) = self.get_resolved(value_to_resolved(&base)?, &name)?;
self.pop()?;
self.push(v)
}
/// Stores the value on top of the stack through the reference base under it, and leaves the
/// value.
fn op_put_ref(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.peek(0)?;
let base = self.peek(1)?;
self.set_resolved(value_to_resolved(&base)?, &name, v)?;
let v = self.pop()?;
self.pop()?;
self.push(v)
}
// ---- properties ----
pub(crate) fn object(&self, id: ObjId) -> JsResult<&Object> {
self.heap.object(id).ok_or_else(|| Abrupt::Internal("object out of range".into()))
}
pub(crate) fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> {
self.heap.object_mut(id).ok_or_else(|| Abrupt::Internal("object out of range".into()))
}
/// [[GetOwnProperty]] (section 8.12.1, with the special cases of arrays, strings and
/// arguments objects).
pub(crate) fn get_own_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
let o = self.object(id)?;
match &o.class {
Class::Array { length, length_writable } if is(k, "length") => {
return Ok(Some(Prop::Data { value: Value::Number(f64::from(*length)), flags: if *length_writable { WRITABLE } else { 0 } }));
}
Class::String(s) => {
if is(k, "length") {
return Ok(Some(Prop::Data { value: Value::Number(s.len() as f64), flags: 0 }));
}
if let Some(i) = array_index(k)
&& (i as usize) < s.len()
{
let unit = if s.is_rope() {
let owed = self.flattened_fuel.get();
let flattened = self.flattened.get().saturating_add(string_bytes(s.len()));
if self.heap.bytes.saturating_add(flattened) > self.limits.heap_bytes {
// The copy does not fit without a collection, which needs `&mut self`:
// the unit is read along the rope instead, a unit of fuel per node.
let Some((unit, visited)) = s.unit_at(i as usize, self.fuel.saturating_sub(owed)) else {
return Err(Abrupt::Limit(LimitKind::Fuel));
};
self.flattened_fuel.set(owed.saturating_add(visited));
unit
} else {
// Flattening copies the units. The run ends here when the fuel for
// the copy is not left; otherwise the next step takes it, and the
// next limit check adds the copy's bytes.
let fuel = owed.saturating_add((s.len() / crate::string_builtins::UNITS_PER_FUEL) as u64 + 1);
if fuel > self.fuel {
return Err(Abrupt::Limit(LimitKind::Fuel));
}
self.flattened_fuel.set(fuel);
self.flattened.set(flattened);
s.flat().get(i as usize).copied()
}
} else {
s.flat().get(i as usize).copied()
}
.unwrap_or(0);
return Ok(Some(Prop::Data { value: Value::String(Str::from_units(vec![unit])), flags: ENUMERABLE }));
}
}
Class::Arguments(map) => {
if let Some(name) = array_index(k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref)
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
{
let flags = *flags;
return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags }));
}
}
// A numeric name of a typed array is an element or nothing (section 9.4.5.1).
Class::TypedArray(view) => {
if let Some(n) = crate::builtins::binary::canonical_index(k) {
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
}
}
Class::ModuleNamespace(exports) => {
if let Some((env, name)) = exports.binding(k)
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
{
return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags }));
}
}
_ => {}
}
Ok(o.props.get(k).cloned())
}
/// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like):
/// [`Self::get_own_property`], except that an export of a module namespace object read before
/// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5).
pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
self.check_namespace_export(id, k)?;
self.get_own_property(id, k)
}
/// [`Self::own_property`] for a name or a Symbol: [`Self::get_own_pk`], with the same
/// `ReferenceError` for a namespace export read before its module initialized it.
pub(crate) fn own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
if let PropKey::Str(name) = k {
self.check_namespace_export(id, name)?;
}
self.get_own_pk(id, k)
}
/// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module
/// has not initialized yet.
fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> {
if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class)
&& let Some((env, name)) = exports.binding(k)
&& self.uninitialized(*env, name)
{
return Err(self.not_initialized(k));
}
Ok(())
}
/// [[GetProperty]]: the property found on the object or its prototype chain.
pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
Ok(self.find_property_on(id, k)?.map(|(_, p)| p))
}
/// [`Self::find_property`], with the object on the prototype chain that has the property.
fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult<Option<(ObjId, Prop)>> {
let mut cur = Some(id);
let mut steps = 0usize;
while let Some(o) = cur {
if let Some(p) = self.get_own_property(o, k)? {
return Ok(Some((o, p)));
}
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
if crate::builtins::binary::typed_key(self, o, k).is_some() {
return Ok(None);
}
cur = self.object(o)?.proto;
steps += 1;
if steps > 1_000_000 {
return internal("prototype chain too long");
}
}
Ok(None)
}
pub(crate) fn has_property(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
Ok(self.find_property(id, k)?.is_some())
}
/// [[Get]] starting at `start`, with `receiver` as `this` for a getter.
pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
// An array index of an object of a host class with an indexer is the indexer's answer.
if let Some(i) = array_index(k)
&& let Some(f) = self.host_indexer(start)?
{
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
}
let found = self.find_property_on(start, k)?;
// A module's export read before the module ran is in its temporal dead zone (ECMA-262
// 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it
// through a prototype chain.
if let Some((holder, _)) = &found {
self.check_namespace_export(*holder, k)?;
}
match found.map(|(_, p)| p) {
// A name the object and its prototypes lack is the indexer's answer too.
None => match self.host_indexer(start)? {
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
None => Ok(Value::Undefined),
},
Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
Some(Prop::Data { value, .. }) => Ok(value),
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
}
}
/// [[Get]] of a name that is not an array index, without the indexer of an object of a host
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
let found = self.find_property_on(start, k)?;
if let Some((holder, _)) = &found {
self.check_namespace_export(*holder, k)?;
}
match found.map(|(_, p)| p) {
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
Some(Prop::Data { value, .. }) => Ok(value),
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
}
}
/// The prototype a primitive's properties are looked up on.
pub(crate) fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult<ObjId> {
match v {
Value::Object(o) => Ok(*o),
Value::String(_) => Ok(self.intrinsics.string_proto),
Value::Number(_) => Ok(self.intrinsics.number_proto),
Value::Bool(_) => Ok(self.intrinsics.boolean_proto),
Value::Symbol(_) => Ok(self.symbols.objects.map_or(self.intrinsics.object_proto, |o| o.symbol_proto)),
Value::Undefined | Value::Null => {
let key = String::from_utf16_lossy(k);
let base = if matches!(v, Value::Null) { "null" } else { "undefined" };
Err(self.type_error(&format!("cannot read property '{key}' of {base}")))
}
}
}
/// `base[k]` for any value (GetValue, section 8.7.1).
pub(crate) fn get_value(&mut self, base: &Value, k: &[u16]) -> JsResult<Value> {
if self.options.e4x && self.is_xml(base) {
return self.xml_get(base, &Value::String(Str::from_units(k.to_vec())));
}
if let Value::String(s) = base {
if is(k, "length") {
return Ok(Value::Number(s.len() as f64));
}
if let Some(i) = array_index(k)
&& (i as usize) < s.len()
{
let unit = flat_charged(self, s)?.get(i as usize).copied().unwrap_or(0);
return Ok(Value::String(Str::from_units(vec![unit])));
}
}
let start = self.primitive_proto(base, k)?;
self.get_from(start, k, base)
}
/// Adds or replaces an own property directly, keeping the heap estimate.
pub(crate) fn define(&mut self, id: ObjId, k: Key, prop: Prop) -> JsResult<()> {
let o = self.object_mut(id)?;
let new = !o.props.contains(&k);
if let Class::Array { length, .. } = &mut o.class
&& let Some(i) = array_index(&k)
&& i >= *length
{
*length = i + 1;
}
let name_len = k.len();
let index = new && k.first().is_some_and(|&u| (u16::from(b'0')..=u16::from(b'9')).contains(&u));
o.props.insert(k, prop);
if new {
self.heap.bytes += PROP_BYTES + string_bytes(name_len);
}
if index {
self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1);
}
Ok(())
}
/// [[DefineOwnProperty]] (section 8.12.9, with the array rules of section 15.4.5.1 and the
/// arguments object rules of section 10.6). Returns whether the property was defined; with
/// `throw` a rejection throws a `TypeError` instead.
pub(crate) fn define_own_property(&mut self, id: ObjId, k: Key, desc: &Desc, throw: bool) -> JsResult<bool> {
match &self.object(id)?.class {
Class::Array { length, length_writable } => {
let (length, length_writable) = (*length, *length_writable);
if is(&k, "length") {
return self.define_array_length(id, desc, throw);
}
if let Some(i) = array_index(&k)
&& i >= length
&& !length_writable
{
return self.reject_bool(throw, &k, "the array's length is read-only");
}
self.define_ordinary(id, k, desc, throw)
}
Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => {
crate::builtins::binary::define_element(self, id, &k, desc, throw)
}
Class::Arguments(map) => {
let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned();
if !self.define_ordinary(id, k.clone(), desc, false)? {
return self.reject_bool(throw, &k, "the property cannot be redefined");
}
if let Some(name) = mapped {
let env = match &self.object(id)?.class {
Class::Arguments(map) => Some(map.env),
_ => None,
};
if let Some(v) = desc.value.clone().filter(|_| !desc.is_accessor())
&& let Some(env) = env
&& let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env)
&& let Some(b) = bindings.get_mut(&name)
{
b.value = v;
}
if (desc.is_accessor() || desc.writable == Some(false))
&& let Class::Arguments(map) = &mut self.object_mut(id)?.class
&& let Some(slot) = array_index(&k).and_then(|i| map.names.get_mut(i as usize))
{
*slot = None;
}
}
Ok(true)
}
Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw),
_ => self.define_ordinary(id, k, desc, throw),
}
}
/// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a
/// descriptor that leaves an export as it is (enumerable, writable, not configurable, its
/// current value) succeeds.
fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else {
return self.reject_bool(throw, k, "a module namespace object is not extensible");
};
let unchanged = desc.configurable != Some(true)
&& desc.enumerable != Some(false)
&& !desc.is_accessor()
&& desc.writable != Some(false)
&& desc.value.as_ref().is_none_or(|v| same_value(v, &value));
if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") }
}
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
if throw {
let key = String::from_utf16_lossy(k);
return Err(self.type_error(&format!("cannot define property '{key}': {why}")));
}
Ok(false)
}
/// The default [[DefineOwnProperty]] (section 8.12.9).
fn define_ordinary(&mut self, id: ObjId, k: Key, desc: &Desc, throw: bool) -> JsResult<bool> {
let current = self.get_own_property(id, &k)?;
let o = self.object(id)?;
let virtual_string = matches!(&o.class, Class::String(s) if is(&k, "length") || array_index(&k).is_some_and(|i| (i as usize) < s.len()));
let Some(current) = current else {
if !o.extensible {
return self.reject_bool(throw, &k, "the object is not extensible");
}
// The object and the descriptor's values stay rooted while the heap is checked.
let mut roots = vec![Value::Object(id)];
roots.extend(desc.value.iter().cloned());
roots.extend(desc.get.flatten().into_iter().chain(desc.set.flatten()).map(Value::Object));
self.rooted(&roots, |i| i.reserve_heap(binding_bytes(k.len())))?;
let flags = desc.flags_or(0);
let prop = if desc.is_accessor() {
Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & !WRITABLE }
} else {
Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags }
};
self.define(id, k, prop)?;
return Ok(true);
};
let Some(merged) = merge_desc(&current, desc) else { return self.reject_bool(throw, &k, "the property cannot be redefined") };
// An index or the length of a String object cannot change, so a definition that passes
// the checks leaves it as it is.
if virtual_string {
return Ok(true);
}
self.define(id, k, merged)?;
Ok(true)
}
/// Defining an array's `length` (section 15.4.5.1, step 3).
fn define_array_length(&mut self, id: ObjId, desc: &Desc, throw: bool) -> JsResult<bool> {
let length_key = key("length");
let Some(v) = desc.value.clone() else {
let Some(current) = self.get_own_property(id, &length_key)? else { return internal("an array without a length") };
let Some(merged) = merge_desc(&current, desc) else { return self.reject_bool(throw, &length_key, "the length cannot be redefined") };
if let Class::Array { length_writable, .. } = &mut self.object_mut(id)?.class {
*length_writable = merged.flags() & WRITABLE != 0;
}
return Ok(true);
};
let new = to_uint32(self.to_number(&v)?);
if f64::from(new) != self.to_number(&v)? {
return Err(self.throw(ErrorType::Range, "invalid array length"));
}
let Some(current) = self.get_own_property(id, &length_key)? else { return internal("an array without a length") };
let Class::Array { length: old, length_writable } = self.object(id)?.class else { return internal("not an array") };
let new_desc = Desc { value: Some(Value::Number(f64::from(new))), ..desc.clone() };
if new >= old {
let Some(merged) = merge_desc(&current, &new_desc) else { return self.reject_bool(throw, &length_key, "the length cannot be redefined") };
if let Class::Array { length, length_writable } = &mut self.object_mut(id)?.class {
*length = new;
*length_writable = merged.flags() & WRITABLE != 0;
}
return Ok(true);
}
if !length_writable {
return self.reject_bool(throw, &length_key, "it is read-only");
}
let checked = Desc { writable: None, ..new_desc };
if merge_desc(&current, &checked).is_none() {
return self.reject_bool(throw, &length_key, "the length cannot be redefined");
}
let read_only = desc.writable == Some(false);
if !self.shrink_array(id, new, read_only)? {
return self.reject_bool(throw, &length_key, "an element cannot be deleted");
}
Ok(true)
}
/// Sets an array's length to `new`, deleting the elements at and past it from the last one
/// down (section 15.4.5.1, step 3.l). An element that cannot be deleted stops it, leaving
/// the length one past that element, and gives `false`. Each property takes a unit of fuel
/// before anything is removed. With `read_only` the length is made read-only afterwards
/// either way.
fn shrink_array(&mut self, id: ObjId, new: u32, read_only: bool) -> JsResult<bool> {
let Class::Array { length: old, .. } = self.object(id)?.class else { return internal("not an array") };
let mut ok = true;
let mut length = new;
if new < old {
for _ in 0..self.object(id)?.props.len() {
self.use_fuel()?;
}
let o = self.object_mut(id)?;
let mut doomed: Vec<(u32, Key)> =
o.props.iter().filter_map(|(k, _)| array_index(k).filter(|&i| i >= new).map(|i| (i, k.clone()))).collect();
doomed.sort_unstable_by_key(|d| std::cmp::Reverse(d.0));
for (i, k) in doomed {
if o.props.get(&k).is_some_and(|p| !p.configurable()) {
length = i + 1;
ok = false;
break;
}
o.props.remove(&k);
}
}
if let Class::Array { length: l, length_writable } = &mut self.object_mut(id)?.class {
*l = length;
if read_only {
*length_writable = false;
}
}
Ok(ok)
}
/// The names of an object's own properties (section 15.2.3.4): a String object's indices and
/// `length` first, then the rest in the order they were added, which is the order `for-in`
/// visits them, then an array's `length`. Each name takes a unit of fuel, and the heap for the
/// list is checked first.
pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult<Vec<Key>> {
let o = self.object(id)?;
// A typed array's indices come first, as a String object's do (section 9.4.5.6).
let string_len = match &o.class {
Class::String(s) => s.len(),
Class::TypedArray(view) => view.length,
_ => 0,
};
let is_string = matches!(o.class, Class::String(_));
let is_array = matches!(o.class, Class::Array { .. });
let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array));
self.reserve_heap(index_keys_bytes(string_len).saturating_add(count.saturating_mul(KEY_ENTRY_BYTES)))?;
let mut out = Vec::with_capacity(count);
for i in 0..string_len {
self.use_fuel()?;
out.push(index_key(u32::try_from(i).unwrap_or(u32::MAX)));
}
if is_string {
out.push(key("length"));
}
for _ in 0..self.object(id)?.props.len() {
self.use_fuel()?;
}
out.extend(self.object(id)?.props.keys());
if is_array {
out.push(key("length"));
}
Ok(out)
}
/// Runs `f` with `values` kept reachable for any collection it starts.
pub(crate) fn rooted<T>(&mut self, values: &[Value], f: impl FnOnce(&mut Self) -> JsResult<T>) -> JsResult<T> {
let mark = self.temp_roots.len();
self.temp_roots.extend(values.iter().cloned());
let r = f(self);
self.temp_roots.truncate(mark);
r
}
pub(crate) fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> {
if throw {
let key = String::from_utf16_lossy(k);
return Err(self.type_error(&format!("cannot assign to property '{key}': {why}")));
}
Ok(())
}
/// [[Put]] (section 8.12.5).
pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> {
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
return crate::builtins::binary::set_element(self, id, n, &v);
}
// A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9).
if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) {
return self.reject(throw, &k, "a module namespace object is read-only");
}
match self.get_own_property(id, &k)? {
Some(Prop::Data { flags, .. }) => {
if flags & WRITABLE == 0 {
return self.reject(throw, &k, "it is read-only");
}
return self.write_own(id, k, v, throw);
}
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
None => {}
}
let mut inherited = None;
let mut cur = self.object(id)?.proto;
let mut steps = 0usize;
while let Some(o) = cur {
// A write that reaches a module namespace object on the prototype chain is refused
// there too: its [[Set]] returns false for every key.
if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) {
return self.reject(throw, &k, "a module namespace object is read-only");
}
if let Some(p) = self.get_own_property(o, &k)? {
inherited = Some(p);
break;
}
cur = self.object(o)?.proto;
steps += 1;
if steps > 1_000_000 {
return internal("prototype chain too long");
}
}
match inherited {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"),
_ => {}
}
if !self.object(id)?.extensible {
// A name that an object of a host class with an indexer lacks, and its prototypes lack
// too, is read with the indexer first, so assigning it throws what reading it throws.
if inherited.is_none()
&& array_index(&k).is_none()
&& let Some(f) = self.host_indexer(id)?
{
self.host_index(&f, id, Self::indexer_key(&k), false)?;
}
return self.reject(throw, &k, "the object is not extensible");
}
let o = self.object(id)?;
if let Class::Array { length, length_writable: false } = o.class
&& array_index(&k).is_some_and(|i| i >= length)
{
return self.reject(throw, &k, "the array's length is read-only");
}
self.define(id, k, Prop::Data { value: v, flags: OPEN })
}
/// Sets the value of an existing writable own data property.
fn write_own(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> {
let o = self.object(id)?;
match &o.class {
Class::Array { .. } if is(&k, "length") => return self.set_array_length(id, &v, throw),
Class::Arguments(map) => {
if let Some(name) = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref) {
let (env, name) = (map.env, name.clone());
if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env)
&& let Some(b) = bindings.get_mut(&name)
{
b.value = v.clone();
}
}
}
_ => {}
}
match self.object_mut(id)?.props.get_mut(&k) {
Some(Prop::Data { value, .. }) => {
*value = v;
Ok(())
}
_ => internal("own data property vanished"),
}
}
/// Assigning to an array's `length` (section 15.4.5.1). [[Put]] defines the value, so the
/// value is converted once with ToUint32 and once with ToNumber, as in steps 3.c and 3.d.
fn set_array_length(&mut self, id: ObjId, v: &Value, throw: bool) -> JsResult<()> {
let new = to_uint32(self.to_number(v)?);
if f64::from(new) != self.to_number(v)? {
return Err(self.throw(ErrorType::Range, "invalid array length"));
}
let Class::Array { length_writable, .. } = self.object(id)?.class else { return internal("not an array") };
if !length_writable {
return self.reject(throw, &key("length"), "it is read-only");
}
if !self.shrink_array(id, new, false)? {
return self.reject(throw, &key("length"), "an element cannot be deleted");
}
Ok(())
}
/// [[Delete]] (section 8.12.7).
pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult<bool> {
// A typed array's element cannot be deleted, and a numeric name it has no element for
// is not a property it can hold (section 9.4.5.6 of later editions).
if crate::builtins::binary::typed_key(self, id, k).is_some() {
if self.get_own_property(id, k)?.is_none() {
return Ok(true);
}
if throw {
let key = String::from_utf16_lossy(k);
return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array")));
}
return Ok(false);
}
match self.get_own_property(id, k)? {
None => Ok(true),
Some(p) if p.configurable() => {
let o = self.object_mut(id)?;
o.props.remove(k);
if let Class::Arguments(map) = &mut o.class
&& let Some(slot) = array_index(k).and_then(|i| map.names.get_mut(i as usize))
{
*slot = None;
}
Ok(true)
}
Some(_) if throw => {
let key = String::from_utf16_lossy(k);
Err(self.type_error(&format!("cannot delete property '{key}'")))
}
Some(_) => Ok(false),
}
}
/// PutValue on a property reference (section 8.7.2), whose base may be a primitive.
pub(crate) fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> {
if self.options.e4x && self.is_xml(base) {
return self.xml_put(base, &Value::String(Str::from_rc(k)), &v);
}
let strict = self.strict();
match base {
Value::Object(o) => {
let throw = self.strict_writes();
self.put(*o, k, v, throw)
}
Value::Undefined | Value::Null => {
let key = String::from_utf16_lossy(&k);
let base = if matches!(base, Value::Null) { "null" } else { "undefined" };
Err(self.type_error(&format!("cannot set property '{key}' of {base}")))
}
_ => {
let proto = self.primitive_proto(base, &k)?;
let own = matches!(base, Value::String(s) if is(&k, "length") || array_index(&k).is_some_and(|i| (i as usize) < s.len()));
if !own && let Some(Prop::Accessor { set: Some(s), .. }) = self.find_property(proto, &k)? {
return self.call(&Value::Object(s), base, &[v]).map(drop);
}
self.reject(strict, &k, "the value is a primitive")
}
}
}
fn op_get_member(&mut self, n: u32, with_this: bool) -> JsResult<()> {
let name = self.name(n)?;
let base = self.peek(0)?;
if with_this && self.options.e4x && self.is_xml(&base) {
let (f, this) = self.xml_method(&base, &name)?;
self.replace(1, f)?;
return self.push(this);
}
let v = self.get_value(&base, &name)?;
self.replace(1, v)?;
if with_this { self.push(base) } else { Ok(()) }
}
fn op_set_member(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.peek(0)?;
let base = self.peek(1)?;
self.put_value(&base, name, v.clone())?;
self.replace(2, v)
}
/// Throws when `base` is `null` or `undefined`, naming the property `k` when it is a primitive
/// of at most [`NAMED_KEY_UNITS`] units, which converts without running script code, and the
/// access as a read, or as a write when `set`.
fn check_coercible(&mut self, base: &Value, k: Option<&Value>, set: bool) -> JsResult<()> {
if !base.is_nullish() {
return Ok(());
}
let key = match k {
Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None,
Some(Value::Object(_)) | None => None,
Some(Value::Symbol(s)) if s.description().is_some_and(|d| d.len() > NAMED_KEY_UNITS) => None,
Some(Value::Symbol(s)) => Some(self.sym_name(s)?),
Some(k) => Some(self.to_str(k)?.to_rust_string()),
};
let base = if matches!(base, Value::Null) { "null" } else { "undefined" };
Err(match (key, set) {
(Some(key), false) => self.type_error(&format!("cannot read property '{key}' of {base}")),
(Some(key), true) => self.type_error(&format!("cannot set property '{key}' of {base}")),
(None, false) => self.type_error(&format!("cannot read a property of {base}")),
(None, true) => self.type_error(&format!("cannot set a property of {base}")),
})
}
fn op_check_object(&mut self) -> JsResult<()> {
let base = self.peek(0)?;
self.check_coercible(&base, None, true)
}
fn op_to_key(&mut self) -> JsResult<()> {
let k = self.peek(0)?;
let base = self.peek(1)?;
if self.is_xml_access(&base, &k) {
return Ok(());
}
self.check_coercible(&base, Some(&k), true)?;
let key = match self.to_prop_key(&k)? {
PropKey::Str(name) => Value::String(Str::from_rc(name)),
PropKey::Sym(s) => Value::Symbol(s),
};
self.replace(1, key)
}
fn op_get_index(&mut self, with_this: bool) -> JsResult<()> {
let k = self.peek(0)?;
let base = self.peek(1)?;
if self.is_xml_access(&base, &k) {
if with_this {
let name = self.xml_method_key(&k)?;
let (f, this) = self.xml_method(&base, &name)?;
self.replace(2, f)?;
return self.push(this);
}
let v = self.xml_get(&base, &k)?;
return self.replace(2, v);
}
self.check_coercible(&base, Some(&k), false)?;
let v = self.with_prop_key(&k, |i, key| i.get_value_pk(&base, &key))?;
self.replace(2, v)?;
if with_this { self.push(base) } else { Ok(()) }
}
fn op_set_index(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let k = self.peek(1)?;
let base = self.peek(2)?;
if self.is_xml_access(&base, &k) {
self.xml_put(&base, &k, &v)?;
return self.replace(3, v);
}
let key = self.to_prop_key(&k)?;
self.put_value_pk(&base, key, v.clone())?;
self.replace(3, v)
}
fn op_delete_member(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let base = self.peek(0)?;
if self.options.e4x && self.is_xml(&base) {
let r = self.xml_delete(&base, &Value::String(Str::from_rc(name)))?;
return self.replace(1, Value::Bool(r));
}
let o = self.to_object(&base)?;
let strict = self.strict();
let r = self.delete(o, &name, strict)?;
self.replace(1, Value::Bool(r))
}
fn op_delete_index(&mut self) -> JsResult<()> {
let k = self.peek(0)?;
let base = self.peek(1)?;
if self.is_xml_access(&base, &k) {
let r = self.xml_delete(&base, &k)?;
return self.replace(2, Value::Bool(r));
}
self.check_coercible(&base, Some(&k), false)?;
let key = self.to_prop_key(&k)?;
let o = self.to_object(&base)?;
let strict = self.strict();
let r = self.delete_pk(o, &key, strict)?;
self.replace(2, Value::Bool(r))
}
fn inc_property(&mut self, base: &Value, key: PropKey, prefix: bool, dec: bool) -> JsResult<Value> {
let v = self.get_value_pk(base, &key)?;
let old = self.to_number(&v)?;
let new = if dec { old - 1.0 } else { old + 1.0 };
self.put_value_pk(base, key, Value::Number(new))?;
Ok(Value::Number(if prefix { new } else { old }))
}
fn op_inc_member(&mut self, n: u32, prefix: bool, dec: bool) -> JsResult<()> {
let name = self.name(n)?;
let base = self.peek(0)?;
let r = self.inc_property(&base, PropKey::Str(name), prefix, dec)?;
self.replace(1, r)
}
fn op_inc_index(&mut self, prefix: bool, dec: bool) -> JsResult<()> {
let k = self.peek(0)?;
let base = self.peek(1)?;
if self.is_xml_access(&base, &k) {
let v = self.xml_get(&base, &k)?;
let old = self.to_number(&v)?;
let new = if dec { old - 1.0 } else { old + 1.0 };
self.xml_put(&base, &k, &Value::Number(new))?;
return self.replace(2, Value::Number(if prefix { new } else { old }));
}
self.check_coercible(&base, Some(&k), false)?;
let r = self.with_prop_key(&k, |i, key| i.inc_property(&base, key, prefix, dec))?;
self.replace(2, r)
}
// ---- object literals and functions ----
fn op_new_object(&mut self) -> JsResult<()> {
let o = self.new_object();
self.push(Value::Object(o))
}
pub(crate) fn new_object(&mut self) -> ObjId {
let proto = self.intrinsics.object_proto;
self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))
}
fn op_new_array(&mut self) -> JsResult<()> {
let proto = self.intrinsics.array_proto;
let a = self.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto)));
self.push(Value::Object(a))
}
fn op_array_push(&mut self, with_value: bool) -> JsResult<()> {
let v = if with_value { Some(self.pop()?) } else { None };
let Value::Object(a) = self.peek(0)? else { return internal("array literal is not an object") };
let o = self.object_mut(a)?;
let Class::Array { length, .. } = &mut o.class else { return internal("array literal is not an array") };
let i = *length;
if i == u32::MAX - 1 {
return Err(self.throw(ErrorType::Range, "array literal too long"));
}
*length = i + 1;
match v {
Some(v) => self.define(a, index_key(i), Prop::Data { value: v, flags: OPEN }),
None => Ok(()),
}
}
fn op_init_prop(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.pop()?;
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
self.define(o, name, Prop::Data { value: v, flags: OPEN })
}
fn op_init_accessor(&mut self, n: u32, getter: bool) -> JsResult<()> {
let name = self.name(n)?;
let Value::Object(f) = self.pop()? else { return internal("accessor is not a function") };
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
let (mut get, mut set) = match self.object(o)?.props.get(&name) {
Some(Prop::Accessor { get, set, .. }) => (*get, *set),
_ => (None, None),
};
if getter {
get = Some(f);
} else {
set = Some(f);
}
self.define(o, name, Prop::Accessor { get, set, flags: ENUMERABLE | CONFIGURABLE })
}
/// Ends the run with the heap limit when the object literal `o` does not have the computed key
/// `k` yet and a new property for it would not fit. `value` is kept through any collection.
fn reserve_literal_key(&mut self, o: ObjId, k: &Value, value: Value) -> JsResult<()> {
let bytes = match k {
Value::Symbol(s) => (self.get_own_sym(o, s)?.is_none()).then_some(PROP_BYTES),
Value::String(s) => {
let name = s.flat();
(!self.object(o)?.props.contains(&name)).then(|| PROP_BYTES + string_bytes(name.len()))
}
_ => return internal("computed property name is not a key"),
};
match bytes {
Some(bytes) => self.rooted(&[k.clone(), value], |i| i.reserve_heap(bytes)),
None => Ok(()),
}
}
/// `object key value` → `object`: a property with a computed name, the key already a name or
/// a Symbol.
fn op_init_index(&mut self) -> JsResult<()> {
let v = self.pop()?;
let k = self.pop()?;
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
self.reserve_literal_key(o, &k, v.clone())?;
let prop = Prop::Data { value: v, flags: OPEN };
match k {
Value::Symbol(s) => self.define_sym(o, s, prop),
Value::String(s) => self.define(o, s.flat(), prop),
_ => internal("computed property name is not a key"),
}
}
/// `object key function` → `object`: a getter (or a setter) with a computed name.
fn op_init_accessor_index(&mut self, getter: bool) -> JsResult<()> {
let Value::Object(f) = self.pop()? else { return internal("accessor is not a function") };
let k = self.pop()?;
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
self.reserve_literal_key(o, &k, Value::Object(f))?;
let current = match &k {
Value::Symbol(s) => self.get_own_sym(o, s)?,
Value::String(s) => self.object(o)?.props.get(&s.flat()).cloned(),
_ => return internal("computed property name is not a key"),
};
let (mut get, mut set) = match current {
Some(Prop::Accessor { get, set, .. }) => (get, set),
_ => (None, None),
};
if getter {
get = Some(f);
} else {
set = Some(f);
}
let prop = Prop::Accessor { get, set, flags: ENUMERABLE | CONFIGURABLE };
match k {
Value::Symbol(s) => self.define_sym(o, s, prop),
Value::String(s) => self.define(o, s.flat(), prop),
_ => internal("computed property name is not a key"),
}
}
/// `__proto__: value` in an object literal: an object or `null` becomes the new object's
/// prototype, and any other value is ignored (ECMA-262 2015 section B.3.1).
fn op_init_proto(&mut self) -> JsResult<()> {
let v = self.pop()?;
let Value::Object(o) = self.peek(0)? else { return internal("object literal is not an object") };
let proto = match v {
Value::Object(p) => Some(p),
Value::Null => None,
_ => return Ok(()),
};
self.object_mut(o)?.proto = proto;
Ok(())
}
fn op_set_function_name(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let Value::Object(f) = self.peek(0)? else { return internal("a function to name is not an object") };
self.set_function_name(f, Value::String(Str::from_rc(name)))
}
/// `key function` → `key function`: names the function after the computed key under it. A
/// Symbol key gives its description in brackets, or the empty string when it has none
/// (ECMA-262 2015 section 9.2.11).
fn op_set_function_name_key(&mut self, prefix: NamePrefix) -> JsResult<()> {
let Value::Object(f) = self.peek(0)? else { return internal("a function to name is not an object") };
let name = match self.peek(1)? {
Value::String(s) if prefix == NamePrefix::None => Value::String(s),
Value::String(s) => self.wrap_str(prefix.text(), Some(&s), "")?,
Value::Symbol(k) => match k.description() {
Some(d) => self.wrap_str(&format!("{}[", prefix.text()), Some(d), "]")?,
None => self.wrap_str(prefix.text(), None, "")?,
},
_ => return internal("computed property name is not a key"),
};
self.set_function_name(f, name)
}
/// Gives `f` its `name` (ECMA-262 2015 section 9.2.11): not writable, not enumerable,
/// configurable.
pub(crate) fn set_function_name(&mut self, f: ObjId, name: Value) -> JsResult<()> {
// A class whose static members define `name` keeps that member (section 12.14.4,
// step 1.e): its own `name` is no longer the empty string it was made with.
let object = self.object(f)?;
let class_ctor = matches!(&object.class, Class::Function(Func::Closure { code, .. }) if code.class_ctor);
let default = match object.props.get(&key("name")) {
None => true,
Some(Prop::Data { value: Value::String(s), .. }) => s.len() == 0,
Some(_) => false,
};
if class_ctor && !default {
return Ok(());
}
// The empty `name` an ECMAScript 2015 function is made with is replaced in place.
if !self.object(f)?.props.contains(&key("name")) {
self.rooted(&[name.clone(), Value::Object(f)], |i| i.reserve_heap(PROP_BYTES + string_bytes("name".len())))?;
}
self.define(f, key("name"), Prop::Data { value: name, flags: CONFIGURABLE })
}
fn op_closure(&mut self, i: u32) -> JsResult<()> {
let frame = self.frame()?;
let (env, this) = (frame.env, frame.this.clone());
// In an arrow function or a derived class constructor, and in the direct eval code they
// run, `this` is already a binding of the environment chain, which the new function reads
// as it is when it runs.
let this_bound = frame.this_in_env;
let Some(code) = frame.code.functions.get(i as usize).cloned() else { return internal("function out of range") };
// An arrow function keeps the `this` of the code it is made in (ECMA-262 2015 section
// 14.2.16), in an environment of its own that only the call reads.
let env = if code.arrow && code.uses_this && !this_bound {
self.reserve_heap(ENV_BYTES + binding_bytes(ARROW_THIS.len()))?;
let mut bindings = PropMap::default();
bindings.insert(Rc::from(ARROW_THIS), Binding::new(this, false, false));
self.heap.bytes += string_bytes(ARROW_THIS.len());
self.heap.alloc_env(Env::Decl { bindings, outer: Some(env) })
} else {
env
};
let f = self.make_closure(code, env)?;
self.push(Value::Object(f))
}
/// A function object for `code` closing over `env` (section 13.2).
pub(crate) fn make_closure(&mut self, code: Rc<Code>, env: EnvId) -> JsResult<ObjId> {
let env = match &code.self_name {
Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }),
None => env,
};
let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten();
let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto);
let length = code.length;
let strict = code.strict;
let arrow = code.arrow;
let method = code.method;
let class_ctor = code.class_ctor;
let self_name = code.self_name.clone();
let own_name = code.own_name.clone();
// With ECMAScript 2015, `length` can be redefined (section 19.2.4.1).
let length_flags = if code.es2015 { CONFIGURABLE } else { 0 };
let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto)));
self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: length_flags })?;
if let Some(name) = own_name {
self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?;
}
// A generator function's `prototype`, a generator method's included, inherits from
// %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13).
// A generator function has no own `caller` or `arguments`, strict or not
// (section 16.2).
if let (false, Some((_, generator_proto))) = (arrow, generator) {
let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto)));
self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?;
if let Some(name) = self_name {
self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?;
}
return Ok(f);
}
// An arrow function, a method and an accessor of ECMAScript 2015 code have no
// `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8); a class
// constructor gets its `prototype` from the class.
if arrow || method || class_ctor {
return Ok(f);
}
let p = self.new_object();
self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?;
self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?;
if strict {
let thrower = Some(self.intrinsics.throw_type_error);
for name in ["caller", "arguments"] {
self.define(f, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?;
}
}
if let Some(name) = self_name {
self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?;
}
Ok(f)
}
pub(crate) fn env_insert(&mut self, env: EnvId, name: Key, b: Binding) -> JsResult<()> {
let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) else { return internal("not a declarative environment") };
let new = !bindings.contains(&name);
let name_len = name.len();
bindings.insert(name, b);
if new {
self.heap.bytes += PROP_BYTES + string_bytes(name_len);
}
Ok(())
}
fn op_regexp(&mut self, i: u32) -> JsResult<()> {
let Some((source, flags)) = self.frame()?.code.regexps.get(i as usize).cloned() else { return internal("regular expression out of range") };
let r = crate::regexp_builtins::new_regexp(self, &source, &flags)?;
self.push(Value::Object(r))
}
// ---- environments ----
fn op_push_with(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let object = self.to_object(&v)?;
self.pop()?;
let outer = self.frame()?.env;
let env = self.heap.alloc_env(Env::Obj { object, with_this: true, outer: Some(outer) });
let frame = self.frame_mut()?;
frame.env = env;
frame.env_depth += 1;
Ok(())
}
fn op_push_catch(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.pop()?;
let outer = self.frame()?.env;
let mut bindings = PropMap::default();
let name_bytes = string_bytes(name.len());
bindings.insert(name, Binding::new(v, true, false));
let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
self.heap.bytes += name_bytes;
let frame = self.frame_mut()?;
frame.env = env;
frame.env_depth += 1;
Ok(())
}
fn op_pop_env(&mut self) -> JsResult<()> {
let env = self.frame()?.env;
let Some(outer) = self.heap.env(env).and_then(Env::outer) else { return internal("left the outermost environment") };
let frame = self.frame_mut()?;
if frame.env_depth == 0 {
return internal("left more environments than were entered");
}
frame.env = outer;
frame.env_depth -= 1;
Ok(())
}
fn op_push_block(&mut self, i: u32) -> JsResult<()> {
let frame = self.frame()?;
let (code, outer) = (frame.code.clone(), frame.env);
let env = self.block_env(&code, i, outer)?;
let frame = self.frame_mut()?;
frame.env = env;
frame.env_depth += 1;
Ok(())
}
/// A copy of the current environment's bindings in a new environment with the same outer
/// one (ECMA-262 2015 section 13.7.4.9). Each binding takes a unit of fuel.
fn op_copy_env(&mut self) -> JsResult<()> {
let env = self.frame()?.env;
let Some(Env::Decl { bindings, outer }) = self.heap.env(env) else { return internal("not a declarative environment") };
let (count, outer) = (bindings.len(), *outer);
let bytes = bindings.iter().map(|(k, _)| binding_bytes(k.len())).sum::<usize>();
for _ in 0..count {
self.use_fuel()?;
}
self.reserve_heap(ENV_BYTES.saturating_add(bytes))?;
let Some(Env::Decl { bindings, .. }) = self.heap.env(env) else { return internal("not a declarative environment") };
let copy = bindings.clone();
let name_bytes = copy.iter().map(|(k, _)| string_bytes(k.len())).sum::<usize>();
let new = self.heap.alloc_env(Env::Decl { bindings: copy, outer });
self.heap.bytes += name_bytes;
self.frame_mut()?.env = new;
Ok(())
}
/// The nearest declarative binding of `name` from the current environment out.
fn find_binding(&self, name: &[u16]) -> JsResult<Option<EnvId>> {
let mut cur = Some(self.frame()?.env);
while let Some(e) = cur {
match self.heap.env(e) {
Some(Env::Decl { bindings, outer }) => {
if bindings.contains(name) {
return Ok(Some(e));
}
cur = *outer;
}
Some(Env::Obj { outer, .. }) => cur = *outer,
None => return internal("environment out of range"),
}
}
Ok(None)
}
fn op_init_var(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.pop()?;
let Some(env) = self.find_binding(&name)? else { return internal("initializing a binding that was not declared") };
let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) else { return internal("not a declarative environment") };
let Some(b) = bindings.get_mut(&name) else { return internal("binding missing") };
b.value = v;
b.uninitialized = false;
Ok(())
}
fn op_load_param(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let Some(env) = self.find_binding(&name)? else { return internal("parameter missing") };
let v = self.binding_value(env, &name)?;
self.push(v)
}
/// Enters the body of a function with default values for its parameters: a variable environment
/// inside the parameters' one, whose variables start with the value of a parameter of the
/// same name (ECMA-262 2015 section 9.2.12, step 28), and the body's function declarations
/// and `let` and `const` names.
fn op_body_env(&mut self) -> JsResult<()> {
let frame = self.frame()?;
let (code, params) = (frame.code.clone(), frame.env);
// The parameters' values may have filled the room the call reserved, so the body's
// environments and declarations are checked against the heap again, together, and each
// declaration again just before it is made.
let top = code.top_scope.map_or(0, |i| scope_bytes(&code, i));
self.reserve_heap(declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(top))?;
// Each new environment is in the frame, where the collector finds it, before the next
// allocation.
let var_env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(params) });
self.frame_mut()?.var_env = var_env;
let lex = self.top_env(&code, var_env)?;
self.frame_mut()?.env = lex;
// The declarations are checked after the `let` and `const` environment has taken its room.
self.reserve_heap(declaration_bytes(&code))?;
for (name, fi) in &code.fun_decls {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
self.reserve_heap(binding_bytes(name.len()).saturating_add(closure_bytes(&fcode)))?;
let f = self.make_closure(fcode, lex)?;
self.temp_roots.push(Value::Object(f));
let r = self.env_insert(var_env, name.clone(), Binding::new(Value::Object(f), true, false));
self.temp_roots.pop();
r?;
}
for v in &code.vars {
self.use_fuel()?;
if matches!(self.heap.env(var_env), Some(Env::Decl { bindings, .. }) if bindings.contains(v)) {
continue;
}
let initial = match self.heap.env(params) {
Some(Env::Decl { bindings, .. }) => bindings.get(v).map_or(Value::Undefined, |b| b.value.clone()),
_ => Value::Undefined,
};
// The initial value is reachable from the parameters' environment while the heap is
// checked.
self.reserve_heap(binding_bytes(v.len()))?;
self.env_insert(var_env, v.clone(), Binding::new(initial, true, false))?;
}
Ok(())
}
/// Assigns a function declared in a block to the variable of the same name.
fn op_annex_b(&mut self, n: u32) -> JsResult<()> {
let name = self.name(n)?;
let v = self.peek(0)?;
let var_env = self.frame()?.var_env;
match self.heap.env(var_env) {
Some(Env::Decl { .. }) => self.env_insert(var_env, name, Binding::new(v, true, false))?,
Some(&Env::Obj { object, .. }) => self.put(object, name, v, false)?,
None => return internal("environment out of range"),
}
self.pop().map(drop)
}
// ---- ECMAScript 2015 spread and templates ----
/// Takes the array of a call's or `new`'s arguments off the stack and pushes its elements.
fn unpack_args(&mut self) -> JsResult<u32> {
let Value::Object(a) = self.peek(0)? else { return internal("arguments are not an array") };
let length = match &self.object(a)?.class {
Class::Array { length, .. } => *length,
_ => return internal("arguments are not an array"),
};
if length as usize > MAX_APPLY_ARGS {
return Err(self.throw(ErrorType::Range, "too many arguments"));
}
let mut args = Vec::with_capacity(length as usize);
for i in 0..length {
args.push(
self.get_own_property(a, &index_key(i))?
.and_then(|p| if let Prop::Data { value, .. } = p { Some(value) } else { None })
.unwrap_or(Value::Undefined),
);
}
self.pop()?;
self.stack.extend(args);
Ok(length)
}
fn op_call_spread(&mut self, eval: bool) -> JsResult<()> {
let n = self.unpack_args()?;
self.op_call(n, eval)
}
fn op_new_spread(&mut self) -> JsResult<()> {
let n = self.unpack_args()?;
self.op_new(n)
}
/// The template object of `templates[i]` of the running code: a frozen array of the cooked
/// strings whose `raw` property is a frozen array of the raw strings, made once for each
/// site (ECMA-262 2015 section 12.2.9.3).
fn op_template_object(&mut self, i: u32) -> JsResult<()> {
let code = self.frame()?.code.clone();
let site = (Rc::as_ptr(&code) as usize, i);
if let Some(&(_, id)) = self.template_objects.get(&site) {
return self.push(Value::Object(id));
}
let Some(t) = code.templates.get(i as usize) else { return internal("template out of range") };
// Both arrays with their index properties and keys, and the cooked array's `raw`, as
// [`Self::define`] counts them.
let bytes = OBJECT_BYTES
.saturating_mul(2)
.saturating_add(index_names_bytes(t.cooked.len(), PROP_BYTES))
.saturating_add(index_names_bytes(t.raw.len(), PROP_BYTES))
.saturating_add(PROP_BYTES + string_bytes("raw".len()));
self.reserve_heap(bytes)?;
let raw = self.frozen_array(&t.raw)?;
// The raw array stays reachable while the template object is made.
self.push(Value::Object(raw))?;
let cooked = self.frozen_array(&t.cooked)?;
self.push(Value::Object(cooked))?;
self.define(cooked, key("raw"), Prop::Data { value: Value::Object(raw), flags: 0 })?;
if let Some(o) = self.heap.object_mut(cooked) {
o.extensible = false;
}
// The template object replaces the raw array under it on the stack.
self.pop()?;
self.pop()?;
self.template_objects.insert(site, (code, cooked));
self.push(Value::Object(cooked))
}
fn frozen_array(&mut self, strings: &[Str]) -> JsResult<ObjId> {
let proto = self.intrinsics.array_proto;
let length = u32::try_from(strings.len()).map_err(|_| self.throw(ErrorType::Range, "template too long"))?;
let a = self.heap.alloc_object(Object::new(Class::Array { length, length_writable: false }, Some(proto)));
// The array stays reachable while it is filled.
self.temp_roots.push(Value::Object(a));
let mut fill = || -> JsResult<()> {
for (i, s) in strings.iter().enumerate() {
self.use_fuel()?;
self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: Value::String(s.clone()), flags: ENUMERABLE })?;
}
Ok(())
};
let r = fill();
self.temp_roots.pop();
r?;
if let Some(o) = self.heap.object_mut(a) {
o.extensible = false;
}
Ok(a)
}
// ---- for-in ----
/// The names `for-in` visits (section 12.6.4): the enumerable properties of the object and
/// its prototypes, own properties in the order they were added, each name once, and none
/// that an object nearer the start of the chain has (enumerable or not).
///
/// For a String object, the heap budget for all its index names is checked before any is
/// built. Each index name and each property visited takes a unit of fuel.
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<Vec<Key>> {
if self.options.e4x && self.is_xml(&Value::Object(id)) {
return self.xml_enumerate(id);
}
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
let mut cur = Some(id);
while let Some(o) = cur {
let obj = self.object(o)?;
let string_len = match &obj.class {
Class::String(s) => Some(s.len()),
Class::TypedArray(view) => Some(view.length),
_ => None,
};
let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_));
if let Some(len) = string_len {
self.reserve_heap(index_keys_bytes(len))?;
for i in 0..len {
self.use_fuel()?;
let k = index_key(u32::try_from(i).unwrap_or(u32::MAX));
if seen.insert(k.clone()) {
out.push(k);
}
}
}
if is_array {
seen.insert(key("length"));
}
for _ in 0..self.object(o)?.props.len() {
self.use_fuel()?;
}
let obj = self.object(o)?;
for (k, p) in obj.props.iter() {
if seen.insert(k.clone()) && p.enumerable() {
out.push(k.clone());
}
}
cur = obj.proto;
}
Ok(out)
}
fn op_for_in_start(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let (keys, object) = if v.is_nullish() {
(Vec::new(), None)
} else {
let o = self.to_object(&v)?;
// A wrapper made by ToObject is not on the stack; a collection while the names are
// listed or their bytes reserved must not free it.
let saved = self.temp_roots.len();
self.temp_roots.push(Value::Object(o));
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
let keys = self.enumerable_keys(o).and_then(|keys| {
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
self.reserve_heap(bytes)?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
Ok(keys)
});
self.temp_roots.truncate(saved);
(keys?, Some(o))
};
let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, pos: 0, object })), None));
self.replace(1, Value::Object(iter))
}
fn op_for_in_next(&mut self, target: u32) -> JsResult<()> {
let Value::Object(iter) = self.peek(0)? else { return internal("for-in iterator is not an object") };
loop {
let Class::ForIn(state) = &mut self.object_mut(iter)?.class else { return internal("not a for-in iterator") };
let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) };
state.pos += 1;
let object = state.object;
if let Some(o) = object
&& self.scope_has(o, &k)?
{
return self.push(Value::String(Str::from_rc(k)));
}
}
}
// ---- calls ----
pub(crate) fn is_callable(&self, v: &Value) -> bool {
v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_)))
}
pub(crate) fn func_of(&self, v: &Value) -> Option<Func> {
match &self.heap.object(v.as_object()?)?.class {
Class::Function(f) => Some(f.clone()),
_ => None,
}
}
/// Resolves `call` and `apply` and runs native and host functions; a function written in
/// JavaScript comes back to be entered by the caller.
fn prepare_call(&mut self, mut f: Value, mut this: Value, mut args: Vec<Value>) -> JsResult<Prepared> {
loop {
let Some(func) = self.func_of(&f) else { return Err(self.type_error("the value is not a function")) };
match func {
Func::Closure { code, .. } if code.class_ctor => {
return Err(self.type_error("a class constructor cannot be called without 'new'"));
}
Func::Closure { code, env } => {
let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?;
return Ok(Prepared::Closure(Entry { callee, code, env, this, args, new_target: None }));
}
Func::Native { kind: NativeKind::Resume(mode), .. } => {
self.use_fuel()?;
let sent = args.into_iter().next().unwrap_or(Value::Undefined);
return self.prepare_resume(this, mode, sent);
}
Func::Native { kind: NativeKind::Call, .. } => {
self.use_fuel()?;
f = this;
this = if args.is_empty() { Value::Undefined } else { args.remove(0) };
}
Func::Native { kind: NativeKind::Apply, .. } => {
self.use_fuel()?;
if !self.is_callable(&this) {
return Err(self.type_error("apply was called on a value that is not a function"));
}
let list = args.get(1).cloned().unwrap_or(Value::Undefined);
let mut roots = vec![f.clone(), this.clone()];
roots.extend(args.iter().cloned());
let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?;
f = this;
this = args.first().cloned().unwrap_or(Value::Undefined);
args = expanded;
}
Func::Bound { target, this: bound_this, args: bound_args } => {
self.use_fuel()?;
let mut all = Vec::with_capacity(bound_args.len().saturating_add(args.len()));
all.extend(bound_args.iter().cloned());
all.append(&mut args);
args = all;
this = bound_this;
f = Value::Object(target);
}
Func::Native { f: native, .. } => {
// A list from `apply` and the arguments a bound function adds are not on the
// operand stack, and a native function can run JavaScript that collects, so the
// arguments stay rooted for the call.
let mark = self.temp_roots.len();
self.temp_roots.push(this.clone());
self.temp_roots.extend(args.iter().cloned());
let held = self.held_bytes;
let r = native(self, this, &args, false);
self.held_bytes = held;
self.temp_roots.truncate(mark);
return Ok(Prepared::Done(r?));
}
Func::Pausable { f: native, .. } => {
let mark = self.temp_roots.len();
self.temp_roots.push(this.clone());
self.temp_roots.extend(args.iter().cloned());
let held = self.held_bytes;
let r = native(self, this, &args).and_then(|p| self.ask(p));
self.held_bytes = held;
self.temp_roots.truncate(mark);
return Ok(Prepared::Done(r?));
}
Func::Data { f, name, read } => {
// The arguments are read before the function runs, and a result being built
// keeps itself reachable.
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
}
Func::Eval { f, end, strict_writes, name, site } => {
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?));
}
Func::Host { f: host, .. } => {
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
return match host(&js_args) {
Ok(v) => Ok(Prepared::Done(self.from_js_value(v)?)),
Err(message) => {
let bytes = string_bytes(message.encode_utf16().count());
self.reserve_heap(bytes)?;
self.heap.bytes += bytes;
Err(self.throw(ErrorType::Error, &message))
}
};
}
}
}
}
/// The elements of an array-like `apply` argument (section 15.3.4.3).
fn list_from_array_like(&mut self, list: &Value) -> JsResult<Vec<Value>> {
let Value::Object(o) = list else {
if list.is_nullish() {
return Ok(Vec::new());
}
return Err(self.type_error("the argument list is not an object"));
};
let len = self.get_from(*o, &key("length"), list)?;
let n = to_uint32(self.to_number(&len)?) as usize;
if n > MAX_APPLY_ARGS {
return Err(self.throw(ErrorType::Range, "too many arguments"));
}
let saved = self.temp_roots.len();
let mut out = Vec::with_capacity(n);
for i in 0..n {
// Each element read takes fuel, so a long array-like list stays within the run's limits.
match self.use_fuel().and_then(|()| self.get_from(*o, &index_key(u32::try_from(i).unwrap_or(u32::MAX)), list)) {
Ok(v) => {
self.temp_roots.push(v.clone());
out.push(v);
}
Err(e) => {
self.temp_roots.truncate(saved);
return Err(e);
}
}
}
self.temp_roots.truncate(saved);
Ok(out)
}
fn op_call(&mut self, argc: u32, eval: bool) -> JsResult<()> {
let n = argc as usize;
let start =
self.stack.len().checked_sub(n + 2).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("call below the stack".into()))?;
let f = self.stack.get(start).cloned().unwrap_or(Value::Undefined);
let this = self.stack.get(start + 1).cloned().unwrap_or(Value::Undefined);
let args: Vec<Value> = self.stack.get(start + 2..).map(<[Value]>::to_vec).unwrap_or_default();
if eval && f.as_object() == Some(self.intrinsics.eval) {
return self.direct_eval(start, args);
}
match self.prepare_call(f, this, args)? {
Prepared::Done(v) => {
self.stack.truncate(start);
self.push(v)
}
Prepared::Closure(entry) => {
self.stack.truncate(start);
self.enter_function(entry, None, false)
}
Prepared::Resume(r) => {
self.stack.truncate(start);
self.enter_resumed(*r, false)
}
}
}
fn op_new(&mut self, argc: u32) -> JsResult<()> {
let n = argc as usize;
let start =
self.stack.len().checked_sub(n + 1).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("new below the stack".into()))?;
let f = self.stack.get(start).cloned().unwrap_or(Value::Undefined);
let args: Vec<Value> = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default();
self.construct(start, f, args, None)
}
/// Pushes a frame for a call to a function written in JavaScript, its operands already off
/// the stack.
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
let Entry { callee, code, env, this, args, new_target } = entry;
self.check_frame_room()?;
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
// An arrow function reads the `arguments` object of the function around it.
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
// The array a rest parameter gets: its binding and one property for each extra argument.
let rest = match &code.rest {
Some(name) => {
let extra = args.len().saturating_sub(code.params.len());
OBJECT_BYTES.saturating_add(binding_bytes(name.len())).saturating_add(extra.saturating_mul(binding_bytes(10)))
}
None => 0,
};
let need = declaration_bytes(&code)
.saturating_add(ENV_BYTES)
.saturating_add(params)
.saturating_add(arguments)
.saturating_add(rest)
.saturating_add(crate::class_ops::hidden_bytes(&code));
// The callee, the receiver and the arguments stay reachable until the frame holds them:
// the reservation and the scopes, functions and objects the call makes can collect.
let mark = self.temp_roots.len();
self.temp_roots.push(Value::Object(callee));
self.temp_roots.push(this.clone());
self.temp_roots.extend(construct.map(Value::Object));
self.temp_roots.extend(new_target.map(Value::Object));
self.temp_roots.extend(args.iter().cloned());
let enter = || -> JsResult<()> {
self.reserve_heap(need)?;
let this = if code.arrow {
if code.uses_this { self.arrow_this(env) } else { Value::Undefined }
} else if code.strict {
this
} else {
match this {
Value::Undefined | Value::Null => Value::Object(self.global),
Value::Object(_) => this,
prim => Value::Object(self.to_object(&prim)?),
}
};
self.temp_roots.push(this.clone());
let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?;
let this_env = self.function_bindings(&code, var_env, callee, new_target)?;
let base = self.stack.len();
let this_in_env = code.arrow || code.derived;
self.frames.push(Frame {
code,
pc: 0,
base,
env: fenv,
var_env,
env_depth: 0,
this,
this_in_env,
strict_class: false,
callee: Some(callee),
construct,
new_target,
this_env,
completion: Value::Undefined,
boundary,
generator: None,
chained: false,
pending_module: false,
});
Ok(())
};
let r = enter();
self.temp_roots.truncate(mark);
r
}
/// Declaration binding instantiation for function code (section 10.5). Each parameter and
/// declaration takes a unit of fuel.
/// Gives the environment the body runs in and its variable environment. A function with
/// default values for its parameters gets its parameters uninitialized, and its code enters the
/// body's environments with [`Op::BodyEnv`] once they are initialized (ECMA-262 2015 section
/// 9.2.12).
fn instantiate_function(&mut self, code: &Rc<Code>, outer: EnvId, args: &[Value], callee: ObjId) -> JsResult<(EnvId, EnvId)> {
let mut bindings = PropMap::default();
for (i, p) in code.params.iter().enumerate() {
self.use_fuel()?;
let mut b = Binding::new(args.get(i).cloned().unwrap_or(Value::Undefined), true, false);
b.uninitialized = code.param_init;
b.lexical = code.param_init;
bindings.insert(p.clone(), b);
}
if let Some(rest) = &code.rest {
let extra = args.get(code.params.len()..).unwrap_or_default();
let a = self.array_of(extra)?;
let mut b = Binding::new(Value::Object(a), true, false);
b.uninitialized = code.param_init;
b.lexical = code.param_init;
bindings.insert(rest.clone(), b);
}
for name in &code.pattern_names {
self.use_fuel()?;
bindings.insert(name.clone(), Binding::lexical(false));
}
let name_bytes = bindings.iter().map(|(k, _)| string_bytes(k.len())).sum::<usize>();
let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
self.heap.bytes += name_bytes;
let has = |interp: &Self, name: &[u16]| matches!(interp.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
let needs_arguments = code.uses_arguments && !code.arrow;
if code.param_init {
if needs_arguments && !has(self, &key("arguments")) {
// The environment stays reachable while the object, which can collect, is made.
self.temp_envs.push(env);
let a = self.create_arguments(code, env, args, callee);
self.temp_envs.pop();
self.env_insert(env, key("arguments"), Binding::new(Value::Object(a?), !code.strict, false))?;
}
return Ok((env, env));
}
// The environments stay reachable while the body's scope, its functions and its
// `arguments` object, each of which can collect, are made.
let mark = self.temp_envs.len();
self.temp_envs.push(env);
let r = self.instantiate_function_body(code, env, args, callee, needs_arguments);
self.temp_envs.truncate(mark);
r.map(|lex| (lex, env))
}
/// Declares the body of function code in its variable environment `env`, which the caller
/// keeps reachable: the `let` and `const` names at its top, its functions, its `arguments`
/// object and its variables. Gives the environment of the top `let` and `const` names, which
/// it adds to the temporary roots for the caller to remove.
fn instantiate_function_body(&mut self, code: &Rc<Code>, env: EnvId, args: &[Value], callee: ObjId, needs_arguments: bool) -> JsResult<EnvId> {
let has = |interp: &Self, name: &[u16]| matches!(interp.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
let lex = self.top_env(code, env)?;
self.temp_envs.push(lex);
// The call reserved room for the declarations and the `arguments` object before the `let`
// and `const` environment took some of it.
let arguments = if needs_arguments && !has(self, &key("arguments")) { arguments_bytes(args.len()) } else { 0 };
self.reserve_heap(declaration_bytes(code).saturating_add(arguments))?;
for (name, fi) in &code.fun_decls {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
let f = self.make_closure(fcode, lex)?;
self.env_insert(env, name.clone(), Binding::new(Value::Object(f), true, false))?;
}
if needs_arguments && !has(self, &key("arguments")) {
let a = self.create_arguments(code, env, args, callee)?;
self.env_insert(env, key("arguments"), Binding::new(Value::Object(a), !code.strict, false))?;
}
for v in &code.vars {
self.use_fuel()?;
if !has(self, v) {
self.env_insert(env, v.clone(), Binding::new(Value::Undefined, true, false))?;
}
}
Ok(lex)
}
/// The environment of the `let` and `const` names at the top of `code`, inside `outer`, or
/// `outer` when it has none.
fn top_env(&mut self, code: &Code, outer: EnvId) -> JsResult<EnvId> {
match code.top_scope {
Some(i) => self.block_env(code, i, outer),
None => Ok(outer),
}
}
/// A new environment for `code.scopes[i]` inside `outer`: its `let` and `const` names not yet
/// initialized and its function declarations made. Each name takes a unit of fuel.
fn block_env(&mut self, code: &Code, i: u32, outer: EnvId) -> JsResult<EnvId> {
let Some(scope) = code.scopes.get(i as usize) else { return internal("scope out of range") };
self.reserve_heap(scope_bytes(code, i))?;
let mut bindings = PropMap::default();
for (name, constant) in &scope.lets {
self.use_fuel()?;
bindings.insert(name.clone(), Binding::lexical(*constant));
}
let name_bytes = bindings.iter().map(|(k, _)| string_bytes(k.len())).sum::<usize>();
let env = self.heap.alloc_env(Env::Decl { bindings, outer: Some(outer) });
self.heap.bytes += name_bytes;
// The environment and each closure stay reachable while the next one is made.
self.temp_envs.push(env);
let mark = self.temp_roots.len();
let mut fill = || -> JsResult<()> {
for (name, fi) in &scope.funcs {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
let f = self.make_closure(fcode, env)?;
self.temp_roots.push(Value::Object(f));
self.env_insert(env, name.clone(), Binding { lexical: true, ..Binding::new(Value::Object(f), true, false) })?;
}
Ok(())
};
let r = fill();
self.temp_roots.truncate(mark);
self.temp_envs.pop();
r.map(|()| env)
}
/// An array of `values`, in order.
pub(crate) fn array_of(&mut self, values: &[Value]) -> JsResult<ObjId> {
let proto = self.intrinsics.array_proto;
let length = u32::try_from(values.len()).map_err(|_| self.throw(ErrorType::Range, "array too long"))?;
let a = self.heap.alloc_object(Object::new(Class::Array { length, length_writable: true }, Some(proto)));
for (i, v) in values.iter().enumerate() {
self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?;
}
Ok(a)
}
/// The `arguments` object (section 10.6). Its elements follow the parameters only outside
/// strict mode code in a function with plain parameters (ECMA-262 2015 section 9.2.12).
fn create_arguments(&mut self, code: &Code, env: EnvId, args: &[Value], callee: ObjId) -> JsResult<ObjId> {
let mut names = vec![None; args.len()];
if !code.strict && code.simple_params() {
let mut mapped = std::collections::HashSet::new();
for (i, p) in code.params.iter().enumerate().take(args.len()).rev() {
if mapped.insert(p.clone())
&& let Some(slot) = names.get_mut(i)
{
*slot = Some(p.clone());
}
}
}
let proto = self.intrinsics.object_proto;
let extra = crate::heap::ARG_NAME_BYTES.saturating_mul(names.len());
self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?;
let a = self.heap.alloc_object(Object::new(Class::Arguments(Box::new(ArgMap { env, names })), Some(proto)));
self.heap.bytes = self.heap.bytes.saturating_add(extra);
for (i, v) in args.iter().enumerate() {
self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?;
}
self.define(a, key("length"), Prop::Data { value: Value::Number(args.len() as f64), flags: HIDDEN })?;
if code.strict || !code.simple_params() {
let thrower = Some(self.intrinsics.throw_type_error);
for name in ["callee", "caller"] {
self.define(a, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?;
}
} else {
self.define(a, key("callee"), Prop::Data { value: Value::Object(callee), flags: HIDDEN })?;
}
crate::builtins::iterator::define_arguments_iterator(self, a)?;
Ok(a)
}
/// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host
/// function is called as the script's own code calls it, so it may wait; then the resume
/// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands
/// in for that answer is the call's result for now. A resume function that asks [`Self::again`]
/// makes that call next, in this loop, so a built-in may ask any number of times.
fn ask(&mut self, p: Pause) -> JsResult<Value> {
let mut p = p;
loop {
let Pause { host, args, keep, resume, failed } = p;
let mark = self.temp_roots.len();
self.temp_roots.push(host.clone());
self.temp_roots.extend(args.iter().cloned());
self.temp_roots.extend(keep.iter().cloned());
let was_waiting = self.waiting;
let answer = match self.func_of(&host) {
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read),
_ => self.call(&host, &Value::Undefined, &args),
};
let mut stop = Ok(());
if let Err(e) = &answer
&& let Some(failed) = failed
{
// The thrown value stays kept from collection while `failed` runs.
if let Abrupt::Throw(v) = e {
self.temp_roots.push(v.clone());
}
stop = failed(self, &keep);
}
self.temp_roots.truncate(mark);
// A stop from `failed` is not masked by a thrown error the script could catch.
if matches!(answer, Err(Abrupt::Throw(_))) {
stop?;
}
let answer = answer?;
let r = Resumption { resume, keep, failed };
if self.waiting && !was_waiting {
self.resuming = Some(r);
return Ok(answer);
}
let v = self.resume_once(r, answer)?;
match self.again.take() {
Some(next) => p = next,
None => return Ok(v),
}
}
}
/// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function, and
/// makes the host call it asks for next, if any.
fn resume(&mut self, r: Resumption, answer: Value) -> JsResult<Value> {
let v = self.resume_once(r, answer)?;
match self.again.take() {
Some(next) => self.ask(next),
None => Ok(v),
}
}
fn resume_once(&mut self, r: Resumption, answer: Value) -> JsResult<Value> {
let mark = self.temp_roots.len();
self.temp_roots.push(answer.clone());
self.temp_roots.extend(r.keep.iter().cloned());
let v = (r.resume)(self, &r.keep, answer);
self.temp_roots.truncate(mark);
if v.is_err() {
self.again = None;
}
v
}
/// Calls `f` from Rust and returns its result, running the loop again for a function written
/// in JavaScript.
pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult<Value> {
if self.reentry >= self.limits.reentry {
return Err(Abrupt::Limit(LimitKind::Reentry));
}
let saved = self.stack.len();
self.stack.push(f.clone());
self.stack.push(this.clone());
self.stack.extend(args.iter().cloned());
self.reentry += 1;
let r = self.call_rooted(f.clone(), this.clone(), args.to_vec(), saved);
self.reentry -= 1;
self.stack.truncate(saved);
r
}
/// Starts a call to `f` with no frame running, for a promise job: a native or host function
/// runs now and gives `Some` with its result, and a function written in JavaScript gets a
/// boundary frame that the caller runs, and gives `None`. A host function called here cannot
/// wait for its result, since no script code is running; a function written in JavaScript
/// runs as the script's own code does.
pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec<Value>) -> JsResult<Option<Value>> {
self.reentry += 1;
let prepared = self.prepare_call(f, this, args);
self.reentry -= 1;
match prepared? {
Prepared::Done(v) => Ok(Some(v)),
Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None),
Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None),
}
}
fn call_rooted(&mut self, f: Value, this: Value, args: Vec<Value>, saved: usize) -> JsResult<Value> {
match self.prepare_call(f, this, args)? {
Prepared::Done(v) => Ok(v),
Prepared::Closure(entry) => {
self.stack.truncate(saved);
self.enter_function(entry, None, true)?;
self.execute()
}
Prepared::Resume(r) => {
self.stack.truncate(saved);
self.enter_resumed(*r, true)?;
self.execute()
}
}
}
// ---- eval and scripts ----
/// The options for source parsed next in this run: [`Options::max_source_units`] is what
/// the run may still parse.
fn remaining_source_options(&self) -> Options {
Options { max_source_units: self.options.max_source_units.saturating_sub(self.source_units), ..self.options.clone() }
}
/// Checks that `units` more code units of source fit in what this run may still parse,
/// before the source is flattened or encoded.
pub(crate) fn check_source_units(&self, units: usize) -> Result<(), CompileError> {
crate::check_length(units, &self.remaining_source_options()).map_err(CompileError::Syntax)
}
/// Encodes `text` as UTF-16 for parsing, after checking that it fits in what this run may
/// still parse.
pub(crate) fn encode_source(&self, text: &str) -> Result<Vec<u16>, CompileError> {
crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax)
}
/// Gives `units`, source a script evaluates at run time, to the realm's code observer.
pub(crate) fn observe_code(&self, units: &[u16]) {
if let Some(f) = &self.code_observer {
f(units);
}
}
/// Parses and compiles source for eval code or a script, counting it against the source
/// limit.
pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
let writes = self.writes_mode();
self.compile_source_writes(units, strict, writes, kind)
}
/// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`.
pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
self.compile_units(units, strict, writes, kind, SuperRules::default())
}
/// [`Interp::compile_source_writes`]; `supers` says what `super` and `new.target` may do at
/// the top of the code: what they may do where a direct `eval` is called.
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, supers: SuperRules) -> Result<Rc<Code>, CompileError> {
self.source_units = self.source_units.saturating_add(units.len());
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
let program = crate::parse_utf16_with_supers(units, &options, supers).map_err(CompileError::Syntax)?;
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
compile_program(&program, &source, kind).map_err(|e| match e {
CompileFail::Syntax(s) => CompileError::Syntax(s),
CompileFail::Internal(m) => CompileError::Internal(m),
})
}
/// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the
/// source limit, with [`Self::source_tag`] as its source's tag.
pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc<Code>, crate::ModuleInfo), CompileError> {
self.source_units = self.source_units.saturating_add(units.len());
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
let options = Options { max_source_units: remaining, ..self.options.clone() };
let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?;
let writes = self.writes_mode();
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e {
CompileFail::Syntax(s) => CompileError::Syntax(s),
CompileFail::Internal(m) => CompileError::Internal(m),
})?;
Ok((code, info))
}
/// Turns a compile failure inside a running script into what it throws.
pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt {
match e {
CompileError::Syntax(s) => self.throw(ErrorType::Syntax, &s.message),
CompileError::Internal(m) => Abrupt::Internal(m),
}
}
fn direct_eval(&mut self, start: usize, args: Vec<Value>) -> JsResult<()> {
let x = args.into_iter().next().unwrap_or(Value::Undefined);
let Value::String(s) = &x else {
self.stack.truncate(start);
return self.push(x);
};
let strict = self.strict();
self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?;
self.prepare_source(s.len())?;
let units = self.flat_reserved(s)?;
self.observe_code(&units);
// The eval code may use `super` and `new.target` as the code that calls it may, and reads
// the `new.target` of the function it is in (section 18.2.1.1).
let supers = self.frame()?.code.supers;
let new_target = if supers.new_target { self.caller_new_target()? } else { None };
let writes = self.writes_mode();
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, supers).map_err(|e| self.compile_error_to_abrupt(e))?;
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
let frame = self.frame()?;
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
let (env, var_env) = if code.strict {
let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(caller_env) });
(e, e)
} else {
(caller_env, caller_var_env)
};
self.stack.truncate(start);
self.check_frame_room()?;
let env = self.instantiate_pending(&code, env, var_env, true)?;
self.push_code_frame(code, env, var_env, this, false)?;
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
let frame = self.frame_mut()?;
frame.this_in_env = this_in_env;
frame.new_target = new_target.and_then(|v| v.as_object());
Ok(())
}
/// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the
/// code counted against the heap, until its frame holds them: the scopes and functions it
/// makes can collect.
fn instantiate_pending(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
let mark = self.temp_envs.len();
self.temp_envs.push(env);
self.temp_codes.push(code.clone());
let r = self.instantiate_global(code, env, var_env, is_eval);
self.temp_codes.pop();
self.temp_envs.truncate(mark);
r
}
/// Indirect eval and scripts: runs `code` in the global environment and returns its
/// completion value.
pub(crate) fn run_global(&mut self, code: Rc<Code>, is_eval: bool) -> JsResult<Value> {
// Indirect eval runs inside an operation and counts against the re-entry limit; the
// script a realm runs does not.
let nested = usize::from(is_eval);
if is_eval && self.reentry >= self.limits.reentry {
return Err(Abrupt::Limit(LimitKind::Reentry));
}
self.enter_global(code, is_eval)?;
self.reentry += nested;
let r = self.execute();
self.reentry -= nested;
r
}
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run.
pub(crate) fn enter_global(&mut self, code: Rc<Code>, is_eval: bool) -> JsResult<()> {
// A script's `let` and `const` names are counted with its declarations, so none of them
// is declared unless all of them fit.
let top = code.top_scope.map_or(0, |i| scope_bytes(&code, i));
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(top))?;
let (scope, global) = (self.global_scope(), self.global);
let (env, var_env) = if code.strict && is_eval {
let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
(e, e)
} else {
(scope, self.global_env)
};
// The frame limit is checked before anything is declared, so a script that cannot start
// leaves the global scope as it was.
self.check_frame_room()?;
let env = self.instantiate_pending(&code, env, var_env, is_eval)?;
self.push_code_frame(code, env, var_env, Value::Object(global), true)
}
/// The environment global code runs in: the one that holds the scripts' `let` and `const`
/// names, inside the global object's.
pub(crate) fn global_scope(&self) -> EnvId {
self.global_lex
}
/// Sets [`Options::es2015`] for the next runs. The first run with it on gives the built-in
/// functions their ECMAScript 2015 `name` and `length` ([`crate::builtins::es2015_names`]).
pub(crate) fn set_es2015(&mut self, es2015: bool) {
self.options.es2015 = es2015;
}
/// Declares a script's top-level `let` and `const` names in the global scope, uninitialized
/// (ECMA-262 2015 section 15.1.8): a name another script declared with `let` or `const`, a
/// name global code declared with `var` or as a function, a non-configurable property of the
/// global object (such as the built-in `undefined`) or a `var` or function of this script that
/// another script declared with `let` or `const` is a `SyntaxError`, and nothing is declared.
/// With [`Options::es2015`], a function of this script that cannot replace a property of the
/// global object, or a `var` it cannot add, is a `TypeError`, also before anything is declared.
fn declare_global_lexical(&mut self, code: &Code, lex: EnvId) -> JsResult<()> {
let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets);
let in_lex = |interp: &Self, name: &[u16]| matches!(interp.heap.env(lex), Some(Env::Decl { bindings, .. }) if bindings.contains(name));
let global = self.global;
for (name, _) in lets {
self.use_fuel()?;
let restricted = self.get_own_property(global, name)?.is_some_and(|p| !p.configurable());
if in_lex(self, name) || restricted || self.global_vars.contains(name) {
let ident = String::from_utf16_lossy(name);
return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'")));
}
}
for name in code.vars.iter().chain(code.fun_decls.iter().map(|(k, _)| k)) {
if in_lex(self, name) {
let ident = String::from_utf16_lossy(name);
return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'")));
}
}
if self.options.es2015 {
self.check_global_functions(code)?;
self.check_global_vars(code)?;
}
// The room for the names and the declarations is checked before any name is added, so a
// run that stops at the heap limit here adds no name to the global scope.
let names = lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len())));
self.reserve_heap(names.saturating_add(declaration_bytes(code)))?;
for (name, constant) in lets {
let b = Binding::lexical(*constant);
self.env_insert(lex, name.clone(), b)?;
}
Ok(())
}
/// The test `declare` makes for a function in an object environment, on the global object's
/// own property, for every function `code` declares before any is (ECMA-262 2015 sections
/// 15.1.8, step 8, and 18.2.1.2, step 8, CanDeclareGlobalFunction): a function that cannot
/// replace its property is a `TypeError`.
fn check_global_functions(&mut self, code: &Code) -> JsResult<()> {
let global = self.global;
for (name, _) in &code.fun_decls {
let replaceable = match self.get_own_property(global, name)? {
None => self.object(global)?.extensible,
Some(p) if p.configurable() => true,
Some(Prop::Data { flags, .. }) => flags & (WRITABLE | ENUMERABLE) == WRITABLE | ENUMERABLE,
Some(_) => false,
};
if !replaceable {
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("cannot declare function {ident}")));
}
}
Ok(())
}
/// The test for every `var` name `code` declares on the global object, made before any is
/// declared (ECMA-262 2015 sections 15.1.8, step 10, and 18.2.1.2, step 8,
/// CanDeclareGlobalVar): a name the global object does not have as its own property needs an
/// extensible global object, or it is a `TypeError`.
fn check_global_vars(&mut self, code: &Code) -> JsResult<()> {
let global = self.global;
if self.object(global)?.extensible {
return Ok(());
}
for name in &code.vars {
self.use_fuel()?;
if self.get_own_property(global, name)?.is_none() {
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("cannot declare variable {ident}")));
}
}
Ok(())
}
/// A [`LimitKind::Frames`] error when no other frame fits under the frame limit.
fn check_frame_room(&self) -> JsResult<()> {
if self.frames.len() - self.pending_module_frames >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
Ok(())
}
fn push_code_frame(&mut self, code: Rc<Code>, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> {
self.check_frame_room()?;
let base = self.stack.len();
self.frames.push(Frame {
code,
pc: 0,
base,
env,
var_env,
env_depth: 0,
this,
this_in_env: false,
strict_class: false,
callee: None,
construct: None,
new_target: None,
this_env: None,
completion: Value::Undefined,
boundary,
generator: None,
chained: false,
pending_module: false,
});
Ok(())
}
/// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4,
/// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global
/// scope holds its variables and functions, and one inside that its `let` and `const` names,
/// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary
/// roots for the caller to remove.
pub(crate) fn instantiate_module(&mut self, code: &Rc<Code>) -> JsResult<(EnvId, EnvId)> {
// The code itself was counted when the module was loaded ([`Self::hold_module_code`]).
self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?;
let scope = self.global_lex;
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
self.temp_envs.push(env);
let lex = self.instantiate_global(code, env, env, true)?;
self.temp_envs.push(lex);
Ok((lex, env))
}
/// Adds `binding` (an import) to the module environment `env`, which must not have `name`.
pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> {
self.use_fuel()?;
// The binding's value (a namespace object) stays reachable while room is made.
self.temp_roots.push(binding.value.clone());
let reserved = self.reserve_heap(binding_bytes(name.len()));
self.temp_roots.pop();
reserved?;
self.env_insert(env, name, binding)
}
/// The environment that holds `name` of a module whose code runs in `lex` inside `env`.
pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option<EnvId> {
[lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name)))
}
/// A module namespace object for the exports `exports`, each `(name, binding)` with the
/// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit
/// order and distinct.
pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult<ObjId> {
let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::<usize>();
let bindings = PROP_BYTES.saturating_mul(exports.len());
let tag = self.well_known(|symbols| &symbols.to_string_tag);
let tagged = if tag.is_some() { PROP_BYTES.saturating_add(string_bytes(6)) } else { 0 };
let extra = bindings.saturating_add(names).saturating_add(tagged);
self.reserve_heap(OBJECT_BYTES.saturating_add(bindings).saturating_add(extra))?;
let mut object = Object::new(Class::ModuleNamespace(Box::default()), None);
if let Some(tag) = tag {
object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 });
}
object.extensible = false;
for (name, _) in &exports {
self.use_fuel()?;
let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone());
object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE });
}
object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports }));
let namespace = self.heap.alloc_object(object);
self.heap.bytes = self.heap.bytes.saturating_add(extra);
Ok(namespace)
}
/// Pushes the frames of a run of modules: `modules` in the order they run, each with its code,
/// the environment it runs in and the outer one. The last is the boundary frame, pushed first;
/// each of the others is pushed above the one that runs after it, so the first to run is on
/// top.
pub(crate) fn push_module_frames(&mut self, modules: &[(Rc<Code>, EnvId, EnvId)]) -> JsResult<()> {
for (i, (code, env, var_env)) in modules.iter().enumerate().rev() {
let last = i + 1 == modules.len();
self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?;
if let Some(frame) = self.frames.last_mut() {
frame.chained = !last;
frame.pending_module = true;
}
self.pending_module_frames += 1;
}
Ok(())
}
/// Ends module linking: drops the temporary roots from `mark` on.
pub(crate) fn drop_temp_envs(&mut self, mark: usize) {
self.temp_envs.truncate(mark);
}
pub(crate) fn temp_envs_mark(&self) -> usize {
self.temp_envs.len()
}
/// Counts a loaded module's code against the heap once, when the module is loaded, and keeps
/// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules
/// load counts it too.
pub(crate) fn hold_module_code(&mut self, code: &Rc<Code>) -> JsResult<()> {
self.charge_code(code, 0)?;
self.temp_codes.push(code.clone());
Ok(())
}
pub(crate) fn temp_codes_mark(&self) -> usize {
self.temp_codes.len()
}
/// Ends module linking: drops the modules' code held from `mark` on.
pub(crate) fn drop_temp_codes(&mut self, mark: usize) {
self.temp_codes.truncate(mark);
}
/// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it.
pub(crate) fn hold(&mut self, v: Value) {
self.temp_roots.push(v);
}
pub(crate) fn temp_roots_mark(&self) -> usize {
self.temp_roots.len()
}
pub(crate) fn drop_temp_roots(&mut self, mark: usize) {
self.temp_roots.truncate(mark);
}
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
///
/// Gives the environment the code runs in: `env`, or with [`Options::es2015`] eval code's own
/// environment of its `let` and `const` names. A script's `let` and `const` names go in the
/// global scope ([`Self::declare_global_lexical`]).
fn instantiate_global(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
// Strict eval code's own environment is in no frame yet, so it is a root while the
// declarations reserve heap.
let mark = self.temp_envs.len();
self.temp_envs.extend([env, var_env]);
let r = self.instantiate_global_rooted(code, env, var_env, is_eval);
self.temp_envs.truncate(mark);
r
}
/// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`].
fn instantiate_global_rooted(&mut self, code: &Rc<Code>, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<EnvId> {
let configurable = if is_eval { CONFIGURABLE } else { 0 };
if is_eval && !code.strict && self.options.es2015 {
self.check_eval_vars(code, env, var_env)?;
if var_env == self.global_env {
self.check_global_functions(code)?;
self.check_global_vars(code)?;
}
}
let global_lets = !is_eval && env == self.global_lex;
let lex = match code.top_scope {
_ if global_lets => {
self.declare_global_lexical(code, env)?;
env
}
Some(i) => self.block_env(code, i, env)?,
None => env,
};
// The caller reserved room for the declarations before the `let` and `const` names took
// some of it (a script's names in the global scope were checked with the declarations
// before they were added). Their environment stays reachable if the check collects.
self.temp_envs.push(lex);
let r = self.reserve_heap(declaration_bytes(code)).and_then(|()| self.declare_global_functions_and_vars(code, lex, var_env, configurable));
self.temp_envs.pop();
if r.is_err() && global_lets {
// A script that stops before it runs, at a limit, leaves none of its `let` and `const`
// names behind, so running it again in the same realm does not redeclare them.
let lets = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[][..], |s| &s.lets);
if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(lex) {
for (name, _) in lets {
bindings.remove(name);
}
}
}
r.map(|()| lex)
}
/// Declares the functions and variables of global or eval code for
/// [`Self::instantiate_global_rooted`], each taking a unit of fuel.
fn declare_global_functions_and_vars(&mut self, code: &Rc<Code>, lex: EnvId, var_env: EnvId, configurable: u8) -> JsResult<()> {
// Functions close over the code's own environment with ES2015's scoping, and over its
// variable environment otherwise (ECMA-262 5.1 section 13). When that is the global
// object's, they close over the global scope inside it, which also holds the scripts'
// `let` and `const` names, as global code's functions do in either language.
let on_global = var_env == self.global_env;
let scope = if self.options.es2015 {
lex
} else if on_global {
self.global_lex
} else {
var_env
};
for (name, fi) in &code.fun_decls {
self.use_fuel()?;
let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") };
let f = self.make_closure(fcode, scope)?;
self.declare(var_env, name, Some(Value::Object(f)), configurable)?;
self.note_global_var(on_global, name)?;
}
for v in &code.vars {
self.use_fuel()?;
self.declare(var_env, v, None, configurable)?;
self.note_global_var(on_global, v)?;
}
Ok(())
}
/// Adds `name`, which global code just declared, to [`Self::global_vars`] when `on_global`
/// and the global object has it as an own property. A `var` that an inherited property
/// satisfied, without one, is not added.
fn note_global_var(&mut self, on_global: bool, name: &Key) -> JsResult<()> {
if on_global && self.get_own_property(self.global, name)?.is_some() {
self.global_vars.insert(name.clone());
}
Ok(())
}
/// A `var` or function that eval code outside strict mode code declares must not take the name
/// of a `let`, a `const` or a block's function from the code's environment `env` out to the
/// variable environment it declares them in (ECMA-262 2015 section 18.2.1.2, step 5), nor, in
/// a default parameter's value, the name of a parameter (ECMA-262 2017 section 18.2.1.3): that
/// is a `SyntaxError`, and nothing is declared. A `catch` parameter does not count (Annex
/// B.3.5). Each name and each environment passed takes a unit of fuel.
fn check_eval_vars(&mut self, code: &Code, env: EnvId, var_env: EnvId) -> JsResult<()> {
for name in code.vars.iter().chain(code.fun_decls.iter().map(|(k, _)| k)) {
self.use_fuel()?;
let mut cur = Some(env);
while let Some(e) = cur {
self.use_fuel()?;
cur = match self.heap.env(e) {
Some(Env::Decl { bindings, outer }) => {
if bindings.get(name).is_some_and(|b| b.lexical) {
let ident = String::from_utf16_lossy(name);
return Err(self.throw(ErrorType::Syntax, &format!("redeclaration of '{ident}'")));
}
*outer
}
Some(Env::Obj { outer, .. }) => *outer,
None => return internal("environment out of range"),
}
.filter(|_| e != var_env);
}
}
Ok(())
}
/// Declares `name` in a variable environment, with `value` for a function declaration.
fn declare(&mut self, env: EnvId, name: &Key, value: Option<Value>, configurable: u8) -> JsResult<()> {
match self.heap.env(env) {
Some(Env::Decl { bindings, .. }) => {
let exists = bindings.contains(name);
match value {
Some(v) => self.env_insert(env, name.clone(), Binding::new(v, true, configurable != 0)),
None if !exists => self.env_insert(env, name.clone(), Binding::new(Value::Undefined, true, configurable != 0)),
None => Ok(()),
}
}
Some(Env::Obj { object, .. }) => {
let object = *object;
// ECMA-262 2015 section 8.1.1.4.17 reads the object's own property, so a name it
// only inherits gets a new own property; section 10.5 of the 5.1 edition reads the
// inherited one as well.
let declared = if self.options.es2015 { self.get_own_property(object, name)?.is_some() } else { self.has_property(object, name)? };
let flags = WRITABLE | ENUMERABLE | configurable;
match value {
None if declared => Ok(()),
None => self.define(object, name.clone(), Prop::Data { value: Value::Undefined, flags }),
Some(v) => {
// ECMA-262 2015 section 8.1.1.4.18 reads the object's own property, and
// section 10.5 of the 5.1 edition the property it inherits as well.
let existing = if self.options.es2015 { self.get_own_property(object, name)? } else { self.find_property(object, name)? };
// A new own property needs an extensible object (ECMA-262 2015 section
// 8.1.1.4.16; section 8.12.9 of the 5.1 edition, step 3).
let defines = existing.as_ref().is_none_or(Prop::configurable);
if defines && !self.object(object)?.extensible && self.get_own_property(object, name)?.is_none() {
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("cannot declare function {ident}")));
}
match existing {
None => self.define(object, name.clone(), Prop::Data { value: v, flags }),
Some(p) if p.configurable() => self.define(object, name.clone(), Prop::Data { value: v, flags }),
Some(Prop::Data { flags: f, .. }) if f & (WRITABLE | ENUMERABLE) == WRITABLE | ENUMERABLE => {
self.put(object, name.clone(), v, true)
}
Some(_) => {
let ident = String::from_utf16_lossy(name);
Err(self.type_error(&format!("cannot declare function {ident}")))
}
}
}
}
}
None => internal("environment out of range"),
}
}
// ---- conversions ----
pub(crate) fn type_of(&self, v: &Value) -> &'static str {
match v {
Value::Undefined => "undefined",
Value::Null => "object",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Symbol(_) => "symbol",
Value::Object(_) if self.options.e4x && self.is_xml(v) => "xml",
Value::Object(_) if self.is_callable(v) => "function",
Value::Object(_) => "object",
}
}
/// ToPrimitive (section 9.1) through [[DefaultValue]] (section 8.12.8). In a realm with
/// [`crate::Options::es2015`], an object's `@@toPrimitive` method is called first when it
/// has one (ECMA-262 11th edition, section 7.1.1).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_primitive(&mut self, v: &Value, hint: Hint) -> JsResult<Value> {
let Value::Object(o) = v else { return Ok(v.clone()) };
if let Some(r) = self.exotic_to_primitive(*o, v, hint)? {
return Ok(r);
}
self.ordinary_to_primitive(*o, v, hint)
}
/// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the
/// `@@toPrimitive` method.
pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult<Value> {
// Without a hint, a Date object converts as with the String hint. In a realm with
// `Options::es2015`, `Date.prototype[@@toPrimitive]` picks that order for a Date instead,
// and OrdinaryToPrimitive treats a missing hint as the Number hint (ECMA-262 11th edition,
// sections 7.1.1.1 and 20.4.4.45).
let date = hint == Hint::Default && !self.options.es2015 && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_)));
let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] };
for name in order {
let f = self.get_from(o, &key(name), v)?;
if self.is_callable(&f) {
let r = self.call(&f, v, &[])?;
if !matches!(r, Value::Object(_)) {
return Ok(r);
}
}
}
Err(self.type_error("cannot convert the object to a primitive value"))
}
/// ToNumber (section 9.3). In a realm with [`crate::Options::es2015`], a string may also be a
/// `0b` or `0o` literal (ECMA-262 11th edition, section 7.1.3.1).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_number(&mut self, v: &Value) -> JsResult<f64> {
Ok(match v {
Value::Undefined => f64::NAN,
Value::Null => 0.0,
Value::Bool(b) => f64::from(u8::from(*b)),
Value::Number(n) => *n,
Value::String(s) => string_to_number(&flat_charged(self, s)?, self.options.es2015),
Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")),
Value::Object(_) => {
let p = self.to_primitive(v, Hint::Number)?;
return self.to_number(&p);
}
})
}
/// ToString applied to a primitive, with a Symbol written as `Symbol(description)` for
/// messages, its description cut as [`crate::symbol::Sym::message_name`] cuts it;
/// [`Self::to_str`] refuses a Symbol.
pub(crate) fn primitive_to_str(&mut self, v: &Value) -> Str {
match v {
Value::Undefined => Str::from("undefined"),
Value::Null => Str::from("null"),
Value::Bool(b) => Str::from(if *b { "true" } else { "false" }),
Value::Number(n) => {
let s = number_to_str(*n);
self.heap.bytes += string_bytes(s.len());
s
}
Value::String(s) => s.clone(),
Value::Object(_) => Str::from("[object]"),
Value::Symbol(s) => {
let (units, _) = s.message_name();
self.heap.bytes += string_bytes(units.len());
Str::from_units(units)
}
}
}
/// ToString (section 9.8); a Symbol throws a `TypeError` (ECMA-262 11th edition, section
/// 7.1.17).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_str(&mut self, v: &Value) -> JsResult<Str> {
let p = self.to_primitive(v, Hint::String)?;
if matches!(p, Value::Symbol(_)) {
return Err(self.type_error("cannot convert a Symbol value to a string"));
}
Ok(self.primitive_to_str(&p))
}
/// A property name from a value (ToString, with a short way for array indices).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_key(&mut self, v: &Value) -> JsResult<Key> {
match v {
Value::String(s) => self.flat_reserved(s),
Value::Number(n) if *n >= 0.0 && *n < 4_294_967_295.0 && n.fract() == 0.0 => Ok(index_key(*n as u32)),
_ => {
let s = self.to_str(v)?;
self.flat_reserved(&s)
}
}
}
/// Runs `f` with the property name [`Self::to_key`] makes from `v`. A name converted from a
/// value that is not a string is kept reachable while `f` runs, so a collection that a getter
/// or setter starts still counts its units.
pub(crate) fn with_key<T>(&mut self, v: &Value, f: impl FnOnce(&mut Self, Key) -> JsResult<T>) -> JsResult<T> {
let name = self.to_key(v)?;
if matches!(v, Value::String(_)) {
return f(self, name);
}
let root = Value::String(Str::from_rc(name.clone()));
self.rooted(&[root], |i| f(i, name))
}
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that
/// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays
/// rooted while the copy is reserved; everything else the caller still needs must be
/// reachable from the roots.
fn flat_reserved(&mut self, s: &Str) -> JsResult<Key> {
if s.is_rope() {
let bytes = string_bytes(s.len());
self.rooted(&[Value::String(s.clone())], |i| i.reserve_heap(bytes))?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
}
Ok(s.flat())
}
/// ToObject (section 9.9).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_object(&mut self, v: &Value) -> JsResult<ObjId> {
let (class, proto) = match v {
Value::Object(o) => return Ok(*o),
Value::Undefined | Value::Null => return Err(self.type_error("cannot convert undefined or null to an object")),
Value::Bool(b) => (Class::Boolean(*b), self.intrinsics.boolean_proto),
Value::Number(n) => (Class::Number(*n), self.intrinsics.number_proto),
Value::String(s) => (Class::String(s.clone()), self.intrinsics.string_proto),
Value::Symbol(s) => (Class::Symbol(s.clone()), self.primitive_proto(v, &[])?),
};
Ok(self.heap.alloc_object(Object::new(class, Some(proto))))
}
/// Concatenates two strings, ending the run with the heap limit when the result could not
/// be flattened within it.
pub(crate) fn concat(&mut self, a: &Str, b: &Str) -> JsResult<Str> {
let len = a.len() + b.len();
if len > self.limits.heap_bytes / 4 {
return Err(Abrupt::Limit(LimitKind::Heap));
}
self.heap.bytes += ROPE_BYTES;
Ok(Str::concat(a, b))
}
// ---- operators ----
fn op_unary(&mut self, op: Op) -> JsResult<()> {
let v = self.peek(0)?;
if self.unit_values.is_some()
&& let Some(r) = crate::unit_value::unary(self, op, &v)?
{
return self.replace(1, r);
}
let r = match op {
Op::Neg => Value::Number(-self.to_number(&v)?),
Op::Plus | Op::ToNumber => Value::Number(self.to_number(&v)?),
Op::BitNot => Value::Number(f64::from(!to_int32(self.to_number(&v)?))),
Op::Not => Value::Bool(!v.truthy()),
Op::Typeof => Value::str(self.type_of(&v)),
_ => return internal("not a unary operator"),
};
self.replace(1, r)
}
fn op_binary(&mut self, op: BinaryOp) -> JsResult<()> {
let b = self.peek(0)?;
let a = self.peek(1)?;
let r = self.binary(op, &a, &b)?;
self.replace(2, r)
}
pub(crate) fn binary(&mut self, op: BinaryOp, a: &Value, b: &Value) -> JsResult<Value> {
if self.unit_values.is_some()
&& (matches!(a, Value::Object(_)) || matches!(b, Value::Object(_)))
&& let Some(r) = crate::unit_value::binary(self, op, a, b)?
{
return Ok(r);
}
let num = |interp: &mut Self, f: fn(f64, f64) -> f64| -> JsResult<Value> {
let x = interp.to_number(a)?;
let y = interp.to_number(b)?;
Ok(Value::Number(f(x, y)))
};
let int = |interp: &mut Self, f: fn(i32, i32) -> i32| -> JsResult<Value> {
let x = to_int32(interp.to_number(a)?);
let y = to_int32(interp.to_number(b)?);
Ok(Value::Number(f64::from(f(x, y))))
};
match op {
BinaryOp::Add => self.add(a, b),
BinaryOp::Sub => num(self, |x, y| x - y),
BinaryOp::Mul => num(self, |x, y| x * y),
BinaryOp::Div => num(self, |x, y| x / y),
BinaryOp::Mod => num(self, |x, y| x % y),
BinaryOp::Shl => int(self, |x, y| x.wrapping_shl((y & 31) as u32)),
BinaryOp::Shr => int(self, |x, y| x >> (y & 31)),
BinaryOp::UShr => {
let x = to_uint32(self.to_number(a)?);
let y = to_uint32(self.to_number(b)?);
Ok(Value::Number(f64::from(x >> (y & 31))))
}
BinaryOp::BitAnd => int(self, |x, y| x & y),
BinaryOp::BitOr => int(self, |x, y| x | y),
BinaryOp::BitXor => int(self, |x, y| x ^ y),
BinaryOp::Lt => Ok(Value::Bool(self.less_than(a, b, true)? == Some(true))),
BinaryOp::Gt => Ok(Value::Bool(self.less_than(b, a, false)? == Some(true))),
BinaryOp::LtEq => Ok(Value::Bool(self.less_than(b, a, false)? == Some(false))),
BinaryOp::GtEq => Ok(Value::Bool(self.less_than(a, b, true)? == Some(false))),
BinaryOp::Eq => Ok(Value::Bool(self.loose_eq(a, b)?)),
BinaryOp::NotEq => Ok(Value::Bool(!self.loose_eq(a, b)?)),
BinaryOp::StrictEq => Ok(Value::Bool(strict_eq(a, b))),
BinaryOp::StrictNotEq => Ok(Value::Bool(!strict_eq(a, b))),
BinaryOp::Instanceof => self.instance_of(a, b).map(Value::Bool),
BinaryOp::In => {
if self.options.e4x && self.is_xml(b) {
return self.xml_has(b, a).map(Value::Bool);
}
let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) };
let k = self.to_prop_key(a)?;
self.has_pk_indexed(*o, &k).map(Value::Bool)
}
}
}
/// The addition operator (section 11.6.1).
fn add(&mut self, a: &Value, b: &Value) -> JsResult<Value> {
if let (Value::Number(x), Value::Number(y)) = (a, b) {
return Ok(Value::Number(x + y));
}
if self.options.e4x && self.is_xml(a) && self.is_xml(b) {
return self.xml_concat(a, b);
}
let pa = self.to_primitive(a, Hint::Default)?;
// The right side's conversion can run script, so the left side's result stays counted.
let pb = self.rooted(std::slice::from_ref(&pa), |i| i.to_primitive(b, Hint::Default))?;
if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) {
// Both are primitives, so this converts them without running script code; a Symbol
// throws.
let sa = self.to_str(&pa)?;
let sb = self.to_str(&pb)?;
return self.concat(&sa, &sb).map(Value::String);
}
Ok(Value::Number(self.to_number(&pa)? + self.to_number(&pb)?))
}
/// The abstract relational comparison `x < y` (section 11.8.5): `None` when either side is
/// NaN.
fn less_than(&mut self, x: &Value, y: &Value, left_first: bool) -> JsResult<Option<bool>> {
// The second conversion can run script, so the first one's result stays counted.
let (px, py) = if left_first {
let px = self.to_primitive(x, Hint::Number)?;
let py = self.rooted(std::slice::from_ref(&px), |i| i.to_primitive(y, Hint::Number))?;
(px, py)
} else {
let py = self.to_primitive(y, Hint::Number)?;
(self.rooted(std::slice::from_ref(&py), |i| i.to_primitive(x, Hint::Number))?, py)
};
if let (Value::String(a), Value::String(b)) = (&px, &py) {
// Both stay rooted, so the first copy is still counted while the second is made.
return self.rooted(&[px.clone(), py.clone()], |i| {
let (a, b) = (flat_charged(i, a)?, flat_charged(i, b)?);
Ok(Some(*a < *b))
});
}
let nx = self.to_number(&px)?;
let ny = self.to_number(&py)?;
if nx.is_nan() || ny.is_nan() {
return Ok(None);
}
Ok(Some(nx < ny))
}
/// The abstract equality comparison (section 11.9.3).
pub(crate) fn loose_eq(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
if self.options.e4x
&& let Some(r) = self.xml_loose_eq(a, b)?
{
return Ok(r);
}
let (mut x, mut y) = (a.clone(), b.clone());
loop {
match (&x, &y) {
(Value::Undefined | Value::Null, Value::Undefined | Value::Null) => return Ok(true),
(Value::Number(_), Value::Number(_))
| (Value::String(_), Value::String(_))
| (Value::Bool(_), Value::Bool(_))
| (Value::Symbol(_), Value::Symbol(_))
| (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)),
(Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => {
return Ok(*n == string_to_number(&flat_charged(self, s)?, self.options.es2015));
}
(Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))),
(_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))),
(Value::Number(_) | Value::String(_) | Value::Symbol(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?,
(Value::Object(_), Value::Number(_) | Value::String(_) | Value::Symbol(_)) => x = self.to_primitive(&x, Hint::Default)?,
_ => return Ok(false),
}
}
}
/// `instanceof` (sections 11.8.6 and 15.3.5.3). In a realm with [`crate::Options::es2015`],
/// the right side's `@@hasInstance` method answers when it has one (ECMA-262 11th edition,
/// section 12.10.4).
fn instance_of(&mut self, v: &Value, f: &Value) -> JsResult<bool> {
if let Some(r) = self.has_instance_hook(v, f)? {
return Ok(r);
}
if !self.is_callable(f) {
return Err(self.type_error("the right side of 'instanceof' is not a function"));
}
self.ordinary_has_instance(v, f)
}
/// OrdinaryHasInstance (ECMA-262 11th edition, section 7.3.21): `false` when `f` is not a
/// function.
pub(crate) fn ordinary_has_instance(&mut self, v: &Value, f: &Value) -> JsResult<bool> {
let Some(mut fid) = f.as_object().filter(|_| self.is_callable(f)) else { return Ok(false) };
// A bound function answers for its target (section 15.3.4.5.3), or the target's own
// `@@hasInstance` method does.
while let Some(Func::Bound { target, .. }) = self.func_of(&Value::Object(fid)) {
self.use_fuel()?;
fid = target;
if let Some(r) = self.bound_target_hook(v, fid)? {
return Ok(r);
}
}
let f = &Value::Object(fid);
let Value::Object(mut o) = v.clone() else { return Ok(false) };
let Value::Object(proto) = self.get_from(fid, &key("prototype"), f)? else {
return Err(self.type_error("the function's prototype is not an object"));
};
let mut steps = 0usize;
while let Some(p) = self.object(o)?.proto {
if p == proto {
return Ok(true);
}
o = p;
steps += 1;
if steps > 1_000_000 {
return internal("prototype chain too long");
}
}
Ok(false)
}
// ---- host values ----
pub(crate) fn to_js_value(&self, v: &Value) -> crate::JsValue {
match v {
Value::Undefined => crate::JsValue::Undefined,
Value::Null => crate::JsValue::Null,
Value::Bool(b) => crate::JsValue::Bool(*b),
Value::Number(n) => crate::JsValue::Number(*n),
Value::String(s) => crate::JsValue::String(s.to_rust_string()),
Value::Object(o) => crate::JsValue::Object(self.heap.object(*o).map_or("Object", |o| o.class.name()).to_string()),
Value::Symbol(s) => crate::JsValue::Symbol(s.description().map(Str::to_rust_string)),
}
}
/// A host value as a JavaScript value. A string or a Symbol's description is charged to the
/// heap before it is built, and one that does not fit in it ends the run with the heap limit.
/// A Symbol in a realm without [`crate::Options::es2015`] throws a `TypeError`. Everything the
/// caller still needs must be reachable from the roots.
#[allow(clippy::wrong_self_convention)]
pub(crate) fn from_js_value(&mut self, v: crate::JsValue) -> JsResult<Value> {
Ok(match v {
crate::JsValue::Undefined => Value::Undefined,
crate::JsValue::Null => Value::Null,
crate::JsValue::Bool(b) => Value::Bool(b),
crate::JsValue::Number(n) => Value::Number(n),
crate::JsValue::String(s) => {
let bytes = string_bytes(s.encode_utf16().count());
self.reserve_heap(bytes)?;
self.heap.bytes += bytes;
Value::str(&s)
}
crate::JsValue::Object(_) => Value::Object(self.new_object()),
crate::JsValue::Symbol(_) if !self.options.es2015 => {
return Err(self.type_error("a host function returned a Symbol in a realm without Symbol"));
}
crate::JsValue::Symbol(description) => {
let bytes = crate::heap::SYMBOL_BYTES + description.as_ref().map_or(0, |d| string_bytes(d.encode_utf16().count()));
self.reserve_heap(bytes)?;
self.heap.bytes += bytes;
let description = description.map(|d| Str::from_units(d.encode_utf16().collect()));
Value::Symbol(crate::symbol::Sym::new(description, false))
}
})
}
/// A description of a thrown value that runs no JavaScript: `Name: message` for an error,
/// the text of a primitive.
pub(crate) fn describe(&mut self, v: &Value) -> String {
self.describe_prefix(v, usize::MAX)
}
/// [`Interp::describe`] with each string it reads cut to its first `max_units` code units
/// before it is copied.
pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String {
let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) };
let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) {
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)),
_ => None,
};
match (data(self, "name"), data(self, "message")) {
(Some(n), Some(m)) if !m.is_empty() => format!("{n}: {m}"),
(Some(n), _) => n,
(None, Some(m)) => m,
(None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())),
}
}
/// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read
/// along its strings without copying them.
fn describe_hash(&self, o: ObjId) -> u64 {
let data = |k: &str| match self.find_property(o, &key(k)) {
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s),
_ => None,
};
let mut h = DescriptionHash::default();
match (data("name"), data("message")) {
(Some(n), Some(m)) if m.len() != 0 => {
n.for_each_chunk(|c| h.units(c));
h.text(": ");
m.for_each_chunk(|c| h.units(c));
}
(Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)),
(None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))),
}
h.finish()
}
}
/// A compile failure, before it becomes an exception or a run error.
pub(crate) enum CompileError {
Syntax(crate::SyntaxError),
Internal(String),
}
/// A property descriptor (section 8.10): each field is `None` when it is absent. `get` and `set`
/// are `Some(None)` when present as `undefined`.
#[derive(Clone, Default, Debug)]
pub(crate) struct Desc {
pub(crate) value: Option<Value>,
pub(crate) get: Option<Option<ObjId>>,
pub(crate) set: Option<Option<ObjId>>,
pub(crate) writable: Option<bool>,
pub(crate) enumerable: Option<bool>,
pub(crate) configurable: Option<bool>,
}
impl Desc {
/// A data descriptor with every attribute given.
pub(crate) fn data(value: Value, flags: u8) -> Self {
Desc {
value: Some(value),
writable: Some(flags & WRITABLE != 0),
enumerable: Some(flags & ENUMERABLE != 0),
configurable: Some(flags & CONFIGURABLE != 0),
..Desc::default()
}
}
pub(crate) fn is_accessor(&self) -> bool {
self.get.is_some() || self.set.is_some()
}
pub(crate) fn is_data(&self) -> bool {
self.value.is_some() || self.writable.is_some()
}
/// The attribute flags the descriptor gives, each absent one taken from `default`.
pub(crate) fn flags_or(&self, default: u8) -> u8 {
let pick = |field: Option<bool>, bit: u8| match field {
Some(true) => bit,
Some(false) => 0,
None => default & bit,
};
pick(self.writable, WRITABLE) | pick(self.enumerable, ENUMERABLE) | pick(self.configurable, CONFIGURABLE)
}
}
/// SameValue (section 9.12).
pub(crate) fn same_value(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) => (x.is_nan() && y.is_nan()) || (x == y && x.is_sign_negative() == y.is_sign_negative()),
_ => strict_eq(a, b),
}
}
/// Steps 5 to 12 of [[DefineOwnProperty]] (section 8.12.9) for an existing property: the
/// property after `desc` is applied, or `None` when the change is not allowed.
pub(crate) fn merge_desc(current: &Prop, desc: &Desc) -> Option<Prop> {
let flags = current.flags();
let configurable = flags & CONFIGURABLE != 0;
if !configurable {
if desc.configurable == Some(true) {
return None;
}
if desc.enumerable.is_some_and(|e| e != (flags & ENUMERABLE != 0)) {
return None;
}
}
let attrs = |base: u8, writable_bit: bool| {
let f = desc.flags_or(base);
if writable_bit { f } else { f & !WRITABLE }
};
match current {
Prop::Data { .. } if desc.is_accessor() => {
if !configurable {
return None;
}
Some(Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: attrs(flags & !WRITABLE, false) })
}
Prop::Accessor { .. } if desc.is_data() => {
if !configurable {
return None;
}
Some(Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags: attrs(flags & !WRITABLE, true) })
}
Prop::Data { value, .. } => {
if !configurable && flags & WRITABLE == 0 {
if desc.writable == Some(true) {
return None;
}
if desc.value.as_ref().is_some_and(|v| !same_value(v, value)) {
return None;
}
}
Some(Prop::Data { value: desc.value.clone().unwrap_or_else(|| value.clone()), flags: attrs(flags, true) })
}
Prop::Accessor { get, set, .. } => {
if !configurable && (desc.get.is_some_and(|g| g != *get) || desc.set.is_some_and(|s| s != *set)) {
return None;
}
Some(Prop::Accessor { get: desc.get.unwrap_or(*get), set: desc.set.unwrap_or(*set), flags: attrs(flags, false) })
}
}
}
/// The strict equality comparison (section 11.9.6).
pub(crate) fn strict_eq(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
(Value::Number(x), Value::Number(y)) => x == y,
(Value::String(x), Value::String(y)) => x == y,
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Object(x), Value::Object(y)) => x == y,
(Value::Symbol(x), Value::Symbol(y)) => x == y,
_ => false,
}
}