Skip to main content

quickjs/
interp.rs

1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::{OpFormat, Opcode};
22use js_gc::{Gc, Heap};
23
24use crate::object::{
25    Callable, ClosureEnv, CompiledCode, JsObject, NativeFn, ObjectKind, Property, array_index,
26    lookup,
27};
28use crate::value::{Cell, Value, number_to_string};
29
30/// Why execution stopped.
31#[derive(Debug, Clone)]
32pub enum Signal {
33    /// A JavaScript exception carrying the thrown value.
34    Throw(Value),
35    /// The runtime ran out of memory.
36    OutOfMemory,
37}
38
39/// What an execution step produced.
40pub type JsResult<T> = std::result::Result<T, Signal>;
41
42/// The result of one instruction.
43enum Step {
44    /// Keep executing the current frame.
45    Continue,
46    /// The current frame returned this value.
47    Return(Value),
48}
49
50/// Everything one JavaScript realm owns.
51///
52/// A realm is the set of objects a script can reach without naming them: the global
53/// object, the prototype chain roots, and the global binding cells.
54pub struct Realm {
55    /// The global object.
56    pub global: Gc<JsObject>,
57    /// `Object.prototype`.
58    pub object_proto: Gc<JsObject>,
59    /// `Function.prototype`, which is itself callable.
60    pub function_proto: Gc<JsObject>,
61    /// `Array.prototype`.
62    pub array_proto: Gc<JsObject>,
63    /// Reference cells for globals declared by the script.
64    ///
65    /// A declared global is read with `get_var` (by name) but written with
66    /// `put_var_ref` (through the cell), so the cell is what makes a function
67    /// declaration and its uses agree on one binding.
68    pub globals: BTreeMap<String, Gc<Cell>>,
69    /// Names of the globals that came from a *declaration*, which are
70    /// non-configurable properties of the global object.
71    pub declared: Vec<String>,
72    /// Names among the lexical globals that are `const`.
73    ///
74    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
75    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
76    /// path does not carry, so a store through it would look like a plain `let`. The
77    /// realm records it once, at declaration, and answers for every reader.
78    pub lexical_consts: BTreeSet<String>,
79    /// The error constructors by class name, so a runtime error can throw a real
80    /// `TypeError` instance rather than a look-alike object.
81    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
82    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
83    pub string_proto: Option<Gc<JsObject>>,
84    /// `Number.prototype`.
85    pub number_proto: Option<Gc<JsObject>>,
86    /// `Boolean.prototype`.
87    pub boolean_proto: Option<Gc<JsObject>>,
88    /// `Error.prototype`, the prototype of every error instance.
89    pub error_proto: Gc<JsObject>,
90}
91
92/// One activation record.
93struct Frame {
94    /// The bytecode being run.
95    code: Gc<CompiledCode>,
96    /// The cells this closure captured.
97    env: Gc<ClosureEnv>,
98    /// The `this` binding.
99    this: Value,
100    /// Argument slots, sized to the declared parameter count.
101    args: Vec<Value>,
102    /// The values the caller actually passed, which is what `arguments` exposes.
103    passed: Vec<Value>,
104    /// Local slots.
105    locals: Vec<Value>,
106    /// Reference cells for this frame's own captured bindings.
107    cells: Vec<Gc<Cell>>,
108    /// The operand stack.
109    stack: Vec<Value>,
110    /// Byte offset of the next instruction.
111    pc: usize,
112    /// Byte offset of the instruction being executed, which is what a stack trace
113    /// reports. `pc` has already moved past it by the time an instruction runs.
114    at: usize,
115    /// The callee, so a native builtin can tell which constructor it is.
116    callee: Value,
117    /// Whether this frame's body ended in a `tail_call`.
118    ///
119    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
120    /// with its own frame just like `call` does and only skips storing the result
121    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
122    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
123    /// pushed as usual, and this marker makes its return value the *caller's* return
124    /// value without running the instructions after the call.
125    tail: bool,
126}
127
128/// The interpreter: a realm plus a frame stack.
129pub struct Interp<'a> {
130    /// The heap everything is allocated on.
131    pub heap: &'a Heap,
132    /// The realm.
133    pub realm: Realm,
134    /// Active frames, outermost first.
135    frames: Vec<Frame>,
136    /// Text written by `print` and friends, in order.
137    ///
138    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
139    /// once at the end, which is also when upstream's line buffering becomes
140    /// visible for the cases compared here.
141    pub output: String,
142    /// The most frames that may be live at once.
143    pub max_frames: usize,
144}
145
146impl<'a> Interp<'a> {
147    /// Build an interpreter over `heap`, with a fresh realm.
148    pub fn new(heap: &'a Heap) -> Interp<'a> {
149        let object_proto = JsObject::ordinary(heap, None);
150        let function_proto = JsObject::function(
151            heap,
152            Some(object_proto.clone()),
153            Callable::Native {
154                func: |_, _, _| Ok(Value::Undefined),
155            },
156        );
157        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
158        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
159        let mut interp = Interp {
160            heap,
161            realm: Realm {
162                global,
163                object_proto,
164                function_proto,
165                array_proto,
166                globals: BTreeMap::new(),
167                declared: Vec::new(),
168                lexical_consts: BTreeSet::new(),
169                errors: BTreeMap::new(),
170                string_proto: None,
171                number_proto: None,
172                boolean_proto: None,
173                error_proto: JsObject::ordinary(heap, None),
174            },
175            frames: Vec::new(),
176            output: String::new(),
177            max_frames: 4096,
178        };
179        crate::builtins::install(&mut interp);
180        interp
181    }
182
183    // -- allocation helpers -------------------------------------------------
184
185    /// A new string value.
186    pub fn string(&self, text: impl Into<String>) -> Value {
187        Value::string(self.heap, text)
188    }
189
190    /// A new ordinary object with the given prototype.
191    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
192        JsObject::ordinary(self.heap, proto)
193    }
194
195    /// A new array.
196    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
197        let array = JsObject::array(
198            self.heap,
199            Some(self.realm.array_proto.clone()),
200            elements.len(),
201        );
202        for (index, element) in elements.into_iter().enumerate() {
203            array.array_set(index, element);
204        }
205        array
206    }
207
208    /// A new native function object.
209    ///
210    /// The observable `name` and `length` are installed as properties here, which is
211    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
212    /// so `f.name = "x"` behaves like the writable property it is.
213    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
214        let function = JsObject::function(
215            self.heap,
216            Some(self.realm.function_proto.clone()),
217            Callable::Native { func },
218        );
219        function.define(
220            "name",
221            Property::with_attributes(self.string(name), false, false),
222        );
223        function.define(
224            "length",
225            Property::with_attributes(Value::Int(length as i32), false, false),
226        );
227        function
228    }
229
230    /// A new bound function.
231    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
232        JsObject::function(
233            self.heap,
234            Some(self.realm.function_proto.clone()),
235            Callable::Bound { target, this, args },
236        )
237    }
238
239    /// A new reference cell.
240    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
241        Gc::new(self.heap, Cell::new(value))
242    }
243
244    // -- running ------------------------------------------------------------
245
246    /// Evaluate `code` as a script body and return its completion value.
247    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
248        let compiled = Gc::new(self.heap, CompiledCode::new(code));
249        let closure_vars = compiled.code.closure_vars.clone();
250        let env = self.global_env(&closure_vars);
251        let this = Value::Object(self.realm.global.clone());
252        let callee = Value::Undefined;
253        self.execute(compiled, env, this, Vec::new(), callee)
254    }
255
256    /// Compile and run `source` in global scope, returning its completion value.
257    ///
258    /// This is what `eval` and `new Function` use. Running it as a script means it
259    /// sees the global object and nothing else, which is right for `eval("1+1")` and
260    /// for a `Function` body; a *direct* eval that reads a local variable would need
261    /// the compiler to hand its variable environment over, which is not implemented.
262    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
263        // The reference names eval'd code `<input>` rather than inheriting the caller's
264        // file name, and stack traces show it, so `eval("1 + x")` failing reports
265        // `(<input>:1:5)`.
266        const EVAL_FILE: &str = "<input>";
267        // A *direct* eval inherits the strictness of the code that called it, which is
268        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
269        // implicit global. The caller's frame is the innermost one here, because a
270        // native function does not push a frame of its own.
271        let strict = self.current_strict();
272        let parsed = if strict {
273            js_parse::parse_script_strict(source)
274        } else {
275            js_parse::parse_script(source)
276        };
277        let program = match parsed {
278            Ok(program) => program,
279            Err(error) => {
280                return Err(Signal::Throw(self.syntax_error_at(
281                    EVAL_FILE,
282                    error.span.start.line,
283                    error.span.start.column,
284                    &format!("invalid source: {error}"),
285                )));
286            }
287        };
288        let mut compiled = match js_compile::compile_script(&program) {
289            Ok(compiled) => compiled,
290            // A construct the compiler does not handle yet is reported the same way a
291            // parse error is: it happens before anything runs, so the trace is the
292            // position in the source followed by the caller.
293            Err(error) => {
294                return Err(Signal::Throw(self.syntax_error_at(
295                    EVAL_FILE,
296                    error.span.start.line,
297                    error.span.start.column,
298                    &error.message,
299                )));
300            }
301        };
302        compiled.set_filename(EVAL_FILE);
303        self.run_script(compiled)
304    }
305
306    /// A `SyntaxError` that reports where in the source it happened.
307    ///
308    /// Compile-time failures never run, so they have no frame of their own; the
309    /// reference still puts the position first in the trace, with no function name and
310    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
311    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
312    /// reference borrows), which is how a script reads the position without parsing
313    /// the trace.
314    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
315        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
316        let value = self.make_error("SyntaxError", message);
317        if let Value::Object(object) = &value {
318            let text = self.string(blamed);
319            object.define("stack", Property::with_attributes(text, true, true));
320            let name = self.string(file);
321            object.define("fileName", Property::with_attributes(name, true, true));
322            object.define(
323                "lineNumber",
324                Property::with_attributes(Value::Int(line as i32), true, true),
325            );
326            object.define(
327                "columnNumber",
328                Property::with_attributes(Value::Int(column as i32), true, true),
329            );
330        }
331        value
332    }
333
334    /// Run a compiled script whose completion value is a function, returning it.
335    ///
336    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
337    /// get the closure out, which keeps the constant-pool plumbing in one place.
338    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
339        self.run_script(code)
340    }
341
342    /// The environment of a script or of any function compiled at global scope:
343    /// every entry is a global binding, so each one resolves to the realm's cell.
344    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
345        let mut cells = Vec::with_capacity(closure_vars.len());
346        for closure_var in closure_vars {
347            let cell = match closure_var.closure_type {
348                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
349                    if closure_var.is_lexical =>
350                {
351                    // A lexical declaration: the cell is created here holding the
352                    // dead-zone marker, which is what makes the binding exist and
353                    // unreadable before its initialiser runs.
354                    self.declare_global(&closure_var.name, closure_var.is_const);
355                    self.realm.globals[&closure_var.name].clone()
356                }
357                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
358                    // A `var` or function declaration becomes a property of the global
359                    // object, and it exists from here on — which is why
360                    // `print(v); var v = 1` prints `undefined` instead of raising.
361                    // Declaring it at instantiation time (rather than at the
362                    // initialiser) is also what makes it non-configurable: the store
363                    // then lands on an existing property instead of creating one.
364                    self.declare_var_global(&closure_var.name);
365                    // The cell is a placeholder that nothing indexes; it cannot be
366                    // omitted because the slot has to hold something.
367                    self.new_cell(Value::Undefined)
368                }
369                _ => {
370                    // An undeclared global is read by name; the cell is a
371                    // placeholder that nothing indexes.
372                    self.new_cell(Value::Undefined)
373                }
374            };
375            cells.push(cell);
376        }
377        Gc::new(self.heap, ClosureEnv { cells })
378    }
379
380    /// Push a frame and run until it returns.
381    fn execute(
382        &mut self,
383        code: Gc<CompiledCode>,
384        env: Gc<ClosureEnv>,
385        this: Value,
386        args: Vec<Value>,
387        callee: Value,
388    ) -> JsResult<Value> {
389        let depth = self.frames.len();
390        self.push_frame(code, env, this, args, callee)?;
391        loop {
392            match self.step() {
393                Ok(Step::Continue) => {}
394                Ok(Step::Return(value)) => {
395                    self.frames.pop();
396                    // A frame that ended in a `tail_call` hands its value straight to
397                    // its caller: nothing after the call can run, so every frame above
398                    // the callee unwinds with the same value. See [`Frame::tail`] —
399                    // the reference does not reuse frames either, so recursion depth
400                    // and the stack-overflow limit behave the same way.
401                    while self.frames.len() > depth && self.frame().tail {
402                        self.frames.pop();
403                    }
404                    if self.frames.len() == depth {
405                        return Ok(value);
406                    }
407                    // The caller resumes with the value on its stack.
408                    self.frames
409                        .last_mut()
410                        .expect("a caller is live")
411                        .stack
412                        .push(value);
413                }
414                Err(Signal::Throw(value)) => {
415                    // A handler lives on the stack of the frame that is throwing —
416                    // `catch` pushed it there — so this frame gets the first chance
417                    // to catch before it is popped.
418                    let value = value;
419                    loop {
420                        if self.frames.len() <= depth {
421                            return Err(Signal::Throw(value));
422                        }
423                        if self.catch_here(value.clone()).is_some() {
424                            break;
425                        }
426                        self.frames.pop();
427                    }
428                }
429                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
430            }
431        }
432    }
433
434    /// Install a handler for `value` if this frame has one, resuming at it.
435    ///
436    /// The scan is the reference's: walk the frame's stack downwards looking for the
437    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
438    /// `0` is an enumerator marker rather than a handler — it exists so that a
439    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
440    /// here and the unwinding continues.
441    fn catch_here(&mut self, value: Value) -> Option<()> {
442        let frame = self.frames.last_mut()?;
443        while let Some(top) = frame.stack.pop() {
444            if let Value::CatchOffset(offset) = top {
445                if offset == 0 {
446                    continue;
447                }
448                frame.stack.push(value);
449                frame.pc = offset as usize;
450                return Some(());
451            }
452        }
453        None
454    }
455
456    fn push_frame(
457        &mut self,
458        code: Gc<CompiledCode>,
459        env: Gc<ClosureEnv>,
460        this: Value,
461        mut args: Vec<Value>,
462        callee: Value,
463    ) -> JsResult<()> {
464        if self.frames.len() >= self.max_frames {
465            return Err(Signal::Throw(
466                self.string("Maximum call stack size exceeded"),
467            ));
468        }
469        let arg_count = code.code.args.len();
470        // How many were actually passed, which `arguments.length` reports and
471        // `assert(x)` depends on: a call with one argument must not look like a call
472        // with one argument and an explicit `undefined`.
473        let passed = args.len();
474        // Missing arguments are `undefined` in their slots; extra ones are dropped
475        // from the slots but still reachable through `arguments`.
476        let mut passed_values = args.clone();
477        args.resize(arg_count, Value::Undefined);
478        args.truncate(arg_count);
479        let cell_count = code.code.var_ref_count as usize;
480        let mut cells = Vec::with_capacity(cell_count);
481        for _ in 0..cell_count {
482            cells.push(self.new_cell(Value::Undefined));
483        }
484        let locals = vec![Value::Undefined; code.code.vars.len()];
485        // A captured argument lives in its cell, not in the argument slot, so the
486        // incoming value has to be moved there before the body runs.
487        for (slot, cell) in code.arg_cell.iter().enumerate() {
488            if *cell >= 0
489                && let Some(value) = args.get(slot).cloned()
490            {
491                cells[*cell as usize].set(value);
492            }
493        }
494        // Sloppy mode substitutes the global object for a missing receiver and boxes a
495        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
496        // reports `object`. Strict mode passes the value through untouched.
497        let this = if code.code.strict {
498            this
499        } else if this.is_nullish() {
500            Value::Object(self.realm.global.clone())
501        } else if matches!(this, Value::Object(_)) {
502            this
503        } else {
504            match crate::builtins::this_object(self, &this) {
505                Ok(boxed) => Value::Object(boxed),
506                Err(_) => this,
507            }
508        };
509        self.frames.push(Frame {
510            code,
511            env,
512            this,
513            args,
514            passed: passed_values.drain(..passed).collect(),
515            locals,
516            cells,
517            stack: Vec::with_capacity(16),
518            pc: 0,
519            at: 0,
520            callee,
521            tail: false,
522        });
523        Ok(())
524    }
525
526    fn frame(&self) -> &Frame {
527        self.frames.last().expect("a frame is live")
528    }
529
530    fn frame_mut(&mut self) -> &mut Frame {
531        self.frames.last_mut().expect("a frame is live")
532    }
533
534    // -- slot access --------------------------------------------------------
535
536    fn read_slot(&self, cell: i32, value: &Value) -> Value {
537        match cell {
538            -1 => value.clone(),
539            index => self
540                .frame()
541                .cells
542                .get(index as usize)
543                .expect("a cell index in range")
544                .get(),
545        }
546    }
547
548    fn get_arg(&self, slot: usize) -> Value {
549        let frame = self.frame();
550        let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
551        let value = frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
552        self.read_slot(cell, &value)
553    }
554
555    fn put_arg(&mut self, slot: usize, value: Value) {
556        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
557        if cell == -1 {
558            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
559                *slot = value;
560            }
561        } else {
562            self.frame().cells[cell as usize].set(value);
563        }
564    }
565
566    fn get_loc(&self, slot: usize) -> Value {
567        let frame = self.frame();
568        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
569        let value = frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
570        self.read_slot(cell, &value)
571    }
572
573    fn put_loc(&mut self, slot: usize, value: Value) {
574        let cell = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
575        if cell == -1 {
576            if let Some(slot) = self.frame_mut().locals.get_mut(slot) {
577                *slot = value;
578            }
579        } else {
580            self.frame().cells[cell as usize].set(value);
581        }
582    }
583
584    // -- globals ------------------------------------------------------------
585
586    /// The name a global-slot operand refers to.
587    fn global_name(&self, slot: usize) -> String {
588        self.frame()
589            .code
590            .code
591            .closure_vars
592            .get(slot)
593            .map(|c| c.name.clone())
594            .unwrap_or_default()
595    }
596
597    /// The facts about a global binding that decide where it lives.
598    ///
599    /// A script's globals split in two, and the split is observable: `var` and
600    /// function declarations become properties of the global object (`globalThis.v`
601    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
602    /// declarations live in the global *lexical* environment and are invisible there
603    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
604    /// `is_lexical` flag means the answer is already in the bytecode.
605    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
606        let name = self.global_name(slot);
607        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
608        // while forwarding a reference through a nested function is built with the
609        // flags cleared, so `const c` would look like an ordinary `var` from inside a
610        // closure. Presence in the realm's lexical table is the same fact, recorded
611        // once, and every slot sees it.
612        let lexical = self.realm.globals.contains_key(&name);
613        let is_const = self.realm.lexical_consts.contains(&name);
614        (name, lexical, is_const)
615    }
616
617    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
618        let (name, lexical, _) = self.global_binding(slot);
619        if lexical {
620            // A lexical global is a binding in a side table, so the dead zone is
621            // visible and it is nowhere on the global object.
622            if let Some(cell) = self.realm.globals.get(&name) {
623                let value = cell.get();
624                if matches!(value, Value::Uninitialized) {
625                    return Err(self.throw_reference(&name));
626                }
627                return Ok(value);
628            }
629            return Err(self.throw_reference(&name));
630        }
631        // A `var` global is an ordinary property, so the prototype chain and the
632        // global object's own builtins are all reachable through it.
633        match self.get_property(&self.realm.global.clone(), &name)? {
634            Some(value) => Ok(value),
635            None => Err(self.throw_reference(&name)),
636        }
637    }
638
639    /// Store to a global binding.
640    ///
641    /// Returns a signal when the store is refused: a `const` global may only be
642    /// written by its initialiser, and a non-configurable `var` global may not be
643    /// deleted but is always writable.
644    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
645        let (name, lexical, is_const) = self.global_binding(slot);
646        if lexical {
647            if let Some(cell) = self.realm.globals.get(&name).cloned() {
648                if is_const && !matches!(cell.get(), Value::Uninitialized) {
649                    return Err(self.read_only_global(&name));
650                }
651                cell.set(value);
652                return Ok(());
653            }
654            // Writing an undeclared lexical global is a `ReferenceError` in strict
655            // mode and a silent global creation otherwise; creating the cell here
656            // keeps both paths from losing the value.
657            let cell = self.new_cell(value);
658            self.realm.globals.insert(name, cell);
659            return Ok(());
660        }
661        let global = self.realm.global.clone();
662        match global.own_property(&name) {
663            // A `var` global is writable, so the store goes straight through — but
664            // through the property, so `globalThis.v = 3` and `v = 3` agree.
665            Some(_) => self.set_property_with(&global, &name, value, DeleteFailure::Throw),
666            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
667            // declaration creates a *configurable* property, which is what makes it
668            // deletable and is the one way a global differs from a declared `var`.
669            // In strict mode the same store is a `ReferenceError` instead: that is the
670            // whole point of strict mode, and creating the global silently meant
671            // `"use strict"; x = 1` looked like it worked.
672            None => {
673                if self.current_strict() {
674                    return Err(self.throw_reference(&name));
675                }
676                global.define_data(&name, value);
677                Ok(())
678            }
679        }
680    }
681
682    /// Whether the code currently running is strict.
683    ///
684    /// Read off the frame's function, which is where the parser's answer ended up; a
685    /// native function never runs strict-only checks, and there is no frame at all
686    /// before the first script.
687    pub fn current_strict(&self) -> bool {
688        self.frames
689            .last()
690            .is_some_and(|frame| frame.code.code.strict)
691    }
692
693    /// Initialise a declared global, which is what ends its dead zone.
694    ///
695    /// A `var` global becomes a property of the global object: writable, so a later
696    /// assignment goes through, and non-configurable, so `delete` refuses.
697    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
698        let (name, lexical, _) = self.global_binding(slot);
699        if lexical {
700            // The cell exists (created at declaration time) holding the dead-zone
701            // marker; storing the value is what makes the binding readable.
702            if let Some(cell) = self.realm.globals.get(&name).cloned() {
703                cell.set(value);
704                return Ok(());
705            }
706            let cell = self.new_cell(value);
707            self.realm.globals.insert(name, cell);
708            return Ok(());
709        }
710        let global = self.realm.global.clone();
711        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
712        // to answer `false` and leave the binding in place. `with_attributes` ties
713        // `configurable` to `writable`, so the property is built field by field.
714        global.define(
715            &name,
716            Property {
717                value: Some(value),
718                writable: true,
719                enumerable: true,
720                configurable: false,
721                ..Property::default()
722            },
723        );
724        Ok(())
725    }
726
727    /// The `TypeError` a store to a `const` global raises.
728    fn read_only_global(&self, name: &str) -> Signal {
729        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
730    }
731
732    // -- properties ---------------------------------------------------------
733
734    /// Read `object[key]`, following the prototype chain.
735    ///
736    /// An inherited accessor runs with the *receiver* as `this`, which is why the
737    /// lookup returns the owner rather than just the value.
738    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
739        if let Some(value) = self.own_element(object, key) {
740            return Ok(Some(value));
741        }
742        // `length` is not stored as a property: an array's length is its element
743        // count, and keeping one copy of it is what makes `push`/`pop` and
744        // `a.length = n` agree.
745        if key == "length"
746            && let Some(length) = object.array_length()
747        {
748            return Ok(Some(Value::Int(length as i32)));
749        }
750        match lookup(object, key) {
751            Some((_, property)) => {
752                if property.is_accessor() {
753                    match &property.getter {
754                        Some(getter) if !matches!(getter, Value::Undefined) => {
755                            let receiver = Value::Object(object.clone());
756                            self.call_value(getter.clone(), receiver, Vec::new())
757                                .map(Some)
758                        }
759                        // An accessor with no getter reads as `undefined`.
760                        _ => Ok(Some(Value::Undefined)),
761                    }
762                } else {
763                    Ok(property.value)
764                }
765            }
766            None => Ok(None),
767        }
768    }
769
770    /// The own array element `key` names, if this object has one.
771    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
772        let index = array_index(key)?;
773        // A hole reads as `undefined` but is not a stored `undefined`; mapping it
774        // here keeps that distinction out of every read site.
775        object.array_get(index as usize).map(|value| match value {
776            Value::Hole => Value::Undefined,
777            other => other,
778        })
779    }
780
781    /// Store `object[key] = value`, honouring setters and inherited properties.
782    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
783        self.set_property_with(object, key, value, DeleteFailure::Throw)
784    }
785
786    /// Store a property, choosing what to do when the object refuses.
787    ///
788    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
789    /// mode, which is the one place assignment differs by mode. Native code (the array
790    /// methods, `JSON`) always asks for the throw.
791    pub fn set_property_with(
792        &mut self,
793        object: &Gc<JsObject>,
794        key: &str,
795        value: Value,
796        on_failure: DeleteFailure,
797    ) -> JsResult<()> {
798        if let Some(index) = array_index(key) {
799            if object.is_array() {
800                // Adding an index past the end makes the array longer, which a
801                // non-extensible array refuses.
802                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
803                    return match on_failure {
804                        DeleteFailure::Throw => Err(self.type_error(format!(
805                            "cannot add property '{key}', object is not extensible"
806                        ))),
807                        DeleteFailure::Ignore => Ok(()),
808                    };
809                }
810                if object.element_is_locked(index) {
811                    return match on_failure {
812                        DeleteFailure::Throw => {
813                            Err(self.type_error(format!("'{key}' is read-only")))
814                        }
815                        DeleteFailure::Ignore => Ok(()),
816                    };
817                }
818                object.array_set(index as usize, value);
819                return Ok(());
820            }
821        }
822        if key == "length" && object.is_array() {
823            let length = value.to_number();
824            if length.is_finite() && length >= 0.0 {
825                let length = length as usize;
826                // `a.length = n` with `n` below a non-configurable element cannot
827                // drop that element, so the whole assignment fails. The spec makes
828                // this a `TypeError` rather than a silent no-op, in any mode.
829                if let Some(blocked) = (length..object.array_length().unwrap_or(0))
830                    .find(|index| object.element_is_locked(*index as u32))
831                {
832                    // Sloppy mode stops the truncation at the blocking element
833                    // instead of failing; strict mode raises.
834                    // Both modes stop at the blocking element; they differ in
835                    // whether that is reported. The reference truncates *then*
836                    // throws, so the array is left in the shortened state.
837                    object.array_truncate(blocked + 1);
838                    return match on_failure {
839                        DeleteFailure::Throw => {
840                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
841                        }
842                        DeleteFailure::Ignore => Ok(()),
843                    };
844                }
845                object.array_set_length(length);
846                return Ok(());
847            }
848        }
849        if !object.is_extensible() && !object.has_own(key) && lookup(object, key).is_none() {
850            return match on_failure {
851                DeleteFailure::Throw => Err(self.type_error(format!(
852                    "cannot add property '{key}', object is not extensible"
853                ))),
854                DeleteFailure::Ignore => Ok(()),
855            };
856        }
857        if let Some((owner, property)) = lookup(object, key) {
858            if property.is_accessor() {
859                if let Some(setter) = &property.setter
860                    && !matches!(setter, Value::Undefined)
861                {
862                    let receiver = Value::Object(object.clone());
863                    self.call_value(setter.clone(), receiver, vec![value])?;
864                }
865                return Ok(());
866            }
867            // An inherited *data* property is shadowed by an own property on the
868            // receiver; a non-writable one is not.
869            if owner.ptr_eq(object) && !property.writable {
870                return match on_failure {
871                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
872                    DeleteFailure::Ignore => Ok(()),
873                };
874            }
875            // An existing writable own property keeps its attributes: only the value
876            // moves. Redefining instead would reset them, which is how a
877            // non-configurable global `var` used to become deletable.
878            if owner.ptr_eq(object) && object.write_value(key, value.clone()) {
879                return Ok(());
880            }
881        }
882        // No own data property: create one, shadowing whatever the prototype holds.
883        object.define_data(key, value);
884        Ok(())
885    }
886
887    /// Delete `object[key]`.
888    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> bool {
889        if let Some(index) = array_index(key) {
890            if let Some(elements) = object.array_elements()
891                && (index as usize) < elements.len()
892            {
893                // A hole rather than a shift: `delete a[0]` leaves `length` alone and
894                // the index stops answering `in`.
895                if object.element_is_locked(index) {
896                    return false;
897                }
898                object.array_set(index as usize, Value::Hole);
899                return true;
900            }
901        }
902        object.delete(key)
903    }
904
905    // -- calling ------------------------------------------------------------
906
907    /// Call `callee` with `this` and `args`.
908    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
909        let Value::Object(function) = &callee else {
910            // `typeof x === "function"` is not enough to make `x()` legal: only a
911            // callable object is. `null` and `undefined` need no special wording
912            // here — their `ToString` already reads the way the reference's does.
913            let what = format!("{} is not a function", callee.to_js_string());
914            return Err(Signal::Throw(self.make_error("TypeError", &what)));
915        };
916        let callable = function.with(|data| match &data.kind {
917            ObjectKind::Function(callable) => match callable {
918                Callable::Native { func } => Some(NativeCall::Native(*func)),
919                Callable::Bound {
920                    target,
921                    this,
922                    args: leading,
923                } => Some(NativeCall::Bound {
924                    target: target.clone(),
925                    this: this.clone(),
926                    leading: leading.clone(),
927                }),
928                Callable::Bytecode { code, env } => {
929                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
930                }
931            },
932            _ => None,
933        });
934        match callable {
935            Some(NativeCall::Native(func)) => func(self, this, &args),
936            Some(NativeCall::Bound {
937                target,
938                this: bound_this,
939                leading,
940            }) => {
941                let mut all = leading;
942                all.extend(args);
943                self.call_value(target, bound_this, all)
944            }
945            Some(NativeCall::Bytecode(code, env)) => self.execute(code, env, this, args, callee),
946            None => Err(Signal::Throw(
947                self.make_error("TypeError", "not a function"),
948            )),
949        }
950    }
951
952    /// Give a freshly built function its own `prototype` object.
953    ///
954    /// Every function that can be used with `new` carries one, and its
955    /// `constructor` points back at the function — a reference cycle, which is
956    /// exactly what the collector's cycle pass exists to reclaim.
957    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
958        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
959        let constructor = Value::Object(function.clone());
960        prototype.define(
961            "constructor",
962            Property::with_attributes(constructor, true, false),
963        );
964        let value = Value::Object(prototype);
965        function.define("prototype", Property::with_attributes(value, true, false));
966    }
967
968    /// The object `special_object` builds.
969    ///
970    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
971    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
972    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
973    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
974    /// write through `arguments` does not reach the parameter.
975    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
976        match magic {
977            0 | 1 => {
978                let args = self.frame().passed.clone();
979                let proto = self.realm.object_proto.clone();
980                let object = self.new_object(Some(proto));
981                object.define_data("length", Value::Int(args.len() as i32));
982                for (index, value) in args.into_iter().enumerate() {
983                    object.define_data(&index.to_string(), value);
984                }
985                Ok(Value::Object(object))
986            }
987            // `this function`: what a named function expression binds its own name to.
988            2 => Ok(self
989                .current_callee()
990                .map_or(Value::Undefined, Value::Object)),
991            other => Err(Signal::Throw(self.make_error(
992                "InternalError",
993                &format!("special_object {other} is not implemented yet"),
994            ))),
995        }
996    }
997
998    /// Call `callee`, or push its frame and let the main loop run it.
999    ///
1000    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
1001    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
1002    /// continues, so `function f(){ return f() }` costs heap and stops at
1003    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
1004    /// is entered directly, and natives do not re-enter JavaScript in this
1005    /// milestone.
1006    ///
1007    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
1008    /// because the returning frame will.
1009    fn call_or_push(
1010        &mut self,
1011        callee: Value,
1012        this: Value,
1013        args: Vec<Value>,
1014    ) -> JsResult<Option<Value>> {
1015        if let Value::Object(function) = &callee
1016            && let Some((code, env)) = bytecode_of(function)
1017        {
1018            self.push_frame(code, env, this, args, callee)?;
1019            return Ok(None);
1020        }
1021        self.call_value(callee, this, args).map(Some)
1022    }
1023
1024    /// `new callee(args)`.
1025    ///
1026    /// A constructor differs from a plain call in three ways: it gets a fresh object
1027    /// as `this` whose prototype is the constructor's `prototype` property, its
1028    /// return value is *replaced* by that object unless it returns an object itself,
1029    /// and a native constructor is expected to initialise the object it is given
1030    /// rather than build one.
1031    pub fn construct(
1032        &mut self,
1033        callee: Value,
1034        _new_target: Value,
1035        args: Vec<Value>,
1036    ) -> JsResult<Value> {
1037        // `new` on a bound function constructs its *target*, prepending the arguments
1038        // the bind fixed and ignoring the bound `this` — a bound function is a
1039        // constructor only when its target is one, and `new` always makes a fresh
1040        // object of the target's prototype rather than reusing the bound receiver.
1041        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
1042        // ran the body with `this === null` and threw on `this.x = a`.
1043        let mut callee = callee;
1044        let mut args = args;
1045        loop {
1046            let Some(object) = callee.as_object().cloned() else {
1047                return Err(Signal::Throw(
1048                    self.make_error("TypeError", "not a constructor"),
1049                ));
1050            };
1051            let bound = object.with(|data| match &data.kind {
1052                ObjectKind::Function(Callable::Bound {
1053                    target,
1054                    args: leading,
1055                    ..
1056                }) => Some((target.clone(), leading.clone())),
1057                _ => None,
1058            });
1059            let Some((target, leading)) = bound else {
1060                break;
1061            };
1062            let mut all = leading;
1063            all.extend(args);
1064            args = all;
1065            callee = target;
1066        }
1067        let Value::Object(function) = &callee else {
1068            unreachable!("the loop above only breaks on an object");
1069        };
1070        // `new` on a native builtin: hand it the fresh object, which is how the
1071        // error classes and the object wrappers will initialise their own fields.
1072        let prototype = self.get_property(function, "prototype")?;
1073        let prototype = match prototype {
1074            Some(Value::Object(proto)) => Some(proto),
1075            _ => Some(self.realm.object_proto.clone()),
1076        };
1077        let this = Value::Object(self.new_object(prototype));
1078        let result = self.call_value(callee, this.clone(), args)?;
1079        // A constructor that returns an object overrides `this`; any other return
1080        // value (including `undefined`) is ignored.
1081        Ok(match result {
1082            Value::Object(_) => result,
1083            _ => this,
1084        })
1085    }
1086
1087    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
1088    ///
1089    /// The error classes themselves arrive with the builtins milestone; what
1090    /// matters here is that the thrown value stringifies the way a script printing
1091    /// the caught value expects.
1092    pub fn make_error(&self, name: &str, message: &str) -> Value {
1093        let proto = self
1094            .realm
1095            .errors
1096            .get(name)
1097            .map(|constructor| self.prototype_of(constructor))
1098            .unwrap_or_else(|| self.realm.error_proto.clone());
1099        let error = self.new_object(Some(proto));
1100        // `name` and `message` are own properties of the instance, which is what
1101        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
1102        // `Error`.
1103        error.define(
1104            "name",
1105            Property::with_attributes(self.string(name), true, false),
1106        );
1107        error.define(
1108            "message",
1109            Property::with_attributes(self.string(message), true, false),
1110        );
1111        // The trace is captured where the error is *made*, which is where the reference
1112        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
1113        // way out, so a caught engine error already has its stack even if the handler
1114        // never rethrows it.
1115        self.add_stack(&error);
1116        Value::Object(error)
1117    }
1118
1119    /// Give an error object its `stack` property, from the current frame stack.
1120    ///
1121    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
1122    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
1123    /// `stack` a script set, is not rewritten.
1124    pub fn add_stack(&self, object: &Gc<JsObject>) {
1125        if object.has_own("stack") {
1126            return;
1127        }
1128        let trace = self.stack_trace();
1129        let text = self.string(trace);
1130        object.define("stack", Property::with_attributes(text, true, true));
1131    }
1132
1133    /// The function object currently being called, if any.
1134    ///
1135    /// A native function is a bare `fn` pointer, so it cannot capture which class
1136    /// it belongs to; it reads that from the callee instead. This is also what a
1137    /// stack trace would use.
1138    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
1139        match &self.frames.last()?.callee {
1140            Value::Object(object) => Some(object.clone()),
1141            _ => None,
1142        }
1143    }
1144
1145    /// The `prototype` property of a constructor, falling back to
1146    /// `Object.prototype` for anything that is not shaped like one.
1147    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
1148        constructor
1149            .own_property("prototype")
1150            .and_then(|property| property.value)
1151            .and_then(|value| value.as_object().cloned())
1152            .unwrap_or_else(|| self.realm.object_proto.clone())
1153    }
1154
1155    /// Throw a `TypeError` carrying `message`.
1156    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
1157        Signal::Throw(self.make_error("TypeError", message.as_ref()))
1158    }
1159
1160    /// Throw a `RangeError` carrying `message`.
1161    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
1162        Signal::Throw(self.make_error("RangeError", message.as_ref()))
1163    }
1164
1165    /// The `ReferenceError` a read of an uninitialised binding raises.
1166    /// The name of the binding `slot` refers to, for an error message.
1167    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
1168        match kind {
1169            VarSlot::Loc => self
1170                .frame()
1171                .code
1172                .code
1173                .vars
1174                .get(slot)
1175                .map(|v| v.name.clone()),
1176            VarSlot::Closure => self
1177                .frame()
1178                .code
1179                .code
1180                .closure_vars
1181                .get(slot)
1182                .map(|c| c.name.clone()),
1183        }
1184        .unwrap_or_default()
1185    }
1186
1187    /// Whether `slot` names a `const` binding, which rejects every store after its
1188    /// initialiser.
1189    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
1190        match kind {
1191            VarSlot::Loc => self
1192                .frame()
1193                .code
1194                .code
1195                .vars
1196                .get(slot)
1197                .is_some_and(|v| v.is_const),
1198            VarSlot::Closure => self
1199                .frame()
1200                .code
1201                .code
1202                .closure_vars
1203                .get(slot)
1204                .is_some_and(|c| c.is_const),
1205        }
1206    }
1207
1208    /// The `TypeError` a store to a `const` binding raises.
1209    ///
1210    /// `const` is enforced here rather than at compile time because the binding can be
1211    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
1212    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
1213    /// both halves of what "checked store" means: the dead zone is over, and the
1214    /// binding is writable.
1215    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
1216        let name = self.binding_name(slot, kind);
1217        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
1218    }
1219
1220    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
1221        let name = match kind {
1222            VarSlot::Loc => self
1223                .frame()
1224                .code
1225                .code
1226                .vars
1227                .get(slot)
1228                .map(|v| v.name.clone()),
1229            VarSlot::Closure => self
1230                .frame()
1231                .code
1232                .code
1233                .closure_vars
1234                .get(slot)
1235                .map(|c| c.name.clone()),
1236        }
1237        .unwrap_or_default();
1238        Signal::Throw(self.make_error(
1239            "ReferenceError",
1240            &format!("cannot access '{name}' before initialization"),
1241        ))
1242    }
1243
1244    fn throw_reference(&self, name: &str) -> Signal {
1245        Signal::Throw(self.make_error("ReferenceError", &format!("{name} is not defined")))
1246    }
1247
1248    // -- the instruction loop -----------------------------------------------
1249
1250    fn step(&mut self) -> JsResult<Step> {
1251        let pc = self.frame().pc;
1252        let code = self.frame().code.clone();
1253        let bytes = &code.code.code;
1254        if pc >= bytes.len() {
1255            return Ok(Step::Return(Value::Undefined));
1256        }
1257        let Some(decoded) = decode(bytes, pc) else {
1258            return Err(Signal::Throw(
1259                self.make_error("InternalError", "undecodable bytecode"),
1260            ));
1261        };
1262        let (op, a, b, next) = decoded;
1263        self.frame_mut().at = pc;
1264        self.frame_mut().pc = next;
1265        self.execute_instruction(op, a, b, next)
1266    }
1267
1268    fn push(&mut self, value: Value) {
1269        self.frame_mut().stack.push(value);
1270    }
1271
1272    fn pop(&mut self) -> Value {
1273        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
1274    }
1275
1276    fn pop_n(&mut self, count: usize) -> Vec<Value> {
1277        let frame = self.frame_mut();
1278        let start = frame.stack.len().saturating_sub(count);
1279        frame.stack.split_off(start)
1280    }
1281
1282    fn peek(&self, back: usize) -> Value {
1283        let frame = self.frame();
1284        frame
1285            .stack
1286            .get(frame.stack.len().wrapping_sub(1 + back))
1287            .cloned()
1288            .unwrap_or(Value::Undefined)
1289    }
1290
1291    #[allow(clippy::too_many_lines)]
1292    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
1293        use Opcode::*;
1294        match op {
1295            // -- constants and stack shuffling -----------------------------
1296            Nop => {}
1297            PushMinus1 => self.push(Value::Int(-1)),
1298            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
1299                let value = match op {
1300                    Push0 => 0,
1301                    Push1 => 1,
1302                    Push2 => 2,
1303                    Push3 => 3,
1304                    Push4 => 4,
1305                    Push5 => 5,
1306                    Push6 => 6,
1307                    _ => 7,
1308                };
1309                self.push(Value::Int(value));
1310            }
1311            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
1312            PushTrue => self.push(Value::Bool(true)),
1313            PushFalse => self.push(Value::Bool(false)),
1314            PushEmptyString => self.push(self.string("")),
1315            Undefined => self.push(Value::Undefined),
1316            Null => self.push(Value::Null),
1317            Object => {
1318                let proto = self.realm.object_proto.clone();
1319                self.push(Value::Object(self.new_object(Some(proto))));
1320            }
1321            PushThis => {
1322                let this = self.frame().this.clone();
1323                self.push(this);
1324            }
1325            PushConst | PushConst8 => {
1326                let value = self.constant(a as usize)?;
1327                self.push(value);
1328            }
1329            PushAtomValue => {
1330                let text = self.atom_text(a as usize);
1331                self.push(self.string(text));
1332            }
1333            Dup => {
1334                let value = self.peek(0);
1335                self.push(value);
1336            }
1337            Dup1 => {
1338                let value = self.peek(1);
1339                self.push(value);
1340            }
1341            Drop => {
1342                self.pop();
1343            }
1344            Nip => {
1345                // `a b -> b`
1346                let top = self.pop();
1347                self.pop();
1348                self.push(top);
1349            }
1350            Insert2 => {
1351                // `obj a -> a obj a`
1352                let value = self.pop();
1353                let object = self.pop();
1354                self.push(value.clone());
1355                self.push(object);
1356                self.push(value);
1357            }
1358            Insert3 => {
1359                // `obj prop a -> a obj prop a`
1360                let value = self.pop();
1361                let key = self.pop();
1362                let object = self.pop();
1363                self.push(value.clone());
1364                self.push(object);
1365                self.push(key);
1366                self.push(value);
1367            }
1368            Rot3r => {
1369                // `a b c -> c a b`
1370                let c = self.pop();
1371                let b = self.pop();
1372                let a_value = self.pop();
1373                self.push(c);
1374                self.push(a_value);
1375                self.push(b);
1376            }
1377
1378            // -- slots ------------------------------------------------------
1379            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
1380                let slot = self.slot_operand(op, a);
1381                let value = self.get_loc(slot);
1382                self.push(value);
1383            }
1384            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
1385                let slot = self.slot_operand(op, a);
1386                let value = self.pop();
1387                self.put_loc(slot, value);
1388            }
1389            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
1390                let slot = self.slot_operand(op, a);
1391                let value = self.pop();
1392                self.put_loc(slot, value.clone());
1393                self.push(value);
1394            }
1395            // The `_check` forms are the temporal dead zone: they throw when the
1396            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
1397            // *reads*, so only the two writes may pop — mishandling that quietly
1398            // consumes the value the caller pushed just before.
1399            GetLocCheck => {
1400                let slot = self.slot_operand(op, a);
1401                let value = self.get_loc(slot);
1402                if matches!(value, Value::Uninitialized) {
1403                    return Err(self.dead_zone(slot, VarSlot::Loc));
1404                }
1405                self.push(value);
1406            }
1407            PutLocCheck | SetLocCheck => {
1408                let slot = self.slot_operand(op, a);
1409                let value = self.pop();
1410                if matches!(value, Value::Uninitialized) {
1411                    return Err(self.dead_zone(slot, VarSlot::Loc));
1412                }
1413                // The initialiser goes through `put_loc`, not this, so any store that
1414                // reaches here is a later assignment — which a `const` refuses.
1415                if self.is_read_only(slot, VarSlot::Loc) {
1416                    return Err(self.read_only(slot, VarSlot::Loc));
1417                }
1418                if op == SetLocCheck {
1419                    self.put_loc(slot, value.clone());
1420                    self.push(value);
1421                } else {
1422                    self.put_loc(slot, value);
1423                }
1424            }
1425            SetLocUninitialized => {
1426                let slot = self.slot_operand(op, a);
1427                self.put_loc(slot, Value::Uninitialized);
1428            }
1429            CloseLoc => {
1430                // "Close" a binding: give it a *fresh* cell holding the current
1431                // value. Closures created before this point keep the old cell and the
1432                // ones created after see the new one, which is what makes every
1433                // iteration of `for (let i ...)` capture its own `i`, and what freezes
1434                // a block-scoped binding when the block ends.
1435                //
1436                // Clearing the slot instead (which this used to do) broke both: a
1437                // closure over a captured block variable read `undefined`, and a loop
1438                // terminated after one iteration.
1439                let slot = self.slot_operand(op, a);
1440                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
1441                if index >= 0 {
1442                    let current = self.frame().cells[index as usize].get();
1443                    let fresh = self.new_cell(current);
1444                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
1445                        *cell = fresh;
1446                    }
1447                }
1448            }
1449            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
1450                let slot = self.slot_operand(op, a);
1451                let value = self.get_arg(slot);
1452                self.push(value);
1453            }
1454            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
1455                let slot = self.slot_operand(op, a);
1456                let value = self.pop();
1457                self.put_arg(slot, value);
1458            }
1459            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
1460                let slot = self.slot_operand(op, a);
1461                let value = self.pop();
1462                self.put_arg(slot, value.clone());
1463                self.push(value);
1464            }
1465
1466            // -- closure variables ------------------------------------------
1467            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
1468                let slot = self.slot_operand(op, a);
1469                let value = self.cell_value(slot)?;
1470                self.push(value);
1471            }
1472            GetVarRefCheck => {
1473                let slot = self.slot_operand(op, a);
1474                let value = self.cell_value(slot)?;
1475                if matches!(value, Value::Uninitialized) {
1476                    return Err(self.dead_zone(slot, VarSlot::Closure));
1477                }
1478                self.push(value);
1479            }
1480            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
1481                let slot = self.slot_operand(op, a);
1482                let value = self.pop();
1483                // Same rule as `PutLocCheck`: a checked store to a captured binding
1484                // refuses a `const` once its initialiser has run.
1485                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
1486                    return Err(self.read_only(slot, VarSlot::Closure));
1487                }
1488                self.set_cell(slot, value)?;
1489            }
1490            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
1491                let slot = self.slot_operand(op, a);
1492                let value = self.pop();
1493                self.set_cell(slot, value.clone())?;
1494                self.push(value);
1495            }
1496
1497            // -- globals ----------------------------------------------------
1498            GetVar => {
1499                let value = self.get_global(a as usize)?;
1500                self.push(value);
1501            }
1502            GetVarUndef => {
1503                let value = self
1504                    .get_global(a as usize)
1505                    .or_else(|_| Ok(Value::Undefined))?;
1506                self.push(value);
1507            }
1508            DeleteVar => {
1509                // `delete name` for a name that is not a declared binding. A lexical
1510                // global lives in the reference table and cannot be deleted; anything
1511                // reachable only as a property of the global object is *implicit* —
1512                // `x = 1` with no declaration — and goes away if it is configurable,
1513                // which is what `delete` on an implicit global answers.
1514                let name = self.atom_text(a as usize);
1515                let global = self.realm.global.clone();
1516                let deleted = if self.realm.globals.contains_key(&name) {
1517                    false
1518                } else if global.own_property(&name).is_some() {
1519                    self.delete_property(&global, &name)
1520                } else {
1521                    true
1522                };
1523                self.push(Value::Bool(deleted));
1524            }
1525            PutVar => {
1526                let value = self.pop();
1527                self.put_global(a as usize, value)?;
1528            }
1529            PutVarInit => {
1530                let slot = a as usize;
1531                let value = self.pop();
1532                self.init_global(slot, value)?;
1533            }
1534
1535            // -- arithmetic -------------------------------------------------
1536            Add => self.binary_add()?,
1537            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
1538                let raw = self.pop();
1539                let right = self.numeric(raw)?;
1540                let raw = self.pop();
1541                let left = self.numeric(raw)?;
1542                self.push(arithmetic(op, left, right)?);
1543            }
1544            Neg => {
1545                let raw = self.pop();
1546                let value = self.numeric(raw)?;
1547                self.push(negate(value));
1548            }
1549            Plus => {
1550                let value = self.pop();
1551                let numeric = self.numeric_of(value)?;
1552                self.push(numeric);
1553            }
1554            Inc => {
1555                let raw = self.pop();
1556                let value = self.numeric(raw)?;
1557                self.push(increment(value));
1558            }
1559            Dec => {
1560                let raw = self.pop();
1561                let value = self.numeric(raw)?;
1562                self.push(decrement(value));
1563            }
1564            PostInc | PostDec => {
1565                // `x -> x x+1`: the *new* value ends up on top, so the store the
1566                // compiler emits right after (`put_var`) writes the incremented
1567                // one, while the old value stays underneath for the expression's
1568                // own result. Getting this backwards makes `i++` a no-op, which
1569                // turns `while (i < 3)` into an infinite loop.
1570                let raw = self.pop();
1571                let value = self.numeric(raw)?;
1572                let updated = if op == PostInc {
1573                    increment(value.clone())
1574                } else {
1575                    decrement(value.clone())
1576                };
1577                self.push(value);
1578                self.push(updated);
1579            }
1580            Not => {
1581                let raw = self.pop();
1582                let value = self.numeric(raw)?;
1583                self.push(Value::Int(!value.to_int32()));
1584            }
1585            Lnot => {
1586                let value = self.pop();
1587                self.push(Value::Bool(!value.to_boolean()));
1588            }
1589
1590            // -- comparison -------------------------------------------------
1591            Lt | Lte | Gt | Gte => {
1592                let right = self.pop();
1593                let left = self.pop();
1594                self.push(compare(op, left, right, self));
1595            }
1596            Eq | Neq => {
1597                let right = self.pop();
1598                let left = self.pop();
1599                let equal = self.abstract_equals(left, right)?;
1600                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
1601            }
1602            StrictEq => {
1603                let right = self.pop();
1604                let left = self.pop();
1605                self.push(Value::Bool(left.strict_equals(&right)));
1606            }
1607            StrictNeq => {
1608                let right = self.pop();
1609                let left = self.pop();
1610                self.push(Value::Bool(!left.strict_equals(&right)));
1611            }
1612            IsUndefinedOrNull => {
1613                let value = self.pop();
1614                self.push(Value::Bool(value.is_nullish()));
1615            }
1616            Typeof => {
1617                let value = self.pop();
1618                self.push(self.string(value.type_of()));
1619            }
1620            Instanceof => {
1621                let constructor = self.pop();
1622                let object = self.pop();
1623                let answer = self.instance_of(&object, &constructor)?;
1624                self.push(Value::Bool(answer));
1625            }
1626            In => {
1627                let object = self.pop();
1628                let key = self.pop();
1629                let answer = self.has_property(&key, &object)?;
1630                self.push(Value::Bool(answer));
1631            }
1632
1633            // -- control flow -----------------------------------------------
1634            Goto | Goto8 | Goto16 => {
1635                self.frame_mut().pc = a as usize;
1636            }
1637            IfTrue | IfTrue8 => {
1638                let value = self.pop();
1639                if value.to_boolean() {
1640                    self.frame_mut().pc = a as usize;
1641                }
1642            }
1643            IfFalse | IfFalse8 => {
1644                let value = self.pop();
1645                if !value.to_boolean() {
1646                    self.frame_mut().pc = a as usize;
1647                }
1648            }
1649            Catch => {
1650                // Pushes the handler target onto the value stack; `unwind` finds it.
1651                self.push(Value::CatchOffset(a));
1652            }
1653            Gosub => {
1654                self.push(Value::ReturnAddress(next as u32));
1655                self.frame_mut().pc = a as usize;
1656            }
1657            Ret => {
1658                let value = self.pop();
1659                match value {
1660                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
1661                    _ => {
1662                        return Err(Signal::Throw(
1663                            self.make_error("InternalError", "invalid return address"),
1664                        ));
1665                    }
1666                }
1667            }
1668            NipCatch => {
1669                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
1670                // including the marker, keeping the top value.
1671                let top = self.pop();
1672                loop {
1673                    match self.pop() {
1674                        Value::CatchOffset(_) | Value::Undefined => break,
1675                        _ => {}
1676                    }
1677                    if self.frame().stack.is_empty() {
1678                        break;
1679                    }
1680                }
1681                self.push(top);
1682            }
1683            Throw => {
1684                let value = self.pop();
1685                return Err(Signal::Throw(value));
1686            }
1687            ThrowError => {
1688                let name = self.atom_text(a as usize);
1689                let (class, message) = match b {
1690                    0 => ("TypeError", format!("'{name}' is read-only")),
1691                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
1692                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
1693                    _ => ("TypeError", format!("invalid operation on '{name}'")),
1694                };
1695                return Err(Signal::Throw(self.make_error(class, &message)));
1696            }
1697            Return => {
1698                let value = self.pop();
1699                return Ok(Step::Return(value));
1700            }
1701            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
1702
1703            // -- calls ------------------------------------------------------
1704            Call | Call0 | Call1 | Call2 | Call3 => {
1705                let argc = self.argc_operand(op, a);
1706                let args = self.pop_n(argc);
1707                let callee = self.pop();
1708                // A plain call has no receiver; the callee decides what to do with
1709                // `undefined` (a sloppy function substitutes the global object).
1710                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
1711                    self.push(result);
1712                }
1713            }
1714            CallConstructor => {
1715                // `constructor this_obj args… -> object`. The duplicated
1716                // constructor is `new.target`; this milestone does not expose it,
1717                // so the extra copy is simply consumed here.
1718                let argc = a as usize;
1719                let args = self.pop_n(argc);
1720                let new_target = self.pop();
1721                let callee = self.pop();
1722                let result = self.construct(callee, new_target, args)?;
1723                self.push(result);
1724            }
1725            CallMethod => {
1726                let argc = a as usize;
1727                let args = self.pop_n(argc);
1728                let callee = self.pop();
1729                let this = self.pop();
1730                if let Some(result) = self.call_or_push(callee, this, args)? {
1731                    self.push(result);
1732                }
1733            }
1734            TailCall | TailCallMethod => {
1735                // `tail_call` is `call` whose result is returned immediately — the
1736                // reference jumps straight to `done` instead of storing the value and
1737                // running on. The callee still gets its own frame, so deep tail
1738                // recursion hits the stack limit exactly like plain recursion does;
1739                // marking this frame lets the return path unwind without needing
1740                // instructions after the call.
1741                let argc = if op == TailCallMethod {
1742                    a as usize
1743                } else {
1744                    self.argc_operand(op, a)
1745                };
1746                let args = self.pop_n(argc);
1747                let callee = self.pop();
1748                let this = if op == TailCallMethod {
1749                    self.pop()
1750                } else {
1751                    Value::Undefined
1752                };
1753                if let Value::Object(function) = &callee
1754                    && let Some((code, env)) = bytecode_of(function)
1755                {
1756                    self.frame_mut().tail = true;
1757                    self.push_frame(code, env, this, args, callee)?;
1758                    return Ok(Step::Continue);
1759                }
1760                // A native callee has no frame to reuse, so its value is simply
1761                // returned.
1762                let value = self.call_value(callee, this, args)?;
1763                return Ok(Step::Return(value));
1764            }
1765
1766            // -- objects ----------------------------------------------------
1767            SpecialObject => {
1768                let value = self.special_object(a)?;
1769                self.push(value);
1770            }
1771            GetLength => {
1772                // `get_length` is the `.length` read; an array and a string answer
1773                // from their own length, anything else from the property.
1774                let target = self.pop();
1775                let value = match &target {
1776                    Value::Object(object) => match object.array_length() {
1777                        Some(length) => Value::Int(length as i32),
1778                        None => self.read_field(&target, "length")?,
1779                    },
1780                    Value::String(text) => Value::Int(text.utf16_len() as i32),
1781                    _ => self.read_field(&target, "length")?,
1782                };
1783                self.push(value);
1784            }
1785            GetField | GetField2 => {
1786                let object = self.pop();
1787                let key = self.atom_text(a as usize);
1788                let value = self.read_field(&object, &key)?;
1789                if op == GetField2 {
1790                    self.push(object);
1791                }
1792                self.push(value);
1793            }
1794            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
1795                let key = self.pop();
1796                let object = self.pop();
1797                let text = self.propkey_of(&key);
1798                let value = self.read_field(&object, &text)?;
1799                if matches!(op, GetArrayEl2 | GetArrayEl3) {
1800                    self.push(object);
1801                }
1802                if op == GetArrayEl3 {
1803                    self.push(key);
1804                }
1805                self.push(value);
1806            }
1807            PutField => {
1808                let value = self.pop();
1809                let object = self.pop();
1810                let key = self.atom_text(a as usize);
1811                self.write_field(&object, &key, value)?;
1812            }
1813            PutArrayEl => {
1814                let value = self.pop();
1815                let key = self.pop();
1816                let object = self.pop();
1817                let text = self.propkey_of(&key);
1818                self.write_field(&object, &text, value)?;
1819            }
1820            DefineField => {
1821                let value = self.pop();
1822                let object = self.pop();
1823                let key = self.atom_text(a as usize);
1824                // `{m: function(){}}` names the function `m`, the same way assigning
1825                // it to a property does. Without this the frame is anonymous and a
1826                // stack trace reads `at  (file:1:2)`.
1827                self.set_function_name(&value, &key);
1828                if let Some(target) = object.as_object() {
1829                    // Only an *array* stores into the element vector. A numeric key
1830                    // on an ordinary object is an ordinary property, which is what
1831                    // makes `{1: 'a'}` iterate as a key rather than disappear.
1832                    let stored = target.is_array()
1833                        && array_index(&key)
1834                            .is_some_and(|index| target.array_set(index as usize, value.clone()));
1835                    if !stored {
1836                        target.define_data(&key, value);
1837                    }
1838                }
1839                self.push(object);
1840            }
1841            DefineArrayEl => {
1842                // `obj key value -> obj key`
1843                let value = self.pop();
1844                let key = self.pop();
1845                let object = self.peek(0);
1846                let text = self.propkey_of(&key);
1847                self.write_field(&object, &text, value)?;
1848                self.push(key);
1849            }
1850            DefineMethod => {
1851                let function = self.pop();
1852                let object = self.pop();
1853                let key = self.atom_text(a as usize);
1854                self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
1855                if let Some(array) = object.as_object() {
1856                    define_function_property(array, &key, function, b);
1857                }
1858                self.push(object);
1859            }
1860            DefineMethodComputed => {
1861                let function = self.pop();
1862                let key = self.pop();
1863                let object = self.pop();
1864                let text = self.propkey_of(&key);
1865                self.set_function_name(&function, &key_with_accessor_prefix(&text, a));
1866                if let Some(array) = object.as_object() {
1867                    define_function_property(array, &text, function, a);
1868                }
1869                self.push(object);
1870            }
1871            SetProto => {
1872                let proto = self.pop();
1873                let object = self.pop();
1874                if let Some(target) = object.as_object() {
1875                    target.set_proto(proto.as_object().cloned());
1876                }
1877                self.push(object);
1878            }
1879            CopyDataProperties => {
1880                let exclusion = self.pop();
1881                let source = self.pop();
1882                let target = self.peek(0);
1883                self.copy_properties(&target, &source, &exclusion)?;
1884                self.push(source);
1885                self.push(exclusion);
1886            }
1887            ToPropkey => {
1888                let value = self.pop();
1889                let key = self.propkey_of(&value);
1890                self.push(self.string(key));
1891            }
1892            SetName => {
1893                let function = self.peek(0);
1894                let name = self.atom_text(a as usize);
1895                self.set_function_name(&function, &name);
1896            }
1897            SetNameComputed => {
1898                let key = self.peek(1);
1899                let function = self.peek(0);
1900                let name = self.propkey_of(&key);
1901                self.set_function_name(&function, &name);
1902            }
1903
1904            // -- arrays -----------------------------------------------------
1905            ArrayFrom => {
1906                let count = a as usize;
1907                let elements = self.pop_n(count);
1908                let array = self.new_array(elements);
1909                self.push(Value::Object(array));
1910            }
1911            Append => {
1912                // `array index iterable -> array new_index`
1913                let iterable = self.pop();
1914                self.pop();
1915                let array = self.peek(0);
1916                let added = self.append_enumerate(&array, &iterable)?;
1917                self.push(Value::Int(added));
1918            }
1919
1920            // -- iteration --------------------------------------------------
1921            ForInStart => {
1922                let object = self.realm.global.clone();
1923                let _ = &object;
1924                let value = self.pop();
1925                let record = self.for_in_record(&value);
1926                self.push(Value::Object(record));
1927            }
1928            ForInNext => {
1929                // `record -> record key done`. The flag is *done*, not "found":
1930                // the compiler tests it with `if_false` to jump back into the body,
1931                // so reporting `true` while keys remain would end the loop at once.
1932                let record = self.peek(0);
1933                match self.for_in_advance(&record) {
1934                    Some(key) => {
1935                        let text = self.string(key);
1936                        self.push(text);
1937                        self.push(Value::Bool(false));
1938                    }
1939                    None => {
1940                        self.push(Value::Undefined);
1941                        self.push(Value::Bool(true));
1942                    }
1943                }
1944            }
1945            ForOfStart => {
1946                let value = self.pop();
1947                let iterator = self.get_iterator(&value)?;
1948                self.push(iterator.object);
1949                self.push(iterator.next);
1950                self.push(Value::CatchOffset(0));
1951            }
1952            ForOfNext => {
1953                let offset = b as usize;
1954                let _ = offset;
1955                // `iter next catch_offset -> iter next catch_offset value done`
1956                // `iter next catch_offset -> iter next catch_offset value done`
1957                let iterator = Iterator {
1958                    object: self.peek(2),
1959                    next: self.peek(1),
1960                };
1961                let (value, done) = self.iterator_step(&iterator)?;
1962                self.push(value);
1963                self.push(Value::Bool(done));
1964            }
1965            IteratorClose => {
1966                // `iter next catch_offset ->`
1967                self.pop();
1968                self.pop();
1969                self.pop();
1970            }
1971            ForAwaitOfStart => {
1972                return Err(Signal::Throw(
1973                    self.make_error("TypeError", "for await is not implemented yet"),
1974                ));
1975            }
1976
1977            Delete => {
1978                // `delete obj[key]`, where the key was just pushed. Deleting an array
1979                // index leaves a *hole* rather than closing the gap, and a
1980                // non-configurable property answers `false` and stays.
1981                let key = self.pop();
1982                let target = self.pop();
1983                let key = self.propkey_of(&key);
1984                let deleted = match &target {
1985                    Value::Object(object) => {
1986                        let object = object.clone();
1987                        self.delete_property(&object, &key)
1988                    }
1989                    // A string's `length` and its index properties are
1990                    // non-configurable, so deleting one answers `false`.
1991                    Value::String(text) => {
1992                        !(key == "length"
1993                            || array_index(&key)
1994                                .is_some_and(|index| (index as usize) < text.utf16_len()))
1995                    }
1996                    // Any other primitive has no own properties; deleting nothing
1997                    // succeeds.
1998                    _ => true,
1999                };
2000                self.push(Value::Bool(deleted));
2001            }
2002
2003            // -- exceptions and bookkeeping ---------------------------------
2004            Fclosure | Fclosure8 => {
2005                let value = self.closure(a as usize)?;
2006                self.push(value);
2007            }
2008
2009            other => {
2010                let name = other.info().name;
2011                return Err(Signal::Throw(self.make_error(
2012                    "InternalError",
2013                    &format!("{name} is not implemented yet"),
2014                )));
2015            }
2016        }
2017        Ok(Step::Continue)
2018    }
2019
2020    // -- operand helpers ----------------------------------------------------
2021
2022    /// The slot index an operand names, taking short forms into account.
2023    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
2024        use Opcode::*;
2025        match op {
2026            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
2027            | SetVarRef0 => 0,
2028            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
2029            | SetVarRef1 => 1,
2030            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
2031            | SetVarRef2 => 2,
2032            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
2033            | SetVarRef3 => 3,
2034            _ => a as usize,
2035        }
2036    }
2037
2038    /// The argument count of a call, taking `call0`…`call3` into account.
2039    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
2040        use Opcode::*;
2041        match op {
2042            Call0 => 0,
2043            Call1 => 1,
2044            Call2 => 2,
2045            Call3 => 3,
2046            _ => a as usize,
2047        }
2048    }
2049
2050    fn atom_text(&self, index: usize) -> String {
2051        self.frame()
2052            .code
2053            .code
2054            .atoms
2055            .get(index)
2056            .map(|atom| match atom {
2057                Atom::Str(text) => text.clone(),
2058                Atom::Index(value) => value.to_string(),
2059            })
2060            .unwrap_or_default()
2061    }
2062
2063    fn constant(&self, index: usize) -> JsResult<Value> {
2064        let constant = self.frame().code.code.cpool.get(index);
2065        Ok(match constant {
2066            Some(Constant::Number(number)) => Value::Float(*number),
2067            Some(Constant::String(text)) => self.string(text.clone()),
2068            Some(Constant::Function(_)) => {
2069                return Err(Signal::Throw(
2070                    self.make_error("InternalError", "a bare function constant"),
2071                ));
2072            }
2073            _ => Value::Undefined,
2074        })
2075    }
2076
2077    /// The reference cell a closure-variable slot names.
2078    ///
2079    /// Two kinds of binding share this addressing: a genuine closure variable
2080    /// (captured from an enclosing function) lives in this frame's environment,
2081    /// while a *declared global* lives in the realm so that a script, a function
2082    /// declaration and their uses all see one binding. A plain `Global` — an
2083    /// undeclared name that may be satisfied by the global object — has no cell at
2084    /// all, which is how `typeof x` still works for a name that does not exist.
2085    /// The reference cell a closure-variable slot names.
2086    ///
2087    /// The environment is resolved once, when the closure is built, and this is
2088    /// just the lookup afterwards. A *declared global* is in there too, pointing at
2089    /// the realm's cell, so a script, a hoisted function declaration and their uses
2090    /// all share one binding. A plain `Global` — a name the script never declared —
2091    /// is read and written through `get_var`/`put_var` by name instead, which is
2092    /// what lets the global object satisfy it.
2093    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
2094        self.frame().env.cells.get(slot).cloned()
2095    }
2096
2097    /// Whether `slot` refers to a global binding through the reference table.
2098    ///
2099    /// A global's cell in the closure environment only exists so the slot has
2100    /// something to point at; the binding itself lives on the global object (a `var`)
2101    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
2102    /// be routed, not performed on the placeholder.
2103    fn is_global_slot(&self, slot: usize) -> bool {
2104        self.frame()
2105            .code
2106            .code
2107            .closure_vars
2108            .get(slot)
2109            .is_some_and(|c| {
2110                matches!(
2111                    c.closure_type,
2112                    ClosureType::GlobalDecl
2113                        | ClosureType::Global
2114                        | ClosureType::GlobalRef
2115                        | ClosureType::ModuleDecl
2116                        | ClosureType::ModuleImport
2117                )
2118            })
2119    }
2120
2121    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
2122        if self.is_global_slot(slot) {
2123            return self.get_global(slot);
2124        }
2125        Ok(self
2126            .var_ref_cell(slot)
2127            .map(|cell| cell.get())
2128            .unwrap_or(Value::Undefined))
2129    }
2130
2131    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
2132        // A function declaration is hoisted by storing into a global reference before
2133        // the body runs, so this path is also what puts it on the global object.
2134        if self.is_global_slot(slot) {
2135            return self.put_global(slot, value);
2136        }
2137        if let Some(cell) = self.var_ref_cell(slot) {
2138            cell.set(value);
2139        }
2140        Ok(())
2141    }
2142
2143    // -- closures -----------------------------------------------------------
2144
2145    /// Build the closure for the function constant `index`.
2146    ///
2147    /// Every entry in the child's closure table names where its binding lives in
2148    /// *this* frame: a local or argument slot that was marked captured, or a cell
2149    /// this frame is itself holding. That is how a variable three functions deep
2150    /// stays one binding.
2151    fn closure(&mut self, index: usize) -> JsResult<Value> {
2152        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
2153        else {
2154            return Err(Signal::Throw(
2155                self.make_error("InternalError", "fclosure of a non-function"),
2156            ));
2157        };
2158        let mut cells = Vec::with_capacity(function.closure_vars.len());
2159        for closure_var in &function.closure_vars {
2160            let cell = match closure_var.closure_type {
2161                ClosureType::Arg => {
2162                    let slot = closure_var.var_idx as usize;
2163                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
2164                }
2165                ClosureType::Local => {
2166                    let slot = closure_var.var_idx as usize;
2167                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
2168                }
2169                ClosureType::Ref | ClosureType::GlobalRef => {
2170                    // A `Ref` names a cell in this frame's own closure table; a
2171                    // `GlobalRef` also starts there, then resolves by name below.
2172                    let slot = closure_var.var_idx as usize;
2173                    if let Some(cell) = self.frame().env.cells.get(slot) {
2174                        cells.push(cell.clone());
2175                        continue;
2176                    }
2177                    -1
2178                }
2179                _ => -1,
2180            };
2181            if cell >= 0 {
2182                let cell = self.frame().cells[cell as usize].clone();
2183                cells.push(cell);
2184                continue;
2185            }
2186            // A global: the cell is created on demand and shared through the realm,
2187            // so every function sees one binding.
2188            let name = closure_var.name.clone();
2189            let cell = match self.realm.globals.get(&name) {
2190                Some(cell) => cell.clone(),
2191                None => {
2192                    let cell = self.new_cell(Value::Undefined);
2193                    self.realm.globals.insert(name.clone(), cell.clone());
2194                    cell
2195                }
2196            };
2197            cells.push(cell);
2198        }
2199        let name = function.name.clone();
2200        let length = function.args.len() as u32;
2201        let code = Gc::new(self.heap, CompiledCode::new(*function));
2202        let env = Gc::new(self.heap, ClosureEnv { cells });
2203        let object = JsObject::function(
2204            self.heap,
2205            Some(self.realm.function_proto.clone()),
2206            Callable::Bytecode { code, env },
2207        );
2208        object.define(
2209            "length",
2210            Property::with_attributes(Value::Int(length as i32), false, false),
2211        );
2212        if !name.is_empty() {
2213            object.define(
2214                "name",
2215                Property::with_attributes(self.string(name), false, false),
2216            );
2217        }
2218        self.install_function_prototype(&object);
2219        Ok(Value::Object(object))
2220    }
2221
2222    // -- conversions used by the operators ----------------------------------
2223
2224    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
2225        // `+x` is `ToNumber`, which for a string parses it and for an object runs
2226        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
2227        // string, which then behaves differently in every later comparison.
2228        match value {
2229            Value::Int(_) | Value::Float(_) => Ok(value),
2230            other => Ok(Value::Float(self.to_js_number(&other)?)),
2231        }
2232    }
2233
2234    fn numeric(&mut self, value: Value) -> JsResult<Value> {
2235        // `ToNumber` on an object runs `ToPrimitive` first, which is how
2236        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
2237        // heard at all. Reading the object's own tag instead (`other.to_number()`)
2238        // turned the whole operand into `NaN` and swallowed the exception.
2239        match value {
2240            Value::Int(_) | Value::Float(_) => Ok(value),
2241            other => Ok(Value::Float(self.to_js_number(&other)?)),
2242        }
2243    }
2244
2245    fn binary_add(&mut self) -> JsResult<()> {
2246        let right = self.pop();
2247        let left = self.pop();
2248        // `+` concatenates when either operand is a string *after* `ToPrimitive`.
2249        let left = self.primitive_of(left)?;
2250        let right = self.primitive_of(right)?;
2251        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
2252            let text = format!("{}{}", left.to_js_string(), right.to_js_string());
2253            self.push(self.string(text));
2254            return Ok(());
2255        }
2256        let left = self.numeric(left)?;
2257        let right = self.numeric(right)?;
2258        self.push(add_numbers(left, right));
2259        Ok(())
2260    }
2261
2262    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
2263        self.to_primitive(value, Hint::Default)
2264    }
2265
2266    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
2267    ///
2268    /// The order depends on the hint: the "number" order tries `valueOf` first and
2269    /// `toString` second, the "string" order the other way round, and the default
2270    /// hint uses the number order. A result that is still an object is a `TypeError`,
2271    /// because no built-in `valueOf`/`toString` returns one.
2272    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
2273        let Value::Object(object) = &value else {
2274            return Ok(value);
2275        };
2276        let order: [&str; 2] = match hint {
2277            Hint::String => ["toString", "valueOf"],
2278            Hint::Number | Hint::Default => ["valueOf", "toString"],
2279        };
2280        let receiver = object.clone();
2281        for method in order {
2282            if let Some(function) = self.get_property(&receiver, method)?
2283                && matches!(&function, Value::Object(object) if object.is_callable())
2284            {
2285                let result =
2286                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
2287                if !matches!(result, Value::Object(_)) {
2288                    return Ok(result);
2289                }
2290            }
2291        }
2292        Err(self.type_error("cannot convert object to primitive value"))
2293    }
2294
2295    /// `ToString` with the object case going through `ToPrimitive`.
2296    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
2297        if matches!(value, Value::Object(_)) {
2298            let primitive = self.to_primitive(value.clone(), Hint::String)?;
2299            return Ok(primitive.to_js_string());
2300        }
2301        Ok(value.to_js_string())
2302    }
2303
2304    /// `ToNumber` with the object case going through `ToPrimitive`.
2305    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
2306        if matches!(value, Value::Object(_)) {
2307            let primitive = self.to_primitive(value.clone(), Hint::Number)?;
2308            return Ok(primitive.to_number());
2309        }
2310        Ok(value.to_number())
2311    }
2312
2313    fn propkey_of(&mut self, value: &Value) -> String {
2314        match value {
2315            Value::Int(_) | Value::Float(_) => number_to_string(value.to_number()),
2316            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
2317            // falling back to its `ToString` would print `[object Object]`.
2318            Value::Object(_) => self
2319                .to_js_string(value)
2320                .unwrap_or_else(|_| "[object Object]".to_string()),
2321            other => other.to_js_string(),
2322        }
2323    }
2324
2325    // -- object operations used by instructions -----------------------------
2326
2327    fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
2328        let Value::Object(object) = object else {
2329            // Reading a property of `undefined`/`null` is the classic TypeError.
2330            if object.is_nullish() {
2331                return Err(Signal::Throw(self.make_error(
2332                    "TypeError",
2333                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
2334                )));
2335            }
2336            // A string has `length` and index access without being boxed.
2337            if let Value::String(text) = object {
2338                if key == "length" {
2339                    return Ok(Value::Int(text.utf16_len() as i32));
2340                }
2341                if let Some(index) = array_index(key) {
2342                    let units: Vec<u16> = text.as_str().encode_utf16().collect();
2343                    return Ok(match units.get(index as usize) {
2344                        Some(unit) => {
2345                            let character = String::from_utf16_lossy(&[*unit]);
2346                            self.string(character)
2347                        }
2348                        None => Value::Undefined,
2349                    });
2350                }
2351            }
2352            // A property of a primitive is looked up on its prototype: this is what
2353            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
2354            let prototype = match object {
2355                Value::String(_) => self.realm.string_proto.clone(),
2356                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
2357                Value::Bool(_) => self.realm.boolean_proto.clone(),
2358                _ => None,
2359            };
2360            if let Some(prototype) = prototype
2361                && let Some(value) = self.get_property(&prototype, key)?
2362            {
2363                return Ok(value);
2364            }
2365            return Ok(Value::Undefined);
2366        };
2367        Ok(self.get_property(object, key)?.unwrap_or(Value::Undefined))
2368    }
2369
2370    fn write_field(&mut self, object: &Value, key: &str, value: Value) -> JsResult<()> {
2371        let Value::Object(object) = object else {
2372            return Err(Signal::Throw(self.make_error(
2373                "TypeError",
2374                &format!("cannot set property '{key}' of {}", object.to_js_string()),
2375            )));
2376        };
2377        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
2378        let on_failure = if self.frame().code.code.strict {
2379            DeleteFailure::Throw
2380        } else {
2381            DeleteFailure::Ignore
2382        };
2383        self.set_property_with(object, key, value, on_failure)
2384    }
2385
2386    /// `a == b`, the coercing comparison.
2387    ///
2388    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
2389    /// which is what makes `[] == ""` true: `[]` becomes `""` via
2390    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
2391    /// because the conversion is allowed to call script code, so the two primitive
2392    /// operands are handed back to it.
2393    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
2394        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
2395            return Ok(left.loose_equals(&right));
2396        }
2397        // `null == undefined` holds even though neither is an object.
2398        if matches!(left, Value::Undefined | Value::Null)
2399            && matches!(right, Value::Undefined | Value::Null)
2400        {
2401            return Ok(true);
2402        }
2403        if matches!(left, Value::Undefined | Value::Null)
2404            || matches!(right, Value::Undefined | Value::Null)
2405        {
2406            return Ok(false);
2407        }
2408        // Two objects compare by identity. Only an object *against a primitive* is
2409        // converted, which is why `{} == {}` is false while `[] == ""` is true.
2410        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
2411            return Ok(a.ptr_eq(b));
2412        }
2413        let left = self.to_primitive(left, Hint::Default)?;
2414        let right = self.to_primitive(right, Hint::Default)?;
2415        Ok(left.loose_equals(&right))
2416    }
2417
2418    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
2419        let Value::Object(object) = object else {
2420            return Err(Signal::Throw(
2421                self.make_error("TypeError", "cannot use 'in' on a non-object"),
2422            ));
2423        };
2424        let text = self.propkey_of(key);
2425        if object.own_property(&text).is_some() {
2426            return Ok(true);
2427        }
2428        // An array hole is an index that exists as a slot but not as a property, so
2429        // `1 in [1,,3]` is `false` even though reading `a[1]` yields `undefined`.
2430        if let Some(index) = array_index(&text)
2431            && object
2432                .array_get(index as usize)
2433                .is_some_and(|value| !matches!(value, Value::Hole))
2434        {
2435            return Ok(true);
2436        }
2437        Ok(lookup(object, &text).is_some())
2438    }
2439
2440    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
2441        let Value::Object(target) = object else {
2442            return Ok(false);
2443        };
2444        let Value::Object(function) = constructor else {
2445            return Err(Signal::Throw(self.make_error(
2446                "TypeError",
2447                "right-hand side of 'instanceof' is not callable",
2448            )));
2449        };
2450        let prototype = self.get_property(function, "prototype")?;
2451        let Some(Value::Object(prototype)) = prototype else {
2452            return Ok(false);
2453        };
2454        Ok(target
2455            .chain()
2456            .iter()
2457            .any(|ancestor| ancestor.ptr_eq(&prototype)))
2458    }
2459
2460    fn copy_properties(
2461        &mut self,
2462        target: &Value,
2463        source: &Value,
2464        _exclusion: &Value,
2465    ) -> JsResult<()> {
2466        let (Some(target), Value::Object(source)) = (target.as_object(), source) else {
2467            // Spreading `undefined`/`null` is a no-op, and spreading a primitive
2468            // copies nothing that a script can observe here.
2469            return Ok(());
2470        };
2471        let mut keys = source.own_enumerable_keys();
2472        if let Some(length) = source.array_length() {
2473            keys.retain(|key| key != "length");
2474            for index in 0..length {
2475                if let Some(value) = source.array_get(index) {
2476                    target.define_data(&index.to_string(), value);
2477                }
2478            }
2479        }
2480        for key in keys {
2481            if let Some(property) = source.own_property(&key)
2482                && let Some(value) = property.value
2483            {
2484                target.define_data(&key, value);
2485            }
2486        }
2487        Ok(())
2488    }
2489
2490    // -- iteration ---------------------------------------------------------
2491
2492    /// Build the key list a `for-in` loop walks.
2493    ///
2494    /// The order is the specification's: integer-like keys in ascending numeric
2495    /// order, then the string keys in insertion order, own properties before
2496    /// inherited ones, and a shadowed key only appears once.
2497    fn for_in_record(&mut self, value: &Value) -> Gc<JsObject> {
2498        let record = self.new_object(None);
2499        let mut keys: Vec<String> = Vec::new();
2500        if let Value::Object(object) = value {
2501            let mut chain = vec![object.clone()];
2502            chain.extend(object.chain());
2503            for object in chain {
2504                let mut own = object.own_enumerable_keys();
2505                if let Some(length) = object.array_length() {
2506                    own.retain(|key| key != "length");
2507                    for index in 0..length {
2508                        if object.array_get(index).is_some() {
2509                            own.push(index.to_string());
2510                        }
2511                    }
2512                }
2513                for key in own {
2514                    if !keys.contains(&key) {
2515                        keys.push(key);
2516                    }
2517                }
2518            }
2519        }
2520        let indices: Vec<String> = {
2521            let mut numeric: Vec<u32> = keys.iter().filter_map(|k| array_index(k)).collect();
2522            numeric.sort_unstable();
2523            numeric.into_iter().map(|n| n.to_string()).collect()
2524        };
2525        let strings: Vec<String> = keys
2526            .into_iter()
2527            .filter(|key| array_index(key).is_none())
2528            .collect();
2529        let mut ordered = indices;
2530        ordered.extend(strings);
2531        for (index, key) in ordered.into_iter().enumerate() {
2532            record.define_data(&index.to_string(), self.string(key));
2533        }
2534        record.define_data("__index", Value::Int(0));
2535        record
2536    }
2537
2538    fn for_in_advance(&mut self, record: &Value) -> Option<String> {
2539        let Value::Object(record) = record else {
2540            return None;
2541        };
2542        let index = record
2543            .own_property("__index")
2544            .and_then(|property| property.value)
2545            .map(|value| value.to_int32())
2546            .unwrap_or(0);
2547        match record.own_property(&index.to_string()) {
2548            Some(property) => {
2549                record.define_data("__index", Value::Int(index + 1));
2550                property.value.map(|value| value.to_js_string())
2551            }
2552            None => None,
2553        }
2554    }
2555
2556    /// The iterator for `for-of`: the object and its `next` method.
2557    ///
2558    /// An object that already carries a `next` method is used as it is — that is what
2559    /// `arr.values()` returns — and only arrays and strings get the built-in
2560    /// sequence iterator.
2561    fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
2562        // An existing iterator: `for (x of arr.entries())`.
2563        if let Value::Object(object) = value {
2564            if let Some(next) = self.get_property(object, "next")?
2565                && matches!(&next, Value::Object(function) if object.is_callable() || function.is_callable())
2566            {
2567                return Ok(Iterator {
2568                    object: value.clone(),
2569                    next,
2570                });
2571            }
2572        }
2573        if let Value::Object(object) = value
2574            && object.is_array()
2575        {
2576            let length = object.array_length().unwrap_or(0);
2577            let iterator = self.new_object(None);
2578            iterator.define_data("target", value.clone());
2579            iterator.define_data("__length", Value::Int(length as i32));
2580            iterator.define_data("__index", Value::Int(0));
2581            return Ok(Iterator {
2582                object: Value::Object(iterator.clone()),
2583                next: Value::Undefined,
2584            });
2585        }
2586        if let Value::String(text) = value {
2587            let iterator = self.new_object(None);
2588            let chars: Vec<Value> = (0..text.utf16_len())
2589                .map(|index| self.string(text.as_str().get(index..index + 1).unwrap_or("")))
2590                .collect();
2591            let array = self.new_array(chars);
2592            iterator.define_data("target", Value::Object(array));
2593            iterator.define_data("__length", Value::Int(0));
2594            iterator.define_data("__index", Value::Int(0));
2595            return Ok(Iterator {
2596                object: Value::Object(iterator.clone()),
2597                next: Value::Undefined,
2598            });
2599        }
2600        Err(Signal::Throw(
2601            self.make_error("TypeError", "value is not iterable"),
2602        ))
2603    }
2604
2605    /// One step of an internal iterator: the value and whether it is exhausted.
2606    fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
2607        // A real iterator (`next` is a function) answers with a result object.
2608        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
2609            let result =
2610                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
2611            let Some(result) = result.as_object().cloned() else {
2612                return Err(self.type_error("iterator result is not an object"));
2613            };
2614            let done = self
2615                .get_property(&result, "done")?
2616                .is_some_and(|value| value.to_boolean());
2617            let value = self
2618                .get_property(&result, "value")?
2619                .unwrap_or(Value::Undefined);
2620            return Ok((value, done));
2621        }
2622        let Value::Object(object) = &iterator.object else {
2623            return Ok((Value::Undefined, true));
2624        };
2625        let Some(target) = object.own_property("target").and_then(|p| p.value) else {
2626            return Ok((Value::Undefined, true));
2627        };
2628        let index = object
2629            .own_property("__index")
2630            .and_then(|p| p.value)
2631            .map(|v| v.to_int32())
2632            .unwrap_or(0);
2633        let Value::Object(sequence) = &target else {
2634            return Ok((Value::Undefined, true));
2635        };
2636        if index as usize >= sequence.array_length().unwrap_or(0) {
2637            return Ok((Value::Undefined, true));
2638        }
2639        object.define_data("__index", Value::Int(index + 1));
2640        // Iteration yields `undefined` for a hole — `[...[1,,3]]` is
2641        // `[1, undefined, 3]` with a real element in the middle, because the spread
2642        // stores whatever the iterator produced.
2643        Ok((
2644            match sequence.array_get(index as usize) {
2645                Some(Value::Hole) | None => Value::Undefined,
2646                Some(value) => value,
2647            },
2648            false,
2649        ))
2650    }
2651
2652    /// Append every element of `iterable` to `array`, returning how many.
2653    /// `[...iterable]`: append everything the iterator yields, and answer the next
2654    /// index.
2655    ///
2656    /// This goes through the same iterator machinery `for-of` uses rather than copying
2657    /// an array's elements, because a spread source is any iterable: a string spreads
2658    /// into its characters and an array iterator spreads into its results. Handling
2659    /// only arrays made `[..."ab"]` come out empty with no error at all.
2660    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
2661        let Some(target) = array.as_object().cloned() else {
2662            return Ok(0);
2663        };
2664        let start = target.array_length().unwrap_or(0);
2665        let mut added = 0;
2666        let iterator = self.get_iterator(iterable)?;
2667        loop {
2668            let (value, done) = self.iterator_step(&iterator)?;
2669            if done {
2670                break;
2671            }
2672            target.array_set(start + added, value);
2673            added += 1;
2674        }
2675        Ok((start + added) as i32)
2676    }
2677
2678    /// How an uncaught exception is reported.
2679    ///
2680    /// The reference reports a pending exception through `JS_PrintValue`, which ends
2681    /// up calling the thrown value's `toString`, so `throw new TypeError("x")` prints
2682    /// `TypeError: x`. Reading `name`/`message` off the object directly got this wrong
2683    /// two ways: `name` usually lives on the prototype rather than on the instance, and
2684    /// a thrown non-error object was not consulted at all, coming out as
2685    /// `[object Object]`. Routing through `ToString` keeps every case on one path and
2686    /// honours a user-defined `toString`, as the reference does.
2687    ///
2688    /// A `toString` that throws must not take the reporter down with it, so that case
2689    /// falls back to the type-level rendering. The reference's printer also walks into
2690    /// plain objects (`throw 1, {a:1}` prints `{ a: 1 }`); that formatting is a gap
2691    /// shared with `console.log`.
2692    pub fn describe_exception(&mut self, value: &Value) -> String {
2693        self.to_js_string(value).unwrap_or_else(|_| display(value))
2694    }
2695
2696    /// The current call stack, formatted the way `qjs` prints `error.stack`.
2697    ///
2698    /// One `    at name (file:line:col)` line per active frame, innermost first. The
2699    /// position is the one recorded for the instruction each frame is stopped on, which
2700    /// is why the compiler builds a pc-to-position table per function: without it a
2701    /// trace could only name the function, not the line inside it.
2702    ///
2703    /// A frame whose code has no positions prints just `(file)`, matching the
2704    /// reference's output for stripped bytecode.
2705    pub fn stack_trace(&self) -> String {
2706        let mut out = String::new();
2707        for frame in self.frames.iter().rev() {
2708            let code = &frame.code.code;
2709            let file = code.filename.as_deref().unwrap_or("<input>");
2710            // The name comes from the function *object*, not from the compiled code:
2711            // an anonymous function expression is named by the property it is stored
2712            // in (`{valueOf: function(){}}`), which only the object knows.
2713            let bound_name = match &frame.callee {
2714                Value::Object(object) => {
2715                    object
2716                        .own_property("name")
2717                        .and_then(|property| match property.value {
2718                            Some(Value::String(text)) if !text.as_str().is_empty() => {
2719                                Some(text.as_str().to_string())
2720                            }
2721                            _ => None,
2722                        })
2723                }
2724                _ => None,
2725            };
2726            out.push_str("    at ");
2727            out.push_str(bound_name.as_deref().unwrap_or(&code.name));
2728            match code.position_at(frame.at as u32) {
2729                Some((line, column)) => {
2730                    out.push_str(&format!(" ({file}:{line}:{column})\n"));
2731                }
2732                None => out.push_str(&format!(" ({file})\n")),
2733            }
2734        }
2735        out
2736    }
2737
2738    /// Give an anonymous function the name of the property it is stored in.
2739    ///
2740    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
2741    /// enumerable and not configurable, and a function that already has a real name
2742    /// keeps it.
2743    ///
2744    /// "Already named" means a *non-empty* name: every function object is created with
2745    /// a `name` of `""` so the property exists on all of them, and treating that empty
2746    /// string as a name left every anonymous function nameless — which is how a stack
2747    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
2748    fn set_function_name(&mut self, function: &Value, name: &str) {
2749        let Value::Object(object) = function else {
2750            return;
2751        };
2752        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
2753            && !existing.as_str().is_empty()
2754        {
2755            return;
2756        }
2757        let text = self.string(name);
2758        object.define("name", Property::with_attributes(text, false, false));
2759    }
2760
2761    // -- global declarations -----------------------------------------------
2762
2763    /// Declare a global binding, creating its reference cell.
2764    /// Declare a `var` or function global, whose home is the global object.
2765    ///
2766    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
2767    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
2768    /// such as `print`, or a redeclaration — is left alone.
2769    pub fn declare_var_global(&mut self, name: &str) {
2770        let global = self.realm.global.clone();
2771        if global.own_property(name).is_some() {
2772            return;
2773        }
2774        global.define(
2775            name,
2776            Property {
2777                value: Some(Value::Undefined),
2778                writable: true,
2779                enumerable: true,
2780                configurable: false,
2781                ..Property::default()
2782            },
2783        );
2784    }
2785
2786    /// Declare a *lexical* global binding, which starts in its dead zone.
2787    ///
2788    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
2789    /// global object and is created when its initialiser runs.
2790    pub fn declare_global(&mut self, name: &str, is_const: bool) {
2791        if is_const {
2792            self.realm.lexical_consts.insert(name.to_string());
2793        }
2794        if !self.realm.globals.contains_key(name) {
2795            // `Uninitialized` rather than `Undefined`: the binding exists but is not
2796            // readable until its initialiser runs, and that is what `let x` before
2797            // `x = 1` has to observe.
2798            let cell = self.new_cell(Value::Uninitialized);
2799            self.realm.globals.insert(name.to_string(), cell);
2800            self.realm.declared.push(name.to_string());
2801        }
2802    }
2803}
2804
2805/// The bytecode and environment of a function object, if it is a bytecode function.
2806///
2807/// Extracted before a call so no borrow of the object is held across it.
2808fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
2809    function.with(|data| match &data.kind {
2810        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
2811        _ => None,
2812    })
2813}
2814
2815/// A native call target, extracted before the call so no borrow is held.
2816enum NativeCall {
2817    Native(NativeFn),
2818    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
2819    Bound {
2820        target: Value,
2821        this: Value,
2822        leading: Vec<Value>,
2823    },
2824}
2825
2826/// What a store does when the object refuses the write.
2827#[derive(Clone, Copy, PartialEq, Eq)]
2828pub enum DeleteFailure {
2829    /// Raise a `TypeError`, which is what strict mode and every built-in does.
2830    Throw,
2831    /// Ignore the write, which is what a sloppy-mode assignment does.
2832    Ignore,
2833}
2834
2835/// Which type `ToPrimitive` prefers when it converts an object.
2836#[derive(Clone, Copy, PartialEq, Eq)]
2837pub enum Hint {
2838    /// The default hint, which behaves like [`Hint::Number`].
2839    Default,
2840    /// `Number(obj)` and the arithmetic operators.
2841    Number,
2842    /// `String(obj)` and `ToPropertyKey`.
2843    String,
2844}
2845
2846/// Which table a binding slot indexes, for the messages that name it.
2847#[derive(Clone, Copy)]
2848enum VarSlot {
2849    Loc,
2850    Closure,
2851}
2852
2853/// An internal iterator: the sequence plus a cursor.
2854struct Iterator {
2855    object: Value,
2856    next: Value,
2857}
2858
2859/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
2860/// and plain `a` for a method.
2861///
2862/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
2863/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
2864/// reads `at get a (file:1:2)`.
2865fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
2866    match flags & 3 {
2867        1 => format!("get {key}"),
2868        2 => format!("set {key}"),
2869        _ => key.to_string(),
2870    }
2871}
2872
2873/// Define a method or accessor property, per the `define_method` flag byte.
2874///
2875/// The low two bits pick value/getter/setter and bit 2 marks the property
2876/// enumerable.
2877///
2878/// A getter and a setter arrive as two separate `define_method` instructions, and the
2879/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
2880/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
2881/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
2882/// `JS_DefineProperty`, which leaves the other half alone.
2883fn define_function_property(object: &Gc<JsObject>, key: &str, function: Value, flags: u32) {
2884    let enumerable = flags & 4 != 0;
2885    let kind = flags & 3;
2886    let existing = object.own_property(key);
2887    let property = match kind {
2888        1 => Property {
2889            getter: Some(function),
2890            // The setter half, if this literal already defined one.
2891            setter: existing
2892                .filter(Property::is_accessor)
2893                .and_then(|p| p.setter),
2894            enumerable,
2895            configurable: true,
2896            ..Property::default()
2897        },
2898        2 => Property {
2899            getter: existing
2900                .filter(Property::is_accessor)
2901                .and_then(|p| p.getter),
2902            setter: Some(function),
2903            enumerable,
2904            configurable: true,
2905            ..Property::default()
2906        },
2907        _ => Property {
2908            value: Some(function),
2909            writable: true,
2910            enumerable,
2911            configurable: true,
2912            ..Property::default()
2913        },
2914    };
2915    object.define(key, property);
2916}
2917
2918// ---------------------------------------------------------------------------
2919// Operand decoding
2920// ---------------------------------------------------------------------------
2921
2922/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
2923///
2924/// Jump operands are resolved to absolute byte offsets here, because the encoding
2925/// stores them relative to the byte after the opcode and every use site would
2926/// otherwise repeat that arithmetic.
2927fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
2928    let op = Opcode::from_u8(*code.get(pc)?)?;
2929    let info = op.info();
2930    let base = pc + 1;
2931    let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
2932    let read_u16 = |offset: usize| -> u32 {
2933        let mut value = 0u32;
2934        for index in 0..2 {
2935            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
2936        }
2937        value
2938    };
2939    let read_u32 = |offset: usize| -> u32 {
2940        let mut value = 0u32;
2941        for index in 0..4 {
2942            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
2943        }
2944        value
2945    };
2946    let jump = |offset: usize, width: usize| -> u32 {
2947        let raw = match width {
2948            1 => read_u8(offset) as u8 as i8 as i64,
2949            2 => read_u16(offset) as u16 as i16 as i64,
2950            _ => read_u32(offset) as i32 as i64,
2951        };
2952        (base as i64 + raw) as u32
2953    };
2954    let (a, b) = match info.format {
2955        OpFormat::None
2956        | OpFormat::NoneInt
2957        | OpFormat::NoneLoc
2958        | OpFormat::NoneArg
2959        | OpFormat::NoneVarRef
2960        | OpFormat::Npopx => (0, 0),
2961        OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
2962        OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
2963        OpFormat::Label8 => (jump(0, 1), 0),
2964        OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
2965            (read_u16(0), 0)
2966        }
2967        OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
2968        OpFormat::Label16 => (jump(0, 2), 0),
2969        OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
2970        OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
2971        OpFormat::I32 | OpFormat::Label => (
2972            if info.format == OpFormat::Label {
2973                jump(0, 4)
2974            } else {
2975                read_u32(0) as i32 as u32
2976            },
2977            0,
2978        ),
2979        OpFormat::AtomU8 | OpFormat::AtomLabelU8 => (read_u32(0), read_u8(4)),
2980        OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
2981            (read_u32(0), read_u16(4))
2982        }
2983    };
2984    Some((op, a, b, pc + info.size as usize))
2985}
2986
2987/// How `print` renders a value: the reference's `JS_PrintValue`.
2988///
2989/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
2990/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
2991/// The format is reproduced closely because the test suite compares output text:
2992///
2993/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
2994/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
2995/// * a cycle prints `[circular N]` with `N` the stack index of the object;
2996/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
2997///   end print as `<N empty item(s)>`;
2998/// * a string is quoted inside a container but raw at the top level, which is why
2999///   `print("x")` and `print(["x"])` differ.
3000pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
3001    // A string argument is printed raw: `js_print` converts it with `ToString`
3002    // instead of dumping it, and the quoting only appears inside a container.
3003    if let Value::String(text) = value {
3004        return text.as_str().to_string();
3005    }
3006    let mut printer = Printer {
3007        interp,
3008        out: String::new(),
3009        stack: Vec::new(),
3010    };
3011    printer.value(value, 0);
3012    printer.out
3013}
3014
3015/// The `JS_PrintValue` state: output, and the objects currently being printed.
3016struct Printer<'a, 'rt> {
3017    /// Kept for the class-name lookups that typed arrays and `Date` will need.
3018    #[allow(dead_code)]
3019    interp: &'a Interp<'rt>,
3020    out: String,
3021    stack: Vec<Gc<JsObject>>,
3022}
3023
3024impl Printer<'_, '_> {
3025    /// Depth past which a container is summarised by its class name.
3026    const MAX_DEPTH: usize = 2;
3027
3028    fn value(&mut self, value: &Value, level: usize) {
3029        match value {
3030            Value::Undefined
3031            | Value::Uninitialized
3032            | Value::Hole
3033            | Value::CatchOffset(_)
3034            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
3035            Value::Null => self.out.push_str("null"),
3036            Value::Bool(true) => self.out.push_str("true"),
3037            Value::Bool(false) => self.out.push_str("false"),
3038            Value::Int(number) => self.out.push_str(&number.to_string()),
3039            Value::Float(number) => {
3040                self.out
3041                    .push_str(&crate::value::number_to_string_for_print(*number));
3042            }
3043            Value::String(text) => self.print_string(text.as_str()),
3044            Value::Object(object) => self.object(object, level),
3045        }
3046    }
3047
3048    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
3049        // A cycle is reported rather than followed; the index is where the object
3050        // already sits in the print stack, which is what the reference shows.
3051        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
3052            self.out.push_str(&format!("[circular {index}]"));
3053            return;
3054        }
3055        if object.is_callable() {
3056            let name = object
3057                .own_property("name")
3058                .and_then(|property| property.value)
3059                .map(|value| value.to_js_string())
3060                .unwrap_or_default();
3061            if name.is_empty() {
3062                self.out.push_str("[Function (anonymous)]");
3063            } else {
3064                self.out.push_str(&format!("[Function {name}]"));
3065            }
3066            return;
3067        }
3068        if level >= Self::MAX_DEPTH {
3069            let class = if object.is_array() { "Array" } else { "Object" };
3070            self.out.push_str(&format!("[{class}]"));
3071            return;
3072        }
3073        self.stack.push(object.clone());
3074        if object.is_array() {
3075            self.array(object, level);
3076        } else {
3077            self.plain_object(object, level);
3078        }
3079        self.stack.pop();
3080    }
3081
3082    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
3083        let elements = object.array_elements().unwrap_or_default();
3084        self.out.push_str("[ ");
3085        // An interior hole means the array is "sparse": the reference prints those
3086        // as `index: value` pairs and says nothing about the holes themselves, while
3087        // a hole run at the end becomes a single `<N empty items>` note.
3088        let last_present = elements
3089            .iter()
3090            .rposition(|value| !matches!(value, Value::Hole));
3091        let has_interior_hole = match last_present {
3092            Some(last) => elements[..last]
3093                .iter()
3094                .any(|value| matches!(value, Value::Hole)),
3095            None => false,
3096        };
3097        let mut first = true;
3098        if has_interior_hole {
3099            let mut index = 0;
3100            while index < elements.len() {
3101                let value = &elements[index];
3102                if matches!(value, Value::Hole) {
3103                    index += 1;
3104                    continue;
3105                }
3106                if !first {
3107                    self.out.push_str(", ");
3108                }
3109                first = false;
3110                self.out.push_str(&format!("{index}: "));
3111                self.value(value, level + 1);
3112                index += 1;
3113            }
3114        } else {
3115            for (index, value) in elements.iter().enumerate() {
3116                if matches!(value, Value::Hole) {
3117                    continue;
3118                }
3119                if !first {
3120                    self.out.push_str(", ");
3121                }
3122                first = false;
3123                let _ = index;
3124                self.value(value, level + 1);
3125            }
3126            if let Some(last) = last_present {
3127                let trailing = elements.len() - last - 1;
3128                if trailing > 0 {
3129                    if !first {
3130                        self.out.push_str(", ");
3131                    }
3132                    self.out.push_str(&format!(
3133                        "<{trailing} empty item{}>",
3134                        if trailing > 1 { "s" } else { "" }
3135                    ));
3136                }
3137            } else if !elements.is_empty() {
3138                let count = elements.len();
3139                self.out.push_str(&format!(
3140                    "<{count} empty item{}>",
3141                    if count > 1 { "s" } else { "" }
3142                ));
3143            }
3144        }
3145        self.out.push_str(" ]");
3146    }
3147
3148    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
3149        self.out.push_str("{ ");
3150        let mut first = true;
3151        for key in object.own_keys() {
3152            let Some(property) = object.own_property(&key) else {
3153                continue;
3154            };
3155            if !property.enumerable {
3156                continue;
3157            }
3158            if !first {
3159                self.out.push_str(", ");
3160            }
3161            first = false;
3162            self.out
3163                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(&key)));
3164            self.out.push_str(": ");
3165            // An accessor has no value to dump; the reference names the half that
3166            // exists instead of calling it.
3167            if property.is_accessor() {
3168                let text = match (property.getter.is_some(), property.setter.is_some()) {
3169                    (true, true) => "[Getter/Setter]",
3170                    (false, true) => "[Setter]",
3171                    _ => "[Getter]",
3172                };
3173                self.out.push_str(text);
3174            } else {
3175                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
3176            }
3177        }
3178        self.out.push_str(" }");
3179    }
3180
3181    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
3182    fn print_string(&mut self, text: &str) {
3183        self.out.push('"');
3184        for character in text.chars() {
3185            match character {
3186                '"' => self.out.push_str("\\\""),
3187                '\\' => self.out.push_str("\\\\"),
3188                '\n' => self.out.push_str("\\n"),
3189                '\r' => self.out.push_str("\\r"),
3190                '\t' => self.out.push_str("\\t"),
3191                c if (c as u32) < 0x20 => {
3192                    self.out.push_str(&format!("\\u{:04x}", c as u32));
3193                }
3194                c => self.out.push(c),
3195            }
3196        }
3197        self.out.push('"');
3198    }
3199}
3200
3201/// How `print` renders a value.
3202///
3203/// `ToString`, except that negative zero keeps its sign — the reference's host
3204/// printer does that while `String(-0)` is `"0"`.
3205pub fn display(value: &Value) -> String {
3206    match value {
3207        Value::Float(number) => crate::value::number_to_string_for_print(*number),
3208        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
3209            "undefined".to_string()
3210        }
3211        other => other.to_js_string(),
3212    }
3213}
3214
3215// ---------------------------------------------------------------------------
3216// Numeric operators
3217// ---------------------------------------------------------------------------
3218
3219/// `a + b` keeping the `Int` representation when it fits.
3220fn add_numbers(left: Value, right: Value) -> Value {
3221    match (&left, &right) {
3222        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
3223            Some(sum) => Value::Int(sum),
3224            None => Value::Float(*a as f64 + *b as f64),
3225        },
3226        _ => Value::Float(left.to_number() + right.to_number()),
3227    }
3228}
3229
3230/// The arithmetic operators other than `+`, which needs string concatenation.
3231fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
3232    use Opcode::*;
3233    let (a, b) = (left.to_number(), right.to_number());
3234    Ok(match op {
3235        Sub => match (&left, &right) {
3236            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
3237                Some(value) => Value::Int(value),
3238                None => Value::Float(a - b),
3239            },
3240            _ => Value::Float(a - b),
3241        },
3242        Mul => Value::Float(a * b),
3243        Div => Value::Float(a / b),
3244        Mod => Value::Float(js_mod(a, b)),
3245        Pow => Value::Float(a.powf(b)),
3246        And => Value::Int(left.to_int32() & right.to_int32()),
3247        Or => Value::Int(left.to_int32() | right.to_int32()),
3248        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
3249        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
3250        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
3251        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
3252        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
3253        // fits the small-integer representation stays an `Int`; the rest become a
3254        // float, which is how the reference keeps `n >>> 0` non-negative.
3255        Shr => {
3256            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
3257            match i32::try_from(shifted) {
3258                Ok(value) => Value::Int(value),
3259                Err(_) => Value::Float(shifted as f64),
3260            }
3261        }
3262        _ => Value::Float(a),
3263    })
3264}
3265
3266/// `%`, which follows the sign of the dividend rather than Rust's.
3267fn js_mod(left: f64, right: f64) -> f64 {
3268    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
3269        return f64::NAN;
3270    }
3271    if right.is_infinite() {
3272        return left;
3273    }
3274    let remainder = left % right;
3275    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
3276    // the spec makes the sign match the dividend.
3277    if remainder == 0.0 {
3278        0.0f64.copysign(left)
3279    } else {
3280        remainder
3281    }
3282}
3283
3284fn negate(value: Value) -> Value {
3285    match value {
3286        Value::Int(0) => Value::Float(-0.0),
3287        Value::Int(i) => Value::Int(-i),
3288        other => Value::Float(-other.to_number()),
3289    }
3290}
3291
3292fn increment(value: Value) -> Value {
3293    match value {
3294        Value::Int(i) => match i.checked_add(1) {
3295            Some(next) => Value::Int(next),
3296            None => Value::Float(i as f64 + 1.0),
3297        },
3298        other => Value::Float(other.to_number() + 1.0),
3299    }
3300}
3301
3302fn decrement(value: Value) -> Value {
3303    match value {
3304        Value::Int(i) => match i.checked_sub(1) {
3305            Some(next) => Value::Int(next),
3306            None => Value::Float(i as f64 - 1.0),
3307        },
3308        other => Value::Float(other.to_number() - 1.0),
3309    }
3310}
3311
3312/// The relational operators.
3313///
3314/// Strings compare by UTF-16 code unit when both sides are strings, which is why
3315/// `"10" < "9"` is true.
3316fn compare(op: Opcode, left: Value, right: Value, interp: &Interp<'_>) -> Value {
3317    use Opcode::*;
3318    let ordering = if let (Value::String(a), Value::String(b)) = (&left, &right) {
3319        Some(a.as_str().cmp(b.as_str()))
3320    } else {
3321        let (a, b) = (left.to_number(), right.to_number());
3322        // Any comparison involving `NaN` is false, which `partial_cmp` expresses.
3323        a.partial_cmp(&b)
3324    };
3325    let _ = interp;
3326    let answer = match (op, ordering) {
3327        (_, None) => false,
3328        (Lt, Some(ordering)) => ordering.is_lt(),
3329        (Lte, Some(ordering)) => ordering.is_le(),
3330        (Gt, Some(ordering)) => ordering.is_gt(),
3331        (Gte, Some(ordering)) => ordering.is_ge(),
3332        _ => false,
3333    };
3334    Value::Bool(answer)
3335}