Skip to main content

nodejs/
host.rs

1//! The JavaScript object heap and runtime, reached from fusevm through
2//! registered builtins (`register_builtin`) and the strict numeric hook.
3//!
4//! node-js owns no VM and no JIT: the compiler lowers JS to `fusevm::Chunk`, and
5//! every JS-specific operation the VM can't do natively is a builtin call that
6//! lands here. Local variables live in `Rc<RefCell>` environments chained
7//! parent-to-child, so a nested function/closure captures its enclosing scope by
8//! reference.
9//!
10//! Value representation:
11//!   - immediate: `Value::Float` (every JS number — one IEEE-754 f64 type),
12//!     `Value::Bool` (true/false), `Value::Undef` (undefined);
13//!   - heap `Value::Obj(u32)` handles: string, array, object, function,
14//!     builtin-namespace, and the canonical `null` — the reference types.
15
16use fusevm::{Chunk, NumOp, VMResult, Value, VM};
17use indexmap::IndexMap;
18use std::cell::RefCell;
19use std::collections::HashMap;
20use std::collections::HashSet;
21use std::rc::Rc;
22use std::sync::mpsc::{Receiver, Sender};
23use std::time::{Duration, Instant};
24
25/// A unit of I/O work handed from a background I/O thread to the main-thread
26/// event loop. It is a boxed closure so `host.rs` stays agnostic of `net`/`http`:
27/// the I/O thread captures only plain `Send` data (bytes, ids, `TcpStream`s) and
28/// the closure runs the JS-touching dispatch on the main thread (where the
29/// thread-local host lives). I/O threads NEVER touch the host directly.
30pub type IoTask = Box<dyn FnOnce() -> Result<(), String> + Send>;
31
32/// Builtin ids emitted by the compiler and registered on every VM. The compiler
33/// (`compiler.rs`) and the handler table (`builtins.rs::install`) must agree on
34/// these exactly.
35pub mod ops {
36    pub const GETLOCAL: u16 = 1; // [name] -> value (scope-chain read)
37    pub const SETLOCAL: u16 = 2; // [name, value] -> value (assignment)
38    pub const DECLARE: u16 = 3; // [name, value] -> value (let/const/var into current scope)
39    pub const DELNAME: u16 = 4; // [name]
40    pub const GETATTR: u16 = 5; // [recv, name] -> value (member .x)
41    pub const SETATTR: u16 = 6; // [recv, name, value]
42    pub const GETITEM: u16 = 7; // [recv, idx] -> value (computed [k])
43    pub const SETITEM: u16 = 8; // [recv, idx, value]
44    pub const DELITEM: u16 = 9; // [recv, idx] -> Bool (delete obj[k])
45    pub const MKSTR: u16 = 10; // [parts...] -> str (concat)
46    pub const MKARR: u16 = 11; // [items...] -> array
47    pub const MKOBJ: u16 = 12; // [tag,k,v,...] -> object (tag 1 = ...spread of k)
48    pub const CALL: u16 = 13; // [name, args...] -> resolve name & call
49    pub const CALL_METHOD: u16 = 14; // [recv, name, args...]
50    pub const CALL_VALUE: u16 = 15; // [callable, args...]
51    pub const NEW: u16 = 16; // [ctor, args...] -> instance
52    pub const TRUTHY: u16 = 17; // [v] -> Bool (JS truthiness)
53    pub const TOSTR: u16 = 18; // [v] -> str via String(v)
54    pub const MKFUNC: u16 = 19; // [func_id, defaults...] -> closure
55    pub const GETITER: u16 = 20; // [iterable] -> iterator (left on stack)
56    pub const FORITER: u16 = 21; // peek iterator -> pushes value + Bool(has_next)
57    pub const FORIN_KEYS: u16 = 22; // [obj] -> array of enumerable keys
58    pub const CONTAINS: u16 = 23; // [key, obj] -> Bool (`in`)
59    pub const SIG_RETURN: u16 = 24; // [v] -> return v from the function
60    pub const BINOP: u16 = 25; // [tag, a, b] -> bitwise/shift result (JS int32 semantics)
61    pub const UNARY: u16 = 26; // [tag, v] -> unary +/~ result
62    pub const STRICT_EQ: u16 = 27; // [a, b] -> Bool (===)
63    pub const LOOSE_EQ: u16 = 28; // [a, b] -> Bool (==)
64    pub const TYPEOF: u16 = 29; // [v] -> str
65    pub const LOAD_NULL: u16 = 30; // [] -> the canonical null
66    pub const THROW: u16 = 31; // [v] -> throw
67    pub const TRY: u16 = 32; // [try_id] -> run a try/catch/finally block
68    pub const NULLISH: u16 = 33; // [v] -> Bool (v is null or undefined)
69    pub const UNPACK: u16 = 34; // [iterable, count, star] -> pushes count values
70    pub const BUILD_ARGS: u16 = 35; // [tag,val,...] -> flat array (tag 1 = ...spread)
71    pub const THIS: u16 = 36; // [] -> current `this`
72    pub const INSTANCEOF: u16 = 37; // [a, b] -> Bool
73    pub const DELPROP_NAME: u16 = 38; // [recv, name] -> Bool (delete obj.name)
74    pub const APPLY: u16 = 39; // [callable, argsArray] -> call with spread args
75    pub const APPLY_METHOD: u16 = 40; // [recv, name, argsArray] -> method call with spread
76    pub const OBJ_REST: u16 = 41; // [obj, excludedKeys] -> object of remaining keys
77    pub const DIV: u16 = 42; // [a, b] -> IEEE `a / b` (JS: x/0 = ±Infinity, 0/0 = NaN)
78    pub const MKCLASS: u16 = 43; // [parent_or_undef, ctor_fn] -> class constructor value
79    pub const DEF_MEMBER: u16 = 44; // [class, name, kind, is_static, fn] -> define method/get/set
80    pub const SUPER_CALL: u16 = 45; // [args...] -> invoke parent ctor on `this`, then init fields
81    pub const SUPER_GET: u16 = 46; // [name] -> resolve `super.name` (method up the parent chain)
82    pub const YIELD: u16 = 47; // [v] -> suspend the running generator, yield v
83    pub const PROPKEY: u16 = 48; // [v] -> property-key string (Symbol -> internal key, else String())
84    pub const NEW_TARGET: u16 = 49; // [] -> the current frame's new.target (undefined if not `new`)
85    pub const DEF_FIELD: u16 = 50; // [class, name, thunk] -> register an instance field initializer
86    pub const AWAIT: u16 = 51; // [v] -> await v (suspend the async coroutine until v settles)
87    pub const DEF_ACCESSOR: u16 = 52; // [obj, name, kind, fn] -> install a getter/setter on obj
88    pub const DBG_LINE: u16 = 53; // [line] -> DAP statement marker (debug only)
89    pub const MKBIGINT: u16 = 54; // [decimal_str] -> heap BigInt value
90    pub const MKREGEX: u16 = 55; // [pattern, flags] -> heap RegExp value
91    pub const TAG_TMPL: u16 = 56; // [tag, cooked..., raw..., n, values...] -> tagged-template call
92    pub const GET_ASYNC_ITER: u16 = 57; // [iterable] -> async iterator (for-await-of)
93    pub const ASYNC_STEP: u16 = 58; // [asyncIterator] -> Promise of {value, done}
94    pub const NUM_STEP: u16 = 59; // [tag(±1), old] -> pushes ToNumeric(old), returns old±1 (type-preserving; BigInt-aware ++/--)
95    pub const ITER_CLOSE: u16 = 60; // [iterator] -> close it (for-of break: run a generator's finally / call .return())
96    pub const TYPEOF_NAME: u16 = 61; // [name] -> str; `typeof <ident>` reads the name WITHOUT throwing (unbound -> "undefined")
97    pub const SIG_BREAK: u16 = 62; // [label|""] -> raise a Break signal and halt the chunk (break out of a `try`)
98    pub const SIG_CONTINUE: u16 = 63; // [label|""] -> raise a Continue signal and halt the chunk
99    pub const SIG_UNWIND: u16 = 64; // [tag] -> 0 none / 1 break here / 2 continue here; halts the chunk to propagate
100    pub const PUSH_SCOPE: u16 = 65; // [] -> enter a fresh block scope (`let`/`const` live here)
101    pub const POP_SCOPE: u16 = 66; // [] -> leave the innermost block scope
102    pub const COPY_SCOPE: u16 = 67; // [] -> replace the innermost block scope with a COPY (per-iteration `let`)
103    pub const DECLARE_VAR: u16 = 68; // [name, value] -> declare at FUNCTION scope, ignoring block scopes (`var`)
104    pub const NAMED_EVAL: u16 = 69; // [key, kind, fn] -> fn; SetFunctionName for a COMPUTED key (kind picks the `get `/`set ` prefix)
105    pub const POW: u16 = 70; // [a, b] -> JS `a ** b` (NOT native `Op::Pow`: IEEE pow answers 1 for `(-1) ** Infinity` and `1 ** NaN`)
106    pub const DECLARE_CONST: u16 = 71; // [name, value] -> value; like DECLARE but the binding is IMMUTABLE (`const`)
107    pub const MARK_HOLE: u16 = 72; // [arr, index] -> arr; record an ELIDED array-literal element
108    pub const SETLOCAL_STRICT: u16 = 73; // [name, value] -> value; like SETLOCAL but an UNRESOLVABLE name throws ReferenceError instead of creating a global (strict-mode PutValue)
109    pub const HOIST_VAR: u16 = 74; // [name] -> create the `var` binding as undefined IF ABSENT (hoisting)
110    pub const FORIN_ALIVE: u16 = 75; // [obj, key] -> Bool; is `key` STILL an enumerable property of `obj`? (a `for-in` body may have deleted it)
111    pub const HOIST_TDZ: u16 = 76; // [name] -> declare `name` in the CURRENT scope as UNINITIALIZED (the `let`/`const`/`class` temporal dead zone)
112    pub const NEW_SPREAD: u16 = 77; // [ctor, argsArray] -> instance; `new C(...xs)`, where the argument list is built at run time
113    pub const SUPER_CALL_SPREAD: u16 = 78; // [argsArray] -> invoke the parent ctor with a run-time argument list (`super(...xs)`)
114    pub const SUPER_SET: u16 = 89; // [name, value] -> value; `super.name = value` (setter on the parent chain, else a data write on `this`)
115    pub const YIELD_DELEGATE: u16 = 90; // [v] -> sent; `yield*`'s suspension: a forced return/throw is recorded for DELEGATE_STEP instead of raised
116    pub const DELEGATE_STEP: u16 = 91; // [iterator, sent] -> [iterator, step]; one step of `yield*` applying next / throw / return to the delegate
117    pub const MAP_ARGS: u16 = 80; // [names] -> undefined; alias a sloppy function's parameters (comma-joined) to its `arguments` object
118    pub const WITH_PUSH: u16 = 81; // [obj] -> undefined; enter a `with` scope (ToObject; nullish throws)
119    pub const WITH_GET: u16 = 82; // [name] -> value; like GETLOCAL, but a `with` object that has `name` answers first
120    pub const WITH_SET: u16 = 83; // [name, value] -> value; like SETLOCAL, `with`-aware
121    pub const WITH_SET_STRICT: u16 = 84; // [name, value] -> value; like SETLOCAL_STRICT, `with`-aware
122    pub const WITH_TYPEOF: u16 = 85; // [name] -> str; like TYPEOF_NAME, `with`-aware
123    pub const WITH_FN: u16 = 86; // [name] -> [fn, this]; the callee of `name(...)` and the `with` object that is its `this`
124    pub const CALL_THIS: u16 = 87; // [callable, this, args...] -> call with an explicit `this`
125    pub const APPLY_THIS: u16 = 88; // [callable, this, argsArray] -> call with an explicit `this` and spread args
126    pub const ITER_RESULT: u16 = 79; // [step] -> step; TypeError unless an object (`IteratorNext` step 3, after a `for await` step's await)
127}
128
129/// Per-call-site callee SOURCE TEXT, for the `TypeError` a failed call raises.
130///
131/// V8 reports the callee the way the source wrote it — `z.f is not a function`,
132/// not `f is not a function` — by re-printing the AST of the call it was
133/// evaluating. The text is therefore a static property of the SITE, so the
134/// compiler records it once per call op and nothing is carried at run time: the
135/// table is consulted only on the error path.
136///
137/// Keyed by the chunk's `op_hash` (which `ChunkBuilder::build` computes anyway)
138/// paired with the op index. `op_hash` covers the op vector but not the name
139/// pool, so two chunks that compile to the same ops with different names share a
140/// key; the consequence is confined to which receiver text an error message
141/// names, never to what a program does.
142mod call_sites {
143    use std::cell::RefCell;
144
145    thread_local! {
146        pub(super) static SITES: RefCell<rustc_hash::FxHashMap<(u64, usize), String>> =
147            RefCell::new(rustc_hash::FxHashMap::default());
148    }
149
150    /// Record every call site of a freshly built chunk.
151    pub fn register(op_hash: u64, sites: Vec<(usize, String)>) {
152        if sites.is_empty() {
153            return;
154        }
155        SITES.with(|m| {
156            let mut m = m.borrow_mut();
157            for (ip, text) in sites {
158                m.insert((op_hash, ip), text);
159            }
160        });
161    }
162
163    /// The callee text recorded for the op at `ip` of the chunk `op_hash`.
164    pub fn text(op_hash: u64, ip: usize) -> Option<String> {
165        SITES.with(|m| m.borrow().get(&(op_hash, ip)).cloned())
166    }
167
168    pub fn clear() {
169        SITES.with(|m| m.borrow_mut().clear());
170    }
171}
172
173pub use call_sites::{clear as clear_call_sites, register as register_call_sites};
174
175/// How many `for…of` / `yield*` iterators are parked on the VM stack at each
176/// `yield` op, recorded by the compiler the same way callee text is.
177///
178/// A `.return()`/`.throw()` injected at a suspension point halts the generator's
179/// chunk outright, which jumps past the loop exits that would have closed those
180/// iterators — so the halt path has to close them itself, and this is how it
181/// knows how many are there and that they are the top of the stack.
182mod yield_sites {
183    use std::cell::RefCell;
184
185    thread_local! {
186        pub(super) static DEPTHS: RefCell<rustc_hash::FxHashMap<(u64, usize), usize>> =
187            RefCell::new(rustc_hash::FxHashMap::default());
188    }
189
190    pub fn register(op_hash: u64, sites: Vec<(usize, usize)>) {
191        if sites.is_empty() {
192            return;
193        }
194        DEPTHS.with(|m| {
195            let mut m = m.borrow_mut();
196            for (ip, depth) in sites {
197                m.insert((op_hash, ip), depth);
198            }
199        });
200    }
201
202    pub fn depth(op_hash: u64, ip: usize) -> usize {
203        DEPTHS.with(|m| m.borrow().get(&(op_hash, ip)).copied().unwrap_or(0))
204    }
205
206    pub fn clear() {
207        DEPTHS.with(|m| m.borrow_mut().clear());
208    }
209}
210
211pub use yield_sites::{clear as clear_yield_sites, register as register_yield_sites};
212
213/// Every call site and yield site registered so far, as the cache stores them:
214/// `(op_hash, ip)` keys with their recorded value.
215///
216/// The tables are built by the COMPILER (`finish_chunk`), so a run that loads a
217/// program from the bytecode cache never fills them — and everything that reads
218/// them silently degrades: a generator's parked `for…of`/`yield*` iterators are
219/// not closed on an injected `.return()`, so their `finally` never runs, and a
220/// `TypeError` loses the callee's source text. Storing them alongside the
221/// program is what makes a cache hit behave like a compile.
222pub type SiteTables = (Vec<((u64, usize), String)>, Vec<((u64, usize), usize)>);
223
224/// Snapshot both registries.
225pub fn site_tables() -> SiteTables {
226    let calls = call_sites::SITES.with(|m| {
227        m.borrow()
228            .iter()
229            .map(|(k, v)| (*k, v.clone()))
230            .collect::<Vec<_>>()
231    });
232    let yields =
233        yield_sites::DEPTHS.with(|m| m.borrow().iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>());
234    (calls, yields)
235}
236
237/// Put a snapshot back — what a cache hit does in place of compiling.
238pub fn restore_site_tables(t: &SiteTables) {
239    call_sites::SITES.with(|m| {
240        let mut m = m.borrow_mut();
241        for (k, v) in &t.0 {
242            m.insert(*k, v.clone());
243        }
244    });
245    yield_sites::DEPTHS.with(|m| {
246        let mut m = m.borrow_mut();
247        for (k, v) in &t.1 {
248            m.insert(*k, *v);
249        }
250    });
251}
252
253/// The number of loop iterators parked on the stack at the op currently
254/// executing, for the abrupt-completion close in `b_yield`.
255pub fn parked_iters(vm: &fusevm::VM) -> usize {
256    yield_sites::depth(vm.chunk.op_hash, vm.ip.saturating_sub(1))
257}
258
259/// Rewrite a `<subject> is not a function` / `is not a constructor` message with
260/// the SOURCE TEXT of the callee at the currently executing op, as V8 does.
261///
262/// `subject` is what the raising code named — the method name, or the callee's
263/// rendered value. The message's own subject must END WITH it, which is the
264/// guard that keeps an unrelated error raised deeper inside a native method from
265/// being relabelled with this call's text. (A native dispatcher may prefix its
266/// own receiver word, e.g. `map.get is not a function`, so the whole subject is
267/// replaced rather than trimmed by length.)
268///
269/// Returns the message unchanged when no site was recorded, so a shape the
270/// printer declines to print keeps the old wording rather than an invented one.
271/// The source text recorded for the op currently executing, if any. `vm.ip` has
272/// already advanced past it.
273pub fn call_site_text(vm: &fusevm::VM) -> Option<String> {
274    call_sites::text(vm.chunk.op_hash, vm.ip.saturating_sub(1))
275}
276
277pub fn name_call_site(vm: &fusevm::VM, subject: &str, msg: String) -> String {
278    for tail in [
279        " is not a function",
280        " is not a constructor",
281        " is not iterable",
282    ] {
283        let Some(head) = msg.strip_suffix(tail) else {
284            continue;
285        };
286        // The prefix is the error class (`TypeError: `); the rest is the subject.
287        // The FIRST separator, not the last: a rendered VALUE can contain one —
288        // `{ a: 1 } is not iterable` split at the last `": "` left the subject
289        // as `1 }`, which matched nothing and silently skipped the rename.
290        let (prefix, found) = match head.find(": ") {
291            Some(i) => (&head[..i + 2], &head[i + 2..]),
292            None => ("", head),
293        };
294        if !found.ends_with(subject) {
295            return msg;
296        }
297        // `vm.ip` has already advanced past the op being executed.
298        let Some(text) = call_sites::text(vm.chunk.op_hash, vm.ip.saturating_sub(1)) else {
299            return msg;
300        };
301        return format!("{prefix}{text}{tail}");
302    }
303    msg
304}
305
306/// `SIG_UNWIND` scope tags: what the emitting site is nested in.
307pub mod unwind {
308    /// No enclosing loop in this chunk — any pending signal propagates outward.
309    pub const NO_LOOP: &str = "";
310    /// An enclosing UNLABELED loop in this chunk.
311    pub const PLAIN_LOOP: &str = "\u{0}";
312    /// `SIG_UNWIND` result codes.
313    pub const NONE: i64 = 0;
314    pub const BREAK: i64 = 1;
315    pub const CONTINUE: i64 = 2;
316}
317
318/// `DEF_MEMBER` member-kind tags.
319pub mod member {
320    pub const METHOD: i64 = 0;
321    pub const GET: i64 = 1;
322    pub const SET: i64 = 2;
323    /// A static FIELD (`static x = 1`), which is a data property of the
324    /// constructor rather than a method. Only distinguished from `METHOD` for a
325    /// PRIVATE name, where the declaration must install the private element
326    /// without tripping the brand check an ordinary write to `#x` gets — and
327    /// where node's brand-check message words a field differently from a method.
328    pub const STATIC_FIELD: i64 = 3;
329}
330
331/// Bitwise/shift op tags carried by `ops::BINOP` (JS ToInt32/ToUint32 rules).
332pub mod binop {
333    pub const BITAND: i64 = 0;
334    pub const BITOR: i64 = 1;
335    pub const BITXOR: i64 = 2;
336    pub const SHL: i64 = 3;
337    pub const SHR: i64 = 4;
338    pub const USHR: i64 = 5;
339}
340
341/// Unary op tags carried by `ops::UNARY`.
342pub mod unop {
343    pub const POS: i64 = 0; // unary +
344    pub const BITNOT: i64 = 1; // ~
345}
346
347// ── heap objects ───────────────────────────────────────────────────────────
348
349/// A compiled function template: parameter shape + body chunk. Shared by every
350/// closure created from the same function/arrow.
351#[derive(Clone, serde::Serialize, serde::Deserialize)]
352pub struct FuncDef {
353    pub name: String,
354    /// Parameter binding templates (destructuring lowered by the compiler into
355    /// the body prologue; here we only track the simple arg slots).
356    pub params: Vec<ParamSlot>,
357    pub chunk: Chunk,
358    pub is_arrow: bool,
359    /// True for a `function*`/`*method`/generator arrow: calling it builds a
360    /// suspended generator instead of running the body.
361    pub is_generator: bool,
362    /// True for an `async` function/method/arrow: calling it drives a coroutine
363    /// and returns a Promise; `await` inside suspends via the same yielder.
364    pub is_async: bool,
365    /// True when the function body (or the enclosing program) is strict. A
366    /// SLOPPY function called with no receiver gets the GLOBAL object as
367    /// `this`; a strict one keeps `undefined` (10.2.1.2 OrdinaryCallBindThis).
368    #[serde(default)]
369    pub strict: bool,
370    /// True for a MethodDefinition (`{ m(){} }`, a class method/accessor). A
371    /// non-generator method is not a constructor, so it owns no `prototype`.
372    #[serde(default)]
373    pub is_method: bool,
374    /// True for a NAMED function *expression* (`const f = function fact(n) {…}`):
375    /// the closure gets an extra environment binding its own name to itself, so
376    /// the body can recurse through that name even when the outer binding differs.
377    #[serde(default)]
378    pub self_name: bool,
379    /// The definition's byte range in its script (`(0, 0)`: none), for
380    /// `Function.prototype.toString` (20.2.3.5).
381    #[serde(default)]
382    pub span: (u32, u32),
383    /// The host `scripts` entry `span` indexes, set when the program loads.
384    #[serde(default)]
385    pub script: Option<u32>,
386}
387
388/// One parameter slot. `name` is the simple bound name; a destructuring pattern
389/// is lowered to a synthetic `.arg{i}` name plus body prologue code.
390#[derive(Clone, serde::Serialize, serde::Deserialize)]
391pub struct ParamSlot {
392    pub name: String,
393    /// True for the `...rest` collector.
394    pub rest: bool,
395    /// True if this slot has a default expression (applied in the body prologue).
396    pub has_default: bool,
397}
398
399thread_local! {
400    /// The source position of the op in the innermost frame that is calling
401    /// out right now — see [`set_op_pos`].
402    static OP_POS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
403}
404
405/// Record that the innermost frame is executing the op at source position
406/// `pos` (`0`: unknown, ignored) — called by every op that can run user code
407/// (the calls, `new`, and the property reads and writes that may reach a
408/// getter or setter). It is a thread-local cell rather than a host write
409/// because a property read is the hottest op there is; the position moves into
410/// the frame's [`Frame::pos`] only when that frame stops being the innermost,
411/// and is cleared then, so it always describes the innermost frame.
412pub fn set_op_pos(pos: u32) {
413    if pos != 0 {
414        OP_POS.with(|p| p.set(pos));
415    }
416}
417
418/// The innermost frame is gone (popped, or swapped out with its generator):
419/// what was pending for it describes no frame that remains.
420fn clear_op_pos() {
421    OP_POS.with(|p| p.set(0));
422}
423
424/// Where a script's text came from, as node names it in a source arrow and a
425/// stack frame: the absolute path of a CommonJS file, the `file://` URL of an
426/// ES module, `[eval]` / `[stdin]` for source given on the command line.
427#[derive(Clone, Debug)]
428pub struct ScriptOrigin {
429    pub name: String,
430    /// Lines the loader put in front of the user's text (the CommonJS
431    /// wrapper's opening line), subtracted from every reported line.
432    pub line_shift: u32,
433    /// The runtime's own JavaScript (the ES module loader and the other JS
434    /// factories): node shows its internals as `node:internal/…` frames that do
435    /// not exist here, so this code's frames are left out of a stack and a
436    /// source arrow never points into it.
437    pub internal: bool,
438}
439
440impl ScriptOrigin {
441    pub fn named(name: impl Into<String>) -> ScriptOrigin {
442        ScriptOrigin {
443            name: name.into(),
444            line_shift: 0,
445            internal: false,
446        }
447    }
448
449    pub fn internal(name: impl Into<String>) -> ScriptOrigin {
450        ScriptOrigin {
451            internal: true,
452            ..ScriptOrigin::named(name)
453        }
454    }
455}
456
457/// One script's range of the source address space: positions
458/// `base ..= base + len` belong to `scripts[script]`.
459pub struct ScriptRange {
460    pub base: u32,
461    pub len: u32,
462    pub script: u32,
463    pub origin: ScriptOrigin,
464    /// Byte offset of every line start, computed on the first lookup.
465    line_starts: std::cell::OnceCell<Vec<u32>>,
466}
467
468/// A source position resolved to node's terms.
469pub struct SourceLocation<'a> {
470    pub name: &'a str,
471    /// 1-based, as node prints them; the column counts UTF-16 units, as V8's.
472    pub line: u32,
473    pub col: u32,
474    /// The text of that line, without its terminator.
475    pub source_line: &'a str,
476    /// See [`ScriptOrigin::internal`].
477    pub internal: bool,
478}
479
480/// The raise an in-flight exception came from: its error string, the source
481/// position of the op that raised it, the frame depth it was raised at, and —
482/// for an error the runtime raised rather than a JS `throw` — the stack frames
483/// live at that moment, which are gone by the time a `catch` (or the fatal
484/// report) builds the error object.
485///
486/// A raise propagates outward through every enclosing chunk, each of which
487/// re-reports the same string. A report of the same string at the same or a
488/// shallower depth is that propagation and keeps the original site; a
489/// `catch` clears it, so the next raise of an equal string is recorded anew.
490#[derive(Clone, Debug)]
491pub struct ThrowSite {
492    pub msg: String,
493    pub pos: u32,
494    /// One past the last position the report's caret underlines, for a
495    /// SyntaxError, whose range is its offending token (empty at the end of
496    /// the input); 0 for V8's one-character raise range.
497    pub end: u32,
498    pub depth: usize,
499    pub frames: Option<String>,
500}
501
502/// A compiled `try`/`catch`/`finally` block. Bodies are bare chunks run in the
503/// current scope.
504#[derive(Clone, serde::Serialize, serde::Deserialize)]
505pub struct TryDef {
506    pub block: Chunk,
507    /// `(catch_param_name, catch_body)`.
508    pub handler: Option<(Option<String>, Chunk)>,
509    pub finalizer: Option<Chunk>,
510}
511
512/// A live closure value.
513#[derive(Clone)]
514pub struct FuncVal {
515    pub def_id: usize,
516    /// Captured lexical environment (enclosing scope chain), for free vars.
517    pub env: Option<Env>,
518    /// `this` captured at definition time (arrow functions).
519    pub this: Option<Value>,
520    pub is_arrow: bool,
521    /// The owning class name for a method (drives `super` resolution). `None` for
522    /// plain functions/arrows.
523    pub home_class: Option<String>,
524    /// Whether that method is a STATIC one. `super.x` resolves against a
525    /// different object in each case — the parent constructor for a static
526    /// method, the parent's prototype for an instance method — and the class
527    /// name alone cannot tell them apart, since both carry the same one.
528    pub home_static: bool,
529    /// The object literal a shorthand method was defined in, for `super` inside
530    /// it. A class method resolves `super` through `home_class` instead; this
531    /// is the `[[HomeObject]]` an ordinary `{ m() { super.x } }` needs, and
532    /// without it there was nothing to resolve against.
533    pub home_object: Option<Value>,
534    /// `new.target` captured at definition (arrow functions): an arrow has none
535    /// of its own, so `new.target` and a `super()` call inside it use the
536    /// enclosing constructor's.
537    pub new_target: Option<Value>,
538}
539
540/// What an array iterator yields at each index: `keys()`, `values()` (and
541/// `Symbol.iterator`), or `entries()`.
542#[derive(Clone, Copy, PartialEq, Eq)]
543pub enum ArrayIterKind {
544    Keys,
545    Values,
546    Entries,
547}
548
549/// A heap object.
550#[derive(Clone)]
551pub enum JsObj {
552    Str(String),
553    Array(Vec<Value>),
554    Object(IndexMap<String, Value>),
555    Func(FuncVal),
556    /// A first-class reference to a builtin function or namespace
557    /// (`console.log`, `Math`, `parseInt`).
558    Builtin(String),
559    /// A bound method value (`obj.method` captured then called): dispatches
560    /// through `call_method(recv, name, args)` when invoked.
561    BoundMethod {
562        recv: Value,
563        name: String,
564    },
565    /// The single canonical `null`.
566    Null,
567    /// An iterator over a sequence, with a cursor.
568    ///
569    /// `items` is a snapshot, taken when the iterator was made. An ARRAY
570    /// iterator is not one: `array` names the array and what each step yields,
571    /// and every step reads the array as it is then (23.1.5.1), so a `for-of`
572    /// sees an element pushed or written during the loop and stops at a length
573    /// that shrank. `items` is empty for those.
574    ///
575    /// `brand` names the built-in iterator prototype a snapshot stands for —
576    /// `"String Iterator"`, `"URLSearchParams Iterator"`, … — which is its
577    /// `Symbol.toStringTag` and its `util.inspect` prefix. `None` is an
578    /// iterator the runtime makes for its own iteration and never hands out.
579    /// An array iterator is always `"Array Iterator"`, whatever this says.
580    Iter {
581        items: Vec<Value>,
582        idx: usize,
583        array: Option<(Value, ArrayIterKind)>,
584        brand: Option<&'static str>,
585    },
586    /// A bound function (`fn.bind(thisArg, ...preargs)`).
587    BoundFunc {
588        target: Value,
589        this: Value,
590        args: Vec<Value>,
591    },
592    /// A class constructor value: the runtime object produced by a `class`.
593    Class(ClassVal),
594    /// A `Symbol` — a unique property key. `registered` marks a `Symbol.for`
595    /// key (shared) vs a fresh `Symbol()`.
596    Symbol {
597        desc: Option<String>,
598        id: u64,
599    },
600    /// A `Map` (or `WeakMap` when `weak`): insertion-ordered key→value entries.
601    Map {
602        entries: IndexMap<MapKey, (Value, Value)>,
603        weak: bool,
604    },
605    /// A `Set` (or `WeakSet` when `weak`): insertion-ordered unique values.
606    Set {
607        entries: IndexMap<MapKey, Value>,
608        weak: bool,
609    },
610    /// A live generator, backed by a stackful `corosensei` coroutine in
611    /// `JsHost.generators`.
612    Generator {
613        id: u32,
614    },
615    /// A Promise, backed by a `PromiseCell` in `JsHost.promises`.
616    Promise {
617        id: u32,
618    },
619    /// An arbitrary-precision `BigInt` (`typeof === "bigint"`).
620    BigInt(num_bigint::BigInt),
621    /// A compiled regular expression (`/pat/flags` or `new RegExp(...)`).
622    RegExp(Box<RegExpObj>),
623    /// A `Proxy`: every essential internal method is diverted to `handler`'s
624    /// traps (see `crate::proxy`). `revoked` is set by the thunk
625    /// `Proxy.revocable` hands back, after which every operation throws.
626    Proxy {
627        target: Value,
628        handler: Value,
629        revoked: bool,
630    },
631}
632
633/// Which variant a heap object is, carrying none of its contents.
634///
635/// Property access has to pick a branch by variant, but the code inside a branch
636/// re-enters the host (`bound_method`, `lookup_chain`, `invoke`), so it cannot
637/// hold a `&JsObj` borrow across the match. The way out used to be
638/// `h.get(v).cloned()` — which deep-copies the entire backing store (a whole
639/// `Vec<Value>`, `IndexMap`, or `String`) just to read its tag. That made one
640/// property read O(len) and any loop over a collection O(n^2). This type is the
641/// same discriminant with nothing attached, so the probe is O(1) and each branch
642/// re-borrows for only the one field it actually needs.
643/// The well-known symbols node-js actually honors. `Symbol.<name>` is the
644/// interned symbol `@@Symbol.<name>`, and using it as a property key stores
645/// under the sentinel string `@@<name>` (`property_key`) so the internal
646/// lookups (`@@iterator`, `@@toPrimitive`, …) can find it without a symbol
647/// table walk. Symbols V8 defines but node-js does not act on are deliberately
648/// absent: a symbol that reads back while the operator it names ignores it would
649/// be a silent fake. `hasInstance` is listed because `instance_of` consults it.
650pub const WELL_KNOWN_SYMBOLS: &[&str] = &[
651    "iterator",
652    "asyncIterator",
653    "toPrimitive",
654    "toStringTag",
655    "hasInstance",
656    // Nine more the table was missing entirely, so `Symbol.species` and friends
657    // read `undefined` and no protocol keyed on them could be expressed.
658    "species",
659    "isConcatSpreadable",
660    "match",
661    "matchAll",
662    "replace",
663    "search",
664    "split",
665    "unscopables",
666    "dispose",
667    "asyncDispose",
668];
669
670/// Whether the internal key `k` came from a SYMBOL used as a property key
671/// (`@@sym:<id>`, or a well-known `@@iterator`), as opposed to one of node-js's
672/// hidden slots (`@@native`, `@@bytes`, `@@ms`, `@@kind`, …). Only the former
673/// is an observable JavaScript property.
674pub fn is_symbol_key(k: &str) -> bool {
675    match k.strip_prefix("@@") {
676        Some(rest) => rest
677            .strip_prefix("sym:")
678            .map(|i| i.parse::<u64>().is_ok())
679            .unwrap_or_else(|| WELL_KNOWN_SYMBOLS.contains(&rest)),
680        None => false,
681    }
682}
683
684#[derive(Clone, Copy, PartialEq, Eq, Debug)]
685pub enum ObjKind {
686    Str,
687    Array,
688    Object,
689    Func,
690    Builtin,
691    BoundMethod,
692    Null,
693    Iter,
694    BoundFunc,
695    Class,
696    Symbol,
697    Map,
698    Set,
699    Generator,
700    Promise,
701    BigInt,
702    RegExp,
703    Proxy,
704}
705
706impl JsObj {
707    /// This object's variant, without touching its contents.
708    pub fn kind(&self) -> ObjKind {
709        match self {
710            JsObj::Str(_) => ObjKind::Str,
711            JsObj::Array(_) => ObjKind::Array,
712            JsObj::Object(_) => ObjKind::Object,
713            JsObj::Func(_) => ObjKind::Func,
714            JsObj::Builtin(_) => ObjKind::Builtin,
715            JsObj::BoundMethod { .. } => ObjKind::BoundMethod,
716            JsObj::Null => ObjKind::Null,
717            JsObj::Iter { .. } => ObjKind::Iter,
718            JsObj::BoundFunc { .. } => ObjKind::BoundFunc,
719            JsObj::Class(_) => ObjKind::Class,
720            JsObj::Symbol { .. } => ObjKind::Symbol,
721            JsObj::Map { .. } => ObjKind::Map,
722            JsObj::Set { .. } => ObjKind::Set,
723            JsObj::Generator { .. } => ObjKind::Generator,
724            JsObj::Promise { .. } => ObjKind::Promise,
725            JsObj::BigInt(_) => ObjKind::BigInt,
726            JsObj::RegExp(_) => ObjKind::RegExp,
727            JsObj::Proxy { .. } => ObjKind::Proxy,
728        }
729    }
730}
731
732/// A `RegExp` object: the compiled `fancy_regex::Regex` plus the JS-visible
733/// source, flag booleans, and the mutable `lastIndex` cursor (used by `g`/`y`
734/// matching). fancy-regex adds lookaround + backreferences on top of the Rust
735/// `regex` fast path, so the JS grammar node-js can accept is a near-superset.
736#[derive(Clone)]
737pub struct RegExpObj {
738    /// The translated regex. Construction of a pattern fancy-regex still cannot
739    /// express (documented in BUGS.md) throws at `RegExp` build time, so a live
740    /// `RegExpObj` always holds a compiled engine.
741    ///
742    /// Shared (`Rc`) rather than owned, because a regex LITERAL builds a fresh
743    /// `RegExpObj` on every evaluation — it has to, since `lastIndex` is
744    /// per-object mutable state — while the compiled engine behind it is
745    /// immutable and identical every time. See `regexp::compiled`.
746    pub re: std::rc::Rc<crate::regexp::Engine>,
747    pub source: String,
748    pub flags: String,
749    pub global: bool,
750    pub ignore_case: bool,
751    pub multiline: bool,
752    pub dot_all: bool,
753    pub sticky: bool,
754    pub unicode: bool,
755    /// `lastIndex`, in UTF-16 code units; advanced by `exec`/`test` under the
756    /// `g`/`y` flags. The newtype keeps it from being confused with the regex
757    /// engine's byte offsets, which are the same shape and differ off the BMP.
758    pub last_index: crate::utf16::U16Index,
759}
760
761/// A Promise's settled state and pending reactions.
762pub struct PromiseCell {
763    pub state: PromiseState,
764    pub value: Value,
765    /// Reactions registered while still pending; drained (as microtasks) on
766    /// settle.
767    pub reactions: Vec<PromiseReaction>,
768    /// True once a rejection has been observed by a handler (`.then`/`.catch`),
769    /// so the loop doesn't report it as unhandled.
770    pub handled: bool,
771    /// For the result promise of an async body: the source position of the
772    /// `await` it is suspended in (0 when running, done, or not an async
773    /// body). What node's unsettled top-level `await` warning points at.
774    pub await_pos: u32,
775}
776
777/// A pending Promise reaction: a user `.then` (JS handlers + a result promise) or
778/// a native continuation (Promise chaining / async `await` resumption).
779pub enum PromiseReaction {
780    Js {
781        on_ful: Value,
782        on_rej: Value,
783        result: Value,
784        /// The async context frame `.then` was called in; the handler runs in it.
785        frame: AsyncFrame,
786    },
787    Native(Box<dyn FnOnce(PromiseState, Value) -> Result<(), String>>),
788}
789
790#[derive(Default, Clone, Copy, PartialEq, Eq)]
791pub enum PromiseState {
792    #[default]
793    Pending,
794    Fulfilled,
795    Rejected,
796}
797
798/// A live class constructor. The prototype object (holding instance methods) and
799/// the static-side own properties live on the heap; `parent` is the superclass
800/// constructor value (`None` for a base class).
801#[derive(Clone)]
802pub struct ClassVal {
803    pub name: String,
804    /// The constructor function value (a `JsObj::Func`), or `None` for a class
805    /// with only a synthesized default constructor.
806    pub ctor: Option<Value>,
807    pub parent: Option<Value>,
808    /// `C.prototype` — the object instances delegate to.
809    pub proto: Value,
810    /// Static own properties (static methods/fields), plus `name`/`prototype`.
811    pub statics: IndexMap<String, Value>,
812    /// Instance field initializers: `(name, thunk_fn, name_anon_init)`, run
813    /// per-instance after `super()` (or at construction start for a base class).
814    /// `name_anon_init` records the SYNTACTIC fact that the initializer was an
815    /// anonymous function definition, so 15.7.10 NamedEvaluation applies to its
816    /// result — it cannot be re-derived at run time (a field initialised from an
817    /// already-anonymous function held elsewhere must not be renamed).
818    pub fields: Vec<(String, Value, bool)>,
819    /// The FuncDef holding the class's source span (`String(C)`).
820    pub source_def: Option<usize>,
821}
822
823/// The result of resolving `super.name`: a getter to invoke (accessor property)
824/// or a directly-usable value (method / data property).
825pub enum SuperRef {
826    Getter(Value),
827    Data(Value),
828}
829
830/// How a `yield*` was resumed when it was not by an ordinary `.next(x)`: the
831/// completion a `.return(v)` or `.throw(e)` forced onto the suspended generator,
832/// which 15.5.5 hands to the DELEGATE rather than raising at the `yield*`.
833pub enum DelegateResume {
834    Return(Value),
835    Throw(Value),
836}
837
838/// A `Map`/`Set` key under SameValueZero: `NaN` collapses to one key, `-0` and
839/// `+0` are the same key, primitives compare by value, objects by heap identity.
840#[derive(Clone, PartialEq, Eq, Hash)]
841pub enum MapKey {
842    Undef,
843    Null,
844    Bool(bool),
845    /// f64 bit pattern with `NaN` canonicalized and `-0` normalized to `+0`.
846    Num(u64),
847    /// A `BigInt` key, by its decimal string (SameValueZero: `1n` is one key).
848    Big(String),
849    Str(String),
850    /// Heap identity (objects, arrays, functions, symbols).
851    Ref(u32),
852    /// A builtin intrinsic, by the name it answers to. Every bare reference
853    /// to `Math` or `parseInt` allocates a fresh handle, so heap identity
854    /// would make `new Set([Math, Math])` two entries; `strict_eq` compares
855    /// these by name too.
856    Intrinsic(String),
857}
858
859// ── environments ─────────────────────────────────────────────────────────────
860
861/// The map behind a scope. Hashing these with `FxHash` instead of the default
862/// was measured SLOWER, not faster — fib went 652ms to 1086ms and a 5M-iteration
863/// counting loop 1894ms to 2381ms on the same machine — so the default stands.
864pub type VarMap = IndexMap<String, Value>;
865
866/// A local-variable environment, shared (by `Rc`) between a frame and any nested
867/// function that captures it.
868pub struct EnvData {
869    pub vars: VarMap,
870    /// The names in `vars` that were declared `const`, so an assignment to one
871    /// throws (16.1.3 / 8.5.2 — an immutable binding rejects SetMutableBinding).
872    ///
873    /// A separate set rather than a flag inside `VarMap`'s value, because
874    /// `set_name` is a hot path — the common case is an env with NO consts,
875    /// where `is_empty()` settles it without hashing the name a second time.
876    pub consts: rustc_hash::FxHashSet<String>,
877    pub parent: Option<Env>,
878    /// Sloppy-mode mapped `arguments` for the activation this env holds the
879    /// parameters of (10.4.4). `None` for every other scope, which keeps the
880    /// per-write check in `set_name` to one pointer test.
881    pub mapped: Option<Box<MappedArgs>>,
882    /// The binding object of a `with` statement: this scope has no variables of
883    /// its own, and a name is looked up on the object before the scopes beyond.
884    pub with_obj: Option<Value>,
885}
886
887/// The aliasing between a sloppy function's `arguments` object and its
888/// parameter bindings: while `names[i]` is non-empty, `arguments[i]` and that
889/// parameter are two names for one slot. A write through either side shows on
890/// the other until `delete arguments[i]` removes the link.
891pub struct MappedArgs {
892    pub arguments: Value,
893    /// `names[i]` is the parameter `arguments[i]` aliases, or empty when index
894    /// `i` is unmapped (past the passed arguments, a shadowed duplicate name,
895    /// or deleted).
896    pub names: Vec<String>,
897}
898pub type Env = Rc<RefCell<EnvData>>;
899
900/// An accessor property: `(getter, setter)`, either optional.
901pub type Accessor = (Option<Value>, Option<Value>);
902
903/// Prefix of the hidden property-map entry that reserves an accessor's slot in
904/// own-key insertion order (see `set_accessor`).
905/// The built-in iterator prototypes `ensure_iterator_protos` installs: the
906/// `native_protos` key (also the `@proto:<key>:next` thunk's class) and the
907/// `@@toStringTag` each carries, which is also the brand an iterator of that
908/// kind reports.
909pub const ITERATOR_PROTOS: &[(&str, &str)] = &[
910    ("ArrayIterator", "Array Iterator"),
911    ("MapIterator", "Map Iterator"),
912    ("SetIterator", "Set Iterator"),
913    ("StringIterator", "String Iterator"),
914    ("RegExpStringIterator", "RegExp String Iterator"),
915];
916
917pub const ORD_MARKER: &str = "@@ord:";
918
919/// The three ECMAScript own-property attributes. `PropAttrs::default()` is the
920/// all-true shape a plain `o.k = v` assignment produces, which is why only
921/// deviations need storing.
922#[derive(Clone, Copy, Debug, PartialEq, Eq)]
923pub struct PropAttrs {
924    pub writable: bool,
925    pub enumerable: bool,
926    pub configurable: bool,
927}
928
929impl Default for PropAttrs {
930    fn default() -> Self {
931        PropAttrs {
932            writable: true,
933            enumerable: true,
934            configurable: true,
935        }
936    }
937}
938
939impl PropAttrs {
940    /// The attribute shape V8 gives an internal-but-inspectable slot such as
941    /// `Error.prototype.message`, `err.stack` or a `Buffer`'s view metadata:
942    /// readable and replaceable, but never enumerated.
943    pub const HIDDEN: PropAttrs = PropAttrs {
944        writable: true,
945        enumerable: false,
946        configurable: true,
947    };
948}
949
950fn new_env(parent: Option<Env>) -> Env {
951    Rc::new(RefCell::new(EnvData {
952        vars: VarMap::default(),
953        consts: rustc_hash::FxHashSet::default(),
954        parent,
955        mapped: None,
956        with_obj: None,
957    }))
958}
959
960/// A fresh empty scope chained under `parent`.
961pub fn child_env(parent: Env) -> Env {
962    new_env(Some(parent))
963}
964
965/// One function activation.
966pub struct Frame {
967    pub env: Env,
968    /// The env this activation started in — the FUNCTION scope. `var` and hoisted
969    /// function declarations bind here no matter how many block scopes are open.
970    pub base_env: Env,
971    pub this_obj: Option<Value>,
972    /// `new.target` for this activation (the constructor when invoked via `new`).
973    pub new_target: Option<Value>,
974    /// The class value owning the running method (drives `super`); `None` outside
975    /// a class method/constructor.
976    pub home_class: Option<Value>,
977    /// Whether the running method is a static one — see `FuncVal::home_static`.
978    pub home_static: bool,
979    /// The object literal owning the running method — see
980    /// `FuncVal::home_object`.
981    pub home_object: Option<Value>,
982    /// Whether the code in this activation is strict. A write the object
983    /// refuses is a silent no-op in sloppy mode and a `TypeError` here, so the
984    /// ASSIGNMENT SITE decides — not the object being written to.
985    pub strict: bool,
986    /// Source line the frame is currently executing (updated by the DAP line hook
987    /// under `--dap`; stays 0 on ordinary runs).
988    pub line: u32,
989    /// The source position (in the host's source address space, see
990    /// [`JsHost::source_location`]) of the op this frame is executing, as of
991    /// its last call out or raise: what its `at …(file:line:col)` stack line
992    /// reports. Written by the call ops, `new` and the raise paths; `0` until
993    /// the frame does one of those.
994    pub pos: u32,
995    /// Whether this is an arrow function's activation. Its `this_obj` is the
996    /// lexical `this`, not a receiver, so its stack line has no `Type.` prefix.
997    pub arrow: bool,
998    /// The function name that owns this frame, for the DAP `stackTrace`; `None`
999    /// for the module frame and anonymous activations.
1000    pub owner: Option<String>,
1001    /// True ONLY for the program's module frame. A generator/async body runs on a
1002    /// coroutine whose swapped-in context holds just ITS OWN frame, so the frame
1003    /// COUNT cannot tell "module scope" from "coroutine body scope" — without this
1004    /// flag every top-level `let`/`var` in such a body declared a GLOBAL, shared
1005    /// across concurrent activations of the same function.
1006    pub is_module: bool,
1007    /// Whether this activation's `this` is bound yet — see [`ThisState`].
1008    pub this_state: ThisState,
1009}
1010
1011/// The `[[ThisBindingStatus]]` of a function environment (9.1.1.3), as far as it
1012/// is observable: only a DERIVED class constructor starts with `this`
1013/// uninitialized, and only `super()` binds it.
1014///
1015/// The instance is still allocated up front (`construct_class`), so the
1016/// state is what makes it unreachable until then: `this` before `super()`, a
1017/// second `super()`, and returning without one are each the error node raises
1018/// rather than a silent write to the pre-allocated object.
1019#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1020pub enum ThisState {
1021    /// Every other activation: `this` is whatever was passed in.
1022    #[default]
1023    Plain,
1024    /// A derived constructor before `super()` has returned.
1025    Pending,
1026    /// A derived constructor after `super()`.
1027    Bound,
1028}
1029
1030/// A non-local control signal. `Break`/`Continue` carry the optional loop label
1031/// and are only raised when the target loop lives in an ENCLOSING chunk (a
1032/// `break` inside a `try` block, which the host runs as its own chunk); a
1033/// same-chunk `break` is a plain compiler-resolved jump.
1034#[derive(Clone)]
1035pub enum Signal {
1036    Return(Value),
1037    Break(Option<String>),
1038    Continue(Option<String>),
1039}
1040
1041/// The JavaScript runtime.
1042pub struct JsHost {
1043    heap: Vec<JsObj>,
1044    /// Function templates, indexed by def id.
1045    pub funcs: Vec<FuncDef>,
1046    /// Every script text a loaded program was parsed from; a `FuncDef`'s
1047    /// `script` indexes it and its `span` slices it.
1048    pub scripts: Vec<std::sync::Arc<str>>,
1049    /// While a generator or async body runs, the frames of every context that
1050    /// resumed one, outermost first: a body runs with only its own frame
1051    /// installed, and these are the callers a stack trace continues into.
1052    outer_frames: Vec<Vec<Frame>>,
1053    /// The scripts that own a range of the source address space, by ascending
1054    /// base — what a source position resolves against. See
1055    /// [`JsHost::register_source`].
1056    pub source_map: Vec<ScriptRange>,
1057    /// try/catch/finally block templates, indexed by try id.
1058    pub tries: Vec<TryDef>,
1059    /// Module-level (global) names.
1060    globals: VarMap,
1061    /// The one uninitialized-binding marker, allocated on first use. See
1062    /// [`JsHost::tdz_marker`].
1063    tdz: Option<Value>,
1064    /// Module-top-level names still in their temporal dead zone. Kept out of
1065    /// `globals` so the marker is never reachable as `globalThis.<name>`.
1066    tdz_globals: rustc_hash::FxHashSet<String>,
1067    /// The call environment behind each mapped `arguments` object, by heap
1068    /// index: the route a write to `arguments[i]` takes to reach its parameter.
1069    mapped_arg_envs: rustc_hash::FxHashMap<u32, Env>,
1070    /// Top-level `const` names (a module frame declares into `globals`), so an
1071    /// assignment to one throws the same way a block-scoped `const` does.
1072    global_consts: rustc_hash::FxHashSet<String>,
1073    /// The frame stack (bottom = module).
1074    frames: Vec<Frame>,
1075    /// The program's top-level scope — the scope runtime-compiled source runs in
1076    /// (`new Function`, indirect `eval`, `vm.runInThisContext`; see
1077    /// `run_chunk_in_global_scope`), as opposed to whatever function frame
1078    /// happens to be executing when that source is compiled.
1079    ///
1080    /// Held as its own field rather than read off `frames[0]` because a coroutine
1081    /// body runs with `frames` SWAPPED for its own one-frame context
1082    /// (`install_gen_ctx`), so the bottom frame is not the top-level frame there.
1083    ///
1084    /// Note this is node-js's ONE top-level scope. Node distinguishes the global
1085    /// scope from a CommonJS module's scope (a module body is a wrapper
1086    /// function), so in Node a file's top-level `var` is invisible to dynamic
1087    /// code; here the entry file is evaluated with Script semantics, so it stays
1088    /// visible. That is the same entry-file-is-a-Script divergence `BUGS.md`
1089    /// records for top-level `return`, not a separate one — and `node -e`, which
1090    /// really is a Script, matches Node exactly.
1091    global_env: Env,
1092    pub error: Option<String>,
1093    /// The in-flight thrown value, if any (JS `throw`).
1094    pub exc: Option<Value>,
1095    /// Where the in-flight exception was raised — see [`ThrowSite`].
1096    pub throw_site: Option<ThrowSite>,
1097    /// Whether the exception that is about to end the process is an unhandled
1098    /// promise rejection, whose source arrow node takes from where the error
1099    /// was CREATED rather than from where it was thrown.
1100    pub fatal_from_promise: bool,
1101    /// Whether the module frame (frame 0) no longer runs the program's top
1102    /// level: once that has returned, or when the entry is an ES module (whose
1103    /// body runs in a function of its own). A stack then leaves the frame out.
1104    pub module_frame_done: bool,
1105    /// The current async context frame (see [`Task`]).
1106    pub async_frame: AsyncFrame,
1107    pub signal: Option<Signal>,
1108    /// A forced `.return(v)` / `.throw(e)` that arrived at a `yield*`, waiting
1109    /// for the delegate step that applies it to the delegate (see
1110    /// `DelegateResume`).
1111    pub delegate_resume: Option<DelegateResume>,
1112    /// Nesting count of [`JsHost::with_forced_strict`].
1113    forced_strict: u32,
1114    /// Promises that settled REJECTED this tick. Drained at each microtask
1115    /// checkpoint: any still without a handler is an unhandled rejection.
1116    pub pending_rejections: Vec<u32>,
1117    /// `process.on(event, fn)` listeners, by event name.
1118    pub process_listeners: IndexMap<String, Vec<ProcListener>>,
1119    /// The canonical `null` handle (allocated once).
1120    null_val: Value,
1121    /// `[[Prototype]]` link per heap object, by heap index. Absent = default
1122    /// (`Object.prototype` for objects, `null` for the root).
1123    protos: HashMap<u32, Value>,
1124    /// Heap objects whose `[[Prototype]]` is *explicitly* null — via
1125    /// `Object.create(null)` or `Object.setPrototypeOf(o, null)`. Distinct from a
1126    /// bare `{}` (absent from `protos` but conceptually `Object.prototype`), which
1127    /// is why `Object.create(null) instanceof Object` can read `false`.
1128    null_proto_objs: HashSet<u32>,
1129    /// Own properties of function objects (functions are objects in JS): a live
1130    /// closure's `name`/`prototype`/static-ish members. Keyed by heap index.
1131    fn_props: HashMap<u32, IndexMap<String, Value>>,
1132    /// Accessor (getter/setter) properties per owning object, by heap index then
1133    /// key: `(get, set)`. Class `get x()`/`set x()` install here on the prototype.
1134    accessors: HashMap<u32, IndexMap<String, Accessor>>,
1135    /// Own-property attributes that deviate from the plain-assignment default
1136    /// (`{writable, enumerable, configurable}` all true), by heap index then key.
1137    /// Only non-default entries are stored, so an ordinary object costs nothing;
1138    /// `prop_attrs` returns the default for any key absent here. This is what
1139    /// makes `Object.defineProperty(o, k, {enumerable: false})` invisible to
1140    /// `Object.keys`/`for-in`/`JSON.stringify` while `getOwnPropertyNames` still
1141    /// reports it, and what hides `Error`'s `message`/`stack` the way V8 does.
1142    prop_attrs: HashMap<u32, IndexMap<String, PropAttrs>>,
1143    /// Heap objects sealed against new properties by `Object.preventExtensions`,
1144    /// `Object.seal` or `Object.freeze`.
1145    non_extensible: HashSet<u32>,
1146    /// Private names (`#m`) declared as a METHOD or accessor rather than as a
1147    /// field, for the brand-check error text: node distinguishes `Receiver must
1148    /// be an instance of class C` (a private method or accessor) from `Cannot
1149    /// read private member #x …` (a private field). Which class is answered by
1150    /// the running method's home class, not by this set, so two classes
1151    /// declaring the same private method name stay exact.
1152    private_methods: HashSet<String>,
1153    /// The ELIDED element positions of each array, by heap index. Absent (the
1154    /// overwhelmingly common case) means the array is dense.
1155    ///
1156    /// A hole is deliberately NOT a `Value` variant. A sentinel value would have
1157    /// to be mapped back to `undefined` at every element read in the runtime, and
1158    /// a single missed read would leak an un-nameable value into user code — a
1159    /// worse failure than storing `undefined` and losing the distinction. Keeping
1160    /// the marker OUTSIDE the value domain makes that leak structurally
1161    /// impossible: the element vector still holds a perfectly ordinary
1162    /// `Value::Undef` at a hole, so any code path that has not been taught about
1163    /// holes degrades to exactly the pre-existing behaviour (a visible
1164    /// `undefined`) instead of producing something unrepresentable.
1165    ///
1166    /// Sized like the array it describes in the worst case (`new Array(n)` marks
1167    /// every index), which is the same order as the `Vec<Value>` already paid for
1168    /// that array — so it cannot turn a working allocation into an OOM.
1169    array_holes: HashMap<u32, rustc_hash::FxHashSet<usize>>,
1170    /// See `take_super_replacement`.
1171    super_replacement: Option<Value>,
1172    /// Set by `run_class_ctor` for the one call that follows: the next user
1173    /// function activation is a derived constructor and starts `Pending`.
1174    derived_ctor_next: bool,
1175    /// Whether the entry script's top-level `var`s bind to its own scope rather
1176    /// than to the globals map — the CommonJS wrapper Node puts every file in.
1177    module_scope: bool,
1178    /// User-assigned static properties on a builtin namespace/constructor, keyed
1179    /// by namespace name then property (`Error` → `prepareStackTrace`,
1180    /// `stackTraceLimit`). Each bare `Error` reference allocates a fresh
1181    /// `Builtin` handle, so these cannot live in `fn_props` (which is per-heap-
1182    /// index); this stable side table lets `Error.prepareStackTrace = fn` persist.
1183    builtin_statics: HashMap<String, IndexMap<String, Value>>,
1184    /// `lib/buffer.js`'s shared allocation pool, `(allocPool, poolSize,
1185    /// poolOffset)` — created on first use by `buffer::pooled`.
1186    pub buffer_pool: Option<(Value, usize, usize)>,
1187    /// The shared well-known `Object.prototype` object (chain root for objects).
1188    object_proto: Value,
1189    /// Class name of each class `prototype` object, by heap index — lets an
1190    /// instance recover its constructor name (for `util.inspect` prefix and
1191    /// `obj.constructor.name`).
1192    proto_class: HashMap<u32, Value>,
1193    /// Class constructor values by name, so a running method's `home_class` name
1194    /// resolves to its class value (for `super`).
1195    class_registry: HashMap<String, Value>,
1196    /// Well-known prototype objects for the builtin error constructors, by name.
1197    error_protos: HashMap<String, Value>,
1198    /// The template object of each tagged-template SITE, keyed by the chunk that
1199    /// holds the site and the site's ordinal within its compilation.
1200    ///
1201    /// GetTemplateObject (13.2.8.4) caches by Parse Node, so a site evaluated
1202    /// twice hands back the SAME object: ``const t = () => tag`x`;`` makes
1203    /// `t() === t()` true, and a tag that memoizes on the strings array — the
1204    /// documented reason the object is cached, and how `lit-html` and `graphql`
1205    /// avoid re-parsing — saw a fresh array every call here. Two sites with
1206    /// identical text are still distinct objects, which the chunk hash plus the
1207    /// ordinal keep apart.
1208    template_objects: HashMap<(u64, u64), Value>,
1209    /// Real prototype *objects* for the builtin exotics whose instances need a
1210    /// genuine `[[Prototype]]` link (`Buffer`, `Uint8Array`). Most builtin
1211    /// prototypes are `Builtin("<Ctor>.prototype")` thunk namespaces, which
1212    /// cannot appear on a prototype chain and report `typeof "function"`.
1213    native_protos: HashMap<String, Value>,
1214    /// `Symbol.for` registry: description → symbol value.
1215    symbol_registry: HashMap<String, Value>,
1216    /// Monotonic id source for fresh `Symbol()` values.
1217    next_symbol: u64,
1218    /// Every live symbol by its id, so a `@@sym:<id>` property key can be
1219    /// turned back into the symbol VALUE for `Object.getOwnPropertySymbols`.
1220    symbols_by_id: HashMap<u64, Value>,
1221    /// Well-known symbol ids (`Symbol.iterator` …) to their ECMAScript name.
1222    /// Identity is by id, not description, so a user `Symbol("Symbol.iterator")`
1223    /// is a distinct key.
1224    well_known_ids: HashMap<u64, String>,
1225    /// Suspended generator coroutines, indexed by `JsObj::Generator.id`.
1226    generators: Vec<GenCell>,
1227    /// Promise cells, indexed by `JsObj::Promise.id`.
1228    promises: Vec<PromiseCell>,
1229    /// Whether the loop is part-way through draining the microtask queue, so a
1230    /// `nextTick` queued by one of them waits for the round to finish. See
1231    /// `next_microtask`.
1232    draining_micro: bool,
1233    /// `process.nextTick` callbacks (drained before promise microtasks).
1234    pub nextticks: std::collections::VecDeque<Task>,
1235    /// Promise-reaction / `queueMicrotask` microtasks.
1236    pub microtasks: std::collections::VecDeque<Task>,
1237    /// Completed asynchronous I/O whose callback is waiting for the loop's poll
1238    /// phase: an `fs` callback, a `child_process.exec` result, a `zlib` or
1239    /// `crypto` thread-pool job. In node these arrive from libuv as MACROTASKS,
1240    /// so every `nextTick` and promise job queued by the code that started the
1241    /// operation runs first. See `queue_io_callback`.
1242    io_completions: std::collections::VecDeque<Task>,
1243    /// `setTimeout`/`setInterval`/`setImmediate` macrotasks.
1244    pub macrotasks: Vec<Timer>,
1245    /// Monotonic timer-id source.
1246    next_timer: u64,
1247    /// The virtual clock (ms): the `vdeadline` of the latest timer fired.
1248    virtual_now: f64,
1249    /// Cloned by I/O worker threads to post `IoTask`s back to the main-thread
1250    /// event loop. Kept alive for the host's lifetime so the loop's `recv` never
1251    /// sees a spurious `Disconnected` while a server is running.
1252    io_tx: Sender<IoTask>,
1253    /// Owned by the event loop (taken out for the blocking `recv`). Receives the
1254    /// `IoTask`s posted by I/O threads.
1255    io_rx: Option<Receiver<IoTask>>,
1256    /// Ref-count of "things keeping the process alive": open listeners, live
1257    /// sockets, ref'd handles. The loop exits only when this is `0` AND both task
1258    /// queues are empty. A pure script never touches it, so it exits exactly as
1259    /// before.
1260    open_handles: usize,
1261    /// In-process output sink. When `Some`, everything the program writes to
1262    /// stdout/stderr is appended here instead of reaching the process streams —
1263    /// what an embedder (a TUI that owns the terminal) needs so a `console.log`
1264    /// cannot corrupt its display. `None` (the default) is the ordinary
1265    /// standalone `node` behaviour: writes go straight to the real streams.
1266    ///
1267    /// Bytes, not `String`: a program may legitimately write output that is not
1268    /// valid UTF-8 (`process.stdout.write(Buffer.from([0xff]))`), and a `String`
1269    /// buffer can only hold the lossy `U+FFFD` transcription of it.
1270    capture: Option<Vec<u8>>,
1271    /// Whether [`Self::capture`] also takes stderr writes: set by
1272    /// [`JsHost::begin_capture`] (a TUI keeps both streams off the terminal),
1273    /// cleared by [`JsHost::begin_stdout_capture`].
1274    capture_stderr: bool,
1275    /// Standard input an embedder supplied ([`JsHost::set_stdin`]); `None` reads
1276    /// the process stdin. Read through [`with_stdin_reader`].
1277    stdin: Option<std::io::Cursor<Vec<u8>>>,
1278    /// `process.exitCode`: the code the process exits with when the event loop
1279    /// drains, or `None` while unset. Separate from an explicit
1280    /// `process.exit(n)`, which exits immediately with `n`.
1281    pub exit_code: Option<i32>,
1282    /// An `uncaughtException` listener itself threw. Node treats that as fatal
1283    /// with status 7 and fires no `exit` event.
1284    pub fatal_handler_failed: bool,
1285    /// Whether the `exit` event has already been emitted, so the `process.exit`
1286    /// path and the end-of-loop path cannot both fire it (Node's `_exiting`).
1287    pub exiting: bool,
1288    /// The one `globalThis` object. It has to be a singleton: `globalThis` is an
1289    /// identity in JS, so `globalThis === globalThis` is `true` and a property
1290    /// written through one read is visible through the next. Minting a fresh
1291    /// object per read made both false.
1292    global_obj: Value,
1293}
1294
1295/// One `process.on`/`process.once` registration. `once` is not decoration: a
1296/// `once` listener must be UNREGISTERED before it runs, so a second `emit` of
1297/// the same event does not reach it. Treating `once` as an alias of `on` made
1298/// `process.once('e', f); process.emit('e'); process.emit('e')` call `f` twice
1299/// and leave it in `process.listeners('e')` — node v26.7.0 calls it once and
1300/// reports zero listeners afterwards.
1301#[derive(Clone)]
1302pub struct ProcListener {
1303    pub f: Value,
1304    pub once: bool,
1305}
1306
1307/// A queued unit of work: either a JS callback invocation (`queueMicrotask`,
1308/// `nextTick`, timer body) or a native step (Promise reaction / async resume).
1309///
1310/// Each carries the ASYNC CONTEXT FRAME current when it was queued and runs in
1311/// it — node's `AsyncContextFrame`, which is what an `AsyncLocalStorage`
1312/// store follows across `setTimeout`, `nextTick`, promise jobs and I/O
1313/// callbacks.
1314pub enum Task {
1315    Js {
1316        cb: Value,
1317        args: Vec<Value>,
1318        frame: AsyncFrame,
1319    },
1320    Native(Box<dyn FnOnce() -> Result<(), String>>, AsyncFrame),
1321}
1322
1323impl Task {
1324    fn run(self) -> Result<(), String> {
1325        match self {
1326            Task::Js { cb, args, frame } => in_frame(frame, || invoke(&cb, args, None).map(|_| ())),
1327            Task::Native(f, frame) => in_frame(frame, f),
1328        }
1329    }
1330}
1331
1332/// An async context frame: each `AsyncLocalStorage` (by heap index) with its
1333/// store. Immutable once built — a `run`/`enterWith` makes a new one — so a
1334/// queued task can hold the frame it was created in.
1335pub type AsyncFrame = std::rc::Rc<Vec<(u32, Value)>>;
1336
1337/// Run `f` with `frame` as the current async context frame, restoring the
1338/// previous one afterwards (a store a callback `enterWith`s stays inside it).
1339pub fn in_frame<R>(frame: AsyncFrame, f: impl FnOnce() -> R) -> R {
1340    let prev = with_host(|h| std::mem::replace(&mut h.async_frame, frame));
1341    let r = f();
1342    with_host(|h| h.async_frame = prev);
1343    r
1344}
1345
1346/// The current frame with `key`'s store set to `store` (or removed, for `None`).
1347pub fn frame_with(key: u32, store: Option<Value>) -> AsyncFrame {
1348    let cur = with_host(|h| h.async_frame.clone());
1349    let mut v: Vec<(u32, Value)> = cur.iter().filter(|(k, _)| *k != key).cloned().collect();
1350    if let Some(s) = store {
1351        v.push((key, s));
1352    }
1353    std::rc::Rc::new(v)
1354}
1355
1356/// A scheduled macrotask (`setTimeout`/`setInterval`/`setImmediate`). Ordering
1357/// is by `(delay, seq)` — a deterministic virtual clock, never wall time.
1358pub struct Timer {
1359    pub id: u64,
1360    pub delay: f64,
1361    pub seq: u64,
1362    pub callback: Value,
1363    pub args: Vec<Value>,
1364    pub cancelled: bool,
1365    /// Repeat period in ms for a `setInterval` timer; `None` for the one-shot
1366    /// `setTimeout`/`setImmediate`. A repeating timer is re-armed with a fresh
1367    /// deadline each time it fires, so it keeps the loop alive indefinitely —
1368    /// exactly like Node, where `setInterval` runs until cleared.
1369    pub interval: Option<f64>,
1370    /// Node's `ref`/`unref` handle bit. Only a *referenced* pending timer keeps
1371    /// the event loop alive; an unref'd one still fires while the loop happens
1372    /// to be alive for another reason, but never holds it open by itself.
1373    pub refed: bool,
1374    /// Real wall-clock deadline (`now + delay`), used only on the real-clock
1375    /// path (an open handle or a pending interval). On the pure virtual clock
1376    /// this is ignored.
1377    pub deadline: Instant,
1378    /// The async context frame the timer was created in; its callback runs in it.
1379    pub frame: AsyncFrame,
1380    /// The virtual-clock deadline: the host's `virtual_now` when scheduled plus
1381    /// `delay`. The virtual clock fires timers in this order, so a 5 ms timer
1382    /// scheduled at virtual time 10 runs after a 12 ms one scheduled at 0;
1383    /// ordering by `delay` alone ran every short timer first, however late it
1384    /// was scheduled.
1385    pub vdeadline: f64,
1386}
1387
1388/// One suspended generator. `coro` is `None` only while actively running (taken
1389/// out across `Coroutine::resume`); `ctx` holds its volatile execution context
1390/// (frames/signal/error/exc) while suspended.
1391struct GenCell {
1392    coro: Option<corosensei::Coroutine<Value, Value, Result<Value, String>>>,
1393    /// Raw pointer to the coroutine body's `Yielder`, published on entry (same
1394    /// thread → valid for the body's life). Read by `yield` to suspend.
1395    yielder: *const (),
1396    ctx: GenContext,
1397    done: bool,
1398    /// True once the body has been resumed at least once (so it is suspended at a
1399    /// `yield`). `.return()`/`.throw()` only unwind a *started* generator.
1400    started: bool,
1401    /// A completion injected by `.return(v)` / `.throw(e)`: consumed by the next
1402    /// `yield` resume so the body unwinds (running any pending `finally`).
1403    inject: Option<GenInject>,
1404    /// True for an `async function*` body, where `await` AND `yield` share one
1405    /// coroutine yielder: `await` wraps its operand in an await marker so the
1406    /// driver can tell an internal suspension from a real yield.
1407    async_gen: bool,
1408    /// `[[AsyncGeneratorQueue]]` — pending requests as
1409    /// `(completion, step promise id)`. ECMA-262 27.6.3.6 keeps this queue so
1410    /// overlapping requests resume the body ONE AT A TIME and settle in request
1411    /// order; without it a second request issued before the first settles races
1412    /// past it and the results arrive swapped. `.next`, `.return` AND `.throw`
1413    /// all enqueue — a `.return()` that skipped the queue would terminate the
1414    /// body while an earlier `.next()` was still suspended on an `await`, and
1415    /// that `.next()` would then wrongly report `{done: true}`.
1416    queue: std::collections::VecDeque<(GenReq, u32)>,
1417    /// True while a queued request is being driven.
1418    running: bool,
1419    /// The [`stack_floor`] that applies while this generator's body is running.
1420    ///
1421    /// A corosensei coroutine executes on its OWN mmap'd stack, so the address
1422    /// range the thread's pthread record describes says nothing about how much
1423    /// room the body has left. Recorded from the coroutine's `Stack::limit()` at
1424    /// construction and swapped in around every resume; without it the guard
1425    /// compared a coroutine stack pointer against the main stack's floor and
1426    /// (depending on where mmap landed) either fired immediately or never.
1427    stack_floor: usize,
1428}
1429
1430/// A forced completion pushed into a suspended generator by `.return()`/`.throw()`.
1431enum GenInject {
1432    Return(Value),
1433    Throw(Value),
1434}
1435
1436/// One queued `[[AsyncGeneratorQueue]]` request. ECMA-262 27.6.3.6
1437/// `AsyncGeneratorEnqueue` records a *completion*, not just a sent value, which
1438/// is why `.return()` and `.throw()` queue behind pending `.next()` calls
1439/// instead of unwinding the body on the spot.
1440#[derive(Clone)]
1441pub enum GenReq {
1442    /// `.next(v)` — resume normally with `v`.
1443    Next(Value),
1444    /// `.return(v)` — resume with a forced return completion.
1445    Return(Value),
1446    /// `.throw(e)` — resume with a forced throw completion.
1447    Throw(Value),
1448}
1449
1450/// The mutable "execution registers" swapped at every generator resume/suspend
1451/// boundary so a suspended generator's half-finished frame/signal state never
1452/// leaks into the resuming caller. The heap, function/class tables and globals
1453/// are shared and never swapped.
1454#[derive(Default)]
1455struct GenContext {
1456    frames: Vec<Frame>,
1457    error: Option<String>,
1458    exc: Option<Value>,
1459    signal: Option<Signal>,
1460}
1461
1462thread_local! {
1463    /// Id of the generator whose body is currently executing, or `None` at the
1464    /// root. `yield` suspends this generator.
1465    static CUR_GEN: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
1466}
1467
1468thread_local! {
1469    static HOST: RefCell<JsHost> = RefCell::new(JsHost::new());
1470}
1471
1472/// Run `f` with mutable access to the thread-local host.
1473pub fn with_host<R>(f: impl FnOnce(&mut JsHost) -> R) -> R {
1474    HOST.with(|h| f(&mut h.borrow_mut()))
1475}
1476
1477/// Reset the host to a clean slate (fresh module frame).
1478/// Run `f` against the program's standard input: the buffer set by
1479/// [`JsHost::set_stdin`] when there is one, else the locked process stdin.
1480///
1481/// The buffer is taken out of the host for the duration of `f`, so `f` runs
1482/// with no host borrow held.
1483pub fn with_stdin_reader<T>(f: impl FnOnce(&mut dyn std::io::BufRead) -> T) -> T {
1484    let Some(mut buf) = with_host(|h| h.stdin.take()) else {
1485        return f(&mut std::io::stdin().lock());
1486    };
1487    let r = f(&mut buf);
1488    with_host(|h| h.stdin = Some(buf));
1489    r
1490}
1491
1492pub fn reset_host() {
1493    with_host(|h| *h = JsHost::new());
1494    // Drop any cached module handles / factory closure — they index the old heap.
1495    crate::module::reset();
1496}
1497
1498impl Default for JsHost {
1499    fn default() -> Self {
1500        Self::new()
1501    }
1502}
1503
1504impl JsHost {
1505    pub fn new() -> JsHost {
1506        let global_env = new_env(None);
1507        let (io_tx, io_rx) = std::sync::mpsc::channel();
1508        let mut h = JsHost {
1509            tdz: None,
1510            tdz_globals: Default::default(),
1511            mapped_arg_envs: Default::default(),
1512            heap: Vec::new(),
1513            funcs: Vec::new(),
1514            scripts: Vec::new(),
1515            source_map: Vec::new(),
1516            outer_frames: Vec::new(),
1517            tries: Vec::new(),
1518            globals: VarMap::default(),
1519            global_consts: rustc_hash::FxHashSet::default(),
1520            frames: vec![Frame {
1521                env: global_env.clone(),
1522                base_env: global_env.clone(),
1523                this_obj: None,
1524                new_target: None,
1525                home_class: None,
1526                home_static: false,
1527                home_object: None,
1528                strict: false,
1529                line: 0,
1530                pos: 0,
1531                arrow: false,
1532                owner: None,
1533                is_module: true,
1534                this_state: ThisState::Plain,
1535            }],
1536            global_env,
1537            error: None,
1538            exc: None,
1539            throw_site: None,
1540            fatal_from_promise: false,
1541            module_frame_done: false,
1542            async_frame: std::rc::Rc::new(Vec::new()),
1543            signal: None,
1544            pending_rejections: Vec::new(),
1545            process_listeners: IndexMap::new(),
1546            null_val: Value::Undef,
1547            protos: HashMap::new(),
1548            null_proto_objs: HashSet::new(),
1549            fn_props: HashMap::new(),
1550            accessors: HashMap::new(),
1551            prop_attrs: HashMap::new(),
1552            non_extensible: HashSet::new(),
1553            private_methods: HashSet::new(),
1554            array_holes: HashMap::new(),
1555            super_replacement: None,
1556            derived_ctor_next: false,
1557            delegate_resume: None,
1558            forced_strict: 0,
1559            module_scope: false,
1560            builtin_statics: HashMap::new(),
1561            buffer_pool: None,
1562            object_proto: Value::Undef,
1563            proto_class: HashMap::new(),
1564            class_registry: HashMap::new(),
1565            error_protos: HashMap::new(),
1566            template_objects: HashMap::new(),
1567            native_protos: HashMap::new(),
1568            symbol_registry: HashMap::new(),
1569            next_symbol: 1,
1570            symbols_by_id: HashMap::new(),
1571            well_known_ids: HashMap::new(),
1572            generators: Vec::new(),
1573            promises: Vec::new(),
1574            microtasks: std::collections::VecDeque::new(),
1575            draining_micro: false,
1576            io_completions: std::collections::VecDeque::new(),
1577            nextticks: std::collections::VecDeque::new(),
1578            macrotasks: Vec::new(),
1579            next_timer: 1,
1580            virtual_now: 0.0,
1581            io_tx,
1582            io_rx: Some(io_rx),
1583            open_handles: 0,
1584            capture: None,
1585            capture_stderr: false,
1586            stdin: None,
1587            exit_code: None,
1588            fatal_handler_failed: false,
1589            exiting: false,
1590            global_obj: Value::Undef,
1591        };
1592        h.null_val = h.alloc(JsObj::Null);
1593        // `Object.prototype`: the chain root, its own `[[Prototype]]` is null.
1594        h.object_proto = h.new_object(IndexMap::new());
1595        h.global_obj = h.new_object(IndexMap::new());
1596        h
1597    }
1598
1599    /// Whether `v` IS the one `globalThis` object (not merely an object).
1600    pub fn is_global_object(&self, v: &Value) -> bool {
1601        !matches!(self.global_obj, Value::Undef) && self.global_obj == *v
1602    }
1603
1604    /// The `globalThis` object — one per host, so its identity and its
1605    /// properties both survive across reads.
1606    pub fn global_object(&mut self) -> Value {
1607        if matches!(self.global_obj, Value::Undef) {
1608            self.global_obj = self.new_object(IndexMap::new());
1609        }
1610        self.global_obj.clone()
1611    }
1612
1613    // ── prototype chain ──────────────────────────────────────────────────
1614    /// The `[[Prototype]]` of a heap value, if explicitly linked.
1615    pub fn proto_of(&self, v: &Value) -> Option<Value> {
1616        if let Value::Obj(i) = v {
1617            self.protos.get(i).cloned()
1618        } else {
1619            None
1620        }
1621    }
1622    /// Set `v`'s `[[Prototype]]` to `proto`. Null links the object as an explicit
1623    /// null-prototype object (recorded so `instanceof Object` reads false);
1624    /// undefined just clears any link without the null marker.
1625    pub fn set_proto(&mut self, v: &Value, proto: Value) {
1626        if let Value::Obj(i) = v {
1627            if self.is_null(&proto) {
1628                self.protos.remove(i);
1629                self.null_proto_objs.insert(*i);
1630            } else if matches!(proto, Value::Undef) {
1631                self.protos.remove(i);
1632            } else {
1633                self.protos.insert(*i, proto);
1634                self.null_proto_objs.remove(i);
1635            }
1636        }
1637    }
1638    /// Whether `v`'s `[[Prototype]]` was explicitly set to null.
1639    pub fn has_null_proto(&self, v: &Value) -> bool {
1640        matches!(v, Value::Obj(i) if self.null_proto_objs.contains(i))
1641    }
1642    /// Whether `util.inspect` renders `v` with the `[Object: null prototype]`
1643    /// tag. That is a question about the object's ACTUAL `[[Prototype]]`, which
1644    /// for `Object.prototype` is null even though nothing ever set it so: it is
1645    /// the chain root and was never passed through `set_proto`, so the
1646    /// explicitly-nulled registry does not hold it and `console.log(Object
1647    /// .prototype)` printed a bare `{}` where node prints the tag.
1648    ///
1649    /// Kept apart from [`Self::has_null_proto`], which nine other call sites ask
1650    /// about whether Object.prototype's own methods and `__proto__` accessor are
1651    /// INHERITED. `Object.prototype` inherits nothing and still owns all of them.
1652    pub fn inspects_null_proto(&self, v: &Value) -> bool {
1653        self.has_null_proto(v) || *v == self.object_proto
1654    }
1655    pub fn object_proto(&self) -> Value {
1656        self.object_proto.clone()
1657    }
1658    /// Record that the prototype object `proto` belongs to the class constructor
1659    /// `class_val` (so instances can recover their constructor).
1660    pub fn tag_proto_class(&mut self, proto: &Value, class_val: Value) {
1661        if let Value::Obj(i) = proto {
1662            self.proto_class.insert(*i, class_val);
1663        }
1664    }
1665    /// The class whose `prototype` object IS `v`, if `v` is one.
1666    pub fn class_owning_proto(&self, v: &Value) -> Option<Value> {
1667        match v {
1668            Value::Obj(i) => self.proto_class.get(i).cloned(),
1669            _ => None,
1670        }
1671    }
1672    /// The class constructor value nearest in `obj`'s prototype chain, if any.
1673    pub fn class_of(&self, obj: &Value) -> Option<Value> {
1674        let mut cur = self.proto_of(obj);
1675        while let Some(p) = cur {
1676            if let Value::Obj(i) = &p {
1677                if let Some(c) = self.proto_class.get(i) {
1678                    return Some(c.clone());
1679                }
1680            }
1681            cur = self.proto_of(&p);
1682        }
1683        None
1684    }
1685    /// The constructor display name of `obj` for `util.inspect` (empty ⇒ plain
1686    /// object, no prefix).
1687    pub fn ctor_name(&self, obj: &Value) -> String {
1688        if let Some(c) = self.class_of(obj) {
1689            // `callable_name`, not the class record's own name: an anonymous
1690            // class expression is named by inference from its binding
1691            // (`const X = class {}`), which lands as an own `name` property,
1692            // and node prints `new X()` as `X {}`.
1693            if let Some(JsObj::Class(_)) = self.get(&c) {
1694                return self.callable_name(&c);
1695            }
1696        }
1697        // A `function F(){}` constructor is not a `class`, so it has no
1698        // `proto_class` entry. V8's `getConstructorName` walks the prototype
1699        // chain for an own `constructor` that is a named function — which is
1700        // what makes `console.log(new F())` print `F { y: 2 }`.
1701        let mut cur = self.proto_of(obj);
1702        while let Some(p) = cur {
1703            let ctor = match self.get(&p) {
1704                Some(JsObj::Object(props)) => props.get("constructor").cloned(),
1705                Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => self.fn_prop(&p, "constructor"),
1706                _ => None,
1707            };
1708            if let Some(f) = ctor {
1709                let n = self.callable_name(&f);
1710                if !n.is_empty() {
1711                    return n;
1712                }
1713            }
1714            cur = self.proto_of(&p);
1715        }
1716        String::new()
1717    }
1718
1719    /// The prefix node's `getPrefix` gives a builtin collection: `Map(2) ` for
1720    /// a plain one, `M2(2) [Map] ` for an instance of a subclass (constructor
1721    /// name, then the builtin tag in brackets). `size` is `None` for a kind
1722    /// with no count (`Promise`).
1723    fn builtin_prefix(&self, v: &Value, tag: &str, size: Option<usize>) -> String {
1724        let ctor = self.ctor_name(v);
1725        let count = size.map(|n| format!("({n})")).unwrap_or_default();
1726        if ctor.is_empty() || ctor == tag {
1727            format!("{tag}{count} ")
1728        } else {
1729            format!("{ctor}{count} [{tag}] ")
1730        }
1731    }
1732
1733    /// The `[Name]` stub a builtin collection collapses to past the depth
1734    /// limit: `[Map]`, or `[M2 [Map]]` for a subclass instance.
1735    fn builtin_depth_stub(&self, v: &Value, tag: &str) -> String {
1736        let ctor = self.ctor_name(v);
1737        if ctor.is_empty() || ctor == tag {
1738            format!("[{tag}]")
1739        } else {
1740            format!("[{ctor} [{tag}]]")
1741        }
1742    }
1743
1744    /// Whether a callable owns a `prototype` property. `MakeConstructor`
1745    /// (10.2.5) runs for an ordinary function definition and for every
1746    /// generator; an arrow, a `MethodDefinition`, an async function and a bound
1747    /// function are not constructors and own none.
1748    /// `Some("Generator")` / `Some("AsyncGenerator")` for a `function*` /
1749    /// `async function*`, naming the intrinsic its objects inherit from.
1750    pub fn generator_kind(&self, v: &Value) -> Option<&'static str> {
1751        match self.get(v) {
1752            Some(JsObj::Func(f)) => match self.funcs.get(f.def_id) {
1753                Some(d) if d.is_generator && d.is_async => Some("AsyncGenerator"),
1754                Some(d) if d.is_generator => Some("Generator"),
1755                _ => None,
1756            },
1757            _ => None,
1758        }
1759    }
1760
1761    pub fn owns_prototype(&self, v: &Value) -> bool {
1762        match self.get(v) {
1763            Some(JsObj::Class(_)) => true,
1764            Some(JsObj::Func(f)) => match self.funcs.get(f.def_id) {
1765                Some(d) => d.is_generator || !(d.is_arrow || d.is_async || d.is_method),
1766                None => false,
1767            },
1768            _ => false,
1769        }
1770    }
1771
1772    /// A function's own-property table (created on demand).
1773    pub fn fn_prop(&self, v: &Value, name: &str) -> Option<Value> {
1774        if let Value::Obj(i) = v {
1775            self.fn_props.get(i).and_then(|m| m.get(name).cloned())
1776        } else {
1777            None
1778        }
1779    }
1780
1781    /// A class static member, inherited down the constructor chain: a subclass
1782    /// sees its superclass's `static` methods/fields (`Sub.create` → `Base.create`).
1783    pub fn class_static(&self, class_val: &Value, name: &str) -> Option<Value> {
1784        let mut cur = class_val.clone();
1785        loop {
1786            if let Some(v) = self.fn_prop(&cur, name) {
1787                return Some(v);
1788            }
1789            match self.get(&cur) {
1790                Some(JsObj::Class(c)) => cur = c.parent.clone()?,
1791                _ => return None,
1792            }
1793        }
1794    }
1795
1796    /// The first `extends` ancestor that is NOT a user class — the builtin
1797    /// constructor a class chain bottoms out in (`class D extends Array {}` →
1798    /// the `Array` builtin), or `None` for a chain of user classes only.
1799    ///
1800    /// `class_static` walks `ClassVal.parent` and gives up the moment the parent
1801    /// stops being a `Class`, so a static declared by the BUILTIN half of the
1802    /// chain was unreachable: `D.from` read `undefined` where node inherits
1803    /// `Array.from`. Returning the ancestor lets the caller finish the lookup
1804    /// with an ordinary property read, which is what reaches a builtin's
1805    /// statics.
1806    pub fn class_builtin_ancestor(&self, class_val: &Value) -> Option<Value> {
1807        let mut cur = class_val.clone();
1808        loop {
1809            match self.get(&cur) {
1810                Some(JsObj::Class(c)) => cur = c.parent.clone()?,
1811                _ => return Some(cur),
1812            }
1813        }
1814    }
1815    pub fn set_fn_prop(&mut self, v: &Value, name: &str, val: Value) {
1816        if let Value::Obj(i) = v {
1817            self.fn_props
1818                .entry(*i)
1819                .or_default()
1820                .insert(name.to_string(), val);
1821        }
1822        // `name` and `prototype` are own properties of every function/class, but
1823        // never enumerable ones (SetFunctionName 10.2.9, MakeConstructor
1824        // 10.2.5), so `Object.keys(fn)` and `for (k in fn)` report only what a
1825        // script assigned. An ARRAY receiver reaching the same side table has no
1826        // such exotic keys — `arr.name = 'x'` is an ordinary enumerable property.
1827        if !matches!(
1828            self.kind_of(v),
1829            Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc)
1830        ) {
1831            return;
1832        }
1833        let attrs = match name {
1834            "name" => PropAttrs {
1835                writable: false,
1836                enumerable: false,
1837                configurable: true,
1838            },
1839            "prototype" => PropAttrs {
1840                writable: true,
1841                enumerable: false,
1842                configurable: false,
1843            },
1844            _ => return,
1845        };
1846        self.set_prop_attrs(v, name, attrs);
1847    }
1848    /// A user-assigned static on a builtin namespace (`Error.prepareStackTrace`).
1849    pub fn builtin_static(&self, ns: &str, name: &str) -> Option<Value> {
1850        self.builtin_statics
1851            .get(ns)
1852            .and_then(|m| m.get(name).cloned())
1853    }
1854    /// Assign a static on a builtin namespace (persists across fresh `Builtin`
1855    /// handles for the same namespace).
1856    pub fn set_builtin_static(&mut self, ns: &str, name: &str, val: Value) {
1857        self.builtin_statics
1858            .entry(ns.to_string())
1859            .or_default()
1860            .insert(name.to_string(), val);
1861    }
1862    /// `delete <ns>.<name>` for a script-assigned static. Reports whether the
1863    /// key was there — without this, `delete Array.prototype.patch` answered
1864    /// true and left the entry in place, so the patch outlived its own removal.
1865    pub fn remove_builtin_static(&mut self, ns: &str, name: &str) -> bool {
1866        self.builtin_statics
1867            .get_mut(ns)
1868            .is_some_and(|m| m.shift_remove(name).is_some())
1869    }
1870    /// Every namespace a script has assigned a static onto, with that
1871    /// namespace's assigned keys — the source of the user-added half of
1872    /// `Object.getOwnPropertyNames(Array.prototype)`.
1873    pub fn builtin_static_keys(&self, ns: &str) -> Vec<String> {
1874        self.builtin_statics
1875            .get(ns)
1876            .map(|m| m.keys().cloned().collect())
1877            .unwrap_or_default()
1878    }
1879    /// Drop an own property from the side table (`delete arr.foo`,
1880    /// `delete fn.tag`). Reports whether the key was there.
1881    pub fn remove_fn_prop(&mut self, v: &Value, name: &str) -> bool {
1882        match v {
1883            Value::Obj(i) => self
1884                .fn_props
1885                .get_mut(i)
1886                .map(|m| m.shift_remove(name).is_some())
1887                .unwrap_or(false),
1888            _ => false,
1889        }
1890    }
1891    /// Whether `key` is one of the synthesized own properties (`length`,
1892    /// `name`) of a function, class or bound function.
1893    fn is_fn_intrinsic_key(&self, v: &Value, key: &str) -> bool {
1894        matches!(key, "length" | "name")
1895            && matches!(
1896                self.kind_of(v),
1897                Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc)
1898            )
1899    }
1900    /// The tombstone key recording `delete fn.<key>` for a synthesized property.
1901    fn fn_deleted_key(key: &str) -> String {
1902        format!("@@deleted:{key}")
1903    }
1904    /// `delete fn.length` / `delete fn.name`: remember that the synthesized own
1905    /// property is gone so every reader falls through to `Function.prototype`.
1906    pub fn mark_fn_intrinsic_deleted(&mut self, v: &Value, key: &str) {
1907        if self.is_fn_intrinsic_key(v, key) {
1908            self.set_fn_prop(v, &Self::fn_deleted_key(key), Value::Bool(true));
1909        }
1910    }
1911    /// Whether the synthesized `length`/`name` of `v` has been deleted and not
1912    /// since redefined (a redefinition stores a real side-table entry).
1913    pub fn fn_intrinsic_deleted(&self, v: &Value, key: &str) -> bool {
1914        self.is_fn_intrinsic_key(v, key)
1915            && self.fn_prop(v, &Self::fn_deleted_key(key)).is_some()
1916            && self.fn_prop(v, key).is_none()
1917    }
1918    /// Whether a write to `key` hits a read-only `length`/`name`: still
1919    /// synthesized (no stored redefinition) and, for `name`, already non-empty.
1920    /// An EMPTY name is left writable because the compiler's NamedEvaluation
1921    /// (SetFunctionName on an anonymous function) assigns it through the same
1922    /// store as a script assignment.
1923    pub fn fn_intrinsic_readonly(&self, v: &Value, key: &str) -> bool {
1924        self.is_fn_intrinsic_key(v, key)
1925            && self.fn_prop(v, key).is_none()
1926            && (key == "length"
1927                || self.fn_intrinsic_deleted(v, key)
1928                || !self.callable_name(v).is_empty())
1929    }
1930    pub fn fn_prop_keys(&self, v: &Value) -> Vec<String> {
1931        if let Value::Obj(i) = v {
1932            self.fn_props
1933                .get(i)
1934                .map(|m| m.keys().cloned().collect())
1935                .unwrap_or_default()
1936        } else {
1937            Vec::new()
1938        }
1939    }
1940
1941    /// Install an accessor `(get, set)` for `key` on the object `owner`.
1942    pub fn set_accessor(
1943        &mut self,
1944        owner: &Value,
1945        key: &str,
1946        get: Option<Value>,
1947        set: Option<Value>,
1948    ) {
1949        if let Value::Obj(i) = owner {
1950            // Accessors live in their own table, but JS reports own keys in a
1951            // single insertion order across data AND accessor properties. Drop an
1952            // ordering marker into the property map so
1953            // `{ a: 1, get b() {}, c: 3 }` enumerates a, b, c — not a, c, b.
1954            // The marker is `@@`-prefixed, so it is invisible to every reader.
1955            let marker = format!("{ORD_MARKER}{key}");
1956            match self.get_mut(owner) {
1957                Some(JsObj::Object(props)) => {
1958                    if !props.contains_key(key) && !props.contains_key(&marker) {
1959                        props.insert(marker, Value::Undef);
1960                    }
1961                }
1962                // A function or class keeps its own properties in the fn-prop
1963                // side table, so its ordering marker belongs there. Without it a
1964                // static accessor enumerated AFTER every static field and method
1965                // regardless of where the class body declared it: node reports
1966                // `class A { static s = 2; static get sv(){} static m(){} }` as
1967                // `['sv', 'm', 's']` — the methods and accessors in source order
1968                // first, then the fields — and this reported `['m', 's', 'sv']`.
1969                Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => {
1970                    let table = self.fn_props.entry(*i).or_default();
1971                    if !table.contains_key(key) && !table.contains_key(&marker) {
1972                        table.insert(marker, Value::Undef);
1973                    }
1974                }
1975                _ => {}
1976            }
1977            let slot = self
1978                .accessors
1979                .entry(*i)
1980                .or_default()
1981                .entry(key.to_string())
1982                .or_insert((None, None));
1983            if get.is_some() {
1984                slot.0 = get;
1985            }
1986            if set.is_some() {
1987                slot.1 = set;
1988            }
1989        }
1990    }
1991    /// The accessor `(get, set)` for `key` directly on `owner` (no chain walk).
1992    /// Drop an own accessor property entirely, marker and all.
1993    ///
1994    /// `delete obj.accessorProp` used to clear only the property map, and an
1995    /// accessor does not live there — so the delete reported success while the
1996    /// getter kept answering and `in` kept reporting the key.
1997    pub fn remove_accessor(&mut self, owner: &Value, key: &str) {
1998        if let Value::Obj(i) = owner {
1999            if let Some(m) = self.accessors.get_mut(i) {
2000                m.shift_remove(key);
2001            }
2002        }
2003        let marker = format!("{ORD_MARKER}{key}");
2004        match self.get_mut(owner) {
2005            Some(JsObj::Object(props)) => {
2006                props.shift_remove(&marker);
2007            }
2008            Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => {
2009                if let Value::Obj(i) = owner {
2010                    if let Some(t) = self.fn_props.get_mut(i) {
2011                        t.shift_remove(&marker);
2012                    }
2013                }
2014            }
2015            _ => {}
2016        }
2017    }
2018
2019    /// Turn an own accessor property into a data property carrying `value`,
2020    /// keeping its place in the own-key order.
2021    ///
2022    /// `set_accessor` records that order with an `@@ord:` marker in the
2023    /// property map rather than a real key, so deleting the accessor and
2024    /// inserting the value would append the key at the end instead. Node
2025    /// reports `{ a: 1, get b() {}, c: 3 }` redefined through
2026    /// `Object.defineProperty(o, 'b', { value })` as `a, b, c`.
2027    pub fn accessor_to_data(&mut self, owner: &Value, key: &str, value: Value) {
2028        if let Value::Obj(i) = owner {
2029            if let Some(m) = self.accessors.get_mut(i) {
2030                m.shift_remove(key);
2031            }
2032        }
2033        let marker = format!("{ORD_MARKER}{key}");
2034        let swap = |map: &mut IndexMap<String, Value>| match map.get_index_of(&marker) {
2035            Some(pos) => {
2036                *map = map
2037                    .iter()
2038                    .enumerate()
2039                    .map(|(n, (k, v))| {
2040                        if n == pos {
2041                            (key.to_string(), value.clone())
2042                        } else {
2043                            (k.clone(), v.clone())
2044                        }
2045                    })
2046                    .collect();
2047            }
2048            None => {
2049                map.insert(key.to_string(), value.clone());
2050            }
2051        };
2052        let fn_table = matches!(
2053            self.get(owner),
2054            Some(JsObj::Func(_)) | Some(JsObj::Class(_))
2055        );
2056        if fn_table {
2057            if let Value::Obj(i) = owner {
2058                swap(self.fn_props.entry(*i).or_default());
2059            }
2060        } else if let Some(JsObj::Object(props)) = self.get_mut(owner) {
2061            swap(props);
2062        }
2063    }
2064
2065    /// Move the per-heap-index bookkeeping of `src` onto `dst`.
2066    ///
2067    /// Used when one object becomes another in place (a class extending a
2068    /// builtin exotic). The prototype link is deliberately NOT moved: `dst`
2069    /// already points at the leaf class's prototype, which is the one its
2070    /// methods must resolve through.
2071    pub fn move_index_state(&mut self, src: u32, dst: u32) {
2072        if let Some(holes) = self.array_holes.remove(&src) {
2073            self.array_holes.insert(dst, holes);
2074        }
2075        if let Some(attrs) = self.prop_attrs.remove(&src) {
2076            self.prop_attrs.entry(dst).or_default().extend(attrs);
2077        }
2078        if let Some(props) = self.fn_props.remove(&src) {
2079            self.fn_props.entry(dst).or_default().extend(props);
2080        }
2081        if let Some(acc) = self.accessors.remove(&src) {
2082            self.accessors.entry(dst).or_default().extend(acc);
2083        }
2084    }
2085
2086    pub fn own_accessor(&self, owner: &Value, key: &str) -> Option<(Option<Value>, Option<Value>)> {
2087        if let Value::Obj(i) = owner {
2088            self.accessors.get(i).and_then(|m| m.get(key).cloned())
2089        } else {
2090            None
2091        }
2092    }
2093
2094    /// The own accessor-property keys of `owner`, in installation order.
2095    pub fn own_accessor_keys(&self, owner: &Value) -> Vec<String> {
2096        match owner {
2097            Value::Obj(i) => self
2098                .accessors
2099                .get(i)
2100                .map(|m| m.keys().cloned().collect())
2101                .unwrap_or_default(),
2102            _ => Vec::new(),
2103        }
2104    }
2105
2106    // ── own-property attributes ──────────────────────────────────────────
2107
2108    /// Record non-default attributes for `owner[key]`. Storing the default shape
2109    /// clears the entry so the table only ever holds deviations.
2110    pub fn set_prop_attrs(&mut self, owner: &Value, key: &str, attrs: PropAttrs) {
2111        if let Value::Obj(i) = owner {
2112            if attrs == PropAttrs::default() {
2113                if let Some(m) = self.prop_attrs.get_mut(i) {
2114                    m.shift_remove(key);
2115                }
2116            } else {
2117                self.prop_attrs
2118                    .entry(*i)
2119                    .or_default()
2120                    .insert(key.to_string(), attrs);
2121            }
2122        }
2123    }
2124
2125    /// Copy every recorded property attribute from `from` to `to`. A pass that
2126    /// rebuilds an object (`JSON.stringify`'s `toJSON` walk) must carry them
2127    /// across or the copy silently re-exposes non-enumerable slots.
2128    pub fn copy_prop_attrs(&mut self, from: &Value, to: &Value) {
2129        if let (Value::Obj(f), Value::Obj(_)) = (from, to) {
2130            if let Some(m) = self.prop_attrs.get(f).cloned() {
2131                for (k, a) in m {
2132                    self.set_prop_attrs(to, &k, a);
2133                }
2134            }
2135        }
2136    }
2137
2138    /// The attributes of own property `owner[key]` (all-true when unrecorded).
2139    pub fn prop_attrs(&self, owner: &Value, key: &str) -> PropAttrs {
2140        // An array's `length` is the array exotic's own property (10.4.2):
2141        // never enumerated and never configurable, and writable until
2142        // `Object.freeze` clears that — which is what stops a `push` from
2143        // extending a frozen array. Reporting it unconditionally writable made
2144        // `Object.isFrozen(Object.freeze([]))` false once the elements started
2145        // being sealed, because `length` was then the one key that never
2146        // followed.
2147        if key == "length" && matches!(self.get(owner), Some(JsObj::Array(_))) {
2148            let writable = match owner {
2149                Value::Obj(i) => self
2150                    .prop_attrs
2151                    .get(i)
2152                    .and_then(|m| m.get(key))
2153                    .map(|a| a.writable)
2154                    .unwrap_or(true),
2155                _ => true,
2156            };
2157            return PropAttrs {
2158                writable,
2159                enumerable: false,
2160                // An ARGUMENTS object's `length` is an ordinary data property
2161                // (10.4.4.6), so it is configurable where a real array's is
2162                // not. The two share a backing representation here, so the
2163                // exotic's attributes have to be told apart explicitly.
2164                configurable: crate::builtins::is_arguments_h(self, owner),
2165            };
2166        }
2167        match owner {
2168            Value::Obj(i) => self
2169                .prop_attrs
2170                .get(i)
2171                .and_then(|m| m.get(key))
2172                .copied()
2173                .unwrap_or_default(),
2174            _ => PropAttrs::default(),
2175        }
2176    }
2177
2178    /// Whether own property `owner[key]` shows up in `for-in`/`Object.keys`.
2179    /// Internal slots (`@@…`) and private class fields (`#…`) never do.
2180    pub fn is_enumerable(&self, owner: &Value, key: &str) -> bool {
2181        !key.starts_with("@@") && !key.starts_with('#') && self.prop_attrs(owner, key).enumerable
2182    }
2183
2184    /// Mark `owner[key]` non-enumerable, leaving it writable/configurable — the
2185    /// shape of every V8 "hidden but real" own property.
2186    pub fn hide_prop(&mut self, owner: &Value, key: &str) {
2187        self.set_prop_attrs(owner, key, PropAttrs::HIDDEN);
2188    }
2189
2190    /// Whether a plain `owner[key] = v` assignment is allowed to land. A
2191    /// non-writable data property silently ignores the write in sloppy mode,
2192    /// which is the mode every script here runs in; so does adding a *new* key to
2193    /// a non-extensible object.
2194    pub fn can_write_prop(&self, owner: &Value, key: &str) -> bool {
2195        if !self.prop_attrs(owner, key).writable || self.past_fixed_length(owner, key) {
2196            return false;
2197        }
2198        // An intrinsic prototype on the chain may define the name NON-WRITABLE,
2199        // and those members own no map entry for the walk below to find:
2200        // `o[Symbol.toStringTag] = 'x'` where `o` inherits from `Map.prototype`
2201        // is refused in node and was creating an own property here, which then
2202        // changed the object's brand.
2203        // The receiver's OWN kind counts too, not only the prototypes an
2204        // explicit link reaches: a plain array inherits `Array.prototype`
2205        // implicitly, with no link for the walk to follow, and
2206        // `a[Symbol.unscopables] = 'x'` is refused there just the same.
2207        //
2208        // Restricted to SYMBOL-keyed members. The string-keyed non-writable
2209        // ones — `Function.prototype.length`/`name`, `String.prototype.length`
2210        // — are also OWN properties of every instance, so the inherited rule
2211        // never decides them; applying it anyway blocked `SetFunctionName`
2212        // itself, and naming the setter in `Object.defineProperty(o, 'v', {set
2213        // (x) {…}})` then threw.
2214        if key.starts_with("@@")
2215            && crate::builtins::own_ctor_name(self, owner)
2216                .into_iter()
2217                .chain(crate::builtins::chain_intrinsic_ctors_h(self, owner))
2218                .any(|c| crate::builtins::is_proto_readonly(c, key))
2219        {
2220            return false;
2221        }
2222        // 10.1.9.2: with no OWN property, the inherited one decides. A
2223        // non-writable data property up the chain blocks the write rather than
2224        // being shadowed — including one on a frozen prototype. Only own
2225        // attributes were consulted, so `Object.create(frozenBase).f = 2`
2226        // quietly created an own property node refuses to create.
2227        //
2228        // An inherited ACCESSOR does not block: its setter runs, and the write
2229        // path checks for one before reaching here.
2230        let has_own = match self.get(owner) {
2231            Some(JsObj::Object(p)) => p.contains_key(key),
2232            _ => true,
2233        };
2234        if !has_own {
2235            let mut cur = self.proto_of(owner);
2236            while let Some(proto) = cur {
2237                if self.own_accessor(&proto, key).is_some() {
2238                    break;
2239                }
2240                let present =
2241                    matches!(self.get(&proto), Some(JsObj::Object(p)) if p.contains_key(key));
2242                if present {
2243                    if !self.prop_attrs(&proto, key).writable {
2244                        return false;
2245                    }
2246                    break;
2247                }
2248                cur = self.proto_of(&proto);
2249            }
2250        }
2251        if self.is_extensible(owner) {
2252            return true;
2253        }
2254        // A non-extensible object refuses a NEW key. Only the plain-object arm
2255        // could name its own keys, so every other shape answered "own" for any
2256        // key at all: `Object.freeze(arr).extra = 1` landed, and so did a write
2257        // to the frozen template object a tagged template hands its tag.
2258        match self.get(owner) {
2259            Some(JsObj::Object(p)) => p.contains_key(key),
2260            Some(JsObj::Array(items)) => {
2261                key == "length"
2262                    || key
2263                        .parse::<usize>()
2264                        .map(|i| i < items.len())
2265                        .unwrap_or(false)
2266                    || self.fn_prop(owner, key).is_some()
2267            }
2268            // A RegExp's `lastIndex` is an own property, so a merely
2269            // NON-EXTENSIBLE regexp still accepts a write to it.
2270            Some(JsObj::RegExp(_)) => key == "lastIndex" || self.fn_prop(owner, key).is_some(),
2271            // Every other shape keeps its own properties in the fn-prop side
2272            // table (a function's statics, a Map's assigned properties), so
2273            // "does it already own this key" is that table's question. Answering
2274            // a blanket `true` let a NEW key land on a frozen function and a
2275            // frozen Map.
2276            _ => self.fn_prop(owner, key).is_some(),
2277        }
2278    }
2279
2280    /// Whether `key` is an array index at or past the `length` of an array
2281    /// whose `length` is not writable — an element 10.4.2.1 step 3.b refuses
2282    /// to add, since adding it would have to grow `length`.
2283    pub fn past_fixed_length(&self, owner: &Value, key: &str) -> bool {
2284        match self.get(owner) {
2285            Some(JsObj::Array(items)) => {
2286                array_index(key).is_some_and(|i| i as usize >= items.len())
2287                    && !self.prop_attrs(owner, "length").writable
2288                    && !crate::builtins::is_arguments_h(self, owner)
2289            }
2290            _ => false,
2291        }
2292    }
2293
2294    /// Mark `v` closed to new properties (`Object.preventExtensions`).
2295    pub fn prevent_extensions(&mut self, v: &Value) {
2296        if let Value::Obj(i) = v {
2297            self.non_extensible.insert(*i);
2298        }
2299    }
2300
2301    pub fn is_extensible(&self, v: &Value) -> bool {
2302        !matches!(v, Value::Obj(i) if self.non_extensible.contains(i))
2303    }
2304
2305    /// Whether `v` is closed to new properties or carries any own property
2306    /// that is not a plain writable, enumerable, configurable data property —
2307    /// the objects on which a write or delete can be refused.
2308    pub fn has_integrity_limits(&self, v: &Value) -> bool {
2309        match v {
2310            Value::Obj(i) => {
2311                self.non_extensible.contains(i)
2312                    || self.prop_attrs.contains_key(i)
2313                    || self.accessors.contains_key(i)
2314            }
2315            _ => false,
2316        }
2317    }
2318
2319    /// Apply `Object.seal` (`freeze == false`) or `Object.freeze` (`true`): close
2320    /// the object and strip `configurable` — and, when freezing, `writable` —
2321    /// from every own property, data and accessor alike.
2322    pub fn seal_object(&mut self, v: &Value, freeze: bool) {
2323        self.prevent_extensions(v);
2324        let mut keys = self.integrity_keys(v);
2325        keys.extend(self.own_accessor_keys(v));
2326        for k in keys {
2327            let mut a = self.prop_attrs(v, &k);
2328            a.configurable = false;
2329            if freeze {
2330                a.writable = false;
2331            }
2332            self.set_prop_attrs(v, &k, a);
2333        }
2334    }
2335
2336    /// The own DATA-property keys SetIntegrityLevel (7.3.15) walks.
2337    ///
2338    /// An array's elements are own properties too, and only the `Object` arm was
2339    /// walked — so `Object.freeze([1, 2])` sealed nothing: `a[0] = 9` wrote
2340    /// through, and the elements still reported `writable: true,
2341    /// configurable: true` while `Object.isFrozen` answered true over an empty
2342    /// key list. `length` is an own property as well, and freezing it is what
2343    /// stops a `push` from extending a frozen array.
2344    fn integrity_keys(&self, v: &Value) -> Vec<String> {
2345        let side_table_keys = |v: &Value| -> Vec<String> {
2346            match v {
2347                Value::Obj(i) => self
2348                    .fn_props
2349                    .get(i)
2350                    .map(|m| m.keys().cloned().collect())
2351                    .unwrap_or_default(),
2352                _ => Vec::new(),
2353            }
2354        };
2355        match self.get(v) {
2356            Some(JsObj::Object(p)) => p.keys().cloned().collect(),
2357            // A RegExp's only own property is its `lastIndex` cursor, which
2358            // lives in the `RegExpObj` struct. Without it here `Object.freeze`
2359            // sealed nothing and a frozen regexp's cursor still moved.
2360            Some(JsObj::RegExp(_)) => vec!["lastIndex".to_string()],
2361            // A function's statics and a Map's assigned properties live in the
2362            // fn-prop side table, and freezing has to reach them too.
2363            Some(JsObj::Func(_))
2364            | Some(JsObj::Class(_))
2365            | Some(JsObj::Map { .. })
2366            | Some(JsObj::Set { .. })
2367            | Some(JsObj::Promise { .. }) => side_table_keys(v),
2368            Some(JsObj::Array(items)) => (0..items.len())
2369                .map(|i| i.to_string())
2370                .chain(std::iter::once("length".to_string()))
2371                // A named property stuck on an array (`a.tag = 't'`, a match
2372                // array's `.index`/`.groups`) is an own property too, and
2373                // freezing has to reach it.
2374                .chain(match v {
2375                    Value::Obj(i) => self
2376                        .fn_props
2377                        .get(i)
2378                        .map(|m| m.keys().cloned().collect::<Vec<_>>())
2379                        .unwrap_or_default(),
2380                    _ => Vec::new(),
2381                })
2382                .collect(),
2383            _ => Vec::new(),
2384        }
2385    }
2386
2387    /// `Object.isSealed` (`freeze == false`) / `Object.isFrozen` (`true`).
2388    pub fn is_sealed(&self, v: &Value, freeze: bool) -> bool {
2389        if self.is_extensible(v) {
2390            return false;
2391        }
2392        let mut keys = self.integrity_keys(v);
2393        keys.extend(self.own_accessor_keys(v));
2394        keys.iter().all(|k| {
2395            let a = self.prop_attrs(v, k);
2396            !a.configurable && (!freeze || !a.writable)
2397        })
2398    }
2399
2400    /// A fresh unique `Symbol(desc)` value.
2401    pub fn new_symbol(&mut self, desc: Option<String>) -> Value {
2402        let id = self.next_symbol;
2403        self.next_symbol += 1;
2404        let v = self.alloc(JsObj::Symbol { desc, id });
2405        self.symbols_by_id.insert(id, v.clone());
2406        v
2407    }
2408
2409    /// The symbol VALUE an internal symbol property key (`@@sym:<id>` or a
2410    /// well-known `@@iterator`) came from.
2411    pub fn symbol_of_key(&self, k: &str) -> Option<Value> {
2412        if let Some(id) = k.strip_prefix("@@sym:").and_then(|i| i.parse::<u64>().ok()) {
2413            return self.symbols_by_id.get(&id).cloned();
2414        }
2415        let name = k.strip_prefix("@@")?;
2416        WELL_KNOWN_SYMBOLS
2417            .contains(&name)
2418            .then(|| {
2419                self.symbol_registry
2420                    .get(&format!("@@Symbol.{name}"))
2421                    .cloned()
2422            })
2423            .flatten()
2424    }
2425
2426    /// The own symbol-keyed property keys of `v` as SYMBOL values —
2427    /// `Object.getOwnPropertySymbols` / the symbol half of `Reflect.ownKeys`.
2428    pub fn own_symbol_keys(&self, v: &Value) -> Vec<Value> {
2429        let mut keys: Vec<String> = match self.get(v) {
2430            Some(JsObj::Object(p)) => p.keys().cloned().collect(),
2431            // An Array/Function receiver has no property map: its non-index own
2432            // properties — symbol-keyed ones included — live in the fn-prop side
2433            // table, and are just as much own properties as an object's.
2434            Some(_) => self.fn_prop_keys(v),
2435            None => return Vec::new(),
2436        };
2437        // A symbol-keyed ACCESSOR is an own property too: it sits in the table
2438        // as its ordering marker, or — defined on a class body — only in the
2439        // accessor table, so `Reflect.ownKeys(C.prototype)` omitted the
2440        // `Symbol.split` of `class C { get [Symbol.split]() {} }`.
2441        for k in keys.iter_mut() {
2442            if let Some(real) = k.strip_prefix(ORD_MARKER) {
2443                *k = real.to_string();
2444            }
2445        }
2446        for k in self.own_accessor_keys(v) {
2447            if !keys.contains(&k) {
2448                keys.push(k);
2449            }
2450        }
2451        let mut seen: Vec<&str> = Vec::new();
2452        keys.iter()
2453            .filter(|k| {
2454                let fresh = !seen.contains(&k.as_str());
2455                seen.push(k);
2456                fresh
2457            })
2458            .filter_map(|k| self.symbol_of_key(k))
2459            .collect()
2460    }
2461
2462    /// The own SYMBOL-keyed enumerable `(internal key, value)` pairs of `v` —
2463    /// what `CopyDataProperties` (object spread, `Object.assign`) copies
2464    /// alongside the string keys, and what `Object.keys` / `for-in` /
2465    /// `JSON.stringify` deliberately skip.
2466    pub fn own_symbol_entries(&self, v: &Value) -> Vec<(String, Value)> {
2467        match self.get(v) {
2468            Some(JsObj::Object(p)) => p
2469                .iter()
2470                .filter(|(k, _)| is_symbol_key(k) && self.prop_attrs(v, k).enumerable)
2471                .map(|(k, val)| (k.clone(), val.clone()))
2472                .collect(),
2473            // Array/Function: the side table (see `own_symbol_keys`).
2474            Some(_) => self
2475                .fn_prop_keys(v)
2476                .into_iter()
2477                .filter(|k| is_symbol_key(k) && self.prop_attrs(v, k).enumerable)
2478                .map(|k| {
2479                    let val = self.fn_prop(v, &k).unwrap_or(Value::Undef);
2480                    (k, val)
2481                })
2482                .collect(),
2483            None => Vec::new(),
2484        }
2485    }
2486    /// The shared `Symbol.for(key)` value (interned by description).
2487    pub fn symbol_for(&mut self, key: &str) -> Value {
2488        if let Some(v) = self.symbol_registry.get(key) {
2489            return v.clone();
2490        }
2491        let s = self.new_symbol(Some(key.to_string()));
2492        self.symbol_registry.insert(key.to_string(), s.clone());
2493        s
2494    }
2495    /// A process-wide symbol node keeps privately (`events.errorMonitor`): one
2496    /// identity for every read, described by `desc`, but NOT in the
2497    /// `Symbol.for` registry, so `Symbol.keyFor` answers `undefined` for it.
2498    /// It shares the registry map under a `@@Symbol.` key, which
2499    /// `symbol_registry_key` already excludes.
2500    pub fn internal_symbol(&mut self, desc: &str) -> Value {
2501        let key = format!("@@Symbol.@internal:{desc}");
2502        if let Some(v) = self.symbol_registry.get(&key) {
2503            return v.clone();
2504        }
2505        let s = self.new_symbol(Some(desc.to_string()));
2506        self.symbol_registry.insert(key, s.clone());
2507        s
2508    }
2509    /// `Symbol.keyFor(sym)`: the registry key `Symbol.for` interned `sym` under,
2510    /// or `undefined` for a symbol that is not in the registry at all.
2511    ///
2512    /// Matched by symbol IDENTITY, not by description — `Symbol.for('k')` and
2513    /// `Symbol('k')` share a description and only the first is registered. The
2514    /// `@@Symbol.*` well-known entries are registry-internal and never a
2515    /// `keyFor` answer, matching node: `Symbol.keyFor(Symbol.iterator)` is
2516    /// `undefined` there.
2517    pub fn symbol_registry_key(&mut self, sym: &Value) -> Value {
2518        let Some(key) = self
2519            .symbol_registry
2520            .iter()
2521            .find(|(k, v)| self.strict_eq(v, sym) && !k.starts_with("@@Symbol."))
2522            .map(|(k, _)| k.clone())
2523        else {
2524            return Value::Undef;
2525        };
2526        self.new_str(key)
2527    }
2528    /// The well-known `Symbol.iterator` (a fixed shared symbol whose internal
2529    /// property key is `@@iterator`).
2530    pub fn well_known_iterator(&mut self) -> Value {
2531        self.symbol_for("@@Symbol.iterator")
2532    }
2533    /// The well-known `Symbol.asyncIterator` (internal key `@@asyncIterator`).
2534    pub fn well_known_async_iterator(&mut self) -> Value {
2535        self.symbol_for("@@Symbol.asyncIterator")
2536    }
2537    /// A well-known symbol by its ECMAScript name (`toPrimitive`,
2538    /// `toStringTag`, …). Its internal property key is `@@<name>` — see
2539    /// [`WELL_KNOWN_SYMBOLS`] and `property_key`.
2540    ///
2541    /// Its DESCRIPTION is `Symbol.<name>`, so `String(Symbol.iterator)` prints
2542    /// `Symbol(Symbol.iterator)` as V8 does, while the registry key keeps the
2543    /// `@@` prefix — `Symbol.for('Symbol.iterator')` therefore stays a
2544    /// different symbol, and identification is by id, so a user-made
2545    /// `Symbol('Symbol.iterator')` is not mistaken for the well-known one.
2546    pub fn well_known_symbol(&mut self, name: &str) -> Value {
2547        let key = format!("@@Symbol.{name}");
2548        if let Some(v) = self.symbol_registry.get(&key) {
2549            return v.clone();
2550        }
2551        let s = self.new_symbol(Some(format!("Symbol.{name}")));
2552        if let Some(JsObj::Symbol { id, .. }) = self.get(&s) {
2553            self.well_known_ids.insert(*id, name.to_string());
2554        }
2555        self.symbol_registry.insert(key, s.clone());
2556        s
2557    }
2558    /// The internal property-key string for a value used as a key. A `Symbol`
2559    /// maps to a stable per-symbol string so symbol-keyed props round-trip;
2560    /// `Symbol.iterator` maps to the sentinel `@@iterator`.
2561    pub fn property_key(&self, v: &Value) -> String {
2562        if let Some(JsObj::Symbol { id, .. }) = self.get(v) {
2563            if let Some(n) = self.well_known_ids.get(id) {
2564                return format!("@@{n}");
2565            }
2566            return format!("@@sym:{id}");
2567        }
2568        self.str_of(v)
2569    }
2570
2571    pub fn null(&self) -> Value {
2572        self.null_val.clone()
2573    }
2574    pub fn is_null(&self, v: &Value) -> bool {
2575        matches!(self.get(v), Some(JsObj::Null))
2576    }
2577
2578    // ── program loading ──────────────────────────────────────────────────
2579    pub fn program_offsets(&self) -> (usize, usize) {
2580        (self.funcs.len(), self.tries.len())
2581    }
2582    pub fn load_program(&mut self, funcs: Vec<FuncDef>, tries: Vec<TryDef>) {
2583        self.funcs.extend(funcs);
2584        self.tries.extend(tries);
2585    }
2586    /// The source text of function `def_id`, when its program kept one.
2587    pub fn func_source(&self, def_id: usize) -> Option<&str> {
2588        let d = self.funcs.get(def_id)?;
2589        let (start, end) = d.span;
2590        if end == 0 {
2591            return None;
2592        }
2593        self.scripts
2594            .get(d.script? as usize)?
2595            .get(start as usize..end as usize)
2596    }
2597    pub fn try_def(&self, id: usize) -> Option<TryDef> {
2598        self.tries.get(id).cloned()
2599    }
2600
2601    /// What `try` statement `id` HAS — `(has handler, catch parameter name, has
2602    /// finalizer)` — without copying its chunks. Running a `try` used to clone
2603    /// the whole `TryDef`, so a `try` inside a loop deep-copied its block, its
2604    /// handler and its finalizer on every iteration just to learn its shape.
2605    pub fn try_shape(&self, id: usize) -> Option<(bool, Option<String>, bool)> {
2606        let t = self.tries.get(id)?;
2607        Some((
2608            t.handler.is_some(),
2609            t.handler.as_ref().and_then(|(bind, _)| bind.clone()),
2610            t.finalizer.is_some(),
2611        ))
2612    }
2613
2614    /// One `try` part's bytecode: 0 = block, 1 = handler body, 2 = finalizer.
2615    /// Reached only when no pooled VM already holds that chunk.
2616    pub fn try_chunk(&self, id: usize, part: u64) -> Option<Chunk> {
2617        let t = self.tries.get(id)?;
2618        match part {
2619            0 => Some(t.block.clone()),
2620            1 => t.handler.as_ref().map(|(_, body)| body.clone()),
2621            _ => t.finalizer.clone(),
2622        }
2623    }
2624
2625    // ── heap allocation / accessors ──────────────────────────────────────
2626    pub fn alloc(&mut self, obj: JsObj) -> Value {
2627        self.heap.push(obj);
2628        Value::Obj((self.heap.len() - 1) as u32)
2629    }
2630    pub fn get(&self, v: &Value) -> Option<&JsObj> {
2631        if let Value::Obj(i) = v {
2632            self.heap.get(*i as usize)
2633        } else {
2634            None
2635        }
2636    }
2637    pub fn get_mut(&mut self, v: &Value) -> Option<&mut JsObj> {
2638        if let Value::Obj(i) = v {
2639            self.heap.get_mut(*i as usize)
2640        } else {
2641            None
2642        }
2643    }
2644    /// Which variant `v` points at, without copying its contents. Use this in
2645    /// place of `get(v).cloned()` whenever only the tag is needed — see
2646    /// [`ObjKind`].
2647    pub fn kind_of(&self, v: &Value) -> Option<ObjKind> {
2648        self.get(v).map(JsObj::kind)
2649    }
2650    pub fn new_str(&mut self, s: impl Into<String>) -> Value {
2651        self.alloc(JsObj::Str(s.into()))
2652    }
2653    pub fn new_array(&mut self, items: Vec<Value>) -> Value {
2654        self.alloc(JsObj::Array(items))
2655    }
2656
2657    /// Record that `name` was declared as a private method or accessor.
2658    pub fn note_private_method(&mut self, name: &str) {
2659        self.private_methods.insert(name.to_string());
2660    }
2661
2662    /// Whether `name` was declared as a private method/accessor by some class,
2663    /// as opposed to a private field.
2664    pub fn is_private_method(&self, name: &str) -> bool {
2665        self.private_methods.contains(name)
2666    }
2667
2668    /// The name of the class whose body the running function belongs to. Only a
2669    /// method of that class can even mention its private names, so this is the
2670    /// class a failed brand check must name.
2671    /// The `super` binding of the frame now running: the owning class name,
2672    /// whether the method is static, and the home object of an object-literal
2673    /// method. An ARROW captures all three at creation, the way it captures
2674    /// `this` — `super` inside an arrow means the enclosing METHOD's `super`.
2675    /// Whether the activation now running is strict code.
2676    /// Whether `v` is a function whose own body is SLOPPY — not an arrow, and
2677    /// with no `'use strict'` of its own or inherited from its script. This is
2678    /// the receiver test the `arguments`/`caller` poison pill keys on: node
2679    /// decides by the FUNCTION, never by the code doing the reading.
2680    pub fn fn_is_sloppy(&self, v: &Value) -> bool {
2681        match self.get(v) {
2682            Some(JsObj::Func(fv)) => {
2683                !fv.is_arrow && !self.funcs.get(fv.def_id).is_some_and(|d| d.strict)
2684            }
2685            _ => false,
2686        }
2687    }
2688    pub fn current_strict(&self) -> bool {
2689        self.frame().strict || self.forced_strict > 0
2690    }
2691
2692    /// Run `f` with every write refusal treated as in strict code, whatever the
2693    /// running function's own mode: a builtin that performs `Set(O, P, V, true)`
2694    /// (`Object.assign`) throws on a refused write even when called from sloppy
2695    /// code.
2696    pub fn with_forced_strict<T>(f: impl FnOnce() -> T) -> T {
2697        with_host(|h| h.forced_strict += 1);
2698        let r = f();
2699        with_host(|h| h.forced_strict -= 1);
2700        r
2701    }
2702
2703    /// Mark the frame about to run as STRICT — used for a program whose own top
2704    /// level says `'use strict'`, which has no `FuncDef` to carry the flag.
2705    pub fn set_current_strict(&mut self) {
2706        if let Some(f) = self.frames.last_mut() {
2707            f.strict = true;
2708        }
2709    }
2710
2711    pub fn current_home(&self) -> (Option<String>, bool, Option<Value>) {
2712        (
2713            self.current_home_class_name(),
2714            self.frame().home_static,
2715            self.frame().home_object.clone(),
2716        )
2717    }
2718
2719    pub fn current_home_class_name(&self) -> Option<String> {
2720        match self.get(&self.current_home_class()?) {
2721            Some(JsObj::Class(c)) => Some(c.name.clone()),
2722            _ => None,
2723        }
2724    }
2725
2726    /// Whether `recv` itself carries the private name `key`. Private elements
2727    /// are never inherited — `Object.create(instance)` has none of its
2728    /// prototype's — so a private METHOD is installed on every instance when it
2729    /// is constructed (see [`install_private_methods`]) rather than found one
2730    /// link up on the class prototype.
2731    pub fn has_private(&self, recv: &Value, key: &str) -> bool {
2732        let owns = match self.get(recv) {
2733            Some(JsObj::Object(p)) => p.contains_key(key),
2734            Some(JsObj::Class(c)) => c.statics.contains_key(key),
2735            _ => false,
2736        };
2737        owns || self.own_accessor(recv, key).is_some() || self.fn_prop(recv, key).is_some()
2738    }
2739
2740    /// `C.prototype` of the class whose method is running.
2741    pub fn current_home_proto(&self) -> Option<Value> {
2742        match self.get(&self.current_home_class()?) {
2743            Some(JsObj::Class(c)) => Some(c.proto.clone()),
2744            _ => None,
2745        }
2746    }
2747
2748    // ── array holes ──────────────────────────────────────────────────────
2749    //
2750    // Every read/write of an array's elision set goes through this block. See
2751    // the `array_holes` field for why the marker lives here rather than in
2752    // `Value`.
2753
2754    /// Whether element `i` of array `arr` is an elided element (a "hole"), as
2755    /// opposed to a stored `undefined`. `false` for anything that is not an
2756    /// array, and for every index of a dense one.
2757    pub fn is_hole(&self, arr: &Value, i: usize) -> bool {
2758        match (arr, ()) {
2759            (Value::Obj(idx), ()) => self.array_holes.get(idx).is_some_and(|hs| hs.contains(&i)),
2760            _ => false,
2761        }
2762    }
2763
2764    /// Whether `arr` has any elided element at all — one hash probe, and the
2765    /// guard every hole-aware code path takes before doing anything slower.
2766    pub fn has_holes(&self, arr: &Value) -> bool {
2767        matches!(arr, Value::Obj(i) if self.array_holes.contains_key(i))
2768    }
2769
2770    /// `arr`'s hole positions in ASCENDING order, or an empty vec if dense.
2771    /// Sorted because every consumer (own-key enumeration, `util.inspect`
2772    /// run-grouping) needs index order, and the backing set has none.
2773    pub fn hole_indices(&self, arr: &Value) -> Vec<usize> {
2774        let Value::Obj(i) = arr else {
2775            return Vec::new();
2776        };
2777        let Some(hs) = self.array_holes.get(i) else {
2778            return Vec::new();
2779        };
2780        let mut v: Vec<usize> = hs.iter().copied().collect();
2781        v.sort_unstable();
2782        v
2783    }
2784
2785    /// Record element `i` of `arr` as elided.
2786    pub fn mark_hole(&mut self, arr: &Value, i: usize) {
2787        if let Value::Obj(idx) = arr {
2788            self.array_holes.entry(*idx).or_default().insert(i);
2789        }
2790    }
2791
2792    /// Record `range` of `arr` as elided (a `new Array(n)`, a `length` grow, or
2793    /// the gap a write past the end opens).
2794    pub fn mark_hole_range(&mut self, arr: &Value, range: std::ops::Range<usize>) {
2795        if range.is_empty() {
2796            return;
2797        }
2798        if let Value::Obj(idx) = arr {
2799            self.array_holes.entry(*idx).or_default().extend(range);
2800        }
2801    }
2802
2803    /// Element `i` now holds a real value: it is no longer a hole. Every write
2804    /// to an array index calls this, which is what keeps a stale hole record
2805    /// from outliving the elision it described.
2806    pub fn clear_hole(&mut self, arr: &Value, i: usize) {
2807        let Value::Obj(idx) = arr else { return };
2808        let Some(hs) = self.array_holes.get_mut(idx) else {
2809            return;
2810        };
2811        hs.remove(&i);
2812        if hs.is_empty() {
2813            self.array_holes.remove(idx);
2814        }
2815    }
2816
2817    /// `arr` is dense from here on (`fill` over the whole array, a fresh
2818    /// dense assignment into an existing handle).
2819    pub fn clear_holes(&mut self, arr: &Value) {
2820        if let Value::Obj(idx) = arr {
2821            self.array_holes.remove(idx);
2822        }
2823    }
2824
2825    /// Copy `src`'s elision set onto `dst`, optionally shifting each position by
2826    /// `f`. Used by every method that derives a new array whose holes track the
2827    /// source's (`slice`, `concat`, `map`).
2828    pub fn copy_holes(&mut self, src: &Value, dst: &Value, f: impl Fn(usize) -> Option<usize>) {
2829        if !self.has_holes(src) {
2830            return;
2831        }
2832        let moved: rustc_hash::FxHashSet<usize> =
2833            self.hole_indices(src).into_iter().filter_map(f).collect();
2834        self.install_holes(dst, moved);
2835    }
2836
2837    /// Rewrite `arr`'s own elision set in place: `f(i)` gives the position each
2838    /// existing hole moves to, or `None` if the mutation removed it. This is the
2839    /// one primitive behind every structural array mutation — `shift` is
2840    /// `i.checked_sub(1)`, `unshift(k)` is `i + k`, `reverse` is `len-1-i`, and
2841    /// `splice` is the general case.
2842    pub fn remap_holes(&mut self, arr: &Value, f: impl Fn(usize) -> Option<usize>) {
2843        if !self.has_holes(arr) {
2844            return;
2845        }
2846        let moved: rustc_hash::FxHashSet<usize> =
2847            self.hole_indices(arr).into_iter().filter_map(f).collect();
2848        self.install_holes(arr, moved);
2849    }
2850
2851    /// Replace `arr`'s elision set outright, dropping the record entirely when
2852    /// the new set is empty so `has_holes` stays a single negative probe for the
2853    /// dense case.
2854    pub fn install_holes(&mut self, arr: &Value, holes: rustc_hash::FxHashSet<usize>) {
2855        let Value::Obj(idx) = arr else { return };
2856        if holes.is_empty() {
2857            self.array_holes.remove(idx);
2858        } else {
2859            self.array_holes.insert(*idx, holes);
2860        }
2861    }
2862
2863    /// Forget any hole at or past `len` — what a `pop`, a `length` shrink or a
2864    /// truncating `splice` leaves behind.
2865    pub fn truncate_holes(&mut self, arr: &Value, len: usize) {
2866        self.remap_holes(arr, |i| (i < len).then_some(i));
2867    }
2868
2869    /// `util.inspect`'s `formatSpecialArray`: the element strings of a SPARSE
2870    /// array, where each maximal run of elided positions collapses to a single
2871    /// `<N empty items>` entry. Returns the entries and whether the last of them
2872    /// is the `... N more items` tail (which the grid layout must not size a
2873    /// column to).
2874    ///
2875    /// The `maxArrayLength` cap counts ENTRIES, not indices, so a run costs one
2876    /// slot however long it is — matching node, where `[ ...Array(200) ]`-style
2877    /// sparse arrays print a single `<200 empty items>`.
2878    fn inspect_sparse(
2879        &self,
2880        v: &Value,
2881        items: &[Value],
2882        indent: usize,
2883        st: &mut InspectCycles,
2884    ) -> (Vec<String>, bool) {
2885        let holes: rustc_hash::FxHashSet<usize> = self.hole_indices(v).into_iter().collect();
2886        let empties = |n: usize| {
2887            let unit = if n == 1 { "item" } else { "items" };
2888            format!("<{n} empty {unit}>")
2889        };
2890        let mut out: Vec<String> = Vec::new();
2891        // The first index not yet accounted for by an entry.
2892        let mut index = 0usize;
2893        for (i, it) in items.iter().enumerate() {
2894            if out.len() >= inspect_max_array_length() {
2895                break;
2896            }
2897            if holes.contains(&i) {
2898                continue;
2899            }
2900            if i > index {
2901                out.push(empties(i - index));
2902                index = i;
2903                if out.len() >= inspect_max_array_length() {
2904                    break;
2905                }
2906            }
2907            out.push(self.inspect_lvl(it, indent + 2, st));
2908            index = i + 1;
2909        }
2910        let remaining = items.len() - index;
2911        if remaining == 0 {
2912            return (out, false);
2913        }
2914        if out.len() < inspect_max_array_length() {
2915            // Trailing holes are still `<N empty items>`, not a truncation.
2916            out.push(empties(remaining));
2917            (out, false)
2918        } else {
2919            let unit = if remaining == 1 { "item" } else { "items" };
2920            out.push(format!("... {remaining} more {unit}"));
2921            (out, true)
2922        }
2923    }
2924    pub fn new_object(&mut self, mut props: IndexMap<String, Value>) -> Value {
2925        // Integer-index keys enumerate ascending-first regardless of the order
2926        // they were supplied in (object literal, spread, Object.assign result).
2927        canonicalize_own_keys(&mut props);
2928        // A map carrying the hidden `@@native` tag IS an instance of that native
2929        // class, so it hangs off the class prototype rather than
2930        // `Object.prototype`. Eleven classes — `Hash`, `Cipheriv`,
2931        // `StringDecoder`, `Script`, `URLSearchParams`, `Console`,
2932        // `AbortController` among them — built plain objects instead, so
2933        // `x.constructor.name` read `"Object"` and a chain walk found none of
2934        // the class's methods. Linking HERE means a construction site cannot
2935        // forget it; the tag is already in the map at every one of them.
2936        let tag = props.get("@@native").and_then(|v| self.as_str(v));
2937        let obj = self.alloc(JsObj::Object(props));
2938        if let Some(proto) = tag.and_then(|t| self.ensure_ctor_proto(&t)) {
2939            self.set_proto(&obj, proto);
2940        }
2941        obj
2942    }
2943    pub fn as_str(&self, v: &Value) -> Option<String> {
2944        match v {
2945            Value::Str(s) => Some((**s).clone()),
2946            Value::Obj(_) => match self.get(v) {
2947                Some(JsObj::Str(s)) => Some(s.clone()),
2948                _ => None,
2949            },
2950            _ => None,
2951        }
2952    }
2953
2954    // ── scope / names ────────────────────────────────────────────────────
2955    fn frame(&self) -> &Frame {
2956        self.frames.last().unwrap()
2957    }
2958    fn cur_env(&self) -> Env {
2959        self.frame().env.clone()
2960    }
2961
2962    // ── DAP debug introspection (used only under `--dap`) ────────────────────
2963    /// Number of active call frames (the debugger's step-depth reference).
2964    pub fn frame_depth(&self) -> usize {
2965        self.frames.len()
2966    }
2967    /// Record the source line the innermost frame is executing (DAP line hook).
2968    pub fn set_cur_line(&mut self, line: u32) {
2969        if let Some(f) = self.frames.last_mut() {
2970            f.line = line;
2971        }
2972    }
2973    /// V8's `Error.stackTraceLimit` — how many frames a captured stack keeps.
2974    ///
2975    /// The default is 10, it is settable, and setting it to 0 is the documented
2976    /// way to make error construction cheap. It did not exist, so the read was
2977    /// `undefined` and every stack carried every frame regardless.
2978    pub fn stack_trace_limit(&self) -> usize {
2979        match self.builtin_static("Error", "stackTraceLimit") {
2980            Some(v) => {
2981                let n = self.to_number(&v);
2982                if n.is_finite() && n > 0.0 {
2983                    n as usize
2984                } else if n.is_nan() || n <= 0.0 {
2985                    0
2986                } else {
2987                    usize::MAX
2988                }
2989            }
2990            None => 10,
2991        }
2992    }
2993
2994    /// The `.stack` tail for an error created right now: one `    at …` line
2995    /// per live frame, innermost first, in V8's `CallSite` format —
2996    /// `at f (file:line:col)`, `at new C (…)`, `at Object.m (…)`, and the bare
2997    /// `at file:line:col` of an anonymous function or a script's top level.
2998    ///
2999    /// Each frame's location is the op it was executing when it last called
3000    /// out (see [`Frame::pos`]), so the innermost frame of a `new Error()` names
3001    /// the `new` and every outer frame names its call. These are the user's
3002    /// frames only: node's own loader frames (`Module._compile`, …) and the
3003    /// frames of native functions (`Array.map (<anonymous>)`) do not exist in
3004    /// this runtime.
3005    pub fn stack_frames(&self) -> String {
3006        self.stack_frames_from(self.frames.len())
3007    }
3008
3009    /// [`JsHost::stack_frames`] over the frames below `top` — the error
3010    /// constructors skip the frames of the subclass constructors that are
3011    /// building the error, as V8's `SKIP_UNTIL_SEEN` mode does.
3012    pub fn stack_frames_from(&self, top: usize) -> String {
3013        let limit = self.stack_trace_limit();
3014        if limit == 0 {
3015            return String::new();
3016        }
3017        let mut out = String::new();
3018        // The running context's frames, then — when a generator or async body
3019        // is running — the frames of each context that resumed it, innermost
3020        // first. Each item: the frame, whether it is the bottom of its
3021        // context, and its position.
3022        let current = self.frames[..top]
3023            .iter()
3024            .enumerate()
3025            .rev()
3026            .map(|(i, f)| (f, i == 0, self.frame_pos_of(i)));
3027        let resumers = self
3028            .outer_frames
3029            .iter()
3030            .rev()
3031            .flat_map(|fs| fs.iter().enumerate().rev().map(|(i, f)| (f, i == 0, f.pos)));
3032        let shown = current
3033            .chain(resumers)
3034            .map(|(f, bottom, pos)| (f, bottom, pos, self.source_location(pos)))
3035            // The program's own frame once its top level has finished (a
3036            // timer or a promise reaction runs on it, where node has only its
3037            // own loop frames) or before it has run anything (a SyntaxError),
3038            // and the runtime's internal JS.
3039            .filter(|(f, bottom, pos, loc)| {
3040                !(*bottom && f.is_module && (self.module_frame_done || *pos == 0))
3041                    && !loc.as_ref().is_some_and(|l| l.internal)
3042            })
3043            .map(|(f, _, _, loc)| (f, loc));
3044        for (f, loc) in shown.take(limit) {
3045            let name = self.frame_function_name(f, loc.as_ref().map(|l| l.name));
3046            out.push_str("\n    at ");
3047            match (name, loc) {
3048                (Some(n), Some(l)) => {
3049                    out.push_str(&format!("{n} ({}:{}:{})", l.name, l.line, l.col))
3050                }
3051                (Some(n), None) => out.push_str(&n),
3052                (None, Some(l)) => out.push_str(&format!("{}:{}:{}", l.name, l.line, l.col)),
3053                (None, None) => out.push_str("<anonymous>"),
3054            }
3055        }
3056        // With no frame at all there is still V8's one anonymous line. Frames
3057        // that exist but were left out stand for node's own, which a stack
3058        // there shows instead.
3059        if out.is_empty() && top == 0 {
3060            out.push_str("\n    at <anonymous>");
3061        }
3062        out
3063    }
3064
3065    /// How V8's `CallSite` names the function of frame `f`
3066    /// (`CallSiteInfo::GetFunctionName` / `GetTypeName`): `new F` for a
3067    /// construct call; `Type.f` for a method call on a receiver of type `Type`
3068    /// (the CommonJS module function is anonymous and called on
3069    /// `module.exports`, hence `Object.<anonymous>`); a plain `f` when the
3070    /// receiver is the global object or `undefined`, or the function is an
3071    /// arrow; nothing for an anonymous function or the top level of an
3072    /// `[eval]` script or an ES module.
3073    fn frame_function_name(&self, f: &Frame, script: Option<&str>) -> Option<String> {
3074        let own = f.owner.as_deref().filter(|n| !n.is_empty());
3075        if f.new_target.is_some() {
3076            return Some(format!("new {}", own.unwrap_or("<anonymous>")));
3077        }
3078        if f.is_module {
3079            // A top level. A CommonJS entry file's runs inside node's module
3080            // wrapper, called on `module.exports`; it is named by its path.
3081            return match script {
3082                Some(s) if s.starts_with('/') => Some("Object.<anonymous>".to_string()),
3083                Some(_) => None,
3084                None => Some("Object.<anonymous>".to_string()),
3085            };
3086        }
3087        // `GetTypeName`: a function receiver (a static method's class) is
3088        // named by its own name, anything else by its constructor's.
3089        let method_type = match &f.this_obj {
3090            Some(t @ Value::Obj(_)) if !f.arrow && !self.is_global_object(t) => {
3091                let own_name = match self.get(t) {
3092                    Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => self.callable_name(t),
3093                    _ => String::new(),
3094                };
3095                Some(match own_name {
3096                    n if !n.is_empty() => n,
3097                    _ => match self.ctor_name(t) {
3098                        n if n.is_empty() => "Object".to_string(),
3099                        n => n,
3100                    },
3101                })
3102            }
3103            _ => None,
3104        };
3105        match (method_type, own) {
3106            // `AppendMethodCall` drops the type when the name already starts
3107            // with it; an accessor (`get g`) prints without one as well.
3108            (Some(t), Some(n))
3109                if n.starts_with(&t) || n.starts_with("get ") || n.starts_with("set ") =>
3110            {
3111                Some(n.to_string())
3112            }
3113            (Some(t), Some(n)) => Some(format!("{t}.{n}")),
3114            (Some(t), None) => Some(format!("{t}.<anonymous>")),
3115            (None, Some(n)) => Some(n.to_string()),
3116            (None, None) => None,
3117        }
3118    }
3119
3120    /// Give `script` the next range of the source address space and return its
3121    /// base: a [`crate::ast::Pos`] `p` in that script becomes `base + p - 1`, so
3122    /// one `u32` names a place in any loaded script. Ranges are never reused.
3123    pub fn register_source(&mut self, script: u32, origin: ScriptOrigin) -> u32 {
3124        let base = self.source_map.last().map_or(1, |r| r.base + r.len + 1);
3125        let len = self.scripts[script as usize].len() as u32;
3126        self.source_map.push(ScriptRange {
3127            base,
3128            len,
3129            script,
3130            origin,
3131            line_starts: std::cell::OnceCell::new(),
3132        });
3133        base
3134    }
3135
3136    /// The position of the first reference to identifier `name` at or after
3137    /// `pos`, else `pos` itself.
3138    ///
3139    /// An identifier carries no position of its own, so an op that reads or
3140    /// writes a name is placed at its statement; V8 places a `ReferenceError`
3141    /// at the identifier. The first whole-word occurrence from the statement on
3142    /// that is not a property name (`o.name`) is the reference evaluated first.
3143    pub fn name_position(&self, pos: u32, name: &str) -> u32 {
3144        let Some(r) = pos
3145            .checked_sub(1)
3146            .and_then(|_| {
3147                self.source_map
3148                    .partition_point(|r| r.base <= pos)
3149                    .checked_sub(1)
3150            })
3151            .map(|i| &self.source_map[i])
3152        else {
3153            return pos;
3154        };
3155        let Some(text) = self.scripts.get(r.script as usize) else {
3156            return pos;
3157        };
3158        let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
3159        let start = (pos - r.base) as usize;
3160        let Some(tail) = text.get(start..) else {
3161            return pos;
3162        };
3163        for (at, _) in tail.match_indices(name) {
3164            let before = text[..start + at].chars().next_back();
3165            let after = tail[at + name.len()..].chars().next();
3166            if before.is_some_and(|c| is_ident(c) || c == '.') || after.is_some_and(is_ident) {
3167                continue;
3168            }
3169            return r.base + (start + at) as u32;
3170        }
3171        pos
3172    }
3173
3174    /// Resolve a source-address-space position (`0`: none) to its script's
3175    /// name, line, column and line text.
3176    pub fn source_location(&self, pos: u32) -> Option<SourceLocation<'_>> {
3177        if pos == 0 {
3178            return None;
3179        }
3180        let r = &self.source_map[self
3181            .source_map
3182            .partition_point(|r| r.base <= pos)
3183            .checked_sub(1)?];
3184        let text: &str = self.scripts.get(r.script as usize)?;
3185        let mut off = ((pos - r.base) as usize).min(text.len());
3186        while !text.is_char_boundary(off) {
3187            off -= 1;
3188        }
3189        let starts = r.line_starts.get_or_init(|| {
3190            std::iter::once(0)
3191                .chain(text.match_indices('\n').map(|(i, _)| i as u32 + 1))
3192                .collect()
3193        });
3194        let line_ix = starts.partition_point(|&s| s as usize <= off) - 1;
3195        let start = starts[line_ix] as usize;
3196        let end = starts
3197            .get(line_ix + 1)
3198            .map_or(text.len(), |&s| s as usize - 1);
3199        let source_line = text[start..end]
3200            .strip_suffix('\r')
3201            .unwrap_or(&text[start..end]);
3202        // A stack captures up to ten of these per error; most lines are ASCII,
3203        // whose UTF-16 length is the byte length.
3204        let prefix = &text[start..off];
3205        let col = if prefix.is_ascii() {
3206            prefix.len()
3207        } else {
3208            prefix.encode_utf16().count()
3209        };
3210        Some(SourceLocation {
3211            name: &r.origin.name,
3212            line: (line_ix as u32 + 1)
3213                .saturating_sub(r.origin.line_shift)
3214                .max(1),
3215            col: col as u32 + 1,
3216            source_line,
3217            internal: r.origin.internal,
3218        })
3219    }
3220
3221    /// Before the innermost frame changes (a callee's frame is pushed, a
3222    /// generator's context swapped in or out): move the op position pending
3223    /// for it (see [`set_op_pos`]) into its [`Frame::pos`].
3224    fn settle_op_pos(&mut self) {
3225        let pos = OP_POS.with(|p| p.replace(0));
3226        if pos != 0 {
3227            if let Some(f) = self.frames.last_mut() {
3228                f.pos = pos;
3229            }
3230        }
3231    }
3232
3233    /// Where frame `i` is: its [`Frame::pos`], or for the innermost frame the
3234    /// op position still pending for it.
3235    fn frame_pos_of(&self, i: usize) -> u32 {
3236        if i + 1 == self.frames.len() {
3237            let pending = OP_POS.with(|p| p.get());
3238            if pending != 0 {
3239                return pending;
3240            }
3241        }
3242        self.frames.get(i).map_or(0, |f| f.pos)
3243    }
3244
3245    /// How many frames are live, counting those of the contexts that resumed
3246    /// the running generator or async body.
3247    pub fn stack_depth(&self) -> usize {
3248        self.frames.len() + self.outer_frames.iter().map(Vec::len).sum::<usize>()
3249    }
3250
3251    /// Where the innermost frame below `top` is: where an error whose stack
3252    /// starts there was created.
3253    pub fn frame_pos_below(&self, top: usize) -> u32 {
3254        top.checked_sub(1).map_or(0, |i| self.frame_pos_of(i))
3255    }
3256
3257    /// The frames an error constructed now captures end below this index.
3258    ///
3259    /// An error built through `super()` from a subclass constructor does not
3260    /// show the constructors that are building it: V8 captures in
3261    /// `SKIP_UNTIL_SEEN` mode, skipping every frame up to and including the one
3262    /// running `new.target`, so `new MyErr()` reports the frame that said `new`.
3263    /// Those are the innermost frames that are derived constructors still
3264    /// waiting on `super()`, all for the same `new.target`.
3265    pub fn error_capture_top(&self) -> usize {
3266        let mut top = self.frames.len();
3267        let Some(Value::Obj(target)) = self
3268            .frames
3269            .last()
3270            .filter(|f| f.this_state == ThisState::Pending)
3271            .and_then(|f| f.new_target.clone())
3272        else {
3273            return top;
3274        };
3275        while top > 0 {
3276            let f = &self.frames[top - 1];
3277            match &f.new_target {
3278                Some(Value::Obj(t)) if *t == target && f.this_state == ThisState::Pending => {
3279                    top -= 1
3280                }
3281                _ => break,
3282            }
3283        }
3284        top
3285    }
3286
3287    /// Record that the op at source position `pos` raised `msg` — unless this
3288    /// is the same raise propagating outward (see [`ThrowSite`]). A raise the
3289    /// runtime makes (`native`: not a JS `throw`) also keeps the live frames,
3290    /// for the error object a `catch` or the fatal report builds later.
3291    pub fn note_raise(&mut self, msg: &str, pos: u32, native: bool) {
3292        let depth = self.stack_depth();
3293        if native {
3294            if let Some(s) = &self.throw_site {
3295                if s.msg == msg && depth <= s.depth {
3296                    return;
3297                }
3298            }
3299        }
3300        if pos != 0 {
3301            OP_POS.with(|p| p.set(0));
3302            if let Some(f) = self.frames.last_mut() {
3303                f.pos = pos;
3304            }
3305        }
3306        let frames = native.then(|| self.stack_frames());
3307        self.throw_site = Some(ThrowSite {
3308            msg: msg.to_string(),
3309            pos,
3310            end: 0,
3311            depth,
3312            frames,
3313        });
3314    }
3315
3316    /// The stack frames an error built from runtime error string `msg` carries:
3317    /// those live when it was raised, if that raise was recorded, else the
3318    /// current ones.
3319    pub fn raise_frames(&self, msg: &str) -> String {
3320        match &self.throw_site {
3321            Some(ThrowSite {
3322                msg: m,
3323                frames: Some(f),
3324                ..
3325            }) if m == msg => f.clone(),
3326            _ => self.stack_frames(),
3327        }
3328    }
3329
3330    /// The call stack as (frame name, line) pairs, innermost first — for the DAP
3331    /// `stackTrace`. `owner` carries the function name where known.
3332    pub fn dbg_stack(&self) -> Vec<(String, u32)> {
3333        self.frames
3334            .iter()
3335            .rev()
3336            .map(|f| {
3337                let name = f.owner.clone().unwrap_or_else(|| "<module>".to_string());
3338                (name, f.line)
3339            })
3340            .collect()
3341    }
3342    /// The innermost frame's locals as (name, inspect) pairs — for DAP `variables`.
3343    pub fn dbg_locals(&self) -> Vec<(String, String)> {
3344        let env = self.cur_env();
3345        let names: Vec<String> = env.borrow().vars.keys().cloned().collect();
3346        names
3347            .into_iter()
3348            .map(|n| {
3349                let v = self.read_name(&n).unwrap_or(Value::Undef);
3350                (n, self.inspect(&v))
3351            })
3352            .collect()
3353    }
3354
3355    /// Scope-chain read: local + enclosing chain, then globals.
3356    /// Whether `name` is a module-top-level binding that has not reached its
3357    /// declaration yet. Separate from [`JsHost::is_tdz`], which answers for a
3358    /// block-scoped one by inspecting the value it holds.
3359    pub fn is_tdz_global(&self, name: &str) -> bool {
3360        self.tdz_globals.contains(name)
3361    }
3362
3363    pub fn read_name(&self, name: &str) -> Option<Value> {
3364        let mut env = Some(self.cur_env());
3365        while let Some(e) = env {
3366            if let Some(v) = e.borrow().vars.get(name) {
3367                return Some(v.clone());
3368            }
3369            env = e.borrow().parent.clone();
3370        }
3371        self.globals.get(name).cloned()
3372    }
3373    pub fn read_global(&self, name: &str) -> Option<Value> {
3374        self.globals.get(name).cloned()
3375    }
3376
3377    /// Whether `name` is bound anywhere on the scope chain or in the globals —
3378    /// `read_name(..).is_some()` without cloning the value it finds. The
3379    /// strict-mode assignment path asks this and nothing else.
3380    pub fn has_name(&self, name: &str) -> bool {
3381        let mut env = Some(self.cur_env());
3382        while let Some(e) = env {
3383            if e.borrow().vars.contains_key(name) {
3384                return true;
3385            }
3386            env = e.borrow().parent.clone();
3387        }
3388        self.globals.contains_key(name)
3389    }
3390
3391    /// Assign to an existing binding up the scope chain, else create a global
3392    /// (JS assignment to an undeclared name targets the global object).
3393    /// Assign to an existing binding, or create a global. Returns `false` when
3394    /// the nearest binding is an immutable (`const`) one, which the caller turns
3395    /// into `TypeError: Assignment to constant variable.` — assigning to a
3396    /// `const` used to succeed SILENTLY, so code that node rejects ran on with
3397    /// a mutated constant.
3398    #[must_use]
3399    pub fn set_name(&mut self, name: &str, val: Value) -> bool {
3400        let mut env = Some(self.cur_env());
3401        while let Some(e) = env {
3402            // `get_mut`, not `contains_key` + `insert`: overwriting an existing
3403            // binding hashed the name twice and allocated a fresh `String` key
3404            // for a key that was already there — once per assignment, so once
3405            // per loop iteration in any counting loop.
3406            //
3407            // The const check runs only at the env that OWNS the name, and the
3408            // `is_empty` guard settles the common (no consts here) case without
3409            // hashing the name again.
3410            let mut b = e.borrow_mut();
3411            if b.vars.contains_key(name) {
3412                if !b.consts.is_empty() && b.consts.contains(name) {
3413                    return false;
3414                }
3415                let alias = Self::arguments_alias(&b, name);
3416                let (stored, mirror) = match alias {
3417                    Some(_) => (val.clone(), Some(val)),
3418                    None => (val, None),
3419                };
3420                if let Some(slot) = b.vars.get_mut(name) {
3421                    *slot = stored;
3422                }
3423                drop(b);
3424                if let (Some((args, i)), Some(v)) = (alias, mirror) {
3425                    self.set_argument_slot(&args, i, v);
3426                }
3427                return true;
3428            }
3429            drop(b);
3430            env = e.borrow().parent.clone();
3431        }
3432        if self.global_consts.contains(name) {
3433            return false;
3434        }
3435        match self.globals.get_mut(name) {
3436            Some(slot) => *slot = val,
3437            None => {
3438                self.globals.insert(name.to_string(), val);
3439            }
3440        }
3441        true
3442    }
3443
3444    /// Declare a `const` binding: the same placement as [`Self::declare_name`],
3445    /// plus recording the name as immutable in whichever scope received it.
3446    pub fn declare_const_name(&mut self, name: &str, val: Value) {
3447        let f = self.frame();
3448        let to_globals = f.is_module && Rc::ptr_eq(&f.env, &f.base_env);
3449        self.declare_name(name, val);
3450        if to_globals {
3451            self.global_consts.insert(name.to_string());
3452        } else {
3453            self.cur_env().borrow_mut().consts.insert(name.to_string());
3454        }
3455    }
3456
3457    /// The value a lexical binding holds between entering its scope and reaching
3458    /// its declaration — its TEMPORAL DEAD ZONE. One heap object for the whole
3459    /// process, so the check is a heap-index comparison and the marker cannot be
3460    /// produced by any JavaScript expression. It never escapes: every path that
3461    /// could read it throws first.
3462    pub fn tdz_marker(&mut self) -> Value {
3463        if let Some(v) = &self.tdz {
3464            return v.clone();
3465        }
3466        let v = self.alloc(JsObj::Builtin("@@tdz".into()));
3467        self.tdz = Some(v.clone());
3468        v
3469    }
3470
3471    /// Whether `v` is the uninitialized-binding marker.
3472    pub fn is_tdz(&self, v: &Value) -> bool {
3473        matches!((&self.tdz, v), (Some(Value::Obj(a)), Value::Obj(b)) if a == b)
3474    }
3475
3476    /// Declare `name` in the CURRENT scope as uninitialized, unless that scope
3477    /// already binds it. Emitted at the top of every scope for each `let`,
3478    /// `const` and `class` declared directly in it, so a read before the
3479    /// declaration throws instead of finding an OUTER binding of the same name —
3480    /// `let x = 1; { x; let x = 2 }` used to read the outer `1`.
3481    pub fn hoist_tdz(&mut self, name: &str) {
3482        let marker = self.tdz_marker();
3483        let f = self.frame();
3484        // At module top level a lexical binding lives in `globals`, which is ALSO
3485        // what backs `globalThis.<name>` — so parking the marker there exposes it
3486        // to JavaScript, and `const crypto = …` made `globalThis.crypto` read
3487        // back as the marker. Top-level dead zones are tracked in a separate set
3488        // that only the name-read path consults.
3489        if f.is_module && Rc::ptr_eq(&f.env, &f.base_env) {
3490            if !self.globals.contains_key(name) {
3491                self.tdz_globals.insert(name.to_string());
3492            }
3493            return;
3494        }
3495        let env = self.cur_env();
3496        let mut e = env.borrow_mut();
3497        if !e.vars.contains_key(name) {
3498            e.vars.insert(name.to_string(), marker);
3499        }
3500    }
3501
3502    /// Declare a new binding in the current scope (`let`/`const`). At the top of
3503    /// the module frame there is no local env, so those names become globals; once
3504    /// a block scope is open the binding belongs to that block.
3505    pub fn declare_name(&mut self, name: &str, val: Value) {
3506        let f = self.frame();
3507        if f.is_module && Rc::ptr_eq(&f.env, &f.base_env) {
3508            self.tdz_globals.remove(name);
3509            self.globals.insert(name.to_string(), val);
3510        } else {
3511            self.cur_env()
3512                .borrow_mut()
3513                .vars
3514                .insert(name.to_string(), val);
3515        }
3516    }
3517
3518    /// Declare a `var` (or a hoisted function declaration): FUNCTION-scoped, so it
3519    /// skips every open block scope and lands in the activation's base env.
3520    /// Create a hoisted `var` binding, initialised to `undefined`, only when the
3521    /// name is not already bound in this activation.
3522    ///
3523    /// `var` bindings come into existence when the scope is entered, not where
3524    /// the declaration is written — `f(){ x; var x = 1 }` reads `undefined`
3525    /// rather than throwing. "If absent" is what keeps a parameter intact: in
3526    /// `function f(a) { var a; }` the `var` names a binding that already exists
3527    /// and must not be reset, which is also why a bare `var x;` emits nothing at
3528    /// its own position.
3529    pub fn hoist_var_name(&mut self, name: &str) {
3530        // The ENTRY script's top level is a CommonJS module body, not global
3531        // scope: node wraps every file in a function, so a top-level `var` is a
3532        // local of that wrapper. Binding it into the globals map made
3533        // `var x = 3` at the top of the entry readable as `globalThis.x`, where
3534        // node says `undefined` — a REQUIRED module already ran inside a real
3535        // frame and behaved correctly, so only the entry file differed.
3536        if self.frame().is_module && !self.module_scope {
3537            self.globals.entry(name.to_string()).or_insert(Value::Undef);
3538            return;
3539        }
3540        let base = self.frame().base_env.clone();
3541        let mut env = base.borrow_mut();
3542        if !env.vars.contains_key(name) {
3543            env.vars.insert(name.to_string(), Value::Undef);
3544        }
3545    }
3546
3547    pub fn declare_var_name(&mut self, name: &str, val: Value) {
3548        if self.frame().is_module && !self.module_scope {
3549            self.globals.insert(name.to_string(), val);
3550            return;
3551        }
3552        let base = self.frame().base_env.clone();
3553        let alias = Self::arguments_alias(&base.borrow(), name);
3554        if let Some((args, i)) = alias {
3555            self.set_argument_slot(&args, i, val.clone());
3556        }
3557        base.borrow_mut().vars.insert(name.to_string(), val);
3558    }
3559
3560    /// Enter a `with` scope whose binding object is `obj`.
3561    pub fn push_with_scope(&mut self, obj: Value) {
3562        let child = child_env(self.cur_env());
3563        child.borrow_mut().with_obj = Some(obj);
3564        self.frames.last_mut().unwrap().env = child;
3565    }
3566
3567    /// Whether the running code sits inside a `with` body.
3568    pub fn in_with_scope(&self) -> bool {
3569        let mut env = Some(self.cur_env());
3570        while let Some(e) = env {
3571            if e.borrow().with_obj.is_some() {
3572                return true;
3573            }
3574            env = e.borrow().parent.clone();
3575        }
3576        false
3577    }
3578
3579    /// The `with` binding objects `name` would be looked up on, innermost first,
3580    /// stopping at the first ordinary scope that binds it: an inner binding
3581    /// shadows every object beyond it.
3582    pub fn with_objects_before_binding(&self, name: &str) -> Vec<Value> {
3583        let mut out = Vec::new();
3584        let mut env = Some(self.cur_env());
3585        while let Some(e) = env {
3586            let b = e.borrow();
3587            match &b.with_obj {
3588                Some(o) => out.push(o.clone()),
3589                None if b.vars.contains_key(name) => break,
3590                None => {}
3591            }
3592            let parent = b.parent.clone();
3593            drop(b);
3594            env = parent;
3595        }
3596        out
3597    }
3598
3599    /// The `arguments` slot `name` is aliased to in `env`, as `(arguments, index)`.
3600    fn arguments_alias(env: &EnvData, name: &str) -> Option<(Value, usize)> {
3601        let m = env.mapped.as_ref()?;
3602        let i = m.names.iter().position(|n| n == name)?;
3603        Some((m.arguments.clone(), i))
3604    }
3605
3606    /// Store `val` into element `i` of the `arguments` array `args`.
3607    fn set_argument_slot(&mut self, args: &Value, i: usize, val: Value) {
3608        if let Some(JsObj::Array(items)) = self.get_mut(args) {
3609            if let Some(slot) = items.get_mut(i) {
3610                *slot = val;
3611            }
3612        }
3613    }
3614
3615    /// Alias the parameters named by `names` (in order) to the `arguments`
3616    /// object bound in the nearest scope that has one — 10.4.4.7
3617    /// `CreateMappedArgumentsObject`. Only indices the caller supplied are
3618    /// mapped, and a name that repeats is mapped at its LAST occurrence only.
3619    pub fn map_arguments(&mut self, names: &[String]) {
3620        let mut env = Some(self.cur_env());
3621        while let Some(e) = env {
3622            let args = e.borrow().vars.get("arguments").cloned();
3623            if let Some(args) = args {
3624                let Value::Obj(id) = args else { return };
3625                let Some(JsObj::Array(items)) = self.heap.get(id as usize) else {
3626                    return;
3627                };
3628                let argc = items.len();
3629                let mapped: Vec<String> = names
3630                    .iter()
3631                    .enumerate()
3632                    .take(argc)
3633                    .map(|(i, n)| {
3634                        if names[i + 1..].contains(n) {
3635                            String::new()
3636                        } else {
3637                            n.clone()
3638                        }
3639                    })
3640                    .collect();
3641                e.borrow_mut().mapped = Some(Box::new(MappedArgs {
3642                    arguments: args,
3643                    names: mapped,
3644                }));
3645                self.mapped_arg_envs.insert(id, e.clone());
3646                return;
3647            }
3648            env = e.borrow().parent.clone();
3649        }
3650    }
3651
3652    /// `arguments[i] = v` on a mapped object: write the aliased parameter too.
3653    pub fn write_mapped_argument(&mut self, args: &Value, i: usize, val: &Value) {
3654        let Value::Obj(id) = args else { return };
3655        let Some(env) = self.mapped_arg_envs.get(id).cloned() else {
3656            return;
3657        };
3658        let name = match env.borrow().mapped.as_ref() {
3659            Some(m) => m.names.get(i).filter(|n| !n.is_empty()).cloned(),
3660            None => None,
3661        };
3662        if let Some(n) = name {
3663            if let Some(slot) = env.borrow_mut().vars.get_mut(&n) {
3664                *slot = val.clone();
3665            }
3666        }
3667    }
3668
3669    /// After an `Array.prototype` mutator rewrote a mapped `arguments` object's
3670    /// elements in place, push every still-aliased element into its parameter.
3671    pub fn sync_arguments_to_params(&mut self, args: &Value) {
3672        let Value::Obj(id) = args else { return };
3673        let Some(env) = self.mapped_arg_envs.get(id).cloned() else {
3674            return;
3675        };
3676        let items = match self.heap.get(*id as usize) {
3677            Some(JsObj::Array(items)) => items.clone(),
3678            _ => return,
3679        };
3680        let names = match env.borrow().mapped.as_ref() {
3681            Some(m) => m.names.clone(),
3682            None => return,
3683        };
3684        for (i, n) in names.iter().enumerate() {
3685            if let (false, Some(v)) = (n.is_empty(), items.get(i)) {
3686                if let Some(slot) = env.borrow_mut().vars.get_mut(n) {
3687                    *slot = v.clone();
3688                }
3689            }
3690        }
3691    }
3692
3693    /// `delete arguments[i]`: the index stops aliasing its parameter.
3694    pub fn unmap_argument(&mut self, args: &Value, i: usize) {
3695        let Value::Obj(id) = args else { return };
3696        if let Some(env) = self.mapped_arg_envs.get(id) {
3697            if let Some(m) = env.borrow_mut().mapped.as_mut() {
3698                if let Some(n) = m.names.get_mut(i) {
3699                    n.clear();
3700                }
3701            }
3702        }
3703    }
3704
3705    /// Enter a fresh block scope.
3706    pub fn push_scope(&mut self) {
3707        let env = self.cur_env();
3708        self.frames.last_mut().unwrap().env = child_env(env);
3709    }
3710
3711    /// Open a scope that is also the activation's VARIABLE environment, and
3712    /// return the previous one so the caller can restore it.
3713    ///
3714    /// A block scope is not enough for a strict direct `eval`: `var` and a
3715    /// hoisted function declaration bind to `base_env`, so they walked straight
3716    /// past a plain `push_scope` and still landed in the caller's function
3717    /// scope. Only `let`/`const` were contained.
3718    pub fn push_var_scope(&mut self) -> Env {
3719        let env = child_env(self.cur_env());
3720        let f = self.frames.last_mut().unwrap();
3721        let prev = std::mem::replace(&mut f.base_env, env.clone());
3722        f.env = env;
3723        prev
3724    }
3725
3726    /// Restore the variable environment a `push_var_scope` replaced.
3727    pub fn pop_var_scope(&mut self, prev: Env) {
3728        let f = self.frames.last_mut().unwrap();
3729        f.env = prev.clone();
3730        f.base_env = prev;
3731    }
3732
3733    /// Leave the innermost block scope (never pops past the activation's base).
3734    pub fn pop_scope(&mut self) {
3735        let cur = self.cur_env();
3736        if Rc::ptr_eq(&cur, &self.frame().base_env) {
3737            return;
3738        }
3739        let parent = cur.borrow().parent.clone();
3740        if let Some(p) = parent {
3741            self.frames.last_mut().unwrap().env = p;
3742        }
3743    }
3744
3745    /// Replace the innermost block scope with a fresh copy of its bindings — the
3746    /// per-iteration environment a `for (let i …)` loop creates, so a closure made
3747    /// in one iteration keeps that iteration's value.
3748    pub fn copy_scope(&mut self) {
3749        let cur = self.cur_env();
3750        if Rc::ptr_eq(&cur, &self.frame().base_env) {
3751            return;
3752        }
3753        let parent = cur.borrow().parent.clone();
3754        let fresh = new_env(parent);
3755        fresh.borrow_mut().vars = cur.borrow().vars.clone();
3756        self.frames.last_mut().unwrap().env = fresh;
3757    }
3758
3759    /// The current block-scope env, for save/restore across a nested chunk.
3760    pub fn scope_snapshot(&self) -> Env {
3761        self.cur_env()
3762    }
3763    pub fn restore_scope(&mut self, env: Env) {
3764        self.frames.last_mut().unwrap().env = env;
3765    }
3766    pub fn set_global(&mut self, name: &str, val: Value) {
3767        self.globals.insert(name.to_string(), val);
3768    }
3769
3770    // ── output capture ───────────────────────────────────────────────────
3771    //
3772    // Every write a *program* makes — `console.log`, `process.stdout.write`,
3773    // `print` — funnels through `write_out`, so turning capture on redirects all
3774    // of them at once. Diagnostics the runtime itself emits (the REPL banner, a
3775    // crash traceback from `main`) deliberately do not: they belong to the
3776    // process, not to the program.
3777
3778    /// Start capturing program output in-process. Any text already captured is
3779    /// discarded, so each run starts clean.
3780    pub fn begin_capture(&mut self) {
3781        self.capture = Some(Vec::new());
3782        self.capture_stderr = true;
3783    }
3784
3785    /// Like [`begin_capture`], but only stdout is captured; stderr writes
3786    /// (`console.error`, `process.stderr.write`) still reach the process.
3787    ///
3788    /// [`begin_capture`]: JsHost::begin_capture
3789    pub fn begin_stdout_capture(&mut self) {
3790        self.capture = Some(Vec::new());
3791        self.capture_stderr = false;
3792    }
3793
3794    /// Make `input` the program's standard input: `process.stdin`,
3795    /// `fs.readFileSync(0)`, `fs.readSync(0, …)` and `readline` all read it
3796    /// instead of the process stdin.
3797    pub fn set_stdin(&mut self, input: &[u8]) {
3798        self.stdin = Some(std::io::Cursor::new(input.to_vec()));
3799    }
3800
3801    /// Stop capturing and take everything written since [`begin_capture`],
3802    /// returning the empty string when capture was not on. The captured bytes
3803    /// are rendered lossily: this API hands back a `String`, so a program that
3804    /// wrote non-UTF-8 gets `U+FFFD` here even though the same write reaches a
3805    /// real stdout byte-exact. Use [`end_capture_bytes`] to keep those bytes.
3806    ///
3807    /// [`begin_capture`]: JsHost::begin_capture
3808    /// [`end_capture_bytes`]: JsHost::end_capture_bytes
3809    pub fn end_capture(&mut self) -> String {
3810        String::from_utf8_lossy(&self.capture.take().unwrap_or_default()).into_owned()
3811    }
3812
3813    /// Stop capturing and take the raw bytes, without the lossy transcription
3814    /// [`end_capture`] applies.
3815    ///
3816    /// [`end_capture`]: JsHost::end_capture
3817    pub fn end_capture_bytes(&mut self) -> Vec<u8> {
3818        self.capture.take().unwrap_or_default()
3819    }
3820
3821    /// Whether output is being captured — the one thing a caller needs to know
3822    /// before asking the real stream a question (`isTTY`, cursor position).
3823    pub fn capturing(&self) -> bool {
3824        self.capture.is_some()
3825    }
3826
3827    /// Write program output: into the capture buffer when capturing, else to the
3828    /// process stream `stderr` selects. `s` is written verbatim — callers add
3829    /// their own line ending, as `console.log` does and `process.stdout.write`
3830    /// does not.
3831    pub fn write_out(&mut self, s: &str, stderr: bool) {
3832        self.write_out_bytes(s.as_bytes(), stderr);
3833    }
3834
3835    /// Write program output as raw BYTES. `process.stdout.write(buf)` hands Node
3836    /// a byte string and Node writes it through untouched, so a `Buffer` holding
3837    /// `ff fe 41` reaches stdout as those three bytes. Routing it through a Rust
3838    /// `String` first replaced every non-UTF-8 byte with `U+FFFD` — three bytes
3839    /// became seven — so the byte path exists separately from [`write_out`].
3840    ///
3841    /// [`write_out`]: JsHost::write_out
3842    pub fn write_out_bytes(&mut self, bytes: &[u8], stderr: bool) {
3843        if let Some(buf) = &mut self.capture {
3844            if !stderr || self.capture_stderr {
3845                buf.extend_from_slice(bytes);
3846                return;
3847            }
3848        }
3849        use std::io::Write as _;
3850        if stderr {
3851            let mut e = std::io::stderr();
3852            let _ = e.write_all(bytes);
3853            let _ = e.flush();
3854        } else {
3855            let mut o = std::io::stdout();
3856            let _ = o.write_all(bytes);
3857            let _ = o.flush();
3858        }
3859    }
3860    pub fn del_name(&mut self, name: &str) {
3861        if self
3862            .cur_env()
3863            .borrow_mut()
3864            .vars
3865            .shift_remove(name)
3866            .is_some()
3867        {
3868            return;
3869        }
3870        self.globals.shift_remove(name);
3871    }
3872
3873    pub fn current_this(&self) -> Option<Value> {
3874        self.frame().this_obj.clone()
3875    }
3876
3877    /// The running activation's [`ThisState`].
3878    pub fn this_state(&self) -> ThisState {
3879        self.frame().this_state
3880    }
3881
3882    /// Mark the next user-function activation as a derived constructor.
3883    pub fn mark_next_call_derived_ctor(&mut self) {
3884        self.derived_ctor_next = true;
3885    }
3886
3887    /// BindThisValue (9.1.1.3.1) for a `super()` that has just returned: the
3888    /// nearest derived-constructor activation becomes `Bound`. That is the top
3889    /// frame, or — for `super()` inside an arrow — the constructor below the
3890    /// arrow's own frame. `false` when it was already bound: the second call.
3891    pub fn bind_super_this(&mut self) -> bool {
3892        let Some(f) = self
3893            .frames
3894            .iter_mut()
3895            .rev()
3896            .find(|f| f.this_state != ThisState::Plain)
3897        else {
3898            return true;
3899        };
3900        if f.this_state == ThisState::Bound {
3901            return false;
3902        }
3903        f.this_state = ThisState::Bound;
3904        true
3905    }
3906
3907    /// The object a `super()` call substituted for the instance, if any.
3908    ///
3909    /// `construct_class` allocates the instance up front, so when a base
3910    /// constructor RETURNS an object the substitution happens deep inside the
3911    /// VM, after that allocation. This carries it back out. Each
3912    /// `construct_class` saves and restores the previous value around its own
3913    /// run, so a `new` inside a constructor body cannot steal it.
3914    pub fn take_super_replacement(&mut self) -> Option<Value> {
3915        self.super_replacement.take()
3916    }
3917
3918    pub fn swap_super_replacement(&mut self, v: Option<Value>) -> Option<Value> {
3919        std::mem::replace(&mut self.super_replacement, v)
3920    }
3921
3922    /// Rebind the running activation's `this`.
3923    ///
3924    /// Only `super()` does this: when the parent constructor RETURNS an object,
3925    /// 15.7.15 makes that object the derived instance, so the rest of the
3926    /// derived constructor has to write to it rather than to the one allocated
3927    /// before the call.
3928    pub fn set_current_this(&mut self, v: Value) {
3929        if let Some(f) = self.frames.last_mut() {
3930            f.this_obj = Some(v.clone());
3931        }
3932        self.super_replacement = Some(v);
3933    }
3934    /// The callbacks to run for `event`, consuming any `once` registration in
3935    /// the same step — so a listener that re-emits the event cannot re-enter a
3936    /// one-shot handler.
3937    /// Whether any `process.on(event)` listener is registered.
3938    pub fn has_process_listeners(&self, event: &str) -> bool {
3939        self.process_listeners
3940            .get(event)
3941            .is_some_and(|l| !l.is_empty())
3942    }
3943
3944    pub fn take_process_listeners(&mut self, event: &str) -> Vec<Value> {
3945        let Some(list) = self.process_listeners.get_mut(event) else {
3946            return Vec::new();
3947        };
3948        let fired: Vec<Value> = list.iter().map(|l| l.f.clone()).collect();
3949        list.retain(|l| !l.once);
3950        fired
3951    }
3952
3953    /// Bind the TOP-LEVEL `this` — the value a `this` outside any function sees.
3954    ///
3955    /// Node answers differently per entry point and both answers are objects:
3956    /// `node f.js` runs a CommonJS module, so top-level `this` is
3957    /// `module.exports`; `node -e` and `node -` run a Script, so it is
3958    /// `globalThis`. Verified on node v26.7.0 —
3959    /// `console.log(this === globalThis, this === module.exports)` is
3960    /// `false true` from a file and `true false` from `-e` and from stdin. It
3961    /// was `undefined` at every entry point here, so `this.x = 1` at module
3962    /// scope threw instead of populating the exports object.
3963    ///
3964    /// Only the base frame is touched: a plain function call still gets its own
3965    /// (`undefined`) binding rather than inheriting this one.
3966    pub fn set_top_this(&mut self, v: Value) {
3967        if let Some(f) = self.frames.first_mut() {
3968            f.this_obj = Some(v);
3969        }
3970    }
3971    pub fn current_env_capture(&self) -> Env {
3972        self.frame().env.clone()
3973    }
3974    pub fn current_new_target(&self) -> Option<Value> {
3975        self.frame().new_target.clone()
3976    }
3977    fn current_home_class(&self) -> Option<Value> {
3978        self.frame().home_class.clone()
3979    }
3980
3981    /// The running method's `(home_class, is_static, home_object)`, for the
3982    /// `super.x` lookup that has to leave the host borrow (see `b_super_get`).
3983    pub fn super_home(&self) -> (Option<Value>, bool, Option<Value>) {
3984        let f = self.frame();
3985        (f.home_class.clone(), f.home_static, f.home_object.clone())
3986    }
3987
3988    /// The `(parent_ctor, this_class_fields)` for a running constructor's
3989    /// `super(...)`, derived from the frame's home class.
3990    pub fn super_context(&self) -> (Option<Value>, Vec<(String, Value, bool)>) {
3991        match self.current_home_class() {
3992            Some(cv) => match self.get(&cv) {
3993                Some(JsObj::Class(c)) => (c.parent.clone(), c.fields.clone()),
3994                _ => (None, Vec::new()),
3995            },
3996            None => (None, Vec::new()),
3997        }
3998    }
3999
4000    /// Resolve `super.name` to either the parent-prototype getter (to be invoked
4001    /// by the caller, outside any host borrow) or a directly-usable value.
4002    /// The object `super.x` is looked up on: the prototype of the running
4003    /// method's home object.
4004    ///
4005    /// A shorthand method in an OBJECT LITERAL resolves `super` through its
4006    /// home object's prototype; only a class method has a home CLASS. A STATIC
4007    /// method's home object is the constructor, so `super.x` reads off the
4008    /// parent CONSTRUCTOR; an instance method's is the prototype object, so it
4009    /// reads off the parent's prototype.
4010    fn super_target(&self) -> Option<Value> {
4011        if let Some(home) = self.frame().home_object.clone() {
4012            return Some(self.proto_of(&home).unwrap_or(Value::Undef));
4013        }
4014        let parent = self
4015            .current_home_class()
4016            .and_then(|cv| match self.get(&cv) {
4017                Some(JsObj::Class(c)) => c.parent.clone(),
4018                _ => None,
4019            })?;
4020        Some(if self.frame().home_static {
4021            parent
4022        } else {
4023            match self.get(&parent) {
4024                Some(JsObj::Class(pc)) => pc.proto.clone(),
4025                _ => self.fn_prop(&parent, "prototype").unwrap_or(Value::Undef),
4026            }
4027        })
4028    }
4029
4030    /// The accessor `super.name = v` finds: `Some(Some(setter))` runs,
4031    /// `Some(None)` is a getter-only property that refuses the write, and
4032    /// `None` means no accessor, so the write lands on `this` as a data
4033    /// property (OrdinarySet with the receiver, 10.1.9.2).
4034    pub fn super_setter(&self, name: &str) -> Option<Option<Value>> {
4035        let target = self.super_target()?;
4036        lookup_accessor(self, &target, name).map(|(_, setter)| setter)
4037    }
4038
4039    pub fn super_resolve(&self, name: &str) -> SuperRef {
4040        let Some(target) = self.super_target() else {
4041            return SuperRef::Data(Value::Undef);
4042        };
4043        if let Some((Some(getter), _)) = lookup_accessor(self, &target, name) {
4044            return SuperRef::Getter(getter);
4045        }
4046        if let Some(v) = lookup_chain(self, &target, name) {
4047            return SuperRef::Data(v);
4048        }
4049        // A static method lives in the fn-prop side table, not the property map.
4050        SuperRef::Data(self.fn_prop(&target, name).unwrap_or(Value::Undef))
4051    }
4052
4053    // ── signals / errors ─────────────────────────────────────────────────
4054    pub fn take_error(&mut self) -> Option<String> {
4055        self.error.take()
4056    }
4057    pub fn raise_str(&mut self, class: &str, msg: &str) -> String {
4058        let s = if msg.is_empty() {
4059            class.to_string()
4060        } else {
4061            format!("{class}: {msg}")
4062        };
4063        self.error = Some(s.clone());
4064        s
4065    }
4066}
4067
4068// ── error constructors ───────────────────────────────────────────────────────
4069
4070pub fn type_error(msg: &str) -> String {
4071    format!("TypeError: {msg}")
4072}
4073pub fn ref_error(name: &str) -> String {
4074    // A CommonJS wrapper name referenced from an ES module (`esm::lower`
4075    // renames it so that it resolves to nothing) is reported by its own name.
4076    let name = name
4077        .strip_prefix(crate::esm::CJS_FREE_PREFIX)
4078        .unwrap_or(name);
4079    format!("ReferenceError: {name} is not defined")
4080}
4081
4082/// The error a read of a lexical binding still in its TEMPORAL DEAD ZONE
4083/// raises. Distinct from [`ref_error`] on purpose: node says which of the two
4084/// happened, and the difference is how a reader tells a misspelled name from a
4085/// `let` used above its declaration.
4086pub fn tdz_error(name: &str) -> String {
4087    format!("ReferenceError: Cannot access '{name}' before initialization")
4088}
4089pub fn range_error(msg: &str) -> String {
4090    format!("RangeError: {msg}")
4091}
4092
4093/// V8's `String::kMaxLength` on a 64-bit build, in UTF-16 code units — the
4094/// largest string the engine will materialize.
4095///
4096/// Measured on node v26.7.0 (darwin arm64):
4097/// `require('buffer').constants.MAX_STRING_LENGTH` is `536870888`,
4098/// `'a'.repeat(536870888)` succeeds with that length, and
4099/// `'a'.repeat(536870889)` is `RangeError: Invalid string length`.
4100pub const MAX_STRING_LENGTH: usize = 536_870_888;
4101
4102/// The error V8 raises for a string operation whose RESULT would exceed
4103/// [`MAX_STRING_LENGTH`]. It is raised from the length arithmetic, before any
4104/// allocation: `'a'.repeat(2**40)` throws promptly on node where node-js used to
4105/// sit building a 1 TiB `String` until it was killed.
4106pub fn invalid_string_length() -> String {
4107    range_error("Invalid string length")
4108}
4109
4110/// `ToUint32`-validated array length — ECMA-262 10.4.2.2 `ArrayCreate` step 1
4111/// and 10.4.2.4 `ArraySetLength` step 3.
4112///
4113/// A length is legal only if `ToUint32(v)` equals `ToNumber(v)` exactly, so
4114/// `-1`, `1.5`, `NaN`, `Infinity`, `'x'` and `2**32` are all
4115/// `RangeError: Invalid array length` while `'3'` is `3` and `-0` is `0`
4116/// (measured on node v26.7.0: `new Array(-0).length` is `0`, `a.length = '3'`
4117/// leaves `3`, `a.length = 'x'` throws). node-js validated none of them — it
4118/// built `[-1]` from `new Array(-1)`, silently ignored `a.length = -1`, and sat
4119/// materializing four billion elements for `a.length = 2**32`.
4120pub fn to_array_length(v: &Value) -> Result<usize, String> {
4121    // 10.4.2.4 steps 2-3 run TWO conversions: `ToUint32(value)` and then
4122    // `ToNumber(value)`, compared against each other. Both are observable — a
4123    // counting `valueOf` sees two calls in node and saw one here — and the
4124    // second is what makes `arr.length = 1.5` a RangeError rather than 1.
4125    let u32_pass = to_number_value(v)?;
4126    let n = to_number_value(v)?;
4127    let _ = u32_pass;
4128    // `ToUint32`: truncate toward zero, then modulo 2^32.
4129    let u = if n.is_finite() {
4130        (n.trunc() as i64).rem_euclid(1i64 << 32) as u32
4131    } else {
4132        0
4133    };
4134    // `-0` compares equal to `0` here, which is what makes `new Array(-0)` legal.
4135    if (u as f64) != n {
4136        return Err(range_error("Invalid array length"));
4137    }
4138    Ok(u as usize)
4139}
4140
4141/// A Node *coded* error raised from the JS layer: `Name [ERR_CODE]: message`.
4142///
4143/// `builtins::synth_error` parses that head back apart, so the bracketed code
4144/// becomes the enumerable `err.code` that `err.code === 'ERR_INVALID_URL'`-style
4145/// handling reads. Writing the head by hand at each throw site is what left a
4146/// dozen of them with `err.code === undefined` while the message matched.
4147///
4148/// Use this for errors Node raises from `lib/internal/errors.js`, whose `.name`
4149/// is left bracketed while the stack is captured and therefore shows up in both
4150/// `String(err)` and `err.stack` — measured on v26.7.0:
4151///
4152/// ```text
4153/// process.exit(1.5) -> RangeError [ERR_OUT_OF_RANGE]: The value of "code" …
4154/// ```
4155pub fn coded_error(class: &str, code: &str, msg: &str) -> String {
4156    format!("{class} [{code}]: {msg}")
4157}
4158
4159/// The marker `plain_coded_error` hides a code behind, and `synth_error` strips.
4160pub const CODE_MARK: &str = "\u{1}code:";
4161
4162/// Marks an error string as a `DOMException` carrying a WHATWG error NAME
4163/// rather than one of the ECMAScript error classes. WebCrypto and the abort
4164/// APIs reject with these, and the name (`NotSupportedError`) is not a class
4165/// `synth_error` could otherwise recognise.
4166pub const DOM_MARK: &str = "\u{1}dom:";
4167
4168/// A `DOMException` error string: `name` is the WHATWG error name.
4169pub fn dom_error(name: &str, msg: &str) -> String {
4170    format!("{DOM_MARK}{name}\u{1}{msg}")
4171}
4172
4173/// A Node coded error raised from the *native* layer: `.code` is set, but the
4174/// name is never bracketed, so `String(err)` is the plain `Name: message`.
4175///
4176/// The distinction is observable and is not a stylistic choice — on v26.7.0,
4177/// `String(new URL("/x") error)` is `TypeError: Invalid URL` with
4178/// `.code === 'ERR_INVALID_URL'`, while the JS-layer `process.exit(1.5)` error
4179/// brackets its code into the very same two reads. Encoding both through one
4180/// `Name [CODE]:` head would have to pick one and be wrong about the other.
4181///
4182/// The code rides in a marker at the head of the message rather than in the
4183/// error class, because the class text is exactly what must NOT carry it. The
4184/// marker is an internal wire format between a throw site and `synth_error`; it
4185/// never survives into a `.message`.
4186pub fn plain_coded_error(class: &str, code: &str, msg: &str) -> String {
4187    format!("{class}: {CODE_MARK}{code}\u{1}{msg}")
4188}
4189
4190/// Marks the start of the extra string own properties a
4191/// [`plain_coded_error_with`] error carries after its message.
4192pub const FIELDS_MARK: char = '\u{2}';
4193
4194/// [`plain_coded_error`] plus extra enumerable string own properties, set after
4195/// `code` in the order given — `new URL('x', 'nope')` throws with
4196/// `Object.keys(e)` reading `["code","input","base"]`.
4197///
4198/// Each field is `key\u{3}<byte length>\u{3}value`, so a value (a URL input is
4199/// arbitrary user text) may carry any character, the separators included.
4200pub fn plain_coded_error_with(
4201    class: &str,
4202    code: &str,
4203    msg: &str,
4204    fields: &[(&str, &str)],
4205) -> String {
4206    let mut s = plain_coded_error(class, code, msg);
4207    s.push(FIELDS_MARK);
4208    for (k, v) in fields {
4209        s.push_str(&format!("{k}\u{3}{}\u{3}{v}", v.len()));
4210    }
4211    s
4212}
4213
4214/// An error string as a person reads it: `TypeError: Invalid URL`, with the
4215/// internal code and field markers of [`plain_coded_error`] /
4216/// [`plain_coded_error_with`] removed. An uncaught native error is printed
4217/// from its string, and printed the wire format (`\u{1}code:ERR_INVALID_URL…`).
4218pub fn plain_error_text(e: &str) -> String {
4219    let Some(i) = e.find(CODE_MARK) else {
4220        return e.to_string();
4221    };
4222    let (head, rest) = e.split_at(i);
4223    match rest[CODE_MARK.len()..].split_once('\u{1}') {
4224        Some((_, m)) => format!("{head}{}", split_error_fields(m).0),
4225        None => e.to_string(),
4226    }
4227}
4228
4229/// Split a [`plain_coded_error_with`] message back into the message and its
4230/// fields. A message with no field mark comes back whole with no fields.
4231pub fn split_error_fields(msg: &str) -> (&str, Vec<(&str, &str)>) {
4232    let Some((head, mut rest)) = msg.split_once(FIELDS_MARK) else {
4233        return (msg, Vec::new());
4234    };
4235    let mut fields = Vec::new();
4236    while let Some((k, tail)) = rest.split_once('\u{3}') {
4237        let Some((len, tail)) = tail.split_once('\u{3}') else {
4238            break;
4239        };
4240        let Ok(len) = len.parse::<usize>() else { break };
4241        let Some(v) = tail.get(..len) else { break };
4242        fields.push((k, v));
4243        rest = &tail[len..];
4244    }
4245    (head, fields)
4246}
4247
4248/// `TypeError [ERR_INVALID_ARG_TYPE]: The "<name>" <kind> must be of type
4249/// <expected>. Received …` — Node's single most common argument rejection.
4250pub fn invalid_arg_type(name: &str, kind: &str, expected: &str, v: &Value) -> String {
4251    coded_error(
4252        "TypeError",
4253        "ERR_INVALID_ARG_TYPE",
4254        &format!(
4255            "The \"{name}\" {kind} must be of type {expected}. Received {}",
4256            crate::stdlib::received_desc(v)
4257        ),
4258    )
4259}
4260
4261// ── the fusevm run plumbing ──────────────────────────────────────────────────
4262
4263thread_local! {
4264    static DEBUG_MODE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4265}
4266
4267/// Enable/disable DAP debug execution (`node --dap`).
4268pub fn set_debug_mode(on: bool) {
4269    DEBUG_MODE.with(|d| d.set(on));
4270}
4271
4272// ── join cycle detection ─────────────────────────────────────────────────────
4273
4274thread_local! {
4275    /// Heap handles whose join is in progress, innermost last — V8's JoinStack.
4276    static JOIN_STACK: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
4277}
4278
4279/// V8's `JoinStackPush`: record that `v` is being joined, or report `false` if
4280/// it already is.
4281///
4282/// `Array.prototype.join` (and `toString`/`toLocaleString`, which route through
4283/// it) is the one place the language walks an object graph with no depth bound,
4284/// so every engine cuts re-entrance here: a receiver already on the stack
4285/// contributes the EMPTY STRING rather than recursing. Measured on node v26.7.0,
4286/// `const a=[1]; a.push(a); a.push(2); a.join('-')` is `"1--2"`, and
4287/// `String(a)`/`` `${a}` `` on `a=[a]` are both `""`. node-js had no such cut and
4288/// recursed until the native stack overflowed, ABORTING the process (exit 134) —
4289/// uncatchable, where node returns a string.
4290///
4291/// Only re-entrance is cut, not repetition: `[a,a].join('|')` still renders `a`
4292/// twice, because the first render pops before the second pushes.
4293///
4294/// A `true` return MUST be paired with [`join_stack_pop`].
4295pub fn join_stack_push(v: &Value) -> bool {
4296    match v {
4297        Value::Obj(i) => JOIN_STACK.with(|s| {
4298            let mut s = s.borrow_mut();
4299            if s.contains(i) {
4300                false
4301            } else {
4302                s.push(*i);
4303                true
4304            }
4305        }),
4306        _ => true,
4307    }
4308}
4309
4310/// Pop the innermost [`join_stack_push`].
4311pub fn join_stack_pop() {
4312    JOIN_STACK.with(|s| {
4313        s.borrow_mut().pop();
4314    });
4315}
4316
4317// ── native stack guard ───────────────────────────────────────────────────────
4318
4319thread_local! {
4320    /// Lowest stack address a nested run may start from, or 0 before the
4321    /// running thread's bounds have been measured. Cached because the pthread
4322    /// query is a syscall-free but non-trivial read and this is on every call.
4323    static STACK_FLOOR: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4324}
4325
4326/// Stack left unusable below the floor, as a fraction of the whole stack: the
4327/// throw itself still has to unwind, build an `Error`, capture `.stack` and run
4328/// whatever `catch` receives it, all of which needs room *below* the deepest
4329/// call that was allowed.
4330const STACK_RESERVE_DIVISOR: usize = 8;
4331/// Floor of that reserve, for a thread whose stack is small enough that an
4332/// eighth of it would not cover the unwind.
4333const STACK_RESERVE_MIN: usize = 512 * 1024;
4334/// Reserve assumed on a platform whose stack bounds cannot be queried. Deliberately
4335/// large relative to a default 8 MiB stack — over-reserving costs recursion
4336/// depth, under-reserving costs the process.
4337const STACK_RESERVE_FALLBACK: usize = 1024 * 1024;
4338
4339/// The address of a local in the caller's frame — how far down the stack
4340/// execution currently is. `black_box` keeps the probe from being optimized into
4341/// a different frame.
4342fn stack_pointer() -> usize {
4343    let probe = 0u8;
4344    std::hint::black_box(&probe) as *const u8 as usize
4345}
4346
4347/// The running thread's `(lowest address, size)` stack bounds.
4348///
4349/// Asked of pthread rather than assumed, because the three threads that run JS
4350/// have three different stacks: the `node` binary's own (`main.rs` reserves
4351/// [`crate::JS_STACK_SIZE`]), a `worker_threads` thread's, and a `cargo test`
4352/// harness thread's. A fixed byte budget would be wrong on two of the three.
4353fn stack_bounds() -> Option<(usize, usize)> {
4354    #[cfg(target_vendor = "apple")]
4355    {
4356        // SAFETY: both calls are pure reads of the calling thread's own
4357        // pthread record; neither allocates nor can fail.
4358        unsafe {
4359            let me = libc::pthread_self();
4360            let top = libc::pthread_get_stackaddr_np(me) as usize;
4361            let size = libc::pthread_get_stacksize_np(me);
4362            if size == 0 || top < size {
4363                return None;
4364            }
4365            Some((top - size, size))
4366        }
4367    }
4368    #[cfg(target_os = "linux")]
4369    {
4370        // SAFETY: `attr` is initialized by `pthread_getattr_np` before it is
4371        // read, only read on the success path, and destroyed on every path.
4372        unsafe {
4373            let mut attr: libc::pthread_attr_t = std::mem::zeroed();
4374            if libc::pthread_getattr_np(libc::pthread_self(), &mut attr) != 0 {
4375                return None;
4376            }
4377            let mut low: *mut libc::c_void = std::ptr::null_mut();
4378            let mut size: libc::size_t = 0;
4379            let ok = libc::pthread_attr_getstack(&attr, &mut low, &mut size) == 0;
4380            libc::pthread_attr_destroy(&mut attr);
4381            if ok && size != 0 {
4382                return Some((low as usize, size));
4383            }
4384            None
4385        }
4386    }
4387    #[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
4388    {
4389        None
4390    }
4391}
4392
4393/// The stack address below which a further nested VM run must throw instead of
4394/// recursing.
4395///
4396/// Every JS call is a Rust-level recursion — `run_user_func_nt` pushes a
4397/// [`Frame`], then `run_chunk_on` builds a whole new `fusevm::VM` on the stack
4398/// and runs the body, whose own calls land back here. Unbounded JS recursion
4399/// therefore used to exhaust the OS stack and ABORT: `fatal runtime error:
4400/// stack overflow`, exit 134, which no `try`/`catch` can see. V8 throws a
4401/// catchable `RangeError: Maximum call stack size exceeded` instead (measured on
4402/// node v26.7.0: `let d=0; function f(){d++;f()}` reports depth 9901).
4403///
4404/// The floor is derived from the thread's real bounds rather than a frame count
4405/// because a node-js frame has no fixed size — a debug build spends ~98 KiB per
4406/// JS call (measured: `node -e 'function f(n){…f(n-1)}'` survived 83 on an 8 MiB
4407/// stack and no more), a release build far less, and a native builtin recursing
4408/// through a user callback spends a different amount again.
4409fn stack_floor() -> usize {
4410    let cached = STACK_FLOOR.with(|c| c.get());
4411    if cached != 0 {
4412        return cached;
4413    }
4414    let floor = match stack_bounds() {
4415        Some((low, size)) => low + (size / STACK_RESERVE_DIVISOR).max(STACK_RESERVE_MIN),
4416        None => stack_pointer().saturating_sub(STACK_RESERVE_FALLBACK),
4417    };
4418    STACK_FLOOR.with(|c| c.set(floor));
4419    floor
4420}
4421
4422/// Stack given to each generator/async coroutine.
4423///
4424/// corosensei's default is 1 MiB, which at a debug build's ~98 KiB per JS call
4425/// left a `function*` body barely ten frames of recursion before it walked off
4426/// the end. The mapping is `PROT_NONE` reserved and `mprotect`ed, so the cost of
4427/// a larger one is address space, not resident memory — but it IS per live
4428/// generator, so this stays far below the entry thread's
4429/// [`crate::JS_STACK_SIZE`]: a program with thousands of concurrent async calls
4430/// has thousands of these.
4431const CORO_STACK_SIZE: usize = 16 * 1024 * 1024;
4432
4433/// The [`stack_floor`] that applies while a coroutine on `stack` is running.
4434fn coro_stack_floor(stack: &impl corosensei::stack::Stack) -> usize {
4435    stack.limit().get() + (CORO_STACK_SIZE / STACK_RESERVE_DIVISOR).max(STACK_RESERVE_MIN)
4436}
4437
4438/// corosensei's own `DefaultStack::default()` size, used only when the
4439/// [`CORO_STACK_SIZE`] reservation is refused and the coroutine therefore runs
4440/// on a stack whose bounds are not ours to read.
4441const CORO_FALLBACK_STACK_SIZE: usize = 1024 * 1024;
4442
4443/// Give a coroutine whose stack bounds are unknown a floor measured from where
4444/// its body starts. Called once, at body entry, on the coroutine's own stack.
4445fn ensure_coroutine_floor() {
4446    if STACK_FLOOR.with(|c| c.get()) != 0 {
4447        return;
4448    }
4449    let budget = CORO_FALLBACK_STACK_SIZE
4450        - (CORO_FALLBACK_STACK_SIZE / STACK_RESERVE_DIVISOR).max(STACK_RESERVE_MIN);
4451    STACK_FLOOR.with(|c| c.set(stack_pointer().saturating_sub(budget)));
4452}
4453
4454/// Install `floor` as the current stack floor, returning the previous one.
4455///
4456/// Used around a coroutine resume, which switches to a stack the thread's
4457/// pthread record knows nothing about. A floor of 0 means "not known" and makes
4458/// the next [`stack_floor`] measure again, which is the right answer for the
4459/// entry thread and a conservative one for a fallback coroutine stack.
4460fn swap_stack_floor(floor: usize) -> usize {
4461    STACK_FLOOR.with(|c| c.replace(floor))
4462}
4463
4464/// Whether the native stack is too close to its floor for one more nested run.
4465pub fn stack_exhausted() -> bool {
4466    stack_pointer() <= stack_floor()
4467}
4468
4469/// The error V8 raises when the call stack is exhausted. Catchable, and with the
4470/// `RangeError` constructor node uses — not a `panic!`.
4471pub fn stack_overflow_error() -> String {
4472    range_error("Maximum call stack size exceeded")
4473}
4474
4475/// Pool key for the body of user function `def_id`.
4476pub fn func_key(def_id: usize) -> u64 {
4477    1 << 40 | def_id as u64
4478}
4479
4480/// Pool key for one part of `try` statement `try_id`: 0 = the block, 1 = the
4481/// handler, 2 = the finalizer.
4482pub fn try_key(try_id: usize, part: u64) -> u64 {
4483    2 << 40 | (try_id as u64) << 2 | part
4484}
4485
4486thread_local! {
4487    /// VMs that have finished a run, kept for the next one — grouped by the
4488    /// chunk they still hold.
4489    ///
4490    /// Every JS call, every `try` block and every generator step runs its chunk
4491    /// through [`run_chunk_on`], which used to build a `fusevm::VM` from
4492    /// scratch: three `Vec` allocations, 70 `register_builtin` writes, an `Arc`
4493    /// for the numeric hook, and the JIT enable — per call. `fib(27)` makes
4494    /// 400k calls, so it built 400k VMs to run 23 ops each.
4495    ///
4496    /// Worse, the caller had to hand over an OWNED `Chunk`, so every call also
4497    /// deep-copied the function's whole compiled body: six `Vec`s, a `String`,
4498    /// and `sub_chunks` recursively. Keying the pool by chunk means a repeated
4499    /// call takes back the VM that already holds that body and copies nothing:
4500    /// `VM::reset` is handed the chunk the VM was already carrying.
4501    ///
4502    /// `VM::reset` keeps the builtin table, the hooks and the JIT setting, so a
4503    /// recycled VM needs none of that again. Each key holds a stack of VMs, and
4504    /// a nested (or recursive) call takes the next one, so a key grows to the
4505    /// deepest simultaneous entry into that function and no further.
4506    static VM_POOL: RefCell<rustc_hash::FxHashMap<u64, Vec<VM>>> =
4507        RefCell::new(rustc_hash::FxHashMap::default());
4508}
4509
4510/// An idle VM filed under `key`, if any.
4511fn take_pooled(key: u64) -> Option<VM> {
4512    VM_POOL.with(|p| p.borrow_mut().get_mut(&key).and_then(|v| v.pop()))
4513}
4514
4515/// File a finished VM under `key` for the next run to take.
4516fn put_pooled(key: u64, vm: VM) {
4517    VM_POOL.with(|p| p.borrow_mut().entry(key).or_default().push(vm));
4518}
4519
4520/// Take a VM ready to run `chunk` — recycled if one is idle, otherwise built
4521/// and fitted with the builtins and hooks a fresh VM needs.
4522fn acquire_vm(chunk: Chunk) -> VM {
4523    if let Some(mut vm) = take_pooled(0) {
4524        vm.reset(chunk);
4525        return vm;
4526    }
4527    let mut vm = VM::new(chunk);
4528    crate::builtins::install(&mut vm);
4529    vm.set_numeric_hook(std::sync::Arc::new(|op, a, b| {
4530        crate::builtins::numeric_hook(op, a, b)
4531    }));
4532    // Under `--dap` the tracing JIT would compile hot loops and skip the
4533    // per-statement `DBG_LINE` markers, so debug runs stay on the pure
4534    // interpreter. The `DBG_LINE` builtin fires the debugger line hook; the
4535    // extension seam mirrors pythonrs should the marker emission ever switch.
4536    // The mode is fixed before the first chunk runs, so a pooled VM can never
4537    // come back wearing the wrong one.
4538    if DEBUG_MODE.with(|d| d.get()) {
4539        vm.set_extension_handler(Box::new(|vm, id, _| {
4540            crate::dap::on_ext(vm, id);
4541        }));
4542    } else {
4543        vm.enable_tracing_jit();
4544    }
4545    vm
4546}
4547
4548/// Register every node-js builtin + the numeric hook on a VM, then run it.
4549///
4550/// For a chunk that runs once — a module body, an `eval` — there is nothing to
4551/// key a pool by, so this resets a spare VM with the caller's chunk. Anything
4552/// that runs repeatedly (a function body, a `try` block) goes through
4553/// [`run_chunk_keyed`] instead and never copies its chunk twice.
4554pub fn run_chunk_on(chunk: Chunk) -> Result<Value, String> {
4555    // Checked before the `VM` is built: `VM::new` + `install` are themselves
4556    // several KiB of frame, so a check after them could already have overflowed.
4557    if stack_exhausted() {
4558        return Err(stack_overflow_error());
4559    }
4560    finish_run(0, acquire_vm(chunk))
4561}
4562
4563/// Run the chunk filed under `key`, building it with `make` only if no VM is
4564/// already holding it. A recycled VM re-runs the chunk it kept, so a repeated
4565/// call copies no bytecode at all.
4566pub fn run_chunk_keyed(key: u64, make: impl FnOnce() -> Chunk) -> Result<Value, String> {
4567    if stack_exhausted() {
4568        return Err(stack_overflow_error());
4569    }
4570    let vm = match take_pooled(key) {
4571        Some(mut vm) => {
4572            // Hand the VM back the chunk it is already carrying: `reset` takes
4573            // an owned `Chunk`, and this is the one place where the owned chunk
4574            // costs nothing.
4575            let held = std::mem::take(&mut vm.chunk);
4576            vm.reset(held);
4577            vm
4578        }
4579        None => acquire_vm(make()),
4580    };
4581    finish_run(key, vm)
4582}
4583
4584/// Run a prepared VM to completion and file it back under `key`.
4585fn finish_run(key: u64, mut vm: VM) -> Result<Value, String> {
4586    let outcome = vm.run();
4587    let result = match outcome {
4588        _ if with_host(|h| h.error.is_some()) => {
4589            Err(with_host(|h| h.take_error()).expect("just checked"))
4590        }
4591        VMResult::Ok(v) => Ok(v),
4592        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
4593        VMResult::Error(e) => Err(e),
4594    };
4595    put_pooled(key, vm);
4596    result
4597}
4598
4599/// Run `chunk` in the GLOBAL scope instead of the caller's.
4600///
4601/// `run_chunk_on` executes on whatever frame is current, so a nested run sees —
4602/// and can shadow — the *calling function's* locals. That is right for a direct
4603/// `eval`, and wrong for every other runtime-source construct: a `new Function`
4604/// body, an indirect `eval` and `vm.runInThisContext` are all specified to run
4605/// in the global scope (ECMA-262 19.2.1.1 `PerformEval` with a null
4606/// `strictCaller`/`direct` pair; `FunctionBody` is instantiated with the *global*
4607/// environment, 20.2.1.1.1 step 26). Measured against node v26.7.0,
4608/// `function outer(){ let loc = 42; return vm.runInThisContext('typeof loc'); }`
4609/// is `"undefined"` there and was `"number"` here.
4610///
4611/// A `var` the chunk itself declares lands in the top-level scope and persists,
4612/// so successive `vm.runInThisContext` calls share it.
4613pub fn run_chunk_in_global_scope(chunk: Chunk) -> Result<Value, String> {
4614    // An INDIRECT eval really is global code (19.2.1.1 step 6): its `var`s bind
4615    // to the global object, not to the entry module's wrapper scope. The flag
4616    // that keeps the entry script's own `var`s out of the globals map has to be
4617    // lifted for the duration, or `(0, eval)('var g = 1')` stopped reaching
4618    // `globalThis.g`.
4619    let prev_scope = with_host(|h| std::mem::take(&mut h.module_scope));
4620    let out = run_chunk_in_global_scope_inner(chunk, false);
4621    with_host(|h| h.module_scope = prev_scope);
4622    out
4623}
4624
4625/// [`run_chunk_in_global_scope`] for an INDIRECT eval, whose `let`, `const`
4626/// and `class` live in a fresh declarative environment under the global one
4627/// (19.2.1.1 `PerformEval` step 16) and die with it, while its `var`s still
4628/// bind globally. A script (`vm.runInThisContext`) shares the global lexical
4629/// scope instead.
4630pub fn run_chunk_in_eval_scope(chunk: Chunk) -> Result<Value, String> {
4631    let prev_scope = with_host(|h| std::mem::take(&mut h.module_scope));
4632    let out = run_chunk_in_global_scope_inner(chunk, true);
4633    with_host(|h| h.module_scope = prev_scope);
4634    out
4635}
4636
4637fn run_chunk_in_global_scope_inner(chunk: Chunk, own_lexical: bool) -> Result<Value, String> {
4638    let global_env = with_host(|h| h.global_env.clone());
4639    with_host(|h| {
4640        h.settle_op_pos();
4641        h.frames.push(Frame {
4642            env: global_env.clone(),
4643            base_env: global_env,
4644            this_obj: None,
4645            new_target: None,
4646            home_class: None,
4647            home_static: false,
4648            home_object: None,
4649            strict: false,
4650            line: 0,
4651            pos: 0,
4652            arrow: false,
4653            owner: None,
4654            is_module: true,
4655            this_state: ThisState::Plain,
4656        });
4657        if own_lexical {
4658            h.push_scope();
4659        }
4660    });
4661    let r = run_chunk_on(chunk);
4662    with_host(|h| {
4663        h.frames.pop();
4664        clear_op_pos();
4665    });
4666    r
4667}
4668
4669/// Run the top-level program chunk, then drain the event loop (microtasks +
4670/// timers) until quiescent — matching Node, which keeps the process alive while
4671/// pending async work remains.
4672pub fn run_main(chunk: Chunk) -> Result<Value, String> {
4673    with_host(|h| h.module_scope = true);
4674    let mut r = run_chunk_on(chunk);
4675    with_host(|h| {
4676        h.signal = None;
4677        h.module_frame_done = true;
4678    });
4679    if let Err(e) = &r {
4680        if recover_uncaught(e, "uncaughtException")? {
4681            r = Ok(Value::Undef);
4682        }
4683    }
4684    if r.is_ok() {
4685        // A callback that throws ends this drain; a handled exception resumes
4686        // it where it stopped, as node's loop carries on after
4687        // `process._fatalException` reports the error handled.
4688        while let Err(e) = run_event_loop() {
4689            if !recover_uncaught(&e, "uncaughtException")? {
4690                return Err(e);
4691            }
4692        }
4693        finish_process_events()?;
4694    }
4695    r
4696}
4697
4698/// The value an exception that reached the top of the stack carries: the
4699/// thrown value, or an `Error` built from an internal error string.
4700fn uncaught_value(msg: &str) -> Value {
4701    with_host(|h| h.exc.take())
4702        .unwrap_or_else(|| with_host(|h| crate::builtins::synth_error(h, msg)))
4703}
4704
4705/// What node writes to stderr for the exception `msg` that is ending the
4706/// process — `ReportFatalException` (`src/node_errors.cc`), fed by
4707/// `fatalExceptionStackEnhancers` (`lib/internal/errors.js`):
4708///
4709/// - an object (an `Error` or anything else) prints the source arrow — the
4710///   `file:line` header, the source line and a `^` under the raise, then a
4711///   blank line — followed by `util.inspect(err, { customInspect: false,
4712///   depth: 5 })`, which for an error is its `stack` plus any own properties;
4713/// - a primitive prints a blank line, the arrow, the value, and the
4714///   `--trace-uncaught` hint (`AppendExceptionLine` writes the arrow itself
4715///   for a non-error);
4716/// - both end with a blank line and `Node.js <version>`.
4717///
4718/// The arrow points where the exception was thrown, except for an unhandled
4719/// rejection, whose error has no throw site and is shown where it was created.
4720/// node colours the inspected error when stderr is a terminal; this runtime's
4721/// `util.inspect` has no colours, so it never does.
4722pub fn fatal_report(msg: &str) -> String {
4723    let value = uncaught_value(msg);
4724    let (is_object, is_error, pos, end) = with_host(|h| {
4725        let is_object = matches!(h.type_of(&value), "object" | "function") && !h.is_null(&value);
4726        let is_error = crate::builtins::has_error_data(h, &value);
4727        let (pos, end) = if h.fatal_from_promise {
4728            match lookup_chain(h, &value, "@@pos") {
4729                Some(Value::Int(p)) => (p as u32, 0),
4730                _ => (0, 0),
4731            }
4732        } else {
4733            h.throw_site
4734                .as_ref()
4735                .filter(|s| s.msg == msg)
4736                .map_or((0, 0), |s| (s.pos, s.end))
4737        };
4738        (is_object, is_error, pos, end)
4739    });
4740    let arrow = with_host(|h| source_arrow_span(h, pos, end));
4741    // `AppendExceptionLine` keeps the arrow on the error for the report to
4742    // print only for a native error, or for anything thrown by `[eval]` /
4743    // `[stdin]` source (which node runs through `vm`); otherwise it writes
4744    // the arrow to stderr itself, behind a blank line, and the report follows
4745    // with no separating line.
4746    let arrow_on_error = is_error
4747        || with_host(|h| {
4748            h.source_location(pos)
4749                .is_some_and(|l| l.name.starts_with('['))
4750        });
4751    let mut out = String::new();
4752    if is_object {
4753        let shown = with_host(|h| {
4754            let mut opts: IndexMap<String, Value> = IndexMap::new();
4755            opts.insert("customInspect".into(), Value::Bool(false));
4756            opts.insert("depth".into(), Value::Int(5));
4757            h.new_object(opts)
4758        });
4759        let mut trace = match crate::stdlib::util::call("inspect", &[value.clone(), shown]) {
4760            Some(Ok(s)) => with_host(|h| h.str_of(&s)),
4761            _ => with_host(|h| h.str_of(&value)),
4762        };
4763        // `inspect` brackets an error whose stack has no frames
4764        // (`[SyntaxError: …]`). node's always has some — its own loader's,
4765        // which this runtime leaves out — so the header prints bare there.
4766        if is_error && trace.starts_with('[') {
4767            let stack = crate::builtins::get_property(&value, "stack")
4768                .ok()
4769                .map(|s| with_host(|h| h.str_of(&s)));
4770            if let Some(stack) = stack.filter(|s| !s.contains("\n    at ")) {
4771                if trace.strip_prefix('[').and_then(|t| t.strip_suffix(']')) == Some(stack.as_str())
4772                {
4773                    trace = stack;
4774                }
4775            }
4776        }
4777        match arrow {
4778            Some(a) if arrow_on_error => {
4779                out.push_str(&a);
4780                out.push('\n');
4781            }
4782            Some(a) => {
4783                out.push('\n');
4784                out.push_str(&a);
4785            }
4786            None => {}
4787        }
4788        out.push_str(&trace);
4789        out.push('\n');
4790    } else {
4791        if let Some(a) = arrow {
4792            out.push('\n');
4793            out.push_str(&a);
4794        }
4795        out.push_str(&with_host(|h| h.str_of(&value)));
4796        out.push('\n');
4797        let argv0 = std::env::args().next().unwrap_or_default();
4798        let exe = std::path::Path::new(&argv0)
4799            .file_stem()
4800            .and_then(|s| s.to_str())
4801            .filter(|s| !s.is_empty())
4802            .unwrap_or("node")
4803            .to_string();
4804        out.push_str(&format!(
4805            "(Use `{exe} --trace-uncaught ...` to show where the exception was thrown)\n"
4806        ));
4807    }
4808    out.push_str(&format!(
4809        "\nNode.js {}\n",
4810        crate::stdlib::process::NODE_VERSION
4811    ));
4812    out
4813}
4814
4815/// Record that `src`, which node names `origin`, failed to parse with `msg`
4816/// at script-relative position `pos` (from `parser::take_error_pos`): the
4817/// text joins the source address space so the SyntaxError's report can show
4818/// node's arrow under the offending token.
4819///
4820/// The end of the underlined span comes from `parser::take_error_end`.
4821pub fn note_syntax_error(src: &str, origin: ScriptOrigin, msg: &str, pos: u32) {
4822    let end = crate::parser::take_error_end();
4823    if pos == 0 {
4824        return;
4825    }
4826    with_host(|h| {
4827        let script = h.scripts.len() as u32;
4828        h.scripts.push(src.into());
4829        let base = h.register_source(script, origin);
4830        let frames = Some(h.stack_frames());
4831        h.throw_site = Some(ThrowSite {
4832            msg: msg.to_string(),
4833            pos: base + pos - 1,
4834            end: if end >= pos { base + end - 1 } else { 0 },
4835            depth: h.stack_depth(),
4836            frames,
4837        });
4838    });
4839}
4840
4841/// Run `f` — the `exit` listeners of a dying process — without letting it
4842/// disturb the exception [`fatal_report`] then describes: node emits `exit`
4843/// inside `process._fatalException` and prints the report after it returns,
4844/// and a listener that throws and catches would otherwise replace the record.
4845pub fn preserving_fatal_state<R>(f: impl FnOnce() -> R) -> R {
4846    let saved = with_host(|h| (h.exc.clone(), h.throw_site.clone(), h.fatal_from_promise));
4847    let r = f();
4848    with_host(|h| (h.exc, h.throw_site, h.fatal_from_promise) = saved);
4849    r
4850}
4851
4852/// node's source arrow for position `pos` (`GetErrorSource`,
4853/// `src/node_errors.cc`): `file:line`, the source line, and a caret line that
4854/// copies the line's tabs and puts one `^` under the column — V8 reports a
4855/// raise as the one-character range `[pos, pos + 1)`.
4856pub fn source_arrow(h: &JsHost, pos: u32) -> Option<String> {
4857    source_arrow_span(h, pos, 0)
4858}
4859
4860/// [`source_arrow`] for the range `[pos, end)`: one `^` per column, none for
4861/// an empty range (the end of the input), and no caret line at all for a
4862/// range that runs past the end of its line, as `GetErrorSource` prints it.
4863/// An `end` of 0 is the one-character range.
4864pub fn source_arrow_span(h: &JsHost, pos: u32, end: u32) -> Option<String> {
4865    let l = h.source_location(pos).filter(|l| !l.internal)?;
4866    let head = format!("{}:{}\n{}\n", l.name, l.line, l.source_line);
4867    let end_col = match h.source_location(end) {
4868        _ if end == 0 || end < pos => l.col + 1,
4869        Some(e) if e.line == l.line => e.col,
4870        _ => return Some(head),
4871    };
4872    let mut caret: String = l
4873        .source_line
4874        .chars()
4875        .take(l.col as usize - 1)
4876        .map(|c| if c == '\t' { '\t' } else { ' ' })
4877        .collect();
4878    for _ in l.col..end_col {
4879        caret.push('^');
4880    }
4881    Some(format!("{head}{caret}\n"))
4882}
4883
4884/// Offer an uncaught exception to `process.on('uncaughtException')`; `Ok(true)`
4885/// means a listener took it and the program carries on.
4886fn recover_uncaught(msg: &str, origin: &str) -> Result<bool, String> {
4887    let has_listeners = with_host(|h| {
4888        h.has_process_listeners("uncaughtException")
4889            || h.has_process_listeners("uncaughtExceptionMonitor")
4890    });
4891    if !has_listeners {
4892        return Ok(false);
4893    }
4894    let err = uncaught_value(msg);
4895    let handled = deliver_uncaught(&err, origin)?;
4896    if !handled {
4897        // Unhandled after all (only a monitor was listening): put the value
4898        // back so the fatal report prints the thrown value.
4899        with_host(|h| h.exc = Some(err));
4900    }
4901    Ok(handled)
4902}
4903
4904/// Node's `process._fatalException`: every `uncaughtExceptionMonitor` listener
4905/// sees `(err, origin)` first, then — if any `uncaughtException` listener
4906/// exists — each of those is called and the exception counts as handled.
4907/// A listener that throws is fatal with status 7.
4908fn deliver_uncaught(err: &Value, origin: &str) -> Result<bool, String> {
4909    let origin = with_host(|h| h.new_str(origin));
4910    for f in with_host(|h| h.take_process_listeners("uncaughtExceptionMonitor")) {
4911        invoke(&f, vec![err.clone(), origin.clone()], None)?;
4912    }
4913    let listeners = with_host(|h| h.take_process_listeners("uncaughtException"));
4914    if listeners.is_empty() {
4915        return Ok(false);
4916    }
4917    for f in listeners {
4918        if let Err(e) = invoke(&f, vec![err.clone(), origin.clone()], None) {
4919            with_host(|h| h.fatal_handler_failed = true);
4920            return Err(e);
4921        }
4922    }
4923    Ok(true)
4924}
4925
4926/// The shutdown sequence Node runs once the loop has drained on its own: fire
4927/// `beforeExit` (which MAY schedule more work, in which case the loop runs
4928/// again and `beforeExit` fires again), then fire `exit` exactly once.
4929///
4930/// Neither event fired at all before this existed, so `process.on('exit', …)`
4931/// was a registration with no delivery — a listener whose body printed was
4932/// silently dropped, and one that set `process.exitCode` could not affect the
4933/// status. Measured on node v26.7.0,
4934/// `process.on('exit', c => console.log('exit', c))` prints `exit 0`.
4935///
4936/// An explicit `process.exit()` never reaches here (it leaves the process from
4937/// inside the builtin), and neither does an uncaught exception — matching
4938/// Node, where `beforeExit` is skipped on both paths.
4939fn finish_process_events() -> Result<(), String> {
4940    // Bounded: a `beforeExit` listener that re-arms work every time would spin
4941    // forever, exactly as it does in Node, but a runaway here would hang a
4942    // parity run with no output, so it is capped and then treated as drained.
4943    for _ in 0..1000 {
4944        let code = with_host(|h| h.exit_code).unwrap_or(0);
4945        if !crate::stdlib::process::emit_before_exit(code)? {
4946            break;
4947        }
4948        let more = with_host(|h| h.loop_alive());
4949        if !more {
4950            break;
4951        }
4952        run_event_loop()?;
4953    }
4954    crate::esm::settle_unfinished_entry()?;
4955    let code = with_host(|h| h.exit_code).unwrap_or(0);
4956    crate::stdlib::process::emit_exit_event(code)
4957}
4958
4959// ── formatting ───────────────────────────────────────────────────────────────
4960
4961/// Format a JS number exactly as `Number.prototype.toString` does for the common
4962/// range (no exponential-notation threshold handling for very large/small).
4963pub fn fmt_number(f: f64) -> String {
4964    if f.is_nan() {
4965        return "NaN".into();
4966    }
4967    if f.is_infinite() {
4968        return if f > 0.0 { "Infinity" } else { "-Infinity" }.into();
4969    }
4970    if f == 0.0 {
4971        // Covers -0.0 too: (-0).toString() === "0".
4972        return "0".into();
4973    }
4974    if f < 0.0 {
4975        return format!("-{}", js_number_repr(-f));
4976    }
4977    js_number_repr(f)
4978}
4979
4980/// If `k` is an array-index property key, return its numeric value. Per
4981/// ECMAScript, a String property key `P` is an array index iff
4982/// `ToString(ToUint32(P)) === P` and `ToUint32(P) !== 2^32 - 1` — i.e. a
4983/// canonical decimal (no leading zeros, no sign) in the range `0..=2^32-2`.
4984pub fn array_index(k: &str) -> Option<u32> {
4985    if k.is_empty() {
4986        return None;
4987    }
4988    if k == "0" {
4989        return Some(0);
4990    }
4991    // A leading '0' (other than the lone "0" above) is non-canonical.
4992    if k.as_bytes()[0] == b'0' {
4993        return None;
4994    }
4995    if !k.bytes().all(|b| b.is_ascii_digit()) {
4996        return None;
4997    }
4998    match k.parse::<u64>() {
4999        // Array index must be < 2^32-1; u32::MAX == 2^32-1 is excluded.
5000        Ok(n) if n < u32::MAX as u64 => Some(n as u32),
5001        _ => None,
5002    }
5003}
5004
5005/// Compare two own-property keys for `OrdinaryOwnPropertyKeys` enumeration order:
5006/// integer-index keys sort ascending-numeric and precede all string keys; two
5007/// non-index keys compare `Equal` so a *stable* sort leaves them in insertion
5008/// order. (Symbols are stored as `@@…`/`#…` string keys and are non-index, so
5009/// they also fall into the stable-insertion-order tail.)
5010pub fn key_order_cmp(a: &str, b: &str) -> std::cmp::Ordering {
5011    use std::cmp::Ordering;
5012    match (array_index(a), array_index(b)) {
5013        (Some(x), Some(y)) => x.cmp(&y),
5014        (Some(_), None) => Ordering::Less,
5015        (None, Some(_)) => Ordering::Greater,
5016        (None, None) => Ordering::Equal,
5017    }
5018}
5019
5020/// Reorder an object's own-property map into `OrdinaryOwnPropertyKeys` order in
5021/// place: array-index keys ascending first, then the remaining keys in their
5022/// existing (insertion) order. A no-op unless at least one index key is present,
5023/// so the overwhelmingly common all-string-key object keeps its exact order and
5024/// pays nothing. `IndexMap::sort_by` is a stable sort.
5025pub fn canonicalize_own_keys(props: &mut IndexMap<String, Value>) {
5026    if props.keys().any(|k| array_index(k).is_some()) {
5027        props.sort_by(|ak, _, bk, _| key_order_cmp(ak, bk));
5028    }
5029}
5030
5031/// The shortest round-trip decimal digits of a positive finite `a` and its
5032/// decimal exponent: `a == d1.d2…dk × 10^e` with `d1 != 0`.
5033///
5034/// Rust's `{:e}` yields the shortest digit string closest to `a`, but on an
5035/// exact tie between two equally close candidates it rounds UP, where
5036/// ECMA-262 Number::toString (and V8's bignum-dtoa) take the EVEN last digit:
5037/// `25577030267034.8125` prints `25577030267034.812` in node. A tie needs the
5038/// value to sit exactly halfway, i.e. to terminate one digit past the shortest
5039/// form with a `5`, so it is detected with an exact expansion, and only for
5040/// 16+ digit results (the only ones whose rounding interval can hold two
5041/// candidates).
5042pub fn shortest_digits(a: f64) -> (String, i32) {
5043    let sci = format!("{a:e}");
5044    let (mant, exp_str) = sci.split_once('e').expect("LowerExp always has 'e'");
5045    let e: i32 = exp_str.parse().expect("LowerExp exponent is an integer");
5046    let mut s: String = mant.chars().filter(|c| *c != '.').collect();
5047    let k = s.len();
5048    let last = s.as_bytes()[k - 1];
5049    if k >= 16 && last % 2 == 1 && is_exact_midpoint(a, k, e) {
5050        let lower = format!("{}{}", &s[..k - 1], (last - 1) as char);
5051        let reparsed: f64 = format!("{lower}e{}", e - (k as i32 - 1))
5052            .parse()
5053            .unwrap_or(f64::NAN);
5054        if reparsed == a {
5055            s = lower;
5056        }
5057    }
5058    (s, e)
5059}
5060
5061/// True when `a` is exactly `k + 1` significant digits long ending in `5`,
5062/// i.e. it lies exactly halfway between two `k`-digit decimals.
5063fn is_exact_midpoint(a: f64, k: usize, e: i32) -> bool {
5064    let exact = format!("{a:.1100e}");
5065    let (mant, exp_str) = exact.split_once('e').expect("LowerExp always has 'e'");
5066    if exp_str.parse::<i32>().ok() != Some(e) {
5067        return false;
5068    }
5069    let digits: Vec<u8> = mant.bytes().filter(u8::is_ascii_digit).collect();
5070    digits.get(k) == Some(&b'5') && digits[k + 1..].iter().all(|&d| d == b'0')
5071}
5072
5073/// ECMAScript `Number::toString` layout for a positive, finite, nonzero value.
5074///
5075/// Rust's `Display`/`LowerExp` give the shortest round-trip decimal digits, but
5076/// NOT JavaScript's exponential-vs-fixed threshold: Rust prints `1e21` as
5077/// `1000000000000000000000` and `1e-7` as `0.0000001`, whereas JS prints `1e+21`
5078/// and `1e-7`. So we take the shortest digits from `{:e}` and re-lay them out per
5079/// the spec (steps 5–10 of Number::toString): `k` significant digits `s` with
5080/// decimal exponent `n` (value = s × 10^(n−k)); exponential form only when
5081/// `n > 21` or `n ≤ -6`.
5082fn js_number_repr(a: f64) -> String {
5083    let (s, e) = shortest_digits(a);
5084    let k = s.len() as i32; // number of significant digits
5085    let n = e + 1; // value = s × 10^(n−k), 10^(k−1) ≤ s < 10^k
5086
5087    if k <= n && n <= 21 {
5088        // Integer with trailing zeros: all digits, then n−k zeros.
5089        let mut out = s;
5090        out.push_str(&"0".repeat((n - k) as usize));
5091        out
5092    } else if 0 < n && n <= 21 {
5093        // Decimal point inside the digit run: n digits, '.', the rest.
5094        format!("{}.{}", &s[..n as usize], &s[n as usize..])
5095    } else if -6 < n && n <= 0 {
5096        // Leading "0." then (−n) zeros then all digits.
5097        format!("0.{}{}", "0".repeat((-n) as usize), s)
5098    } else {
5099        // Exponential form. Exponent digit is n−1, always signed.
5100        let exp = n - 1;
5101        let sign = if exp >= 0 { '+' } else { '-' };
5102        let mag = exp.abs();
5103        if k == 1 {
5104            format!("{s}e{sign}{mag}")
5105        } else {
5106            format!("{}.{}e{sign}{mag}", &s[..1], &s[1..])
5107        }
5108    }
5109}
5110
5111impl JsHost {
5112    /// The `typeof` string for `v`.
5113    pub fn type_of(&self, v: &Value) -> &'static str {
5114        match v {
5115            Value::Undef => "undefined",
5116            Value::Bool(_) => "boolean",
5117            Value::Int(_) | Value::Float(_) => "number",
5118            Value::Str(_) => "string",
5119            Value::Obj(_) => match self.get(v) {
5120                Some(JsObj::Str(_)) => "string",
5121                // 10.5's `[[Call]]` slot exists on a proxy exactly when its
5122                // target is callable, so `typeof` classifies by the target —
5123                // `typeof new Proxy(function(){}, {})` is `'function'`. The walk
5124                // is bounded: a proxy of a proxy defers again.
5125                Some(JsObj::Proxy { target, .. }) => {
5126                    let mut cur = target;
5127                    for _ in 0..100 {
5128                        match self.get(cur) {
5129                            Some(JsObj::Proxy { target: t, .. }) => cur = t,
5130                            _ => break,
5131                        }
5132                    }
5133                    if is_callable(self, cur) {
5134                        "function"
5135                    } else {
5136                        "object"
5137                    }
5138                }
5139                Some(JsObj::Func(_))
5140                | Some(JsObj::BoundMethod { .. })
5141                | Some(JsObj::BoundFunc { .. })
5142                | Some(JsObj::Class(_)) => "function",
5143                // A Builtin is a callable (`Array`, `parseInt`, `Math.floor`) —
5144                // `typeof === "function"` — EXCEPT the non-callable namespace
5145                // objects (`Math`, `JSON`, `require('fs')`, …) which are "object".
5146                Some(JsObj::Builtin(n)) => {
5147                    if builtin_is_callable(n) {
5148                        "function"
5149                    } else {
5150                        "object"
5151                    }
5152                }
5153                Some(JsObj::Symbol { .. }) => "symbol",
5154                Some(JsObj::BigInt(_)) => "bigint",
5155                _ => "object", // arrays, objects, null, Map/Set, generators
5156            },
5157            _ => "object",
5158        }
5159    }
5160
5161    /// JS truthiness: false / 0 / -0 / NaN / "" / null / undefined are falsy.
5162    pub fn truthy(&self, v: &Value) -> bool {
5163        match v {
5164            Value::Undef => false,
5165            Value::Bool(b) => *b,
5166            Value::Int(n) => *n != 0,
5167            Value::Float(f) => *f != 0.0 && !f.is_nan(),
5168            Value::Str(s) => !s.is_empty(),
5169            Value::Obj(_) => match self.get(v) {
5170                Some(JsObj::Str(s)) => !s.is_empty(),
5171                Some(JsObj::Null) => false,
5172                Some(JsObj::BigInt(b)) => !num_traits::Zero::is_zero(b),
5173                _ => true, // arrays, objects, functions
5174            },
5175            _ => true,
5176        }
5177    }
5178
5179    /// Coerce to a number (`ToNumber`): the arithmetic-context conversion.
5180    pub fn to_number(&self, v: &Value) -> f64 {
5181        match v {
5182            Value::Undef => f64::NAN,
5183            Value::Bool(b) => {
5184                if *b {
5185                    1.0
5186                } else {
5187                    0.0
5188                }
5189            }
5190            Value::Int(n) => *n as f64,
5191            Value::Float(f) => *f,
5192            Value::Str(s) => str_to_number(s),
5193            Value::Obj(_) => match self.get(v) {
5194                Some(JsObj::Str(s)) => str_to_number(s),
5195                Some(JsObj::Null) => 0.0,
5196                Some(JsObj::BigInt(b)) => bigint_to_f64(b),
5197                Some(JsObj::Array(items)) => {
5198                    // [] -> 0, [x] -> ToNumber(x), else NaN.
5199                    if items.is_empty() {
5200                        0.0
5201                    } else if items.len() == 1 {
5202                        self.to_number(&items[0])
5203                    } else {
5204                        f64::NAN
5205                    }
5206                }
5207                _ => f64::NAN,
5208            },
5209            _ => f64::NAN,
5210        }
5211    }
5212
5213    /// `String(v)` — the string-coercion form (raw, unquoted).
5214    pub fn str_of(&self, v: &Value) -> String {
5215        match v {
5216            Value::Undef => "undefined".into(),
5217            Value::Bool(b) => if *b { "true" } else { "false" }.into(),
5218            Value::Int(n) => n.to_string(),
5219            Value::Float(f) => fmt_number(*f),
5220            Value::Str(s) => (**s).clone(),
5221            Value::Obj(_) => match self.get(v) {
5222                Some(JsObj::Str(s)) => s.clone(),
5223                Some(JsObj::Null) => "null".into(),
5224                Some(JsObj::BigInt(b)) => b.to_string(),
5225                Some(JsObj::RegExp(r)) => format!("/{}/{}", r.source, r.flags),
5226                Some(JsObj::Array(items)) => {
5227                    // Array.prototype.toString: comma-join, null/undefined -> "".
5228                    // Guarded by the JoinStack (see `join_stack_push`) so a
5229                    // self-referential array yields "" instead of recursing until
5230                    // the native stack aborts the process.
5231                    if !join_stack_push(v) {
5232                        return String::new();
5233                    }
5234                    let parts: Vec<String> = items
5235                        .iter()
5236                        .map(|x| match x {
5237                            Value::Undef => String::new(),
5238                            _ if self.is_null(x) => String::new(),
5239                            _ => self.str_of(x),
5240                        })
5241                        .collect();
5242                    join_stack_pop();
5243                    parts.join(",")
5244                }
5245                Some(JsObj::Object(props)) => {
5246                    // A native `Buffer` stringifies to its decoded (utf-8)
5247                    // contents, matching `buf.toString()` — needed for `'' + buf`,
5248                    // template interpolation, and `data += chunk` (the pattern
5249                    // Express/body-parser use to read a request body).
5250                    if props.get("@@native").map(|t| self.str_of(t)).as_deref() == Some("Buffer") {
5251                        let bytes = crate::stdlib::buffer::window_bytes_h(self, props);
5252                        String::from_utf8_lossy(&bytes).into_owned()
5253                    } else if let Some(s) = self.error_to_string(v) {
5254                        s
5255                    } else {
5256                        "[object Object]".into()
5257                    }
5258                }
5259                Some(JsObj::Func(f)) => {
5260                    // A function built from runtime source (`new Function`,
5261                    // `vm.compileFunction`) retains the exact text V8 synthesizes
5262                    // for it, so `Function.prototype.toString` reports what Node
5263                    // reports. Every other function slices its span out of the
5264                    // script it was parsed from; only one whose program kept no
5265                    // text (an AOT image, a `rust { }` desugared file) falls back
5266                    // to the placeholder.
5267                    if let Some(src) = self.fn_prop(v, "@@source") {
5268                        return self.str_of(&src);
5269                    }
5270                    if let Some(text) = self.func_source(f.def_id) {
5271                        return text.to_string();
5272                    }
5273                    let name = self
5274                        .funcs
5275                        .get(f.def_id)
5276                        .map(|d| d.name.clone())
5277                        .unwrap_or_default();
5278                    format!("function {name}() {{ [code] }}")
5279                }
5280                // The native-code form names the FUNCTION, not its key:
5281                // `String(Math.max)` is `function max() { [native code] }`.
5282                Some(JsObj::Builtin(n)) => {
5283                    // The `console` methods are the exception node itself makes:
5284                    // each is a wrapper, so `String(console.log)` is the
5285                    // ANONYMOUS native-code form even though `console.log.name`
5286                    // is `log`. Measured on v26.8.1.
5287                    if n.starts_with("console.") {
5288                        "function () { [native code] }".into()
5289                    } else if let Some(accessor) = crate::builtins::proto_getter_name(n) {
5290                        // An accessor half names itself `get size` / `set
5291                        // arguments`, which `builtin_name` cannot build because
5292                        // it returns a borrowed `&str`.
5293                        format!("function {accessor}() {{ [native code] }}")
5294                    } else {
5295                        format!(
5296                            "function {}() {{ [native code] }}",
5297                            crate::builtins::builtin_name(n)
5298                        )
5299                    }
5300                }
5301                // A method read off an instance names itself the same way the
5302                // prototype method it resolves to does: `String([].slice)` is
5303                // `function slice() { [native code] }`.
5304                Some(JsObj::BoundMethod { name, .. }) => {
5305                    format!("function {name}() {{ [native code] }}")
5306                }
5307                Some(JsObj::BoundFunc { .. }) => "function () { [native code] }".into(),
5308                // `Function.prototype.toString` refuses to expose a proxy's
5309                // target: V8 reports the native-code form for a proxy of ANY
5310                // callable, so `String(new Proxy(function f(){}, {}))` is
5311                // `function () { [native code] }`, not `f`'s source.
5312                Some(JsObj::Proxy { .. }) if is_callable(self, v) => {
5313                    "function () { [native code] }".into()
5314                }
5315                Some(JsObj::Class(c)) => match c.source_def.and_then(|d| self.func_source(d)) {
5316                    Some(text) => text.to_string(),
5317                    None => format!("class {} {{ }}", c.name),
5318                },
5319                Some(JsObj::Symbol { desc, .. }) => {
5320                    // `String(sym)` is allowed (unlike implicit coercion) and yields
5321                    // `Symbol(desc)`.
5322                    match desc {
5323                        Some(d) => format!("Symbol({d})"),
5324                        None => "Symbol()".into(),
5325                    }
5326                }
5327                _ => "[object Object]".into(),
5328            },
5329            _ => "[object Object]".into(),
5330        }
5331    }
5332
5333    /// The `Symbol.toStringTag` string `util.inspect` renders as a `[Tag]`
5334    /// prefix. V8 suppresses the tag when it is an OWN ENUMERABLE property,
5335    /// because it is then already listed as a `Symbol(Symbol.toStringTag): …`
5336    /// entry and showing it twice would be wrong.
5337    ///
5338    /// Only a DATA property is seen. A tag supplied by a prototype getter
5339    /// (`class C { get [Symbol.toStringTag]() { … } }`) would need a JS call,
5340    /// which cannot run under the host borrow `inspect` holds — such an object
5341    /// prints without the prefix.
5342    /// `[String: 'ab']` / `[Number: 1]` / `[Boolean: false]` — how node renders
5343    /// a primitive wrapper, distinguishing it from the bare primitive.
5344    fn inspect_wrapper(&self, v: &Value, indent: usize, st: &mut InspectCycles) -> Option<String> {
5345        let prim = match self.get(v) {
5346            Some(JsObj::Object(p)) => p.get("@@primitive").cloned()?,
5347            _ => return None,
5348        };
5349        let ctor = match &prim {
5350            Value::Bool(_) => "Boolean",
5351            Value::Int(_) | Value::Float(_) => "Number",
5352            // BigInt and Symbol primitives live on the heap; their boxes are
5353            // `[BigInt: 1n]` and `[Symbol: Symbol(s)]`.
5354            _ => match self.get(&prim) {
5355                Some(JsObj::BigInt(_)) => "BigInt",
5356                Some(JsObj::Symbol { .. }) => "Symbol",
5357                _ => "String",
5358            },
5359        };
5360        let head = format!("[{ctor}: {}]", self.inspect_lvl(&prim, indent, st));
5361        // Extra own properties still print, as `[String: 'ab'] { tag: 1 }`. The
5362        // boxed characters are NOT extras — node hides the index properties of
5363        // a String wrapper, showing only what was added to it.
5364        let width = if ctor == "String" {
5365            self.str_of(&prim).chars().count()
5366        } else {
5367            0
5368        };
5369        let extras: Vec<String> = match self.get(v) {
5370            Some(JsObj::Object(p)) => p
5371                .iter()
5372                .filter(|(k, _)| {
5373                    !k.starts_with("@@")
5374                        && !k.starts_with('#')
5375                        && self.prop_attrs(v, k).enumerable
5376                        && !k.parse::<usize>().is_ok_and(|i| i < width)
5377                })
5378                .map(|(k, val)| {
5379                    format!("{}: {}", fmt_key(k), self.inspect_lvl(val, indent + 2, st))
5380                })
5381                .collect(),
5382            _ => Vec::new(),
5383        };
5384        if extras.is_empty() {
5385            return Some(head);
5386        }
5387        Some(self.render_object(&extras, &format!("{head} "), indent, st))
5388    }
5389
5390    /// The `key: value` parts for own properties a script attached to an exotic
5391    /// whose contents are internal slots — `new Map([['k',1]])` with `m.x = 5`
5392    /// prints `Map(1) { 'k' => 1, x: 5 }`.
5393    fn side_table_parts(&self, v: &Value, indent: usize, st: &mut InspectCycles) -> Vec<String> {
5394        self.fn_prop_keys(v)
5395            .into_iter()
5396            .filter(|k| {
5397                !k.starts_with("@@")
5398                    && !k.starts_with('#')
5399                    && !is_symbol_key(k)
5400                    && self.prop_attrs(v, k).enumerable
5401            })
5402            .map(|k| {
5403                let val = self.fn_prop(v, &k).unwrap_or(Value::Undef);
5404                format!(
5405                    "{}: {}",
5406                    fmt_key(&k),
5407                    self.inspect_lvl(&val, indent + 2, st)
5408                )
5409            })
5410            .collect()
5411    }
5412
5413    fn inspect_tag(&self, v: &Value) -> Option<String> {
5414        let own = matches!(self.get(v), Some(JsObj::Object(p)) if p.contains_key("@@toStringTag"));
5415        if own && self.prop_attrs(v, "@@toStringTag").enumerable {
5416            return None;
5417        }
5418        let t = lookup_chain(self, v, "@@toStringTag")?;
5419        self.as_str(&t)
5420    }
5421
5422    /// `console.log`-style rendering of a top-level argument: bare strings print
5423    /// raw; everything else uses `inspect`.
5424    pub fn console_format(&self, v: &Value) -> String {
5425        match v {
5426            Value::Str(_) => self.str_of(v),
5427            Value::Obj(_) if matches!(self.get(v), Some(JsObj::Str(_))) => self.str_of(v),
5428            _ => self.inspect(v),
5429        }
5430    }
5431
5432    /// `util.inspect`-style rendering (nested; strings quoted).
5433    pub fn inspect(&self, v: &Value) -> String {
5434        self.inspect_lvl(v, 0, &mut InspectCycles::default())
5435    }
5436
5437    /// `util.inspect` at a given indentation level, with the cycle guard applied
5438    /// around the object cases.
5439    ///
5440    /// A value already being rendered further up the chain is a CYCLE, and Node
5441    /// marks both ends of it: the back-edge prints `[Circular *N]` and the
5442    /// object it points back at is prefixed `<ref *N>`. Without this the walk
5443    /// only stopped when the depth limit turned the back-edge into `[Object]`,
5444    /// so `const c={a:1}; c.c=c` printed the misleading
5445    /// `{ a: 1, c: { a: 1, c: { a: 1, c: [Object] } } }` instead of
5446    /// `<ref *1> { a: 1, c: [Circular *1] }`.
5447    ///
5448    /// The `*N` id is only assigned when the back-edge is reached, i.e. while
5449    /// the target's own children are being rendered — so the prefix can only be
5450    /// decided after `inspect_value` returns.
5451    /// Whether `v` renders as a LEAF — a finished string produced without
5452    /// recursing into any child.
5453    ///
5454    /// Node assigns `ctx.currentDepth = recurseTimes` in `formatRaw`, but only
5455    /// after the early returns for the shapes that answer immediately: a bare
5456    /// Date is its ISO string, a regex is its literal, an empty container is its
5457    /// braces, and a Buffer is whatever its `[util.inspect.custom]` says. None of
5458    /// those record a depth, so a group containing one is not pushed over the
5459    /// `compact` threshold by it — `util.inspect([new Date(0), null], { compact:
5460    /// 1 })` stays on one line. Charging them a level broke exactly those groups.
5461    fn renders_without_expanding(&self, v: &Value) -> bool {
5462        let plain_props = |p: &IndexMap<String, Value>| {
5463            p.keys().all(|k| k.starts_with("@@") || k.starts_with('#'))
5464        };
5465        match self.get(v) {
5466            // A regex never recurses, with or without its hidden `lastIndex`.
5467            Some(JsObj::RegExp(_)) => true,
5468            Some(JsObj::Map { entries, .. }) => entries.is_empty(),
5469            Some(JsObj::Set { entries, .. }) => entries.is_empty(),
5470            Some(JsObj::Array(items)) => items.is_empty() && self.own_symbol_entries(v).is_empty(),
5471            Some(JsObj::Object(p)) => match p.get("@@native").map(|t| self.str_of(t)).as_deref() {
5472                Some("Buffer") => inspect_custom(),
5473                // Own properties added to a Date DO get expanded after it.
5474                Some("Date") => plain_props(p),
5475                Some(_) => false,
5476                None => plain_props(p) && self.own_symbol_entries(v).is_empty(),
5477            },
5478            _ => false,
5479        }
5480    }
5481
5482    fn inspect_lvl(&self, v: &Value, indent: usize, st: &mut InspectCycles) -> String {
5483        if !matches!(v, Value::Obj(_)) {
5484            return self.inspect_value(v, indent, st);
5485        }
5486        match custom_render(v) {
5487            Some(CustomRender::Text(s)) => {
5488                return s.replace('\n', &format!("\n{}", " ".repeat(indent)))
5489            }
5490            Some(CustomRender::Value(r)) => return self.inspect_lvl(&r, indent, st),
5491            None => {}
5492        }
5493        if st.seen.iter().any(|p| self.strict_eq(p, v)) {
5494            return format!("[Circular *{}]", st.mark(self, v));
5495        }
5496        st.seen.push(v.clone());
5497        // Node ASSIGNS `ctx.currentDepth = recurseTimes` on entry to each value
5498        // it expands — not a running maximum — so after the children have been
5499        // rendered it holds the depth of the last chain below this group, which
5500        // is what `reduceToSingleString` compares. A value the depth limit
5501        // stubs out as `[Object]` is never expanded and must not count, or an
5502        // object whose deepest level was elided would break where node joins.
5503        // Only a value node actually EXPANDS advances the depth. A string,
5504        // symbol or bigint is a JS primitive that this host happens to store on
5505        // the heap, so it reaches here as `Value::Obj` where an unboxed number
5506        // returns above — and counting it as a level made any group holding one
5507        // look deeper than it was. Under `compact: 1` that is the difference
5508        // between node's `Map(2) { 'k2' => 8, 'j' => 5 }` and breaking the same
5509        // Map across four lines, because its string KEYS were being charged a
5510        // nesting level.
5511        if indent as i64 <= inspect_indent_limit()
5512            && !is_primitive(self, v)
5513            && !self.renders_without_expanding(v)
5514        {
5515            st.deepest = indent;
5516        }
5517        let body = self.inspect_value(v, indent, st);
5518        st.seen.pop();
5519        match st.id_of(self, v) {
5520            Some(id) => format!("<ref *{id}> {body}"),
5521            None => body,
5522        }
5523    }
5524
5525    /// The rendering itself, once `inspect_lvl` has established that `v` is not
5526    /// a back-edge into an object already on the stack.
5527    fn inspect_value(&self, v: &Value, indent: usize, st: &mut InspectCycles) -> String {
5528        if let Some(s) = self.inspect_wrapper(v, indent, st) {
5529            return s;
5530        }
5531        match v {
5532            Value::Undef => "undefined".into(),
5533            Value::Bool(b) => if *b { "true" } else { "false" }.into(),
5534            Value::Int(n) => inspect_number(n.to_string()),
5535            // `util.inspect` distinguishes negative zero; `String(-0)` does not.
5536            Value::Float(f) if *f == 0.0 && f.is_sign_negative() => "-0".into(),
5537            Value::Float(f) => inspect_number(fmt_number(*f)),
5538            Value::Str(s) => inspect_string(s),
5539            Value::Obj(_) => match self.get(v) {
5540                Some(JsObj::Str(s)) => inspect_string(s),
5541                Some(JsObj::Null) => "null".into(),
5542                // `util.inspect` renders a bigint with the `n` suffix, a regex bare.
5543                Some(JsObj::BigInt(b)) => format!("{}n", inspect_number(b.to_string())),
5544                // `lastIndex` is a non-enumerable own property of every regex,
5545                // so `showHidden` (and therefore `%o`) appends it:
5546                // `/x/g { [lastIndex]: 0 }`.
5547                // Own enumerable properties a script added follow the literal:
5548                // `/x/g { y: 2 }`.
5549                Some(JsObj::RegExp(r)) => {
5550                    let body = format!("/{}/{}", r.source, r.flags);
5551                    let mut inner: Vec<String> = Vec::new();
5552                    if inspect_show_hidden() {
5553                        inner.push(format!("[lastIndex]: {}", r.last_index.get()));
5554                    }
5555                    for k in self.fn_prop_keys(v) {
5556                        if k.starts_with("@@")
5557                            || k.starts_with('#')
5558                            || !self.prop_attrs(v, &k).enumerable
5559                        {
5560                            continue;
5561                        }
5562                        let val = self.fn_prop(v, &k).unwrap_or(Value::Undef);
5563                        inner.push(format!(
5564                            "{}: {}",
5565                            fmt_key(&k),
5566                            self.inspect_lvl(&val, indent + 2, st)
5567                        ));
5568                    }
5569                    if inner.is_empty() {
5570                        return body;
5571                    }
5572                    if indent as i64 > inspect_indent_limit() {
5573                        return "[RegExp]".into();
5574                    }
5575                    self.render_object(&inner, &format!("{body} "), indent, st)
5576                }
5577                // `util.inspect` on node v26.7.0 renders a proxy as
5578                // `Proxy(<target>)` — the target's own rendering, wrapped. It
5579                // deliberately does NOT run the handler's traps, so this stays a
5580                // pure `&self` read like every other inspect arm.
5581                // `showProxy` (and `%o`) shows both halves: `Proxy [ target, handler ]`.
5582                Some(JsObj::Proxy {
5583                    target, handler, ..
5584                }) if inspect_show_proxy() => {
5585                    if indent as i64 > inspect_indent_limit() {
5586                        return "Proxy [Array]".into();
5587                    }
5588                    let inner = vec![
5589                        self.inspect_lvl(target, indent + 2, st),
5590                        self.inspect_lvl(handler, indent + 2, st),
5591                    ];
5592                    self.render_array(
5593                        &inner,
5594                        &[target.clone(), handler.clone()],
5595                        indent,
5596                        ArrayLayout {
5597                            has_props: false,
5598                            has_tail: false,
5599                            base: "Proxy ",
5600                        },
5601                        st,
5602                    )
5603                }
5604                Some(JsObj::Proxy { target, .. }) => {
5605                    format!("Proxy({})", self.inspect_lvl(target, indent, st))
5606                }
5607                // `arguments` is backed by an Array but is an ordinary-shaped
5608                // exotic to util.inspect: node prints its indices as quoted
5609                // keys under the `[Arguments]` tag, `[Arguments] { '0': 1 }`.
5610                Some(JsObj::Array(items)) if crate::builtins::is_arguments_h(self, v) => {
5611                    if indent as i64 > inspect_indent_limit() {
5612                        return "[Arguments]".into();
5613                    }
5614                    let mut inner: Vec<String> = items
5615                        .iter()
5616                        .enumerate()
5617                        .map(|(i, x)| format!("'{i}': {}", self.inspect_lvl(x, indent + 2, st)))
5618                        .collect();
5619                    for k in self.fn_prop_keys(v) {
5620                        if k.starts_with("@@") || !self.prop_attrs(v, &k).enumerable {
5621                            continue;
5622                        }
5623                        let val = self.fn_prop(v, &k).unwrap_or(Value::Undef);
5624                        inner.push(format!(
5625                            "{}: {}",
5626                            fmt_key(&k),
5627                            self.inspect_lvl(&val, indent + 2, st)
5628                        ));
5629                    }
5630                    if inner.is_empty() {
5631                        return "[Arguments] {}".into();
5632                    }
5633                    self.render_object(&inner, "[Arguments] ", indent, st)
5634                }
5635                Some(JsObj::Array(items)) => {
5636                    // Own enumerable non-index string props (e.g. a `str.match(re)`
5637                    // result's `index`/`input`/`groups`, or a user-assigned
5638                    // `arr.foo`) render after the elements, as `key: value`.
5639                    let prop_keys: Vec<String> = self
5640                        .fn_prop_keys(v)
5641                        .into_iter()
5642                        .filter(|k| {
5643                            !k.starts_with("@@")
5644                                && !k.starts_with('#')
5645                                && self.prop_attrs(v, k).enumerable
5646                        })
5647                        .collect();
5648                    // An own enumerable SYMBOL-keyed property renders after the
5649                    // string keys as `Symbol(desc): value`, as it does on an
5650                    // object receiver.
5651                    // An instance of an Array SUBCLASS leads with its
5652                    // constructor and length, `Bar(2) [ 1, 2 ]`, as node's
5653                    // `getPrefix` does for any non-`Array` constructor.
5654                    let sub = match self.proto_of(v) {
5655                        Some(_) => self.ctor_name(v),
5656                        None => String::new(),
5657                    };
5658                    let base = if sub.is_empty() || sub == "Array" {
5659                        String::new()
5660                    } else {
5661                        format!("{sub}({}) ", items.len())
5662                    };
5663                    let sym_entries = self.own_symbol_entries(v);
5664                    // Under `showHidden` even an empty array has something to
5665                    // show — node prints `[ [length]: 0 ]`, not `[]`.
5666                    if items.is_empty()
5667                        && prop_keys.is_empty()
5668                        && sym_entries.is_empty()
5669                        && !inspect_show_hidden()
5670                    {
5671                        return format!("{base}[]");
5672                    }
5673                    // Node's default inspect depth is 2 (root = depth 0); deeper
5674                    // nesting collapses to `[Array]`. indent grows by 2 per level.
5675                    if indent as i64 > inspect_indent_limit() {
5676                        return "[Array]".into();
5677                    }
5678                    // `util.inspect`'s `maxArrayLength` (default 100): only the
5679                    // first 100 elements are formatted, and the rest collapse to
5680                    // a `... N more items` entry. Without the cap a 120-element
5681                    // array printed all 120 — and, because the grid column width
5682                    // is computed from what is SHOWN, every column was also one
5683                    // character wider than node's.
5684                    // A SPARSE array takes node's `formatSpecialArray` path: an
5685                    // elided run renders as `<N empty items>` rather than as the
5686                    // `undefined` it reads back as.
5687                    let (mut inner, has_tail) = if self.has_holes(v) {
5688                        self.inspect_sparse(v, items, indent, st)
5689                    } else {
5690                        let shown = items.len().min(inspect_max_array_length());
5691                        let mut inner: Vec<String> = items[..shown]
5692                            .iter()
5693                            .map(|x| self.inspect_lvl(x, indent + 2, st))
5694                            .collect();
5695                        let remaining = items.len() - shown;
5696                        if remaining > 0 {
5697                            let unit = if remaining == 1 { "item" } else { "items" };
5698                            inner.push(format!("... {remaining} more {unit}"));
5699                        }
5700                        (inner, remaining > 0)
5701                    };
5702                    // `showHidden` exposes the non-enumerable `length`, which an
5703                    // array always has. It sorts BEFORE any own property node
5704                    // shows (`[ 1, [length]: 1, x: 2 ]`) and, being an entry
5705                    // rather than an element, it also turns the column grid off —
5706                    // which is why a ten-element array under `showHidden` prints
5707                    // on one line rather than as a grid.
5708                    let show_hidden = inspect_show_hidden();
5709                    if show_hidden {
5710                        inner.push(format!("[length]: {}", items.len()));
5711                    }
5712                    let has_props = show_hidden || !prop_keys.is_empty() || !sym_entries.is_empty();
5713                    for k in &prop_keys {
5714                        let val = self.fn_prop(v, k).unwrap_or(Value::Undef);
5715                        inner.push(format!(
5716                            "{}: {}",
5717                            fmt_key(k),
5718                            self.inspect_lvl(&val, indent + 2, st)
5719                        ));
5720                    }
5721                    for (k, val) in &sym_entries {
5722                        let label = match self.symbol_of_key(k) {
5723                            Some(s) => self.inspect(&s),
5724                            None => continue,
5725                        };
5726                        inner.push(format!(
5727                            "{label}: {}",
5728                            self.inspect_lvl(val, indent + 2, st)
5729                        ));
5730                    }
5731                    self.render_array(
5732                        &inner,
5733                        items,
5734                        indent,
5735                        ArrayLayout {
5736                            has_props,
5737                            has_tail,
5738                            base: &base,
5739                        },
5740                        st,
5741                    )
5742                }
5743                // `URLSearchParams` renders its pairs, not its slots:
5744                // `URLSearchParams { 'a' => '1', 'b' => '2' }`. Keys repeat,
5745                // which is why it is a pair list rather than a Map rendering.
5746                Some(JsObj::Object(props))
5747                    if props.get("@@native").map(|t| self.str_of(t)).as_deref()
5748                        == Some("URLSearchParams") =>
5749                {
5750                    let pairs: Vec<Value> = match props.get("@@pairs").and_then(|a| self.get(a)) {
5751                        Some(JsObj::Array(items)) => items.clone(),
5752                        _ => Vec::new(),
5753                    };
5754                    if pairs.is_empty() {
5755                        return "URLSearchParams {}".into();
5756                    }
5757                    let inner: Vec<String> = pairs
5758                        .iter()
5759                        .filter_map(|kv| match self.get(kv) {
5760                            Some(JsObj::Array(p)) if p.len() == 2 => Some(format!(
5761                                "{} => {}",
5762                                self.inspect_lvl(&p[0], indent + 2, st),
5763                                self.inspect_lvl(&p[1], indent + 2, st)
5764                            )),
5765                            _ => None,
5766                        })
5767                        .collect();
5768                    self.render_object(&inner, "URLSearchParams ", indent, st)
5769                }
5770                // A typed array renders as `Uint8Array(3) [ 1, 2, 3 ]` — its
5771                // constructor and length, then the elements laid out exactly as
5772                // an array's. Without this it fell through to the generic object
5773                // arm and printed the `{ length, byteLength, byteOffset,
5774                // BYTES_PER_ELEMENT }` bookkeeping instead of the CONTENTS,
5775                // which is the whole reason anyone logs one.
5776                Some(JsObj::Object(props))
5777                    if props.get("@@native").map(|t| self.str_of(t)).as_deref()
5778                        == Some("TypedArray") =>
5779                {
5780                    let kind = props
5781                        .get("@@kind")
5782                        .map(|k| self.str_of(k))
5783                        .unwrap_or_else(|| "TypedArray".into());
5784                    // Rendered as STRINGS: a 64-bit view's elements are BigInts,
5785                    // which this shared borrow cannot allocate as values.
5786                    let elems = crate::stdlib::typedarray::elems_display(self, v);
5787                    // The grid layout sizes its columns from the VALUES; a
5788                    // 64-bit view's come back as `undefined` (no allocation is
5789                    // possible here), which only affects column padding.
5790                    let vals = crate::stdlib::typedarray::elems_with_host(self, v);
5791                    let base = self.builtin_prefix(v, &kind, Some(elems.len()));
5792                    if indent as i64 > inspect_indent_limit() {
5793                        return self.builtin_depth_stub(v, &kind);
5794                    }
5795                    let shown = elems.len().min(inspect_max_array_length());
5796                    let mut inner: Vec<String> = elems[..shown].to_vec();
5797                    let remaining = elems.len() - shown;
5798                    if remaining > 0 {
5799                        let unit = if remaining == 1 { "item" } else { "items" };
5800                        inner.push(format!("... {remaining} more {unit}"));
5801                    }
5802                    // A view's whole identity — its element width, its window
5803                    // onto the backing store, and the store itself — is
5804                    // non-enumerable, so `showHidden` is the only way to see it.
5805                    // `util.format('%o', view)` goes through here, since `%o`
5806                    // implies `showHidden`.
5807                    let show_hidden = inspect_show_hidden();
5808                    if show_hidden {
5809                        let bpe = crate::stdlib::typedarray::bytes_per_element(&kind);
5810                        let byte_offset = props
5811                            .get("byteOffset")
5812                            .map(|x| self.to_number(x))
5813                            .unwrap_or(0.0);
5814                        inner.push(format!("[BYTES_PER_ELEMENT]: {bpe}"));
5815                        inner.push(format!("[length]: {}", elems.len()));
5816                        inner.push(format!("[byteLength]: {}", elems.len() * bpe));
5817                        inner.push(format!("[byteOffset]: {}", fmt_number(byte_offset)));
5818                        // An ArrayBuffer reached AS a view's backing store is
5819                        // rendered by node WITHOUT its contents — just
5820                        // `ArrayBuffer { [byteLength]: N }` — even though the
5821                        // same buffer inspected on its own leads with
5822                        // `[Uint8Contents]`. Recursing through the normal
5823                        // ArrayBuffer branch therefore printed the bytes twice,
5824                        // once as the view's elements and again as the store's.
5825                        let buf_len = props
5826                            .get("@@buffer")
5827                            .and_then(|b| self.get(b))
5828                            .and_then(|o| match o {
5829                                JsObj::Object(bp) => bp.get("@@bytes").cloned(),
5830                                _ => None,
5831                            })
5832                            .and_then(|b| {
5833                                self.get(&b).map(|o| match o {
5834                                    JsObj::Array(items) => items.len(),
5835                                    _ => 0,
5836                                })
5837                            })
5838                            .unwrap_or(0);
5839                        inner.push(format!(
5840                            "[buffer]: ArrayBuffer {{ [byteLength]: {buf_len} }}"
5841                        ));
5842                    }
5843                    self.render_array(
5844                        &inner,
5845                        &vals,
5846                        indent,
5847                        ArrayLayout {
5848                            has_props: show_hidden,
5849                            has_tail: remaining > 0,
5850                            base: &base,
5851                        },
5852                        st,
5853                    )
5854                }
5855                // An `ArrayBuffer` renders its CONTENTS, which is the only way
5856                // to see them — it exposes no indices of its own:
5857                // `ArrayBuffer { [Uint8Contents]: <00 01>, [byteLength]: 2 }`.
5858                Some(JsObj::Object(props))
5859                    if props.get("@@native").map(|t| self.str_of(t)).as_deref()
5860                        == Some("ArrayBuffer") =>
5861                {
5862                    if indent as i64 > inspect_indent_limit() {
5863                        return self.builtin_depth_stub(v, "ArrayBuffer");
5864                    }
5865                    let bytes = crate::stdlib::buffer::window_bytes_h(self, props);
5866                    let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
5867                    let mut parts = vec![
5868                        format!("[Uint8Contents]: <{}>", hex.join(" ")),
5869                        format!("[byteLength]: {}", bytes.len()),
5870                    ];
5871                    if props.contains_key("@@maxByteLength") {
5872                        let max = props
5873                            .get("@@maxByteLength")
5874                            .map(|m| self.to_number(m))
5875                            .unwrap_or(0.0);
5876                        parts.insert(1, format!("maxByteLength: {}", fmt_number(max)));
5877                    }
5878                    self.render_object(
5879                        &parts,
5880                        &self.builtin_prefix(v, "ArrayBuffer", None),
5881                        indent,
5882                        st,
5883                    )
5884                }
5885                // A live Map/Set iterator shows what it has left to yield, as
5886                // node's `formatIterator` does: `[Map Entries] { [ 1, 'a' ] }`,
5887                // `[Set Iterator] { 1 }`, and `{  }` once it is exhausted.
5888                Some(JsObj::Object(_))
5889                    if crate::builtins::collection_iterator_view(self, v).is_some() =>
5890                {
5891                    let (brand, rest) = crate::builtins::collection_iterator_view(self, v)
5892                        .unwrap_or(("Map Iterator", Vec::new()));
5893                    if indent as i64 > inspect_indent_limit() {
5894                        let stub = if brand.starts_with("Map") {
5895                            "Map Iterator"
5896                        } else {
5897                            "Set Iterator"
5898                        };
5899                        return format!("[Object [{stub}]]");
5900                    }
5901                    let entries = brand.ends_with("Entries");
5902                    let shown = rest.len().min(100);
5903                    let mut inner: Vec<String> = rest[..shown]
5904                        .iter()
5905                        .map(|(k, val)| {
5906                            let ks = self.inspect_lvl(k, indent + 2, st);
5907                            if entries {
5908                                let vs = self.inspect_lvl(val, indent + 2, st);
5909                                format!("[ {ks}, {vs} ]")
5910                            } else {
5911                                ks
5912                            }
5913                        })
5914                        .collect();
5915                    if rest.len() > shown {
5916                        let more = rest.len() - shown;
5917                        inner.push(format!(
5918                            "... {more} more item{}",
5919                            if more == 1 { "" } else { "s" }
5920                        ));
5921                    }
5922                    if inner.is_empty() {
5923                        return format!("[{brand}] {{  }}");
5924                    }
5925                    self.render_object(&inner, &format!("[{brand}] "), indent, st)
5926                }
5927                // A `Date` renders as its ISO-8601 form. Its time value lives in
5928                // the internal `@@ms` slot, which the generic object branch below
5929                // does not show, so without this arm every Date printed as `{}` —
5930                // including through `console.log(d)`, inside arrays, objects and
5931                // Maps, and in an `assert` diff.
5932                Some(JsObj::Object(props))
5933                    if props.get("@@native").map(|t| self.str_of(t)).as_deref() == Some("Date") =>
5934                {
5935                    let base = crate::stdlib::date::inspect_with_host(self, v);
5936                    // Own properties added to a Date follow the date itself, the
5937                    // way node appends them: `2020-01-01T00:00:00.000Z { x: 1 }`.
5938                    let extra = self.side_table_parts(v, indent, st);
5939                    let mut inner: Vec<String> = props
5940                        .iter()
5941                        .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
5942                        .map(|(k, val)| format!("{k}: {}", self.inspect_lvl(val, indent + 2, st)))
5943                        .collect();
5944                    inner.extend(extra);
5945                    if inner.is_empty() {
5946                        return base;
5947                    }
5948                    self.render_object(&inner, &format!("{base} "), indent, st)
5949                }
5950                // A `Buffer` renders as `<Buffer 01 02 03>` — hex bytes, capped
5951                // at 50 with a `... N more byte(s)` tail, exactly as
5952                // `util.inspect` does. Without this a `console.log(buf)` (the
5953                // single most common thing anyone does with a Buffer) printed
5954                // the internal `{ length, byteLength, … }` bookkeeping.
5955                Some(JsObj::Object(props))
5956                    if props.get("@@native").map(|t| self.str_of(t)).as_deref()
5957                        == Some("Buffer") =>
5958                {
5959                    let bytes = crate::stdlib::buffer::window_bytes_h(self, props);
5960                    // `<Buffer …>` is Buffer's `[util.inspect.custom]` hook, not
5961                    // the shape of the object. Under `customInspect: false` node
5962                    // does not call that hook and falls back to the generic
5963                    // byte-view rendering — which is what an `assert` diff shows,
5964                    // since assert inspects with the hook disabled so that a
5965                    // failure names the differing BYTE rather than two opaque hex
5966                    // blobs. The constructor is `Buffer` while the brand is still
5967                    // `Uint8Array`, so node prints both.
5968                    if !inspect_custom() {
5969                        let base = format!("Buffer({}) [Uint8Array] ", bytes.len());
5970                        if indent as i64 > inspect_indent_limit() {
5971                            return "[Buffer [Uint8Array]]".into();
5972                        }
5973                        let shown = bytes.len().min(inspect_max_array_length());
5974                        let mut inner: Vec<String> =
5975                            bytes[..shown].iter().map(|b| b.to_string()).collect();
5976                        let vals: Vec<Value> = bytes[..shown]
5977                            .iter()
5978                            .map(|b| Value::Float(*b as f64))
5979                            .collect();
5980                        let remaining = bytes.len() - shown;
5981                        if remaining > 0 {
5982                            let unit = if remaining == 1 { "item" } else { "items" };
5983                            inner.push(format!("... {remaining} more {unit}"));
5984                        }
5985                        return self.render_array(
5986                            &inner,
5987                            &vals,
5988                            indent,
5989                            ArrayLayout {
5990                                has_props: false,
5991                                has_tail: remaining > 0,
5992                                base: &base,
5993                            },
5994                            st,
5995                        );
5996                    }
5997                    const MAX: usize = 50;
5998                    let shown: Vec<String> =
5999                        bytes.iter().take(MAX).map(|b| format!("{b:02x}")).collect();
6000                    let mut out = format!("<Buffer {}", shown.join(" "));
6001                    if bytes.len() > MAX {
6002                        let more = bytes.len() - MAX;
6003                        let unit = if more == 1 { "byte" } else { "bytes" };
6004                        out.push_str(&format!(" ... {more} more {unit}"));
6005                    }
6006                    out.push('>');
6007                    out
6008                }
6009                // An Error inspects as its `.stack` — never as an object literal
6010                // exposing the internal `message`/`stack` slots. Any own property
6011                // a script added beyond those follows in braces, as V8 renders
6012                // it: `Error: x\n    at … { code: 'C' }`.
6013                Some(JsObj::Object(_)) if self.error_to_string(v).is_some() => {
6014                    let mut stack = lookup_chain(self, v, "stack")
6015                        .map(|s| self.str_of(&s))
6016                        // node's `getStackString` falls back on a FALSY stack, so
6017                        // `err.stack = ""` still prints `[Error: m]`.
6018                        .filter(|s| !s.is_empty())
6019                        .unwrap_or_else(|| self.error_to_string(v).unwrap_or_default());
6020                    // A `DOMException` prints its CLASS and then its name —
6021                    // `DOMException [AbortError]: m` — where a plain error
6022                    // prints only its stack head.
6023                    if let Some(JsObj::Object(p)) = self.get(v) {
6024                        if let Some(n) = p.get("@@domName") {
6025                            let name = self.str_of(n);
6026                            stack = format!(
6027                                "DOMException [{name}]{}",
6028                                stack.strip_prefix(&name).unwrap_or(&stack)
6029                            );
6030                        }
6031                    }
6032                    self.format_error_tail(v, stack, indent, st)
6033                }
6034                Some(JsObj::Object(props)) => {
6035                    // Instances print with their constructor name as a prefix
6036                    // (`C { x: 1 }`); plain objects have none; a null-prototype
6037                    // object (e.g. an `Object.groupBy` result) is tagged
6038                    // `[Object: null prototype]`.
6039                    let ctor = match self.ctor_name(v) {
6040                        n if n.is_empty() => "Object".to_string(),
6041                        n => n,
6042                    };
6043                    // A native class that node gives a CUSTOM inspect to prints
6044                    // the accessor values it curates rather than the instance's
6045                    // own properties, which are hidden slots and print as
6046                    // nothing. `TextEncoder`'s omits the class name entirely.
6047                    let native = props.get("@@native").map(|t| self.str_of(t));
6048                    let (inspect_members, show_class) = native
6049                        .as_deref()
6050                        .map(crate::stdlib::instance_inspect_members)
6051                        .unwrap_or((&[], true));
6052                    // A class with a custom inspect prints ONLY what that
6053                    // inspect curates: a subclass's own properties and the
6054                    // inherited `Symbol.toStringTag` suffix are both left out,
6055                    // so `class S extends AbortController { z = 1 }` prints as
6056                    // `S { signal: … }`, not `S [AbortController] { z: 1, … }`.
6057                    let curated = native
6058                        .as_deref()
6059                        .map(crate::stdlib::instance_inspect_is_custom)
6060                        .unwrap_or(false);
6061                    let plain_prefix = if ctor == "Object" || !show_class {
6062                        String::new()
6063                    } else {
6064                        format!("{ctor} ")
6065                    };
6066                    let prefix = if props.contains_key(ESM_NAMESPACE_SNAPSHOT) {
6067                        "[Module: null prototype] ".to_string()
6068                    } else if self.inspects_null_proto(v) {
6069                        "[Object: null prototype] ".to_string()
6070                    } else {
6071                        // An inherited `Symbol.toStringTag` shows as `Ctor [Tag] `,
6072                        // native classes included: a `SecretKeyObject` prints as
6073                        // `SecretKeyObject [KeyObject] {}`.
6074                        match self.inspect_tag(v) {
6075                            Some(t) if t != ctor && !curated => format!("{ctor} [{t}] "),
6076                            _ => plain_prefix.clone(),
6077                        }
6078                    };
6079                    // Skip node-js's internal slots (`@@native`, `@@bytes`, …) and
6080                    // private class fields; a real symbol-keyed own property is a
6081                    // visible one and renders as `Symbol(desc): value`.
6082                    // An own ACCESSOR has no value to print: node shows the
6083                    // label `[Getter]` / `[Setter]` / `[Getter/Setter]` in its
6084                    // place. It is found through the `@@ord:` marker the
6085                    // property map holds for it, which is also what puts it in
6086                    // declaration order among the data properties. Without this
6087                    // an accessor rendered as nothing at all — `{ get z(){} }`
6088                    // printed `{}`.
6089                    // A DataView leads with its three view fields, bracketed as
6090                    // node's `formatRaw` prints them (`keys.unshift('byteLength',
6091                    // 'byteOffset', 'buffer')`), ahead of any own property.
6092                    let is_view = native.as_deref() == Some("DataView");
6093                    let view_fields: &[&str] = if is_view {
6094                        &["byteLength", "byteOffset", "buffer"]
6095                    } else {
6096                        &[]
6097                    };
6098                    if is_view && indent as i64 > inspect_indent_limit() {
6099                        return self.builtin_depth_stub(v, "DataView");
6100                    }
6101                    let prefix = if is_view {
6102                        self.builtin_prefix(v, "DataView", None)
6103                    } else {
6104                        prefix
6105                    };
6106                    let mut shown: Vec<(String, Result<&Value, AccessorShown>)> = view_fields
6107                        .iter()
6108                        .filter_map(|k| props.get(*k).map(|val| (format!("[{k}]"), Ok(val))))
6109                        .collect();
6110                    shown.extend(props.iter().filter(|_| !curated).filter_map(|(k, val)| {
6111                        match k.strip_prefix(ORD_MARKER) {
6112                            // A SYMBOL-keyed accessor is listed with the other
6113                            // symbol keys below, after every string key.
6114                            Some(real) if is_symbol_key(real) => None,
6115                            Some(real) => {
6116                                let attrs = self.prop_attrs(v, real);
6117                                let label = match self.own_accessor(v, real)? {
6118                                    (Some(_), Some(_)) => "Getter/Setter",
6119                                    (Some(_), None) => "Getter",
6120                                    (None, Some(_)) => "Setter",
6121                                    (None, None) => return None,
6122                                };
6123                                // Under `getters`, the value the pre-pass read.
6124                                let read = getter_render(v, real);
6125                                attrs
6126                                    .enumerable
6127                                    .then(|| (fmt_key(real), Err((label, read))))
6128                            }
6129                            // Only an ENUMERABLE own property is shown, as node
6130                            // does: a native instance keeps bookkeeping (a
6131                            // `URLSearchParams`'s `size`) as a hidden own slot,
6132                            // and printing it would report a spec getter as data.
6133                            None if !k.starts_with("@@")
6134                                && !k.starts_with('#')
6135                                && self.prop_attrs(v, k).enumerable =>
6136                            {
6137                                Some((fmt_key(k), Ok(val)))
6138                            }
6139                            None => None,
6140                        }
6141                    }));
6142                    // The curated accessor values, read from the hidden slots the
6143                    // getters read, in the order node prints them.
6144                    for name in inspect_members {
6145                        if let Some(val) = props.get(&format!("@@{name}")) {
6146                            shown.push(((*name).to_string(), Ok(val)));
6147                        }
6148                    }
6149                    // Symbol keys, data and accessor alike, in insertion order.
6150                    // An accessor's ordering marker resolves back to its symbol;
6151                    // without this arm `{ get [Symbol.iterator]() {} }` printed
6152                    // its getter under the internal `'@@iterator'` spelling.
6153                    shown.extend(props.iter().filter_map(|(k, val)| {
6154                        if let Some(real) = k.strip_prefix(ORD_MARKER) {
6155                            let sym = self.symbol_of_key(real)?;
6156                            if !self.prop_attrs(v, real).enumerable {
6157                                return None;
6158                            }
6159                            let label = match self.own_accessor(v, real)? {
6160                                (Some(_), Some(_)) => "Getter/Setter",
6161                                (Some(_), None) => "Getter",
6162                                (None, Some(_)) => "Setter",
6163                                (None, None) => return None,
6164                            };
6165                            return Some((
6166                                self.inspect(&sym),
6167                                Err((label, getter_render(v, real))),
6168                            ));
6169                        }
6170                        let sym = self.symbol_of_key(k)?;
6171                        self.prop_attrs(v, k)
6172                            .enumerable
6173                            .then(|| (self.inspect(&sym), Ok(val)))
6174                    }));
6175                    if shown.is_empty() {
6176                        return format!("{prefix}{{}}");
6177                    }
6178                    // Depth limit (Node default 2): deeper objects collapse to
6179                    // `[Object]` (or `[ClassName]` for a named instance).
6180                    if indent as i64 > inspect_indent_limit() {
6181                        return if self.inspects_null_proto(v) {
6182                            // Already bracketed (`[Object: null prototype]`).
6183                            prefix.trim_end().to_string()
6184                        } else if plain_prefix.is_empty() {
6185                            "[Object]".into()
6186                        } else {
6187                            format!("[{}]", plain_prefix.trim_end())
6188                        };
6189                    }
6190                    let inner: Vec<String> = shown
6191                        .iter()
6192                        .map(|(k, val)| match val {
6193                            Ok(val) => format!("{k}: {}", self.inspect_lvl(val, indent + 2, st)),
6194                            Err((label, None)) => format!("{k}: [{label}]"),
6195                            // node's `formatProperty` under `getters`: an object
6196                            // follows the bracket, anything else goes inside it.
6197                            Err((label, Some(Ok(got)))) => {
6198                                if matches!(got, Value::Obj(_))
6199                                    && !is_primitive(self, got)
6200                                    && !self.is_null(got)
6201                                {
6202                                    format!(
6203                                        "{k}: [{label}] {}",
6204                                        self.inspect_lvl(got, indent + 2, st)
6205                                    )
6206                                } else {
6207                                    format!(
6208                                        "{k}: [{label}: {}]",
6209                                        self.inspect_lvl(got, indent + 2, st)
6210                                    )
6211                                }
6212                            }
6213                            Err((label, Some(Err(e)))) => {
6214                                format!("{k}: [{label}: <Inspection threw ({})>]", self.str_of(e))
6215                            }
6216                        })
6217                        .collect();
6218                    self.render_object(&inner, &prefix, indent, st)
6219                }
6220                Some(JsObj::Symbol { desc, .. }) => match desc {
6221                    Some(d) => format!("Symbol({d})"),
6222                    None => "Symbol()".into(),
6223                },
6224                Some(JsObj::Class(c)) => {
6225                    // Named like a function (`callable_name`), so a class
6226                    // expression picks up its inferred binding name, and one
6227                    // with no name at all prints `(anonymous)`. node's
6228                    // `getClassBase` appends `extends <name>` only when the
6229                    // parent HAS a name: `class extends null {}` prints
6230                    // without it.
6231                    let mut name = self.callable_name(v);
6232                    if name.is_empty() {
6233                        name = "(anonymous)".into();
6234                    }
6235                    let pname = c
6236                        .parent
6237                        .as_ref()
6238                        .map(|p| self.callable_name(p))
6239                        .unwrap_or_default();
6240                    let base = if pname.is_empty() {
6241                        format!("[class {name}]")
6242                    } else {
6243                        format!("[class {name} extends {pname}]")
6244                    };
6245                    self.with_callable_props(v, base, indent, st)
6246                }
6247                // A Map/Set renders its members at the NEXT nesting level, and
6248                // collapses to `[Map]`/`[Set]` past the depth limit exactly as an
6249                // array collapses to `[Array]`. Both used to recurse through
6250                // `inspect`, which restarts at indent 0, so the depth gate never
6251                // fired: nesting printed one level too deep at every depth
6252                // (measured on node v26.7.0, four nested Maps print
6253                // `Map(1) { 'a' => Map(1) { 'b' => Map(1) { 'c' => [Map] } } }`),
6254                // and a SELF-referential Map or Set recursed forever and aborted
6255                // the process — `const m=new Map(); m.set('m',m); console.log(m)`
6256                // died with `fatal runtime error: stack overflow`, which no
6257                // `try`/`catch` can see. An empty one still prints in full at any
6258                // depth, as `[]`/`{}` do.
6259                // A WEAK collection never shows its contents: node prints
6260                // `WeakMap { <items unknown> }` whether it holds anything or
6261                // not, because the entries are not enumerable by design.
6262                Some(JsObj::Map { weak: true, .. }) => "WeakMap { <items unknown> }".into(),
6263                Some(JsObj::Set { weak: true, .. }) => "WeakSet { <items unknown> }".into(),
6264                Some(JsObj::Map { entries, .. }) => {
6265                    let extra = self.side_table_parts(v, indent, st);
6266                    let prefix = self.builtin_prefix(v, "Map", Some(entries.len()));
6267                    if entries.is_empty() && extra.is_empty() {
6268                        return format!("{prefix}{{}}");
6269                    }
6270                    if indent as i64 > inspect_indent_limit() {
6271                        return self.builtin_depth_stub(v, "Map");
6272                    }
6273                    let mut inner: Vec<String> = entries
6274                        .values()
6275                        .map(|(k, val)| {
6276                            // Sequenced, not nested in one `format!`: both arms
6277                            // need the same `&mut` cycle state.
6278                            let ks = self.inspect_lvl(k, indent + 2, st);
6279                            let vs = self.inspect_lvl(val, indent + 2, st);
6280                            format!("{ks} => {vs}")
6281                        })
6282                        .collect();
6283                    inner.extend(extra);
6284                    // Laid out by the SAME routine as a plain object, not joined
6285                    // onto one line unconditionally. `Map`/`Set` were the only
6286                    // containers that never consulted `breakLength` or `compact`,
6287                    // so every collection wide enough to wrap printed as one long
6288                    // line: node breaks a seven-member Set of ten-character
6289                    // strings across seven lines, and `util.inspect(m, {compact:
6290                    // false})` — which assert's own diff renderer depends on —
6291                    // could not break a Map at all. Node builds these through
6292                    // `reduceToSingleString` with `braces[0]` of `Map(n) {`, which
6293                    // is this `prefix` (the trailing space is the brace gap).
6294                    self.render_object(&inner, &prefix, indent, st)
6295                }
6296                Some(JsObj::Set { entries, .. }) => {
6297                    let extra = self.side_table_parts(v, indent, st);
6298                    let prefix = self.builtin_prefix(v, "Set", Some(entries.len()));
6299                    if entries.is_empty() && extra.is_empty() {
6300                        return format!("{prefix}{{}}");
6301                    }
6302                    if indent as i64 > inspect_indent_limit() {
6303                        return self.builtin_depth_stub(v, "Set");
6304                    }
6305                    let mut inner: Vec<String> = entries
6306                        .values()
6307                        .map(|v| self.inspect_lvl(v, indent + 2, st))
6308                        .collect();
6309                    inner.extend(extra);
6310                    // Same layout routine as a Map (see above). Note node does
6311                    // NOT column-group a wide Set the way it grids an array:
6312                    // `groupArrayElements` is reached only from the list
6313                    // formatter, so a 30-member Set is thirty lines.
6314                    self.render_object(&inner, &prefix, indent, st)
6315                }
6316                // The brand is `Symbol.toStringTag`, which an async generator
6317                // inherits as `AsyncGenerator`.
6318                Some(JsObj::Generator { .. }) if self.is_async_gen_val(v) => {
6319                    "Object [AsyncGenerator] {}".into()
6320                }
6321                Some(JsObj::Generator { .. }) => "Object [Generator] {}".into(),
6322                Some(JsObj::Iter { array: Some(_), .. }) => "Object [Array Iterator] {}".into(),
6323                // node lists what a URLSearchParams iterator has left; every other
6324                // built-in iterator prints as an empty object under its brand.
6325                Some(JsObj::Iter {
6326                    items,
6327                    idx,
6328                    brand: Some(b),
6329                    ..
6330                }) => {
6331                    if *b == "URLSearchParams Iterator" {
6332                        let rest: Vec<String> = items[(*idx).min(items.len())..]
6333                            .iter()
6334                            .map(|v| self.inspect_lvl(v, indent + 2, st))
6335                            .collect();
6336                        format!("{b} {{ {} }}", rest.join(", "))
6337                    } else {
6338                        format!("Object [{b}] {{}}")
6339                    }
6340                }
6341                Some(JsObj::Promise { id }) => match self.promises.get(*id as usize) {
6342                    Some(c) => {
6343                        // `P2 [Promise] { 3 }` for an instance of a subclass.
6344                        let prefix = self.builtin_prefix(v, "Promise", None);
6345                        match c.state {
6346                            PromiseState::Pending => format!("{prefix}{{ <pending> }}"),
6347                            PromiseState::Fulfilled => {
6348                                format!("{prefix}{{ {} }}", self.inspect_lvl(&c.value, 0, st))
6349                            }
6350                            PromiseState::Rejected => format!(
6351                                "{prefix}{{ <rejected> {} }}",
6352                                self.inspect_lvl(&c.value, 0, st)
6353                            ),
6354                        }
6355                    }
6356                    None => "Promise { <pending> }".into(),
6357                },
6358                Some(JsObj::Func(f)) => {
6359                    // `callable_name`, not the FuncDef name: an anonymous
6360                    // function expression gets its name by inference from the
6361                    // binding it initialises (`const f = function(){}`), and
6362                    // that lands as an own `name` property.
6363                    let name = self.callable_name(v);
6364                    // util.inspect labels a function by its kind, the same
6365                    // string V8 gives it as `Symbol.toStringTag`:
6366                    // `[AsyncFunction: af]`, `[GeneratorFunction: g]`.
6367                    let kind = match self.funcs.get(f.def_id) {
6368                        Some(d) if d.is_generator && d.is_async => "AsyncGeneratorFunction",
6369                        Some(d) if d.is_generator => "GeneratorFunction",
6370                        Some(d) if d.is_async => "AsyncFunction",
6371                        _ => "Function",
6372                    };
6373                    let base = if name.is_empty() {
6374                        format!("[{kind} (anonymous)]")
6375                    } else {
6376                        format!("[{kind}: {name}]")
6377                    };
6378                    self.with_callable_props(v, base, indent, st)
6379                }
6380                Some(JsObj::Builtin(n)) => {
6381                    // A namespace object is not a function and must not be
6382                    // printed as one. The three ECMAScript namespaces carry a
6383                    // `Symbol.toStringTag` and inspect as `Object [Math] {}`;
6384                    // their members are all non-enumerable, so the braces really
6385                    // are empty. A `require()`d module namespace has no tag and
6386                    // node prints its members, which cannot be rendered here —
6387                    // formatting a member means allocating its value, and this
6388                    // runs under the host borrow.
6389                    if !builtin_is_callable(n) {
6390                        match crate::builtins::well_known_tag(self, v) {
6391                            Some(tag) => format!("Object [{tag}] {{}}"),
6392                            // `Set.prototype` inspects under the CONSTRUCTOR's
6393                            // name, not the key: node prints `Object [Set] {}`.
6394                            None => {
6395                                format!("Object [{}] {{}}", n.trim_end_matches(".prototype"))
6396                            }
6397                        }
6398                    } else {
6399                        // A measured core function can be anonymous (`os.freemem`
6400                        // is an arrow assigned by name-less property).
6401                        let base = match crate::builtins::builtin_name(n) {
6402                            "" => "[Function (anonymous)]".to_string(),
6403                            name => format!("[Function: {name}]"),
6404                        };
6405                        self.with_core_symbol_props(n, base, indent, st)
6406                    }
6407                }
6408                // A bound method is not anonymous: it is the prototype method it
6409                // resolves to, so `console.log(new Uint8Array(1).set)` reports
6410                // `[Function: set]`.
6411                Some(JsObj::BoundMethod { name, .. }) => format!("[Function: {name}]"),
6412                Some(JsObj::BoundFunc { target, .. }) => {
6413                    let n = self.callable_name(target);
6414                    if n.is_empty() {
6415                        "[Function: bound ]".into()
6416                    } else {
6417                        format!("[Function: bound {n}]")
6418                    }
6419                }
6420                _ => "undefined".into(),
6421            },
6422            _ => "undefined".into(),
6423        }
6424    }
6425
6426    /// Append a core function's ENUMERABLE measured symbol-keyed properties
6427    /// (`CORE_SYMBOL_PROPS`) to its `[Function: f]` base, as `util.inspect`
6428    /// shows them: `setTimeout`'s `util.promisify.custom` getter as
6429    /// `[Getter]`, `os.freemem`'s `Symbol.toPrimitive` as the anonymous
6430    /// function it is. Rendered from the table alone: this runs under the host
6431    /// borrow, which neither a symbol nor a value can be allocated through.
6432    fn with_core_symbol_props(
6433        &self,
6434        ns: &str,
6435        base: String,
6436        indent: usize,
6437        st: &mut InspectCycles,
6438    ) -> String {
6439        let inner: Vec<String> = crate::builtins::core_symbol_props(ns)
6440            .iter()
6441            .filter(|row| row.3)
6442            .filter_map(|&(_, spelling, accessor, ..)| {
6443                let key = match spelling.strip_prefix("for:") {
6444                    Some(k) => format!("Symbol({k})"),
6445                    None => format!("Symbol(Symbol.{})", spelling.trim_start_matches("@@")),
6446                };
6447                let value = if accessor {
6448                    "[Getter]".to_string()
6449                } else {
6450                    let fn_key = crate::builtins::os_to_primitive_key(ns, spelling)?;
6451                    match crate::builtins::builtin_name(&fn_key) {
6452                        "" => "[Function (anonymous)]".to_string(),
6453                        name => format!("[Function: {name}]"),
6454                    }
6455                };
6456                Some(format!("{key}: {value}"))
6457            })
6458            .collect();
6459        if inner.is_empty() {
6460            return base;
6461        }
6462        self.render_object(&inner, &format!("{base} "), indent, st)
6463    }
6464
6465    /// Append a callable's own enumerable properties to its `[Function: f]` /
6466    /// `[class C]` base, the way `util.inspect` does: `[Function: f] { a: 1 }`.
6467    /// A callable with none renders as the bare base.
6468    fn with_callable_props(
6469        &self,
6470        v: &Value,
6471        base: String,
6472        indent: usize,
6473        st: &mut InspectCycles,
6474    ) -> String {
6475        let mut inner: Vec<String> = self
6476            .own_enum_key_names(v)
6477            .into_iter()
6478            .map(|k| {
6479                let val = self.fn_prop(v, &k).unwrap_or(Value::Undef);
6480                format!(
6481                    "{}: {}",
6482                    fmt_key(&k),
6483                    self.inspect_lvl(&val, indent + 2, st)
6484                )
6485            })
6486            .collect();
6487        for (k, val) in self.own_symbol_entries(v) {
6488            if let Some(sym) = self.symbol_of_key(&k) {
6489                inner.push(format!(
6490                    "{}: {}",
6491                    self.inspect(&sym),
6492                    self.inspect_lvl(&val, indent + 2, st)
6493                ));
6494            }
6495        }
6496        if inner.is_empty() {
6497            return base;
6498        }
6499        self.render_object(&inner, &format!("{base} "), indent, st)
6500    }
6501
6502    /// Render a non-empty array's already-formatted element strings, applying
6503    /// Node's `util.inspect` layout: a single line when it fits, else a multi-line
6504    /// grid via `groupArrayElements` (for >6 entries), else one element per line.
6505    /// `values` is the raw element list (drives numeric right-alignment); `indent`
6506    /// is the array's own indentation level.
6507    fn render_array(
6508        &self,
6509        output: &[String],
6510        values: &[Value],
6511        indent: usize,
6512        opts: ArrayLayout<'_>,
6513        st: &InspectCycles,
6514    ) -> String {
6515        let ArrayLayout {
6516            has_props,
6517            has_tail,
6518            base,
6519        } = opts;
6520        // Group array elements together if the array has more than six entries.
6521        // Arrays carrying extra own props (`index`/`input`/… on a match result)
6522        // are never grid-grouped — Node lays those out plainly.
6523        // `compact: false` (held as 0) also turns the GRID off, not just the
6524        // single-line join. Node reaches `groupArrayElements` only under
6525        // `ctx.compact >= 1`, so `util.inspect(arr, { compact: false })` is one
6526        // element per line however many there are; without this gate a 30-element
6527        // array still came back column-aligned in three rows, which is the form
6528        // assert's diff renderer splits on — every array diff would have been
6529        // computed over grid rows instead of elements.
6530        let entries = output.len();
6531        let (lines, grouped) = if entries > 6 && !has_props && inspect_compact() >= 1 {
6532            group_array_elements(self, output, values, indent, has_tail)
6533        } else {
6534            (output.to_vec(), false)
6535        };
6536        // A typed array prints its constructor and length ahead of the brackets
6537        // (`Uint8Array(3) [ 1, 2, 3 ]`); node counts that as `base` in the
6538        // break-length seed, so a long tag wraps the list one entry sooner.
6539        if output.is_empty() {
6540            return format!("{base}[]");
6541        }
6542        // If no grouping happened, try to line everything up on a single line.
6543        if !grouped {
6544            // start = output.length + indentationLvl + braces[0].len(1) + base + 10
6545            let start = output.len() + indent + 1 + base.chars().count() + 10;
6546            if self.may_compact(indent, st) && is_below_break_length(output, start) {
6547                return format!("{base}[ {} ]", output.join(", "));
6548            }
6549        }
6550        // Otherwise: one (grouped or single) entry per line, indented by indent+2.
6551        let pad = " ".repeat(indent);
6552        let sep = format!(",\n{pad}  ");
6553        format!("{base}[\n{pad}  {}\n{pad}]", lines.join(&sep))
6554    }
6555
6556    /// Render a non-empty object's already-formatted `key: value` strings with
6557    /// Node's `util.inspect` layout: a single line when it fits `breakLength`,
6558    /// else one property per line indented by `indent + 2`. `prefix` is the
6559    /// constructor/`[Object: null prototype]` tag (with trailing space) or empty.
6560    /// Mirrors `render_array`'s break decision, including the `compact` depth
6561    /// gate.
6562    /// Whether a group at `indent` may be joined onto one line.
6563    ///
6564    /// Node's `reduceToSingleString`: only while the subtree below this group is
6565    /// SHALLOWER than `compact` (default 3). `compact: false` is held as 0, so
6566    /// nothing qualifies and every group breaks.
6567    fn may_compact(&self, indent: usize, st: &InspectCycles) -> bool {
6568        let compact = inspect_compact();
6569        if compact < 1 {
6570            return false;
6571        }
6572        // Levels, not columns: the indent advances by two per level.
6573        let depth_below = (st.deepest.saturating_sub(indent)) / 2;
6574        (depth_below as i64) < compact
6575    }
6576
6577    /// The rest of node's `formatError` once the stack head is settled: which
6578    /// own keys print, the `[...]` brackets for a stack without frames, the
6579    /// re-indentation of a nested stack, and `reduceToSingleString` with the
6580    /// stack as `base` (a multi-line stack forces the multi-line brace form).
6581    fn format_error_tail(
6582        &self,
6583        v: &Value,
6584        mut stack: String,
6585        indent: usize,
6586        st: &mut InspectCycles,
6587    ) -> String {
6588        let own = |k: &str| match self.get(v) {
6589            Some(JsObj::Object(p)) => p.get(k).cloned(),
6590            _ => None,
6591        };
6592        let string_in_stack = |k: &str, stack: &str| match lookup_chain(self, v, k) {
6593            Some(s) if self.type_of(&s) == "string" => stack.contains(&self.str_of(&s)),
6594            _ => true,
6595        };
6596        // Enumerable own keys, minus `stack` and a `message`/`name` the stack
6597        // already shows; then `cause` and an array `errors`, which print as
6598        // hidden keys even though they are non-enumerable.
6599        let mut keys: Vec<(String, bool)> = self
6600            .own_enum_key_names(v)
6601            .into_iter()
6602            .filter(|k| match k.as_str() {
6603                "stack" => false,
6604                "message" | "name" => !string_in_stack(k, &stack),
6605                _ => true,
6606            })
6607            .map(|k| (k, false))
6608            .collect();
6609        if own("cause").is_some() && !keys.iter().any(|(k, _)| k == "cause") {
6610            keys.push(("cause".into(), true));
6611        }
6612        if own("errors").is_some_and(|e| matches!(self.get(&e), Some(JsObj::Array(_))))
6613            && !keys.iter().any(|(k, _)| k == "errors")
6614        {
6615            keys.push(("errors".into(), true));
6616        }
6617        // Wrap the stack in brackets when no frame follows the message.
6618        let message = match lookup_chain(self, v, "message") {
6619            Some(m) if self.type_of(&m) == "string" => self.str_of(&m),
6620            _ => String::new(),
6621        };
6622        let pos = match stack.find(message.as_str()) {
6623            Some(i) if !message.is_empty() && i > 0 => i + message.len(),
6624            _ => 0,
6625        };
6626        if !stack[pos..].contains("\n    at") {
6627            stack = format!("[{stack}]");
6628        }
6629        if indent != 0 {
6630            stack = stack.replace('\n', &format!("\n{}", " ".repeat(indent)));
6631        }
6632        if keys.is_empty() {
6633            return stack;
6634        }
6635        let output: Vec<String> = keys
6636            .iter()
6637            .map(|(k, hidden)| {
6638                let val = self
6639                    .fn_prop(v, k)
6640                    .or_else(|| own(k))
6641                    .unwrap_or(Value::Undef);
6642                let key = if *hidden {
6643                    format!("[{k}]")
6644                } else {
6645                    fmt_key(k)
6646                };
6647                format!("{key}: {}", self.inspect_lvl(&val, indent + 2, st))
6648            })
6649            .collect();
6650        let start = output.len() + indent + 1 + stack.chars().count() + 10;
6651        if self.may_compact(indent, st)
6652            && !stack.contains('\n')
6653            && is_below_break_length(&output, start)
6654        {
6655            return format!("{stack} {{ {} }}", output.join(", "));
6656        }
6657        let pad = " ".repeat(indent);
6658        let sep = format!(",\n{pad}  ");
6659        format!("{stack} {{\n{pad}  {}\n{pad}}}", output.join(&sep))
6660    }
6661
6662    fn render_object(
6663        &self,
6664        output: &[String],
6665        prefix: &str,
6666        indent: usize,
6667        st: &InspectCycles,
6668    ) -> String {
6669        // start = output.length + indentationLvl + braces[0].len + base(0) + 10.
6670        // For a tagged object Node folds the tag into `braces[0]` (e.g.
6671        // `"Point {"`, `"[Object: null prototype] {"`), so its length is the
6672        // prefix (which carries the trailing space) plus the `{`.
6673        // `sorted: true` orders the RENDERED entries, not the keys. Node sorts
6674        // the finished `key: value` strings (`output.sort()` in `formatRaw` for
6675        // the object shape), which is observably different from sorting keys
6676        // whenever a key needs quoting — `'b-b': 1` sorts under `'`, not `b`.
6677        // `assert`'s diff renderer depends on this: without it two objects
6678        // carrying the same properties in a different insertion order diffed as
6679        // a wholesale rewrite of every line instead of as equal.
6680        let sorted_output;
6681        let output = if inspect_sorted() {
6682            let mut v = output.to_vec();
6683            v.sort();
6684            sorted_output = v;
6685            &sorted_output[..]
6686        } else {
6687            output
6688        };
6689        let braces0 = prefix.chars().count() + 1;
6690        let start = output.len() + indent + braces0 + 10;
6691        if self.may_compact(indent, st) && is_below_break_length(output, start) {
6692            return format!("{prefix}{{ {} }}", output.join(", "));
6693        }
6694        let pad = " ".repeat(indent);
6695        let sep = format!(",\n{pad}  ");
6696        format!("{prefix}{{\n{pad}  {}\n{pad}}}", output.join(&sep))
6697    }
6698
6699    /// The `.name` of any callable (function/class/builtin/bound).
6700    pub fn callable_name(&self, v: &Value) -> String {
6701        // A user-set `.name` own property wins.
6702        if let Some(n) = self.fn_prop(v, "name") {
6703            return self.str_of(&n);
6704        }
6705        match self.get(v) {
6706            Some(JsObj::Func(f)) => self
6707                .funcs
6708                .get(f.def_id)
6709                .map(|d| d.name.clone())
6710                .unwrap_or_default(),
6711            Some(JsObj::Class(c)) => c.name.clone(),
6712            // Not the whole key: a builtin's `.name` is its last segment, and a
6713            // prototype thunk's key is `@proto:<Ctor>:<method>` — which has no
6714            // `.` at all, so this reported the internal spelling verbatim and
6715            // `console.log(Uint8Array.prototype.set)` printed
6716            // `[Function: @proto:TypedArray:set]`.
6717            Some(JsObj::Builtin(n)) => crate::builtins::builtin_name(n).to_string(),
6718            Some(JsObj::BoundFunc { target, .. }) => {
6719                format!("bound {}", self.callable_name(target))
6720            }
6721            Some(JsObj::BoundMethod { name, .. }) => name.clone(),
6722            _ => String::new(),
6723        }
6724    }
6725
6726    // ── equality / comparison / arithmetic (numeric-hook + builtin paths) ──
6727
6728    /// Strict equality (`===`): same type and same value, no coercion.
6729    pub fn strict_eq(&self, a: &Value, b: &Value) -> bool {
6730        match (a, b) {
6731            (Value::Undef, Value::Undef) => true,
6732            (Value::Bool(x), Value::Bool(y)) => x == y,
6733            (Value::Str(x), Value::Str(y)) => x == y,
6734            _ => {
6735                // Numbers (NaN !== NaN, +0 === -0).
6736                let an = matches!(a, Value::Int(_) | Value::Float(_));
6737                let bn = matches!(b, Value::Int(_) | Value::Float(_));
6738                if an && bn {
6739                    let x = self.to_number(a);
6740                    let y = self.to_number(b);
6741                    return x == y;
6742                }
6743                // BigInt === BigInt compares by value (each literal is a distinct
6744                // heap cell, so reference identity would be wrong). BigInt is never
6745                // `===` a Number (different types).
6746                if let (Some(x), Some(y)) = (self.as_bigint(a), self.as_bigint(b)) {
6747                    return x == y;
6748                }
6749                // Heap values.
6750                if let (Some(sa), Some(sb)) = (self.as_str(a), self.as_str(b)) {
6751                    return sa == sb;
6752                }
6753                let na = self.is_null(a);
6754                let nb = self.is_null(b);
6755                if na || nb {
6756                    return na && nb;
6757                }
6758                // A builtin namespace/constructor/prototype is a SINGLETON in JS
6759                // (`Math === Math`, `Array.prototype === Array.prototype`), but
6760                // every bare reference here allocates a fresh handle, so compare
6761                // those by name rather than by heap index.
6762                if let (Some(JsObj::Builtin(x)), Some(JsObj::Builtin(y))) =
6763                    (self.get(a), self.get(b))
6764                {
6765                    return builtin_identity(x) == builtin_identity(y);
6766                }
6767                // Reference identity for arrays/objects/functions.
6768                matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
6769            }
6770        }
6771    }
6772
6773    /// Whether `v` is `null` or `undefined`.
6774    pub fn is_nullish(&self, v: &Value) -> bool {
6775        matches!(v, Value::Undef) || self.is_null(v)
6776    }
6777
6778    /// The ECMAScript "loose type" of `v` for the `==` algorithm: `"number"`,
6779    /// `"string"` (primitive or heap string), `"boolean"`, `"undefined"`,
6780    /// `"null"`, or `"object"` (array / plain object / function).
6781    fn js_type(&self, v: &Value) -> &'static str {
6782        match v {
6783            Value::Undef => "undefined",
6784            Value::Bool(_) => "boolean",
6785            Value::Int(_) | Value::Float(_) => "number",
6786            Value::Str(_) => "string",
6787            Value::Obj(_) => match self.get(v) {
6788                Some(JsObj::Str(_)) => "string",
6789                Some(JsObj::Null) => "null",
6790                Some(JsObj::BigInt(_)) => "bigint",
6791                _ => "object",
6792            },
6793            _ => "object",
6794        }
6795    }
6796
6797    /// Loose equality (`==`) following the ECMAScript Abstract Equality Comparison.
6798    /// Objects reduce via `ToPrimitive` (which for our heap objects is always their
6799    /// string `toString`), so `[0] == "0"` is `true` (string compare of `"0"`) but
6800    /// `[0] == ""` is `false` — never a number coercion of the object.
6801    pub fn loose_eq(&self, a: &Value, b: &Value) -> bool {
6802        // Same type: identical to `===` (number==number, string==string, etc.).
6803        if self.strict_eq(a, b) {
6804            return true;
6805        }
6806        let ta = self.js_type(a);
6807        let tb = self.js_type(b);
6808        // null and undefined are loosely equal only to each other.
6809        if self.is_nullish(a) || self.is_nullish(b) {
6810            return self.is_nullish(a) && self.is_nullish(b);
6811        }
6812        // BigInt ⇄ (Number | String | Boolean | Object): compare mathematical
6813        // values (both-BigInt was already settled by the `strict_eq` above).
6814        if ta == "bigint" || tb == "bigint" {
6815            return self.bigint_loose_eq(a, b);
6816        }
6817        if ta == tb {
6818            // Same type but not strict-equal (and not nullish) ⇒ not equal.
6819            return false;
6820        }
6821        // number ⇄ string: compare as numbers.
6822        if (ta == "number" && tb == "string") || (ta == "string" && tb == "number") {
6823            return self.to_number(a) == self.to_number(b);
6824        }
6825        // boolean side coerces to number, then recompares.
6826        if ta == "boolean" {
6827            return self.loose_eq(&Value::Float(self.to_number(a)), b);
6828        }
6829        if tb == "boolean" {
6830            return self.loose_eq(a, &Value::Float(self.to_number(b)));
6831        }
6832        // object ⇄ (number|string): ToPrimitive the object (→ its string form),
6833        // then recompare as string==string or number==string.
6834        if ta == "object" && (tb == "number" || tb == "string") {
6835            let pa = self.str_of(a);
6836            return if tb == "string" {
6837                pa == self.str_of(b)
6838            } else {
6839                str_to_number(&pa) == self.to_number(b)
6840            };
6841        }
6842        if tb == "object" && (ta == "number" || ta == "string") {
6843            let pb = self.str_of(b);
6844            return if ta == "string" {
6845                self.str_of(a) == pb
6846            } else {
6847                self.to_number(a) == str_to_number(&pb)
6848            };
6849        }
6850        false
6851    }
6852
6853    /// The numeric-hook arithmetic/relational fallback for non-native operands
6854    /// (called by fusevm when at least one operand isn't `Int`/`Float`).
6855    pub fn arith(&mut self, op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
6856        use NumOp::*;
6857        match op {
6858            Add => {
6859                // `+`: if either operand is a string, concatenate string forms;
6860                // otherwise numeric addition.
6861                let a_str = self.prefers_string(a);
6862                let b_str = self.prefers_string(b);
6863                if a_str || b_str {
6864                    // String concatenation wins even with a bigint operand
6865                    // (`1n + "x"` → `"1x"`).
6866                    let s = format!("{}{}", self.str_of(a), self.str_of(b));
6867                    Ok(self.new_str(s))
6868                } else if self.is_bigint_val(a) || self.is_bigint_val(b) {
6869                    self.bigint_arith(op, a, b)
6870                } else {
6871                    Ok(Value::Float(self.to_number(a) + self.to_number(b)))
6872                }
6873            }
6874            Sub | Mul | Div | Mod | Pow if self.is_bigint_val(a) || self.is_bigint_val(b) => {
6875                self.bigint_arith(op, a, b)
6876            }
6877            Sub => Ok(Value::Float(self.to_number(a) - self.to_number(b))),
6878            Mul => Ok(Value::Float(self.to_number(a) * self.to_number(b))),
6879            Div => Ok(Value::Float(self.to_number(a) / self.to_number(b))),
6880            Mod => Ok(Value::Float(js_mod(self.to_number(a), self.to_number(b)))),
6881            Pow => Ok(Value::Float(crate::builtins::js_pow(
6882                self.to_number(a),
6883                self.to_number(b),
6884            ))),
6885            Neg if self.is_bigint_val(a) => self.bigint_arith(op, a, b),
6886            Neg => Ok(Value::Float(-self.to_number(a))),
6887            Lt | Le | Gt | Ge => Ok(Value::Bool(self.relational(op, a, b))),
6888            Eq => Ok(Value::Bool(self.loose_eq(a, b))),
6889            Ne => Ok(Value::Bool(!self.loose_eq(a, b))),
6890        }
6891    }
6892
6893    /// Whether `v`'s primitive (`ToPrimitive` with the default hint) is a string,
6894    /// which drives `+` toward concatenation. Primitive strings qualify, and so
6895    /// do heap objects whose default `ToPrimitive` is their (string) `toString`:
6896    /// arrays (`[1,2,3]+3 → "1,2,33"`), plain objects (`{}+[] → "[object Object]"`),
6897    /// and functions. `null`/`undefined`/`boolean`/`number` do not.
6898    fn prefers_string(&self, v: &Value) -> bool {
6899        match v {
6900            Value::Str(_) => true,
6901            // A BigInt's `ToPrimitive` is the bigint itself (numeric), NOT a string,
6902            // so `1n + 2n` is bigint addition, not concatenation. `null` has no
6903            // string primitive either.
6904            Value::Obj(_) => !matches!(
6905                self.get(v),
6906                Some(JsObj::Null) | Some(JsObj::BigInt(_)) | None
6907            ),
6908            _ => false,
6909        }
6910    }
6911
6912    /// Relational comparison (`< <= > >=`) with JS coercion: string/string is
6913    /// lexicographic, otherwise numeric (NaN yields false).
6914    fn relational(&self, op: NumOp, a: &Value, b: &Value) -> bool {
6915        use std::cmp::Ordering;
6916        let ord = if let (Some(x), Some(y)) = (self.as_bigint(a), self.as_bigint(b)) {
6917            // BigInt < BigInt: exact (no f64 precision loss for large magnitudes).
6918            x.cmp(&y)
6919        } else if let (Some(x), Some(y)) = (self.as_str(a), self.as_str(b)) {
6920            // 7.2.13 IsLessThan compares CODE UNITS, which is not Rust's `str`
6921            // order once an astral character meets a BMP one — see `utf16`.
6922            crate::utf16::cmp_units(&x, &y)
6923        } else {
6924            let x = self.to_number(a);
6925            let y = self.to_number(b);
6926            match x.partial_cmp(&y) {
6927                Some(o) => o,
6928                None => return false, // NaN operand
6929            }
6930        };
6931        match op {
6932            NumOp::Lt => ord == Ordering::Less,
6933            NumOp::Le => ord != Ordering::Greater,
6934            NumOp::Gt => ord == Ordering::Greater,
6935            NumOp::Ge => ord != Ordering::Less,
6936            _ => false,
6937        }
6938    }
6939
6940    /// Bitwise/shift ops with JS ToInt32/ToUint32 semantics — or true
6941    /// arbitrary-width BigInt bitwise when both operands are BigInt (mixing a
6942    /// BigInt with a Number throws, matching Node).
6943    pub fn bitwise(&mut self, tag: i64, a: &Value, b: &Value) -> Result<Value, String> {
6944        if self.is_bigint_val(a) || self.is_bigint_val(b) {
6945            return self.bigint_bitwise(tag, a, b);
6946        }
6947        let x = to_int32(self.to_number(a));
6948        let y = to_int32(self.to_number(b));
6949        let r: i64 = match tag {
6950            binop::BITAND => (x & y) as i64,
6951            binop::BITOR => (x | y) as i64,
6952            binop::BITXOR => (x ^ y) as i64,
6953            binop::SHL => (x.wrapping_shl((y as u32) & 31)) as i64,
6954            binop::SHR => (x >> ((y as u32) & 31)) as i64,
6955            binop::USHR => (to_uint32(self.to_number(a)) >> ((y as u32) & 31)) as i64,
6956            _ => 0,
6957        };
6958        Ok(Value::Float(r as f64))
6959    }
6960
6961    // ── BigInt operations ────────────────────────────────────────────────────
6962    /// Whether `v` is a heap `BigInt`.
6963    pub fn is_bigint_val(&self, v: &Value) -> bool {
6964        matches!(self.get(v), Some(JsObj::BigInt(_)))
6965    }
6966    /// The `BigInt` value of `v` (a heap bigint), else `None`.
6967    pub fn as_bigint(&self, v: &Value) -> Option<num_bigint::BigInt> {
6968        match self.get(v) {
6969            Some(JsObj::BigInt(b)) => Some(b.clone()),
6970            _ => None,
6971        }
6972    }
6973    /// Allocate a heap `BigInt`.
6974    pub fn new_bigint(&mut self, b: num_bigint::BigInt) -> Value {
6975        self.alloc(JsObj::BigInt(b))
6976    }
6977
6978    /// BigInt arithmetic (`+ - * / % **`, unary `-`). Requires BOTH operands to be
6979    /// BigInt for a binary op; mixing a BigInt with a Number throws the exact Node
6980    /// `TypeError` (a string operand is handled as concatenation before we get
6981    /// here). Division/`%` truncate toward zero; `**` needs a non-negative
6982    /// exponent.
6983    fn bigint_arith(&mut self, op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
6984        use num_traits::{Signed, Zero};
6985        use NumOp::*;
6986        if op == Neg {
6987            let x = self.as_bigint(a).expect("bigint_arith Neg on non-bigint");
6988            return Ok(self.new_bigint(-x));
6989        }
6990        let (x, y) = match (self.as_bigint(a), self.as_bigint(b)) {
6991            (Some(x), Some(y)) => (x, y),
6992            // Exactly one side is a BigInt → the other is a Number/Boolean: illegal.
6993            _ => {
6994                return Err(type_error(
6995                    "Cannot mix BigInt and other types, use explicit conversions",
6996                ))
6997            }
6998        };
6999        let r = match op {
7000            Add => x + y,
7001            Sub => x - y,
7002            Mul => x * y,
7003            Div => {
7004                if y.is_zero() {
7005                    return Err("RangeError: Division by zero".into());
7006                }
7007                x / y // truncates toward zero (matches JS BigInt division)
7008            }
7009            Mod => {
7010                if y.is_zero() {
7011                    return Err("RangeError: Division by zero".into());
7012                }
7013                x % y // sign follows the dividend (truncated), like JS
7014            }
7015            Pow => {
7016                if y.is_negative() {
7017                    return Err("RangeError: Exponent must be positive".into());
7018                }
7019                let exp = num_traits::ToPrimitive::to_u32(&y)
7020                    .ok_or_else(|| "RangeError: Maximum BigInt size exceeded".to_string())?;
7021                num_traits::Pow::pow(x, exp)
7022            }
7023            _ => return Err(type_error("unsupported BigInt operation")),
7024        };
7025        Ok(self.new_bigint(r))
7026    }
7027
7028    /// BigInt bitwise (`& | ^ << >>`); `>>>` has no BigInt form. Both operands must
7029    /// be BigInt (mixing throws).
7030    fn bigint_bitwise(&mut self, tag: i64, a: &Value, b: &Value) -> Result<Value, String> {
7031        let (x, y) = match (self.as_bigint(a), self.as_bigint(b)) {
7032            (Some(x), Some(y)) => (x, y),
7033            _ => {
7034                return Err(type_error(
7035                    "Cannot mix BigInt and other types, use explicit conversions",
7036                ))
7037            }
7038        };
7039        let r = match tag {
7040            binop::BITAND => x & y,
7041            binop::BITOR => x | y,
7042            binop::BITXOR => x ^ y,
7043            binop::SHL => {
7044                let n = num_traits::ToPrimitive::to_i64(&y).unwrap_or(0);
7045                if n >= 0 {
7046                    x << (n as usize)
7047                } else {
7048                    x >> ((-n) as usize)
7049                }
7050            }
7051            binop::SHR => {
7052                let n = num_traits::ToPrimitive::to_i64(&y).unwrap_or(0);
7053                if n >= 0 {
7054                    x >> (n as usize)
7055                } else {
7056                    x << ((-n) as usize)
7057                }
7058            }
7059            binop::USHR => {
7060                return Err(type_error(
7061                    "BigInts have no unsigned right shift, use >> instead",
7062                ))
7063            }
7064            _ => return Err(type_error("unsupported BigInt operation")),
7065        };
7066        Ok(self.new_bigint(r))
7067    }
7068
7069    /// BigInt ⇄ (Number | Boolean | String | Object) loose equality (`==`). Both
7070    /// being BigInt was already handled by `strict_eq`.
7071    fn bigint_loose_eq(&self, a: &Value, b: &Value) -> bool {
7072        // Order so `big` is the BigInt side and `other` the counterpart.
7073        let (big, other) = match (self.as_bigint(a), self.as_bigint(b)) {
7074            (Some(x), _) => (x, b),
7075            (_, Some(y)) => (y, a),
7076            _ => return false,
7077        };
7078        match other {
7079            Value::Bool(bo) => big == num_bigint::BigInt::from(*bo as i64),
7080            Value::Int(n) => big == num_bigint::BigInt::from(*n),
7081            Value::Float(f) => {
7082                // Equal only when the float is an integer with the same value.
7083                if !f.is_finite() || f.fract() != 0.0 {
7084                    return false;
7085                }
7086                bigint_to_f64(&big) == *f
7087            }
7088            Value::Str(s) => match parse_bigint_str(s) {
7089                Some(bs) => big == bs,
7090                None => false,
7091            },
7092            Value::Obj(_) => match self.get(other) {
7093                // A heap string parses like a primitive string.
7094                Some(JsObj::Str(s)) => parse_bigint_str(s).map(|bs| big == bs).unwrap_or(false),
7095                _ => {
7096                    // Other objects reduce via ToPrimitive (their string form).
7097                    let s = self.str_of(other);
7098                    parse_bigint_str(&s).map(|bs| big == bs).unwrap_or(false)
7099                }
7100            },
7101            _ => false,
7102        }
7103    }
7104}
7105
7106/// Parse a string to a BigInt under JS `StringToBigInt` rules: trimmed, empty →
7107/// `0n`, decimal or `0x`/`0o`/`0b` prefixed; any junk → `None`.
7108pub fn parse_bigint_str(s: &str) -> Option<num_bigint::BigInt> {
7109    let t = crate::utf16::js_trim(s);
7110    if t.is_empty() {
7111        return Some(num_bigint::BigInt::from(0));
7112    }
7113    let (radix, digits) = if let Some(h) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
7114        (16, h)
7115    } else if let Some(o) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) {
7116        (8, o)
7117    } else if let Some(bb) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) {
7118        (2, bb)
7119    } else {
7120        (10, t)
7121    };
7122    num_bigint::BigInt::parse_bytes(digits.as_bytes(), radix)
7123}
7124
7125/// Coerce a BigInt to `f64` (for `Number(bigint)` and mixed relational compares);
7126/// out-of-range magnitudes become ±Infinity, matching Node.
7127pub fn bigint_to_f64(b: &num_bigint::BigInt) -> f64 {
7128    num_traits::ToPrimitive::to_f64(b).unwrap_or_else(|| {
7129        if num_traits::Signed::is_negative(b) {
7130            f64::NEG_INFINITY
7131        } else {
7132            f64::INFINITY
7133        }
7134    })
7135}
7136
7137/// JS `%` remainder (sign follows the dividend; matches `f64::rem`).
7138fn js_mod(a: f64, b: f64) -> f64 {
7139    a % b
7140}
7141
7142/// Cycle bookkeeping for one `util.inspect` render.
7143///
7144/// `seen` is the chain of objects currently being rendered (an entry appearing
7145/// twice is a back-edge), and `refs` records every object a back-edge pointed
7146/// at, in first-encountered order — its position + 1 is the `*N` id Node prints
7147/// in `[Circular *N]` / `<ref *N>`.
7148/// How an array-shaped group is laid out, beyond its entries themselves.
7149#[derive(Clone, Copy)]
7150struct ArrayLayout<'a> {
7151    /// Extra own properties follow the elements, which suppresses grid grouping.
7152    has_props: bool,
7153    /// `output`'s last entry is the `... N more items` tail rather than a real
7154    /// element, so the grid must not size a column to it.
7155    has_tail: bool,
7156    /// A constructor tag printed before the brackets, with a trailing space
7157    /// (`"Uint8Array(3) "`), or empty for a plain array.
7158    base: &'a str,
7159}
7160
7161#[derive(Default)]
7162struct InspectCycles {
7163    seen: Vec<Value>,
7164    refs: Vec<Value>,
7165    /// The indent level of the value most recently EXPANDED — node's
7166    /// `ctx.currentDepth`. `reduceToSingleString` puts a group on one line only
7167    /// while `currentDepth - thisDepth < compact`, so without it a deeply
7168    /// nested object printed on one line where node breaks the outer levels.
7169    deepest: usize,
7170}
7171
7172impl InspectCycles {
7173    /// Record `v` as a cycle target (idempotent) and return its 1-based id.
7174    fn mark(&mut self, h: &JsHost, v: &Value) -> usize {
7175        if let Some(id) = self.id_of(h, v) {
7176            return id;
7177        }
7178        self.refs.push(v.clone());
7179        self.refs.len()
7180    }
7181
7182    /// The `*N` id already assigned to `v`, if any.
7183    fn id_of(&self, h: &JsHost, v: &Value) -> Option<usize> {
7184        self.refs
7185            .iter()
7186            .position(|p| h.strict_eq(p, v))
7187            .map(|i| i + 1)
7188    }
7189}
7190
7191thread_local! {
7192    /// The active `util.inspect` `depth` (nesting levels shown before collapsing
7193    /// to `[Object]`/`[Array]`). Node's default is 2; `util.inspect(v,{depth:N})`
7194    /// overrides it for one call, `console.log`/`util.format` use the default.
7195    /// Signed, because `util.inspect(v, { depth: -1 })` is legal and means
7196    /// "already past the limit" — everything collapses to `[Object]` at the top
7197    /// level. Held as `usize` it read as an enormous depth and expanded fully.
7198    static INSPECT_MAX_DEPTH: std::cell::Cell<i64> = const { std::cell::Cell::new(2) };
7199
7200    /// `util.inspect`'s `compact` option. Node's default is the NUMBER 3: a
7201    /// group is put on one line only when the subtree below it is shallower
7202    /// than this. `compact: false` is held as 0, which no subtree depth is
7203    /// below, so every group breaks — which is exactly what node does.
7204    static INSPECT_COMPACT: std::cell::Cell<i64> = const { std::cell::Cell::new(DEFAULT_COMPACT) };
7205
7206    /// `util.inspect`'s `breakLength`. Node's default is 128, but `util.inspect`
7207    /// itself passes 80.
7208    static INSPECT_BREAK_LENGTH: std::cell::Cell<usize> = const { std::cell::Cell::new(80) };
7209
7210    /// `util.inspect`'s `sorted` option: emit an object's own keys in code-unit
7211    /// order instead of insertion order. Off by default. `assert`'s diff renderer
7212    /// turns it on so that two objects built with the same keys in a different
7213    /// order diff as equal rather than as a wholesale rewrite.
7214    static INSPECT_SORTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
7215
7216    /// `util.inspect`'s `maxArrayLength`: how many entries are formatted before
7217    /// the rest collapse into `... N more items`. Node's default is 100;
7218    /// `Infinity`/`null` means "all", held here as `usize::MAX`.
7219    static INSPECT_MAX_ARRAY_LENGTH: std::cell::Cell<usize> = const { std::cell::Cell::new(DEFAULT_MAX_ARRAY_LENGTH) };
7220
7221    /// `util.inspect`'s `customInspect` option: whether a value's own
7222    /// `[util.inspect.custom]` rendering is used. On by default; `assert` turns
7223    /// it off so a diff shows an object's real structure rather than whatever
7224    /// summary it prefers to print.
7225    static INSPECT_CUSTOM: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
7226
7227    /// `util.inspect`'s `showHidden`: reveal the non-enumerable slots a value
7228    /// carries — an array's `length`, a typed array's element width and window
7229    /// onto its backing store. Off by default; `util.format`'s `%o` turns it on.
7230    static INSPECT_SHOW_HIDDEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
7231
7232    /// `util.inspect`'s `numericSeparator`: group digits with `_`.
7233    static INSPECT_NUMERIC_SEPARATOR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
7234
7235    /// `util.inspect`'s `maxStringLength` (UTF-16 units shown before the
7236    /// `... N more characters` trailer). Node's default is 10000.
7237    static INSPECT_MAX_STRING_LENGTH: std::cell::Cell<usize> = const { std::cell::Cell::new(DEFAULT_MAX_STRING_LENGTH) };
7238
7239    /// `util.inspect`'s `showProxy`: render a Proxy as `Proxy [ target, handler ]`.
7240    static INSPECT_SHOW_PROXY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
7241}
7242
7243/// Node's default `maxStringLength`.
7244pub(crate) const DEFAULT_MAX_STRING_LENGTH: usize = 10000;
7245
7246/// Set the `util.inspect` `numericSeparator` option for the next render.
7247pub fn set_inspect_numeric_separator(s: bool) {
7248    INSPECT_NUMERIC_SEPARATOR.with(|x| x.set(s));
7249}
7250
7251fn inspect_numeric_separator() -> bool {
7252    INSPECT_NUMERIC_SEPARATOR.with(|x| x.get())
7253}
7254
7255/// Set the `util.inspect` `maxStringLength` for the next render.
7256pub fn set_inspect_max_string_length(n: usize) {
7257    INSPECT_MAX_STRING_LENGTH.with(|x| x.set(n));
7258}
7259
7260fn inspect_max_string_length() -> usize {
7261    INSPECT_MAX_STRING_LENGTH.with(|x| x.get())
7262}
7263
7264/// Set the `util.inspect` `showProxy` option for the next render.
7265pub fn set_inspect_show_proxy(s: bool) {
7266    INSPECT_SHOW_PROXY.with(|x| x.set(s));
7267}
7268
7269pub(crate) fn inspect_show_proxy() -> bool {
7270    INSPECT_SHOW_PROXY.with(|x| x.get())
7271}
7272
7273/// Node's `formatNumber` under `numericSeparator`: `_` every three digits,
7274/// counted from the decimal point outward on both sides. An exponential or
7275/// non-finite form is left alone.
7276fn numeric_separated(s: &str) -> String {
7277    if s.contains('e') || s.contains('N') || s.contains('I') {
7278        return s.to_string();
7279    }
7280    let (sign, digits) = match s.strip_prefix('-') {
7281        Some(d) => ("-", d),
7282        None => ("", s),
7283    };
7284    let (int, frac) = match digits.split_once('.') {
7285        Some((i, f)) => (i, Some(f)),
7286        None => (digits, None),
7287    };
7288    let mut grouped = String::new();
7289    for (i, c) in int.chars().enumerate() {
7290        if i > 0 && (int.len() - i) % 3 == 0 {
7291            grouped.push('_');
7292        }
7293        grouped.push(c);
7294    }
7295    if let Some(f) = frac {
7296        grouped.push('.');
7297        let chars: Vec<char> = f.chars().collect();
7298        for (i, chunk) in chars.chunks(3).enumerate() {
7299            if i > 0 {
7300                grouped.push('_');
7301            }
7302            grouped.extend(chunk);
7303        }
7304    }
7305    format!("{sign}{grouped}")
7306}
7307
7308/// A number as `util.inspect` prints it: `-0` kept, digits grouped under
7309/// `numericSeparator`.
7310fn inspect_number(s: String) -> String {
7311    if inspect_numeric_separator() {
7312        numeric_separated(&s)
7313    } else {
7314        s
7315    }
7316}
7317
7318/// A quoted string as `util.inspect` prints it, cut to `maxStringLength` UTF-16
7319/// units with node's `... N more characters` trailer.
7320fn inspect_string(s: &str) -> String {
7321    let max = inspect_max_string_length();
7322    let units = crate::utf16::Units::of(s);
7323    if units.len() <= max {
7324        return quote_str(s);
7325    }
7326    let rest = units.len() - max;
7327    let plural = if rest == 1 { "" } else { "s" };
7328    format!(
7329        "{}... {rest} more character{plural}",
7330        quote_str(&units.slice(0, max))
7331    )
7332}
7333
7334/// Set the `util.inspect` `showHidden` option for the next render.
7335pub fn set_inspect_show_hidden(s: bool) {
7336    INSPECT_SHOW_HIDDEN.with(|x| x.set(s));
7337}
7338
7339pub(crate) fn inspect_show_hidden() -> bool {
7340    INSPECT_SHOW_HIDDEN.with(|x| x.get())
7341}
7342
7343/// Set the `util.inspect` `customInspect` option for the next render.
7344pub fn set_inspect_custom(c: bool) {
7345    INSPECT_CUSTOM.with(|x| x.set(c));
7346}
7347
7348pub(crate) fn inspect_custom() -> bool {
7349    INSPECT_CUSTOM.with(|x| x.get())
7350}
7351
7352/// Set the `util.inspect` `sorted` option for the next render.
7353pub fn set_inspect_sorted(s: bool) {
7354    INSPECT_SORTED.with(|x| x.set(s));
7355}
7356
7357pub(crate) fn inspect_sorted() -> bool {
7358    INSPECT_SORTED.with(|x| x.get())
7359}
7360
7361/// Set the `util.inspect` `maxArrayLength` for the next render.
7362pub fn set_inspect_max_array_length(n: usize) {
7363    INSPECT_MAX_ARRAY_LENGTH.with(|x| x.set(n));
7364}
7365
7366pub(crate) fn inspect_max_array_length() -> usize {
7367    INSPECT_MAX_ARRAY_LENGTH.with(|x| x.get())
7368}
7369
7370/// Set the `util.inspect` `compact` option for the next render (0 for `false`).
7371pub fn set_inspect_compact(c: i64) {
7372    INSPECT_COMPACT.with(|x| x.set(c));
7373}
7374
7375/// Set the `util.inspect` `breakLength` for the next render.
7376pub fn set_inspect_break_length(n: usize) {
7377    INSPECT_BREAK_LENGTH.with(|x| x.set(n));
7378}
7379
7380pub(crate) fn inspect_compact() -> i64 {
7381    INSPECT_COMPACT.with(|x| x.get())
7382}
7383
7384/// Set the `util.inspect` depth for the next render (restore to 2 after).
7385pub fn set_inspect_max_depth(d: i64) {
7386    INSPECT_MAX_DEPTH.with(|c| c.set(d));
7387}
7388/// Twice the configured depth, which is what the inspect walk compares its
7389/// indent against. Saturating, because `util.inspect(x, { depth: null })` and
7390/// `{ depth: Infinity }` both set the depth to `usize::MAX`, and doubling that
7391/// overflowed and panicked the process — an abort no script could catch.
7392fn inspect_indent_limit() -> i64 {
7393    inspect_max_depth().saturating_mul(2)
7394}
7395
7396pub(crate) fn inspect_max_depth() -> i64 {
7397    INSPECT_MAX_DEPTH.with(|c| c.get())
7398}
7399
7400/// ECMA-262 `ToInt32` (7.1.6): truncate toward zero, reduce modulo 2^32, then
7401/// reinterpret as signed.
7402///
7403/// The reduction has to happen in `f64`, not by casting through `i64`. Rust
7404/// saturates an out-of-range float-to-int cast, so `1e300 as i64` is `i64::MAX`
7405/// and `1e300 | 0` came out `-1` where every engine says `0`; the same
7406/// saturation made `1e300 >>> 0` report `4294967295`. `rem_euclid` on a
7407/// power-of-two modulus is exact for every finite double, so this is the whole
7408/// fix — and it is the form `Math.clz32` already used.
7409pub(crate) fn to_int32(f: f64) -> i32 {
7410    to_uint32(f) as i32
7411}
7412pub(crate) fn to_uint32(f: f64) -> u32 {
7413    if !f.is_finite() {
7414        return 0;
7415    }
7416    f.trunc().rem_euclid(4294967296.0) as u32
7417}
7418
7419/// The value of a run of digits in `radix` (2..=36), the way V8 computes it —
7420/// which is exact for decimal and the power-of-two radixes and deliberately
7421/// approximate for the rest, so a faithful result needs V8's own algorithm:
7422///
7423/// * radix 10: the correctly rounded decimal value;
7424/// * radix 2, 4, 8, 16, 32 (`InternalStringToIntDouble`): the digits are
7425///   accumulated into 53 bits and the dropped tail rounds half to even;
7426/// * any other radix (`HandleGenericCase`): 32-bit multiply-and-add over the
7427///   longest part that fits, parts combined in a double. 19.2.5 allows an
7428///   implementation-approximated value there, and `parseInt('…', 36)` of a long
7429///   string differs in the last digit between algorithms.
7430///
7431/// The caller passes only valid digits for `radix`.
7432pub(crate) fn digits_to_number(digits: &str, radix: u32) -> f64 {
7433    if digits.is_empty() {
7434        return f64::NAN;
7435    }
7436    if radix == 10 {
7437        return digits.parse::<f64>().unwrap_or(f64::NAN);
7438    }
7439    let ds: Vec<u32> = digits
7440        .chars()
7441        .map(|c| c.to_digit(radix).unwrap_or(0))
7442        .collect();
7443    if radix.is_power_of_two() {
7444        let log2 = radix.trailing_zeros();
7445        let mut number: u64 = 0;
7446        let mut exponent: i32 = 0;
7447        let mut i = 0;
7448        while i < ds.len() {
7449            number = number * u64::from(radix) + u64::from(ds[i]);
7450            let mut overflow = number >> 53;
7451            if overflow != 0 {
7452                // The value no longer fits 53 bits: drop the low bits and round
7453                // them half to even, counting every further digit as exponent.
7454                let mut overflow_bits = 1;
7455                while overflow > 1 {
7456                    overflow_bits += 1;
7457                    overflow >>= 1;
7458                }
7459                let dropped = number & ((1u64 << overflow_bits) - 1);
7460                number >>= overflow_bits;
7461                exponent = overflow_bits;
7462                let mut zero_tail = true;
7463                i += 1;
7464                while i < ds.len() {
7465                    exponent += log2 as i32;
7466                    zero_tail = zero_tail && ds[i] == 0;
7467                    i += 1;
7468                }
7469                let middle = 1u64 << (overflow_bits - 1);
7470                if dropped > middle || (dropped == middle && (number & 1 != 0 || !zero_tail)) {
7471                    number += 1;
7472                }
7473                if number & (1u64 << 53) != 0 {
7474                    exponent += 1;
7475                    number >>= 1;
7476                }
7477                break;
7478            }
7479            i += 1;
7480        }
7481        return number as f64 * 2f64.powi(exponent);
7482    }
7483    // Leading zeros are skipped first, which moves where the parts begin.
7484    let mut result = 0.0f64;
7485    let mut i = ds.iter().take_while(|&&d| d == 0).count();
7486    const MAX_MULTIPLIER: u32 = 0xFFFF_FFFF / 36;
7487    while i < ds.len() {
7488        let (mut part, mut multiplier) = (0u32, 1u32);
7489        while i < ds.len() {
7490            let m = multiplier * radix;
7491            if m > MAX_MULTIPLIER {
7492                break;
7493            }
7494            part = part * radix + ds[i];
7495            multiplier = m;
7496            i += 1;
7497        }
7498        // One fused multiply-add per part: the reference build contracts
7499        // `result * multiplier + part`, which rounds once rather than twice
7500        // (see `crate::ieee754` on contraction).
7501        result = result.mul_add(f64::from(multiplier), f64::from(part));
7502    }
7503    result
7504}
7505
7506/// `StringNumericLiteral` (7.1.4.1.1) decimal grammar: `Infinity`, or digits
7507/// with an optional fraction and exponent — what Rust's own float parser
7508/// accepts a superset of (`inf`, `nan`, `infinity`, any case).
7509fn is_decimal_numeric_literal(s: &str) -> bool {
7510    let b = s.as_bytes();
7511    let mut i = 0;
7512    if matches!(b.first(), Some(b'+' | b'-')) {
7513        i = 1;
7514    }
7515    if &s[i..] == "Infinity" {
7516        return true;
7517    }
7518    let int_start = i;
7519    while b.get(i).is_some_and(u8::is_ascii_digit) {
7520        i += 1;
7521    }
7522    let mut digits = i - int_start;
7523    if b.get(i) == Some(&b'.') {
7524        i += 1;
7525        let frac_start = i;
7526        while b.get(i).is_some_and(u8::is_ascii_digit) {
7527            i += 1;
7528        }
7529        digits += i - frac_start;
7530    }
7531    if digits == 0 {
7532        return false;
7533    }
7534    if matches!(b.get(i), Some(b'e' | b'E')) {
7535        i += 1;
7536        if matches!(b.get(i), Some(b'+' | b'-')) {
7537            i += 1;
7538        }
7539        let exp_start = i;
7540        while b.get(i).is_some_and(u8::is_ascii_digit) {
7541            i += 1;
7542        }
7543        if i == exp_start {
7544            return false;
7545        }
7546    }
7547    i == b.len()
7548}
7549
7550/// Parse a string in numeric context (`ToNumber`): trimmed, empty -> 0.
7551fn str_to_number(s: &str) -> f64 {
7552    let t = crate::utf16::js_trim(s);
7553    if t.is_empty() {
7554        return 0.0;
7555    }
7556    // A radix prefix takes no sign and at least one digit, any length.
7557    for (prefixes, radix) in [(["0x", "0X"], 16), (["0o", "0O"], 8), (["0b", "0B"], 2)] {
7558        if let Some(digits) = prefixes.iter().find_map(|p| t.strip_prefix(p)) {
7559            return if !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix)) {
7560                digits_to_number(digits, radix)
7561            } else {
7562                f64::NAN
7563            };
7564        }
7565    }
7566    if !is_decimal_numeric_literal(t) {
7567        return f64::NAN;
7568    }
7569    match t {
7570        "Infinity" | "+Infinity" => f64::INFINITY,
7571        "-Infinity" => f64::NEG_INFINITY,
7572        _ => t.parse::<f64>().unwrap_or(f64::NAN),
7573    }
7574}
7575
7576// ── `[util.inspect.custom]` ──────────────────────────────────────────────────
7577//
7578// The inspect walk runs under an immutable host borrow and cannot call into
7579// JS, so an object's own `[util.inspect.custom](depth, options, inspect)` is
7580// run in a PRE-PASS over the same subtree the walk will render, and the walk
7581// substitutes each answer: a string is printed verbatim (its newlines indented
7582// to the current level, as node's `formatValue` does), anything else is
7583// rendered in the object's place. A method that returns the receiver itself
7584// leaves it to the ordinary rendering.
7585
7586/// What a custom inspect method answered for one object.
7587#[derive(Clone)]
7588enum CustomRender {
7589    Text(String),
7590    Value(Value),
7591}
7592
7593/// An accessor as the generic object arm shows it: its label, and under the
7594/// `getters` option what reading it produced (a value, or the thrown error's
7595/// text).
7596type AccessorShown = (&'static str, Option<Result<Value, Value>>);
7597
7598thread_local! {
7599    static CUSTOM_RENDERS: RefCell<HashMap<u32, CustomRender>> = RefCell::new(HashMap::new());
7600    /// The stand-in object for each module namespace in the current render.
7601    static NAMESPACE_SNAPSHOTS: RefCell<HashMap<String, Value>> = RefCell::new(HashMap::new());
7602    /// `getters`: the value each own getter returned, keyed by object and key.
7603    static GETTER_RENDERS: RefCell<HashMap<(u32, String), Result<Value, Value>>> = RefCell::new(HashMap::new());
7604    /// `util.inspect`'s `getters` option: 0 off, 1 every getter, 2 only
7605    /// getters without a setter (`'get'`), 3 only those with one (`'set'`).
7606    static INSPECT_GETTERS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
7607}
7608
7609/// Set the `util.inspect` `getters` option for the next render.
7610pub fn set_inspect_getters(g: u8) {
7611    INSPECT_GETTERS.with(|x| x.set(g));
7612}
7613
7614fn getter_render(v: &Value, key: &str) -> Option<Result<Value, Value>> {
7615    let Value::Obj(id) = v else { return None };
7616    GETTER_RENDERS.with(|m| m.borrow().get(&(*id, key.to_string())).cloned())
7617}
7618
7619fn custom_render(v: &Value) -> Option<CustomRender> {
7620    let Value::Obj(id) = v else { return None };
7621    CUSTOM_RENDERS.with(|m| m.borrow().get(id).cloned())
7622}
7623
7624/// `h.inspect(v)` with every `[util.inspect.custom]` method in the rendered
7625/// subtree run first. The entry point for every JS-facing render
7626/// (`util.inspect`, `console.log`, `util.format`).
7627pub fn inspect_js(v: &Value) -> Result<String, String> {
7628    with_custom_renders(v, |h| h.inspect(v))
7629}
7630
7631/// [`inspect_js`] for `console.log`'s argument form: a bare string prints raw.
7632pub fn console_format_js(v: &Value) -> Result<String, String> {
7633    with_custom_renders(v, |h| h.console_format(v))
7634}
7635
7636fn with_custom_renders(
7637    v: &Value,
7638    render: impl FnOnce(&JsHost) -> String,
7639) -> Result<String, String> {
7640    // A custom method may itself call `inspect`, so the outer render's
7641    // answers are set aside and restored rather than shared.
7642    let saved = CUSTOM_RENDERS.with(|m| std::mem::take(&mut *m.borrow_mut()));
7643    let saved_getters = GETTER_RENDERS.with(|m| std::mem::take(&mut *m.borrow_mut()));
7644    let saved_snaps = NAMESPACE_SNAPSHOTS.with(|m| std::mem::take(&mut *m.borrow_mut()));
7645    let mut seen = HashSet::new();
7646    let mut ctx = None;
7647    let r = collect_custom_renders(v, 0, &mut seen, &mut ctx);
7648    let out = r.map(|()| with_host(|h| render(h)));
7649    CUSTOM_RENDERS.with(|m| *m.borrow_mut() = saved);
7650    GETTER_RENDERS.with(|m| *m.borrow_mut() = saved_getters);
7651    NAMESPACE_SNAPSHOTS.with(|m| *m.borrow_mut() = saved_snaps);
7652    out
7653}
7654
7655/// The text node prints for a getter that threw: the error's `stack`, or the
7656/// value itself when it has none.
7657fn uncaught_text(msg: &str) -> String {
7658    let err = with_host(|h| h.exc.take())
7659        .unwrap_or_else(|| with_host(|h| crate::builtins::synth_error(h, msg)));
7660    match crate::builtins::get_property(&err, "stack") {
7661        Ok(s) if with_host(|h| h.type_of(&s) == "string") => with_host(|h| h.str_of(&s)),
7662        _ => with_host(|h| h.str_of(&err)),
7663    }
7664}
7665
7666/// The `(options, inspect)` arguments node passes a custom method, built once
7667/// per render: its user options with a colourless `stylize`, and `util.inspect`.
7668fn custom_inspect_args() -> Result<(Value, Value), String> {
7669    let stylize = crate::eval_internal("(function stylizeNoColor(str) { return str; })")?;
7670    let depth = inspect_max_depth();
7671    let opts = with_host(|h| {
7672        let num = |n: i64| {
7673            if n >= i64::MAX / 4 {
7674                Value::Float(f64::INFINITY)
7675            } else {
7676                Value::Float(n as f64)
7677            }
7678        };
7679        let max_array = inspect_max_array_length();
7680        let mut m: IndexMap<String, Value> = IndexMap::new();
7681        m.insert("stylize".into(), stylize);
7682        m.insert("showHidden".into(), Value::Bool(inspect_show_hidden()));
7683        m.insert("depth".into(), num(depth));
7684        m.insert("colors".into(), Value::Bool(false));
7685        m.insert("customInspect".into(), Value::Bool(true));
7686        m.insert("showProxy".into(), Value::Bool(false));
7687        m.insert(
7688            "maxArrayLength".into(),
7689            if max_array == usize::MAX {
7690                Value::Float(f64::INFINITY)
7691            } else {
7692                Value::Float(max_array as f64)
7693            },
7694        );
7695        m.insert("maxStringLength".into(), Value::Float(10000.0));
7696        let bl = break_length();
7697        m.insert(
7698            "breakLength".into(),
7699            if bl == usize::MAX {
7700                Value::Float(f64::INFINITY)
7701            } else {
7702                Value::Float(bl as f64)
7703            },
7704        );
7705        let compact = inspect_compact();
7706        m.insert(
7707            "compact".into(),
7708            match compact {
7709                0 => Value::Bool(false),
7710                i64::MAX => Value::Bool(true),
7711                n => Value::Float(n as f64),
7712            },
7713        );
7714        m.insert("sorted".into(), Value::Bool(inspect_sorted()));
7715        m.insert("getters".into(), Value::Bool(false));
7716        m.insert("numericSeparator".into(), Value::Bool(false));
7717        h.new_object(m)
7718    });
7719    let inspect = with_host(|h| h.alloc(JsObj::Builtin("util.inspect".into())));
7720    Ok((opts, inspect))
7721}
7722
7723/// The stand-in `util.inspect` renders for the module namespace object `ns`:
7724/// a null-prototype object of its exports in `[[Exports]]` order, tagged so the
7725/// render prefixes it `[Module: null prototype]`. A binding that is not yet
7726/// initialized renders as `<uninitialized>`.
7727fn esm_namespace_snapshot(ns: &Value) -> Result<Value, String> {
7728    // The export names are the proxy target's string keys. They are read off
7729    // the target rather than through `Object.keys`, whose [[GetOwnProperty]]
7730    // reads each value and so throws for a binding still in its dead zone.
7731    let keys: Vec<String> = with_host(|h| {
7732        let target = match h.get(ns) {
7733            Some(JsObj::Proxy { target, .. }) => target.clone(),
7734            _ => return Vec::new(),
7735        };
7736        match h.get(&target) {
7737            Some(JsObj::Object(p)) => p.keys().filter(|k| !k.starts_with("@@")).cloned().collect(),
7738            _ => Vec::new(),
7739        }
7740    });
7741    let mut props = IndexMap::new();
7742    for k in keys {
7743        let val = match crate::builtins::get_property(ns, &k) {
7744            Ok(v) => v,
7745            Err(_) => {
7746                with_host(|h| h.exc = None);
7747                let marker = with_host(|h| h.new_object(IndexMap::new()));
7748                if let Value::Obj(i) = marker {
7749                    CUSTOM_RENDERS.with(|m| {
7750                        m.borrow_mut()
7751                            .insert(i, CustomRender::Text("<uninitialized>".into()))
7752                    });
7753                }
7754                marker
7755            }
7756        };
7757        props.insert(k, val);
7758    }
7759    props.insert(ESM_NAMESPACE_SNAPSHOT.to_string(), Value::Bool(true));
7760    Ok(with_host(|h| {
7761        let snap = h.new_object(props);
7762        let null = h.null();
7763        h.set_proto(&snap, null);
7764        snap
7765    }))
7766}
7767
7768/// Hidden slot marking an [`esm_namespace_snapshot`].
7769const ESM_NAMESPACE_SNAPSHOT: &str = "@@esmNamespaceSnapshot";
7770
7771/// Walk what the render will expand from `v` at nesting `level`, running each
7772/// custom inspect method found and recording its answer.
7773/// The plain-object stand-in for module namespace `ns` in one render: its
7774/// enumerable keys (`namespace_keys`, node's order) and their values.
7775fn namespace_snapshot(ns: &str) -> Value {
7776    if let Some(s) = NAMESPACE_SNAPSHOTS.with(|m| m.borrow().get(ns).cloned()) {
7777        return s;
7778    }
7779    let snap = with_host(|h| h.new_object(IndexMap::new()));
7780    NAMESPACE_SNAPSHOTS.with(|m| m.borrow_mut().insert(ns.to_string(), snap.clone()));
7781    for k in crate::stdlib::namespace_keys(ns) {
7782        // An export node defines as an accessor renders as `[Getter]` (or
7783        // `[Getter/Setter]`), so the stand-in carries the accessor itself.
7784        if let Some(row) = crate::builtins::core_accessor_export(ns, &k) {
7785            let (get, set) = crate::builtins::core_accessor_functions(row);
7786            with_host(|h| h.set_accessor(&snap, &k, Some(get), set));
7787            continue;
7788        }
7789        let val = crate::builtins::namespace_property(ns, &k);
7790        with_host(|h| {
7791            if let Some(JsObj::Object(p)) = h.get_mut(&snap) {
7792                p.insert(k, val);
7793            }
7794        });
7795    }
7796    snap
7797}
7798
7799fn collect_custom_renders(
7800    v: &Value,
7801    level: i64,
7802    seen: &mut HashSet<u32>,
7803    ctx: &mut Option<(Value, Value)>,
7804) -> Result<(), String> {
7805    let Value::Obj(id) = v else { return Ok(()) };
7806    if !seen.insert(*id) {
7807        return Ok(());
7808    }
7809    // An ES module namespace object is not a proxy to `util.inspect`: node
7810    // prints `[Module: null prototype] { … }` with each export's CURRENT value,
7811    // and `<uninitialized>` for a binding still in its dead zone. The values
7812    // need the getters run, so a snapshot is rendered in its place.
7813    if crate::esm::is_namespace(v) {
7814        let snap = esm_namespace_snapshot(v)?;
7815        CUSTOM_RENDERS.with(|m| {
7816            m.borrow_mut()
7817                .insert(*id, CustomRender::Value(snap.clone()))
7818        });
7819        return collect_custom_renders(&snap, level, seen, ctx);
7820    }
7821    let skip = with_host(|h| is_primitive(h, v) || matches!(h.get(v), Some(JsObj::Proxy { .. })));
7822    if skip {
7823        return Ok(());
7824    }
7825    let key = with_host(|h| {
7826        let sym = h.symbol_for("nodejs.util.inspect.custom");
7827        h.property_key(&sym)
7828    });
7829    let method = if inspect_custom() {
7830        crate::builtins::get_property(v, &key)?
7831    } else {
7832        Value::Undef
7833    };
7834    if with_host(|h| is_callable(h, &method)) {
7835        if ctx.is_none() {
7836            *ctx = Some(custom_inspect_args()?);
7837        }
7838        let (opts, inspect) = ctx.clone().unwrap_or((Value::Undef, Value::Undef));
7839        let max = inspect_max_depth();
7840        let depth = if max >= i64::MAX / 4 {
7841            Value::Float(f64::INFINITY)
7842        } else {
7843            Value::Float((max - level) as f64)
7844        };
7845        let ret = invoke(&method, vec![depth, opts, inspect], Some(v.clone()))?;
7846        if !with_host(|h| h.strict_eq(&ret, v)) {
7847            let text = with_host(|h| match h.get(&ret) {
7848                _ if matches!(ret, Value::Str(_)) => Some(h.str_of(&ret)),
7849                Some(JsObj::Str(s)) => Some(s.clone()),
7850                _ => None,
7851            });
7852            let render = match text {
7853                Some(s) => CustomRender::Text(s),
7854                None => {
7855                    collect_custom_renders(&ret, level, seen, ctx)?;
7856                    CustomRender::Value(ret)
7857                }
7858            };
7859            CUSTOM_RENDERS.with(|m| m.borrow_mut().insert(*id, render));
7860            return Ok(());
7861        }
7862    }
7863    // A core-module namespace (`require('path')`) inspects as node prints it:
7864    // a plain object of its members. Rendering one needs each member's VALUE,
7865    // which cannot be built under the render's host borrow, so a snapshot is
7866    // built here and rendered in its place — one per module per render, so
7867    // `path.posix` inside `path` is the same object and prints `[Circular]`.
7868    if let Some(ns) = with_host(|h| match h.get(v) {
7869        Some(JsObj::Builtin(n))
7870            if !builtin_is_callable(n) && crate::stdlib::core_keys(n).is_some() =>
7871        {
7872            Some(n.clone())
7873        }
7874        _ => None,
7875    }) {
7876        let snap = namespace_snapshot(&ns);
7877        CUSTOM_RENDERS.with(|m| {
7878            m.borrow_mut()
7879                .insert(*id, CustomRender::Value(snap.clone()))
7880        });
7881        return collect_custom_renders(&snap, level, seen, ctx);
7882    }
7883    // Only a value the render EXPANDS has its children rendered.
7884    if level > inspect_max_depth() {
7885        return Ok(());
7886    }
7887    let children: Vec<Value> = with_host(|h| match h.get(v) {
7888        Some(JsObj::Array(items)) => items.clone(),
7889        Some(JsObj::Map { entries, .. }) => entries
7890            .values()
7891            .flat_map(|(k, val)| [k.clone(), val.clone()])
7892            .collect(),
7893        Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
7894        Some(JsObj::Object(props)) => props
7895            .iter()
7896            .filter(|(k, _)| {
7897                (!k.starts_with("@@") || h.symbol_of_key(k).is_some())
7898                    && !k.starts_with('#')
7899                    && h.prop_attrs(v, k).enumerable
7900            })
7901            .map(|(_, val)| val.clone())
7902            .collect(),
7903        _ => Vec::new(),
7904    });
7905    for c in &children {
7906        collect_custom_renders(c, level + 1, seen, ctx)?;
7907    }
7908    // `getters`: read each own enumerable accessor the option selects, as
7909    // node's `formatProperty` does, so the walk can print what it returned.
7910    let mode = INSPECT_GETTERS.with(|x| x.get());
7911    if mode != 0 {
7912        let getters: Vec<(String, Value)> = with_host(|h| {
7913            h.own_accessor_keys(v)
7914                .into_iter()
7915                .filter(|k| h.prop_attrs(v, k).enumerable)
7916                .filter_map(|k| match h.own_accessor(v, &k)? {
7917                    (Some(g), set) if mode == 1 || (mode == 2) == set.is_none() => Some((k, g)),
7918                    _ => None,
7919                })
7920                .collect()
7921        });
7922        for (k, g) in getters {
7923            let read = match invoke(&g, Vec::new(), Some(v.clone())) {
7924                Ok(val) => {
7925                    collect_custom_renders(&val, level + 1, seen, ctx)?;
7926                    Ok(val)
7927                }
7928                Err(e) => {
7929                    let thrown = uncaught_text(&e);
7930                    Err(with_host(|h| h.new_str(thrown)))
7931                }
7932            };
7933            GETTER_RENDERS.with(|m| m.borrow_mut().insert((*id, k), read));
7934        }
7935    }
7936    Ok(())
7937}
7938
7939/// `util.inspect` break length (the width past which entries wrap). Node's default.
7940fn break_length() -> usize {
7941    INSPECT_BREAK_LENGTH.with(|x| x.get())
7942}
7943/// Node's default `compact` setting (the `compact * 4` column cap term).
7944/// Node's DEFAULT `compact` setting, and the initial value of
7945/// `INSPECT_COMPACT`. The grid's column cap is `compact * 4`, so it has to be
7946/// read through `inspect_compact()` at render time: under `{ compact: 1 }` node
7947/// lays a byte array out four columns wide, and the hardcoded 3 gave twelve.
7948const DEFAULT_COMPACT: i64 = 3;
7949/// Node's default `maxArrayLength` — the initial value of
7950/// `INSPECT_MAX_ARRAY_LENGTH`, which `util.inspect(v, { maxArrayLength: N })`
7951/// overrides per call. Read it through `inspect_max_array_length()`, never
7952/// directly: as a bare constant the option had no effect and a 120-element array
7953/// was truncated at 100 even under `maxArrayLength: Infinity`.
7954pub(crate) const DEFAULT_MAX_ARRAY_LENGTH: usize = 100;
7955
7956/// Whether `output` fits on a single line — a faithful port of Node's
7957/// `isBelowBreakLength` (no colors, no `base`). `start` is the caller's seed
7958/// length (braces + indentation + slack).
7959fn is_below_break_length(output: &[String], start: usize) -> bool {
7960    let limit = break_length();
7961    let mut total = output.len() + start;
7962    if total + output.len() > limit {
7963        return false;
7964    }
7965    for o in output {
7966        if o.contains('\n') {
7967            return false;
7968        }
7969        total += o.chars().count();
7970        if total > limit {
7971            return false;
7972        }
7973    }
7974    true
7975}
7976
7977/// Faithful port of Node's `util.inspect` `groupArrayElements`: lay out the
7978/// already-formatted element strings into an aligned multi-column grid. Returns
7979/// `(lines, grouped)` — `grouped` is false when Node would leave the output
7980/// ungrouped (so the caller falls back to single-line / one-per-line).
7981fn group_array_elements(
7982    host: &JsHost,
7983    output: &[String],
7984    values: &[Value],
7985    indentation_lvl: usize,
7986    has_tail: bool,
7987) -> (Vec<String>, bool) {
7988    let separator_space = 2usize; // ", " between entries
7989                                  // A `... N more items` tail is not an element: node drops it from the grid
7990                                  // (`outputLength--`) so it neither widens a column nor occupies a cell, then
7991                                  // re-appends it as its own final line.
7992    let output_length = output.len() - usize::from(has_tail);
7993    let data_len: Vec<usize> = output.iter().map(|o| o.chars().count()).collect();
7994    let mut total_length = 0usize;
7995    let mut max_length = 0usize;
7996    for &len in &data_len[..output_length] {
7997        total_length += len + separator_space;
7998        if len > max_length {
7999            max_length = len;
8000        }
8001    }
8002    let actual_max = max_length + separator_space;
8003    // Only group when ≥3 entries fit across AND the entries aren't wildly uneven.
8004    if !(actual_max * 3 + indentation_lvl < break_length()
8005        && (total_length as f64 / actual_max as f64 > 5.0 || max_length <= 6))
8006    {
8007        return (output.to_vec(), false);
8008    }
8009    let approx_char_heights = 2.5f64;
8010    // Node divides by `output.length` here, NOT `outputLength`: the
8011    // `... N more items` tail counts toward the average even though it was
8012    // dropped from the totals, which shifts the column count of a truncated
8013    // array (`"x".repeat(200).split("")` lays out 12 columns, not 11).
8014    let average_bias = (actual_max as f64 - total_length as f64 / output.len() as f64).sqrt();
8015    let biased_max = (actual_max as f64 - 3.0 - average_bias).max(1.0);
8016    // Ideally a square grid; capped by break length, compact*4, and 15 columns.
8017    let columns = [
8018        ((approx_char_heights * biased_max * output_length as f64).sqrt() / biased_max).round()
8019            as i64,
8020        ((break_length() - indentation_lvl) as f64 / actual_max as f64).floor() as i64,
8021        inspect_compact().saturating_mul(4),
8022        15,
8023    ]
8024    .into_iter()
8025    .min()
8026    .unwrap();
8027    if columns <= 1 {
8028        return (output.to_vec(), false);
8029    }
8030    let columns = columns as usize;
8031    // The widest entry (plus separator) in each column.
8032    let mut max_line_length = vec![0usize; columns];
8033    for (i, slot) in max_line_length.iter_mut().enumerate() {
8034        let mut line_length = 0;
8035        let mut j = i;
8036        while j < output_length {
8037            if data_len[j] > line_length {
8038                line_length = data_len[j];
8039            }
8040            j += columns;
8041        }
8042        *slot = line_length + separator_space;
8043    }
8044    // Right-align (padStart) only when every element is a number/bigint.
8045    let pad_start = values.iter().all(|v| {
8046        matches!(v, Value::Int(_) | Value::Float(_))
8047            || matches!(host.get(v), Some(JsObj::BigInt(_)))
8048    });
8049    let mut tmp = Vec::new();
8050    let mut i = 0;
8051    while i < output_length {
8052        let max = (i + columns).min(output_length);
8053        let mut str_line = String::new();
8054        let mut j = i;
8055        while j < max.saturating_sub(1) {
8056            // `output[j]` has no colors here, so padding == max_line_length[col].
8057            let col = j - i;
8058            let cell = format!("{}, ", output[j]);
8059            let target = max_line_length[col];
8060            str_line.push_str(&pad_to(&cell, target, pad_start));
8061            j += 1;
8062        }
8063        // The last cell of the row: right-aligned entries pad without the ", ".
8064        if pad_start {
8065            let col = j - i;
8066            let target = max_line_length[col] - separator_space;
8067            str_line.push_str(&pad_to(&output[j], target, true));
8068        } else {
8069            str_line.push_str(&output[j]);
8070        }
8071        tmp.push(str_line);
8072        i += columns;
8073    }
8074    if has_tail {
8075        tmp.push(output[output_length].clone());
8076    }
8077    (tmp, true)
8078}
8079
8080/// Pad `s` to `width` chars: right-justified when `pad_start`, else left-justified.
8081/// (Padding is measured in chars; already ANSI-free here.)
8082fn pad_to(s: &str, width: usize, pad_start: bool) -> String {
8083    let len = s.chars().count();
8084    if len >= width {
8085        return s.to_string();
8086    }
8087    let fill = " ".repeat(width - len);
8088    if pad_start {
8089        format!("{fill}{s}")
8090    } else {
8091        format!("{s}{fill}")
8092    }
8093}
8094
8095/// Quote a string the way `util.inspect` does — a port of `strEscape` in Node's
8096/// `lib/internal/util/inspect.js`.
8097///
8098/// The quote character is chosen so the contents need as little escaping as
8099/// possible: single quotes normally, double quotes when the string contains a
8100/// `'` but no `"`, and a backtick when it contains both (and neither a backtick
8101/// nor a `${`). Only the ACTIVE quote is backslash-escaped, alongside `\` and
8102/// the C0 controls + DEL, which use Node's `meta` table (`\n`, `\t`, `\b`,
8103/// `\f`, `\r` short forms; `\x0B`, `\x1F`, `\x7F` uppercase-hex otherwise).
8104fn quote_str(s: &str) -> String {
8105    let quote = if !s.contains('\'') {
8106        '\''
8107    } else if !s.contains('"') {
8108        '"'
8109    } else if !s.contains('`') && !s.contains("${") {
8110        '`'
8111    } else {
8112        '\''
8113    };
8114    let mut out = String::with_capacity(s.len() + 2);
8115    out.push(quote);
8116    for c in s.chars() {
8117        match c {
8118            _ if c == quote => {
8119                out.push('\\');
8120                out.push(c);
8121            }
8122            '\\' => out.push_str("\\\\"),
8123            '\u{8}' => out.push_str("\\b"),
8124            '\t' => out.push_str("\\t"),
8125            '\n' => out.push_str("\\n"),
8126            '\u{c}' => out.push_str("\\f"),
8127            '\r' => out.push_str("\\r"),
8128            '\u{0}'..='\u{1f}' | '\u{7f}' => out.push_str(&format!("\\x{:02X}", c as u32)),
8129            _ => out.push(c),
8130        }
8131    }
8132    out.push(quote);
8133    out
8134}
8135
8136/// Render an object key: bare if it is a valid identifier, quoted otherwise.
8137fn fmt_key(k: &str) -> String {
8138    // node prints an OWN `__proto__` key computed-style, so it cannot be read
8139    // back as the prototype setter: `{ ['__proto__']: 5 }`.
8140    if k == "__proto__" {
8141        return "['__proto__']".to_string();
8142    }
8143    let ok = !k.is_empty()
8144        && k.chars()
8145            .next()
8146            .map(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
8147            .unwrap_or(false)
8148        && k.chars()
8149            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
8150    if ok {
8151        k.to_string()
8152    } else {
8153        quote_str(k)
8154    }
8155}
8156
8157// ── iteration ────────────────────────────────────────────────────────────────
8158
8159impl JsHost {
8160    /// Collect an iterable into a vector of values (arrays, strings, Map/Set).
8161    /// Generators and user `Symbol.iterator` objects go through `iter_all`, which
8162    /// holds no host borrow across resumes.
8163    pub fn iter_vec(&mut self, v: &Value) -> Result<Vec<Value>, String> {
8164        match self.get(v) {
8165            Some(JsObj::Array(items)) => Ok(items.clone()),
8166            Some(JsObj::Str(s)) => {
8167                let chars: Vec<String> = s.chars().map(|c| c.to_string()).collect();
8168                Ok(chars.into_iter().map(|c| self.new_str(c)).collect())
8169            }
8170            // A live array iterator, read from where its cursor stands. The
8171            // backing slots only: `iter_all` steps one through `[[Get]]` instead.
8172            Some(JsObj::Iter {
8173                idx,
8174                array: Some((arr, kind)),
8175                ..
8176            }) => {
8177                let (idx, kind) = (*idx, *kind);
8178                let items = match self.get(arr) {
8179                    Some(JsObj::Array(items)) if idx < items.len() => items[idx..].to_vec(),
8180                    _ => Vec::new(),
8181                };
8182                Ok(items
8183                    .into_iter()
8184                    .enumerate()
8185                    .map(|(n, v)| {
8186                        let key = Value::Float((idx + n) as f64);
8187                        match kind {
8188                            ArrayIterKind::Keys => key,
8189                            ArrayIterKind::Values => v,
8190                            ArrayIterKind::Entries => self.new_array(vec![key, v]),
8191                        }
8192                    })
8193                    .collect())
8194            }
8195            Some(JsObj::Iter { items, idx, .. }) => Ok(items[*idx..].to_vec()),
8196            Some(JsObj::Set { entries, .. }) => Ok(entries.values().cloned().collect()),
8197            Some(JsObj::Map { entries, .. }) => {
8198                // Map iterates as `[key, value]` pairs.
8199                let pairs: Vec<(Value, Value)> = entries.values().cloned().collect();
8200                Ok(pairs
8201                    .into_iter()
8202                    .map(|(k, v)| self.new_array(vec![k, v]))
8203                    .collect())
8204            }
8205            // A `Buffer` iterates over its BYTES and a typed array over its
8206            // ELEMENTS — both are iterable in Node. Only `@@bytes` was handled
8207            // here, so `[...buf]` worked while `[...new Uint8Array([1])]` threw
8208            // "object is not iterable", which is the same invariant holding at
8209            // one of its two sites.
8210            Some(JsObj::Object(props))
8211                if props.contains_key("@@bytes") || props.contains_key("@@buffer") =>
8212            {
8213                // Iterating a view over a DETACHED buffer throws, naming the
8214                // `values` iterator — reading its elements answers zero length,
8215                // but spreading it is a method call and does not.
8216                if crate::stdlib::typedarray::view_detached_h(self, v) {
8217                    return Err(crate::stdlib::typedarray::detached_error(
8218                        "%TypedArray%.prototype",
8219                        "values",
8220                        false,
8221                    ));
8222                }
8223                Ok(crate::stdlib::typedarray::elems_mut_host(self, v))
8224            }
8225            // V8 names the VALUE, not its type: `[...5]` is `5 is not iterable`,
8226            // `[...{}]` is `{} is not iterable`. Reporting `typeof` instead
8227            // produced `number is not iterable`, which no engine emits.
8228            _ => {
8229                let shown = self.inspect(v);
8230                Err(type_error(&format!("{shown} is not iterable")))
8231            }
8232        }
8233    }
8234
8235    /// Enumerable string keys of an object/array (for `for-in`). Internal
8236    /// symbol-keyed props (`@@…`) are not enumerable.
8237    /// `for-in` visits own enumerable keys, then every *inherited* enumerable key
8238    /// not already seen, walking the whole prototype chain. Class methods and the
8239    /// builtin prototypes are non-enumerable, so in practice this only surfaces
8240    /// keys a script put on a prototype itself (`F.prototype.y = 2`) — but that
8241    /// is exactly the constructor-function idiom older packages are written in.
8242    pub fn enum_keys(&mut self, v: &Value) -> Vec<Value> {
8243        let mut keys = self.own_enum_key_names(v);
8244        let mut cur = self.proto_of(v);
8245        let mut hops = 0;
8246        while let Some(p) = cur {
8247            // A cyclic or pathologically deep chain must not hang the loop.
8248            hops += 1;
8249            if hops > 100 || matches!(p, Value::Undef) || self.is_null(&p) {
8250                break;
8251            }
8252            for k in self.own_enum_key_names(&p) {
8253                if !keys.contains(&k) {
8254                    keys.push(k);
8255                }
8256            }
8257            cur = self.proto_of(&p);
8258        }
8259        keys.into_iter().map(|k| self.new_str(k)).collect()
8260    }
8261
8262    /// The own *enumerable* string keys of `v`, in property order — the single
8263    /// source of truth behind `for-in`, `Object.keys`/`values`/`entries`,
8264    /// object spread, `Object.assign` and `JSON.stringify`. Internal slots
8265    /// (`@@…`), private fields (`#…`) and anything marked non-enumerable via
8266    /// `prop_attrs` are excluded.
8267    pub fn own_enum_key_names(&self, v: &Value) -> Vec<String> {
8268        self.own_key_names(v, true)
8269    }
8270
8271    /// Own string keys of `v` in insertion order. `enum_only` drops the
8272    /// non-enumerable ones (`Object.keys`); otherwise every own key is reported
8273    /// (`getOwnPropertyNames`/`Reflect.ownKeys`).
8274    pub fn own_key_names(&self, v: &Value, enum_only: bool) -> Vec<String> {
8275        let mut keys = self.own_enum_data_keys(v, enum_only);
8276        // A global a SCRIPT created (`x = 1` with no declaration) is an own
8277        // ENUMERABLE property of the global object, but lives in the globals map
8278        // rather than in its property map — so no listing saw it, while
8279        // `globalThis.x` read it back and its descriptor called it enumerable.
8280        //
8281        // Node's own enumerable globals (`setTimeout`, `structuredClone`, …) come
8282        // FIRST, in bootstrap order, and are not in either map. Two kinds of
8283        // name in the globals map are not properties of the global object at
8284        // all: the CommonJS wrapper's parameters and the compiler's `.`-prefixed
8285        // temporaries (`.forin0`), which no identifier can spell.
8286        if self.is_global_object(v) {
8287            // The globals map holds every script-created global in CREATION
8288            // order (`globalThis.y = 1` writes it as well as the property map),
8289            // so it is walked before the property map's own order.
8290            let mut listed: Vec<String> = crate::builtins::enumerable_lazy_globals()
8291                .map(str::to_string)
8292                .collect();
8293            for k in self.globals.keys() {
8294                if crate::builtins::is_script_global_name(k)
8295                    && (!enum_only || self.prop_attrs(v, k).enumerable)
8296                    && !listed.contains(k)
8297                {
8298                    listed.push(k.clone());
8299                }
8300            }
8301            for k in keys.drain(..) {
8302                if !listed.contains(&k) {
8303                    listed.push(k);
8304                }
8305            }
8306            keys = listed;
8307        }
8308        // A RegExp's `lastIndex` is a SYNTHESIZED own property — it lives in the
8309        // `RegExpObj` struct, not a property map — so nothing above can list it.
8310        // Non-enumerable, so only `getOwnPropertyNames` sees it.
8311        if !enum_only && matches!(self.get(v), Some(JsObj::RegExp(_))) {
8312            keys.push("lastIndex".to_string());
8313        }
8314        // An accessor defined before its object had any ordering marker (a class
8315        // prototype accessor, say) still has to appear.
8316        for k in self.own_accessor_keys(v) {
8317            if (!enum_only || self.prop_attrs(v, &k).enumerable) && !keys.contains(&k) {
8318                keys.push(k);
8319            }
8320        }
8321        // Only STRING keys belong here. An accessor resolved from its ordering
8322        // marker or from the accessor table may be symbol-keyed, and listing it
8323        // leaked the internal spelling: `Object.getOwnPropertyNames` of
8324        // `{ get [Symbol.split]() {} }` reported `'@@split'`.
8325        keys.retain(|k| !k.starts_with("@@") && !k.starts_with('#'));
8326        // OrdinaryOwnPropertyKeys (10.1.11.1): every array-index key first, in
8327        // ascending numeric order, then the other string keys in creation
8328        // order. A function's or class's own keys (`static 2() {}`,
8329        // `f[0] = 1`) and a class prototype's methods kept creation order. The
8330        // partition is stable, so a listing that is already ordered (an
8331        // array's indices, then `length`) comes through unchanged.
8332        let (mut ordered, rest): (Vec<String>, Vec<String>) =
8333            keys.into_iter().partition(|k| array_index(k).is_some());
8334        ordered.sort_by_key(|k| array_index(k));
8335        ordered.extend(rest);
8336        ordered
8337    }
8338
8339    /// The keys that own a slot in the object's property map, in insertion
8340    /// order, resolving accessor ordering markers back to their real key.
8341    /// Every global a SCRIPT created, in creation order — the own enumerable
8342    /// keys of the global object that live in the globals map rather than in
8343    /// its property map. `x = 1` with no declaration makes one, and
8344    /// `Object.keys(globalThis)` reports it in node.
8345    pub fn script_global_names(&self) -> Vec<String> {
8346        self.globals.keys().cloned().collect()
8347    }
8348    /// Drop a global a script created. Reports whether it was there.
8349    pub fn remove_global(&mut self, name: &str) -> bool {
8350        self.globals.shift_remove(name).is_some()
8351    }
8352    fn own_enum_data_keys(&self, v: &Value, enum_only: bool) -> Vec<String> {
8353        match self.get(v) {
8354            // A `Buffer` is an index-keyed exotic: its own enumerable keys are
8355            // `"0".."len-1"` (the bytes live in the hidden `@@bytes` slot), never
8356            // the `length`/`byteLength` view metadata, which V8 keeps on the
8357            // prototype chain or as non-enumerable own slots.
8358            // A `Buffer` and every other typed array are index-keyed exotics:
8359            // their own enumerable keys are `"0".."len-1"` (the elements live in
8360            // a hidden slot), never the `length`/`byteLength` view metadata,
8361            // which V8 keeps on the prototype chain or as non-enumerable own
8362            // slots. Only `Buffer` had this arm, so `Object.keys(u8)` was empty
8363            // and `JSON.stringify(u8)` was `{}` where node gives
8364            // `{"0":10,"1":9}` — `hasOwnProperty(0)` already answered true, so
8365            // the two views of the same question disagreed.
8366            Some(JsObj::Object(props))
8367                if matches!(
8368                    props.get("@@native").map(|t| self.str_of(t)).as_deref(),
8369                    Some("Buffer") | Some("TypedArray")
8370                ) =>
8371            {
8372                // A view over a DETACHED buffer has no index properties at all:
8373                // its own `length` still holds the old count, so reading that
8374                // back left `Object.keys` listing eight names over no bytes.
8375                if crate::stdlib::typedarray::view_detached_h(self, v) {
8376                    return Vec::new();
8377                }
8378                // A Buffer counts its window onto its store; every other view
8379                // reports the element count of its window onto the ArrayBuffer.
8380                let n = if props.contains_key("@@bytes") {
8381                    crate::stdlib::buffer::window_h(self, props).1
8382                } else {
8383                    props
8384                        .get("length")
8385                        .map(|l| self.to_number(l))
8386                        .unwrap_or(0.0) as usize
8387                };
8388                (0..n).map(|i| i.to_string()).collect()
8389            }
8390            Some(JsObj::Object(props)) => props
8391                .keys()
8392                .filter_map(|k| match k.strip_prefix(ORD_MARKER) {
8393                    Some(real) => Some(real.to_string()),
8394                    None if !k.starts_with("@@") && !k.starts_with('#') => Some(k.clone()),
8395                    None => None,
8396                })
8397                .filter(|k| !enum_only || self.prop_attrs(v, k).enumerable)
8398                .collect(),
8399            // A STRING is an index-keyed exotic too (10.4.3): its own keys are
8400            // its UTF-16 code-unit indices, plus the non-enumerable `length`.
8401            // Without this arm every whole-object view of a string primitive was
8402            // empty — `for (const k in 'ab')` iterated nothing, `Object.keys`
8403            // and `Object.assign({}, 'ab')` reported `{}` — while `'ab'[0]` and
8404            // `'ab'.length` answered normally, so the two views disagreed. The
8405            // spread form `{...'ab'}` went through a different path and was
8406            // already right, which is what made the gap easy to miss.
8407            Some(JsObj::Str(s)) => {
8408                let mut keys: Vec<String> =
8409                    (0..crate::utf16::len(s)).map(|i| i.to_string()).collect();
8410                if !enum_only {
8411                    keys.push("length".into());
8412                }
8413                keys
8414            }
8415            // `OrdinaryOwnPropertyKeys` on an array exotic: the integer indices
8416            // ascending, then the exotic non-enumerable `length`, then the
8417            // ordinary string keys in insertion order. Those ordinary keys have
8418            // no property map to live in — a `str.match()` result's
8419            // `index`/`input`/`groups` and any user-assigned `arr.foo` are kept
8420            // in the fn-prop side table — so they are read back from there.
8421            Some(JsObj::Array(items)) => {
8422                // An ELIDED element is not an own property at all, so it
8423                // contributes no key — the difference behind
8424                // `Object.keys([1,,3])` being `['0','2']`.
8425                let mut keys: Vec<String> = (0..items.len())
8426                    .filter(|i| !self.is_hole(v, *i))
8427                    .map(|i| i.to_string())
8428                    .collect();
8429                if !enum_only {
8430                    keys.push("length".into());
8431                }
8432                keys.extend(self.fn_prop_keys(v).into_iter().filter(|k| {
8433                    !k.starts_with("@@")
8434                        && !k.starts_with('#')
8435                        && (!enum_only || self.prop_attrs(v, k).enumerable)
8436                }));
8437                keys
8438            }
8439            // A function/class keeps every own property in the side table. Its
8440            // exotic `name`/`length`/`prototype` and its class methods are all
8441            // non-enumerable, so under `enum_only` what is left is exactly what
8442            // a script assigned; `getOwnPropertyNames` reports the exotics too,
8443            // in V8's order (`length`, `name`, `prototype`, then the rest).
8444            Some(JsObj::Func(_)) | Some(JsObj::Class(_)) | Some(JsObj::BoundFunc { .. }) => {
8445                let mut keys: Vec<String> = Vec::new();
8446                if !enum_only {
8447                    if !self.fn_intrinsic_deleted(v, "length") {
8448                        keys.push("length".into());
8449                    }
8450                    if !self.fn_intrinsic_deleted(v, "name") {
8451                        keys.push("name".into());
8452                    }
8453                    if self.owns_prototype(v) {
8454                        keys.push("prototype".into());
8455                    }
8456                }
8457                let rest: Vec<String> = self
8458                    .fn_prop_keys(v)
8459                    .into_iter()
8460                    // An accessor's ordering marker resolves back to its real
8461                    // key, so a static getter enumerates where it was declared.
8462                    .filter_map(|k| match k.strip_prefix(ORD_MARKER) {
8463                        Some(real) => Some(real.to_string()),
8464                        None if !k.starts_with("@@") && !k.starts_with('#') => Some(k),
8465                        None => None,
8466                    })
8467                    .filter(|k| {
8468                        !keys.contains(k) && (!enum_only || self.prop_attrs(v, k).enumerable)
8469                    })
8470                    .collect();
8471                keys.extend(rest);
8472                keys
8473            }
8474            // A builtin namespace (`require('buffer')`, `Buffer`) enumerates the
8475            // members node-js implements, so a package that copies a namespace
8476            // key-by-key gets the working set instead of an empty object.
8477            Some(JsObj::Builtin(ns))
8478                if enum_only && !crate::stdlib::namespace_statics_enumerable(ns) =>
8479            {
8480                Vec::new()
8481            }
8482            Some(JsObj::Builtin(ns)) => crate::stdlib::namespace_keys(&ns.clone()),
8483            // A `Map`/`Set`/`Promise`/`RegExp`/generator holds only its internal
8484            // slots, so what a script assigned lives in the side table — and is
8485            // just as much an own property as an object's.
8486            Some(_) => self
8487                .fn_prop_keys(v)
8488                .into_iter()
8489                .filter(|k| {
8490                    !k.starts_with("@@")
8491                        && !k.starts_with('#')
8492                        && (!enum_only || self.prop_attrs(v, k).enumerable)
8493                })
8494                .collect(),
8495            _ => Vec::new(),
8496        }
8497    }
8498
8499    /// The own enumerable `(key, value)` pairs of `v`. Buffer index keys resolve
8500    /// through the byte store; everything else reads the property map. Own
8501    /// accessor keys come back as `Undef` here — `own_enum_entries_deep` runs
8502    /// their getters, which cannot happen under the host borrow.
8503    pub fn own_enum_entries(&self, v: &Value) -> Vec<(String, Value)> {
8504        self.own_enum_key_names(v)
8505            .into_iter()
8506            .map(|k| {
8507                let val = match self.get(v) {
8508                    // A Buffer's index keys read out of the hidden `@@bytes`
8509                    // array; resolve inline rather than through
8510                    // `buffer::byte_get`, which would re-borrow the host.
8511                    Some(JsObj::Object(props)) => props.get(&k).cloned().unwrap_or_else(|| {
8512                        // A Buffer's elements live in `@@bytes` and every
8513                        // other typed array's in `@@elems`; both are index
8514                        // keys with no entry in the property map.
8515                        match k.parse::<usize>() {
8516                            Ok(i) => crate::stdlib::typedarray::elems_with_host(self, v)
8517                                .get(i)
8518                                .cloned()
8519                                .unwrap_or(Value::Undef),
8520                            _ => Value::Undef,
8521                        }
8522                    }),
8523                    // A Map/Set/Promise/RegExp/generator keeps every own
8524                    // property in the side table.
8525                    Some(
8526                        JsObj::Map { .. }
8527                        | JsObj::Set { .. }
8528                        | JsObj::Promise { .. }
8529                        | JsObj::RegExp(_)
8530                        | JsObj::Generator { .. }
8531                        | JsObj::Symbol { .. }
8532                        | JsObj::BigInt(_)
8533                        | JsObj::Iter { .. },
8534                    ) => self.fn_prop(v, &k).unwrap_or(Value::Undef),
8535                    // An index reads the element; any other own key (`foo`,
8536                    // a match result's `index`) lives in the side table.
8537                    Some(JsObj::Array(items)) => k
8538                        .parse::<usize>()
8539                        .ok()
8540                        .and_then(|i| items.get(i).cloned())
8541                        .or_else(|| self.fn_prop(v, &k))
8542                        .unwrap_or(Value::Undef),
8543                    Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => {
8544                        self.fn_prop(v, &k).unwrap_or(Value::Undef)
8545                    }
8546                    _ => Value::Undef,
8547                };
8548                (k, val)
8549            })
8550            .collect()
8551    }
8552}
8553
8554/// The own enumerable `(key, value)` pairs of `v` with every enumerable own
8555/// accessor's getter invoked — the observable shape `Object.values`,
8556/// `Object.entries`, object spread and `JSON.stringify` all need. Must be called
8557/// outside a `with_host` borrow because a getter re-enters the host.
8558pub fn own_enum_entries_deep(v: &Value) -> Result<Vec<(String, Value)>, String> {
8559    // A Proxy has no property map at all: its own enumerable entries come from
8560    // the `ownKeys` + `getOwnPropertyDescriptor` + `get` traps. A trap that
8561    // throws surfaces as an empty result here because this signature is
8562    // infallible; the callers that MUST propagate a trap throw (`Object.keys`
8563    // and friends) go through `builtins::object_keys`, which does.
8564    if with_host(|h| h.kind_of(v)) == Some(ObjKind::Proxy) {
8565        return crate::proxy::own_enum_entries(v);
8566    }
8567    // A builtin namespace (`require('path')`, `Buffer`) has no property map at
8568    // all: its members are resolved on demand by `namespace_property`, which
8569    // re-enters the host and so cannot run inside `own_enum_entries`'s borrow.
8570    // Without this, spread and `Object.assign` copied the namespace's KEYS with
8571    // `undefined` for every value — measured against node v26.7.0,
8572    // `{...require('path')}.join` was `undefined` here and a function there,
8573    // while `Object.entries(require('path'))` (which resolves through
8574    // `builtins`, not through this borrow) was already correct. Two enumeration
8575    // paths, one of them silently value-less.
8576    if let Some(ns) = with_host(|h| match h.get(v) {
8577        Some(JsObj::Builtin(ns)) => Some(ns.clone()),
8578        _ => None,
8579    }) {
8580        return Ok(with_host(|h| h.own_enum_key_names(v))
8581            .into_iter()
8582            .map(|k| {
8583                let val = crate::builtins::namespace_property(&ns, &k);
8584                (k, val)
8585            })
8586            .collect());
8587    }
8588    // A string primitive's own entries are its code units. `own_enum_entries`
8589    // cannot build them: allocating the one-character string for each index
8590    // needs `&mut` host access, and it runs under a shared borrow.
8591    if let Some(sv) = with_host(|h| match h.get(v) {
8592        Some(JsObj::Str(s)) => Some(s.clone()),
8593        _ => None,
8594    }) {
8595        let units = crate::utf16::Units::of(&sv);
8596        return Ok(with_host(|h| {
8597            (0..units.len())
8598                .filter_map(|i| units.unit_str(i).map(|c| (i.to_string(), h.new_str(c))))
8599                .collect()
8600        }));
8601    }
8602    // The global object's enumerable builtins and script-created globals live
8603    // outside its property map, so each value is a full property READ —
8604    // `Object.entries(globalThis)` paired every key with `undefined`.
8605    if with_host(|h| h.is_global_object(v)) {
8606        let keys = with_host(|h| h.own_enum_key_names(v));
8607        let mut out = Vec::with_capacity(keys.len());
8608        for k in keys {
8609            let val = crate::builtins::get_property(v, &k)?;
8610            out.push((k, val));
8611        }
8612        return Ok(out);
8613    }
8614    let accessor_keys: Vec<String> = with_host(|h| {
8615        h.own_accessor_keys(v)
8616            .into_iter()
8617            .filter(|k| h.prop_attrs(v, k).enumerable)
8618            .collect()
8619    });
8620    let entries = with_host(|h| h.own_enum_entries(v));
8621    // A getter that THROWS propagates: `Object.entries`, `Object.assign`,
8622    // object spread and `JSON.stringify` all read through here, and every one
8623    // of them swallowed the exception and reported the property as absent (or
8624    // as `null`) instead.
8625    let mut out = Vec::with_capacity(entries.len());
8626    for (k, val) in entries {
8627        if accessor_keys.contains(&k) {
8628            out.push((k.clone(), get_prop_chain(v, &k)?));
8629        } else {
8630            out.push((k, val));
8631        }
8632    }
8633    Ok(out)
8634}
8635
8636// ── function invocation ──────────────────────────────────────────────────────
8637
8638/// Marshal a JS call argument into a native fusevm `Value` for `rust { }` FFI.
8639/// JS strings ride as `Value::Obj(JsObj::Str)` heap handles, which fusevm's
8640/// marshaller cannot read (it calls `Value::to_str`, which returns `"(obj:N)"`
8641/// for a handle); rewrite them to a native `Value::Str`. Numbers are already
8642/// native `Value::Int`/`Value::Float`, so they pass through (fusevm coerces
8643/// Float→i64/f64 per the export signature).
8644fn marshal_ffi_arg(v: &Value) -> Value {
8645    match v {
8646        Value::Obj(_) => match with_host(|h| h.as_str(v)) {
8647            Some(s) => Value::str(s),
8648            None => v.clone(),
8649        },
8650        _ => v.clone(),
8651    }
8652}
8653
8654/// Resolve a bare name and call it (`f(args)`, `parseInt(args)`).
8655pub fn call_named(name: &str, args: Vec<Value>) -> Result<Value, String> {
8656    // Inline Rust FFI: the `rust { ... }` desugar emits `__rust_compile(b64,
8657    // line)`; compile + register the block's exported functions, returning JS
8658    // `undefined` (`Value::Undef`).
8659    if name == "__rust_compile" {
8660        let b64 = args
8661            .first()
8662            .map(|v| with_host(|h| h.str_of(v)))
8663            .unwrap_or_default();
8664        return fusevm::ffi::compile_and_register(&b64).map(|_| Value::Undef);
8665    }
8666    if let Some(v) = with_host(|h| h.read_name(name)) {
8667        return invoke(&v, args, None);
8668    }
8669    // A DIRECT eval — the literal `eval(src)` call form — is the ONLY one that
8670    // evaluates in the CALLER's scope; `(0, eval)(src)`, `const e = eval; e(src)`
8671    // and `[eval][0](src)` all reach the same function value but are INDIRECT
8672    // evals and evaluate in the global scope (ECMA-262 19.2.1.1 `PerformEval`).
8673    // This is the one place the two forms are distinguishable without a compiler
8674    // change: `call_named` is reached only from `ops::CALL`, which the compiler
8675    // emits exclusively for a bare-identifier callee, while every value-call form
8676    // goes through `invoke` → `call_builtin_function`. The `read_name` miss above
8677    // has already established that `eval` is not shadowed by a user binding.
8678    if name == "eval" {
8679        return crate::builtins::eval_source(args.first(), true);
8680    }
8681    if crate::builtins::is_known_builtin(name) {
8682        return crate::builtins::call_builtin_function(name, args);
8683    }
8684    // A `rust { ... }` block's exported functions are callable by bareword.
8685    // Reached only after user names/globals and builtins all miss, so JS code
8686    // always wins; the registry membership check keeps this off the hot path.
8687    if fusevm::ffi::is_registered(name) {
8688        let margs: Vec<Value> = args.iter().map(marshal_ffi_arg).collect();
8689        if let Some(r) = fusevm::ffi::try_call(name, &margs) {
8690            return r;
8691        }
8692    }
8693    // A lazily bound global that is not itself a builtin key (`SubtleCrypto`
8694    // reads as the class kept under another key): call what the READ gives,
8695    // so `SubtleCrypto()` and `const S = SubtleCrypto; S()` agree.
8696    if let Some(v) = crate::builtins::global_binding(name) {
8697        return invoke(&v, args, None);
8698    }
8699    Err(ref_error(name))
8700}
8701
8702thread_local! {
8703    /// The constructor a builtin STATIC is currently being invoked on.
8704    ///
8705    /// `A.from(x)` on `class A extends Array` re-dispatches against the `Array`
8706    /// builtin, which is reached by NAME and so cannot see `A`. The species
8707    /// rules need it: `Array.from`, `Array.of` and every `Promise` static build
8708    /// their result with `this`, so on a subclass they must construct through
8709    /// it. A stack, since one static can call another.
8710    static STATIC_THIS: std::cell::RefCell<Vec<Value>> =
8711        const { std::cell::RefCell::new(Vec::new()) };
8712}
8713
8714/// The receiver check every `Promise` static runs before anything else: a
8715/// non-object is refused with V8's per-method wording, an object that is not a
8716/// constructor with `<value> is not a constructor`.
8717fn promise_static_receiver(name: &str, recv: &Value) -> Result<(), String> {
8718    let is_object = with_host(|h| !is_primitive(h, recv) && !h.is_nullish(recv));
8719    if !is_object {
8720        let msg = match name {
8721            "Promise.resolve" => "PromiseResolve called on non-object".to_string(),
8722            "Promise.reject" => "PromiseReject called on non-object".to_string(),
8723            _ => format!("{name} called on non-object"),
8724        };
8725        return Err(type_error(&msg));
8726    }
8727    if !with_host(|h| is_callable(h, recv)) {
8728        let shown = crate::builtins::no_side_effects_string_pub(recv);
8729        return Err(type_error(&format!("{shown} is not a constructor")));
8730    }
8731    Ok(())
8732}
8733
8734/// Run `f` with `recv` recorded as the receiver of a builtin static call.
8735pub fn with_static_this<R>(recv: &Value, f: impl FnOnce() -> R) -> R {
8736    STATIC_THIS.with(|s| s.borrow_mut().push(recv.clone()));
8737    let out = f();
8738    STATIC_THIS.with(|s| {
8739        s.borrow_mut().pop();
8740    });
8741    out
8742}
8743
8744/// The constructor the running builtin static was called on, if it was reached
8745/// through a subclass rather than directly.
8746pub fn current_static_this() -> Option<Value> {
8747    STATIC_THIS.with(|s| s.borrow().last().cloned())
8748}
8749
8750/// The call half of `proxy.m(...)` once `Get(proxy, "m")` has produced the
8751/// callable `f`: the method runs with the PROXY as `this`. Split out so a caller
8752/// that has already done the `Get` (ToPrimitive's `OrdinaryToPrimitive`) does not
8753/// read the property a second time through the `get` trap.
8754pub fn call_proxy_method(
8755    recv: &Value,
8756    name: &str,
8757    f: Value,
8758    args: Vec<Value>,
8759) -> Result<Value, String> {
8760    // `Function.prototype.call`/`apply`/`bind`/`toString` and the REFLECTIVE
8761    // `Object.prototype` methods are generic over `this`. node-js models each
8762    // as a thunk BOUND to the object it was read off — through a proxy, that
8763    // is the target — so invoking the thunk answers for the target and skips
8764    // the traps entirely: `pf.call(1, 2)` never reached the `apply` trap and
8765    // `p.hasOwnProperty(k)` never reached the descriptor trap. Re-dispatch
8766    // those against the PROXY, which is the `this` the real method receives.
8767    //
8768    // `toString`/`valueOf`/`toLocaleString` are deliberately NOT re-dispatched
8769    // for a non-callable proxy: they resolve by the TARGET's kind (a proxy of
8770    // an array stringifies `1,2` through `Array.prototype.toString`, not
8771    // `[object Object]`), which the bound thunk already gets right.
8772    if with_host(|h| matches!(h.get(&f), Some(JsObj::BoundMethod { .. }))) {
8773        if with_host(|h| is_callable(h, recv)) {
8774            if let Some(r) = crate::builtins::function_builtin_method(recv, name, &args)? {
8775                return Ok(r);
8776            }
8777        }
8778        if matches!(
8779            name,
8780            "hasOwnProperty" | "propertyIsEnumerable" | "isPrototypeOf"
8781        ) {
8782            return crate::builtins::object_builtin_method(recv, name, args);
8783        }
8784        // The three above resolve by the TARGET's kind, and the thunk is
8785        // already bound to the target — so it must be invoked WITHOUT a
8786        // receiver override. Passing the proxy as `this` made the
8787        // `BoundMethod` arm of `invoke` prefer it over its own receiver and
8788        // call straight back into this branch, so `String(new Proxy({}, {}))`
8789        // recursed until the stack overflowed and the process aborted.
8790        if matches!(name, "toString" | "valueOf" | "toLocaleString") {
8791            return invoke(&f, args, None);
8792        }
8793    }
8794    invoke(&f, args, Some(recv.clone()))
8795}
8796
8797/// `recv.name(args)`.
8798pub fn call_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
8799    // `undefined.foo()` is a `[[Get]]` and THEN a call (13.3.6 EvaluateCall), so
8800    // the failure is the property read, not the call: node reports
8801    // `Cannot read properties of undefined (reading 'foo')`. node-js ran the
8802    // whole method dispatch against the nullish receiver, found nothing, and
8803    // reported `undefined.foo is not a function` — the wrong error class of
8804    // message for the single most common runtime fault in JS, and one that
8805    // points at the callee instead of at the base that was nullish.
8806    if with_host(|h| h.is_nullish(recv)) {
8807        return Err(type_error(&format!(
8808            "Cannot read properties of {} (reading '{name}')",
8809            with_host(|h| h.str_of(recv))
8810        )));
8811    }
8812    // `this.#m(…)` is a `[[PrivateGet]]` followed by a call, so the brand check
8813    // comes first: an unbranded receiver throws here rather than reporting the
8814    // method missing. Only a `#`-prefixed name pays the extra probe.
8815    if name.starts_with('#') && !with_host(|h| h.has_private(recv, name)) {
8816        return Err(crate::builtins::private_brand_message(name, false));
8817    }
8818    // `proxy.m(…)` is 13.3.6 `EvaluateCall`: `Get(proxy, "m")` — through the
8819    // `get` trap — then a call with the PROXY as `this`. The `lookup_*` shortcuts
8820    // below all read a property map a proxy does not have.
8821    if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
8822        let f = crate::builtins::get_property(recv, name)?;
8823        if !with_host(|h| is_callable(h, &f)) {
8824            return Err(type_error(&format!("{name} is not a function")));
8825        }
8826        return call_proxy_method(recv, name, f, args);
8827    }
8828    // Namespace builtins (`console`, `Math`, `JSON`, ...): dispatch by qualified
8829    // name.
8830    if let Some(ns) = with_host(|h| match h.get(recv) {
8831        Some(JsObj::Builtin(ns)) => Some(ns.clone()),
8832        _ => None,
8833    }) {
8834        // `stream/web`'s members are the `webstreams.js` port's functions, not
8835        // dispatch entries: call what the read gives.
8836        if ns == "stream/web" && crate::stdlib::stream_web::is_class(name) {
8837            let member = crate::stdlib::stream_web::constant(name).unwrap_or(Value::Undef);
8838            return invoke(&member, args, Some(recv.clone()));
8839        }
8840        let qualified = format!("{ns}.{name}");
8841        if crate::builtins::is_known_builtin(&qualified) {
8842            return crate::builtins::call_builtin_function(&qualified, args);
8843        }
8844        // A member that is not itself a dispatch entry but reads back as a
8845        // function — `Function.prototype`, the one callable prototype — is
8846        // called as what it reads as, with the namespace as `this`.
8847        let member = crate::builtins::namespace_property(&ns, name);
8848        if with_host(|h| is_callable(h, &member)) {
8849            return invoke(&member, args, Some(recv.clone()));
8850        }
8851    }
8852    // Object / instance: an accessor getter that yields a function, an own or
8853    // inherited method (class methods live on the prototype chain), then an
8854    // Object.prototype builtin (hasOwnProperty …). Resolve via `lookup_*`
8855    // directly — NOT get_property — so the Object.prototype-builtin fallback
8856    // never routes back through a BoundMethod and recurses.
8857    if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Object) {
8858        // A native stdlib instance (`Buffer`/crypto `Hash`/`EventEmitter`/`URL`/
8859        // fs `Stats`/http `ServerResponse`…) carries a hidden `@@native` tag.
8860        // A user-added or reparented-prototype method takes precedence over the
8861        // native dispatcher — matching JS resolution order (own → prototype
8862        // chain). This is what lets Express work: it does
8863        // `Object.setPrototypeOf(res, app.response)` and calls `res.send(...)`,
8864        // where `send` is a plain function on the reparented prototype. Native
8865        // instance methods (`res.end`/`write`/…) are NOT stored as plain
8866        // function properties, so `lookup_chain` misses them and we fall through
8867        // to `instance_call` for the real native behavior.
8868        if let Some(tag) = crate::stdlib::native_tag(recv) {
8869            if let Some(f) = with_host(|h| lookup_chain(h, recv, name)) {
8870                if with_host(|h| is_callable(h, &f)) {
8871                    return invoke(&f, args, Some(recv.clone()));
8872                }
8873            }
8874            // `Object.prototype` methods reach a native instance too — a Buffer
8875            // inherits `hasOwnProperty`/`isPrototypeOf` through its prototype
8876            // chain, and the native dispatcher has no entry for them.
8877            if crate::builtins::is_object_builtin_method(name)
8878                && !crate::stdlib::instance_has_method(&tag, name)
8879            {
8880                return crate::builtins::object_builtin_method(recv, name, args);
8881            }
8882            return crate::stdlib::instance_call(&tag, recv, name, args);
8883        }
8884        // A primitive wrapper forwards to the primitive's method table, the
8885        // same way a native instance forwards to its tag's. A user method on
8886        // the wrapper or anywhere on its chain still wins first.
8887        if let Some(prim) = crate::builtins::wrapped_primitive(recv) {
8888            if let Some(f) = with_host(|h| lookup_chain(h, recv, name)) {
8889                if with_host(|h| is_callable(h, &f)) {
8890                    return invoke(&f, args, Some(recv.clone()));
8891                }
8892            }
8893            // The reflective `Object.prototype` methods answer for the WRAPPER
8894            // — `w.hasOwnProperty("0")` asks about the wrapper's own index
8895            // properties, not about the string.
8896            if crate::builtins::is_object_builtin_method(name) {
8897                return crate::builtins::object_builtin_method(recv, name, args);
8898            }
8899            return call_method(&prim, name, args);
8900        }
8901        if let Some((Some(getter), _)) = with_host(|h| lookup_accessor(h, recv, name)) {
8902            let f = invoke(&getter, Vec::new(), Some(recv.clone()))?;
8903            if with_host(|h| is_callable(h, &f)) {
8904                return invoke(&f, args, Some(recv.clone()));
8905            }
8906        }
8907        // A Proxy in the prototype chain serves the method through its `get`
8908        // trap. `lookup_chain` below reads property maps, which a proxy has none
8909        // of, so without this `child.m()` on `Object.create(proxy)` reported
8910        // "m is not a function" even though `child.m` already read correctly.
8911        if crate::builtins::proxy_proto_link(recv, name).is_some() {
8912            let f = crate::builtins::get_property(recv, name)?;
8913            if !with_host(|h| is_callable(h, &f)) {
8914                return Err(type_error(&format!("{name} is not a function")));
8915            }
8916            return invoke(&f, args, Some(recv.clone()));
8917        }
8918        if let Some(f) = with_host(|h| lookup_chain(h, recv, name)) {
8919            if with_host(|h| is_callable(h, &f)) {
8920                return invoke(&f, args, Some(recv.clone()));
8921            }
8922            return Err(type_error(&format!("{name} is not a function")));
8923        }
8924        // A method patched onto `Object.prototype`. `lookup_chain` cannot find
8925        // it: a plain object is not LINKED to the intrinsic prototype object,
8926        // its `Object.prototype` members are synthesized instead. So
8927        // `Object.prototype.tap = f; ({}).tap()` reported "is not a function"
8928        // while `({}).tap` already read back as `f`.
8929        if let Some(f) = crate::builtins::inherited_builtin_static(recv, name) {
8930            if with_host(|h| is_callable(h, &f)) {
8931                return invoke(&f, args, Some(recv.clone()));
8932            }
8933        }
8934        // A method from an intrinsic prototype this object's CHAIN passes
8935        // through — `Object.create(Array.prototype).push(1)`. The read already
8936        // resolves it through the same owner oracle; dispatch reported "is not
8937        // a function", the read and the call disagreeing once more.
8938        if let Some(owner) = crate::builtins::inherited_method_owner_pub(recv, name) {
8939            if owner != "Object" {
8940                return crate::builtins::proto_method(recv, &format!("{owner}:{name}"), args);
8941            }
8942        }
8943        if crate::builtins::is_object_builtin_method(name) {
8944            return crate::builtins::object_builtin_method(recv, name, args);
8945        }
8946        if name == "constructor" {
8947            if let Some(r) = call_default_ctor(recv, &args) {
8948                return r;
8949            }
8950        }
8951        // The global object serves every builtin global as a property
8952        // (`globalThis.parseInt`, `globalThis["Map"]`) through the property
8953        // read, not through the chain walk above; `[[Get]]` then call is the
8954        // definition of a method call, so use it before giving up.
8955        if with_host(|h| h.is_global_object(recv)) {
8956            let f = crate::builtins::get_property(recv, name)?;
8957            if with_host(|h| is_callable(h, &f)) {
8958                return invoke(&f, args, Some(recv.clone()));
8959            }
8960        }
8961        return Err(type_error(&format!("{name} is not a function")));
8962    }
8963    // Function value methods: call / apply / bind, then any static method stored
8964    // on the function object.
8965    if matches!(
8966        with_host(|h| h.kind_of(recv)),
8967        Some(ObjKind::Func)
8968            | Some(ObjKind::Class)
8969            | Some(ObjKind::BoundFunc)
8970            | Some(ObjKind::BoundMethod)
8971            | Some(ObjKind::Builtin)
8972    ) {
8973        // A static method (own or inherited): `this` is the constructor (`recv`).
8974        // It is looked up BEFORE `Function.prototype`'s `call`/`apply`/`bind`/
8975        // `toString`, since an own property shadows an inherited one — `static
8976        // call(o) {}` is the class's, not `Function.prototype.call`.
8977        let stat = if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Class) {
8978            with_host(|h| h.class_static(recv, name))
8979        } else {
8980            with_host(|h| h.fn_prop(recv, name))
8981        };
8982        if let Some(f) = stat {
8983            if with_host(|h| is_callable(h, &f)) {
8984                return invoke(&f, args, Some(recv.clone()));
8985            }
8986        }
8987        if let Some(r) = crate::builtins::function_builtin_method(recv, name, &args)? {
8988            return Ok(r);
8989        }
8990        // `class_static` only walks user-class `extends` links, so a chain that
8991        // bottoms out in a BUILTIN constructor (`class D extends Array {}`)
8992        // could not reach that builtin's statics: `D.from([1,2])` threw
8993        // "from is not a function" even though `typeof D.from` said `function`.
8994        // Re-dispatch the call against that ancestor, which is what reaches a
8995        // builtin namespace's methods.
8996        if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Class) {
8997            if let Some(anc) = with_host(|h| h.class_builtin_ancestor(recv)) {
8998                if with_host(|h| h.kind_of(&anc)) == Some(ObjKind::Builtin) {
8999                    // The subclass is recorded so a species-aware static
9000                    // (`Array.from`, `Promise.resolve`, …) builds its result
9001                    // through it rather than through the builtin.
9002                    return with_static_this(recv, || call_method(&anc, name, args));
9003                }
9004            }
9005        }
9006        // A method inherited via the function's [[Prototype]] chain (set with
9007        // `Object.setPrototypeOf(fn, proto)`) — the `router` package's router
9008        // functions inherit `route`/`use`/`get`/… from `Router.prototype`.
9009        if let Some(f) = with_host(|h| lookup_chain(h, recv, name)) {
9010            if with_host(|h| is_callable(h, &f)) {
9011                return invoke(&f, args, Some(recv.clone()));
9012            }
9013        }
9014        // An `Object.prototype` method invoked with a builtin namespace/prototype
9015        // as `this` (`hasOwnProperty.call(Map.prototype, 'get')`, the get-intrinsic
9016        // ownership probe) — dispatch it against the builtin receiver.
9017        if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Builtin)
9018            && crate::builtins::is_object_builtin_method(name)
9019        {
9020            return crate::builtins::object_builtin_method(recv, name, args);
9021        }
9022    }
9023    if name == "constructor" {
9024        if let Some(r) = call_default_ctor(recv, &args) {
9025            return r;
9026        }
9027    }
9028    // Type methods (array/string/number, Map/Set/Symbol/generator methods).
9029    crate::builtins::call_type_method(recv, name, args)
9030}
9031
9032/// `x.constructor(...)` invoked as a CALL when nothing on `x`'s prototype chain
9033/// owns a `constructor` slot.
9034///
9035/// Reading the property already resolves a builtin instance's native constructor
9036/// (the `constructor` arm of `builtins::get_property`), but the CALL path only
9037/// consulted the prototype chain, so the two disagreed:
9038/// `(function(){}).constructor === Function` read `true` while
9039/// `(function(){}).constructor('return 9')` threw
9040/// `TypeError: constructor is not a function`. That call form is exactly how
9041/// `get-intrinsic` — a transitive dependency of express — reaches the `Function`
9042/// constructor. Resolved here through the same one definition the read uses, so
9043/// the two can no longer drift apart. `None` means "not resolvable/callable",
9044/// leaving the caller's original error in place.
9045fn call_default_ctor(recv: &Value, args: &[Value]) -> Option<Result<Value, String>> {
9046    let ctor = crate::builtins::get_property(recv, "constructor").ok()?;
9047    with_host(|h| is_callable(h, &ctor)).then(|| invoke(&ctor, args.to_vec(), None))
9048}
9049
9050/// Call any callable value.
9051pub fn invoke(callable: &Value, args: Vec<Value>, this: Option<Value>) -> Result<Value, String> {
9052    // `[[Call]]` on a Proxy runs the `apply` trap (or forwards to the target).
9053    // Probed by kind first so the ordinary call path never clones its arguments.
9054    if with_host(|h| h.kind_of(callable)) == Some(ObjKind::Proxy) {
9055        // 10.5.12: a proxy has `[[Call]]` only when its target does, and that is
9056        // settled before the handler is consulted — revoked or not.
9057        if !with_host(|h| is_callable(h, callable)) {
9058            return Err(type_error(&format!(
9059                "{} is not a function",
9060                with_host(|h| h.str_of(callable))
9061            )));
9062        }
9063        return crate::proxy::apply(callable, args, this).map(|r| r.expect("kind_of said Proxy"));
9064    }
9065    let obj = with_host(|h| h.get(callable).cloned());
9066    match obj {
9067        // A builtin-prototype method thunk (`Object.prototype.toString`): dispatch
9068        // against the invoke-time `this` (supplied by `.call`/`.apply`).
9069        Some(JsObj::Builtin(name)) if name.starts_with("@proto:") => {
9070            let recv = this.unwrap_or(Value::Undef);
9071            crate::builtins::proto_method(&recv, &name["@proto:".len()..], args)
9072        }
9073        // An intrinsic prototype's GETTER, borrowed off its descriptor — the
9074        // form a library uses to read a slot from an arbitrary receiver
9075        // (`Object.getOwnPropertyDescriptor(Map.prototype, 'size').get
9076        // .call(m)`). It brand-checks `this` and reads, or throws naming
9077        // itself.
9078        // The setter half of the `arguments`/`caller` poison pill — the only
9079        // intrinsic accessor here that has one, and it throws like its getter.
9080        Some(JsObj::Builtin(name)) if name.starts_with("@protoset:") => {
9081            let _ = &name;
9082            let recv = this.unwrap_or(Value::Undef);
9083            // The setter half accepts silently for the same receivers the
9084            // getter answers for, and throws for the rest.
9085            if with_host(|h| h.fn_is_sloppy(&recv)) {
9086                Ok(Value::Undef)
9087            } else {
9088                Err(type_error(crate::builtins::POISON_PILL))
9089            }
9090        }
9091        Some(JsObj::Builtin(name)) if name.starts_with("@protoget:") => {
9092            let recv = this.unwrap_or(Value::Undef);
9093            let rest = &name["@protoget:".len()..];
9094            let (ctor, key) = rest.split_once(':').unwrap_or((rest, ""));
9095            crate::builtins::proto_getter_call(ctor, key, &recv)
9096        }
9097        // `NativeCtor.call(obj, …)` — ES5 "constructor stealing", still shipped by
9098        // libraries that predate `class`. `iconv-lite`'s internal codec is exactly
9099        // this:
9100        //
9101        //     function InternalDecoder(options, codec) { StringDecoder.call(this, codec.enc); }
9102        //     InternalDecoder.prototype = StringDecoder.prototype;
9103        //
9104        // A native constructor builds a fresh tagged object, so initializing the
9105        // SUPPLIED object means building one and moving its slots across.
9106        //
9107        // The guard is deliberately narrow: `obj` must already inherit from THIS
9108        // constructor's prototype, i.e. the subclass really did adopt it. Without
9109        // that, `Date.call(x)` and `Buffer.call(x)` — which in JS ignore `this` and
9110        // return a string / a buffer — would start mutating `x` instead.
9111        Some(JsObj::Builtin(ref name)) if steals_ctor(name, this.as_ref()) => {
9112            let target = this.expect("guard checked");
9113            let built = crate::stdlib::construct(name, &args)
9114                .expect("guard checked a native constructor")?;
9115            adopt_native_slots(&target, &built);
9116            Ok(Value::Undef)
9117        }
9118        // A `Promise` static reached through `.call`/`.apply` checks its
9119        // receiver first, as 27.2.4 does: `Promise.resolve.call(1)` throws.
9120        Some(JsObj::Builtin(name)) if name.starts_with("Promise.") && this.is_some() => {
9121            let recv = this.expect("guard checked");
9122            promise_static_receiver(&name, &recv)?;
9123            crate::builtins::call_builtin_function(&name, args)
9124        }
9125        Some(JsObj::Builtin(name)) => crate::builtins::call_builtin_function(&name, args),
9126        Some(JsObj::Func(fv)) => run_user_func_of(&fv, args, this, Some(callable.clone())),
9127        // A method read off an object is modelled as a thunk BOUND to it, but an
9128        // explicit `.call`/`.apply` receiver still wins — `Function.prototype.call`
9129        // rebinds `this`, and every `Array.prototype` method is generic over it, so
9130        // `[].slice.call(arrayLike)` must run against the ARGUMENT. Dropping the
9131        // override made that read back as the empty array the thunk was read off.
9132        // A nullish override is ignored: it carries no receiver to dispatch on.
9133        Some(JsObj::BoundMethod { recv, name }) => {
9134            let target = match &this {
9135                Some(t) if !matches!(t, Value::Undef) && !with_host(|h| h.is_null(t)) => t,
9136                _ => &recv,
9137            };
9138            // A thunk read off an ARRAY carries an `Array.prototype` method, and
9139            // those are generic over `this` — route the rebound call through
9140            // `proto_method` so an array-LIKE receiver takes the generic path
9141            // instead of being told the method does not exist.
9142            if with_host(|h| h.kind_of(&recv)) == Some(ObjKind::Array) {
9143                return crate::builtins::proto_method(target, &format!("Array:{name}"), args);
9144            }
9145            call_method(target, &name, args)
9146        }
9147        Some(JsObj::BoundFunc {
9148            target,
9149            this: bthis,
9150            args: pre,
9151        }) => {
9152            let mut all = pre;
9153            all.extend(args);
9154            invoke(&target, all, Some(bthis))
9155        }
9156        Some(JsObj::Class(c)) => Err(type_error(&format!(
9157            "Class constructor {} cannot be invoked without 'new'",
9158            c.name
9159        ))),
9160        _ => Err(type_error(&format!(
9161            "{} is not a function",
9162            with_host(|h| h.str_of(callable))
9163        ))),
9164    }
9165}
9166
9167/// Whether calling the native constructor `name` with `this` is the ES5
9168/// constructor-stealing pattern rather than an ordinary call.
9169///
9170/// True only when `name` really is a native stdlib constructor AND `this` is a
9171/// plain object that already inherits from that constructor's prototype — the
9172/// signature of `Sub.prototype = Native.prototype; Native.call(this, …)`. An
9173/// object that merely happens to be passed as `this` does not qualify, so
9174/// `Date.call(x)` / `Buffer.call(x)` keep their JS meaning (ignore `this`).
9175fn steals_ctor(name: &str, this: Option<&Value>) -> bool {
9176    let Some(target) = this else { return false };
9177    if !with_host(|h| matches!(h.get(target), Some(JsObj::Object(_)))) {
9178        return false;
9179    }
9180    // Already initialized (e.g. a re-entrant call) — nothing to steal.
9181    if crate::stdlib::native_tag(target).is_some() {
9182        return false;
9183    }
9184    let Some(proto) = with_host(|h| h.ensure_ctor_proto(name)) else {
9185        return false;
9186    };
9187    let mut cur = with_host(|h| h.proto_of(target));
9188    while let Some(p) = cur {
9189        if p == proto {
9190            return true;
9191        }
9192        cur = with_host(|h| h.proto_of(&p));
9193    }
9194    false
9195}
9196
9197/// Move a freshly-constructed native instance's state onto `target`, so an
9198/// object built by a subclass constructor becomes a working instance of the
9199/// native class. Copies every own key the native constructor set — the hidden
9200/// `@@`-prefixed slots that carry the state AND the plain ones it exposes
9201/// (`StringDecoder`'s `encoding`) — without disturbing keys `target` already has.
9202fn adopt_native_slots(target: &Value, built: &Value) {
9203    let slots: Vec<(String, Value)> = with_host(|h| match h.get(built) {
9204        Some(JsObj::Object(p)) => p.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
9205        _ => Vec::new(),
9206    });
9207    with_host(|h| {
9208        if let Some(JsObj::Object(p)) = h.get_mut(target) {
9209            for (k, v) in slots {
9210                p.insert(k, v);
9211            }
9212        }
9213    });
9214}
9215
9216/// Execute a user function/closure body on a fresh frame.
9217pub fn run_user_func(fv: &FuncVal, args: Vec<Value>, this: Option<Value>) -> Result<Value, String> {
9218    run_user_func_of(fv, args, this, None)
9219}
9220
9221/// [`run_user_func`] with the function VALUE the call came through, which the
9222/// `arguments` object needs for its `callee`.
9223pub fn run_user_func_of(
9224    fv: &FuncVal,
9225    args: Vec<Value>,
9226    this: Option<Value>,
9227    callee: Option<Value>,
9228) -> Result<Value, String> {
9229    run_user_func_full(fv, args, this, None, callee)
9230}
9231
9232/// As `run_user_func`, but with an explicit `new.target` (set by `new`).
9233pub fn run_user_func_nt(
9234    fv: &FuncVal,
9235    args: Vec<Value>,
9236    this: Option<Value>,
9237    new_target: Option<Value>,
9238) -> Result<Value, String> {
9239    run_user_func_full(fv, args, this, new_target, None)
9240}
9241
9242fn run_user_func_full(
9243    fv: &FuncVal,
9244    args: Vec<Value>,
9245    this: Option<Value>,
9246    new_target: Option<Value>,
9247    callee: Option<Value>,
9248) -> Result<Value, String> {
9249    // Consumed first, before anything here can start another call.
9250    let derived_ctor = with_host(|h| std::mem::take(&mut h.derived_ctor_next));
9251    // Only the light fields: cloning the whole `FuncDef` cloned its `Chunk` —
9252    // the entire compiled body, `sub_chunks` and all — on every single call.
9253    // The chunk is now reached once per pooled VM, in the two arms below.
9254    let (params, is_generator, is_async, is_arrow_def, def_name) = with_host(|h| {
9255        let d = &h.funcs[fv.def_id];
9256        (
9257            d.params.clone(),
9258            d.is_generator,
9259            d.is_async,
9260            d.is_arrow,
9261            d.name.clone(),
9262        )
9263    });
9264    // The name a stack frame shows: the definition's own, else the one the
9265    // function value was given (`{ m() {} }`, `const f = () => {}`).
9266    let def_name = match (&callee, def_name.is_empty()) {
9267        (Some(c), true) => with_host(|h| h.callable_name(c)),
9268        _ => def_name,
9269    };
9270    let env = new_env(fv.env.clone());
9271    // Bind the simple/rest arg slots; destructuring + defaults run in the body
9272    // prologue (compiled ahead of the user statements).
9273    let fn_is_sloppy = with_host(|h| !h.funcs.get(fv.def_id).is_some_and(|d| d.strict));
9274    bind_params(
9275        &env,
9276        &params,
9277        args,
9278        is_arrow_def,
9279        callee.as_ref(),
9280        fn_is_sloppy && !is_arrow_def,
9281    );
9282    // Arrow functions capture `this` lexically; regular functions receive it.
9283    let mut this_val = if fv.is_arrow { fv.this.clone() } else { this };
9284    let new_target = if fv.is_arrow {
9285        fv.new_target.clone()
9286    } else {
9287        new_target
9288    };
9289    // 10.2.1.2 OrdinaryCallBindThis: in SLOPPY mode an absent or nullish `this`
9290    // becomes the global object. Only a strict function keeps `undefined`, and
9291    // an arrow has no `this` of its own to substitute. Leaving it undefined
9292    // meant a plain `f()`, a detached method, a callback and `f.call(null)` all
9293    // saw `undefined` where node sees `globalThis`.
9294    let sloppy_this = !fv.is_arrow
9295        && !with_host(|h| h.funcs.get(fv.def_id).is_some_and(|d| d.strict))
9296        && match &this_val {
9297            None => true,
9298            Some(v) => matches!(v, Value::Undef) || with_host(|h| h.is_null(v)),
9299        };
9300    if sloppy_this {
9301        this_val = Some(with_host(|h| h.global_object()));
9302    } else if !fv.is_arrow && !with_host(|h| h.funcs.get(fv.def_id).is_some_and(|d| d.strict)) {
9303        // The other half of OrdinaryCallBindThis: a SLOPPY function boxes a
9304        // primitive `this` with `ToObject`, so `f.call(5)` sees a `Number`
9305        // wrapper rather than the number. Only strict mode passes it through.
9306        if let Some(t) = this_val.clone() {
9307            let boxed = crate::builtins::to_object(&t);
9308            this_val = Some(boxed);
9309        }
9310    }
9311    // A generator function does not run its body on call — it returns a suspended
9312    // generator over the already-bound frame.
9313    if is_generator {
9314        let chunk = with_host(|h| h.funcs[fv.def_id].chunk.clone());
9315        let strict = with_host(|h| h.funcs.get(fv.def_id).is_some_and(|d| d.strict));
9316        let gen = make_generator(chunk, env, this_val, fv, strict, Some(def_name.clone()));
9317        if is_async {
9318            if let Some(JsObj::Generator { id }) = with_host(|h| h.get(&gen).cloned()) {
9319                with_host(|h| h.generators[id as usize].async_gen = true);
9320            }
9321        }
9322        let proto = match &callee {
9323            Some(f) => crate::builtins::generator_instance_proto(f),
9324            None => with_host(|h| {
9325                h.ensure_native_protos();
9326                h.native_proto(if is_async {
9327                    "AsyncGenerator"
9328                } else {
9329                    "Generator"
9330                })
9331            }),
9332        };
9333        if let Some(p) = proto {
9334            with_host(|h| h.set_proto(&gen, p));
9335        }
9336        return Ok(gen);
9337    }
9338    // An async function runs on a coroutine and returns a Promise: it executes
9339    // synchronously up to the first `await`, then continues via microtasks.
9340    if is_async {
9341        let chunk = with_host(|h| h.funcs[fv.def_id].chunk.clone());
9342        let strict = with_host(|h| h.funcs.get(fv.def_id).is_some_and(|d| d.strict));
9343        let gen = make_generator(chunk, env, this_val, fv, strict, Some(def_name.clone()));
9344        return Ok(run_async(gen));
9345    }
9346    let home = fv
9347        .home_class
9348        .as_ref()
9349        .and_then(|n| with_host(|h| h.class_registry.get(n).cloned()));
9350    // Resolved BEFORE the borrow below: reading the function table re-enters
9351    // the host, and doing it inside the frame-push closure double-borrows.
9352    let fn_strict = with_host(|h| h.funcs.get(fv.def_id).is_some_and(|d| d.strict));
9353    with_host(|h| {
9354        h.settle_op_pos();
9355        h.frames.push(Frame {
9356            base_env: env.clone(),
9357            env,
9358            this_obj: this_val,
9359            new_target,
9360            home_class: home,
9361            home_static: fv.home_static,
9362            home_object: fv.home_object.clone(),
9363            strict: fn_strict,
9364            line: 0,
9365            pos: 0,
9366            arrow: fv.is_arrow,
9367            owner: Some(def_name),
9368            is_module: false,
9369            this_state: if derived_ctor {
9370                ThisState::Pending
9371            } else {
9372                ThisState::Plain
9373            },
9374        })
9375    });
9376    let r = run_chunk_keyed(func_key(fv.def_id), || {
9377        with_host(|h| h.funcs[fv.def_id].chunk.clone())
9378    });
9379    let (sig, this_state) = with_host(|h| {
9380        let frame = h.frames.pop();
9381        clear_op_pos();
9382        (h.signal.take(), frame.map(|f| f.this_state))
9383    });
9384    let ret = match r {
9385        Err(e) => return Err(e),
9386        Ok(_) => match sig {
9387            Some(Signal::Return(v)) => v,
9388            _ => Value::Undef,
9389        },
9390    };
9391    // 10.2.2 [[Construct]] steps 10-12 for a derived constructor: an object
9392    // return wins; any other non-undefined return is a TypeError; and falling
9393    // off the end (or `return;`) needs `this` to have been bound by `super()`.
9394    if derived_ctor && !returns_object(&ret) {
9395        if !matches!(ret, Value::Undef) {
9396            return Err(type_error(
9397                "Derived constructors may only return object or undefined",
9398            ));
9399        }
9400        if this_state == Some(ThisState::Pending) {
9401            return Err(this_before_super_error());
9402        }
9403    }
9404    Ok(ret)
9405}
9406
9407/// Bind positional args into a fresh call environment. The compiler emits the
9408/// param names in `def.params`; a `...rest` slot collects the tail as an array.
9409fn bind_params(
9410    env: &Env,
9411    params: &[ParamSlot],
9412    args: Vec<Value>,
9413    is_arrow: bool,
9414    callee: Option<&Value>,
9415    sloppy: bool,
9416) {
9417    let mut vars = VarMap::default();
9418    let mut i = 0;
9419    for slot in params {
9420        if slot.rest {
9421            let rest: Vec<Value> = args.get(i..).map(|s| s.to_vec()).unwrap_or_default();
9422            let arr = with_host(|h| h.new_array(rest));
9423            vars.insert(slot.name.clone(), arr);
9424        } else {
9425            let v = args.get(i).cloned().unwrap_or(Value::Undef);
9426            vars.insert(slot.name.clone(), v);
9427            i += 1;
9428        }
9429    }
9430    // `arguments` array (simple approximation — see BUGS.md: it is a real
9431    // Array, not an Arguments exotic). An ARROW function never gets one:
9432    // `FunctionDeclarationInstantiation` (10.2.11) creates the binding only for
9433    // a non-arrow, so `arguments` inside an arrow resolves lexically to the
9434    // enclosing function's. Binding an empty one here made
9435    // `function f(){ const g = () => [...arguments]; }` see zero args.
9436    if !is_arrow {
9437        let args_arr = with_host(|h| {
9438            let a = h.new_array(args);
9439            // Marked so it can be told apart from an ordinary array: node's
9440            // `arguments` is an exotic, and without the mark
9441            // `Array.isArray(arguments)` was true, the brand was
9442            // `[object Array]` and `util.types.isArgumentsObject` was false.
9443            // The backing representation stays an Array, which is what keeps
9444            // indices, `length`, spread and `for-of` working.
9445            h.set_fn_prop(&a, "@@arguments", Value::Bool(true));
9446            // `callee` is the function itself in SLOPPY code (it is a poison
9447            // pill only in strict, which the read path handles). It read back
9448            // `undefined`, so the pre-`class` self-reference idiom
9449            // `(function(){ arguments.callee })` found nothing.
9450            if let Some(f) = callee {
9451                if sloppy {
9452                    h.set_fn_prop(&a, "@@callee", f.clone());
9453                }
9454            }
9455            a
9456        });
9457        vars.entry("arguments".to_string()).or_insert(args_arr);
9458    }
9459    env.borrow_mut().vars = vars;
9460}
9461
9462/// Construct an instance with `new` — creates a fresh object, binds it as
9463/// `this`, runs the constructor, and returns the object (unless the constructor
9464/// returns its own object).
9465pub fn construct(ctor: &Value, args: Vec<Value>) -> Result<Value, String> {
9466    construct_nt(ctor, args, ctor.clone())
9467}
9468
9469/// `new` with an explicit `new.target` (differs from `ctor` when a derived class
9470/// calls `super(...)` — the target stays the originally-`new`ed class).
9471pub fn construct_nt(ctor: &Value, args: Vec<Value>, new_target: Value) -> Result<Value, String> {
9472    // `new proxy(…)` runs the `construct` trap (or forwards to the target).
9473    if with_host(|h| h.kind_of(ctor)) == Some(ObjKind::Proxy) {
9474        if !is_constructor(ctor) {
9475            return Err(not_a_constructor(ctor));
9476        }
9477        return crate::proxy::construct(ctor, args, &new_target)
9478            .map(|r| r.expect("kind_of said Proxy"));
9479    }
9480    let obj = with_host(|h| h.get(ctor).cloned());
9481    match obj {
9482        Some(JsObj::Class(_)) => construct_class(ctor, args, new_target),
9483        Some(JsObj::Func(fv)) => {
9484            // Only an ORDINARY function has a `[[Construct]]` slot. An arrow, a
9485            // `function*` and an `async function` are callable but not
9486            // constructable (10.2.2 is installed only for the ordinary case), so
9487            // `new` on one is a TypeError — node-js instead ran the body and
9488            // handed back a half-built instance (for a generator, an object whose
9489            // constructor had returned a suspended generator).
9490            let non_ctor = with_host(|h| {
9491                h.funcs
9492                    .get(fv.def_id)
9493                    // A MethodDefinition is in the same boat: `new ({m(){}}).m()`
9494                    // is `TypeError: o.m is not a constructor` on node v26.7.0,
9495                    // which is also why a method owns no `prototype`.
9496                    .map(|d| d.is_generator || d.is_async || d.is_method)
9497                    .unwrap_or(false)
9498            });
9499            if fv.is_arrow || non_ctor {
9500                return Err(not_a_constructor(ctor));
9501            }
9502            // A plain constructor function: instance delegates to `fn.prototype`
9503            // (auto-created with a `.constructor` back-link if not yet accessed).
9504            let inst = with_host(|h| {
9505                let o = h.new_object(IndexMap::new());
9506                let proto = h.fn_prop(ctor, "prototype").unwrap_or_else(|| {
9507                    let p = h.new_object(IndexMap::new());
9508                    if let Some(JsObj::Object(pp)) = h.get_mut(&p) {
9509                        pp.insert("constructor".to_string(), ctor.clone());
9510                    }
9511                    // `F.prototype.constructor` is non-enumerable in JS.
9512                    h.hide_prop(&p, "constructor");
9513                    h.set_fn_prop(ctor, "prototype", p.clone());
9514                    p
9515                });
9516                h.set_proto(&o, proto);
9517                o
9518            });
9519            let r = run_user_func_nt(&fv, args, Some(inst.clone()), Some(new_target))?;
9520            if returns_object(&r) {
9521                Ok(r)
9522            } else {
9523                Ok(inst)
9524            }
9525        }
9526        Some(JsObj::Builtin(name)) => crate::builtins::construct_builtin(&name, args),
9527        Some(JsObj::BoundFunc {
9528            target, args: pre, ..
9529        }) => {
9530            let mut all = pre;
9531            all.extend(args);
9532            construct_nt(&target, all, new_target)
9533        }
9534        _ => Err(not_a_constructor(ctor)),
9535    }
9536}
9537
9538/// `IsConstructor` (7.2.4): whether `v` has a `[[Construct]]` slot. An arrow, a
9539/// generator, an async function and a method are callable but not constructors;
9540/// a bound function and a proxy follow their target. Builtins have no slot
9541/// table here, so one counts when it is a bare capitalised global (`Map`,
9542/// `Symbol`) and not a namespaced static (`Math.max`) or a lowercase function.
9543pub(crate) fn is_constructor(v: &Value) -> bool {
9544    match with_host(|h| h.get(v).cloned()) {
9545        Some(JsObj::Class(_)) => true,
9546        Some(JsObj::Func(fv)) => {
9547            !fv.is_arrow
9548                && !with_host(|h| {
9549                    h.funcs
9550                        .get(fv.def_id)
9551                        .map(|d| d.is_generator || d.is_async || d.is_method)
9552                        .unwrap_or(false)
9553                })
9554        }
9555        Some(JsObj::BoundFunc { target, .. }) => is_constructor(&target),
9556        Some(JsObj::Builtin(name)) => {
9557            !name.contains('.') && name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
9558        }
9559        // A proxy is a constructor exactly when its target is (10.5.14 step 8).
9560        Some(JsObj::Proxy { target, .. }) => is_constructor(&target),
9561        _ => false,
9562    }
9563}
9564
9565/// `TypeError: <callee> is not a constructor`.
9566///
9567/// V8 names the callee by its SOURCE TEXT (`new g()` reports `g`, `new o.m()`
9568/// reports `o.m`); node-js keeps no spans, so a named callable is reported by
9569/// its name — the same string in the common case — and anything else by its
9570/// value.
9571pub(crate) fn not_a_constructor(ctor: &Value) -> String {
9572    let name = with_host(|h| match h.callable_name(ctor) {
9573        n if n.is_empty() => h.str_of(ctor),
9574        n => n,
9575    });
9576    type_error(&format!("{name} is not a constructor"))
9577}
9578
9579/// Whether a constructor's return value is an object (so `new` yields it instead
9580/// of the fresh instance). In JS "object" includes functions — the `router`
9581/// package's constructor `return router` (a function) must be honored, or the
9582/// returned router loses its callable identity.
9583fn returns_object(r: &Value) -> bool {
9584    matches!(
9585        with_host(|h| h.get(r).cloned()),
9586        Some(JsObj::Object(_))
9587            | Some(JsObj::Array(_))
9588            | Some(JsObj::Map { .. })
9589            | Some(JsObj::Set { .. })
9590            | Some(JsObj::Func(_))
9591            | Some(JsObj::Class(_))
9592            | Some(JsObj::BoundFunc { .. })
9593            | Some(JsObj::BoundMethod { .. })
9594            | Some(JsObj::RegExp(_))
9595    )
9596}
9597
9598/// Construct a `class` instance: allocate the object linked to `C.prototype`,
9599/// run field initializers + the constructor (which may call `super(...)`).
9600fn construct_class(
9601    class_val: &Value,
9602    args: Vec<Value>,
9603    new_target: Value,
9604) -> Result<Value, String> {
9605    let cv = match with_host(|h| h.get(class_val).cloned()) {
9606        Some(JsObj::Class(c)) => c,
9607        _ => return Err(type_error("not a class")),
9608    };
9609    // Resolve the prototype of the *most-derived* class being `new`ed, so an
9610    // instance created through a `super()` chain still delegates to the leaf
9611    // prototype (correct method resolution).
9612    let leaf_proto = match with_host(|h| h.get(&new_target).cloned()) {
9613        Some(JsObj::Class(c)) => c.proto.clone(),
9614        _ => cv.proto.clone(),
9615    };
9616    let inst = with_host(|h| {
9617        let o = h.new_object(IndexMap::new());
9618        h.set_proto(&o, leaf_proto.clone());
9619        o
9620    });
9621    // A `super()` deeper in may substitute the instance; the previous value is
9622    // restored so a `new` inside a constructor body cannot be mistaken for one.
9623    let saved = with_host(|h| h.swap_super_replacement(None));
9624    let ran = run_class_ctor(&cv, &inst, args, &new_target);
9625    let substituted = with_host(|h| {
9626        let s = h.take_super_replacement();
9627        h.swap_super_replacement(saved);
9628        s
9629    });
9630    // A constructor that returns an object replaces the instance (`new`
9631    // semantics); failing that, whatever `super()` substituted for it.
9632    match ran? {
9633        Some(obj) if returns_object(&obj) => Ok(obj),
9634        _ => Ok(substituted.unwrap_or(inst)),
9635    }
9636}
9637
9638/// Run one class's field initializers then its constructor on an existing
9639/// instance. Returns the constructor's explicit object return (if any). For a
9640/// base class this is the whole init; for a derived class the constructor body
9641/// reaches `super(...)` which recurses into the parent.
9642fn run_class_ctor(
9643    cv: &ClassVal,
9644    inst: &Value,
9645    args: Vec<Value>,
9646    new_target: &Value,
9647) -> Result<Option<Value>, String> {
9648    // A derived class must run its fields AFTER super() returns; SUPER_CALL does
9649    // that. A base class initializes fields before the constructor body.
9650    if cv.parent.is_none() {
9651        init_fields(cv, inst)?;
9652    }
9653    match &cv.ctor {
9654        Some(ctor_fn) => {
9655            let fv = match with_host(|h| h.get(ctor_fn).cloned()) {
9656                Some(JsObj::Func(f)) => f,
9657                _ => return Err(type_error("class constructor is not a function")),
9658            };
9659            if cv.parent.is_some() {
9660                with_host(|h| h.mark_next_call_derived_ctor());
9661            }
9662            let r = run_user_func_nt(&fv, args, Some(inst.clone()), Some(new_target.clone()))?;
9663            return Ok(Some(r));
9664        }
9665        None => {
9666            // Default constructor: `constructor(...a){ super(...a); }` for a
9667            // derived class, empty for a base class.
9668            if let Some(parent) = &cv.parent {
9669                // A base constructor's returned object becomes the instance, so
9670                // the implicit `constructor(...a){ super(...a) }` hands it on.
9671                if let Some(replacement) = super_construct(parent, args, inst, new_target)? {
9672                    init_fields(cv, &replacement)?;
9673                    return Ok(Some(replacement));
9674                }
9675                init_fields(cv, inst)?;
9676            }
9677        }
9678    }
9679    Ok(None)
9680}
9681
9682/// `InitializeInstanceElements` step 1 (15.7.14): give `inst` every private
9683/// method and accessor of the class whose prototype is `proto`, before any
9684/// field initializer runs. They are held on the class prototype as a template;
9685/// the instance's own copy is what the brand check finds.
9686pub fn install_private_methods(proto: &Value, inst: &Value) {
9687    with_host(|h| {
9688        let methods: Vec<(String, Value)> = match h.get(proto) {
9689            Some(JsObj::Object(p)) => p
9690                .iter()
9691                .filter(|(k, _)| k.starts_with('#'))
9692                .map(|(k, v)| (k.clone(), v.clone()))
9693                .collect(),
9694            _ => Vec::new(),
9695        };
9696        let accessors: Vec<(String, Accessor)> = h
9697            .own_accessor_keys(proto)
9698            .into_iter()
9699            .filter(|k| k.starts_with('#'))
9700            .filter_map(|k| h.own_accessor(proto, &k).map(|a| (k, a)))
9701            .collect();
9702        for (k, v) in methods {
9703            if let Some(JsObj::Object(p)) = h.get_mut(inst) {
9704                p.insert(k.clone(), v);
9705            }
9706            h.hide_prop(inst, &k);
9707        }
9708        for (k, (getter, setter)) in accessors {
9709            h.set_accessor(inst, &k, getter, setter);
9710            h.hide_prop(inst, &k);
9711        }
9712    });
9713}
9714
9715/// Evaluate and assign a class's instance-field initializers on `inst`.
9716fn init_fields(cv: &ClassVal, inst: &Value) -> Result<(), String> {
9717    install_private_methods(&cv.proto, inst);
9718    for (name, thunk, name_anon) in &cv.fields {
9719        init_one_field(inst, name, thunk, *name_anon)?;
9720    }
9721    Ok(())
9722}
9723
9724/// Evaluate ONE instance-field initializer thunk and install the result on
9725/// `inst`.
9726///
9727/// Shared by the base-class path (`init_fields`) and the derived-class path
9728/// that runs after `super(...)`; the two used to be separate loops, and only the
9729/// first canonicalized an array-index key.
9730///
9731/// `name_anon` carries 15.7.10's NamedEvaluation: `class C { f = function(){} }`
9732/// gives the function the name `f`. It is decided by the compiler from the
9733/// syntax, never from the value.
9734pub fn init_one_field(
9735    inst: &Value,
9736    name: &str,
9737    thunk: &Value,
9738    name_anon: bool,
9739) -> Result<(), String> {
9740    // The thunk is an arrow capturing the class scope; run it with `this`=inst
9741    // so `this.other`-referencing initializers work.
9742    let val = invoke(thunk, Vec::new(), Some(inst.clone()))?;
9743    with_host(|h| {
9744        if name_anon {
9745            let s = h.new_str(name.to_string());
9746            h.set_fn_prop(&val, "name", s);
9747        }
9748        if let Some(JsObj::Object(props)) = h.get_mut(inst) {
9749            let is_new = !props.contains_key(name);
9750            props.insert(name.to_string(), val);
9751            if is_new && array_index(name).is_some() {
9752                canonicalize_own_keys(props);
9753            }
9754        }
9755    });
9756    Ok(())
9757}
9758
9759/// Run a parent constructor as part of `super(...)`: dispatch on the parent's
9760/// kind (class vs plain function vs builtin) using the existing instance.
9761/// Run the parent constructor against `inst`.
9762///
9763/// Returns the object the parent's `[[Construct]]` produced when that is NOT
9764/// `inst` — a base constructor is allowed to `return` one, and 15.7.15 makes it
9765/// the derived instance too. The caller rebinds `this` to it, so the rest of the
9766/// derived constructor writes to the object `new` will hand back.
9767pub fn super_construct(
9768    parent: &Value,
9769    args: Vec<Value>,
9770    inst: &Value,
9771    new_target: &Value,
9772) -> Result<Option<Value>, String> {
9773    match with_host(|h| h.get(parent).cloned()) {
9774        Some(JsObj::Class(pcv)) => Ok(run_class_ctor(&pcv, inst, args, new_target)?
9775            .filter(|r| returns_object(r) && !with_host(|h| h.strict_eq(r, inst)))),
9776        Some(JsObj::Func(fv)) => {
9777            let r = run_user_func_nt(&fv, args, Some(inst.clone()), Some(new_target.clone()))?;
9778            Ok(Some(r).filter(|r| returns_object(r) && !with_host(|h| h.strict_eq(r, inst))))
9779        }
9780        Some(JsObj::Builtin(name)) => {
9781            // A keyed collection fills itself through `this.set`/`this.add`,
9782            // looked up on the SUBCLASS instance, so the instance has to be the
9783            // collection before the first entry goes in.
9784            let init = args.first().filter(|a| !with_host(|h| h.is_nullish(a)));
9785            if let (true, Some(init)) = (
9786                matches!(name.as_str(), "Map" | "WeakMap" | "Set" | "WeakSet"),
9787                init,
9788            ) {
9789                let built = crate::builtins::construct_builtin(&name, Vec::new())?;
9790                become_exotic(inst, &built);
9791                crate::builtins::add_entries_via_adder(inst, &name, init)?;
9792                return Ok(None);
9793            }
9794            let built = crate::builtins::construct_builtin(&name, args)?;
9795            // An EXOTIC parent (`class A extends Array`) keeps its behaviour in
9796            // the heap variant, not in a property map, so copying own props
9797            // cannot carry it: the instance has to BECOME the built object.
9798            // Without this `new (class extends Array {})().push` was not a
9799            // function, and the same for Map, Set, RegExp, Promise and
9800            // Function — subclassing a builtin produced a plain object.
9801            if !become_exotic(inst, &built) {
9802                // An `Error` subclass is ordinary: its state IS own properties.
9803                adopt_own_props(inst, &built);
9804            }
9805            Ok(None)
9806        }
9807        // A Proxy parent (`class D extends new Proxy(B, {})`): `super(…)` is
9808        // `[[Construct]]` on the proxy, so the `construct` trap runs (or forwards
9809        // to the target). node-js initializes an ALREADY-allocated `inst` rather
9810        // than adopting the constructor's return value, so what the proxy built
9811        // is moved across — the same move the builtin arm makes.
9812        Some(JsObj::Proxy { .. }) => {
9813            let built = construct_nt(parent, args, new_target.clone())?;
9814            if !become_exotic(inst, &built) {
9815                adopt_own_props(inst, &built);
9816            }
9817            Ok(None)
9818        }
9819        _ => Err(type_error("super is not a constructor")),
9820    }
9821}
9822
9823/// Move `built`'s own properties (and their attributes) onto `inst`. Used where
9824/// a parent constructor produces a fresh object but node-js's class model has
9825/// already allocated the instance `this` is bound to.
9826/// Replace `inst`'s heap object with `built`'s, so an instance whose class
9827/// extends a builtin EXOTIC really is one.
9828///
9829/// `inst` keeps its identity and its prototype link — the leaf class's
9830/// prototype, which is what method resolution and `instanceof` walk — while its
9831/// contents become the exotic the parent constructor produced. The side tables
9832/// keyed by heap index (array holes, property attributes, the fn-prop table)
9833/// move across with it.
9834///
9835/// Returns false for a variant whose state is ordinary own properties
9836/// (`Error`), which the caller copies instead.
9837fn become_exotic(inst: &Value, built: &Value) -> bool {
9838    let exotic = matches!(
9839        with_host(|h| h.get(built).cloned()),
9840        Some(JsObj::Array(_))
9841            | Some(JsObj::Map { .. })
9842            | Some(JsObj::Set { .. })
9843            | Some(JsObj::RegExp(_))
9844            | Some(JsObj::Promise { .. })
9845            | Some(JsObj::Func(_))
9846            | Some(JsObj::Str(_))
9847            | Some(JsObj::BigInt(_))
9848            | Some(JsObj::Symbol { .. })
9849    );
9850    if !exotic {
9851        return false;
9852    }
9853    let (Value::Obj(dst), Value::Obj(src)) = (inst, built) else {
9854        return false;
9855    };
9856    let (dst, src) = (*dst, *src);
9857    with_host(|h| {
9858        if let Some(obj) = h.get(built).cloned() {
9859            if let Some(slot) = h.get_mut(inst) {
9860                *slot = obj;
9861            }
9862        }
9863        h.move_index_state(src, dst);
9864    });
9865    true
9866}
9867
9868fn adopt_own_props(inst: &Value, built: &Value) {
9869    let entries: Vec<(String, Value)> = with_host(|h| match h.get(built) {
9870        Some(JsObj::Object(p)) => p.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
9871        _ => Vec::new(),
9872    });
9873    with_host(|h| {
9874        let keys: Vec<String> = entries.iter().map(|(k, _)| k.clone()).collect();
9875        if let Some(JsObj::Object(props)) = h.get_mut(inst) {
9876            for (k, v) in entries {
9877                props.insert(k, v);
9878            }
9879            canonicalize_own_keys(props);
9880        }
9881        // The copied slots keep the attributes the source gave them, so
9882        // `class E extends Error` instances hide `message`/`stack` too.
9883        for k in keys {
9884            let a = h.prop_attrs(built, &k);
9885            h.set_prop_attrs(inst, &k, a);
9886        }
9887    });
9888}
9889
9890// ── class construction (runtime) ─────────────────────────────────────────────
9891
9892/// Build a class constructor value from its parts. The compiler emits (via
9893/// `MKCLASS`) the evaluated parent (or undefined) and the constructor closure (or
9894/// undefined for a default constructor); methods/getters/setters/statics/fields
9895/// are installed afterward by `DEF_MEMBER`/`DEF_FIELD`.
9896pub fn build_class(name: &str, parent: Value, ctor: Value, source_def: Option<usize>) -> Value {
9897    // A Proxy parent (`class D extends new Proxy(B, {})`): `D.prototype`'s
9898    // `[[Prototype]]` is `Get(parent, "prototype")` — a read that runs the `get`
9899    // trap and so re-enters the host, which the borrow below cannot allow.
9900    // Without it the link fell back to `Object.prototype` and every inherited
9901    // method went missing.
9902    let proxy_parent_proto = (with_host(|h| h.kind_of(&parent)) == Some(ObjKind::Proxy))
9903        .then(|| crate::builtins::get_property(&parent, "prototype").ok())
9904        .flatten();
9905    with_host(|h| {
9906        let parent_opt = if matches!(parent, Value::Undef) {
9907            None
9908        } else {
9909            Some(parent.clone())
9910        };
9911        // The class prototype delegates to the parent's prototype (or
9912        // Object.prototype for a base class). Extending a builtin error links to
9913        // that error's prototype so `instanceof Error` holds for the subclass.
9914        let parent_proto = match &parent_opt {
9915            Some(_) if proxy_parent_proto.is_some() => {
9916                proxy_parent_proto.clone().expect("checked is_some")
9917            }
9918            Some(p) => match h.get(p).cloned() {
9919                Some(JsObj::Class(pc)) => pc.proto.clone(),
9920                Some(JsObj::Builtin(bn)) => {
9921                    h.ensure_error_protos();
9922                    h.ensure_native_protos();
9923                    // `class S extends String {}` links to the REAL
9924                    // `String.prototype`, the same way an error subclass links
9925                    // to its error prototype. Without it `S.prototype`'s
9926                    // `[[Prototype]]` fell back to `Object.prototype`, so
9927                    // `new S("hi") instanceof String` read false and
9928                    // `String(new S("hi"))` reported `[object String]` instead
9929                    // of `hi`.
9930                    // `ensure_ctor_proto`, not `native_proto`: a stdlib class's
9931                    // prototype is built on first use, and `class AC extends
9932                    // AbortController {}` declared before any instance existed
9933                    // found none and fell back to `Object.prototype`, so
9934                    // `new AC().signal` read `undefined`.
9935                    error_proto_of(h, &bn)
9936                        .or_else(|| h.ensure_ctor_proto(&bn))
9937                        .or_else(|| h.fn_prop(p, "prototype"))
9938                        .unwrap_or_else(|| h.object_proto())
9939                }
9940                _ => h
9941                    .fn_prop(p, "prototype")
9942                    .unwrap_or_else(|| h.object_proto()),
9943            },
9944            None => h.object_proto(),
9945        };
9946        let proto = h.new_object(IndexMap::new());
9947        h.set_proto(&proto, parent_proto);
9948        let ctor_opt = if matches!(ctor, Value::Undef) {
9949            None
9950        } else {
9951            Some(ctor.clone())
9952        };
9953        // Give the constructor closure its home class (for `super.method()`), and
9954        // record its `.name`.
9955        if let Some(cf) = &ctor_opt {
9956            if let Some(JsObj::Func(f)) = h.get_mut(cf) {
9957                f.home_class = Some(name.to_string());
9958            }
9959        }
9960        let cval = ClassVal {
9961            name: name.to_string(),
9962            ctor: ctor_opt,
9963            parent: parent_opt,
9964            proto: proto.clone(),
9965            statics: IndexMap::new(),
9966            fields: Vec::new(),
9967            source_def,
9968        };
9969        let class_val = h.alloc(JsObj::Class(cval));
9970        h.class_registry.insert(name.to_string(), class_val.clone());
9971        // Link prototype → class (for instance display + `constructor`), and give
9972        // the class its own `prototype` fn-prop so `C.prototype` reads work.
9973        h.tag_proto_class(&proto, class_val.clone());
9974        h.set_fn_prop(&class_val, "prototype", proto.clone());
9975        // `Class.prototype.constructor === Class`.
9976        if let Some(JsObj::Object(p)) = h.get_mut(&proto) {
9977            p.insert("constructor".to_string(), class_val.clone());
9978        }
9979        h.hide_prop(&proto, "constructor");
9980        class_val
9981    })
9982}
9983
9984/// Install a method / getter / setter on a class (`DEF_MEMBER`). `kind` is a
9985/// `member::*` tag; `is_static` targets the constructor side.
9986pub fn define_member(class_val: &Value, name: &str, kind: i64, is_static: bool, func: Value) {
9987    with_host(|h| {
9988        let cname = match h.get(class_val) {
9989            Some(JsObj::Class(c)) => c.name.clone(),
9990            _ => String::new(),
9991        };
9992        // A private method/accessor: remember which class declared it, so a
9993        // brand-check failure can name the class the way node does. A static
9994        // FIELD is data, not a method, so it keeps the field wording.
9995        if name.starts_with('#') && kind != member::STATIC_FIELD {
9996            h.note_private_method(name);
9997        }
9998        // Give the method its home class for `super.x()`, and record whether it
9999        // is static — `super` resolves against a different object either way.
10000        if let Some(JsObj::Func(f)) = h.get_mut(&func) {
10001            f.home_class = Some(cname);
10002            f.home_static = is_static;
10003        }
10004        // Static members live on the constructor (fn-props / static accessors);
10005        // instance members on the prototype.
10006        let target = if is_static {
10007            class_val.clone()
10008        } else {
10009            match h.get(class_val) {
10010                Some(JsObj::Class(c)) => c.proto.clone(),
10011                _ => return,
10012            }
10013        };
10014        match kind {
10015            member::GET => h.set_accessor(&target, name, Some(func), None),
10016            member::SET => h.set_accessor(&target, name, None, Some(func)),
10017            _ => {
10018                // A static field is enumerable (`Object.keys(C)` lists it) unlike
10019                // a method, so it must not reach the `hide_prop` below.
10020                if kind == member::STATIC_FIELD {
10021                    if let Some(JsObj::Class(c)) = h.get_mut(class_val) {
10022                        c.statics.insert(name.to_string(), func.clone());
10023                    }
10024                    h.set_fn_prop(class_val, name, func);
10025                    return;
10026                }
10027                if is_static {
10028                    if let Some(JsObj::Class(c)) = h.get_mut(class_val) {
10029                        c.statics.insert(name.to_string(), func.clone());
10030                    }
10031                    h.set_fn_prop(class_val, name, func);
10032                } else if let Some(JsObj::Object(p)) = h.get_mut(&target) {
10033                    p.insert(name.to_string(), func);
10034                }
10035            }
10036        }
10037        // Class methods and accessors are non-enumerable (ES2015 ClassDefinition-
10038        // Evaluation), so `for (k in instance)` walking the prototype chain never
10039        // yields them and `Object.keys(C.prototype)` is empty.
10040        h.hide_prop(&target, name);
10041    });
10042}
10043
10044/// Register an instance-field initializer thunk on a class (`DEF_FIELD`).
10045pub fn define_field(class_val: &Value, name: &str, thunk: Value, name_anon: bool) {
10046    with_host(|h| {
10047        if let Some(JsObj::Class(c)) = h.get_mut(class_val) {
10048            c.fields.push((name.to_string(), thunk, name_anon));
10049        }
10050    });
10051}
10052
10053/// The `[[Prototype]]` object a constructor value hands to its instances
10054/// (`Ctor.prototype`), for `instanceof`.
10055fn ctor_prototype(h: &JsHost, ctor: &Value) -> Option<Value> {
10056    match h.get(ctor) {
10057        Some(JsObj::Class(c)) => Some(c.proto.clone()),
10058        Some(JsObj::Func(_)) => h.fn_prop(ctor, "prototype"),
10059        // A builtin's prototype lives in one of two registries: the error
10060        // prototypes, or the native exotic prototypes (`Buffer.prototype`,
10061        // `Uint8Array.prototype`). Consulting only the first made `instanceof`
10062        // blind to the real `Buffer.prototype → Uint8Array.prototype` chain, so
10063        // `Buffer.prototype instanceof Uint8Array` read false even though the
10064        // link was there — the instance case only passed via a native-tag
10065        // special case, which a prototype object does not carry.
10066        Some(JsObj::Builtin(name)) => h
10067            .error_protos
10068            .get(name)
10069            .or_else(|| h.native_protos.get(name))
10070            .cloned(),
10071        Some(JsObj::BoundFunc { target, .. }) => ctor_prototype(h, &target.clone()),
10072        _ => None,
10073    }
10074}
10075
10076/// `ctor.prototype` in the SAME representation `builtins::prototype_of` yields,
10077/// so a chain walk driven by that function can compare the two with `strict_eq`.
10078///
10079/// `ctor_prototype` answers only for the constructors whose prototype object
10080/// really exists on the heap (classes, user functions, the error and native
10081/// exotics). A bare builtin like `Object`/`Array` has none there — its instances
10082/// report `h.object_proto()` / a `Builtin("<C>.prototype")` handle — so this
10083/// mirrors that fallback rather than reporting "no prototype" and failing every
10084/// comparison.
10085fn walk_target_prototype(ctor: &Value) -> Option<Value> {
10086    if let Some(p) = with_host(|h| ctor_prototype(h, ctor)) {
10087        return Some(p);
10088    }
10089    let name = with_host(|h| match h.get(ctor) {
10090        Some(JsObj::Builtin(n)) => Some(n.clone()),
10091        _ => None,
10092    })?;
10093    if name == "Object" {
10094        return Some(with_host(|h| h.object_proto()));
10095    }
10096    Some(with_host(|h| {
10097        h.alloc(JsObj::Builtin(format!("{name}.prototype")))
10098    }))
10099}
10100
10101/// V8's "not a function" wording for a value that was expected to be callable.
10102/// A number/string/boolean is named WITH its value (`number 1 is not a
10103/// function`, `string "s" is not a function`); every other type is named by type
10104/// alone (`object is not a function`, `symbol is not a function`).
10105pub fn not_a_function_message(v: &Value) -> String {
10106    with_host(|h| match v {
10107        Value::Undef => "undefined is not a function".into(),
10108        Value::Bool(b) => format!("boolean {b} is not a function"),
10109        Value::Int(_) | Value::Float(_) => format!("number {} is not a function", h.str_of(v)),
10110        Value::Str(s) => format!("string \"{s}\" is not a function"),
10111        Value::Obj(_) => match h.get(v) {
10112            Some(JsObj::Str(s)) => format!("string \"{s}\" is not a function"),
10113            Some(JsObj::Symbol { .. }) => "symbol is not a function".into(),
10114            Some(JsObj::BigInt(_)) => "bigint is not a function".into(),
10115            _ => "object is not a function".into(),
10116        },
10117        _ => "object is not a function".into(),
10118    })
10119}
10120
10121/// `obj instanceof ctor` — walk `obj`'s prototype chain looking for
10122/// `ctor.prototype`.
10123pub fn instance_of(obj: &Value, ctor: &Value) -> Result<bool, String> {
10124    // 13.10.2 InstanceofOperator step 3: a `Symbol.hasInstance` method on the
10125    // right-hand side REPLACES the prototype-chain walk entirely, and it is
10126    // consulted before the callability check — which is why a plain (uncallable)
10127    // object that defines it is a legal `instanceof` right-hand side.
10128    if matches!(ctor, Value::Obj(_)) {
10129        // `class C { static [Symbol.hasInstance](){} }` and a method defined on a
10130        // plain function both land in the fn-prop side table (which
10131        // `class_static` reads, following the `extends` chain), NOT in an object
10132        // property map — so consulting only `lookup_chain` would find the object
10133        // literal form and silently miss the two forms V8 users actually write.
10134        let handler = match with_host(|h| h.class_static(ctor, "@@hasInstance")) {
10135            Some(f) => Some(f),
10136            None => protocol_lookup(ctor, "@@hasInstance")?,
10137        };
10138        // GetMethod (7.3.11) treats only `undefined`/`null` as "absent"; anything
10139        // else that is not callable is a TypeError, so a data property here does
10140        // NOT fall back to the prototype walk.
10141        match handler {
10142            Some(f) if with_host(|h| is_callable(h, &f)) => {
10143                let r = invoke(&f, vec![obj.clone()], Some(ctor.clone()))?;
10144                return Ok(with_host(|h| h.truthy(&r)));
10145            }
10146            Some(f)
10147                if !matches!(f, Value::Undef)
10148                    && !with_host(|h| matches!(h.get(&f), Some(JsObj::Null))) =>
10149            {
10150                return Err(type_error(&not_a_function_message(&f)));
10151            }
10152            _ => {}
10153        }
10154    }
10155    ordinary_has_instance(obj, ctor, true)
10156}
10157
10158/// `OrdinaryHasInstance(C, O)` (7.3.21) behind `instanceof`: the
10159/// prototype-chain walk with no `Symbol.hasInstance` lookup. `validate_rhs` is
10160/// the operator's own step 4 — a right-hand side that is not callable is a
10161/// TypeError; reached through `Function.prototype[Symbol.hasInstance]` instead,
10162/// a non-callable `C` is simply `false`.
10163pub fn ordinary_has_instance(
10164    obj: &Value,
10165    ctor: &Value,
10166    validate_rhs: bool,
10167) -> Result<bool, String> {
10168    // 13.10.2 InstanceofOperator validates the RIGHT-hand side FIRST, so
10169    // `1 instanceof 3` throws even though the left side could never match.
10170    // Returning early on the left side skipped that check entirely.
10171    let ctor_callable = with_host(|h| {
10172        matches!(
10173            h.get(ctor),
10174            Some(JsObj::Func(_))
10175                | Some(JsObj::Class(_))
10176                | Some(JsObj::Builtin(_))
10177                | Some(JsObj::BoundFunc { .. })
10178        )
10179    });
10180    if !ctor_callable && !validate_rhs {
10181        return Ok(false);
10182    }
10183    if !ctor_callable {
10184        // V8 has TWO messages here and they are not interchangeable: a primitive
10185        // right-hand side is "not an object", an object that is merely not
10186        // callable is "not callable". Only the second was implemented, so
10187        // `1 instanceof 3` reported nothing at all.
10188        return Err(type_error(if with_host(|h| !is_primitive(h, ctor)) {
10189            "Right-hand side of 'instanceof' is not callable"
10190        } else {
10191            "Right-hand side of 'instanceof' is not an object"
10192        }));
10193    }
10194    // A non-object left-hand side is never an instance — but only after the
10195    // right-hand side has been validated above.
10196    if !matches!(obj, Value::Obj(_)) {
10197        return Ok(false);
10198    }
10199    // A Proxy shares no heap variant with its target, so the structural arms
10200    // below would misclassify it. 10.5.3 says `OrdinaryHasInstance` walks
10201    // `[[GetPrototypeOf]]`, i.e. the handler's `getPrototypeOf` trap — run that
10202    // walk here, which also gives a custom trap the final say.
10203    if with_host(|h| h.kind_of(obj)) == Some(ObjKind::Proxy) {
10204        with_host(|h| {
10205            h.ensure_error_protos();
10206            h.ensure_native_protos();
10207        });
10208        let Some(target) = walk_target_prototype(ctor) else {
10209            return Ok(false);
10210        };
10211        let mut cur = crate::proxy::get_prototype_of(obj)?.unwrap_or(Value::Undef);
10212        for _ in 0..100 {
10213            if matches!(cur, Value::Undef) || with_host(|h| h.is_null(&cur)) {
10214                return Ok(false);
10215            }
10216            if with_host(|h| h.strict_eq(&cur, &target)) {
10217                return Ok(true);
10218            }
10219            cur = crate::builtins::prototype_of(&cur);
10220        }
10221        return Ok(false);
10222    }
10223    // Builtin constructors whose instances aren't prototype-linked in our model
10224    // (arrays/plain objects/functions) get a structural instanceof.
10225    if let Some(JsObj::Builtin(name)) = with_host(|h| h.get(ctor).cloned()) {
10226        // …but an object whose chain PASSES THROUGH the intrinsic prototype is
10227        // an instance regardless of its own kind, which is the whole of the ES5
10228        // subclassing pattern: `F.prototype = Object.create(Array.prototype)`
10229        // makes `new F() instanceof Array` true. A structural test alone said
10230        // false.
10231        if crate::builtins::chain_intrinsic_ctors_pub(obj).contains(&name.as_str()) {
10232            return Ok(true);
10233        }
10234        let kind = with_host(|h| h.get(obj).cloned());
10235        match name.as_str() {
10236            "Array" => return Ok(matches!(kind, Some(JsObj::Array(_)))),
10237            "Function" => return Ok(with_host(|h| is_callable(h, obj))),
10238            // Map/Set/Promise instances are distinct heap variants, not
10239            // prototype-linked, so match them structurally (a WeakMap/WeakSet is a
10240            // Map/Set with `weak: true`, so `weakMap instanceof Map` is false).
10241            "Map" => return Ok(matches!(kind, Some(JsObj::Map { weak: false, .. }))),
10242            "WeakMap" => return Ok(matches!(kind, Some(JsObj::Map { weak: true, .. }))),
10243            "Set" => return Ok(matches!(kind, Some(JsObj::Set { weak: false, .. }))),
10244            "WeakSet" => return Ok(matches!(kind, Some(JsObj::Set { weak: true, .. }))),
10245            "Promise" => return Ok(matches!(kind, Some(JsObj::Promise { .. }))),
10246            // A RegExp is its own heap variant too, not a prototype-linked object.
10247            "RegExp" => return Ok(matches!(kind, Some(JsObj::RegExp(_)))),
10248            "Object" => {
10249                // Everything object-typed except a null-prototype object is an
10250                // Object instance.
10251                let is_obj = matches!(
10252                    kind,
10253                    Some(JsObj::Object(_))
10254                        | Some(JsObj::Array(_))
10255                        // A namespace object and a builtin function are both
10256                        // `instanceof Object`: `Math instanceof Object` is true.
10257                        | Some(JsObj::Builtin(_))
10258                        | Some(JsObj::Func(_))
10259                        | Some(JsObj::Class(_))
10260                        | Some(JsObj::Map { .. })
10261                        | Some(JsObj::Set { .. })
10262                        | Some(JsObj::Promise { .. })
10263                        | Some(JsObj::Generator { .. })
10264                        | Some(JsObj::RegExp(_))
10265                );
10266                if is_obj {
10267                    // A null-prototype object (Object.create(null) or
10268                    // setPrototypeOf(o, null)) is NOT an Object instance.
10269                    if with_host(|h| h.has_null_proto(obj)) {
10270                        return Ok(false);
10271                    }
10272                    return Ok(true);
10273                }
10274                return Ok(false);
10275            }
10276            // A Node `Buffer` IS a `Uint8Array` subclass instance.
10277            "Uint8Array" if crate::stdlib::native_tag(obj).as_deref() == Some("Buffer") => {
10278                return Ok(true);
10279            }
10280            // Every typed array carries the same `TypedArray` tag; the constructor
10281            // it is an instance of is its ELEMENT KIND.
10282            k if crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray") => {
10283                return Ok(crate::stdlib::typedarray::kind_of(obj) == k);
10284            }
10285            // A native-tagged instance (`WeakRef`, `FinalizationRegistry`,
10286            // `TextEncoder`, …) is an instance of the builtin whose name matches
10287            // its hidden `@@native` tag.
10288            // A singleton kept as a namespace is the one instance of its class
10289            // (`performance` is also an `EventTarget`).
10290            c if matches!(&kind, Some(JsObj::Builtin(n))
10291                if crate::stdlib::singleton_class(n) == Some(c)
10292                    || (n == "performance" && c == "EventTarget")) =>
10293            {
10294                return Ok(true);
10295            }
10296            other => {
10297                if crate::stdlib::native_tag(obj).as_deref() == Some(other) {
10298                    return Ok(true);
10299                }
10300            }
10301        }
10302    }
10303    with_host(|h| h.ensure_error_protos());
10304    // The native exotic prototypes are built lazily; `instanceof` may be the
10305    // first thing to ask for them, so materialise them before the chain walk.
10306    with_host(|h| h.ensure_native_protos());
10307    let target = match with_host(|h| ctor_prototype(h, ctor)) {
10308        Some(p) => p,
10309        None => {
10310            // 7.3.21 step 5: `C.prototype` that is not an object is a
10311            // TypeError. A function with no `[[Construct]]` (an arrow, a
10312            // method, an async function) has no `prototype` at all.
10313            let no_ctor = with_host(|h| match h.get(ctor) {
10314                Some(JsObj::Func(fv)) => {
10315                    fv.is_arrow
10316                        || h.funcs
10317                            .get(fv.def_id)
10318                            .is_some_and(|d| d.is_async || d.is_method)
10319                }
10320                _ => false,
10321            });
10322            if no_ctor {
10323                return Err(type_error(
10324                    "Function has non-object prototype 'undefined' in instanceof check",
10325                ));
10326            }
10327            return Ok(false);
10328        }
10329    };
10330    let mut cur = with_host(|h| h.proto_of(obj));
10331    while let Some(p) = cur {
10332        if with_host(|h| h.strict_eq(&p, &target)) {
10333            return Ok(true);
10334        }
10335        cur = with_host(|h| h.proto_of(&p));
10336    }
10337    Ok(false)
10338}
10339
10340// ── generators (stackful coroutines, same-thread via corosensei) ─────────────
10341
10342impl JsHost {
10343    /// Swap the volatile execution context in one shot, returning the previous
10344    /// one — installs a generator's context on resume, pulls it back on suspend.
10345    fn install_gen_ctx(&mut self, mut c: GenContext) -> GenContext {
10346        self.settle_op_pos();
10347        std::mem::swap(&mut self.frames, &mut c.frames);
10348        std::mem::swap(&mut self.error, &mut c.error);
10349        std::mem::swap(&mut self.exc, &mut c.exc);
10350        std::mem::swap(&mut self.signal, &mut c.signal);
10351        c
10352    }
10353    pub fn is_generator_val(&self, v: &Value) -> bool {
10354        matches!(self.get(v), Some(JsObj::Generator { .. }))
10355    }
10356    /// Whether `v` is an ASYNC generator object — the borrow-free form of
10357    /// [`is_async_generator`], usable from code already holding the host.
10358    pub fn is_async_gen_val(&self, v: &Value) -> bool {
10359        match self.get(v) {
10360            Some(JsObj::Generator { id }) => self
10361                .generators
10362                .get(*id as usize)
10363                .map(|g| g.async_gen)
10364                .unwrap_or(false),
10365            _ => false,
10366        }
10367    }
10368    pub fn gen_done(&self, id: u32) -> bool {
10369        self.generators
10370            .get(id as usize)
10371            .map(|g| g.done)
10372            .unwrap_or(true)
10373    }
10374    fn gen_started(&self, id: u32) -> bool {
10375        self.generators
10376            .get(id as usize)
10377            .map(|g| g.started)
10378            .unwrap_or(false)
10379    }
10380}
10381
10382/// Build a suspended generator whose body is `chunk`, run in a frame with the
10383/// already-bound `env`. Nothing executes until the first `gen_resume`. The
10384/// frame's home class/object and arrow-ness come from the function value `fv`.
10385fn make_generator(
10386    chunk: Chunk,
10387    env: Env,
10388    this_val: Option<Value>,
10389    fv: &FuncVal,
10390    strict: bool,
10391    owner: Option<String>,
10392) -> Value {
10393    let home = fv
10394        .home_class
10395        .as_ref()
10396        .and_then(|n| with_host(|h| h.class_registry.get(n).cloned()));
10397    let frame = Frame {
10398        base_env: env.clone(),
10399        env,
10400        this_obj: this_val,
10401        new_target: None,
10402        home_class: home,
10403        home_static: fv.home_static,
10404        home_object: fv.home_object.clone(),
10405        strict,
10406        line: 0,
10407        pos: 0,
10408        arrow: fv.is_arrow,
10409        owner,
10410        is_module: false,
10411        this_state: ThisState::Plain,
10412    };
10413    let id = with_host(|h| {
10414        let id = h.generators.len() as u32;
10415        h.generators.push(GenCell {
10416            coro: None,
10417            yielder: std::ptr::null(),
10418            ctx: GenContext {
10419                frames: vec![frame],
10420                ..GenContext::default()
10421            },
10422            done: false,
10423            started: false,
10424            inject: None,
10425            async_gen: false,
10426            queue: std::collections::VecDeque::new(),
10427            running: false,
10428            stack_floor: 0,
10429        });
10430        id
10431    });
10432    let body = move |yielder: &corosensei::Yielder<Value, Value>, _first: Value| {
10433        ensure_coroutine_floor();
10434        // Same thread → publish the yielder so `yield` (deep in the body's VM)
10435        // can reach it. Valid for the whole body lifetime.
10436        with_host(|h| h.generators[id as usize].yielder = yielder as *const _ as *const ());
10437        let r = run_chunk_on(chunk);
10438        // A `return` inside the body leaves a Return signal carrying the final
10439        // value; capture it so `.next()` reports it as the completion value.
10440        let ret = with_host(|h| match h.signal.take() {
10441            Some(Signal::Return(v)) => v,
10442            _ => Value::Undef,
10443        });
10444        r.map(|_| ret)
10445    };
10446    // The body's stack is allocated here rather than left to `Coroutine::new` so
10447    // that its size is ours to choose and, above all, so its `limit()` is known:
10448    // that address is what `stack_exhausted` must compare against while the body
10449    // runs, since a coroutine does NOT run on the thread stack pthread reports.
10450    // A refused reservation still yields a working generator on corosensei's own
10451    // 1 MiB default, with a floor derived on entry instead.
10452    let (coro, floor) = match corosensei::stack::DefaultStack::new(CORO_STACK_SIZE) {
10453        Ok(stack) => {
10454            let floor = coro_stack_floor(&stack);
10455            (corosensei::Coroutine::with_stack(stack, body), floor)
10456        }
10457        Err(_) => (corosensei::Coroutine::new(body), 0),
10458    };
10459    with_host(|h| {
10460        h.generators[id as usize].coro = Some(coro);
10461        h.generators[id as usize].stack_floor = floor;
10462    });
10463    with_host(|h| h.alloc(JsObj::Generator { id }))
10464}
10465
10466/// `yield v` — suspend the running generator, handing `v` to the resumer; returns
10467/// the value the next `gen_resume(x)` supplies (a `.next(x)` argument).
10468pub fn gen_yield(v: Value) -> Result<Value, String> {
10469    let id = match CUR_GEN.with(|c| c.get()) {
10470        Some(id) => id,
10471        None => return Err(type_error("yield outside a generator")),
10472    };
10473    let yp = with_host(|h| h.generators[id as usize].yielder);
10474    // SAFETY: same-thread coroutine; the yielder lives for the whole body, and we
10475    // only reach here from inside that body (its stack is live).
10476    let yielder = unsafe { &*(yp as *const corosensei::Yielder<Value, Value>) };
10477    let sent = yielder.suspend(v);
10478    // On resume, a `.return(v)`/`.throw(e)` may have queued a forced completion:
10479    // convert it into a Return signal / thrown value so the body unwinds and any
10480    // `finally` runs, exactly as a source-level `return`/`throw` would.
10481    if let Some(inj) = with_host(|h| h.generators[id as usize].inject.take()) {
10482        match inj {
10483            GenInject::Return(rv) => {
10484                with_host(|h| h.signal = Some(Signal::Return(rv)));
10485                return Ok(Value::Undef);
10486            }
10487            GenInject::Throw(ev) => {
10488                let msg = with_host(|h| crate::builtins::error_string(h, &ev));
10489                with_host(|h| h.exc = Some(ev));
10490                return Err(msg);
10491            }
10492        }
10493    }
10494    Ok(sent)
10495}
10496
10497/// `generator.return(v)`: force the generator to complete, running any pending
10498/// `finally`. If it is already done (or never started) it just reports
10499/// `{value:v, done:true}` without executing the body.
10500pub fn gen_return(gen: &Value, v: Value) -> Result<GenStep, String> {
10501    let id = match with_host(|h| h.get(gen).cloned()) {
10502        Some(JsObj::Generator { id }) => id,
10503        _ => return Err(type_error("not a generator")),
10504    };
10505    // Not started yet (coro present, ctx never resumed) OR already done → no body
10506    // to unwind: complete immediately with the supplied value.
10507    let started = with_host(|h| h.gen_started(id));
10508    if with_host(|h| h.generators[id as usize].done) || !started {
10509        with_host(|h| h.generators[id as usize].done = true);
10510        return Ok(GenStep::Done(v));
10511    }
10512    with_host(|h| h.generators[id as usize].inject = Some(GenInject::Return(v)));
10513    gen_resume(gen, Value::Undef)
10514}
10515
10516/// `generator.throw(e)`: inject a throw at the suspension point, running any
10517/// pending `finally` and letting an enclosing `try/catch` in the body handle it.
10518pub fn gen_throw(gen: &Value, e: Value) -> Result<GenStep, String> {
10519    let id = match with_host(|h| h.get(gen).cloned()) {
10520        Some(JsObj::Generator { id }) => id,
10521        _ => return Err(type_error("not a generator")),
10522    };
10523    let started = with_host(|h| h.gen_started(id));
10524    if with_host(|h| h.generators[id as usize].done) || !started {
10525        // A throw into a done/unstarted generator propagates to the caller.
10526        with_host(|h| h.generators[id as usize].done = true);
10527        let msg = with_host(|h| crate::builtins::error_string(h, &e));
10528        with_host(|h| h.exc = Some(e));
10529        return Err(msg);
10530    }
10531    with_host(|h| h.generators[id as usize].inject = Some(GenInject::Throw(e)));
10532    gen_resume(gen, Value::Undef)
10533}
10534
10535/// Outcome of resuming a generator: a yielded value (not done), or the final
10536/// completion value (done).
10537pub enum GenStep {
10538    Yield(Value),
10539    Done(Value),
10540}
10541
10542/// Resume a generator until its next `yield` or its body returns. Preserves the
10543/// shared host: the coroutine is taken out so the body re-enters `with_host`
10544/// freely, and the volatile context is swapped so the caller's frames/signal
10545/// survive the switch.
10546pub fn gen_resume(gen: &Value, send: Value) -> Result<GenStep, String> {
10547    let id = match with_host(|h| h.get(gen).cloned()) {
10548        Some(JsObj::Generator { id }) => id,
10549        _ => return Err(type_error("not a generator")),
10550    };
10551    if with_host(|h| h.generators[id as usize].done) {
10552        return Ok(GenStep::Done(Value::Undef));
10553    }
10554    let mut coro = match with_host(|h| h.generators[id as usize].coro.take()) {
10555        Some(c) => c,
10556        None => return Err("TypeError: generator already executing".into()),
10557    };
10558    with_host(|h| h.generators[id as usize].started = true);
10559    let gen_ctx = with_host(|h| std::mem::take(&mut h.generators[id as usize].ctx));
10560    let mut caller_ctx = with_host(|h| {
10561        let mut caller = h.install_gen_ctx(gen_ctx);
10562        h.outer_frames.push(std::mem::take(&mut caller.frames));
10563        caller
10564    });
10565    let prev = CUR_GEN.with(|c| c.replace(Some(id)));
10566    // The body runs on the coroutine's OWN stack, so the guard's floor has to
10567    // move with it and move back on suspend — generators nest, and a resume from
10568    // inside another generator must restore that one's floor, not the thread's.
10569    let coro_floor = with_host(|h| h.generators[id as usize].stack_floor);
10570    let caller_floor = swap_stack_floor(coro_floor);
10571
10572    let out = coro.resume(send); // no host borrow held; body drives its own VM
10573
10574    let measured = swap_stack_floor(caller_floor);
10575    // A coroutine on corosensei's default stack has no known bounds, so the
10576    // floor it measured for itself on first entry is kept for later resumes.
10577    if coro_floor == 0 && measured != 0 {
10578        with_host(|h| h.generators[id as usize].stack_floor = measured);
10579    }
10580    CUR_GEN.with(|c| c.set(prev));
10581    let mut gen_ctx = with_host(|h| {
10582        caller_ctx.frames = h.outer_frames.pop().unwrap_or_default();
10583        h.install_gen_ctx(caller_ctx)
10584    });
10585    // A `throw` inside the body left the thrown VALUE in the generator's context,
10586    // which the swap above just stashed away. Hand it to the caller so the
10587    // rejection/catch keeps the original error object instead of a string rebuild.
10588    let thrown = gen_ctx.exc.take();
10589    with_host(|h| {
10590        if let Some(v) = thrown {
10591            h.exc = Some(v);
10592        }
10593        h.generators[id as usize].ctx = gen_ctx;
10594        h.generators[id as usize].coro = Some(coro);
10595    });
10596
10597    match out {
10598        corosensei::CoroutineResult::Yield(y) => Ok(GenStep::Yield(y)),
10599        corosensei::CoroutineResult::Return(r) => {
10600            // Release the coroutine — and with it the mmap'd stack it owns —
10601            // the moment the body completes. `h.generators` only ever grows (an
10602            // id is never reused), so a program that awaits in a loop otherwise
10603            // accumulates one whole [`CORO_STACK_SIZE`] reservation per call for
10604            // the life of the process. A finished generator is never resumed:
10605            // `gen_resume` returns `Done` on the `done` flag before it looks.
10606            with_host(|h| {
10607                let g = &mut h.generators[id as usize];
10608                g.done = true;
10609                g.coro = None;
10610            });
10611            match r {
10612                Ok(v) => Ok(GenStep::Done(v)),
10613                Err(e) => Err(e),
10614            }
10615        }
10616    }
10617}
10618
10619/// Force a generator to completion (used by `.return()` and abandoned loops):
10620/// marks it done without running further.
10621pub fn gen_close(gen: &Value) {
10622    if let Some(JsObj::Generator { id }) = with_host(|h| h.get(gen).cloned()) {
10623        with_host(|h| h.generators[id as usize].done = true);
10624    }
10625}
10626
10627// ── iteration protocol (arrays, strings, Map/Set, generators, Symbol.iterator) ─
10628
10629/// Convert a Map/Set key value into a `MapKey` under SameValueZero.
10630pub fn map_key(h: &JsHost, v: &Value) -> MapKey {
10631    match v {
10632        Value::Undef => MapKey::Undef,
10633        Value::Bool(b) => MapKey::Bool(*b),
10634        Value::Int(n) => MapKey::Num(norm_num_bits(*n as f64)),
10635        Value::Float(f) => MapKey::Num(norm_num_bits(*f)),
10636        Value::Str(s) => MapKey::Str((**s).clone()),
10637        Value::Obj(i) => match h.get(v) {
10638            Some(JsObj::Str(s)) => MapKey::Str(s.clone()),
10639            Some(JsObj::Null) => MapKey::Null,
10640            Some(JsObj::BigInt(b)) => MapKey::Big(b.to_string()),
10641            Some(JsObj::Builtin(n)) => MapKey::Intrinsic(builtin_identity(n).to_string()),
10642            _ => MapKey::Ref(*i),
10643        },
10644        _ => MapKey::Undef,
10645    }
10646}
10647
10648/// Canonical bit pattern for a Map/Set numeric key: `NaN` → one value, `-0` → `+0`.
10649fn norm_num_bits(f: f64) -> u64 {
10650    if f.is_nan() {
10651        return f64::NAN.to_bits();
10652    }
10653    if f == 0.0 {
10654        return 0.0f64.to_bits(); // fold -0 into +0
10655    }
10656    f.to_bits()
10657}
10658
10659/// Fully materialize any iterable into a vector of values.
10660/// Pull at most `n` values, then close the iterator — 8.6.2
10661/// IteratorBindingInitialization, which is what an array destructuring pattern
10662/// without a `...rest` element performs.
10663///
10664/// The distinction from [`iter_all`] is not an optimization. A pattern names a
10665/// fixed number of targets, so the spec pulls exactly that many and calls
10666/// IteratorClose on whatever is left; draining instead made
10667///
10668/// ```text
10669/// const [first] = infiniteGenerator();
10670/// ```
10671///
10672/// run forever. It is also observable on any finite iterator, as the count of
10673/// `next()` calls and whether `return()` ever ran.
10674///
10675/// A `...rest` element genuinely consumes the remainder, so those patterns keep
10676/// using `iter_all` and an unbounded source hangs there in node too.
10677pub fn iter_take(v: &Value, n: usize) -> Result<Vec<Value>, String> {
10678    // A Proxy's iterator comes from its traps and is stepped like any other:
10679    // only `n` steps run, so `const [a, b] = proxy` reads `length` three times
10680    // rather than once per element.
10681    if let Some(iterator) = crate::proxy::get_iterator(v)? {
10682        if with_host(|h| matches!(h.get(&iterator), Some(JsObj::Iter { .. }))) {
10683            let mut out = Vec::new();
10684            while out.len() < n {
10685                match crate::builtins::iter_step(&iterator).transpose()?.flatten() {
10686                    Some(x) => out.push(x),
10687                    None => break,
10688                }
10689            }
10690            return Ok(out);
10691        }
10692        return take_from_iterator(&iterator, n);
10693    }
10694    if with_host(|h| h.is_generator_val(v)) {
10695        let mut out = Vec::new();
10696        while out.len() < n {
10697            match gen_resume(v, Value::Undef)? {
10698                GenStep::Yield(x) => out.push(x),
10699                _ => return Ok(out), // ran out on its own; nothing left to close
10700            }
10701        }
10702        // Stopped early: `.return()` resumes it at the yield so `finally` runs,
10703        // and a throw from that `finally` is the destructuring's (7.4.11 with a
10704        // normal completion).
10705        gen_return(v, Value::Undef)?;
10706        return Ok(out);
10707    }
10708    if let Some(iter_fn) = user_iterator_fn(v) {
10709        let iterator = call_iterator_method(&iter_fn, v)?;
10710        return take_from_iterator(&iterator, n);
10711    }
10712    // Arrays, strings, Map/Set: already materialized, and their built-in
10713    // iterators carry no `return`, so there is nothing to close. The same
10714    // reachability rule as `iter_all` applies — this is the DESTRUCTURING
10715    // entry point, and `const [x] = a` bound 1 from an array whose prototype no
10716    // longer carried `Symbol.iterator`.
10717    if !crate::builtins::own_intrinsic_reachable_pub(v) {
10718        let shown = with_host(|h| h.inspect(v));
10719        return Err(type_error(&format!("{shown} is not iterable")));
10720    }
10721    with_host(|h| h.iter_vec(v)).map(|items| items.into_iter().take(n).collect())
10722}
10723
10724/// Up to `n` steps of a protocol iterator object, then IteratorClose if it did
10725/// not run out on its own.
10726fn take_from_iterator(iterator: &Value, n: usize) -> Result<Vec<Value>, String> {
10727    let mut out = Vec::new();
10728    while out.len() < n {
10729        match iterator_step_value(iterator)? {
10730            Some(v) => out.push(v),
10731            None => return Ok(out),
10732        }
10733    }
10734    // IteratorClose (7.4.11) for a NORMAL completion: `return` is optional on
10735    // the protocol, but when present its throw propagates and its result must
10736    // be an object.
10737    if let Ok(ret) = get_prop_chain(iterator, "return") {
10738        if with_host(|h| is_callable(h, &ret)) {
10739            let result = invoke(&ret, Vec::new(), Some(iterator.clone()))?;
10740            require_iter_result(&result)?;
10741        }
10742    }
10743    Ok(out)
10744}
10745
10746/// `GetIteratorFromMethod` (7.4.3): call `@@iterator` on `src` and refuse a
10747/// result that is not an object, with V8's wording, before anything reads
10748/// `next` off it.
10749pub fn call_iterator_method(iter_fn: &Value, src: &Value) -> Result<Value, String> {
10750    let iterator = invoke(iter_fn, Vec::new(), Some(src.clone()))?;
10751    if with_host(|h| is_primitive(h, &iterator) || h.is_nullish(&iterator)) {
10752        return Err(type_error(
10753            "Result of the Symbol.iterator method is not an object",
10754        ));
10755    }
10756    Ok(iterator)
10757}
10758
10759/// [`iter_all`] for a BUILTIN consuming an iterable argument (`new Set(x)`,
10760/// `Object.fromEntries(x)`, `Promise.all(x)`): V8 has no source text to name
10761/// there, so a non-iterable is reported by type —
10762/// `number 5 is not iterable (cannot read property Symbol(Symbol.iterator))`.
10763pub fn iter_all_for_builtin(v: &Value) -> Result<Vec<Value>, String> {
10764    iter_all(v).map_err(|e| {
10765        let shown = with_host(|h| h.inspect(v));
10766        if e == type_error(&format!("{shown} is not iterable")) {
10767            type_error(&crate::builtins::not_iterable_typed(v))
10768        } else {
10769            e
10770        }
10771    })
10772}
10773
10774pub fn iter_all(v: &Value) -> Result<Vec<Value>, String> {
10775    // A Proxy iterates through its traps (see `crate::proxy::iterate`); it has
10776    // no heap variant `iter_vec` could recognise.
10777    if let Some(items) = crate::proxy::iterate(v)? {
10778        return Ok(items);
10779    }
10780    // Generators / user iterators must resume without a live host borrow.
10781    if with_host(|h| h.is_generator_val(v)) {
10782        let mut out = Vec::new();
10783        while let GenStep::Yield(x) = gen_resume(v, Value::Undef)? {
10784            out.push(x);
10785        }
10786        return Ok(out);
10787    }
10788    // A live array iterator is stepped to the end, so an accessor or a hole
10789    // reads as `a[i]` does and the iterator is left exhausted, as spreading it
10790    // leaves it in node.
10791    if with_host(|h| matches!(h.get(v), Some(JsObj::Iter { array: Some(_), .. }))) {
10792        let mut out = Vec::new();
10793        while let Some(x) = crate::builtins::iter_step(v).transpose()?.flatten() {
10794            out.push(x);
10795        }
10796        return Ok(out);
10797    }
10798    // Object with a user-defined Symbol.iterator: drive its iterator protocol.
10799    // Checked BEFORE the reachability guard below, since an own `Symbol
10800    // .iterator` makes a value iterable no matter what its prototype is.
10801    if let Some(iter_fn) = user_iterator_fn(v) {
10802        let iterator = call_iterator_method(&iter_fn, v)?;
10803        return drain_iterator(&iterator);
10804    }
10805    // The fast paths below read a builtin's backing storage directly, which is
10806    // only legitimate while that builtin's `Symbol.iterator` is still
10807    // reachable: replacing the prototype takes it away, and node then reports
10808    // the value as not iterable. Spread, destructuring and `Array.from`'s
10809    // iterable branch all funnel through here.
10810    if !crate::builtins::own_intrinsic_reachable_pub(v) {
10811        let shown = with_host(|h| h.inspect(v));
10812        return Err(type_error(&format!("{shown} is not iterable")));
10813    }
10814    // A String wrapper iterates its code POINTS, exactly as the primitive does
10815    // (22.1.3.34) — `[...new String("ab")]` is `["a","b"]`, not a TypeError.
10816    if let Some(prim) = crate::builtins::wrapped_primitive(v) {
10817        if with_host(|h| matches!(h.get(&prim), Some(JsObj::Str(_)))) {
10818            return iter_all(&prim);
10819        }
10820    }
10821    // An array's index ACCESSORS are not in its backing vector, so iterating one
10822    // (spread, `for-of`, `Array.from`) has to resolve them the way the
10823    // `Array.prototype` methods do.
10824    let mut items = with_host(|h| h.iter_vec(v))?;
10825    if with_host(|h| matches!(h.get(v), Some(JsObj::Array(_)))) {
10826        crate::builtins::resolve_index_accessors_pub(v, &mut items);
10827    }
10828    Ok(items)
10829}
10830
10831// ── async iteration (`for await (… of …)`) ───────────────────────────────────
10832
10833/// Obtain an async iterator for `for await`. If `src` has a `Symbol.asyncIterator`
10834/// method, use it (its `.next()` returns a promise of `{value, done}`); otherwise
10835/// fall back to the sync iterable, materialized into a `JsObj::Iter` whose values
10836/// are awaited one at a time by `async_step`.
10837pub fn get_async_iterator(src: &Value) -> Result<Value, String> {
10838    if let Some(f) = user_async_iterator_fn(src) {
10839        let iterator = invoke(&f, Vec::new(), Some(src.clone()))?;
10840        if with_host(|h| is_primitive(h, &iterator) || h.is_nullish(&iterator)) {
10841            return Err(type_error(
10842                "Result of the Symbol.asyncIterator method is not an object",
10843            ));
10844        }
10845        return Ok(iterator);
10846    }
10847    // An `async function*` object IS its own async iterator; draining it into a
10848    // list here would run the whole body (and any `finally`) before the consumer
10849    // sees the first value.
10850    if let Some(JsObj::Generator { id }) = with_host(|h| h.get(src).cloned()) {
10851        if with_host(|h| h.generators[id as usize].async_gen) {
10852            return Ok(src.clone());
10853        }
10854    }
10855    let items = iter_all(src)?;
10856    Ok(with_host(|h| {
10857        h.alloc(JsObj::Iter {
10858            items,
10859            idx: 0,
10860            array: None,
10861            brand: None,
10862        })
10863    }))
10864}
10865
10866/// If `v` has an own/inherited `Symbol.asyncIterator` method, return it.
10867fn user_async_iterator_fn(v: &Value) -> Option<Value> {
10868    // A PROXY supplies the protocol through its `get` trap and is not a plain
10869    // object, so the shape test below rejects it outright.
10870    if with_host(|h| h.kind_of(v)) == Some(ObjKind::Proxy) {
10871        return protocol_lookup(v, "@@asyncIterator")
10872            .ok()
10873            .flatten()
10874            .filter(|f| with_host(|h| is_callable(h, f)));
10875    }
10876    let is_plain = with_host(|h| matches!(h.get(v), Some(JsObj::Object(_))));
10877    if !is_plain {
10878        return None;
10879    }
10880    // Full property resolution, not a stored-property lookup — the same reason
10881    // `user_iterator_fn` does it for the SYNC protocol. A NATIVE-tagged object
10882    // dispatches its methods through the stdlib method table rather than a
10883    // property map, so `lookup_chain` reported no `Symbol.asyncIterator` for one
10884    // even though reading it gives a function: `for await (const v of
10885    // timersPromises.setInterval(…))` said the iterator "is not iterable".
10886    let f = crate::builtins::get_property(v, "@@asyncIterator").ok()?;
10887    with_host(|h| is_callable(h, &f)).then_some(f)
10888}
10889
10890/// One step of a `for await` loop: return a Promise that settles to a
10891/// `{value, done}` record. For a native async iterator this is `iter.next()`
10892/// (already a promise of the record). For the sync fallback it pops the next raw
10893/// value, awaits it, and packages `{value: resolved, done:false}` (or
10894/// `{done:true}` at exhaustion).
10895pub fn async_step(iterator: &Value) -> Result<Value, String> {
10896    // An `async function*` object: resume it through the await-aware driver.
10897    if let Some(JsObj::Generator { id }) = with_host(|h| h.get(iterator).cloned()) {
10898        if with_host(|h| h.generators[id as usize].async_gen) {
10899            return Ok(async_gen_step(iterator, Value::Undef));
10900        }
10901    }
10902    // Sync-fallback iterator: drive it here, awaiting each yielded value.
10903    if let Some(JsObj::Iter { items, idx, .. }) = with_host(|h| h.get(iterator).cloned()) {
10904        if idx >= items.len() {
10905            // `AsyncFromSyncIteratorContinuation` resolves the record THROUGH a
10906            // promise even at exhaustion, so the `done: true` step costs the same
10907            // two microtask ticks a value step does.
10908            let step = with_host(|h| h.new_promise());
10909            let sid = with_host(|h| h.promise_id(&step).unwrap());
10910            with_host(|h| {
10911                h.queue_micro_native(Box::new(move || {
10912                    resolve_promise_val(sid, iter_record(Value::Undef, true));
10913                    Ok(())
10914                }))
10915            });
10916            return Ok(step);
10917        }
10918        let raw = items[idx].clone();
10919        with_host(|h| {
10920            if let Some(JsObj::Iter { idx, .. }) = h.get_mut(iterator) {
10921                *idx += 1;
10922            }
10923        });
10924        // Await the raw value (adopts a promise's resolution), then wrap.
10925        let step = with_host(|h| h.new_promise());
10926        let sid = with_host(|h| h.promise_id(&step).unwrap());
10927        let raw_p = promise_of(&raw);
10928        let raw_id = with_host(|h| h.promise_id(&raw_p).unwrap());
10929        subscribe_native(
10930            raw_id,
10931            Box::new(move |state, val| {
10932                if state == PromiseState::Rejected {
10933                    reject_promise_val(sid, val);
10934                } else {
10935                    resolve_promise_val(sid, iter_record(val, false));
10936                }
10937                Ok(())
10938            }),
10939        );
10940        return Ok(step);
10941    }
10942    // Native async iterator: `iter.next()` returns the {value,done} promise.
10943    // Whether what it settles to is an object is checked after the `await`
10944    // (`ITER_RESULT`), which adds no microtask turn of its own.
10945    let r = call_method(iterator, "next", Vec::new())?;
10946    Ok(promise_of(&r))
10947}
10948
10949/// If `v` has an own/inherited `Symbol.iterator` method (internal key
10950/// `@@iterator`), return it. Arrays/strings use the native fast path instead.
10951pub fn user_iterator_fn(v: &Value) -> Option<Value> {
10952    let is_plain = with_host(|h| matches!(h.get(v), Some(JsObj::Object(_))));
10953    if !is_plain {
10954        return None;
10955    }
10956    // Full property resolution, not a stored-property lookup: a NATIVE-tagged
10957    // object (`URLSearchParams`, `Headers`) dispatches its methods through the
10958    // stdlib method table rather than a property map, so `lookup_chain` reported
10959    // no `Symbol.iterator` for one even though reading it gave a function —
10960    // `[...new URLSearchParams('a=1')]` threw `{} is not iterable`.
10961    let f = crate::builtins::get_property(v, "@@iterator").ok()?;
10962    with_host(|h| is_callable(h, &f)).then_some(f)
10963}
10964
10965/// [`iter_for_each`] for a BUILTIN consuming an iterable argument, with the
10966/// type-named not-iterable wording of [`iter_all_for_builtin`].
10967pub fn iter_for_each_for_builtin(
10968    src: &Value,
10969    mut f: impl FnMut(Value, usize) -> Result<(), String>,
10970) -> Result<(), String> {
10971    // Mapped only when the failure came before any element was visited, so a
10972    // callback's own error is never reworded. Nothing is probed up front: that
10973    // would consume a generator.
10974    let mut visited = false;
10975    let r = iter_for_each(src, |v, i| {
10976        visited = true;
10977        f(v, i)
10978    });
10979    match r {
10980        Err(e) if !visited => {
10981            let shown = with_host(|h| h.inspect(src));
10982            if e == type_error(&format!("{shown} is not iterable")) {
10983                Err(type_error(&crate::builtins::not_iterable_typed(src)))
10984            } else {
10985                Err(e)
10986            }
10987        }
10988        r => r,
10989    }
10990}
10991
10992/// Drive an iterator object (one with a `.next()` returning `{value, done}`) to
10993/// exhaustion.
10994/// Step `src`'s iterator, handing each value to `f`, and CLOSE the iterator if
10995/// `f` exits abruptly (7.4.9 IteratorClose).
10996///
10997/// The difference from `iter_all` + a loop is that this never materializes the
10998/// whole sequence: `Array.from(infinite, mapFn)` where `mapFn` throws has to
10999/// stop at the first call, and draining first means it never gets there at all.
11000pub fn iter_for_each(
11001    src: &Value,
11002    mut f: impl FnMut(Value, usize) -> Result<(), String>,
11003) -> Result<(), String> {
11004    // Only a USER iterator can be infinite or observe its own close; every
11005    // other shape is already a finite materialized sequence.
11006    let Some(iter_fn) = user_iterator_fn(src) else {
11007        for (i, v) in iter_all(src)?.into_iter().enumerate() {
11008            f(v, i)?;
11009        }
11010        return Ok(());
11011    };
11012    let iterator = call_iterator_method(&iter_fn, src)?;
11013    let mut i = 0usize;
11014    loop {
11015        let Some(value) = iterator_step_value(&iterator)? else {
11016            return Ok(());
11017        };
11018        if let Err(e) = f(value, i) {
11019            // The callback's error wins over anything `return()` raises, so a
11020            // throwing `return` is swallowed here (7.4.9 step 6).
11021            let _ = close_iterator(&iterator);
11022            return Err(e);
11023        }
11024        i += 1;
11025    }
11026}
11027
11028/// Call `iterator.return()` if it has one, as IteratorClose does.
11029pub fn close_iterator(iterator: &Value) -> Result<(), String> {
11030    let has = crate::builtins::get_property(iterator, "return")?;
11031    if with_host(|h| is_callable(h, &has)) {
11032        call_method(iterator, "return", Vec::new())?;
11033    }
11034    Ok(())
11035}
11036
11037pub(crate) fn drain_iterator(iterator: &Value) -> Result<Vec<Value>, String> {
11038    let mut out = Vec::new();
11039    while let Some(v) = iterator_step_value(iterator)? {
11040        out.push(v);
11041    }
11042    Ok(out)
11043}
11044
11045/// `IteratorStepValue` (7.4.8): call `next`, refuse a result that is not an
11046/// object, then read `done` and — unless done — `value`. Without the object
11047/// check a `next` returning a primitive read `done` as `undefined` forever, so
11048/// the loop never ended.
11049pub fn iterator_step_value(iterator: &Value) -> Result<Option<Value>, String> {
11050    // `GetIteratorFromMethod` reads `next` once and every step CALLS that
11051    // value, so a missing one is `undefined is not a function`, not a method
11052    // lookup failure on the iterator.
11053    let next = get_prop_chain(iterator, "next")?;
11054    if !with_host(|h| is_callable(h, &next)) {
11055        return Err(type_error(&not_a_function_message(&next)));
11056    }
11057    let result = call_method(iterator, "next", Vec::new())?;
11058    require_iter_result(&result)?;
11059    // Read first: resolving the property re-enters the host, so doing it
11060    // inside the `with_host` closure double-borrows and aborts.
11061    let done = get_prop_chain(&result, "done")?;
11062    if with_host(|h| h.truthy(&done)) {
11063        return Ok(None);
11064    }
11065    get_prop_chain(&result, "value").map(Some)
11066}
11067
11068/// 7.4.4 `IteratorNext` step 3: an iterator result must be an object.
11069pub fn require_iter_result(result: &Value) -> Result<(), String> {
11070    let object = with_host(|h| {
11071        matches!(result, Value::Obj(_)) && !h.is_null(result) && !is_primitive(h, result)
11072    });
11073    if object {
11074        return Ok(());
11075    }
11076    Err(type_error(&format!(
11077        "Iterator result {} is not an object",
11078        crate::builtins::no_side_effects_string_pub(result)
11079    )))
11080}
11081
11082/// Property read that walks the prototype chain (used by iteration helpers).
11083/// Whether the builtin named `n` is CALLABLE. Most are (`Array`, `parseInt`,
11084/// `Math.floor`); the exceptions are the namespace objects a script can only
11085/// read properties off (`Math`, `JSON`, every `require()`d core module), which
11086/// report `typeof === "object"` and carry no `name`/`length`.
11087pub fn builtin_is_callable(n: &str) -> bool {
11088    // A `<Ctor>.prototype` handle is a namespace of methods, not a function:
11089    // `typeof Set.prototype` is `"object"`, and treating it as callable made it
11090    // brand `[object Function]`, inspect as `[Function: prototype]`, and answer
11091    // `true` to `instanceof Function`. `Function.prototype` is the one that
11092    // really IS callable (10.2.4: it is an anonymous built-in that returns
11093    // undefined), which is why it is not stripped here.
11094    if n != "Function.prototype" && n.ends_with(".prototype") {
11095        return false;
11096    }
11097    // A `match` rather than a slice scan: this runs on every callability test,
11098    // which is every call and every `ToPrimitive`, and a `contains` over the
11099    // list below compares against all 56 entries before answering "callable" —
11100    // the common case. The compiler turns the arms into a length-then-bytes
11101    // decision tree instead.
11102    !matches!(
11103        n,
11104        "Math"
11105            | "JSON"
11106            | "console"
11107            | "Reflect"
11108            | "process"
11109            | "Atomics"
11110            | "performance"
11111            | "fs"
11112            | "path"
11113            | "os"
11114            | "util"
11115            | "util/types"
11116            | "crypto"
11117            | "webcrypto"
11118            | "SubtleCrypto"
11119            | "querystring"
11120            | "events"
11121            | "timers"
11122            | "perf_hooks"
11123            | "async_hooks"
11124            | "diagnostics_channel"
11125            | "v8"
11126            | "dns"
11127            | "punycode"
11128            | "child_process"
11129            | "tty"
11130            | "url"
11131            | "zlib"
11132            | "string_decoder"
11133            | "http"
11134            | "net"
11135            | "buffer"
11136            | "function"
11137            | "path/win32"
11138            | "fs/promises"
11139            | "stream/promises"
11140            | "stream/consumers"
11141            | "stream/web"
11142            | "timers/promises"
11143            | "dns/promises"
11144            | "https"
11145            | "http2"
11146            | "tls"
11147            | "dgram"
11148            | "cluster"
11149            | "worker_threads"
11150            | "readline"
11151            | "readline/promises"
11152            | "repl"
11153            | "vm"
11154            | "domain"
11155            | "trace_events"
11156            | "wasi"
11157            | "inspector"
11158            | "object"
11159    )
11160        // The live `require.cache` view is a plain object to a script, not
11161        // something it can call.
11162        && n != crate::builtins::REQUIRE_CACHE
11163}
11164
11165pub fn get_prop_chain(recv: &Value, name: &str) -> Result<Value, String> {
11166    crate::builtins::get_property(recv, name)
11167}
11168
11169/// Whether `v` is an ECMAScript primitive, i.e. `ToPrimitive` is the identity
11170/// on it. `undefined`, `null`, booleans, numbers, strings, symbols and bigints
11171/// qualify; every other heap cell (objects, arrays, functions, `Map`/`Set`,
11172/// native-tagged instances) is an object and must be converted.
11173pub fn is_primitive(h: &JsHost, v: &Value) -> bool {
11174    match v {
11175        Value::Obj(_) => matches!(
11176            h.get(v),
11177            None | Some(JsObj::Null)
11178                | Some(JsObj::Str(_))
11179                | Some(JsObj::Symbol { .. })
11180                | Some(JsObj::BigInt(_))
11181        ),
11182        _ => true,
11183    }
11184}
11185
11186/// `ToPrimitive(v, hint)` — ECMA-262 7.1.1. `hint` is `"default"`, `"number"`
11187/// or `"string"`.
11188///
11189/// An object carrying a `Symbol.toPrimitive` method (internal key
11190/// `@@toPrimitive`) has it called with the hint and must return a primitive.
11191/// Otherwise `OrdinaryToPrimitive` (7.1.1.1) tries `valueOf` then `toString` —
11192/// the order reversed for the string hint — and takes the FIRST call whose
11193/// result is a primitive. An object that yields no primitive (a null-prototype
11194/// object has neither method) throws V8's
11195/// `TypeError: Cannot convert object to primitive value`.
11196///
11197/// This is the conversion behind `+`, `-`/`*`/`/`/`%`/`**`, the relational
11198/// operators, `==` against a primitive, and `ToPropertyKey` — all of which used
11199/// to read `str_of` directly and so never invoked a user `valueOf`.
11200pub fn to_primitive(v: &Value, hint: &str) -> Result<Value, String> {
11201    if with_host(|h| is_primitive(h, v)) {
11202        return Ok(v.clone());
11203    }
11204    if let Some(f) = protocol_lookup(v, "@@toPrimitive")? {
11205        if with_host(|h| is_callable(h, &f)) {
11206            let hv = with_host(|h| h.new_str(hint.to_string()));
11207            let r = invoke(&f, vec![hv], Some(v.clone()))?;
11208            if with_host(|h| is_primitive(h, &r)) {
11209                return Ok(r);
11210            }
11211            return Err(type_error("Cannot convert object to primitive value"));
11212        }
11213        // 7.3.11 GetMethod: a present, non-nullish, non-callable value is a
11214        // TypeError, worded the way V8 words a bad callee (type, then value).
11215        if !with_host(|h| h.is_nullish(&f)) {
11216            return Err(type_error(&format!(
11217                "{} is not a function",
11218                describe_non_callable(&f)
11219            )));
11220        }
11221    }
11222    // `Date.prototype[@@toPrimitive]` (21.4.4.45) treats the DEFAULT hint as
11223    // `"string"`, which is why `new Date() + 1` concatenates while
11224    // `new Date() - 1` is arithmetic.
11225    let hint = if hint == "default" && crate::stdlib::native_tag(v).as_deref() == Some("Date") {
11226        "string"
11227    } else {
11228        hint
11229    };
11230    ordinary_to_primitive(v, hint)
11231}
11232
11233/// V8's rendering of a non-callable value in an "is not a function" message
11234/// for a `GetMethod` failure: `number 7`, `string "s"`, `boolean true`, and the
11235/// bare type name for everything else.
11236fn describe_non_callable(v: &Value) -> String {
11237    with_host(|h| {
11238        let t = h.type_of(v);
11239        match t {
11240            "number" | "boolean" => format!("{t} {}", h.str_of(v)),
11241            "string" => format!("string \"{}\"", h.str_of(v)),
11242            _ => t.to_string(),
11243        }
11244    })
11245}
11246
11247/// `OrdinaryToPrimitive(O, hint)` (7.1.1.1): `valueOf` then `toString`, the
11248/// order reversed for the `"string"` hint, each read with `[[Get]]`; the first
11249/// call that returns a primitive wins.
11250pub fn ordinary_to_primitive(v: &Value, hint: &str) -> Result<Value, String> {
11251    let order = if hint == "string" {
11252        ["toString", "valueOf"]
11253    } else {
11254        ["valueOf", "toString"]
11255    };
11256    // Whether either candidate was actually CALLED. The `[object Tag]` fallback
11257    // below is for exotics whose property funnel exposes no callable
11258    // `toString`, not for an object whose own methods ran and returned
11259    // non-primitives — that case is the spec's TypeError, and branding it
11260    // instead meant `({ valueOf: () => ({}), toString: () => ({}) }) + 1`
11261    // quietly produced `"[object Object]1"`.
11262    let mut called_any = false;
11263    for m in order {
11264        let f = crate::builtins::get_property(v, m).unwrap_or(Value::Undef);
11265        if !with_host(|h| is_callable(h, &f)) {
11266            continue;
11267        }
11268        called_any = true;
11269        // On a Proxy the resolved method is a thunk bound to the TARGET, so
11270        // invoking it directly would stringify the target — `String(new
11271        // Proxy(function f(){}, {}))` reported `f`'s source where V8 reports the
11272        // native-code form. `call_proxy_method` re-dispatches the generic
11273        // `Function.prototype`/`Object.prototype` methods against the proxy,
11274        // reusing the method already read here (the `get` trap fires once).
11275        let r = if with_host(|h| h.kind_of(v)) == Some(ObjKind::Proxy) {
11276            call_proxy_method(v, m, f, Vec::new())?
11277        } else {
11278            invoke(&f, Vec::new(), Some(v.clone()))?
11279        };
11280        if with_host(|h| is_primitive(h, &r)) {
11281            return Ok(r);
11282        }
11283    }
11284    // Every object except a null-prototype one inherits `Object.prototype
11285    // .toString`, which always returns a string — so the exhausted-methods
11286    // TypeError is reachable only there. The exotics whose property funnel has
11287    // no `toString` entry of its own (`Map`, `Set`, `Promise`, …) land here and
11288    // get the same `[object Tag]` brand V8 gives them.
11289    // A proxy WITH a `get` trap is not one of those exotics: the trap answered
11290    // for both method names, and if what came back was not callable there is
11291    // nothing left to call — `String(new Proxy({}, { get: () => undefined }))`
11292    // is a TypeError on node, where branding it `[object Object]` invented a
11293    // conversion the trap explicitly refused. A TRAPLESS proxy is different: its
11294    // read forwarded to the target, so `String(new Proxy(new Map(), {}))` gets
11295    // the target's `[object Map]` brand exactly as the bare `Map` does.
11296    if !called_any && !with_host(|h| h.has_null_proto(v)) && !crate::proxy::has_trap(v, "get") {
11297        return crate::builtins::proto_method(v, "Object:toString", Vec::new());
11298    }
11299    Err(type_error("Cannot convert object to primitive value"))
11300}
11301
11302/// `ToString(v)` with `ToPrimitive` method dispatch: an object is converted
11303/// with the string hint (so a user `toString` — or `valueOf`, if `toString`
11304/// is absent or returns an object — is invoked), then rendered by `str_of`.
11305/// Returns a heap string value.
11306pub fn to_string_value(v: &Value) -> Result<Value, String> {
11307    let p = to_primitive(v, "string")?;
11308    // `ToString(symbol)` throws (7.1.17 step 2) — the ONLY conversion a symbol
11309    // refuses. `String(sym)` is the documented exception and is handled at that
11310    // call site, not here, so every implicit coercion (`sym + ''`, `` `${sym}` ``,
11311    // `[sym].join()`) rejects the way node does instead of silently rendering
11312    // `Symbol(desc)`.
11313    if with_host(|h| matches!(h.get(&p), Some(JsObj::Symbol { .. }))) {
11314        return Err(type_error("Cannot convert a Symbol value to a string"));
11315    }
11316    Ok(with_host(|h| {
11317        let s = h.str_of(&p);
11318        h.new_str(s)
11319    }))
11320}
11321
11322/// `String(v)` — 22.1.1.1. Identical to [`to_string_value`] except that a
11323/// SYMBOL argument is allowed and renders as `Symbol(desc)` (step 2a).
11324pub fn string_ctor_value(v: &Value) -> Result<Value, String> {
11325    if with_host(|h| matches!(h.get(v), Some(JsObj::Symbol { .. }))) {
11326        return Ok(with_host(|h| {
11327            let s = h.str_of(v);
11328            h.new_str(s)
11329        }));
11330    }
11331    to_string_value(v)
11332}
11333
11334/// `ToNumber(v)` — ECMA-262 7.1.4 — with the object case going through
11335/// `ToPrimitive(v, number)` first, so `+{ valueOf() { return 7 } }` is `7` and
11336/// `+new Date(0)` is `0`. `JsHost::to_number` alone cannot do this: it runs
11337/// under the host borrow and so can never invoke a JS `valueOf`.
11338pub fn to_number_value(v: &Value) -> Result<f64, String> {
11339    // `ToNumber(symbol)` throws (7.1.4 step 2). It is primitive, so without this
11340    // it fell into `to_number` and quietly produced `NaN` — `Number(Symbol())`
11341    // and `+Symbol()` are both `TypeError` on node v26.7.0.
11342    if with_host(|h| matches!(h.get(v), Some(JsObj::Symbol { .. }))) {
11343        return Err(type_error("Cannot convert a Symbol value to a number"));
11344    }
11345    // A BigInt PRIMITIVE is refused here too (7.1.4 step 2 is only about symbols
11346    // and BigInts together: `ToNumber(1n)` throws). Only the post-`ToPrimitive`
11347    // check below caught a boxed one.
11348    if with_host(|h| matches!(h.get(v), Some(JsObj::BigInt(_)))) {
11349        return Err(type_error("Cannot convert a BigInt value to a number"));
11350    }
11351    if let Some(n) = with_host(|h| is_primitive(h, v).then(|| h.to_number(v))) {
11352        return Ok(n);
11353    }
11354    let p = to_primitive(v, "number")?;
11355    // Steps 2-3 apply to the ToPrimitive RESULT, not only to the argument. Only
11356    // the argument was checked, so an object whose conversion yields a symbol or
11357    // a BigInt slipped past: `+Object(9n)` answered 9 and
11358    // `+{ [Symbol.toPrimitive]() { return Symbol('s') } }` answered NaN, where
11359    // both are TypeErrors. `Number(x)` is ToNumeric and keeps its own path,
11360    // which is why `Number(Object(9n))` is still 9.
11361    match with_host(|h| h.get(&p).cloned()) {
11362        Some(JsObj::Symbol { .. }) => Err(type_error("Cannot convert a Symbol value to a number")),
11363        Some(JsObj::BigInt(_)) => Err(type_error("Cannot convert a BigInt value to a number")),
11364        _ => Ok(with_host(|h| h.to_number(&p))),
11365    }
11366}
11367
11368/// `ToPropertyKey(v)` — ECMA-262 7.1.19. A symbol keeps its stable internal
11369/// key; anything else is `ToPrimitive(v, string)` then `ToString`, so
11370/// `obj[{ toString() { return 'k' } }]` really reads `obj.k`.
11371pub fn to_property_key(v: &Value) -> Result<String, String> {
11372    // One borrow for the overwhelmingly common primitive key (`a[i]`, `o[s]`,
11373    // `o[sym]`); only an object key pays for the conversion.
11374    if let Some(k) = with_host(|h| is_primitive(h, v).then(|| h.property_key(v))) {
11375        return Ok(k);
11376    }
11377    let p = to_primitive(v, "string")?;
11378    Ok(with_host(|h| h.str_of(&p)))
11379}
11380
11381/// Whether `h.get(v)` is any callable kind. A Proxy is callable exactly when its
11382/// target is (10.5: the `[[Call]]` slot is installed only for a callable
11383/// target), so `typeof` and every `is_callable` guard agree on one answer.
11384pub fn is_callable(h: &JsHost, v: &Value) -> bool {
11385    match h.get(v) {
11386        // Not every builtin is a function: the namespace objects (`Math`,
11387        // `require('fs')`) and the `<Ctor>.prototype` handles are data, and
11388        // calling one is a `TypeError` in node exactly as `typeof` says.
11389        Some(JsObj::Builtin(n)) => builtin_is_callable(n),
11390        Some(JsObj::Func(_))
11391        | Some(JsObj::BoundMethod { .. })
11392        | Some(JsObj::BoundFunc { .. })
11393        | Some(JsObj::Class(_)) => true,
11394        Some(JsObj::Proxy { target, .. }) => is_callable(h, target),
11395        _ => false,
11396    }
11397}
11398
11399/// Walk `recv`'s own props then its prototype chain for `key`, returning the
11400/// stored value (methods, inherited data props). Does NOT invoke accessors.
11401/// A PROTOCOL lookup — `Symbol.toPrimitive`, `Symbol.hasInstance`, `toJSON`,
11402/// `then` and the rest — which the spec performs with `[[Get]]`.
11403///
11404/// That distinction only shows on a PROXY: `lookup_chain` walks the property
11405/// map and never asks the handler, so a proxy supplying a protocol method
11406/// through its `get` trap was invisible and the operation fell back to the
11407/// default. Everything else takes the cheap chain walk.
11408pub fn protocol_lookup(v: &Value, key: &str) -> Result<Option<Value>, String> {
11409    if with_host(|h| h.kind_of(v)) == Some(ObjKind::Proxy) {
11410        let got = crate::builtins::get_property(v, key)?;
11411        return Ok((!matches!(got, Value::Undef)).then_some(got));
11412    }
11413    // A builtin `os` function's own `[Symbol.toPrimitive]` lives in no property
11414    // map; the namespace read synthesizes it.
11415    if key == "@@toPrimitive" {
11416        if let Some(JsObj::Builtin(n)) = with_host(|h| h.get(v).cloned()) {
11417            if n.starts_with("os.") {
11418                let got = crate::builtins::namespace_property(&n, key);
11419                if !matches!(got, Value::Undef) {
11420                    return Ok(Some(got));
11421                }
11422            }
11423        }
11424    }
11425    Ok(with_host(|h| lookup_chain(h, v, key)))
11426}
11427
11428pub fn lookup_chain(h: &JsHost, recv: &Value, key: &str) -> Option<Value> {
11429    if let Some(JsObj::Object(p)) = h.get(recv) {
11430        if let Some(v) = p.get(key) {
11431            return Some(v.clone());
11432        }
11433    }
11434    let mut cur = h.proto_of(recv);
11435    while let Some(p) = cur {
11436        // A chain link may be a plain object OR a function/class (the `router`
11437        // package sets `Router.prototype = function(){}` and hangs its methods off
11438        // that function, so the methods live in the fn-prop side table).
11439        match h.get(&p) {
11440            Some(JsObj::Object(props)) => {
11441                if let Some(v) = props.get(key) {
11442                    return Some(v.clone());
11443                }
11444            }
11445            Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => {
11446                if let Some(v) = h.fn_prop(&p, key) {
11447                    return Some(v);
11448                }
11449            }
11450            // An intrinsic prototype kept as a namespace handle
11451            // (`Iterator.prototype`, `Array.prototype`): what a script
11452            // assigned onto it lives in the namespace's side table, so
11453            // `Object.create(Array.prototype)` inherits a patched member.
11454            Some(JsObj::Builtin(ns)) => {
11455                if let Some(v) = h.builtin_static(ns, key) {
11456                    return Some(v);
11457                }
11458            }
11459            _ => {}
11460        }
11461        cur = h.proto_of(&p);
11462    }
11463    None
11464}
11465
11466/// Find a getter/setter accessor for `key` on `recv` or up its prototype chain.
11467pub fn lookup_accessor(
11468    h: &JsHost,
11469    recv: &Value,
11470    key: &str,
11471) -> Option<(Option<Value>, Option<Value>)> {
11472    if let Some(a) = h.own_accessor(recv, key) {
11473        return Some(a);
11474    }
11475    let mut cur = h.proto_of(recv);
11476    while let Some(p) = cur {
11477        if let Some(a) = h.own_accessor(&p, key) {
11478            return Some(a);
11479        }
11480        cur = h.proto_of(&p);
11481    }
11482    // A STATIC accessor declared by an ancestor class. A subclass reaches its
11483    // parent's statics through `ClassVal.parent`, not the `protos` map the walk
11484    // above reads — classes are not linked there, so that walk ended at once.
11485    // Static methods and fields already inherited because `class_static` does
11486    // this same parent walk for `fn_prop`; only accessors had no equivalent:
11487    //
11488    //     class Base { static get kind() { return 'base' } }
11489    //     class Sub extends Base {}
11490    //     Sub.plain()  // worked, a fn_prop
11491    //     Sub.kind     // undefined; node reads 'base'
11492    //
11493    // The caller invokes the getter with the class it was READ off as `this`,
11494    // so a getter reading `this.x` sees the subclass, per 10.2.4.
11495    let mut cls = recv.clone();
11496    while let Some(JsObj::Class(c)) = h.get(&cls) {
11497        let Some(parent) = c.parent.clone() else {
11498            break;
11499        };
11500        if let Some(a) = h.own_accessor(&parent, key) {
11501            return Some(a);
11502        }
11503        cls = parent;
11504    }
11505    None
11506}
11507
11508/// Register a builtin error prototype (for `instanceof Error` etc.).
11509pub fn set_error_proto(name: &str, proto: Value) {
11510    with_host(|h| {
11511        h.error_protos.insert(name.to_string(), proto);
11512    });
11513}
11514pub fn error_proto(name: &str) -> Option<Value> {
11515    with_host(|h| h.error_protos.get(name).cloned())
11516}
11517/// Error prototype lookup with a borrowed host (used inside a `with_host` block).
11518pub fn error_proto_of(h: &JsHost, name: &str) -> Option<Value> {
11519    h.error_protos.get(name).cloned()
11520}
11521
11522impl JsHost {
11523    /// `Error.prototype.toString` for an object whose prototype chain reaches
11524    /// `Error.prototype`: `"Name"` with an empty message, else `"Name: message"`.
11525    /// `None` for anything that is not an error, so the caller keeps its own
11526    /// stringification.
11527    pub fn error_to_string(&self, v: &Value) -> Option<String> {
11528        let base = self.error_protos.get("Error")?;
11529        let mut cur = self.proto_of(v);
11530        let mut is_error = false;
11531        while let Some(p) = cur {
11532            if self.strict_eq(&p, base) {
11533                is_error = true;
11534                break;
11535            }
11536            cur = self.proto_of(&p);
11537        }
11538        if !is_error {
11539            return None;
11540        }
11541        let name = lookup_chain(self, v, "name")
11542            .map(|n| self.str_of(&n))
11543            .unwrap_or_else(|| "Error".into());
11544        let message = lookup_chain(self, v, "message")
11545            .map(|m| self.str_of(&m))
11546            .unwrap_or_default();
11547        // Node's internal coded errors override `toString` as
11548        // `${name} [${code}]: ${message}` (internal/errors.js NodeError). The
11549        // `@@nodeError` tag marks the errors `synth_error` built from a
11550        // `Name [ERR_CODE]: …` string, so a user error that merely has a `.code`
11551        // property still stringifies plainly.
11552        if let Some(JsObj::Object(p)) = self.get(v) {
11553            if p.contains_key("@@nodeError") {
11554                if let Some(code) = p.get("code").map(|c| self.str_of(c)) {
11555                    return Some(format!("{name} [{code}]: {message}"));
11556                }
11557            }
11558        }
11559        Some(match (name.is_empty(), message.is_empty()) {
11560            (true, _) => message,
11561            (false, true) => name,
11562            (false, false) => format!("{name}: {message}"),
11563        })
11564    }
11565}
11566
11567/// The set of builtin error constructor names forming the error hierarchy.
11568pub const ERROR_NAMES: &[&str] = &[
11569    "Error",
11570    "TypeError",
11571    "RangeError",
11572    "SyntaxError",
11573    "ReferenceError",
11574    "EvalError",
11575    "URIError",
11576    "AggregateError",
11577    // `assert`'s error class. It is NOT a global (node exposes it only as
11578    // `assert.AssertionError`, and `GLOBAL_FUNCS` is a separate table), but it
11579    // has to be a name `synth_error` recognizes: without it the head
11580    // `AssertionError [ERR_ASSERTION]: …` failed the class check and fell into
11581    // the `Error` branch with the WHOLE head kept as the message, so `e.name`
11582    // was `Error` and `e.message` carried a prefix node keeps out of it.
11583    "AssertionError",
11584    // The WHATWG error class `AbortSignal.reason` carries. Unlike the others its
11585    // `name` comes from the SECOND constructor argument rather than from the
11586    // class, so its prototype keeps the base default and each instance stamps
11587    // its own name into an internal slot.
11588    "DOMException",
11589];
11590
11591impl JsHost {
11592    /// Lazily build the builtin error prototype chain: `Error.prototype →
11593    /// Object.prototype`, and every specific error's prototype → `Error.prototype`.
11594    /// Populated once; instances link to these so `e instanceof TypeError` and
11595    /// `e instanceof Error` both hold.
11596    /// The real `Buffer.prototype` object, building the
11597    /// `Buffer.prototype → Uint8Array.prototype → Object.prototype` chain on
11598    /// first use.
11599    ///
11600    /// A `Buffer` used to be a bare tagged object with no `[[Prototype]]` at
11601    /// all, so `Object.getPrototypeOf(buf) === Buffer.prototype` read false and
11602    /// `instanceof` had to be special-cased around it. Each prototype is a
11603    /// genuine object carrying `@proto:<Ctor>:<method>` thunks for its instance
11604    /// methods, so `Buffer.prototype.slice.call(buf, 1)` still dispatches the
11605    /// way it did when `Buffer.prototype` was a `Builtin` namespace.
11606    pub fn ensure_native_protos(&mut self) {
11607        // The wrapper prototypes share this registry and this guard would skip
11608        // them, so they are built through their own.
11609        self.ensure_wrapper_protos();
11610        self.ensure_function_kind_protos();
11611        if self.native_protos.contains_key("Buffer") {
11612            return;
11613        }
11614        let obj_proto = self.object_proto();
11615        // `Object.prototype` is the one builtin prototype that already existed as
11616        // a real object (it is the chain root). Register it so `Object.prototype`
11617        // reads resolve to THAT object rather than a fresh `Builtin` namespace —
11618        // otherwise `Object.getPrototypeOf(C.prototype) === Object.prototype`
11619        // compares a real object against a thunk and reads false.
11620        self.native_protos
11621            .insert("Object".to_string(), obj_proto.clone());
11622        for m in crate::builtins::OBJECT_PROTO_METHODS {
11623            let thunk = self.alloc(JsObj::Builtin(format!("@proto:Object:{m}")));
11624            if let Some(JsObj::Object(p)) = self.get_mut(&obj_proto) {
11625                p.insert((*m).to_string(), thunk);
11626            }
11627            self.hide_prop(&obj_proto, m);
11628        }
11629        // `Buffer.prototype → Uint8Array.prototype → %TypedArray%.prototype →
11630        // Object.prototype`, which is the chain node v26.7.0 really has. The
11631        // shared iteration methods (`every`, `map`, `filter`, …) live on the
11632        // `%TypedArray%.prototype` intermediate, NOT on `Uint8Array.prototype`:
11633        // measured, `Uint8Array.prototype.hasOwnProperty('every')` is false in
11634        // Node while the intermediate owns it. `%TypedArray%` is not a global,
11635        // so it is reachable only by walking the chain — exactly as in Node.
11636        // Every element kind gets its own prototype hanging off the shared
11637        // intermediate, so `Object.getPrototypeOf(new Int32Array(1))` is
11638        // `Int32Array.prototype` rather than some other kind's. Linking them all
11639        // to `Uint8Array.prototype` would have been the easy version and would
11640        // have made an `Int32Array` claim the wrong prototype.
11641        let mut chain: Vec<(&str, Value)> = vec![("TypedArray", obj_proto)];
11642        for kind in crate::stdlib::typedarray::ELEMENT_KINDS {
11643            chain.push((kind, Value::Undef)); // parent: %TypedArray%.prototype
11644        }
11645        // `Buffer.prototype`'s parent is `Uint8Array.prototype` specifically.
11646        chain.push(("Buffer", Value::Undef));
11647        let mut prev: Option<Value> = None;
11648        for (ctor, parent) in chain.drain(..) {
11649            let proto = self.new_object(IndexMap::new());
11650            // Each kind hangs off the shared intermediate; `Buffer` hangs off
11651            // `Uint8Array.prototype`; the intermediate itself off
11652            // `Object.prototype`.
11653            let parent = match ctor {
11654                "TypedArray" => parent,
11655                "Buffer" => self
11656                    .native_protos
11657                    .get("Uint8Array")
11658                    .cloned()
11659                    .unwrap_or_else(|| prev.clone().expect("intermediate built first")),
11660                _ => self
11661                    .native_protos
11662                    .get("TypedArray")
11663                    .cloned()
11664                    .unwrap_or_else(|| prev.clone().expect("intermediate built first")),
11665            };
11666            self.set_proto(&proto, parent);
11667            // `%TypedArray%.prototype` has no reachable constructor global, so
11668            // it gets no `constructor` slot (Node's is the anonymous
11669            // `%TypedArray%` intrinsic).
11670            if ctor != "TypedArray" {
11671                let ctor_val = self.alloc(JsObj::Builtin(ctor.to_string()));
11672                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11673                    p.insert("constructor".into(), ctor_val);
11674                }
11675                self.hide_prop(&proto, "constructor");
11676            }
11677            let methods: &[&str] = match ctor {
11678                "Buffer" => crate::stdlib::buffer::INSTANCE_METHODS,
11679                "TypedArray" => crate::stdlib::typedarray::PROTOTYPE_METHODS,
11680                // `Uint8Array` alone owns the base64/hex pair — no other view
11681                // has them, which is the whole reason they cannot live on the
11682                // shared `%TypedArray%` prototype above.
11683                "Uint8Array" => crate::stdlib::typedarray::UINT8_PROTOTYPE_METHODS,
11684                // Every other kind's prototype owns no methods; it inherits them
11685                // from the intermediate above. It does own `BYTES_PER_ELEMENT`,
11686                // which is per-kind and which Node really keeps there (measured:
11687                // `Uint8Array.prototype.hasOwnProperty('BYTES_PER_ELEMENT')`).
11688                _ => &[],
11689            };
11690            if crate::stdlib::typedarray::ELEMENT_KINDS.contains(&ctor) {
11691                let bpe = Value::Float(crate::stdlib::typedarray::bytes_per_element(ctor) as f64);
11692                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11693                    p.insert("BYTES_PER_ELEMENT".into(), bpe);
11694                }
11695                self.hide_prop(&proto, "BYTES_PER_ELEMENT");
11696            }
11697            // The intermediate also owns `[Symbol.iterator]` (the same function
11698            // as its `values`): the generated table lists it, and
11699            // `getOwnPropertySymbols` already reported it, but the READ found
11700            // no entry and answered `undefined`.
11701            let symbol_methods = match ctor {
11702                "TypedArray" => crate::builtins::proto_symbol_methods(ctor)
11703                    .into_iter()
11704                    .filter(|m| *m == "@@iterator")
11705                    .collect(),
11706                _ => Vec::new(),
11707            };
11708            for m in methods.iter().copied().chain(symbol_methods) {
11709                let thunk = self.alloc(JsObj::Builtin(format!("@proto:{ctor}:{m}")));
11710                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11711                    p.insert(m.to_string(), thunk);
11712                }
11713                self.hide_prop(&proto, m);
11714            }
11715            self.native_protos.insert(ctor.to_string(), proto.clone());
11716            prev = Some(proto);
11717        }
11718    }
11719
11720    /// `String.prototype`, `Number.prototype` and `Boolean.prototype` as REAL
11721    /// objects.
11722    ///
11723    /// A wrapper built by `new String("a")` needs a genuine `[[Prototype]]`
11724    /// link: `Builtin("String.prototype")` is a thunk namespace that cannot
11725    /// appear on a prototype chain, so `Object.getPrototypeOf(w) ===
11726    /// String.prototype` and `w instanceof String` both read false while the
11727    /// wrapper's methods still resolved through the string funnel. Registering
11728    /// them here puts them on the same footing as `Buffer.prototype`.
11729    /// `GeneratorFunction.prototype`, `AsyncFunction.prototype` and
11730    /// `AsyncGeneratorFunction.prototype` — the intrinsics a generator or async
11731    /// function's `[[Prototype]]` really points at.
11732    ///
11733    /// None are globals (node exposes them only through
11734    /// `Object.getPrototypeOf(function*(){}).constructor`), so they live here
11735    /// rather than among the wrapper constructors. Each hangs off
11736    /// `Function.prototype` and carries the `Symbol.toStringTag` that names it.
11737    pub fn ensure_function_kind_protos(&mut self) {
11738        if self.native_protos.contains_key("GeneratorFunction") {
11739            return;
11740        }
11741        let base = self
11742            .native_protos
11743            .get("Function")
11744            .cloned()
11745            .unwrap_or_else(|| self.object_proto());
11746        for ctor in [
11747            "GeneratorFunction",
11748            "AsyncFunction",
11749            "AsyncGeneratorFunction",
11750        ] {
11751            let proto = self.new_object(IndexMap::new());
11752            self.set_proto(&proto, base.clone());
11753            let ctor_val = self.alloc(JsObj::Builtin(ctor.to_string()));
11754            let tag = self.new_str(ctor);
11755            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11756                p.insert("constructor".into(), ctor_val);
11757                p.insert("@@toStringTag".into(), tag);
11758            }
11759            self.hide_prop(&proto, "constructor");
11760            self.hide_prop(&proto, "@@toStringTag");
11761            self.native_protos.insert(ctor.to_string(), proto);
11762        }
11763        self.ensure_generator_protos();
11764        self.ensure_iterator_protos();
11765    }
11766
11767    /// `%ArrayIteratorPrototype%`, `%MapIteratorPrototype%`,
11768    /// `%SetIteratorPrototype%`, `%StringIteratorPrototype%` and
11769    /// `%RegExpStringIteratorPrototype%` (ECMA-262 23.1.5.2, 24.1.5.2,
11770    /// 24.2.6.2, 22.1.5.1, 22.2.9.2): each owns `next` and a non-writable
11771    /// `@@toStringTag`, and inherits from `Iterator.prototype`. A built-in
11772    /// iterator reported `Iterator.prototype` itself as its prototype, so the
11773    /// standard probe `Object.getPrototypeOf(Object.getPrototypeOf([].values()))
11774    /// === Iterator.prototype` was false. Keyed in `native_protos` by
11775    /// [`ITERATOR_PROTOS`]'s first column; `alloc_iter` and `collection_iterator`
11776    /// link each new iterator to one by brand.
11777    fn ensure_iterator_protos(&mut self) {
11778        self.well_known_symbol("toStringTag");
11779        let fixed = PropAttrs {
11780            writable: false,
11781            enumerable: false,
11782            configurable: true,
11783        };
11784        for (key, tag) in ITERATOR_PROTOS {
11785            let proto = self.new_object(IndexMap::new());
11786            let iter_proto = self.alloc(JsObj::Builtin("Iterator.prototype".into()));
11787            self.set_proto(&proto, iter_proto);
11788            let next = self.alloc(JsObj::Builtin(format!("@proto:{key}:next")));
11789            let tag = self.new_str(*tag);
11790            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11791                p.insert("next".into(), next);
11792                p.insert("@@toStringTag".into(), tag);
11793            }
11794            self.hide_prop(&proto, "next");
11795            self.set_prop_attrs(&proto, "@@toStringTag", fixed);
11796            self.native_protos.insert((*key).into(), proto);
11797        }
11798    }
11799
11800    /// Allocate a built-in iterator (`JsObj::Iter`) linked to its kind's
11801    /// intrinsic prototype, so a read, `in`, `instanceof` and a patched
11802    /// `next` all see the chain `Object.getPrototypeOf` reports.
11803    pub fn alloc_iter(&mut self, it: JsObj) -> Value {
11804        let v = self.alloc(it);
11805        if let Some(key) = self.iterator_proto_key(&v) {
11806            if !self.native_protos.contains_key(key) {
11807                self.ensure_native_protos();
11808            }
11809            if let Some(p) = self.native_proto(key) {
11810                self.set_proto(&v, p);
11811            }
11812        }
11813        v
11814    }
11815
11816    /// The [`ITERATOR_PROTOS`] key of the intrinsic prototype a built-in
11817    /// iterator inherits from, read with the borrow held. `None` for anything
11818    /// that is not one of those five iterator kinds.
11819    pub fn iterator_proto_key(&self, v: &Value) -> Option<&'static str> {
11820        let brand = match self.get(v)? {
11821            JsObj::Iter { array: Some(_), .. } => "Array Iterator",
11822            JsObj::Iter { brand: Some(b), .. } => b,
11823            JsObj::Object(_) => match crate::builtins::collection_iterator_view(self, v)?.0 {
11824                "Map Iterator" | "Map Entries" => "Map Iterator",
11825                _ => "Set Iterator",
11826            },
11827            _ => return None,
11828        };
11829        ITERATOR_PROTOS
11830            .iter()
11831            .find(|(_, tag)| *tag == brand)
11832            .map(|(key, _)| *key)
11833    }
11834
11835    /// `%AsyncIteratorPrototype%`, `%GeneratorPrototype%` and
11836    /// `%AsyncGeneratorPrototype%` (ECMA-262 27.1.3, 27.5.1, 27.6.1), hung off
11837    /// `GeneratorFunction.prototype.prototype` and
11838    /// `AsyncGeneratorFunction.prototype.prototype`.
11839    ///
11840    /// Each generator function's own `prototype` inherits from the matching
11841    /// one, and each generator object from its function's `prototype`, so
11842    /// `Object.getPrototypeOf(Object.getPrototypeOf(async function* () {})
11843    /// .prototype)` — the idiom node's own `lib/` uses to reach
11844    /// `%AsyncIteratorPrototype%` — is a real object with
11845    /// `[Symbol.asyncIterator]` and `[Symbol.asyncDispose]`. It read `null`.
11846    /// `%GeneratorPrototype%` inherits from `Iterator.prototype`.
11847    fn ensure_generator_protos(&mut self) {
11848        // The keys below are SYMBOL keys only once their well-known symbols
11849        // exist; `own_symbol_keys` cannot mint one, so listing these
11850        // prototypes before any script read `Symbol.asyncIterator` showed none.
11851        for s in ["asyncIterator", "asyncDispose", "toStringTag"] {
11852            self.well_known_symbol(s);
11853        }
11854        let attrs_fixed = PropAttrs {
11855            writable: false,
11856            enumerable: false,
11857            configurable: true,
11858        };
11859        let async_iter = self.new_object(IndexMap::new());
11860        let obj_proto = self.object_proto();
11861        self.set_proto(&async_iter, obj_proto);
11862        for m in ["@@asyncIterator", "@@asyncDispose"] {
11863            let thunk = self.alloc(JsObj::Builtin(format!("@proto:AsyncIterator:{m}")));
11864            if let Some(JsObj::Object(p)) = self.get_mut(&async_iter) {
11865                p.insert(m.into(), thunk);
11866            }
11867            self.hide_prop(&async_iter, m);
11868        }
11869        self.native_protos
11870            .insert("AsyncIterator".into(), async_iter.clone());
11871        let iter_proto = self.alloc(JsObj::Builtin("Iterator.prototype".into()));
11872        for (kind, fn_kind, parent) in [
11873            ("Generator", "GeneratorFunction", iter_proto),
11874            ("AsyncGenerator", "AsyncGeneratorFunction", async_iter),
11875        ] {
11876            let Some(fn_proto) = self.native_protos.get(fn_kind).cloned() else {
11877                continue;
11878            };
11879            let proto = self.new_object(IndexMap::new());
11880            self.set_proto(&proto, parent);
11881            let tag = self.new_str(kind);
11882            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11883                p.insert("constructor".into(), fn_proto.clone());
11884            }
11885            for m in ["next", "return", "throw"] {
11886                let thunk = self.alloc(JsObj::Builtin(format!("@proto:{kind}:{m}")));
11887                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11888                    p.insert(m.into(), thunk);
11889                }
11890                self.hide_prop(&proto, m);
11891            }
11892            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11893                p.insert("@@toStringTag".into(), tag);
11894            }
11895            self.set_prop_attrs(&proto, "constructor", attrs_fixed);
11896            self.set_prop_attrs(&proto, "@@toStringTag", attrs_fixed);
11897            if let Some(JsObj::Object(p)) = self.get_mut(&fn_proto) {
11898                p.insert("prototype".into(), proto.clone());
11899            }
11900            self.set_prop_attrs(&fn_proto, "prototype", attrs_fixed);
11901            self.native_protos.insert(kind.into(), proto);
11902        }
11903    }
11904
11905    pub fn ensure_wrapper_protos(&mut self) {
11906        if self.native_protos.contains_key("String") {
11907            return;
11908        }
11909        let obj_proto = self.object_proto();
11910        for ctor in ["String", "Number", "Boolean", "Symbol", "BigInt"] {
11911            let proto = self.new_object(IndexMap::new());
11912            self.set_proto(&proto, obj_proto.clone());
11913            let ctor_val = self.alloc(JsObj::Builtin(ctor.to_string()));
11914            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11915                p.insert("constructor".into(), ctor_val);
11916            }
11917            self.hide_prop(&proto, "constructor");
11918            // The three conversions must be here because `Object.prototype`
11919            // also defines them: without a shadowing entry a wrapper would
11920            // inherit the object forms and `String(new String("a"))` would
11921            // report `[object Object]`.
11922            //
11923            // The REST are here because the prototype is a real object a script
11924            // can read a method OFF of. Only the three were installed, on the
11925            // reasoning that `charAt`/`toFixed`/… reach the primitive through
11926            // `call_method` anyway — true for `s.charAt(0)` and false for the
11927            // generic-borrowing form: `String.prototype.trim` read `undefined`,
11928            // so `String.prototype.trim.call(s)` — and `Number.prototype
11929            // .toFixed.call(n)`, and every `Array.prototype`-style borrow of a
11930            // wrapper method — threw. `Array.prototype`/`Object.prototype`
11931            // already carried their whole method set; these three did not.
11932            let methods: Vec<&str> = ["toString", "valueOf", "toLocaleString"]
11933                .into_iter()
11934                .chain(match ctor {
11935                    "String" => crate::builtins::STRING_PROTO_METHODS.iter().copied(),
11936                    "Number" => crate::builtins::NUMBER_PROTO_METHODS.iter().copied(),
11937                    _ => [].iter().copied(),
11938                })
11939                // The symbol-keyed methods come from the generated intrinsic
11940                // table, so this object advertises exactly the symbol methods
11941                // node defines on it — `String.prototype[Symbol.iterator]` was
11942                // `undefined` because only the string-keyed lists were walked.
11943                .chain(crate::builtins::proto_symbol_methods(ctor))
11944                .collect();
11945            let mut seen: Vec<&str> = Vec::new();
11946            for m in methods {
11947                if seen.contains(&m) {
11948                    continue;
11949                }
11950                seen.push(m);
11951                let thunk = self.alloc(JsObj::Builtin(format!("@proto:{ctor}:{m}")));
11952                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11953                    p.insert(m.to_string(), thunk);
11954                }
11955                self.hide_prop(&proto, m);
11956            }
11957            // `Symbol.prototype` and `BigInt.prototype` are the two wrapper
11958            // prototypes that carry a `@@toStringTag`; the other three are
11959            // branded by their internal slot instead, and node reports
11960            // `undefined` for their tag. Without it
11961            // `Object.prototype.toString.call(Symbol.prototype)` read
11962            // `[object Object]` where node says `[object Symbol]`.
11963            if matches!(ctor, "Symbol" | "BigInt") {
11964                let tag = self.new_str(ctor.to_string());
11965                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11966                    p.insert("@@toStringTag".into(), tag);
11967                }
11968                // Not `hide_prop`: a well-known `@@toStringTag` is read-only as
11969                // well as non-enumerable (20.4.3.6), and `hide_prop` leaves it
11970                // writable.
11971                self.set_prop_attrs(
11972                    &proto,
11973                    "@@toStringTag",
11974                    PropAttrs {
11975                        writable: false,
11976                        enumerable: false,
11977                        configurable: true,
11978                    },
11979                );
11980            }
11981            // `Symbol.prototype[@@toPrimitive]` (20.4.3.5) is what a string or
11982            // numeric conversion of a symbol reaches FIRST. Its absence was
11983            // observable in the failure wording: `String(Symbol.prototype)`
11984            // throws in node because `@@toPrimitive` rejects a non-Symbol
11985            // `this`, and here the conversion fell through to `toString` and
11986            // named that method in the message instead.
11987            if ctor == "Symbol" {
11988                let thunk = self.alloc(JsObj::Builtin("@proto:Symbol:@@toPrimitive".to_string()));
11989                if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
11990                    p.insert("@@toPrimitive".into(), thunk);
11991                }
11992                self.hide_prop(&proto, "@@toPrimitive");
11993            }
11994            self.native_protos.insert(ctor.to_string(), proto);
11995        }
11996    }
11997
11998    /// The cached template object for one tagged-template site, if it has been
11999    /// evaluated before.
12000    pub fn template_object(&self, key: (u64, u64)) -> Option<Value> {
12001        self.template_objects.get(&key).cloned()
12002    }
12003    /// Record the template object for one tagged-template site.
12004    pub fn set_template_object(&mut self, key: (u64, u64), v: Value) {
12005        self.template_objects.insert(key, v);
12006    }
12007
12008    /// The real prototype object for a builtin exotic, if it has one.
12009    pub fn native_proto(&self, ctor: &str) -> Option<Value> {
12010        self.native_protos.get(ctor).cloned()
12011    }
12012
12013    /// The constructor name whose `.prototype` object IS `v`, for a prototype
12014    /// this host built as a real object (`String.prototype`, `TypeError
12015    /// .prototype`, `Buffer.prototype`) rather than as a `Builtin` namespace.
12016    ///
12017    /// A prototype is an ORDINARY object: it carries no instance's internal
12018    /// slot, so `Object.prototype.toString.call(TypeError.prototype)` is
12019    /// `[object Object]` and not `[object Error]`. Nothing distinguished the two
12020    /// before, so the brand fell through to the "does it look like an Error"
12021    /// test and answered for the prototype as if it were an instance.
12022    pub fn intrinsic_proto_ctor(&self, v: &Value) -> Option<&str> {
12023        if !matches!(v, Value::Obj(_)) {
12024            return None;
12025        }
12026        self.native_protos
12027            .iter()
12028            .chain(self.error_protos.iter())
12029            .find(|(_, p)| *p == v)
12030            .map(|(name, _)| name.as_str())
12031    }
12032
12033    /// The real `.prototype` object for a native stdlib constructor (`StringDecoder`,
12034    /// `Hash`, `URLSearchParams`, …), built on first read and cached.
12035    ///
12036    /// `Ctor.prototype` used to read `undefined` for every native class outside the
12037    /// hand-written `is_builtin_ctor` list, which broke the ES5 subclassing pattern
12038    /// that libraries still use. `iconv-lite`'s internal codec — reached from
12039    /// `raw-body` on every `express.json()` request — does exactly this:
12040    ///
12041    /// ```text
12042    /// var StringDecoder = require('string_decoder').StringDecoder;
12043    /// if (!StringDecoder.prototype.end) StringDecoder.prototype.end = function () {};
12044    /// function InternalDecoder(options, codec) { StringDecoder.call(this, codec.enc); }
12045    /// InternalDecoder.prototype = StringDecoder.prototype;
12046    /// ```
12047    ///
12048    /// The first line threw `Cannot read properties of undefined (reading 'end')`.
12049    ///
12050    /// Methods come from `stdlib::instance_method_lists`, the same table a method
12051    /// READ consults, so the prototype can never advertise a name the dispatcher
12052    /// does not implement. Each is the `@proto:<Ctor>:<method>` thunk that
12053    /// dispatches against its invoke-time `this`, so a subclass instance whose
12054    /// prototype IS this object gets the native implementation. Returns `None` for
12055    /// a tag with no instance methods, leaving those constructors as they were.
12056    pub fn ensure_ctor_proto(&mut self, ctor: &str) -> Option<Value> {
12057        if let Some(p) = self.native_protos.get(ctor) {
12058            return Some(p.clone());
12059        }
12060        // `Buffer` and the typed-array kinds belong to the chain
12061        // `ensure_native_protos` builds. Building one of them here first hung it
12062        // straight off `Object.prototype` AND registered it, which made that
12063        // chain's own `contains_key("Buffer")` guard skip the build for the rest
12064        // of the process: after `Buffer.from([1])`, `Buffer.prototype instanceof
12065        // Uint8Array` read false.
12066        if ctor == "Buffer"
12067            || ctor == "TypedArray"
12068            || crate::stdlib::typedarray::ELEMENT_KINDS.contains(&ctor)
12069        {
12070            self.ensure_native_protos();
12071            return self.native_protos.get(ctor).cloned();
12072        }
12073        let (own, emitter) = crate::stdlib::instance_method_lists(ctor);
12074        // A class can carry accessors and no methods at all
12075        // (`AsymmetricKeyObject` is only `asymmetricKeyType` and
12076        // `asymmetricKeyDetails`), so an empty method list does not mean there
12077        // is no prototype to build.
12078        let (accessor_list, _) = crate::stdlib::instance_accessors(ctor);
12079        if own.is_empty() && emitter.is_empty() && accessor_list.is_empty() {
12080            return None;
12081        }
12082        // A native class with a real PARENT hangs off that parent's prototype
12083        // rather than straight off `Object.prototype`. The stream hierarchy is
12084        // `Readable → Stream → EventEmitter`, which is what makes
12085        // `new Readable() instanceof Stream` hold and what an ES5 subclass
12086        // doing `Object.create(Stream.prototype)` inherits from.
12087        let parent_proto = match crate::stdlib::native_parent(ctor) {
12088            Some(p) => self
12089                .ensure_ctor_proto(p)
12090                .unwrap_or_else(|| self.object_proto()),
12091            None => self.object_proto(),
12092        };
12093        let proto = self.new_object(IndexMap::new());
12094        self.set_proto(&proto, parent_proto);
12095        let ctor_val = self.alloc(JsObj::Builtin(ctor.to_string()));
12096        if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
12097            p.insert("constructor".into(), ctor_val);
12098        }
12099        self.hide_prop(&proto, "constructor");
12100        // node's `EventEmitter.prototype` carries the three instance-field
12101        // defaults as ordinary data properties.
12102        if ctor == "EventEmitter" {
12103            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
12104                p.insert("_events".into(), Value::Undef);
12105                p.insert("_eventsCount".into(), Value::Float(0.0));
12106                p.insert("_maxListeners".into(), Value::Undef);
12107            }
12108        }
12109        // A prototype member is ENUMERABLE in node for every class but the few
12110        // written as ES classes, so `for (const k in url)` walks `href` and the
12111        // rest. Hiding all of them made that loop find nothing.
12112        let visible = crate::stdlib::instance_members_enumerable(ctor);
12113        let symbols = crate::builtins::proto_symbol_methods(ctor);
12114        for m in own.iter().chain(emitter.iter()).chain(symbols.iter()) {
12115            // An emitter method the class INHERITS lives on
12116            // `EventEmitter.prototype` alone (measured: `EMITTER_OVERRIDES`), so
12117            // it is the one function every emitter shares: `child.on ===
12118            // EventEmitter.prototype.on`.
12119            if ctor != "EventEmitter"
12120                && emitter.contains(m)
12121                && crate::stdlib::events::inherits_proto_method(ctor, m)
12122            {
12123                continue;
12124            }
12125            let thunk = self.alloc(JsObj::Builtin(format!("@proto:{ctor}:{m}")));
12126            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
12127                p.insert((*m).to_string(), thunk);
12128            }
12129            // A symbol-keyed member never enumerates.
12130            if !visible || m.starts_with("@@") {
12131                self.hide_prop(&proto, m);
12132            }
12133        }
12134        // Accessors and the class's `Symbol.toStringTag`, both of which live on
12135        // the PROTOTYPE in node — an instance owns neither.
12136        let (accessors, tag) = crate::stdlib::instance_accessors(ctor);
12137        for (key, settable) in accessors {
12138            let get = self.alloc(JsObj::Builtin(format!("@proto:{ctor}:@get@{key}")));
12139            let set =
12140                settable.then(|| self.alloc(JsObj::Builtin(format!("@proto:{ctor}:@set@{key}"))));
12141            self.set_accessor(&proto, key, Some(get), set);
12142            if !visible {
12143                self.hide_prop(&proto, key);
12144            }
12145        }
12146        for m in crate::stdlib::instance_late_methods(ctor) {
12147            let thunk = self.alloc(JsObj::Builtin(format!("@proto:{ctor}:{m}")));
12148            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
12149                p.insert((*m).to_string(), thunk);
12150            }
12151            if !visible {
12152                self.hide_prop(&proto, m);
12153            }
12154        }
12155        if !tag.is_empty() {
12156            let tag = self.new_str(tag.to_string());
12157            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
12158                p.insert("@@toStringTag".into(), tag);
12159            }
12160            self.hide_prop(&proto, "@@toStringTag");
12161        }
12162        // A class node models with interleaved methods and accessors lists its
12163        // members in node's order (measured: `CLASS_PROTO_ORDER`), not methods
12164        // first: `AbortSignal.prototype` is `constructor, aborted, reason, throwIfAborted, …`.
12165        let display = crate::stdlib::class_display_name(ctor);
12166        let t = crate::core_arity::CLASS_PROTO_ORDER;
12167        if let Ok(i) = t.binary_search_by(|(c, _)| (*c).cmp(display)) {
12168            if let Some(JsObj::Object(p)) = self.get_mut(&proto) {
12169                let mut ordered = IndexMap::with_capacity(p.len());
12170                for name in t[i].1 {
12171                    let marker = format!("{ORD_MARKER}{name}");
12172                    for k in [name.to_string(), marker] {
12173                        if let Some(v) = p.shift_remove(&k) {
12174                            ordered.insert(k, v);
12175                        }
12176                    }
12177                }
12178                ordered.extend(p.drain(..));
12179                *p = ordered;
12180            }
12181        }
12182        self.native_protos.insert(ctor.to_string(), proto.clone());
12183        Some(proto)
12184    }
12185
12186    /// `<ErrorClass>.prototype`, once [`JsHost::ensure_error_protos`] has run.
12187    /// The error prototypes live in their own table, so `ensure_ctor_proto` —
12188    /// which answers from `native_protos` — does not find them.
12189    pub fn error_proto(&self, name: &str) -> Option<Value> {
12190        self.error_protos.get(name).cloned()
12191    }
12192
12193    pub fn ensure_error_protos(&mut self) {
12194        if !self.error_protos.is_empty() {
12195            return;
12196        }
12197        let obj_proto = self.object_proto();
12198        // Error.prototype first (the shared base).
12199        let err_proto = self.new_object(IndexMap::new());
12200        self.set_proto(&err_proto, obj_proto);
12201        let nm = self.new_str("Error");
12202        let empty = self.new_str("");
12203        let ctor = self.alloc(JsObj::Builtin("Error".into()));
12204        // `Error.prototype.toString` (20.5.3.4) has to be an OWN property here,
12205        // not a fallback the stringifier applies when nothing else matches: it
12206        // exists precisely to shadow `Object.prototype.toString`. Without it,
12207        // the first read of `Error.prototype` or `Object.prototype` — which
12208        // `x instanceof Error` performs, so ordinary code triggers it —
12209        // materialised `Object.prototype.toString`, the chain lookup started
12210        // finding it, and `String(err)` flipped from `Error: m` to
12211        // `[object Error]` for the REST OF THE PROCESS, including errors
12212        // created before the read.
12213        let to_string = self.alloc(JsObj::Builtin("@proto:Error:toString".into()));
12214        if let Some(JsObj::Object(p)) = self.get_mut(&err_proto) {
12215            p.insert("name".into(), nm);
12216            p.insert("message".into(), empty);
12217            p.insert("constructor".into(), ctor);
12218            p.insert("toString".into(), to_string);
12219        }
12220        // Everything on `Error.prototype` is non-enumerable in V8.
12221        for k in ["name", "message", "constructor", "toString"] {
12222            self.hide_prop(&err_proto, k);
12223        }
12224        self.error_protos.insert("Error".into(), err_proto.clone());
12225        for name in &ERROR_NAMES[1..] {
12226            let p = self.new_object(IndexMap::new());
12227            self.set_proto(&p, err_proto.clone());
12228            let nm = self.new_str(*name);
12229            let ctor = self.alloc(JsObj::Builtin((*name).to_string()));
12230            if let Some(JsObj::Object(o)) = self.get_mut(&p) {
12231                o.insert("name".into(), nm);
12232                o.insert("constructor".into(), ctor);
12233            }
12234            self.hide_prop(&p, "name");
12235            self.hide_prop(&p, "constructor");
12236            self.error_protos.insert((*name).to_string(), p);
12237        }
12238    }
12239}
12240
12241// ── Map/Set element access (used by builtins) ────────────────────────────────
12242
12243impl JsHost {
12244    /// A function's `.length`: the count of leading params before the first one
12245    /// with a default or the rest element.
12246    pub fn func_arity(&self, v: &Value) -> usize {
12247        // 20.2.3.2: a bound function's `length` is the target's, less the
12248        // arguments already bound, floored at 0. Reporting 0 for every bound
12249        // function breaks arity dispatch — express picks error-handling
12250        // middleware with `fn.length === 4`, so a bound handler was never
12251        // recognised as one.
12252        if let Some(JsObj::BoundFunc { target, args, .. }) = self.get(v) {
12253            return self.func_arity(&target.clone()).saturating_sub(args.len());
12254        }
12255        // A builtin's arity is the specified one, so `Math.max.bind(null,1)`
12256        // reports 1 rather than the 0 a target of unknown arity would give.
12257        if let Some(JsObj::Builtin(n)) = self.get(v) {
12258            return crate::builtins::builtin_meta(n)
12259                .map(|(_, len)| len as usize)
12260                .unwrap_or(0);
12261        }
12262        let def_id = match self.get(v) {
12263            Some(JsObj::Func(f)) => Some(f.def_id),
12264            Some(JsObj::Class(c)) => match c.ctor.as_ref().and_then(|cf| self.get(cf)) {
12265                Some(JsObj::Func(f)) => Some(f.def_id),
12266                _ => None,
12267            },
12268            _ => None,
12269        };
12270        match def_id.and_then(|id| self.funcs.get(id)) {
12271            Some(def) => def
12272                .params
12273                .iter()
12274                .take_while(|p| !p.rest && !p.has_default)
12275                .count(),
12276            None => 0,
12277        }
12278    }
12279
12280    pub fn is_map(&self, v: &Value) -> bool {
12281        matches!(self.get(v), Some(JsObj::Map { .. }))
12282    }
12283    pub fn is_set(&self, v: &Value) -> bool {
12284        matches!(self.get(v), Some(JsObj::Set { .. }))
12285    }
12286}
12287
12288// ── promises & the event loop ────────────────────────────────────────────────
12289
12290impl JsHost {
12291    /// Allocate a fresh pending promise, returning its heap value.
12292    pub fn new_promise(&mut self) -> Value {
12293        let id = self.promises.len() as u32;
12294        self.promises.push(PromiseCell {
12295            state: PromiseState::Pending,
12296            value: Value::Undef,
12297            reactions: Vec::new(),
12298            handled: false,
12299            await_pos: 0,
12300        });
12301        self.alloc(JsObj::Promise { id })
12302    }
12303    pub fn promise_id(&self, v: &Value) -> Option<u32> {
12304        match self.get(v) {
12305            Some(JsObj::Promise { id }) => Some(*id),
12306            _ => None,
12307        }
12308    }
12309    pub fn promise_state(&self, id: u32) -> PromiseState {
12310        self.promises[id as usize].state
12311    }
12312    pub fn promise_value(&self, id: u32) -> Value {
12313        self.promises[id as usize].value.clone()
12314    }
12315    pub fn promise_mark_handled(&mut self, id: u32) {
12316        self.promises[id as usize].handled = true;
12317    }
12318    /// Take the pending reactions of a promise (called on settle).
12319    pub fn take_reactions(&mut self, id: u32) -> Vec<PromiseReaction> {
12320        std::mem::take(&mut self.promises[id as usize].reactions)
12321    }
12322    pub fn add_reaction(&mut self, id: u32, r: PromiseReaction) {
12323        self.promises[id as usize].reactions.push(r);
12324    }
12325    pub fn settle_promise(&mut self, id: u32, state: PromiseState, value: Value) {
12326        let c = &mut self.promises[id as usize];
12327        if c.state != PromiseState::Pending {
12328            return; // already settled — resolve/reject are one-shot
12329        }
12330        c.state = state;
12331        c.value = value;
12332    }
12333    pub fn queue_micro(&mut self, cb: Value, args: Vec<Value>) {
12334        let frame = self.async_frame.clone();
12335        self.microtasks.push_back(Task::Js { cb, args, frame });
12336    }
12337    /// Deliver the callback of an asynchronous I/O operation that has already
12338    /// completed. node-js performs the operation synchronously, but the callback
12339    /// still belongs to the loop's POLL phase, not to the microtask queue: node
12340    /// runs it as a libuv completion, after the nextTick and promise jobs the
12341    /// starting code queued (`fs.stat(f, cb); Promise.resolve().then(p)` runs `p`
12342    /// first) and with a full microtask checkpoint after it.
12343    pub fn queue_io_callback(&mut self, cb: Value, args: Vec<Value>) {
12344        let frame = self.async_frame.clone();
12345        self.io_completions.push_back(Task::Js { cb, args, frame });
12346    }
12347    /// A native step delivered as an I/O completion, in the same poll-phase
12348    /// queue as [`JsHost::queue_io_callback`] (a `fs/promises` settlement).
12349    pub fn queue_io_native(&mut self, f: Box<dyn FnOnce() -> Result<(), String>>) {
12350        let frame = self.async_frame.clone();
12351        self.io_completions.push_back(Task::Native(f, frame));
12352    }
12353    pub fn queue_nexttick(&mut self, cb: Value, args: Vec<Value>) {
12354        let frame = self.async_frame.clone();
12355        self.nextticks.push_back(Task::Js { cb, args, frame });
12356    }
12357    /// Schedule a native (Rust) microtask — used by Promise reactions and async
12358    /// resumption.
12359    pub fn queue_micro_native(&mut self, f: Box<dyn FnOnce() -> Result<(), String>>) {
12360        let frame = self.async_frame.clone();
12361        self.microtasks.push_back(Task::Native(f, frame));
12362    }
12363    /// Schedule a macrotask. `interval` is the repeat period for `setInterval`
12364    /// (`None` for the one-shot `setTimeout`/`setImmediate`). Returns the timer
12365    /// id, which the `Timeout`/`Immediate` handle object carries so `clear*`,
12366    /// `ref`/`unref` and `refresh` can find this entry again.
12367    pub fn add_timer(
12368        &mut self,
12369        delay: f64,
12370        callback: Value,
12371        args: Vec<Value>,
12372        interval: Option<f64>,
12373    ) -> u64 {
12374        let id = self.next_timer;
12375        self.next_timer += 1;
12376        // Real deadline for the real-clock path; `setImmediate` (delay < 0) is
12377        // clamped to "now". Virtual-clock ordering still uses `delay`/`seq`.
12378        let deadline = Instant::now() + Duration::from_millis(delay.max(0.0) as u64);
12379        self.macrotasks.push(Timer {
12380            id,
12381            delay,
12382            seq: id,
12383            callback,
12384            args,
12385            cancelled: false,
12386            interval,
12387            refed: true,
12388            deadline,
12389            frame: self.async_frame.clone(),
12390            vdeadline: self.virtual_now + delay,
12391        });
12392        id
12393    }
12394    /// Re-arm a repeating timer that is about to fire, keeping its id (so a
12395    /// `clearInterval` from *inside* the callback cancels this very entry) and
12396    /// taking a fresh `seq` so same-delay peers still round-robin.
12397    ///
12398    /// Called BEFORE the callback runs: if it were called after, the entry would
12399    /// be absent while the callback executed and a `clearInterval(t)` there would
12400    /// cancel nothing, resurrecting an interval the program had stopped.
12401    fn rearm_timer(&mut self, t: &Timer, period: f64) {
12402        let seq = self.next_timer;
12403        self.next_timer += 1;
12404        let deadline = Instant::now() + Duration::from_millis(period.max(0.0) as u64);
12405        self.macrotasks.push(Timer {
12406            id: t.id,
12407            delay: t.delay,
12408            seq,
12409            callback: t.callback.clone(),
12410            args: t.args.clone(),
12411            cancelled: false,
12412            interval: Some(period),
12413            refed: t.refed,
12414            deadline,
12415            frame: t.frame.clone(),
12416            vdeadline: self.virtual_now + period,
12417        });
12418    }
12419    /// `timeout.ref()` / `timeout.unref()` — set the handle bit on a pending
12420    /// timer. A no-op once the timer has fired or been cleared (Node likewise
12421    /// treats `ref`/`unref` on a dead timer as inert).
12422    pub fn set_timer_refed(&mut self, id: u64, refed: bool) {
12423        for t in &mut self.macrotasks {
12424            if t.id == id && !t.cancelled {
12425                t.refed = refed;
12426            }
12427        }
12428    }
12429    /// `timeout.hasRef()` — whether a still-pending timer holds the loop open.
12430    /// A fired or cleared timer reports `false`, matching Node.
12431    pub fn timer_has_ref(&self, id: u64) -> bool {
12432        self.macrotasks
12433            .iter()
12434            .any(|t| t.id == id && !t.cancelled && t.refed)
12435    }
12436    /// `timeout.refresh()` — restart the countdown from now, as if the timer had
12437    /// just been scheduled.
12438    pub fn refresh_timer(&mut self, id: u64) {
12439        let now = Instant::now();
12440        for t in &mut self.macrotasks {
12441            if t.id == id && !t.cancelled {
12442                t.deadline = now + Duration::from_millis(t.delay.max(0.0) as u64);
12443                t.vdeadline = self.virtual_now + t.delay;
12444            }
12445        }
12446    }
12447    /// Clone the I/O sender for a background I/O thread.
12448    pub fn io_sender(&self) -> Sender<IoTask> {
12449        self.io_tx.clone()
12450    }
12451    /// Register a live handle (listener/socket/ref'd resource) keeping the loop
12452    /// alive.
12453    pub fn incr_handle(&mut self) {
12454        self.open_handles += 1;
12455    }
12456    /// Release a handle; the loop exits once this reaches `0` with empty queues.
12457    pub fn decr_handle(&mut self) {
12458        self.open_handles = self.open_handles.saturating_sub(1);
12459    }
12460    pub fn open_handles(&self) -> usize {
12461        self.open_handles
12462    }
12463    /// Pop the earliest timer whose real deadline is at or before `now` (I/O
12464    /// path). Ties break by `seq`.
12465    fn pop_due_timer(&mut self, now: Instant) -> Option<Timer> {
12466        let idx = self
12467            .macrotasks
12468            .iter()
12469            .enumerate()
12470            .filter(|(_, t)| !t.cancelled && t.deadline <= now)
12471            .min_by(|(_, a), (_, b)| a.deadline.cmp(&b.deadline).then(a.seq.cmp(&b.seq)))
12472            .map(|(i, _)| i);
12473        idx.map(|i| self.macrotasks.remove(i))
12474    }
12475    /// Time until the earliest pending timer's deadline (I/O path blocking bound),
12476    /// or `None` if no timers are pending. Clamped to `0` for already-due timers.
12477    fn next_timer_timeout(&self, now: Instant) -> Option<Duration> {
12478        self.macrotasks
12479            .iter()
12480            .filter(|t| !t.cancelled)
12481            .map(|t| t.deadline)
12482            .min()
12483            .map(|d| d.saturating_duration_since(now))
12484    }
12485    pub fn cancel_timer(&mut self, id: u64) {
12486        for t in &mut self.macrotasks {
12487            if t.id == id {
12488                t.cancelled = true;
12489            }
12490        }
12491    }
12492    fn pop_next_timer(&mut self) -> Option<Timer> {
12493        // Earliest (vdeadline, seq) fires first — a deterministic virtual
12494        // clock, advanced to each timer's deadline as it fires.
12495        let idx = self
12496            .macrotasks
12497            .iter()
12498            .enumerate()
12499            .filter(|(_, t)| !t.cancelled)
12500            .min_by(|(_, a), (_, b)| {
12501                a.vdeadline
12502                    .partial_cmp(&b.vdeadline)
12503                    .unwrap_or(std::cmp::Ordering::Equal)
12504                    .then(a.seq.cmp(&b.seq))
12505            })
12506            .map(|(i, _)| i)?;
12507        let t = self.macrotasks.remove(idx);
12508        self.virtual_now = self.virtual_now.max(t.vdeadline);
12509        Some(t)
12510    }
12511    fn next_microtask(&mut self) -> Option<Task> {
12512        // Node's `processTicksAndRejections` runs in ROUNDS: drain the nextTick
12513        // queue, then drain the microtask queue in full, then repeat if the
12514        // microtasks queued more ticks. A tick queued from INSIDE a microtask
12515        // therefore waits for the rest of that microtask queue.
12516        //
12517        // Preferring ticks on every step interleaved the two, so
12518        // `Promise.resolve().then(() => process.nextTick(f))` ran `f` before the
12519        // promise callbacks queued behind it — the one ordering difference a
12520        // library scheduling work from a `.then` can actually observe.
12521        if !self.draining_micro {
12522            if let Some(t) = self.nextticks.pop_front() {
12523                return Some(t);
12524            }
12525        }
12526        if let Some(t) = self.microtasks.pop_front() {
12527            // Stay in the microtask phase until this queue is exhausted —
12528            // INCLUDING jobs the task about to run queues itself, which V8's
12529            // `RunMicrotasks` also drains before returning. Clearing the flag
12530            // when the queue looked empty at POP time let a tick queued by the
12531            // last job's own continuation jump ahead of the jobs that
12532            // continuation queued (`await null; process.nextTick(t);
12533            // queueMicrotask(q)` ran `t` before `q`).
12534            self.draining_micro = true;
12535            return Some(t);
12536        }
12537        self.draining_micro = false;
12538        self.nextticks.pop_front()
12539    }
12540    fn has_microtasks(&self) -> bool {
12541        !self.nextticks.is_empty() || !self.microtasks.is_empty()
12542    }
12543    fn next_io_completion(&mut self) -> Option<Task> {
12544        self.io_completions.pop_front()
12545    }
12546    /// Node's loop-alive test: queued jobs, an open handle, a referenced timer,
12547    /// or an I/O completion still waiting for its callback.
12548    fn loop_alive(&self) -> bool {
12549        self.has_microtasks()
12550            || !self.io_completions.is_empty()
12551            || self.open_handles() > 0
12552            || self.has_refed_macrotasks()
12553    }
12554    /// Whether any pending timer is *referenced* — the timer half of Node's
12555    /// handle count. Only these keep the loop alive; unref'd timers still fire
12556    /// while something else holds the loop open, but never hold it themselves.
12557    fn has_refed_macrotasks(&self) -> bool {
12558        self.macrotasks.iter().any(|t| !t.cancelled && t.refed)
12559    }
12560    /// Whether any pending timer repeats. A repeating timer cannot run on the
12561    /// virtual clock: virtual time never advances, so the interval would re-arm
12562    /// at the same instant forever, spinning a core and starving every
12563    /// longer-delay timer behind it. Its presence forces the real clock.
12564    fn has_pending_interval(&self) -> bool {
12565        self.macrotasks
12566            .iter()
12567            .any(|t| !t.cancelled && t.interval.is_some())
12568    }
12569}
12570
12571/// Drive the event loop to quiescence.
12572///
12573/// **Liveness** is Node's handle count: the loop runs while a microtask is
12574/// pending, an open handle is registered (a listening server, a live socket, an
12575/// in-flight async op), or a *referenced* timer is still pending. That last term
12576/// is what makes `setInterval(fn, 1000)` hold the process open forever, as it
12577/// does in Node — the interval re-arms itself, so a ref'd timer is always
12578/// pending and the loop never reaches its exit condition.
12579///
12580/// Two **clock regimes**, selected per iteration:
12581///
12582/// - **Virtual clock** (no open handles and no repeating timer): the original
12583///   deterministic path — fire the earliest `(delay, seq)` timer immediately, no
12584///   real waiting. Parity output and test speed for ordinary `setTimeout`
12585///   scripts are unchanged.
12586/// - **Real clock** (an open handle, or any pending interval): fire every timer
12587///   whose wall-clock deadline has passed, then BLOCK on the I/O channel
12588///   (`recv_timeout` bounded by the next deadline, or unbounded `recv` if no
12589///   timers) and run the received `IoTask` on the main thread. The host keeps
12590///   its own `Sender`, so `recv` never disconnects while the process should stay
12591///   alive.
12592///
12593///   A repeating timer *must* take this path: virtual time never advances, so an
12594///   interval on the virtual clock would re-fire at the same instant forever,
12595///   spinning a core and starving every longer-delay timer behind it.
12596///
12597/// Errors thrown by a task/timer/I/O dispatch abort the loop (uncaught → surfaced).
12598pub fn run_event_loop() -> Result<(), String> {
12599    // Own the receiver for the loop's duration (blocking `recv` cannot hold a
12600    // host borrow); restore it afterward so a re-entrant run reuses the channel.
12601    let rx = with_host(|h| h.io_rx.take());
12602    let result = drive_event_loop(rx.as_ref());
12603    with_host(|h| h.io_rx = rx);
12604    result
12605}
12606
12607fn drive_event_loop(rx: Option<&Receiver<IoTask>>) -> Result<(), String> {
12608    loop {
12609        // 1) Exhaust the microtask queue (nextTick before promise reactions),
12610        //    then report anything that rejected with nobody watching.
12611        while let Some(task) = with_host(|h| h.next_microtask()) {
12612            task.run()?;
12613        }
12614        check_unhandled_rejections()?;
12615
12616        // 2) Liveness (Node's handle count). Nothing referenced left to do ⇒ the
12617        //    process exits, dropping any unref'd timers still pending — which is
12618        //    why `setTimeout(fn, 1000).unref()` never fires, while an unref'd
12619        //    timer behind a ref'd one does.
12620        let alive = with_host(|h| h.loop_alive());
12621        if !alive {
12622            break;
12623        }
12624
12625        // 3) Poll phase for I/O that has already completed: one callback per
12626        //    turn, so the microtask checkpoint above runs between callbacks.
12627        //    Ahead of the timers, matching what node reports for an fs callback
12628        //    and a `setTimeout(0)`/`setImmediate` scheduled alongside it.
12629        if let Some(task) = with_host(|h| h.next_io_completion()) {
12630            task.run()?;
12631            continue;
12632        }
12633
12634        // 4) Pick the clock regime for this turn.
12635        let virtual_clock = with_host(|h| h.open_handles() == 0 && !h.has_pending_interval());
12636        if virtual_clock {
12637            // ── virtual-clock regime (unchanged for one-shot timers) ─────────
12638            match with_host(|h| h.pop_next_timer()) {
12639                Some(t) => fire_timer(t)?,
12640                // Unreachable while `alive` holds (a ref'd timer must exist),
12641                // but exiting is the safe reading of "nothing left to run".
12642                None => break,
12643            }
12644            continue;
12645        }
12646
12647        // ── real-clock / blocking-I/O regime ─────────────────────────────────
12648        let now = Instant::now();
12649        if let Some(t) = with_host(|h| h.pop_due_timer(now)) {
12650            fire_timer(t)?;
12651            continue; // re-drain microtasks, re-check deadlines
12652        }
12653        // Nothing due and no pending microtasks: block for the next I/O event,
12654        // bounded by the soonest timer deadline so due timers still fire on time.
12655        let rx = rx.expect("blocking-I/O regime requires the I/O receiver");
12656        let timeout = with_host(|h| h.next_timer_timeout(now));
12657        let recv = match timeout {
12658            Some(d) => rx.recv_timeout(d),
12659            None => rx
12660                .recv()
12661                .map_err(|_| std::sync::mpsc::RecvTimeoutError::Disconnected),
12662        };
12663        match recv {
12664            Ok(task) => task()?,
12665            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} // a timer is now due
12666            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, // no senders left
12667        }
12668    }
12669    Ok(())
12670}
12671
12672/// Run one due timer's callback, first re-arming it if it repeats.
12673///
12674/// The re-arm happens BEFORE the callback runs so that a `clearInterval(t)`
12675/// issued from inside that callback cancels the next occurrence. Re-arming
12676/// afterwards would leave the interval absent from the queue for the duration of
12677/// its own callback, so the `clear` would match nothing and the freshly pushed
12678/// entry would resurrect an interval the program had just stopped.
12679fn fire_timer(t: Timer) -> Result<(), String> {
12680    if let Some(period) = t.interval {
12681        with_host(|h| h.rearm_timer(&t, period));
12682    }
12683    in_frame(t.frame, || invoke(&t.callback, t.args, None))?;
12684    Ok(())
12685}
12686
12687// ── async functions & promise resolution (native) ────────────────────────────
12688
12689/// Drive a freshly-built async coroutine and return its result promise.
12690fn run_async(gen: Value) -> Value {
12691    let result = with_host(|h| h.new_promise());
12692    let rid = with_host(|h| h.promise_id(&result).unwrap());
12693    drive_async(gen, rid, Value::Undef);
12694    result
12695}
12696
12697/// Resume an async coroutine one step, wiring `await` continuations to promise
12698/// settlement.
12699fn drive_async(gen: Value, rid: u32, send: Value) {
12700    let step = gen_resume(&gen, send);
12701    with_host(|h| h.promises[rid as usize].await_pos = AWAIT_POS.with(|p| p.replace(0)));
12702    match step {
12703        Ok(GenStep::Yield(awaited)) => {
12704            let ap = promise_of(&awaited);
12705            let aid = with_host(|h| h.promise_id(&ap).unwrap());
12706            let gen2 = gen.clone();
12707            subscribe_native(
12708                aid,
12709                Box::new(move |state, val| {
12710                    // Resume the coroutine with a `[tag, value]` packet the AWAIT
12711                    // op unwraps (tag 1 ⇒ the awaited promise rejected → throw).
12712                    let tag = if state == PromiseState::Rejected {
12713                        1.0
12714                    } else {
12715                        0.0
12716                    };
12717                    let packet = with_host(|h| h.new_array(vec![Value::Float(tag), val]));
12718                    drive_async(gen2, rid, packet);
12719                    Ok(())
12720                }),
12721            );
12722        }
12723        Ok(GenStep::Done(v)) => resolve_promise_val(rid, v),
12724        Err(e) => {
12725            let ev = take_exc_or_error(&e);
12726            reject_promise_val(rid, ev);
12727        }
12728    }
12729}
12730
12731/// The AWAIT op body (runs inside the async coroutine): suspend, yielding the
12732/// awaited value; on resume, unwrap the settlement packet (throwing on reject).
12733///
12734/// `pos` is the `await` keyword's source position, which the driver records
12735/// on the body's result promise while it is suspended there.
12736pub fn await_value(awaited: Value, pos: u32) -> Result<Value, String> {
12737    // Inside an `async function*`, `await` and `yield` share one coroutine
12738    // yielder, so an awaited value has to be tagged or the driver would hand it
12739    // to the consumer as if the body had yielded it.
12740    let awaited = match CUR_GEN.with(|c| c.get()) {
12741        Some(id) if with_host(|h| h.generators[id as usize].async_gen) => with_host(|h| {
12742            let mut m = IndexMap::new();
12743            m.insert(AWAIT_MARKER.to_string(), awaited);
12744            h.new_object(m)
12745        }),
12746        _ => awaited,
12747    };
12748    AWAIT_POS.with(|p| p.set(pos));
12749    let packet = gen_yield(awaited)?;
12750    let items = with_host(|h| h.iter_vec(&packet)).unwrap_or_default();
12751    let tag = items
12752        .first()
12753        .map(|v| with_host(|h| h.to_number(v)))
12754        .unwrap_or(0.0);
12755    let val = items.get(1).cloned().unwrap_or(Value::Undef);
12756    if tag == 1.0 {
12757        with_host(|h| h.exc = Some(val.clone()));
12758        Err(with_host(|h| crate::builtins::error_string(h, &val)))
12759    } else {
12760        Ok(val)
12761    }
12762}
12763
12764thread_local! {
12765    /// The position of the `await` a coroutine has just suspended in, handed
12766    /// from [`await_value`] (inside the coroutine) to the driver that resumed
12767    /// it, which takes it on the yield.
12768    static AWAIT_POS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
12769}
12770
12771/// The `await` position the async body settling promise `p` is suspended in,
12772/// or 0.
12773pub fn suspended_await_pos(p: &Value) -> u32 {
12774    with_host(|h| {
12775        h.promise_id(p)
12776            .map_or(0, |id| h.promises[id as usize].await_pos)
12777    })
12778}
12779
12780/// Hidden key marking an `await` suspension inside an async generator.
12781const AWAIT_MARKER: &str = "@@await";
12782
12783/// The operand of an `await` suspension, or `None` for a real `yield`.
12784fn await_marker(v: &Value) -> Option<Value> {
12785    with_host(|h| match h.get(v) {
12786        Some(JsObj::Object(props)) if props.len() == 1 => props.get(AWAIT_MARKER).cloned(),
12787        _ => None,
12788    })
12789}
12790
12791/// `AsyncGeneratorEnqueue` — queue one request against an `async function*` and
12792/// hand back the promise its `{value, done}` record (or rejection) will settle.
12793///
12794/// All three of `.next`, `.return` and `.throw` come through here, so a request
12795/// never resumes the body while an earlier one is still suspended on an
12796/// internal `await`.
12797pub fn async_gen_enqueue(gen: &Value, req: GenReq) -> Value {
12798    let step = with_host(|h| h.new_promise());
12799    let sid = with_host(|h| h.promise_id(&step).unwrap());
12800    let id = match with_host(|h| match h.get(gen) {
12801        Some(JsObj::Generator { id }) => Some(*id),
12802        _ => None,
12803    }) {
12804        Some(id) => id,
12805        None => return step,
12806    };
12807    with_host(|h| h.generators[id as usize].queue.push_back((req, sid)));
12808    pump_async_gen(gen.clone(), id);
12809    step
12810}
12811
12812/// One `.next(v)` of an `async function*`.
12813pub fn async_gen_step(gen: &Value, send: Value) -> Value {
12814    async_gen_enqueue(gen, GenReq::Next(send))
12815}
12816
12817/// `AsyncGeneratorResumeNext`: start the oldest queued request, unless one is
12818/// already in flight (the body may only be resumed by one request at a time).
12819fn pump_async_gen(gen: Value, id: u32) {
12820    if with_host(|h| h.generators[id as usize].running) {
12821        return;
12822    }
12823    let Some((req, sid)) = with_host(|h| h.generators[id as usize].queue.pop_front()) else {
12824        return;
12825    };
12826    with_host(|h| h.generators[id as usize].running = true);
12827    start_async_gen_req(gen, sid, req);
12828}
12829
12830/// Begin one queued request: resume the body with the completion it carries,
12831/// then hand the outcome to the shared continuation.
12832///
12833/// A RETURN completion always Awaits its value before the body sees it — via
12834/// `AsyncGeneratorUnwrapYieldResumption` (ECMA-262 27.6.3.7) when the generator
12835/// is suspended at a `yield`, and via `AsyncGeneratorAwaitReturn` (27.6.3.9)
12836/// when it is not yet started or already completed. So a `.return()` settles one
12837/// microtask after a `.next()` or `.throw()` issued in its place would, and the
12838/// `finally` it unwinds through runs a tick later too. Skipping that tick lets a
12839/// `.return()` overtake the reactions of the `.next()` it followed.
12840fn start_async_gen_req(gen: Value, sid: u32, req: GenReq) {
12841    if matches!(req, GenReq::Return(_)) {
12842        with_host(|h| {
12843            h.queue_micro_native(Box::new(move || {
12844                resume_async_gen_req(gen, sid, req);
12845                Ok(())
12846            }))
12847        });
12848        return;
12849    }
12850    resume_async_gen_req(gen, sid, req);
12851}
12852
12853/// Deliver a queued completion to the body and settle its step promise.
12854fn resume_async_gen_req(gen: Value, sid: u32, req: GenReq) {
12855    let step = match req {
12856        GenReq::Next(v) => gen_resume(&gen, v),
12857        GenReq::Return(v) => gen_return(&gen, v),
12858        GenReq::Throw(e) => gen_throw(&gen, e),
12859    };
12860    settle_async_gen_step(gen, sid, step);
12861}
12862
12863/// One request has settled: release the body and start the next queued request.
12864fn finish_async_gen_step(gen: Value, id: u32) {
12865    with_host(|h| h.generators[id as usize].running = false);
12866    pump_async_gen(gen, id);
12867}
12868
12869/// Whether `v` is an `async function*` object (its `.next()` yields promises).
12870pub fn is_async_generator(v: &Value) -> bool {
12871    let id = match with_host(|h| match h.get(v) {
12872        Some(JsObj::Generator { id }) => Some(*id),
12873        _ => None,
12874    }) {
12875        Some(id) => id,
12876        None => return false,
12877    };
12878    with_host(|h| h.generators[id as usize].async_gen)
12879}
12880
12881/// A `{ value, done }` iterator-result object.
12882fn iter_record(value: Value, done: bool) -> Value {
12883    with_host(|h| {
12884        let mut m = IndexMap::new();
12885        m.insert("value".to_string(), value);
12886        m.insert("done".to_string(), Value::Bool(done));
12887        h.new_object(m)
12888    })
12889}
12890
12891/// Resume a request that was suspended on an internal `await` (always a normal
12892/// completion — the awaited promise's outcome rides in `packet`).
12893fn drive_async_gen(gen: Value, sid: u32, packet: Value) {
12894    let step = gen_resume(&gen, packet);
12895    settle_async_gen_step(gen, sid, step);
12896}
12897
12898/// Turn one body resumption into a settled step promise: transparently re-drive
12899/// internal `await` suspensions, and settle on the first REAL yield or on the
12900/// body's completion. Shared by the initial resume of a queued request and by
12901/// every await-resumption of it.
12902fn settle_async_gen_step(gen: Value, sid: u32, step: Result<GenStep, String>) {
12903    with_host(|h| h.promises[sid as usize].await_pos = AWAIT_POS.with(|p| p.replace(0)));
12904    let id = match with_host(|h| match h.get(&gen) {
12905        Some(JsObj::Generator { id }) => Some(*id),
12906        _ => None,
12907    }) {
12908        Some(id) => id,
12909        None => return,
12910    };
12911    match step {
12912        Ok(GenStep::Yield(v)) => match await_marker(&v) {
12913            Some(awaited) => {
12914                // An internal `await`: settle it, then resume the body. The
12915                // request stays in flight across the suspension.
12916                let ap = promise_of(&awaited);
12917                let aid = with_host(|h| h.promise_id(&ap).unwrap());
12918                subscribe_native(
12919                    aid,
12920                    Box::new(move |state, val| {
12921                        let tag = if state == PromiseState::Rejected {
12922                            1.0
12923                        } else {
12924                            0.0
12925                        };
12926                        let packet = with_host(|h| h.new_array(vec![Value::Float(tag), val]));
12927                        drive_async_gen(gen.clone(), sid, packet);
12928                        Ok(())
12929                    }),
12930                );
12931            }
12932            // ECMA-262 27.6.3.8 AsyncGeneratorYield step 5: the yielded value is
12933            // AWAITED before the step promise settles, so `yield somePromise`
12934            // hands the consumer the RESOLVED value (and costs its microtask).
12935            None => {
12936                let yp = promise_of(&v);
12937                let yid = with_host(|h| h.promise_id(&yp).unwrap());
12938                subscribe_native(
12939                    yid,
12940                    Box::new(move |state, val| {
12941                        if state == PromiseState::Rejected {
12942                            reject_promise_val(sid, val);
12943                        } else {
12944                            resolve_promise_val(sid, iter_record(val, false));
12945                        }
12946                        finish_async_gen_step(gen.clone(), id);
12947                        Ok(())
12948                    }),
12949                );
12950            }
12951        },
12952        Ok(GenStep::Done(v)) => {
12953            resolve_promise_val(sid, iter_record(v, true));
12954            finish_async_gen_step(gen, id);
12955        }
12956        Err(e) => {
12957            let ev = take_exc_or_error(&e);
12958            reject_promise_val(sid, ev);
12959            finish_async_gen_step(gen, id);
12960        }
12961    }
12962}
12963
12964/// A promise for `v`: `v` itself if it is already a promise, else a promise
12965/// resolved with `v`.
12966pub fn promise_of(v: &Value) -> Value {
12967    if with_host(|h| h.promise_id(v)).is_some() {
12968        return v.clone();
12969    }
12970    let p = with_host(|h| h.new_promise());
12971    let id = with_host(|h| h.promise_id(&p).unwrap());
12972    resolve_promise_val(id, v.clone());
12973    p
12974}
12975
12976/// Register a native reaction on promise `id` (schedules immediately if already
12977/// settled).
12978pub fn subscribe_native(id: u32, f: Box<dyn FnOnce(PromiseState, Value) -> Result<(), String>>) {
12979    // The continuation (`await` resumption above all) runs in the async context
12980    // frame it was registered in, not the settling code's.
12981    let frame = with_host(|h| h.async_frame.clone());
12982    let f: Box<dyn FnOnce(PromiseState, Value) -> Result<(), String>> =
12983        Box::new(move |s, v| in_frame(frame, || f(s, v)));
12984    // A native continuation (`await`, promise adoption, `for await`) observes a
12985    // rejection exactly as a `.catch` does, so it is not "unhandled".
12986    with_host(|h| h.promise_mark_handled(id));
12987    let state = with_host(|h| h.promise_state(id));
12988    if state == PromiseState::Pending {
12989        with_host(|h| h.add_reaction(id, PromiseReaction::Native(f)));
12990    } else {
12991        let val = with_host(|h| h.promise_value(id));
12992        with_host(|h| h.queue_micro_native(Box::new(move || f(state, val))));
12993    }
12994}
12995
12996/// The Promise "resolve" operation: adopt `value`'s state if it is a promise,
12997/// else fulfill with it.
12998pub fn resolve_promise_val(id: u32, value: Value) {
12999    if with_host(|h| h.promise_state(id)) != PromiseState::Pending {
13000        return;
13001    }
13002    if let Some(vid) = with_host(|h| h.promise_id(&value)) {
13003        if vid == id {
13004            // Resolving a promise with itself → reject with a TypeError.
13005            let e = with_host(|h| {
13006                crate::builtins::synth_error(h, "TypeError: Chaining cycle detected")
13007            });
13008            reject_promise_val(id, e);
13009            return;
13010        }
13011        // A native promise is still a thenable, so the spec routes it through
13012        // `NewPromiseResolveThenableJob` too — one microtask before the adoption
13013        // is even registered. (`await` does NOT pay this: V8's await optimization
13014        // subscribes to a native promise directly, which `await_value` mirrors.)
13015        with_host(|h| {
13016            h.queue_micro_native(Box::new(move || {
13017                subscribe_native(
13018                    vid,
13019                    Box::new(move |state, val| {
13020                        with_host(|h| h.settle_promise(id, state, val.clone()));
13021                        schedule_reactions(id);
13022                        Ok(())
13023                    }),
13024                );
13025                Ok(())
13026            }))
13027        });
13028        return;
13029    }
13030    // ECMA-262 27.2.1.3.2: any OBJECT carrying a callable `then` is assimilated
13031    // through a dedicated job — the promise adopts what `then` reports, it is
13032    // never fulfilled WITH the thenable itself.
13033    if let Some(then) = thenable_then(&value) {
13034        with_host(|h| {
13035            h.queue_micro_native(Box::new(move || resolve_thenable_job(id, value, then)))
13036        });
13037        return;
13038    }
13039    with_host(|h| h.settle_promise(id, PromiseState::Fulfilled, value));
13040    schedule_reactions(id);
13041}
13042
13043/// `value.then` if `value` is an object with a callable `then` — the test that
13044/// makes a value a *thenable*. Primitives (and objects without one) are `None`.
13045fn thenable_then(value: &Value) -> Option<Value> {
13046    // A PROXY is not a plain object and supplies `then` through its `get` trap,
13047    // so both tests below missed it: `Promise.resolve(proxyThenable)` fulfilled
13048    // WITH the proxy instead of adopting it.
13049    if with_host(|h| h.kind_of(value)) == Some(ObjKind::Proxy) {
13050        return protocol_lookup(value, "then")
13051            .ok()
13052            .flatten()
13053            .filter(|f| with_host(|h| is_callable(h, f)));
13054    }
13055    if !with_host(|h| matches!(h.get(value), Some(JsObj::Object(_)))) {
13056        return None;
13057    }
13058    let then = with_host(|h| lookup_chain(h, value, "then"))?;
13059    with_host(|h| is_callable(h, &then)).then_some(then)
13060}
13061
13062/// `NewPromiseResolveThenableJob`: hand the thenable this promise's own resolve /
13063/// reject continuations and let it settle us. A throw out of `then` rejects.
13064fn resolve_thenable_job(id: u32, thenable: Value, then: Value) -> Result<(), String> {
13065    let res = with_host(|h| h.alloc(JsObj::Builtin(format!("@@presolve:{id}"))));
13066    let rej = with_host(|h| h.alloc(JsObj::Builtin(format!("@@preject:{id}"))));
13067    if let Err(e) = invoke(&then, vec![res, rej], Some(thenable)) {
13068        let ev = take_exc_or_error(&e);
13069        reject_promise_val(id, ev);
13070    }
13071    Ok(())
13072}
13073
13074pub fn reject_promise_val(id: u32, value: Value) {
13075    if with_host(|h| h.promise_state(id)) != PromiseState::Pending {
13076        return;
13077    }
13078    with_host(|h| {
13079        h.settle_promise(id, PromiseState::Rejected, value);
13080        h.pending_rejections.push(id);
13081    });
13082    schedule_reactions(id);
13083}
13084
13085/// Report every promise that settled rejected since the last checkpoint and
13086/// still has no handler. Node's default is `--unhandled-rejections=throw`: the
13087/// rejection becomes an uncaught exception (stderr + exit 1) unless a
13088/// `process.on('unhandledRejection')` listener takes it.
13089fn check_unhandled_rejections() -> Result<(), String> {
13090    loop {
13091        let ids: Vec<u32> = with_host(|h| std::mem::take(&mut h.pending_rejections));
13092        if ids.is_empty() {
13093            return Ok(());
13094        }
13095        for id in ids {
13096            let unhandled = with_host(|h| {
13097                h.promise_state(id) == PromiseState::Rejected && !h.promises[id as usize].handled
13098            });
13099            if !unhandled {
13100                continue;
13101            }
13102            // Report each promise at most once, however many checkpoints pass.
13103            with_host(|h| h.promise_mark_handled(id));
13104            let val = with_host(|h| h.promise_value(id));
13105            let listeners = with_host(|h| h.take_process_listeners("unhandledRejection"));
13106            if listeners.is_empty() {
13107                // Node's default `--unhandled-rejections=throw` raises it as an
13108                // uncaught exception with origin `unhandledRejection`, so an
13109                // `uncaughtException` listener can still take it.
13110                if with_host(|h| {
13111                    h.has_process_listeners("uncaughtException")
13112                        || h.has_process_listeners("uncaughtExceptionMonitor")
13113                }) {
13114                    let err = unhandled_rejection_error(&val)?;
13115                    if deliver_uncaught(&err, "unhandledRejection")? {
13116                        continue;
13117                    }
13118                }
13119                let msg = with_host(|h| crate::builtins::error_string(h, &val));
13120                with_host(|h| {
13121                    h.exc = Some(val);
13122                    h.fatal_from_promise = true;
13123                });
13124                return Err(msg);
13125            }
13126            let promise = with_host(|h| h.alloc(JsObj::Promise { id }));
13127            for f in listeners {
13128                invoke(&f, vec![val.clone(), promise.clone()], None)?;
13129            }
13130        }
13131    }
13132}
13133
13134/// What an unhandled rejection is raised as: the reason itself when it is an
13135/// `Error`, else node's `UnhandledPromiseRejection` wrapper — an `Error` whose
13136/// message quotes the inspected reason, with own enumerable `code` and `name`.
13137fn unhandled_rejection_error(reason: &Value) -> Result<Value, String> {
13138    let error_ctor = crate::builtins::global_binding("Error").unwrap_or(Value::Undef);
13139    if instance_of(reason, &error_ctor).unwrap_or(false) {
13140        return Ok(reason.clone());
13141    }
13142    Ok(with_host(|h| {
13143        let shown = h.inspect(reason);
13144        let msg = format!(
13145            "Error: This error originated either by throwing inside of an async function \
13146             without a catch block, or by rejecting a promise which was not handled with \
13147             .catch(). The promise rejected with the reason \"{shown}\"."
13148        );
13149        let err = crate::builtins::synth_error(h, &msg);
13150        let code = h.new_str("ERR_UNHANDLED_REJECTION");
13151        let name = h.new_str("UnhandledPromiseRejection");
13152        if let Some(JsObj::Object(p)) = h.get_mut(&err) {
13153            p.insert("code".into(), code);
13154            p.insert("name".into(), name);
13155        }
13156        err
13157    }))
13158}
13159
13160/// Drain a settled promise's reactions into microtasks.
13161fn schedule_reactions(id: u32) {
13162    let reactions = with_host(|h| h.take_reactions(id));
13163    let state = with_host(|h| h.promise_state(id));
13164    let value = with_host(|h| h.promise_value(id));
13165    for r in reactions {
13166        let value = value.clone();
13167        match r {
13168            PromiseReaction::Native(f) => {
13169                with_host(|h| h.queue_micro_native(Box::new(move || f(state, value))));
13170            }
13171            PromiseReaction::Js {
13172                on_ful,
13173                on_rej,
13174                result,
13175                frame,
13176            } => {
13177                with_host(|h| {
13178                    h.queue_micro_native(Box::new(move || {
13179                        in_frame(frame, || {
13180                            run_js_reaction(state, value, on_ful, on_rej, result)
13181                        })
13182                    }))
13183                });
13184            }
13185        }
13186    }
13187}
13188
13189/// Run a `.then` reaction: call the appropriate handler and settle the result
13190/// promise with its outcome (or pass through if there is no handler).
13191fn run_js_reaction(
13192    state: PromiseState,
13193    value: Value,
13194    on_ful: Value,
13195    on_rej: Value,
13196    result: Value,
13197) -> Result<(), String> {
13198    let rid = match with_host(|h| h.promise_id(&result)) {
13199        Some(i) => i,
13200        None => return Ok(()),
13201    };
13202    let handler = if state == PromiseState::Rejected {
13203        on_rej
13204    } else {
13205        on_ful
13206    };
13207    if with_host(|h| is_callable(h, &handler)) {
13208        match invoke(&handler, vec![value], None) {
13209            Ok(r) => resolve_promise_val(rid, r),
13210            Err(e) => reject_promise_val(rid, take_exc_or_error(&e)),
13211        }
13212    } else if state == PromiseState::Rejected {
13213        reject_promise_val(rid, value);
13214    } else {
13215        resolve_promise_val(rid, value);
13216    }
13217    Ok(())
13218}
13219
13220/// The JS value of a just-caught error: the live `exc` (a real thrown value) or a
13221/// synthesized `Error` from the internal message.
13222pub fn take_exc_or_error(e: &str) -> Value {
13223    with_host(|h| {
13224        h.error.take();
13225        h.exc
13226            .take()
13227            .unwrap_or_else(|| crate::builtins::synth_error(h, e))
13228    })
13229}
13230
13231/// Register a user `.then` reaction (JS handlers + result promise).
13232pub fn promise_then(p: &Value, on_ful: Value, on_rej: Value) -> Value {
13233    let id = match with_host(|h| h.promise_id(p)) {
13234        Some(i) => i,
13235        None => return Value::Undef,
13236    };
13237    with_host(|h| h.promise_mark_handled(id));
13238    // The result is built with the RECEIVER's species, so a subclass promise
13239    // stays a subclass promise through a `.then` chain.
13240    let result = match crate::builtins::promise_species_from(p) {
13241        Ok(Some(sp)) => sp,
13242        _ => with_host(|h| h.new_promise()),
13243    };
13244    let reaction = PromiseReaction::Js {
13245        on_ful,
13246        on_rej,
13247        result: result.clone(),
13248        frame: with_host(|h| h.async_frame.clone()),
13249    };
13250    let state = with_host(|h| h.promise_state(id));
13251    if state == PromiseState::Pending {
13252        with_host(|h| h.add_reaction(id, reaction));
13253    } else {
13254        let value = with_host(|h| h.promise_value(id));
13255        if let PromiseReaction::Js {
13256            on_ful,
13257            on_rej,
13258            result,
13259            frame,
13260        } = reaction
13261        {
13262            with_host(|h| {
13263                h.queue_micro_native(Box::new(move || {
13264                    in_frame(frame, || {
13265                        run_js_reaction(state, value, on_ful, on_rej, result)
13266                    })
13267                }))
13268            });
13269        }
13270    }
13271    result
13272}
13273
13274/// The ReferenceError for touching `this` in a derived constructor before
13275/// `super()` — or returning from one without calling it.
13276pub fn this_before_super_error() -> String {
13277    "ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor".to_string()
13278}
13279
13280/// The intrinsic a builtin name denotes. Two property paths that the spec
13281/// defines as the SAME function object compare `===`: `Number.parseInt` is
13282/// `%parseInt%` (21.1.2.13) and `Number.parseFloat` is `%parseFloat%`
13283/// (21.1.2.12), so `Number.parseInt === parseInt` is `true`.
13284///
13285/// A prototype ALIAS is the same: `String.prototype.trimLeft` IS `trimStart`,
13286/// `Set.prototype.keys` IS `values`, `Date.prototype.toGMTString` IS
13287/// `toUTCString`, and each `[Symbol.iterator]` the spec defines as an existing
13288/// method (`Array.prototype[@@iterator]` is `values`) is that method. The
13289/// generated arity table already records each alias by the name of the function
13290/// it aliases, so an `@proto:` key whose table name is a plain identifier other
13291/// than its own last segment resolves to that sibling. A table name in brackets
13292/// (`[Symbol.iterator]`) is a function of its own, not an alias.
13293fn builtin_identity(name: &str) -> std::borrow::Cow<'_, str> {
13294    use std::borrow::Cow;
13295    match name {
13296        "Number.parseInt" => return Cow::Borrowed("parseInt"),
13297        "Number.parseFloat" => return Cow::Borrowed("parseFloat"),
13298        _ => {}
13299    }
13300    if let Some((ctor, member)) = name
13301        .strip_prefix("@proto:")
13302        .and_then(|rest| rest.rsplit_once(':'))
13303    {
13304        if let Some((aliased, _)) = crate::builtins::builtin_meta(name) {
13305            if aliased != member && !aliased.starts_with('[') {
13306                return Cow::Owned(format!("@proto:{ctor}:{aliased}"));
13307            }
13308        }
13309    }
13310    Cow::Borrowed(name)
13311}