nodejs/builtins.rs
1//! Builtin op handlers (compiler-emitted `CallBuiltin` ids) plus the JS standard
2//! library (`console`, `Math`, `JSON`, `Object`, array/string methods) reachable
3//! from the host. Handlers pop their arguments off the VM operand stack and
4//! return the result value, which the VM pushes back.
5
6use crate::host::{self, ops, with_host, FuncVal, JsObj, ObjKind};
7use crate::ieee754;
8use fusevm::{NumOp, Value, VM};
9use indexmap::IndexMap;
10
11/// Register every node-js builtin id on a VM.
12pub fn install(vm: &mut VM) {
13 vm.register_builtin(ops::GETLOCAL, b_getlocal);
14 vm.register_builtin(ops::SETLOCAL, b_setlocal);
15 vm.register_builtin(ops::SETLOCAL_STRICT, b_setlocal_strict);
16 vm.register_builtin(ops::DECLARE, b_declare);
17 vm.register_builtin(ops::DECLARE_CONST, b_declare_const);
18 vm.register_builtin(ops::MARK_HOLE, b_mark_hole);
19 vm.register_builtin(ops::DELNAME, b_delname);
20 vm.register_builtin(ops::GETATTR, b_getattr);
21 vm.register_builtin(ops::SETATTR, b_setattr);
22 vm.register_builtin(ops::GETITEM, b_getitem);
23 vm.register_builtin(ops::SETITEM, b_setitem);
24 vm.register_builtin(ops::DELITEM, b_delitem);
25 vm.register_builtin(ops::MKSTR, b_mkstr);
26 vm.register_builtin(ops::MKARR, b_mkarr);
27 vm.register_builtin(ops::MKOBJ, b_mkobj);
28 vm.register_builtin(ops::CALL, b_call);
29 vm.register_builtin(ops::CALL_METHOD, b_call_method);
30 vm.register_builtin(ops::CALL_VALUE, b_call_value);
31 vm.register_builtin(ops::NEW, b_new);
32 vm.register_builtin(ops::TRUTHY, b_truthy);
33 vm.register_builtin(ops::TOSTR, b_tostr);
34 vm.register_builtin(ops::MKFUNC, b_mkfunc);
35 vm.register_builtin(ops::GETITER, b_getiter);
36 vm.register_builtin(ops::FORITER, b_foriter);
37 vm.register_builtin(ops::FORIN_KEYS, b_forin_keys);
38 vm.register_builtin(ops::FORIN_ALIVE, b_forin_alive);
39 vm.register_builtin(ops::HOIST_TDZ, b_hoist_tdz);
40 vm.register_builtin(ops::NEW_SPREAD, b_new_spread);
41 vm.register_builtin(ops::SUPER_CALL_SPREAD, b_super_call_spread);
42 vm.register_builtin(ops::CONTAINS, b_contains);
43 vm.register_builtin(ops::SIG_RETURN, b_sig_return);
44 vm.register_builtin(ops::BINOP, b_binop);
45 vm.register_builtin(ops::UNARY, b_unary);
46 vm.register_builtin(ops::STRICT_EQ, b_strict_eq);
47 vm.register_builtin(ops::LOOSE_EQ, b_loose_eq);
48 vm.register_builtin(ops::TYPEOF, b_typeof);
49 vm.register_builtin(ops::LOAD_NULL, b_load_null);
50 vm.register_builtin(ops::THROW, b_throw);
51 vm.register_builtin(ops::TRY, b_try);
52 vm.register_builtin(ops::NULLISH, b_nullish);
53 vm.register_builtin(ops::UNPACK, b_unpack);
54 vm.register_builtin(ops::BUILD_ARGS, b_build_args);
55 vm.register_builtin(ops::THIS, b_this);
56 vm.register_builtin(ops::INSTANCEOF, b_instanceof);
57 vm.register_builtin(ops::DELPROP_NAME, b_delprop_name);
58 vm.register_builtin(ops::APPLY, b_apply);
59 vm.register_builtin(ops::APPLY_METHOD, b_apply_method);
60 vm.register_builtin(ops::OBJ_REST, b_obj_rest);
61 vm.register_builtin(ops::DIV, b_div);
62 vm.register_builtin(ops::POW, b_pow);
63 vm.register_builtin(ops::MKCLASS, b_mkclass);
64 vm.register_builtin(ops::DEF_MEMBER, b_def_member);
65 vm.register_builtin(ops::DEF_FIELD, b_def_field);
66 vm.register_builtin(ops::SUPER_CALL, b_super_call);
67 vm.register_builtin(ops::SUPER_GET, b_super_get);
68 vm.register_builtin(ops::YIELD, b_yield);
69 vm.register_builtin(ops::PROPKEY, b_propkey);
70 vm.register_builtin(ops::NEW_TARGET, b_new_target);
71 vm.register_builtin(ops::AWAIT, b_await);
72 vm.register_builtin(ops::DEF_ACCESSOR, b_def_accessor);
73 vm.register_builtin(ops::DBG_LINE, b_dbg_line);
74 vm.register_builtin(ops::MKBIGINT, b_mkbigint);
75 vm.register_builtin(ops::MKREGEX, b_mkregex);
76 vm.register_builtin(ops::TAG_TMPL, b_tag_tmpl);
77 vm.register_builtin(ops::GET_ASYNC_ITER, b_get_async_iter);
78 vm.register_builtin(ops::ASYNC_STEP, b_async_step);
79 vm.register_builtin(ops::ITER_RESULT, b_iter_result);
80 vm.register_builtin(ops::NUM_STEP, b_num_step);
81 vm.register_builtin(ops::ITER_CLOSE, b_iter_close);
82 vm.register_builtin(ops::TYPEOF_NAME, b_typeof_name);
83 vm.register_builtin(ops::SIG_BREAK, b_sig_break);
84 vm.register_builtin(ops::SIG_CONTINUE, b_sig_continue);
85 vm.register_builtin(ops::SIG_UNWIND, b_sig_unwind);
86 vm.register_builtin(ops::PUSH_SCOPE, b_push_scope);
87 vm.register_builtin(ops::POP_SCOPE, b_pop_scope);
88 vm.register_builtin(ops::COPY_SCOPE, b_copy_scope);
89 vm.register_builtin(ops::DECLARE_VAR, b_declare_var);
90 vm.register_builtin(ops::HOIST_VAR, b_hoist_var);
91 vm.register_builtin(ops::MAP_ARGS, b_map_args);
92 vm.register_builtin(ops::YIELD_DELEGATE, b_yield_delegate);
93 vm.register_builtin(ops::DELEGATE_STEP, b_delegate_step);
94 vm.register_builtin(ops::SUPER_SET, b_super_set);
95 vm.register_builtin(ops::WITH_PUSH, b_with_push);
96 vm.register_builtin(ops::WITH_GET, b_with_get);
97 vm.register_builtin(ops::WITH_SET, b_with_set);
98 vm.register_builtin(ops::WITH_SET_STRICT, b_with_set_strict);
99 vm.register_builtin(ops::WITH_TYPEOF, b_with_typeof);
100 vm.register_builtin(ops::WITH_FN, b_with_fn);
101 vm.register_builtin(ops::CALL_THIS, b_call_this);
102 vm.register_builtin(ops::APPLY_THIS, b_apply_this);
103 vm.register_builtin(ops::NAMED_EVAL, b_named_eval);
104}
105
106/// `ITER_CLOSE`: close the iterator on the stack (a for-of `break`). A generator
107/// runs its pending `finally`; a user iterator object gets its `.return()` called
108/// if present; a plain materialized iterator just drops. Returns `undefined`.
109/// `IteratorClose` (7.4.9): resume a generator with a forced return so its
110/// pending `finally` runs, or invoke a user iterator's `.return()`. A value that
111/// is neither is left alone.
112pub(crate) fn close_iterator(it: &Value) -> Result<(), String> {
113 if with_host(|h| h.is_generator_val(it)) {
114 host::gen_return(it, Value::Undef)?;
115 return Ok(());
116 }
117 if matches!(with_host(|h| h.get(it).cloned()), Some(JsObj::Object(_))) {
118 if let Some(f) = with_host(|h| host::lookup_chain(h, it, "return")) {
119 if with_host(|h| host::is_callable(h, &f)) {
120 // 7.4.11 IteratorClose step 9: the result of `return()` must be
121 // an object, or the close itself is a TypeError.
122 let result = host::invoke(&f, Vec::new(), Some(it.clone()))?;
123 host::require_iter_result(&result)?;
124 }
125 }
126 }
127 Ok(())
128}
129
130fn b_iter_close(vm: &mut VM, _: u8) -> Value {
131 let it = vm.pop();
132 // A `finally` may print or yield, but the loop is done either way; an error
133 // it raises still propagates.
134 match close_iterator(&it) {
135 Ok(()) => Value::Undef,
136 Err(e) => abort_without_closing(vm, e),
137 }
138}
139
140/// `NUM_STEP`: the `++`/`--` core. Pops `old` and the step `tag` (`+1`/`-1`),
141/// pushes `ToNumeric(old)` (a BigInt stays a BigInt, else a Number), and returns
142/// `old ± 1` in the SAME numeric type — so `x++` on a BigInt neither coerces to
143/// Number nor throws the mix error.
144fn b_num_step(vm: &mut VM, _: u8) -> Value {
145 let old = vm.pop();
146 let tag = match vm.pop() {
147 Value::Int(n) => n,
148 Value::Float(f) => f as i64,
149 _ => 1,
150 };
151 if with_host(|h| h.is_bigint_val(&old)) {
152 let b = with_host(|h| h.as_bigint(&old)).unwrap();
153 let old_n = with_host(|h| h.new_bigint(b.clone()));
154 let new = with_host(|h| h.new_bigint(b + num_bigint::BigInt::from(tag)));
155 vm.push(old_n);
156 new
157 } else {
158 let n = with_host(|h| h.to_number(&old));
159 vm.push(Value::Float(n));
160 Value::Float(n + tag as f64)
161 }
162}
163
164/// `ASYNC_STEP`: one step of a `for await` loop — returns a Promise of the
165/// `{value, done}` record (see `host::async_step`).
166fn b_async_step(vm: &mut VM, _: u8) -> Value {
167 let iter = vm.pop();
168 let r = host::async_step(&iter);
169 finish(vm, r)
170}
171
172/// `ITER_RESULT`: the awaited result of an async iterator's `next()` must be an
173/// object (7.4.4 step 3); a primitive one would read `done` as `undefined`
174/// forever. Leaves the record on the stack.
175fn b_iter_result(vm: &mut VM, _: u8) -> Value {
176 let step = vm.pop();
177 match host::require_iter_result(&step) {
178 Ok(()) => step,
179 Err(e) => abort(vm, e),
180 }
181}
182
183/// `MKBIGINT`: pop the canonical decimal digit string constant, allocate the heap
184/// BigInt. The lexer already validated the digits, so parsing cannot fail here.
185fn b_mkbigint(vm: &mut VM, _: u8) -> Value {
186 let digits = sval(&vm.pop());
187 match digits.parse::<num_bigint::BigInt>() {
188 Ok(b) => with_host(|h| h.new_bigint(b)),
189 Err(_) => abort(vm, host::type_error("invalid BigInt literal")),
190 }
191}
192
193/// `TAG_TMPL`: invoke a tagged template. The compiler emits the operands as
194/// `[tag, n, m, cooked×n, raw×n, values×m]` (see `compile_tagged_template`).
195/// Builds the `strings` array (carrying its `.raw` array) and calls
196/// `tag(strings, ...values)`.
197/// Reject a non-callable where node's scheduling entry points demand one.
198///
199/// Every one of them validates SYNCHRONOUSLY — `try { queueMicrotask(1) }
200/// catch` catches an `ERR_INVALID_ARG_TYPE` in node. Here the value was queued
201/// unchecked and the failure surfaced from the event loop instead, as an
202/// uncaught `1 is not a function` that killed the process past any `try` around
203/// the call.
204fn require_callback(cb: &Value) -> Result<(), String> {
205 if with_host(|h| host::is_callable(h, cb)) {
206 return Ok(());
207 }
208 Err(host::invalid_arg_type(
209 "callback", "argument", "function", cb,
210 ))
211}
212
213fn b_tag_tmpl(vm: &mut VM, argc: u8) -> Value {
214 note_site(vm);
215 // The chunk holding this site, read before the operands are popped and
216 // before any host borrow: together with the compiler's per-site ordinal it
217 // names the Parse Node whose template object 13.2.8.4 caches.
218 let chunk = vm.chunk.op_hash;
219 let mut all = pop_n(vm, argc as usize);
220 let int_of = |v: &Value| match v {
221 Value::Int(n) => *n as usize,
222 Value::Float(f) => *f as usize,
223 _ => 0,
224 };
225 let this = all.remove(0);
226 let tag = all.remove(0);
227 let n = int_of(&all.remove(0));
228 let mcount = int_of(&all.remove(0));
229 let site = int_of(&all.remove(0)) as u64;
230 let cooked: Vec<Value> = all.drain(0..n.min(all.len())).collect();
231 let raw: Vec<Value> = all.drain(0..n.min(all.len())).collect();
232 let values: Vec<Value> = all.drain(0..mcount.min(all.len())).collect();
233 // GetTemplateObject caches by Parse Node, so a site evaluated twice hands
234 // back the SAME object — the whole point of the caching, since a tag that
235 // memoizes on the strings array (lit-html, graphql-tag) re-parses its
236 // template on every call without it.
237 let key = (chunk, site);
238 let strings = match with_host(|h| h.template_object(key)) {
239 Some(cached) => cached,
240 None => {
241 // strings = cooked array; strings.raw = raw array.
242 let strings = with_host(|h| h.new_array(cooked));
243 let raw_arr = with_host(|h| h.new_array(raw));
244 // `raw` is an own property that is neither writable, enumerable, nor
245 // configurable, so it stays out of `Object.keys(strings)` while
246 // `getOwnPropertyNames` still reports it.
247 with_host(|h| {
248 h.set_fn_prop(&strings, "raw", raw_arr.clone());
249 h.set_prop_attrs(
250 &strings,
251 "raw",
252 host::PropAttrs {
253 writable: false,
254 enumerable: false,
255 configurable: false,
256 },
257 );
258 // Steps 12-13 run SetIntegrityLevel(frozen) on the raw array and
259 // then on the template object itself. Without them a tag could
260 // write through its own strings array and corrupt every later
261 // evaluation of the site — which is exactly what caching makes
262 // reachable, so the freeze and the cache belong together.
263 h.seal_object(&raw_arr, true);
264 h.seal_object(&strings, true);
265 h.set_template_object(key, strings.clone());
266 });
267 strings
268 }
269 };
270 let mut call_args = vec![strings];
271 call_args.extend(values);
272 let this = match this {
273 Value::Undef => None,
274 v => Some(v),
275 };
276 let r = host::invoke(&tag, call_args, this);
277 finish(vm, r)
278}
279
280/// `GET_ASYNC_ITER`: obtain an async iterator for `for await (… of …)`. If the
281/// value has a `Symbol.asyncIterator`, use it; otherwise fall back to its sync
282/// iterator (each yielded value is awaited). Returns the iterator object/handle.
283fn b_get_async_iter(vm: &mut VM, _: u8) -> Value {
284 let src = vm.pop();
285 let r = host::get_async_iterator(&src).map_err(|e| {
286 // `for await` names the source AND says ASYNC: `for await (const x of
287 // o)` is `o is not async iterable`. Built here rather than through
288 // `name_call_site`, whose suffix table has no entry that composes.
289 match host::call_site_text(vm) {
290 Some(t) if e.ends_with(" is not iterable") => {
291 host::type_error(&format!("{t} is not async iterable"))
292 }
293 _ => e,
294 }
295 });
296 finish(vm, r)
297}
298
299/// `MKREGEX`: pop `(pattern, flags)`, translate the JS pattern to a Rust `regex`,
300/// and allocate a `RegExp`. A pattern using a JS feature Rust `regex` cannot
301/// express (backreference/lookaround) throws a `SyntaxError` here.
302fn b_mkregex(vm: &mut VM, _: u8) -> Value {
303 let flags = sval(&vm.pop());
304 let pattern = sval(&vm.pop());
305 match crate::regexp::build_regexp(&pattern, &flags) {
306 Ok(v) => v,
307 Err(e) => abort(vm, e),
308 }
309}
310
311/// DAP per-statement marker (`node --dap` only; the compiler emits this before
312/// each statement under `debug`). Pops the source line pushed by the preceding
313/// `LoadInt` and fires the debugger line hook, which pauses at breakpoints/step
314/// targets. Returns `undefined` (the compiler pops it). A no-op unless a debug
315/// session is active.
316fn b_dbg_line(vm: &mut VM, _: u8) -> Value {
317 let line = match vm.pop() {
318 Value::Int(n) => n as u32,
319 _ => 0,
320 };
321 crate::dap::on_debug_line(line);
322 Value::Undef
323}
324
325/// Install an object-literal getter/setter on an object (`kind` is `member::GET`
326/// or `member::SET`). Keeps the object on the stack.
327fn b_def_accessor(vm: &mut VM, _: u8) -> Value {
328 let func = vm.pop();
329 let kind = match vm.pop() {
330 Value::Int(n) => n,
331 _ => 0,
332 };
333 let name = sval(&vm.pop());
334 let obj = vm.pop();
335 with_host(|h| {
336 if kind == host::member::SET {
337 h.set_accessor(&obj, &name, None, Some(func));
338 } else {
339 h.set_accessor(&obj, &name, Some(func), None);
340 }
341 });
342 obj
343}
344
345fn b_await(vm: &mut VM, _: u8) -> Value {
346 let v = vm.pop();
347 match host::await_value(v, op_pos(vm)) {
348 Ok(r) => r,
349 Err(e) => abort(vm, e),
350 }
351}
352
353// ── classes / super / generators / property keys (compiler-emitted ops) ──────
354
355fn b_mkclass(vm: &mut VM, argc: u8) -> Value {
356 // The fourth argument, when present, is the FuncDef carrying the class's
357 // source span.
358 let source_def = match argc {
359 4 => match vm.pop() {
360 Value::Int(n) => Some(n as usize),
361 _ => None,
362 },
363 _ => None,
364 };
365 let ctor = vm.pop();
366 let parent = vm.pop();
367 let name = sval(&vm.pop());
368 host::build_class(&name, parent, ctor, source_def)
369}
370
371fn b_def_member(vm: &mut VM, _: u8) -> Value {
372 let func = vm.pop();
373 let is_static = matches!(vm.pop(), Value::Bool(true));
374 let kind = match vm.pop() {
375 Value::Int(n) => n,
376 _ => 0,
377 };
378 let name = sval(&vm.pop());
379 let class_val = vm.pop();
380 host::define_member(&class_val, &name, kind, is_static, func);
381 class_val
382}
383
384fn b_def_field(vm: &mut VM, _: u8) -> Value {
385 // `name_anon`: the initializer was an anonymous function definition, so
386 // 15.7.10 NamedEvaluation names its result after the field. Syntactic —
387 // decided by the compiler, not re-derived from the produced value.
388 let name_anon = matches!(vm.pop(), Value::Bool(true));
389 let thunk = vm.pop();
390 let name = sval(&vm.pop());
391 let class_val = vm.pop();
392 host::define_field(&class_val, &name, thunk, name_anon);
393 class_val
394}
395
396/// `super(...args)` in a derived constructor: run the parent constructor on the
397/// current `this`, then this class's field initializers.
398/// `SUPER_CALL_SPREAD` — `super(...xs)`, where the argument list is built at
399/// run time. Shares everything below with the fixed-arity form; only where the
400/// arguments come from differs.
401fn b_super_call_spread(vm: &mut VM, _: u8) -> Value {
402 note_site(vm);
403 let arr = vm.pop();
404 let args = host::iter_all(&arr).unwrap_or_default();
405 super_call_with(vm, args)
406}
407
408fn b_super_call(vm: &mut VM, argc: u8) -> Value {
409 note_site(vm);
410 let args = pop_n(vm, argc as usize);
411 super_call_with(vm, args)
412}
413
414fn super_call_with(vm: &mut VM, args: Vec<Value>) -> Value {
415 let this = with_host(|h| h.current_this());
416 let this = match this {
417 Some(t) => t,
418 None => return abort(vm, host::type_error("'super' keyword unexpected here")),
419 };
420 // The class whose constructor is running = the running method's home class.
421 let (parent, fields) = with_host(|h| h.super_context());
422 let (parent, fields) = match parent {
423 Some(p) => (p, fields),
424 None => return abort(vm, host::type_error("'super' keyword unexpected here")),
425 };
426 let nt = with_host(|h| h.current_new_target()).unwrap_or_else(|| this.clone());
427 let this = match host::super_construct(&parent, args, &this, &nt) {
428 Err(e) => return abort(vm, e),
429 // The parent returned an object of its own: 15.7.15 makes THAT the
430 // instance, so `this` is rebound to it for the rest of the constructor
431 // and it is what `new` hands back.
432 Ok(Some(replacement)) => {
433 with_host(|h| h.set_current_this(replacement.clone()));
434 replacement
435 }
436 Ok(None) => this,
437 };
438 if !with_host(|h| h.bind_super_this()) {
439 return abort(
440 vm,
441 "ReferenceError: Super constructor may only be called once".to_string(),
442 );
443 }
444 // Run this (derived) class's own instance-field initializers after super.
445 if let Some(proto) = with_host(|h| h.current_home_proto()) {
446 host::install_private_methods(&proto, &this);
447 }
448 for (name, thunk, name_anon) in fields {
449 if let Err(e) = host::init_one_field(&this, &name, &thunk, name_anon) {
450 return abort(vm, e);
451 }
452 }
453 Value::Undef
454}
455
456/// `super.name` — a method from the parent's prototype, or a getter's result.
457fn b_super_get(vm: &mut VM, _: u8) -> Value {
458 let name = sval(&vm.pop());
459 match with_host(|h| h.super_resolve(&name)) {
460 // The host walks only the property maps it owns. A member a builtin
461 // prototype supplies natively — `Object.prototype.toString`, `Map
462 // .prototype.get`, `Array.prototype.push` — is not in any of them, so
463 // finish the `[[Get]]` on the super base with an ordinary property read.
464 host::SuperRef::Data(Value::Undef) => {
465 let Some(base) = super_builtin_base() else {
466 return Value::Undef;
467 };
468 let this = with_host(|h| h.current_this()).unwrap_or(Value::Undef);
469 match get_property_recv(&base, &name, &this) {
470 Ok(v) => v,
471 Err(e) => abort(vm, e),
472 }
473 }
474 host::SuperRef::Data(v) => v,
475 host::SuperRef::Getter(getter) => {
476 let this = with_host(|h| h.current_this());
477 match host::invoke(&getter, Vec::new(), this) {
478 Ok(v) => v,
479 Err(e) => abort(vm, e),
480 }
481 }
482 }
483}
484
485/// The object a `super.x` read continues on once the host's own chain walk has
486/// come up empty: `HomeObject.[[GetPrototypeOf]]()` (13.3.7.3), where that
487/// prototype is a builtin one the host does not model as a property map.
488///
489/// - an object-literal method: its home object's prototype (`Object.prototype`
490/// for a plain literal);
491/// - a static method: the class constructor's prototype (`Function.prototype`
492/// for a base class, the parent constructor otherwise);
493/// - an instance method of a class whose chain bottoms out in a builtin
494/// (`class C extends Map`): that builtin's `prototype`, since `C.prototype`
495/// is not linked to it as a real object;
496/// - any other instance method: the home prototype's own prototype.
497fn super_builtin_base() -> Option<Value> {
498 let (class, is_static, home_object) = with_host(|h| h.super_home());
499 if let Some(home) = home_object {
500 return Some(prototype_of(&home));
501 }
502 let class = class?;
503 if is_static {
504 return Some(prototype_of(&class));
505 }
506 match with_host(|h| h.class_builtin_ancestor(&class)) {
507 Some(builtin) => get_property(&builtin, "prototype").ok(),
508 None => Some(prototype_of(&with_host(|h| h.current_home_proto())?)),
509 }
510}
511
512/// `super.name = value`: a setter found on the parent chain runs with the
513/// current `this`; otherwise the value is stored on `this` itself.
514fn b_super_set(vm: &mut VM, _: u8) -> Value {
515 let val = vm.pop();
516 let name = sval(&vm.pop());
517 let this = with_host(|h| h.current_this()).unwrap_or(Value::Undef);
518 match with_host(|h| h.super_setter(&name)) {
519 Some(Some(setter)) => match host::invoke(&setter, vec![val.clone()], Some(this)) {
520 Ok(_) => val,
521 Err(e) => abort(vm, e),
522 },
523 Some(None) => {
524 if with_host(|h| h.current_strict()) {
525 return abort(
526 vm,
527 host::type_error(&format!(
528 "Cannot set property {name} of #<Object> which has only a getter"
529 )),
530 );
531 }
532 val
533 }
534 None => match set_property(&this, &name, val.clone()) {
535 Ok(()) => val,
536 Err(e) => abort(vm, e),
537 },
538 }
539}
540
541/// Close every loop iterator parked on `vm`'s stack at the op now executing,
542/// innermost first. Called where a chunk is about to be halted abruptly, since
543/// the code that would ordinarily close them is being jumped over.
544///
545/// A close runs user code (a generator's `finally`), which can itself throw; the
546/// error is deliberately dropped, because it must not replace the completion
547/// that caused the unwind.
548fn close_parked_iters(vm: &mut VM) {
549 let n = host::parked_iters(vm);
550 close_n_parked_iters(vm, n);
551}
552
553fn close_n_parked_iters(vm: &mut VM, n: usize) {
554 if n == 0 {
555 return;
556 }
557 // The completion that caused the unwind is already pending on the host.
558 // Closing an iterator resumes ANOTHER generator, which settles its own
559 // signal/error state, so the pending one is saved across the close and put
560 // back — otherwise the outer `.return()` would be lost.
561 let saved = with_host(|h| (h.signal.take(), h.error.take(), h.exc.take()));
562 for _ in 0..n {
563 let it = vm.pop();
564 let _ = close_iterator(&it);
565 }
566 with_host(|h| {
567 h.signal = saved.0;
568 h.error = saved.1;
569 h.exc = saved.2;
570 });
571}
572
573fn b_yield(vm: &mut VM, _: u8) -> Value {
574 let v = vm.pop();
575 match host::gen_yield(v) {
576 Ok(sent) => {
577 // A `.return()`/`.throw()` injected on resume sets a pending Return
578 // signal (or error); halt the chunk so the body unwinds through any
579 // enclosing `try/finally`, exactly like a source `return`/`throw`.
580 if with_host(|h| h.error.is_some() || h.signal.is_some()) {
581 // Halting jumps past the loop exits, so the `for…of` / `yield*`
582 // iterators parked on this chunk's stack would be abandoned
583 // still-suspended. They sit directly beneath the yielded value
584 // (innermost last), and the compiler recorded how many are
585 // there for this exact op.
586 close_parked_iters(vm);
587 vm.ip = vm.chunk.ops.len();
588 }
589 sent
590 }
591 // An injected `.throw()` comes back as an error rather than a signal,
592 // and abandons the parked iterators the same way. The thrown value is
593 // already on the host as `exc`; `close_parked_iters` puts back whatever
594 // it saves, so the close cannot swallow it.
595 Err(e) => {
596 close_parked_iters(vm);
597 abort(vm, e)
598 }
599 }
600}
601
602/// `yield*`'s suspension. A `.return(v)` / `.throw(e)` forced onto the
603/// generator while it is delegating is NOT raised here — 15.5.5 hands it to
604/// the delegate (`return` / `throw` on the inner iterator), which may refuse
605/// it, absorb it, or yield again. So the completion is parked on the host for
606/// `DELEGATE_STEP`, and execution simply continues.
607fn b_yield_delegate(vm: &mut VM, _: u8) -> Value {
608 let v = vm.pop();
609 with_host(|h| h.delegate_resume = None);
610 match host::gen_yield(v) {
611 Ok(sent) => {
612 if let Some(host::Signal::Return(rv)) = with_host(|h| h.signal.take()) {
613 with_host(|h| h.delegate_resume = Some(host::DelegateResume::Return(rv)));
614 return Value::Undef;
615 }
616 sent
617 }
618 Err(_) => {
619 let ev = with_host(|h| h.exc.take()).unwrap_or(Value::Undef);
620 with_host(|h| h.delegate_resume = Some(host::DelegateResume::Throw(ev)));
621 Value::Undef
622 }
623 }
624}
625
626/// One step of a sync `yield*` (15.5.5 steps 7.a-7.c): the delegate is on top of
627/// the stack, `sent` is what resumed the generator. Leaves the delegate and the
628/// step result, which the compiled loop then tests for `done`.
629fn b_delegate_step(vm: &mut VM, _: u8) -> Value {
630 let sent = vm.pop();
631 let it = match vm.stack.last() {
632 Some(v) => v.clone(),
633 None => return abort(vm, "internal: DELEGATE_STEP with empty stack".into()),
634 };
635 let resume = with_host(|h| h.delegate_resume.take());
636 // `return` / `throw` of the delegate; a generator always has both.
637 let method = |name: &str| -> Result<Option<Value>, String> {
638 if with_host(|h| h.is_generator_val(&it)) {
639 return Ok(Some(Value::Undef));
640 }
641 let f = host::get_prop_chain(&it, name)?;
642 Ok(with_host(|h| host::is_callable(h, &f)).then_some(f))
643 };
644 let call = |name: &str, arg: Value| -> Result<Value, String> {
645 let r = host::call_method(&it, name, vec![arg])?;
646 host::require_iter_result(&r)?;
647 Ok(r)
648 };
649 let step = match resume {
650 None => call("next", sent),
651 Some(host::DelegateResume::Throw(ev)) => match method("throw") {
652 Err(e) => Err(e),
653 Ok(Some(_)) => call("throw", ev),
654 // No `throw`: the delegate is closed, and the generator gets a
655 // TypeError at the `yield*` (7.4.11 IteratorClose, then step 7.b.iii.5).
656 Ok(None) => {
657 return match close_iterator(&it) {
658 Ok(()) => abort_iterator_error(
659 vm,
660 host::type_error("The iterator does not provide a 'throw' method."),
661 ),
662 Err(e) => abort_iterator_error(vm, e),
663 };
664 }
665 },
666 Some(host::DelegateResume::Return(rv)) => match method("return") {
667 Err(e) => Err(e),
668 // No `return`: the generator itself returns `rv`.
669 Ok(None) => return halt_generator_return(vm, rv),
670 Ok(Some(_)) => match call("return", rv) {
671 Err(e) => Err(e),
672 Ok(r) => {
673 let done = get_property(&r, "done").map(|d| with_host(|h| h.truthy(&d)));
674 match done {
675 Err(e) => Err(e),
676 Ok(true) => match get_property(&r, "value") {
677 Ok(v) => return halt_generator_return(vm, v),
678 Err(e) => Err(e),
679 },
680 Ok(false) => Ok(r),
681 }
682 }
683 },
684 },
685 };
686 match step {
687 Ok(r) => r,
688 Err(e) => abort_iterator_error(vm, e),
689 }
690}
691
692/// Complete the running generator with a `return` of `value`: the delegate on
693/// top of the stack is finished (not closed), the iterators outside it are, and
694/// the chunk halts with a pending Return so `finally` blocks run.
695fn halt_generator_return(vm: &mut VM, value: Value) -> Value {
696 let n = host::parked_iters(vm);
697 if n > 0 {
698 vm.pop();
699 close_n_parked_iters(vm, n - 1);
700 }
701 with_host(|h| h.signal = Some(host::Signal::Return(value)));
702 vm.ip = vm.chunk.ops.len();
703 Value::Undef
704}
705
706/// `PROPKEY` — ToPropertyKey (7.1.19) for an object literal's COMPUTED key.
707///
708/// It called `JsHost::property_key` directly, which is the primitive-only half
709/// of the conversion, so an object key never ran `ToPrimitive`:
710/// `{ [{toString(){return "TS"}}]: 1 }` keyed on `"[object Object]"` while the
711/// member form `a[o] = 1` — which does go through `host::to_property_key` —
712/// keyed on `"TS"`. The two forms are the same abstract operation and now share
713/// the same implementation.
714fn b_propkey(vm: &mut VM, _: u8) -> Value {
715 let v = vm.pop();
716 match host::to_property_key(&v) {
717 Ok(k) => with_host(|h| h.new_str(k)),
718 Err(e) => abort(vm, e),
719 }
720}
721
722fn b_new_target(_vm: &mut VM, _: u8) -> Value {
723 with_host(|h| h.current_new_target().unwrap_or(Value::Undef))
724}
725
726/// `a / b` with JS/IEEE-754 semantics. fusevm's native `Op::Div` returns `Undef`
727/// for a zero divisor (so a frontend whose `/` differs must lower to a builtin —
728/// its own documented guidance), but JavaScript requires `x/0 === ±Infinity` and
729/// `0/0 === NaN`, so `/` is lowered here instead.
730///
731/// Being a builtin rather than a native op means it does NOT reach the numeric
732/// hook, so `/` was the one arithmetic operator that never ran `ToPrimitive`:
733/// `({valueOf(){return 7}}) / 2` was `NaN` where every other operator gave
734/// `3.5`, and `new Date(2) / 1` was `NaN` instead of `2`. It goes through the
735/// hook now, so `/` coerces exactly as `*` and `-` do.
736fn b_div(vm: &mut VM, _: u8) -> Value {
737 let b = vm.pop();
738 let a = vm.pop();
739 let r = numeric_hook(NumOp::Div, &a, &b);
740 finish(vm, r)
741}
742
743/// `a ** b`. Same reason `/` is a builtin: fusevm's native `Op::Pow` is IEEE-754
744/// `pow`, which returns 1 for `(-1) ** Infinity` and for `1 ** NaN` where the
745/// spec says NaN. Routing through the numeric hook also keeps BigInt `**` on the
746/// one code path that already handles it.
747fn b_pow(vm: &mut VM, _: u8) -> Value {
748 let b = vm.pop();
749 let a = vm.pop();
750 let r = numeric_hook(NumOp::Pow, &a, &b);
751 finish(vm, r)
752}
753
754/// `{ ...rest } = obj`: a new object of `obj`'s own keys minus the excluded set.
755fn b_obj_rest(vm: &mut VM, _: u8) -> Value {
756 let excluded = vm.pop();
757 let obj = vm.pop();
758 // The excluded keys are normalized exactly as a property READ normalizes
759 // them, not merely stringified: a symbol key lives on the object under its
760 // internal `@@sym:<id>` spelling, and `str_of` renders it `Symbol(k)`, which
761 // matches no key at all — so `const { [sym]: v, ...rest } = o` left the
762 // symbol-keyed property in `rest`.
763 let excl: Vec<String> = with_host(|h| h.iter_vec(&excluded))
764 .unwrap_or_default()
765 .iter()
766 .filter_map(|v| host::to_property_key(v).ok())
767 .collect();
768 // CopyDataProperties (ECMA-262 7.3.25) copies the own ENUMERABLE keys,
769 // symbol-keyed ones included. `own_enum_key_names` is what `Object.keys`
770 // uses, so an ACCESSOR is in the list — reading the property map directly
771 // missed one entirely, and `const { ...r } = { get g() {…} }` produced an
772 // object with no `g` and never ran the getter.
773 // A PROXY answers from its traps — `ownKeys`, then a
774 // `getOwnPropertyDescriptor` per key to test enumerability — which
775 // `own_enum_key_names` cannot see. Rest over one produced an empty object
776 // and ran no traps at all.
777 if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
778 let keys = match crate::proxy::own_keys(&obj) {
779 Ok(k) => k.unwrap_or_default(),
780 Err(e) => return abort(vm, e),
781 };
782 let mut pairs: Vec<(String, Value)> = Vec::new();
783 for k in keys {
784 if excl.contains(&k) {
785 continue;
786 }
787 // The enumerability test and the READ interleave per key, as node's
788 // trap log shows — testing every key first and then reading them
789 // all produced the right object through the wrong trap sequence.
790 match crate::proxy::own_enumerable(&obj, &k) {
791 Ok(false) => continue,
792 Ok(true) => {}
793 Err(e) => return abort(vm, e),
794 }
795 match get_property(&obj, &k) {
796 Ok(v) => pairs.push((k, v)),
797 Err(e) => return abort(vm, e),
798 }
799 }
800 return with_host(|h| h.new_object(pairs.into_iter().collect()));
801 }
802 let keys: Vec<String> = with_host(|h| {
803 // `own_enum_key_names` is the STRING half — the same list `Object.keys`
804 // gives, so an accessor is in it. The symbol-keyed half lives in the
805 // property map under the internal `@@sym:` spelling and has to be
806 // collected separately, since `Object.keys` deliberately omits it.
807 let mut ks = h.own_enum_key_names(&obj);
808 if let Some(JsObj::Object(m)) = h.get(&obj) {
809 for k in m.keys() {
810 if host::is_symbol_key(k) && h.prop_attrs(&obj, k).enumerable {
811 ks.push(k.clone());
812 }
813 }
814 }
815 ks
816 })
817 .into_iter()
818 .filter(|k| {
819 // An internal slot (`@@native`, `@@bytes`, …) or a private class field
820 // is not a property; a SYMBOL key shares the `@@` prefix but is one, so
821 // the two cases cannot be told apart by the prefix alone.
822 !excl.contains(k)
823 && (host::is_symbol_key(k) || !(k.starts_with("@@") || k.starts_with('#')))
824 })
825 .collect();
826 // Each value is read through `[[Get]]`, OUTSIDE the host borrow: a getter is
827 // user code and re-entering the VM under the borrow aborts the process.
828 let mut pairs: Vec<(String, Value)> = Vec::with_capacity(keys.len());
829 for k in keys {
830 match get_property(&obj, &k) {
831 Ok(v) => pairs.push((k, v)),
832 Err(e) => return abort(vm, e),
833 }
834 }
835 with_host(|h| {
836 let props: IndexMap<String, Value> = pairs.into_iter().collect();
837 h.new_object(props)
838 })
839}
840
841// ── helpers ──────────────────────────────────────────────────────────────────
842
843fn pop_n(vm: &mut VM, n: usize) -> Vec<Value> {
844 let mut v = Vec::with_capacity(n);
845 for _ in 0..n {
846 v.push(vm.pop());
847 }
848 v.reverse();
849 v
850}
851
852/// Read a compiler-internal name string (native `Value::Str` or heap `str`).
853fn sval(v: &Value) -> String {
854 if let Value::Str(s) = v {
855 return (**s).clone();
856 }
857 with_host(|h| h.as_str(v)).unwrap_or_default()
858}
859
860/// The same string, without `sval`'s deep copy. Every identifier the compiler
861/// emits is a `Value::Str` constant, so a variable read or write that went
862/// through `sval` heap-allocated and memcpy'd the NAME once per access — on the
863/// hot path of every loop. `Value::Str` is an `Arc<String>`, so cloning the
864/// handle is a refcount bump instead.
865fn sname(v: &Value) -> std::sync::Arc<String> {
866 match v {
867 Value::Str(s) => s.clone(),
868 _ => std::sync::Arc::new(sval(v)),
869 }
870}
871
872/// Raise `e` out of the running chunk. A throw abandons every `for…of` /
873/// `yield*` iterator parked on the stack beneath the op that raised it, and
874/// each is closed first (14.7.5.7 `ForIn/OfBodyEvaluation` step: on a throw
875/// completion `IteratorClose` runs, its own failure suppressed so `e` wins).
876fn abort(vm: &mut VM, e: String) -> Value {
877 close_parked_iters(vm);
878 let pos = op_pos(vm);
879 with_host(|h| {
880 h.note_raise(&e, pos, true);
881 h.error = Some(e);
882 });
883 vm.ip = vm.chunk.ops.len();
884 Value::Undef
885}
886
887/// [`abort`] for an error about identifier `name` (unbound, or in its dead
888/// zone), placed at the identifier rather than its statement — see
889/// `JsHost::name_position`.
890fn abort_at_name(vm: &mut VM, e: String, name: &str) -> Value {
891 let pos = op_pos(vm);
892 with_host(|h| {
893 let at = h.name_position(pos, name);
894 h.note_raise(&e, at, true);
895 });
896 abort(vm, e)
897}
898
899/// The source position of the op now executing (`0`: none) — see
900/// [`crate::ast::Pos`] and `lib::load_merged_from`.
901fn op_pos(vm: &VM) -> u32 {
902 vm.ip
903 .checked_sub(1)
904 .and_then(|ip| vm.chunk.lines.get(ip))
905 .copied()
906 .unwrap_or(0)
907}
908
909/// Record the op now executing as the current frame's place, before an op
910/// that may run user code: what that frame's `at …(file:line:col)` stack line
911/// shows while the call runs, and where a `new Error()` it makes was created
912/// (see `host::set_op_pos`).
913fn note_site(vm: &VM) {
914 host::set_op_pos(op_pos(vm));
915}
916
917/// [`abort`] for an error the ITERATOR PROTOCOL itself raised (`next` threw, or
918/// its result had no `done`/`value`): that iterator is already finished and is
919/// not closed — only the loops outside it are. The failing iterator is the top
920/// of the stack.
921fn abort_iterator_error(vm: &mut VM, e: String) -> Value {
922 let n = host::parked_iters(vm);
923 if n > 0 {
924 vm.pop();
925 close_n_parked_iters(vm, n - 1);
926 }
927 with_host(|h| h.error = Some(e));
928 vm.ip = vm.chunk.ops.len();
929 Value::Undef
930}
931
932/// [`abort`] when the op itself has already taken its own iterator off the
933/// stack (`ITER_CLOSE`): nothing is closed, since the count the compiler
934/// recorded includes the iterator this op just consumed.
935fn abort_without_closing(vm: &mut VM, e: String) -> Value {
936 with_host(|h| h.error = Some(e));
937 vm.ip = vm.chunk.ops.len();
938 Value::Undef
939}
940
941/// Halt the chunk if a call left an error or non-local signal pending.
942fn finish(vm: &mut VM, r: Result<Value, String>) -> Value {
943 match r {
944 Ok(v) => {
945 if with_host(|h| h.error.is_some() || h.signal.is_some()) {
946 vm.ip = vm.chunk.ops.len();
947 }
948 v
949 }
950 Err(e) => abort(vm, e),
951 }
952}
953
954// ── name handlers ─────────────────────────────────────────────────────────────
955
956/// The value a bare global identifier resolves to, or `None` if unbound.
957///
958/// Shared by `b_getlocal` (the `x` form) and the `globalThis.x` property read,
959/// which must agree: a name reachable one way and not the other is exactly the
960/// discrepancy that left `globalThis.process` undefined while `process` worked.
961pub(crate) fn global_binding(name: &str) -> Option<Value> {
962 global_binding_from(name, false)
963}
964
965/// [`global_binding`] restricted to what the GLOBAL OBJECT really holds.
966///
967/// A `globalThis.x` read falls back to the same lazy binding a bare `x` gets,
968/// which is what makes `globalThis.Math` and `globalThis.process` work — but
969/// the bare-identifier lookup walks the SCOPE CHAIN, so while any function was
970/// running its locals were readable off `globalThis`: `function f() { let zzq =
971/// 2; return typeof globalThis.zzq }` answered for a name the global object has
972/// never heard of. Only the globals map and the lazy builtins below may answer
973/// here.
974pub(crate) fn global_object_binding(name: &str) -> Option<Value> {
975 global_binding_from(name, true)
976}
977
978/// Whether `name` is a global bound LAZILY — resolved on read by
979/// [`global_binding_from`] rather than stored in any map.
980fn is_lazy_global(name: &str) -> bool {
981 matches!(
982 name,
983 "undefined"
984 | "NaN"
985 | "Infinity"
986 | "globalThis"
987 | "global"
988 | "crypto"
989 | "performance"
990 | "SubtleCrypto"
991 ) || is_namespace(name)
992 || is_known_builtin(name)
993}
994
995/// The lazily-bound globals node makes ENUMERABLE own properties of the
996/// global object, in node's order — the head of `Object.keys(globalThis)`.
997/// A name this runtime does not bind (`navigator`) is left out rather than
998/// listed with nothing behind it.
999pub(crate) fn enumerable_lazy_globals() -> impl Iterator<Item = &'static str> {
1000 ENUMERABLE_GLOBALS
1001 .iter()
1002 .copied()
1003 .filter(|n| is_lazy_global(n))
1004}
1005
1006/// Whether a name in the globals map is a real property of the global object:
1007/// not a CommonJS wrapper parameter and not a compiler temporary (`.forin0`).
1008pub(crate) fn is_script_global_name(name: &str) -> bool {
1009 !name.starts_with('.') && !CJS_WRAPPER_LOCALS.contains(&name)
1010}
1011
1012fn global_binding_from(name: &str, object_only: bool) -> Option<Value> {
1013 let bound = with_host(|h| {
1014 if object_only {
1015 h.read_global(name)
1016 } else {
1017 h.read_name(name)
1018 }
1019 });
1020 if let Some(v) = bound {
1021 return Some(v);
1022 }
1023 // Globals bound lazily: numeric sentinels + builtin namespaces.
1024 match name {
1025 "undefined" => return Some(Value::Undef),
1026 "NaN" => return Some(Value::Float(f64::NAN)),
1027 "Infinity" => return Some(Value::Float(f64::INFINITY)),
1028 // One object, not a fresh one per read: `globalThis === globalThis` is
1029 // `true` in JS, and `globalThis.x = 1` is readable back as
1030 // `globalThis.x`. Both were false while each read minted a new object.
1031 // `global` is Node's alias for the same object.
1032 "globalThis" | "global" => return Some(with_host(|h| h.global_object())),
1033 // The WHATWG `crypto` global IS `require('crypto').webcrypto`, not the
1034 // node-flavoured module: `globalThis.crypto.randomUUID` exists while
1035 // `globalThis.crypto.createHash` does not.
1036 "crypto" => return Some(with_host(|h| h.alloc(JsObj::Builtin("webcrypto".into())))),
1037 // The global `performance` IS `require('perf_hooks').performance`.
1038 "performance" => return Some(with_host(|h| h.alloc(JsObj::Builtin("performance".into())))),
1039 // The `SubtleCrypto` CLASS; the bare name `SubtleCrypto` is this
1040 // frontend's key for the `crypto.subtle` instance.
1041 // The ES module entry points lowered code calls: `import(…)` and the
1042 // entry module's `runMain`. A `%` keeps them out of reach of source.
1043 crate::esm::IMPORT_FN => {
1044 return Some(with_host(|h| {
1045 h.alloc(JsObj::Builtin("@@esm.import".into()))
1046 }))
1047 }
1048 crate::esm::MAIN_FN => {
1049 return Some(with_host(|h| h.alloc(JsObj::Builtin("@@esm.main".into()))))
1050 }
1051 "SubtleCrypto" => {
1052 return Some(with_host(|h| {
1053 h.alloc(JsObj::Builtin(crate::stdlib::SUBTLE_CRYPTO_CLASS.into()))
1054 }))
1055 }
1056 // The web-stream classes are the `webstreams.js` port's constructors.
1057 n if crate::stdlib::stream_web::is_global_class(n) => {
1058 return crate::stdlib::stream_web::constant(n);
1059 }
1060 _ => {}
1061 }
1062 if is_namespace(name) || is_known_builtin(name) {
1063 return Some(with_host(|h| h.alloc(JsObj::Builtin(name.to_string()))));
1064 }
1065 None
1066}
1067
1068fn b_getlocal(vm: &mut VM, _: u8) -> Value {
1069 let name = sname(&vm.pop());
1070 // A module-top-level dead zone is tracked by NAME rather than by a parked
1071 // marker, so that the marker is never reachable as `globalThis.<name>`. It
1072 // only applies when nothing on the scope chain SHADOWS the name — a class's
1073 // own inner binding for its name does exactly that while its static
1074 // initializers run.
1075 if with_host(|h| h.is_tdz_global(&name) && h.read_name(&name).is_none()) {
1076 return abort_at_name(vm, host::tdz_error(&name), &name);
1077 }
1078 match global_binding(&name) {
1079 // The binding EXISTS but has not reached its declaration yet.
1080 Some(v) if with_host(|h| h.is_tdz(&v)) => abort_at_name(vm, host::tdz_error(&name), &name),
1081 Some(v) => v,
1082 None => abort_at_name(vm, host::ref_error(&name), &name),
1083 }
1084}
1085
1086/// `HOIST_TDZ` — declare one `let`/`const`/`class` name as uninitialized at the
1087/// top of the scope that declares it.
1088fn b_hoist_tdz(vm: &mut VM, _: u8) -> Value {
1089 let name = sname(&vm.pop());
1090 with_host(|h| h.hoist_tdz(&name));
1091 Value::Undef
1092}
1093
1094/// The three global VALUE properties that are `{writable: false}` (19.1.1-19.1.3).
1095/// Assigning to one is a silent no-op in sloppy code and a `TypeError` in strict
1096/// code — and, either way, never rebinds the name.
1097const READONLY_GLOBALS: [&str; 3] = ["undefined", "NaN", "Infinity"];
1098
1099fn readonly_global_error(name: &str) -> String {
1100 host::type_error(&format!(
1101 "Cannot assign to read only property '{name}' of object '#<Object>'"
1102 ))
1103}
1104
1105fn b_setlocal(vm: &mut VM, _: u8) -> Value {
1106 let val = vm.pop();
1107 let name = sname(&vm.pop());
1108 // Sloppy assignment to a non-writable global is DISCARDED, not applied:
1109 // `undefined = 1` used to rebind the name and make every later `undefined`
1110 // read back as `1`.
1111 if READONLY_GLOBALS.contains(&name.as_str()) && !with_host(|h| h.has_name(&name)) {
1112 return val;
1113 }
1114 // Assigning to a binding still in its temporal dead zone throws too —
1115 // `{ x = 1; let x }` is a ReferenceError, not an initialization.
1116 if with_host(|h| match h.read_name(&name) {
1117 Some(v) => h.is_tdz(&v),
1118 None => h.is_tdz_global(&name),
1119 }) {
1120 return abort(vm, host::tdz_error(&name));
1121 }
1122 // An assignment to a `const` binding throws (8.5.2 SetMutableBinding on an
1123 // immutable binding). This used to succeed silently.
1124 if !with_host(|h| h.set_name(&name, val.clone())) {
1125 return abort(vm, host::type_error("Assignment to constant variable."));
1126 }
1127 val
1128}
1129
1130/// Strict-mode `x = v` (6.2.5.6 `PutValue` with an unresolvable reference):
1131/// where sloppy code silently creates a global, strict code throws
1132/// `ReferenceError: x is not defined`.
1133///
1134/// A separate opcode rather than a runtime flag: strictness is a static property
1135/// of the code, so the compiler already knows which of the two an assignment is
1136/// and sloppy code — everything in a CommonJS module without the directive —
1137/// keeps the exact instruction it had.
1138fn b_setlocal_strict(vm: &mut VM, _: u8) -> Value {
1139 let val = vm.pop();
1140 let name = sname(&vm.pop());
1141 if !binding_exists(&name) {
1142 return abort_at_name(vm, host::ref_error(&name), &name);
1143 }
1144 if READONLY_GLOBALS.contains(&name.as_str()) && !with_host(|h| h.has_name(&name)) {
1145 return abort(vm, readonly_global_error(&name));
1146 }
1147 if !with_host(|h| h.set_name(&name, val.clone())) {
1148 return abort(vm, host::type_error("Assignment to constant variable."));
1149 }
1150 val
1151}
1152
1153/// Whether `name` resolves to anything — a scope binding, a global, or a lazily
1154/// materialised builtin namespace. `global_binding` answers the same question
1155/// but ALLOCATES the namespace object to do it, which an assignment then throws
1156/// away.
1157fn binding_exists(name: &str) -> bool {
1158 if with_host(|h| h.has_name(name)) {
1159 return true;
1160 }
1161 matches!(
1162 name,
1163 "undefined" | "NaN" | "Infinity" | "globalThis" | "global"
1164 ) || is_namespace(name)
1165 || is_known_builtin(name)
1166}
1167
1168fn b_declare(vm: &mut VM, _: u8) -> Value {
1169 let val = vm.pop();
1170 let name = sname(&vm.pop());
1171 with_host(|h| h.declare_name(&name, val.clone()));
1172 val
1173}
1174
1175/// `const x = …`: like `DECLARE`, but the binding is immutable, so a later
1176/// assignment to the name throws instead of overwriting it.
1177fn b_declare_const(vm: &mut VM, _: u8) -> Value {
1178 let val = vm.pop();
1179 let name = sname(&vm.pop());
1180 with_host(|h| h.declare_const_name(&name, val.clone()));
1181 val
1182}
1183
1184/// `var x = …` / a hoisted `function f(){}`: bind at function scope, skipping any
1185/// open block scopes, so the name outlives the block it was written in.
1186/// `var` hoisting: create the binding as `undefined` unless it already exists.
1187fn b_hoist_var(vm: &mut VM, _: u8) -> Value {
1188 let name = sname(&vm.pop());
1189 with_host(|h| h.hoist_var_name(&name));
1190 Value::Undef
1191}
1192
1193// ── `with` ─────────────────────────────────────────────────────────────────
1194
1195/// The object of the innermost enclosing `with` scope that binds `name`, if any
1196/// (9.1.1.2.1 HasBinding): the object has the property, and its
1197/// `@@unscopables` does not mask it. A scope that binds `name` ordinarily
1198/// shadows every `with` object beyond it.
1199fn with_binding_object(name: &str) -> Result<Option<Value>, String> {
1200 for obj in with_host(|h| h.with_objects_before_binding(name)) {
1201 if !has_property(&obj, name)? {
1202 continue;
1203 }
1204 let unscopables = get_property(&obj, "@@unscopables")?;
1205 let masked = if matches!(unscopables, Value::Obj(_))
1206 && !with_host(|h| host::is_primitive(h, &unscopables))
1207 {
1208 let flag = get_property(&unscopables, name)?;
1209 with_host(|h| h.truthy(&flag))
1210 } else {
1211 false
1212 };
1213 if !masked {
1214 return Ok(Some(obj));
1215 }
1216 }
1217 Ok(None)
1218}
1219
1220/// `with (obj) body`: `ToObject(obj)` (nullish throws), then a scope that
1221/// answers names from it.
1222fn b_with_push(vm: &mut VM, _: u8) -> Value {
1223 let v = vm.pop();
1224 if with_host(|h| h.is_nullish(&v)) {
1225 return abort(
1226 vm,
1227 host::type_error("Cannot convert undefined or null to object"),
1228 );
1229 }
1230 let obj = to_object(&v);
1231 with_host(|h| h.push_with_scope(obj));
1232 Value::Undef
1233}
1234
1235fn b_with_get(vm: &mut VM, _: u8) -> Value {
1236 let name_val = vm.pop();
1237 let name = sname(&name_val);
1238 match with_binding_object(&name) {
1239 Err(e) => abort(vm, e),
1240 Ok(Some(obj)) => {
1241 let r = get_property(&obj, &name);
1242 finish(vm, r)
1243 }
1244 Ok(None) => {
1245 vm.push(name_val);
1246 b_getlocal(vm, 0)
1247 }
1248 }
1249}
1250
1251fn with_set(vm: &mut VM, strict: bool) -> Value {
1252 let val = vm.pop();
1253 let name_val = vm.pop();
1254 let name = sname(&name_val);
1255 match with_binding_object(&name) {
1256 Err(e) => abort(vm, e),
1257 Ok(Some(obj)) => match set_property(&obj, &name, val.clone()) {
1258 Ok(()) => val,
1259 Err(e) => abort(vm, e),
1260 },
1261 Ok(None) => {
1262 vm.push(name_val);
1263 vm.push(val);
1264 if strict {
1265 b_setlocal_strict(vm, 0)
1266 } else {
1267 b_setlocal(vm, 0)
1268 }
1269 }
1270 }
1271}
1272
1273fn b_with_set(vm: &mut VM, _: u8) -> Value {
1274 with_set(vm, false)
1275}
1276
1277fn b_with_set_strict(vm: &mut VM, _: u8) -> Value {
1278 with_set(vm, true)
1279}
1280
1281fn b_with_typeof(vm: &mut VM, _: u8) -> Value {
1282 let name_val = vm.pop();
1283 let name = sname(&name_val);
1284 match with_binding_object(&name) {
1285 Err(e) => abort(vm, e),
1286 Ok(Some(obj)) => match get_property(&obj, &name) {
1287 Ok(v) => with_host(|h| {
1288 let t = h.type_of(&v);
1289 h.new_str(t)
1290 }),
1291 Err(e) => abort(vm, e),
1292 },
1293 Ok(None) => {
1294 vm.push(name_val);
1295 b_typeof_name(vm, 0)
1296 }
1297 }
1298}
1299
1300/// The callee of an identifier call inside `with`: when the object supplies the
1301/// name it is also the `this` of the call (13.3.6.1 step 1.b — a reference whose
1302/// base is an Object Environment Record with `withEnvironment` set).
1303fn b_with_fn(vm: &mut VM, _: u8) -> Value {
1304 let name_val = vm.pop();
1305 let name = sname(&name_val);
1306 match with_binding_object(&name) {
1307 Err(e) => abort(vm, e),
1308 Ok(Some(obj)) => match get_property(&obj, &name) {
1309 Ok(f) => {
1310 vm.push(f);
1311 obj
1312 }
1313 Err(e) => abort(vm, e),
1314 },
1315 Ok(None) => {
1316 vm.push(name_val);
1317 let f = b_getlocal(vm, 0);
1318 vm.push(f);
1319 Value::Undef
1320 }
1321 }
1322}
1323
1324fn b_call_this(vm: &mut VM, argc: u8) -> Value {
1325 note_site(vm);
1326 let mut args = pop_n(vm, argc as usize);
1327 let callable = args.remove(0);
1328 let this = args.remove(0);
1329 let this = (!matches!(this, Value::Undef)).then_some(this);
1330 let r = host::invoke(&callable, args, this).map_err(|e| {
1331 let shown = with_host(|h| h.str_of(&callable));
1332 host::name_call_site(vm, &shown, e)
1333 });
1334 finish(vm, r)
1335}
1336
1337fn b_apply_this(vm: &mut VM, _: u8) -> Value {
1338 note_site(vm);
1339 let args_arr = vm.pop();
1340 let this = vm.pop();
1341 let callable = vm.pop();
1342 let this = (!matches!(this, Value::Undef)).then_some(this);
1343 let args = host::iter_all(&args_arr).unwrap_or_default();
1344 let r = host::invoke(&callable, args, this);
1345 finish(vm, r)
1346}
1347
1348/// `MAP_ARGS`: alias the running sloppy function's parameters to its
1349/// `arguments` object. The name list is the compiler's, comma-joined.
1350fn b_map_args(vm: &mut VM, _: u8) -> Value {
1351 let names = sname(&vm.pop());
1352 let names: Vec<String> = names.split(',').map(str::to_string).collect();
1353 with_host(|h| h.map_arguments(&names));
1354 Value::Undef
1355}
1356
1357fn b_declare_var(vm: &mut VM, _: u8) -> Value {
1358 let val = vm.pop();
1359 let name = sname(&vm.pop());
1360 with_host(|h| h.declare_var_name(&name, val.clone()));
1361 val
1362}
1363
1364fn b_push_scope(_: &mut VM, _: u8) -> Value {
1365 with_host(|h| h.push_scope());
1366 Value::Undef
1367}
1368
1369fn b_pop_scope(_: &mut VM, _: u8) -> Value {
1370 with_host(|h| h.pop_scope());
1371 Value::Undef
1372}
1373
1374fn b_copy_scope(_: &mut VM, _: u8) -> Value {
1375 with_host(|h| h.copy_scope());
1376 Value::Undef
1377}
1378
1379fn b_delname(vm: &mut VM, _: u8) -> Value {
1380 let name = sval(&vm.pop());
1381 with_host(|h| h.del_name(&name));
1382 Value::Bool(true)
1383}
1384
1385fn b_this(vm: &mut VM, _: u8) -> Value {
1386 if with_host(|h| h.this_state()) == host::ThisState::Pending {
1387 return abort(vm, host::this_before_super_error());
1388 }
1389 with_host(|h| h.current_this().unwrap_or(Value::Undef))
1390}
1391
1392fn b_load_null(_vm: &mut VM, _: u8) -> Value {
1393 with_host(|h| h.null())
1394}
1395
1396// ── attribute / item handlers ─────────────────────────────────────────────────
1397
1398fn b_getattr(vm: &mut VM, _: u8) -> Value {
1399 note_site(vm);
1400 let name = sval(&vm.pop());
1401 let recv = vm.pop();
1402 match get_property(&recv, &name) {
1403 Ok(v) => v,
1404 Err(e) => abort(vm, e),
1405 }
1406}
1407
1408/// Read `recv.name` (also the computed-key path for string keys). Walks own
1409/// properties, accessors, and the prototype chain (class methods / getters).
1410/// Read one small piece out of `recv`'s heap cell under a short borrow.
1411///
1412/// The closure must not call back into the host (`with_host` is a `RefCell`
1413/// borrow and re-entering panics) — which is exactly why it hands back only the
1414/// value needed: the caller re-enters freely afterwards. This replaces the old
1415/// `h.get(recv).cloned()` habit, which deep-copied a whole `Vec`/`IndexMap`/
1416/// `String` just to look at it.
1417fn peek<R>(recv: &Value, f: impl FnOnce(&JsObj) -> Option<R>) -> Option<R> {
1418 with_host(|h| h.get(recv).and_then(f))
1419}
1420
1421/// The nearest `[[Prototype]]` link of `recv` that is a Proxy, when the chain
1422/// reaches it without a closer link already owning `name`.
1423///
1424/// A proxy prototype answers only from the position it occupies in the chain: a
1425/// nearer prototype that owns the key (as a data property or an accessor) still
1426/// wins, exactly as `OrdinaryGet` walks one link at a time.
1427pub(crate) fn proxy_proto_link(recv: &Value, name: &str) -> Option<Value> {
1428 with_host(|h| {
1429 let mut cur = h.proto_of(recv);
1430 for _ in 0..100 {
1431 let p = cur?;
1432 match h.get(&p) {
1433 Some(JsObj::Proxy { .. }) => return Some(p),
1434 Some(JsObj::Object(props)) if props.contains_key(name) => return None,
1435 _ => {}
1436 }
1437 if h.own_accessor(&p, name).is_some() {
1438 return None;
1439 }
1440 cur = h.proto_of(&p);
1441 }
1442 None
1443 })
1444}
1445
1446/// The CommonJS wrapper's parameters. They are function locals in Node, not
1447/// global-object properties, so `globalThis.require` is `undefined` and
1448/// `Object.getOwnPropertyDescriptor(globalThis, 'module')` reports no property —
1449/// even though the bare `require` and `module` both work.
1450const CJS_WRAPPER_LOCALS: &[&str] = &[
1451 "require",
1452 "module",
1453 "exports",
1454 "__filename",
1455 "__dirname",
1456 "__cjs_require",
1457 "__cjs_resolve",
1458];
1459
1460/// The globals node exposes as ENUMERABLE own properties of the global object —
1461/// the timer family and the WHATWG additions, measured on v26.8.1. Everything
1462/// else (`Math`, `parseInt`, the constructors) is non-enumerable.
1463const ENUMERABLE_GLOBALS: &[&str] = &[
1464 "global",
1465 "clearImmediate",
1466 "setImmediate",
1467 "clearInterval",
1468 "clearTimeout",
1469 "setInterval",
1470 "setTimeout",
1471 "queueMicrotask",
1472 "structuredClone",
1473 "atob",
1474 "btoa",
1475 "performance",
1476 "fetch",
1477 "crypto",
1478 "navigator",
1479 "sessionStorage",
1480];
1481
1482pub fn get_property(recv: &Value, name: &str) -> Result<Value, String> {
1483 // A `#`-prefixed key is a PRIVATE name. `[[PrivateGet]]` (7.3.31) throws
1484 // when the receiver carries no such private element — it does NOT read back
1485 // as `undefined`, which is what `C.prototype.method.call({})` used to do.
1486 if name.starts_with('#') && !with_host(|h| h.is_nullish(recv) || h.has_private(recv, name)) {
1487 return Err(private_brand_message(name, false));
1488 }
1489 get_property_recv(recv, name, recv)
1490}
1491
1492/// The `TypeError` a failed private brand check raises. Node words it two ways:
1493/// a private METHOD or accessor names the class the receiver should have been an
1494/// instance of, while a private FIELD names the member.
1495pub fn private_brand_message(name: &str, writing: bool) -> String {
1496 if with_host(|h| h.is_private_method(name)) {
1497 if let Some(class) = with_host(|h| h.current_home_class_name()) {
1498 return host::type_error(&format!("Receiver must be an instance of class {class}"));
1499 }
1500 }
1501 let verb = if writing { "write" } else { "read" };
1502 let prep = if writing { "to" } else { "from" };
1503 host::type_error(&format!(
1504 "Cannot {verb} private member {name} {prep} an object whose class did not declare it"
1505 ))
1506}
1507
1508/// `[[Get]](name, receiver)` — 10.1.8. `receiver` is the object the read STARTED
1509/// from and is what a getter sees as `this`; it differs from `recv` only when the
1510/// read was forwarded down a prototype chain, which is why `Reflect.get(t, k, r)`
1511/// and a Proxy `get` trap's third argument both need it. Every ordinary read
1512/// passes `recv` itself.
1513/// Re-format an error's `.stack` header on its first read, the way V8 does.
1514///
1515/// The constructor could only stamp the name it was called with, so a subclass
1516/// that sets `this.name` after `super()` — or any `e.name = …` / `e.message = …`
1517/// before the first read — left a stale header. Node re-reads both properties at
1518/// format time, including one inherited from the prototype (`E.prototype.name`).
1519///
1520/// It is formatted ONCE: node caches the string, so renaming AFTER a read does
1521/// not change what later reads return. `@@stackRaw` is the not-yet-formatted
1522/// marker and is dropped here; an explicit `e.stack = …` drops it too, so an
1523/// assignment is never clobbered by a later read.
1524/// The key of node's DEFAULT `Error.prepareStackTrace`. Recognised by name so
1525/// the ordinary stack path can skip the hook round-trip when nothing custom is
1526/// installed.
1527pub const DEFAULT_PREPARE: &str = "ErrorPrepareStackTrace";
1528
1529pub fn materialize_stack(recv: &Value) {
1530 let Some(frames) = with_host(|h| match h.get(recv) {
1531 Some(JsObj::Object(p)) => p.get("@@stackRaw").cloned(),
1532 _ => None,
1533 }) else {
1534 return;
1535 };
1536 // A custom `Error.prepareStackTrace` replaces the string entirely (V8's
1537 // stack-introspection hook, which every source-map library installs). It was
1538 // honoured only by `Error.captureStackTrace`, so an ordinary `err.stack`
1539 // read bypassed it and handed back the default text.
1540 let prep = with_host(|h| h.builtin_static("Error", "prepareStackTrace"));
1541 if let Some(f) = prep.filter(|f| {
1542 // The default hook produces exactly what the fast path below produces,
1543 // so it is skipped rather than called.
1544 !matches!(
1545 with_host(|h| h.get(f).cloned()),
1546 Some(JsObj::Builtin(ref n)) if n == DEFAULT_PREPARE
1547 ) && matches!(
1548 with_host(|h| h.get(f).cloned()),
1549 Some(JsObj::Func(_)) | Some(JsObj::Builtin(_)) | Some(JsObj::BoundFunc { .. })
1550 )
1551 }) {
1552 // Clear the raw marker FIRST: the hook may read `.stack` itself, and a
1553 // second materialization would re-enter this path forever.
1554 with_host(|h| {
1555 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
1556 p.shift_remove("@@stackRaw");
1557 }
1558 });
1559 let limit = with_host(|h| h.stack_trace_limit());
1560 if let Ok(sites) = crate::module::callsite_stack(limit) {
1561 if let Ok(out) = host::invoke(&f, vec![recv.clone(), sites], None) {
1562 with_host(|h| {
1563 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
1564 p.insert("stack".into(), out);
1565 }
1566 });
1567 return;
1568 }
1569 }
1570 }
1571 with_host(|h| {
1572 let frames = h.str_of(&frames);
1573 let name = host::lookup_chain(h, recv, "name")
1574 .map(|v| h.str_of(&v))
1575 .unwrap_or_else(|| "Error".to_string());
1576 let message = host::lookup_chain(h, recv, "message")
1577 .map(|v| h.str_of(&v))
1578 .unwrap_or_default();
1579 let header = if message.is_empty() {
1580 name
1581 } else {
1582 format!("{name}: {message}")
1583 };
1584 let sv = h.new_str(format!("{header}{frames}"));
1585 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
1586 p.insert("stack".into(), sv);
1587 p.shift_remove("@@stackRaw");
1588 }
1589 });
1590}
1591
1592pub fn get_property_recv(recv: &Value, name: &str, receiver: &Value) -> Result<Value, String> {
1593 // `[[Get]]` on a Proxy: the handler's `get` trap, or a forward to the
1594 // target. Checked before anything else so no ordinary-object shortcut can
1595 // read past the handler.
1596 if let Some(v) = crate::proxy::get(recv, name, receiver)? {
1597 return Ok(v);
1598 }
1599 if with_host(|h| h.is_nullish(recv)) {
1600 return Err(host::type_error(&format!(
1601 "Cannot read properties of {} (reading '{name}')",
1602 with_host(|h| h.str_of(recv))
1603 )));
1604 }
1605 if name == "stack" {
1606 materialize_stack(recv);
1607 }
1608 // A `DOMException`'s `name`/`message`/`code` are prototype accessors over
1609 // internal slots, so they resolve here rather than out of a property map.
1610 if let Some(v) = dom_exception_slot(recv, name) {
1611 return Ok(v);
1612 }
1613 // A read off `globalThis` for a name the object does not own falls back to
1614 // the same lazy global binding the bare identifier gets. Without it the
1615 // global object was an empty bag: `globalThis.process`, `.console`, `.Math`
1616 // and `.JSON` were all `undefined`, so `process === globalThis.process` was
1617 // `false` and any `globalThis.X` feature probe reported the feature missing.
1618 if with_host(|h| h.is_global_object(recv)) {
1619 let own = with_host(|h| match h.get(recv) {
1620 Some(JsObj::Object(p)) => p.contains_key(name),
1621 _ => false,
1622 });
1623 // The CommonJS wrapper's parameters are function locals in Node, not
1624 // global-object properties: `typeof globalThis.require` is `undefined`
1625 // there even though the bare `require` works.
1626 if !own && !CJS_WRAPPER_LOCALS.contains(&name) {
1627 if let Some(v) = global_object_binding(name) {
1628 return Ok(v);
1629 }
1630 }
1631 }
1632 // Accessor (own or inherited getter) takes precedence over the chain walk.
1633 // The getter runs with the RECEIVER as `this`, not the object that owns it.
1634 if let Some((getter, _)) = with_host(|h| host::lookup_accessor(h, recv, name)) {
1635 return match getter {
1636 Some(g) => host::invoke(&g, Vec::new(), Some(receiver.clone())),
1637 None => Ok(Value::Undef), // set-only property reads as undefined
1638 };
1639 }
1640 // `Symbol.toStringTag` read as an ordinary property. The builtins that carry
1641 // one expose it to a plain read, not just to `Object.prototype.toString` —
1642 // `new Uint8Array(1)[Symbol.toStringTag]` is `'Uint8Array'`, and a `Buffer`
1643 // inherits `'Uint8Array'` from the typed-array prototype it now really has.
1644 // Anything the receiver's own chain provides wins (a class may define its
1645 // own getter), so this is only the fallback.
1646 if name == "@@toStringTag" {
1647 // A data tag on the chain is the answer itself: an exotic receiver's
1648 // own read path (a built-in iterator's) does not walk to it.
1649 if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
1650 return Ok(v);
1651 }
1652 if let Some(tag) = with_host(|h| well_known_tag(h, recv)) {
1653 return Ok(with_host(|h| h.new_str(tag)));
1654 }
1655 }
1656 // `constructor`: a user class/function sets it on the prototype chain, and
1657 // that wins; otherwise every builtin instance reports its native
1658 // constructor (so `[].constructor`, `new Map().constructor`,
1659 // `Promise.resolve(1).constructor`, `(5).constructor` match Node).
1660 if name == "constructor" {
1661 if let Some(v) = with_host(|h| {
1662 match h.get(recv) {
1663 Some(JsObj::Object(p)) => p.get("constructor").cloned(),
1664 _ => None,
1665 }
1666 .or_else(|| host::lookup_chain(h, recv, "constructor"))
1667 }) {
1668 return Ok(v);
1669 }
1670 // An intrinsic prototype the receiver's CHAIN reaches owns a
1671 // `constructor` too, and it wins over the receiver's own kind:
1672 // `Object.create(Map.prototype).constructor` is `Map`, not `Object`.
1673 // Deciding from the kind alone also mis-named the receiver in every
1674 // message that renders one — the brand-check errors say `#<Map>`.
1675 if let Some(c) = chain_intrinsic_ctors(recv)
1676 .into_iter()
1677 .find(|c| is_builtin_ctor(c))
1678 {
1679 return Ok(with_host(|h| h.alloc(JsObj::Builtin(c.to_string()))));
1680 }
1681 if let Some(cn) = with_host(|h| default_ctor_name(h, recv)) {
1682 return Ok(with_host(|h| h.alloc(JsObj::Builtin(cn.to_string()))));
1683 }
1684 }
1685 // `__proto__` (Annex B B.2.2.1) is an accessor on `Object.prototype`, so it
1686 // answers for EVERY object that inherits from it, not only plain ones —
1687 // `[].__proto__` is `Array.prototype`. Only the plain-object arm handled it,
1688 // so an array, function or builtin instance read `undefined`. An object with
1689 // a null prototype inherits no such accessor and reads `undefined`, which is
1690 // why this is skipped there rather than answering `null`.
1691 if name == "__proto__"
1692 && !with_host(|h| h.has_null_proto(recv))
1693 && peek(recv, |o| match o {
1694 JsObj::Object(p) => Some(p.contains_key("__proto__")),
1695 _ => Some(false),
1696 }) != Some(true)
1697 {
1698 return Ok(prototype_of(recv));
1699 }
1700 // An ACCESSOR member read off the intrinsic prototype ITSELF is not a
1701 // method: it RUNS the getter with that prototype as `this`, and all but two
1702 // of `RegExp.prototype`'s then fail their brand check and throw. Every one
1703 // answered `undefined`, so both the value and the failure were invisible.
1704 // Both representations of a prototype reach here — the namespace handles
1705 // and the real objects (`Symbol.prototype`, `String.prototype`).
1706 if let Some(ctor) = intrinsic_proto_of(recv) {
1707 if is_proto_accessor(&ctor, name) {
1708 return proto_getter_call(&ctor, name, recv);
1709 }
1710 }
1711 let kind = with_host(|h| h.kind_of(recv));
1712 // A subclass of a builtin exotic (`class C extends Map { get(k) {…} }`)
1713 // owns methods on `C.prototype`, which sits BEFORE the builtin prototype on
1714 // the chain. The kind arms below answer native method names first, so
1715 // `c.get` read `Map.prototype.get` while `c.get(k)` called the override —
1716 // the read and the call disagreeing. A prototype-method THUNK does not
1717 // count: the shared `Object.prototype` carries them, and its `toString`
1718 // must not shadow `Array.prototype.toString`.
1719 if matches!(
1720 kind,
1721 Some(ObjKind::Map | ObjKind::Set | ObjKind::Promise | ObjKind::Array)
1722 ) && name != "length"
1723 && name.parse::<usize>().is_err()
1724 && with_host(|h| h.fn_prop(recv, name)).is_none()
1725 {
1726 if let Some(f) = with_host(|h| host::lookup_chain(h, recv, name)) {
1727 let thunk = with_host(
1728 |h| matches!(h.get(&f), Some(JsObj::Builtin(n)) if n.starts_with("@proto")),
1729 );
1730 if !thunk {
1731 return Ok(f);
1732 }
1733 }
1734 }
1735 #[allow(unused_mut)]
1736 let mut out = match kind {
1737 Some(ObjKind::Object) => {
1738 let numeric = !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit());
1739 // A view over a DETACHED buffer reports zero extent. Its own
1740 // `length`/`byteLength`/`byteOffset` properties still hold the old
1741 // numbers — the buffer does not know its views, so it cannot rewrite
1742 // them — and reading them straight back made a detached view still
1743 // look eight bytes long.
1744 if matches!(name, "length" | "byteLength" | "byteOffset")
1745 && crate::stdlib::typedarray::view_detached(recv)
1746 {
1747 match crate::stdlib::native_tag(recv).as_deref() {
1748 Some("TypedArray" | "Buffer") => return Ok(Value::Float(0.0)),
1749 // A DataView THROWS where a typed array answers zero — its
1750 // extent accessors are brand-checked and node reports the
1751 // getter by name.
1752 Some("DataView") => {
1753 return Err(crate::stdlib::typedarray::detached_error(
1754 "get DataView.prototype",
1755 name,
1756 false,
1757 ))
1758 }
1759 _ => {}
1760 }
1761 }
1762 // Typed-array element read (`ta[i]`): elements live in a hidden
1763 // `@@elems`, not as own numeric props, so intercept integer keys.
1764 if numeric && crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray") {
1765 if let Some(v) = crate::stdlib::typedarray::elem_get(recv, name) {
1766 return Ok(v);
1767 }
1768 }
1769 // `buf[i]`: a Buffer's bytes live in a hidden `@@bytes` array, not as
1770 // own numeric props, so integer keys read through to it.
1771 if numeric
1772 && peek(recv, |o| match o {
1773 JsObj::Object(p) => Some(p.contains_key("@@bytes")),
1774 _ => None,
1775 })
1776 .unwrap_or(false)
1777 {
1778 return Ok(crate::stdlib::buffer::byte_get(recv, name));
1779 }
1780 if let Some(v) = peek(recv, |o| match o {
1781 JsObj::Object(p) => p.get(name).cloned(),
1782 _ => None,
1783 }) {
1784 v
1785 } else if let Some(link) = proxy_proto_link(recv, name) {
1786 // A Proxy sitting in the prototype chain. `OrdinaryGet` (10.1.8.1
1787 // step 4) forwards to the parent's `[[Get]]` with the ORIGINAL
1788 // receiver, so the trap sees the child as `receiver` and `this`
1789 // inside a trap-served getter resolves to the child, not the
1790 // proxy. `lookup_chain` cannot do this: it reads property maps,
1791 // and a proxy has none.
1792 return Ok(crate::proxy::get(&link, name, recv)?.expect("link is a proxy"));
1793 } else if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
1794 // A method / data property inherited from the prototype chain.
1795 v
1796 } else if crate::stdlib::native_tag(recv)
1797 .map(|tag| crate::stdlib::instance_has_method(&tag, name))
1798 .unwrap_or(false)
1799 {
1800 // A native instance method read as a property (`server.listen`) →
1801 // a bound method, dispatched via `instance_call` when invoked.
1802 bound_method(recv, name)
1803 } else if is_object_method(name) && !with_host(|h| h.has_null_proto(recv)) {
1804 // `Object.create(null)` inherits nothing, so `toString`/`valueOf`
1805 // read as `undefined` there — which is also what makes
1806 // `Object.create(null) + 1` the spec `TypeError` instead of a
1807 // silent `"[object Object]1"`.
1808 bound_method(recv, name)
1809 } else {
1810 Value::Undef
1811 }
1812 }
1813 Some(ObjKind::Class) | Some(ObjKind::Func) | Some(ObjKind::BoundFunc) => {
1814 function_property(recv, name)
1815 }
1816 // A method READ off an instance (`[].slice`, `new Map().get`) is a bound
1817 // thunk here. It is a function value, so it answers the function
1818 // properties: `[].slice.name` was `undefined` where node reports
1819 // `slice`, and `String([].slice)` fell through to
1820 // `Object.prototype.toString`.
1821 Some(ObjKind::BoundMethod) => bound_method_property(recv, name),
1822 Some(ObjKind::Symbol) => match name {
1823 "description" => {
1824 match peek(recv, |o| match o {
1825 JsObj::Symbol { desc, .. } => desc.clone(),
1826 _ => None,
1827 }) {
1828 Some(d) => with_host(|h| h.new_str(d)),
1829 None => Value::Undef,
1830 }
1831 }
1832 "toString" => bound_method(recv, name),
1833 // Anything else a symbol answers, it inherits from
1834 // `Symbol.prototype`. The arm used to stop at `undefined`, so
1835 // `Symbol('x')[Symbol.toPrimitive]` and `Symbol('x').valueOf` read
1836 // as absent even though the prototype defines both — a symbol is an
1837 // ordinary object for the purpose of a property LOOKUP, only its
1838 // methods are branded.
1839 _ => with_host(|h| {
1840 h.ensure_wrapper_protos();
1841 h.native_proto("Symbol")
1842 })
1843 .and_then(|p| with_host(|h| host::lookup_chain(h, &p, name)))
1844 .unwrap_or(Value::Undef),
1845 },
1846 Some(ObjKind::BigInt) => {
1847 if matches!(
1848 name,
1849 "toString" | "valueOf" | "toLocaleString" | "constructor"
1850 ) {
1851 bound_method(recv, name)
1852 } else {
1853 Value::Undef
1854 }
1855 }
1856 Some(ObjKind::RegExp) => {
1857 // A RegExp holds no collection, so cloning the compiled pattern here
1858 // does not scale with any input size; `regexp_property` re-enters the
1859 // host to allocate `source`/`flags`, so it cannot run under a borrow.
1860 let r = peek(recv, |o| match o {
1861 JsObj::RegExp(r) => Some(r.clone()),
1862 _ => None,
1863 });
1864 match r {
1865 Some(r) => crate::regexp::regexp_property(&r, name).unwrap_or_else(|| {
1866 // An OWN property beats the prototype method of the same
1867 // name, which is ordinary resolution order. It mattered once
1868 // the symbol-keyed methods existed: `re[Symbol.match] =
1869 // false` disowns the regexp label (7.2.8), and the method
1870 // was shadowing the assignment so the value never took.
1871 if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
1872 return v;
1873 }
1874 if crate::regexp::is_regexp_method(name) {
1875 bound_method(recv, name)
1876 } else {
1877 Value::Undef
1878 }
1879 }),
1880 None => Value::Undef,
1881 }
1882 }
1883 // A WeakMap/WeakSet has NO `size` (its contents are not observable), so
1884 // the read must be `undefined` rather than a live count.
1885 Some(ObjKind::Map) => {
1886 let (len, weak) = peek(recv, |o| match o {
1887 JsObj::Map { entries, weak } => Some((entries.len(), *weak)),
1888 _ => None,
1889 })
1890 .unwrap_or((0, false));
1891 match name {
1892 "size" if !weak => Value::Float(len as f64),
1893 "@@iterator" => bound_method(recv, name),
1894 _ if is_map_method(name) => bound_method(recv, name),
1895 _ => with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef),
1896 }
1897 }
1898 Some(ObjKind::Set) => {
1899 let (len, weak) = peek(recv, |o| match o {
1900 JsObj::Set { entries, weak } => Some((entries.len(), *weak)),
1901 _ => None,
1902 })
1903 .unwrap_or((0, false));
1904 match name {
1905 "size" if !weak => Value::Float(len as f64),
1906 "@@iterator" => bound_method(recv, name),
1907 _ if is_set_method(name) => bound_method(recv, name),
1908 _ => with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef),
1909 }
1910 }
1911 Some(ObjKind::Generator) => {
1912 // A generator IS its own iterator, so it answers for the matching
1913 // symbol — `@@asyncIterator` for an async one, `@@iterator` for a
1914 // sync one. Neither was advertised, so `ag()[Symbol.asyncIterator]`
1915 // was `undefined` even though `for await` over it worked through a
1916 // different path.
1917 let want = if with_host(|h| h.is_async_gen_val(recv)) {
1918 "@@asyncIterator"
1919 } else {
1920 "@@iterator"
1921 };
1922 // `next`/`return`/`throw` and `[Symbol.asyncIterator]` are the
1923 // intrinsic prototypes' own functions, so they and anything else
1924 // are inherited: from the function's `prototype`, then
1925 // `%GeneratorPrototype%` and `Iterator.prototype` (or
1926 // `%AsyncGeneratorPrototype%` and `%AsyncIteratorPrototype%`).
1927 // The sync `[Symbol.iterator]` and the iterator helpers still
1928 // dispatch on the generator itself.
1929 let inherited = name == "@@asyncIterator" || is_generator_method(name);
1930 if !inherited && (name == want || crate::stdlib::iterator::is_helper(name)) {
1931 bound_method(recv, name)
1932 } else {
1933 match with_host(|h| h.fn_prop(recv, name).ok_or_else(|| h.proto_of(recv))) {
1934 Ok(v) => v,
1935 Err(Some(proto)) => get_property_recv(&proto, name, receiver)?,
1936 Err(None) if name == want || inherited => bound_method(recv, name),
1937 Err(None) => Value::Undef,
1938 }
1939 }
1940 }
1941 Some(ObjKind::Promise) => {
1942 if matches!(name, "then" | "catch" | "finally") {
1943 bound_method(recv, name)
1944 } else {
1945 with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef)
1946 }
1947 }
1948 Some(ObjKind::Iter) => {
1949 if matches!(name, "next" | "return" | "@@iterator")
1950 || crate::stdlib::iterator::is_helper(name)
1951 {
1952 bound_method(recv, name)
1953 } else {
1954 with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef)
1955 }
1956 }
1957 Some(ObjKind::Array) => {
1958 if name == "length" {
1959 let n = peek(recv, |o| match o {
1960 JsObj::Array(items) => Some(items.len()),
1961 _ => None,
1962 })
1963 .unwrap_or(0);
1964 Value::Float(n as f64)
1965 } else if let Ok(i) = name.parse::<usize>() {
1966 peek(recv, |o| match o {
1967 JsObj::Array(items) => items.get(i).cloned(),
1968 _ => None,
1969 })
1970 // An index PAST an `arguments` object's length is an ordinary
1971 // own property in the side table, since adding one must not
1972 // move `length`. The array read alone could not see it, so the
1973 // write was invisible to every later read.
1974 .or_else(|| with_host(|h| h.fn_prop(recv, name)))
1975 .unwrap_or(Value::Undef)
1976 } else if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
1977 // Extra own props attached to an array (e.g. `RegExp.exec` result's
1978 // `.index`/`.input`/`.groups`). An OWN property is found before
1979 // the prototype's (10.1.8.1 OrdinaryGet), so `a.join = f` makes
1980 // `a.join` be `f` rather than the inherited method.
1981 v
1982 } else if name == "@@iterator"
1983 || is_object_method(name)
1984 // An `arguments` object is array-BACKED here but is not an
1985 // Array: node's exposes no `Array.prototype` method, which is
1986 // exactly why the idiom is `Array.prototype.slice.call(args)`.
1987 // Exposing them made `arguments.map` a function.
1988 || (is_array_method(name) && !is_arguments(recv))
1989 {
1990 bound_method(recv, name)
1991 } else {
1992 Value::Undef
1993 }
1994 }
1995 Some(ObjKind::Str) => {
1996 // `.length` and `s[i]` count UTF-16 code units, not code points.
1997 if name == "length" {
1998 let n = peek(recv, |o| match o {
1999 JsObj::Str(s) => Some(crate::utf16::len(s)),
2000 _ => None,
2001 })
2002 .unwrap_or(0);
2003 Value::Float(n as f64)
2004 } else if let Ok(i) = name.parse::<usize>() {
2005 match peek(recv, |o| match o {
2006 JsObj::Str(s) => crate::utf16::Units::of(s).unit_str(i),
2007 _ => None,
2008 }) {
2009 Some(c) => with_host(|h| h.new_str(c)),
2010 None => Value::Undef,
2011 }
2012 } else if name == "@@iterator" || is_string_method(name) {
2013 bound_method(recv, name)
2014 } else {
2015 Value::Undef
2016 }
2017 }
2018 Some(ObjKind::Builtin) => {
2019 let ns = peek(recv, |o| match o {
2020 JsObj::Builtin(ns) => Some(ns.clone()),
2021 _ => None,
2022 })
2023 .unwrap_or_default();
2024 let v = namespace_property(&ns, name);
2025 // `Function.prototype`'s methods READ off a builtin function. The
2026 // CALL forms (`Math.max.call(null, 1, 2)`) already dispatched, but
2027 // the read answered `undefined` — so `typeof Math.max.bind` was
2028 // `"undefined"`, and `String(Math.max)` found no `toString` to
2029 // invoke and fell back to `Object.prototype.toString`'s
2030 // `[object Function]` where node reports the native-code form.
2031 if matches!(v, Value::Undef)
2032 && is_function_method(name)
2033 && host::builtin_is_callable(&ns)
2034 {
2035 return Ok(bound_method(recv, name));
2036 }
2037 v
2038 }
2039 _ => {
2040 // Primitive numbers/booleans: method access -> bound method.
2041 if matches!(recv, Value::Float(_) | Value::Int(_)) && is_number_method(name) {
2042 bound_method(recv, name)
2043 } else {
2044 Value::Undef
2045 }
2046 }
2047 };
2048 // Every object INHERITS the `Object.prototype` methods, and each kind's
2049 // read arm above knows only its OWN. So `typeof new Map().toString`,
2050 // `typeof f.hasOwnProperty` and `typeof /a/.propertyIsEnumerable` all
2051 // answered `undefined` — for Map the CALL already worked, which is the
2052 // read and the dispatch disagreeing about the same method.
2053 //
2054 // Which prototype owns the name is decided by the same helper the `in`
2055 // operator uses, so the two cannot drift, and the result is the SHARED
2056 // intrinsic rather than a per-read thunk.
2057 // `arguments.callee` (and `.caller`) is a POISON PILL in strict code — the
2058 // accessor throws rather than answering, which is how a strict function
2059 // keeps its caller unreachable. It read back as `undefined` here, which a
2060 // feature probe reads as "not supported" rather than "forbidden".
2061 // Measured: on an ARGUMENTS object only `callee` is poisoned (`caller` is
2062 // simply absent and reads `undefined`); on a strict FUNCTION both `caller`
2063 // and `arguments` are.
2064 if name == "callee" && is_arguments(recv) && with_host(|h| h.current_strict()) {
2065 return Err(host::type_error(POISON_PILL));
2066 }
2067 if matches!(name, "caller" | "arguments")
2068 && matches!(
2069 with_host(|h| h.kind_of(recv)),
2070 Some(ObjKind::Func) | Some(ObjKind::Class)
2071 )
2072 {
2073 return poison_pill_read(recv);
2074 }
2075 // `arguments.callee` in SLOPPY code is the running function — the
2076 // pre-`class` self-reference idiom. It read back `undefined`.
2077 if name == "callee" && is_arguments(recv) {
2078 if let Some(f) = with_host(|h| h.fn_prop(recv, "@@callee")) {
2079 return Ok(f);
2080 }
2081 }
2082 // A method SYNTHESIZED from the receiver's kind is only reachable while the
2083 // receiver's intrinsic prototype is still on its chain. `Object
2084 // .setPrototypeOf(a, {})` must make `a.join` `undefined`; the kind arm
2085 // above answers from the kind alone and cannot know the link changed. Only
2086 // a synthesized value is dropped — the two shapes a method read produces —
2087 // and only when the receiver does not own the name itself.
2088 if matches!(
2089 with_host(|h| h.get(&out).cloned()),
2090 Some(JsObj::BoundMethod { .. })
2091 ) || matches!(
2092 with_host(|h| h.get(&out).cloned()),
2093 Some(JsObj::Builtin(ns)) if ns.starts_with("@proto:")
2094 ) {
2095 // The kind arms synthesize their OWN kind's methods, so that is the
2096 // prototype whose reachability decides. Clearing the value here lets
2097 // the `inherited_method_owner` fallback below re-supply the
2098 // `Object.prototype` form where one exists — which is why
2099 // `a.toString` stays a function after the link is replaced while
2100 // `a.join` does not.
2101 if !own_intrinsic_reachable(recv) && !has_own_for_shadow(recv, name) {
2102 out = Value::Undef;
2103 }
2104 }
2105 // A key the receiver does not OWN is looked up on its prototype chain. The
2106 // exotic arms above answer from their own storage and stop, so an array
2107 // given a prototype inherited nothing through a read: with
2108 // `Object.setPrototypeOf(a, {1: 'q'})`, `a[1]` was `undefined` at an elided
2109 // index and at one past the end, while `1 in a` already answered true —
2110 // the two views of the same question disagreeing. An accessor was found
2111 // (`lookup_accessor` walks), so only DATA properties went missing.
2112 //
2113 // A plain object's arm already consults the chain, and an array with no
2114 // explicit prototype has no links to walk, so this changes neither.
2115 if !name.starts_with('#') && !name.starts_with("@@") && !has_own_for_shadow(recv, name) {
2116 if matches!(out, Value::Undef) {
2117 if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
2118 return Ok(v);
2119 }
2120 }
2121 // Then a monkey-patched intrinsic prototype member, which shadows the
2122 // synthesized one: after `Array.prototype.join = f`, `[1, 2].join` must
2123 // BE `f`. An explicitly-set prototype above wins over it, as the chain
2124 // order requires.
2125 if let Some(v) = inherited_builtin_static(recv, name) {
2126 return Ok(v);
2127 }
2128 }
2129 if matches!(out, Value::Undef) && !name.starts_with('#') {
2130 if let Some(owner) = inherited_method_owner(recv, name) {
2131 // An INHERITED accessor runs, it does not hand back a thunk, and
2132 // its brand check is about the receiver's internal slot rather than
2133 // its chain — `Object.create(Map.prototype).size` throws in node
2134 // even though `Map.prototype` is right there above it. This
2135 // answered `undefined`, which is the value a real Map would never
2136 // give and a plain object should never reach.
2137 if is_proto_accessor(owner, name) && !getter_in_flight(owner, name) {
2138 return proto_getter_call(owner, name, recv);
2139 }
2140 let key = format!("@proto:{owner}:{name}");
2141 if builtin_meta(&key).is_some() {
2142 return Ok(with_host(|h| h.alloc(JsObj::Builtin(key))));
2143 }
2144 // A DATA member of the prototype — `Array.prototype[Symbol
2145 // .unscopables]` is an object, not a method, so it is in neither
2146 // function table. Read it off the prototype itself rather than
2147 // answering `undefined`: an instance inherits it.
2148 let v = namespace_property(&format!("{owner}.prototype"), name);
2149 if !matches!(v, Value::Undef) {
2150 return Ok(v);
2151 }
2152 }
2153 }
2154 Ok(out)
2155}
2156
2157/// The namespace name of the `require.cache` view. A `Builtin` rather than an
2158/// object literal because the module cache is the single source of truth: a
2159/// populated copy would answer reads correctly and silently ignore a `delete`,
2160/// which is the operation the property exists for.
2161pub const REQUIRE_CACHE: &str = "__cjs_cache";
2162
2163/// The builtin constructor name for a value with no own/inherited `constructor`
2164/// property, so `x.constructor` (and thus `x.constructor.name`) matches Node for
2165/// arrays, plain objects, Map/Set, promises, iterators, functions, and boxed
2166/// primitives. `None` ⇒ leave `.constructor` as `undefined` (e.g. generators,
2167/// whose `.constructor.name` is `""` in Node — not worth modelling).
2168fn default_ctor_name(h: &host::JsHost, recv: &Value) -> Option<&'static str> {
2169 match h.get(recv) {
2170 Some(JsObj::Array(_)) => Some("Array"),
2171 Some(JsObj::Object(props)) => {
2172 // A native instance reports its own constructor, not Object — e.g.
2173 // `qs` does `buf.constructor.isBuffer(buf)`, so a Buffer's
2174 // `.constructor` must be `Buffer` (which carries `isBuffer`). Read
2175 // the `@@native` tag off the already-borrowed host (calling
2176 // `native_tag`, which re-enters `with_host`, would double-borrow).
2177 match props.get("@@native").map(|t| h.str_of(t)).as_deref() {
2178 Some("Buffer") => Some("Buffer"),
2179 Some("URL") => Some("URL"),
2180 Some("Date") => Some("Date"),
2181 Some("WeakRef") => Some("WeakRef"),
2182 Some("FinalizationRegistry") => Some("FinalizationRegistry"),
2183 Some("TextEncoder") => Some("TextEncoder"),
2184 Some("TextDecoder") => Some("TextDecoder"),
2185 Some("EventEmitter") => Some("EventEmitter"),
2186 Some("Timeout") => Some("Timeout"),
2187 Some("Immediate") => Some("Immediate"),
2188 _ => Some("Object"),
2189 }
2190 }
2191 Some(JsObj::Map { weak, .. }) => Some(if *weak { "WeakMap" } else { "Map" }),
2192 Some(JsObj::Set { weak, .. }) => Some(if *weak { "WeakSet" } else { "Set" }),
2193 Some(JsObj::Promise { .. }) => Some("Promise"),
2194 Some(JsObj::Str(_)) => Some("String"),
2195 Some(JsObj::Symbol { .. }) => Some("Symbol"),
2196 Some(JsObj::BigInt(_)) => Some("BigInt"),
2197 Some(JsObj::RegExp(_)) => Some("RegExp"),
2198 Some(JsObj::Iter { .. }) => Some("Iterator"),
2199 Some(JsObj::Func(f)) => {
2200 // A generator or async function is NOT an ordinary function: its
2201 // `[[Prototype]]` is `GeneratorFunction.prototype` (or the async
2202 // variants'), and so is its `constructor`. All three reported plain
2203 // `Function`, so `g.constructor.name` was `Function` where node
2204 // says `GeneratorFunction`.
2205 Some(match h.funcs.get(f.def_id) {
2206 Some(d) if d.is_generator && d.is_async => "AsyncGeneratorFunction",
2207 Some(d) if d.is_generator => "GeneratorFunction",
2208 Some(d) if d.is_async => "AsyncFunction",
2209 _ => "Function",
2210 })
2211 }
2212 Some(JsObj::Class(_)) | Some(JsObj::BoundFunc { .. }) => Some("Function"),
2213 _ => match recv {
2214 Value::Float(_) | Value::Int(_) => Some("Number"),
2215 Value::Bool(_) => Some("Boolean"),
2216 _ => None,
2217 },
2218 }
2219}
2220
2221/// The builtin constructor *functions*, so `Ctor.name` is the constructor name.
2222/// Excludes the non-callable namespaces (`Math`, `JSON`, `console`, `Reflect`,
2223/// `process`), whose `.name` is `undefined` in Node.
2224///
2225/// Most are also globals, but not all: `Timeout`/`Immediate` are unexposed in
2226/// Node (`typeof Timeout === 'undefined'`) yet still name themselves through a
2227/// handle's `.constructor.name`, so they belong here and not in `GLOBALS`.
2228/// The builtins that expose a `Symbol.species` accessor. Each returns `this`,
2229/// so a subclass is its own species unless it overrides the getter.
2230fn has_species(name: &str) -> bool {
2231 matches!(
2232 name,
2233 "Array" | "Map" | "Set" | "WeakMap" | "WeakSet" | "Promise" | "RegExp" | "ArrayBuffer"
2234 ) || crate::stdlib::typedarray::is_ctor(name)
2235}
2236
2237fn is_builtin_ctor(name: &str) -> bool {
2238 matches!(
2239 name,
2240 "Array"
2241 | "Object"
2242 | "Number"
2243 | "String"
2244 | "Boolean"
2245 | "Symbol"
2246 | "Function"
2247 | "Map"
2248 | "Set"
2249 | "WeakMap"
2250 | "WeakSet"
2251 | "Promise"
2252 | "BigInt"
2253 | "Iterator"
2254 | "RegExp"
2255 | "Date"
2256 | "ArrayBuffer"
2257 | "DataView"
2258 | "Uint8Array"
2259 | "Int8Array"
2260 | "Uint8ClampedArray"
2261 | "Int16Array"
2262 | "Uint16Array"
2263 | "Int32Array"
2264 | "Uint32Array"
2265 | "Float32Array"
2266 | "Float64Array"
2267 | "BigInt64Array"
2268 | "BigUint64Array"
2269 | "WeakRef"
2270 | "FinalizationRegistry"
2271 | "TextEncoder"
2272 | "TextDecoder"
2273 | "IncomingMessage"
2274 | "ServerResponse"
2275 | "EventEmitter"
2276 | "Buffer"
2277 | "URL"
2278 | "URLSearchParams"
2279 | "Timeout"
2280 | "Immediate"
2281 ) || host::ERROR_NAMES.contains(&name)
2282 // The stream base classes are constructors too, and `require('stream')`
2283 // IS `Stream`, so `require('stream').name` has to answer.
2284 || crate::stdlib::stream::is_class(name)
2285}
2286
2287/// The intrinsic key of the method `<instance>.<method>` resolves to, so a bound
2288/// thunk can look its `name`/`length` up in the same table a
2289/// `<Ctor>.prototype.<method>` thunk uses. `None` when the receiver has no
2290/// builtin constructor to name (a native stdlib instance, whose methods are
2291/// node's own JS and have no specified arity).
2292fn bound_method_key(recv: &Value, method: &str) -> Option<String> {
2293 let ctor = with_host(|h| default_ctor_name(h, recv))?;
2294 Some(format!("@proto:{ctor}:{method}"))
2295}
2296
2297/// `[[Get]]` on a bound method thunk. It is a function, so `name`, `length` and
2298/// the `Function.prototype` methods all answer; `length` only when the intrinsic
2299/// table knows the method, because inventing an arity is worse than the
2300/// `undefined` a caller can test for.
2301fn bound_method_property(recv: &Value, name: &str) -> Value {
2302 let method = peek(recv, |o| match o {
2303 JsObj::BoundMethod { name, .. } => Some(name.clone()),
2304 _ => None,
2305 })
2306 .unwrap_or_default();
2307 let key = peek(recv, |o| match o {
2308 JsObj::BoundMethod { recv, .. } => Some(recv.clone()),
2309 _ => None,
2310 })
2311 .and_then(|inner| bound_method_key(&inner, &method));
2312 let meta = key.as_deref().and_then(builtin_meta);
2313 match name {
2314 "name" => {
2315 let n = meta.map(|(n, _)| n.to_string()).unwrap_or(method);
2316 with_host(|h| h.new_str(n))
2317 }
2318 "length" => match meta {
2319 Some((_, len)) => Value::Float(len as f64),
2320 None => Value::Undef,
2321 },
2322 _ if is_function_method(name) => bound_method(recv, name),
2323 _ => with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef),
2324 }
2325}
2326
2327fn bound_method(recv: &Value, name: &str) -> Value {
2328 // An ECMAScript intrinsic is ONE function object shared by every instance:
2329 // `[1].push === Array.prototype.push` and `[1].push === [2].push` are both
2330 // true. Reading one off an instance used to mint a fresh thunk bound to that
2331 // instance, so every such comparison answered false — and a detached method
2332 // kept working on the receiver it was read off, where node throws because it
2333 // has no `this` at all.
2334 if let Some(key) = bound_method_key(recv, name) {
2335 if builtin_meta(&key).is_some() {
2336 return with_host(|h| h.alloc(JsObj::Builtin(key)));
2337 }
2338 }
2339 with_host(|h| {
2340 h.alloc(JsObj::BoundMethod {
2341 recv: recv.clone(),
2342 name: name.to_string(),
2343 })
2344 })
2345}
2346
2347/// `Object.prototype` methods reachable on any object.
2348fn is_object_method(name: &str) -> bool {
2349 matches!(
2350 name,
2351 "hasOwnProperty"
2352 | "isPrototypeOf"
2353 | "propertyIsEnumerable"
2354 | "toString"
2355 | "toLocaleString"
2356 | "valueOf"
2357 | "constructor"
2358 | "__defineGetter__"
2359 | "__defineSetter__"
2360 | "__lookupGetter__"
2361 | "__lookupSetter__"
2362 )
2363}
2364
2365/// The `Object.prototype` methods installed as thunks on the real
2366/// `Object.prototype` object, so `Object.prototype.toString.call(x)` and a class
2367/// prototype's inherited `hasOwnProperty` both resolve through the chain.
2368pub const OBJECT_PROTO_METHODS: &[&str] = &[
2369 "hasOwnProperty",
2370 "isPrototypeOf",
2371 "propertyIsEnumerable",
2372 "toString",
2373 "toLocaleString",
2374 "valueOf",
2375 "__defineGetter__",
2376 "__defineSetter__",
2377 "__lookupGetter__",
2378 "__lookupSetter__",
2379];
2380
2381/// A typed array with elements cannot be frozen or sealed: its indices are
2382/// non-configurable by construction, so making them non-writable would violate
2383/// the invariant, and node refuses outright rather than half-applying it. An
2384/// EMPTY view and a `DataView` are both fine.
2385/// `TestIntegrityLevel` (7.3.16) — `Object.isFrozen` / `Object.isSealed`.
2386///
2387/// Over a PROXY it is a sequence of traps (`isExtensible`, `ownKeys`, then a
2388/// `getOwnPropertyDescriptor` per key), not a question for the host: the proxy
2389/// OBJECT was being inspected, so a frozen proxy answered false and the handler
2390/// never saw the query.
2391fn integrity_level(v: &Value, freeze: bool) -> Result<Value, String> {
2392 if with_host(|h| h.kind_of(v)) != Some(ObjKind::Proxy) {
2393 return Ok(Value::Bool(with_host(|h| h.is_sealed(v, freeze))));
2394 }
2395 // An EXTENSIBLE object is neither sealed nor frozen, whatever its keys say.
2396 if crate::proxy::is_extensible(v)?.unwrap_or(true) {
2397 return Ok(Value::Bool(false));
2398 }
2399 for key in crate::proxy::own_keys(v)?.unwrap_or_default() {
2400 let Some(d) = crate::proxy::get_own_descriptor(v, &key)? else {
2401 continue;
2402 };
2403 let flag = |name: &str| {
2404 with_host(|h| match h.get(&d) {
2405 Some(JsObj::Object(p)) => p.get(name).map(|x| h.truthy(x)).unwrap_or(false),
2406 _ => false,
2407 })
2408 };
2409 let is_data = with_host(
2410 |h| matches!(h.get(&d), Some(JsObj::Object(p)) if !p.contains_key("get") && !p.contains_key("set")),
2411 );
2412 if flag("configurable") || (freeze && is_data && flag("writable")) {
2413 return Ok(Value::Bool(false));
2414 }
2415 }
2416 Ok(Value::Bool(true))
2417}
2418
2419/// `SetIntegrityLevel` (7.3.15) over a PROXY, which is a sequence of TRAPS —
2420/// `preventExtensions`, then `ownKeys`, then a `getOwnPropertyDescriptor` and a
2421/// `defineProperty` per key. It ran none of them: the host sealed the proxy
2422/// OBJECT, so the handler never saw the operation and the target was untouched.
2423///
2424/// Returns false for a non-proxy, which takes the ordinary path.
2425fn seal_proxy(v: &Value, freeze: bool) -> Result<bool, String> {
2426 if with_host(|h| h.kind_of(v)) != Some(ObjKind::Proxy) {
2427 return Ok(false);
2428 }
2429 if crate::proxy::prevent_extensions(v)? != Some(true) {
2430 return Err(crate::proxy::prevent_extensions_refused());
2431 }
2432 let keys = crate::proxy::own_keys(v)?.unwrap_or_default();
2433 for key in keys {
2434 // SEALING asks for no descriptor at all — it only strips
2435 // `configurable`, which is the same for a data property and an
2436 // accessor. FREEZING has to know which it is, because only a data
2437 // property has a `writable` to strip, and that is the one extra trap
2438 // call node makes.
2439 let accessor = if freeze {
2440 let Some(cur) = crate::proxy::get_own_descriptor(v, &key)? else {
2441 continue;
2442 };
2443 with_host(
2444 |h| matches!(h.get(&cur), Some(JsObj::Object(p)) if p.contains_key("get") || p.contains_key("set")),
2445 )
2446 } else {
2447 false
2448 };
2449 let desc = with_host(|h| {
2450 let mut m: IndexMap<String, Value> = IndexMap::new();
2451 m.insert("configurable".into(), Value::Bool(false));
2452 if freeze && !accessor {
2453 m.insert("writable".into(), Value::Bool(false));
2454 }
2455 h.new_object(m)
2456 });
2457 if !crate::proxy::define_property(v, &key, &desc)? {
2458 return Err(host::type_error(&format!(
2459 "'defineProperty' on proxy: trap returned falsish for property '{key}'"
2460 )));
2461 }
2462 }
2463 Ok(true)
2464}
2465
2466fn reject_sealing_a_view(v: &Value, verb: &str) -> Result<(), String> {
2467 let has_elements = matches!(
2468 crate::stdlib::native_tag(v).as_deref(),
2469 Some("TypedArray") | Some("Buffer")
2470 ) && !crate::stdlib::typedarray::elem_values(v).is_empty();
2471 if has_elements {
2472 return Err(host::type_error(&format!(
2473 "Cannot {verb} array buffer views with elements"
2474 )));
2475 }
2476 Ok(())
2477}
2478
2479pub fn is_object_builtin_method(name: &str) -> bool {
2480 matches!(
2481 name,
2482 "hasOwnProperty"
2483 | "isPrototypeOf"
2484 | "propertyIsEnumerable"
2485 | "toString"
2486 | "toLocaleString"
2487 | "valueOf"
2488 | "__defineGetter__"
2489 | "__defineSetter__"
2490 | "__lookupGetter__"
2491 | "__lookupSetter__"
2492 )
2493}
2494
2495/// The `Symbol.toStringTag` STRING on `recv`'s chain, if any — steps 16-17 of
2496/// 20.1.3.6, the hook by which a class names its own brand.
2497///
2498/// A Proxy has no chain to probe: the step is an unconditional
2499/// `Get(O, @@toStringTag)`, so its `get` trap decides. Probing first (as an
2500/// ordinary receiver does, to keep the read off objects that carry no tag)
2501/// would always miss and brand every tagged proxy `[object Object]`.
2502///
2503/// The read runs OUTSIDE the host borrow so a getter-valued tag can be invoked.
2504fn to_string_tag(recv: &Value) -> Result<Option<String>, String> {
2505 let tagged = with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy)
2506 || with_host(|h| {
2507 host::lookup_chain(h, recv, "@@toStringTag").is_some()
2508 || host::lookup_accessor(h, recv, "@@toStringTag").is_some()
2509 // An exotic with no property map (a Map, a Promise) keeps its
2510 // own symbol-keyed properties in the side table.
2511 || h.fn_prop(recv, "@@toStringTag").is_some()
2512 });
2513 if !tagged {
2514 return Ok(None);
2515 }
2516 let t = get_property(recv, "@@toStringTag")?;
2517 Ok(with_host(|h| h.as_str(&t)))
2518}
2519
2520/// Dispatch an `Object.prototype` builtin method on an object/instance.
2521pub fn object_builtin_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
2522 match name {
2523 // Annex B B.2.2.2-B.2.2.5. Legacy, but still present in node and still
2524 // reached by pre-`defineProperty` libraries; all four were missing, so
2525 // `o.__defineGetter__` threw "is not a function".
2526 "__defineGetter__" | "__defineSetter__" => {
2527 let getter = name == "__defineGetter__";
2528 let f = args.get(1).cloned().unwrap_or(Value::Undef);
2529 if !with_host(|h| host::is_callable(h, &f)) {
2530 return Err(host::type_error(&format!(
2531 "Object.prototype.{name}: Expecting function"
2532 )));
2533 }
2534 let key = host::to_property_key(&arg0(&args))?;
2535 let desc = with_host(|h| {
2536 let mut m: IndexMap<String, Value> = IndexMap::new();
2537 m.insert(if getter { "get" } else { "set" }.into(), f);
2538 m.insert("enumerable".into(), Value::Bool(true));
2539 m.insert("configurable".into(), Value::Bool(true));
2540 h.new_object(m)
2541 });
2542 apply_descriptor(recv, &key, &desc)?;
2543 Ok(Value::Undef)
2544 }
2545 "__lookupGetter__" | "__lookupSetter__" => {
2546 let want_get = name == "__lookupGetter__";
2547 let key = host::to_property_key(&arg0(&args))?;
2548 // Walks the prototype chain, unlike `getOwnPropertyDescriptor`.
2549 let found = with_host(|h| host::lookup_accessor(h, recv, &key));
2550 Ok(match found {
2551 Some((g, st)) => {
2552 let side = if want_get { g } else { st };
2553 side.unwrap_or(Value::Undef)
2554 }
2555 None => Value::Undef,
2556 })
2557 }
2558 "hasOwnProperty" => {
2559 let k = host::to_property_key(&arg0(&args))?;
2560 // The global object OWNS its lazily-bound builtins and every global
2561 // a script created; neither lives in its property map.
2562 if with_host(|h| h.is_global_object(recv))
2563 && !CJS_WRAPPER_LOCALS.contains(&k.as_str())
2564 && global_object_binding(&k).is_some()
2565 {
2566 return Ok(Value::Bool(true));
2567 }
2568 // A builtin namespace/prototype receiver (`Map.prototype`) reports
2569 // ownership via `has_property` (its methods resolve as thunks).
2570 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Builtin) {
2571 // …except a singleton (`performance`, `crypto`), whose members
2572 // are all inherited from its class prototype.
2573 if matches!(with_host(|h| h.get(recv).cloned()), Some(JsObj::Builtin(n)) if crate::stdlib::singleton_class(&n).is_some())
2574 {
2575 return Ok(Value::Bool(false));
2576 }
2577 return Ok(Value::Bool(has_property(recv, &k)?));
2578 }
2579 // `HasOwnProperty` (7.3.12) is `[[GetOwnProperty]]`, so on a Proxy it
2580 // is the `getOwnPropertyDescriptor` trap — NOT the `has` trap and not
2581 // the target's property map.
2582 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
2583 let d = crate::proxy::get_own_descriptor(recv, &k)?.unwrap_or(Value::Undef);
2584 return Ok(Value::Bool(!matches!(d, Value::Undef)));
2585 }
2586 // A Buffer's / typed array's own keys are its element indices: the
2587 // `length`/`byteLength` slots are internal bookkeeping, and V8
2588 // reports `hasOwnProperty('length')` as false for a typed array.
2589 // Shared with the `in` operator so the two cannot drift apart.
2590 if let Some(hit) = crate::stdlib::typedarray::has_index(recv, &k) {
2591 return Ok(Value::Bool(hit));
2592 }
2593 // A function's `length`/`name`/`prototype` and a RegExp's
2594 // `lastIndex` are SYNTHESIZED own properties: they read back but
2595 // own no map entry, so this answered false where node says true.
2596 if synthesized_own_descriptor(recv, &k).is_some() {
2597 return Ok(Value::Bool(true));
2598 }
2599 if uses_side_table(recv) {
2600 return Ok(Value::Bool(with_host(|h| h.fn_prop(recv, &k).is_some())));
2601 }
2602 let has = with_host(|h| match h.get(recv) {
2603 Some(JsObj::Object(p)) => p.contains_key(&k) || h.own_accessor(recv, &k).is_some(),
2604 Some(JsObj::Array(items)) => {
2605 k == "length"
2606 // A named own property (`a.join = f`) lives in the side table.
2607 || h.fn_prop(recv, &k).is_some()
2608 || h.own_accessor(recv, &k).is_some()
2609 || k.parse::<usize>()
2610 .map(|i| i < items.len() && !h.is_hole(recv, i))
2611 .unwrap_or(false)
2612 }
2613 _ => false,
2614 });
2615 Ok(Value::Bool(has))
2616 }
2617 "isPrototypeOf" => {
2618 let target = arg0(&args);
2619 // The ARGUMENT is what gets walked, so a proxy there needs its
2620 // `getPrototypeOf` trap for the FIRST hop: `proto_of` reads a link a
2621 // proxy does not hold, which reported `false` for every proxy. From
2622 // the second hop on the chain is ordinary objects again, walked by
2623 // the recorded link exactly as before.
2624 // Each further hop is `[[GetPrototypeOf]]` (`prototype_of`), the same
2625 // answer `Object.getPrototypeOf` gives: the recorded link alone
2626 // misses a class's parent constructor and every default prototype,
2627 // so `A.isPrototypeOf(B)` for `class B extends A` and
2628 // `Error.isPrototypeOf(RangeError)` read false.
2629 let non_null = |p: Value| Some(p).filter(|p| !with_host(|h| h.is_null(p)));
2630 let mut cur = match crate::proxy::get_prototype_of(&target)? {
2631 Some(p) => non_null(p),
2632 None if with_host(|h| crate::host::is_primitive(h, &target)) => None,
2633 None => non_null(prototype_of(&target)),
2634 };
2635 // Bounded: a chain longer than any real one is a cycle.
2636 for _ in 0..100_000 {
2637 let Some(p) = cur else { break };
2638 if with_host(|h| h.strict_eq(&p, recv)) {
2639 return Ok(Value::Bool(true));
2640 }
2641 cur = non_null(prototype_of(&p));
2642 }
2643 Ok(Value::Bool(false))
2644 }
2645 "propertyIsEnumerable" => {
2646 // A SYMBOL key is answered by `[[GetOwnProperty]]` (20.1.3.4). The
2647 // key below is the symbol's display string, which names no property,
2648 // so every symbol-keyed property — an object literal's, a function's,
2649 // a core function's measured ones — read as not enumerable.
2650 if with_host(|h| matches!(h.get(&arg0(&args)), Some(JsObj::Symbol { .. }))) {
2651 let desc = object_get_own_descriptor(vec![recv.clone(), arg0(&args)])?;
2652 if with_host(|h| h.is_nullish(&desc)) {
2653 return Ok(Value::Bool(false));
2654 }
2655 let enumerable = get_property(&desc, "enumerable")?;
2656 return Ok(Value::Bool(with_host(|h| h.truthy(&enumerable))));
2657 }
2658 let k = with_host(|h| h.str_of(&arg0(&args)));
2659 // Own *and* enumerable — a non-enumerable own slot reads false. On a
2660 // Proxy that question is `[[GetOwnProperty]]`, i.e. the descriptor
2661 // trap, since there is no property map to enumerate.
2662 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
2663 let has = crate::proxy::own_enum_string_keys(recv)?.contains(&k);
2664 return Ok(Value::Bool(has));
2665 }
2666 let has = with_host(|h| h.own_enum_key_names(recv).contains(&k));
2667 Ok(Value::Bool(has))
2668 }
2669 "toString" => {
2670 // An instance with a custom `toString` up the chain is handled by
2671 // call_method before reaching here; this is the default — and the
2672 // default consults `Symbol.toStringTag` (20.1.3.6 steps 16-17).
2673 // Only the EXPLICIT `Object.prototype.toString.call(o)` did, so a
2674 // tagged object branded itself `[object T]` when asked one way and
2675 // `[object Object]` when converted the other (`String(o)`, `${o}`,
2676 // `o + ''`, `o.toString()`), which is the path ordinary code takes.
2677 // 20.1.3.6 step 5 begins with IsArray, which a revoked proxy
2678 // throws from; V8 reports it under this method's name.
2679 crate::proxy::require_live(recv, "Object.prototype.toString")?;
2680 if let Some(t) = to_string_tag(recv)? {
2681 return Ok(with_host(|h| h.new_str(format!("[object {t}]"))));
2682 }
2683 Ok(with_host(|h| {
2684 let s = h.str_of(recv);
2685 h.new_str(s)
2686 }))
2687 }
2688 // `Object.prototype.toLocaleString` (20.1.3.5) is defined as
2689 // `Invoke(this, "toString")` — no locale behavior of its own. It was
2690 // installed as a thunk on `Object.prototype` but had no dispatch arm, so
2691 // calling it threw `is not a function` on every plain object.
2692 "toLocaleString" => {
2693 let v = host::call_method(recv, "toString", Vec::new())?;
2694 Ok(v)
2695 }
2696 "valueOf" => Ok(recv.clone()),
2697 _ => Err(host::type_error(&format!("{name} is not a function"))),
2698 }
2699}
2700
2701/// The `TypeError` for calling a constructor that is not callable. V8 words it
2702/// differently for the classes node implements in JavaScript (`URL`,
2703/// `TextEncoder`, the fetch classes) and for the engine-native ones.
2704fn requires_new(name: &str) -> String {
2705 if crate::stdlib::fetch::is_class(name)
2706 || crate::stdlib::event_target::is_class(name)
2707 || matches!(
2708 name,
2709 "URL"
2710 | "URLSearchParams"
2711 | "TextEncoder"
2712 | "TextDecoder"
2713 | "AbortController"
2714 | "AbortSignal"
2715 )
2716 {
2717 return host::type_error(&format!(
2718 "Class constructor {name} cannot be invoked without 'new'"
2719 ));
2720 }
2721 host::type_error(&format!("Constructor {name} requires 'new'"))
2722}
2723
2724/// Native constructors whose call form is a TypeError rather than a conversion
2725/// or a second entry point (`String`, `Number`, `Error`, `Date`… are all
2726/// callable and are matched by their own arms above).
2727fn is_new_only_ctor(name: &str) -> bool {
2728 crate::stdlib::typedarray::is_ctor(name)
2729 || crate::stdlib::fetch::is_class(name)
2730 || crate::stdlib::event_target::is_class(name)
2731 || matches!(
2732 name,
2733 "ArrayBuffer"
2734 | "DataView"
2735 | "WeakRef"
2736 | "FinalizationRegistry"
2737 | "Iterator"
2738 | "URL"
2739 | "URLSearchParams"
2740 | "TextEncoder"
2741 | "TextDecoder"
2742 | "AbortController"
2743 | "AbortSignal"
2744 )
2745}
2746
2747/// `Function.prototype` methods (`call`/`apply`/`bind`) plus `Symbol.prototype`/
2748/// generator handling done elsewhere. Returns `Ok(None)` if `name` is not one of
2749/// these (so the caller can try statics).
2750pub fn function_builtin_method(
2751 recv: &Value,
2752 name: &str,
2753 args: &[Value],
2754) -> Result<Option<Value>, String> {
2755 match name {
2756 "call" => {
2757 let this = args.first().cloned();
2758 let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
2759 Ok(Some(host::invoke(recv, rest, this)?))
2760 }
2761 "apply" => {
2762 let this = args.first().cloned();
2763 let arr = args.get(1).cloned().unwrap_or(Value::Undef);
2764 // `Function.prototype.apply` takes an ARRAY-LIKE, not an iterable
2765 // (10.2.4.3 → CreateListFromArrayLike): `f.apply(null, arguments)`
2766 // and `f.apply(null, {length: 2, 0: 'x', 1: 'y'})` are the shapes
2767 // this is written for, and both produced an empty list. A nullish
2768 // second argument means no arguments at all.
2769 let call_args = if matches!(arr, Value::Undef) || with_host(|h| h.is_null(&arr)) {
2770 Vec::new()
2771 } else {
2772 create_list_from_array_like(&arr)?
2773 };
2774 Ok(Some(host::invoke(recv, call_args, this)?))
2775 }
2776 "bind" => {
2777 let this = args.first().cloned().unwrap_or(Value::Undef);
2778 let pre = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
2779 Ok(Some(with_host(|h| {
2780 h.alloc(JsObj::BoundFunc {
2781 target: recv.clone(),
2782 this,
2783 args: pre,
2784 })
2785 })))
2786 }
2787 "toString" => Ok(Some(with_host(|h| {
2788 let s = h.str_of(recv);
2789 h.new_str(s)
2790 }))),
2791 _ => Ok(None),
2792 }
2793}
2794
2795fn is_function_method(name: &str) -> bool {
2796 matches!(name, "call" | "apply" | "bind" | "toString")
2797}
2798fn is_map_method(name: &str) -> bool {
2799 matches!(
2800 name,
2801 "get" | "set" | "has" | "delete" | "clear" | "forEach" | "keys" | "values" | "entries"
2802 )
2803}
2804fn is_set_method(name: &str) -> bool {
2805 matches!(
2806 name,
2807 "add"
2808 | "has"
2809 | "delete"
2810 | "clear"
2811 | "forEach"
2812 | "keys"
2813 | "values"
2814 | "entries"
2815 | "union"
2816 | "intersection"
2817 | "difference"
2818 | "symmetricDifference"
2819 | "isSubsetOf"
2820 | "isSupersetOf"
2821 | "isDisjointFrom"
2822 )
2823}
2824fn is_generator_method(name: &str) -> bool {
2825 matches!(name, "next" | "return" | "throw")
2826}
2827
2828/// A property read on a function/class value: own fn-props (statics, name,
2829/// prototype, length) plus inherited statics and `call`/`apply`/`bind`.
2830fn function_property(recv: &Value, name: &str) -> Value {
2831 // After `delete fn.length` / `delete fn.name` the read falls through to
2832 // `Function.prototype`, whose `length` is 0 and `name` is "".
2833 if with_host(|h| h.fn_intrinsic_deleted(recv, name)) {
2834 return if name == "name" {
2835 new_s(String::new())
2836 } else {
2837 Value::Float(0.0)
2838 };
2839 }
2840 // A class static, inherited down the constructor chain.
2841 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Class) {
2842 if let Some(v) = with_host(|h| h.class_static(recv, name)) {
2843 return v;
2844 }
2845 // A class's own `name` and `length` are its own, not the builtin
2846 // ancestor's: `class A extends Array {}` has `A.name === "A"` and
2847 // `A.length === 0`, but both were read off `Array`. Only a class that
2848 // WOULD fall through to an ancestor takes this path; a plain class keeps
2849 // the ordinary computation below.
2850 if matches!(name, "name" | "length")
2851 && with_host(|h| h.class_static(recv, name)).is_none()
2852 && with_host(|h| h.class_builtin_ancestor(recv))
2853 .is_some_and(|a| matches!(with_host(|h| h.kind_of(&a)), Some(ObjKind::Builtin)))
2854 {
2855 if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
2856 return v;
2857 }
2858 if name == "name" {
2859 let n = with_host(|h| h.callable_name(recv));
2860 return with_host(|h| h.new_str(n));
2861 }
2862 // The class's own constructor decides its arity; with no explicit
2863 // one the implicit `constructor(...args)` has length 0.
2864 let ctor = with_host(|h| match h.get(recv) {
2865 Some(JsObj::Class(c)) => c.ctor.clone(),
2866 _ => None,
2867 });
2868 return match ctor {
2869 Some(c) => get_property(&c, "length").unwrap_or(Value::Float(0.0)),
2870 None => Value::Float(0.0),
2871 };
2872 }
2873 // `Symbol.species` is an accessor returning `this`, so a subclass that
2874 // does not override it IS its own species. Reading it off the builtin
2875 // ancestor below would answer with the ancestor — `A[Symbol.species]`
2876 // came back as `Array`, which sent every derived result to a plain
2877 // array.
2878 if name == "@@species"
2879 && with_host(|h| h.class_static(recv, "@@species")).is_none()
2880 && with_host(|h| h.class_builtin_ancestor(recv))
2881 .is_some_and(|a| matches!(with_host(|h| h.kind_of(&a)), Some(ObjKind::Builtin)))
2882 {
2883 return recv.clone();
2884 }
2885 // The chain may bottom out in a BUILTIN constructor (`class D extends
2886 // Array {}`), whose statics `class_static` cannot see — it only walks
2887 // `ClassVal.parent` links between user classes. Finish the lookup with an
2888 // ordinary read on that ancestor so `D.from` inherits `Array.from`.
2889 if let Some(anc) = with_host(|h| h.class_builtin_ancestor(recv)) {
2890 if let Ok(v) = get_property(&anc, name) {
2891 if !matches!(v, Value::Undef) {
2892 return v;
2893 }
2894 }
2895 }
2896 } else if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
2897 return v;
2898 }
2899 // A method inherited via the function's [[Prototype]] chain (set with
2900 // `Object.setPrototypeOf(fn, proto)` — the `router` package makes each router
2901 // *function* inherit `route`/`use`/`get`/… from `Router.prototype` this way).
2902 if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
2903 return v;
2904 }
2905 match name {
2906 "name" => with_host(|h| {
2907 let n = h.callable_name(recv);
2908 h.new_str(n)
2909 }),
2910 "length" => Value::Float(with_host(|h| h.func_arity(recv)) as f64),
2911 "prototype" => ensure_fn_prototype(recv),
2912 _ if is_function_method(name) => bound_method(recv, name),
2913 _ => Value::Undef,
2914 }
2915}
2916
2917/// The `.prototype` of a function value, auto-created on first access (as Node
2918/// does for every non-arrow function) with `.constructor` linking back. Arrow
2919/// functions have no `prototype`.
2920fn ensure_fn_prototype(recv: &Value) -> Value {
2921 if let Some(p) = with_host(|h| h.fn_prop(recv, "prototype")) {
2922 return p;
2923 }
2924 // Only a constructor gets one: an arrow, a method definition and an async
2925 // function are not constructors, and a class sets its own (10.2.5).
2926 if with_host(|h| h.kind_of(recv)) != Some(ObjKind::Func) {
2927 return Value::Undef;
2928 }
2929 if !with_host(|h| h.owns_prototype(recv)) {
2930 return Value::Undef;
2931 }
2932 with_host(|h| {
2933 let proto = h.new_object(IndexMap::new());
2934 // A generator function's `prototype` has no `constructor` and inherits
2935 // from `%GeneratorPrototype%` / `%AsyncGeneratorPrototype%` (15.5.4,
2936 // 15.6.4), which is where its objects find `next`.
2937 if let Some(kind) = h.generator_kind(recv) {
2938 h.ensure_native_protos();
2939 if let Some(gp) = h.native_proto(kind) {
2940 h.set_proto(&proto, gp);
2941 }
2942 } else {
2943 if let Some(JsObj::Object(p)) = h.get_mut(&proto) {
2944 p.insert("constructor".to_string(), recv.clone());
2945 }
2946 h.hide_prop(&proto, "constructor");
2947 }
2948 h.set_fn_prop(recv, "prototype", proto.clone());
2949 proto
2950 })
2951}
2952
2953/// The prototype a generator object inherits from: its function's
2954/// `prototype` when that is an object, else the intrinsic
2955/// `%GeneratorPrototype%` / `%AsyncGeneratorPrototype%` (27.5.3.x
2956/// `OrdinaryCreateFromConstructor` with the intrinsic fallback).
2957pub fn generator_instance_proto(func: &Value) -> Option<Value> {
2958 let kind = with_host(|h| h.generator_kind(func))?;
2959 let p = ensure_fn_prototype(func);
2960 if with_host(|h| !h.is_nullish(&p) && !host::is_primitive(h, &p)) {
2961 return Some(p);
2962 }
2963 with_host(|h| {
2964 h.ensure_native_protos();
2965 h.native_proto(kind)
2966 })
2967}
2968
2969/// The numeric constants a core namespace owns, in the order node reports them
2970/// under `getOwnPropertyNames`. ONE table rather than a value match plus a name
2971/// list: the enumeration and the read have to agree, and they did not — every
2972/// one of these read correctly while `Object.getOwnPropertyNames(Math)` omitted
2973/// all eight of Math's, so a member that plainly exists was invisible to any
2974/// reflective copy of the namespace.
2975///
2976/// Each is `{ writable: false, enumerable: false, configurable: false }`, which
2977/// is what separates them from the methods alongside them.
2978pub fn namespace_constants(ns: &str) -> &'static [(&'static str, f64)] {
2979 const MATH: &[(&str, f64)] = &[
2980 ("E", std::f64::consts::E),
2981 ("LN10", std::f64::consts::LN_10),
2982 ("LN2", std::f64::consts::LN_2),
2983 ("LOG10E", std::f64::consts::LOG10_E),
2984 ("LOG2E", std::f64::consts::LOG2_E),
2985 ("PI", std::f64::consts::PI),
2986 ("SQRT1_2", std::f64::consts::FRAC_1_SQRT_2),
2987 ("SQRT2", std::f64::consts::SQRT_2),
2988 ];
2989 const NUMBER: &[(&str, f64)] = &[
2990 ("MAX_VALUE", f64::MAX),
2991 // The smallest positive value a Number can hold, which is the
2992 // smallest SUBNORMAL double (`5e-324`), not Rust's
2993 // `f64::MIN_POSITIVE` — that is the smallest *normal* double,
2994 // `2.2250738585072014e-308`, ~256 binary orders of magnitude too
2995 // large.
2996 // The literal, not `f64::from_bits(1)`: that is only const-callable from
2997 // Rust 1.83 and this crate's MSRV is 1.80. It parses to the same
2998 // bit pattern — the smallest positive subnormal.
2999 ("MIN_VALUE", 5e-324),
3000 ("NaN", f64::NAN),
3001 ("NEGATIVE_INFINITY", f64::NEG_INFINITY),
3002 ("POSITIVE_INFINITY", f64::INFINITY),
3003 ("MAX_SAFE_INTEGER", 9007199254740991.0),
3004 ("MIN_SAFE_INTEGER", -9007199254740991.0),
3005 ("EPSILON", f64::EPSILON),
3006 ];
3007 match ns {
3008 "Math" => MATH,
3009 "Number" => NUMBER,
3010 _ => &[],
3011 }
3012}
3013
3014/// The descriptor of `<ns>.<key>`, whose attributes fall into four groups —
3015/// measured on node v26.8.1:
3016///
3017/// ```text
3018/// Math.PI, Number.MAX_SAFE_INTEGER, Number.prototype w=false e=false c=false
3019/// Math.max.name, Math.max.length w=false e=false c=true
3020/// Math.floor, Array.from, Array.prototype.slice w=true e=false c=true
3021/// require('path').join w=true e=true c=true
3022/// ```
3023///
3024/// So: a constant (and a constructor's `prototype` — an ordinary core-module
3025/// function's is writable) is frozen, a function's own
3026/// `name`/`length` is read-only but configurable, and everything else is an
3027/// ordinary method — enumerable exactly when the namespace enumerates it, which
3028/// is what separates a core module's exports from an ECMAScript namespace's.
3029fn builtin_member_descriptor(ns: &str, key: &str, value: Value) -> Value {
3030 if let Some(row) = core_symbol_prop(ns, key) {
3031 return core_symbol_descriptor(ns, row, value);
3032 }
3033 if let Some(row) = core_accessor_export(ns, key) {
3034 return core_accessor_descriptor(row);
3035 }
3036 let frozen = namespace_constants(ns).iter().any(|(k, _)| *k == key)
3037 || key == "prototype" && !core_function_prototyped(ns)
3038 || (ns == "Symbol" && host::WELL_KNOWN_SYMBOLS.contains(&key));
3039 let own_fn_meta = matches!(key, "name" | "length") && host::builtin_is_callable(ns);
3040 // A key a SCRIPT assigned is an ordinary writable/enumerable/configurable
3041 // data property, whatever the namespace's built-in members look like — the
3042 // synthesized answer reported it non-enumerable, so a monkey-patched member
3043 // described itself as one of the intrinsics.
3044 let assigned = !intrinsic_proto_member(ns, key)
3045 && !crate::stdlib::namespace_keys(ns).iter().any(|k| k == key)
3046 && with_host(|h| h.builtin_static(ns, key).is_some());
3047 let enumerable = assigned
3048 || (!frozen
3049 && !own_fn_meta
3050 && crate::stdlib::namespace_statics_enumerable(ns)
3051 && crate::stdlib::namespace_keys(ns).iter().any(|k| k == key));
3052 with_host(|h| {
3053 let mut m: IndexMap<String, Value> = IndexMap::new();
3054 m.insert("value".into(), value);
3055 m.insert(
3056 "writable".into(),
3057 Value::Bool(assigned || (!frozen && !own_fn_meta)),
3058 );
3059 m.insert("enumerable".into(), Value::Bool(enumerable));
3060 m.insert(
3061 "configurable".into(),
3062 Value::Bool(assigned || builtin_member_configurable(ns, key)),
3063 );
3064 h.new_object(m)
3065 })
3066}
3067
3068/// The builtin key of `os.<m>[Symbol.toPrimitive]` (`os.@@toPrimitive:<m>`),
3069/// for `name` the `@@toPrimitive` key of one of the `os` value functions.
3070pub fn os_to_primitive_key(ns: &str, name: &str) -> Option<String> {
3071 let m = ns.strip_prefix("os.")?;
3072 (name == "@@toPrimitive" && crate::stdlib::os::TO_PRIMITIVE.contains(&m))
3073 .then(|| format!("os.@@toPrimitive:{m}"))
3074}
3075
3076/// One measured own symbol-keyed property of a core function:
3077/// `(key, symbol, accessor, enumerable, writable, configurable)`.
3078pub type CoreSymbolProp = (&'static str, &'static str, bool, bool, bool, bool);
3079
3080/// The measured own symbol-keyed properties (`CORE_SYMBOL_PROPS`) of the core
3081/// function keyed `ns`. A global timer function is its `timers` twin in node
3082/// (`setTimeout === require('timers').setTimeout`), so it answers for it.
3083pub fn core_symbol_props(ns: &str) -> &'static [CoreSymbolProp] {
3084 let t = crate::core_arity::CORE_SYMBOL_PROPS;
3085 let rows = |k: &str| -> &'static [CoreSymbolProp] {
3086 &t[t.partition_point(|r| r.0 < k)..t.partition_point(|r| r.0 <= k)]
3087 };
3088 match rows(ns) {
3089 [] if !ns.contains('.') => rows(&format!("timers.{ns}")),
3090 found => found,
3091 }
3092}
3093
3094/// The symbol a `CORE_SYMBOL_PROPS` spelling names: `@@<name>` a well-known
3095/// symbol, `for:<key>` the `Symbol.for` registry's.
3096pub fn core_symbol_value(h: &mut host::JsHost, spelling: &str) -> Value {
3097 match spelling.strip_prefix("for:") {
3098 Some(k) => h.symbol_for(k),
3099 None => h.well_known_symbol(spelling.trim_start_matches("@@")),
3100 }
3101}
3102
3103/// The `CORE_SYMBOL_PROPS` row of `<ns>[key]`, `key` being the internal
3104/// property-key spelling of a symbol.
3105fn core_symbol_prop(ns: &str, key: &str) -> Option<CoreSymbolProp> {
3106 let rows = core_symbol_props(ns);
3107 if rows.is_empty() || !host::is_symbol_key(key) {
3108 return None;
3109 }
3110 rows.iter().copied().find(|r| {
3111 with_host(|h| {
3112 let sym = core_symbol_value(h, r.1);
3113 h.property_key(&sym) == key
3114 })
3115 })
3116}
3117
3118/// The descriptor of a measured symbol-keyed property: an accessor's getter
3119/// is a function named `get` returning the property's value, as node's are.
3120fn core_symbol_descriptor(ns: &str, row: CoreSymbolProp, value: Value) -> Value {
3121 let (_, spelling, accessor, enumerable, writable, configurable) = row;
3122 with_host(|h| {
3123 let mut m: IndexMap<String, Value> = IndexMap::new();
3124 if accessor {
3125 let getter = h.alloc(JsObj::Builtin(format!(
3126 "{CORE_SYMBOL_GETTER}{ns}:{spelling}"
3127 )));
3128 m.insert("get".into(), getter);
3129 m.insert("set".into(), Value::Undef);
3130 } else {
3131 m.insert("value".into(), value);
3132 m.insert("writable".into(), Value::Bool(writable));
3133 }
3134 m.insert("enumerable".into(), Value::Bool(enumerable));
3135 m.insert("configurable".into(), Value::Bool(configurable));
3136 h.new_object(m)
3137 })
3138}
3139
3140/// The key prefix of a measured symbol accessor's getter,
3141/// `@coresymget:<ns>:<spelling>`.
3142const CORE_SYMBOL_GETTER: &str = "@coresymget:";
3143
3144/// Run the getter [`core_symbol_descriptor`] hands out: the read it stands for.
3145fn call_core_symbol_getter(rest: &str) -> Result<Value, String> {
3146 let (ns, spelling) = rest.split_once(':').unwrap_or((rest, ""));
3147 let spelling_key = spelling.to_string();
3148 let key = with_host(|h| {
3149 let sym = core_symbol_value(h, &spelling_key);
3150 h.property_key(&sym)
3151 });
3152 Ok(namespace_property(ns, &key))
3153}
3154
3155/// One measured accessor export of a core module:
3156/// `(namespace, key, has_setter, enumerable, configurable, getter_name,
3157/// setter_name)`.
3158pub type CoreAccessorExport = (
3159 &'static str,
3160 &'static str,
3161 bool,
3162 bool,
3163 bool,
3164 &'static str,
3165 &'static str,
3166);
3167
3168/// The `CORE_ACCESSOR_EXPORTS` row of `<ns>.<key>`: an export node defines as
3169/// a getter (`timers.promises`, `fs.ReadStream`, `crypto.webcrypto`).
3170pub fn core_accessor_export(ns: &str, key: &str) -> Option<CoreAccessorExport> {
3171 let t = crate::core_arity::CORE_ACCESSOR_EXPORTS;
3172 t.binary_search_by(|r| (r.0, r.1).cmp(&(ns, key)))
3173 .ok()
3174 .map(|i| t[i])
3175}
3176
3177/// The key prefixes of an accessor export's getter and setter,
3178/// `@coreexportget:<ns>:<key>` / `@coreexportset:<ns>:<key>`.
3179pub const CORE_EXPORT_GETTER: &str = "@coreexportget:";
3180pub const CORE_EXPORT_SETTER: &str = "@coreexportset:";
3181
3182/// The getter and (if node defines one) setter function values of an
3183/// accessor export.
3184pub fn core_accessor_functions(row: CoreAccessorExport) -> (Value, Option<Value>) {
3185 let (ns, key, has_setter, ..) = row;
3186 with_host(|h| {
3187 let get = h.alloc(JsObj::Builtin(format!("{CORE_EXPORT_GETTER}{ns}:{key}")));
3188 let set =
3189 has_setter.then(|| h.alloc(JsObj::Builtin(format!("{CORE_EXPORT_SETTER}{ns}:{key}"))));
3190 (get, set)
3191 })
3192}
3193
3194/// The descriptor of an accessor export: `{ get, set, enumerable,
3195/// configurable }`, as node reports it.
3196fn core_accessor_descriptor(row: CoreAccessorExport) -> Value {
3197 let (get, set) = core_accessor_functions(row);
3198 with_host(|h| {
3199 let mut m: IndexMap<String, Value> = IndexMap::new();
3200 m.insert("get".into(), get);
3201 m.insert("set".into(), set.unwrap_or(Value::Undef));
3202 m.insert("enumerable".into(), Value::Bool(row.3));
3203 m.insert("configurable".into(), Value::Bool(row.4));
3204 h.new_object(m)
3205 })
3206}
3207
3208/// `name`/`length` of an accessor export's getter or setter thunk: the
3209/// measured name; a getter takes no argument and a setter one.
3210fn core_accessor_function_meta(key: &str) -> Option<(&'static str, u32)> {
3211 let (rest, setter) = match key.strip_prefix(CORE_EXPORT_GETTER) {
3212 Some(rest) => (rest, false),
3213 None => (key.strip_prefix(CORE_EXPORT_SETTER)?, true),
3214 };
3215 let (ns, member) = rest.split_once(':')?;
3216 let row = core_accessor_export(ns, member)?;
3217 Some(if setter { (row.6, 1) } else { (row.5, 0) })
3218}
3219
3220/// Run an accessor export's getter or setter thunk: the read or write it
3221/// stands for.
3222fn call_core_accessor_function(key: &str, args: &[Value]) -> Option<Result<Value, String>> {
3223 let (rest, setter) = match key.strip_prefix(CORE_EXPORT_GETTER) {
3224 Some(rest) => (rest, false),
3225 None => (key.strip_prefix(CORE_EXPORT_SETTER)?, true),
3226 };
3227 let (ns, member) = rest.split_once(':')?;
3228 if !setter {
3229 return Some(Ok(namespace_property(ns, member)));
3230 }
3231 let target = with_host(|h| h.alloc(JsObj::Builtin(ns.to_string())));
3232 let value = args.first().cloned().unwrap_or(Value::Undef);
3233 Some(set_property_pub(&target, member, value).map(|()| Value::Undef))
3234}
3235
3236/// Whether `<ns>.<key>` may be deleted — the `configurable` half of
3237/// [`builtin_member_descriptor`], split out so `delete` can ask without
3238/// building a descriptor object.
3239/// Whether `key` is one of the members the intrinsic prototype namespace `ns`
3240/// really defines — as opposed to a name a script added. An assignment over one
3241/// of these is a `[[Set]]` and leaves its attributes alone.
3242fn intrinsic_proto_member(ns: &str, key: &str) -> bool {
3243 intrinsic_proto_members(ns).is_some_and(|members| {
3244 members
3245 .iter()
3246 .any(|m| m.strip_prefix('+').unwrap_or(m) == key)
3247 })
3248}
3249
3250fn builtin_member_configurable(ns: &str, key: &str) -> bool {
3251 !(namespace_constants(ns).iter().any(|(k, _)| *k == key)
3252 || key == "prototype"
3253 || (ns == "Symbol" && host::WELL_KNOWN_SYMBOLS.contains(&key)))
3254}
3255
3256/// The value of `<ns>.<name>` when it is one of those constants.
3257fn namespace_constant(ns: &str, name: &str) -> Option<f64> {
3258 namespace_constants(ns)
3259 .iter()
3260 .find(|(k, _)| *k == name)
3261 .map(|(_, v)| *v)
3262}
3263
3264/// Whether `ctor` is a WebIDL interface, whose prototype members are plain
3265/// assigned — and so ENUMERABLE — rather than the non-enumerable ones an
3266/// ECMAScript builtin defines. The generated member table records the same
3267/// distinction with its `+` prefix.
3268fn is_webidl_proto(ctor: &str) -> bool {
3269 intrinsic_proto_members(&format!("{ctor}.prototype"))
3270 .is_some_and(|ms| ms.iter().any(|m| m.starts_with('+')))
3271}
3272
3273/// The intrinsic constructor a value's own kind implies — the prototype it
3274/// inherits with no explicit link.
3275pub(crate) fn own_ctor_name(h: &host::JsHost, v: &Value) -> Option<&'static str> {
3276 default_ctor_name(h, v)
3277}
3278
3279/// Whether `ctor.prototype` defines `key` as a NON-WRITABLE data property, so
3280/// an object inheriting it refuses an assignment to that name.
3281pub(crate) fn is_proto_readonly(ctor: &str, key: &str) -> bool {
3282 crate::arity::PROTO_READONLY
3283 .binary_search_by(|(k, _)| (*k).cmp(ctor))
3284 .ok()
3285 .is_some_and(|i| crate::arity::PROTO_READONLY[i].1.contains(&key))
3286}
3287
3288/// Whether `ctor.prototype` defines `key` as an ACCESSOR rather than a data
3289/// property or a method.
3290pub(crate) fn is_proto_accessor(ctor: &str, key: &str) -> bool {
3291 crate::arity::PROTO_ACCESSORS
3292 .binary_search_by(|(k, _)| (*k).cmp(ctor))
3293 .ok()
3294 .is_some_and(|i| crate::arity::PROTO_ACCESSORS[i].1.contains(&key))
3295}
3296
3297/// The constructor whose `.prototype` IS `recv`, whichever of the two
3298/// representations it uses — a `Builtin` namespace handle or a real object.
3299pub(crate) fn intrinsic_proto_of(recv: &Value) -> Option<String> {
3300 with_host(|h| match h.get(recv) {
3301 Some(JsObj::Builtin(ns)) => ns.strip_suffix(".prototype").map(str::to_string),
3302 _ => h.intrinsic_proto_ctor(recv).map(str::to_string),
3303 })
3304}
3305
3306/// The getter function of an intrinsic prototype accessor, as a first-class
3307/// value — what `Object.getOwnPropertyDescriptor(Map.prototype, 'size').get`
3308/// hands back, and the form a library uses to borrow one.
3309fn proto_getter(ctor: &str, key: &str) -> Value {
3310 with_host(|h| h.alloc(JsObj::Builtin(format!("@protoget:{ctor}:{key}"))))
3311}
3312
3313/// Whether `recv` carries the internal slot `ctor`'s accessor demands. This is
3314/// a BRAND check, not a chain walk: `Object.create(Map.prototype).size` throws
3315/// in node even though `Map.prototype` is right there on the chain.
3316fn brand_matches(recv: &Value, ctor: &str) -> bool {
3317 if let Some(tag) = crate::stdlib::native_tag(recv) {
3318 if tag == ctor || (ctor == "TypedArray" && tag == "TypedArray") {
3319 return true;
3320 }
3321 }
3322 match ctor {
3323 "TypedArray" => crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray"),
3324 "ArrayBuffer" => with_host(
3325 |h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@bytes")),
3326 ),
3327 _ => {
3328 let own = match wrapped_primitive(recv).as_ref().and_then(wrapper_ctor_of) {
3329 Some(c) => Some(c),
3330 None => with_host(|h| default_ctor_name(h, recv)),
3331 };
3332 own == Some(ctor)
3333 }
3334 }
3335}
3336
3337thread_local! {
3338 /// The `(ctor, key)` prototype accessors whose tail read is in flight.
3339 ///
3340 /// A getter's last step reads the value off the receiver, and when the
3341 /// receiver does not STORE it that read walks the chain, finds the same
3342 /// accessor and runs it again: `new TextDecoder().fatal` recursed until the
3343 /// stack overflowed and aborted the process. An accessor already in flight
3344 /// answers `undefined` for its own key rather than re-entering — the value
3345 /// a missing internal slot has, and what node reports for one.
3346 static GETTERS_IN_FLIGHT: std::cell::RefCell<Vec<(String, String)>> =
3347 const { std::cell::RefCell::new(Vec::new()) };
3348}
3349
3350/// Whether `ctor`'s `key` getter is already running further down the stack.
3351fn getter_in_flight(ctor: &str, key: &str) -> bool {
3352 GETTERS_IN_FLIGHT.with(|g| g.borrow().iter().any(|(c, k)| c == ctor && k == key))
3353}
3354
3355/// Invoke an intrinsic prototype's getter against `recv` — the body behind the
3356/// `@protoget:` thunks.
3357///
3358/// Reading one OFF THE PROTOTYPE (`Map.prototype.size`) is the case that was
3359/// wrong: it answered `undefined` where node runs the getter, fails the brand
3360/// check and throws. `RegExp.prototype` is the documented exception — 22.2.6.10
3361/// and .13 return `"(?:)"` and `""` for it specifically, so the one receiver
3362/// that would otherwise throw for every flag reads two of them back.
3363pub(crate) fn proto_getter_call(ctor: &str, key: &str, recv: &Value) -> Result<Value, String> {
3364 let is_the_prototype = with_host(
3365 |h| matches!(h.get(recv), Some(JsObj::Builtin(ns)) if *ns == format!("{ctor}.prototype")),
3366 );
3367 if is_the_prototype && ctor == "RegExp" {
3368 // 22.2.6.x each carry the same step: when `this` IS `%RegExp.prototype%`
3369 // the getter returns rather than throwing. `source` and `flags` have
3370 // their own values there; every flag getter answers `undefined`.
3371 return Ok(match key {
3372 "source" => with_host(|h| h.new_str("(?:)".to_string())),
3373 "flags" => with_host(|h| h.new_str(String::new())),
3374 _ => Value::Undef,
3375 });
3376 }
3377 // `RegExp.prototype.flags` (22.2.6.5) is the one that is GENERIC: it reads
3378 // the individual flag properties off whatever object it is handed and
3379 // concatenates their letters, so a plain object answers `""` rather than
3380 // throwing, and one carrying `global`/`ignoreCase` answers `"gi"`.
3381 if ctor == "RegExp" && key == "flags" && !brand_matches(recv, ctor) {
3382 if !with_host(|h| is_object_like(h, recv)) {
3383 return Err(regexp_brand_error(key, recv));
3384 }
3385 let mut out = String::new();
3386 for (prop, letter) in REGEXP_FLAG_LETTERS {
3387 let v = get_property(recv, prop)?;
3388 if with_host(|h| h.truthy(&v)) {
3389 out.push(*letter);
3390 }
3391 }
3392 return Ok(with_host(|h| h.new_str(out)));
3393 }
3394 // `Function.prototype.arguments`/`caller` are POISON PILLS (10.2.4.1): both
3395 // the getter and the setter throw for every receiver, which is how a strict
3396 // function keeps its caller unreachable. They are not brand checks and do
3397 // not name the receiver.
3398 if ctor == "Function" && matches!(key, "arguments" | "caller") {
3399 return poison_pill_read(recv);
3400 }
3401 if !brand_matches(recv, ctor) {
3402 return Err(match ctor {
3403 "RegExp" => regexp_brand_error(key, recv),
3404 "Symbol" => {
3405 host::type_error("Symbol.prototype.description requires that 'this' be a Symbol")
3406 }
3407 _ => host::type_error(&format!(
3408 "Method get {ctor}.prototype.{key} called on incompatible receiver {}",
3409 brand_receiver_string(recv)
3410 )),
3411 });
3412 }
3413 // A native instance keeps an accessor's value in the hidden `@@<key>` slot,
3414 // so that the public name can be a getter on the prototype rather than an
3415 // own enumerable property. Read it straight: the chain walk below would
3416 // find this same accessor and run it again.
3417 if let Some(v) = with_host(|h| match h.get(recv) {
3418 Some(JsObj::Object(p)) => p.get(&format!("@@{key}")).cloned(),
3419 _ => None,
3420 }) {
3421 return Ok(v);
3422 }
3423 GETTERS_IN_FLIGHT.with(|g| g.borrow_mut().push((ctor.to_string(), key.to_string())));
3424 let out = get_property(recv, key);
3425 GETTERS_IN_FLIGHT.with(|g| {
3426 g.borrow_mut().pop();
3427 });
3428 out
3429}
3430
3431/// `Function.prototype.arguments`/`caller` read against `recv`.
3432///
3433/// The pill is conditional and the condition is the RECEIVER, not the reading
3434/// code: a sloppy non-arrow function answers `null` (node stopped populating
3435/// these long ago but kept them readable), and everything else — an arrow, a
3436/// strict function, a non-function — throws. Keying it on the READER's
3437/// strictness, which is what this did, made `strictFn.arguments` answer
3438/// `undefined` from sloppy code and a sloppy function throw from strict code:
3439/// wrong in both directions.
3440pub(crate) fn poison_pill_read(recv: &Value) -> Result<Value, String> {
3441 if with_host(|h| h.fn_is_sloppy(recv)) {
3442 return Ok(with_host(|h| h.null()));
3443 }
3444 Err(host::type_error(POISON_PILL))
3445}
3446
3447/// The message both halves of the `arguments`/`caller` poison pill throw.
3448pub(crate) const POISON_PILL: &str = "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them";
3449
3450/// How a REJECTED receiver is rendered in a brand-check message.
3451///
3452/// `no_side_effects_string` answers for most of them, but two kinds differ:
3453/// an intrinsic PROTOTYPE renders `#<Map>` rather than `[object Map]`, and so
3454/// does an `ArrayBuffer`/`DataView` instance, which this host tags natively and
3455/// that function therefore brands. Node draws the line at whether the value is
3456/// one of the ES5-era classes (`Array`, `Date`, `RegExp` are `[object X]`); the
3457/// two cases here are the ones that fall on the other side of it.
3458fn brand_receiver_string(recv: &Value) -> String {
3459 if let Some(ctor) = intrinsic_proto_of(recv) {
3460 return format!("#<{ctor}>");
3461 }
3462 match crate::stdlib::native_tag(recv).as_deref() {
3463 Some(tag @ ("ArrayBuffer" | "DataView")) => format!("#<{tag}>"),
3464 _ => no_side_effects_string(recv),
3465 }
3466}
3467
3468/// The flag properties `RegExp.prototype.flags` reads, in the order 22.2.6.5
3469/// concatenates their letters.
3470const REGEXP_FLAG_LETTERS: &[(&str, char)] = &[
3471 ("hasIndices", 'd'),
3472 ("global", 'g'),
3473 ("ignoreCase", 'i'),
3474 ("multiline", 'm'),
3475 ("dotAll", 's'),
3476 ("unicode", 'u'),
3477 ("unicodeSets", 'v'),
3478 ("sticky", 'y'),
3479];
3480
3481/// `RegExp.prototype`'s flag getters word their brand failure their own way,
3482/// and `flags` distinguishes a non-object receiver from a non-RegExp one
3483/// because 22.2.6.5 reads the individual flags off any object it is given.
3484fn regexp_brand_error(key: &str, recv: &Value) -> String {
3485 if key == "flags" && !with_host(|h| matches!(recv, Value::Obj(_)) && !h.is_null(recv)) {
3486 return host::type_error(&format!(
3487 "RegExp.prototype.flags getter called on non-object {}",
3488 no_side_effects_string(recv)
3489 ));
3490 }
3491 host::type_error(&format!(
3492 "RegExp.prototype.{key} getter called on non-RegExp object"
3493 ))
3494}
3495
3496/// A property on a builtin namespace object (`Math.PI`, `Number.MAX_SAFE_INTEGER`,
3497/// `console.log`).
3498pub fn namespace_property(ns: &str, name: &str) -> Value {
3499 // `require.cache[id]` — a LIVE view of the module cache, not a copy, so a
3500 // read sees whatever is loaded now and `delete` (see `delete_property`)
3501 // actually invalidates.
3502 if ns == REQUIRE_CACHE {
3503 return crate::module::cache_get(name).unwrap_or(Value::Undef);
3504 }
3505 // A property a SCRIPT assigned onto this namespace wins over everything
3506 // synthesized below, including a member the namespace really has. That is
3507 // what monkey-patching an intrinsic is: `Array.prototype.join = f` must make
3508 // `[1, 2].join()` call `f`, and a polyfill's `Array.prototype.at = impl` has
3509 // to read back at all. Only the two `Error` hooks consulted this table, so
3510 // every other assignment onto a builtin — the whole polyfill idiom — was
3511 // stored by `set_property` and then never read: the write appeared to
3512 // succeed, `Object.isExtensible` said true, and the value came back
3513 // `undefined`.
3514 if let Some(v) = with_host(|h| h.builtin_static(ns, name)) {
3515 return v;
3516 }
3517 // A singleton (`performance`, `crypto`, `crypto.subtle`) reads its methods
3518 // and `constructor` off its class prototype, so `performance.now ===
3519 // Performance.prototype.now` and `crypto.constructor === Crypto`.
3520 if let Some(class) = crate::stdlib::singleton_class(ns) {
3521 if name == "constructor" {
3522 return with_host(|h| h.alloc(JsObj::Builtin(class.into())));
3523 }
3524 if crate::stdlib::instance_method_lists(class)
3525 .0
3526 .contains(&name)
3527 {
3528 return with_host(|h| h.alloc(JsObj::Builtin(format!("@proto:{class}:{name}"))));
3529 }
3530 }
3531 // `os.arch[Symbol.toPrimitive]` (and the other `os` value functions): an
3532 // anonymous function returning the call's result.
3533 if let Some(key) = os_to_primitive_key(ns, name) {
3534 return with_host(|h| h.alloc(JsObj::Builtin(key)));
3535 }
3536 // A core-module function written as an ordinary `function` owns a
3537 // `prototype` (`fs.readFileSync.prototype.constructor === fs.readFileSync`);
3538 // which ones do is measured into `CORE_PROTOTYPED`. One object per
3539 // function, so the read is stable.
3540 if name == "prototype" && core_function_prototyped(ns) {
3541 return core_function_prototype(ns);
3542 }
3543 // `require('timers').setTimeout` IS the global `setTimeout` (and likewise
3544 // the other five); it was a distinct function, so `===` said false.
3545 if ns == "timers"
3546 && matches!(
3547 name,
3548 "setTimeout"
3549 | "setInterval"
3550 | "setImmediate"
3551 | "clearTimeout"
3552 | "clearInterval"
3553 | "clearImmediate"
3554 )
3555 {
3556 return with_host(|h| h.alloc(JsObj::Builtin(name.to_string())));
3557 }
3558 // `fn[util.promisify.custom]` on the builtins node gives a custom
3559 // promisified form (`setTimeout`, `fs.exists`, `child_process.exec`, …):
3560 // the same function `util.promisify(fn)` returns. The read answered
3561 // `undefined` while `promisify` itself knew the form.
3562 if name.starts_with("@@sym:")
3563 && name
3564 == with_host(|h| {
3565 let s = h.symbol_for("nodejs.util.promisify.custom");
3566 h.property_key(&s)
3567 })
3568 {
3569 if let Some(Ok(v)) = crate::stdlib::util::custom_promisified(ns) {
3570 return v;
3571 }
3572 }
3573 // The ENTRY script's `require` is this builtin rather than the per-module
3574 // closure, so its `cache` has to be handed out here too.
3575 // `require.extensions` — the legacy loader map. Deprecated but still read
3576 // (and sometimes written) by tooling that hooks module loading, and it was
3577 // absent entirely. The three keys node ships are present; installing a
3578 // custom loader through them is NOT honoured by this runtime's loader, so
3579 // the map reports what it can serve rather than pretending otherwise.
3580 // `util.promisify.custom` — the registered symbol a module attaches to a
3581 // callback function to supply its own promisified form. It was `undefined`,
3582 // so the lookup that decides whether to use one always missed.
3583 if ns == "util.promisify" && name == "custom" {
3584 return with_host(|h| h.symbol_for("nodejs.util.promisify.custom"));
3585 }
3586 // `util.inspect.custom` — the registered symbol an object implements to
3587 // supply its own `util.inspect` rendering.
3588 if ns == "util.inspect" && name == "custom" {
3589 return with_host(|h| h.symbol_for("nodejs.util.inspect.custom"));
3590 }
3591 // `process.memoryUsage.rss()` — node's fast path for the one figure that
3592 // does not need the whole object built.
3593 if ns == "process.memoryUsage" && name == "rss" {
3594 return with_host(|h| h.alloc(JsObj::Builtin("process.memoryUsage.rss".to_string())));
3595 }
3596 if ns == "require" && name == "extensions" {
3597 return with_host(|h| {
3598 let mut m: IndexMap<String, Value> = IndexMap::new();
3599 for ext in [".js", ".json", ".node"] {
3600 let f = h.alloc(JsObj::Builtin(format!("@@extension:{ext}")));
3601 m.insert(ext.to_string(), f);
3602 }
3603 h.new_object(m)
3604 });
3605 }
3606 // `require.resolve.paths(spec)` — the directories a lookup would search:
3607 // `null` for a core module, the `node_modules` chain otherwise.
3608 if ns == "require.resolve" && name == "paths" {
3609 return with_host(|h| h.alloc(JsObj::Builtin("require.resolve.paths".to_string())));
3610 }
3611 if ns == "require" && name == "cache" {
3612 return with_host(|h| h.alloc(JsObj::Builtin(REQUIRE_CACHE.to_string())));
3613 }
3614 // The legacy numeric codes `DOMException` carries as statics
3615 // (`DOMException.ABORT_ERR` is 20), named by uppercasing the error name.
3616 if ns == "DOMException" {
3617 if let Some((_, code)) = DOM_EXCEPTION_CODES
3618 .iter()
3619 .find(|(n, _)| legacy_code_name(n) == name)
3620 {
3621 return Value::Float(*code);
3622 }
3623 }
3624 // Numeric constants.
3625 if let Some(k) = namespace_constant(ns, name) {
3626 return Value::Float(k);
3627 }
3628 // `Ctor.name` on a builtin constructor is the constructor name (`Array.name`
3629 // === "Array"); non-callable namespaces (`Math`/`JSON`) fall through to
3630 // `undefined`.
3631 // `GeneratorFunction.prototype` and the two async variants are REAL objects
3632 // in `native_protos`, not `Builtin("X.prototype")` namespace handles — they
3633 // sit on the prototype chain of every generator/async function, which a
3634 // handle cannot do. Without this the read fell through to `undefined`.
3635 if name == "prototype"
3636 && matches!(
3637 ns,
3638 "GeneratorFunction" | "AsyncFunction" | "AsyncGeneratorFunction"
3639 )
3640 {
3641 return with_host(|h| {
3642 h.ensure_native_protos();
3643 h.native_proto(ns).unwrap_or(Value::Undef)
3644 });
3645 }
3646 // `Error.prepareStackTrace` has a DEFAULT hook in node
3647 // (`ErrorPrepareStackTrace`), so a library probing `if
3648 // (Error.prepareStackTrace)` finds one. Reading `undefined` sent that probe
3649 // down the wrong branch. The default renders the header plus the frames,
3650 // which is what the fast path in `materialize_stack` already produces — it
3651 // recognises this exact builtin and skips the round trip.
3652 if ns == "Error" && name == "prepareStackTrace" {
3653 return with_host(|h| h.builtin_static("Error", "prepareStackTrace")).unwrap_or_else(
3654 || with_host(|h| h.alloc(JsObj::Builtin(DEFAULT_PREPARE.to_string()))),
3655 );
3656 }
3657 // `Error.stackTraceLimit` defaults to 10 and is settable; an assignment
3658 // lands in the builtin-static side table, which the read below consults
3659 // first. Without a default the READ was `undefined`, so a library doing
3660 // `const old = Error.stackTraceLimit` and restoring it later installed
3661 // `undefined` and disabled the limit permanently.
3662 if ns == "Error" && name == "stackTraceLimit" {
3663 return with_host(|h| h.builtin_static("Error", "stackTraceLimit"))
3664 .unwrap_or(Value::Float(10.0));
3665 }
3666 // `Ctor[Symbol.species]` is an accessor returning `this` on every builtin
3667 // that has one (23.1.2.5, 27.2.4.7, …). It was absent, so the species
3668 // protocol had nothing to read and every derived result came back a plain
3669 // builtin.
3670 if name == "@@species" && has_species(ns) {
3671 return with_host(|h| h.alloc(JsObj::Builtin(ns.to_string())));
3672 }
3673 if name == "name" && is_builtin_ctor(ns) {
3674 return with_host(|h| h.new_str(ns.to_string()));
3675 }
3676 // A well-known symbol (`Symbol.iterator`, `Symbol.toPrimitive`, …) used as a
3677 // computed property/method key.
3678 if ns == "Symbol" && host::WELL_KNOWN_SYMBOLS.contains(&name) {
3679 return with_host(|h| h.well_known_symbol(name));
3680 }
3681 // Non-function constants on a stdlib namespace (`path.sep`, `os.EOL`,
3682 // `buffer.Buffer`, `url.URL`).
3683 if let Some(v) = crate::stdlib::constant(ns, name) {
3684 return v;
3685 }
3686 // `Ctor.prototype` on a builtin constructor (`Object.prototype`,
3687 // `Array.prototype`, …): a prototype namespace whose methods are callable
3688 // thunks (`Object.prototype.toString.call(x)` is a load-time idiom in the
3689 // `get-intrinsic`/`function-bind` family).
3690 if name == "prototype" && is_builtin_ctor(ns) {
3691 // Same reasoning as the native prototypes below, for the error
3692 // hierarchy: `new Error(...)` links its `[[Prototype]]` to the REAL
3693 // `error_protos` object, so `Error.prototype` has to read back that same
3694 // object. It resolved to a fresh `Builtin("Error.prototype")` thunk
3695 // instead, which is a FUNCTION — so `Object.getPrototypeOf(new
3696 // Error("x")) === Error.prototype` was false, and `typeof
3697 // Error.prototype` was `"function"` where node says `"object"`.
3698 if host::ERROR_NAMES.contains(&ns) {
3699 if let Some(p) = with_host(|h| {
3700 h.ensure_error_protos();
3701 host::error_proto_of(h, ns)
3702 }) {
3703 return p;
3704 }
3705 }
3706 // `Buffer`/`Uint8Array` have real prototype *objects* — a Buffer's
3707 // `[[Prototype]]` points at one, so `Object.getPrototypeOf(buf) ===
3708 // Buffer.prototype` must compare equal, which a freshly-allocated
3709 // `Builtin` handle never can.
3710 if let Some(p) = with_host(|h| {
3711 h.ensure_native_protos();
3712 h.native_proto(ns)
3713 }) {
3714 return p;
3715 }
3716 // `EventEmitter.prototype` is the real object every emitter's chain
3717 // reaches, built on the first read rather than on the first emitter,
3718 // so the two reads cannot disagree.
3719 if ns == "EventEmitter" {
3720 if let Some(p) = with_host(|h| h.ensure_ctor_proto(ns)) {
3721 return p;
3722 }
3723 }
3724 let _ = ns;
3725 return with_host(|h| h.alloc(JsObj::Builtin(format!("{ns}.prototype"))));
3726 }
3727 // A NATIVE stdlib constructor's `.prototype` (`StringDecoder`, `Hash`,
3728 // `URLSearchParams`, …). These are absent from `is_builtin_ctor`, so the arm
3729 // above never fired and the read produced `undefined` — which broke the ES5
3730 // subclassing pattern libraries still ship. `iconv-lite`'s internal codec
3731 // reads `StringDecoder.prototype.end` at load, and threw
3732 // `Cannot read properties of undefined (reading 'end')`. Built from the same
3733 // instance-method table a method read consults, so the two cannot disagree.
3734 if name == "prototype" {
3735 if let Some(p) = with_host(|h| h.ensure_ctor_proto(ns)) {
3736 return p;
3737 }
3738 }
3739 // A method read off a builtin prototype namespace (`Array.prototype.slice`):
3740 // a `@proto:<Ctor>:<method>` thunk that, when invoked (typically via
3741 // `.call`/`.apply`), dispatches `method` against the invoke-time `this`.
3742 //
3743 // The thunk is minted only for a name the prototype REALLY carries. Minting
3744 // one unconditionally made every absent name answer with a function:
3745 // `Array.prototype.totallyBogus` was `[Function: totallyBogus]` where node
3746 // says `undefined`, and so was every well-known symbol a prototype does not
3747 // define — `Array.prototype[Symbol.toStringTag]` came back a function
3748 // instead of `undefined`, which is a value `Object.prototype.toString` and
3749 // every `typeof`/truthiness test downstream then read wrong.
3750 //
3751 // Existence is decided by the generated intrinsic table, which is read out
3752 // of the reference engine, so this cannot drift from what node defines.
3753 // A name the prototype does not define but `Object.prototype` does is
3754 // INHERITED, and node hands back Object.prototype's own function object
3755 // (`Map.prototype.toString === Object.prototype.toString` is `true`), so it
3756 // resolves to the `Object` thunk rather than a per-ctor one. That is also
3757 // what makes `String(Map.prototype)` print `[object Map]`: `Map.prototype`
3758 // has no own `toString`, and the inherited one is the generic tag reader,
3759 // not a Map method that rejects a non-Map `this`.
3760 if let Some(ctor) = ns.strip_suffix(".prototype") {
3761 // `Array.prototype[Symbol.unscopables]` (23.1.3.38) is a DATA property,
3762 // not an intrinsic function, so it is not in the arity table the lookup
3763 // above consults. It lists the methods a `with` block must NOT bring
3764 // into scope — the ones added after `with` existed, so old code using a
3765 // variable of the same name keeps working.
3766 if name == "@@unscopables" && ctor == "Array" {
3767 return with_host(|h| {
3768 let mut m: IndexMap<String, Value> = IndexMap::new();
3769 for k in [
3770 "at",
3771 "copyWithin",
3772 "entries",
3773 "fill",
3774 "find",
3775 "findIndex",
3776 "findLast",
3777 "findLastIndex",
3778 "flat",
3779 "flatMap",
3780 "includes",
3781 "keys",
3782 "toReversed",
3783 "toSorted",
3784 "toSpliced",
3785 "values",
3786 ] {
3787 m.insert(k.to_string(), Value::Bool(true));
3788 }
3789 let o = h.new_object(m);
3790 let null = h.null();
3791 h.set_proto(&o, null);
3792 o
3793 });
3794 }
3795 if builtin_meta(&format!("@proto:{ctor}:{name}")).is_some() {
3796 return with_host(|h| h.alloc(JsObj::Builtin(format!("@proto:{ctor}:{name}"))));
3797 }
3798 if ctor != "Object" && builtin_meta(&format!("@proto:Object:{name}")).is_some() {
3799 return with_host(|h| h.alloc(JsObj::Builtin(format!("@proto:Object:{name}"))));
3800 }
3801 // `constructor` is excluded from the table because it is not a method:
3802 // it is the constructor function itself, and node compares equal
3803 // (`Array.prototype.constructor === Array`). It used to resolve to a
3804 // `@proto:Array:constructor` thunk, which is a different object every
3805 // read and so never compared equal to anything.
3806 if name == "constructor" && is_builtin_ctor(ctor) {
3807 return with_host(|h| h.alloc(JsObj::Builtin(ctor.to_string())));
3808 }
3809 return Value::Undef;
3810 }
3811 // `querystring.encode`/`decode` are not copies of `stringify`/`parse` but
3812 // the same functions (`qs.encode === qs.stringify`, and its `.name` is
3813 // `stringify`), so they resolve to the one builtin.
3814 let name = match (ns, name) {
3815 ("querystring", "encode") => "stringify",
3816 ("querystring", "decode") => "parse",
3817 _ => name,
3818 };
3819 let qualified = format!("{ns}.{name}");
3820 if is_known_builtin(&qualified) {
3821 return with_host(|h| h.alloc(JsObj::Builtin(qualified)));
3822 }
3823 // A property the user stuck on this builtin namespace (`Error.prepareStackTrace`).
3824 if let Some(v) = with_host(|h| h.builtin_static(ns, name)) {
3825 return v;
3826 }
3827 // A builtin FUNCTION's own `name` and `length` (10.3.3-4: every one has
3828 // both). `Math.max.name` was `undefined` — as was every `.name` a library
3829 // reads to identify a callback it was handed. The non-callable namespaces
3830 // fall through: `Math.name` and `require('fs').length` really are undefined.
3831 if host::builtin_is_callable(ns) {
3832 match name {
3833 "name" => {
3834 if let Some(n) = proto_getter_name(ns) {
3835 return with_host(|h| h.new_str(n));
3836 }
3837 return with_host(|h| h.new_str(builtin_name(ns).to_string()));
3838 }
3839 // Only the intrinsics have a specified arity; a core-module
3840 // function's is a property of node's own JS source, so it stays
3841 // `undefined` rather than being invented here.
3842 "length" => {
3843 // A getter takes no argument (10.2.9 / the accessor grammar),
3844 // so its `length` is 0 — it is not in the intrinsic table,
3845 // which holds only named functions.
3846 if proto_getter_name(ns).is_some() {
3847 return Value::Float(0.0);
3848 }
3849 if let Some((_, len)) = builtin_meta(ns) {
3850 return Value::Float(len as f64);
3851 }
3852 }
3853 _ => {}
3854 }
3855 }
3856 Value::Undef
3857}
3858
3859/// Dispatch a `@proto:<Ctor>:<method>` thunk (a method read off a builtin
3860/// prototype, e.g. `Object.prototype.toString`) against `recv` (its invoke-time
3861/// `this`). `Object.prototype.toString` yields the `[object Tag]` brand string
3862/// libraries type-check on; every other method routes through normal method
3863/// dispatch on `recv`.
3864/// The TypeError a `<Ctor>.prototype.<method>` thunk throws when it is invoked
3865/// with NO receiver — `const f = [].push; f(1)`.
3866///
3867/// Reading a method off an instance used to mint a thunk bound to that
3868/// instance, so a detached method silently kept working on the object it came
3869/// from. Now that it is the shared intrinsic, a bare call has no `this` and has
3870/// to say so. Node words it four ways, and which one a method gets is not
3871/// something that can be derived — the split was measured across every method
3872/// of each prototype:
3873///
3874/// ```text
3875/// ToObject(this) "Cannot convert undefined or null to object"
3876/// RequireObjectCoercible "<Ctor>.prototype.<m> called on null or undefined"
3877/// brand check "<Ctor>.prototype.<m> requires that 'this' be a <X>"
3878/// everything else the generic incompatible-receiver message
3879/// ```
3880fn nullish_receiver_error(ctor: &str, method: &str, recv: &str) -> Option<String> {
3881 // `Array.prototype` splits: the CALLBACK-taking methods plus `concat` and
3882 // the two `indexOf` family members name themselves, the rest go through
3883 // `ToObject` and report its message.
3884 const ARRAY_NAMED: &[&str] = &[
3885 "concat",
3886 "every",
3887 "filter",
3888 "find",
3889 "findIndex",
3890 "findLast",
3891 "findLastIndex",
3892 "forEach",
3893 "indexOf",
3894 "map",
3895 "reduce",
3896 "reduceRight",
3897 "some",
3898 ];
3899 const TO_OBJECT: &str = "Cannot convert undefined or null to object";
3900 let named = |c: &str| format!("{c}.prototype.{method} called on null or undefined");
3901 let branded =
3902 |c: &str, want: &str| format!("{c}.prototype.{method} requires that 'this' be a {want}");
3903 // The generic form names the receiver, so a `null` one must not be reported
3904 // as `undefined`.
3905 let generic = |c: &str, m: &str| {
3906 format!("Method {c}.prototype.{m} called on incompatible receiver {recv}")
3907 };
3908 Some(match ctor {
3909 "Array" if ARRAY_NAMED.contains(&method) => named("Array"),
3910 "Array" => TO_OBJECT.to_string(),
3911 // `Object.prototype.toString` is the one method that ACCEPTS a nullish
3912 // receiver — it answers `[object Undefined]`.
3913 "Object" if method == "toString" => return None,
3914 "Object" if method == "toLocaleString" => named("Object"),
3915 "Object" => TO_OBJECT.to_string(),
3916 // Both aliases report the LEGACY name in the message, which is the one
3917 // place `name` and the message disagree.
3918 "String" if method == "trimStart" => named("String").replace("trimStart", "trimLeft"),
3919 "String" if method == "trimEnd" => named("String").replace("trimEnd", "trimRight"),
3920 "String" if matches!(method, "toString" | "valueOf") => branded("String", "String"),
3921 "String" if method == "@@iterator" => {
3922 "String.prototype[Symbol.iterator] called on null or undefined".to_string()
3923 }
3924 "String" => named("String"),
3925 "Number" => branded("Number", "Number"),
3926 "Boolean" => branded("Boolean", "Boolean"),
3927 "Symbol" => branded("Symbol", "Symbol"),
3928 "Function" if method == "bind" => "Bind must be called on a function".to_string(),
3929 "Function" if matches!(method, "call" | "apply") => format!(
3930 "Function.prototype.{method} was called on {recv}, which is {recv} and not a function"
3931 ),
3932 "Function" => branded("Function", "Function"),
3933 // `Promise.prototype.catch`/`finally` are written in terms of `then`, so
3934 // a nullish receiver fails inside them and reports that instead.
3935 "Promise" if method == "catch" => {
3936 "Cannot read properties of undefined (reading 'then')".to_string()
3937 }
3938 "Promise" if method == "finally" => {
3939 "Promise.prototype.finally called on non-object".to_string()
3940 }
3941 "Date" if method == "toJSON" => TO_OBJECT.to_string(),
3942 // The plain GETTERS and `valueOf` read `[[DateValue]]` directly and
3943 // report that slot check; every setter, every `to*String` and the two
3944 // legacy year methods go through the generic receiver check first.
3945 "Date" if method == "valueOf" || (method.starts_with("get") && method != "getYear") => {
3946 "this is not a Date object.".to_string()
3947 }
3948 // An ALIAS reports the method it aliases: `toGMTString` IS `toUTCString`
3949 // and `Set.prototype.keys` IS `values`, one function object each.
3950 "Date" if method == "toGMTString" => generic("Date", "toUTCString"),
3951 // V8 names this symbol-keyed builtin in brackets.
3952 "Date" if method == "@@toPrimitive" => format!(
3953 "Method Date.prototype [ @@toPrimitive ] called on incompatible receiver {recv}"
3954 ),
3955 "Set" if method == "keys" => generic("Set", "values"),
3956 // Everything else that is brand-checked names itself. Node reaches this
3957 // wording from a `[[GetOwnProperty]]`-style slot check; here the check
3958 // is the receiver's kind, and only the message has to agree.
3959 "ArrayBuffer" | "DataView" | "RegExp" | "WeakRef" | "Map" | "Set" | "WeakMap"
3960 | "WeakSet" | "Promise" | "Date" => generic(ctor, method),
3961 "URLSearchParams" => "Value of \"this\" must be of type URLSearchParams".to_string(),
3962 // Node's `URL` methods fail while reaching for their internal state, and
3963 // report the read that failed rather than the method.
3964 "URL" => "Cannot read properties of undefined (reading 'URL')".to_string(),
3965 _ => return None,
3966 })
3967}
3968
3969/// Whether `<ctor>.prototype.<method>` begins with a `this<Type>Value` brand
3970/// check (21.1.3, 20.3.3, 22.1.3.29/.35, 21.2.3). Every `Number.prototype`
3971/// method does; of `String.prototype` only `toString`/`valueOf` do — the rest
3972/// are generic and coerce their receiver with `ToString`.
3973fn is_brand_checked_primitive_method(ctor: &str, method: &str) -> bool {
3974 match ctor {
3975 "Number" => matches!(
3976 method,
3977 "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision"
3978 ),
3979 "BigInt" => matches!(method, "toString" | "toLocaleString" | "valueOf"),
3980 "String" | "Boolean" => matches!(method, "toString" | "valueOf"),
3981 _ => false,
3982 }
3983}
3984
3985/// `this<Type>Value(recv)` for `ctor` ∈ Number/String/Boolean/BigInt: the
3986/// primitive itself, the primitive a wrapper boxes, or — for the three
3987/// prototypes that are themselves wrappers (21.1.3, 22.1.3, 20.3.3) — the
3988/// prototype's own `+0` / `""` / `false`. `None` is the TypeError case.
3989fn this_primitive_value(ctor: &str, recv: &Value) -> Option<Value> {
3990 let expected = match ctor {
3991 "Number" => "number",
3992 "String" => "string",
3993 "Boolean" => "boolean",
3994 "BigInt" => "bigint",
3995 _ => return None,
3996 };
3997 let is_expected = |v: &Value| with_host(|h| h.type_of(v)) == expected;
3998 if is_expected(recv) {
3999 return Some(recv.clone());
4000 }
4001 if let Some(prim) = wrapped_primitive(recv).filter(is_expected) {
4002 return Some(prim);
4003 }
4004 if with_host(|h| h.intrinsic_proto_ctor(recv) == Some(ctor)) {
4005 return match ctor {
4006 "Number" => Some(Value::Float(0.0)),
4007 "String" => Some(with_host(|h| h.new_str(""))),
4008 "Boolean" => Some(Value::Bool(false)),
4009 _ => None,
4010 };
4011 }
4012 None
4013}
4014
4015/// The methods of `%GeneratorPrototype%`, `%AsyncGeneratorPrototype%` and
4016/// `%AsyncIteratorPrototype%` (installed by `ensure_generator_protos`), called
4017/// through the prototype rather than off a generator: a matching generator
4018/// runs the method; anything else is V8's incompatible-receiver TypeError,
4019/// which the async form REJECTS with (27.6.3.3 `AsyncGeneratorValidate`).
4020fn generator_proto_method(
4021 recv: &Value,
4022 ctor: &str,
4023 method: &str,
4024 args: &[Value],
4025) -> Option<Result<Value, String>> {
4026 match (ctor, method) {
4027 // 27.1.4.13 `%Iterator.prototype%[@@iterator]`: return `this`. Routing
4028 // an ordinary receiver back through `call_method` found this thunk
4029 // on its chain again and overflowed the stack.
4030 ("Iterator", "@@iterator") => Some(Ok(recv.clone())),
4031 // The helpers are generic over any receiver with a `next`; the same
4032 // re-dispatch would find them on the chain again.
4033 ("Iterator", m) if crate::stdlib::iterator::is_helper(m) => {
4034 Some(crate::stdlib::iterator::call(recv, m, args))
4035 }
4036 ("AsyncIterator", "@@asyncIterator") => Some(Ok(recv.clone())),
4037 // 27.1.3.1: call `this.return()` if there is one, and settle with
4038 // `undefined` once its result does.
4039 ("AsyncIterator", "@@asyncDispose") => Some(async_iterator_dispose(recv)),
4040 ("Generator" | "AsyncGenerator", "next" | "return" | "throw") => {
4041 let is_async = ctor == "AsyncGenerator";
4042 let ok =
4043 with_host(|h| h.is_generator_val(recv) && h.is_async_gen_val(recv) == is_async);
4044 if ok {
4045 return Some(host::call_method(recv, method, args.to_vec()));
4046 }
4047 let err = host::type_error(&format!(
4048 "Method [{ctor}].prototype.{method} called on incompatible receiver {}",
4049 no_side_effects_string(recv)
4050 ));
4051 if !is_async {
4052 return Some(Err(err));
4053 }
4054 let reason = with_host(|h| synth_error(h, &err));
4055 let p = with_host(|h| h.new_promise());
4056 if let Some(id) = with_host(|h| h.promise_id(&p)) {
4057 host::reject_promise_val(id, reason);
4058 }
4059 Some(Ok(p))
4060 }
4061 _ => None,
4062 }
4063}
4064
4065/// `next` of the built-in iterator prototypes (`ensure_iterator_protos`),
4066/// called through the prototype: an iterator of that kind steps; anything
4067/// else is V8's incompatible-receiver TypeError, which names the prototype by
4068/// its tag (and `%RegExpStringIterator%` by its intrinsic name).
4069fn iterator_proto_next(
4070 recv: &Value,
4071 ctor: &str,
4072 method: &str,
4073 args: &[Value],
4074) -> Option<Result<Value, String>> {
4075 let (_, tag) = host::ITERATOR_PROTOS.iter().find(|(k, _)| *k == ctor)?;
4076 if method != "next" {
4077 return None;
4078 }
4079 if with_host(|h| h.iterator_proto_key(recv)) == Some(ctor) {
4080 // Stepped directly: dispatching `next` by name would find this very
4081 // thunk on the chain again.
4082 return Some(match ctor {
4083 "MapIterator" | "SetIterator" => collection_iterator_next(recv),
4084 _ => iter_method(recv, "next", args.to_vec()),
4085 });
4086 }
4087 let label = if ctor == "RegExpStringIterator" {
4088 "%RegExpStringIterator%"
4089 } else {
4090 tag
4091 };
4092 Some(Err(host::type_error(&format!(
4093 "Method {label}.prototype.next called on incompatible receiver {}",
4094 no_side_effects_string(recv)
4095 ))))
4096}
4097
4098/// `%AsyncIteratorPrototype%[@@asyncDispose]()`.
4099fn async_iterator_dispose(recv: &Value) -> Result<Value, String> {
4100 let reject = |e: &str| {
4101 let p = with_host(|h| h.new_promise());
4102 if let Some(id) = with_host(|h| h.promise_id(&p)) {
4103 host::reject_promise_val(id, host::take_exc_or_error(e));
4104 }
4105 Ok(p)
4106 };
4107 let ret = match get_property(recv, "return") {
4108 Ok(r) => r,
4109 Err(e) => return reject(&e),
4110 };
4111 if with_host(|h| h.is_nullish(&ret)) {
4112 return Ok(host::promise_of(&Value::Undef));
4113 }
4114 let result = match host::invoke(&ret, Vec::new(), Some(recv.clone())) {
4115 Ok(r) => r,
4116 Err(e) => return reject(&e),
4117 };
4118 // `@@pnoop` answers `undefined`, the value the dispose settles with.
4119 let to_undef = make_builtin("@@pnoop".to_string());
4120 host::call_method(&host::promise_of(&result), "then", vec![to_undef])
4121}
4122
4123pub fn proto_method(recv: &Value, ctor_method: &str, args: Vec<Value>) -> Result<Value, String> {
4124 let (ctor, method) = ctor_method.split_once(':').unwrap_or(("", ctor_method));
4125 // A prototype slot that holds ANOTHER method's function object (24.1.3.12,
4126 // 24.2.3.8, 24.2.3.10: `Map.prototype[@@iterator]` is `entries`,
4127 // `Set.prototype.keys` and `[@@iterator]` are `values`) runs, and fails its
4128 // brand check, under that method's name.
4129 let method = match (ctor, method) {
4130 ("Set", "keys" | "@@iterator") => "values",
4131 ("Map", "@@iterator") => "entries",
4132 _ => method,
4133 };
4134 if let Some(r) = generator_proto_method(recv, ctor, method, &args) {
4135 return r;
4136 }
4137 if let Some(r) = iterator_proto_next(recv, ctor, method, &args) {
4138 return r;
4139 }
4140 // A prototype ACCESSOR installed by `ensure_ctor_proto`: it reads or writes
4141 // the instance's hidden `@@<name>` slot, which is where the value lives now
4142 // that the public name is a getter rather than an own property.
4143 if let Some(key) = method.strip_prefix("@get@") {
4144 if let Some(v) = with_host(|h| match h.get(recv) {
4145 Some(JsObj::Object(p)) => p.get(&format!("@@{key}")).cloned(),
4146 _ => None,
4147 }) {
4148 return Ok(v);
4149 }
4150 // No stored slot: the value is COMPUTED, so ask the class. `KeyObject`'s
4151 // `symmetricKeySize` is the secret's byte length, which nothing stores.
4152 let tag = crate::stdlib::native_tag(recv).unwrap_or_default();
4153 // A singleton's accessor (`crypto.subtle` read through
4154 // `Crypto.prototype`) answers what the namespace holds.
4155 if let Some(JsObj::Builtin(ns)) = with_host(|h| h.get(recv).cloned()) {
4156 if crate::stdlib::singleton_class(&ns) == Some(ctor) {
4157 // The namespace's own constant, not a property read: a read
4158 // would find this very getter on the prototype again.
4159 return Ok(crate::stdlib::constant(&ns, key).unwrap_or(Value::Undef));
4160 }
4161 }
4162 if tag != ctor && crate::stdlib::brand_checked_class(ctor) {
4163 return Err(host::coded_error(
4164 "TypeError",
4165 "ERR_INVALID_THIS",
4166 &format!("Value of \"this\" must be of type {ctor}"),
4167 ));
4168 }
4169 return crate::stdlib::instance_call(&tag, recv, method, args);
4170 }
4171 if let Some(key) = method.strip_prefix("@set@") {
4172 let v = args.first().cloned().unwrap_or(Value::Undef);
4173 // A setter that is a VERB rather than a stored value (`url.href = …`
4174 // reparses, `event.cancelBubble = true` stops propagation) skips the
4175 // slot write.
4176 if ctor == "URL" || ctor == "Event" {
4177 crate::stdlib::instance_accessor_written(ctor, key, recv, &v)?;
4178 return Ok(Value::Undef);
4179 }
4180 with_host(|h| {
4181 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
4182 p.insert(format!("@@{key}"), v.clone());
4183 }
4184 });
4185 crate::stdlib::instance_accessor_written(ctor, key, recv, &v)?;
4186 return Ok(Value::Undef);
4187 }
4188 // `Function.prototype[Symbol.hasInstance](V)` is OrdinaryHasInstance(this,
4189 // V): the prototype walk alone, never the receiver's own `@@hasInstance`.
4190 if ctor == "Function" && method == "@@hasInstance" {
4191 let obj = arg0(&args);
4192 return Ok(Value::Bool(host::ordinary_has_instance(&obj, recv, false)?));
4193 }
4194 if with_host(|h| h.is_nullish(recv)) {
4195 let shown = if with_host(|h| h.is_null(recv)) {
4196 "null"
4197 } else {
4198 "undefined"
4199 };
4200 if let Some(msg) = nullish_receiver_error(ctor, method, shown) {
4201 return Err(format!("TypeError: {msg}"));
4202 }
4203 }
4204 // `Function.prototype.call`/`apply`/`bind`/`toString` reached with a
4205 // receiver that is not callable — `Function.prototype.call.call(1)`, or a
4206 // borrowed `call` applied to a plain object. Each starts with an
4207 // `IsCallable(this)` check and V8 words the failure per method, naming
4208 // the receiver the side-effect-free way and its type by `typeof` (with
4209 // `null` for null). Falling through dispatched `call` ON the receiver and
4210 // reported the method missing instead.
4211 if ctor == "Function"
4212 && matches!(method, "call" | "apply" | "bind" | "toString")
4213 && !with_host(|h| host::is_callable(h, recv))
4214 {
4215 let msg = match method {
4216 "bind" => "Bind must be called on a function".to_string(),
4217 "toString" => {
4218 "Function.prototype.toString requires that 'this' be a Function".to_string()
4219 }
4220 _ => {
4221 let kind = with_host(|h| {
4222 if h.is_null(recv) {
4223 "null"
4224 } else {
4225 h.type_of(recv)
4226 }
4227 });
4228 let kind = match kind {
4229 "object" => "an object".to_string(),
4230 "null" | "undefined" => kind.to_string(),
4231 other => format!("a {other}"),
4232 };
4233 format!(
4234 "Function.prototype.{method} was called on {}, which is {kind} and not a function",
4235 no_side_effects_string(recv)
4236 )
4237 }
4238 };
4239 return Err(host::type_error(&msg));
4240 }
4241 // `Error.prototype.toString` (20.5.3.4): `name`, `message`, or `name:
4242 // message`, read off the chain so a subclass's `this.name = 'E'` is honored.
4243 if ctor == "Error" && method == "toString" {
4244 // A `DOMException` keeps its `name`/`message` in internal slots, so the
4245 // chain read below would find the class name on the prototype instead.
4246 if let Some(n) = dom_exception_slot(recv, "name") {
4247 let name = with_host(|h| h.str_of(&n));
4248 let msg = dom_exception_slot(recv, "message")
4249 .map(|m| with_host(|h| h.str_of(&m)))
4250 .unwrap_or_default();
4251 let s = if msg.is_empty() {
4252 name
4253 } else {
4254 format!("{name}: {msg}")
4255 };
4256 return Ok(with_host(|h| h.new_str(s)));
4257 }
4258 // `name` and `message` are read with `[[Get]]` (20.5.3.4 steps 3 and 5),
4259 // so a PROXY supplies them through its `get` trap. Reading the stored
4260 // ones first made `String(new Proxy(err, handler))` ignore the handler.
4261 let via_proxy = with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy);
4262 let stored = (!via_proxy).then(|| with_host(|h| h.error_to_string(recv)));
4263 let s = match stored.flatten() {
4264 Some(s) => s,
4265 None => {
4266 let read = |k: &str| -> Result<Option<String>, String> {
4267 Ok(host::protocol_lookup(recv, k)?.map(|v| with_host(|h| h.str_of(&v))))
4268 };
4269 let name = read("name")?.unwrap_or_else(|| "Error".into());
4270 let msg = read("message")?.unwrap_or_default();
4271 if msg.is_empty() {
4272 name
4273 } else {
4274 format!("{name}: {msg}")
4275 }
4276 }
4277 };
4278 return Ok(with_host(|h| h.new_str(s)));
4279 }
4280 // The methods that read their receiver through `thisNumberValue` /
4281 // `thisBooleanValue` / `thisStringValue` / `thisBigIntValue` accept only the
4282 // primitive, its wrapper, or the prototype object (which carries the zero
4283 // value) — anything else is a TypeError naming the method. Unchecked,
4284 // `Number.prototype.valueOf.call({})` answered `{}`, `toFixed.call({})`
4285 // reported "toFixed is not a function", and `Number.prototype.valueOf()`
4286 // recursed through the generic conversion until the stack overflowed.
4287 if is_brand_checked_primitive_method(ctor, method) {
4288 let Some(prim) = this_primitive_value(ctor, recv) else {
4289 return Err(format!(
4290 "TypeError: {ctor}.prototype.{method} requires that 'this' be a {ctor}"
4291 ));
4292 };
4293 return host::call_method(&prim, method, args);
4294 }
4295 // A primitive wrapper's `toString`/`valueOf`/`toLocaleString`: unwrap and
4296 // answer as the boxed primitive does. `Number.prototype.toString.call(5)`
4297 // arrives with an already-primitive receiver and needs no unwrapping.
4298 if matches!(ctor, "String" | "Number" | "Boolean") {
4299 let prim = wrapped_primitive(recv).unwrap_or_else(|| recv.clone());
4300 // Every other `String.prototype` method is GENERIC: it starts with
4301 // `ToString(RequireObjectCoercible(this))` (22.1.3), and a nullish
4302 // receiver was refused above. Handing a number or an object straight to
4303 // `call_method` looked the method up on THAT type instead, so
4304 // `String.prototype.trim.call(12)` reported `trim is not a function`.
4305 if ctor == "String" && with_host(|h| h.as_str(&prim).is_none()) {
4306 let s = host::to_string_value(&prim)?;
4307 return host::call_method(&s, method, args);
4308 }
4309 return host::call_method(&prim, method, args);
4310 }
4311 // `thisSymbolValue`/`thisBigIntValue` (20.4.3, 21.2.3) accept a WRAPPER as
4312 // readily as the primitive, and neither was unwrapped here. A BigInt
4313 // wrapper's `valueOf` therefore re-entered the generic conversion, which
4314 // looked `valueOf` up again and called it again: `+Object(9n)` recursed
4315 // until the stack overflowed and ABORTED the process, which no try/catch can
4316 // see. A Symbol wrapper failed the brand check below instead and reported
4317 // that `this` was not a Symbol, when it is one. Only a real wrapper is
4318 // unwrapped — `Symbol.prototype` itself boxes nothing and still has to reach
4319 // the brand check.
4320 if matches!(ctor, "Symbol" | "BigInt") {
4321 if let Some(prim) = wrapped_primitive(recv) {
4322 return host::call_method(&prim, method, args);
4323 }
4324 }
4325 if ctor == "Object" && method == "toString" {
4326 // Steps 16-17 of 20.1.3.6: a `Symbol.toStringTag` STRING on the receiver
4327 // (own or inherited, data property or getter) replaces the builtin brand,
4328 // which is how a class advertises its own (`class C { get
4329 // [Symbol.toStringTag]() { return 'Cee' } }` → `[object Cee]`). The read
4330 // runs outside the host borrow so an accessor can be invoked.
4331 // A Proxy has no chain to probe: 20.1.3.6 step 15 is an unconditional
4332 // `Get(O, @@toStringTag)`, so the `get` trap decides. Probing first (as
4333 // the ordinary receiver does, to keep the read off objects that have no
4334 // tag) would always miss and brand every tagged proxy `[object Object]`.
4335 crate::proxy::require_live(recv, "Object.prototype.toString")?;
4336 if let Some(s) = to_string_tag(recv)? {
4337 return Ok(with_host(|h| h.new_str(format!("[object {s}]"))));
4338 }
4339 return Ok(with_host(|h| h.new_str(object_tag(h, recv))));
4340 }
4341 // These thunks now live on the real `Object.prototype` object, i.e. on the
4342 // receiver's own chain — routing back through `call_method` would re-resolve
4343 // this very thunk and recurse.
4344 if ctor == "Object" && is_object_builtin_method(method) {
4345 return object_builtin_method(recv, method, args);
4346 }
4347 // `EventEmitter.prototype.<m>` mixed onto a receiver (express's `app`): run the
4348 // emitter method directly against `recv` (routing back through `call_method`
4349 // would re-resolve the mixed-in thunk and recurse).
4350 if ctor == "EventEmitter" {
4351 return crate::stdlib::events::instance_call(recv, method, args);
4352 }
4353 // Same recursion hazard for the exotics with a real prototype object: the
4354 // thunk now lives ON the receiver's prototype chain, so `call_method` would
4355 // re-resolve this very thunk. Dispatch straight to the native instance
4356 // implementation when the receiver is in fact an instance of `ctor`.
4357 if ctor == "Buffer" && crate::stdlib::native_tag(recv).as_deref() == Some("Buffer") {
4358 return crate::stdlib::buffer::instance_call(recv, method, &args);
4359 }
4360 // The shared typed-array methods now live on the `%TypedArray%.prototype`
4361 // intermediate, so their thunks are tagged `TypedArray`; `Uint8Array` still
4362 // appears for anything read directly off `Uint8Array.prototype`. Both
4363 // dispatch the same way, and both must bypass `call_method` or the thunk
4364 // would re-resolve itself off the receiver's chain and recurse.
4365 if ctor == "Uint8Array" || ctor == "TypedArray" {
4366 match crate::stdlib::native_tag(recv).as_deref() {
4367 Some("Buffer") => return crate::stdlib::buffer::instance_call(recv, method, &args),
4368 Some("TypedArray") => {
4369 return crate::stdlib::typedarray::instance_call(recv, method, &args)
4370 }
4371 _ => {}
4372 }
4373 }
4374 // `Array.prototype.<m>.call(arrayLike)` — every `Array.prototype` method is
4375 // GENERIC over `this` (23.1.3: each starts with `ToObject(this)` and
4376 // `LengthOfArrayLike`), which is what makes
4377 // `Array.prototype.slice.call(arguments)` the idiom it is. The receiver here
4378 // is not an Array, so `call_method` would report the method missing.
4379 if ctor == "Array" && with_host(|h| h.kind_of(recv)) != Some(ObjKind::Array) {
4380 // `toString` is generic over `join`, not over the elements: copying an
4381 // array-like into a temporary Array would lose the receiver's own `join`.
4382 if method == "toString" {
4383 return array_to_string(recv);
4384 }
4385 // The iterator factories copy nothing: the iterator they return reads
4386 // `length` and each index off the receiver at every step (23.1.5.1).
4387 let kind = match method {
4388 "keys" => Some(host::ArrayIterKind::Keys),
4389 "values" | "@@iterator" => Some(host::ArrayIterKind::Values),
4390 "entries" => Some(host::ArrayIterKind::Entries),
4391 _ => None,
4392 };
4393 if let Some(kind) = kind {
4394 return Ok(array_iterator(recv, kind));
4395 }
4396 return array_generic(recv, method, args);
4397 }
4398 // The general form of the two special cases above: a thunk taken off a native
4399 // constructor's real prototype, invoked with a receiver that IS an instance of
4400 // that constructor. Routing back through `call_method` would re-resolve this
4401 // very thunk off the receiver's own chain and recurse forever, which is why
4402 // each such prototype needed a hand-written bypass; now they all have one.
4403 // A SUBCLASS counts: `SecretKeyObject` reaches `KeyObject.prototype.equals`
4404 // through its chain, and requiring an exact tag match sent that call back
4405 // into `call_method`, which re-resolved this same thunk and recursed until
4406 // the stack overflowed.
4407 if let Some(tag) = crate::stdlib::native_tag(recv) {
4408 let mut c = Some(tag.as_str());
4409 while let Some(t) = c {
4410 if t == ctor {
4411 return crate::stdlib::instance_call(&tag, recv, method, args);
4412 }
4413 c = crate::stdlib::native_parent(t);
4414 }
4415 }
4416 // The `Event` / `EventTarget` methods are branded too: `Event.prototype
4417 // .preventDefault.call({})` is `TypeError [ERR_INVALID_THIS]`, which the
4418 // module's own dispatcher raises for a receiver that is not an instance.
4419 if matches!(ctor, "Event" | "EventTarget") {
4420 return crate::stdlib::event_target::instance_call(ctor, recv, method, &args);
4421 }
4422 // A BRANDED method reached with a receiver that has no such internal slot.
4423 // Every arm above dispatches a receiver that IS an instance, so arriving
4424 // here with one of these constructors means the brand check failed — the
4425 // spec's very first step for each of them (24.2.3.x reads `[[SetData]]`,
4426 // 24.1.3.x `[[MapData]]`, 27.2.5.4 `[[PromiseState]]`, 23.2.3.x
4427 // `ValidateTypedArray`). Falling through to ordinary dispatch reported
4428 // `union is not a function`, which says the method does not exist rather
4429 // than that the receiver is the wrong kind of object.
4430 // `Date.prototype`'s methods split in two: the ones that read the time value
4431 // (`ThisTimeValue`, 21.4.4.x) report `this is not a Date object.`, and the
4432 // rest take the ordinary branded form. Measured on node v26.8.1:
4433 // `Date.prototype.getTime.call({})` is the first, `.toISOString.call({})`
4434 // and `.setHours.call({})` the second.
4435 // `RegExp.prototype.test` and `toString` are generic over any object
4436 // (22.2.6.16-17); `exec`, `compile` and the rest need a real RegExp.
4437 if ctor == "RegExp" && with_host(|h| h.kind_of(recv)) != Some(ObjKind::RegExp) {
4438 let object = with_host(|h| is_object_like(h, recv));
4439 return match method {
4440 "test" if object => crate::regexp::regexp_test_generic(
4441 recv,
4442 &args.first().cloned().unwrap_or(Value::Undef),
4443 ),
4444 "toString" if object => crate::regexp::regexp_to_string_generic(recv),
4445 _ => Err(crate::regexp::incompatible_receiver(method, recv)),
4446 };
4447 }
4448 // `Date.prototype[@@toPrimitive]` alone is generic: it accepts any object.
4449 if ctor == "Date" && method == "@@toPrimitive" {
4450 return date_to_primitive(recv, &args);
4451 }
4452 if ctor == "Date" && crate::stdlib::native_tag(recv).as_deref() != Some("Date") {
4453 const THIS_TIME_VALUE: &[&str] = &[
4454 "getTime",
4455 "valueOf",
4456 "getYear",
4457 "getFullYear",
4458 "getMonth",
4459 "getDate",
4460 "getDay",
4461 "getHours",
4462 "getMinutes",
4463 "getSeconds",
4464 "getMilliseconds",
4465 "getUTCFullYear",
4466 "getUTCMonth",
4467 "getUTCDate",
4468 "getUTCDay",
4469 "getUTCHours",
4470 "getUTCMinutes",
4471 "getUTCSeconds",
4472 "getUTCMilliseconds",
4473 "getTimezoneOffset",
4474 ];
4475 if THIS_TIME_VALUE.contains(&method) {
4476 return Err(host::type_error("this is not a Date object."));
4477 }
4478 // `toJSON` (21.4.4.37) is deliberately generic — it converts the
4479 // receiver and INVOKES `toISOString` on it, so it fails on the missing
4480 // method rather than on a brand.
4481 if method != "toJSON" {
4482 return Err(host::type_error(&format!(
4483 "Method Date.prototype.{method} called on incompatible receiver {}",
4484 no_side_effects_string(recv)
4485 )));
4486 }
4487 }
4488 // `%TypedArray%.prototype`'s methods split the same way: `ValidateTypedArray`
4489 // (23.2.4.4) reports `this is not a typed array.`, while the handful that
4490 // check the receiver at the call boundary take the branded form. Measured
4491 // over all 27 shared methods on node v26.8.1; `toString` is the one that is
4492 // genuinely generic (it is `Array.prototype.toString`) and never brands.
4493 if matches!(ctor, "TypedArray" | "Uint8Array")
4494 && !matches!(
4495 crate::stdlib::native_tag(recv).as_deref(),
4496 Some("TypedArray") | Some("Buffer")
4497 )
4498 {
4499 const BRANDED: &[&str] = &[
4500 "slice",
4501 "subarray",
4502 "join",
4503 "sort",
4504 "at",
4505 "toReversed",
4506 "toSorted",
4507 "toLocaleString",
4508 ];
4509 if BRANDED.contains(&method) {
4510 return Err(host::type_error(&format!(
4511 "Method %TypedArray%.prototype.{method} called on incompatible receiver {}",
4512 no_side_effects_string(recv)
4513 )));
4514 }
4515 // The four base64/hex methods brand themselves against `Uint8Array`
4516 // specifically — a WRONG view is as incompatible as a plain object, and
4517 // the generic guard here cannot tell those apart.
4518 if crate::stdlib::typedarray::UINT8_PROTOTYPE_METHODS.contains(&method) {
4519 return Err(host::type_error(&format!(
4520 "Method Uint8Array.prototype.{method} called on incompatible receiver {}",
4521 no_side_effects_string(recv)
4522 )));
4523 }
4524 if method != "toString" {
4525 return Err(host::type_error("this is not a typed array."));
4526 }
4527 }
4528 // `Function.prototype.call`/`apply`/`bind` with a callable PROXY as `this`
4529 // (`pf.call(null, 4, 5)`, reached through the target's chain). Handing
4530 // that back to `call_method` read `call` off the proxy again, which
4531 // resolved to this same thunk, and recursed until the stack overflowed and
4532 // aborted the process. The three are defined on the callee alone, so they
4533 // run here: the proxy's `apply` trap (or its target) gets the call.
4534 // `toString` recursed the same way.
4535 if ctor == "Function"
4536 && matches!(method, "call" | "apply" | "bind" | "toString")
4537 && with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy)
4538 {
4539 let mut rest = args.into_iter();
4540 let this_arg = rest.next().unwrap_or(Value::Undef);
4541 match method {
4542 "call" => return host::invoke(recv, rest.collect(), Some(this_arg)),
4543 "apply" => {
4544 let list = match rest.next() {
4545 None | Some(Value::Undef) => Vec::new(),
4546 Some(v) if with_host(|h| h.is_null(&v)) => Vec::new(),
4547 Some(v) => create_list_from_array_like(&v)?,
4548 };
4549 return host::invoke(recv, list, Some(this_arg));
4550 }
4551 "bind" => {
4552 let target = recv.clone();
4553 let pre: Vec<Value> = rest.collect();
4554 return Ok(with_host(|h| {
4555 h.alloc(JsObj::BoundFunc {
4556 target,
4557 this: this_arg,
4558 args: pre,
4559 })
4560 }));
4561 }
4562 // A proxy has no source text; V8 prints the native form for it.
4563 _ => return Ok(with_host(|h| h.new_str("function () { [native code] }"))),
4564 }
4565 }
4566 // `Symbol.prototype`'s methods are branded, and the receiver that reaches
4567 // them is very often NOT a symbol: `Symbol.prototype` itself is an ordinary
4568 // object. Without this check `Symbol.prototype.toString()` re-entered the
4569 // generic string conversion, which looked `toString` up again and called it
4570 // again — an infinite recursion that overflowed the stack and ABORTED the
4571 // process, which no `try`/`catch` can see. Node throws a plain TypeError.
4572 // The wording is Symbol's own, not the "incompatible receiver" form the
4573 // collections use.
4574 if ctor == "Symbol" && with_host(|h| h.kind_of(recv)) != Some(ObjKind::Symbol) {
4575 // A symbol-KEYED method is named in brackets rather than after a dot:
4576 // node's wording is `Symbol.prototype [ @@toPrimitive ] requires …`.
4577 // That is the message `String(Symbol.prototype)` produces, since the
4578 // conversion reaches `@@toPrimitive` before it would reach `toString`.
4579 let named = match method.strip_prefix("@@") {
4580 Some(sym) => format!("Symbol.prototype [ @@{sym} ]"),
4581 None => format!("Symbol.prototype.{method}"),
4582 };
4583 return Err(host::type_error(&format!(
4584 "{named} requires that 'this' be a Symbol"
4585 )));
4586 }
4587 if let Some(label) = branded_method_label(ctor, recv) {
4588 return Err(host::type_error(&format!(
4589 "Method {label}.prototype.{method} called on incompatible receiver {}",
4590 no_side_effects_string(recv)
4591 )));
4592 }
4593 // The brand check passed, so the receiver IS an instance of `ctor`: run the
4594 // kind's native method directly. `call_method` resolves the name off the
4595 // receiver's chain first, where a subclass override of the same name sits —
4596 // `class C extends Map { get(k) { return super.get(k) } }` and
4597 // `Map.prototype.get.call(this, k)` inside it both found `C.prototype.get`
4598 // again and recursed until the stack overflowed.
4599 if !method.starts_with("@@") {
4600 match (ctor, with_host(|h| h.kind_of(recv))) {
4601 ("Array", Some(ObjKind::Array)) => return array_method(recv, method, args),
4602 ("Map" | "WeakMap", Some(ObjKind::Map)) => return map_method(recv, method, args),
4603 ("Set" | "WeakSet", Some(ObjKind::Set)) => return set_method(recv, method, args),
4604 ("Promise", Some(ObjKind::Promise)) => return promise_method(recv, method, args),
4605 _ => {}
4606 }
4607 }
4608 host::call_method(recv, method, args)
4609}
4610
4611/// The name a branded prototype method reports itself under when its receiver
4612/// fails the brand check, or `None` when `ctor`'s methods are generic over
4613/// `this` (every `Array.prototype` and `Object.prototype` method is) or the
4614/// receiver really is an instance.
4615///
4616fn branded_method_label(ctor: &str, recv: &Value) -> Option<&'static str> {
4617 let kind = with_host(|h| h.kind_of(recv));
4618 // `weak` is part of the brand: a `WeakSet` has `[[WeakSetData]]`, not
4619 // `[[SetData]]`, so `Set.prototype.has.call(new WeakSet())` is incompatible
4620 // even though both are `JsObj::Set` here.
4621 let weak = peek(recv, |o| match o {
4622 JsObj::Set { weak, .. } | JsObj::Map { weak, .. } => Some(*weak),
4623 _ => None,
4624 })
4625 .unwrap_or(false);
4626 let ok = match ctor {
4627 "Set" => kind == Some(ObjKind::Set) && !weak,
4628 "WeakSet" => kind == Some(ObjKind::Set) && weak,
4629 "Map" => kind == Some(ObjKind::Map) && !weak,
4630 "WeakMap" => kind == Some(ObjKind::Map) && weak,
4631 "Promise" => kind == Some(ObjKind::Promise),
4632 _ => return None,
4633 };
4634 if ok {
4635 return None;
4636 }
4637 Some(match ctor {
4638 "Set" => "Set",
4639 "WeakSet" => "WeakSet",
4640 "Map" => "Map",
4641 "WeakMap" => "WeakMap",
4642 _ => "Promise",
4643 })
4644}
4645
4646/// V8's `Object::NoSideEffectsToString`, the rendering an engine-thrown message
4647/// uses for a value it must not run user code on. Measured on node v26.8.1
4648/// through `Map.prototype.get.call(x)`:
4649///
4650/// ```text
4651/// 5 / 'str' / true / null / undefined / 9n the value's own ToString
4652/// Symbol('s') Symbol(s)
4653/// function f(){} its source text
4654/// new Error('e') Error: e
4655/// {} / new (class A {}) #<Object> / #<A>
4656/// new Map() / Promise.resolve() #<Map> / #<Promise>
4657/// [] / new Date() / /re/ / new Uint8Array() [object Array] / [object Date] / …
4658/// { toString() {} } / Object.create(null) [object Object]
4659/// ```
4660///
4661/// The split is one test: a receiver whose `toString` is still
4662/// `Object.prototype.toString` prints `#<Constructor>`, and any other receiver
4663/// prints what the BUILTIN brand would be — V8 never calls the user's method,
4664/// which is why an object with its own `toString` prints `[object Object]` and
4665/// not what that method returns.
4666/// [`no_side_effects_string`] for callers outside this module.
4667/// `Date.prototype[@@toPrimitive](hint)` (21.4.4.45). Not branded: any OBJECT
4668/// receiver is converted, a Proxy through its `get` trap. `"string"` and
4669/// `"default"` try `toString` first, `"number"` tries `valueOf` first, and any
4670/// other hint is a TypeError — then `OrdinaryToPrimitive` does the rest.
4671pub(crate) fn date_to_primitive(recv: &Value, args: &[Value]) -> Result<Value, String> {
4672 if !with_host(|h| is_object_like(h, recv)) {
4673 return Err(host::type_error(&format!(
4674 "Method Date.prototype [ @@toPrimitive ] called on incompatible receiver {}",
4675 no_side_effects_string(recv)
4676 )));
4677 }
4678 let hint = args.first().cloned().unwrap_or(Value::Undef);
4679 let try_first = match with_host(|h| h.as_str(&hint)).as_deref() {
4680 Some("string") | Some("default") => "string",
4681 Some("number") => "number",
4682 _ => {
4683 return Err(host::type_error(&format!(
4684 "Invalid hint: {}",
4685 no_side_effects_string(&hint)
4686 )))
4687 }
4688 };
4689 host::ordinary_to_primitive(recv, try_first)
4690}
4691
4692pub(crate) fn no_side_effects_string_pub(recv: &Value) -> String {
4693 no_side_effects_string(recv)
4694}
4695
4696fn no_side_effects_string(recv: &Value) -> String {
4697 if with_host(|h| host::is_primitive(h, recv)) || with_host(|h| host::is_callable(h, recv)) {
4698 return with_host(|h| h.str_of(recv));
4699 }
4700 if let Some(s) = with_host(|h| h.error_to_string(recv)) {
4701 return s;
4702 }
4703 // `native_tag` re-enters the host, so it is read BEFORE the borrow below
4704 // rather than inside it.
4705 let native = crate::stdlib::native_tag(recv).is_some();
4706 let brands_itself = with_host(|h| {
4707 // `Object.prototype.toString` reaches every object as a thunk on the
4708 // real prototype object, so its presence proves nothing; only a
4709 // toString the receiver's chain OVERRIDES it with counts.
4710 let overridden = host::lookup_chain(h, recv, "toString")
4711 .map(|f| !matches!(h.get(&f), Some(JsObj::Builtin(n)) if n == "@proto:Object:toString"))
4712 .unwrap_or(false);
4713 native
4714 || overridden
4715 || h.has_null_proto(recv)
4716 || !matches!(
4717 h.kind_of(recv),
4718 Some(ObjKind::Object)
4719 | Some(ObjKind::Map)
4720 | Some(ObjKind::Set)
4721 | Some(ObjKind::Promise)
4722 )
4723 });
4724 if brands_itself {
4725 return with_host(|h| object_tag(h, recv));
4726 }
4727 let ctor = get_property(recv, "constructor")
4728 .ok()
4729 .map(|c| with_host(|h| h.callable_name(&c)))
4730 .filter(|n| !n.is_empty())
4731 .unwrap_or_else(|| "Object".to_string());
4732 format!("#<{ctor}>")
4733}
4734
4735/// The value of `v[Symbol.toStringTag]` for a builtin that genuinely carries
4736/// one, or `None` when reading that symbol must yield `undefined`.
4737///
4738/// Every builtin brand is already computed in exactly one place (`object_tag`),
4739/// so this reuses it and subtracts the legacy builtins, which brand for
4740/// `Object.prototype.toString` but expose no `Symbol.toStringTag` property.
4741/// The subtracted list is measured against node v26.7.0, not assumed: `[]`,
4742/// `function(){}`, `{}`, `new Date()`, `/x/` and `new Error()` all read
4743/// `undefined`, while `Map`/`Set`/`Promise`/typed arrays/`ArrayBuffer`/
4744/// `DataView`/`WeakRef`/`FinalizationRegistry`/`BigInt`/`Symbol`/generators/
4745/// async+generator functions/`Math`/`JSON`/`Reflect`/`URL`/`URLSearchParams`/
4746/// `TextEncoder`/`TextDecoder` all read their brand.
4747pub(crate) fn well_known_tag(h: &host::JsHost, v: &Value) -> Option<String> {
4748 // A primitive never carries the symbol except a BigInt/Symbol wrapper, both
4749 // of which `object_tag` already brands.
4750 let tag = object_brand(h, v);
4751 const NO_TAG: &[&str] = &[
4752 "Undefined",
4753 "Null",
4754 "Boolean",
4755 "Number",
4756 "String",
4757 "Array",
4758 "Function",
4759 "Object",
4760 "Date",
4761 "RegExp",
4762 "Error",
4763 ];
4764 if NO_TAG.contains(&tag.as_str()) {
4765 return None;
4766 }
4767 Some(tag)
4768}
4769
4770/// The constructor name of the nearest intrinsic prototype on `v`'s chain that
4771/// carries an own `Symbol.toStringTag`, if any.
4772fn chain_tag_ctor(h: &host::JsHost, v: &Value) -> Option<String> {
4773 let mut cur = h.proto_of(v);
4774 for _ in 0..100 {
4775 let p = cur?;
4776 if h.is_null(&p) {
4777 return None;
4778 }
4779 let name = match h.get(&p) {
4780 Some(JsObj::Builtin(ns)) => ns.strip_suffix(".prototype").map(str::to_string),
4781 _ => h.intrinsic_proto_ctor(&p).map(str::to_string),
4782 }
4783 // A CLASS prototype is not linked to the builtin its class extends —
4784 // the relationship lives on the class value — so the walk crosses over
4785 // there, or `Object.create(D.prototype)` for `class D extends Map`
4786 // finds nothing.
4787 .or_else(|| {
4788 h.class_owning_proto(&p)
4789 .and_then(|c| h.class_builtin_ancestor(&c))
4790 .map(|b| h.callable_name(&b))
4791 .filter(|n| !n.is_empty())
4792 });
4793 if let Some(n) = name {
4794 if intrinsic_proto_members(&format!("{n}.prototype"))
4795 .is_some_and(|ms| ms.contains(&"@@toStringTag"))
4796 {
4797 return Some(n);
4798 }
4799 }
4800 cur = h.proto_of(&p);
4801 }
4802 None
4803}
4804
4805/// The `Object.prototype.toString` brand tag for `v` (`[object Array]` etc.).
4806/// Every builtin exotic object reports its own brand, which is how packages
4807/// type-test values they did not construct (`toString.call(x) ===
4808/// '[object Uint8Array]'`). A `Buffer` reports `Uint8Array` because in Node it
4809/// IS a `Uint8Array` subclass and inherits that `Symbol.toStringTag`.
4810pub(crate) fn object_tag(h: &host::JsHost, v: &Value) -> String {
4811 format!("[object {}]", object_brand(h, v))
4812}
4813
4814/// The bare brand name behind `Object.prototype.toString` (`Array`, `Uint8Array`
4815/// …), without the `[object …]` wrapper. Split out so the brand and the
4816/// `Symbol.toStringTag` property read cannot disagree about what a value is.
4817/// Whether `v` is a function's `arguments` object.
4818///
4819/// Backed by an Array so indices, `length`, spread and `for-of` all work, but
4820/// marked so it does not pass for one: node's is an exotic, and `isArray`, the
4821/// brand and `util.types.isArgumentsObject` all have to tell them apart.
4822pub fn is_arguments(v: &Value) -> bool {
4823 with_host(|h| is_arguments_h(h, v))
4824}
4825
4826/// `is_arguments` for a caller that already holds the host borrow — `object_brand`
4827/// runs under one, and re-entering through `with_host` aborts the process.
4828pub fn is_arguments_h(h: &host::JsHost, v: &Value) -> bool {
4829 h.fn_prop(v, "@@arguments").is_some()
4830}
4831
4832fn object_brand(h: &host::JsHost, v: &Value) -> String {
4833 // A `<C>.prototype` this host built as a real object is an ORDINARY object:
4834 // it holds no instance slot, so only the branded few report anything but
4835 // `[object Object]`. Checked before the match because those prototypes are
4836 // plain `JsObj::Object`s and would otherwise be branded by whatever their
4837 // own properties happen to look like — `TypeError.prototype` has `name` and
4838 // `message`, which read as an Error instance.
4839 if let Some(ctor) = h.intrinsic_proto_ctor(v) {
4840 return if BRANDED_PROTOS.contains(&ctor) {
4841 ctor.to_string()
4842 } else {
4843 "Object".to_string()
4844 };
4845 }
4846 let tag: String = match v {
4847 Value::Undef => "Undefined".into(),
4848 Value::Bool(_) => "Boolean".into(),
4849 Value::Int(_) | Value::Float(_) => "Number".into(),
4850 Value::Str(_) => "String".into(),
4851 Value::Obj(_) => match h.get(v) {
4852 Some(JsObj::Null) => "Null".into(),
4853 Some(JsObj::Str(_)) => "String".into(),
4854 Some(JsObj::Array(_)) if is_arguments_h(h, v) => "Arguments".into(),
4855 Some(JsObj::Array(_)) => "Array".into(),
4856 // An array iterator and a Map/Set iterator carry the tags of their
4857 // prototypes (23.1.5.2.2, 24.1.5.2.2, 24.2.6.2.2).
4858 Some(JsObj::Iter { array: Some(_), .. }) => "Array Iterator".into(),
4859 Some(JsObj::Iter { brand: Some(b), .. }) => (*b).into(),
4860 Some(JsObj::Object(_)) if collection_iterator_view(h, v).is_some() => {
4861 match collection_iterator_view(h, v).map(|(b, _)| b) {
4862 Some(b) if b.starts_with("Map") => "Map Iterator".into(),
4863 _ => "Set Iterator".into(),
4864 }
4865 }
4866 // A lazy iterator helper brands as node does.
4867 Some(JsObj::Object(p))
4868 if p.get("@@native").map(|t| h.str_of(t)).as_deref() == Some("IteratorHelper") =>
4869 {
4870 "Iterator Helper".into()
4871 }
4872 // A `DOMException` brands by its class, not as a plain `Error`.
4873 Some(JsObj::Object(p)) if p.contains_key("@@domName") => "DOMException".into(),
4874 // 20.1.3.6 steps 5-8 brand a wrapper by its internal slot, so
4875 // `Object.prototype.toString.call(new Number(1))` is
4876 // `[object Number]` rather than `[object Object]`.
4877 Some(JsObj::Object(p)) if p.contains_key("@@primitive") => match p["@@primitive"] {
4878 Value::Bool(_) => "Boolean".into(),
4879 Value::Int(_) | Value::Float(_) => "Number".into(),
4880 _ => "String".into(),
4881 },
4882 // 20.1.3.6 step 3 brands by `IsArray`, which follows a Proxy to its
4883 // `[[ProxyTarget]]` — `Object.prototype.toString.call(new Proxy([],
4884 // {}))` is `'[object Array]'`. Everything else about a proxy brands
4885 // as a plain Object (a `Symbol.toStringTag` read through the `get`
4886 // trap is handled by the caller, before this).
4887 Some(JsObj::Proxy { target, .. }) => {
4888 let mut cur = target;
4889 for _ in 0..100 {
4890 match h.get(cur) {
4891 Some(JsObj::Proxy { target: t, .. }) => cur = t,
4892 _ => break,
4893 }
4894 }
4895 match h.get(cur) {
4896 Some(JsObj::Array(_)) => "Array".into(),
4897 _ => "Object".into(),
4898 }
4899 }
4900 // `function*` / `async function` / `async function*` carry their own
4901 // `Symbol.toStringTag` in V8 (27.3.3.2, 27.7.3.2, 27.4.3.2).
4902 Some(JsObj::Func(f)) => match h.funcs.get(f.def_id) {
4903 Some(d) if d.is_generator && d.is_async => "AsyncGeneratorFunction".into(),
4904 Some(d) if d.is_generator => "GeneratorFunction".into(),
4905 Some(d) if d.is_async => "AsyncFunction".into(),
4906 _ => "Function".into(),
4907 },
4908 // `Math`/`JSON`/`Reflect` are namespace OBJECTS, not callables, and
4909 // brand by name (21.3.1.9, 25.5.3, 28.1.14).
4910 Some(JsObj::Builtin(n)) if matches!(n.as_str(), "Math" | "JSON" | "Reflect") => {
4911 n.clone()
4912 }
4913 // `performance`, `crypto` and `crypto.subtle` brand as their class,
4914 // and `process` carries a `process` tag; all are singletons this
4915 // frontend keeps as namespaces, and all branded `[object Object]`.
4916 Some(JsObj::Builtin(n)) if crate::stdlib::singleton_class(n).is_some() => {
4917 crate::stdlib::class_display_name(crate::stdlib::singleton_class(n).unwrap_or(""))
4918 .to_string()
4919 }
4920 Some(JsObj::Builtin(n)) if n == "process" => "process".into(),
4921 // A `<Ctor>.prototype` object brands as the constructor it belongs
4922 // to — `Object.prototype.toString.call(Set.prototype)` is
4923 // `[object Set]` — and a `require()`d module namespace is a plain
4924 // object. Neither is a function, so neither brands as one.
4925 Some(JsObj::Builtin(n)) if !host::builtin_is_callable(n) => {
4926 match n.strip_suffix(".prototype") {
4927 Some(ctor) if BRANDED_PROTOS.contains(&ctor) => ctor.to_string(),
4928 _ => "Object".into(),
4929 }
4930 }
4931 Some(JsObj::Class(_))
4932 | Some(JsObj::Builtin(_))
4933 | Some(JsObj::BoundFunc { .. })
4934 | Some(JsObj::BoundMethod { .. }) => "Function".into(),
4935 // A suspended generator object is `[object Generator]`; an async one
4936 // `[object AsyncGenerator]`.
4937 Some(JsObj::Generator { .. }) if h.is_async_gen_val(v) => "AsyncGenerator".into(),
4938 Some(JsObj::Generator { .. }) => "Generator".into(),
4939 Some(JsObj::RegExp(_)) => "RegExp".into(),
4940 Some(JsObj::Map { weak, .. }) => if *weak { "WeakMap" } else { "Map" }.into(),
4941 Some(JsObj::Set { weak, .. }) => if *weak { "WeakSet" } else { "Set" }.into(),
4942 Some(JsObj::Promise { .. }) => "Promise".into(),
4943 Some(JsObj::Symbol { .. }) => "Symbol".into(),
4944 Some(JsObj::BigInt(_)) => "BigInt".into(),
4945 // Native-tagged instances brand by their tag; a typed array brands by
4946 // its element kind (`@@kind`), and every Error subclass is `Error`.
4947 Some(JsObj::Object(p)) => match p.get("@@native").map(|t| h.str_of(t)).as_deref() {
4948 Some("TypedArray") => p
4949 .get("@@kind")
4950 .map(|k| h.str_of(k))
4951 .unwrap_or_else(|| "Uint8Array".into()),
4952 Some("Buffer") => "Uint8Array".into(),
4953 // Every native class that really carries a `Symbol.toStringTag`
4954 // in Node brands by its own name. Verified against node v26:
4955 // `Object.prototype.toString.call(new WeakRef({}))` is
4956 // `[object WeakRef]`. The rest of the `@@native` tags
4957 // (`EventEmitter`, `Server`, `Hash`, `Readable`, …) are plain
4958 // classes with NO tag, so they stay `[object Object]` — listing
4959 // them here would invent a brand Node does not have.
4960 Some(
4961 t @ ("ArrayBuffer"
4962 | "DataView"
4963 | "Date"
4964 | "WeakRef"
4965 | "FinalizationRegistry"
4966 | "TextEncoder"
4967 | "TextDecoder"
4968 | "URL"
4969 | "URLSearchParams"),
4970 ) => t.into(),
4971 _ if has_error_data(h, v) => "Error".into(),
4972 _ => "Object".into(),
4973 },
4974 _ => "Object".into(),
4975 },
4976 // node-js only produces the Value variants above; fusevm's shell-oriented
4977 // variants never arise here.
4978 _ => "Object".into(),
4979 };
4980 // Nothing about the value itself brands it. An ordinary object whose CHAIN
4981 // reaches an intrinsic prototype carrying an own `Symbol.toStringTag`
4982 // borrows that one: 20.1.3.6 step 15 is a `Get`, which walks.
4983 // `Object.prototype.toString.call(Object.create(Map.prototype))` is
4984 // `[object Map]` and was `[object Object]`.
4985 //
4986 // Only as a FALLBACK, and only for the prototypes that REALLY carry the
4987 // symbol. A typed array reaches `%TypedArray%.prototype`, whose tag is an
4988 // ACCESSOR returning the specific kind, so consulting the chain FIRST
4989 // branded every view `[object TypedArray]` instead of `[object Uint8Array]`
4990 // — three records caught it. `Error.prototype` carries no tag at all, so
4991 // inheriting from it borrows nothing.
4992 if tag == "Object" && !has_error_data(h, v) {
4993 if let Some(ctor) = chain_tag_ctor(h, v) {
4994 return ctor;
4995 }
4996 }
4997 tag
4998}
4999
5000fn b_setattr(vm: &mut VM, _: u8) -> Value {
5001 note_site(vm);
5002 let val = vm.pop();
5003 let name = sval(&vm.pop());
5004 let recv = vm.pop();
5005 if let Err(e) = set_property(&recv, &name, val.clone()) {
5006 return abort(vm, e);
5007 }
5008 val
5009}
5010
5011/// `NAMED_EVAL` — SetFunctionName (10.2.9) for a function whose name is only
5012/// known at run time, i.e. one defined under a COMPUTED key: `{ [k]: () => {} }`,
5013/// `class C { static [k] = function(){} }`.
5014///
5015/// The compiler emits this ONLY where the grammar says NamedEvaluation applies
5016/// (`IsAnonymousFunctionDefinition` is a syntactic predicate, not a runtime one:
5017/// `{ m: someAlreadyAnonymousFn }` must NOT be renamed), so the name is set
5018/// unconditionally here.
5019///
5020/// A symbol key becomes `[description]` per step 2 of SetFunctionName; `kind`
5021/// contributes the accessor prefix, so `{ get [k](){} }` is `get <key>`.
5022fn b_named_eval(vm: &mut VM, _: u8) -> Value {
5023 let func = vm.pop();
5024 let kind = vm.pop().to_int();
5025 let key = vm.pop();
5026 let key = sval(&key);
5027 // `@@sym:<id>` / `@@iterator` — an internal symbol key. Step 2: an empty
5028 // description gives the empty name, not `[undefined]`.
5029 let base = match with_host(|h| h.symbol_of_key(&key)) {
5030 Some(sym) => match with_host(|h| h.get(&sym).cloned()) {
5031 Some(JsObj::Symbol {
5032 desc: Some(desc), ..
5033 }) => format!("[{desc}]"),
5034 _ => String::new(),
5035 },
5036 None => key,
5037 };
5038 let name = match kind {
5039 host::member::GET => format!("get {base}"),
5040 host::member::SET => format!("set {base}"),
5041 _ => base,
5042 };
5043 with_host(|h| {
5044 let s = h.new_str(name);
5045 h.set_fn_prop(&func, "name", s);
5046 });
5047 func
5048}
5049
5050/// `[[Set]]` reachable from `crate::proxy`'s no-trap forward, which has to land
5051/// on the same path a plain `o.k = v` takes.
5052pub fn set_property_pub(recv: &Value, name: &str, val: Value) -> Result<(), String> {
5053 set_property(recv, name, val)
5054}
5055
5056/// An object's OWN property as `(value, writable, configurable, is_accessor)`,
5057/// or `None` when it has none. Reads through a Proxy's
5058/// `getOwnPropertyDescriptor` trap, so it answers for any object.
5059pub fn own_prop_facts(obj: &Value, key: &str) -> Option<(Value, bool, bool, bool)> {
5060 let k = with_host(|h| h.new_str(key.to_string()));
5061 let d = own_descriptor_pub(obj, k).ok()?;
5062 if matches!(d, Value::Undef) {
5063 return None;
5064 }
5065 let field = |n: &str| get_property(&d, n).unwrap_or(Value::Undef);
5066 // Each read is hoisted out of the `with_host` borrow: `get_property` takes
5067 // the host itself, so reading inside the closure double-borrows.
5068 let value = field("value");
5069 let writable = field("writable");
5070 let configurable = field("configurable");
5071 let truthy = |v: &Value| with_host(|h| h.truthy(v));
5072 let is_accessor = with_host(|h| host::lookup_chain(h, &d, "get").is_some());
5073 Some((value, truthy(&writable), truthy(&configurable), is_accessor))
5074}
5075
5076/// `OrdinarySetWithOwnDescriptor` (10.1.9.2) with a receiver distinct from the
5077/// object the lookup started on — what `Reflect.set(t, k, v, receiver)` and a
5078/// proxy `set` trap forwarding to it both need.
5079///
5080/// The distinction that matters: an accessor found on `target`'s chain RUNS,
5081/// with `receiver` as `this`; a data property does not write to `target` at all
5082/// but is CREATED on `receiver` through its `[[DefineOwnProperty]]`. Routing
5083/// that second case back through `[[Set]]` made a proxy receiver re-enter its
5084/// own `set` trap forever — the trap body `Reflect.set(t, k, v, recv)` is the
5085/// documented way to forward a write, so the recursion hit every faithful
5086/// handler.
5087pub fn set_with_receiver(
5088 target: &Value,
5089 key: &str,
5090 val: Value,
5091 receiver: &Value,
5092) -> Result<bool, String> {
5093 // A proxy target answers through its own trap, which re-enters here with
5094 // whatever receiver the handler passes on.
5095 if crate::proxy::parts(target).is_some() {
5096 return crate::proxy::set(target, key, &val, receiver);
5097 }
5098 // An accessor anywhere on the target's chain wins, and sees `receiver`.
5099 if let Some((_, setter)) = with_host(|h| host::lookup_accessor(h, target, key)) {
5100 return match setter {
5101 Some(s) => {
5102 host::invoke(&s, vec![val], Some(receiver.clone()))?;
5103 Ok(true)
5104 }
5105 // A getter with no setter refuses the write rather than shadowing it.
5106 None => Ok(false),
5107 };
5108 }
5109 if !with_host(|h| h.can_write_prop(target, key)) {
5110 return Ok(false);
5111 }
5112 // Steps 3.b-3.d: only an object can receive the property, and its OWN
5113 // property decides — an accessor or a read-only slot refuses, and every
5114 // other case defines a plain data property.
5115 //
5116 // `is_object_like`, not a shape test: a string, a symbol and a bigint are
5117 // PRIMITIVES that ride as `Value::Obj` handles here, so the shape check
5118 // passed them through to `defineProperty`, which then threw `called on
5119 // non-object` where 10.1.9.2 step 3.b simply reports `false`.
5120 if !with_host(|h| is_object_like(h, receiver)) {
5121 return Ok(false);
5122 }
5123 let existing = own_prop_facts(receiver, key);
5124 if let Some((_, writable, _, is_accessor)) = &existing {
5125 if *is_accessor || !writable {
5126 return Ok(false);
5127 }
5128 }
5129 // Steps 3.d.iii and 3.e both DEFINE, they do not assign: a setter inherited
5130 // by the receiver must not run, and a proxy receiver must reach its
5131 // `defineProperty` trap rather than its `set` trap. An existing property
5132 // gets `{ value }` alone (3.d.iii), so its other attributes stay; a new one
5133 // is a full writable/enumerable/configurable data property (3.e).
5134 let desc = with_host(|h| {
5135 let mut m: IndexMap<String, Value> = IndexMap::new();
5136 m.insert("value".into(), val);
5137 if existing.is_none() {
5138 m.insert("writable".into(), Value::Bool(true));
5139 m.insert("enumerable".into(), Value::Bool(true));
5140 m.insert("configurable".into(), Value::Bool(true));
5141 }
5142 h.new_object(m)
5143 });
5144 if crate::proxy::parts(receiver).is_some() {
5145 return crate::proxy::define_property(receiver, key, &desc);
5146 }
5147 let k = with_host(|h| h.new_str(key.to_string()));
5148 define_property_pub(receiver, k, desc)?;
5149 Ok(true)
5150}
5151
5152/// Whether the first argument is a PRIMITIVE — including the three that ride as
5153/// heap handles, which a shape test misses.
5154fn is_primitive_arg(args: &[Value]) -> bool {
5155 let v = arg0(args);
5156 with_host(|h| host::is_primitive(h, &v))
5157}
5158
5159/// The `TypeError` a refused write raises in strict code, worded as V8 does.
5160///
5161/// Adding a key to a non-extensible object reports differently from assigning
5162/// to a read-only one, and the object is named by its brand — `#<Object>` for a
5163/// plain object, `[object Array]` for an array.
5164/// A property key as V8 prints it in a message: a symbol key as `Symbol(desc)`
5165/// rather than its internal `@@…` spelling.
5166fn display_key(name: &str) -> String {
5167 if name.starts_with("@@") {
5168 if let Some(sym) = with_host(|h| h.symbol_of_key(name)) {
5169 return with_host(|h| h.str_of(&sym));
5170 }
5171 }
5172 name.to_string()
5173}
5174
5175fn write_refused(recv: &Value, name: &str) -> String {
5176 // V8 reports an element refused by a fixed `length` as that `length`.
5177 let name = if with_host(|h| h.past_fixed_length(recv, name)) {
5178 "length"
5179 } else {
5180 name
5181 };
5182 let shown = display_key(name);
5183 let extensible = with_host(|h| h.is_extensible(recv));
5184 // Which of the two messages applies turns on whether the key already
5185 // EXISTS. Every shape that keeps its own properties in the fn-prop side
5186 // table answered a blanket `true` here, so adding a key to a frozen
5187 // function reported "read only" where node reports "not extensible".
5188 let has_own = with_host(|h| match h.get(recv) {
5189 Some(JsObj::Object(p)) => p.contains_key(name),
5190 Some(JsObj::Array(items)) => {
5191 name == "length"
5192 || name
5193 .parse::<usize>()
5194 .map(|i| i < items.len() && !h.is_hole(recv, i))
5195 .unwrap_or(false)
5196 || h.fn_prop(recv, name).is_some()
5197 }
5198 Some(JsObj::RegExp(_)) => name == "lastIndex" || h.fn_prop(recv, name).is_some(),
5199 _ => h.fn_prop(recv, name).is_some(),
5200 });
5201 if !extensible && !has_own {
5202 return host::type_error(&format!(
5203 "Cannot add property {shown}, object is not extensible"
5204 ));
5205 }
5206 // The receiver renders the way every other brand-check message renders one
5207 // — `#<Object>`, `[object Array]`, `[object RegExp]`, `#<Map>`, `#<C>` for a
5208 // class instance, `Error: m` for an error. Only Array was special-cased, so
5209 // every other exotic reported `#<Object>`.
5210 let kind = if with_host(|h| host::is_callable(h, recv)) {
5211 "function"
5212 } else {
5213 "object"
5214 };
5215 host::type_error(&format!(
5216 "Cannot assign to read only property '{shown}' of {kind} '{}'",
5217 no_side_effects_string(recv)
5218 ))
5219}
5220
5221fn set_property(recv: &Value, name: &str, val: Value) -> Result<(), String> {
5222 // 6.2.5.6 `PutValue` begins with `RequireObjectCoercible`: writing any
5223 // property of `undefined` or `null` throws, naming the key. Every such
5224 // write was silently discarded, so `u.x = 1` — the mirror of the single
5225 // most common runtime fault in JS, which the READ side already reports —
5226 // looked like it had succeeded.
5227 if with_host(|h| h.is_nullish(recv)) {
5228 return Err(host::type_error(&format!(
5229 "Cannot set properties of {} (setting '{name}')",
5230 with_host(|h| h.str_of(recv))
5231 )));
5232 }
5233 // A write to a PRIMITIVE receiver has no target — `ToObject` makes a
5234 // throwaway wrapper — so it is discarded in sloppy code and throws in
5235 // strict (10.1.9.2 / 6.2.5.6 again). The refusal was silent in both.
5236 // `is_primitive` rather than a shape test: a string, a symbol and a bigint
5237 // ride as `Value::Obj` handles in this host, so a check for a non-`Obj`
5238 // value caught only numbers and booleans.
5239 if with_host(|h| host::is_primitive(h, recv)) && with_host(|h| h.current_strict()) {
5240 return Err(host::type_error(&format!(
5241 "Cannot create property '{name}' on {} '{}'",
5242 with_host(|h| h.type_of(recv)),
5243 with_host(|h| h.str_of(recv))
5244 )));
5245 }
5246 // `[[PrivateSet]]` (7.3.32) refuses a receiver that carries no such private
5247 // element. The class's own field initializers install theirs directly
5248 // (`host::init_one_field`), so a declaration never reaches this check.
5249 if name.starts_with('#') && !with_host(|h| h.has_private(recv, name)) {
5250 return Err(private_brand_message(name, true));
5251 }
5252 // `[[Set]]` on a Proxy: the handler's `set` trap, or a forward to the target.
5253 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
5254 // A `set` trap that returns falsish REFUSED the write: silent in sloppy
5255 // code, a TypeError in strict, exactly as an ordinary refused write is.
5256 if crate::proxy::set(recv, name, &val, recv)? {
5257 return Ok(());
5258 }
5259 if with_host(|h| h.current_strict()) {
5260 if let Some(e) = crate::esm::namespace_refusal(recv, crate::esm::Refused::Set, name) {
5261 return Err(e);
5262 }
5263 return Err(host::type_error(&format!(
5264 "'set' on proxy: trap returned falsish for property '{name}'"
5265 )));
5266 }
5267 return Ok(());
5268 }
5269 // A Proxy on the PROTOTYPE chain: `OrdinarySet` (10.1.9.2 step 2) hands a
5270 // key the receiver does not own to `parent.[[Set]](P, V, Receiver)`, so the
5271 // proxy's `set` trap runs with the ORIGINAL object as its receiver. The
5272 // write used to land straight on the receiver, and a trap inherited through
5273 // `Object.create(proxy)` never fired. A nearer link owning the key (data or
5274 // accessor) still wins, as `proxy_proto_link` checks.
5275 if name != "__proto__"
5276 && peek(recv, |o| match o {
5277 JsObj::Object(p) => Some(!p.contains_key(name)),
5278 _ => None,
5279 })
5280 .unwrap_or(false)
5281 && !with_host(|h| h.own_accessor(recv, name).is_some())
5282 {
5283 if let Some(link) = proxy_proto_link(recv, name) {
5284 if crate::proxy::set(&link, name, &val, recv)? {
5285 return Ok(());
5286 }
5287 if with_host(|h| h.current_strict()) {
5288 return Err(host::type_error(&format!(
5289 "'set' on proxy: trap returned falsish for property '{name}'"
5290 )));
5291 }
5292 return Ok(());
5293 }
5294 }
5295 // `globalThis.x = 1` creates a real global binding, so the bare `x` reads it
5296 // back. Writing only the own property left the two views disagreeing:
5297 // `globalThis.zz` was 7 while `zz` was still a `ReferenceError`.
5298 if with_host(|h| h.is_global_object(recv)) && !name.starts_with("@@") {
5299 with_host(|h| h.set_name(name, val.clone()));
5300 }
5301 // `obj.__proto__ = p` re-links the prototype — but only for the two values
5302 // the Annex B setter accepts, an Object or `null`. Everything else is a
5303 // silent no-op in Node (`o.__proto__ = 5` leaves `Object.getPrototypeOf(o)`
5304 // untouched and creates no own key), and a null-prototype object inherits
5305 // no such setter at all, so there the assignment is an ORDINARY own
5306 // property write. Re-linking unconditionally made `o.__proto__ = 5` set the
5307 // prototype to the number 5.
5308 if name == "__proto__" && with_host(|h| h.kind_of(recv)) == Some(ObjKind::Object) {
5309 if with_host(|h| h.has_null_proto(recv)) {
5310 // falls through to the ordinary own-property write below
5311 } else {
5312 let assignable =
5313 with_host(|h| h.is_null(&val) || matches!(h.kind_of(&val), Some(ObjKind::Object)));
5314 if assignable {
5315 // The `__proto__` setter runs `[[SetPrototypeOf]]`, which a
5316 // NON-EXTENSIBLE object refuses — and unlike an ordinary
5317 // refused write, the setter throws in sloppy code too. It was
5318 // rewriting the link of a frozen object.
5319 if would_cycle(recv, &val) {
5320 return Err(host::type_error("Cyclic __proto__ value"));
5321 }
5322 if !with_host(|h| h.is_extensible(recv)) && !same_prototype(recv, &val) {
5323 return Err(host::type_error(&format!(
5324 "{} is not extensible",
5325 no_side_effects_string(recv)
5326 )));
5327 }
5328 with_host(|h| h.set_proto(recv, val));
5329 }
5330 return Ok(());
5331 }
5332 }
5333 // Every environment value is a STRING. `process.env.PORT = 8080` stores
5334 // "8080", so `process.env.PORT + 1` concatenates the way it does in a real
5335 // process; storing the number made it add instead.
5336 if !name.starts_with("@@")
5337 && with_host(
5338 |h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@envObject")),
5339 )
5340 {
5341 let text = with_host(|h| h.str_of(&val));
5342 // Write THROUGH to the real environment as well. `process.env` is not a
5343 // private map: node applies the change to the process, so a child
5344 // spawned afterwards inherits it. Keeping it only in the JS object meant
5345 // `process.env.NODE_ENV = 'production'` was invisible to every
5346 // `spawnSync`/`execSync` that followed.
5347 std::env::set_var(name, &text);
5348 let sv = with_host(|h| h.new_str(text));
5349 with_host(|h| {
5350 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
5351 p.insert(name.to_string(), sv);
5352 }
5353 });
5354 return Ok(());
5355 }
5356 // Assigning `e.stack` wins permanently: drop the not-yet-formatted marker so
5357 // no later read re-derives a header over the top of the assigned value.
5358 if name == "stack" {
5359 with_host(|h| {
5360 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
5361 p.shift_remove("@@stackRaw");
5362 }
5363 });
5364 }
5365 // An inherited/own setter accessor intercepts the write. This is checked
5366 // BEFORE the writable test because 10.1.9.2 branches on the descriptor
5367 // kind first: `writable` is a data-property attribute and means nothing on
5368 // an accessor, where the setter alone decides. Testing it first meant an
5369 // accessor defined through `Object.defineProperty` — which leaves
5370 // `writable` false, having no such field — silently swallowed every write
5371 // instead of calling its setter, so the standard clone idiom
5372 // `Object.create(proto, Object.getOwnPropertyDescriptors(src))` produced an
5373 // object whose setters did nothing. An accessor from an object literal
5374 // carries all-true attributes, which is why only the former broke.
5375 if let Some((getter, setter)) = with_host(|h| host::lookup_accessor(h, recv, name)) {
5376 if let Some(setter) = setter {
5377 // A setter that throws propagates out of the assignment.
5378 host::invoke(&setter, vec![val], Some(recv.clone()))?;
5379 return Ok(());
5380 }
5381 // Only a getter: the write is refused — silent in sloppy mode, a
5382 // TypeError in strict code. The `return` above matters, since a
5383 // successful setter call must not fall into this.
5384 let _ = getter;
5385 if with_host(|h| h.current_strict()) {
5386 return Err(host::type_error(&format!(
5387 "Cannot set property {name} of #<Object> which has only a getter"
5388 )));
5389 }
5390 return Ok(());
5391 }
5392 // A non-writable property, or a new key on a non-extensible object, refuses
5393 // the write. In SLOPPY mode that is silent; in strict code it is a
5394 // TypeError, and the ASSIGNMENT SITE decides which — not the object. Every
5395 // refusal used to be silent, so `'use strict'` did not catch a write to a
5396 // frozen object, which is most of the reason to freeze one.
5397 // A function's own `length` and `name` are read-only (10.2.8-9) until
5398 // redefined or deleted, so an assignment to the synthesized one is refused.
5399 let readonly_intrinsic = with_host(|h| h.fn_intrinsic_readonly(recv, name));
5400 if readonly_intrinsic || !with_host(|h| h.can_write_prop(recv, name)) {
5401 if with_host(|h| h.current_strict()) {
5402 return Err(write_refused(recv, name));
5403 }
5404 return Ok(());
5405 }
5406 // Writing `name`/`prototype`/statics on a function value.
5407 if matches!(
5408 with_host(|h| h.kind_of(recv)),
5409 Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc)
5410 ) {
5411 with_host(|h| h.set_fn_prop(recv, name, val));
5412 return Ok(());
5413 }
5414 // Writing a static onto a builtin namespace/ctor (`Error.prepareStackTrace`).
5415 // Each bare reference is a fresh `Builtin` handle, so route to the stable
5416 // per-namespace side table rather than the per-index `fn_props`.
5417 if let Some(ns) = peek(recv, |o| match o {
5418 JsObj::Builtin(ns) => Some(ns.clone()),
5419 _ => None,
5420 }) {
5421 // `process.exitCode` is an accessor in Node, not a data property: the
5422 // setter validates and stores the code the process will finally exit
5423 // with. Landing it in the generic static table made it a write-only
5424 // decoration — `process.exitCode = 3` read back as 3 and the process
5425 // still exited 0.
5426 if ns == "process" && name == "exitCode" {
5427 return crate::stdlib::process::set_exit_code(&val);
5428 }
5429 with_host(|h| h.set_builtin_static(&ns, name, val));
5430 return Ok(());
5431 }
5432 // A write onto a REAL intrinsic prototype object (`Object.prototype`,
5433 // `String.prototype`, `TypeError.prototype`) is mirrored into the
5434 // per-namespace side table as well as the object's own map. Instances are
5435 // not linked to these objects by `proto_of` — the chain walk never reaches
5436 // them — so the mirror is what makes `String.prototype.pad = f` visible as
5437 // `"x".pad`. The own-map write below still happens, so reading the
5438 // prototype itself and enumerating it keep working unchanged.
5439 if let Some(ns) = with_host(|h| {
5440 h.intrinsic_proto_ctor(recv)
5441 .map(str::to_string)
5442 .or_else(|| (h.object_proto() == *recv).then(|| "Object".to_string()))
5443 }) {
5444 with_host(|h| h.set_builtin_static(&format!("{ns}.prototype"), name, val.clone()));
5445 }
5446 // `re.lastIndex = n` on a RegExp advances/resets its match cursor. The
5447 // writability check above already refused it on a FROZEN regexp, which it
5448 // could only do once `integrity_keys` learned that `lastIndex` is an own
5449 // property.
5450 if name == "lastIndex" {
5451 if let Some(n) = with_host(|h| match h.get(recv) {
5452 Some(JsObj::RegExp(_)) => Some(h.to_number(&val)),
5453 _ => None,
5454 }) {
5455 with_host(|h| {
5456 if let Some(JsObj::RegExp(r)) = h.get_mut(recv) {
5457 r.last_index = if n.is_finite() && n >= 0.0 {
5458 crate::utf16::U16Index::new(n as usize)
5459 } else {
5460 crate::utf16::U16Index::ZERO
5461 };
5462 }
5463 });
5464 return Ok(());
5465 }
5466 }
5467 // An `arguments` object is an ORDINARY object with a `length` data property,
5468 // not an array: a write PAST the end adds an index and leaves `length`
5469 // alone. The array backing grew it instead, so `f(1)` followed by
5470 // `arguments[1] = 9` reported `arguments.length` as 2.
5471 if let Ok(i) = name.parse::<usize>() {
5472 if is_arguments(recv) && i >= array_len(recv) {
5473 with_host(|h| h.set_fn_prop(recv, name, val));
5474 return Ok(());
5475 }
5476 if is_arguments(recv) {
5477 with_host(|h| h.write_mapped_argument(recv, i, &val));
5478 }
5479 }
5480 // Typed-array element write (`ta[i] = v`): coerce + store into `@@elems`.
5481 if !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit()) {
5482 let is_ta = crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray");
5483 if is_ta && crate::stdlib::typedarray::elem_set(recv, name, &val)? {
5484 return Ok(());
5485 }
5486 // An index write to a view over a DETACHED buffer is DROPPED. Falling
5487 // through would store it as an ordinary own property, which then showed
5488 // up in `getOwnPropertyDescriptor` over a buffer with no bytes.
5489 if is_ta && crate::stdlib::typedarray::view_detached(recv) {
5490 return Ok(());
5491 }
5492 // `buf[i] = n` writes through to the Buffer's hidden byte array.
5493 if crate::stdlib::buffer::byte_set(recv, name, &val) {
5494 return Ok(());
5495 }
5496 }
5497 // Any own property on an exotic with no property map of its own. This sits
5498 // BELOW the exotic-specific writes above, so a RegExp's `lastIndex` still
5499 // moves its match cursor rather than being shadowed by a side-table entry.
5500 if uses_side_table(recv) {
5501 with_host(|h| h.set_fn_prop(recv, name, val));
5502 return Ok(());
5503 }
5504 // An arbitrary own prop on an array (e.g. exec-result `.index`/`.input`).
5505 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Array)
5506 && name != "length"
5507 && name.parse::<usize>().is_err()
5508 {
5509 with_host(|h| h.set_fn_prop(recv, name, val));
5510 return Ok(());
5511 }
5512 // `arr.length = n` (10.4.2.4 `ArraySetLength`) validates BEFORE it resizes,
5513 // and does so outside the host borrow because `ToNumber` may run a user
5514 // `valueOf`. An invalid length throws instead of being silently coerced to 0.
5515 let new_len = if name == "length" && with_host(|h| h.kind_of(recv)) == Some(ObjKind::Array) {
5516 let want = host::to_array_length(&val)?;
5517 // 10.4.2.4 steps 15-17: shrinking deletes from the END downwards and
5518 // STOPS at the first element that cannot be deleted, leaving the length
5519 // just past it. Truncating regardless discarded a non-configurable
5520 // element and reported a length node would not have accepted.
5521 let floor = with_host(|h| {
5522 let old = match h.get(recv) {
5523 Some(JsObj::Array(items)) => items.len(),
5524 _ => 0,
5525 };
5526 let mut stop = want;
5527 for i in (want..old).rev() {
5528 if !h.prop_attrs(recv, &i.to_string()).configurable {
5529 stop = i + 1;
5530 break;
5531 }
5532 }
5533 stop
5534 });
5535 Some((floor.max(want), want))
5536 } else {
5537 None
5538 };
5539 with_host(|h| match h.get_mut(recv) {
5540 Some(JsObj::Object(props)) => {
5541 // Adding a *new* array-index key must re-place it into ascending
5542 // integer-key order (updating an existing key keeps its position).
5543 let is_new = !props.contains_key(name);
5544 props.insert(name.to_string(), val);
5545 if is_new && host::array_index(name).is_some() {
5546 host::canonicalize_own_keys(props);
5547 }
5548 }
5549 Some(JsObj::Array(items)) => {
5550 if let Some((n, _)) = new_len {
5551 // Growing `length` appends HOLES (`a=[1]; a.length=3` still has
5552 // just the one own key); shrinking drops any hole past the end.
5553 let old = items.len();
5554 items.resize(n, Value::Undef);
5555 if n > old {
5556 h.mark_hole_range(recv, old..n);
5557 } else {
5558 h.truncate_holes(recv, n);
5559 }
5560 } else if let Ok(i) = name.parse::<usize>() {
5561 // A write PAST the end leaves the skipped positions elided.
5562 let old = items.len();
5563 if i >= old {
5564 items.resize(i + 1, Value::Undef);
5565 }
5566 items[i] = val;
5567 if i > old {
5568 h.mark_hole_range(recv, old..i);
5569 }
5570 // …and the written index itself is no longer one. This is the
5571 // single site that keeps a hole record from outliving the
5572 // elision it describes: every array element write in the
5573 // language reaches it.
5574 h.clear_hole(recv, i);
5575 }
5576 }
5577 _ => {}
5578 });
5579 // Step 17.b.ii: the delete that stopped the shrink makes `[[Set]]` return
5580 // false, which strict code reports as that failed delete.
5581 if let Some((n, want)) = new_len {
5582 if n > want && with_host(|h| h.current_strict()) {
5583 return Err(refused_delete_error(recv, &(n - 1).to_string()));
5584 }
5585 }
5586 Ok(())
5587}
5588
5589fn b_getitem(vm: &mut VM, _: u8) -> Value {
5590 note_site(vm);
5591 let idx = vm.pop();
5592 let recv = vm.pop();
5593 let key = match host::to_property_key(&idx) {
5594 Ok(k) => k,
5595 Err(e) => return abort(vm, e),
5596 };
5597 match get_property(&recv, &key) {
5598 Ok(v) => v,
5599 Err(e) => abort(vm, e),
5600 }
5601}
5602
5603fn b_setitem(vm: &mut VM, _: u8) -> Value {
5604 note_site(vm);
5605 let val = vm.pop();
5606 let idx = vm.pop();
5607 let recv = vm.pop();
5608 let key = match host::to_property_key(&idx) {
5609 Ok(k) => k,
5610 Err(e) => return abort(vm, e),
5611 };
5612 if let Err(e) = set_property(&recv, &key, val.clone()) {
5613 return abort(vm, e);
5614 }
5615 val
5616}
5617
5618/// `[[Delete]]` (10.1.10) for an already-resolved property key: the one place
5619/// `delete o[k]`, `delete o.k` and `Reflect.deleteProperty` all go through, so
5620/// the three cannot drift. Reports `false` for a non-configurable property
5621/// (sloppy mode ignores the failure rather than throwing) and `true` otherwise,
5622/// which is also what deleting an absent key reports.
5623pub fn delete_property(recv: &Value, key: &str) -> Result<bool, String> {
5624 // 13.5.1.2 step 5 runs `ToObject` on the base, which a nullish one refuses.
5625 // `delete u.x` reported success instead.
5626 if with_host(|h| h.is_nullish(recv)) {
5627 return Err(host::type_error(
5628 "Cannot convert undefined or null to object",
5629 ));
5630 }
5631 // `[[Delete]]` on a Proxy runs the handler's `deleteProperty` trap, which may
5632 // throw — the reason this reports a `Result` rather than a bare `bool`.
5633 if let Some(b) = crate::proxy::delete(recv, key)? {
5634 return Ok(b);
5635 }
5636 // 10.4.5.4: a typed array's in-range index is not configurable, so
5637 // `delete u8[0]` is false; an index past the end does not exist, so true.
5638 if crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray") {
5639 if let Ok(i) = key.parse::<usize>() {
5640 let len = get_property(recv, "length")
5641 .ok()
5642 .map_or(0.0, |l| with_host(|h| h.to_number(&l)));
5643 return Ok((i as f64) >= len);
5644 }
5645 }
5646 // `delete globalThis.x` removes a global a script created. It lives in the
5647 // globals map, not the object's property map, so the ordinary path reported
5648 // success and removed nothing — the binding stayed readable afterwards.
5649 if with_host(|h| h.is_global_object(recv)) && with_host(|h| h.remove_global(key)) {
5650 return Ok(true);
5651 }
5652 // `delete require.cache[id]` drops the module so the next `require` of that
5653 // file runs it again — the whole point of exposing the cache.
5654 if peek(recv, |o| match o {
5655 JsObj::Builtin(ns) => Some(ns == REQUIRE_CACHE),
5656 _ => None,
5657 }) == Some(true)
5658 {
5659 return Ok(crate::module::cache_delete(key));
5660 }
5661 // `delete process.env.X` unsets the variable in the PROCESS, not just in the
5662 // JS view, so a child spawned afterwards no longer sees it.
5663 if !key.starts_with("@@")
5664 && with_host(
5665 |h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@envObject")),
5666 )
5667 {
5668 std::env::remove_var(key);
5669 }
5670 // A member of a builtin NAMESPACE (`Math.PI`, `Number.MAX_VALUE`,
5671 // `Object.prototype`) is non-configurable when it is a constant or a
5672 // constructor's `prototype`, and `delete` of one answers false without
5673 // removing anything. There is no property map behind a namespace, so the
5674 // ordinary attribute lookup below cannot tell — it reported success for
5675 // every one of them.
5676 // A REAL intrinsic prototype object carries the write in its own map AND in
5677 // the side table the instance read consults, so the delete has to clear
5678 // both. Clearing only the map left `Object.prototype.patch` deleted as far
5679 // as the prototype was concerned and still inherited by every object.
5680 if let Some(ns) = with_host(|h| {
5681 h.intrinsic_proto_ctor(recv)
5682 .map(str::to_string)
5683 .or_else(|| (h.object_proto() == *recv).then(|| "Object".to_string()))
5684 }) {
5685 with_host(|h| h.remove_builtin_static(&format!("{ns}.prototype"), key));
5686 }
5687 if let Some(ns) = peek(recv, |o| match o {
5688 JsObj::Builtin(ns) => Some(ns.clone()),
5689 _ => None,
5690 }) {
5691 // A script-assigned static is an ordinary configurable property and is
5692 // removed from the side table the assignment landed in. Falling through
5693 // to the attribute check below answered true and deleted nothing, so a
5694 // patch survived its own `delete`.
5695 if with_host(|h| h.remove_builtin_static(&ns, key)) {
5696 return Ok(true);
5697 }
5698 if ns != REQUIRE_CACHE && !builtin_member_configurable(&ns, key) {
5699 return Ok(false);
5700 }
5701 }
5702 if !with_host(|h| h.prop_attrs(recv, key).configurable) {
5703 return Ok(false);
5704 }
5705 if let Ok(i) = key.parse::<usize>() {
5706 with_host(|h| h.unmap_argument(recv, i));
5707 }
5708 // An accessor lives in its own table, not the property map, so removing it
5709 // has to be explicit — otherwise `delete` reported success while the getter
5710 // kept answering and `in` kept reporting the key.
5711 if with_host(|h| h.own_accessor(recv, key).is_some()) {
5712 with_host(|h| h.remove_accessor(recv, key));
5713 return Ok(true);
5714 }
5715 with_host(|h| {
5716 let index = key.parse::<usize>();
5717 match h.get_mut(recv) {
5718 Some(JsObj::Object(props)) => {
5719 props.shift_remove(key);
5720 return;
5721 }
5722 Some(JsObj::Array(items)) => {
5723 if let Ok(i) = index {
5724 if i < items.len() {
5725 // `delete a[i]` punches a HOLE: the length is unchanged
5726 // but the index stops being an own property.
5727 items[i] = Value::Undef;
5728 h.mark_hole(recv, i);
5729 }
5730 return;
5731 }
5732 }
5733 _ => {}
5734 }
5735 // A non-index key on an array (`arr.foo`, `arr[sym]`), or any own key on
5736 // a function/class, is an ordinary own property kept in the side table.
5737 h.remove_fn_prop(recv, key);
5738 // A function's `length`/`name` are synthesized rather than stored, so
5739 // deleting one leaves a tombstone for the readers to honour.
5740 h.mark_fn_intrinsic_deleted(recv, key);
5741 });
5742 Ok(true)
5743}
5744
5745fn b_delitem(vm: &mut VM, _: u8) -> Value {
5746 let strict = vm.pop();
5747 let idx = vm.pop();
5748 let recv = vm.pop();
5749 // `delete o[k]` keys through ToPropertyKey (7.1.19), exactly as the read and
5750 // the write do: `String(k)` would turn a Symbol into its `Symbol(desc)`
5751 // description and delete a key nothing ever wrote.
5752 let key = match host::to_property_key(&idx) {
5753 Ok(k) => k,
5754 Err(e) => return abort(vm, e),
5755 };
5756 match delete_property(&recv, &key) {
5757 Ok(false) if with_host(|h| h.truthy(&strict)) => {
5758 abort(vm, refused_delete_error(&recv, &key))
5759 }
5760 Ok(b) => Value::Bool(b),
5761 Err(e) => abort(vm, e),
5762 }
5763}
5764
5765fn b_delprop_name(vm: &mut VM, _: u8) -> Value {
5766 let strict = vm.pop();
5767 let name = sval(&vm.pop());
5768 let recv = vm.pop();
5769 match delete_property(&recv, &name) {
5770 Ok(false) if with_host(|h| h.truthy(&strict)) => {
5771 abort(vm, refused_delete_error(&recv, &name))
5772 }
5773 Ok(b) => Value::Bool(b),
5774 Err(e) => abort(vm, e),
5775 }
5776}
5777
5778/// The TypeError a STRICT `delete` of a non-configurable property raises. The
5779/// receiver renders the way every other brand-check message renders one.
5780fn refused_delete_error(recv: &Value, key: &str) -> String {
5781 // A PROXY names the trap that refused. Only the `delete` OPERATOR reports
5782 // it; `Reflect.deleteProperty` answers `false`, which is why this lives
5783 // here rather than in the shared `[[Delete]]`.
5784 if let Some(e) = crate::esm::namespace_refusal(recv, crate::esm::Refused::Delete, key) {
5785 return e;
5786 }
5787 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
5788 return host::type_error(&format!(
5789 "'deleteProperty' on proxy: trap returned falsish for property '{key}'"
5790 ));
5791 }
5792 // A non-callable builtin NAMESPACE renders as a plain object here — node
5793 // reports `#<Object>` for `Math`, not its `[object Math]` brand.
5794 let shown = match peek(recv, |o| match o {
5795 JsObj::Builtin(ns) => Some(ns.clone()),
5796 _ => None,
5797 }) {
5798 Some(ns) if !host::builtin_is_callable(&ns) => "#<Object>".to_string(),
5799 _ => no_side_effects_string(recv),
5800 };
5801 host::type_error(&format!("Cannot delete property '{key}' of {shown}"))
5802}
5803
5804// ── constructors ──────────────────────────────────────────────────────────────
5805
5806fn b_mkstr(vm: &mut VM, argc: u8) -> Value {
5807 let parts = pop_n(vm, argc as usize);
5808 let s: String = with_host(|h| parts.iter().map(|p| h.str_of(p)).collect());
5809 with_host(|h| h.new_str(s))
5810}
5811
5812fn b_mkarr(vm: &mut VM, argc: u8) -> Value {
5813 let items = pop_n(vm, argc as usize);
5814 with_host(|h| h.new_array(items))
5815}
5816
5817/// `MARK_HOLE [arr, index]`: record `arr[index]` as an ELIDED element. Emitted
5818/// only for an array literal that actually contains an elision, so a dense
5819/// literal costs nothing. Returns `undefined`; the array stays on the stack
5820/// underneath (the compiler `Dup`s it).
5821fn b_mark_hole(vm: &mut VM, _: u8) -> Value {
5822 let idx = vm.pop();
5823 let arr = vm.pop();
5824 let i = match idx {
5825 Value::Int(i) if i >= 0 => i as usize,
5826 _ => return Value::Undef,
5827 };
5828 with_host(|h| h.mark_hole(&arr, i));
5829 Value::Undef
5830}
5831
5832fn b_mkobj(vm: &mut VM, argc: u8) -> Value {
5833 let flat = pop_n(vm, argc as usize);
5834 let mut props: IndexMap<String, Value> = IndexMap::new();
5835 // A literal `__proto__: x` key sets the object's prototype (not an own prop).
5836 let mut proto_override: Option<Value> = None;
5837 let mut method_keys: Vec<String> = Vec::new();
5838 let mut i = 0;
5839 while i + 2 < flat.len() || (i + 2 == flat.len() && flat.len() % 3 == 0 && i < flat.len()) {
5840 if i + 2 >= flat.len() {
5841 break;
5842 }
5843 // Tag 2: an ACCESSOR's position. An accessor lives in its own table, so
5844 // the literal reserves its slot here with the `@@ord:` marker key that
5845 // `own_enum_data_keys` resolves back — otherwise `{ get g(){}, d: 2 }`
5846 // enumerated `d, g`, because `DEF_ACCESSOR` runs after `MKOBJ` and its
5847 // marker landed at the end.
5848 if matches!(flat[i], Value::Int(2)) {
5849 let key = with_host(|h| h.str_of(&flat[i + 1]));
5850 props
5851 .entry(format!("{}{key}", host::ORD_MARKER))
5852 .or_insert(Value::Undef);
5853 i += 3;
5854 continue;
5855 }
5856 // Tag 3: a METHOD DEFINITION — an ordinary property whose key is also
5857 // recorded so the literal can become its `[[HomeObject]]` below.
5858 if matches!(flat[i], Value::Int(3)) {
5859 let key = with_host(|h| h.str_of(&flat[i + 1]));
5860 method_keys.push(key.clone());
5861 props.insert(key, flat[i + 2].clone());
5862 i += 3;
5863 continue;
5864 }
5865 let spread = matches!(flat[i], Value::Int(1));
5866 if spread {
5867 let src = flat[i + 1].clone();
5868 // A STRING source spreads its index properties (`{..."ab"}` is
5869 // `{0:'a',1:'b'}`): CopyDataProperties (7.3.25) calls ToObject, and a
5870 // String exotic object owns one enumerable property per UTF-16 code
5871 // UNIT (10.4.3). `own_enum_entries_deep` only walks heap objects, so
5872 // a string source contributed nothing and `{..."ab"}` was `{}`.
5873 // Every other primitive (number/boolean/symbol) boxes to an object
5874 // with no own enumerable properties, and null/undefined are ignored,
5875 // so those correctly stay no-ops on the path below.
5876 if let Some(s) = with_host(|h| h.as_str(&src)) {
5877 for idx in 0..crate::utf16::len(&s) {
5878 if let Ok(ch) = get_property(&src, &idx.to_string()) {
5879 props.insert(idx.to_string(), ch);
5880 }
5881 }
5882 i += 3;
5883 continue;
5884 }
5885 // Object spread copies own *enumerable* properties only — never the
5886 // hidden `@@…` slots (copying `@@native` used to turn `{...buf}`
5887 // into something that still claimed to be a Buffer) and never a
5888 // property a descriptor marked non-enumerable.
5889 // A getter that throws during spread propagates as a thrown value,
5890 // which in the VM means aborting the frame.
5891 let entries = match host::own_enum_entries_deep(&src) {
5892 Ok(e) => e,
5893 Err(e) => return abort(vm, e),
5894 };
5895 for (k, v) in entries {
5896 props.insert(k, v);
5897 }
5898 // `CopyDataProperties` (7.3.25) copies own enumerable SYMBOL keys
5899 // too — only `Object.keys`/`for-in`/`JSON.stringify` skip them.
5900 for (k, v) in with_host(|h| h.own_symbol_entries(&src)) {
5901 props.insert(k, v);
5902 }
5903 } else {
5904 let key = with_host(|h| h.str_of(&flat[i + 1]));
5905 let computed = matches!(flat[i], Value::Int(4));
5906 if key == "__proto__" && !computed {
5907 proto_override = Some(flat[i + 2].clone());
5908 } else {
5909 props.insert(key, flat[i + 2].clone());
5910 }
5911 }
5912 i += 3;
5913 }
5914 with_host(|h| {
5915 let o = h.new_object(props);
5916 if let Some(p) = proto_override {
5917 if matches!(p, Value::Obj(_)) {
5918 h.set_proto(&o, p);
5919 }
5920 }
5921 // A method DEFINED here takes the literal as its `[[HomeObject]]`, which
5922 // is what `super` inside it resolves through. The home object is fixed
5923 // at definition, so a method that merely arrives as a value
5924 // (`{ m: other.m }`) keeps the one it was defined with — stamping every
5925 // method-valued property instead rebound the original and changed what
5926 // IT resolved.
5927 for key in &method_keys {
5928 let m = match h.get(&o) {
5929 Some(JsObj::Object(p)) => p.get(key).cloned(),
5930 _ => None,
5931 };
5932 if let Some(m) = m {
5933 if let Some(JsObj::Func(f)) = h.get_mut(&m) {
5934 f.home_object = Some(o.clone());
5935 }
5936 }
5937 }
5938 o
5939 })
5940}
5941
5942fn b_mkfunc(vm: &mut VM, _: u8) -> Value {
5943 let def_id = match vm.pop() {
5944 Value::Int(n) => n as usize,
5945 Value::Float(f) => f as usize,
5946 _ => return abort(vm, "internal: MKFUNC id".into()),
5947 };
5948 let (is_arrow, self_name) = with_host(|h| match h.funcs.get(def_id) {
5949 Some(d) => (
5950 d.is_arrow,
5951 (d.self_name && !d.name.is_empty()).then(|| d.name.clone()),
5952 ),
5953 None => (false, None),
5954 });
5955 with_host(|h| {
5956 let mut env = h.current_env_capture();
5957 let this = h.current_this();
5958 let new_target = if is_arrow {
5959 h.current_new_target()
5960 } else {
5961 None
5962 };
5963 // An arrow has no `super` of its own: it uses the enclosing METHOD's,
5964 // exactly as it uses the enclosing `this`. Nothing was captured, so
5965 // `super.m()` inside an arrow reported the method missing — in a class
5966 // method as well as an object literal.
5967 let (home_class, home_static, home_object) = if is_arrow {
5968 h.current_home()
5969 } else {
5970 (None, false, None)
5971 };
5972 // A named function expression closes over an extra scope holding its own
5973 // name, so the body can recurse through it (`function f(){ … f() … }`)
5974 // independently of whatever the outer binding is later set to.
5975 if self_name.is_some() {
5976 env = host::child_env(env);
5977 }
5978 let f = h.alloc(JsObj::Func(FuncVal {
5979 def_id,
5980 env: Some(env.clone()),
5981 this,
5982 is_arrow,
5983 home_class,
5984 home_static,
5985 home_object,
5986 new_target,
5987 }));
5988 if let Some(n) = self_name {
5989 env.borrow_mut().vars.insert(n, f.clone());
5990 }
5991 f
5992 })
5993}
5994
5995// ── truthiness / coercion / equality ──────────────────────────────────────────
5996
5997fn b_truthy(vm: &mut VM, _: u8) -> Value {
5998 let v = vm.pop();
5999 Value::Bool(with_host(|h| h.truthy(&v)))
6000}
6001
6002fn b_nullish(vm: &mut VM, _: u8) -> Value {
6003 let v = vm.pop();
6004 Value::Bool(with_host(|h| h.is_nullish(&v)))
6005}
6006
6007fn b_tostr(vm: &mut VM, _: u8) -> Value {
6008 let v = vm.pop();
6009 // ToString with user-`toString`/`valueOf` dispatch (template interpolation,
6010 // `String(x)`, object keys).
6011 match host::to_string_value(&v) {
6012 Ok(s) => s,
6013 Err(e) => abort(vm, e),
6014 }
6015}
6016
6017fn b_typeof(vm: &mut VM, _: u8) -> Value {
6018 let v = vm.pop();
6019 with_host(|h| {
6020 let t = h.type_of(&v);
6021 h.new_str(t)
6022 })
6023}
6024
6025/// `typeof <bare ident>`: read the name like `b_getlocal` but return "undefined"
6026/// (never a ReferenceError) when the name is unbound — JS `typeof` semantics.
6027fn b_typeof_name(vm: &mut VM, _: u8) -> Value {
6028 let name = sval(&vm.pop());
6029 // `typeof` does NOT excuse the temporal dead zone: it answers "undefined"
6030 // for an UNBOUND name, but a `let` above its declaration is bound and
6031 // throws. Reading the marker's type answered "function".
6032 if with_host(|h| h.is_tdz_global(&name) && h.read_name(&name).is_none()) {
6033 return abort(vm, host::tdz_error(&name));
6034 }
6035 if let Some(v) = with_host(|h| h.read_name(&name)) {
6036 if with_host(|h| h.is_tdz(&v)) {
6037 return abort(vm, host::tdz_error(&name));
6038 }
6039 }
6040 // Bound name (user variable) → typeof its value.
6041 if let Some(v) = with_host(|h| h.read_name(&name)) {
6042 return with_host(|h| {
6043 let t = h.type_of(&v);
6044 h.new_str(t)
6045 });
6046 }
6047 // Lazily-bound globals resolve through `global_binding`, the same lookup
6048 // `b_getlocal` uses, so `typeof crypto` cannot answer "undefined" for a
6049 // name that `crypto.randomUUID()` reads successfully.
6050 match global_binding(&name) {
6051 Some(v) => with_host(|h| {
6052 let t = h.type_of(&v);
6053 h.new_str(t)
6054 }),
6055 None => with_host(|h| h.new_str("undefined")),
6056 }
6057}
6058
6059fn b_strict_eq(vm: &mut VM, _: u8) -> Value {
6060 let b = vm.pop();
6061 let a = vm.pop();
6062 Value::Bool(with_host(|h| h.strict_eq(&a, &b)))
6063}
6064
6065fn b_loose_eq(vm: &mut VM, _: u8) -> Value {
6066 let b = vm.pop();
6067 let a = vm.pop();
6068 // Abstract Equality steps 10-11 (7.2.15): object ⇄ primitive converts the
6069 // object with `ToPrimitive` — a JS `valueOf`/`Symbol.toPrimitive` call, so it
6070 // runs before the host borrow. Object ⇄ object stays a reference check.
6071 let (a, b) = match with_host(|h| (host::is_primitive(h, &a), host::is_primitive(h, &b))) {
6072 (false, true) if coerces_against_object(&b) => match host::to_primitive(&a, "default") {
6073 Ok(p) => (p, b),
6074 Err(e) => return abort(vm, e),
6075 },
6076 (true, false) if coerces_against_object(&a) => match host::to_primitive(&b, "default") {
6077 Ok(p) => (a, p),
6078 Err(e) => return abort(vm, e),
6079 },
6080 _ => (a, b),
6081 };
6082 Value::Bool(with_host(|h| h.loose_eq(&a, &b)))
6083}
6084
6085fn b_instanceof(vm: &mut VM, _: u8) -> Value {
6086 let ctor = vm.pop();
6087 let obj = vm.pop();
6088 match host::instance_of(&obj, &ctor) {
6089 Ok(b) => Value::Bool(b),
6090 Err(e) => abort(vm, e),
6091 }
6092}
6093
6094// ── bitwise / unary ───────────────────────────────────────────────────────────
6095
6096fn b_binop(vm: &mut VM, _: u8) -> Value {
6097 let b = vm.pop();
6098 let a = vm.pop();
6099 let tag = match vm.pop() {
6100 Value::Int(n) => n,
6101 _ => 0,
6102 };
6103 // Both operands are ToPrimitive-d with the number hint before ToInt32
6104 // (ECMA-262 13.12.1), which has to happen outside the host borrow.
6105 let r = host::to_primitive(&a, "number")
6106 .and_then(|a| host::to_primitive(&b, "number").map(|b| (a, b)))
6107 .and_then(|(a, b)| with_host(|h| h.bitwise(tag, &a, &b)));
6108 finish(vm, r)
6109}
6110
6111fn b_unary(vm: &mut VM, _: u8) -> Value {
6112 let v = vm.pop();
6113 let tag = match vm.pop() {
6114 Value::Int(n) => n,
6115 _ => 0,
6116 };
6117 // Unary `+`/`~` on a BigInt: `+` is a hard TypeError in JS; `~x` is `-x - 1`
6118 // computed in arbitrary precision.
6119 if with_host(|h| h.is_bigint_val(&v)) {
6120 return match tag {
6121 host::unop::POS => abort(
6122 vm,
6123 host::type_error("Cannot convert a BigInt value to a number"),
6124 ),
6125 host::unop::BITNOT => {
6126 let b = with_host(|h| h.as_bigint(&v)).unwrap();
6127 let r = -(b + num_bigint::BigInt::from(1));
6128 with_host(|h| h.new_bigint(r))
6129 }
6130 _ => Value::Undef,
6131 };
6132 }
6133 // `ToNumber` outside the host borrow: an object operand's `valueOf` /
6134 // `Symbol.toPrimitive` is a JS call, so it cannot run under `with_host`.
6135 let n = match host::to_number_value(&v) {
6136 Ok(n) => n,
6137 Err(e) => return abort(vm, e),
6138 };
6139 match tag {
6140 host::unop::POS => Value::Float(n),
6141 host::unop::BITNOT => {
6142 let i = if n.is_finite() {
6143 n.trunc() as i64 as i32
6144 } else {
6145 0
6146 };
6147 Value::Float(!i as f64)
6148 }
6149 _ => Value::Undef,
6150 }
6151}
6152
6153// ── membership ────────────────────────────────────────────────────────────────
6154
6155fn b_contains(vm: &mut VM, _: u8) -> Value {
6156 let container = vm.pop();
6157 let key = vm.pop();
6158 // `x in y` requires y to be an object. V8 names both operands:
6159 // `Cannot use 'in' operator to search for 'a' in 5`.
6160 // A heap-backed PRIMITIVE — a string, a symbol, a bigint — is a
6161 // `Value::Obj` in this host but is not an object, so the shape test alone
6162 // let `'length' in 'ab'` and `'description' in Symbol('x')` answer `true`
6163 // where node throws. `is_primitive` is the same predicate `ToObject` and
6164 // `typeof` use, so the three cannot disagree about what an object is.
6165 if !matches!(container, Value::Obj(_)) || with_host(|h| host::is_primitive(h, &container)) {
6166 let (k, c) = with_host(|h| (h.property_key(&key), h.str_of(&container)));
6167 return abort(
6168 vm,
6169 host::type_error(&format!(
6170 "Cannot use 'in' operator to search for '{k}' in {c}"
6171 )),
6172 );
6173 }
6174 let k = match host::to_property_key(&key) {
6175 Ok(k) => k,
6176 Err(e) => return abort(vm, e),
6177 };
6178 match has_property(&container, &k) {
6179 Ok(b) => Value::Bool(b),
6180 Err(e) => abort(vm, e),
6181 }
6182}
6183
6184// ── control ───────────────────────────────────────────────────────────────────
6185
6186fn b_sig_return(vm: &mut VM, _: u8) -> Value {
6187 let v = vm.pop();
6188 with_host(|h| h.signal = Some(host::Signal::Return(v.clone())));
6189 vm.ip = vm.chunk.ops.len();
6190 v
6191}
6192
6193/// `break [label]` whose target loop lives in an enclosing chunk (the statement is
6194/// inside a `try` block, which the host runs as its own chunk). Raise the signal
6195/// and halt this chunk; `SIG_UNWIND` after the `TRY` op re-dispatches it.
6196fn b_sig_break(vm: &mut VM, _: u8) -> Value {
6197 let label = sval(&vm.pop());
6198 let label = (!label.is_empty()).then_some(label);
6199 with_host(|h| h.signal = Some(host::Signal::Break(label)));
6200 vm.ip = vm.chunk.ops.len();
6201 Value::Undef
6202}
6203
6204/// `continue [label]` out of a `try` block — see [`b_sig_break`].
6205fn b_sig_continue(vm: &mut VM, _: u8) -> Value {
6206 let label = sval(&vm.pop());
6207 let label = (!label.is_empty()).then_some(label);
6208 with_host(|h| h.signal = Some(host::Signal::Continue(label)));
6209 vm.ip = vm.chunk.ops.len();
6210 Value::Undef
6211}
6212
6213/// Dispatch a pending control signal at the instruction after a `TRY`. `tag`
6214/// describes what the `try` is nested in (see [`host::unwind`]):
6215///
6216/// * no signal → `NONE`, execution continues normally;
6217/// * `Return`, or no enclosing loop in this chunk → halt the chunk so the signal
6218/// keeps travelling outward;
6219/// * `break`/`continue` targeting the enclosing loop → consume it and report
6220/// `BREAK`/`CONTINUE` so the compiler-emitted jump lands on the loop's exit /
6221/// continue target;
6222/// * a LABELED `break`/`continue` for some outer loop → report `BREAK` but leave
6223/// the signal pending, so leaving this loop re-dispatches it one level out.
6224fn b_sig_unwind(vm: &mut VM, _: u8) -> Value {
6225 let cont_tag = sval(&vm.pop());
6226 let brk_tag = sval(&vm.pop());
6227 let sig = match with_host(|h| h.signal.clone()) {
6228 Some(s) => s,
6229 None => return Value::Int(host::unwind::NONE),
6230 };
6231 // Nothing in this chunk can catch a `break`: halt so the signal keeps going.
6232 let propagate = |vm: &mut VM| {
6233 vm.ip = vm.chunk.ops.len();
6234 Value::Int(host::unwind::NONE)
6235 };
6236 match &sig {
6237 host::Signal::Return(_) => propagate(vm),
6238 host::Signal::Break(label) => {
6239 if brk_tag == host::unwind::NO_LOOP {
6240 return propagate(vm);
6241 }
6242 let mine = match label {
6243 None => true, // unlabeled: always the innermost enclosing context
6244 Some(l) => brk_tag == *l,
6245 };
6246 if mine {
6247 with_host(|h| h.signal = None);
6248 }
6249 // Not ours: still leave this context by its break exit, keeping the
6250 // signal pending for the next dispatch point one level out.
6251 Value::Int(host::unwind::BREAK)
6252 }
6253 host::Signal::Continue(label) => {
6254 let mine = match label {
6255 // Unlabeled `continue` binds to the innermost continue-catching
6256 // loop — which a `switch` between here and it is NOT.
6257 None => cont_tag != host::unwind::NO_LOOP,
6258 Some(l) => cont_tag == *l,
6259 };
6260 if mine {
6261 with_host(|h| h.signal = None);
6262 return Value::Int(host::unwind::CONTINUE);
6263 }
6264 if brk_tag == host::unwind::NO_LOOP {
6265 return propagate(vm);
6266 }
6267 // The target loop is further out: exit the innermost context here and
6268 // re-dispatch there.
6269 Value::Int(host::unwind::BREAK)
6270 }
6271 }
6272}
6273
6274fn b_throw(vm: &mut VM, _: u8) -> Value {
6275 let v = vm.pop();
6276 let pos = op_pos(vm);
6277 let msg = with_host(|h| {
6278 h.exc = Some(v.clone());
6279 // Prefer an error object's message for the top-level report.
6280 let msg = error_display(h, &v);
6281 if h.source_location(pos).is_some_and(|l| l.internal) {
6282 // The runtime's own JS re-throwing for the program — the ES module
6283 // loader handing back an evaluation error. node reports that
6284 // error as it does a rejection, where it was created.
6285 if let Some(Value::Int(created)) = host::lookup_chain(h, &v, "@@pos") {
6286 h.throw_site = Some(host::ThrowSite {
6287 msg: msg.clone(),
6288 pos: created as u32,
6289 end: 0,
6290 depth: h.stack_depth(),
6291 frames: None,
6292 });
6293 }
6294 } else {
6295 // A `throw` is always a fresh raise, a re-`throw` of a caught value
6296 // included: node's arrow points at the statement that threw last.
6297 h.note_raise(&msg, pos, false);
6298 }
6299 msg
6300 });
6301 abort(vm, msg)
6302}
6303
6304/// `Uncaught Name: message` for a thrown error object, `Uncaught <value>`
6305/// otherwise. `name` is usually inherited (`TypeError.prototype.name`), so it
6306/// is read along the prototype chain — data properties only, since this runs
6307/// inside a host borrow.
6308fn error_display(h: &host::JsHost, v: &Value) -> String {
6309 if let Some(JsObj::Object(props)) = h.get(v) {
6310 if let Some(m) = props.get("message") {
6311 let name = host::lookup_chain(h, v, "name")
6312 .map(|x| h.str_of(&x))
6313 .unwrap_or_else(|| "Error".into());
6314 return format!("Uncaught {name}: {}", h.str_of(m));
6315 }
6316 }
6317 format!("Uncaught {}", h.str_of(v))
6318}
6319
6320fn b_try(vm: &mut VM, _: u8) -> Value {
6321 let id = match vm.pop() {
6322 Value::Int(n) => n as usize,
6323 _ => return abort(vm, "internal: TRY id".into()),
6324 };
6325 // Shape only. Running a `try` used to clone the whole `TryDef` — its block,
6326 // its handler and its finalizer bytecode — every time control entered it,
6327 // which for a `try` inside a loop is once per iteration.
6328 let (has_handler, catch_bind, has_finalizer) = match with_host(|h| h.try_shape(id)) {
6329 Some(t) => t,
6330 None => return abort(vm, "internal: unknown try id".into()),
6331 };
6332 let mut pending: Option<String> = None;
6333 // Each sub-block runs as its own chunk on THIS frame, so a throw part-way
6334 // through can leave block scopes open. Snapshot the scope and restore it
6335 // before the handler and after the whole statement.
6336 let scope = with_host(|h| h.scope_snapshot());
6337
6338 with_host(|h| h.push_scope()); // the try block is its own block scope
6339 let body_res = host::run_chunk_keyed(host::try_key(id, 0), || {
6340 with_host(|h| h.try_chunk(id, 0)).expect("try block exists")
6341 });
6342 with_host(|h| h.restore_scope(scope.clone()));
6343 let signal_after = with_host(|h| h.signal.is_some());
6344 if let Err(e) = body_res {
6345 if signal_after {
6346 pending = Some(e);
6347 } else if has_handler {
6348 // Bind the thrown value (or a synthesized error) to the catch param.
6349 let thrown =
6350 with_host(|h| h.exc.clone()).unwrap_or_else(|| with_host(|h| synth_error(h, &e)));
6351 with_host(|h| {
6352 h.error = None;
6353 h.exc = None;
6354 h.throw_site = None;
6355 });
6356 // The catch parameter is block-scoped to the handler.
6357 with_host(|h| h.push_scope());
6358 if let Some(name) = &catch_bind {
6359 with_host(|h| h.declare_name(name, thrown));
6360 }
6361 let hres = host::run_chunk_keyed(host::try_key(id, 1), || {
6362 with_host(|h| h.try_chunk(id, 1)).expect("handler exists")
6363 });
6364 with_host(|h| h.restore_scope(scope.clone()));
6365 if let Err(e2) = hres {
6366 pending = Some(e2);
6367 }
6368 } else {
6369 pending = Some(e);
6370 }
6371 }
6372
6373 // finally always runs; a finally error/signal supersedes.
6374 if has_finalizer {
6375 let sig_before = with_host(|h| h.signal.take());
6376 // The pending throw's VALUE lives in the host, not in `pending`'s
6377 // message, and any throw the finalizer catches for itself overwrites
6378 // it (a nested `try` clears it once handled). It is set aside here and
6379 // put back below when the finalizer completes normally; without that,
6380 // `try { throw o } finally { try { throw 2 } catch {} }` rethrew an
6381 // error synthesized from the message, so `e !== o` and `e.code` was gone.
6382 let pending_thrown = with_host(|h| (h.exc.take(), h.error.take()));
6383 with_host(|h| h.push_scope()); // ditto for `finally`
6384 let fres = host::run_chunk_keyed(host::try_key(id, 2), || {
6385 with_host(|h| h.try_chunk(id, 2)).expect("finalizer exists")
6386 });
6387 with_host(|h| h.restore_scope(scope.clone()));
6388 match fres {
6389 Ok(_) => {
6390 if with_host(|h| h.signal.is_none()) {
6391 // The finalizer completed normally: the try/catch block's own
6392 // abrupt completion resumes, its thrown value included.
6393 with_host(|h| {
6394 h.signal = sig_before;
6395 (h.exc, h.error) = pending_thrown;
6396 });
6397 } else {
6398 // ECMA-262 14.15.3 TryStatement evaluation: when the finalizer's
6399 // completion is abrupt (`return`/`break`/`continue` inside
6400 // `finally`), that completion REPLACES the try/catch block's —
6401 // including a pending throw, which is discarded, not rethrown.
6402 pending = None;
6403 with_host(|h| {
6404 h.error = None;
6405 h.exc = None;
6406 });
6407 }
6408 }
6409 Err(e) => pending = Some(e),
6410 }
6411 }
6412
6413 if let Some(e) = pending {
6414 return abort(vm, e);
6415 }
6416 Value::Undef
6417}
6418
6419/// Synthesize an `Error`-shaped object from an internal error string, linked to
6420/// the matching builtin error prototype so `instanceof`/`.constructor` work.
6421pub(crate) fn synth_error(h: &mut host::JsHost, e: &str) -> Value {
6422 h.ensure_error_protos();
6423 // A `DOMException` marker: the WHATWG error NAME rides in the string, since
6424 // it is not one of the ECMAScript error classes below.
6425 if let Some(rest) = e.strip_prefix(host::DOM_MARK) {
6426 if let Some((name, msg)) = rest.split_once('\u{1}') {
6427 return dom_exception_with(h, name, msg);
6428 }
6429 }
6430 // A `Name [ERR_CODE]: message` head carries a Node error `code` next to the
6431 // error class, exactly as Node's internal errors render it in `.stack`.
6432 let (head, rest) = match e.split_once(": ") {
6433 Some((n, m)) => (n, m.to_string()),
6434 None => ("", e.to_string()),
6435 };
6436 let (base, code) = match head.split_once(" [") {
6437 Some((n, c)) if c.ends_with(']') => (n, Some(c[..c.len() - 1].to_string())),
6438 _ => (head, None),
6439 };
6440 let (name, mut message) = if host::ERROR_NAMES.contains(&base) {
6441 (base.to_string(), rest)
6442 } else {
6443 ("Error".to_string(), e.to_string())
6444 };
6445 // A `host::plain_coded_error` marker: the code rides at the head of the
6446 // MESSAGE rather than in the class, because Node's native-layer errors set
6447 // `.code` while leaving `String(err)` unbracketed (`TypeError: Invalid URL`
6448 // with `code === 'ERR_INVALID_URL'`). Strip it back off here — the marker is
6449 // internal and must never reach a user-visible `.message`.
6450 let mut code = code;
6451 // Whether `String(err)`/`err.stack` show `Name [CODE]:` — true for the
6452 // bracketed head, false for the marker form.
6453 let mut bracketed = code.is_some();
6454 // Extra own properties (`input`, `base`) from `host::plain_coded_error_with`.
6455 let mut fields: Vec<(String, String)> = Vec::new();
6456 if let Some(rest) = message.strip_prefix(host::CODE_MARK) {
6457 if let Some((c, m)) = rest.split_once('\u{1}') {
6458 code = Some(c.to_string());
6459 bracketed = false;
6460 let (m, fs) = host::split_error_fields(m);
6461 fields = fs
6462 .into_iter()
6463 .map(|(k, v)| (k.to_string(), v.to_string()))
6464 .collect();
6465 message = m.to_string();
6466 }
6467 }
6468 let label = match (&code, bracketed) {
6469 (Some(c), true) => format!("{name} [{c}]"),
6470 _ => name.clone(),
6471 };
6472 let frames = h.raise_frames(e);
6473 let stack = if message.is_empty() {
6474 format!("{label}{frames}")
6475 } else {
6476 format!("{label}: {message}{frames}")
6477 };
6478 let sv = h.new_str(stack);
6479 // Own-key order as node reports it: the captured `stack` first; then a
6480 // Node JS-layer (bracketed) error has `code` before `message`
6481 // (`['stack', 'code', 'message']` for `Buffer.from(5)`), while a
6482 // native-layer one has `message` before `code` and its extra fields
6483 // (`['stack', 'message', 'code', 'input']` for `new URL('bad')`).
6484 let mut props: IndexMap<String, Value> = IndexMap::new();
6485 props.insert("stack".into(), sv);
6486 let cv = code.as_ref().map(|c| h.new_str(c.clone()));
6487 if let (true, Some(cv)) = (bracketed, &cv) {
6488 props.insert("code".into(), cv.clone());
6489 }
6490 let mv = h.new_str(message.clone());
6491 props.insert("message".into(), mv);
6492 if let Some(cv) = cv {
6493 // Already placed for a bracketed error; IndexMap keeps that position.
6494 props.insert("code".into(), cv);
6495 for (k, v) in fields {
6496 let fv = h.new_str(v);
6497 props.insert(k, fv);
6498 }
6499 if bracketed {
6500 // Marks this as a Node JS-layer error, whose `toString` brackets the
6501 // code. A native-layer error has the same `.code` and does not.
6502 props.insert("@@nodeError".into(), Value::Bool(true));
6503 }
6504 }
6505 // A libuv system-error message is itself the canonical encoding of the
6506 // error's metadata — `ENOENT: no such file or directory, open '/x'` — so a
6507 // filesystem/network failure recovers the enumerable `code`/`errno`/
6508 // `syscall`/`path` own properties that `err.code === 'ENOENT'` checks (the
6509 // single most common error-handling idiom in Node packages) depend on.
6510 for (k, v) in syscall_error_fields(&message) {
6511 let sv = match v {
6512 SysField::Str(s) => h.new_str(s),
6513 SysField::Num(n) => Value::Float(n),
6514 };
6515 props.insert(k.into(), sv);
6516 }
6517 // An error the runtime raised was created where it was raised — the place
6518 // an unhandled rejection of it, or a re-throw by the runtime's own JS,
6519 // reports (see `host::fatal_report`).
6520 let raised_at = h.throw_site.as_ref().filter(|s| s.msg == e).map(|s| s.pos);
6521 if let Some(pos) = raised_at {
6522 props.insert("@@pos".into(), Value::Int(pos as i64));
6523 }
6524 let obj = h.new_object(props);
6525 if let Some(p) = host::error_proto_of(h, &name) {
6526 h.set_proto(&obj, p);
6527 }
6528 // `message`/`stack` are non-enumerable; a Node `ERR_*` error's `code` is not
6529 // (`Object.keys(e)` on an `ERR_INVALID_ARG_TYPE` reads `["code"]`).
6530 h.hide_prop(&obj, "message");
6531 h.hide_prop(&obj, "stack");
6532 if raised_at.is_some() {
6533 h.hide_prop(&obj, "@@pos");
6534 }
6535 obj
6536}
6537
6538enum SysField {
6539 Str(String),
6540 Num(f64),
6541}
6542
6543/// Decompose a libuv-shaped message (`ECODE: reason, syscall 'path'`) into the
6544/// own properties Node hangs off a system error. Returns empty for any message
6545/// that is not in that shape.
6546fn syscall_error_fields(message: &str) -> Vec<(&'static str, SysField)> {
6547 let (code, rest) = match message.split_once(": ") {
6548 Some((c, r))
6549 if c.len() >= 2
6550 && c.starts_with('E')
6551 && c.bytes()
6552 .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) =>
6553 {
6554 (c, r)
6555 }
6556 _ => return Vec::new(),
6557 };
6558 let mut out: Vec<(&'static str, SysField)> = vec![
6559 ("errno", SysField::Num(errno_for(code))),
6560 ("code", SysField::Str(code.to_string())),
6561 ];
6562 // `reason, syscall 'path'` — the path is optional (`EPIPE: …, write`).
6563 if let Some((_, tail)) = rest.split_once(", ") {
6564 let (syscall, path) = match tail.split_once(" '") {
6565 // A two-path message ends `'from' -> 'to'`; `err.path` is the FIRST
6566 // one, so the scan stops at its closing quote rather than at the
6567 // end of the line — which had been swallowing `' -> 'dest` into the
6568 // path for every `rename` and `copyFile` failure.
6569 Some((s, p)) => (s, p.split_once('\'').map(|(first, _)| first)),
6570 None => (tail, None),
6571 };
6572 out.push(("syscall", SysField::Str(syscall.to_string())));
6573 if let Some(p) = path {
6574 out.push(("path", SysField::Str(p.to_string())));
6575 }
6576 }
6577 out
6578}
6579
6580/// The negative `errno` Node reports for a libuv error code on this platform.
6581/// It is the platform's own number (`ENOTEMPTY` is 66 on macOS, 39 on Linux),
6582/// from the table `util.getSystemErrorMap` reports; a code outside it reports
6583/// the `EIO` number rather than inventing a value.
6584fn errno_for(code: &str) -> f64 {
6585 let n = crate::stdlib::util::errno_by_name(code).map_or(libc::EIO, |(n, _)| n);
6586 -f64::from(n)
6587}
6588
6589// ── iteration ─────────────────────────────────────────────────────────────────
6590
6591fn b_getiter(vm: &mut VM, _: u8) -> Value {
6592 let v = vm.pop();
6593 // A generator is its own iterator (resumed lazily by FORITER).
6594 if with_host(|h| h.is_generator_val(&v)) {
6595 return v;
6596 }
6597 // A Proxy's iterator comes from its traps (`crate::proxy::get_iterator`):
6598 // the `lookup_chain` probe below reads the property map a proxy does not
6599 // have. It is stepped like any other, so the body runs between steps.
6600 if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
6601 return match crate::proxy::get_iterator(&v) {
6602 Ok(Some(it)) => it,
6603 Ok(None) => abort(vm, "internal: kind_of said Proxy".into()),
6604 Err(e) => abort(vm, e),
6605 };
6606 }
6607 // Arrays and strings take the direct path below: they have no iterator
6608 // state to preserve and are the hot case, so they must not pay a property
6609 // lookup and a call per loop.
6610 let direct = matches!(
6611 with_host(|h| h.kind_of(&v)),
6612 Some(ObjKind::Array) | Some(ObjKind::Str)
6613 );
6614 // …but only while their `Symbol.iterator` is still reachable. It comes from
6615 // the intrinsic prototype, so replacing the link takes it away: node reports
6616 // `a is not iterable` for an array whose prototype is a plain object, where
6617 // the fast path below iterated the backing vector regardless.
6618 if !own_intrinsic_reachable(&v)
6619 && !matches!(
6620 get_property(&v, "@@iterator"),
6621 Ok(ref f) if with_host(|h| host::is_callable(h, f))
6622 )
6623 {
6624 let shown = with_host(|h| h.inspect(&v));
6625 let msg = host::type_error(&format!("{shown} is not iterable"));
6626 return abort(vm, host::name_call_site(vm, &shown, msg));
6627 }
6628 // Anything else with a `Symbol.iterator`: call it for the iterator object.
6629 //
6630 // Resolved as a full property READ, not a stored-property lookup. A
6631 // NATIVE-tagged object (`URLSearchParams`, `Headers`, `Map`, `Set`)
6632 // dispatches its methods through the stdlib table rather than a property
6633 // map, so a `lookup_chain` probe found nothing and the loop fell through to
6634 // materializing the value — which threw for `URLSearchParams` and
6635 // snapshotted for `Map`. Spreading the same object already worked, because
6636 // that path had been fixed and this one had not.
6637 if !direct {
6638 if let Ok(iter_fn) = get_property(&v, "@@iterator") {
6639 if with_host(|h| host::is_callable(h, &iter_fn)) {
6640 return match host::call_iterator_method(&iter_fn, &v) {
6641 Ok(it) => it,
6642 Err(e) => abort(vm, e),
6643 };
6644 }
6645 }
6646 }
6647 // An array is iterated live, as its `values()` iterator does: a snapshot
6648 // missed every push during the loop, so a worklist `for (const n of q)
6649 // q.push(…)` stopped after the first element.
6650 if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Array) {
6651 return array_iterator(&v, host::ArrayIterKind::Values);
6652 }
6653 match with_host(|h| h.iter_vec(&v)) {
6654 Ok(items) => with_host(|h| {
6655 h.alloc(JsObj::Iter {
6656 items,
6657 idx: 0,
6658 array: None,
6659 brand: None,
6660 })
6661 }),
6662 // V8 names the SOURCE EXPRESSION, not the value: `for (const x of a)`
6663 // reports `a is not iterable`. The text was recorded for this op.
6664 Err(e) => {
6665 let shown = with_host(|h| h.inspect(&v));
6666 let named = host::name_call_site(vm, &shown, e);
6667 abort(vm, named)
6668 }
6669 }
6670}
6671
6672fn b_forin_keys(vm: &mut VM, _: u8) -> Value {
6673 let v = vm.pop();
6674 // `for-in` over a Proxy is 14.7.5.9 `EnumerateObjectProperties`: the
6675 // `ownKeys` trap filtered by `[[GetOwnProperty]]`'s `enumerable`. Both traps
6676 // are user code, so this cannot run inside `enum_keys`'s `&mut` host borrow.
6677 if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
6678 // `ownKeys` ONLY. The `enumerable` filter is 14.7.5.10's per-key
6679 // `[[GetOwnProperty]]`, which `FORIN_ALIVE` runs at the moment each key
6680 // is visited — so the `getOwnPropertyDescriptor` traps interleave with
6681 // the body the way node's do, instead of all firing up front.
6682 return match crate::proxy::own_keys(&v) {
6683 // EnumerateObjectProperties reaches the prototype next
6684 // (`[[GetPrototypeOf]]`, through the trap), which is observable.
6685 Ok(keys) => match crate::proxy::get_prototype_of(&v) {
6686 Err(e) => abort(vm, e),
6687 Ok(_) => with_host(|h| {
6688 let out: Vec<Value> = keys
6689 .unwrap_or_default()
6690 .into_iter()
6691 .filter(|k| !host::is_symbol_key(k))
6692 .map(|k| h.new_str(k))
6693 .collect();
6694 h.new_array(out)
6695 }),
6696 },
6697 Err(e) => abort(vm, e),
6698 };
6699 }
6700 let mut keys = with_host(|h| h.enum_keys(&v));
6701 // A member patched onto the receiver's INTRINSIC prototype is enumerable
6702 // and inherited, so `for-in` visits it after the own keys — but the
6703 // intrinsic prototypes are not links `enum_keys` can walk, so its chain
6704 // pass never reaches them.
6705 if !with_host(|h| h.has_null_proto(&v)) {
6706 let seen: Vec<String> = keys.iter().map(|k| with_host(|h| h.str_of(k))).collect();
6707 for ns in intrinsic_proto_namespaces(&v) {
6708 for k in with_host(|h| h.builtin_static_keys(&ns)) {
6709 if !seen.contains(&k) && !intrinsic_proto_member(&ns, &k) {
6710 keys.push(with_host(|h| h.new_str(k)));
6711 }
6712 }
6713 }
6714 }
6715 with_host(|h| h.new_array(keys))
6716}
6717
6718/// The intrinsic prototype namespaces `v` inherits from, nearest first — its
6719/// own constructor's and then `Object`'s, the same two steps
6720/// `inherited_builtin_static` looks a value up in.
6721fn intrinsic_proto_namespaces(v: &Value) -> Vec<String> {
6722 let ctor = match wrapped_primitive(v).as_ref().and_then(wrapper_ctor_of) {
6723 Some(c) => Some(c),
6724 None if is_arguments(v) => Some("Object"),
6725 None => with_host(|h| default_ctor_name(h, v)),
6726 };
6727 let mut out: Vec<String> = ctor
6728 .filter(|c| *c != "Object")
6729 .map(|c| format!("{c}.prototype"))
6730 .into_iter()
6731 .collect();
6732 out.push("Object.prototype".to_string());
6733 out
6734}
6735
6736/// `FORIN_ALIVE` — is `key` STILL an enumerable property of `obj`?
6737///
6738/// `for-in` takes its key list once (14.7.5.10 builds it lazily, but a snapshot
6739/// of the enumerable keys is observationally the same for everything except
6740/// this), and the body can delete a key before the loop reaches it. Node does
6741/// not visit a key deleted that way; without this check `delete d.z` inside the
6742/// loop still produced `x,y,z`.
6743///
6744/// The check is `[[GetOwnProperty]]`-shaped rather than `in`: on a Proxy it runs
6745/// the `getOwnPropertyDescriptor` trap, which is what node runs, and NOT the
6746/// `has` trap, which node never fires for `for-in`. That also puts each trap
6747/// call immediately before its visit, matching node's interleaving — the trap
6748/// log used to show every `gopd` up front because the key list was filtered
6749/// eagerly.
6750fn b_forin_alive(vm: &mut VM, _: u8) -> Value {
6751 let key = vm.pop();
6752 let obj = vm.pop();
6753 let name = with_host(|h| h.str_of(&key));
6754 if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
6755 return match crate::proxy::own_enumerable(&obj, &name) {
6756 Ok(b) => Value::Bool(b),
6757 Err(e) => abort(vm, e),
6758 };
6759 }
6760 // A STRING's keys are its character indices. `in` is not defined on a string
6761 // primitive at all, so the ordinary path below has no answer for one and
6762 // `for (const i in 'abc')` came back empty.
6763 if let Some(s) = with_host(|h| h.as_str(&obj)) {
6764 let len = crate::utf16::len(&s);
6765 return Value::Bool(name.parse::<usize>().is_ok_and(|i| i < len));
6766 }
6767 // Any other receiver: EXISTENCE only. Node re-checks that the key is still
6768 // there and does NOT re-check enumerability — making one non-enumerable
6769 // mid-loop still visits it, where re-filtering on `enumerable` dropped it.
6770 // (The Proxy branch above does re-check, because there the answer comes from
6771 // the trap node itself calls.)
6772 Value::Bool(has_property_ordinary(&obj, &name))
6773}
6774
6775fn b_foriter(vm: &mut VM, _: u8) -> Value {
6776 let it = match vm.stack.last() {
6777 Some(v) => v.clone(),
6778 None => return abort(vm, "internal: FORITER with empty stack".into()),
6779 };
6780 // A built-in iterator: a snapshot (strings, a Proxy's items) or live over
6781 // an array.
6782 if let Some(step) = iter_step(&it) {
6783 return match step {
6784 Ok(Some(v)) => {
6785 vm.push(v);
6786 Value::Bool(true)
6787 }
6788 Ok(None) => Value::Bool(false),
6789 Err(e) => abort_iterator_error(vm, e),
6790 };
6791 }
6792 // Generator: resume one step.
6793 if with_host(|h| h.is_generator_val(&it)) {
6794 return match host::gen_resume(&it, Value::Undef) {
6795 Ok(host::GenStep::Yield(v)) => {
6796 vm.push(v);
6797 Value::Bool(true)
6798 }
6799 Ok(host::GenStep::Done(_)) => Value::Bool(false),
6800 Err(e) => abort_iterator_error(vm, e),
6801 };
6802 }
6803 // A user iterator object with a `.next()` returning `{ value, done }`.
6804 match host::iterator_step_value(&it) {
6805 Ok(Some(v)) => {
6806 vm.push(v);
6807 Value::Bool(true)
6808 }
6809 Ok(None) => Value::Bool(false),
6810 Err(e) => abort_iterator_error(vm, e),
6811 }
6812}
6813
6814fn b_unpack(vm: &mut VM, _: u8) -> Value {
6815 let star = match vm.pop() {
6816 Value::Int(n) => n,
6817 _ => -1,
6818 };
6819 let count = match vm.pop() {
6820 Value::Int(n) => n as usize,
6821 _ => 0,
6822 };
6823 let iterable = vm.pop();
6824 // Without a `...rest` element the pattern needs exactly `count` values and
6825 // must then close the iterator; draining hung on an unbounded source.
6826 let items = match if star < 0 {
6827 host::iter_take(&iterable, count)
6828 } else {
6829 host::iter_all(&iterable)
6830 } {
6831 Ok(v) => v,
6832 // Destructuring a non-iterable names the SOURCE EXPRESSION, the way
6833 // `for-of` does: `const [x] = o` reports `o is not iterable`. The text
6834 // was recorded for this op at compile time.
6835 Err(e) => {
6836 // Node names the source only when the pattern's right-hand side is
6837 // a plain IDENTIFIER — `const [x] = o` is `o is not iterable`.
6838 // Anything else (a member, a call, a nested pattern, a parameter)
6839 // reports the TYPE instead, with the property note. Measured across
6840 // twelve shapes rather than guessed.
6841 let msg = match host::call_site_text(vm) {
6842 Some(text) if e.ends_with(" is not iterable") => {
6843 host::type_error(&format!("{text} is not iterable"))
6844 }
6845 None if e.ends_with(" is not iterable") => {
6846 host::type_error(¬_iterable_typed(&iterable))
6847 }
6848 _ => e,
6849 };
6850 return abort(vm, msg);
6851 }
6852 };
6853 let ordered: Vec<Value> = if star < 0 {
6854 (0..count)
6855 .map(|i| items.get(i).cloned().unwrap_or(Value::Undef))
6856 .collect()
6857 } else {
6858 let si = star as usize;
6859 let after = count.saturating_sub(si + 1);
6860 let rest_end = items.len().saturating_sub(after).max(si);
6861 let mut out: Vec<Value> = Vec::with_capacity(count);
6862 for i in 0..si {
6863 out.push(items.get(i).cloned().unwrap_or(Value::Undef));
6864 }
6865 let rest: Vec<Value> = items
6866 .get(si..rest_end)
6867 .map(|s| s.to_vec())
6868 .unwrap_or_default();
6869 out.push(with_host(|h| h.new_array(rest)));
6870 for j in 0..after {
6871 out.push(items.get(rest_end + j).cloned().unwrap_or(Value::Undef));
6872 }
6873 out
6874 };
6875 if ordered.is_empty() {
6876 return Value::Undef;
6877 }
6878 for it in ordered[1..].iter().rev().cloned() {
6879 vm.push(it);
6880 }
6881 ordered[0].clone()
6882}
6883
6884fn b_build_args(vm: &mut VM, argc: u8) -> Value {
6885 let flat = pop_n(vm, argc as usize);
6886 let mut out = Vec::new();
6887 // Elided positions of an array literal (tag 2), recorded as the run-time
6888 // index each lands on — which only this walk knows, because a preceding
6889 // spread contributes an unknown number of elements. Call-argument lists,
6890 // the other `BUILD_ARGS` caller, cannot contain an elision, so this stays
6891 // empty for them.
6892 let mut holes: rustc_hash::FxHashSet<usize> = rustc_hash::FxHashSet::default();
6893 let mut i = 0;
6894 while i + 1 < flat.len() {
6895 let val = flat[i + 1].clone();
6896 match flat[i] {
6897 // Tag 1 is an ARRAY-LITERAL spread, tag 3 a CALL-ARGUMENT one. They
6898 // report a non-iterable differently, which is the only reason the
6899 // two are told apart here.
6900 Value::Int(1) => match host::iter_all(&val).map_err(|e| {
6901 let shown = with_host(|h| h.inspect(&val));
6902 host::name_call_site(vm, &shown, e)
6903 }) {
6904 Ok(items) => out.extend(items),
6905 Err(e) => return abort(vm, e),
6906 },
6907 Value::Int(3) => match host::iter_all(&val) {
6908 Ok(items) => out.extend(items),
6909 Err(e) => {
6910 // A NULLISH spread names the value and what could not be
6911 // read off it; anything else names the missing protocol.
6912 let shown = with_host(|h| h.is_nullish(&val).then(|| h.str_of(&val)));
6913 return abort(
6914 vm,
6915 match shown {
6916 Some(s) => host::type_error(&format!(
6917 "{s} is not iterable (cannot read property {s})"
6918 )),
6919 None if e.ends_with(" is not iterable") => host::type_error(
6920 "Spread syntax requires ...iterable[Symbol.iterator] to be a function",
6921 ),
6922 None => e,
6923 },
6924 );
6925 }
6926 },
6927 Value::Int(2) => {
6928 holes.insert(out.len());
6929 out.push(Value::Undef);
6930 }
6931 _ => out.push(val),
6932 }
6933 i += 2;
6934 }
6935 with_host(|h| {
6936 let arr = h.new_array(out);
6937 h.install_holes(&arr, holes);
6938 arr
6939 })
6940}
6941
6942// ── calls ──────────────────────────────────────────────────────────────────────
6943
6944fn b_call(vm: &mut VM, argc: u8) -> Value {
6945 note_site(vm);
6946 let mut args = pop_n(vm, argc as usize);
6947 let name = sval(&args.remove(0));
6948 let r = host::call_named(&name, args);
6949 // A bare name that resolved to a non-callable reports the VALUE
6950 // (`undefined is not a function`); node names the identifier. Resolving it
6951 // again to learn what the message said costs nothing off the error path.
6952 let r = r.map_err(|e| {
6953 let shown = global_binding(&name)
6954 .map(|v| with_host(|h| h.str_of(&v)))
6955 .unwrap_or_default();
6956 host::name_call_site(vm, &shown, e)
6957 });
6958 finish(vm, r)
6959}
6960
6961/// `recv[0](…)` — a computed call whose key is an ARRAY INDEX rather than a
6962/// method name. `call_method` resolves by name and bottoms out in
6963/// `call_type_method`, which knows `sort`/`slice` and not `"0"`, so an element
6964/// that happens to be a function reported "is not a function". Read the element
6965/// and invoke it with `recv` as `this`, which is the receiver 13.3.6 gives it.
6966/// A computed call's key is a property key, so it goes through ToPropertyKey:
6967/// `arr[0](…)` looks up `"0"`. `sval` only unwraps an existing `Value::Str` and
6968/// answers "" for a number, which turned `arr[0]()` into a call to the method
6969/// named "" — so the key is stringified here instead.
6970fn call_key_of(v: &Value) -> String {
6971 if let Value::Str(s) = v {
6972 return (**s).clone();
6973 }
6974 // `ToPropertyKey`, not `ToString`. A SYMBOL key has an internal `@@name`
6975 // spelling that `str_of` does not produce — it renders
6976 // `Symbol(Symbol.iterator)` — so `obj[Symbol.iterator]()` dispatched a
6977 // method by that display text and reported it was not a function, for every
6978 // object including a plain literal with a computed symbol method. Reading
6979 // the same property without calling it worked, which is what hid this.
6980 with_host(|h| h.property_key(v))
6981}
6982
6983fn index_element_call(recv: &Value, name: &str, args: &[Value]) -> Option<Result<Value, String>> {
6984 if name.is_empty() || !name.bytes().all(|b| b.is_ascii_digit()) {
6985 return None;
6986 }
6987 let f = get_property(recv, name).ok()?;
6988 with_host(|h| host::is_callable(h, &f))
6989 .then(|| host::invoke(&f, args.to_vec(), Some(recv.clone())))
6990}
6991
6992fn b_call_method(vm: &mut VM, argc: u8) -> Value {
6993 note_site(vm);
6994 let mut args = pop_n(vm, argc as usize);
6995 let recv = args.remove(0);
6996 let name = call_key_of(&args.remove(0));
6997 if let Some(r) = index_element_call(&recv, &name, &args) {
6998 return finish(vm, r);
6999 }
7000 let r = host::call_method(&recv, &name, args);
7001 // `z.f()` on a missing method is `z.f is not a function` in node, not
7002 // `f is not a function`: V8 names the callee as the source wrote it. The
7003 // text was recorded for this op at compile time.
7004 let r = r.map_err(|e| host::name_call_site(vm, &name, e));
7005 finish(vm, r)
7006}
7007
7008fn b_call_value(vm: &mut VM, argc: u8) -> Value {
7009 note_site(vm);
7010 let mut args = pop_n(vm, argc as usize);
7011 let callable = args.remove(0);
7012 let r = host::invoke(&callable, args, None);
7013 // The callee here is an expression, not a name, so the message it produced
7014 // describes the VALUE (`undefined is not a function`); node names the
7015 // expression. Same site table, keyed on that rendering.
7016 let r = r.map_err(|e| {
7017 let shown = with_host(|h| h.str_of(&callable));
7018 host::name_call_site(vm, &shown, e)
7019 });
7020 finish(vm, r)
7021}
7022
7023/// `NEW_SPREAD` — `new C(...xs)`, where the argument list is a run-time array
7024/// rather than a fixed count of stack slots.
7025///
7026/// `compile_new` used to compile each argument with `compile_expr`, and a
7027/// spread there evaluates to the SPREAD OBJECT itself — so `new C(...[1, 2])`
7028/// passed the array as one argument and `new Date(...[2020, 0, 1])` built an
7029/// Invalid Date.
7030fn b_new_spread(vm: &mut VM, _: u8) -> Value {
7031 note_site(vm);
7032 let args_arr = vm.pop();
7033 let ctor = vm.pop();
7034 let args = host::iter_all(&args_arr).unwrap_or_default();
7035 let r = host::construct(&ctor, args).map_err(|e| {
7036 let shown = with_host(|h| h.str_of(&ctor));
7037 host::name_call_site(vm, &shown, e)
7038 });
7039 finish(vm, r)
7040}
7041
7042fn b_new(vm: &mut VM, argc: u8) -> Value {
7043 note_site(vm);
7044 let mut args = pop_n(vm, argc as usize);
7045 let ctor = args.remove(0);
7046 let r = host::construct(&ctor, args);
7047 // `new (o.a.b.c)()` on a non-constructor names the expression, as a failed
7048 // call does.
7049 let r = r.map_err(|e| {
7050 let shown = with_host(|h| h.str_of(&ctor));
7051 host::name_call_site(vm, &shown, e)
7052 });
7053 finish(vm, r)
7054}
7055
7056fn b_apply(vm: &mut VM, _: u8) -> Value {
7057 note_site(vm);
7058 let args_arr = vm.pop();
7059 let callable = vm.pop();
7060 let args = host::iter_all(&args_arr).unwrap_or_default();
7061 let r = host::invoke(&callable, args, None);
7062 finish(vm, r)
7063}
7064
7065fn b_apply_method(vm: &mut VM, _: u8) -> Value {
7066 note_site(vm);
7067 let args_arr = vm.pop();
7068 let name = call_key_of(&vm.pop());
7069 let recv = vm.pop();
7070 let args = host::iter_all(&args_arr).unwrap_or_default();
7071 if let Some(r) = index_element_call(&recv, &name, &args) {
7072 return finish(vm, r);
7073 }
7074 let r = host::call_method(&recv, &name, args);
7075 finish(vm, r)
7076}
7077
7078// ── numeric hook ──────────────────────────────────────────────────────────────
7079
7080/// Host callback for arithmetic fusevm cannot complete natively (a non-`Int`/
7081/// non-`Float` operand). Supplies JavaScript `+` concatenation and coercion.
7082///
7083/// Every operand is run through `ToPrimitive` FIRST (ECMA-262 13.15.3 for `+`,
7084/// 13.6.3 for the other arithmetic ops, 13.10.1 for the relational ones), which
7085/// is what invokes a user `valueOf`/`Symbol.toPrimitive`. It has to happen here
7086/// rather than inside `JsHost::arith`, because calling back into JS re-enters
7087/// the VM and `arith` runs under the host's `RefCell` borrow.
7088pub fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
7089 use NumOp::*;
7090 let (a, b) = match op {
7091 // `==`/`!=` only convert when the OTHER side is a primitive that can be
7092 // compared numerically or textually; `{} == {}` stays a reference check.
7093 Eq | Ne => {
7094 let (pa, pb) = with_host(|h| (host::is_primitive(h, a), host::is_primitive(h, b)));
7095 match (pa, pb) {
7096 (false, true) if coerces_against_object(b) => {
7097 (host::to_primitive(a, "default")?, b.clone())
7098 }
7099 (true, false) if coerces_against_object(a) => {
7100 (a.clone(), host::to_primitive(b, "default")?)
7101 }
7102 _ => (a.clone(), b.clone()),
7103 }
7104 }
7105 // `+` uses the default hint (`valueOf` first, but a string result still
7106 // selects concatenation); everything else uses the number hint.
7107 Add => (
7108 host::to_primitive(a, "default")?,
7109 host::to_primitive(b, "default")?,
7110 ),
7111 _ => (
7112 host::to_primitive(a, "number")?,
7113 host::to_primitive(b, "number")?,
7114 ),
7115 };
7116 reject_symbol_operand(op, &a, &b)?;
7117 with_host(|h| h.arith(op, &a, &b))
7118}
7119
7120/// A symbol has no `ToNumber` and no `ToString`, so every operator except the
7121/// equality family rejects it (7.1.4 step 2, 7.1.17 step 2). node-js instead
7122/// concatenated `Symbol(desc)` into the result.
7123///
7124/// Which of the two messages V8 uses is decided by whether the operation is
7125/// STRING concatenation — measured on node v26.7.0, `Symbol() + ''` is
7126/// `Cannot convert a Symbol value to a string` while `Symbol() + 1`,
7127/// `Symbol() + Symbol()` and `Symbol() * 1` are all
7128/// `Cannot convert a Symbol value to a number`. `==`/`===` never convert
7129/// (`Symbol() == 1` is `false`), so they are left alone.
7130fn reject_symbol_operand(op: NumOp, a: &Value, b: &Value) -> Result<(), String> {
7131 use NumOp::*;
7132 if matches!(op, Eq | Ne) {
7133 return Ok(());
7134 }
7135 let (sym, concat) = with_host(|h| {
7136 let is_sym = |v: &Value| matches!(h.get(v), Some(JsObj::Symbol { .. }));
7137 let is_str =
7138 |v: &Value| matches!(v, Value::Str(_)) || matches!(h.get(v), Some(JsObj::Str(_)));
7139 (is_sym(a) || is_sym(b), is_str(a) || is_str(b))
7140 });
7141 if !sym {
7142 return Ok(());
7143 }
7144 Err(host::type_error(if matches!(op, Add) && concat {
7145 "Cannot convert a Symbol value to a string"
7146 } else {
7147 "Cannot convert a Symbol value to a number"
7148 }))
7149}
7150
7151/// Whether a primitive `v` makes `==` against an object convert that object
7152/// (7.2.15 steps 10-11): numbers, strings, bigints and symbols do; `null`,
7153/// `undefined` and booleans are settled without a `ToPrimitive` call
7154/// (a boolean is coerced to a number first, and then it does).
7155fn coerces_against_object(v: &Value) -> bool {
7156 match v {
7157 Value::Undef => false,
7158 Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::Str(_) => true,
7159 _ => with_host(|h| !h.is_null(v)),
7160 }
7161}
7162
7163// ══ standard library ═══════════════════════════════════════════════════════════
7164
7165/// Namespaces reachable as bare globals.
7166fn is_namespace(name: &str) -> bool {
7167 matches!(
7168 name,
7169 "console"
7170 | "Math"
7171 | "JSON"
7172 | "Object"
7173 | "Array"
7174 | "Number"
7175 | "String"
7176 | "Boolean"
7177 | "Symbol"
7178 | "Reflect"
7179 | "Promise"
7180 | "process"
7181 | "Buffer"
7182 | "URL"
7183 | "URLSearchParams"
7184 )
7185}
7186
7187const GLOBAL_FUNCS: &[&str] = &[
7188 "parseInt",
7189 "parseFloat",
7190 "isNaN",
7191 "isFinite",
7192 "encodeURIComponent",
7193 "decodeURIComponent",
7194 "encodeURI",
7195 "decodeURI",
7196 // Annex B legacy encoders. Still globals on every engine, and still called
7197 // by pre-`encodeURIComponent` library code.
7198 "escape",
7199 "unescape",
7200 "eval",
7201 "String",
7202 "Number",
7203 "Boolean",
7204 "Array",
7205 "Object",
7206 "Function",
7207 "Symbol",
7208 "Map",
7209 "Set",
7210 "WeakMap",
7211 "WeakSet",
7212 "Promise",
7213 "Error",
7214 "TypeError",
7215 "RangeError",
7216 "SyntaxError",
7217 "ReferenceError",
7218 "EvalError",
7219 "URIError",
7220 "AggregateError",
7221 "DOMException",
7222 "Iterator",
7223 "BigInt",
7224 "RegExp",
7225 "Date",
7226 "ArrayBuffer",
7227 "DataView",
7228 "Uint8Array",
7229 "Int8Array",
7230 "Uint8ClampedArray",
7231 "Int16Array",
7232 "Uint16Array",
7233 "Int32Array",
7234 "Uint32Array",
7235 "Float32Array",
7236 "Float64Array",
7237 "BigInt64Array",
7238 "BigUint64Array",
7239 "WeakRef",
7240 "FinalizationRegistry",
7241 "TextEncoder",
7242 "TextDecoder",
7243 // WHATWG Fetch globals (see `stdlib::fetch`).
7244 "fetch",
7245 "Headers",
7246 "Request",
7247 "Response",
7248 "Blob",
7249 "File",
7250 "FormData",
7251 "AbortController",
7252 "AbortSignal",
7253 // WHATWG DOM events (see `stdlib::event_target`).
7254 "Event",
7255 "EventTarget",
7256 "CustomEvent",
7257 // The WHATWG stream, messaging and performance classes node also exposes
7258 // as globals. Each was reachable only through its module
7259 // (`require("stream/web").ReadableStream`), so the bare name — the form
7260 // web-targeted code uses — was a ReferenceError. The global and the
7261 // module member are the same constructor.
7262 "ReadableStream",
7263 "ReadableStreamDefaultReader",
7264 "ReadableStreamBYOBReader",
7265 "ReadableStreamDefaultController",
7266 "ReadableByteStreamController",
7267 "ReadableStreamBYOBRequest",
7268 "WritableStream",
7269 "WritableStreamDefaultWriter",
7270 "WritableStreamDefaultController",
7271 "TransformStream",
7272 "TransformStreamDefaultController",
7273 "ByteLengthQueuingStrategy",
7274 "CountQueuingStrategy",
7275 "TextEncoderStream",
7276 "TextDecoderStream",
7277 "CompressionStream",
7278 "DecompressionStream",
7279 "MessageChannel",
7280 "BroadcastChannel",
7281 "Performance",
7282 "PerformanceEntry",
7283 "PerformanceMark",
7284 "PerformanceMeasure",
7285 "PerformanceObserver",
7286 "PerformanceObserverEntryList",
7287 "PerformanceResourceTiming",
7288 "Crypto",
7289 "CryptoKey",
7290 "queueMicrotask",
7291 "setTimeout",
7292 "setInterval",
7293 "setImmediate",
7294 "clearTimeout",
7295 "clearInterval",
7296 "clearImmediate",
7297 "structuredClone",
7298 // Base64 helpers. They existed only as `require('buffer').btoa`, but node
7299 // exposes both as globals, so `btoa('abc')` was a ReferenceError.
7300 "btoa",
7301 "atob",
7302 "Proxy",
7303 "require",
7304 // CommonJS loader dispatch targets referenced by per-module `require`
7305 // closures (see `module.rs`); never written by user code.
7306 "__cjs_require",
7307 "__cjs_resolve",
7308 "__cjs_cache",
7309];
7310
7311const NS_METHODS: &[&str] = &[
7312 "console.log",
7313 "console.error",
7314 "console.warn",
7315 "console.info",
7316 "console.debug",
7317 "Math.abs",
7318 "Math.acos",
7319 "Math.acosh",
7320 "Math.asin",
7321 "Math.asinh",
7322 "Math.atan",
7323 "Math.atanh",
7324 "Math.atan2",
7325 "Math.ceil",
7326 "Math.cbrt",
7327 "Math.expm1",
7328 "Math.clz32",
7329 "Math.cos",
7330 "Math.cosh",
7331 "Math.exp",
7332 "Math.floor",
7333 "Math.f16round",
7334 "Math.fround",
7335 "Math.hypot",
7336 "Math.imul",
7337 "Math.log",
7338 "Math.log1p",
7339 "Math.log2",
7340 "Math.log10",
7341 "Math.max",
7342 "Math.min",
7343 "Math.pow",
7344 "Math.random",
7345 "Math.round",
7346 "Math.sign",
7347 "Math.sin",
7348 "Math.sinh",
7349 "Math.sqrt",
7350 "Math.tan",
7351 "Math.tanh",
7352 "Math.trunc",
7353 "JSON.parse",
7354 "JSON.stringify",
7355 "JSON.rawJSON",
7356 "JSON.isRawJSON",
7357 "Object.keys",
7358 "Object.values",
7359 "Object.entries",
7360 "Object.assign",
7361 "Object.freeze",
7362 "Object.is",
7363 "Object.fromEntries",
7364 "Object.getPrototypeOf",
7365 "Object.setPrototypeOf",
7366 "Object.create",
7367 "Object.getOwnPropertyNames",
7368 "Object.getOwnPropertySymbols",
7369 "Object.defineProperty",
7370 "Object.getOwnPropertyDescriptor",
7371 "Object.getOwnPropertyDescriptors",
7372 "Object.defineProperties",
7373 "Object.isFrozen",
7374 "Object.isSealed",
7375 "Object.seal",
7376 "Object.preventExtensions",
7377 "Object.isExtensible",
7378 "Object.hasOwn",
7379 "Object.groupBy",
7380 "Array.isArray",
7381 "Array.from",
7382 "Array.fromAsync",
7383 "Array.of",
7384 "Number.isFinite",
7385 "Number.isInteger",
7386 "Number.isNaN",
7387 "Number.isSafeInteger",
7388 "Number.parseFloat",
7389 "Number.parseInt",
7390 "String.fromCharCode",
7391 "String.fromCodePoint",
7392 "String.raw",
7393 "Symbol.for",
7394 "Symbol.keyFor",
7395 "BigInt.asIntN",
7396 "BigInt.asUintN",
7397 "Proxy.revocable",
7398 "Reflect.defineProperty",
7399 "Reflect.deleteProperty",
7400 "Reflect.apply",
7401 "Reflect.construct",
7402 "Reflect.get",
7403 "Reflect.getOwnPropertyDescriptor",
7404 "Reflect.getPrototypeOf",
7405 "Reflect.has",
7406 "Reflect.isExtensible",
7407 "Reflect.ownKeys",
7408 "Reflect.preventExtensions",
7409 "Reflect.set",
7410 "Reflect.setPrototypeOf",
7411 "Promise.all",
7412 "Promise.allSettled",
7413 "Promise.any",
7414 "Promise.race",
7415 "Promise.resolve",
7416 "Promise.reject",
7417 "Promise.withResolvers",
7418 "Promise.try",
7419 "RegExp.escape",
7420 "Error.isError",
7421 "Map.groupBy",
7422 "Response.json",
7423 "Response.error",
7424 "Response.redirect",
7425 "AbortSignal.abort",
7426 "AbortSignal.timeout",
7427 "process.nextTick",
7428 "Error.captureStackTrace",
7429 "require.resolve",
7430 "require.resolve.paths",
7431 "process.memoryUsage.rss",
7432];
7433
7434/// The `name` and `length` a builtin function reports, from the generated
7435/// intrinsic table ([`crate::arity::BUILTIN_ARITY`]). `None` for a key the table
7436/// does not cover — every non-function namespace (`Math`, `require('fs')`),
7437/// and the core-module functions, whose arity is not specified anywhere.
7438pub fn builtin_meta(key: &str) -> Option<(&'static str, u32)> {
7439 // A measured symbol accessor's getter (`core_symbol_descriptor`) is
7440 // node's `get`, of length 0.
7441 if key.starts_with(CORE_SYMBOL_GETTER) {
7442 return Some(("get", 0));
7443 }
7444 if let Some(meta) = core_accessor_function_meta(key) {
7445 return Some(meta);
7446 }
7447 // `os.<m>[Symbol.toPrimitive]` is an anonymous arrow of no parameters.
7448 if key.contains(".@@toPrimitive:") {
7449 return Some(("", 0));
7450 }
7451 crate::arity::BUILTIN_ARITY
7452 .binary_search_by(|(k, _, _)| (*k).cmp(key))
7453 .ok()
7454 .map(|i| {
7455 let (_, name, len) = crate::arity::BUILTIN_ARITY[i];
7456 (name, len)
7457 })
7458 .or_else(|| {
7459 TIMER_ARITY
7460 .iter()
7461 .find(|(k, _, _)| *k == key)
7462 .map(|(_, name, len)| (*name, *len))
7463 })
7464 .or_else(|| {
7465 GENERATOR_PROTO_ARITY
7466 .iter()
7467 .find(|(k, _, _)| *k == key)
7468 .map(|(_, name, len)| (*name, *len))
7469 })
7470 // A core-module function (`fs.readFileSync`): measured from the
7471 // reference binary by `gen-core-arity`. `.length` read `undefined` for
7472 // every one of them.
7473 .or_else(|| {
7474 // `require('assert').strict` is the builtin this frontend keys
7475 // `assertStrict` (it is also the `assert/strict` module); the
7476 // measured table keys it as the member it is.
7477 let key = match key {
7478 "assertStrict" => "assert.strict",
7479 k => k,
7480 };
7481 let t = crate::core_arity::CORE_ARITY;
7482 t.binary_search_by(|(k, _, _)| (*k).cmp(key))
7483 .ok()
7484 .map(|i| (t[i].1, t[i].2))
7485 })
7486 // A modelled web/node class's prototype method
7487 // (`@proto:ReadableStream:getReader`), measured by class NAME — the
7488 // `SubtleCrypto` class is keyed `webcrypto.SubtleCrypto` here.
7489 .or_else(|| {
7490 let rest = key.strip_prefix("@proto:")?;
7491 let (ctor, member) = rest.rsplit_once(':')?;
7492 let key = format!(
7493 "@proto:{}:{member}",
7494 crate::stdlib::class_display_name(ctor)
7495 );
7496 let t = crate::core_arity::CLASS_PROTO_ARITY;
7497 t.binary_search_by(|(k, _, _)| (*k).cmp(key.as_str()))
7498 .ok()
7499 .map(|i| (t[i].1, t[i].2))
7500 })
7501}
7502
7503/// `name` and `length` of the timer functions, which no ECMAScript table covers:
7504/// they are Node's own (`lib/timers.js`, `lib/internal/process/task_queues.js`).
7505/// Measured against node v26 — `setTimeout.length` is 2 although its source
7506/// declares more parameters, which is why this is a table and not derived. The
7507/// `timers` module and the globals are the same functions.
7508const TIMER_ARITY: &[(&str, &str, u32)] = &[
7509 ("setTimeout", "setTimeout", 2),
7510 ("setInterval", "setInterval", 2),
7511 ("setImmediate", "setImmediate", 1),
7512 ("clearTimeout", "clearTimeout", 1),
7513 ("clearInterval", "clearInterval", 1),
7514 ("clearImmediate", "clearImmediate", 1),
7515 ("process.nextTick", "nextTick", 1),
7516 ("timers.setTimeout", "setTimeout", 2),
7517 ("timers.setInterval", "setInterval", 2),
7518 ("timers.setImmediate", "setImmediate", 1),
7519 ("timers.clearTimeout", "clearTimeout", 1),
7520 ("timers.clearInterval", "clearInterval", 1),
7521 ("timers.clearImmediate", "clearImmediate", 1),
7522 ("timers/promises.setTimeout", "setTimeout", 2),
7523 ("timers/promises.setInterval", "setInterval", 2),
7524 ("timers/promises.setImmediate", "setImmediate", 1),
7525];
7526
7527/// `name` and `length` of the `%GeneratorPrototype%`, `%AsyncGeneratorPrototype%`
7528/// and `%AsyncIteratorPrototype%` methods (`ensure_generator_protos`) and of the
7529/// five built-in iterator prototypes' `next` (`ensure_iterator_protos`), which the
7530/// generated table does not reach: it walks the global constructors, and these
7531/// prototypes hang off no global. Measured against node v26.12.1.
7532const GENERATOR_PROTO_ARITY: &[(&str, &str, u32)] = &[
7533 ("@proto:Generator:next", "next", 1),
7534 ("@proto:Generator:return", "return", 1),
7535 ("@proto:Generator:throw", "throw", 1),
7536 ("@proto:AsyncGenerator:next", "next", 1),
7537 ("@proto:AsyncGenerator:return", "return", 1),
7538 ("@proto:AsyncGenerator:throw", "throw", 1),
7539 (
7540 "@proto:AsyncIterator:@@asyncIterator",
7541 "[Symbol.asyncIterator]",
7542 0,
7543 ),
7544 (
7545 "@proto:AsyncIterator:@@asyncDispose",
7546 "[Symbol.asyncDispose]",
7547 0,
7548 ),
7549 ("@proto:ArrayIterator:next", "next", 0),
7550 ("@proto:MapIterator:next", "next", 0),
7551 ("@proto:SetIterator:next", "next", 0),
7552 ("@proto:StringIterator:next", "next", 0),
7553 ("@proto:RegExpStringIterator:next", "next", 0),
7554];
7555
7556/// The `name` a builtin function reports. The table answers for an intrinsic;
7557/// anything else falls back to the last segment of the key, which is what the
7558/// name is for every builtin this frontend synthesizes: `@proto:TypedArray:set`
7559/// is `set` and `fs.readFileSync` is `readFileSync`. Reporting the whole key was
7560/// how `[Function: @proto:TypedArray:set]` reached `console.log`.
7561pub fn builtin_name(key: &str) -> &str {
7562 if let Some((name, _)) = builtin_meta(key) {
7563 return name;
7564 }
7565 match key.strip_prefix("@proto:") {
7566 Some(rest) => rest.rsplit(':').next().unwrap_or(rest),
7567 // An accessor's getter is named `get <member>` (10.2.9 SetFunctionName
7568 // with a `get` prefix), which is what `util.inspect` prints for it and
7569 // what a library reads to identify one.
7570 None => key.rsplit('.').next().unwrap_or(key),
7571 }
7572}
7573
7574/// The `name` of an intrinsic accessor's getter thunk, or `None` for anything
7575/// else. Kept out of `builtin_name`'s `&str` return, which cannot own the
7576/// `"get size"` it has to build.
7577pub fn proto_getter_name(key: &str) -> Option<String> {
7578 // A native class's accessor thunk, `@proto:<Ctor>:@get@<member>` (or
7579 // `@set@`), is named the same way: `get locked`, not `@get@locked`.
7580 if let Some(rest) = key.strip_prefix("@proto:") {
7581 let (_, member) = rest.rsplit_once(':')?;
7582 if let Some(m) = member.strip_prefix("@get@") {
7583 return Some(format!("get {m}"));
7584 }
7585 if let Some(m) = member.strip_prefix("@set@") {
7586 return Some(format!("set {m}"));
7587 }
7588 return None;
7589 }
7590 let (verb, rest) = match key.strip_prefix("@protoget:") {
7591 Some(rest) => ("get", rest),
7592 None => ("set", key.strip_prefix("@protoset:")?),
7593 };
7594 let (_, member) = rest.split_once(':')?;
7595 Some(format!("{verb} {member}"))
7596}
7597
7598pub fn is_known_builtin(name: &str) -> bool {
7599 // Binary search over a sorted INDEX of the two tables rather than a scan of
7600 // both. This runs on every call whose callee is a builtin — `call_method`
7601 // asks it before dispatching `Math.max(…)` or `JSON.parse(…)` — and the
7602 // answer came only after a full scan of `GLOBAL_FUNCS` (77) plus a scan of
7603 // `NS_METHODS` up to the entry — 106 string comparisons for `Math.max`, 120
7604 // for `Object.keys` — because those tables are ordered for ENUMERATION (V8's
7605 // own order for `Math`/`Number`/`Reflect`), not for lookup. Eight probes
7606 // now. The index is built once per process and derived FROM those tables, so
7607 // it cannot drift from them.
7608 //
7609 // That is an operation count, not a measured time, and NO wall-clock win is
7610 // claimed. Re-measured in isolation (this hunk alone applied to the previous
7611 // commit, interleaved against it, minimums over ten rounds each): the A/B
7612 // ratio came out 0.753, 1.072, 0.994 and 0.744 across four repeats, while
7613 // the A/A control — the SAME binary under both labels — came out 1.084,
7614 // 1.072, 0.787 and 1.093. The A/B spread lies inside the A/A spread, so on
7615 // this machine the change is not distinguishable from noise. It is kept for
7616 // the comparison count and because it cannot drift from the tables it is
7617 // derived from, not because anything got faster.
7618 static SORTED: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
7619 let sorted = SORTED.get_or_init(|| {
7620 let mut v: Vec<&'static str> = GLOBAL_FUNCS
7621 .iter()
7622 .chain(NS_METHODS.iter())
7623 .copied()
7624 .collect();
7625 v.sort_unstable();
7626 v
7627 });
7628 sorted.binary_search(&name).is_ok() || is_namespace(name) || crate::stdlib::is_method(name)
7629}
7630
7631// ── dynamic functions (runtime source → callable) ────────────────────────────
7632
7633/// Build a callable from a complete function-expression source text — the ONE
7634/// dynamic-function generator on this frontend.
7635///
7636/// `src` is the exact source V8 synthesizes for the construct, WITHOUT the
7637/// wrapping parentheses needed to parse it as an expression: those are added
7638/// here, and `src` itself is retained so `Function.prototype.toString` reports
7639/// what V8 reports. The two callers synthesize different text and both shapes
7640/// are observable — see `stdlib::vm::compile_function` for the measured diff.
7641///
7642/// The body runs in the MODULE scope, never the constructing function's scope
7643/// (20.2.1.1.1 step 26 instantiates a dynamic function's body against the
7644/// *global* environment). That also makes a `var` inside the body a function
7645/// local: measured on node v26.7.0, `new Function('a','var zz = 5; return zz + a')`
7646/// returns 6 and leaves `globalThis.zz` `undefined`.
7647pub fn dynamic_function(src: &str) -> Result<Value, String> {
7648 let f = crate::eval_in_global_scope(&format!("({src})"))?;
7649 with_host(|h| {
7650 let s = h.new_str(src.to_string());
7651 h.set_fn_prop(&f, "@@source", s);
7652 });
7653 Ok(f)
7654}
7655
7656/// `new Function(p1, …, pN, body)` / `Function(p1, …, pN, body)`.
7657///
7658/// Argument convention (20.2.1.1.1): the LAST argument is the body and the rest
7659/// are parameter-list fragments joined with `,` — so a fragment may itself hold
7660/// several parameters (`new Function('a,b', 'c', …)` takes three). With no
7661/// arguments at all, both the parameter list and the body are empty.
7662///
7663/// Measured on node v26.7.0:
7664///
7665/// ```text
7666/// new Function('a','b','return a+b').toString() === 'function anonymous(a,b\n) {\nreturn a+b\n}'
7667/// new Function().toString() === 'function anonymous(\n) {\n\n}'
7668/// new Function('a,b','c','return [a,b,c]').length === 3
7669/// new Function('a','b','return a+b').name === 'anonymous'
7670/// ```
7671pub fn function_ctor(args: &[Value]) -> Result<Value, String> {
7672 let parts: Vec<String> = args.iter().map(|a| with_host(|h| h.str_of(a))).collect();
7673 let (params, body) = match parts.split_last() {
7674 Some((body, params)) => (params.join(","), body.clone()),
7675 None => (String::new(), String::new()),
7676 };
7677 dynamic_function(&format!("function anonymous({params}\n) {{\n{body}\n}}"))
7678}
7679
7680/// `eval(src)`. `direct` selects the scope the source runs in: a DIRECT eval —
7681/// the literal `eval(...)` call form — evaluates in the CALLER's scope, every
7682/// other route to the same function value is an INDIRECT eval and evaluates in
7683/// the global scope (ECMA-262 19.2.1.1 `PerformEval`). The two are told apart in
7684/// `host::call_named`, which `ops::CALL` reaches and `ops::CALL_VALUE`/`APPLY`
7685/// do not.
7686///
7687/// A non-string argument is returned unchanged (19.2.1.1 step 2).
7688pub fn eval_source(arg: Option<&Value>, direct: bool) -> Result<Value, String> {
7689 let v = arg.cloned().unwrap_or(Value::Undef);
7690 let is_string =
7691 matches!(v, Value::Str(_)) || with_host(|h| matches!(h.get(&v), Some(JsObj::Str(_))));
7692 if !is_string {
7693 return Ok(v);
7694 }
7695 let src = with_host(|h| h.str_of(&v));
7696 // A DIRECT eval inherits the caller's strictness (19.2.1.1 step 10), which
7697 // decides both the early errors the COMPILE raises and the variable
7698 // environment below. An INDIRECT one is global-scope sloppy code.
7699 let caller_strict = direct && with_host(|h| h.current_strict());
7700 // A direct eval inside a method (or an arrow in one) may use `super`.
7701 let allow_super = direct
7702 && with_host(|h| {
7703 let (class, _, home) = h.current_home();
7704 class.is_some() || home.is_some()
7705 });
7706 let chunk = crate::load_merged(crate::compile_completion_in(
7707 &src,
7708 caller_strict,
7709 allow_super,
7710 direct && with_host(|h| h.in_with_scope()),
7711 )?);
7712 if !direct {
7713 return host::run_chunk_in_eval_scope(chunk);
7714 }
7715 // A STRICT direct eval gets its OWN variable environment (19.2.1.1 step 12),
7716 // so its `var`s and function declarations die with it. Only a SLOPPY one
7717 // shares the caller's, which is the form that can inject a binding — and
7718 // sharing it unconditionally meant `eval('var x=1')` inside strict code
7719 // left `x` behind.
7720 let strict = caller_strict
7721 || src.trim_start().starts_with("'use strict'")
7722 || src.trim_start().starts_with("\"use strict\"");
7723 if !strict {
7724 // 19.2.1.1 steps 12-13: a SLOPPY direct eval shares the caller's
7725 // VARIABLE environment — which is what lets `eval('var x=1')` inject a
7726 // binding — but gets a fresh LEXICAL one of its own. A `let`, `const`
7727 // or `class` declared inside therefore dies with the eval; every one of
7728 // them was landing in the caller's scope, so `eval('let a=1')` left `a`
7729 // behind and `let a=1; eval('let a=2')` overwrote it.
7730 //
7731 // `push_scope` is exactly that split: `var` and a hoisted function
7732 // declaration bind to `base_env`, which this does not touch.
7733 with_host(|h| h.push_scope());
7734 let out = host::run_chunk_on(chunk);
7735 with_host(|h| h.pop_scope());
7736 return out;
7737 }
7738 let prev = with_host(|h| h.push_var_scope());
7739 let out = host::run_chunk_on(chunk);
7740 with_host(|h| h.pop_var_scope(prev));
7741 out
7742}
7743
7744/// Call a resolved builtin function (global or `namespace.method`).
7745pub fn call_builtin_function(name: &str, args: Vec<Value>) -> Result<Value, String> {
7746 // `require(spec)`: the ENTRY script's top-level require — core module first,
7747 // else the CommonJS loader resolving from the entry file's directory.
7748 if name == "require" {
7749 let spec = with_host(|h| h.str_of(&arg0(&args)));
7750 return crate::module::require(
7751 &spec,
7752 &crate::module::entry_dir(),
7753 &crate::module::entry_file(),
7754 );
7755 }
7756 // `__cjs_require(spec, fromDir, fromFile)`: a per-module `require` closure's
7757 // dispatch into the loader, resolving `spec` against the module's own
7758 // directory; `fromFile` is the requirer a require stack names.
7759 if name == "__cjs_require" {
7760 let spec = with_host(|h| h.str_of(&arg0(&args)));
7761 let from = with_host(|h| h.str_of(args.get(1).unwrap_or(&Value::Undef)));
7762 let file = with_host(|h| h.str_of(args.get(2).unwrap_or(&Value::Undef)));
7763 return crate::module::require(&spec, std::path::Path::new(&from), &file);
7764 }
7765 if let Some(rest) = name.strip_prefix(CORE_SYMBOL_GETTER) {
7766 return call_core_symbol_getter(rest);
7767 }
7768 if let Some(r) = call_core_accessor_function(name, &args) {
7769 return r;
7770 }
7771 // A bareword call of a web-stream class (`ReadableStream()`) calls the
7772 // `webstreams.js` port's class, which refuses a call without `new`.
7773 if crate::stdlib::stream_web::is_global_class(name) {
7774 let class = crate::stdlib::stream_web::constant(name).unwrap_or(Value::Undef);
7775 return host::invoke(&class, args, None);
7776 }
7777 // `Function.prototype` is itself a function (20.2.3): it accepts any
7778 // arguments and returns undefined.
7779 if name == "Function.prototype" {
7780 return Ok(Value::Undef);
7781 }
7782 if name == "process.memoryUsage.rss" {
7783 return Ok(crate::stdlib::process::memory_usage_rss());
7784 }
7785 if name == "require.resolve.paths" {
7786 let spec = with_host(|h| h.str_of(&arg0(&args)));
7787 // A core module is not looked up on disk at all.
7788 if crate::stdlib::is_core(&spec) {
7789 return Ok(with_host(|h| h.null()));
7790 }
7791 let dirs = crate::module::resolve_paths(&spec, &crate::module::entry_dir());
7792 return Ok(with_host(|h| {
7793 let items: Vec<Value> = dirs.into_iter().map(|d| h.new_str(d)).collect();
7794 h.new_array(items)
7795 }));
7796 }
7797 // A `require.extensions` entry. This runtime's loader does not dispatch
7798 // through the map, so calling one is the loader's own behaviour for that
7799 // extension rather than a hook point.
7800 if let Some(ext) = name.strip_prefix("@@extension:") {
7801 let _ = ext;
7802 return Ok(Value::Undef);
7803 }
7804 // `require.resolve(spec)` at the ENTRY level: resolve from the entry dir.
7805 if name == "require.resolve" {
7806 let spec = with_host(|h| h.str_of(&arg0(&args)));
7807 if crate::stdlib::is_core(&spec) {
7808 return Ok(with_host(|h| h.new_str(spec)));
7809 }
7810 return match crate::module::resolve(&spec, &crate::module::entry_dir()) {
7811 Some(p) => Ok(with_host(|h| h.new_str(p.to_string_lossy().to_string()))),
7812 None => Err(crate::module::not_found_error(
7813 &spec,
7814 &crate::module::entry_file(),
7815 )),
7816 };
7817 }
7818 // `__cjs_resolve(spec, fromDir)`: `require.resolve` — the resolved absolute
7819 // path (core modules resolve to the bare specifier, as in Node).
7820 if name == "__cjs_resolve" {
7821 let spec = with_host(|h| h.str_of(&arg0(&args)));
7822 let from = with_host(|h| h.str_of(args.get(1).unwrap_or(&Value::Undef)));
7823 let file = with_host(|h| h.str_of(args.get(2).unwrap_or(&Value::Undef)));
7824 if crate::stdlib::is_core(&spec) {
7825 return Ok(with_host(|h| h.new_str(spec)));
7826 }
7827 return match crate::module::resolve(&spec, std::path::Path::new(&from)) {
7828 Some(p) => Ok(with_host(|h| h.new_str(p.to_string_lossy().to_string()))),
7829 None => Err(crate::module::not_found_error(&spec, &file)),
7830 };
7831 }
7832 // `Error.captureStackTrace(target[, ctor])`: V8's stack capture. Sets
7833 // `target.stack`; when a custom `Error.prepareStackTrace` is installed (the
7834 // stack-introspection pattern used by `depd`), it is called with a synthetic
7835 // CallSite array and its result becomes `.stack`, else `.stack` is a string.
7836 if name == "Error.captureStackTrace" {
7837 let target = arg0(&args);
7838 // V8 refuses a primitive target with this literal message.
7839 if with_host(|h| host::is_primitive(h, &target) || h.is_nullish(&target)) {
7840 return Err(host::type_error("invalid_argument"));
7841 }
7842 let prep = with_host(|h| h.builtin_static("Error", "prepareStackTrace"));
7843 let stack = match prep {
7844 Some(f)
7845 if matches!(
7846 with_host(|h| h.get(&f).cloned()),
7847 Some(JsObj::Func(_)) | Some(JsObj::Builtin(_)) | Some(JsObj::BoundFunc { .. })
7848 ) =>
7849 {
7850 let sites = crate::module::callsite_stack(10)?;
7851 host::invoke(&f, vec![target.clone(), sites], None)?
7852 }
7853 // No hook: node's default rendering, `Name: message` from the
7854 // TARGET (`Error` for a plain object) and then the frames.
7855 _ => {
7856 let sites = crate::module::callsite_stack(10)?;
7857 call_builtin_function(DEFAULT_PREPARE, vec![target.clone(), sites])?
7858 }
7859 };
7860 let _ = set_property(&target, "stack", stack);
7861 // `stack` is installed non-enumerable, so `Object.keys(o)` stays `[]`.
7862 with_host(|h| h.hide_prop(&target, "stack"));
7863 return Ok(Value::Undef);
7864 }
7865 // Native stdlib module methods (path/os/fs/util/assert/crypto/buffer/url).
7866 if let Some(r) = crate::stdlib::call(name, &args) {
7867 return r;
7868 }
7869 match name {
7870 // Node's DEFAULT `Error.prepareStackTrace`: the `Name: message` header
7871 // followed by one ` at <site>` line per call site. Reachable because
7872 // the read hands the hook out, and a library may call it directly to
7873 // render a stack it captured.
7874 DEFAULT_PREPARE => {
7875 let err = arg0(&args);
7876 // Full property reads: a function target's `name` is not in any
7877 // property map, and `Error.captureStackTrace(fn)` heads with it.
7878 let name_v = get_property(&err, "name").unwrap_or(Value::Undef);
7879 let msg_v = get_property(&err, "message").unwrap_or(Value::Undef);
7880 let header = with_host(|h| {
7881 let name = if matches!(name_v, Value::Undef) {
7882 "Error".to_string()
7883 } else {
7884 h.str_of(&name_v)
7885 };
7886 let msg = if matches!(msg_v, Value::Undef) {
7887 String::new()
7888 } else {
7889 h.str_of(&msg_v)
7890 };
7891 if msg.is_empty() {
7892 name
7893 } else if name.is_empty() {
7894 msg
7895 } else {
7896 format!("{name}: {msg}")
7897 }
7898 });
7899 let sites = args.get(1).cloned().unwrap_or(Value::Undef);
7900 let lines = with_host(|h| match h.get(&sites) {
7901 Some(JsObj::Array(items)) => items.clone(),
7902 _ => Vec::new(),
7903 });
7904 let mut out = header;
7905 for s in lines {
7906 let rendered = host::to_string_value(&s)
7907 .map(|v| with_host(|h| h.str_of(&v)))
7908 .unwrap_or_default();
7909 out.push_str("\n at ");
7910 out.push_str(&rendered);
7911 }
7912 Ok(with_host(|h| h.new_str(out)))
7913 }
7914 "console.log" | "console.info" | "console.debug" => {
7915 print_line(&args, false)?;
7916 Ok(Value::Undef)
7917 }
7918 "console.error" | "console.warn" => {
7919 print_line(&args, true)?;
7920 Ok(Value::Undef)
7921 }
7922 "parseInt" | "Number.parseInt" => Ok(Value::Float(parse_int(&args)?)),
7923 "parseFloat" | "Number.parseFloat" => Ok(Value::Float(parse_float(&args)?)),
7924 // `isNaN`/`isFinite` are `ToNumber(x)` too (19.2.3/4).
7925 "isNaN" => Ok(Value::Bool(to_number_arg(&args, 0)?.is_nan())),
7926 "isFinite" => Ok(Value::Bool(to_number_arg(&args, 0)?.is_finite())),
7927 "encodeURIComponent" => uri_encode(&arg_to_string(&args, 0)?, false),
7928 "encodeURI" => uri_encode(&arg_to_string(&args, 0)?, true),
7929 "decodeURIComponent" => uri_decode(&arg_to_string(&args, 0)?, false),
7930 "decodeURI" => uri_decode(&arg_to_string(&args, 0)?, true),
7931 "escape" => legacy_escape(&with_host(|h| h.str_of(&arg0(&args)))),
7932 "unescape" => legacy_unescape(&with_host(|h| h.str_of(&arg0(&args)))),
7933 // Reaching `eval` through this table means the eval FUNCTION VALUE was
7934 // called — `(0, eval)(src)`, `const e = eval; e(src)`, `[eval][0](src)`.
7935 // Those are INDIRECT evals and run in the global scope. A literal
7936 // `eval(src)` is intercepted earlier, in `host::call_named`.
7937 "eval" => eval_source(args.first(), false),
7938 // `new Function(...)` and `Function(...)` are the same operation
7939 // (20.2.1.1 `CreateDynamicFunction` is reached from both [[Call]] and
7940 // [[Construct]]), so both route to the one generator.
7941 "Function" => function_ctor(&args),
7942 // `Buffer(arg[, encodingOrOffset[, length]])` — the deprecated call form
7943 // (DEP0005). Node still supports it and still routes it to the same place
7944 // `new Buffer` goes, which is why `safe-buffer`'s legacy `SafeBuffer`
7945 // wrapper is just `return Buffer(arg, encodingOrOffset, length)`. Measured
7946 // on node v26.7.0: `Buffer('abc').toString() === 'abc'`,
7947 // `Buffer([1,2]).toString('hex') === '0102'`, `Buffer(3).length === 3`.
7948 // Node emits DEP0005 once, on stderr, through the same one-shot machinery
7949 // `url.parse`'s DEP0169 uses, so this does too rather than staying silent
7950 // where Node warns.
7951 "Buffer" => {
7952 crate::stdlib::process::emit_deprecation_warning(
7953 "DEP0005",
7954 "Buffer() is deprecated due to security and usability issues. \
7955 Please use the Buffer.alloc(), Buffer.allocUnsafe(), or \
7956 Buffer.from() methods instead.",
7957 );
7958 crate::stdlib::construct("Buffer", &args)
7959 .unwrap_or_else(|| Err(host::type_error("Buffer is not a function")))
7960 }
7961 "Date" => Ok(crate::stdlib::date::call_as_function()),
7962 "Number.isInteger" => Ok(Value::Bool(is_integer(arg0(&args)))),
7963 "Number.isSafeInteger" => Ok(Value::Bool(is_safe_integer(arg0(&args)))),
7964 "Number.isNaN" => Ok(Value::Bool(
7965 matches!(arg0(&args), Value::Float(f) if f.is_nan()),
7966 )),
7967 "Number.isFinite" => Ok(Value::Bool(
7968 matches!(arg0(&args), Value::Float(f) if f.is_finite())
7969 || matches!(arg0(&args), Value::Int(_)),
7970 )),
7971 "String" => {
7972 if args.is_empty() {
7973 Ok(with_host(|h| h.new_str("")))
7974 } else {
7975 // A symbol argument stringifies to `Symbol(desc)` (explicit String()
7976 // is allowed); everything else via ToString method dispatch.
7977 host::string_ctor_value(&args[0])
7978 }
7979 }
7980 // `Number(v)` is NOT plain ToNumber: 21.1.1.1 step 2 converts the object
7981 // first and then explicitly ACCEPTS a BigInt, returning its mathematical
7982 // value as a Number. Only `Number` does — `+v` and `Math.abs(v)` reject
7983 // one — which is why this cannot just call `to_number_value`.
7984 "Number" => Ok(Value::Float(if args.is_empty() {
7985 0.0
7986 } else {
7987 let prim = host::to_primitive(&args[0], "number")?;
7988 match with_host(|h| h.as_bigint(&prim)) {
7989 Some(b) => host::bigint_to_f64(&b),
7990 None => host::to_number_value(&prim)?,
7991 }
7992 })),
7993 "BigInt" => bigint_ctor(&arg0(&args)),
7994 "RegExp" => regexp_ctor(&args, true),
7995 "BigInt.asIntN" | "BigInt.asUintN" => bigint_as_n(name.ends_with("asUintN"), &args),
7996 "Boolean" => Ok(Value::Bool(with_host(|h| h.truthy(&arg0(&args))))),
7997 // Each argument is truncated to a uint16 and taken as one code UNIT, so
7998 // `String.fromCharCode(0x1D4B3)` is U+D4B3, NOT the astral U+1D4B3, and
7999 // a surrogate PAIR of arguments composes into one character.
8000 "String.fromCharCode" => Ok(with_host(|h| {
8001 let units: Vec<u16> = args
8002 .iter()
8003 .map(|a| crate::utf16::to_uint16(h.to_number(a)))
8004 .collect();
8005 let s = crate::utf16::to_string_lossy(&units);
8006 h.new_str(s)
8007 })),
8008 // `fromCodePoint` takes whole code POINTS and rejects anything that is
8009 // not one — including a lone surrogate, which `fromCharCode` accepts.
8010 "String.fromCodePoint" => {
8011 let mut s = String::new();
8012 for a in &args {
8013 let n = with_host(|h| h.to_number(a));
8014 let cp = if n.is_finite() && n.trunc() == n && (0.0..=0x10FFFF as f64).contains(&n)
8015 {
8016 char::from_u32(n as u32)
8017 } else {
8018 None
8019 };
8020 match cp {
8021 Some(c) => s.push(c),
8022 None => {
8023 return Err(format!(
8024 "RangeError: Invalid code point {}",
8025 with_host(|h| h.str_of(a))
8026 ))
8027 }
8028 }
8029 }
8030 Ok(new_s(s))
8031 }
8032 "String.raw" => string_raw(&args),
8033 // `Array(5)` === `new Array(5)` (length-5 empty), but `Array.of(5)` is `[5]`.
8034 "Array" => construct_builtin("Array", args),
8035 "Array.of" => construct_array_like(host::current_static_this(), args),
8036 // 23.1.2.2 `IsArray` follows a Proxy to its `[[ProxyTarget]]` rather than
8037 // consulting any trap, so `Array.isArray(new Proxy([], {}))` is `true`.
8038 "Array.isArray" => Ok(Value::Bool(is_array(&arg0(&args))?)),
8039 "Array.from" => array_from(args),
8040 "Array.fromAsync" => array_from_async(args),
8041 "Object" => Ok(object_call(args)),
8042 "Object.keys" => object_keys(args, 0),
8043 "Object.values" => object_keys(args, 1),
8044 "Object.entries" => object_keys(args, 2),
8045 "Object.assign" => object_assign(args),
8046 "Object.freeze" => {
8047 let v = arg0(&args);
8048 reject_sealing_a_view(&v, "freeze")?;
8049 if seal_proxy(&v, true)? {
8050 return Ok(v);
8051 }
8052 with_host(|h| h.seal_object(&v, true));
8053 Ok(v)
8054 }
8055 "Object.seal" => {
8056 let v = arg0(&args);
8057 reject_sealing_a_view(&v, "seal")?;
8058 if seal_proxy(&v, false)? {
8059 return Ok(v);
8060 }
8061 with_host(|h| h.seal_object(&v, false));
8062 Ok(v)
8063 }
8064 "Object.preventExtensions" => {
8065 let v = arg0(&args);
8066 match crate::proxy::prevent_extensions(&v)? {
8067 Some(true) => return Ok(v),
8068 Some(false) => return Err(crate::proxy::prevent_extensions_refused()),
8069 None => {}
8070 }
8071 with_host(|h| h.prevent_extensions(&v));
8072 Ok(v)
8073 }
8074 // A PRIMITIVE has no integrity to speak of and 7.3.15/16 answer for it
8075 // without coercion: it is not extensible, and vacuously frozen and
8076 // sealed. Reporting it extensible and unfrozen was the opposite of
8077 // every one of the three.
8078 "Object.isFrozen" if is_primitive_arg(&args) => Ok(Value::Bool(true)),
8079 "Object.isSealed" if is_primitive_arg(&args) => Ok(Value::Bool(true)),
8080 "Object.isExtensible" if is_primitive_arg(&args) => Ok(Value::Bool(false)),
8081 "Object.isFrozen" => integrity_level(&arg0(&args), true),
8082 "Object.isSealed" => integrity_level(&arg0(&args), false),
8083 "Object.isExtensible" => {
8084 let v = arg0(&args);
8085 match crate::proxy::is_extensible(&v)? {
8086 Some(b) => Ok(Value::Bool(b)),
8087 None => Ok(Value::Bool(with_host(|h| h.is_extensible(&v)))),
8088 }
8089 }
8090 // Object.is — SameValue: like `===` but NaN is equal to NaN and +0 is
8091 // distinct from -0.
8092 "Object.is" => {
8093 let a = arg0(&args);
8094 let b = args.get(1).cloned().unwrap_or(Value::Undef);
8095 let num = |v: &Value| match v {
8096 Value::Int(n) => Some(*n as f64),
8097 Value::Float(f) => Some(*f),
8098 _ => None,
8099 };
8100 let r = match (num(&a), num(&b)) {
8101 (Some(x), Some(y)) => {
8102 if x.is_nan() && y.is_nan() {
8103 true
8104 } else if x == 0.0 && y == 0.0 {
8105 x.is_sign_negative() == y.is_sign_negative()
8106 } else {
8107 x == y
8108 }
8109 }
8110 _ => with_host(|h| h.strict_eq(&a, &b)),
8111 };
8112 Ok(Value::Bool(r))
8113 }
8114 "Object.fromEntries" => object_from_entries(args),
8115 // `[[GetPrototypeOf]]`: a Proxy answers from its trap (which may throw),
8116 // so the proxy form cannot share `prototype_of`'s infallible signature.
8117 // `Object.getPrototypeOf` coerces a primitive to its wrapper and
8118 // answers; `Reflect.getPrototypeOf` requires an object (28.1.8).
8119 "Object.getPrototypeOf" | "Reflect.getPrototypeOf" => {
8120 if name == "Reflect.getPrototypeOf" {
8121 reflect_require_object(&arg0(&args), "getPrototypeOf")?;
8122 }
8123 let v = arg0(&args);
8124 match crate::proxy::get_prototype_of(&v)? {
8125 Some(p) => Ok(p),
8126 None => Ok(prototype_of(&v)),
8127 }
8128 }
8129 "Object.setPrototypeOf" => {
8130 let obj = arg0(&args);
8131 let proto = args.get(1).cloned().unwrap_or(Value::Undef);
8132 if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
8133 reject_bad_prototype(&proto)?;
8134 // V8 names no property here, and prints that it did not.
8135 if !crate::proxy::set_prototype_of(&obj, &proto)? {
8136 // A refusing TRAP is the proxy's doing; a handler without
8137 // the trap forwards to the target, whose own refusal is
8138 // the ordinary non-extensible one.
8139 if crate::proxy::has_trap(&obj, "setPrototypeOf") {
8140 return Err(host::type_error(
8141 "'setPrototypeOf' on proxy: trap returned falsish for property 'undefined'",
8142 ));
8143 }
8144 let target = crate::proxy::ultimate_target(&obj).unwrap_or(obj.clone());
8145 return Err(host::type_error(&format!(
8146 "{} is not extensible",
8147 no_side_effects_string(&target)
8148 )));
8149 }
8150 return Ok(obj);
8151 }
8152 // 20.1.2.23: `RequireObjectCoercible` on the target, then the
8153 // prototype type check, then — only for an actual object target —
8154 // the extensibility check. A PRIMITIVE target is returned untouched
8155 // (`Object.setPrototypeOf(1, {})` is `1`), which is why the
8156 // extensibility test cannot come first.
8157 if with_host(|h| matches!(obj, Value::Undef) || h.is_null(&obj)) {
8158 return Err(host::type_error(
8159 "Object.setPrototypeOf called on null or undefined",
8160 ));
8161 }
8162 reject_bad_prototype(&proto)?;
8163 if with_host(|h| is_object_like(h, &obj)) {
8164 // Setting the SAME prototype is a no-op and stays legal even on a
8165 // frozen object: node v26.7.0 accepts
8166 // `Object.setPrototypeOf(Object.freeze({}), Object.prototype)`.
8167 // `prototype_of`, not `proto_of`: an object with no EXPLICIT
8168 // link still has `Object.prototype`, and comparing against the
8169 // absent link would call that a change.
8170 if would_cycle(&obj, &proto) {
8171 return Err(host::type_error("Cyclic __proto__ value"));
8172 }
8173 if !same_prototype(&obj, &proto) && !with_host(|h| h.is_extensible(&obj)) {
8174 // The receiver is named by its brand, as every other
8175 // refusal names it — a NULL-PROTOTYPE object is
8176 // `[object Object]`, not `#<Object>`, because it has no
8177 // constructor to name.
8178 return Err(host::type_error(&format!(
8179 "{} is not extensible",
8180 no_side_effects_string(&obj)
8181 )));
8182 }
8183 with_host(|h| h.set_proto(&obj, proto));
8184 }
8185 Ok(obj)
8186 }
8187 "Object.create" => object_create(args),
8188 "Object.getOwnPropertyNames" => object_keys(args, 3),
8189 "Object.getOwnPropertySymbols" => {
8190 let v = arg0(&args);
8191 require_object_coercible(&v)?;
8192 let syms = proxy_or_own_symbol_keys(&v)?;
8193 Ok(with_host(|h| h.new_array(syms)))
8194 }
8195 // `Object.hasOwn(obj, key)` — the static form of `hasOwnProperty`.
8196 "Object.hasOwn" => {
8197 let obj = arg0(&args);
8198 let key = args.get(1).cloned().unwrap_or(Value::Undef);
8199 object_builtin_method(&obj, "hasOwnProperty", vec![key])
8200 }
8201 "Object.defineProperty" => object_define_property(args),
8202 "Object.getOwnPropertyDescriptor" => object_get_own_descriptor(args),
8203 "Object.getOwnPropertyDescriptors" => object_get_own_descriptors(args),
8204 "Object.defineProperties" => object_define_properties(args),
8205 // `Object.groupBy(items, cb)` (ES2024): group into a null-prototype object
8206 // keyed by `ToPropertyKey(cb(item, i))`, each value an array of members.
8207 "Object.groupBy" => object_group_by(args),
8208 "Symbol" => Ok(with_host(|h| {
8209 let desc = args
8210 .first()
8211 .filter(|a| !matches!(a, Value::Undef))
8212 .map(|a| h.str_of(a));
8213 h.new_symbol(desc)
8214 })),
8215 "Symbol.for" => Ok(with_host(|h| {
8216 let key = h.str_of(&arg0(&args));
8217 h.symbol_for(&key)
8218 })),
8219 // `Symbol.keyFor(sym)` (20.4.2.6) is a REGISTRY lookup, not a
8220 // description read: it answers only for symbols `Symbol.for` created.
8221 // Returning the description made every symbol look registered —
8222 // `Symbol.keyFor(Symbol("k"))` was `"k"` where node says `undefined`.
8223 "Symbol.keyFor" => {
8224 // 20.4.2.6 step 1: the argument must be a Symbol.
8225 let sym = arg0(&args);
8226 if !with_host(|h| matches!(h.get(&sym), Some(JsObj::Symbol { .. }))) {
8227 return Err(host::type_error(&format!(
8228 "{} is not a symbol",
8229 no_side_effects_string(&sym)
8230 )));
8231 }
8232 Ok(with_host(|h| h.symbol_registry_key(&sym)))
8233 }
8234 // These constructors have no [[Call]] behaviour: a plain call throws.
8235 "Promise" => Err(host::type_error(
8236 "Promise constructor cannot be invoked without 'new'",
8237 )),
8238 "Map" | "WeakMap" | "Set" | "WeakSet" => Err(requires_new(name)),
8239 // The classes behind the singletons are ES classes in node: a plain
8240 // call is refused before the illegal-constructor check.
8241 n if crate::stdlib::illegal_constructor(n) => Err(host::type_error(&format!(
8242 "Class constructor {} cannot be invoked without 'new'",
8243 crate::stdlib::class_display_name(n)
8244 ))),
8245 // `Proxy` has no `[[Call]]` slot: it is constructor-only (28.2.1).
8246 "Proxy" => Err(host::type_error("Constructor Proxy requires 'new'")),
8247 "Proxy.revocable" => crate::proxy::revocable(&args),
8248 // `Reflect.ownKeys` reports EVERY own key, non-enumerable included —
8249 // the same set as `getOwnPropertyNames` (node-js has no symbol-keyed
8250 // own properties, so there is no second half to append).
8251 // `Reflect.ownKeys` is `OwnPropertyKeys` (7.3.23): every own key,
8252 // non-enumerable included, strings first and then the SYMBOLS.
8253 "Reflect.ownKeys" => {
8254 let v = arg0(&args);
8255 reflect_require_object(&v, "ownKeys")?;
8256 let names = object_keys(args, 3)?;
8257 let syms = proxy_or_own_symbol_keys(&v)?;
8258 if syms.is_empty() {
8259 return Ok(names);
8260 }
8261 let mut all = with_host(|h| h.iter_vec(&names)).unwrap_or_default();
8262 all.extend(syms);
8263 Ok(with_host(|h| h.new_array(all)))
8264 }
8265 "Reflect.getOwnPropertyDescriptor" => {
8266 reflect_require_object(&arg0(&args), "getOwnPropertyDescriptor")?;
8267 object_get_own_descriptor(args)
8268 }
8269 // `Reflect.defineProperty` REPORTS success as a boolean where
8270 // `Object.defineProperty` throws (28.1.3). It was propagating the
8271 // throw, so the whole point of the reflective form was lost.
8272 "Reflect.defineProperty" => {
8273 reflect_require_object(&arg0(&args), "defineProperty")?;
8274 // Only a REFUSED definition is `false`. A malformed descriptor, or a
8275 // getter on it that throws, is still an exception (28.1.3 step 5
8276 // runs `ToPropertyDescriptor` before `[[DefineOwnProperty]]`).
8277 match object_define_property(args) {
8278 Ok(_) => Ok(Value::Bool(true)),
8279 Err(e)
8280 if e.starts_with("TypeError: Cannot redefine property")
8281 || e.starts_with("TypeError: Cannot define property")
8282 || e.starts_with("TypeError: Invalid typed array index")
8283 || e.starts_with(
8284 "TypeError: 'defineProperty' on proxy: trap returned falsish",
8285 ) =>
8286 {
8287 Ok(Value::Bool(false))
8288 }
8289 Err(e) => Err(e),
8290 }
8291 }
8292 "Reflect.deleteProperty" => {
8293 let obj = arg0(&args);
8294 reflect_require_object(&obj, "deleteProperty")?;
8295 let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
8296 Ok(Value::Bool(delete_property(&obj, &k)?))
8297 }
8298 "Reflect.setPrototypeOf" => {
8299 let obj = arg0(&args);
8300 let p = args.get(1).cloned().unwrap_or(Value::Undef);
8301 reflect_require_object(&obj, "setPrototypeOf")?;
8302 reject_bad_prototype(&p)?;
8303 if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
8304 return Ok(Value::Bool(crate::proxy::set_prototype_of(&obj, &p)?));
8305 }
8306 // 10.1.2.1: a NON-EXTENSIBLE object refuses a prototype change —
8307 // unless the new one is what it already has, which is a no-op. It
8308 // reported success and rewrote the link.
8309 // `Reflect` reports a refusal rather than throwing, for a cycle as
8310 // for a non-extensible receiver.
8311 if would_cycle(&obj, &p) {
8312 return Ok(Value::Bool(false));
8313 }
8314 if !with_host(|h| h.is_extensible(&obj)) {
8315 return Ok(Value::Bool(same_prototype(&obj, &p)));
8316 }
8317 with_host(|h| h.set_proto(&obj, p));
8318 Ok(Value::Bool(true))
8319 }
8320 "Reflect.isExtensible" => {
8321 let v = arg0(&args);
8322 reflect_require_object(&v, "isExtensible")?;
8323 match crate::proxy::is_extensible(&v)? {
8324 Some(b) => Ok(Value::Bool(b)),
8325 None => Ok(Value::Bool(with_host(|h| h.is_extensible(&v)))),
8326 }
8327 }
8328 "Reflect.preventExtensions" => {
8329 let v = arg0(&args);
8330 reflect_require_object(&v, "preventExtensions")?;
8331 if let Some(b) = crate::proxy::prevent_extensions(&v)? {
8332 return Ok(Value::Bool(b));
8333 }
8334 with_host(|h| h.prevent_extensions(&v));
8335 Ok(Value::Bool(true))
8336 }
8337 // `Reflect.apply(target, thisArg, argsList)` / `Reflect.construct(t, a)`.
8338 "Reflect.apply" => {
8339 let f = arg0(&args);
8340 // 28.1.1 step 1 is `IsCallable(target)`, ahead of reading the list.
8341 if !with_host(|h| host::is_callable(h, &f)) {
8342 let kind = with_host(|h| match h.type_of(&f) {
8343 _ if h.is_null(&f) => "null".to_string(),
8344 "object" => "an object".to_string(),
8345 "undefined" => "undefined".to_string(),
8346 other => format!("a {other}"),
8347 });
8348 return Err(host::type_error(&format!(
8349 "Function.prototype.apply was called on {}, which is {kind} and not a function",
8350 no_side_effects_string(&f)
8351 )));
8352 }
8353 let this = args.get(1).cloned();
8354 let list = create_list_from_array_like(&args.get(2).cloned().unwrap_or(Value::Undef))?;
8355 host::invoke(&f, list, this.filter(|t| !with_host(|h| h.is_nullish(t))))
8356 }
8357 // `Reflect.construct(target, args, newTarget)` — the optional third
8358 // argument decides which constructor's `prototype` the instance gets
8359 // (28.1.2). It was ignored, so the result always inherited from
8360 // `target` and `instanceof newTarget` was false.
8361 "Reflect.construct" => {
8362 let f = arg0(&args);
8363 // 28.1.2 steps 1-2: the target, then an EXPLICIT newTarget, must
8364 // both have a `[[Construct]]` slot — checked before the list is read.
8365 for candidate in std::iter::once(&f).chain(args.get(2)) {
8366 if !host::is_constructor(candidate) {
8367 // Reflect names the VALUE (a function by its source text), where
8368 // `new f()` names the call site.
8369 return Err(host::type_error(&format!(
8370 "{} is not a constructor",
8371 no_side_effects_string(candidate)
8372 )));
8373 }
8374 }
8375 let list = create_list_from_array_like(&args.get(1).cloned().unwrap_or(Value::Undef))?;
8376 let new_target = args.get(2).cloned().unwrap_or_else(|| f.clone());
8377 host::construct_nt(&f, list, new_target)
8378 }
8379 "Reflect.has" => {
8380 let obj = arg0(&args);
8381 reflect_require_object(&obj, "has")?;
8382 let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
8383 Ok(Value::Bool(has_property(&obj, &k)?))
8384 }
8385 // `Reflect.get(target, key, receiver)` — the optional third argument is
8386 // what a getter sees as `this` (28.1.6). Defaults to the target.
8387 "Reflect.get" => {
8388 let obj = arg0(&args);
8389 reflect_require_object(&obj, "get")?;
8390 let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
8391 let receiver = args.get(2).cloned().unwrap_or_else(|| obj.clone());
8392 get_property_recv(&obj, &k, &receiver)
8393 }
8394 // `Reflect.set(target, key, value, receiver)` — the optional fourth
8395 // argument is what a setter sees as `this`, and where a DATA property
8396 // lands (28.1.13). It was ignored: the setter ran against the target
8397 // and the property was written there.
8398 "Reflect.set" => {
8399 let obj = arg0(&args);
8400 reflect_require_object(&obj, "set")?;
8401 let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
8402 let v = args.get(2).cloned().unwrap_or(Value::Undef);
8403 let receiver = args.get(3).cloned().unwrap_or_else(|| obj.clone());
8404 Ok(Value::Bool(set_with_receiver(&obj, &k, v, &receiver)?))
8405 }
8406 "JSON.stringify" => json_stringify(args),
8407 "JSON.parse" => json_parse(args),
8408 "JSON.rawJSON" => json_raw(args),
8409 "JSON.isRawJSON" => json_is_raw(args),
8410 "structuredClone" => structured_clone(args),
8411 // The ES module loader's natives (`esm.rs`), handed to `esm_loader.js`.
8412 _ if name.starts_with("@@esm.") => crate::esm::native(&name["@@esm.".len()..], &args),
8413 // The deferred drain a `Readable.from` schedules; the suffix is the
8414 // stream's heap index.
8415 _ if name.starts_with("@@transformCb:") => {
8416 let idx: u32 = name["@@transformCb:".len()..].parse().unwrap_or(0);
8417 crate::stdlib::stream::transform_callback(&Value::Obj(idx), &args)?;
8418 Ok(Value::Undef)
8419 }
8420 _ if name.starts_with("@@streamFlush:") => {
8421 let idx: u32 = name["@@streamFlush:".len()..].parse().unwrap_or(0);
8422 crate::stdlib::stream::flush_from(&Value::Obj(idx))?;
8423 Ok(Value::Undef)
8424 }
8425 // Same implementation the `buffer` module exposes; only the binding was
8426 // missing.
8427 "btoa" | "atob" => crate::stdlib::buffer::module_call(name, &args)
8428 .unwrap_or_else(|| Err(host::type_error(&format!("{name} is not a function")))),
8429 "fetch" => crate::stdlib::fetch::fetch(&args),
8430 // An `AbortSignal.timeout` deadline reached its macrotask: the thunk's
8431 // suffix is the signal's heap index.
8432 _ if name.starts_with("@@aborttimeout:") => {
8433 let idx: u32 = name["@@aborttimeout:".len()..].parse().unwrap_or(0);
8434 crate::stdlib::fetch::fire_timeout_abort(idx)
8435 }
8436 // An `EventTarget` listener threw: node re-raises it on the next tick so
8437 // it reaches `uncaughtException`, not `dispatchEvent`'s caller. The
8438 // suffix is the error's heap index.
8439 _ if name.starts_with("@@rethrow:") => {
8440 let idx: u32 = name["@@rethrow:".len()..].parse().unwrap_or(0);
8441 crate::stdlib::event_target::rethrow(idx)
8442 }
8443 // `addEventListener(…, { signal })`: the signal aborted, so the listener
8444 // the record at this heap index describes is removed.
8445 _ if name.starts_with("@@evunlisten:") => {
8446 let idx: u32 = name["@@evunlisten:".len()..].parse().unwrap_or(0);
8447 crate::stdlib::event_target::unlisten(idx)
8448 }
8449 // The `callback` handed to a `new Writable({ write(chunk, enc, cb) })`
8450 // implementation. Nothing here waits on backpressure, so it only has to
8451 // BE callable — an implementation that ends with `cb()`, which the
8452 // stream contract requires, would otherwise throw.
8453 "@@streamWriteCallback" => Ok(Value::Undef),
8454 "queueMicrotask" | "process.nextTick" => {
8455 let cb = arg0(&args);
8456 require_callback(&cb)?;
8457 let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
8458 enqueue_microtask(name == "process.nextTick", cb, rest);
8459 Ok(Value::Undef)
8460 }
8461 "setTimeout" | "setInterval" | "setImmediate" => {
8462 require_callback(&arg0(&args))?;
8463 schedule_timer(name, args)
8464 }
8465 "clearTimeout" | "clearInterval" => {
8466 crate::stdlib::timers::clear_timeout(&arg0(&args));
8467 Ok(Value::Undef)
8468 }
8469 "clearImmediate" => {
8470 crate::stdlib::timers::clear_immediate(&arg0(&args));
8471 Ok(Value::Undef)
8472 }
8473 "Promise.resolve" => promise_resolve(arg0(&args)),
8474 "Promise.reject" => promise_reject(arg0(&args)),
8475 "Promise.all" => promise_all(args, AllMode::All),
8476 "Promise.allSettled" => promise_all(args, AllMode::AllSettled),
8477 "Promise.race" => promise_race(args, false),
8478 "Promise.any" => promise_race(args, true),
8479 // `Promise.withResolvers()` (ES2024): a new pending promise plus its own
8480 // resolve/reject functions, returned as `{ promise, resolve, reject }`.
8481 "Promise.withResolvers" => promise_with_resolvers(),
8482 "Promise.try" => promise_try(args),
8483 "RegExp.escape" => regexp_escape(args),
8484 "Error.isError" => error_is_error(args),
8485 // `Map.groupBy(items, cb)` (ES2024): group into a `Map` keyed by the raw
8486 // `cb(item, i)` result (SameValueZero), each value an array of members.
8487 "Map.groupBy" => map_group_by(args),
8488 n if host::ERROR_NAMES.contains(&n) => make_error_checked(name, &args),
8489 _ if name.starts_with("Math.") => math_fn(&name[5..], &args),
8490 // Internal continuations (Promise resolve/reject fns, `.finally` wrappers).
8491 // The executor a species-constructed promise is built with: it does
8492 // nothing, because the caller settles the result through its id.
8493 "@@pnoop" => Ok(Value::Undef),
8494 _ if name.starts_with("@@presolve:") => {
8495 let id: u32 = name[11..].parse().unwrap_or(0);
8496 host::resolve_promise_val(id, arg0(&args));
8497 Ok(Value::Undef)
8498 }
8499 _ if name.starts_with("@@preject:") => {
8500 let id: u32 = name[10..].parse().unwrap_or(0);
8501 host::reject_promise_val(id, arg0(&args));
8502 Ok(Value::Undef)
8503 }
8504 // The revoker `Proxy.revocable` hands back, keyed by the proxy's heap
8505 // index so calling it twice is the spec's no-op rather than a re-tear.
8506 _ if name.starts_with("@@prevoke:") => {
8507 let i: u32 = name[10..].parse().unwrap_or(0);
8508 Ok(crate::proxy::revoke(i))
8509 }
8510 _ if name.starts_with("@@finpass:") => {
8511 // finally(cb) on fulfill: run cb, await whatever it returned, then
8512 // pass the original value through.
8513 let i: u32 = name["@@finpass:".len()..].parse().unwrap_or(0);
8514 let result = host::invoke(&Value::Obj(i), Vec::new(), None)?;
8515 Ok(finally_chain(result, arg0(&args), false))
8516 }
8517 _ if name.starts_with("@@finthrow:") => {
8518 // finally(cb) on reject: same, then re-throw the original reason.
8519 let i: u32 = name["@@finthrow:".len()..].parse().unwrap_or(0);
8520 let result = host::invoke(&Value::Obj(i), Vec::new(), None)?;
8521 Ok(finally_chain(result, arg0(&args), true))
8522 }
8523 // The two thunks `finally_chain` hangs off that awaited promise. Each
8524 // carries the value it must reinstate in a one-slot cell, since a
8525 // builtin is identified only by its name and cannot close over one.
8526 _ if name.starts_with("@@finret:") => {
8527 let i: u32 = name["@@finret:".len()..].parse().unwrap_or(0);
8528 get_property(&Value::Obj(i), "0")
8529 }
8530 _ if name.starts_with("@@finrethrow:") => {
8531 let i: u32 = name["@@finrethrow:".len()..].parse().unwrap_or(0);
8532 let reason = get_property(&Value::Obj(i), "0")?;
8533 with_host(|h| h.exc = Some(reason.clone()));
8534 Err(with_host(|h| error_string(h, &reason)))
8535 }
8536 // A native constructor reached by a plain call (`Uint8Array(1)`,
8537 // `DataView(buf)`): V8 names the missing `new`, not a missing function.
8538 _ if is_new_only_ctor(name) => Err(requires_new(name)),
8539 _ => Err(host::type_error(&format!("{name} is not a function"))),
8540 }
8541}
8542
8543/// `BigInt(x)`: convert a boolean/number/string/bigint to a BigInt. A
8544/// non-integer number is a `RangeError`; an unparseable string a `SyntaxError`
8545/// (matching Node's messages).
8546/// V8 names the offending value: `BigInt(undefined)` is `Cannot convert
8547/// undefined to a BigInt`, `BigInt({})` is `Cannot convert [object Object] to a
8548/// BigInt`. The old text said "value" literally, for every input.
8549fn bigint_convert_error(v: &Value) -> String {
8550 let shown = with_host(|h| h.str_of(v));
8551 host::type_error(&format!("Cannot convert {shown} to a BigInt"))
8552}
8553
8554/// `ToBigInt(v)` — 7.1.13. The conversion every BigInt-typed SINK performs: a
8555/// 64-bit typed array's element write, `DataView.prototype.setBigInt64`, and
8556/// BigInt arithmetic's operand check.
8557///
8558/// It is NOT `BigInt(v)`: a Number is a `TypeError` here (`BigInt(1)` is `1n`,
8559/// but `new BigInt64Array(1)[0] = 1` throws), which is the whole point of the
8560/// separate abstract op. Everything else follows `ToPrimitive(v, number)` then
8561/// the type table — booleans convert (`true` → `1n`), strings parse with a
8562/// `SyntaxError` on failure, and `undefined`/`null`/symbols throw.
8563///
8564/// Measured on node v26.8.1, receiver `new BigInt64Array(1)`:
8565///
8566/// ```text
8567/// a[0] = true → 1n
8568/// a[0] = '12' → 12n
8569/// a[0] = [] → 0n (ToPrimitive → "" → 0n)
8570/// a[0] = ['3'] → 3n
8571/// a[0] = 1 → TypeError: Cannot convert 1 to a BigInt
8572/// a[0] = new Number(3) → TypeError: Cannot convert 3 to a BigInt
8573/// a[0] = 'a' → SyntaxError: Cannot convert a to a BigInt
8574/// a[0] = {} → SyntaxError: Cannot convert [object Object] to a BigInt
8575/// ```
8576pub fn to_bigint(v: &Value) -> Result<num_bigint::BigInt, String> {
8577 let prim = host::to_primitive(v, "number")?;
8578 if let Some(b) = with_host(|h| match h.get(&prim) {
8579 Some(JsObj::BigInt(b)) => Some(b.clone()),
8580 _ => None,
8581 }) {
8582 return Ok(b);
8583 }
8584 match &prim {
8585 Value::Bool(b) => Ok(num_bigint::BigInt::from(*b as i64)),
8586 Value::Str(s) => host::parse_bigint_str(s)
8587 .ok_or_else(|| format!("SyntaxError: Cannot convert {s} to a BigInt")),
8588 _ if with_host(|h| matches!(h.get(&prim), Some(JsObj::Str(_)))) => {
8589 let s = with_host(|h| h.str_of(&prim));
8590 host::parse_bigint_str(&s)
8591 .ok_or_else(|| format!("SyntaxError: Cannot convert {s} to a BigInt"))
8592 }
8593 _ => Err(bigint_convert_error(&prim)),
8594 }
8595}
8596
8597fn bigint_ctor(v: &Value) -> Result<Value, String> {
8598 use num_bigint::BigInt;
8599 // 21.2.1.1 step 2: the argument is `ToPrimitive(value, number)` FIRST, so an
8600 // object converts through its `valueOf`/`toString` (`BigInt([7])` is `7n`).
8601 let prim = host::to_primitive(v, "number")?;
8602 let v = &prim;
8603 let big = match v {
8604 Value::Bool(b) => BigInt::from(*b as i64),
8605 Value::Int(n) => BigInt::from(*n),
8606 Value::Float(f) => {
8607 if !f.is_finite() || f.fract() != 0.0 {
8608 let disp = with_host(|h| h.str_of(v));
8609 return Err(format!(
8610 "RangeError: The number {disp} cannot be converted to a BigInt because it is not an integer"
8611 ));
8612 }
8613 // The decimal EXPANSION, not `fmt_number`: `Number.prototype
8614 // .toString` switches to exponential notation at 1e21, and
8615 // `BigInt::parse_bytes` cannot read `"1e+21"` — so `BigInt(1e21)`
8616 // threw `Cannot convert value to a BigInt` where node returns
8617 // `1000000000000000000000n`. `{:.0}` prints an integral f64's exact
8618 // value, which is also what node reports for a magnitude past the
8619 // exactly-representable range (`BigInt(1e30)` is
8620 // `1000000000000000019884624838656n` in both).
8621 match BigInt::parse_bytes(format!("{f:.0}").as_bytes(), 10) {
8622 Some(b) => b,
8623 None => return Err(bigint_convert_error(v)),
8624 }
8625 }
8626 Value::Str(s) => match host::parse_bigint_str(s) {
8627 Some(b) => b,
8628 None => return Err(format!("SyntaxError: Cannot convert {s} to a BigInt")),
8629 },
8630 Value::Obj(_) => match with_host(|h| h.get(v).cloned()) {
8631 Some(JsObj::BigInt(b)) => b,
8632 Some(JsObj::Str(s)) => match host::parse_bigint_str(&s) {
8633 Some(b) => b,
8634 None => return Err(format!("SyntaxError: Cannot convert {s} to a BigInt")),
8635 },
8636 _ => return Err(bigint_convert_error(v)),
8637 },
8638 _ => return Err(bigint_convert_error(v)),
8639 };
8640 Ok(with_host(|h| h.new_bigint(big)))
8641}
8642
8643/// `new RegExp(source[, flags])` / `RegExp(...)`. A first `RegExp` argument copies
8644/// its source (and flags, unless new ones are given).
8645fn regexp_ctor(args: &[Value], called_as_function: bool) -> Result<Value, String> {
8646 let pattern_is_regexp = is_regexp_arg(&arg0(args));
8647 let flags_given = args.get(1).is_some_and(|v| !matches!(v, Value::Undef));
8648 // 22.2.4.1 step 4.b: called as a function with a regexp-like pattern and no
8649 // flags, a pattern whose `constructor` is this very function is returned
8650 // as it is.
8651 if called_as_function && pattern_is_regexp && !flags_given {
8652 let ctor = get_property(&arg0(args), "constructor")?;
8653 let me = global_binding("RegExp").unwrap_or(Value::Undef);
8654 if with_host(|h| h.strict_eq(&ctor, &me)) {
8655 return Ok(arg0(args));
8656 }
8657 }
8658 // Any other regexp-LIKE object (its `Symbol.match` is truthy) supplies its
8659 // `source` and `flags` by property read (step 6.b-c).
8660 if pattern_is_regexp && !with_host(|h| matches!(h.get(&arg0(args)), Some(JsObj::RegExp(_)))) {
8661 let p = arg0(args);
8662 let source = get_property(&p, "source")?;
8663 let source = if matches!(source, Value::Undef) {
8664 String::new()
8665 } else {
8666 host::to_string_value(&source).map(|s| with_host(|h| h.str_of(&s)))?
8667 };
8668 let flags = if flags_given {
8669 arg_to_string(args, 1)?
8670 } else {
8671 let f = get_property(&p, "flags")?;
8672 if matches!(f, Value::Undef) {
8673 String::new()
8674 } else {
8675 host::to_string_value(&f).map(|s| with_host(|h| h.str_of(&s)))?
8676 }
8677 };
8678 let src = if source.is_empty() {
8679 "(?:)".to_string()
8680 } else {
8681 source
8682 };
8683 return crate::regexp::build_regexp(&src, &flags);
8684 }
8685 let (source, existing_flags) = match with_host(|h| h.get(&arg0(args)).cloned()) {
8686 Some(JsObj::RegExp(r)) => (r.source.clone(), Some(r.flags.clone())),
8687 _ => {
8688 let a0 = arg0(args);
8689 // 22.2.4.1 step 9 is `ToString(pattern)`, which a SYMBOL refuses —
8690 // `new RegExp(sym)` was compiling the text `Symbol(d)` into a
8691 // pattern instead of throwing.
8692 let src = if matches!(a0, Value::Undef) {
8693 String::new()
8694 } else {
8695 arg_to_string(args, 0)?
8696 };
8697 (src, None)
8698 }
8699 };
8700 let flags = match args.get(1) {
8701 Some(v) if !matches!(v, Value::Undef) => arg_to_string(args, 1)?,
8702 _ => existing_flags.unwrap_or_default(),
8703 };
8704 // An empty source compiles as the JS canonical `(?:)`.
8705 let src = if source.is_empty() {
8706 "(?:)".to_string()
8707 } else {
8708 source
8709 };
8710 crate::regexp::build_regexp(&src, &flags)
8711}
8712
8713/// `BigInt.asIntN(bits, x)` / `BigInt.asUintN(bits, x)`: wrap `x` to a `bits`-wide
8714/// two's-complement (signed) or unsigned integer (21.2.2.1 / 21.2.2.2).
8715///
8716/// `bits` goes through `ToIndex` (a RangeError outside 0..=2^53-1) and `x`
8717/// through `ToBigInt`, so a Number is a TypeError and a string parses. A width
8718/// at or beyond the operand's own bit length needs no modular reduction, which
8719/// also keeps `asUintN(2 ** 40, 1n)` from materialising a 2^40-bit modulus.
8720fn bigint_as_n(unsigned: bool, args: &[Value]) -> Result<Value, String> {
8721 use num_bigint::BigInt;
8722 use num_traits::Signed;
8723 /// V8's BigInt size ceiling, in bits (`BigInt::kMaxLengthBits`).
8724 const MAX_BIGINT_BITS: u64 = 1 << 30;
8725 let prim = host::to_primitive(&arg0(args), "number")?;
8726 let n = with_host(|h| h.to_number(&prim));
8727 let n = if n.is_nan() { 0.0 } else { n.trunc() };
8728 if !(0.0..=9_007_199_254_740_991.0).contains(&n) {
8729 return Err("RangeError: Invalid value: not (convertible to) a safe integer".into());
8730 }
8731 let bits = n as u64;
8732 let x = to_bigint(&args.get(1).cloned().unwrap_or(Value::Undef))?;
8733 if bits == 0 {
8734 return Ok(with_host(|h| h.new_bigint(BigInt::from(0))));
8735 }
8736 let magnitude_bits = x.bits();
8737 let fits = if unsigned {
8738 !x.is_negative() && magnitude_bits <= bits
8739 } else {
8740 magnitude_bits < bits
8741 };
8742 if fits {
8743 return Ok(with_host(|h| h.new_bigint(x)));
8744 }
8745 if bits > MAX_BIGINT_BITS {
8746 return Err("RangeError: Maximum BigInt size exceeded".into());
8747 }
8748 let modulus = BigInt::from(1) << bits; // 2^bits
8749 // Reduce into [0, 2^bits); for the signed form fold the top half negative.
8750 let mut r = &x % &modulus;
8751 if r.is_negative() {
8752 r += &modulus;
8753 }
8754 if !unsigned {
8755 let half = BigInt::from(1) << (bits - 1);
8756 if r >= half {
8757 r -= &modulus;
8758 }
8759 }
8760 Ok(with_host(|h| h.new_bigint(r)))
8761}
8762
8763/// `String.raw(callSite, ...subs)`: concatenate the raw quasis (`callSite.raw`)
8764/// interleaved with the substitutions.
8765fn string_raw(args: &[Value]) -> Result<Value, String> {
8766 let call_site = arg0(args);
8767 let raw = get_property(&call_site, "raw")?;
8768 let raws = with_host(|h| h.iter_vec(&raw)).unwrap_or_default();
8769 let mut out = String::new();
8770 for (i, r) in raws.iter().enumerate() {
8771 out.push_str(&with_host(|h| h.str_of(r)));
8772 if i + 1 < raws.len() {
8773 if let Some(sub) = args.get(i + 1) {
8774 out.push_str(&with_host(|h| h.str_of(sub)));
8775 }
8776 }
8777 }
8778 Ok(with_host(|h| h.new_str(out)))
8779}
8780
8781/// `Object(x)`: box/pass-through — for our model, non-object args just return a
8782/// fresh object; objects pass through.
8783/// Whether `v`'s own properties live in the fn-prop SIDE TABLE rather than in a
8784/// property map. A `Map`/`Set`/`Promise`/`RegExp`/generator/symbol/bigint is an
8785/// ordinary object that also has internal slots, so it can carry own properties
8786/// like anything else — but its heap variant holds only those slots, so a write
8787/// had nowhere to go and vanished: `m.x = 5` left `m.x` undefined.
8788pub fn uses_side_table(v: &Value) -> bool {
8789 matches!(
8790 with_host(|h| h.kind_of(v)),
8791 Some(
8792 ObjKind::Map
8793 | ObjKind::Set
8794 | ObjKind::Promise
8795 | ObjKind::RegExp
8796 | ObjKind::Generator
8797 | ObjKind::Symbol
8798 | ObjKind::BigInt
8799 | ObjKind::Iter
8800 )
8801 )
8802}
8803
8804fn object_call(args: Vec<Value>) -> Value {
8805 let a = arg0(&args);
8806 // `Object(v)` is `ToObject(v)` (20.1.1.1): a primitive comes back BOXED,
8807 // not replaced by an empty object. `Object(1).valueOf()` was `undefined`.
8808 if matches!(a, Value::Undef) || with_host(|h| h.is_null(&a)) {
8809 return with_host(|h| h.new_object(IndexMap::new()));
8810 }
8811 to_object(&a)
8812}
8813
8814/// The name of the wrapper a primitive boxes into, or `None` when the value is
8815/// already an object.
8816fn wrapper_ctor_of(v: &Value) -> Option<&'static str> {
8817 match v {
8818 Value::Int(_) | Value::Float(_) => Some("Number"),
8819 Value::Bool(_) => Some("Boolean"),
8820 Value::Obj(_) => match with_host(|h| h.get(v).cloned()) {
8821 Some(JsObj::Str(_)) => Some("String"),
8822 Some(JsObj::Symbol { .. }) => Some("Symbol"),
8823 Some(JsObj::BigInt(_)) => Some("BigInt"),
8824 _ => None,
8825 },
8826 _ => None,
8827 }
8828}
8829
8830/// The primitive a wrapper object boxes (`new String("a")` → `"a"`), or `None`
8831/// for every other value. The slot is a hidden `@@primitive` own property —
8832/// the same `@@` marker convention the engine already uses for internal state,
8833/// so it stays out of `Object.keys` and `JSON.stringify` on its own.
8834pub fn wrapped_primitive(v: &Value) -> Option<Value> {
8835 with_host(|h| match h.get(v) {
8836 Some(JsObj::Object(p)) => p.get("@@primitive").cloned(),
8837 _ => None,
8838 })
8839}
8840
8841/// `ToObject(v)` (7.1.18) for a primitive: the wrapper object with the matching
8842/// prototype and a `[[StringData]]`/`[[NumberData]]`/`[[BooleanData]]` slot.
8843///
8844/// A String wrapper also owns its index properties and `length`, which is what
8845/// makes `w[0]`, `w.length` and `Object.keys(w)` answer; all of them are
8846/// non-writable and non-configurable, as the exotic `String` object's are.
8847pub fn to_object(v: &Value) -> Value {
8848 let Some(ctor) = wrapper_ctor_of(v) else {
8849 return v.clone();
8850 };
8851 with_host(|h| h.ensure_wrapper_protos());
8852 let chars: Vec<String> = if ctor == "String" {
8853 with_host(|h| h.str_of(v))
8854 .chars()
8855 .map(|c| c.to_string())
8856 .collect()
8857 } else {
8858 Vec::new()
8859 };
8860 with_host(|h| {
8861 let mut m: IndexMap<String, Value> = IndexMap::new();
8862 for (i, c) in chars.iter().enumerate() {
8863 let s = h.new_str(c.clone());
8864 m.insert(i.to_string(), s);
8865 }
8866 let w = h.new_object(m);
8867 if ctor == "String" {
8868 for i in 0..chars.len() {
8869 h.set_prop_attrs(
8870 &w,
8871 &i.to_string(),
8872 host::PropAttrs {
8873 writable: false,
8874 enumerable: true,
8875 configurable: false,
8876 },
8877 );
8878 }
8879 let len = Value::Float(chars.len() as f64);
8880 if let Some(JsObj::Object(p)) = h.get_mut(&w) {
8881 p.insert("length".into(), len);
8882 }
8883 h.set_prop_attrs(
8884 &w,
8885 "length",
8886 host::PropAttrs {
8887 writable: false,
8888 enumerable: false,
8889 configurable: false,
8890 },
8891 );
8892 }
8893 if let Some(JsObj::Object(p)) = h.get_mut(&w) {
8894 p.insert("@@primitive".into(), v.clone());
8895 }
8896 if let Some(proto) = h.native_proto(ctor) {
8897 h.set_proto(&w, proto);
8898 }
8899 w
8900 })
8901}
8902
8903/// Construct via `new` for the builtin constructors.
8904/// One `[key, value]` entry of a Map's source iterable (24.1.1.2 steps 8.d-8.f).
8905fn map_entry(p: &Value) -> Result<(Value, Value), String> {
8906 // Step 8.d: each entry must be an OBJECT. A string is iterable, so without
8907 // this check `new Map(["ab"])` happily stored `'a' => 'b'` instead of
8908 // throwing — and over an infinite source it never stopped.
8909 if !with_host(|h| is_object_like(h, p)) {
8910 let shown = with_host(|h| h.str_of(p));
8911 return Err(host::type_error(&format!(
8912 "Iterator value {shown} is not an entry object"
8913 )));
8914 }
8915 // The entry is read by INDEX with `[[Get]]` (step 8.e), not iterated: an
8916 // object with a `Symbol.iterator` but no `0`/`1` gives `undefined =>
8917 // undefined`, and an array-LIKE entry works. Iterating it instead accepted
8918 // a string as a pair and rejected the array-like.
8919 Ok((get_property(p, "0")?, get_property(p, "1")?))
8920}
8921
8922/// `super(iterable)` in `class C extends Map` (or `Set`, `WeakMap`,
8923/// `WeakSet`): the source loop of 24.1.1.1 / 24.2.1.1 / 24.3.1.1 / 24.4.1.1
8924/// run against the subclass instance `inst`. The adder is `Get(inst, "set")`
8925/// (`"add"` for the sets), so a subclass override sees every initial entry —
8926/// the base constructor's own loop calls the native method and never did.
8927pub fn add_entries_via_adder(inst: &Value, ctor: &str, init: &Value) -> Result<(), String> {
8928 let is_map = matches!(ctor, "Map" | "WeakMap");
8929 let key = if is_map { "set" } else { "add" };
8930 let adder = get_property(inst, key)?;
8931 if !with_host(|h| host::is_callable(h, &adder)) {
8932 return Err(host::type_error(&format!(
8933 "'{}' returned for property '{key}' of object '{}' is not a function",
8934 no_side_effects_string(&adder),
8935 no_side_effects_string(inst)
8936 )));
8937 }
8938 host::iter_for_each_for_builtin(init, |p, _| {
8939 let args = if is_map {
8940 let (k, v) = map_entry(&p)?;
8941 vec![k, v]
8942 } else {
8943 vec![p]
8944 };
8945 host::invoke(&adder, args, Some(inst.clone()))?;
8946 Ok(())
8947 })
8948}
8949
8950pub fn construct_builtin(name: &str, args: Vec<Value>) -> Result<Value, String> {
8951 // Native stdlib constructors (`new URL(...)`, `new EventEmitter()`, `new Buffer(...)`).
8952 if let Some(r) = crate::stdlib::construct(name, &args) {
8953 return r;
8954 }
8955 match name {
8956 "Array" => {
8957 // `new Array(n)` -> length-n array; `new Array(a, b)` -> [a, b].
8958 // A single NUMBER argument is a length and is validated as one
8959 // (23.1.1.1 step 6), so `new Array(-1)` / `new Array(1.5)` /
8960 // `new Array(2**32)` are all `RangeError: Invalid array length` on
8961 // node v26.7.0; only a non-number single argument is an element.
8962 if args.len() == 1 {
8963 if let Value::Float(_) | Value::Int(_) = args[0] {
8964 let n = host::to_array_length(&args[0])?;
8965 // Every element of `new Array(n)` is a HOLE, not a stored
8966 // `undefined`: `Object.keys(Array(3))` is `[]`.
8967 return Ok(with_host(|h| {
8968 let a = h.new_array(vec![Value::Undef; n]);
8969 h.mark_hole_range(&a, 0..n);
8970 a
8971 }));
8972 }
8973 }
8974 Ok(with_host(|h| h.new_array(args)))
8975 }
8976 "Object" => Ok(object_call(args)),
8977 // `new String(v)` / `new Number(v)` / `new Boolean(v)` — the wrapper
8978 // form. These were not constructors at all, so every one threw.
8979 "String" => Ok(to_object(&host::to_string_value(
8980 &args
8981 .first()
8982 .cloned()
8983 .unwrap_or_else(|| with_host(|h| h.new_str(String::new()))),
8984 )?)),
8985 "Number" => Ok(to_object(&Value::Float(match args.first() {
8986 Some(a) => host::to_number_value(a)?,
8987 None => 0.0,
8988 }))),
8989 "Boolean" => Ok(to_object(&Value::Bool(with_host(|h| {
8990 h.truthy(&arg0(&args))
8991 })))),
8992 "Map" | "WeakMap" => {
8993 let weak = name == "WeakMap";
8994 let m = with_host(|h| {
8995 h.alloc(JsObj::Map {
8996 entries: indexmap::IndexMap::new(),
8997 weak,
8998 })
8999 });
9000 if let Some(init) = args
9001 .first()
9002 .filter(|a| !matches!(a, Value::Undef) && !with_host(|h| h.is_null(a)))
9003 {
9004 // Stepped, not drained: an entry that is not a pair has to
9005 // stop the construction at that element and CLOSE the iterator
9006 // (24.1.1.2 step 8). Materializing first meant a bad entry in an
9007 // infinite source was never reached and the constructor HUNG.
9008 host::iter_for_each_for_builtin(init, |p, _| {
9009 let (k, v) = map_entry(&p)?;
9010 map_method(&m, "set", vec![k, v])?;
9011 Ok(())
9012 })?;
9013 }
9014 Ok(m)
9015 }
9016 "Set" | "WeakSet" => {
9017 let weak = name == "WeakSet";
9018 let s = with_host(|h| {
9019 h.alloc(JsObj::Set {
9020 entries: indexmap::IndexMap::new(),
9021 weak,
9022 })
9023 });
9024 if let Some(init) = args
9025 .first()
9026 .filter(|a| !matches!(a, Value::Undef) && !with_host(|h| h.is_null(a)))
9027 {
9028 host::iter_for_each_for_builtin(init, |v, _| {
9029 set_method(&s, "add", vec![v])?;
9030 Ok(())
9031 })?;
9032 }
9033 Ok(s)
9034 }
9035 "Promise" => new_promise(arg0(&args)),
9036 "Proxy" => crate::proxy::create(&args),
9037 // `new Function(p…, body)` — the same `CreateDynamicFunction` the plain
9038 // call form runs (20.2.1.1). `depd`'s `wrapfunction` builds its
9039 // deprecation wrapper this way, so `require('body-parser')` — and with it
9040 // `require('express')` — dies at load without it.
9041 "Function" => function_ctor(&args),
9042 "RegExp" => regexp_ctor(&args, false),
9043 "BigInt" => Err(host::type_error("BigInt is not a constructor")),
9044 "Error" => make_error_checked(name, &args),
9045 // `new DOMException(message, name)` — the name is an ARGUMENT, and the
9046 // legacy numeric `code` follows from it.
9047 "DOMException" => Ok(dom_exception(&args)),
9048 n if host::ERROR_NAMES.contains(&n) => make_error_checked(name, &args),
9049 _ => Err(host::type_error(&format!("{name} is not a constructor"))),
9050 }
9051}
9052
9053/// The legacy numeric `DOMException.code` a WHATWG error name maps to. A name
9054/// outside the table — including the default `"Error"` — reports 0.
9055pub const DOM_EXCEPTION_CODES: &[(&str, f64)] = &[
9056 ("IndexSizeError", 1.0),
9057 ("DOMStringSizeError", 2.0),
9058 ("HierarchyRequestError", 3.0),
9059 ("WrongDocumentError", 4.0),
9060 ("InvalidCharacterError", 5.0),
9061 ("NoDataAllowedError", 6.0),
9062 ("NoModificationAllowedError", 7.0),
9063 ("NotFoundError", 8.0),
9064 ("NotSupportedError", 9.0),
9065 ("InUseAttributeError", 10.0),
9066 ("InvalidStateError", 11.0),
9067 ("SyntaxError", 12.0),
9068 ("InvalidModificationError", 13.0),
9069 ("NamespaceError", 14.0),
9070 ("InvalidAccessError", 15.0),
9071 ("ValidationError", 16.0),
9072 ("TypeMismatchError", 17.0),
9073 ("SecurityError", 18.0),
9074 ("NetworkError", 19.0),
9075 ("AbortError", 20.0),
9076 ("URLMismatchError", 21.0),
9077 ("QuotaExceededError", 22.0),
9078 ("TimeoutError", 23.0),
9079 ("InvalidNodeTypeError", 24.0),
9080 ("DataCloneError", 25.0),
9081];
9082
9083/// The static name a `DOMException` code is exposed under: the error name minus
9084/// its `Error` suffix, upper-snake-cased, plus `_ERR` — `AbortError` becomes
9085/// `ABORT_ERR`, `IndexSizeError` becomes `INDEX_SIZE_ERR`.
9086fn legacy_code_name(error_name: &str) -> String {
9087 let stem = error_name.strip_suffix("Error").unwrap_or(error_name);
9088 let mut out = String::new();
9089 for (i, c) in stem.chars().enumerate() {
9090 if c.is_ascii_uppercase() && i > 0 {
9091 out.push('_');
9092 }
9093 out.push(c.to_ascii_uppercase());
9094 }
9095 out.push_str("_ERR");
9096 out
9097}
9098
9099/// `new DOMException(message, name)`.
9100///
9101/// The class node's `AbortSignal.reason` rejects with. Its `name` is the second
9102/// ARGUMENT (defaulting to `"Error"`), not the class name, and its `code` is the
9103/// legacy number that name maps to.
9104pub fn dom_exception(args: &[Value]) -> Value {
9105 let message = match args.first() {
9106 None | Some(Value::Undef) => String::new(),
9107 Some(v) => with_host(|h| h.str_of(v)),
9108 };
9109 let name = match args.get(1) {
9110 None | Some(Value::Undef) => "Error".to_string(),
9111 Some(v) => with_host(|h| h.str_of(v)),
9112 };
9113 with_host(|h| dom_exception_with(h, &name, &message))
9114}
9115
9116/// `dom_exception` for a caller that already holds the host borrow.
9117pub(crate) fn dom_exception_with(h: &mut host::JsHost, name: &str, message: &str) -> Value {
9118 let name = name.to_string();
9119 let message = message.to_string();
9120 let code = DOM_EXCEPTION_CODES
9121 .iter()
9122 .find(|(n, _)| *n == name)
9123 .map(|(_, c)| *c)
9124 .unwrap_or(0.0);
9125 let head = if message.is_empty() {
9126 name.clone()
9127 } else {
9128 format!("{name}: {message}")
9129 };
9130 let e = synth_error(h, &head);
9131 {
9132 let nv = h.new_str(name);
9133 let mv = h.new_str(message);
9134 // node's constructor builds the instance with `new Error()`, which captures
9135 // the stack like any error, so frames follow the head.
9136 let frames = h.stack_frames();
9137 let sv = h.new_str(format!("{head}{frames}"));
9138 if let Some(JsObj::Object(p)) = h.get_mut(&e) {
9139 // `name`, `message` and `code` are PROTOTYPE accessors over internal
9140 // slots in node, so `stack` is the instance's only own property.
9141 // Storing them as own keys would show up in
9142 // `Object.getOwnPropertyNames`, which reports just `['stack']`.
9143 p.shift_remove("message");
9144 p.insert("@@domName".into(), nv);
9145 p.insert("@@domMessage".into(), mv);
9146 p.insert("@@domCode".into(), Value::Float(code));
9147 p.insert("stack".into(), sv);
9148 }
9149 h.ensure_error_protos();
9150 if let Some(proto) = host::error_proto_of(h, "DOMException") {
9151 h.set_proto(&e, proto);
9152 }
9153 }
9154 e
9155}
9156
9157/// A `DOMException`'s `name`/`message`/`code`, which live in internal slots
9158/// rather than as own properties. `None` for anything else.
9159pub fn dom_exception_slot(recv: &Value, name: &str) -> Option<Value> {
9160 let slot = match name {
9161 "name" => "@@domName",
9162 "message" => "@@domMessage",
9163 "code" => "@@domCode",
9164 _ => return None,
9165 };
9166 with_host(|h| match h.get(recv) {
9167 Some(JsObj::Object(p)) if p.contains_key("@@domName") => p.get(slot).cloned(),
9168 _ => None,
9169 })
9170}
9171
9172/// Build an `Error` object carrying `msg`, for stdlib callers that need to
9173/// throw a value with extra own properties on it.
9174pub(crate) fn make_error_pub(name: &str, msg: &str) -> Value {
9175 let m = with_host(|h| h.new_str(msg.to_string()));
9176 make_error_inner(name, &[m])
9177}
9178
9179/// [`make_error`] with the message's `ToString` allowed to FAIL. A symbol
9180/// refuses it (20.5.1.1 step 3), so `new Error(sym)` is a TypeError where this
9181/// rendered `Symbol(desc)` into `.message`.
9182fn make_error_checked(name: &str, args: &[Value]) -> Result<Value, String> {
9183 // 20.5.7.1.1 step 5: `errors` is `IterableToList(errors)`, so a value with no
9184 // `@@iterator` — including the absent one — refuses before anything exists.
9185 if name == "AggregateError" {
9186 let errors = arg0(args);
9187 let iter_fn = get_property(&errors, "@@iterator").unwrap_or(Value::Undef);
9188 if !with_host(|h| host::is_callable(h, &iter_fn)) {
9189 return Err(host::type_error(¬_iterable_typed(&errors)));
9190 }
9191 }
9192 if let Some(m) = args.first().filter(|m| !matches!(m, Value::Undef)) {
9193 // AggregateError's message is its SECOND argument.
9194 let idx = usize::from(name == "AggregateError");
9195 if idx == 0 {
9196 host::to_string_value(m)?;
9197 } else if let Some(m2) = args.get(idx).filter(|m| !matches!(m, Value::Undef)) {
9198 host::to_string_value(m2)?;
9199 }
9200 }
9201 Ok(make_error_inner(name, args))
9202}
9203
9204fn make_error_inner(name: &str, args: &[Value]) -> Value {
9205 // `new AggregateError(errors, message)` takes the causes FIRST; every other
9206 // error constructor takes the message first.
9207 let agg = name == "AggregateError";
9208 let (errors, args) = if agg {
9209 (
9210 Some(args.first().cloned().unwrap_or(Value::Undef)),
9211 args.get(1..).unwrap_or(&[]),
9212 )
9213 } else {
9214 (None, args)
9215 };
9216 with_host(|h| {
9217 h.ensure_error_protos();
9218 // Own keys in V8's order: `stack` (captured first), `message`,
9219 // `cause`, then AggregateError's `errors` (20.5.7.1.1 steps 3-5).
9220 let mut props: IndexMap<String, Value> = IndexMap::new();
9221 props.insert("stack".into(), Value::Undef);
9222 let msg = args
9223 .first()
9224 .filter(|a| !matches!(a, Value::Undef))
9225 .map(|a| h.str_of(a));
9226 if let Some(m) = &msg {
9227 let mv = h.new_str(m.clone());
9228 props.insert("message".into(), mv);
9229 }
9230 // `.stack` is engine-specific; a simple `Name: message` header line
9231 // suffices for parity (the fuzzer never prints raw stacks).
9232 //
9233 // V8 formats that header LAZILY, on the first read, from whatever `name`
9234 // and `message` the error carries at that moment — which is why the
9235 // near-universal
9236 //
9237 // class MyErr extends Error { constructor(m) { super(m); this.name = 'MyErr'; } }
9238 //
9239 // reports `MyErr: boom` and not the `Error: boom` this built eagerly,
9240 // inside `super()`, before the subclass had renamed anything. `@@stackRaw`
9241 // carries the frames so the read can redo it; see `materialize_stack`.
9242 let top = h.error_capture_top();
9243 let frames = h.stack_frames_from(top);
9244 let stack = match &msg {
9245 Some(m) if !m.is_empty() => format!("{name}: {m}{frames}"),
9246 _ => format!("{name}{frames}"),
9247 };
9248 let sv = h.new_str(stack);
9249 props.insert("stack".into(), sv);
9250 let raw = h.new_str(frames);
9251 props.insert("@@stackRaw".into(), raw);
9252 // Where the error was created, which is where node's source arrow
9253 // points when it ends the process as an unhandled rejection.
9254 props.insert("@@pos".into(), Value::Int(h.frame_pos_below(top) as i64));
9255 // `new Error(msg, { cause })` (ES2022): installed only when the options
9256 // bag actually has a `cause` key, so `new Error(m, {})` leaves none.
9257 let opts = args.get(1);
9258 if let Some(cause) = opts.and_then(|o| match h.get(o) {
9259 Some(JsObj::Object(p)) => p.get("cause").cloned(),
9260 _ => None,
9261 }) {
9262 props.insert("cause".into(), cause);
9263 }
9264 if let Some(errs) = errors {
9265 // Materialize the iterable into the own `errors` array property.
9266 let items = h.iter_vec(&errs).unwrap_or_default();
9267 let arr = h.new_array(items);
9268 props.insert("errors".into(), arr);
9269 }
9270 let e = h.new_object(props);
9271 if let Some(p) = host::error_proto_of(h, name) {
9272 h.set_proto(&e, p);
9273 }
9274 // Every own slot an error constructor installs is non-enumerable in V8,
9275 // which is why `Object.keys(err)` is `[]` and `JSON.stringify(err)` is
9276 // `{}` — properties a *script* later assigns stay enumerable.
9277 for k in ["message", "stack", "errors", "cause", "@@stackRaw", "@@pos"] {
9278 h.hide_prop(&e, k);
9279 }
9280 e
9281 })
9282}
9283
9284fn print_line(args: &[Value], stderr: bool) -> Result<(), String> {
9285 // Node's console.log(...args) === util.format(...args): printf-style
9286 // substitution when the first arg is a format string, else inspect-and-join.
9287 // A directive can THROW (`console.log('%j', 1n)`), and node lets that reach
9288 // the caller instead of printing a line — so nothing is written on failure.
9289 let line: String = crate::stdlib::util::format(args)?;
9290 with_host(|h| h.write_out(&format!("{line}\n"), stderr));
9291 Ok(())
9292}
9293
9294fn arg0(args: &[Value]) -> Value {
9295 args.first().cloned().unwrap_or(Value::Undef)
9296}
9297/// `ToString(arg)` for a builtin's argument — fallible, because a SYMBOL
9298/// refuses the conversion (7.1.17). Every site that reached for `str_of`
9299/// instead rendered `Symbol(desc)` into its result and reported nothing.
9300fn arg_to_string(args: &[Value], i: usize) -> Result<String, String> {
9301 let v = args.get(i).cloned().unwrap_or(Value::Undef);
9302 let sv = host::to_string_value(&v)?;
9303 Ok(with_host(|h| h.str_of(&sv)))
9304}
9305
9306fn arg_num(args: &[Value], i: usize) -> f64 {
9307 with_host(|h| h.to_number(&args.get(i).cloned().unwrap_or(Value::Undef)))
9308}
9309
9310fn is_integer(v: Value) -> bool {
9311 match v {
9312 Value::Int(_) => true,
9313 Value::Float(f) => f.is_finite() && f.fract() == 0.0,
9314 _ => false,
9315 }
9316}
9317fn is_safe_integer(v: Value) -> bool {
9318 match v {
9319 Value::Float(f) => f.is_finite() && f.fract() == 0.0 && f.abs() <= 9007199254740991.0,
9320 Value::Int(_) => true,
9321 _ => false,
9322 }
9323}
9324
9325/// `encodeURI`/`encodeURIComponent`: percent-encode `s`'s UTF-8 bytes, leaving
9326/// the unreserved set unescaped. `encodeURI` additionally preserves the reserved
9327/// URI characters (`;,/?:@&=+$#`) that delimit a URI's structure.
9328fn uri_encode(s: &str, uri: bool) -> Result<Value, String> {
9329 // Always-unescaped (`encodeURIComponent`'s unreserved set), per the spec.
9330 const UNRESERVED: &[u8] =
9331 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()";
9332 // Reserved characters `encodeURI` leaves intact on top of the unreserved set.
9333 const RESERVED: &[u8] = b";,/?:@&=+$#";
9334 let mut out = String::with_capacity(s.len());
9335 for &b in s.as_bytes() {
9336 if UNRESERVED.contains(&b) || (uri && RESERVED.contains(&b)) {
9337 out.push(b as char);
9338 } else {
9339 out.push('%');
9340 out.push(
9341 char::from_digit((b >> 4) as u32, 16)
9342 .unwrap()
9343 .to_ascii_uppercase(),
9344 );
9345 out.push(
9346 char::from_digit((b & 0xf) as u32, 16)
9347 .unwrap()
9348 .to_ascii_uppercase(),
9349 );
9350 }
9351 }
9352 Ok(with_host(|h| h.new_str(out)))
9353}
9354
9355/// `decodeURI`/`decodeURIComponent`: reverse `%XX` escapes back to UTF-8 text.
9356/// For `decodeURI`, escapes of the reserved delimiters are left as-is (the spec's
9357/// asymmetry with `encodeURI`). Throws `URIError` on a malformed escape.
9358fn uri_decode(s: &str, uri: bool) -> Result<Value, String> {
9359 const RESERVED: &[u8] = b";,/?:@&=+$#";
9360 let bytes = s.as_bytes();
9361 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
9362 let mut i = 0;
9363 while i < bytes.len() {
9364 if bytes[i] == b'%' {
9365 if i + 2 >= bytes.len() {
9366 return Err("URIError: URI malformed".into());
9367 }
9368 let hi = (bytes[i + 1] as char).to_digit(16);
9369 let lo = (bytes[i + 2] as char).to_digit(16);
9370 match (hi, lo) {
9371 (Some(h), Some(l)) => {
9372 let byte = (h * 16 + l) as u8;
9373 // decodeURI keeps reserved-delimiter escapes literal.
9374 if uri && RESERVED.contains(&byte) {
9375 out.extend_from_slice(&bytes[i..i + 3]);
9376 } else {
9377 out.push(byte);
9378 }
9379 i += 3;
9380 }
9381 _ => return Err("URIError: URI malformed".into()),
9382 }
9383 } else {
9384 out.push(bytes[i]);
9385 i += 1;
9386 }
9387 }
9388 match String::from_utf8(out) {
9389 Ok(decoded) => Ok(with_host(|h| h.new_str(decoded))),
9390 Err(_) => Err("URIError: URI malformed".into()),
9391 }
9392}
9393
9394/// `escape` (Annex B.2.1.1) — the pre-`encodeURIComponent` legacy encoder, still
9395/// present in every engine and still reached by old libraries (jQuery's cookie
9396/// plugin, `querystring`-era code). It works on UTF-16 CODE UNITS, not UTF-8
9397/// bytes, which is what separates it from `encodeURIComponent`: a unit below
9398/// `0x100` becomes `%XX`, anything above becomes `%uXXXX`, so an astral
9399/// character yields the two escapes of its surrogate pair
9400/// (`escape("\u{1D4B3}")` is `"%uD835%uDCB3"` on node v26.7.0).
9401///
9402/// The unescaped set is frozen by the spec and is NOT the URI unreserved set —
9403/// it keeps `@*_+-./` and drops `!~'()`.
9404fn legacy_escape(s: &str) -> Result<Value, String> {
9405 const KEEP: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./";
9406 let mut out = String::with_capacity(s.len());
9407 for u in s.encode_utf16() {
9408 if u < 0x100 {
9409 if KEEP.contains(&(u as u8)) {
9410 out.push(u as u8 as char);
9411 } else {
9412 out.push_str(&format!("%{u:02X}"));
9413 }
9414 } else {
9415 out.push_str(&format!("%u{u:04X}"));
9416 }
9417 }
9418 Ok(with_host(|h| h.new_str(out)))
9419}
9420
9421/// `unescape` (Annex B.2.1.2) — the inverse of [`legacy_escape`]. Unlike
9422/// `decodeURIComponent` it never throws: a `%` that does not begin a well-formed
9423/// `%XX` or `%uXXXX` escape is passed through literally
9424/// (`unescape("%u0041%42%zz%2")` is `"AB%zz%2"` on node v26.7.0).
9425///
9426/// Decoding is done in code-unit space and re-joined at the end so a
9427/// `%uD835%uDCB3` pair recomposes into the one astral character it came from.
9428fn legacy_unescape(s: &str) -> Result<Value, String> {
9429 let b = s.as_bytes();
9430 let hex = |i: usize, n: usize| -> Option<u16> {
9431 if i + n > b.len() {
9432 return None;
9433 }
9434 let mut v: u16 = 0;
9435 for &c in &b[i..i + n] {
9436 v = v.checked_mul(16)? + (c as char).to_digit(16)? as u16;
9437 }
9438 Some(v)
9439 };
9440 let units: Vec<u16> = s.encode_utf16().collect();
9441 let mut out: Vec<u16> = Vec::with_capacity(units.len());
9442 let mut i = 0;
9443 while i < b.len() {
9444 // Escapes are pure ASCII, so a byte index is a unit index up to here —
9445 // but the tail may not be, so non-`%` bytes are re-decoded as chars.
9446 if b[i] == b'%' {
9447 if let Some(u) = hex(i + 1, 2) {
9448 out.push(u);
9449 i += 3;
9450 continue;
9451 }
9452 if b.get(i + 1) == Some(&b'u') {
9453 if let Some(u) = hex(i + 2, 4) {
9454 out.push(u);
9455 i += 6;
9456 continue;
9457 }
9458 }
9459 }
9460 let c = s[i..].chars().next().unwrap_or('%');
9461 let mut buf = [0u16; 2];
9462 out.extend_from_slice(c.encode_utf16(&mut buf));
9463 i += c.len_utf8();
9464 }
9465 Ok(with_host(|h| {
9466 h.new_str(crate::utf16::to_string_lossy(&out))
9467 }))
9468}
9469
9470/// `parseInt` begins with `ToString(argument)` (19.2.5 step 1), and that step can
9471/// THROW — a Symbol has no string form, so `parseInt([Symbol()])` is a TypeError
9472/// rather than `NaN`. Reading the argument with `str_of` took the object's brand
9473/// instead of converting it, which both swallowed that throw and ignored any
9474/// `toString` the value defines.
9475fn parse_int(args: &[Value]) -> Result<f64, String> {
9476 // Converted BEFORE the host borrow: `to_string_value` can call back into JS.
9477 let sv = host::to_string_value(&arg0(args))?;
9478 // 19.2.5 step 2 is `ToInt32(radix)`, which runs a user `valueOf` — the
9479 // infallible read below does no `ToPrimitive`, so an object radix came out
9480 // as NaN and the parse silently fell back to auto-detection.
9481 let radix = match args.get(1) {
9482 Some(r) if !matches!(r, Value::Undef) => {
9483 vec![arg0(args), Value::Float(to_number_arg(args, 1)?)]
9484 }
9485 _ => args.to_vec(),
9486 };
9487 Ok(parse_int_str(&with_host(|h| h.str_of(&sv)), &radix))
9488}
9489
9490fn parse_int_str(s: &str, args: &[Value]) -> f64 {
9491 // 19.2.5 step 8: an EXPLICIT radix outside 2..=36 is `NaN`, it does not fall
9492 // back to auto-detection. The old `.filter()` silently discarded a bad radix,
9493 // so `parseInt("10", 37)` answered 10 where every engine says NaN.
9494 let radix_arg = args
9495 .get(1)
9496 .map(|r| with_host(|h| host::to_int32(h.to_number(r))));
9497 let radix = match radix_arg {
9498 Some(0) | None => None,
9499 Some(r) if (2..=36).contains(&r) => Some(r as u32),
9500 Some(_) => return f64::NAN,
9501 };
9502 let t = crate::utf16::js_trim_start(s);
9503 let (neg, digits) = match t.strip_prefix('-') {
9504 Some(rest) => (true, rest),
9505 None => (false, t.strip_prefix('+').unwrap_or(t)),
9506 };
9507 let (radix, digits) = match radix {
9508 Some(16) => (
9509 16u32,
9510 digits
9511 .strip_prefix("0x")
9512 .or_else(|| digits.strip_prefix("0X"))
9513 .unwrap_or(digits),
9514 ),
9515 Some(r) => (r, digits),
9516 None => {
9517 if let Some(hex) = digits
9518 .strip_prefix("0x")
9519 .or_else(|| digits.strip_prefix("0X"))
9520 {
9521 (16, hex)
9522 } else {
9523 (10, digits)
9524 }
9525 }
9526 };
9527 let valid: String = digits.chars().take_while(|c| c.is_digit(radix)).collect();
9528 if valid.is_empty() {
9529 return f64::NAN;
9530 }
9531 let n = host::digits_to_number(&valid, radix);
9532 if neg {
9533 -n
9534 } else {
9535 n
9536 }
9537}
9538
9539/// `parseFloat` likewise starts from `ToString(argument)`; see `parse_int`.
9540fn parse_float(args: &[Value]) -> Result<f64, String> {
9541 let sv = host::to_string_value(&arg0(args))?;
9542 Ok(parse_float_str(&with_host(|h| h.str_of(&sv))))
9543}
9544
9545fn parse_float_str(s: &str) -> f64 {
9546 let t = crate::utf16::js_trim_start(s);
9547 // `Infinity` / `+Infinity` / `-Infinity` are valid parseFloat prefixes.
9548 let inf_body = t
9549 .strip_prefix('+')
9550 .or_else(|| t.strip_prefix('-'))
9551 .unwrap_or(t);
9552 if inf_body.starts_with("Infinity") {
9553 return if t.starts_with('-') {
9554 f64::NEG_INFINITY
9555 } else {
9556 f64::INFINITY
9557 };
9558 }
9559 // The LONGEST prefix that is itself a complete `StrDecimalLiteral`, which is
9560 // not the same as the longest run of characters that could appear in one:
9561 // `"1e"` and `"1e+"` are `1` in every engine, because the exponent part is
9562 // only valid once a digit follows `e`. Tracking `end` at every character
9563 // accepted the dangling `e`, `parse::<f64>` then failed, and the whole call
9564 // came back NaN.
9565 let mut end = 0;
9566 let bytes = t.as_bytes();
9567 let mut seen_dot = false;
9568 let mut seen_e = false;
9569 let mut digits_before_dot = false;
9570 for (i, &c) in bytes.iter().enumerate() {
9571 match c {
9572 b'0'..=b'9' => {
9573 if !seen_dot && !seen_e {
9574 digits_before_dot = true;
9575 }
9576 end = i + 1;
9577 }
9578 // A sign is only meaningful leading, or straight after the exponent
9579 // marker; it never completes a literal on its own.
9580 b'+' | b'-' if i == 0 || bytes[i - 1] == b'e' || bytes[i - 1] == b'E' => {}
9581 // `1.` is a complete literal; a bare `.` is not.
9582 b'.' if !seen_dot && !seen_e => {
9583 seen_dot = true;
9584 if digits_before_dot {
9585 end = i + 1;
9586 }
9587 }
9588 b'e' | b'E' if !seen_e && end > 0 => seen_e = true,
9589 _ => break,
9590 }
9591 }
9592 if end == 0 {
9593 return f64::NAN;
9594 }
9595 t[..end].parse::<f64>().unwrap_or(f64::NAN)
9596}
9597
9598/// ECMA-262 `Number::exponentiate` (6.1.6.1.3), backing both `Math.pow` and the
9599/// `**` operator. Three clauses differ from IEEE-754 `pow`, which is what Rust's
9600/// `powf` implements: a NaN exponent is NaN even for base 1, a NaN base is NaN
9601/// for any non-zero exponent, and `|base| == 1` with an infinite exponent is NaN
9602/// rather than 1.
9603pub(crate) fn js_pow(base: f64, exp: f64) -> f64 {
9604 if exp == 0.0 {
9605 return 1.0;
9606 }
9607 if base.is_nan() || exp.is_nan() {
9608 return f64::NAN;
9609 }
9610 if base.abs() == 1.0 && exp.is_infinite() {
9611 return f64::NAN;
9612 }
9613 base.powf(exp)
9614}
9615
9616fn math_fn(fname: &str, args: &[Value]) -> Result<Value, String> {
9617 // Every `Math` function coerces its arguments with `ToNumber`, and `ToNumber`
9618 // of a BigInt is a TypeError (7.1.4 step 2) — the whole point of BigInt being
9619 // a separate numeric type. `arg_num` reads a BigInt's magnitude instead, so
9620 // `Math.max(1n)` quietly answered 1 where V8 throws. `Math.random` is the one
9621 // exception: it never reads an argument, so `Math.random(1n)` is fine.
9622 // A BigInt WRAPPER converts to a BigInt and is rejected just as the
9623 // primitive is: `Math.abs(Object(9n))` is a TypeError where it answered NaN.
9624 // The boxed value is read BEFORE the borrow — `wrapped_primitive` borrows
9625 // the host itself and cannot run inside another borrow.
9626 let is_bigint = |a: &Value| {
9627 if with_host(|h| matches!(h.get(a), Some(JsObj::BigInt(_)))) {
9628 return true;
9629 }
9630 match wrapped_primitive(a) {
9631 Some(p) => with_host(|h| matches!(h.get(&p), Some(JsObj::BigInt(_)))),
9632 None => false,
9633 }
9634 };
9635 if fname != "random" && args.iter().any(is_bigint) {
9636 return Err(host::type_error(
9637 "Cannot convert a BigInt value to a number",
9638 ));
9639 }
9640 // Every argument is `ToNumber`d (21.3.2.x), which runs a user `valueOf` and
9641 // can throw from it. `arg_num` does no `ToPrimitive` at all, so
9642 // `Math.max({valueOf: () => 1}, 0)` answered NaN.
9643 // EVERY argument, not a fixed prefix: `Math.max`/`min`/`hypot` are
9644 // variadic, and coercing only the first few silently DROPPED the rest —
9645 // `Math.max(...gen)` over five values answered for four of them.
9646 let mut coerced = Vec::with_capacity(args.len());
9647 for a in args {
9648 if matches!(a, Value::Undef) {
9649 coerced.push(a.clone());
9650 continue;
9651 }
9652 let p = host::to_primitive(a, "number")?;
9653 coerced.push(Value::Float(with_host(|h| h.to_number(&p))));
9654 }
9655 let args: &[Value] = &coerced;
9656 let x = arg_num(args, 0);
9657 let r = match fname {
9658 "floor" => x.floor(),
9659 "ceil" => x.ceil(),
9660 // ECMA-262 `Math.round` (21.3.2.28) transcribed clause by clause. The
9661 // obvious `(x + 0.5).floor()` is NOT this function: the addition rounds
9662 // before the floor sees it, so it answers 1 for the largest double below
9663 // 0.5 (`Math.round(0.49999999999999994)` is 0 in every engine) and it
9664 // perturbs integers above 2^52, where `x + 0.5` is no longer
9665 // representable (`Math.round(4503599627370497)` must be the input).
9666 // Splitting the zero-band cases out first also carries the signed zero
9667 // the spec asks for without a post-hoc patch.
9668 "round" => {
9669 if !x.is_finite() || x == 0.0 {
9670 x
9671 } else if x > 0.0 && x < 0.5 {
9672 0.0
9673 } else if (-0.5..0.0).contains(&x) {
9674 -0.0
9675 } else {
9676 // |x| >= 0.5, so `floor` and the subtraction are both exact
9677 // (every double >= 2^52 is already an integer and yields 0 here).
9678 let f = x.floor();
9679 if x - f >= 0.5 {
9680 f + 1.0
9681 } else {
9682 f
9683 }
9684 }
9685 }
9686 "trunc" => x.trunc(),
9687 "abs" => x.abs(),
9688 "sign" => {
9689 if x.is_nan() {
9690 f64::NAN
9691 } else if x > 0.0 {
9692 1.0
9693 } else if x < 0.0 {
9694 -1.0
9695 } else {
9696 x
9697 }
9698 }
9699 "sqrt" => x.sqrt(),
9700 "cbrt" => ieee754::cbrt(x),
9701 "exp" => ieee754::exp(x),
9702 "log" => ieee754::log(x),
9703 "log2" => ieee754::log2(x),
9704 "log10" => ieee754::log10(x),
9705 "sin" => ieee754::sin(x),
9706 "cos" => ieee754::cos(x),
9707 "tan" => ieee754::tan(x),
9708 "asin" => ieee754::asin(x),
9709 "acos" => ieee754::acos(x),
9710 "atan" => ieee754::atan(x),
9711 "atan2" => ieee754::atan2(x, arg_num(args, 1)),
9712 // Rust `powf` is IEEE-754 `pow`, which is NOT JS `**`/`Math.pow`: IEEE
9713 // makes `pow(x, ±0)` and `pow(±1, y)` return 1 unconditionally, so
9714 // `(-1) ** Infinity` and `1 ** NaN` come back 1 where the spec
9715 // (6.1.6.1.3 Number::exponentiate) says NaN. Only the exponent-is-zero
9716 // clause is shared.
9717 "pow" => js_pow(x, arg_num(args, 1)),
9718 // Hyperbolics and the two precision-preserving log/exp forms.
9719 "sinh" => ieee754::sinh(x),
9720 "cosh" => ieee754::cosh(x),
9721 "tanh" => ieee754::tanh(x),
9722 "asinh" => ieee754::asinh(x),
9723 "acosh" => ieee754::acosh(x),
9724 "atanh" => ieee754::atanh(x),
9725 "log1p" => ieee754::log1p(x),
9726 "expm1" => ieee754::expm1(x),
9727 // C-style 32-bit integer multiply: ToInt32 both operands, multiply with
9728 // wraparound, reinterpret as a signed 32-bit result.
9729 "imul" => (host::to_int32(x).wrapping_mul(host::to_int32(arg_num(args, 1)))) as f64,
9730 "hypot" => {
9731 // Scale by the largest magnitude before squaring — this avoids the
9732 // last-ULP error of the naive `sqrt(Σ xᵢ²)` and matches V8's result.
9733 let xs: Vec<f64> = args.iter().map(|a| with_host(|h| h.to_number(a))).collect();
9734 let mut max = 0.0f64;
9735 for x in &xs {
9736 if x.abs() > max {
9737 max = x.abs();
9738 }
9739 }
9740 if xs.iter().any(|x| x.is_infinite()) {
9741 f64::INFINITY
9742 } else if max == 0.0 || !max.is_finite() {
9743 max
9744 } else {
9745 let s: f64 = xs.iter().map(|x| (x / max) * (x / max)).sum();
9746 max * s.sqrt()
9747 }
9748 }
9749 "random" => pseudo_random(),
9750 "max" => {
9751 if args.is_empty() {
9752 f64::NEG_INFINITY
9753 } else {
9754 let mut m = f64::NEG_INFINITY;
9755 for a in args {
9756 let n = with_host(|h| h.to_number(a));
9757 if n.is_nan() {
9758 return Ok(Value::Float(f64::NAN));
9759 }
9760 // `>` cannot separate the zeroes (`0.0 > -0.0` is false), but
9761 // the spec ranks +0 above -0, so `Math.max(-0, 0)` is +0 and
9762 // must not keep the -0 the first iteration installed.
9763 if n > m || (n == m && n == 0.0 && n.is_sign_positive()) {
9764 m = n;
9765 }
9766 }
9767 m
9768 }
9769 }
9770 "min" => {
9771 if args.is_empty() {
9772 f64::INFINITY
9773 } else {
9774 let mut m = f64::INFINITY;
9775 for a in args {
9776 let n = with_host(|h| h.to_number(a));
9777 if n.is_nan() {
9778 return Ok(Value::Float(f64::NAN));
9779 }
9780 // Mirror of `max`: -0 ranks below +0 even though `<` says
9781 // they are equal, so `Math.min(0, -0)` is -0.
9782 if n < m || (n == m && n == 0.0 && n.is_sign_negative()) {
9783 m = n;
9784 }
9785 }
9786 m
9787 }
9788 }
9789 // Count leading zero bits of ToUint32(x) (Math.clz32(1) === 31).
9790 "clz32" => {
9791 let u = if x.is_finite() {
9792 x.trunc().rem_euclid(4294967296.0) as u32
9793 } else {
9794 0
9795 };
9796 u.leading_zeros() as f64
9797 }
9798 // Round to the nearest single-precision float.
9799 "fround" => (x as f32) as f64,
9800 // Round to the nearest IEEE 754 binary16 value, ties to even, straight
9801 // from the double: going through `f32` first would round twice.
9802 "f16round" => f16_round(x),
9803 _ => return Err(host::type_error(&format!("Math.{fname} is not a function"))),
9804 };
9805 Ok(Value::Float(r))
9806}
9807
9808/// A small deterministic PRNG for `Math.random` (output is non-reproducible vs
9809/// Node by nature; kept simple).
9810fn pseudo_random() -> f64 {
9811 use std::cell::Cell;
9812 thread_local!(static SEED: Cell<u64> = const { Cell::new(0x2545F4914F6CDD1D) });
9813 SEED.with(|s| {
9814 let mut x = s.get();
9815 x ^= x << 13;
9816 x ^= x >> 7;
9817 x ^= x << 17;
9818 s.set(x);
9819 (x >> 11) as f64 / (1u64 << 53) as f64
9820 })
9821}
9822
9823// ── Object.* ──────────────────────────────────────────────────────────────────
9824
9825/// The characters of a string PRIMITIVE, as the `ToObject` wrapper's own index
9826/// properties (10.4.3 `StringExoticObject`).
9827///
9828/// `getOwnPropertyDescriptor` begins with `ToObject`, which boxes a string into
9829/// an exotic object whose own keys are its code-unit indices plus `length`;
9830/// this is the descriptor half of that. (The KEY half lives in
9831/// `JsHost::own_enum_data_keys`, the single source every enumeration path
9832/// reads.) Indices are UTF-16 code units, matching `.length` and `s[i]`.
9833///
9834/// A boxed `String` object is deliberately NOT routed here: it can carry
9835/// ordinary own properties too (`const s = new String('ab'); s.x = 1`), and its
9836/// existing path already reports them alongside the indices.
9837fn string_primitive_units(v: &Value) -> Option<Vec<String>> {
9838 // A JS string primitive rides as a `Value::Obj` handle to `JsObj::Str` (see
9839 // `host.rs`); a BOXED `new String(...)` is a different heap object, so this
9840 // never catches one.
9841 let s = match v {
9842 Value::Str(s) => (**s).clone(),
9843 _ => with_host(|h| match h.get(v) {
9844 Some(JsObj::Str(s)) => Some(s.clone()),
9845 _ => None,
9846 })?,
9847 };
9848 let units = crate::utf16::Units::of(&s);
9849 Some((0..units.len()).filter_map(|i| units.unit_str(i)).collect())
9850}
9851
9852fn object_keys(args: Vec<Value>, mode: u8) -> Result<Value, String> {
9853 let v = arg0(&args);
9854 require_object_coercible(&v)?;
9855 // A Proxy answers from its `ownKeys` trap. `getOwnPropertyNames` (mode 3)
9856 // reports every own STRING key the trap named; the enumerating modes
9857 // additionally filter by each key's `[[GetOwnProperty]]`, so both traps run.
9858 if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
9859 if mode == 3 {
9860 let keys = crate::proxy::own_keys(&v)?.unwrap_or_default();
9861 return Ok(with_host(|h| {
9862 let out: Vec<Value> = keys
9863 .into_iter()
9864 .filter(|k| !host::is_symbol_key(k))
9865 .map(|k| h.new_str(k))
9866 .collect();
9867 h.new_array(out)
9868 }));
9869 }
9870 // `Object.keys` (mode 0) must run `ownKeys` and `getOwnPropertyDescriptor`
9871 // and STOP — 7.3.23 never performs `[[Get]]` when only keys are wanted.
9872 // Going through `own_enum_entries` fired the `get` trap once per key, so
9873 // the observable trap sequence carried a trailing `get` node does not
9874 // emit, and a trap with side effects ran when it should not have.
9875 if mode == 0 {
9876 let keys = crate::proxy::own_enum_string_keys(&v)?;
9877 return Ok(with_host(|h| {
9878 let out: Vec<Value> = keys.into_iter().map(|k| h.new_str(k)).collect();
9879 h.new_array(out)
9880 }));
9881 }
9882 let entries = crate::proxy::own_enum_entries(&v)?;
9883 return Ok(with_host(|h| {
9884 let out: Vec<Value> = entries
9885 .into_iter()
9886 .map(|(k, val)| match mode {
9887 0 => h.new_str(k),
9888 1 => val,
9889 _ => {
9890 let ks = h.new_str(k);
9891 h.new_array(vec![ks, val])
9892 }
9893 })
9894 .collect();
9895 h.new_array(out)
9896 }));
9897 }
9898 // An intrinsic prototype this host built as a REAL OBJECT — `Symbol
9899 // .prototype`, `String.prototype`, the error hierarchy — answers from the
9900 // generated table too. It was answering from its own property map instead,
9901 // which carries neither the right names nor V8's order: `Symbol.prototype`
9902 // reported `toLocaleString` and omitted `description`, and
9903 // `String.prototype` omitted `length` and every Annex B HTML method.
9904 //
9905 // `ns` is the namespace SPELLING, so the arm below is shared verbatim —
9906 // the two representations of a prototype cannot answer differently.
9907 let real_proto_ns = with_host(|h| h.intrinsic_proto_ctor(&v).map(|c| format!("{c}.prototype")))
9908 .filter(|ns| intrinsic_proto_members(ns).is_some());
9909 // A builtin prototype namespace that exposes enumerable methods for copying
9910 // (`Object.getOwnPropertyNames(EventEmitter.prototype)` — express's mixin).
9911 if let Some(ns) = real_proto_ns.or_else(|| {
9912 with_host(|h| match h.get(&v) {
9913 Some(JsObj::Builtin(ns)) => Some(ns.clone()),
9914 _ => None,
9915 })
9916 }) {
9917 // An INTRINSIC prototype (`Map.prototype`, `URL.prototype`). Members are
9918 // non-enumerable on an ECMAScript builtin and enumerable on a WebIDL
9919 // interface, which the table records per name.
9920 if let Some(members) = intrinsic_proto_members(&ns) {
9921 let ctor = ns.trim_end_matches(".prototype");
9922 let mut names: Vec<String> = members
9923 .iter()
9924 .filter(|m| mode == 3 || m.starts_with('+'))
9925 .map(|m| m.strip_prefix('+').unwrap_or(m).to_string())
9926 // `getOwnPropertyNames` reports STRING keys only; the table's
9927 // `@@` entries are symbol-keyed members and belong to
9928 // `getOwnPropertySymbols` instead.
9929 .filter(|m| !m.starts_with("@@"))
9930 .collect();
9931 // Plus whatever a script patched onto this prototype under a NEW
9932 // name — an ordinary enumerable own property, so it lists in every
9933 // mode. Without it `Object.keys(Array.prototype)` stayed `[]` after
9934 // an assignment that `Array.prototype.patch` read back happily.
9935 //
9936 // Assigning over an EXISTING member is a `[[Set]]`, which leaves
9937 // that member's attributes alone: restoring a saved `join` must not
9938 // turn it into an enumerable key.
9939 for k in with_host(|h| h.builtin_static_keys(&ns)) {
9940 if !intrinsic_proto_member(&ns, &k) && !names.contains(&k) {
9941 names.push(k);
9942 }
9943 }
9944 return Ok(with_host(|h| {
9945 let out: Vec<Value> = names
9946 .iter()
9947 .map(|name| {
9948 // An accessor member has no thunk — `Map.prototype.size`
9949 // is not a function — so a VALUE read of one answers
9950 // undefined rather than synthesizing a callable.
9951 let val = |h: &mut host::JsHost| {
9952 if let Some(v) = h.builtin_static(&ns, name) {
9953 return v;
9954 }
9955 let key = format!("@proto:{ctor}:{name}");
9956 if builtin_meta(&key).is_some() {
9957 h.alloc(JsObj::Builtin(key))
9958 } else {
9959 Value::Undef
9960 }
9961 };
9962 match mode {
9963 1 => val(h),
9964 2 => {
9965 let ks = h.new_str(name.clone());
9966 let v = val(h);
9967 h.new_array(vec![ks, v])
9968 }
9969 _ => h.new_str(name.clone()),
9970 }
9971 })
9972 .collect();
9973 h.new_array(out)
9974 }));
9975 }
9976 if let Some(names) = builtin_proto_method_names(&ns) {
9977 return Ok(with_host(|h| {
9978 let out: Vec<Value> = names
9979 .iter()
9980 .map(|name| match mode {
9981 1 => h.alloc(JsObj::Builtin(format!(
9982 "@proto:{}:{name}",
9983 ns.trim_end_matches(".prototype")
9984 ))),
9985 2 => {
9986 let ks = h.new_str(*name);
9987 let val = h.alloc(JsObj::Builtin(format!(
9988 "@proto:{}:{name}",
9989 ns.trim_end_matches(".prototype")
9990 )));
9991 h.new_array(vec![ks, val])
9992 }
9993 _ => h.new_str(*name),
9994 })
9995 .collect();
9996 h.new_array(out)
9997 }));
9998 }
9999 // A stdlib namespace (`Buffer`, `require('buffer')`): its own enumerable
10000 // keys are the members node-js implements, each resolved to the same
10001 // first-class value a property read would give.
10002 let mut names = crate::stdlib::namespace_keys(&ns);
10003 // A constructor implemented as a stdlib namespace (`Iterator`, `Buffer`,
10004 // `URL`) owns `length`, `name` and `prototype` ahead of its statics, as
10005 // every function does; its key list names only the statics.
10006 if mode == 3 && !names.is_empty() && is_builtin_ctor(&ns) {
10007 let mut own: Vec<String> = ["length", "name", "prototype"]
10008 .into_iter()
10009 .filter(|k| !names.iter().any(|n| n == k))
10010 .map(str::to_string)
10011 .collect();
10012 own.append(&mut names);
10013 names = own;
10014 }
10015 // An ECMAScript constructor's statics are non-enumerable, so only
10016 // `getOwnPropertyNames` lists them.
10017 if mode != 3 && !crate::stdlib::namespace_statics_enumerable(&ns) {
10018 names.clear();
10019 }
10020 // A core namespace (`Reflect`, `Math`, `JSON`) has no stdlib key list —
10021 // its members live in the builtin dispatch table. They are
10022 // non-enumerable in V8, so they surface only under
10023 // `getOwnPropertyNames`/`Reflect.ownKeys` (mode 3), never `Object.keys`.
10024 if names.is_empty() && mode == 3 {
10025 let prefix = format!("{ns}.");
10026 // A builtin constructor's own `length`/`name`/`prototype` come
10027 // first, as they do in V8.
10028 if is_builtin_ctor(&ns) {
10029 names.extend(["length", "name", "prototype"].map(str::to_string));
10030 }
10031 names.extend(
10032 NS_METHODS
10033 .iter()
10034 .filter_map(|q| q.strip_prefix(&prefix))
10035 .map(|m| m.to_string()),
10036 );
10037 // The numeric constants are members too. Without them
10038 // `getOwnPropertyNames(Math)` reported 35 of the 43 names node-js
10039 // actually answers — the eight it dropped being `PI` and its
10040 // siblings, which read fine and now own a descriptor as well.
10041 names.extend(
10042 namespace_constants(&ns)
10043 .iter()
10044 .map(|(k, _)| (*k).to_string()),
10045 );
10046 }
10047 // A builtin FUNCTION owns exactly `length` and `name` (10.3.3-4), so
10048 // `Object.getOwnPropertyNames(Math.max)` is `[ 'length', 'name' ]` — it
10049 // was `[]`, which said the function had no properties at all while both
10050 // of them read back a value. `length` is listed only where the intrinsic
10051 // table has an arity, so the names never advertise a read that answers
10052 // `undefined`.
10053 if names.is_empty() && mode == 3 && host::builtin_is_callable(&ns) {
10054 if builtin_meta(&ns).is_some() {
10055 names.push("length".to_string());
10056 }
10057 names.push("name".to_string());
10058 if core_function_prototyped(&ns) {
10059 names.push("prototype".to_string());
10060 }
10061 }
10062 // Whatever a script assigned onto the namespace, in assignment order and
10063 // after the built-in members — an ordinary enumerable own property, so
10064 // it surfaces under `Object.keys` too and not only `ownKeys`. These were
10065 // missing from every listing, which made a patched prototype read as
10066 // unpatched to any code that enumerates rather than reads.
10067 for k in with_host(|h| h.builtin_static_keys(&ns)) {
10068 if !names.contains(&k) {
10069 names.push(k);
10070 }
10071 }
10072 if !names.is_empty() {
10073 let entries: Vec<(String, Value)> = names
10074 .into_iter()
10075 .map(|k| {
10076 let val = namespace_property(&ns, &k);
10077 (k, val)
10078 })
10079 .collect();
10080 return Ok(with_host(|h| {
10081 let out: Vec<Value> = entries
10082 .into_iter()
10083 .map(|(k, val)| match mode {
10084 1 => val,
10085 2 => {
10086 let ks = h.new_str(k);
10087 h.new_array(vec![ks, val])
10088 }
10089 _ => h.new_str(k),
10090 })
10091 .collect();
10092 h.new_array(out)
10093 }));
10094 }
10095 }
10096 // mode 3 (`getOwnPropertyNames`) reports every own string key including the
10097 // non-enumerable ones, plus the exotic `length` an array carries.
10098 let entries: Vec<(String, Value)> = with_host(|h| {
10099 if mode == 3 {
10100 // An array's exotic `length` is already placed (after the indices,
10101 // before the ordinary string keys) by `own_key_names`.
10102 return h
10103 .own_key_names(&v, false)
10104 .into_iter()
10105 .map(|k| (k, Value::Undef))
10106 .collect();
10107 }
10108 Vec::new()
10109 });
10110 // `Object.keys` (mode 0) wants NAMES. `own_enum_entries_deep` returns
10111 // key/value pairs, so asking it for them ran every enumerable getter —
10112 // 20.1.2.17 -> 7.3.23 EnumerableOwnProperties only needs `[[GetOwnProperty]]`
10113 // for the enumerable flag, never `[[Get]]`, and a getter can throw or have
10114 // side effects:
10115 //
10116 // let n = 0; const o = { get g() { n++; return 1 } };
10117 // Object.keys(o); n // was 1, node says 0
10118 //
10119 // `values`/`entries` (modes 1 and 2) do read, and still do.
10120 let entries = match mode {
10121 3 => entries,
10122 0 => with_host(|h| h.own_enum_key_names(&v))
10123 .into_iter()
10124 .map(|k| (k, Value::Undef))
10125 .collect(),
10126 _ => host::own_enum_entries_deep(&v)?,
10127 };
10128 Ok(with_host(|h| {
10129 let out: Vec<Value> = entries
10130 .into_iter()
10131 .map(|(k, val)| match mode {
10132 0 | 3 => h.new_str(k),
10133 1 => val,
10134 _ => {
10135 let ks = h.new_str(k);
10136 h.new_array(vec![ks, val])
10137 }
10138 })
10139 .collect();
10140 h.new_array(out)
10141 }))
10142}
10143
10144fn object_assign(args: Vec<Value>) -> Result<Value, String> {
10145 let target = arg0(&args);
10146 // 20.1.2.1 step 1 is `ToObject(target)`, so a nullish TARGET throws while a
10147 // nullish SOURCE is skipped (`Object.assign({}, null)` is `{}`).
10148 require_object_coercible(&target)?;
10149 for src in args.iter().skip(1) {
10150 // `Object.assign` copies own *enumerable* properties, running any getter
10151 // — symbol-keyed ones included (7.3.25).
10152 let entries = host::own_enum_entries_deep(src)?;
10153 let syms = with_host(|h| h.own_symbol_entries(src));
10154 // A plain, open object target with no accessors and no read-only keys is
10155 // filled in place (one borrow, then a single re-canonicalization of the
10156 // integer-index keys). Anything else needs `Set` proper: a frozen or
10157 // non-extensible target, a setter, a read-only property all refuse or
10158 // intercept the write.
10159 let plain_target = with_host(|h| {
10160 matches!(h.get(&target), Some(JsObj::Object(_)))
10161 && h.is_extensible(&target)
10162 && h.own_accessor_keys(&target).is_empty()
10163 && entries
10164 .iter()
10165 .chain(syms.iter())
10166 .all(|(k, _)| h.prop_attrs(&target, k).writable)
10167 });
10168 let filled = plain_target
10169 && with_host(|h| {
10170 if let Some(JsObj::Object(p)) = h.get_mut(&target) {
10171 for (k, v) in entries.iter().cloned().chain(syms.iter().cloned()) {
10172 p.insert(k, v);
10173 }
10174 host::canonicalize_own_keys(p);
10175 return true;
10176 }
10177 false
10178 });
10179 // Any OTHER target — an array being the common one — goes through the
10180 // ordinary Set path. The in-place branch above matched `JsObj::Object`
10181 // only, so `Object.assign([1,2], {extra:9})` silently copied NOTHING and
10182 // returned the untouched array: no error, just a missing property. The
10183 // Set path is what an `arr.extra = 9` assignment already used, so index
10184 // and non-index keys land where they do for a direct write.
10185 if !filled {
10186 host::JsHost::with_forced_strict(|| {
10187 for (k, v) in entries.into_iter().chain(syms) {
10188 set_property(&target, &k, v)?;
10189 }
10190 Ok::<(), String>(())
10191 })?;
10192 }
10193 }
10194 Ok(target)
10195}
10196
10197fn object_from_entries(args: Vec<Value>) -> Result<Value, String> {
10198 // 20.1.2.7: RequireObjectCoercible, then AddEntriesFromIterable — each
10199 // entry must be an object, read by INDEX (`[[Get]]` of "0" and "1"), its
10200 // key through ToPropertyKey, and stored with CreateDataProperty. A bad
10201 // entry stops the walk and closes the iterator.
10202 let src = arg0(&args);
10203 if with_host(|h| h.is_nullish(&src)) {
10204 return Err(host::type_error("undefined is not iterable"));
10205 }
10206 let obj = with_host(|h| h.new_object(IndexMap::new()));
10207 host::iter_for_each_for_builtin(&src, |entry, _| {
10208 if !with_host(|h| is_object_like(h, &entry)) {
10209 let shown = with_host(|h| h.str_of(&entry));
10210 return Err(host::type_error(&format!(
10211 "Iterator value {shown} is not an entry object"
10212 )));
10213 }
10214 let k = get_property(&entry, "0")?;
10215 let v = get_property(&entry, "1")?;
10216 let key = host::to_property_key(&k)?;
10217 with_host(|h| {
10218 if let Some(JsObj::Object(p)) = h.get_mut(&obj) {
10219 p.insert(key, v);
10220 host::canonicalize_own_keys(p);
10221 }
10222 });
10223 Ok(())
10224 })?;
10225 Ok(obj)
10226}
10227
10228/// `Object.groupBy(items, cb)` — group the iterable `items` into a null-prototype
10229/// object. Keys are `ToPropertyKey(cb(item, index))`; values are arrays of the
10230/// members mapped to that key, in first-seen key order.
10231fn object_group_by(args: Vec<Value>) -> Result<Value, String> {
10232 group_by_check_iterable(&arg0(&args), "Object.groupBy")?;
10233 let cb = args.get(1).cloned().unwrap_or(Value::Undef);
10234 let mut groups: IndexMap<String, Vec<Value>> = IndexMap::new();
10235 // Stepped, not drained: the callback runs per element, so a throwing one
10236 // stops at the first. Draining first meant an infinite source never reached
10237 // the callback at all and the call HUNG.
10238 host::iter_for_each(&arg0(&args), |item, i| {
10239 let key_v = host::invoke(&cb, vec![item.clone(), Value::Float(i as f64)], None)?;
10240 let key = with_host(|h| h.property_key(&key_v));
10241 groups.entry(key).or_default().push(item);
10242 Ok(())
10243 })?;
10244 let props: IndexMap<String, Value> = with_host(|h| {
10245 groups
10246 .into_iter()
10247 .map(|(k, v)| (k, h.new_array(v)))
10248 .collect()
10249 });
10250 let obj = with_host(|h| h.new_object(props));
10251 // A null-prototype object (as Node returns), so it has no inherited members.
10252 with_host(|h| {
10253 let nv = h.null();
10254 h.set_proto(&obj, nv);
10255 });
10256 Ok(obj)
10257}
10258
10259/// The `groupBy` family words a non-iterable argument its OWN way — a third
10260/// vocabulary, alongside the array-literal spread's and the call spread's:
10261///
10262/// ```text
10263/// null / undefined "<Name> called on null or undefined"
10264/// anything else "<typeof> [value ]is not iterable (cannot read property
10265/// Symbol(Symbol.iterator))"
10266/// ```
10267///
10268/// A plain object, a symbol and a bigint name only their TYPE; a number, a
10269/// string and a boolean name the value too.
10270fn group_by_check_iterable(v: &Value, name: &str) -> Result<(), String> {
10271 if with_host(|h| h.is_nullish(v)) {
10272 return Err(host::type_error(&format!(
10273 "{name} called on null or undefined"
10274 )));
10275 }
10276 // Asked WITHOUT consuming anything: `iter_all` would drain the iterator
10277 // here, so the stepping loop below then saw an exhausted one — the finite
10278 // case returned an empty group and the infinite case was back to hanging.
10279 let iter_fn = get_property(v, "@@iterator").unwrap_or(Value::Undef);
10280 if with_host(|h| host::is_callable(h, &iter_fn)) {
10281 return Ok(());
10282 }
10283 Err(host::type_error(¬_iterable_typed(v)))
10284}
10285
10286/// The `<type> <value> is not iterable (cannot read property
10287/// Symbol(Symbol.iterator))` wording, which node uses wherever the source has
10288/// no name to report: a plain object, a symbol and a bigint name only their
10289/// TYPE; a number, a string and a boolean name the value too.
10290pub(crate) fn not_iterable_typed(v: &Value) -> String {
10291 let shown = with_host(|h| {
10292 let kind = h.type_of(v);
10293 match kind {
10294 "object" if h.is_null(v) => "object null".to_string(),
10295 "undefined" => "undefined".to_string(),
10296 "object" | "symbol" | "bigint" | "function" => kind.to_string(),
10297 "string" => format!("string \"{}\"", h.str_of(v)),
10298 _ => format!("{kind} {}", h.str_of(v)),
10299 }
10300 });
10301 format!("{shown} is not iterable (cannot read property Symbol(Symbol.iterator))")
10302}
10303
10304/// `Map.groupBy(items, cb)` — like `Object.groupBy` but returns a `Map` keyed by
10305/// the raw `cb(item, index)` value under SameValueZero (so object/any keys work).
10306fn map_group_by(args: Vec<Value>) -> Result<Value, String> {
10307 group_by_check_iterable(&arg0(&args), "Map.groupBy")?;
10308 let cb = args.get(1).cloned().unwrap_or(Value::Undef);
10309 let m = with_host(|h| {
10310 h.alloc(JsObj::Map {
10311 entries: IndexMap::new(),
10312 weak: false,
10313 })
10314 });
10315 // Stepped for the same reason `Object.groupBy` is.
10316 host::iter_for_each(&arg0(&args), |item, i| {
10317 let key_v = host::invoke(&cb, vec![item.clone(), Value::Float(i as f64)], None)?;
10318 let existing = map_method(&m, "get", vec![key_v.clone()])?;
10319 if matches!(existing, Value::Undef) {
10320 let arr = with_host(|h| h.new_array(vec![item]));
10321 map_method(&m, "set", vec![key_v, arr])?;
10322 } else {
10323 with_host(|h| {
10324 if let Some(JsObj::Array(a)) = h.get_mut(&existing) {
10325 a.push(item);
10326 }
10327 });
10328 }
10329 Ok(())
10330 })?;
10331 Ok(m)
10332}
10333
10334/// `Array.fromAsync(items[, mapFn])` — a Promise for an array, awaiting each
10335/// element and each `mapFn` result.
10336///
10337/// Written in JavaScript and compiled once, because the operation IS an async
10338/// function: a Rust builtin runs outside any coroutine and has no way to await,
10339/// so draining a promise from there would mean running the microtask queue by
10340/// hand. Delegating to the engine's own `async`/`for await` keeps the
10341/// suspension semantics — and the ordering they imply — exactly the language's.
10342///
10343/// The source may be an async iterable, a sync iterable, a bare iterator, or an
10344/// array-like. Everything iterable goes through `for await`, which awaits a sync
10345/// source's elements individually — that is what makes
10346/// `Array.fromAsync([1, Promise.resolve(2)])` answer `[1, 2]`. A bare `.next` is
10347/// accepted because an async generator object does not expose
10348/// `Symbol.asyncIterator` on this frontend.
10349fn array_from_async(args: Vec<Value>) -> Result<Value, String> {
10350 thread_local! {
10351 static IMPL: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
10352 }
10353 const SRC: &str = "(async function (items, mapFn, thisArg) {\n\
10354 const out = []; let i = 0;\n\
10355 const step = async (v) => { const a = await v; out.push(mapFn ? await mapFn.call(thisArg, a, i) : a); i++; };\n\
10356 const iterable = items != null && (typeof items[Symbol.asyncIterator] === 'function'\n\
10357 || typeof items[Symbol.iterator] === 'function' || typeof items.next === 'function');\n\
10358 if (iterable) {\n\
10359 for await (const v of items) { out.push(mapFn ? await mapFn.call(thisArg, v, i) : v); i++; }\n\
10360 return out;\n\
10361 }\n\
10362 const len = items == null ? 0 : (Math.trunc(Number(items.length)) || 0);\n\
10363 while (i < len) { await step(items[i]); }\n\
10364 return out;\n\
10365 })";
10366 let f = IMPL.with(|c| c.borrow().clone());
10367 let f = match f {
10368 Some(f) => f,
10369 None => {
10370 let f = crate::eval_internal(SRC)?;
10371 IMPL.with(|c| *c.borrow_mut() = Some(f.clone()));
10372 f
10373 }
10374 };
10375 host::invoke(&f, args, None)
10376}
10377
10378fn array_from(args: Vec<Value>) -> Result<Value, String> {
10379 // `Array.from` accepts generators and user iterables, plus array-likes with a
10380 // numeric `.length`.
10381 let src = arg0(&args);
10382 // 23.1.2.1 step 4: `GetMethod(items, @@iterator)`. Reading it off a nullish
10383 // value throws; a method that is present but not callable throws; only an
10384 // ABSENT one (undefined/null) selects the array-like path.
10385 if with_host(|h| h.is_nullish(&src)) {
10386 return Err(host::type_error(¬_iterable_typed(&src)));
10387 }
10388 let method = get_property(&src, "@@iterator")?;
10389 let has_iter = !with_host(|h| h.is_nullish(&method));
10390 if has_iter && !with_host(|h| host::is_callable(h, &method)) {
10391 return Err(host::type_error(
10392 "%Array%.from requires that the property of the first argument, items[Symbol.iterator], when exists, be a function",
10393 ));
10394 }
10395 if let Some(cb) = args.get(1).cloned() {
10396 // Stepped, not drained: the mapper runs per element as the iterator
10397 // yields it (23.1.2.1 step 6.e). Materializing the whole sequence first
10398 // meant `Array.from(infiniteIterator, fn)` never reached the mapper at
10399 // all and HUNG, and a throwing mapper could not close the iterator.
10400 let this = this_arg(&args, 2);
10401 let mut out = Vec::new();
10402 let mapped = if has_iter {
10403 host::iter_for_each(&src, |v, i| {
10404 out.push(host::invoke(
10405 &cb,
10406 vec![v, Value::Float(i as f64)],
10407 this.clone(),
10408 )?);
10409 Ok(())
10410 })
10411 } else {
10412 Err(String::new())
10413 };
10414 match mapped {
10415 Ok(()) => {}
10416 // An array-LIKE has no iterator; fall back to its indexed items.
10417 Err(_) if !has_iter => {
10418 for (i, it) in array_like_items(&src).into_iter().enumerate() {
10419 out.push(host::invoke(
10420 &cb,
10421 vec![it, Value::Float(i as f64)],
10422 this.clone(),
10423 )?);
10424 }
10425 }
10426 Err(e) => return Err(e),
10427 }
10428 return construct_array_like(host::current_static_this(), out);
10429 }
10430 let items = if has_iter {
10431 host::iter_all(&src)?
10432 } else {
10433 array_like_items(&src)
10434 };
10435 // 23.1.2.1 step 5: `Array.from` builds through `this`, so on a subclass the
10436 // result is an instance of it. It always allocated a plain array, which is
10437 // also why `A.from([1]).map(f) instanceof A` was false — the species chain
10438 // never started.
10439 construct_array_like(host::current_static_this(), items)
10440}
10441
10442/// Items of an array-like `{ length, 0, 1, … }` object (for `Array.from`).
10443pub(crate) fn array_like_items(src: &Value) -> Vec<Value> {
10444 // `LengthOfArrayLike` is `ToLength(Get(O, "length"))`, and `ToNumber` runs a
10445 // user `valueOf` — `Array.from({length: {valueOf: () => 1}})` was empty
10446 // because the infallible read does no `ToPrimitive`. A throw from it is
10447 // swallowed here for the same reason the `length` read is: this helper has
10448 // no way to report one, and every caller treats an unreadable length as 0.
10449 let len = get_property(src, "length")
10450 .ok()
10451 .and_then(|l| host::to_primitive(&l, "number").ok())
10452 .map(|l| with_host(|h| h.to_number(&l)))
10453 .unwrap_or(0.0);
10454 if !len.is_finite() || len <= 0.0 {
10455 return Vec::new();
10456 }
10457 (0..len as usize)
10458 .map(|i| get_property(src, &i.to_string()).unwrap_or(Value::Undef))
10459 .collect()
10460}
10461
10462// ── JSON ──────────────────────────────────────────────────────────────────────
10463
10464fn json_stringify(args: Vec<Value>) -> Result<Value, String> {
10465 // A CALLABLE second argument is the replacer function, and it is checked
10466 // before the array form (`IsCallable` precedes `IsArray` in the spec), so a
10467 // callable never also reaches the key-filter path below.
10468 let replacer = args
10469 .get(1)
10470 .filter(|r| with_host(|h| host::is_callable(h, r)))
10471 .cloned();
10472 // `toJSON` and the replacer run BEFORE serialization and are user code, so
10473 // the tree is rewritten first — outside the host borrow `json_str` holds,
10474 // and before the BigInt walk, which has no cycle guard of its own.
10475 //
10476 // The top-level value is a property of a synthetic wrapper `{ "": value }`
10477 // under key `""`, which is exactly the holder the replacer receives as
10478 // `this` on its first call.
10479 let root = arg0(&args);
10480 let wrapper = with_host(|h| {
10481 let mut m: IndexMap<String, Value> = IndexMap::new();
10482 m.insert(String::new(), root.clone());
10483 h.new_object(m)
10484 });
10485 let v = apply_to_json(&wrapper, "", &root, &mut Vec::new(), replacer.as_ref())?;
10486 // A BigInt anywhere in a serializable position is a TypeError (JSON has no
10487 // bigint form), matching Node's exact message.
10488 if with_host(|h| json_has_bigint(h, &v)) {
10489 return Err(host::type_error("Do not know how to serialize a BigInt"));
10490 }
10491 let indent = json_gap(args.get(2).cloned().unwrap_or(Value::Undef))?;
10492 let keys = json_property_list(args.get(1).cloned().unwrap_or(Value::Undef))?;
10493 let s = with_host(|h| json_str(h, &v, indent.as_deref(), 0, keys.as_deref()));
10494 match s {
10495 Some(s) => Ok(with_host(|h| h.new_str(s))),
10496 None => Ok(Value::Undef),
10497 }
10498}
10499
10500/// One `SerializeJSONProperty(key, holder)` step: rewrite `v` (the value read
10501/// from `holder[key]`) by calling its `toJSON(key)` and then the replacer
10502/// function as `replacer.call(holder, key, value)`, then recurse into whatever
10503/// object survives. Applies to user methods, class methods, and the native
10504/// `Date`/`Buffer`/`URL` accessors alike.
10505///
10506/// Returns a fresh tree; the input is never mutated. `path` carries the chain of
10507/// objects currently being walked so a cyclic structure is reported rather than
10508/// spinning forever.
10509///
10510/// `toJSON` is called on the value ONCE and is NOT re-applied to its own result
10511/// — `{toJSON(){ return {toJSON(){ return 1 }} }}` serializes as `{}` in Node,
10512/// because the inner method is a plain (unserializable) function property of the
10513/// returned object, not a second conversion hook.
10514fn apply_to_json(
10515 holder: &Value,
10516 key: &str,
10517 v: &Value,
10518 path: &mut JsonPath,
10519 rep: Option<&Value>,
10520) -> Result<Value, String> {
10521 let mut v = v.clone();
10522 if matches!(v, Value::Obj(_)) {
10523 let tag = crate::stdlib::native_tag(&v);
10524 // 25.5.2.1 step 2: `toJSON` is looked up with `[[Get]]`, so a PROXY
10525 // supplies one through its `get` trap. `lookup_chain` walks the
10526 // property map and never asks the handler, so a proxy carrying a
10527 // `toJSON` was serialized as a plain object instead of by its own
10528 // method — and node's trap log starts with that `get`.
10529 let to_json = if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
10530 get_property(&v, "toJSON")?
10531 } else {
10532 with_host(|h| host::lookup_chain(h, &v, "toJSON")).unwrap_or(Value::Undef)
10533 };
10534 let has_to_json = with_host(|h| host::is_callable(h, &to_json))
10535 || tag
10536 .as_deref()
10537 .map(crate::stdlib::has_to_json)
10538 .unwrap_or(false);
10539 if has_to_json {
10540 let k = with_host(|h| h.new_str(key.to_string()));
10541 v = host::call_method(&v, "toJSON", vec![k])?;
10542 }
10543 }
10544 if let Some(rep) = rep {
10545 let k = with_host(|h| h.new_str(key.to_string()));
10546 v = host::invoke(rep, vec![k, v.clone()], Some(holder.clone()))?;
10547 }
10548 // How `v` was reached from its holder, as V8 names the step in a
10549 // circular-structure message: `index 1` under an array, else `property 'k'`.
10550 let via = if matches!(with_host(|h| h.get(holder).cloned()), Some(JsObj::Array(_))) {
10551 format!("index {key}")
10552 } else {
10553 format!("property '{key}'")
10554 };
10555 json_walk_children(&v, path, &via, rep)
10556}
10557
10558/// The objects `JSON.stringify` is inside of, outermost first, each with the
10559/// step that reached it from its holder (`property 'x'` / `index 1`).
10560type JsonPath = Vec<(String, Value)>;
10561
10562/// V8's `ConstructCircularStructureErrorMessage`: the cycle from the object it
10563/// starts at to the key that closes it. At most the first two and the last one
10564/// intermediate step are listed, with `| ...` standing for the rest.
10565fn circular_json_message(path: &JsonPath, start: usize, closing: &str) -> String {
10566 const PREFIX: usize = 2;
10567 const POSTFIX: usize = 1;
10568 let ctor = |v: &Value| -> String {
10569 with_host(|h| match h.get(v) {
10570 Some(JsObj::Array(_)) if h.proto_of(v).is_none() => "Array".to_string(),
10571 _ => match h.ctor_name(v) {
10572 n if n.is_empty() => "Object".to_string(),
10573 n => n,
10574 },
10575 })
10576 };
10577 let line = |i: usize| {
10578 format!(
10579 "\n | {} -> object with constructor '{}'",
10580 path[i].0,
10581 ctor(&path[i].1)
10582 )
10583 };
10584 let mut msg = format!(
10585 "Converting circular structure to JSON\n --> starting at object with constructor '{}'",
10586 ctor(&path[start].1)
10587 );
10588 let prefix_end = path.len().min(start + 1 + PREFIX);
10589 for i in start + 1..prefix_end {
10590 msg.push_str(&line(i));
10591 }
10592 if path.len() > prefix_end + POSTFIX {
10593 msg.push_str("\n | ...");
10594 }
10595 for i in prefix_end.max(path.len().saturating_sub(POSTFIX))..path.len() {
10596 msg.push_str(&line(i));
10597 }
10598 msg.push_str(&format!("\n --- {closing} closes the circle"));
10599 msg
10600}
10601
10602/// Whether a raw property key of a host object is one `json_str` serializes. The
10603/// internal slots (`@@`-prefixed symbol keys, `#`-prefixed private fields) are
10604/// invisible to JSON, so the replacer must not be invoked for them either.
10605fn json_visible_key(k: &str) -> bool {
10606 !k.starts_with("@@") && !k.starts_with('#')
10607}
10608
10609/// Recurse into the elements/properties of an already-converted value, running
10610/// `apply_to_json` for each with this value as the holder.
10611fn json_walk_children(
10612 v: &Value,
10613 path: &mut JsonPath,
10614 via: &str,
10615 rep: Option<&Value>,
10616) -> Result<Value, String> {
10617 if !matches!(v, Value::Obj(_)) {
10618 return Ok(v.clone());
10619 }
10620 // A value that contains itself has no JSON form.
10621 if let Some(start) = with_host(|h| path.iter().position(|(_, p)| h.strict_eq(p, v))) {
10622 return Err(host::type_error(&circular_json_message(path, start, via)));
10623 }
10624 // A Proxy owns no property map, so it is snapshotted through its traps into
10625 // the plain array/object `SerializeJSONArray`/`SerializeJSONObject` describe
10626 // — which read every member through `[[Get]]`, exactly as the snapshot does.
10627 if with_host(|h| h.kind_of(v)) == Some(ObjKind::Proxy) {
10628 // A callable proxy is a function to the serializer (25.5.2.1 step 9:
10629 // `IsCallable` → undefined), whatever its target's keys are.
10630 if with_host(|h| host::is_callable(h, v)) {
10631 return Ok(Value::Undef);
10632 }
10633 let snap = crate::proxy::json_snapshot(v)?;
10634 path.push((via.to_string(), v.clone()));
10635 let out = json_walk_children(&snap, path, via, rep);
10636 path.pop();
10637 return out;
10638 }
10639 let obj = with_host(|h| h.get(v).cloned());
10640 path.push((via.to_string(), v.clone()));
10641 let out = (|| match obj {
10642 Some(JsObj::Array(items)) => {
10643 // Read the elements through the accessor-aware funnel: an index
10644 // with a getter must be SERIALIZED as what the getter returns, and
10645 // the backing vector still holds the stale slot.
10646 let mut resolved = items;
10647 // An index with a getter must be SERIALIZED as what the getter
10648 // returns, and it also forces a rebuild below: keeping the original
10649 // array would hand the serializer back the stale backing vector.
10650 let had_accessor = resolve_index_accessors(v, &mut resolved);
10651 let items = resolved;
10652 // An arguments object is array-LIKE, not an Array (`IsArray` is
10653 // false), so SerializeJSONObject writes `{"0":..,"1":..}` — it is
10654 // the indices as enumerable own properties, and nothing else.
10655 if is_arguments(v) {
10656 let mut props = IndexMap::new();
10657 for (i, it) in items.iter().enumerate() {
10658 let nv = apply_to_json(v, &i.to_string(), it, path, rep)?;
10659 props.insert(i.to_string(), nv);
10660 }
10661 return Ok(with_host(|h| h.new_object(props)));
10662 }
10663 let mut out = Vec::with_capacity(items.len());
10664 let mut changed = had_accessor;
10665 for (i, it) in items.iter().enumerate() {
10666 let nv = apply_to_json(v, &i.to_string(), it, path, rep)?;
10667 changed |= !with_host(|h| h.strict_eq(&nv, it));
10668 out.push(nv);
10669 }
10670 // Keep identity when nothing changed, so an enclosing object is not
10671 // needlessly rebuilt (which would drop its property attributes).
10672 if changed {
10673 Ok(with_host(|h| h.new_array(out)))
10674 } else {
10675 Ok(v.clone())
10676 }
10677 }
10678 Some(JsObj::Object(props)) => {
10679 // An enumerable own accessor must have its getter RUN and the result
10680 // serialized. That cannot happen inside `json_str` (which holds the
10681 // host borrow), so materialize here — the same reason `toJSON` is
10682 // applied in this pass.
10683 let has_accessor = with_host(|h| {
10684 h.own_accessor_keys(v)
10685 .iter()
10686 .any(|k| h.prop_attrs(v, k).enumerable)
10687 });
10688 if has_accessor {
10689 let mut next: IndexMap<String, Value> = IndexMap::new();
10690 for (k, val) in host::own_enum_entries_deep(v)? {
10691 let nv = if json_visible_key(&k) {
10692 apply_to_json(v, &k, &val, path, rep)?
10693 } else {
10694 val
10695 };
10696 next.insert(k, nv);
10697 }
10698 return Ok(with_host(|h| h.new_object(next)));
10699 }
10700 // Only rebuild when a descendant actually changed, so plain data keeps
10701 // its identity (and its prototype / native tag).
10702 let mut next: IndexMap<String, Value> = IndexMap::new();
10703 let mut changed = false;
10704 for (k, val) in &props {
10705 let nv = if json_visible_key(k) {
10706 apply_to_json(v, k, val, path, rep)?
10707 } else {
10708 val.clone()
10709 };
10710 changed |= !with_host(|h| h.strict_eq(&nv, val));
10711 next.insert(k.clone(), nv);
10712 }
10713 if changed {
10714 Ok(with_host(|h| {
10715 let o = h.new_object(next);
10716 h.copy_prop_attrs(v, &o);
10717 o
10718 }))
10719 } else {
10720 Ok(v.clone())
10721 }
10722 }
10723 _ => Ok(v.clone()),
10724 })();
10725 path.pop();
10726 out
10727}
10728
10729/// Whether a value tree contains a `BigInt` in a position `JSON.stringify` would
10730/// try to serialize (a value in an array/object) — such a value throws.
10731fn json_has_bigint(h: &host::JsHost, v: &Value) -> bool {
10732 match h.get(v) {
10733 Some(JsObj::BigInt(_)) => true,
10734 Some(JsObj::Array(items)) => items.iter().any(|x| json_has_bigint(h, x)),
10735 Some(JsObj::Object(props)) => props
10736 .iter()
10737 .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
10738 .any(|(_, val)| json_has_bigint(h, val)),
10739 _ => false,
10740 }
10741}
10742
10743fn json_str(
10744 h: &host::JsHost,
10745 v: &Value,
10746 indent: Option<&str>,
10747 depth: usize,
10748 keys: Option<&[String]>,
10749) -> Option<String> {
10750 let sep = if indent.is_none() { ":" } else { ": " };
10751 match v {
10752 Value::Undef => None,
10753 Value::Bool(b) => Some(if *b { "true".into() } else { "false".into() }),
10754 Value::Int(n) => Some(n.to_string()),
10755 Value::Float(f) => Some(if f.is_finite() {
10756 host::fmt_number(*f)
10757 } else {
10758 "null".into()
10759 }),
10760 Value::Str(s) => Some(json_quote(s)),
10761 Value::Obj(_) => match h.get(v) {
10762 Some(JsObj::Str(s)) => Some(json_quote(s)),
10763 Some(JsObj::Null) => Some("null".into()),
10764 // A `JSON.rawJSON` marker contributes its text VERBATIM — that is the
10765 // whole point of it, and it is why a number wider than a `double`
10766 // can survive a round trip.
10767 _ if h.fn_prop(v, "@@rawJSON").is_some() => match h.get(v) {
10768 Some(JsObj::Object(p)) => p.get("rawJSON").map(|r| h.str_of(r)),
10769 _ => None,
10770 },
10771 // A Map/Set has no ENTRIES to serialize (they are internal slots),
10772 // but any own property a script attached is serialized like an
10773 // ordinary object's: `JSON.stringify(Object.assign(new Map(), {a:1}))`
10774 // is `{"a":1}`.
10775 Some(JsObj::Map { .. })
10776 | Some(JsObj::Set { .. })
10777 | Some(JsObj::RegExp(_))
10778 // A Promise and a generator are ORDINARY objects to the serializer:
10779 // their state is internal slots, so they contribute no entries and
10780 // render as `{}`. They were being omitted entirely instead, so a
10781 // promise in an array became `null` and one in an object vanished.
10782 | Some(JsObj::Promise { .. })
10783 | Some(JsObj::Generator { .. }) => {
10784 let parts: Vec<String> = h
10785 .own_enum_entries(v)
10786 .into_iter()
10787 .filter(|(k, _)| !k.starts_with("@@") && !host::is_symbol_key(k))
10788 .filter_map(|(k, val)| {
10789 // A replacer array restricts these exactly as it does an
10790 // ordinary object's keys.
10791 if keys.is_some_and(|allow| !allow.contains(&k)) {
10792 return None;
10793 }
10794 json_str(h, &val, indent, depth + 1, keys)
10795 .map(|s| format!("{}{sep}{s}", json_quote(&k)))
10796 })
10797 .collect();
10798 if parts.is_empty() {
10799 return Some("{}".into());
10800 }
10801 Some(wrap(&parts, "{", "}", indent, depth))
10802 }
10803 // A NON-callable builtin is a namespace object, not a function, so
10804 // it serializes as one: `JSON.stringify(Math)` is `{}` (its members
10805 // are all non-enumerable), where omitting it made the whole property
10806 // disappear from its holder.
10807 Some(JsObj::Builtin(n)) if !host::builtin_is_callable(n) => {
10808 let parts: Vec<String> = crate::stdlib::namespace_keys(n)
10809 .into_iter()
10810 .filter_map(|k| {
10811 let val = h.builtin_static(n, &k)?;
10812 json_str(h, &val, indent, depth + 1, keys)
10813 .map(|s| format!("{}{sep}{s}", json_quote(&k)))
10814 })
10815 .collect();
10816 if parts.is_empty() {
10817 return Some("{}".into());
10818 }
10819 Some(wrap(&parts, "{", "}", indent, depth))
10820 }
10821 // Functions and symbols are omitted (undefined) as values.
10822 Some(JsObj::Func(_))
10823 | Some(JsObj::Builtin(_))
10824 | Some(JsObj::BoundMethod { .. })
10825 | Some(JsObj::BoundFunc { .. })
10826 | Some(JsObj::Class(_))
10827 | Some(JsObj::Symbol { .. }) => None,
10828 Some(JsObj::Array(items)) => {
10829 if items.is_empty() {
10830 return Some("[]".into());
10831 }
10832 let parts: Vec<String> = items
10833 .iter()
10834 .map(|x| {
10835 json_str(h, x, indent, depth + 1, keys).unwrap_or_else(|| "null".into())
10836 })
10837 .collect();
10838 Some(wrap(&parts, "[", "]", indent, depth))
10839 }
10840 // 25.5.2.2 step 4: a String/Number/Boolean/BigInt wrapper serializes
10841 // as the primitive it boxes, not as the object holding it —
10842 // `JSON.stringify(new Number(1))` is `1`, not `{}`. A Symbol wrapper
10843 // is not on that list: it is an ordinary object, `{}`.
10844 Some(JsObj::Object(props))
10845 if props.contains_key("@@primitive")
10846 && !matches!(h.get(&props["@@primitive"]), Some(JsObj::Symbol { .. })) =>
10847 {
10848 json_str(h, &props["@@primitive"].clone(), indent, depth, keys)
10849 }
10850 Some(JsObj::Object(props)) => {
10851 // A replacer array restricts (and orders) which keys are emitted.
10852 let parts: Vec<String> = match keys {
10853 // `[[Get]]` of each listed name (25.5.2.5 step 5.a): own
10854 // elements the property map does not hold (a typed array's)
10855 // and inherited data properties answer too.
10856 Some(allow) => {
10857 let own = h.own_enum_entries(v);
10858 allow
10859 .iter()
10860 .filter_map(|k| {
10861 let val = props
10862 .get(k)
10863 .cloned()
10864 .or_else(|| {
10865 own.iter().find(|(ek, _)| ek == k).map(|(_, x)| x.clone())
10866 })
10867 .or_else(|| host::lookup_chain(h, v, k))?;
10868 json_str(h, &val, indent, depth + 1, keys)
10869 .map(|vs| format!("{}{sep}{vs}", json_quote(k)))
10870 })
10871 .collect()
10872 }
10873 None => h
10874 .own_enum_entries(v)
10875 .iter()
10876 .filter_map(|(k, val)| {
10877 json_str(h, val, indent, depth + 1, keys)
10878 .map(|vs| format!("{}{sep}{vs}", json_quote(k)))
10879 })
10880 .collect(),
10881 };
10882 if parts.is_empty() {
10883 return Some("{}".into());
10884 }
10885 Some(wrap(&parts, "{", "}", indent, depth))
10886 }
10887 _ => Some("null".into()),
10888 },
10889 _ => Some("null".into()),
10890 }
10891}
10892
10893fn wrap(parts: &[String], open: &str, close: &str, indent: Option<&str>, depth: usize) -> String {
10894 let Some(indent) = indent else {
10895 return format!("{open}{}{close}", parts.join(","));
10896 };
10897 {
10898 let pad = indent.repeat(depth + 1);
10899 let pad_close = indent.repeat(depth);
10900 format!(
10901 "{open}\n{pad}{}\n{pad_close}{close}",
10902 parts.join(&format!(",\n{pad}"))
10903 )
10904 }
10905}
10906
10907fn json_quote(s: &str) -> String {
10908 let mut out = String::from("\"");
10909 for c in s.chars() {
10910 match c {
10911 '"' => out.push_str("\\\""),
10912 '\\' => out.push_str("\\\\"),
10913 '\n' => out.push_str("\\n"),
10914 '\t' => out.push_str("\\t"),
10915 '\r' => out.push_str("\\r"),
10916 // QuoteJSONString (25.5.2.2) names SIX short escapes, not four.
10917 // Backspace and form feed were missing, so they fell through to the
10918 // `\uXXXX` arm below and `JSON.stringify("\b")` produced
10919 // `""` where node produces `"\b"`. Both parse back to the same
10920 // string, so the difference is invisible to a round trip and shows
10921 // up only as a byte mismatch against a fixture or a checksum.
10922 '\u{8}' => out.push_str("\\b"),
10923 '\u{c}' => out.push_str("\\f"),
10924 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
10925 _ => out.push(c),
10926 }
10927 }
10928 out.push('"');
10929 out
10930}
10931
10932fn json_parse(args: Vec<Value>) -> Result<Value, String> {
10933 let s = with_host(|h| h.str_of(&arg0(&args)));
10934 let mut p = JsonParser {
10935 chars: s.chars().collect(),
10936 pos: 0,
10937 prims: Vec::new(),
10938 record: args
10939 .get(1)
10940 .is_some_and(|r| with_host(|h| host::is_callable(h, r))),
10941 };
10942 p.skip_ws();
10943 if p.peek().is_none() {
10944 return Err("SyntaxError: Unexpected end of JSON input".into());
10945 }
10946 let v = p.parse_value()?;
10947 let value_end = p.pos;
10948 p.skip_ws();
10949 // Anything after the top-level value is an error — the parser used to accept
10950 // and silently discard it, so `JSON.parse('{"a":1}x')` succeeded.
10951 if let Some(c) = p.peek() {
10952 // V8 names the token kind only when it butts directly against the value
10953 // (`01` -> "Unexpected number at position 1"); with whitespace between
10954 // it is just a non-whitespace character (`1 2`).
10955 // Only a digit butted directly against a completed number literal —
10956 // V8's number scanner is still in number context there. `5"x"` and
10957 // `[0,1]0` exit the scanner cleanly and get the generic message.
10958 let after_number = value_end > 0
10959 && p.pos == value_end
10960 && p.chars[value_end - 1].is_ascii_digit()
10961 && c.is_ascii_digit();
10962 return Err(if after_number {
10963 p.err_at("Unexpected number", p.pos)
10964 } else {
10965 p.err_trailing(p.pos)
10966 });
10967 }
10968 // Optional reviver: walk bottom-up, transforming each (key, value).
10969 if let Some(reviver) = args
10970 .get(1)
10971 .filter(|r| with_host(|h| host::is_callable(h, r)))
10972 .cloned()
10973 {
10974 // The top-level holder is a fresh `{ "": value }` wrapper, as the spec
10975 // constructs before the walk.
10976 let root = with_host(|h| {
10977 let mut m: IndexMap<String, Value> = IndexMap::new();
10978 m.insert(String::new(), v.clone());
10979 h.new_object(m)
10980 });
10981 return json_revive("", v, &reviver, &root, &p.prims, &mut 0);
10982 }
10983 Ok(v)
10984}
10985
10986/// `JSON.parse` reviver walk: recurse into children first, then call
10987/// `reviver(key, value)`; a returned `undefined` drops the property.
10988///
10989/// The reviver runs with the HOLDER as `this` (25.5.1.1
10990/// InternalizeJSONProperty) — the object or array the key lives in, and at the
10991/// top level a wrapper `{ "": value }`. It was being called with no receiver,
10992/// so `this` was undefined and a reviver could not reach its siblings.
10993/// `JSON.rawJSON(text)` — a marker object whose text `JSON.stringify` emits
10994/// VERBATIM, so a number too large for a `double` survives a round trip
10995/// (`JSON.stringify({n: JSON.rawJSON("12345678901234567890")})`).
10996///
10997/// The validation is not "does `JSON.parse` accept it": node's rule, measured
10998/// across the whole matrix, is
10999///
11000/// ```text
11001/// "" -> SyntaxError: Invalid value for JSON.rawJSON
11002/// leading whitespace -> the parse error for that first character
11003/// a complete literal -> ok
11004/// anything left over -> SyntaxError: Invalid value for JSON.rawJSON
11005/// a broken literal -> the parse error the scanner raised
11006/// ```
11007///
11008/// so `" 1"` reports an unexpected token while `"1 "` and `"1,2"` report the
11009/// invalid-value message even though `JSON.parse` accepts the former and gives
11010/// a token error for the latter.
11011fn json_raw(args: Vec<Value>) -> Result<Value, String> {
11012 const INVALID: &str = "SyntaxError: Invalid value for JSON.rawJSON";
11013 let s = with_host(|h| h.str_of(&arg0(&args)));
11014 if s.is_empty() {
11015 return Err(INVALID.into());
11016 }
11017 let mut p = JsonParser {
11018 chars: s.chars().collect(),
11019 pos: 0,
11020 prims: Vec::new(),
11021 record: false,
11022 };
11023 // An object or an array is rejected where it starts, as leading whitespace
11024 // is — both are "not a primitive", but node reports the token.
11025 if matches!(p.peek(), Some('{') | Some('[')) || p.peek().is_some_and(|c| c.is_whitespace()) {
11026 return Err(p.err_token(0));
11027 }
11028 p.parse_value()?;
11029 if p.pos != p.chars.len() {
11030 // A digit butted against a completed number is still in the number
11031 // scanner, so `"01"` reports the scanner's error rather than leftover
11032 // input — the same distinction `json_parse` draws for trailing text.
11033 if p.chars[p.pos - 1].is_ascii_digit() && p.chars[p.pos].is_ascii_digit() {
11034 return Err(p.err_at("Unexpected number", p.pos));
11035 }
11036 return Err(INVALID.into());
11037 }
11038 // A null prototype and one own `rawJSON` property, frozen — the brand is a
11039 // hidden slot so `Object.keys` stays `["rawJSON"]`.
11040 Ok(with_host(|h| {
11041 let mut m: IndexMap<String, Value> = IndexMap::new();
11042 let text = h.new_str(s);
11043 m.insert("rawJSON".into(), text);
11044 let o = h.new_object(m);
11045 let null = h.null();
11046 h.set_proto(&o, null);
11047 h.set_fn_prop(&o, "@@rawJSON", Value::Bool(true));
11048 h.seal_object(&o, true);
11049 o
11050 }))
11051}
11052
11053/// `JSON.isRawJSON(v)` — the brand check. A hand-built `{ rawJSON: "1" }` is
11054/// NOT one, which is why the marker is a hidden slot rather than the property.
11055fn json_is_raw(args: Vec<Value>) -> Result<Value, String> {
11056 Ok(Value::Bool(is_raw_json(&arg0(&args))))
11057}
11058
11059fn is_raw_json(v: &Value) -> bool {
11060 with_host(|h| h.fn_prop(v, "@@rawJSON")).is_some()
11061}
11062
11063fn json_revive(
11064 key: &str,
11065 val: Value,
11066 reviver: &Value,
11067 holder: &Value,
11068 prims: &[String],
11069 next: &mut usize,
11070) -> Result<Value, String> {
11071 // A PRIMITIVE claims the next recorded source slice before its children
11072 // would — it has none — and a container claims nothing. The walk descends in
11073 // the same order the parse produced them, so one cursor lines the two up.
11074 let is_container =
11075 with_host(|h| matches!(h.get(&val), Some(JsObj::Array(_)) | Some(JsObj::Object(_))));
11076 let source = if !is_container {
11077 let s = prims.get(*next).cloned();
11078 if s.is_some() {
11079 *next += 1;
11080 }
11081 s
11082 } else {
11083 None
11084 };
11085 match with_host(|h| h.get(&val).cloned()) {
11086 Some(JsObj::Array(items)) => {
11087 for i in 0..items.len() {
11088 let elem = with_host(|h| match h.get(&val) {
11089 Some(JsObj::Array(it)) => it[i].clone(),
11090 _ => Value::Undef,
11091 });
11092 let nv = json_revive(&i.to_string(), elem, reviver, &val, prims, next)?;
11093 with_host(|h| {
11094 if let Some(JsObj::Array(it)) = h.get_mut(&val) {
11095 it[i] = nv;
11096 }
11097 });
11098 }
11099 }
11100 Some(JsObj::Object(props)) => {
11101 let keys: Vec<String> = props
11102 .keys()
11103 .filter(|k| !k.starts_with("@@"))
11104 .cloned()
11105 .collect();
11106 for k in keys {
11107 let elem = with_host(|h| match h.get(&val) {
11108 Some(JsObj::Object(p)) => p.get(&k).cloned().unwrap_or(Value::Undef),
11109 _ => Value::Undef,
11110 });
11111 let nv = json_revive(&k, elem, reviver, &val, prims, next)?;
11112 with_host(|h| {
11113 if let Some(JsObj::Object(p)) = h.get_mut(&val) {
11114 if matches!(nv, Value::Undef) {
11115 p.shift_remove(&k);
11116 } else {
11117 p.insert(k.clone(), nv);
11118 }
11119 }
11120 });
11121 }
11122 }
11123 _ => {}
11124 }
11125 let kv = with_host(|h| h.new_str(key.to_string()));
11126 // 25.5.1.1 step 2.b: the reviver's THIRD argument. `{ source }` for a
11127 // primitive, an empty object for an array or an object — node passes it
11128 // either way, and code reading `ctx.source` used to die on `undefined`
11129 // because only two arguments were passed.
11130 let ctx = with_host(|h| {
11131 let mut m: IndexMap<String, Value> = IndexMap::new();
11132 if let Some(s) = source {
11133 let sv = h.new_str(s);
11134 m.insert("source".into(), sv);
11135 }
11136 h.new_object(m)
11137 });
11138 host::invoke(reviver, vec![kv, val, ctx], Some(holder.clone()))
11139}
11140
11141struct JsonParser {
11142 chars: Vec<char>,
11143 pos: usize,
11144 /// Source text of each PRIMITIVE value, in parse order — what the reviver's
11145 /// third argument reports as `context.source` (25.5.1.1). Only collected
11146 /// when a reviver was supplied.
11147 ///
11148 /// A flat list rather than a parallel tree because the reviver walk visits
11149 /// primitives in the same depth-first order the parse produced them, so an
11150 /// index into this is enough to line them up.
11151 prims: Vec<String>,
11152 record: bool,
11153}
11154impl JsonParser {
11155 fn peek(&self) -> Option<char> {
11156 self.chars.get(self.pos).copied()
11157 }
11158
11159 fn peek_at(&self, at: usize) -> Option<char> {
11160 self.chars.get(at).copied()
11161 }
11162
11163 /// The four hex digits of a `\uXXXX` escape starting at `at`; a short or
11164 /// non-hex run is V8's "Bad Unicode escape" at the offending character.
11165 fn hex4(&self, at: usize) -> Result<u32, String> {
11166 let mut n = 0u32;
11167 for k in 0..4 {
11168 match self.peek_at(at + k).and_then(|c| c.to_digit(16)) {
11169 Some(d) => n = n * 16 + d,
11170 None => return Err(self.err_at("Bad Unicode escape", at + k)),
11171 }
11172 }
11173 Ok(n)
11174 }
11175
11176 /// `at position N (line L column C)` — the location suffix V8 appends to the
11177 /// positional JSON parse errors. Positions are in UTF-16-ish code units;
11178 /// node-js counts `char`s, which agree for the BMP.
11179 fn at(&self, pos: usize) -> String {
11180 let mut line = 1usize;
11181 let mut col = 1usize;
11182 for c in &self.chars[..pos.min(self.chars.len())] {
11183 if *c == '\n' {
11184 line += 1;
11185 col = 1;
11186 } else {
11187 col += 1;
11188 }
11189 }
11190 format!(" at position {pos} (line {line} column {col})")
11191 }
11192
11193 /// A positional error (`Expected ':' after property name in JSON at …`).
11194 fn err_at(&self, what: &str, pos: usize) -> String {
11195 format!("SyntaxError: {what} in JSON{}", self.at(pos))
11196 }
11197
11198 /// The one positional message V8 does NOT suffix with `in JSON`.
11199 fn err_trailing(&self, pos: usize) -> String {
11200 format!(
11201 "SyntaxError: Unexpected non-whitespace character after JSON{}",
11202 self.at(pos)
11203 )
11204 }
11205
11206 /// V8's default parse error: the offending character plus a window of the
11207 /// source. The whole input is quoted when it is short (<= 20 chars);
11208 /// otherwise a 10-character context window either side of `pos` is shown,
11209 /// elided with `...` on whichever side was cut.
11210 fn err_token(&self, pos: usize) -> String {
11211 const MAX_WHOLE: usize = 20;
11212 const CONTEXT: usize = 10;
11213 let len = self.chars.len();
11214 let Some(c) = self.chars.get(pos) else {
11215 return "SyntaxError: Unexpected end of JSON input".into();
11216 };
11217 // V8 reports the whole input for the JS literals that are famously not
11218 // JSON, without naming an offending character.
11219 let whole: String = self.chars.iter().collect();
11220 if matches!(
11221 whole.as_str(),
11222 "undefined" | "NaN" | "Infinity" | "-Infinity"
11223 ) {
11224 return format!("SyntaxError: \"{whole}\" is not valid JSON");
11225 }
11226 let snippet = if len <= MAX_WHOLE {
11227 format!("\"{whole}\"")
11228 } else {
11229 let start = pos.saturating_sub(CONTEXT);
11230 let end = (pos + CONTEXT).min(len);
11231 let body: String = self.chars[start..end].iter().collect();
11232 let head = if start > 0 { "..." } else { "" };
11233 let tail = if end < len { "..." } else { "" };
11234 format!("{head}\"{body}\"{tail}")
11235 };
11236 format!("SyntaxError: Unexpected token '{c}', {snippet} is not valid JSON")
11237 }
11238
11239 fn skip_ws(&mut self) {
11240 while matches!(
11241 self.peek(),
11242 Some(' ') | Some('\n') | Some('\t') | Some('\r')
11243 ) {
11244 self.pos += 1;
11245 }
11246 }
11247 fn parse_value(&mut self) -> Result<Value, String> {
11248 self.skip_ws();
11249 let start = self.pos;
11250 let prim = matches!(self.peek(), Some(c) if c != '{' && c != '[');
11251 let v = match self.peek() {
11252 Some('{') => self.parse_object(),
11253 Some('[') => self.parse_array(),
11254 Some('"') => {
11255 let s = self.parse_string()?;
11256 Ok(with_host(|h| h.new_str(s)))
11257 }
11258 Some('t') | Some('f') => self.parse_bool(),
11259 Some('n') => {
11260 self.expect_lit("null")?;
11261 Ok(with_host(|h| h.null()))
11262 }
11263 Some(c) if c == '-' || c.is_ascii_digit() => self.parse_number(),
11264 None => Err("SyntaxError: Unexpected end of JSON input".into()),
11265 _ => Err(self.err_token(self.pos)),
11266 }?;
11267 if prim && self.record {
11268 self.prims
11269 .push(self.chars[start..self.pos].iter().collect());
11270 }
11271 Ok(v)
11272 }
11273 fn expect_lit(&mut self, lit: &str) -> Result<(), String> {
11274 for ch in lit.chars() {
11275 match self.peek() {
11276 Some(c) if c == ch => self.pos += 1,
11277 // V8 reports the first character that broke the literal, which is
11278 // why `foo` complains about `'o'` (index 2) and not `'f'`.
11279 None => return Err("SyntaxError: Unexpected end of JSON input".into()),
11280 _ => return Err(self.err_token(self.pos)),
11281 }
11282 }
11283 Ok(())
11284 }
11285 fn parse_bool(&mut self) -> Result<Value, String> {
11286 if self.peek() == Some('t') {
11287 self.expect_lit("true")?;
11288 Ok(Value::Bool(true))
11289 } else {
11290 self.expect_lit("false")?;
11291 Ok(Value::Bool(false))
11292 }
11293 }
11294 /// JSON's number grammar: `-? (0 | [1-9][0-9]*) (. [0-9]+)? ([eE] [+-]? [0-9]+)?`.
11295 /// A leading zero does NOT swallow the following digits — `01` parses as `0`
11296 /// and the stray `1` becomes a trailing-token error, which is how V8 reports
11297 /// it. Each way the grammar can run out has its own message.
11298 fn parse_number(&mut self) -> Result<Value, String> {
11299 let start = self.pos;
11300 if self.peek() == Some('-') {
11301 self.pos += 1;
11302 if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
11303 return Err(self.err_at("No number after minus sign", self.pos));
11304 }
11305 }
11306 if self.peek() == Some('0') {
11307 self.pos += 1;
11308 } else {
11309 while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
11310 self.pos += 1;
11311 }
11312 }
11313 if self.peek() == Some('.') {
11314 self.pos += 1;
11315 if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
11316 return Err(self.err_at("Unterminated fractional number", self.pos));
11317 }
11318 while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
11319 self.pos += 1;
11320 }
11321 }
11322 if matches!(self.peek(), Some('e') | Some('E')) {
11323 self.pos += 1;
11324 if matches!(self.peek(), Some('+') | Some('-')) {
11325 self.pos += 1;
11326 }
11327 if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
11328 return Err(self.err_at("Exponent part is missing a number", self.pos));
11329 }
11330 while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
11331 self.pos += 1;
11332 }
11333 }
11334 let s: String = self.chars[start..self.pos].iter().collect();
11335 s.parse::<f64>()
11336 .map(Value::Float)
11337 .map_err(|_| self.err_at("Unexpected number", start))
11338 }
11339 fn parse_string(&mut self) -> Result<String, String> {
11340 self.pos += 1; // opening quote
11341 let mut out = String::new();
11342 loop {
11343 match self.peek() {
11344 None => return Err(self.err_at("Unterminated string", self.pos)),
11345 Some('"') => {
11346 self.pos += 1;
11347 break;
11348 }
11349 Some('\\') => {
11350 self.pos += 1;
11351 match self.peek() {
11352 Some('n') => out.push('\n'),
11353 Some('t') => out.push('\t'),
11354 Some('r') => out.push('\r'),
11355 Some('"') => out.push('"'),
11356 Some('\\') => out.push('\\'),
11357 Some('/') => out.push('/'),
11358 Some('b') => out.push('\u{08}'),
11359 Some('f') => out.push('\u{0C}'),
11360 Some('u') => {
11361 let n = self.hex4(self.pos + 1)?;
11362 self.pos += 4;
11363 // A high surrogate escape followed by a low one is
11364 // one astral code point; a lone half has no scalar
11365 // value (a Rust `String` cannot hold it) and reads
11366 // as U+FFFD, as the lexer does for a `"\ud800"`
11367 // literal.
11368 if (0xD800..0xDC00).contains(&n)
11369 && self.peek_at(self.pos + 1) == Some('\\')
11370 && self.peek_at(self.pos + 2) == Some('u')
11371 {
11372 if let Ok(lo) = self.hex4(self.pos + 3) {
11373 if (0xDC00..0xE000).contains(&lo) {
11374 let cp = 0x10000 + ((n - 0xD800) << 10) + (lo - 0xDC00);
11375 out.push(char::from_u32(cp).unwrap_or('\u{FFFD}'));
11376 self.pos += 6;
11377 self.pos += 1;
11378 continue;
11379 }
11380 }
11381 }
11382 out.push(char::from_u32(n).unwrap_or('\u{FFFD}'));
11383 }
11384 None => return Err("SyntaxError: Unexpected end of JSON input".into()),
11385 Some(_) => return Err(self.err_at("Bad escaped character", self.pos)),
11386 }
11387 self.pos += 1;
11388 }
11389 // A raw control character is not legal inside a JSON string; it
11390 // has to be escaped. V8 rejects it rather than passing it through.
11391 Some(c) if (c as u32) < 0x20 => {
11392 return Err(self.err_at("Bad control character in string literal", self.pos))
11393 }
11394 Some(c) => {
11395 out.push(c);
11396 self.pos += 1;
11397 }
11398 }
11399 }
11400 Ok(out)
11401 }
11402 fn parse_array(&mut self) -> Result<Value, String> {
11403 self.pos += 1; // [
11404 let mut items = Vec::new();
11405 self.skip_ws();
11406 if self.peek() == Some(']') {
11407 self.pos += 1;
11408 return Ok(with_host(|h| h.new_array(items)));
11409 }
11410 loop {
11411 items.push(self.parse_value()?);
11412 self.skip_ws();
11413 match self.peek() {
11414 Some(',') => {
11415 self.pos += 1;
11416 }
11417 Some(']') => {
11418 self.pos += 1;
11419 break;
11420 }
11421 _ => return Err(self.err_at("Expected ',' or ']' after array element", self.pos)),
11422 }
11423 }
11424 Ok(with_host(|h| h.new_array(items)))
11425 }
11426 fn parse_object(&mut self) -> Result<Value, String> {
11427 self.pos += 1; // {
11428 let mut props: IndexMap<String, Value> = IndexMap::new();
11429 self.skip_ws();
11430 if self.peek() == Some('}') {
11431 self.pos += 1;
11432 return Ok(with_host(|h| h.new_object(props)));
11433 }
11434 loop {
11435 self.skip_ws();
11436 if self.peek() != Some('"') {
11437 // The first key uses the "or '}'" wording (an empty object is
11438 // still legal there); a key after a comma does not. End of input
11439 // reports the same expectation, at the end position.
11440 return Err(if props.is_empty() {
11441 self.err_at("Expected property name or '}'", self.pos)
11442 } else {
11443 self.err_at("Expected double-quoted property name", self.pos)
11444 });
11445 }
11446 let key = self.parse_string()?;
11447 self.skip_ws();
11448 if self.peek() != Some(':') {
11449 return Err(match self.peek() {
11450 None => "SyntaxError: Unexpected end of JSON input".into(),
11451 _ => self.err_at("Expected ':' after property name", self.pos),
11452 });
11453 }
11454 self.pos += 1;
11455 let val = self.parse_value()?;
11456 props.insert(key, val);
11457 self.skip_ws();
11458 match self.peek() {
11459 Some(',') => {
11460 self.pos += 1;
11461 }
11462 Some('}') => {
11463 self.pos += 1;
11464 break;
11465 }
11466 _ => return Err(self.err_at("Expected ',' or '}' after property value", self.pos)),
11467 }
11468 }
11469 Ok(with_host(|h| h.new_object(props)))
11470 }
11471}
11472
11473// ══ type methods (array / string / number) ═══════════════════════════════════
11474
11475fn is_array_method(name: &str) -> bool {
11476 matches!(
11477 name,
11478 "push"
11479 | "pop"
11480 | "shift"
11481 | "unshift"
11482 | "map"
11483 | "filter"
11484 | "forEach"
11485 | "join"
11486 | "slice"
11487 | "indexOf"
11488 | "lastIndexOf"
11489 | "includes"
11490 | "reduce"
11491 | "concat"
11492 | "reverse"
11493 | "sort"
11494 | "find"
11495 | "findIndex"
11496 | "some"
11497 | "every"
11498 | "flat"
11499 | "fill"
11500 | "splice"
11501 | "keys"
11502 | "values"
11503 | "entries"
11504 | "flatMap"
11505 | "at"
11506 | "toString"
11507 | "reduceRight"
11508 | "findLast"
11509 | "findLastIndex"
11510 | "copyWithin"
11511 )
11512}
11513/// Every `String.prototype` method node-js implements.
11514///
11515/// A LIST rather than a `matches!` arm because the same set has to be installed
11516/// on the real `String.prototype` object: a method read off the prototype
11517/// (`String.prototype.trim.call(s)`, the generic-borrowing idiom libraries use)
11518/// found nothing there, so the two views of "which methods exist" would drift
11519/// if they were written twice.
11520pub(crate) const STRING_PROTO_METHODS: &[&str] = &[
11521 "toUpperCase",
11522 "toLowerCase",
11523 "charAt",
11524 "charCodeAt",
11525 "codePointAt",
11526 "indexOf",
11527 "lastIndexOf",
11528 "includes",
11529 "slice",
11530 "substring",
11531 "substr",
11532 "split",
11533 "trim",
11534 "trimStart",
11535 "trimEnd",
11536 // Annex B legacy aliases: the same function objects as `trimStart` and
11537 // `trimEnd` (see `host::builtin_identity`).
11538 "trimLeft",
11539 "trimRight",
11540 "replace",
11541 "replaceAll",
11542 "repeat",
11543 "startsWith",
11544 "endsWith",
11545 "padStart",
11546 "padEnd",
11547 "concat",
11548 "at",
11549 "toString",
11550 "toLocaleString",
11551 "valueOf",
11552 "match",
11553 "matchAll",
11554 "search",
11555 "normalize",
11556 "localeCompare",
11557 "toLocaleUpperCase",
11558 "toLocaleLowerCase",
11559 "isWellFormed",
11560 "toWellFormed",
11561 // Annex B HTML methods (B.2.2.2 CreateHTML).
11562 "anchor",
11563 "big",
11564 "blink",
11565 "bold",
11566 "fixed",
11567 "fontcolor",
11568 "fontsize",
11569 "italics",
11570 "link",
11571 "small",
11572 "strike",
11573 "sub",
11574 "sup",
11575];
11576
11577fn is_string_method(name: &str) -> bool {
11578 STRING_PROTO_METHODS.contains(&name)
11579}
11580
11581/// Every SYMBOL-keyed intrinsic method the generated table lists for `ctor`,
11582/// spelled the way this frontend spells the key (`@@iterator`).
11583///
11584/// A prototype built as a REAL object (`String.prototype`, `URLSearchParams
11585/// .prototype`) installs its methods from a list, and only the string-keyed
11586/// list was walked — so `String.prototype[Symbol.iterator]` read `undefined`
11587/// while `Array.prototype[Symbol.iterator]`, which resolves through the
11588/// `Builtin` namespace and its table gate, answered a function. Derived from
11589/// the table rather than written out, so it cannot name a method node does not
11590/// define nor miss one it does.
11591pub(crate) fn proto_symbol_methods(ctor: &str) -> Vec<&'static str> {
11592 let prefix = format!("@proto:{ctor}:");
11593 crate::arity::BUILTIN_ARITY
11594 .iter()
11595 .filter_map(|(k, _, _)| k.strip_prefix(prefix.as_str()))
11596 .filter(|m| m.starts_with("@@"))
11597 .collect()
11598}
11599
11600/// The builtin constructors whose `.prototype` object is BRANDED — every other
11601/// `<C>.prototype` is an ordinary object and reports `[object Object]`.
11602///
11603/// Measured on node v26.8.1 over every constructor this frontend knows:
11604///
11605/// ```text
11606/// Array/Object/Number/String/Boolean/Function the ES5 legacy slot prototypes
11607/// Symbol/BigInt/Map/Set/WeakMap/WeakSet carry an own @@toStringTag
11608/// Promise/Iterator/ArrayBuffer/DataView "
11609/// WeakRef/FinalizationRegistry/URL "
11610/// URLSearchParams/TextEncoder/TextDecoder "
11611/// Date/RegExp/Error/TypeError/Uint8Array/… [object Object]
11612/// ```
11613///
11614/// The rule this replaces branded EVERY `<C>.prototype` as `C`, so
11615/// `Object.prototype.toString.call(Date.prototype)` read `[object Date]` — and
11616/// a `Date.prototype.toString` call on a plain object named `[object Date]` in
11617/// its own failure message where node names `[object Object]`.
11618pub(crate) const BRANDED_PROTOS: &[&str] = &[
11619 "Array",
11620 "ArrayBuffer",
11621 "BigInt",
11622 "Boolean",
11623 "DataView",
11624 "FinalizationRegistry",
11625 "Function",
11626 "Iterator",
11627 "Map",
11628 "Number",
11629 "Object",
11630 "Promise",
11631 "Set",
11632 "SharedArrayBuffer",
11633 "String",
11634 "Symbol",
11635 "TextDecoder",
11636 "TextEncoder",
11637 "URL",
11638 "URLSearchParams",
11639 "WeakMap",
11640 "WeakRef",
11641 "WeakSet",
11642];
11643
11644/// Whether `v` is a `RegExp` value (drives the regex path of `match`/`replace`/…).
11645/// A user `Symbol.match`/`replace`/`search`/`split`/`matchAll` method on the
11646/// ARGUMENT, which the string method must delegate to (22.1.3.x step 2).
11647///
11648/// `"abc".match(o)` where `o` defines `Symbol.match` calls that method rather
11649/// than coercing `o` to a pattern — the protocol every regexp-like library
11650/// implements. None of the five were consulted, so a custom matcher was
11651/// silently stringified instead.
11652fn symbol_protocol(arg: &Value, sym: &str) -> Option<Value> {
11653 if matches!(arg, Value::Undef) || with_host(|h| h.is_null(arg)) {
11654 return None;
11655 }
11656 let f = get_property(arg, sym).ok()?;
11657 with_host(|h| host::is_callable(h, &f)).then_some(f)
11658}
11659
11660/// 22.1.3.13 / 22.1.3.20 step 2.b: before `matchAll`/`replaceAll` consult the
11661/// argument's protocol method, an argument that `IsRegExp` must carry a `g` in
11662/// its `flags` — read with `[[Get]]`, so a plain object declaring itself a
11663/// regexp through `Symbol.match` is held to it too, and a missing `flags` is
11664/// its own TypeError. Each method has its own V8 wording for both failures.
11665/// `IsArray(v)` (7.2.2): an Array exotic (an `arguments` object is not one),
11666/// or a proxy whose target IsArray — a revoked proxy on the way is a TypeError.
11667pub(crate) fn is_array(v: &Value) -> Result<bool, String> {
11668 let subject = crate::proxy::is_array_subject(v)?;
11669 Ok(with_host(|h| matches!(h.get(&subject), Some(JsObj::Array(_)))) && !is_arguments(&subject))
11670}
11671
11672fn require_global_regexp(method: &str, arg: &Value) -> Result<(), String> {
11673 if with_host(|h| h.is_nullish(arg)) || !is_regexp_arg(arg) {
11674 return Ok(());
11675 }
11676 let flags = get_property(arg, "flags")?;
11677 if with_host(|h| h.is_nullish(&flags)) {
11678 return Err(host::type_error(if method == "replaceAll" {
11679 "String.prototype.replaceAll called on null or undefined"
11680 } else {
11681 "The .flags property of the argument to String.prototype.matchAll cannot be null or undefined"
11682 }));
11683 }
11684 let flags = host::to_string_value(&flags)?;
11685 if !with_host(|h| h.str_of(&flags)).contains('g') {
11686 return Err(host::type_error(&format!(
11687 "String.prototype.{method} called with a non-global RegExp argument"
11688 )));
11689 }
11690 Ok(())
11691}
11692
11693fn is_regexp_arg(v: &Value) -> bool {
11694 // 7.2.8 `IsRegExp` asks `Symbol.match` FIRST, so an object can declare
11695 // itself a regexp — or a real one can disown the label. Only the heap kind
11696 // was checked, so `"a".startsWith({[Symbol.match]: true})` did not throw
11697 // the TypeError the spec requires.
11698 if let Ok(m) = get_property(v, "@@match") {
11699 if !matches!(m, Value::Undef) {
11700 return with_host(|h| h.truthy(&m));
11701 }
11702 }
11703 with_host(|h| h.kind_of(v)) == Some(ObjKind::RegExp)
11704}
11705
11706/// `str.replace(strPattern, fn)` — a function replacer against a literal (string)
11707/// pattern: replace the first (or all) occurrence, calling `fn(match, offset, s)`.
11708/// Calls `repl(matched, offset, subject)` and returns its string. `offset` is a
11709/// UTF-16 index, as in node.
11710fn call_replacer(repl: &Value, pat: &str, offset: usize, s: &str) -> Result<String, String> {
11711 let m = with_host(|h| h.new_str(pat.to_string()));
11712 let str_arg = with_host(|h| h.new_str(s.to_string()));
11713 let r = host::invoke(repl, vec![m, Value::Float(offset as f64), str_arg], None)?;
11714 Ok(with_host(|h| h.str_of(&r)))
11715}
11716
11717fn replace_str_fn(s: &str, pat: &str, repl: &Value, all: bool) -> Result<String, String> {
11718 if pat.is_empty() {
11719 // The empty pattern matches at every code-unit boundary (just index 0
11720 // for `replace`); the unit between two matches is copied through.
11721 let u = crate::utf16::Units::of(s);
11722 let last = if all { u.len() } else { 0 };
11723 let mut out = String::new();
11724 for i in 0..=last {
11725 out.push_str(&call_replacer(repl, pat, i, s)?);
11726 if all && i < u.len() {
11727 out.push_str(&u.unit_str(i).unwrap_or_default());
11728 }
11729 }
11730 if !all {
11731 out.push_str(s);
11732 }
11733 return Ok(out);
11734 }
11735 let mut out = String::new();
11736 let mut rest = s;
11737 let mut base = 0usize;
11738 while let Some(pos) = rest.find(pat) {
11739 out.push_str(&rest[..pos]);
11740 let offset = crate::utf16::index_of_byte(s, base + pos).get();
11741 out.push_str(&call_replacer(repl, pat, offset, s)?);
11742 let consumed = pos + pat.len();
11743 base += consumed;
11744 rest = &rest[consumed..];
11745 if !all {
11746 break;
11747 }
11748 }
11749 out.push_str(rest);
11750 Ok(out)
11751}
11752/// Every `Number.prototype` method node-js implements — a list for the same
11753/// reason [`STRING_PROTO_METHODS`] is one.
11754pub(crate) const NUMBER_PROTO_METHODS: &[&str] = &[
11755 "toFixed",
11756 "toExponential",
11757 "toString",
11758 "toPrecision",
11759 "toLocaleString",
11760 "valueOf",
11761];
11762
11763fn is_number_method(name: &str) -> bool {
11764 NUMBER_PROTO_METHODS.contains(&name)
11765}
11766
11767/// The exotic kinds whose own dispatch table does NOT already reach the
11768/// `Object.prototype` methods, so the inherited ones have to be routed to.
11769///
11770/// An allowlist rather than a catch-all: a primitive receiver also reaches this
11771/// function, and a Number's `toString` is `Number.prototype.toString` — routing
11772/// it to the object form made `(255).toString(16)` report `[object Number]`.
11773fn inherits_object_methods(recv: &Value) -> bool {
11774 matches!(
11775 with_host(|h| h.kind_of(recv)),
11776 Some(
11777 ObjKind::Map
11778 | ObjKind::Set
11779 | ObjKind::Promise
11780 | ObjKind::RegExp
11781 | ObjKind::Generator
11782 | ObjKind::Symbol
11783 | ObjKind::BigInt
11784 | ObjKind::Iter
11785 )
11786 )
11787}
11788
11789/// Whether `recv`'s own prototype defines `name`, shadowing the
11790/// `Object.prototype` method of that name — `RegExp.prototype.toString` does,
11791/// `Map.prototype` does not.
11792fn overrides_object_method(recv: &Value, name: &str) -> bool {
11793 match with_host(|h| h.kind_of(recv)) {
11794 Some(ObjKind::Map) => is_map_method(name),
11795 Some(ObjKind::Set) => is_set_method(name),
11796 Some(ObjKind::RegExp) => crate::regexp::is_regexp_method(name),
11797 // A Symbol has its own `toString`; `valueOf` is the inherited one,
11798 // which returns the receiver — exactly what a symbol needs.
11799 Some(ObjKind::Symbol) => matches!(name, "toString" | "valueOf" | "@@toPrimitive"),
11800 Some(ObjKind::BigInt) => matches!(name, "toString" | "valueOf" | "toLocaleString"),
11801 _ => false,
11802 }
11803}
11804
11805/// Dispatch `recv.name(args)` for the built-in prototype methods.
11806pub fn call_type_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
11807 // An OWN property of an array shadows every inherited method (10.1.8.1
11808 // OrdinaryGet), so `a.join = f; a.join()` calls `f` — and a non-callable
11809 // own value is not a function, whatever the prototype has.
11810 if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Array) && !name.starts_with("@@") {
11811 if let Some(f) = with_host(|h| h.fn_prop(recv, name)) {
11812 if with_host(|h| host::is_callable(h, &f)) {
11813 return host::invoke(&f, args, Some(recv.clone()));
11814 }
11815 return Err(host::type_error(&format!("{name} is not a function")));
11816 }
11817 }
11818 // A USER method on the receiver's prototype chain wins over the builtin of
11819 // the same name — that is how a `class X extends Array` method is reached,
11820 // since the dispatch below goes straight to the builtin table and has no
11821 // entry for it.
11822 //
11823 // Deliberately restricted to a user function: the shared `Object.prototype`
11824 // carries real `@proto:Object:*` thunks, so accepting any callable made a
11825 // bare `map.toString()` resolve to the object form instead of the builtin
11826 // one the exotic is supposed to use.
11827 if let Some(f) = with_host(|h| host::lookup_chain(h, recv, name)) {
11828 if matches!(
11829 with_host(|h| h.kind_of(&f)),
11830 Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc)
11831 ) {
11832 return host::invoke(&f, args, Some(recv.clone()));
11833 }
11834 }
11835 // A method synthesized from the receiver's KIND is unreachable once its
11836 // intrinsic prototype is off the chain. The read already answers
11837 // `undefined` for one; dispatch has its own table and would still have
11838 // called it, so `Object.setPrototypeOf(a, {}); a.join()` returned "1,2"
11839 // while `a.join` was `undefined` — the read and the call disagreeing again,
11840 // in the opposite direction from the monkey-patch case below.
11841 if !own_intrinsic_reachable(recv)
11842 && inherited_method_owner(recv, name).is_none()
11843 && !has_own_for_shadow(recv, name)
11844 && inherited_builtin_static(recv, name).is_none()
11845 && with_host(|h| host::lookup_chain(h, recv, name)).is_none()
11846 {
11847 return Err(host::type_error(&format!("{name} is not a function")));
11848 }
11849 // A method monkey-patched onto the receiver's intrinsic prototype. The READ
11850 // path resolves these, but dispatch goes straight to the builtin table and
11851 // never consults it, so `Array.prototype.last = f; [1].last()` threw "is not
11852 // a function" while `[1].last` WAS `f` — the read and the call disagreeing
11853 // about the same name, on the one path a polyfill actually uses.
11854 if !name.starts_with("@@") && !has_own_for_shadow(recv, name) {
11855 if let Some(f) = inherited_builtin_static(recv, name) {
11856 if with_host(|h| host::is_callable(h, &f)) {
11857 return host::invoke(&f, args, Some(recv.clone()));
11858 }
11859 }
11860 }
11861 // Every object INHERITS the `Object.prototype` methods, and an exotic that
11862 // does not define its own reaches them the same way. Each kind's dispatch
11863 // table below only knows its own methods, so `new Map().toString()`,
11864 // `promise.hasOwnProperty(k)` and `sym.toLocaleString()` all reported "is
11865 // not a function" — `Object.prototype.toString.call(m)` worked while
11866 // `m.toString()` did not.
11867 // The allowlist is the kinds whose own dispatch table below would otherwise
11868 // claim the name. Every OTHER receiver reaches an `Object.prototype` method
11869 // the same way — a function, a class and a bound function included, where
11870 // `f.hasOwnProperty(k)` reported "is not a function" even though the READ
11871 // resolved it. `inherited_method_owner` decides which prototype owns the
11872 // name, so a kind that defines its own still gets its own.
11873 if is_object_builtin_method(name)
11874 && (inherited_method_owner(recv, name) == Some("Object")
11875 || (inherits_object_methods(recv) && !overrides_object_method(recv, name)))
11876 {
11877 // `toString` goes through the branded form (20.1.3.6), which reads
11878 // `Symbol.toStringTag` and falls back to the receiver's own brand —
11879 // `[object Map]`, not the generic stringification.
11880 if name == "toString" {
11881 return proto_method(recv, "Object:toString", args);
11882 }
11883 return object_builtin_method(recv, name, args);
11884 }
11885 // `Object.prototype.valueOf` is inherited by every exotic that does not
11886 // override it (an Array does not), and returns the receiver. Without this
11887 // the `ToPrimitive` probe on `[o] + ''` reached `array_method("valueOf")`
11888 // and threw `valueOf is not a function`.
11889 if name == "valueOf"
11890 && matches!(
11891 with_host(|h| h.kind_of(recv)),
11892 Some(
11893 ObjKind::Array
11894 | ObjKind::Map
11895 | ObjKind::Set
11896 | ObjKind::Generator
11897 | ObjKind::Promise
11898 | ObjKind::Iter
11899 | ObjKind::RegExp
11900 )
11901 )
11902 {
11903 return Ok(recv.clone());
11904 }
11905 // Only the tag is needed to pick the branch — cloning the receiver here made
11906 // every `arr.push(x)` copy the whole array, so a fill loop was O(n^2).
11907 match with_host(|h| h.kind_of(recv)) {
11908 Some(ObjKind::Array) => array_method(recv, name, args),
11909 Some(ObjKind::Str) => {
11910 // `string_method` consumes the text itself, so this clone is the
11911 // payload, not a tag probe.
11912 let s = peek(recv, |o| match o {
11913 JsObj::Str(s) => Some(s.clone()),
11914 _ => None,
11915 })
11916 .unwrap_or_default();
11917 string_method(&s, name, args)
11918 }
11919 Some(ObjKind::Map) => map_method(recv, name, args),
11920 Some(ObjKind::Set) => set_method(recv, name, args),
11921 Some(ObjKind::Generator) if crate::stdlib::iterator::is_helper(name) => {
11922 crate::stdlib::iterator::call(recv, name, &args)
11923 }
11924 Some(ObjKind::Generator) => generator_method(recv, name, args),
11925 Some(ObjKind::Promise) => promise_method(recv, name, args),
11926 Some(ObjKind::Iter) if crate::stdlib::iterator::is_helper(name) => {
11927 crate::stdlib::iterator::call(recv, name, &args)
11928 }
11929 Some(ObjKind::Iter) => iter_method(recv, name, args),
11930 Some(ObjKind::Symbol) => symbol_method(recv, name, args),
11931 Some(ObjKind::BigInt) => {
11932 let b = peek(recv, |o| match o {
11933 JsObj::BigInt(b) => Some(b.clone()),
11934 _ => None,
11935 })
11936 .unwrap_or_default();
11937 bigint_method(&b, name, args)
11938 }
11939 Some(ObjKind::RegExp) => crate::regexp::regexp_method(recv, name, args),
11940 Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc) => {
11941 match function_builtin_method(recv, name, &args)? {
11942 Some(v) => Ok(v),
11943 None => Err(host::type_error(&format!("{name} is not a function"))),
11944 }
11945 }
11946 Some(ObjKind::Object) => {
11947 if let Some(f) = peek(recv, |o| match o {
11948 JsObj::Object(p) => p.get(name).cloned(),
11949 _ => None,
11950 }) {
11951 host::invoke(&f, args, Some(recv.clone()))
11952 } else if name == "hasOwnProperty" {
11953 let k = with_host(|h| h.str_of(&arg0(&args)));
11954 let has = peek(recv, |o| match o {
11955 JsObj::Object(p) => Some(p.contains_key(&k)),
11956 _ => None,
11957 })
11958 .unwrap_or(false);
11959 Ok(Value::Bool(has))
11960 } else if name == "toString" {
11961 Ok(with_host(|h| h.new_str("[object Object]")))
11962 } else {
11963 Err(host::type_error(&format!("{} is not a function", name)))
11964 }
11965 }
11966 _ => {
11967 // Primitive number/bool/string coercions.
11968 if let Value::Float(_) | Value::Int(_) = recv {
11969 return number_method(with_host(|h| h.to_number(recv)), name, args);
11970 }
11971 if let Some(s) = with_host(|h| h.as_str(recv)) {
11972 return string_method(&s, name, args);
11973 }
11974 // `Boolean.prototype` (20.3.3): a boolean is not a heap object here,
11975 // so it reached no branch at all and `true.toString()` threw `is not
11976 // a function`. Its three methods are `toString`, `valueOf`, and the
11977 // inherited `Object.prototype.toLocaleString` — which
11978 // `[1,'a',true].toLocaleString()` invokes per element, so the hole
11979 // was reachable from the array form too.
11980 if let Value::Bool(b) = recv {
11981 return match name {
11982 "toString" | "toLocaleString" => {
11983 Ok(new_s(if *b { "true" } else { "false" }.to_string()))
11984 }
11985 "valueOf" => Ok(Value::Bool(*b)),
11986 _ => Err(host::type_error(&format!("{name} is not a function"))),
11987 };
11988 }
11989 Err(host::type_error(&format!("{} is not a function", name)))
11990 }
11991 }
11992}
11993
11994/// A copy of the whole backing store, for the methods that genuinely consume
11995/// every element (`map`, `filter`, `join`, …). Never call it just to read
11996/// `.len()` — use [`array_len`], or `push`/`unshift` become O(n) per call.
11997/// A LIVE iterator over a `Map` or `Set`.
11998///
11999/// Node's collection iterators see the collection as it is at each step: an
12000/// entry added during iteration IS visited, and one deleted before it is
12001/// reached is NOT. Ours materialized every entry up front, so both were wrong —
12002/// a loop that deletes as it goes still processed the entries it had removed.
12003///
12004/// The cursor is the last key yielded plus the index it was at. On each step
12005/// the key is located again in the CURRENT order: if it is still there the next
12006/// entry follows it, and if it was itself deleted the stored index now names
12007/// the entry that shifted into its place. That reproduces node for the cases
12008/// its own tests turn on — add-during, delete-ahead, delete-self,
12009/// delete-behind, delete-the-rest and clear — without giving `Map` the
12010/// tombstoned entry list node uses internally.
12011fn collection_iterator(coll: &Value, kind: &str) -> Value {
12012 with_host(|h| {
12013 let mut m = IndexMap::new();
12014 m.insert(
12015 "@@native".into(),
12016 h.new_str("CollectionIterator".to_string()),
12017 );
12018 m.insert("@@coll".into(), coll.clone());
12019 m.insert("@@kind".into(), h.new_str(kind.to_string()));
12020 m.insert("@@started".into(), Value::Bool(false));
12021 m.insert("@@lastIdx".into(), Value::Float(0.0));
12022 let it = h.new_object(m);
12023 // `%MapIteratorPrototype%` / `%SetIteratorPrototype%`, not the generic
12024 // native-instance prototype the `@@native` tag would otherwise pick.
12025 h.ensure_native_protos();
12026 let key = if matches!(h.get(coll), Some(JsObj::Map { .. })) {
12027 "MapIterator"
12028 } else {
12029 "SetIterator"
12030 };
12031 if let Some(p) = h.native_proto(key) {
12032 h.set_proto(&it, p);
12033 }
12034 it
12035 })
12036}
12037
12038/// One step of a live collection iterator.
12039pub(crate) fn collection_iterator_next(recv: &Value) -> Result<Value, String> {
12040 let slot = |k: &str| {
12041 with_host(|h| match h.get(recv) {
12042 Some(JsObj::Object(p)) => p.get(k).cloned(),
12043 _ => None,
12044 })
12045 };
12046 let coll = slot("@@coll").unwrap_or(Value::Undef);
12047 let kind = slot("@@kind")
12048 .map(|v| with_host(|h| h.str_of(&v)))
12049 .unwrap_or_default();
12050 let started = slot("@@started").is_some_and(|v| with_host(|h| h.truthy(&v)));
12051 let last_idx = slot("@@lastIdx")
12052 .map(|v| with_host(|h| h.to_number(&v)) as usize)
12053 .unwrap_or(0);
12054 let last_key = slot("@@lastKey");
12055
12056 let next_idx = if !started {
12057 0
12058 } else {
12059 match last_key
12060 .as_ref()
12061 .and_then(|k| with_host(|h| collection_index_of(h, &coll, k)))
12062 {
12063 // Still present: continue after it.
12064 Some(i) => i + 1,
12065 // Deleted since: whatever shifted into its slot is next.
12066 None => last_idx,
12067 }
12068 };
12069 let entry = with_host(|h| collection_entry_at(h, &coll, next_idx));
12070 let Some((k, v)) = entry else {
12071 return Ok(iter_result(Value::Undef, true));
12072 };
12073 with_host(|h| {
12074 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
12075 p.insert("@@started".into(), Value::Bool(true));
12076 p.insert("@@lastIdx".into(), Value::Float(next_idx as f64));
12077 p.insert("@@lastKey".into(), k.clone());
12078 }
12079 });
12080 let out = match kind.as_str() {
12081 "keys" => k,
12082 "values" => v,
12083 _ => with_host(|h| h.new_array(vec![k, v])),
12084 };
12085 Ok(iter_result(out, false))
12086}
12087
12088/// What `util.inspect` shows for a live `Map`/`Set` iterator: its brand
12089/// (`Map Iterator`, `Map Entries`, `Set Iterator`, `Set Entries`) and the
12090/// entries it has still to yield, as `(key, value)` pairs — without advancing
12091/// it. `None` when `v` is not one.
12092pub(crate) fn collection_iterator_view(
12093 h: &host::JsHost,
12094 v: &Value,
12095) -> Option<(&'static str, Vec<(Value, Value)>)> {
12096 let Some(JsObj::Object(p)) = h.get(v) else {
12097 return None;
12098 };
12099 if p.get("@@native").map(|t| h.str_of(t)).as_deref() != Some("CollectionIterator") {
12100 return None;
12101 }
12102 let coll = p.get("@@coll").cloned().unwrap_or(Value::Undef);
12103 let kind = p.get("@@kind").map(|k| h.str_of(k)).unwrap_or_default();
12104 let started = p.get("@@started").is_some_and(|s| h.truthy(s));
12105 let last_idx = p
12106 .get("@@lastIdx")
12107 .map(|n| h.to_number(n) as usize)
12108 .unwrap_or(0);
12109 let is_map = matches!(h.get(&coll), Some(JsObj::Map { .. }));
12110 let brand = match (is_map, kind == "entries") {
12111 (true, true) => "Map Entries",
12112 (true, false) => "Map Iterator",
12113 (false, true) => "Set Entries",
12114 (false, false) => "Set Iterator",
12115 };
12116 // The same cursor rule `collection_iterator_next` steps by.
12117 let mut idx = if !started {
12118 0
12119 } else {
12120 match p
12121 .get("@@lastKey")
12122 .and_then(|k| collection_index_of(h, &coll, k))
12123 {
12124 Some(i) => i + 1,
12125 None => last_idx,
12126 }
12127 };
12128 let mut rest = Vec::new();
12129 while let Some((k, val)) = collection_entry_at(h, &coll, idx) {
12130 rest.push(match kind.as_str() {
12131 "keys" => (k.clone(), k),
12132 "values" => (val.clone(), val),
12133 _ => (k, val),
12134 });
12135 idx += 1;
12136 }
12137 Some((brand, rest))
12138}
12139
12140/// The (key, value) at `idx` in a Map, or (value, value) in a Set.
12141fn collection_entry_at(h: &host::JsHost, coll: &Value, idx: usize) -> Option<(Value, Value)> {
12142 match h.get(coll) {
12143 Some(JsObj::Map { entries, .. }) => entries.get_index(idx).map(|(_, kv)| kv.clone()),
12144 Some(JsObj::Set { entries, .. }) => {
12145 entries.get_index(idx).map(|(_, v)| (v.clone(), v.clone()))
12146 }
12147 _ => None,
12148 }
12149}
12150
12151/// Where `key` currently sits in the collection's order.
12152fn collection_index_of(h: &host::JsHost, coll: &Value, key: &Value) -> Option<usize> {
12153 let mk = host::map_key(h, key);
12154 match h.get(coll) {
12155 Some(JsObj::Map { entries, .. }) => entries.get_index_of(&mk),
12156 Some(JsObj::Set { entries, .. }) => entries.get_index_of(&mk),
12157 _ => None,
12158 }
12159}
12160
12161/// The `thisArg` an iteration method was given, if any.
12162///
12163/// `[1].forEach(fn, thisArg)` binds `thisArg` as the callback's `this`, and so
12164/// do `map`/`filter`/`some`/`every`/`find`/`findIndex`/`findLast`/
12165/// `findLastIndex`/`flatMap`, `Map`/`Set`/TypedArray `forEach`, and
12166/// `Array.from`'s map function. Every one of them was invoking the callback
12167/// with no receiver, so `this` inside it was undefined and the argument did
12168/// nothing.
12169fn this_arg(args: &[Value], idx: usize) -> Option<Value> {
12170 args.get(idx)
12171 .filter(|v| !matches!(v, Value::Undef))
12172 .cloned()
12173}
12174
12175/// The elements of an array, with any INDEX ACCESSOR resolved.
12176///
12177/// `Object.defineProperty(arr, 1, { get })` stores the getter in the accessor
12178/// table, and an array's elements live in a backing vector — so every method
12179/// reading that vector directly (`join`, `map`, `indexOf`, …) saw the stale
12180/// slot and never called the getter, while a plain `arr[1]` read did.
12181///
12182/// An array with no accessors pays one lookup returning an empty list, so the
12183/// ordinary case is unchanged. The getters are invoked OUTSIDE the host borrow,
12184/// since calling one re-enters.
12185/// Walk `recv` the way an `Array.prototype` iteration method does: the LENGTH
12186/// is captured once at entry (LengthOfArrayLike, step 3), but each element is
12187/// read LIVE at its index, and an index that no longer exists is skipped.
12188///
12189/// Snapshotting the whole array instead meant a callback that mutated it was
12190/// not observed: `[1,2,3].forEach(v => a.shift())` visited 1, 2, 3 where node
12191/// visits 1 and 3, and `filter` kept elements the callback had already removed.
12192///
12193/// `f` returns `Some(x)` to stop early with `x`.
12194fn array_walk<T>(
12195 recv: &Value,
12196 mut f: impl FnMut(usize, Value) -> Result<Option<T>, String>,
12197) -> Result<Option<T>, String> {
12198 let len = array_len(recv);
12199 for i in 0..len {
12200 // A HOLE — and an index a shrinking mutation has dropped — is skipped
12201 // without calling the callback.
12202 if index_absent(recv, i) || i >= array_len(recv) {
12203 continue;
12204 }
12205 let v = get_property(recv, &i.to_string())?;
12206 if let Some(out) = f(i, v)? {
12207 return Ok(Some(out));
12208 }
12209 }
12210 Ok(None)
12211}
12212
12213/// `array_walk`'s descending twin, for `reduceRight`/`findLast*`: the same
12214/// capture-length-once, read-each-element-live rule walked from the end. A
12215/// callback that SHRINKS the array is observed by every later step, so the
12216/// indices it drops are skipped rather than served from a stale copy.
12217fn array_walk_rev<T>(
12218 recv: &Value,
12219 from: usize,
12220 mut f: impl FnMut(usize, Value) -> Result<Option<T>, String>,
12221) -> Result<Option<T>, String> {
12222 for i in (0..from).rev() {
12223 if index_absent(recv, i) || i >= array_len(recv) {
12224 continue;
12225 }
12226 let v = get_property(recv, &i.to_string())?;
12227 if let Some(out) = f(i, v)? {
12228 return Ok(Some(out));
12229 }
12230 }
12231 Ok(None)
12232}
12233
12234/// The live read behind `indexOf`/`includes`/`join`: the element at `i`, or
12235/// `undefined` once a mutation has shrunk the array past it.
12236fn array_elem_live(recv: &Value, i: usize) -> Result<Value, String> {
12237 if i >= array_len(recv) {
12238 return Ok(Value::Undef);
12239 }
12240 get_property(recv, &i.to_string())
12241}
12242
12243fn array_items(recv: &Value) -> Vec<Value> {
12244 let mut items = with_host(|h| match h.get(recv) {
12245 Some(JsObj::Array(items)) => items.clone(),
12246 _ => Vec::new(),
12247 });
12248 resolve_index_accessors(recv, &mut items);
12249 items
12250}
12251
12252/// Replace each slot that has an own accessor with what its getter returns.
12253pub(crate) fn resolve_index_accessors_pub(recv: &Value, items: &mut [Value]) {
12254 resolve_index_accessors(recv, items);
12255}
12256
12257/// Returns whether any slot was replaced, which the JSON walk needs: it keeps
12258/// the ORIGINAL array when nothing changed, and the original still holds the
12259/// stale slots.
12260fn resolve_index_accessors(recv: &Value, items: &mut [Value]) -> bool {
12261 let mut indices: Vec<usize> = with_host(|h| h.own_accessor_keys(recv))
12262 .into_iter()
12263 .filter_map(|k| k.parse::<usize>().ok())
12264 .filter(|i| *i < items.len())
12265 .collect();
12266 // An ELIDED index the prototype chain supplies is stale in the backing
12267 // vector too — it holds `undefined` where `[[Get]]` answers the inherited
12268 // value. Spread and `JSON.stringify` both read through here, and both
12269 // rendered the hole rather than what `a[i]` reads.
12270 let inherited: Vec<usize> = with_host(|h| h.hole_indices(recv))
12271 .into_iter()
12272 .filter(|i| *i < items.len() && !indices.contains(i))
12273 .filter(|i| has_property(recv, &i.to_string()).unwrap_or(false))
12274 .collect();
12275 indices.extend(inherited);
12276 let mut replaced = false;
12277 for i in indices {
12278 if let Ok(v) = get_property(recv, &i.to_string()) {
12279 items[i] = v;
12280 replaced = true;
12281 }
12282 }
12283 replaced
12284}
12285
12286/// The ELIDED positions of array `recv` as a membership set. A dense array —
12287/// which is nearly every array — answers with an empty set after a single
12288/// negative hash probe and allocates nothing.
12289///
12290/// The iteration methods split into two groups, and the split is not a matter of
12291/// taste: the ones spec'd through `HasProperty` (`forEach`, `map`, `filter`,
12292/// `some`, `every`, `reduce`, `indexOf`, `flat`, `sort`) SKIP a hole, while the
12293/// ones spec'd through a bare `Get` (`for…of`, spread, `find`, `includes`,
12294/// `join`, `entries`, `Array.from`) see the `undefined` a hole reads back as.
12295fn hole_set(recv: &Value) -> rustc_hash::FxHashSet<usize> {
12296 with_host(|h| h.hole_indices(recv)).into_iter().collect()
12297}
12298
12299/// The indices `recv` genuinely has NO property at — the elided ones the
12300/// prototype chain does not supply either.
12301///
12302/// Every array method tests `HasProperty` before deciding to skip a position
12303/// (23.1.3.x, uniformly), and `HasProperty` walks the chain. Testing elision
12304/// alone made an inherited element invisible to all of them: with
12305/// `Array.prototype[1] = 'p'`, `[1,,3].map(v => v)` produced a hole where node
12306/// produces `'p'`, and `flat`/`concat`/`slice`/`sort`/`indexOf` each dropped
12307/// the same position.
12308///
12309/// `hole_set` remains the elision record itself, which is what `splice` moves
12310/// around — that bookkeeping is about the array's OWN storage and must not
12311/// consult the chain.
12312fn absent_set(recv: &Value) -> rustc_hash::FxHashSet<usize> {
12313 hole_set(recv)
12314 .into_iter()
12315 .filter(|i| !has_property(recv, &i.to_string()).unwrap_or(false))
12316 .collect()
12317}
12318
12319/// The single-index form of [`absent_set`], for the walkers that test one
12320/// position at a time.
12321fn index_absent(recv: &Value, i: usize) -> bool {
12322 with_host(|h| h.is_hole(recv, i)) && !has_property(recv, &i.to_string()).unwrap_or(false)
12323}
12324
12325/// The element count, without copying the elements.
12326fn array_len(recv: &Value) -> usize {
12327 peek(recv, |o| match o {
12328 JsObj::Array(items) => Some(items.len()),
12329 _ => None,
12330 })
12331 .unwrap_or(0)
12332}
12333
12334/// `ArraySpeciesCreate(originalArray, length)` (23.1.3.4) — the constructor an
12335/// array method builds its RESULT with.
12336///
12337/// `map`, `filter`, `slice`, `concat`, `splice`, `flat` and `flatMap` all
12338/// produce an array of the receiver's own species, so on a `class A extends
12339/// Array` the result is an `A`. Every one of them allocated a plain array
12340/// instead, so `A.from([1]).map(x => x) instanceof A` was false.
12341///
12342/// The default `get [Symbol.species]() { return this }` is what makes the
12343/// subclass the species; a class overriding it with `Array` gets a plain array
12344/// back, which is the documented way to opt out.
12345/// Build an array-shaped result through `ctor`, or a plain array when there is
12346/// none to build through.
12347///
12348/// The constructor is called with the LENGTH and the elements written after, as
12349/// 23.1.2.1 and 23.1.3.4 both specify — which is what lets a subclass
12350/// constructor observe the allocation.
12351fn construct_array_like(ctor: Option<Value>, items: Vec<Value>) -> Result<Value, String> {
12352 let Some(ctor) = ctor.filter(|c| {
12353 matches!(
12354 with_host(|h| h.kind_of(c)),
12355 Some(ObjKind::Class) | Some(ObjKind::Func)
12356 )
12357 }) else {
12358 return Ok(with_host(|h| h.new_array(items)));
12359 };
12360 let out = host::construct(&ctor, vec![Value::Float(items.len() as f64)])?;
12361 write_elements(&out, items);
12362 Ok(out)
12363}
12364
12365/// Write `items` into a freshly constructed array-shaped `out`, clearing the
12366/// hole marks the length-only construction left behind.
12367///
12368/// `new A(3)` on `class A extends Array` really does produce three HOLES, and
12369/// the elements written over them stayed marked — so every subclass result of
12370/// `map`/`filter`/`flat` read back as holes: `A.from([1,2,3]).map(x => x * 2)`
12371/// had length 3 and printed `[null,null,null]`, and `0 in` it was false.
12372fn write_elements(out: &Value, items: Vec<Value>) {
12373 with_host(|h| {
12374 h.clear_holes(out);
12375 if let Some(JsObj::Array(dst)) = h.get_mut(out) {
12376 *dst = items;
12377 }
12378 });
12379}
12380
12381/// How a species-built result is written: the length the constructor is called
12382/// with (it differs per method — `map` passes the receiver's, `filter` and
12383/// `concat` 0, `slice` the count) and whether the method then `Set`s `length`
12384/// (`slice`, `splice` and `concat` do; `map`, `filter` and `flat` do not).
12385struct SpeciesWrite {
12386 ctor_len: usize,
12387 set_length: bool,
12388}
12389
12390fn array_species_create(
12391 recv: &Value,
12392 items: Vec<Value>,
12393 how: SpeciesWrite,
12394) -> Result<Value, String> {
12395 let plain = || with_host(|h| h.new_array(items.clone()));
12396 // 23.1.3.4 step 3: only an Array has a species; any other receiver (an
12397 // array-like reached through `.call`) gets a plain Array.
12398 let subject = crate::proxy::is_array_subject(recv).unwrap_or(Value::Undef);
12399 if with_host(|h| h.kind_of(&subject)) != Some(ObjKind::Array) {
12400 return Ok(plain());
12401 }
12402 // Only a subclass instance can have a species of its own: a plain array's
12403 // `constructor` is the `Array` builtin, whose species is `Array`.
12404 // A chain lookup, not `get_property`: an Array receiver resolves its
12405 // properties through the stdlib funnel, which has no `constructor` entry,
12406 // so the read alone reports `undefined` for every subclass instance. A
12407 // Proxy is the exception — it has no property map to walk, and its
12408 // `constructor` comes from the `get` trap, so a proxied subclass array
12409 // produced plain arrays.
12410 let ctor = if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
12411 get_property(recv, "constructor").unwrap_or(Value::Undef)
12412 } else {
12413 with_host(|h| host::lookup_chain(h, recv, "constructor")).unwrap_or(Value::Undef)
12414 };
12415 // `constructor` that is not an object is not consulted for a species; it
12416 // only has to be a constructor if it is to be called (steps 4-7).
12417 if with_host(|h| h.is_nullish(&ctor)) {
12418 return Ok(plain());
12419 }
12420 if !matches!(ctor, Value::Obj(_)) || with_host(|h| host::is_primitive(h, &ctor)) {
12421 return Err(host::type_error(
12422 "object.constructor[Symbol.species] is not a constructor",
12423 ));
12424 }
12425 // `C[@@species]` (23.1.3.4 step 5): a subclass that does not override the
12426 // accessor reads back ITSELF (the `@@species` arm of the class static
12427 // lookup), so an `undefined` or `null` here was written by user code — a
12428 // `static get [Symbol.species]() { return undefined }` — and both mean
12429 // "make a plain Array". A getter that throws propagates.
12430 let species = match get_property(&ctor, "@@species")? {
12431 Value::Undef => return Ok(plain()),
12432 s if with_host(|h| h.is_null(&s)) => return Ok(plain()),
12433 s => s,
12434 };
12435 // Step 7: the species must be a constructor. A builtin namespace object, a
12436 // number or an arrow function is not, and that is a TypeError — not a
12437 // quiet fall back to a plain Array.
12438 if !host::is_constructor(&species) {
12439 return Err(host::type_error(
12440 "object.constructor[Symbol.species] is not a constructor",
12441 ));
12442 }
12443 // The plain `Array` itself builds a plain Array.
12444 let is_array_ctor = matches!(
12445 with_host(|h| h.get(&species).cloned()),
12446 Some(JsObj::Builtin(n)) if n == "Array"
12447 );
12448 if is_array_ctor {
12449 return Ok(plain());
12450 }
12451 let out = host::construct(&species, vec![Value::Float(how.ctor_len as f64)])?;
12452 // The constructor is called with the LENGTH, so the elements are written
12453 // afterwards — which is also what lets a subclass constructor observe the
12454 // allocation, as node's does.
12455 if with_host(|h| matches!(h.get(&out), Some(JsObj::Array(_)))) {
12456 write_elements(&out, items);
12457 return Ok(out);
12458 }
12459 // Any other object is filled the way the spec does it: one
12460 // `CreateDataPropertyOrThrow` per element, then (for the methods that do)
12461 // a `Set(length)`.
12462 let n = items.len();
12463 for (i, v) in items.into_iter().enumerate() {
12464 set_property(&out, &i.to_string(), v)?;
12465 }
12466 if how.set_length {
12467 set_property(&out, "length", Value::Float(n as f64))?;
12468 }
12469 Ok(out)
12470}
12471
12472fn array_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
12473 let r = if ARRAY_MUTATORS.contains(&name) && with_host(|h| h.has_integrity_limits(recv)) {
12474 array_mutate_checked(recv, name, args)
12475 } else {
12476 array_method_on(recv, recv, name, args)
12477 };
12478 // A mutator ran directly on a mapped `arguments` object: its elements are
12479 // aliases of the parameters, so the parameters follow.
12480 if ARRAY_MUTATORS.contains(&name) && is_arguments(recv) {
12481 with_host(|h| h.sync_arguments_to_params(recv));
12482 }
12483 r
12484}
12485
12486/// A mutating `Array.prototype` method on an array that can refuse a write —
12487/// frozen, sealed, non-extensible, or with a property defined read-only,
12488/// non-configurable or as an accessor.
12489///
12490/// The fast implementations edit the element vector directly, which on such
12491/// an array changed it where node throws. These follow the spec text step by
12492/// step instead (23.1.3), each element and `length` written with `Set(…,
12493/// true)` and removed with `DeletePropertyOrThrow`, so the first refused step
12494/// raises the error V8 raises and everything before it has happened.
12495fn array_mutate_checked(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
12496 let args = coerce_numeric_args(ARRAY_METHOD_NUMERIC_ARGS, name, args)?;
12497 host::JsHost::with_forced_strict(|| array_mutate_spec(recv, name, args))
12498}
12499
12500fn array_mutate_spec(o: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
12501 let key = |k: usize| k.to_string();
12502 let get = |k: usize| get_property(o, &key(k));
12503 let has = |k: usize| has_property(o, &key(k));
12504 let set = |k: usize, v: Value| set_property(o, &key(k), v);
12505 // DeletePropertyOrThrow: a refused delete is a TypeError whatever the
12506 // caller's strictness.
12507 let del = |k: usize| match delete_property(o, &key(k))? {
12508 true => Ok(()),
12509 false => Err(refused_delete_error(o, &key(k))),
12510 };
12511 let set_len = |n: usize| set_property(o, "length", Value::Float(n as f64));
12512 // `Set(O, to, Get(O, from))` when `from` is present, else delete `to`:
12513 // the move every shifting method is made of.
12514 let move_elem = |from: usize, to: usize| -> Result<(), String> {
12515 if has(from)? {
12516 let v = get(from)?;
12517 set(to, v)
12518 } else {
12519 del(to)
12520 }
12521 };
12522 let len = array_len(o);
12523 let num = |i: usize| match args.get(i) {
12524 None | Some(Value::Undef) => None,
12525 Some(v) => Some(with_host(|h| h.to_number(v))),
12526 };
12527 // A relative index argument (`ToIntegerOrInfinity`, negative from the
12528 // end), clamped into `0..=len`.
12529 let relative = |n: f64| -> usize {
12530 let n = if n.is_nan() { 0.0 } else { n.trunc() };
12531 if n < 0.0 {
12532 (len as f64 + n).max(0.0) as usize
12533 } else {
12534 n.min(len as f64) as usize
12535 }
12536 };
12537 match name {
12538 // 23.1.3.23
12539 "push" => {
12540 let mut n = len;
12541 for v in args {
12542 set(n, v)?;
12543 n += 1;
12544 }
12545 set_len(n)?;
12546 Ok(Value::Float(n as f64))
12547 }
12548 // 23.1.3.22
12549 "pop" => {
12550 if len == 0 {
12551 set_len(0)?;
12552 return Ok(Value::Undef);
12553 }
12554 let element = get(len - 1)?;
12555 del(len - 1)?;
12556 set_len(len - 1)?;
12557 Ok(element)
12558 }
12559 // 23.1.3.27
12560 "shift" => {
12561 if len == 0 {
12562 set_len(0)?;
12563 return Ok(Value::Undef);
12564 }
12565 let first = get(0)?;
12566 for k in 1..len {
12567 move_elem(k, k - 1)?;
12568 }
12569 del(len - 1)?;
12570 set_len(len - 1)?;
12571 Ok(first)
12572 }
12573 // 23.1.3.37
12574 "unshift" => {
12575 let count = args.len();
12576 if count > 0 {
12577 for k in (1..=len).rev() {
12578 move_elem(k - 1, k + count - 1)?;
12579 }
12580 for (j, v) in args.into_iter().enumerate() {
12581 set(j, v)?;
12582 }
12583 }
12584 set_len(len + count)?;
12585 Ok(Value::Float((len + count) as f64))
12586 }
12587 // 23.1.3.26
12588 "reverse" => {
12589 for lower in 0..len / 2 {
12590 let upper = len - lower - 1;
12591 let lower_v = if has(lower)? { Some(get(lower)?) } else { None };
12592 let upper_v = if has(upper)? { Some(get(upper)?) } else { None };
12593 match (lower_v, upper_v) {
12594 (Some(l), Some(u)) => {
12595 set(lower, u)?;
12596 set(upper, l)?;
12597 }
12598 (None, Some(u)) => {
12599 set(lower, u)?;
12600 del(upper)?;
12601 }
12602 (Some(l), None) => {
12603 del(lower)?;
12604 set(upper, l)?;
12605 }
12606 (None, None) => {}
12607 }
12608 }
12609 Ok(o.clone())
12610 }
12611 // 23.1.3.7
12612 "fill" => {
12613 let value = args.first().cloned().unwrap_or(Value::Undef);
12614 let start = num(1).map_or(0, relative);
12615 let end = num(2).map_or(len, relative);
12616 for k in start..end.max(start) {
12617 set(k, value.clone())?;
12618 }
12619 Ok(o.clone())
12620 }
12621 // 23.1.3.4
12622 "copyWithin" => {
12623 let to = num(0).map_or(0, relative);
12624 let from = num(1).map_or(0, relative);
12625 let fin = num(2).map_or(len, relative);
12626 let count = fin.saturating_sub(from).min(len - to);
12627 if from < to && to < from + count {
12628 for i in (0..count).rev() {
12629 move_elem(from + i, to + i)?;
12630 }
12631 } else {
12632 for i in 0..count {
12633 move_elem(from + i, to + i)?;
12634 }
12635 }
12636 Ok(o.clone())
12637 }
12638 // 23.1.3.30: the present elements are sorted first, then written back
12639 // from index 0, and the indices past them deleted.
12640 "sort" => {
12641 let mut present = Vec::new();
12642 for k in 0..len {
12643 if has(k)? {
12644 present.push(get(k)?);
12645 }
12646 }
12647 let count = present.len();
12648 let tmp = with_host(|h| h.new_array(present));
12649 array_method_on(&tmp, o, "sort", args)?;
12650 let sorted = with_host(|h| match h.get(&tmp) {
12651 Some(JsObj::Array(items)) => items.clone(),
12652 _ => Vec::new(),
12653 });
12654 for (j, v) in sorted.into_iter().enumerate() {
12655 set(j, v)?;
12656 }
12657 for j in count..len {
12658 del(j)?;
12659 }
12660 Ok(o.clone())
12661 }
12662 // 23.1.3.31
12663 "splice" => {
12664 let start = num(0).map_or(0, relative);
12665 let delete = match args.len() {
12666 0 => 0,
12667 1 => len - start,
12668 _ => {
12669 let d = num(1).unwrap_or(0.0);
12670 let d = if d.is_nan() { 0.0 } else { d.trunc() };
12671 (d.max(0.0) as usize).min(len - start)
12672 }
12673 };
12674 let items: Vec<Value> = args.into_iter().skip(2).collect();
12675 let mut removed = Vec::with_capacity(delete);
12676 let mut holes = rustc_hash::FxHashSet::default();
12677 for k in 0..delete {
12678 if has(start + k)? {
12679 removed.push(get(start + k)?);
12680 } else {
12681 holes.insert(k);
12682 removed.push(Value::Undef);
12683 }
12684 }
12685 let out = array_species_create(
12686 o,
12687 removed,
12688 SpeciesWrite {
12689 ctor_len: delete,
12690 set_length: true,
12691 },
12692 )?;
12693 with_host(|h| h.install_holes(&out, holes));
12694 let count = items.len();
12695 if count < delete {
12696 for k in start..len - delete {
12697 move_elem(k + delete, k + count)?;
12698 }
12699 for k in (len - delete + count..len).rev() {
12700 del(k)?;
12701 }
12702 } else if count > delete {
12703 for k in (start + 1..=len - delete).rev() {
12704 move_elem(k + delete - 1, k + count - 1)?;
12705 }
12706 }
12707 for (i, v) in items.into_iter().enumerate() {
12708 set(start + i, v)?;
12709 }
12710 set_len(len - delete + count)?;
12711 Ok(out)
12712 }
12713 _ => array_method_on(o, o, name, args),
12714 }
12715}
12716
12717/// The `Array.prototype` methods that WRITE to their receiver, and so need the
12718/// generic path to copy the result back onto the array-like.
12719const ARRAY_MUTATORS: &[&str] = &[
12720 "push",
12721 "pop",
12722 "shift",
12723 "unshift",
12724 "splice",
12725 "sort",
12726 "reverse",
12727 "fill",
12728 "copyWithin",
12729];
12730
12731/// The non-mutating `Array.prototype` methods whose spec text reads each index
12732/// with `Get` alone (no `HasProperty` step), so a hole is observed as a plain
12733/// `undefined` and a Proxy `has` trap must not fire while the receiver is read.
12734const ARRAY_GET_ONLY: &[&str] = &[
12735 "join",
12736 "toLocaleString",
12737 "includes",
12738 "at",
12739 "find",
12740 "findIndex",
12741 "findLast",
12742 "findLastIndex",
12743 "toReversed",
12744 "toSorted",
12745 "with",
12746];
12747
12748/// Run `Array.prototype.<method>` against an array-LIKE (`{0: 'a', length: 1}`,
12749/// a DOM-ish collection, `arguments`).
12750///
12751/// 23.1.3 defines every one of these over `LengthOfArrayLike(O)` and `Get(O, k)`
12752/// rather than over an Array's element vector, so the receiver only has to have
12753/// a `length`. The elements are read out into a temporary Array, the ordinary
12754/// implementation runs on that, and a MUTATING method writes the result back —
12755/// which keeps one implementation of each method rather than a second, generic
12756/// one that could drift from it.
12757///
12758/// An index the receiver does not own is a HOLE in the temporary, so the
12759/// methods that skip holes skip it here too, exactly as `HasProperty` makes them.
12760fn array_generic(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
12761 // A string has a read-only `length` and read-only indices, so every
12762 // mutator's `Set` fails — V8 names the wrapper `[object String]`.
12763 if ARRAY_MUTATORS.contains(&method) && with_host(|h| h.as_str(recv)).is_some() {
12764 return Err(host::type_error(
12765 "Cannot assign to read only property 'length' of object '[object String]'",
12766 ));
12767 }
12768 // `LengthOfArrayLike` (7.3.18) is `ToLength(Get(O, "length"))`: truncate
12769 // toward zero, NaN and negatives are 0, capped at 2^53-1. (`length: 1.9` is
12770 // 1; the array-length setter's range check is not this conversion.)
12771 let len = {
12772 let l = get_property(recv, "length")?;
12773 let n = host::to_number_value(&l)?;
12774 if n.is_nan() || n <= 0.0 {
12775 0
12776 } else {
12777 n.trunc().min(9_007_199_254_740_991.0) as usize
12778 }
12779 };
12780 // A STRING receiver owns every index of its length; `has_property` answers
12781 // for objects and reports none of them, which made `[].map.call('abc', f)`
12782 // an array of three holes.
12783 let dense = with_host(|h| h.as_str(recv)).is_some() || ARRAY_GET_ONLY.contains(&method);
12784 let mut items = Vec::with_capacity(len);
12785 let mut holes: rustc_hash::FxHashSet<usize> = rustc_hash::FxHashSet::default();
12786 for i in 0..len {
12787 let k = i.to_string();
12788 if dense || has_property(recv, &k)? {
12789 items.push(get_property(recv, &k)?);
12790 } else {
12791 holes.insert(i);
12792 items.push(Value::Undef);
12793 }
12794 }
12795 let tmp = with_host(|h| {
12796 let a = h.new_array(items);
12797 h.install_holes(&a, holes);
12798 a
12799 });
12800 let out = array_method_on(&tmp, recv, method, args)?;
12801 if ARRAY_MUTATORS.contains(&method) {
12802 let result = with_host(|h| match h.get(&tmp) {
12803 Some(JsObj::Array(items)) => items.clone(),
12804 _ => Vec::new(),
12805 });
12806 let result_holes = with_host(|h| h.hole_indices(&tmp));
12807 // Each mutator `Set`s (or `Delete`s, for a hole) the indices it touched
12808 // and then `length`, all with `throw = true`; indices past the new
12809 // length are deleted. The holes the temporary kept stay absent on the
12810 // receiver rather than becoming `undefined` properties.
12811 host::JsHost::with_forced_strict(|| -> Result<(), String> {
12812 for (i, v) in result.iter().enumerate() {
12813 if result_holes.contains(&i) {
12814 delete_property(recv, &i.to_string())?;
12815 } else {
12816 set_property(recv, &i.to_string(), v.clone())?;
12817 }
12818 }
12819 // Only the methods that resize touch `length`: `reverse`, `sort`,
12820 // `fill` and `copyWithin` leave it exactly as the receiver had it.
12821 if !matches!(method, "push" | "pop" | "shift" | "unshift" | "splice") {
12822 return Ok(());
12823 }
12824 for i in result.len()..len {
12825 delete_property(recv, &i.to_string())?;
12826 }
12827 set_property(recv, "length", Value::Float(result.len() as f64))
12828 })?;
12829 }
12830 Ok(out)
12831}
12832
12833/// `Array.prototype.<name>` on `recv`.
12834///
12835/// `this_value` is what a callback receives as its third argument and what a
12836/// mutating method returns — the same object as `recv` for an ordinary array
12837/// call, but the ORIGINAL array-like when `array_generic` runs a method against
12838/// a temporary copy (`Array.prototype.slice.call(arguments)`).
12839fn array_method_on(
12840 recv: &Value,
12841 this_value: &Value,
12842 name: &str,
12843 args: Vec<Value>,
12844) -> Result<Value, String> {
12845 let args = coerce_numeric_args(ARRAY_METHOD_NUMERIC_ARGS, name, args)?;
12846 match name {
12847 "push" => {
12848 // A receiver that could refuse the appends or the `length` write
12849 // runs the spec steps instead (`array_mutate_checked`).
12850 // `push` returns the new length; take it from the same mutable
12851 // borrow rather than copying the array back out to count it.
12852 let len = with_host(|h| {
12853 if let Some(JsObj::Array(items)) = h.get_mut(recv) {
12854 items.extend(args.iter().cloned());
12855 items.len()
12856 } else {
12857 0
12858 }
12859 });
12860 Ok(Value::Float(len as f64))
12861 }
12862 "pop" => Ok(with_host(|h| {
12863 let popped = if let Some(JsObj::Array(items)) = h.get_mut(recv) {
12864 items.pop().unwrap_or(Value::Undef)
12865 } else {
12866 Value::Undef
12867 };
12868 let len = match h.get(recv) {
12869 Some(JsObj::Array(items)) => items.len(),
12870 _ => 0,
12871 };
12872 h.truncate_holes(recv, len);
12873 popped
12874 })),
12875 "shift" => Ok(with_host(|h| {
12876 let shifted = if let Some(JsObj::Array(items)) = h.get_mut(recv) {
12877 if items.is_empty() {
12878 Value::Undef
12879 } else {
12880 items.remove(0)
12881 }
12882 } else {
12883 Value::Undef
12884 };
12885 h.remap_holes(recv, |i| i.checked_sub(1));
12886 shifted
12887 })),
12888 "unshift" => {
12889 with_host(|h| {
12890 if let Some(JsObj::Array(items)) = h.get_mut(recv) {
12891 for (i, a) in args.iter().enumerate() {
12892 items.insert(i, a.clone());
12893 }
12894 }
12895 let n = args.len();
12896 h.remap_holes(recv, |i| Some(i + n));
12897 });
12898 Ok(Value::Float(array_len(recv) as f64))
12899 }
12900 "join" => {
12901 let sep = if args.is_empty() || matches!(args[0], Value::Undef) {
12902 ",".to_string()
12903 } else {
12904 arg_to_string(&args, 0)?
12905 };
12906 join_array(recv, &sep)
12907 }
12908 // `Array.prototype.toLocaleString` (23.1.3.32): comma-join the elements'
12909 // OWN `toLocaleString` results, with `null`/`undefined` contributing the
12910 // empty string. It threw `is not a function` — the whole method was
12911 // missing — so `[1234.5, 'x'].toLocaleString()` was unreachable.
12912 "toLocaleString" => {
12913 // Shares `join`'s JoinStack: measured on node v26.7.0, `h=[1]`
12914 // `h.push(h)` makes `h.toLocaleString()` `"1,"`, not a stack overflow.
12915 if !host::join_stack_push(recv) {
12916 return Ok(with_host(|h| h.new_str(String::new())));
12917 }
12918 let items = array_items(recv);
12919 let mut parts: Vec<String> = Vec::with_capacity(items.len());
12920 for it in &items {
12921 if with_host(|h| h.is_nullish(it)) {
12922 parts.push(String::new());
12923 continue;
12924 }
12925 let v = match host::call_method(it, "toLocaleString", Vec::new()) {
12926 Ok(v) => v,
12927 Err(e) => {
12928 host::join_stack_pop();
12929 return Err(e);
12930 }
12931 };
12932 parts.push(with_host(|h| h.str_of(&v)));
12933 }
12934 host::join_stack_pop();
12935 Ok(with_host(|h| h.new_str(parts.join(","))))
12936 }
12937 // `indexOf`/`lastIndexOf` are spec'd through `HasProperty`, so a hole is
12938 // never a match: `[1,,3].indexOf(undefined)` is `-1`, while the
12939 // `Get`-based `includes` reports `true` for the same array.
12940 "indexOf" => {
12941 let target = arg0(&args);
12942 let len = array_len(recv);
12943 let start = search_start(arg_num(&args, 1), len);
12944 let mut idx = None;
12945 for i in start..len {
12946 // 23.1.3.17 steps 8a-8b: HasProperty first, so a hole — and an
12947 // index a mutation has since dropped — is skipped, not compared.
12948 if index_absent(recv, i) || i >= array_len(recv) {
12949 continue;
12950 }
12951 let x = get_property(recv, &i.to_string())?;
12952 if with_host(|h| h.strict_eq(&x, &target)) {
12953 idx = Some(i);
12954 break;
12955 }
12956 }
12957 Ok(Value::Float(idx.map(|i| i as f64).unwrap_or(-1.0)))
12958 }
12959 "lastIndexOf" => {
12960 let items = array_items(recv);
12961 let holes = absent_set(recv);
12962 let target = arg0(&args);
12963 let from = (args.len() > 1).then(|| arg_num(&args, 1));
12964 let idx = match search_start_last(from, items.len()) {
12965 None => None,
12966 Some(start) => with_host(|h| {
12967 items[..=start]
12968 .iter()
12969 .enumerate()
12970 .rev()
12971 .find(|(i, x)| !holes.contains(i) && h.strict_eq(x, &target))
12972 .map(|(i, _)| i)
12973 }),
12974 };
12975 Ok(Value::Float(idx.map(|i| i as f64).unwrap_or(-1.0)))
12976 }
12977 "includes" => {
12978 // Array.includes uses SameValueZero: unlike `===`, NaN matches NaN.
12979 // Unlike `indexOf` it has no HasProperty step (23.1.3.16 step 5b), so
12980 // a hole reads as `undefined` and `[,].includes(undefined)` is true.
12981 let target = arg0(&args);
12982 let tnan = matches!(target, Value::Float(f) if f.is_nan());
12983 let len = array_len(recv);
12984 let start = search_start(arg_num(&args, 1), len);
12985 let mut found = false;
12986 for i in start..len {
12987 let x = array_elem_live(recv, i)?;
12988 if (tnan && matches!(x, Value::Float(f) if f.is_nan()))
12989 || with_host(|h| h.strict_eq(&x, &target))
12990 {
12991 found = true;
12992 break;
12993 }
12994 }
12995 Ok(Value::Bool(found))
12996 }
12997 "slice" => {
12998 let items = array_items(recv);
12999 let (lo, hi) = slice_bounds(&args, items.len());
13000 let out = array_species_create(
13001 this_value,
13002 items[lo..hi].to_vec(),
13003 SpeciesWrite {
13004 ctor_len: hi - lo,
13005 set_length: true,
13006 },
13007 )?;
13008 with_host(|h| h.copy_holes(recv, &out, |i| (i >= lo && i < hi).then(|| i - lo)));
13009 Ok(out)
13010 }
13011 "concat" => {
13012 // `Symbol.isConcatSpreadable` (23.1.3.1) decides whether a value
13013 // is spread, overriding `IsArray` in BOTH directions: a plain
13014 // array-like opts IN, and an array opts OUT.
13015 let spreadable = |a: &Value| -> Result<bool, String> {
13016 let flag = get_property(a, "@@isConcatSpreadable")?;
13017 if matches!(flag, Value::Undef) {
13018 is_array(a)
13019 } else {
13020 Ok(with_host(|h| h.truthy(&flag)))
13021 }
13022 };
13023 // Step 5 iterates `« O » ++ items`, so the receiver takes the same
13024 // test: a non-spreadable `this` (`concat.call("ab", 1)`) is ONE
13025 // element, its `ToObject` box, not the characters `array_generic`
13026 // read out of it. A hole in a spread receiver or argument stays a
13027 // hole in the result, at its shifted position.
13028 let (mut out, mut holes) = if spreadable(this_value)? {
13029 (array_items(recv), absent_set(recv))
13030 } else {
13031 (vec![to_object(this_value)], Default::default())
13032 };
13033 let mut sources: Vec<(Value, usize)> = Vec::new();
13034 for a in &args {
13035 if !spreadable(a)? {
13036 out.push(a.clone());
13037 continue;
13038 }
13039 match with_host(|h| h.get(a).cloned()) {
13040 // Read off the backing vector rather than through
13041 // `array_items`, so the resolve that does for the receiver
13042 // has to be done here too: 23.1.3.1 step 5.c.iv is a
13043 // `[[Get]]`, and an index with a getter — or an elided one
13044 // the chain supplies — is stale in that vector.
13045 Some(JsObj::Array(mut items)) => {
13046 resolve_index_accessors(a, &mut items);
13047 sources.push((a.clone(), out.len()));
13048 out.extend(items);
13049 }
13050 // An opted-in array-LIKE (or an array proxy) spreads by its
13051 // `length` and index properties rather than by a backing
13052 // vector it has none of: 23.1.3.1 step 5.c.iv asks
13053 // `HasProperty` per index and `Get`s only the present ones,
13054 // so a missing index stays a hole.
13055 _ => {
13056 let len = get_property(a, "length")?;
13057 let n = with_host(|h| h.to_number(&len));
13058 let n = if n.is_finite() {
13059 n.max(0.0) as usize
13060 } else {
13061 0
13062 };
13063 for i in 0..n {
13064 let k = i.to_string();
13065 if has_property(a, &k)? {
13066 out.push(get_property(a, &k)?);
13067 } else {
13068 holes.insert(out.len());
13069 out.push(Value::Undef);
13070 }
13071 }
13072 }
13073 }
13074 }
13075
13076 for (src, base) in sources {
13077 holes.extend(
13078 with_host(|h| h.hole_indices(&src))
13079 .into_iter()
13080 .map(|i| i + base),
13081 );
13082 }
13083 let arr = array_species_create(
13084 this_value,
13085 out,
13086 SpeciesWrite {
13087 ctor_len: 0,
13088 set_length: true,
13089 },
13090 )?;
13091 with_host(|h| h.install_holes(&arr, holes));
13092 Ok(arr)
13093 }
13094 "reverse" => {
13095 let len = array_len(recv);
13096 with_host(|h| {
13097 if let Some(JsObj::Array(items)) = h.get_mut(recv) {
13098 items.reverse();
13099 }
13100 h.remap_holes(recv, |i| Some(len - 1 - i));
13101 });
13102 Ok(this_value.clone())
13103 }
13104 "fill" => {
13105 // fill(value[, start[, end]]) — negative indices count from the end.
13106 let val = arg0(&args);
13107 let len = array_len(recv) as i64;
13108 let norm =
13109 |v: i64| -> usize { (if v < 0 { (len + v).max(0) } else { v.min(len) }) as usize };
13110 let start = if args.len() >= 2 {
13111 norm(arg_num(&args, 1) as i64)
13112 } else {
13113 0
13114 };
13115 let end = if args.len() >= 3 {
13116 norm(arg_num(&args, 2) as i64)
13117 } else {
13118 len as usize
13119 };
13120 with_host(|h| {
13121 if let Some(JsObj::Array(items)) = h.get_mut(recv) {
13122 for it in items.iter_mut().take(end).skip(start) {
13123 *it = val.clone();
13124 }
13125 }
13126 // Every filled position now holds a real value.
13127 h.remap_holes(recv, |i| (i < start || i >= end).then_some(i));
13128 });
13129 Ok(this_value.clone())
13130 }
13131 "copyWithin" => {
13132 // copyWithin(target, start[, end]) — copy a slice within the array.
13133 let items = array_items(recv);
13134 let len = items.len() as i64;
13135 let norm =
13136 |v: i64| -> usize { (if v < 0 { (len + v).max(0) } else { v.min(len) }) as usize };
13137 let target = norm(arg_num(&args, 0) as i64);
13138 let start = if args.len() >= 2 {
13139 norm(arg_num(&args, 1) as i64)
13140 } else {
13141 0
13142 };
13143 let end = if args.len() >= 3 {
13144 norm(arg_num(&args, 2) as i64)
13145 } else {
13146 len as usize
13147 };
13148 let slice: Vec<Value> = items[start..end.max(start)].to_vec();
13149 let copied = slice.len();
13150 // A copied position takes its SOURCE's hole-ness (10.4.2 copyWithin
13151 // deletes the target when the source has no such property);
13152 // everything outside the written range keeps its own.
13153 let src_holes = absent_set(recv);
13154 with_host(|h| {
13155 if let Some(JsObj::Array(a)) = h.get_mut(recv) {
13156 for (k, v) in slice.into_iter().enumerate() {
13157 if target + k < a.len() {
13158 a[target + k] = v;
13159 }
13160 }
13161 }
13162 let len = len as usize;
13163 let mut holes: rustc_hash::FxHashSet<usize> = src_holes
13164 .iter()
13165 .copied()
13166 .filter(|i| *i < target || *i >= (target + copied).min(len))
13167 .collect();
13168 for k in 0..copied {
13169 if target + k < len && src_holes.contains(&(start + k)) {
13170 holes.insert(target + k);
13171 }
13172 }
13173 h.install_holes(recv, holes);
13174 });
13175 Ok(this_value.clone())
13176 }
13177 "at" => {
13178 let items = array_items(recv);
13179 let mut i = arg_num(&args, 0) as i64;
13180 if i < 0 {
13181 i += items.len() as i64;
13182 }
13183 Ok(if i >= 0 && (i as usize) < items.len() {
13184 items[i as usize].clone()
13185 } else {
13186 Value::Undef
13187 })
13188 }
13189 // 23.1.3.21: the callback runs only where `HasProperty` holds, and the
13190 // result array is created with the SAME holes — `[1,,3].map(f)` calls `f`
13191 // twice and yields `[2, <1 empty item>, 6]`.
13192 "map" => {
13193 let holes = absent_set(recv);
13194 let cb = arg0(&args);
13195 // The result keeps the source's LENGTH, so a skipped index still
13196 // occupies a slot; `array_walk` only tells us which ones ran.
13197 let mut out = vec![Value::Undef; array_len(recv)];
13198 array_walk(recv, |i, it| {
13199 let v = host::invoke(
13200 &cb,
13201 vec![it, Value::Float(i as f64), this_value.clone()],
13202 this_arg(&args, 1),
13203 )?;
13204 if i < out.len() {
13205 out[i] = v;
13206 }
13207 Ok(None::<()>)
13208 })?;
13209 let arr = {
13210 let n = out.len();
13211 array_species_create(
13212 this_value,
13213 out,
13214 SpeciesWrite {
13215 ctor_len: n,
13216 set_length: false,
13217 },
13218 )?
13219 };
13220 with_host(|h| h.install_holes(&arr, holes));
13221 Ok(arr)
13222 }
13223 "flatMap" => {
13224 let cb = arg0(&args);
13225 let thisarg = this_arg(&args, 1);
13226 let mut out = Vec::new();
13227 array_walk(recv, |i, v| {
13228 let r = host::invoke(
13229 &cb,
13230 vec![v, Value::Float(i as f64), this_value.clone()],
13231 thisarg.clone(),
13232 )?;
13233 match with_host(|h| h.get(&r).cloned()) {
13234 Some(JsObj::Array(inner)) => out.extend(inner),
13235 _ => out.push(r),
13236 }
13237 Ok(None::<()>)
13238 })?;
13239 array_species_create(
13240 this_value,
13241 out,
13242 SpeciesWrite {
13243 ctor_len: 0,
13244 set_length: false,
13245 },
13246 )
13247 }
13248 "filter" => {
13249 let cb = arg0(&args);
13250 let mut out = Vec::new();
13251 array_walk(recv, |i, it| {
13252 let keep = host::invoke(
13253 &cb,
13254 vec![it.clone(), Value::Float(i as f64), this_value.clone()],
13255 this_arg(&args, 1),
13256 )?;
13257 if with_host(|h| h.truthy(&keep)) {
13258 out.push(it);
13259 }
13260 Ok(None::<()>)
13261 })?;
13262 array_species_create(
13263 this_value,
13264 out,
13265 SpeciesWrite {
13266 ctor_len: 0,
13267 set_length: false,
13268 },
13269 )
13270 }
13271 "forEach" => {
13272 let cb = arg0(&args);
13273 array_walk(recv, |i, it| {
13274 host::invoke(
13275 &cb,
13276 vec![it, Value::Float(i as f64), this_value.clone()],
13277 this_arg(&args, 1),
13278 )?;
13279 Ok(None::<()>)
13280 })?;
13281 Ok(Value::Undef)
13282 }
13283 "find" => {
13284 let items = array_items(recv);
13285 let cb = arg0(&args);
13286 for (i, it) in items.iter().enumerate() {
13287 let m = host::invoke(
13288 &cb,
13289 vec![it.clone(), Value::Float(i as f64), this_value.clone()],
13290 this_arg(&args, 1),
13291 )?;
13292 if with_host(|h| h.truthy(&m)) {
13293 return Ok(it.clone());
13294 }
13295 }
13296 Ok(Value::Undef)
13297 }
13298 "findIndex" => {
13299 let items = array_items(recv);
13300 let cb = arg0(&args);
13301 for (i, it) in items.iter().enumerate() {
13302 let m = host::invoke(
13303 &cb,
13304 vec![it.clone(), Value::Float(i as f64), this_value.clone()],
13305 this_arg(&args, 1),
13306 )?;
13307 if with_host(|h| h.truthy(&m)) {
13308 return Ok(Value::Float(i as f64));
13309 }
13310 }
13311 Ok(Value::Float(-1.0))
13312 }
13313 "some" => {
13314 let cb = arg0(&args);
13315 let thisarg = this_arg(&args, 1);
13316 let hit = array_walk(recv, |i, v| {
13317 let m = host::invoke(
13318 &cb,
13319 vec![v, Value::Float(i as f64), this_value.clone()],
13320 thisarg.clone(),
13321 )?;
13322 Ok(with_host(|h| h.truthy(&m)).then_some(()))
13323 })?;
13324 Ok(Value::Bool(hit.is_some()))
13325 }
13326 "every" => {
13327 let cb = arg0(&args);
13328 let failed = array_walk(recv, |i, it| {
13329 let m = host::invoke(
13330 &cb,
13331 vec![it, Value::Float(i as f64), this_value.clone()],
13332 this_arg(&args, 1),
13333 )?;
13334 Ok((!with_host(|h| h.truthy(&m))).then_some(()))
13335 })?;
13336 Ok(Value::Bool(failed.is_none()))
13337 }
13338 "reduce" => {
13339 let items = array_items(recv);
13340 let holes = absent_set(recv);
13341 let cb = arg0(&args);
13342 let acc;
13343 let mut start = 0;
13344 if args.len() >= 2 {
13345 acc = args[1].clone();
13346 } else {
13347 // With no seed the accumulator is the first PRESENT element, so a
13348 // leading run of holes is skipped rather than seeding `undefined`.
13349 match (0..items.len()).find(|i| !holes.contains(i)) {
13350 Some(i) => {
13351 acc = items[i].clone();
13352 start = i + 1;
13353 }
13354 None => {
13355 return Err(host::type_error(
13356 "Reduce of empty array with no initial value",
13357 ))
13358 }
13359 }
13360 }
13361 // Each element is read LIVE at its index, so a callback that
13362 // shrinks the array is observed — the tail is skipped rather than
13363 // folded from a stale snapshot.
13364 let mut cur = acc;
13365 array_walk(recv, |i, it| {
13366 if i < start {
13367 return Ok(None::<()>);
13368 }
13369 cur = host::invoke(
13370 &cb,
13371 vec![
13372 std::mem::replace(&mut cur, Value::Undef),
13373 it,
13374 Value::Float(i as f64),
13375 this_value.clone(),
13376 ],
13377 this_arg(&args, 1),
13378 )?;
13379 Ok(None::<()>)
13380 })?;
13381 Ok(cur)
13382 }
13383 "reduceRight" => {
13384 let cb = arg0(&args);
13385 let n = array_len(recv);
13386 let mut acc;
13387 let mut from = n; // one past the next index to process (walking down)
13388 if args.len() >= 2 {
13389 acc = args[1].clone();
13390 } else {
13391 let holes = absent_set(recv);
13392 match (0..n).rev().find(|i| !holes.contains(i)) {
13393 Some(k) => {
13394 acc = get_property(recv, &k.to_string())?;
13395 from = k;
13396 }
13397 None => {
13398 return Err(host::type_error(
13399 "Reduce of empty array with no initial value",
13400 ))
13401 }
13402 }
13403 }
13404 // `acc` moves into the closure and back out on every step, so it
13405 // lives in an Option the closure can take from and refill.
13406 let mut slot = Some(acc);
13407 array_walk_rev(recv, from, |i, v| {
13408 let prev = slot.take().expect("accumulator is refilled each step");
13409 slot = Some(host::invoke(
13410 &cb,
13411 vec![prev, v, Value::Float(i as f64), this_value.clone()],
13412 None,
13413 )?);
13414 Ok(None::<()>)
13415 })?;
13416 acc = slot.expect("accumulator is refilled each step");
13417 Ok(acc)
13418 }
13419 "findLast" => {
13420 let items = array_items(recv);
13421 let cb = arg0(&args);
13422 for i in (0..items.len()).rev() {
13423 let m = host::invoke(
13424 &cb,
13425 vec![items[i].clone(), Value::Float(i as f64), this_value.clone()],
13426 this_arg(&args, 1),
13427 )?;
13428 if with_host(|h| h.truthy(&m)) {
13429 return Ok(items[i].clone());
13430 }
13431 }
13432 Ok(Value::Undef)
13433 }
13434 "findLastIndex" => {
13435 let items = array_items(recv);
13436 let cb = arg0(&args);
13437 for i in (0..items.len()).rev() {
13438 let m = host::invoke(
13439 &cb,
13440 vec![items[i].clone(), Value::Float(i as f64), this_value.clone()],
13441 this_arg(&args, 1),
13442 )?;
13443 if with_host(|h| h.truthy(&m)) {
13444 return Ok(Value::Float(i as f64));
13445 }
13446 }
13447 Ok(Value::Float(-1.0))
13448 }
13449 // 23.1.3.30: `SortIndexedProperties` collects only the PRESENT elements,
13450 // and the holes are re-created at the tail — `[3,,1].sort()` is
13451 // `[1, 3, <1 empty item>]` with own keys `['0','1']`.
13452 "sort" => {
13453 let all = array_items(recv);
13454 let holes = absent_set(recv);
13455 let mut items: Vec<Value> = all
13456 .iter()
13457 .enumerate()
13458 .filter(|(i, _)| !holes.contains(i))
13459 .map(|(_, v)| v.clone())
13460 .collect();
13461 sort_values(&mut items, args.first())?;
13462 let present = items.len();
13463 // 23.1.3.30 steps 4-5 write back only the indices BELOW the length
13464 // captured at step 1: `Set` for each sorted element, then `Delete`
13465 // for the holes that followed them. Replacing the whole backing
13466 // vector instead discarded anything the COMPARATOR appended —
13467 // `a.sort((x, y) => { a.push(0); return x - y })` came back at its
13468 // original length with every pushed element gone.
13469 with_host(|h| {
13470 let len = all.len();
13471 if let Some(JsObj::Array(a)) = h.get_mut(recv) {
13472 if a.len() < len {
13473 a.resize(len, Value::Undef);
13474 }
13475 for (i, v) in items.into_iter().enumerate() {
13476 a[i] = v;
13477 }
13478 for slot in a[present..len].iter_mut() {
13479 *slot = Value::Undef;
13480 }
13481 }
13482 h.install_holes(recv, (present..len).collect());
13483 });
13484 Ok(this_value.clone())
13485 }
13486 // ES2023 change-by-copy: sort a fresh copy, leaving the receiver untouched.
13487 "toSorted" => {
13488 let mut items = array_items(recv);
13489 sort_values(&mut items, args.first())?;
13490 Ok(with_host(|h| h.new_array(items)))
13491 }
13492 "toReversed" => {
13493 let mut items = array_items(recv);
13494 items.reverse();
13495 Ok(with_host(|h| h.new_array(items)))
13496 }
13497 "toSpliced" => {
13498 let mut items = array_items(recv);
13499 let len = items.len();
13500 let start = {
13501 let s = arg_num(&args, 0);
13502 if s < 0.0 {
13503 ((len as f64 + s).max(0.0)) as usize
13504 } else {
13505 (s as usize).min(len)
13506 }
13507 };
13508 let delete = if args.len() >= 2 {
13509 (arg_num(&args, 1).max(0.0) as usize).min(len - start)
13510 } else if args.is_empty() {
13511 0
13512 } else {
13513 len - start
13514 };
13515 let inserts: Vec<Value> = args.iter().skip(2).cloned().collect();
13516 items.splice(start..start + delete, inserts);
13517 Ok(with_host(|h| h.new_array(items)))
13518 }
13519 "with" => {
13520 let mut items = array_items(recv);
13521 let len = items.len() as i64;
13522 let rel = arg_num(&args, 0) as i64;
13523 let idx = if rel < 0 { len + rel } else { rel };
13524 if idx < 0 || idx >= len {
13525 return Err(host::range_error(&format!("Invalid index : {rel}")));
13526 }
13527 items[idx as usize] = args.get(1).cloned().unwrap_or(Value::Undef);
13528 Ok(with_host(|h| h.new_array(items)))
13529 }
13530 "flat" => {
13531 // depth defaults to 1; `Infinity` flattens fully. ToIntegerOrInfinity:
13532 // NaN → 0, otherwise truncate toward zero (negatives act as 0).
13533 let raw = if args.is_empty() {
13534 1.0
13535 } else {
13536 arg_num(&args, 0)
13537 };
13538 let depth = if raw.is_nan() {
13539 0.0
13540 } else if raw.is_infinite() {
13541 raw
13542 } else {
13543 raw.trunc()
13544 };
13545 let mut out = Vec::new();
13546 flatten_into(recv, depth, &mut out)?;
13547 array_species_create(
13548 this_value,
13549 out,
13550 SpeciesWrite {
13551 ctor_len: 0,
13552 set_length: false,
13553 },
13554 )
13555 }
13556 // Live over the array (23.1.5.1): each step reads it as it is then.
13557 "keys" => Ok(array_iterator(recv, host::ArrayIterKind::Keys)),
13558 "values" | "@@iterator" => Ok(array_iterator(recv, host::ArrayIterKind::Values)),
13559 "entries" => Ok(array_iterator(recv, host::ArrayIterKind::Entries)),
13560 "splice" => array_splice(recv, args),
13561 "toString" => array_to_string(recv),
13562 // An Array inherits from `Object.prototype` too, so the methods it does
13563 // not override resolve there. `[].hasOwnProperty` already read back as a
13564 // function through the property path, but CALLING it landed here and
13565 // threw `is not a function`.
13566 _ if is_object_builtin_method(name) => object_builtin_method(recv, name, args),
13567 _ => Err(host::type_error(&format!("{name} is not a function"))),
13568 }
13569}
13570
13571/// `Array.prototype.toString` (23.1.3.36): `Get(array, "join")` and call it,
13572/// falling back on `Object.prototype.toString` when that is not callable — so
13573/// an own or inherited `join` override is what stringifies the array. The
13574/// intrinsic `join` read off an Array goes straight to [`join_array`], which
13575/// shares the cycle cut with `join` itself: `ToString` of a nested array lands
13576/// back here.
13577fn array_to_string(recv: &Value) -> Result<Value, String> {
13578 let func = get_property(recv, "join")?;
13579 let intrinsic = with_host(|h| match h.get(&func) {
13580 Some(JsObj::BoundMethod { recv: r, name }) => {
13581 name == "join" && h.kind_of(r) == Some(ObjKind::Array)
13582 }
13583 _ => false,
13584 });
13585 if intrinsic {
13586 return join_array(recv, ",");
13587 }
13588 if with_host(|h| host::is_callable(h, &func)) {
13589 return host::invoke(&func, Vec::new(), Some(recv.clone()));
13590 }
13591 proto_method(recv, "Object:toString", Vec::new())
13592}
13593
13594/// `Array.prototype.join` (23.1.3.18) and, with the default separator,
13595/// `Array.prototype.toString` (23.1.3.36) — one body so both share the cycle
13596/// cut, which is not optional here: `ToString` of an element that is itself an
13597/// array re-enters through `toString`, so guarding only `join` left
13598/// `a=[]; a.push(a); a.join('-')` recursing until the native stack aborted the
13599/// process. On node v26.7.0 that expression is `""`.
13600fn join_array(recv: &Value, sep: &str) -> Result<Value, String> {
13601 if !host::join_stack_push(recv) {
13602 return Ok(with_host(|h| h.new_str(String::new())));
13603 }
13604 // 23.1.3.18 step 6: the length is captured once, then each element is read
13605 // and STRINGIFIED before the next is read. Both halves are observable —
13606 // a getter or a `toString` that shrinks the array is seen by every later
13607 // element, which a read-all-then-convert pass misses.
13608 let parts = (|| -> Result<Vec<String>, String> {
13609 let len = array_len(recv);
13610 let mut out = Vec::with_capacity(len);
13611 for i in 0..len {
13612 let v = array_elem_live(recv, i)?;
13613 out.push(join_parts(std::slice::from_ref(&v))?.remove(0));
13614 }
13615 Ok(out)
13616 })();
13617 host::join_stack_pop();
13618 let s = parts?.join(sep);
13619 Ok(with_host(|h| h.new_str(s)))
13620}
13621
13622/// `Array.prototype.join`'s per-element conversion (23.1.3.18 step 4): a
13623/// `null`/`undefined` element contributes the empty string, every other element
13624/// is `ToString(element)` — which for an object means invoking its `toString`,
13625/// so `[{ toString() { return 'x' } }].join()` is `"x"` and not
13626/// `"[object Object]"`.
13627///
13628/// The all-primitive array — the overwhelmingly common one — is rendered under
13629/// a single host borrow; only an array actually holding an object pays for the
13630/// re-entrant per-element conversion.
13631fn join_parts(items: &[Value]) -> Result<Vec<String>, String> {
13632 let fast = with_host(|h| {
13633 items
13634 .iter()
13635 .map(|x| match x {
13636 Value::Undef => Some(String::new()),
13637 _ if h.is_null(x) => Some(String::new()),
13638 // A SYMBOL element is primitive but has no `ToString`, so it must
13639 // fall through to the fallible path and throw there:
13640 // `[Symbol()].join()` is a TypeError on node v26.7.0.
13641 _ if matches!(h.get(x), Some(JsObj::Symbol { .. })) => None,
13642 _ if host::is_primitive(h, x) => Some(h.str_of(x)),
13643 _ => None,
13644 })
13645 .collect::<Vec<_>>()
13646 });
13647 if fast.iter().all(Option::is_some) {
13648 return Ok(fast.into_iter().flatten().collect());
13649 }
13650 let mut out = Vec::with_capacity(items.len());
13651 for (x, p) in items.iter().zip(fast) {
13652 match p {
13653 Some(s) => out.push(s),
13654 None => {
13655 let s = host::to_string_value(x)?;
13656 out.push(with_host(|h| h.str_of(&s)));
13657 }
13658 }
13659 }
13660 Ok(out)
13661}
13662
13663/// In-place sort of `items` (shared by `sort` and `toSorted`). Stable merge
13664/// sort — O(n log n) comparisons — with the fallible JS comparator called from
13665/// the merge step; default order is by the string form of each element.
13666/// Propagates a comparator error.
13667///
13668/// This was an insertion sort, which is O(n²): sorting 200k numbers with a
13669/// comparator did not finish inside 120s (node v26.7.0: 70ms), and each
13670/// doubling of the input quadrupled the time — 1k/2k/4k/8k/16k measured at
13671/// 0.21/0.81/3.39/12.94/51.36s. The comparator contract is unchanged; only the
13672/// number of times it is called is.
13673pub(crate) fn sort_values(items: &mut [Value], cmp: Option<&Value>) -> Result<(), String> {
13674 // 23.1.3.30 step 1: a comparator that is neither `undefined` nor callable is
13675 // rejected BEFORE any comparison runs. `[2,1].sort(null)` was reaching the
13676 // invoke path and reporting the generic `null is not a function`.
13677 let cmp = match cmp {
13678 Some(Value::Undef) => None,
13679 Some(v) if !with_host(|h| host::is_callable(h, v)) => {
13680 // V8 renders the offending value with `NoSideEffectsToString`, not
13681 // with `util.inspect`: a string appears bare (`: x`) rather than
13682 // quoted, and an array is `[object Array]` rather than `[ 1, 2 ]`.
13683 let shown = no_side_effects_string(v);
13684 return Err(host::type_error(&format!(
13685 "The comparison function must be either a function or undefined: {shown}"
13686 )));
13687 }
13688 other => other,
13689 };
13690 // 23.1.3.30.1 SortIndexedProperties: `undefined` is never handed to the
13691 // comparator — it sorts to the end after the defined values are ordered.
13692 // `[3,undefined,1].sort((x,y)=>x-y)` is `[1,3,undefined]` with ONE call on
13693 // node v26.7.0; the insertion sort called the comparator twice, on
13694 // `undefined`, and left `[3,undefined,1]`. Every element passed over here
13695 // is `undefined`, so swapping keeps the defined values in input order.
13696 let mut defined = 0;
13697 for i in 0..items.len() {
13698 if !matches!(items[i], Value::Undef) {
13699 items.swap(defined, i);
13700 defined += 1;
13701 }
13702 }
13703 merge_sort(&mut items[..defined], cmp)
13704}
13705
13706/// One SortCompare: `> 0` means `b` sorts before `a`. A comparator result runs
13707/// through ToNumber, so a NaN (or a comparator returning `undefined`) is not
13708/// `> 0` and the pair keeps its input order.
13709fn sort_compare(a: &Value, b: &Value, cmp: Option<&Value>) -> Result<f64, String> {
13710 match cmp {
13711 Some(cb) => {
13712 let v = host::invoke(cb, vec![a.clone(), b.clone()], None)?;
13713 Ok(with_host(|h| h.to_number(&v)))
13714 }
13715 None => {
13716 // 23.1.3.30.2 SortCompare with no comparator: compare the ToString
13717 // of each element by CODE UNIT (`utf16::cmp_units`), which differs
13718 // from Rust's `String` order off the BMP.
13719 let x = with_host(|h| h.str_of(a));
13720 let y = with_host(|h| h.str_of(b));
13721 if crate::utf16::cmp_units(&x, &y) == std::cmp::Ordering::Greater {
13722 Ok(1.0)
13723 } else {
13724 Ok(-1.0)
13725 }
13726 }
13727 }
13728}
13729
13730/// Bottom-up stable merge sort. Bottom-up rather than recursive so a large
13731/// array cannot walk the native stack the JS comparator also runs on, and the
13732/// two buffers are swapped each pass instead of copied back.
13733fn merge_sort(items: &mut [Value], cmp: Option<&Value>) -> Result<(), String> {
13734 let n = items.len();
13735 if n < 2 {
13736 return Ok(());
13737 }
13738 let mut src = items.to_vec();
13739 let mut dst = src.clone();
13740 let mut width = 1;
13741 while width < n {
13742 let mut lo = 0;
13743 while lo < n {
13744 let mid = (lo + width).min(n);
13745 let hi = (lo + 2 * width).min(n);
13746 merge(&src[lo..mid], &src[mid..hi], &mut dst[lo..hi], cmp)?;
13747 lo = hi;
13748 }
13749 std::mem::swap(&mut src, &mut dst);
13750 width *= 2;
13751 }
13752 items.clone_from_slice(&src);
13753 Ok(())
13754}
13755
13756/// Merge two sorted runs into `out`. Ties take from `left` first, which is what
13757/// makes the sort stable — `[{k:1},{k:0},{k:1},{k:0}].sort((x,y)=>x.k-y.k)`
13758/// keeps the two `k:0` entries in input order, as node does.
13759fn merge(
13760 left: &[Value],
13761 right: &[Value],
13762 out: &mut [Value],
13763 cmp: Option<&Value>,
13764) -> Result<(), String> {
13765 let (mut i, mut j, mut k) = (0, 0, 0);
13766 while i < left.len() && j < right.len() {
13767 if sort_compare(&left[i], &right[j], cmp)? > 0.0 {
13768 out[k] = right[j].clone();
13769 j += 1;
13770 } else {
13771 out[k] = left[i].clone();
13772 i += 1;
13773 }
13774 k += 1;
13775 }
13776 for v in left[i..].iter().chain(&right[j..]) {
13777 out[k] = v.clone();
13778 k += 1;
13779 }
13780 Ok(())
13781}
13782
13783/// Recursively flatten `items` up to `depth` levels into `out`. `depth` is an
13784/// f64 so `Infinity` (full flatten) and finite counts share one path.
13785///
13786/// `flat` has NO cycle cut — unlike `join`, V8 lets it run out of stack, and
13787/// `a=[1]; a.push(a); a.flat(Infinity)` is `RangeError: Maximum call stack size
13788/// exceeded` on node v26.7.0. That is reproduced by checking the same native
13789/// stack floor the VM does, so the answer is a catchable error rather than the
13790/// `fatal runtime error: stack overflow` abort this used to produce.
13791/// `FlattenIntoArray` (23.1.3.13.1). Takes the source ARRAY rather than its
13792/// elements because each level tests `HasProperty` before recursing, so a hole
13793/// contributes nothing at any depth: `[1,,3].flat()` is the dense `[1, 3]`.
13794fn flatten_into(src: &Value, depth: f64, out: &mut Vec<Value>) -> Result<(), String> {
13795 if host::stack_exhausted() {
13796 return Err(host::stack_overflow_error());
13797 }
13798 let items = array_items(src);
13799 let holes = absent_set(src);
13800 for (i, it) in items.into_iter().enumerate() {
13801 if holes.contains(&i) {
13802 continue;
13803 }
13804 let nested = depth > 0.0 && with_host(|h| h.kind_of(&it)) == Some(ObjKind::Array);
13805 if nested {
13806 flatten_into(&it, depth - 1.0, out)?;
13807 } else {
13808 out.push(it);
13809 }
13810 }
13811 Ok(())
13812}
13813
13814fn array_splice(recv: &Value, args: Vec<Value>) -> Result<Value, String> {
13815 let len = array_len(recv);
13816 let start = {
13817 let s = arg_num(&args, 0);
13818 if s < 0.0 {
13819 ((len as f64 + s).max(0.0)) as usize
13820 } else {
13821 (s as usize).min(len)
13822 }
13823 };
13824 let delete = if args.len() >= 2 {
13825 (arg_num(&args, 1).max(0.0) as usize).min(len - start)
13826 } else {
13827 len - start
13828 };
13829 let inserts: Vec<Value> = args.iter().skip(2).cloned().collect();
13830 let inserted = inserts.len();
13831 // The receiver's holes shift by (inserted - deleted) past the cut, and the
13832 // ones inside the cut move into the RETURNED array at their offset there.
13833 let holes = hole_set(recv);
13834 let removed = with_host(|h| {
13835 if let Some(JsObj::Array(items)) = h.get_mut(recv) {
13836 let removed: Vec<Value> = items.splice(start..start + delete, inserts).collect();
13837 removed
13838 } else {
13839 Vec::new()
13840 }
13841 });
13842 let spliced = with_host(|h| {
13843 h.install_holes(
13844 recv,
13845 holes
13846 .iter()
13847 .filter_map(|&i| {
13848 if i < start {
13849 Some(i)
13850 } else if i < start + delete {
13851 None
13852 } else {
13853 Some(i - delete + inserted)
13854 }
13855 })
13856 .collect(),
13857 );
13858 (removed, holes.clone())
13859 });
13860 // The REMOVED elements come back as an array of the receiver's species
13861 // (23.1.3.31 step 8), so a subclass gets one of its own kind.
13862 let (removed, holes) = spliced;
13863 let removed_len = removed.len();
13864 let out = array_species_create(
13865 recv,
13866 removed,
13867 SpeciesWrite {
13868 ctor_len: removed_len,
13869 set_length: true,
13870 },
13871 )?;
13872 with_host(|h| {
13873 h.install_holes(
13874 &out,
13875 holes
13876 .iter()
13877 .filter(|&&i| i >= start && i < start + delete)
13878 .map(|&i| i - start)
13879 .collect(),
13880 );
13881 });
13882 Ok(out)
13883}
13884
13885fn slice_bounds(args: &[Value], len: usize) -> (usize, usize) {
13886 let norm = |v: f64| -> usize {
13887 if v < 0.0 {
13888 ((len as f64 + v).max(0.0)) as usize
13889 } else {
13890 (v as usize).min(len)
13891 }
13892 };
13893 let lo = if args.is_empty() || matches!(args[0], Value::Undef) {
13894 0
13895 } else {
13896 norm(arg_num(args, 0))
13897 };
13898 let hi = if args.len() < 2 || matches!(args[1], Value::Undef) {
13899 len
13900 } else {
13901 norm(arg_num(args, 1))
13902 };
13903 // A start at or past the end (`'World'.slice(2, 1)`) yields the empty range,
13904 // never a reversed one: JS `slice` clamps `end` up to `start`.
13905 (lo, hi.max(lo))
13906}
13907
13908/// The argument positions each `String.prototype` method coerces with
13909/// `ToNumber` rather than `ToString`. Everything not listed is a string
13910/// position — which matters only for a SYMBOL argument, the one value both
13911/// conversions refuse, and refuse with different wording.
13912///
13913/// Measured per method and per position: `'x'.indexOf(sym)` reports the STRING
13914/// message and `'x'.indexOf('a', sym)` the NUMBER one, and `padStart` is the
13915/// pair the other way round (a length then a pad string).
13916const STRING_METHOD_NUMERIC_ARGS: &[(&str, &[usize])] = &[
13917 ("at", &[0]),
13918 ("charAt", &[0]),
13919 ("charCodeAt", &[0]),
13920 ("codePointAt", &[0]),
13921 ("endsWith", &[1]),
13922 ("includes", &[1]),
13923 ("indexOf", &[1]),
13924 ("lastIndexOf", &[1]),
13925 ("padEnd", &[0]),
13926 ("padStart", &[0]),
13927 ("repeat", &[0]),
13928 ("slice", &[0, 1]),
13929 ("split", &[1]),
13930 ("startsWith", &[1]),
13931 ("substr", &[0, 1]),
13932 ("substring", &[0, 1]),
13933];
13934
13935/// Reject a SYMBOL argument before any string method coerces it. 7.1.17 and
13936/// 7.1.4 both refuse one, so `'x'.padStart(3, sym)` is a TypeError where this
13937/// rendered `Symbol(d)` into the result — silently, which is the shape of
13938/// mistake that makes a symbol key leak into text.
13939fn reject_symbol_args(name: &str, args: &[Value]) -> Result<(), String> {
13940 let numeric = STRING_METHOD_NUMERIC_ARGS
13941 .iter()
13942 .find(|(m, _)| *m == name)
13943 .map(|(_, ps)| *ps)
13944 .unwrap_or(&[]);
13945 for (i, a) in args.iter().enumerate() {
13946 if with_host(|h| matches!(h.get(a), Some(JsObj::Symbol { .. }))) {
13947 let kind = if numeric.contains(&i) {
13948 "number"
13949 } else {
13950 "string"
13951 };
13952 return Err(host::type_error(&format!(
13953 "Cannot convert a Symbol value to a {kind}"
13954 )));
13955 }
13956 }
13957 Ok(())
13958}
13959
13960/// Coerce a string method's arguments the way 22.1.3.x does, BEFORE any arm
13961/// reads them: a numeric position through `ToNumber`, every other through
13962/// `ToString`. Both run a user `valueOf`/`toString`, and none of them ran —
13963/// `'x'.padStart({valueOf: () => 3})` produced `"x"` and
13964/// `'x'.concat({toString: () => 'y'})` produced `"x[object Object]"`.
13965///
13966/// The positions that must NOT be coerced are the ones with their own protocol:
13967/// a RegExp or a `Symbol.replace`/`split`/`match`/`search` carrier at position
13968/// 0 of the method that honours it, and a callable REPLACEMENT at position 1 of
13969/// `replace`/`replaceAll`. Each of those already has a path that handles the
13970/// value as an object, and stringifying it first would take that path away.
13971/// The argument positions each `Array.prototype` method coerces with
13972/// `ToNumber` (23.1.3.x). Everything not listed is a VALUE position and must be
13973/// left alone: `fill`'s first argument, `with`'s second and `splice`'s items
13974/// are stored as given, and `indexOf`/`includes` compare their first argument
13975/// without converting it.
13976const ARRAY_METHOD_NUMERIC_ARGS: &[(&str, &[usize])] = &[
13977 ("at", &[0]),
13978 ("copyWithin", &[0, 1, 2]),
13979 ("fill", &[1, 2]),
13980 ("flat", &[0]),
13981 ("includes", &[1]),
13982 ("indexOf", &[1]),
13983 ("lastIndexOf", &[1]),
13984 ("slice", &[0, 1]),
13985 ("splice", &[0, 1]),
13986 ("toSpliced", &[0, 1]),
13987 ("with", &[0]),
13988];
13989
13990/// The same for `Number.prototype`. `toLocaleString` takes a LOCALE, not a
13991/// number, and is deliberately absent.
13992const NUMBER_METHOD_NUMERIC_ARGS: &[(&str, &[usize])] = &[
13993 ("toExponential", &[0]),
13994 ("toFixed", &[0]),
13995 ("toPrecision", &[0]),
13996 ("toString", &[0]),
13997];
13998
13999/// Replace the listed argument positions with their `ToNumber` value, running a
14000/// user `valueOf` and propagating a throw from it. Every one of these read the
14001/// argument with an INFALLIBLE conversion that does no `ToPrimitive` at all, so
14002/// `[1,2,3].slice({valueOf: () => 1})` sliced from 0 and `(1.234).toFixed(obj)`
14003/// was a RangeError.
14004/// `ToNumber(args[i])`, running a user `valueOf` and propagating its throw.
14005fn to_number_arg(args: &[Value], i: usize) -> Result<f64, String> {
14006 let v = args.get(i).cloned().unwrap_or(Value::Undef);
14007 let p = host::to_primitive(&v, "number")?;
14008 Ok(with_host(|h| h.to_number(&p)))
14009}
14010
14011fn coerce_numeric_args(
14012 table: &[(&str, &[usize])],
14013 name: &str,
14014 mut args: Vec<Value>,
14015) -> Result<Vec<Value>, String> {
14016 let Some((_, positions)) = table.iter().find(|(m, _)| *m == name) else {
14017 return Ok(args);
14018 };
14019 for &i in *positions {
14020 let Some(a) = args.get(i) else { continue };
14021 if matches!(a, Value::Undef) {
14022 continue;
14023 }
14024 let p = host::to_primitive(a, "number")?;
14025 args[i] = Value::Float(with_host(|h| h.to_number(&p)));
14026 }
14027 Ok(args)
14028}
14029
14030/// `RegExpCreate(v, flags)` — the regexp a string method builds from a
14031/// non-RegExp argument. An empty/absent argument makes the empty pattern, which
14032/// matches at position 0.
14033fn regexp_from_arg(v: &Value, flags: &str) -> Result<Value, String> {
14034 let src = if matches!(v, Value::Undef) {
14035 String::new()
14036 } else {
14037 with_host(|h| h.str_of(v))
14038 };
14039 let fv = with_host(|h| h.new_str(flags.to_string()));
14040 let sv = with_host(|h| h.new_str(src));
14041 regexp_ctor(&[sv, fv], false)
14042}
14043
14044fn coerce_string_args(name: &str, args: Vec<Value>) -> Result<Vec<Value>, String> {
14045 let numeric = STRING_METHOD_NUMERIC_ARGS
14046 .iter()
14047 .find(|(m, _)| *m == name)
14048 .map(|(_, ps)| *ps)
14049 .unwrap_or(&[]);
14050 let protocol = match name {
14051 "replace" | "replaceAll" => Some("@@replace"),
14052 "split" => Some("@@split"),
14053 "match" => Some("@@match"),
14054 "matchAll" => Some("@@matchAll"),
14055 "search" => Some("@@search"),
14056 // These three do not CONSUME `Symbol.match`, they reject a value that
14057 // carries it (22.1.3.7/23/24 step 3 — `IsRegExp`). Exempting it keeps
14058 // the object intact so that check still sees one; stringifying first
14059 // turned the TypeError into an ordinary search.
14060 "startsWith" | "endsWith" | "includes" => Some("@@match"),
14061 _ => None,
14062 };
14063 let mut out = Vec::with_capacity(args.len());
14064 for (i, a) in args.into_iter().enumerate() {
14065 if matches!(a, Value::Undef) {
14066 out.push(a);
14067 continue;
14068 }
14069 if numeric.contains(&i) {
14070 let p = host::to_primitive(&a, "number")?;
14071 out.push(Value::Float(with_host(|h| h.to_number(&p))));
14072 continue;
14073 }
14074 // The IsRegExp trio tests `Symbol.match` for TRUTHINESS (7.2.8 step 2),
14075 // not for presence: an object carrying `[Symbol.match]: false` is NOT a
14076 // regexp and coerces like anything else. The consuming protocols use
14077 // `GetMethod`, which additionally requires a callable.
14078 let is_regexp_like = matches!(name, "startsWith" | "endsWith" | "includes");
14079 let carries = |p: &str| match host::protocol_lookup(&a, p) {
14080 Ok(Some(m)) => {
14081 if is_regexp_like {
14082 with_host(|h| h.truthy(&m))
14083 } else {
14084 with_host(|h| host::is_callable(h, &m))
14085 }
14086 }
14087 _ => false,
14088 };
14089 let exempt = with_host(|h| matches!(h.get(&a), Some(JsObj::RegExp(_))))
14090 || (i == 0 && protocol.is_some_and(carries))
14091 || (i == 1
14092 && matches!(name, "replace" | "replaceAll")
14093 && with_host(|h| host::is_callable(h, &a)));
14094 if exempt {
14095 out.push(a);
14096 continue;
14097 }
14098 out.push(host::to_string_value(&a)?);
14099 }
14100 Ok(out)
14101}
14102
14103fn string_method(s: &str, name: &str, args: Vec<Value>) -> Result<Value, String> {
14104 reject_symbol_args(name, &args)?;
14105 if matches!(name, "replaceAll" | "matchAll") {
14106 require_global_regexp(name, &arg0(&args))?;
14107 }
14108 let args = coerce_string_args(name, args)?;
14109 // Every index-bearing method below counts UTF-16 code units, so they all
14110 // work off this one decoding rather than off `s.chars()` (code points),
14111 // which agrees only on the BMP. `@@iterator` is the deliberate exception.
14112 let u = crate::utf16::Units::of(s);
14113 match name {
14114 // `for…of` / spread over a string iterates CODE POINTS, not code units:
14115 // `[..."𝒳"]` is one element in node even though `"𝒳".length` is 2. This
14116 // is the one string operation that is specified in chars, so it stays
14117 // on `s.chars()` on purpose — do not "fix" it to match the others.
14118 "@@iterator" => {
14119 let items: Vec<Value> = s.chars().map(|c| new_s(c.to_string())).collect();
14120 Ok(with_host(|h| {
14121 h.alloc_iter(JsObj::Iter {
14122 items,
14123 idx: 0,
14124 array: None,
14125 brand: Some("String Iterator"),
14126 })
14127 }))
14128 }
14129 "toUpperCase" => Ok(new_s(s.to_uppercase())),
14130 "toLowerCase" => Ok(new_s(s.to_lowercase())),
14131 // `toLocaleUpperCase`/`toLocaleLowerCase` (22.1.3.26/22.1.3.24) differ
14132 // from the plain forms only for the locale-specific mappings (Turkish
14133 // dotless i, Lithuanian accents); with no locale argument they are the
14134 // Unicode Default Case Conversion, which is exactly `to_uppercase`/
14135 // `to_lowercase`. They threw `is not a function` before, so the common
14136 // no-argument call — the only form this runtime can answer, since it
14137 // carries no ICU — failed outright rather than agreeing with node.
14138 // A locale ARGUMENT is accepted and ignored; `'I'.toLocaleLowerCase('tr')`
14139 // is `'i'` here and `'ı'` in node.
14140 // `String.prototype.toLocaleString` (22.1.3.27) is `toString` — a string
14141 // has no locale rendering. Missing it made an ARRAY of strings fail too,
14142 // since `Array.prototype.toLocaleString` invokes it per element.
14143 "toLocaleString" => Ok(new_s(s.to_string())),
14144 "toLocaleUpperCase" => Ok(new_s(s.to_uppercase())),
14145 "toLocaleLowerCase" => Ok(new_s(s.to_lowercase())),
14146 // Locale comparison (ASCII approximation of ICU collation): primary by
14147 // case-folded order, then lowercase sorts before uppercase at a tie.
14148 "localeCompare" => {
14149 let other = with_host(|h| h.str_of(&arg0(&args)));
14150 let (la, lb) = (s.to_lowercase(), other.to_lowercase());
14151 let r = match la.cmp(&lb) {
14152 std::cmp::Ordering::Less => -1.0,
14153 std::cmp::Ordering::Greater => 1.0,
14154 std::cmp::Ordering::Equal => {
14155 let mut t = 0.0;
14156 for (ca, cb) in s.chars().zip(other.chars()) {
14157 if ca != cb {
14158 t = if ca.is_lowercase() { -1.0 } else { 1.0 };
14159 break;
14160 }
14161 }
14162 t
14163 }
14164 };
14165 Ok(Value::Float(r))
14166 }
14167 // `String.prototype.normalize` (22.1.3.15) — real UAX-15 normalization.
14168 //
14169 // This used to return the receiver unchanged and only validate the FORM
14170 // argument, which made every one of the four forms a no-op: `"Å"` (NFC,
14171 // one code point) and `"Å"` (NFD, two) stayed distinct under
14172 // `.normalize()`, so the standard way to compare Unicode text for
14173 // canonical equivalence silently answered `false`, and `NFKC` never
14174 // folded a compatibility character (`"fi"` stayed one code point instead
14175 // of becoming `"fi"`). The tables come from `unicode-normalization`.
14176 "normalize" => {
14177 use unicode_normalization::UnicodeNormalization;
14178 let form = match args.first() {
14179 Some(v) if !matches!(v, Value::Undef) => with_host(|h| h.str_of(v)),
14180 _ => "NFC".to_string(),
14181 };
14182 let out = match form.as_str() {
14183 "NFC" => s.nfc().collect::<String>(),
14184 "NFD" => s.nfd().collect::<String>(),
14185 "NFKC" => s.nfkc().collect::<String>(),
14186 "NFKD" => s.nfkd().collect::<String>(),
14187 _ => {
14188 return Err(host::range_error(
14189 "The normalization form should be one of NFC, NFD, NFKC, NFKD.",
14190 ))
14191 }
14192 };
14193 Ok(new_s(out))
14194 }
14195 // Annex B `CreateHTML(string, tag, attribute, value)`: the receiver
14196 // wrapped in `<tag>`, with ` attribute="value"` on the open tag when
14197 // the method has one — `value` is `ToString`ed even when absent
14198 // (`"x".anchor()` is `<a name="undefined">x</a>`) and only `"` is
14199 // escaped, as `"`.
14200 "anchor" | "big" | "blink" | "bold" | "fixed" | "fontcolor" | "fontsize" | "italics"
14201 | "link" | "small" | "strike" | "sub" | "sup" => {
14202 let (tag, attribute) = match name {
14203 "anchor" => ("a", "name"),
14204 "bold" => ("b", ""),
14205 "fixed" => ("tt", ""),
14206 "fontcolor" => ("font", "color"),
14207 "fontsize" => ("font", "size"),
14208 "italics" => ("i", ""),
14209 "link" => ("a", "href"),
14210 other => (other, ""),
14211 };
14212 let mut open = format!("<{tag}");
14213 if !attribute.is_empty() {
14214 let value = args.first().cloned().unwrap_or(Value::Undef);
14215 let value = with_host(|h| h.str_of(&value)).replace('"', """);
14216 open.push_str(&format!(" {attribute}=\"{value}\""));
14217 }
14218 Ok(new_s(format!("{open}>{s}</{tag}>")))
14219 }
14220 // ES2024 well-formedness (22.1.3.9 / 22.1.3.29). A `String` here is a
14221 // Rust `String`, whose `char` type EXCLUDES `U+D800..=U+DFFF`, so every
14222 // value this runtime can hold is well-formed by construction and
14223 // `toWellFormed` has nothing to replace. Both answers are therefore
14224 // exact for every string that survives storage; the one case node
14225 // answers differently is a surrogate half extracted by `charAt`/`slice`,
14226 // which is already `U+FFFD` here — the documented lone-surrogate
14227 // boundary in `utf16`, not a separate gap.
14228 "isWellFormed" => Ok(Value::Bool(true)),
14229 "toWellFormed" => Ok(new_s(s.to_string())),
14230 // The JS `WhiteSpace` set, not Rust's — they differ on `U+FEFF`.
14231 "trim" => Ok(new_s(crate::utf16::js_trim(s).to_string())),
14232 "trimStart" | "trimLeft" => Ok(new_s(crate::utf16::js_trim_start(s).to_string())),
14233 "trimEnd" | "trimRight" => Ok(new_s(crate::utf16::js_trim_end(s).to_string())),
14234 "toString" | "valueOf" => Ok(new_s(s.to_string())),
14235 "charAt" => {
14236 let at = unit_pos(arg_num(&args, 0)).and_then(|i| u.unit_str(i));
14237 Ok(new_s(at.unwrap_or_default()))
14238 }
14239 "at" => {
14240 let n = arg_num(&args, 0);
14241 // A negative position counts back from the end; `NaN` is 0. An
14242 // infinite position is out of range in either direction.
14243 let i = if n.is_nan() {
14244 Some(0i64)
14245 } else if n.is_finite() {
14246 let i = n.trunc() as i64;
14247 Some(if i < 0 { i + u.len() as i64 } else { i })
14248 } else {
14249 None
14250 };
14251 match i
14252 .and_then(|i| usize::try_from(i).ok())
14253 .and_then(|i| u.unit_str(i))
14254 {
14255 Some(c) => Ok(new_s(c)),
14256 None => Ok(Value::Undef),
14257 }
14258 }
14259 // `charCodeAt` reports the bare code UNIT — the high surrogate of an
14260 // astral character, not the character. `codePointAt` looks ahead one
14261 // unit and reports the whole scalar when the pair is well formed. They
14262 // agree everywhere on the BMP, which is why they used to share an arm.
14263 // They also disagree OUT of range: `charCodeAt` yields `NaN` while
14264 // `codePointAt` yields `undefined` (measured on node v26.7.0).
14265 "charCodeAt" => {
14266 let unit = unit_pos(arg_num(&args, 0)).and_then(|i| u.unit(i));
14267 Ok(Value::Float(unit.map(f64::from).unwrap_or(f64::NAN)))
14268 }
14269 "codePointAt" => match unit_pos(arg_num(&args, 0)).and_then(|i| u.code_point(i)) {
14270 Some(cp) => Ok(Value::Float(f64::from(cp))),
14271 None => Ok(Value::Undef),
14272 },
14273 // The search quartet all honor their optional position argument.
14274 // `"a&b&c".indexOf("&", 2)` must be 3, not 1 — body-parser's
14275 // parameterCount walks a query string with exactly that call.
14276 "indexOf" => {
14277 let needle = needle_units(&args);
14278 let from = clamp_pos(arg_num(&args, 1), u.len());
14279 Ok(Value::Float(
14280 search_from(u.as_slice(), needle.as_slice(), from)
14281 .map(|i| i as f64)
14282 .unwrap_or(-1.0),
14283 ))
14284 }
14285 "lastIndexOf" => {
14286 let needle = needle_units(&args);
14287 // An absent or NaN position means "search the whole string".
14288 let n = arg_num(&args, 1);
14289 let upto = if n.is_nan() {
14290 u.len()
14291 } else {
14292 clamp_pos(n, u.len())
14293 };
14294 Ok(Value::Float(
14295 search_last(u.as_slice(), needle.as_slice(), upto)
14296 .map(|i| i as f64)
14297 .unwrap_or(-1.0),
14298 ))
14299 }
14300 // 22.1.3.7/22.1.3.23/22.1.3.14 step 2: these three reject a REGEXP
14301 // argument outright, and `IsRegExp` is what decides — so an object
14302 // advertising `Symbol.match` is rejected too. None of them checked.
14303 "startsWith" | "endsWith" | "includes" if is_regexp_arg(&arg0(&args)) => {
14304 Err(host::type_error(&format!(
14305 "First argument to String.prototype.{name} must not be a regular expression"
14306 )))
14307 }
14308 "includes" => {
14309 let needle = needle_units(&args);
14310 let from = clamp_pos(arg_num(&args, 1), u.len());
14311 Ok(Value::Bool(
14312 search_from(u.as_slice(), needle.as_slice(), from).is_some(),
14313 ))
14314 }
14315 "startsWith" => {
14316 let needle = needle_units(&args);
14317 let from = clamp_pos(arg_num(&args, 1), u.len());
14318 Ok(Value::Bool(
14319 u.as_slice()[from..].starts_with(needle.as_slice()),
14320 ))
14321 }
14322 "endsWith" => {
14323 let needle = needle_units(&args);
14324 // The 2nd argument is where the string is treated as ENDING.
14325 let end = if args.len() < 2 || matches!(args[1], Value::Undef) {
14326 u.len()
14327 } else {
14328 clamp_pos(arg_num(&args, 1), u.len())
14329 };
14330 Ok(Value::Bool(
14331 u.as_slice()[..end].ends_with(needle.as_slice()),
14332 ))
14333 }
14334 "slice" => {
14335 let (lo, hi) = slice_bounds(&args, u.len());
14336 Ok(new_s(u.slice(lo, hi)))
14337 }
14338 "substring" => {
14339 let mut a = arg_num(&args, 0).max(0.0) as usize;
14340 let mut b = if args.len() < 2 || matches!(args[1], Value::Undef) {
14341 u.len()
14342 } else {
14343 (arg_num(&args, 1).max(0.0) as usize).min(u.len())
14344 };
14345 a = a.min(u.len());
14346 if a > b {
14347 std::mem::swap(&mut a, &mut b);
14348 }
14349 Ok(new_s(u.slice(a, b)))
14350 }
14351 "substr" => {
14352 // A negative start counts from the end: max(len + start, 0).
14353 let len = u.len() as i64;
14354 let mut start = arg_num(&args, 0) as i64;
14355 if start < 0 {
14356 start = (len + start).max(0);
14357 }
14358 let start = (start as usize).min(u.len());
14359 let count = if args.len() >= 2 {
14360 arg_num(&args, 1).max(0.0) as usize
14361 } else {
14362 u.len()
14363 };
14364 let end = start.saturating_add(count).min(u.len());
14365 Ok(new_s(u.slice(start, end)))
14366 }
14367 "repeat" => {
14368 let n = arg_num(&args, 0);
14369 // `RangeError`, not `TypeError`, and the count is named:
14370 // `"x".repeat(-1)` is `RangeError: Invalid count value: -1`.
14371 if n < 0.0 || !n.is_finite() {
14372 return Err(host::range_error(&format!(
14373 "Invalid count value: {}",
14374 host::fmt_number(n)
14375 )));
14376 }
14377 // The PRODUCT is what V8 bounds, so `''.repeat(2**53)` is legal (and
14378 // `''`) while `'ab'.repeat(268435445)` is not: measured on node
14379 // v26.7.0, `'ab'.repeat(268435444).length` is 536870888 and one more
14380 // is `RangeError: Invalid string length`.
14381 if n * crate::utf16::len(s) as f64 > host::MAX_STRING_LENGTH as f64 {
14382 return Err(host::invalid_string_length());
14383 }
14384 Ok(new_s(s.repeat(n as usize)))
14385 }
14386 "concat" => {
14387 let mut out = s.to_string();
14388 for a in &args {
14389 out.push_str(&with_host(|h| h.str_of(a)));
14390 }
14391 Ok(new_s(out))
14392 }
14393 "padStart" => Ok(new_s(pad(s, &args, true)?)),
14394 "padEnd" => Ok(new_s(pad(s, &args, false)?)),
14395 // Regex-taking string methods: dispatch to the regexp module when the
14396 // argument is a RegExp; otherwise keep the plain-string behavior. The
14397 // `g`-flag check `replaceAll`/`matchAll` make first is
14398 // `require_global_regexp`, run before the arguments are coerced.
14399 "match" | "matchAll" | "search" | "split" | "replace" | "replaceAll"
14400 if symbol_protocol(
14401 &arg0(&args),
14402 match name {
14403 "match" => "@@match",
14404 "matchAll" => "@@matchAll",
14405 "search" => "@@search",
14406 "split" => "@@split",
14407 _ => "@@replace",
14408 },
14409 )
14410 .is_some() =>
14411 {
14412 let sym = match name {
14413 "match" => "@@match",
14414 "matchAll" => "@@matchAll",
14415 "search" => "@@search",
14416 "split" => "@@split",
14417 _ => "@@replace",
14418 };
14419 let f = symbol_protocol(&arg0(&args), sym).expect("guard checked");
14420 let sv = with_host(|h| h.new_str(s.to_string()));
14421 let mut rest = vec![sv];
14422 rest.extend(args.iter().skip(1).cloned());
14423 host::invoke(&f, rest, Some(arg0(&args)))
14424 }
14425 // 22.1.3.13/14: a non-RegExp argument is turned INTO one
14426 // (`RegExpCreate(regexp, …)`), so `'abc'.match('b')` matches. It
14427 // answered `null` for every string argument, which reads as "no match"
14428 // — the one answer a caller cannot tell from a real failure.
14429 // `matchAll` builds its with `g`, which 22.1.3.14 requires.
14430 "match" => {
14431 let a = arg0(&args);
14432 let re = if is_regexp_arg(&a) {
14433 a
14434 } else {
14435 regexp_from_arg(&a, "")?
14436 };
14437 crate::regexp::str_match(s, &re)
14438 }
14439 "matchAll" => {
14440 let a = arg0(&args);
14441 let re = if is_regexp_arg(&a) {
14442 a
14443 } else {
14444 regexp_from_arg(&a, "g")?
14445 };
14446 crate::regexp::str_match_all(s, &re)
14447 }
14448 "search" => {
14449 if is_regexp_arg(&arg0(&args)) {
14450 crate::regexp::str_search(s, &arg0(&args))
14451 } else {
14452 // 22.1.3.17 builds a RegExp from the argument, so a
14453 // METACHARACTER matches as one: `'a.c'.search('.')` is 0, not
14454 // 1. The substring approximation this replaces agreed only for
14455 // a literal needle, and answered -1 for an absent argument
14456 // where the empty pattern matches at 0.
14457 let re = regexp_from_arg(&arg0(&args), "")?;
14458 crate::regexp::str_search(s, &re)
14459 }
14460 }
14461 "replace" => {
14462 let pat = arg0(&args);
14463 let repl = args.get(1).cloned().unwrap_or(Value::Undef);
14464 if is_regexp_arg(&pat) {
14465 crate::regexp::str_replace_regex(s, &pat, &repl, false)
14466 } else if with_host(|h| host::is_callable(h, &repl)) {
14467 Ok(new_s(replace_str_fn(
14468 s,
14469 &with_host(|h| h.str_of(&pat)),
14470 &repl,
14471 false,
14472 )?))
14473 } else {
14474 let from = with_host(|h| h.str_of(&pat));
14475 let to = with_host(|h| h.str_of(&repl));
14476 Ok(new_s(replace_str_plain(s, &from, &to, false)))
14477 }
14478 }
14479 "replaceAll" => {
14480 let pat = arg0(&args);
14481 let repl = args.get(1).cloned().unwrap_or(Value::Undef);
14482 if is_regexp_arg(&pat) {
14483 // 22.1.3.20 step 2: a non-global regexp is a TypeError here,
14484 // because `replaceAll` cannot honour "all" without `g`. This
14485 // used to replace only the first match and say nothing.
14486 let global = with_host(|h| match h.get(&pat) {
14487 Some(JsObj::RegExp(r)) => r.global,
14488 _ => true,
14489 });
14490 if !global {
14491 return Err(host::type_error(
14492 "String.prototype.replaceAll called with a non-global RegExp argument",
14493 ));
14494 }
14495 crate::regexp::str_replace_regex(s, &pat, &repl, true)
14496 } else if with_host(|h| host::is_callable(h, &repl)) {
14497 Ok(new_s(replace_str_fn(
14498 s,
14499 &with_host(|h| h.str_of(&pat)),
14500 &repl,
14501 true,
14502 )?))
14503 } else {
14504 let from = with_host(|h| h.str_of(&pat));
14505 let to = with_host(|h| h.str_of(&repl));
14506 Ok(new_s(replace_str_plain(s, &from, &to, true)))
14507 }
14508 }
14509 "split" => {
14510 if is_regexp_arg(&arg0(&args)) {
14511 let limit = args
14512 .get(1)
14513 .filter(|v| !matches!(v, Value::Undef))
14514 .map(|v| with_host(|h| h.to_number(v)) as usize);
14515 return crate::regexp::str_split_regex(s, &arg0(&args), limit);
14516 }
14517 let mut parts: Vec<Value> = if args.is_empty() || matches!(args[0], Value::Undef) {
14518 vec![new_s(s.to_string())]
14519 } else {
14520 let sep = with_host(|h| h.str_of(&args[0]));
14521 if sep.is_empty() {
14522 // `split('')` yields one element per code UNIT, so an astral
14523 // character becomes its two surrogate halves.
14524 (0..u.len())
14525 .filter_map(|i| u.unit_str(i))
14526 .map(new_s)
14527 .collect()
14528 } else {
14529 s.split(&sep as &str)
14530 .map(|p| new_s(p.to_string()))
14531 .collect()
14532 }
14533 };
14534 // Optional limit: keep at most `limit` substrings.
14535 if let Some(lim) = args.get(1).filter(|v| !matches!(v, Value::Undef)) {
14536 let n = with_host(|h| h.to_number(lim));
14537 if n.is_finite() && n >= 0.0 {
14538 parts.truncate(n as usize);
14539 }
14540 }
14541 Ok(with_host(|h| h.new_array(parts)))
14542 }
14543 _ => Err(host::type_error(&format!("{name} is not a function"))),
14544 }
14545}
14546
14547/// GetSubstitution (22.1.3.19) for a STRING search value.
14548///
14549/// `String.prototype.replace`/`replaceAll` expand the same `$` patterns whether
14550/// the pattern is a regexp or a plain string, but the string path here did a
14551/// raw `str::replace` and passed the template through verbatim — so
14552/// `'abc'.replace('b', '[$&]')` produced `a[$&]c` instead of `a[b]c`. The
14553/// regexp path has always expanded them.
14554///
14555/// A string search captures nothing, so only `$$`, `$&`, `` $` `` and `$'`
14556/// apply; `$1` and `$<name>` have no referent and stay literal, which is also
14557/// what node does.
14558fn substitute_plain(templ: &str, matched: &str, position: usize, subject: &str) -> String {
14559 let chars: Vec<char> = templ.chars().collect();
14560 let mut out = String::new();
14561 let mut i = 0;
14562 while i < chars.len() {
14563 if chars[i] == '$' && i + 1 < chars.len() {
14564 match chars[i + 1] {
14565 '$' => {
14566 out.push('$');
14567 i += 2;
14568 continue;
14569 }
14570 '&' => {
14571 out.push_str(matched);
14572 i += 2;
14573 continue;
14574 }
14575 '`' => {
14576 out.push_str(&subject[..position]);
14577 i += 2;
14578 continue;
14579 }
14580 '\'' => {
14581 out.push_str(&subject[position + matched.len()..]);
14582 i += 2;
14583 continue;
14584 }
14585 _ => {}
14586 }
14587 }
14588 out.push(chars[i]);
14589 i += 1;
14590 }
14591 out
14592}
14593
14594/// `replace`/`replaceAll` with a string pattern and a string replacement,
14595/// expanding each match's `$` patterns against its own position.
14596fn replace_str_plain(s: &str, from: &str, to: &str, all: bool) -> String {
14597 if from.is_empty() && !all {
14598 return format!("{}{s}", substitute_plain(to, "", 0, s));
14599 }
14600 if from.is_empty() {
14601 // `replaceAll("")` matches at every code-unit boundary; the unit between
14602 // two matches is copied through (a half of a pair becomes U+FFFD, the
14603 // documented lone-surrogate boundary).
14604 let u = crate::utf16::Units::of(s);
14605 let mut out = String::new();
14606 for i in 0..=u.len() {
14607 let at = crate::utf16::byte_of_index(s, crate::utf16::U16Index::new(i));
14608 out.push_str(&substitute_plain(to, from, at, s));
14609 out.push_str(&u.unit_str(i).unwrap_or_default());
14610 }
14611 return out;
14612 }
14613 let mut out = String::new();
14614 let mut rest = 0usize;
14615 while let Some(rel) = s[rest..].find(from) {
14616 let at = rest + rel;
14617 out.push_str(&s[rest..at]);
14618 out.push_str(&substitute_plain(to, from, at, s));
14619 rest = at + from.len();
14620 if !all {
14621 break;
14622 }
14623 }
14624 out.push_str(&s[rest..]);
14625 out
14626}
14627
14628fn new_s(s: String) -> Value {
14629 with_host(|h| h.new_str(s))
14630}
14631
14632/// Where a forward `indexOf`/`includes` search starts, given the optional
14633/// `fromIndex` (23.1.3.17 steps 4-6, 23.1.3.16 steps 5-7). A negative value
14634/// counts back from the end and clamps at 0; absent or `NaN` is 0. A start at
14635/// or past the end finds nothing, which callers report as `-1` / `false`.
14636pub(crate) fn search_start(n: f64, len: usize) -> usize {
14637 if n.is_nan() {
14638 return 0;
14639 }
14640 let n = n.trunc();
14641 if n >= 0.0 {
14642 if n >= len as f64 {
14643 len
14644 } else {
14645 n as usize
14646 }
14647 } else {
14648 let from_end = len as f64 + n;
14649 if from_end <= 0.0 {
14650 0
14651 } else {
14652 from_end as usize
14653 }
14654 }
14655}
14656
14657/// The INCLUSIVE index a backward `lastIndexOf` starts at (23.1.3.20 steps
14658/// 4-6), or `None` when `fromIndex` places it before the array. Absent means
14659/// the last element — which is why this takes an `Option` rather than reading
14660/// `NaN` as "absent" the way the forward form can: an explicit `NaN` is
14661/// `ToIntegerOrInfinity`'d to 0 and searches only index 0.
14662pub(crate) fn search_start_last(from: Option<f64>, len: usize) -> Option<usize> {
14663 if len == 0 {
14664 return None;
14665 }
14666 let n = match from {
14667 None => return Some(len - 1),
14668 Some(v) if v.is_nan() => 0.0,
14669 Some(v) => v.trunc(),
14670 };
14671 if n >= 0.0 {
14672 Some(if n >= len as f64 { len - 1 } else { n as usize })
14673 } else {
14674 let k = len as f64 + n;
14675 if k < 0.0 {
14676 None
14677 } else {
14678 Some(k as usize)
14679 }
14680 }
14681}
14682
14683/// `ToIntegerOrInfinity(n)` clamped into `0..=len` — the position argument of
14684/// the `String.prototype` search methods. `NaN` (an absent argument) is `0`.
14685fn clamp_pos(n: f64, len: usize) -> usize {
14686 if n.is_nan() || n <= 0.0 {
14687 0
14688 } else if n >= len as f64 {
14689 len
14690 } else {
14691 n.trunc() as usize
14692 }
14693}
14694
14695/// `ToIntegerOrInfinity(n)` as a code-unit position, or `None` when there can be
14696/// no such unit. `NaN` (an absent argument) is 0; a negative or infinite
14697/// position is out of range — `"abc".charCodeAt(-1)` is `NaN`, not `'a'`.
14698fn unit_pos(n: f64) -> Option<usize> {
14699 if n.is_nan() {
14700 Some(0)
14701 } else if n < 0.0 || !n.is_finite() {
14702 None
14703 } else {
14704 Some(n.trunc() as usize)
14705 }
14706}
14707
14708/// The search argument of `indexOf`/`includes`/`startsWith`/… as code units, so
14709/// the needle is compared in the same alphabet the haystack is indexed by.
14710fn needle_units(args: &[Value]) -> crate::utf16::Units {
14711 crate::utf16::Units::of(&with_host(|h| h.str_of(&arg0(args))))
14712}
14713
14714/// The lowest index `>= from` at which `needle` occurs in `hay`. An empty
14715/// needle matches at `from` itself, as JS specifies.
14716fn search_from(hay: &[u16], needle: &[u16], from: usize) -> Option<usize> {
14717 if needle.is_empty() {
14718 return Some(from.min(hay.len()));
14719 }
14720 if needle.len() > hay.len() {
14721 return None;
14722 }
14723 (from..=hay.len().saturating_sub(needle.len())).find(|&i| &hay[i..i + needle.len()] == needle)
14724}
14725
14726/// The highest index `<= upto` at which `needle` occurs in `hay`.
14727fn search_last(hay: &[u16], needle: &[u16], upto: usize) -> Option<usize> {
14728 if needle.is_empty() {
14729 return Some(upto.min(hay.len()));
14730 }
14731 if needle.len() > hay.len() {
14732 return None;
14733 }
14734 let last = hay.len() - needle.len();
14735 (0..=upto.min(last))
14736 .rev()
14737 .find(|&i| &hay[i..i + needle.len()] == needle)
14738}
14739
14740fn pad(s: &str, args: &[Value], start: bool) -> Result<String, String> {
14741 let target_f = arg_num(args, 0);
14742 let target = if target_f.is_finite() && target_f > 0.0 {
14743 target_f as usize
14744 } else {
14745 0
14746 };
14747 // `targetLength` and the padding both count code units: `'𝒳'.padStart(3,'-')`
14748 // is `'-𝒳'` in node, not `'--𝒳'`.
14749 let cur = crate::utf16::len(s);
14750 if cur >= target {
14751 return Ok(s.to_string());
14752 }
14753 let filler = if args.len() >= 2 {
14754 with_host(|h| h.str_of(&args[1]))
14755 } else {
14756 " ".to_string()
14757 };
14758 if filler.is_empty() {
14759 return Ok(s.to_string());
14760 }
14761 // Checked only AFTER the two short-circuits, which is the order V8 uses:
14762 // measured on node v26.7.0, `'ab'.padStart(2**40, '')` is `'ab'` while
14763 // `'ab'.padStart(536870889, 'x')` is `RangeError: Invalid string length`.
14764 if target_f > host::MAX_STRING_LENGTH as f64 {
14765 return Err(host::invalid_string_length());
14766 }
14767 let need = target - cur;
14768 let fill = crate::utf16::Units::of(&filler);
14769 // The filler repeats and is TRUNCATED to the exact unit count, which can cut
14770 // a surrogate pair — node yields a lone surrogate there, we yield U+FFFD
14771 // (see src/utf16.rs).
14772 let units: Vec<u16> = (0..need)
14773 .filter_map(|i| fill.unit(i % fill.len()))
14774 .collect();
14775 let padding = crate::utf16::to_string_lossy(&units);
14776 Ok(if start {
14777 format!("{padding}{s}")
14778 } else {
14779 format!("{s}{padding}")
14780 })
14781}
14782
14783/// V8's radix rejection, shared by `Number.prototype.toString` and
14784/// `BigInt.prototype.toString` — one string, because they are one message and
14785/// the two sites had drifted apart ("radix must be" vs V8's "radix argument
14786/// must be").
14787const RADIX_RANGE: &str = "toString() radix argument must be between 2 and 36";
14788
14789/// `BigInt.prototype` methods: `toString([radix])`, `valueOf`, `toLocaleString`.
14790fn bigint_method(b: &num_bigint::BigInt, name: &str, args: Vec<Value>) -> Result<Value, String> {
14791 match name {
14792 "toString" => {
14793 let radix = match args.first() {
14794 None | Some(Value::Undef) => 10,
14795 Some(_) => {
14796 let t = arg_num(&args, 0).trunc();
14797 if !(2.0..=36.0).contains(&t) {
14798 return Err(host::range_error(RADIX_RANGE));
14799 }
14800 t as u32
14801 }
14802 };
14803 Ok(new_s(b.to_str_radix(radix)))
14804 }
14805 // `BigInt.prototype.toLocaleString` groups thousands like the Number
14806 // one does — `(1234567n).toLocaleString()` is `1,234,567` in node, and
14807 // returning the bare digits made it the only numeric type that skipped
14808 // grouping. Same en-US-shaped output as `Number.prototype`, formatted
14809 // from the EXACT digits; `options` is honored, `locales` ignored (no
14810 // ICU here).
14811 "toLocaleString" => {
14812 let digits = b.magnitude().to_string();
14813 let neg = b.sign() == num_bigint::Sign::Minus;
14814 let opts = args.get(1).cloned().unwrap_or(Value::Undef);
14815 Ok(new_s(crate::numfmt::to_locale_string(
14816 crate::numfmt::Num::BigInt(&digits, neg),
14817 &opts,
14818 )?))
14819 }
14820 "valueOf" => Ok(with_host(|h| h.new_bigint(b.clone()))),
14821 _ => Err(host::type_error(&format!("{name} is not a function"))),
14822 }
14823}
14824
14825fn number_method(n: f64, name: &str, args: Vec<Value>) -> Result<Value, String> {
14826 let args = coerce_numeric_args(NUMBER_METHOD_NUMERIC_ARGS, name, args)?;
14827 match name {
14828 "toFixed" => {
14829 // ToIntegerOrInfinity: a missing or NaN fractionDigits is 0.
14830 let digits = arg_num(&args, 0);
14831 let digits = if digits.is_nan() { 0.0 } else { digits };
14832 if !(0.0..=100.0).contains(&digits.trunc()) {
14833 return Err(host::range_error(
14834 "toFixed() digits argument must be between 0 and 100",
14835 ));
14836 }
14837 Ok(new_s(to_fixed(n, digits as usize)))
14838 }
14839 "toExponential" => {
14840 // `undefined` (or a missing argument) selects the shortest form.
14841 let f = match args.first() {
14842 None | Some(Value::Undef) => None,
14843 Some(_) => {
14844 let d = arg_num(&args, 0).trunc();
14845 // 21.1.3.2 step 4 answers a non-finite receiver BEFORE the
14846 // range check, so `Infinity.toExponential(-1)` is a string.
14847 if !n.is_finite() {
14848 return Ok(new_s(host::fmt_number(n)));
14849 }
14850 if !(0.0..=100.0).contains(&d) {
14851 return Err(host::range_error(
14852 "toExponential() argument must be between 0 and 100",
14853 ));
14854 }
14855 Some(d as usize)
14856 }
14857 };
14858 Ok(new_s(to_exponential(n, f)))
14859 }
14860 "toString" => {
14861 // An out-of-range radix THROWS; it does not silently fall back to
14862 // base 10. `(1).toString(37)` returned "1" here, so a support probe
14863 // was told every radix worked.
14864 let radix = match args.first() {
14865 None | Some(Value::Undef) => 10,
14866 Some(_) => {
14867 let r = arg_num(&args, 0);
14868 let t = r.trunc();
14869 if !(2.0..=36.0).contains(&t) {
14870 return Err(host::range_error(RADIX_RANGE));
14871 }
14872 t as u32
14873 }
14874 };
14875 if radix == 10 {
14876 Ok(new_s(host::fmt_number(n)))
14877 } else {
14878 Ok(new_s(to_radix(n, radix)))
14879 }
14880 }
14881 "toPrecision" => {
14882 // `undefined` (or a missing argument) behaves like `toString()`.
14883 match args.first() {
14884 None | Some(Value::Undef) => Ok(new_s(host::fmt_number(n))),
14885 Some(_) => {
14886 let p = arg_num(&args, 0).trunc();
14887 // 21.1.3.5 step 4: a non-finite receiver is answered
14888 // before the precision is range-checked.
14889 if !n.is_finite() {
14890 return Ok(new_s(host::fmt_number(n)));
14891 }
14892 if !(1.0..=100.0).contains(&p) {
14893 return Err(host::range_error(
14894 "toPrecision() argument must be between 1 and 100",
14895 ));
14896 }
14897 Ok(new_s(to_precision(n, p as usize)))
14898 }
14899 }
14900 }
14901 // The `options` argument (digit options, grouping, percent/currency
14902 // style) is honored in the en-US shape; see `crate::numfmt`.
14903 "toLocaleString" => {
14904 let opts = args.get(1).cloned().unwrap_or(Value::Undef);
14905 Ok(new_s(crate::numfmt::to_locale_string(
14906 crate::numfmt::Num::Float(n),
14907 &opts,
14908 )?))
14909 }
14910 "valueOf" => Ok(Value::Float(n)),
14911 _ => Err(host::type_error(&format!("{name} is not a function"))),
14912 }
14913}
14914
14915/// `Number.prototype.toFixed(f)`: fixed-point with `f` fractional digits, rounding
14916/// half away from zero on the actual IEEE-754 value (so `(1.005).toFixed(2)` is
14917/// `"1.00"` because 1.005 is really 1.00499…). The sign of a negative input is
14918/// preserved even when the rounded magnitude is zero: `(-0.4).toFixed(0) === "-0"`.
14919///
14920/// The rounding is done on the value's EXACT decimal expansion (Rust's fixed
14921/// formatting is exact), not on `x * 10^f` — the latter loses precision for large
14922/// magnitudes (`(9.999999e20).toFixed(4)` must keep every integer digit).
14923fn to_fixed(n: f64, f: usize) -> String {
14924 if !n.is_finite() {
14925 return host::fmt_number(n);
14926 }
14927 // Spec: for |x| ≥ 10^21, toFixed falls back to ToString(x).
14928 if n.abs() >= 1e21 {
14929 return host::fmt_number(n);
14930 }
14931 let neg = n < 0.0;
14932 // Exact decimal with guard digits past the rounding position; then round the
14933 // digit string half-away-from-zero (nonneg operand ⇒ round-half-up).
14934 let full = format!("{:.*}", f + 25, n.abs());
14935 let mut body = round_decimal_string(&full, f);
14936 if neg {
14937 body.insert(0, '-'); // JS keeps the sign even for "-0" / "-0.00".
14938 }
14939 body
14940}
14941
14942/// Round the exact decimal string `s` (`"int.frac"`, nonnegative) to `f`
14943/// fractional digits, half away from zero, propagating carry across the point.
14944fn round_decimal_string(s: &str, f: usize) -> String {
14945 let (int_part, frac_part) = s.split_once('.').unwrap_or((s, ""));
14946 let mut digits: Vec<u8> = int_part
14947 .bytes()
14948 .chain(frac_part.bytes())
14949 .map(|b| b - b'0')
14950 .collect();
14951 let point = int_part.len(); // digits before the decimal point
14952 let keep = point + f; // number of leading digits to keep
14953
14954 // Round up if the first dropped digit is ≥ 5 (exact-half ⇒ up).
14955 if digits.get(keep).map(|&d| d >= 5).unwrap_or(false) {
14956 let mut i = keep;
14957 loop {
14958 if i == 0 {
14959 digits.insert(0, 1);
14960 // A new leading digit shifts the decimal point right by one.
14961 return assemble_decimal(&digits, point + 1, f);
14962 }
14963 i -= 1;
14964 if digits[i] == 9 {
14965 digits[i] = 0;
14966 } else {
14967 digits[i] += 1;
14968 break;
14969 }
14970 }
14971 }
14972 assemble_decimal(&digits, point, f)
14973}
14974
14975/// Reassemble `digits` into `"int.frac"` keeping `f` fractional digits, given that
14976/// `point` digits precede the decimal point.
14977fn assemble_decimal(digits: &[u8], point: usize, f: usize) -> String {
14978 let int_str: String = digits[..point].iter().map(|d| (d + b'0') as char).collect();
14979 let int_str = int_str.trim_start_matches('0');
14980 let int_str = if int_str.is_empty() { "0" } else { int_str };
14981 if f == 0 {
14982 return int_str.to_string();
14983 }
14984 let frac: String = digits[point..point + f]
14985 .iter()
14986 .map(|d| (d + b'0') as char)
14987 .collect();
14988 format!("{int_str}.{frac}")
14989}
14990
14991/// Round the nonnegative finite `a` to `p` significant decimal digits, half away
14992/// from zero, returning the `p` digits and the decimal exponent `e` such that the
14993/// value is `0.d…d × 10^(e+1)` (i.e. `d.d…d e±e`). Rust's `{:.*e}` rounds half to
14994/// EVEN (`(2.5)` at 1 digit would give "2"), but JS rounds half up ("3"), so the
14995/// exact digits are taken with guard positions and rounded here.
14996fn round_significant(a: f64, p: usize) -> (String, i32) {
14997 let sci = format!("{a:.*e}", p - 1 + 25);
14998 let (mant, exp_str) = sci.split_once('e').expect("LowerExp always has 'e'");
14999 let mut e: i32 = exp_str.parse().expect("LowerExp exponent is an integer");
15000 let all: Vec<u8> = mant
15001 .chars()
15002 .filter(|c| c.is_ascii_digit())
15003 .map(|c| c as u8 - b'0')
15004 .collect();
15005 let mut s: String = all[..p].iter().map(|d| (d + b'0') as char).collect();
15006 if all.get(p).map(|&d| d >= 5).unwrap_or(false) {
15007 // Round the p-digit mantissa up, propagating carry; a carry out of the
15008 // leading digit (`9.99 → 10`) bumps the decimal exponent by one.
15009 let mut d: Vec<u8> = all[..p].to_vec();
15010 let mut i = p;
15011 loop {
15012 if i == 0 {
15013 d.insert(0, 1);
15014 d.truncate(p);
15015 e += 1;
15016 break;
15017 }
15018 i -= 1;
15019 if d[i] == 9 {
15020 d[i] = 0;
15021 } else {
15022 d[i] += 1;
15023 break;
15024 }
15025 }
15026 s = d.iter().map(|x| (x + b'0') as char).collect();
15027 }
15028 (s, e)
15029}
15030
15031/// `Number.prototype.toExponential(f)`: one digit before the point and `f` after,
15032/// with a signed decimal exponent (`(100).toExponential(2) === "1.00e+2"`). With
15033/// `f` omitted, as many digits as uniquely identify the value are used
15034/// (`(123456).toExponential() === "1.23456e+5"`). Rounding is half away from zero
15035/// on the exact value, matching `toPrecision`.
15036fn to_exponential(n: f64, f: Option<usize>) -> String {
15037 if !n.is_finite() {
15038 return host::fmt_number(n);
15039 }
15040 let neg = n < 0.0;
15041 let a = n.abs();
15042 let (s, e) = if a == 0.0 {
15043 // Zero has no significant digits: emit "0" padded to the requested width.
15044 ("0".repeat(f.unwrap_or(0) + 1), 0)
15045 } else {
15046 match f {
15047 Some(f) => round_significant(a, f + 1),
15048 None => {
15049 let (digits, exp) = host::shortest_digits(a);
15050 let trimmed = digits.trim_end_matches('0');
15051 let digits = if trimmed.is_empty() { "0" } else { trimmed };
15052 (digits.to_string(), exp)
15053 }
15054 }
15055 };
15056 let sign = if e >= 0 { '+' } else { '-' };
15057 let mag = e.abs();
15058 let body = if s.len() == 1 {
15059 format!("{s}e{sign}{mag}")
15060 } else {
15061 format!("{}.{}e{sign}{mag}", &s[..1], &s[1..])
15062 };
15063 if neg {
15064 format!("-{body}")
15065 } else {
15066 body
15067 }
15068}
15069
15070/// `Number.prototype.toPrecision(p)`: `p` significant digits, switching to
15071/// exponential form when the decimal exponent `e` satisfies `e < -6` or `e ≥ p`
15072/// (ECMAScript Number.prototype.toPrecision). Trailing zeros are significant and
15073/// retained (`(100).toPrecision(5) === "100.00"`).
15074fn to_precision(n: f64, p: usize) -> String {
15075 if !n.is_finite() {
15076 return host::fmt_number(n);
15077 }
15078 if n == 0.0 {
15079 return if p == 1 {
15080 "0".into()
15081 } else {
15082 format!("0.{}", "0".repeat(p - 1))
15083 };
15084 }
15085 let neg = n < 0.0;
15086 let (s, e) = round_significant(n.abs(), p);
15087 let pp = p as i32;
15088
15089 let body = if e < -6 || e >= pp {
15090 // Exponential: first digit, optional '.rest', signed exponent.
15091 let sign = if e >= 0 { '+' } else { '-' };
15092 let mag = e.abs();
15093 if p == 1 {
15094 format!("{s}e{sign}{mag}")
15095 } else {
15096 format!("{}.{}e{sign}{mag}", &s[..1], &s[1..])
15097 }
15098 } else if e >= 0 {
15099 // e in 0..p-1: (e+1) integer digits, then any remaining as fraction.
15100 let ip = (e + 1) as usize;
15101 if ip == p {
15102 s
15103 } else {
15104 format!("{}.{}", &s[..ip], &s[ip..])
15105 }
15106 } else {
15107 // -6 ≤ e < 0: "0." then (−e−1) zeros then all p digits.
15108 format!("0.{}{}", "0".repeat((-e - 1) as usize), s)
15109 };
15110 if neg {
15111 format!("-{body}")
15112 } else {
15113 body
15114 }
15115}
15116
15117/// `Number.prototype.toString(radix)` for radix 2..=36 (radix 10 goes through
15118/// `fmt_number`). Faithful port of V8's `DoubleToRadixCString`: the integer part
15119/// is emitted exact, and fractional digits are produced up to the input double's
15120/// precision (terminating via a ULP-sized `delta`), with round-half-to-even and
15121/// carry-over back into already-written digits (and into the integer part).
15122fn to_radix(n: f64, radix: u32) -> String {
15123 if !n.is_finite() {
15124 return host::fmt_number(n);
15125 }
15126 let digits = b"0123456789abcdefghijklmnopqrstuvwxyz";
15127 let rf = radix as f64;
15128 let neg = n < 0.0;
15129 let value = n.abs();
15130
15131 let mut integer = value.floor();
15132 let mut fraction = value - integer;
15133
15134 // Fraction digits, most-significant first.
15135 let mut frac: Vec<u8> = Vec::new();
15136 // Only compute fractional digits down to the input double's precision.
15137 let mut delta = 0.5 * (next_up(value) - value);
15138 delta = delta.max(next_up(0.0));
15139 if fraction >= delta {
15140 loop {
15141 // Shift up by one digit.
15142 fraction *= rf;
15143 delta *= rf;
15144 let digit = fraction as usize;
15145 frac.push(digits[digit]);
15146 fraction -= digit as f64;
15147 // Round to even.
15148 if (fraction > 0.5 || (fraction == 0.5 && (digit & 1) == 1)) && fraction + delta > 1.0 {
15149 // Carry-over: back-trace already-written fraction digits.
15150 loop {
15151 match frac.pop() {
15152 None => {
15153 // Carried past the point into the integer part.
15154 integer += 1.0;
15155 break;
15156 }
15157 Some(c) => {
15158 let d = if c > b'9' {
15159 (c - b'a' + 10) as u32
15160 } else {
15161 (c - b'0') as u32
15162 };
15163 if d + 1 < radix {
15164 frac.push(digits[(d + 1) as usize]);
15165 break;
15166 }
15167 // digit was radix-1: drop it and keep carrying.
15168 }
15169 }
15170 }
15171 break;
15172 }
15173 if fraction < delta {
15174 break;
15175 }
15176 }
15177 }
15178
15179 // Integer digits, least-significant first (reversed at the end).
15180 let mut int_out: Vec<u8> = Vec::new();
15181 // For magnitudes ≥ 2^53, `fmod` loses low bits: pre-fill trailing zeros.
15182 while v8_exponent(integer / rf) > 0 {
15183 integer /= rf;
15184 int_out.push(b'0');
15185 }
15186 loop {
15187 let remainder = integer % rf;
15188 int_out.push(digits[remainder as usize]);
15189 integer = (integer - remainder) / rf;
15190 if integer <= 0.0 {
15191 break;
15192 }
15193 }
15194 int_out.reverse();
15195
15196 let mut out: Vec<u8> = Vec::new();
15197 if neg {
15198 out.push(b'-');
15199 }
15200 out.extend_from_slice(&int_out);
15201 if !frac.is_empty() {
15202 out.push(b'.');
15203 out.extend_from_slice(&frac);
15204 }
15205 String::from_utf8(out).unwrap()
15206}
15207
15208/// Next representable f64 above `x` (`x` finite, `x ≥ 0`) — V8's `NextDouble`.
15209fn next_up(x: f64) -> f64 {
15210 f64::from_bits(x.to_bits() + 1)
15211}
15212
15213/// V8's `Double::Exponent`: the binary exponent of the significand-scaled value
15214/// (`> 0` iff |x| ≥ 2^53). Used to detect integers past `fmod`'s exact range.
15215fn v8_exponent(x: f64) -> i32 {
15216 let biased = ((x.to_bits() >> 52) & 0x7ff) as i32;
15217 if biased == 0 {
15218 -1074 // denormal
15219 } else {
15220 biased - 1075
15221 }
15222}
15223
15224// ══ Map / Set / Symbol / generator methods ═══════════════════════════════════
15225
15226/// `Map.prototype.set` step 6 and `Set.prototype.add` step 4: a key of `-0` is
15227/// STORED as `+0`. `map_key` already treats the two as one key (SameValueZero),
15228/// but the value kept alongside it is what iteration and `console.log` report,
15229/// and node shows `0` there — `new Map().set(-0, 1)` renders `Map(1) { 0 => 1 }`.
15230fn normalize_zero_key(v: Value) -> Value {
15231 match v {
15232 Value::Float(f) if f == 0.0 && f.is_sign_negative() => Value::Float(0.0),
15233 other => other,
15234 }
15235}
15236
15237fn map_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
15238 match name {
15239 "get" => {
15240 let key = with_host(|h| host::map_key(h, &arg0(&args)));
15241 Ok(with_host(|h| match h.get(recv) {
15242 Some(JsObj::Map { entries, .. }) => entries
15243 .get(&key)
15244 .map(|(_, v)| v.clone())
15245 .unwrap_or(Value::Undef),
15246 _ => Value::Undef,
15247 }))
15248 }
15249 "set" => {
15250 let kv = normalize_zero_key(arg0(&args));
15251 let vv = args.get(1).cloned().unwrap_or(Value::Undef);
15252 reject_non_object_weak_key(recv, &kv, "WeakMap")?;
15253 let key = with_host(|h| host::map_key(h, &kv));
15254 with_host(|h| {
15255 if let Some(JsObj::Map { entries, .. }) = h.get_mut(recv) {
15256 entries.insert(key, (kv, vv));
15257 }
15258 });
15259 Ok(recv.clone())
15260 }
15261 "has" => {
15262 let key = with_host(|h| host::map_key(h, &arg0(&args)));
15263 Ok(Value::Bool(with_host(
15264 |h| matches!(h.get(recv), Some(JsObj::Map { entries, .. }) if entries.contains_key(&key)),
15265 )))
15266 }
15267 "delete" => {
15268 let key = with_host(|h| host::map_key(h, &arg0(&args)));
15269 Ok(Value::Bool(with_host(|h| match h.get_mut(recv) {
15270 Some(JsObj::Map { entries, .. }) => entries.shift_remove(&key).is_some(),
15271 _ => false,
15272 })))
15273 }
15274 "clear" => {
15275 with_host(|h| {
15276 if let Some(JsObj::Map { entries, .. }) = h.get_mut(recv) {
15277 entries.clear();
15278 }
15279 });
15280 Ok(Value::Undef)
15281 }
15282 "forEach" => {
15283 let cb = arg0(&args);
15284 let pairs: Vec<(Value, Value)> = with_host(|h| match h.get(recv) {
15285 Some(JsObj::Map { entries, .. }) => entries.values().cloned().collect(),
15286 _ => Vec::new(),
15287 });
15288 for (k, v) in pairs {
15289 host::invoke(&cb, vec![v, k, recv.clone()], this_arg(&args, 1))?;
15290 }
15291 Ok(Value::Undef)
15292 }
15293 // LIVE, not a snapshot: an entry added during iteration is visited and
15294 // one deleted before it is reached is not.
15295 "keys" | "values" | "entries" | "@@iterator" => Ok(collection_iterator(
15296 recv,
15297 if name == "@@iterator" {
15298 "entries"
15299 } else {
15300 name
15301 },
15302 )),
15303 _ => Err(host::type_error(&format!("map.{name} is not a function"))),
15304 }
15305}
15306
15307/// A weak collection can only hold objects (and unregistered symbols) — a
15308/// primitive key is a `TypeError`, which is how packages probe for weak support.
15309fn reject_non_object_weak_key(recv: &Value, key: &Value, kind: &str) -> Result<(), String> {
15310 let weak = with_host(|h| {
15311 matches!(
15312 h.get(recv),
15313 Some(JsObj::Map { weak: true, .. }) | Some(JsObj::Set { weak: true, .. })
15314 )
15315 });
15316 if !weak {
15317 return Ok(());
15318 }
15319 let is_object = with_host(|h| match key {
15320 Value::Obj(_) => !h.is_null(key) && h.as_str(key).is_none() && h.as_bigint(key).is_none(),
15321 _ => false,
15322 });
15323 if is_object {
15324 return Ok(());
15325 }
15326 Err(host::type_error(if kind == "WeakMap" {
15327 "Invalid value used as weak map key"
15328 } else {
15329 "Invalid value used in weak set"
15330 }))
15331}
15332
15333/// A `Set`-like operand of the ES2025 set methods — 24.2.1.2 `GetSetRecord`.
15334///
15335/// The seven set operations do NOT require a real `Set` on the right-hand side:
15336/// anything with a numeric `size` and callable `has`/`keys` participates, which
15337/// is what lets a `Map`'s key view or a user-written set stand in. The reads
15338/// happen in this order (`size`, `has`, `keys`) and each failure has its own
15339/// diagnostic, so a bad operand reports which field was wrong rather than
15340/// failing later inside the iteration.
15341struct SetRecord {
15342 obj: Value,
15343 /// `size` truncated toward zero, as the spec's `intSize` is; the fractional
15344 /// part is dropped BEFORE the negative check, so `size: -0.5` truncates to
15345 /// `-0` and is accepted while `-1.5` reports `'-1' is an invalid size`.
15346 size: f64,
15347 has: Value,
15348 keys: Value,
15349}
15350
15351fn get_set_record(other: &Value, method: &str) -> Result<SetRecord, String> {
15352 if !with_host(|h| is_object_like(h, other)) {
15353 return Err(host::type_error(&format!(
15354 "Set.prototype.{method} argument must be an object"
15355 )));
15356 }
15357 let raw = get_property(other, "size")?;
15358 let num = host::to_number_value(&raw)?;
15359 if num.is_nan() {
15360 return Err(host::type_error("The .size property is NaN"));
15361 }
15362 let size = num.trunc();
15363 if size < 0.0 {
15364 return Err(host::range_error(&format!("'{size}' is an invalid size")));
15365 }
15366 let has = get_property(other, "has")?;
15367 if !with_host(|h| host::is_callable(h, &has)) {
15368 return Err(host::type_error("string \"has\" is not a function"));
15369 }
15370 let keys = get_property(other, "keys")?;
15371 if !with_host(|h| host::is_callable(h, &keys)) {
15372 return Err(host::type_error("string \"keys\" is not a function"));
15373 }
15374 Ok(SetRecord {
15375 obj: other.clone(),
15376 size,
15377 has,
15378 keys,
15379 })
15380}
15381
15382impl SetRecord {
15383 /// `Call(has, obj, [v])`, coerced to a boolean the way the spec's
15384 /// `ToBoolean(Call(...))` is — a set-like may answer with anything truthy.
15385 fn has(&self, v: &Value) -> Result<bool, String> {
15386 let r = host::invoke(&self.has, vec![v.clone()], Some(self.obj.clone()))?;
15387 Ok(with_host(|h| h.truthy(&r)))
15388 }
15389
15390 /// The operand's elements, drained from the iterator its `keys` method
15391 /// returns. A non-object result is the spec's `Result of the keys method is
15392 /// not an object`, reported before anything is iterated.
15393 fn keys(&self) -> Result<Vec<Value>, String> {
15394 let it = host::invoke(&self.keys, Vec::new(), Some(self.obj.clone()))?;
15395 if !with_host(|h| is_object_like(h, &it)) {
15396 return Err(host::type_error(
15397 "Result of the keys method is not an object",
15398 ));
15399 }
15400 host::drain_iterator(&it)
15401 }
15402}
15403
15404/// The receiver of a set operation must be a real (non-weak) `Set`: these seven
15405/// methods read `[[SetData]]` directly, so a look-alike cannot stand in on the
15406/// LEFT even though it can on the right.
15407fn require_set_receiver(recv: &Value, method: &str) -> Result<(), String> {
15408 if with_host(|h| matches!(h.get(recv), Some(JsObj::Set { weak: false, .. }))) {
15409 return Ok(());
15410 }
15411 Err(host::type_error(&format!(
15412 "Method Set.prototype.{method} called on incompatible receiver {}",
15413 with_host(|h| object_tag(h, recv))
15414 )))
15415}
15416
15417/// The receiver's elements, READ AT THE POINT THE SPEC READS THEM.
15418///
15419/// Every one of these operations copies `[[SetData]]` *after* it has touched
15420/// the operand — `union` and `symmetricDifference` call the operand's `keys`
15421/// first — so a `keys` (or a `has`) that mutates the receiver is visible in the
15422/// result. Snapshotting the receiver up front instead dropped such an element:
15423/// node's `s.union({ keys(){ s.add(99); … } })` contains `99`.
15424fn set_values(recv: &Value) -> Vec<Value> {
15425 with_host(|h| match h.get(recv) {
15426 Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
15427 _ => Vec::new(),
15428 })
15429}
15430
15431fn set_size(recv: &Value) -> f64 {
15432 with_host(|h| match h.get(recv) {
15433 Some(JsObj::Set { entries, .. }) => entries.len() as f64,
15434 _ => 0.0,
15435 })
15436}
15437
15438/// A fresh, ordinary `Set`. The set operations are NOT species-aware: on node
15439/// `class S extends Set {}`, `new S([1]).union(other).constructor` is `Set`.
15440fn new_set(items: Vec<Value>) -> Result<Value, String> {
15441 let s = with_host(|h| {
15442 h.alloc(JsObj::Set {
15443 entries: IndexMap::new(),
15444 weak: false,
15445 })
15446 });
15447 for v in items {
15448 set_method(&s, "add", vec![v])?;
15449 }
15450 Ok(s)
15451}
15452
15453fn set_contains(s: &Value, v: &Value) -> bool {
15454 let key = with_host(|h| host::map_key(h, v));
15455 with_host(
15456 |h| matches!(h.get(s), Some(JsObj::Set { entries, .. }) if entries.contains_key(&key)),
15457 )
15458}
15459
15460/// The seven ES2025 set operations (24.2.4.3, .8, .5, .16, .10, .12, .7).
15461///
15462/// Each one branches on the two sizes and iterates the SMALLER side — not an
15463/// optimization but observable behaviour: which side is walked decides the
15464/// result's order and whether the operand's `has` or its `keys` is the method
15465/// that runs. `intersection` of a 3-element receiver with a 2-element operand
15466/// yields the operand's order, and its `keys` (never its `has`) is called.
15467fn set_operation(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
15468 require_set_receiver(recv, name)?;
15469 let other = get_set_record(&arg0(&args), name)?;
15470 let my_size = set_size(recv);
15471 match name {
15472 "union" => {
15473 let keys = other.keys()?;
15474 let mut out = set_values(recv);
15475 out.extend(keys);
15476 new_set(out)
15477 }
15478 "intersection" => {
15479 let mut out = Vec::new();
15480 if my_size <= other.size {
15481 for v in set_values(recv) {
15482 if other.has(&v)? {
15483 out.push(v);
15484 }
15485 }
15486 } else {
15487 for k in other.keys()? {
15488 if set_contains(recv, &k) {
15489 out.push(k);
15490 }
15491 }
15492 }
15493 new_set(out)
15494 }
15495 "difference" => {
15496 if my_size <= other.size {
15497 let mut out = Vec::new();
15498 for v in set_values(recv) {
15499 if !other.has(&v)? {
15500 out.push(v);
15501 }
15502 }
15503 return new_set(out);
15504 }
15505 let out = new_set(set_values(recv))?;
15506 for k in other.keys()? {
15507 set_method(&out, "delete", vec![k])?;
15508 }
15509 Ok(out)
15510 }
15511 "symmetricDifference" => {
15512 // The operand is drained FIRST — the spec takes the iterator before
15513 // it copies `[[SetData]]`, so a `keys` that mutates the receiver is
15514 // reflected in the result.
15515 let keys = other.keys()?;
15516 let out = new_set(set_values(recv))?;
15517 for k in keys {
15518 if set_contains(recv, &k) {
15519 set_method(&out, "delete", vec![k])?;
15520 } else {
15521 set_method(&out, "add", vec![k])?;
15522 }
15523 }
15524 Ok(out)
15525 }
15526 "isSubsetOf" => {
15527 if my_size > other.size {
15528 return Ok(Value::Bool(false));
15529 }
15530 for v in set_values(recv) {
15531 if !other.has(&v)? {
15532 return Ok(Value::Bool(false));
15533 }
15534 }
15535 Ok(Value::Bool(true))
15536 }
15537 "isSupersetOf" => {
15538 if my_size < other.size {
15539 return Ok(Value::Bool(false));
15540 }
15541 for k in other.keys()? {
15542 if !set_contains(recv, &k) {
15543 return Ok(Value::Bool(false));
15544 }
15545 }
15546 Ok(Value::Bool(true))
15547 }
15548 "isDisjointFrom" => {
15549 if my_size <= other.size {
15550 for v in set_values(recv) {
15551 if other.has(&v)? {
15552 return Ok(Value::Bool(false));
15553 }
15554 }
15555 } else {
15556 for k in other.keys()? {
15557 if set_contains(recv, &k) {
15558 return Ok(Value::Bool(false));
15559 }
15560 }
15561 }
15562 Ok(Value::Bool(true))
15563 }
15564 _ => Err(host::type_error(&format!("set.{name} is not a function"))),
15565 }
15566}
15567
15568fn set_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
15569 match name {
15570 "add" => {
15571 let vv = normalize_zero_key(arg0(&args));
15572 reject_non_object_weak_key(recv, &vv, "WeakSet")?;
15573 let key = with_host(|h| host::map_key(h, &vv));
15574 with_host(|h| {
15575 if let Some(JsObj::Set { entries, .. }) = h.get_mut(recv) {
15576 entries.insert(key, vv);
15577 }
15578 });
15579 Ok(recv.clone())
15580 }
15581 "has" => {
15582 let key = with_host(|h| host::map_key(h, &arg0(&args)));
15583 Ok(Value::Bool(with_host(
15584 |h| matches!(h.get(recv), Some(JsObj::Set { entries, .. }) if entries.contains_key(&key)),
15585 )))
15586 }
15587 "delete" => {
15588 let key = with_host(|h| host::map_key(h, &arg0(&args)));
15589 Ok(Value::Bool(with_host(|h| match h.get_mut(recv) {
15590 Some(JsObj::Set { entries, .. }) => entries.shift_remove(&key).is_some(),
15591 _ => false,
15592 })))
15593 }
15594 "clear" => {
15595 with_host(|h| {
15596 if let Some(JsObj::Set { entries, .. }) = h.get_mut(recv) {
15597 entries.clear();
15598 }
15599 });
15600 Ok(Value::Undef)
15601 }
15602 "forEach" => {
15603 let cb = arg0(&args);
15604 let vals: Vec<Value> = with_host(|h| match h.get(recv) {
15605 Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
15606 _ => Vec::new(),
15607 });
15608 for v in vals {
15609 host::invoke(&cb, vec![v.clone(), v, recv.clone()], this_arg(&args, 1))?;
15610 }
15611 Ok(Value::Undef)
15612 }
15613 "union"
15614 | "intersection"
15615 | "difference"
15616 | "symmetricDifference"
15617 | "isSubsetOf"
15618 | "isSupersetOf"
15619 | "isDisjointFrom" => set_operation(recv, name, args),
15620 // LIVE, as for `Map`. A Set's `keys` and `values` are the same thing.
15621 "keys" | "values" | "entries" | "@@iterator" => Ok(collection_iterator(
15622 recv,
15623 if name == "entries" {
15624 "entries"
15625 } else {
15626 "values"
15627 },
15628 )),
15629 _ => Err(host::type_error(&format!("set.{name} is not a function"))),
15630 }
15631}
15632
15633fn generator_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
15634 // A generator IS its own iterator: both symbol forms return the receiver.
15635 if matches!(name, "@@iterator" | "@@asyncIterator") {
15636 return Ok(recv.clone());
15637 }
15638 // An `async function*` object's methods return PROMISES of the record, and
15639 // its body has to be driven through the await-aware stepper (a plain
15640 // `gen_resume` would surface an internal `await` suspension as a bogus yield).
15641 if host::is_async_generator(recv) {
15642 // All three go through `[[AsyncGeneratorQueue]]` (ECMA-262 27.6.3.6):
15643 // `.return`/`.throw` must wait behind a `.next()` that is still
15644 // suspended on an internal `await`, or that `.next()` would report
15645 // `{done: true}` for a value the body had not yet reached. An uncaught
15646 // `.throw(e)` rejects the returned promise; it does not throw here.
15647 return match name {
15648 "next" => Ok(host::async_gen_enqueue(
15649 recv,
15650 host::GenReq::Next(arg0(&args)),
15651 )),
15652 "return" => Ok(host::async_gen_enqueue(
15653 recv,
15654 host::GenReq::Return(arg0(&args)),
15655 )),
15656 "throw" => Ok(host::async_gen_enqueue(
15657 recv,
15658 host::GenReq::Throw(arg0(&args)),
15659 )),
15660 "@@asyncIterator" => Ok(recv.clone()),
15661 _ => Err(host::type_error(&format!(
15662 "asyncGenerator.{name} is not a function"
15663 ))),
15664 };
15665 }
15666 match name {
15667 "next" => {
15668 let send = arg0(&args);
15669 match host::gen_resume(recv, send)? {
15670 host::GenStep::Yield(v) => Ok(iter_result(v, false)),
15671 host::GenStep::Done(v) => Ok(iter_result(v, true)),
15672 }
15673 }
15674 "return" => {
15675 // Resume with an injected return so any pending `finally` runs; the
15676 // completion may itself be a `finally` yield (not-done) or the value.
15677 match host::gen_return(recv, arg0(&args))? {
15678 host::GenStep::Yield(v) => Ok(iter_result(v, false)),
15679 host::GenStep::Done(v) => Ok(iter_result(v, true)),
15680 }
15681 }
15682 "throw" => {
15683 // Inject a throw at the suspension point: an enclosing `try/catch` in
15684 // the body can handle it (and any `finally` runs); otherwise it
15685 // propagates to the caller.
15686 match host::gen_throw(recv, arg0(&args))? {
15687 host::GenStep::Yield(v) => Ok(iter_result(v, false)),
15688 host::GenStep::Done(v) => Ok(iter_result(v, true)),
15689 }
15690 }
15691 _ => Err(host::type_error(&format!(
15692 "generator.{name} is not a function"
15693 ))),
15694 }
15695}
15696
15697/// A `{ value, done }` iterator-result object.
15698fn iter_result(value: Value, done: bool) -> Value {
15699 with_host(|h| {
15700 let mut m: IndexMap<String, Value> = IndexMap::new();
15701 m.insert("value".into(), value);
15702 m.insert("done".into(), Value::Bool(done));
15703 h.new_object(m)
15704 })
15705}
15706
15707/// A live iterator over array `arr` — what `keys()`, `values()`, `entries()`
15708/// and `Symbol.iterator` return, and what a `for-of` over an array steps.
15709pub(crate) fn array_iterator(arr: &Value, kind: host::ArrayIterKind) -> Value {
15710 with_host(|h| {
15711 h.alloc_iter(JsObj::Iter {
15712 items: Vec::new(),
15713 idx: 0,
15714 array: Some((arr.clone(), kind)),
15715 brand: None,
15716 })
15717 })
15718}
15719
15720/// One step of a `JsObj::Iter`: `None` when `it` is not one, `Some(None)` once
15721/// it is exhausted, otherwise the next value.
15722///
15723/// An array iterator reads the array at every step (23.1.5.1
15724/// `%ArrayIteratorPrototype%.next`): the length is re-read, so an element
15725/// pushed during a `for-of` is visited and one popped is not, and the element
15726/// is read as `a[i]` reads it — an accessor runs, a hole reads through the
15727/// prototype. Once it reports done it stays done, even if the array grows.
15728///
15729/// The array may be any object — `Array.prototype.values.call(arrayLike)`, or a
15730/// `for-of` over a Proxy of an array. For anything but a plain Array the step is
15731/// the spec's own: `LengthOfArrayLike(O)` read afresh, then `Get(O, i)`, both
15732/// through the object's `[[Get]]`, and a throw from either propagates.
15733pub(crate) fn iter_step(it: &Value) -> Option<Result<Option<Value>, String>> {
15734 use host::ArrayIterKind;
15735 // One host borrow for the common case — a snapshot, or an array slot that
15736 // is neither a hole nor an accessor. `Err` carries what only `[[Get]]` can
15737 // read: the array, the kind and the index.
15738 let step = with_host(|h| {
15739 let (arr, kind, i) = match h.get_mut(it) {
15740 Some(JsObj::Iter {
15741 items,
15742 idx,
15743 array: None,
15744 ..
15745 }) => {
15746 let v = items.get(*idx).cloned();
15747 if v.is_some() {
15748 *idx += 1;
15749 }
15750 return Some(Ok(v));
15751 }
15752 Some(JsObj::Iter {
15753 idx,
15754 array: Some((arr, kind)),
15755 ..
15756 }) => (arr.clone(), *kind, *idx),
15757 _ => return None,
15758 };
15759 // `usize::MAX` marks an iterator that has already reported done, and
15760 // it stays done even if the array grows.
15761 if i == usize::MAX {
15762 return Some(Ok(None));
15763 }
15764 let len = match h.get(&arr) {
15765 Some(JsObj::Array(items)) => items.len(),
15766 _ => return Some(Err((arr, kind, i, true))),
15767 };
15768 let done = i >= len;
15769 if let Some(JsObj::Iter { idx, .. }) = h.get_mut(it) {
15770 *idx = if done { usize::MAX } else { i + 1 };
15771 }
15772 if done {
15773 return Some(Ok(None));
15774 }
15775 let key = Value::Float(i as f64);
15776 let slot = match (kind, h.get(&arr)) {
15777 (ArrayIterKind::Keys, _) => return Some(Ok(Some(key))),
15778 (_, Some(JsObj::Array(items)))
15779 if !h.is_hole(&arr, i) && h.own_accessor_keys(&arr).is_empty() =>
15780 {
15781 items[i].clone()
15782 }
15783 _ => return Some(Err((arr, kind, i, false))),
15784 };
15785 Some(Ok(Some(match kind {
15786 ArrayIterKind::Entries => h.new_array(vec![key, slot]),
15787 _ => slot,
15788 })))
15789 })?;
15790 let (arr, kind, i, generic) = match step {
15791 Ok(step) => return Some(Ok(step)),
15792 Err(slow) => slow,
15793 };
15794 Some(array_iter_slow_step(it, &arr, kind, i, generic))
15795}
15796
15797/// The `[[Get]]`-driven half of [`iter_step`]: an element that is a hole or an
15798/// accessor, or (`generic`) a receiver that is not a plain Array, whose length
15799/// is then re-read and compared here rather than off the backing vector.
15800fn array_iter_slow_step(
15801 it: &Value,
15802 arr: &Value,
15803 kind: host::ArrayIterKind,
15804 i: usize,
15805 generic: bool,
15806) -> Result<Option<Value>, String> {
15807 use host::ArrayIterKind;
15808 if generic {
15809 let len = length_of_array_like(arr)?;
15810 let done = i >= len;
15811 with_host(|h| {
15812 if let Some(JsObj::Iter { idx, .. }) = h.get_mut(it) {
15813 *idx = if done { usize::MAX } else { i + 1 };
15814 }
15815 });
15816 if done {
15817 return Ok(None);
15818 }
15819 if kind == ArrayIterKind::Keys {
15820 return Ok(Some(Value::Float(i as f64)));
15821 }
15822 }
15823 let value = get_property(arr, &i.to_string())?;
15824 Ok(Some(match kind {
15825 ArrayIterKind::Entries => with_host(|h| h.new_array(vec![Value::Float(i as f64), value])),
15826 _ => value,
15827 }))
15828}
15829
15830/// `LengthOfArrayLike(O)` (7.3.18): `ToLength(Get(O, "length"))`, the
15831/// `ToNumber` running any user `valueOf`, a throw from either propagating.
15832pub(crate) fn length_of_array_like(o: &Value) -> Result<usize, String> {
15833 let len = get_property(o, "length")?;
15834 let n = host::to_number_value(&len)?;
15835 // ToLength: ToIntegerOrInfinity, clamped to [0, 2^53 - 1].
15836 Ok(if n.is_nan() || n <= 0.0 {
15837 0
15838 } else {
15839 n.trunc().min(9007199254740991.0) as usize
15840 })
15841}
15842
15843/// Built-in iterator object (`arr.values()`, `arr[Symbol.iterator]()`): a
15844/// cursor over a snapshot, or live over an array ([`iter_step`]).
15845fn iter_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
15846 match name {
15847 "next" => Ok(match iter_step(recv).transpose()?.flatten() {
15848 Some(v) => iter_result(v, false),
15849 None => iter_result(Value::Undef, true),
15850 }),
15851 "return" => {
15852 // Exhaust the cursor and report done.
15853 with_host(|h| {
15854 if let Some(JsObj::Iter {
15855 items, idx, array, ..
15856 }) = h.get_mut(recv)
15857 {
15858 *idx = if array.is_some() {
15859 usize::MAX
15860 } else {
15861 items.len()
15862 };
15863 }
15864 });
15865 Ok(iter_result(arg0(&args), true))
15866 }
15867 // An iterator is its own iterable.
15868 "@@iterator" => Ok(recv.clone()),
15869 _ => Err(host::type_error(&format!(
15870 "iterator.{name} is not a function"
15871 ))),
15872 }
15873}
15874
15875fn symbol_method(recv: &Value, name: &str, _args: Vec<Value>) -> Result<Value, String> {
15876 match name {
15877 "toString" => Ok(with_host(|h| {
15878 let s = h.str_of(recv);
15879 h.new_str(s)
15880 })),
15881 // 20.4.3.5: `Symbol.prototype[@@toPrimitive]` returns the symbol
15882 // itself for EVERY hint — it ignores its argument. That is what makes
15883 // `sym + ''` a TypeError rather than a concatenation: the conversion
15884 // succeeds and hands back a symbol, and it is `+` that then rejects it.
15885 "@@toPrimitive" | "valueOf" => Ok(recv.clone()),
15886 _ => Err(host::type_error(&format!(
15887 "symbol.{name} is not a function"
15888 ))),
15889 }
15890}
15891
15892// ══ Object.* prototype helpers, `in`, deep clone ═════════════════════════════
15893
15894fn object_create(args: Vec<Value>) -> Result<Value, String> {
15895 let proto = arg0(&args);
15896 // 20.1.2.2 step 1: the prototype must be an Object or exactly `null`.
15897 // `undefined` is NOT accepted — measured on node v26.7.0,
15898 // `Object.create(undefined)` is
15899 // `TypeError: Object prototype may only be an Object or null: undefined`,
15900 // where node-js quietly built a normal object.
15901 reject_bad_prototype(&proto)?;
15902 let obj = with_host(|h| h.new_object(IndexMap::new()));
15903 // `set_proto` records a null proto as an explicit null-prototype object.
15904 with_host(|h| h.set_proto(&obj, proto));
15905 // Optional second arg: a property-descriptor map.
15906 if let Some(descs) = args.get(1).filter(|d| !matches!(d, Value::Undef)) {
15907 let entries: Vec<(String, Value)> = with_host(|h| match h.get(descs) {
15908 Some(JsObj::Object(p)) => p.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
15909 _ => Vec::new(),
15910 });
15911 for (k, d) in entries {
15912 apply_descriptor(&obj, &k, &d)?;
15913 }
15914 }
15915 Ok(obj)
15916}
15917
15918/// The enumerable method names of a builtin `<Ctor>.prototype` namespace that
15919/// supports being copied via `mixin`/`getOwnPropertyNames`. Currently only
15920/// `EventEmitter.prototype` (the one express mixes onto its app function).
15921/// The own property names of `<Ctor>.prototype`, and whether each is
15922/// enumerable, from the generated [`crate::arity::PROTO_MEMBERS`] table.
15923///
15924/// `Object.getOwnPropertyNames(Map.prototype)` answered `[]` for every
15925/// intrinsic — the members are reachable by NAME through the `@proto:` thunks
15926/// but were not enumerable, so feature detection that walks a prototype found
15927/// nothing there. The table is read from the reference engine rather than
15928/// derived from the arity table because the arity table holds functions only:
15929/// `Map.prototype.size`, `RegExp.prototype.source` and the twelve
15930/// `URL.prototype` components are accessors.
15931fn intrinsic_proto_members(ns: &str) -> Option<&'static [&'static str]> {
15932 let ctor = ns.strip_suffix(".prototype")?;
15933 crate::arity::PROTO_MEMBERS
15934 .binary_search_by(|(k, _)| (*k).cmp(ctor))
15935 .ok()
15936 .map(|i| crate::arity::PROTO_MEMBERS[i].1)
15937}
15938
15939fn builtin_proto_method_names(ns: &str) -> Option<&'static [&'static str]> {
15940 match ns {
15941 "EventEmitter.prototype" => Some(crate::stdlib::events::METHODS),
15942 _ => None,
15943 }
15944}
15945
15946/// The own SYMBOL-keyed property keys of `v` as symbol values. A Proxy's come
15947/// from its `ownKeys` trap (the symbol half of the same list the string keys are
15948/// filtered out of); every other receiver answers from its property map.
15949fn proxy_or_own_symbol_keys(v: &Value) -> Result<Vec<Value>, String> {
15950 if let Some(keys) = crate::proxy::own_keys(v)? {
15951 return Ok(keys
15952 .iter()
15953 .filter(|k| host::is_symbol_key(k))
15954 .map(|k| crate::proxy::key_value(k))
15955 .collect());
15956 }
15957 // An intrinsic prototype's symbol-keyed members come from the generated
15958 // table, which is the only record of them: they own no map entry, so
15959 // `Object.getOwnPropertySymbols(Array.prototype)` was `[]` where node
15960 // reports `Symbol.iterator` and `Symbol.unscopables`.
15961 if let Some(ns) = intrinsic_proto_of(v).map(|c| format!("{c}.prototype")) {
15962 if let Some(members) = intrinsic_proto_members(&ns) {
15963 return Ok(with_host(|h| {
15964 members
15965 .iter()
15966 .filter_map(|m| m.strip_prefix('+').unwrap_or(m).strip_prefix("@@"))
15967 .map(|name| h.well_known_symbol(name))
15968 .collect()
15969 }));
15970 }
15971 }
15972 // A core function's measured symbol-keyed properties
15973 // (`os.freemem[Symbol.toPrimitive]`, `setTimeout[util.promisify.custom]`),
15974 // which it owns no map entry for, then any a script added.
15975 if let Some(JsObj::Builtin(ns)) = with_host(|h| h.get(v).cloned()) {
15976 let rows = core_symbol_props(&ns);
15977 if !rows.is_empty() {
15978 return Ok(with_host(|h| {
15979 let mut keys: Vec<Value> = rows.iter().map(|r| core_symbol_value(h, r.1)).collect();
15980 for k in h.own_symbol_keys(v) {
15981 if !keys.iter().any(|s| h.strict_eq(s, &k)) {
15982 keys.push(k);
15983 }
15984 }
15985 keys
15986 }));
15987 }
15988 }
15989 Ok(with_host(|h| h.own_symbol_keys(v)))
15990}
15991
15992/// `[[DefineOwnProperty]]` reachable from `crate::proxy`'s no-trap forward.
15993pub fn define_property_pub(obj: &Value, key: Value, desc: Value) -> Result<Value, String> {
15994 object_define_property(vec![obj.clone(), key, desc])
15995}
15996
15997/// `[[GetOwnProperty]]` reachable from `crate::proxy`'s no-trap forward.
15998pub fn own_descriptor_pub(obj: &Value, key: Value) -> Result<Value, String> {
15999 object_get_own_descriptor(vec![obj.clone(), key])
16000}
16001
16002fn object_define_property(args: Vec<Value>) -> Result<Value, String> {
16003 let obj = arg0(&args);
16004 // A Proxy defines through its `defineProperty` trap; the target it forwards
16005 // to is where the ordinary path below finally runs.
16006 if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
16007 let key = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
16008 let desc = args.get(2).cloned().unwrap_or(Value::Undef);
16009 if !with_host(|h| is_object_like(h, &desc)) {
16010 return Err(host::type_error(&format!(
16011 "Property description must be an object: {}",
16012 with_host(|h| h.str_of(&desc))
16013 )));
16014 }
16015 // `Object.defineProperty` THROWS on a refusing trap — in sloppy code
16016 // too. `Reflect.defineProperty` is the form that reports `false`.
16017 if !crate::proxy::define_property(&obj, &key, &desc)? {
16018 if let Some(e) = crate::esm::namespace_refusal(&obj, crate::esm::Refused::Define, &key)
16019 {
16020 return Err(e);
16021 }
16022 return Err(host::type_error(&format!(
16023 "'defineProperty' on proxy: trap returned falsish for property '{key}'"
16024 )));
16025 }
16026 return Ok(obj);
16027 }
16028 // 20.1.2.4 steps 1-3, both of which node-js skipped entirely: a non-object
16029 // target and a non-object descriptor each throw before anything is written.
16030 if !with_host(|h| is_object_like(h, &obj)) {
16031 return Err(host::type_error(
16032 "Object.defineProperty called on non-object",
16033 ));
16034 }
16035 let desc = args.get(2).cloned().unwrap_or(Value::Undef);
16036 if !with_host(|h| is_object_like(h, &desc)) {
16037 return Err(host::type_error(&format!(
16038 "Property description must be an object: {}",
16039 with_host(|h| h.str_of(&desc))
16040 )));
16041 }
16042 let key = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
16043 apply_descriptor(&obj, &key, &desc)?;
16044 Ok(obj)
16045}
16046
16047/// Every `Reflect` method requires an OBJECT target and reports a `TypeError`
16048/// for anything else (28.1). A primitive was being accepted and silently
16049/// producing nothing.
16050/// `CreateListFromArrayLike` (7.3.18) — the argument list `Reflect.apply` and
16051/// `Reflect.construct` take.
16052///
16053/// An ARRAY-LIKE counts: `{length: 2, 0: 1, 1: 5}` is a two-element list. The
16054/// iterator was being used instead, so an array-like produced nothing and a
16055/// primitive produced nothing rather than the TypeError node raises.
16056/// Whether `p` is ALREADY `obj`'s prototype — the one case a non-extensible
16057/// object still accepts, because it changes nothing.
16058///
16059/// The observable prototype, not the stored link: an ordinary object has no
16060/// explicit link and inherits `Object.prototype`, so comparing the raw slot
16061/// reported "different" for `setPrototypeOf(frozen, Object.prototype)`.
16062/// Whether making `p` the prototype of `obj` would create a CYCLE — 10.1.2.1
16063/// step 8 walks up from `p` looking for `obj`.
16064///
16065/// Without the check `Object.setPrototypeOf(a, b)` followed by the reverse
16066/// built a ring. Nothing hung, because every chain walk in this host carries a
16067/// hop limit, but a lookup then silently gave up instead of finding a property
16068/// that really was there.
16069pub(crate) fn would_cycle_pub(obj: &Value, p: &Value) -> bool {
16070 would_cycle(obj, p)
16071}
16072
16073fn would_cycle(obj: &Value, p: &Value) -> bool {
16074 let mut cur = Some(p.clone());
16075 for _ in 0..1000 {
16076 let Some(c) = cur else { return false };
16077 if with_host(|h| h.strict_eq(&c, obj)) {
16078 return true;
16079 }
16080 // A PROXY's prototype is its handler's business; the spec skips the
16081 // walk entirely when one is in the chain.
16082 if with_host(|h| h.kind_of(&c)) == Some(ObjKind::Proxy) {
16083 return false;
16084 }
16085 cur = with_host(|h| h.proto_of(&c));
16086 }
16087 false
16088}
16089
16090fn same_prototype(obj: &Value, p: &Value) -> bool {
16091 let cur = prototype_of(obj);
16092 with_host(|h| h.strict_eq(&cur, p) || (h.is_null(&cur) && h.is_null(p)))
16093}
16094
16095fn create_list_from_array_like(v: &Value) -> Result<Vec<Value>, String> {
16096 if !with_host(|h| is_object_like(h, v)) {
16097 return Err(host::type_error(
16098 "CreateListFromArrayLike called on non-object",
16099 ));
16100 }
16101 let len = get_property(v, "length")?;
16102 let n = with_host(|h| h.to_number(&len));
16103 let n = if n.is_finite() && n > 0.0 {
16104 n as usize
16105 } else {
16106 0
16107 };
16108 (0..n).map(|i| get_property(v, &i.to_string())).collect()
16109}
16110
16111fn reflect_require_object(v: &Value, method: &str) -> Result<(), String> {
16112 if with_host(|h| is_object_like(h, v)) {
16113 return Ok(());
16114 }
16115 Err(host::type_error(&format!(
16116 "Reflect.{method} called on non-object"
16117 )))
16118}
16119
16120/// Whether `v` is an Object in the language sense — anything `typeof` calls
16121/// `"object"` (bar `null`) or `"function"`. Used by the argument checks that
16122/// distinguish "an object" from a primitive.
16123fn is_object_like(h: &host::JsHost, v: &Value) -> bool {
16124 matches!(v, Value::Obj(_)) && !h.is_null(v) && !host::is_primitive(h, v)
16125}
16126
16127/// `RequireObjectCoercible(v)` — 7.2.1. The check in front of every `ToObject`,
16128/// which node-js was missing on the whole `Object.keys`/`values`/`entries`/
16129/// `getOwnPropertyNames`/`getOwnPropertySymbols`/`getOwnPropertyDescriptor`/
16130/// `assign` family: each returned an empty result for `null` where node v26.7.0
16131/// throws `TypeError: Cannot convert undefined or null to object`. A PRIMITIVE
16132/// is coercible and keeps working (`Object.keys(1)` is `[]`).
16133fn require_object_coercible(v: &Value) -> Result<(), String> {
16134 if with_host(|h| matches!(v, Value::Undef) || h.is_null(v)) {
16135 return Err(host::type_error(
16136 "Cannot convert undefined or null to object",
16137 ));
16138 }
16139 Ok(())
16140}
16141
16142/// 10.1.2 / 20.1.2.2 step 1: reject a `[[Prototype]]` that is neither an Object
16143/// nor `null`, with V8's wording. Measured on node v26.7.0:
16144/// `Object.create("s")` is
16145/// `TypeError: Object prototype may only be an Object or null: s`.
16146fn reject_bad_prototype(proto: &Value) -> Result<(), String> {
16147 if with_host(|h| h.is_null(proto) || is_object_like(h, proto)) {
16148 return Ok(());
16149 }
16150 Err(host::type_error(&format!(
16151 "Object prototype may only be an Object or null: {}",
16152 with_host(|h| h.str_of(proto))
16153 )))
16154}
16155
16156/// Apply a `{ value | get | set }` descriptor object to `obj[key]`.
16157///
16158/// Per ECMAScript `ToPropertyDescriptor`, an omitted `writable`/`enumerable`/
16159/// `configurable` field defaults to **false** — which is why a `defineProperty`
16160/// data property is invisible to `Object.keys` unless the caller opts in. That
16161/// asymmetry against plain assignment is the whole reason the attribute table
16162/// exists.
16163/// The requested fields of a property descriptor — 10.1.6.2
16164/// `ToPropertyDescriptor`. Each is `None` when the descriptor omits it, which
16165/// is the distinction the merge below turns on: an omitted field LEAVES an
16166/// existing attribute alone rather than resetting it.
16167struct Requested {
16168 value: Option<Value>,
16169 get: Option<Option<Value>>,
16170 set: Option<Option<Value>>,
16171 writable: Option<bool>,
16172 enumerable: Option<bool>,
16173 configurable: Option<bool>,
16174}
16175
16176impl Requested {
16177 /// `ToPropertyDescriptor` (6.2.6.5): each field is read only when the
16178 /// descriptor HAS it (through the prototype chain, so a descriptor built with
16179 /// `Object.create({ value: 1 })` is legal), in the spec's order, and a getter
16180 /// that throws propagates. A `get`/`set` that is neither callable nor
16181 /// `undefined`, and a descriptor naming both an accessor and a data field,
16182 /// are the two TypeErrors the abstract operation raises.
16183 fn read(desc: &Value) -> Result<Self, String> {
16184 let field = |k: &str| -> Result<Option<Value>, String> {
16185 if has_property(desc, k)? {
16186 get_property(desc, k).map(Some)
16187 } else {
16188 Ok(None)
16189 }
16190 };
16191 let flag = |k: &str| -> Result<Option<bool>, String> {
16192 Ok(field(k)?.map(|v| with_host(|h| h.truthy(&v))))
16193 };
16194 let enumerable = flag("enumerable")?;
16195 let configurable = flag("configurable")?;
16196 let value = field("value")?;
16197 let writable = flag("writable")?;
16198 let accessor = |k: &str, what: &str| -> Result<Option<Option<Value>>, String> {
16199 match field(k)? {
16200 None => Ok(None),
16201 Some(Value::Undef) => Ok(Some(None)),
16202 Some(f) if with_host(|h| host::is_callable(h, &f)) => Ok(Some(Some(f))),
16203 Some(f) => Err(host::type_error(&format!(
16204 "{what} must be a function: {}",
16205 no_side_effects_string(&f)
16206 ))),
16207 }
16208 };
16209 let get = accessor("get", "Getter")?;
16210 let set = accessor("set", "Setter")?;
16211 let req = Requested {
16212 value,
16213 get,
16214 set,
16215 writable,
16216 enumerable,
16217 configurable,
16218 };
16219 if req.is_accessor() && req.is_data() {
16220 return Err(host::type_error(&format!(
16221 "Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, {}",
16222 no_side_effects_string(desc)
16223 )));
16224 }
16225 Ok(req)
16226 }
16227
16228 fn is_accessor(&self) -> bool {
16229 self.get.is_some() || self.set.is_some()
16230 }
16231
16232 fn is_data(&self) -> bool {
16233 self.value.is_some() || self.writable.is_some()
16234 }
16235}
16236
16237/// The own property already at `key`, if any, read back through
16238/// `Object.getOwnPropertyDescriptor` so every object kind (array indices, the
16239/// fn-prop side table, Buffer bytes) is covered by one code path.
16240struct Existing {
16241 accessor: bool,
16242 value: Value,
16243 get: Option<Value>,
16244 set: Option<Value>,
16245 writable: bool,
16246 enumerable: bool,
16247 configurable: bool,
16248}
16249
16250fn existing_property(obj: &Value, key: &str) -> Option<Existing> {
16251 let k = with_host(|h| h.new_str(key.to_string()));
16252 let d = own_descriptor_pub(obj, k).ok()?;
16253 if matches!(d, Value::Undef) {
16254 return None;
16255 }
16256 let field = |n: &str| get_property(&d, n).unwrap_or(Value::Undef);
16257 let truthy = |n: &str| {
16258 let v = field(n);
16259 with_host(|h| h.truthy(&v))
16260 };
16261 let accessor = with_host(|h| host::lookup_chain(h, &d, "get").is_some());
16262 Some(Existing {
16263 accessor,
16264 value: field("value"),
16265 get: match field("get") {
16266 Value::Undef => None,
16267 g => Some(g),
16268 },
16269 set: match field("set") {
16270 Value::Undef => None,
16271 st => Some(st),
16272 },
16273 writable: truthy("writable"),
16274 enumerable: truthy("enumerable"),
16275 configurable: truthy("configurable"),
16276 })
16277}
16278
16279/// SameValue (7.2.11) — `===` except that `NaN` equals itself and `+0` and
16280/// `-0` are distinct. 10.1.6.3 compares a redefined value against the current
16281/// one with this, not with strict equality.
16282pub(crate) fn same_value(a: &Value, b: &Value) -> bool {
16283 let num = |v: &Value| match v {
16284 Value::Int(n) => Some(*n as f64),
16285 Value::Float(f) => Some(*f),
16286 _ => None,
16287 };
16288 match (num(a), num(b)) {
16289 (Some(x), Some(y)) => {
16290 if x.is_nan() && y.is_nan() {
16291 true
16292 } else if x == 0.0 && y == 0.0 {
16293 x.is_sign_negative() == y.is_sign_negative()
16294 } else {
16295 x == y
16296 }
16297 }
16298 _ => with_host(|h| h.strict_eq(a, b)),
16299 }
16300}
16301
16302/// 10.1.6.3 `ValidateAndApplyPropertyDescriptor`.
16303///
16304/// None of the validation existed: every `Object.defineProperty` was applied
16305/// unconditionally, so redefining a non-configurable property silently
16306/// succeeded where node throws. Worse in practice, an OMITTED field was read as
16307/// `false` rather than "leave alone", so the ordinary
16308/// `Object.defineProperty(o, 'k', { enumerable: false })` also stripped
16309/// `writable` and `configurable` from a property that had both.
16310///
16311/// Converting an accessor to a data property did not take effect at all: the
16312/// value was written but the accessor stayed in its side table, and accessors
16313/// win on read, so the getter kept answering.
16314fn apply_descriptor(obj: &Value, key: &str, desc: &Value) -> Result<(), String> {
16315 let req = Requested::read(desc)?;
16316 let cur = existing_property(obj, key);
16317
16318 // An array's `length` is the exotic own property whose write resizes the
16319 // array (10.4.2.1); routing it through the ordinary path stored a shadowing
16320 // key and left the elements untouched.
16321 if key == "length" && with_host(|h| h.kind_of(obj)) == Some(ObjKind::Array) {
16322 if let Some(v) = req.value.clone() {
16323 return set_property_pub(obj, "length", v);
16324 }
16325 }
16326
16327 // The other exotics whose own properties are SYNTHESIZED rather than stored
16328 // in a property map: a typed array's elements and a RegExp's `lastIndex`.
16329 // The ordinary path below writes a shadowing map entry the read never
16330 // consults, so `Object.defineProperty(u8, '0', {value: 9})` left `u8[0]`
16331 // unchanged.
16332 // A builtin namespace/prototype has no property map either, so a data
16333 // descriptor has to reach the same side table an assignment does.
16334 // `Object.defineProperty(Array.prototype, 'at', {value: impl})` — how a
16335 // careful polyfill installs itself, precisely to avoid the enumerable
16336 // property a bare assignment creates — wrote a map entry nothing read.
16337 if with_host(|h| h.kind_of(obj)) == Some(ObjKind::Builtin) {
16338 if let Some(v) = req.value.clone() {
16339 return set_property_pub(obj, key, v);
16340 }
16341 }
16342 let exotic_own = (crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray")
16343 && key.parse::<usize>().is_ok())
16344 || (key == "lastIndex" && with_host(|h| matches!(h.get(obj), Some(JsObj::RegExp(_)))));
16345 if exotic_own {
16346 // A typed array element is `{ writable, enumerable, configurable: true }`
16347 // and stays that way (10.4.5.3): naming any of the three as false, or
16348 // an accessor, is a refused definition.
16349 if crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray") {
16350 let len = get_property(obj, "length")
16351 .ok()
16352 .map_or(0.0, |l| with_host(|h| h.to_number(&l)));
16353 if key.parse::<usize>().is_ok_and(|i| (i as f64) >= len) {
16354 return Err(host::type_error("Invalid typed array index"));
16355 }
16356 }
16357 if crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray")
16358 && (req.is_accessor()
16359 || req.configurable == Some(false)
16360 || req.enumerable == Some(false)
16361 || req.writable == Some(false))
16362 {
16363 return Err(host::type_error(&format!(
16364 "Cannot redefine property: {key}"
16365 )));
16366 }
16367 if let Some(v) = req.value.clone() {
16368 return set_property_pub(obj, key, v);
16369 }
16370 }
16371
16372 // 10.1.6.3 step 2: a NEW property cannot be added to a non-extensible
16373 // object. Only an existing property's attributes were being validated, so
16374 // `defineProperty(Object.freeze({}), 'z', …)` silently added one.
16375 if cur.is_none() && !with_host(|h| h.is_extensible(obj)) {
16376 return Err(host::type_error(&format!(
16377 "Cannot define property {key}, object is not extensible"
16378 )));
16379 }
16380 if let Some(c) = &cur {
16381 if !c.configurable {
16382 let rejected = req.configurable == Some(true)
16383 || req.enumerable.is_some_and(|e| e != c.enumerable)
16384 || (req.is_accessor() && !c.accessor)
16385 || (req.is_data() && c.accessor)
16386 || (c.accessor
16387 && ((req.get.is_some() && req.get.clone().flatten() != c.get)
16388 || (req.set.is_some() && req.set.clone().flatten() != c.set)))
16389 || (!c.accessor
16390 && !c.writable
16391 && (req.writable == Some(true)
16392 || req.value.as_ref().is_some_and(|v| !same_value(v, &c.value))));
16393 if rejected {
16394 return Err(host::type_error(&format!(
16395 "Cannot redefine property: {key}"
16396 )));
16397 }
16398 }
16399 }
16400
16401 // An omitted field keeps what the property already had; a brand-new
16402 // property defaults every one of them to false.
16403 let attrs = host::PropAttrs {
16404 writable: req
16405 .writable
16406 .unwrap_or(cur.as_ref().is_some_and(|c| c.writable)),
16407 enumerable: req
16408 .enumerable
16409 .unwrap_or(cur.as_ref().is_some_and(|c| c.enumerable)),
16410 configurable: req
16411 .configurable
16412 .unwrap_or(cur.as_ref().is_some_and(|c| c.configurable)),
16413 };
16414 with_host(|h| h.set_prop_attrs(obj, key, attrs));
16415
16416 if req.is_accessor() {
16417 let get = req
16418 .get
16419 .clone()
16420 .unwrap_or_else(|| cur.as_ref().and_then(|c| c.get.clone()));
16421 let set = req
16422 .set
16423 .clone()
16424 .unwrap_or_else(|| cur.as_ref().and_then(|c| c.set.clone()));
16425 // An ACCESSOR at an index past the end still extends the array
16426 // (10.4.2.1): `Object.defineProperty([1], '4', {get})` gives
16427 // `length === 5` with holes between. Only the DATA path grew it, so
16428 // the accessor landed in the side table while `length` stayed put —
16429 // and with it out of range, `Object.keys` and `JSON.stringify` never
16430 // saw the index at all.
16431 if let (Some(ObjKind::Array), Ok(i)) = (with_host(|h| h.kind_of(obj)), key.parse::<usize>())
16432 {
16433 with_host(|h| {
16434 let old_len = match h.get(obj) {
16435 Some(JsObj::Array(items)) => items.len(),
16436 _ => 0,
16437 };
16438 if i >= old_len {
16439 if let Some(JsObj::Array(items)) = h.get_mut(obj) {
16440 items.resize(i + 1, Value::Undef);
16441 }
16442 h.mark_hole_range(obj, old_len..i + 1);
16443 }
16444 });
16445 }
16446 with_host(|h| h.set_accessor(obj, key, get, set));
16447 return Ok(());
16448 }
16449
16450 if let Some(c) = &cur {
16451 if c.accessor {
16452 if !req.is_data() {
16453 // A generic descriptor — flags only — leaves an accessor an
16454 // accessor. They were already applied above.
16455 return Ok(());
16456 }
16457 let v = req.value.clone().unwrap_or(Value::Undef);
16458 with_host(|h| h.accessor_to_data(obj, key, v));
16459 return Ok(());
16460 }
16461 }
16462
16463 // A flags-only descriptor redefines an EXISTING property in place, but on a
16464 // new key it still creates one (10.1.6.3 step 2.a), holding `undefined`.
16465 let v = match req.value {
16466 Some(v) => v,
16467 None if cur.is_none() => Value::Undef,
16468 None => return Ok(()),
16469 };
16470 write_data_slot(obj, key, v);
16471 Ok(())
16472}
16473
16474/// Store `v` as an own data property, in whichever slot the object kind keeps
16475/// its own properties.
16476fn write_data_slot(obj: &Value, key: &str, v: Value) {
16477 // A function/class receiver stores its own props in the fn-prop side table
16478 // (express `mixin(app, proto)` defines methods onto the `app` *function*).
16479 if matches!(
16480 with_host(|h| h.get(obj).cloned()),
16481 Some(JsObj::Func(_)) | Some(JsObj::Class(_)) | Some(JsObj::BoundFunc { .. })
16482 ) || uses_side_table(obj)
16483 {
16484 with_host(|h| h.set_fn_prop(obj, key, v));
16485 return;
16486 }
16487 if let (Some(ObjKind::Array), Ok(i)) = (with_host(|h| h.kind_of(obj)), key.parse::<usize>()) {
16488 // An array's index keys ARE its elements, and defining one past the end
16489 // grows the array with holes in between (10.4.2.1). This whole branch
16490 // used to be missing: `Object.defineProperty(arr, 1, {value})` wrote
16491 // into the ordinary property map an array does not have, so it was a
16492 // silent no-op.
16493 with_host(|h| {
16494 let old = match h.get(obj) {
16495 Some(JsObj::Array(items)) => items.len(),
16496 _ => 0,
16497 };
16498 if let Some(JsObj::Array(items)) = h.get_mut(obj) {
16499 if i >= old {
16500 items.resize(i + 1, Value::Undef);
16501 }
16502 items[i] = v;
16503 }
16504 if i > old {
16505 h.mark_hole_range(obj, old..i);
16506 }
16507 h.clear_hole(obj, i);
16508 });
16509 return;
16510 }
16511 // A NAMED own property of an array lives in the side table, the same slot
16512 // an assignment (`a.foo = 1`) writes and every read consults. Falling
16513 // through to the property-map arm below wrote nowhere at all, so
16514 // `Object.defineProperty([], 'foo', {value: 3}).foo` was `undefined`.
16515 if with_host(|h| h.kind_of(obj)) == Some(ObjKind::Array) {
16516 with_host(|h| h.set_fn_prop(obj, key, v));
16517 return;
16518 }
16519 with_host(|h| {
16520 if let Some(JsObj::Object(p)) = h.get_mut(obj) {
16521 p.insert(key.to_string(), v);
16522 host::canonicalize_own_keys(p);
16523 }
16524 });
16525}
16526
16527/// `Object.defineProperties(obj, descriptorMap)`.
16528fn object_define_properties(args: Vec<Value>) -> Result<Value, String> {
16529 let obj = arg0(&args);
16530 let descs = args.get(1).cloned().unwrap_or(Value::Undef);
16531 let entries: Vec<(String, Value)> = with_host(|h| match h.get(&descs) {
16532 Some(JsObj::Object(p)) => p.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
16533 _ => Vec::new(),
16534 });
16535 for (k, d) in entries {
16536 apply_descriptor(&obj, &k, &d)?;
16537 }
16538 Ok(obj)
16539}
16540
16541/// The descriptor of an own property a function, a typed array or a RegExp
16542/// SYNTHESIZES rather than keeping in a property map.
16543///
16544/// These read back through the ordinary path but owned no descriptor and did
16545/// not appear under `hasOwnProperty` or `getOwnPropertyNames`, so the five
16546/// views of "does this property exist" disagreed — a read said yes while
16547/// `Object.getOwnPropertyDescriptor(f, 'name')` said no such property, which is
16548/// what a shim checks before patching.
16549fn synthesized_own_descriptor(obj: &Value, key: &str) -> Option<(Value, host::PropAttrs)> {
16550 let ro_configurable = host::PropAttrs {
16551 writable: false,
16552 enumerable: false,
16553 configurable: true,
16554 };
16555 // A callable's `length`/`name` are read-only but configurable; its
16556 // `prototype` is writable and NOT configurable, and a class's is neither.
16557 // An arrow, a method and a bound function own no `prototype` at all.
16558 if with_host(|h| host::is_callable(h, obj)) && !matches!(key, "length" | "name" | "prototype") {
16559 return None;
16560 }
16561 if with_host(|h| h.fn_intrinsic_deleted(obj, key)) {
16562 return None;
16563 }
16564 if with_host(|h| host::is_callable(h, obj)) {
16565 if key == "prototype" {
16566 let p = get_property(obj, "prototype").ok()?;
16567 if matches!(p, Value::Undef) {
16568 return None;
16569 }
16570 return Some((
16571 p,
16572 host::PropAttrs {
16573 writable: with_host(|h| h.kind_of(obj)) != Some(ObjKind::Class),
16574 enumerable: false,
16575 configurable: false,
16576 },
16577 ));
16578 }
16579 return Some((get_property(obj, key).ok()?, ro_configurable));
16580 }
16581 // A typed array's elements are own, enumerable, writable, configurable
16582 // properties; an index past the end owns nothing.
16583 if crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray") {
16584 let v = crate::stdlib::typedarray::elem_get(obj, key)?;
16585 return Some((
16586 v,
16587 host::PropAttrs {
16588 writable: true,
16589 enumerable: true,
16590 configurable: true,
16591 },
16592 ));
16593 }
16594 // A RegExp's `lastIndex` is its own, writable, non-configurable cursor.
16595 if with_host(|h| matches!(h.get(obj), Some(JsObj::RegExp(_)))) && key == "lastIndex" {
16596 return Some((
16597 get_property(obj, "lastIndex").ok()?,
16598 host::PropAttrs {
16599 writable: true,
16600 enumerable: false,
16601 configurable: false,
16602 },
16603 ));
16604 }
16605 None
16606}
16607
16608fn object_get_own_descriptor(args: Vec<Value>) -> Result<Value, String> {
16609 let obj = arg0(&args);
16610 require_object_coercible(&obj)?;
16611 let key = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
16612 // A string primitive's boxed own properties: each code-unit index is an
16613 // enumerable, non-writable, non-configurable data property, and `length` is
16614 // the same minus enumerable.
16615 if let Some(units) = string_primitive_units(&obj) {
16616 let entry = match key.parse::<usize>() {
16617 Ok(i) => units
16618 .get(i)
16619 .map(|c| (with_host(|h| h.new_str(c.clone())), true)),
16620 Err(_) if key == "length" => Some((Value::Float(units.len() as f64), false)),
16621 Err(_) => None,
16622 };
16623 return Ok(match entry {
16624 Some((value, enumerable)) => with_host(|h| {
16625 let mut m: IndexMap<String, Value> = IndexMap::new();
16626 m.insert("value".into(), value);
16627 m.insert("writable".into(), Value::Bool(false));
16628 m.insert("enumerable".into(), Value::Bool(enumerable));
16629 m.insert("configurable".into(), Value::Bool(false));
16630 h.new_object(m)
16631 }),
16632 None => Value::Undef,
16633 });
16634 }
16635 if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
16636 return Ok(crate::proxy::get_own_descriptor(&obj, &key)?.unwrap_or(Value::Undef));
16637 }
16638 // A method read off an enumerable builtin prototype (`EventEmitter.prototype`)
16639 // yields a `{ value: <method thunk> }` data descriptor so `mixin` can copy it.
16640 if let Some(JsObj::Builtin(ns)) = with_host(|h| h.get(&obj).cloned()) {
16641 if let Some(names) = builtin_proto_method_names(&ns) {
16642 if names.contains(&key.as_str()) {
16643 return Ok(with_host(|h| {
16644 let thunk = h.alloc(JsObj::Builtin(format!(
16645 "@proto:{}:{key}",
16646 ns.trim_end_matches(".prototype")
16647 )));
16648 let mut m: IndexMap<String, Value> = IndexMap::new();
16649 m.insert("value".into(), thunk);
16650 m.insert("writable".into(), Value::Bool(true));
16651 m.insert("enumerable".into(), Value::Bool(true));
16652 m.insert("configurable".into(), Value::Bool(true));
16653 h.new_object(m)
16654 }));
16655 }
16656 }
16657 }
16658 // A global the object does not own outright is still an own property of the
16659 // global object — the same lazy binding the bare identifier resolves to.
16660 // Every one of them reported `undefined`, so a feature probe written as
16661 // `getOwnPropertyDescriptor(globalThis, 'structuredClone')` concluded the
16662 // global was absent. The immutable trio (11.1.1 / 19.1.1-3) is frozen; the
16663 // rest are ordinary writable, non-enumerable, configurable bindings.
16664 if with_host(|h| h.is_global_object(&obj)) {
16665 let owned = with_host(|h| match h.get(&obj) {
16666 Some(JsObj::Object(p)) => p.contains_key(&key),
16667 _ => false,
16668 });
16669 if !owned && !CJS_WRAPPER_LOCALS.contains(&key.as_str()) {
16670 // A global a SCRIPT created — `x = 1` with no declaration — is an
16671 // ordinary enumerable property, unlike the builtins.
16672 let script_made = with_host(|h| h.read_global(&key).is_some());
16673 if let Some(v) = global_object_binding(&key) {
16674 let frozen = matches!(key.as_str(), "undefined" | "NaN" | "Infinity");
16675 return Ok(with_host(|h| {
16676 let mut m: IndexMap<String, Value> = IndexMap::new();
16677 m.insert("value".into(), v);
16678 m.insert("writable".into(), Value::Bool(!frozen));
16679 m.insert(
16680 "enumerable".into(),
16681 Value::Bool(script_made || ENUMERABLE_GLOBALS.contains(&key.as_str())),
16682 );
16683 m.insert("configurable".into(), Value::Bool(!frozen));
16684 h.new_object(m)
16685 }));
16686 }
16687 }
16688 }
16689 // Any other member of a builtin namespace (`Math.PI`, `Math.floor`,
16690 // `Array.prototype.slice`, a builtin function's own `name`/`length`). Every
16691 // one of these reads back a value, but none owned a DESCRIPTOR:
16692 // `Object.getOwnPropertyDescriptor(Math, 'PI')` was `undefined`, which reads
16693 // as "no such property" to the shim/polyfill family that probes a namespace
16694 // before patching it.
16695 // An ACCESSOR member describes itself with a `get`, never a `value` — and
16696 // it must do so without READING the property, since running the getter
16697 // against the prototype is exactly what throws. Both prototype
16698 // representations are covered, so `Symbol.prototype.description` and
16699 // `Map.prototype.size` answer alike; both were `undefined`, which reads as
16700 // "no such property" to anything that probes before patching.
16701 if let Some(ctor) = intrinsic_proto_of(&obj) {
16702 if is_proto_accessor(&ctor, &key) {
16703 let getter = proto_getter(&ctor, &key);
16704 // The poison pair is the only ECMAScript accessor here with a
16705 // SETTER, but a WebIDL class has plenty: `URL.prototype.href`,
16706 // `hostname` and the rest are all writable, and reporting them as
16707 // read-only made `Object.getOwnPropertyDescriptor(URL.prototype,
16708 // 'href').set` read `undefined` for a setter that runs.
16709 let writable = (ctor == "Function" && matches!(key.as_str(), "arguments" | "caller"))
16710 || crate::stdlib::instance_accessors(&ctor)
16711 .0
16712 .iter()
16713 .any(|(k, settable)| *k == key && *settable);
16714 let setter = writable
16715 .then(|| with_host(|h| h.alloc(JsObj::Builtin(format!("@protoset:{ctor}:{key}")))));
16716 return Ok(with_host(|h| {
16717 let mut m: IndexMap<String, Value> = IndexMap::new();
16718 m.insert("get".into(), getter);
16719 // `undefined`, not null: a read-only accessor has no setter at
16720 // all, and `JSON.stringify` of the descriptor must drop the key
16721 // rather than report `"set": null`.
16722 m.insert("set".into(), setter.unwrap_or(Value::Undef));
16723 m.insert("enumerable".into(), Value::Bool(is_webidl_proto(&ctor)));
16724 m.insert("configurable".into(), Value::Bool(true));
16725 h.new_object(m)
16726 }));
16727 }
16728 }
16729 if let Some(ns) = with_host(|h| match h.get(&obj) {
16730 Some(JsObj::Builtin(ns)) => Some(ns.clone()),
16731 _ => None,
16732 }) {
16733 let value = namespace_property(&ns, &key);
16734 if !matches!(value, Value::Undef) {
16735 return Ok(builtin_member_descriptor(&ns, &key, value));
16736 }
16737 }
16738 if let Some((value, attrs)) = synthesized_own_descriptor(&obj, &key) {
16739 return Ok(with_host(|h| {
16740 let mut m: IndexMap<String, Value> = IndexMap::new();
16741 m.insert("value".into(), value);
16742 m.insert("writable".into(), Value::Bool(attrs.writable));
16743 m.insert("enumerable".into(), Value::Bool(attrs.enumerable));
16744 m.insert("configurable".into(), Value::Bool(attrs.configurable));
16745 h.new_object(m)
16746 }));
16747 }
16748 // Accessor descriptor?
16749 if let Some((get, set)) = with_host(|h| h.own_accessor(&obj, &key)) {
16750 return Ok(with_host(|h| {
16751 let a = h.prop_attrs(&obj, &key);
16752 let mut m: IndexMap<String, Value> = IndexMap::new();
16753 m.insert("get".into(), get.unwrap_or(Value::Undef));
16754 m.insert("set".into(), set.unwrap_or(Value::Undef));
16755 m.insert("enumerable".into(), Value::Bool(a.enumerable));
16756 m.insert("configurable".into(), Value::Bool(a.configurable));
16757 h.new_object(m)
16758 }));
16759 }
16760 let val = with_host(|h| match h.get(&obj) {
16761 // A Buffer's own properties are exactly its byte indices, read out of the
16762 // hidden `@@bytes` slot; `length`/`byteLength` are internal bookkeeping
16763 // that V8 keeps on the prototype, so they own no descriptor.
16764 Some(JsObj::Object(p))
16765 if p.get("@@native").map(|t| h.str_of(t)).as_deref() == Some("Buffer") =>
16766 {
16767 let bytes = crate::stdlib::buffer::window_bytes_h(h, p);
16768 key.parse::<usize>()
16769 .ok()
16770 .and_then(|i| bytes.get(i))
16771 .map(|b| Value::Float(*b as f64))
16772 }
16773 Some(JsObj::Object(p)) => p.get(&key).cloned(),
16774 // An array's index keys read the elements; `length` is the exotic own
16775 // property; anything else is an ordinary own key in the side table.
16776 Some(JsObj::Array(items)) => match key.parse::<usize>() {
16777 // An ELIDED index owns no property at all, so it has no descriptor.
16778 Ok(i) if h.is_hole(&obj, i) => None,
16779 Ok(i) => items.get(i).cloned(),
16780 Err(_) if key == "length" => Some(Value::Float(items.len() as f64)),
16781 Err(_) => h.fn_prop(&obj, &key),
16782 },
16783 // A function/class own prop lives in the fn-prop side table.
16784 Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => h.fn_prop(&obj, &key),
16785 _ => None,
16786 });
16787 match val {
16788 Some(v) => Ok(with_host(|h| {
16789 let a = h.prop_attrs(&obj, &key);
16790 let mut m: IndexMap<String, Value> = IndexMap::new();
16791 m.insert("value".into(), v);
16792 m.insert("writable".into(), Value::Bool(a.writable));
16793 m.insert("enumerable".into(), Value::Bool(a.enumerable));
16794 m.insert("configurable".into(), Value::Bool(a.configurable));
16795 h.new_object(m)
16796 })),
16797 None => Ok(Value::Undef),
16798 }
16799}
16800
16801/// `Object.getOwnPropertyDescriptors(obj)` (§20.1.2.9) — the descriptor of
16802/// every key `[[OwnPropertyKeys]]` yields: the string keys in
16803/// `getOwnPropertyNames` order, then the symbol keys.
16804/// `Object.create(proto, getOwnPropertyDescriptors(src))` is the standard
16805/// "clone with accessors intact" idiom, so a `[Symbol.toStringTag]` or
16806/// `[Symbol.iterator]` member must survive it too.
16807fn object_get_own_descriptors(args: Vec<Value>) -> Result<Value, String> {
16808 let obj = arg0(&args);
16809 let names = object_keys(vec![obj.clone()], 3)?;
16810 let mut keys: Vec<Value> = with_host(|h| match h.get(&names) {
16811 Some(JsObj::Array(items)) => items.clone(),
16812 _ => Vec::new(),
16813 });
16814 keys.extend(proxy_or_own_symbol_keys(&obj)?);
16815 let mut out: IndexMap<String, Value> = IndexMap::new();
16816 for key in keys {
16817 let k = host::to_property_key(&key)?;
16818 let d = object_get_own_descriptor(vec![obj.clone(), key])?;
16819 if !matches!(d, Value::Undef) {
16820 out.insert(k, d);
16821 }
16822 }
16823 Ok(with_host(|h| h.new_object(out)))
16824}
16825
16826/// `key in obj` respecting the prototype chain. Reports a `Result` because a
16827/// Proxy's `has` trap is user code and may throw.
16828pub fn has_property(obj: &Value, key: &str) -> Result<bool, String> {
16829 if let Some(b) = crate::proxy::has(obj, key)? {
16830 return Ok(b);
16831 }
16832 Ok(has_property_ordinary(obj, key))
16833}
16834
16835/// `[[HasProperty]]` for every non-Proxy receiver.
16836fn has_property_ordinary(obj: &Value, key: &str) -> bool {
16837 // `key in globalThis`: membership matches what the READ answers, which for
16838 // the global object includes every lazily-bound builtin and every global a
16839 // script created. `'Math' in globalThis` and `'x' in globalThis` after
16840 // `x = 1` both answered FALSE while `globalThis.Math` and `globalThis.x`
16841 // read back fine.
16842 if with_host(|h| h.is_global_object(obj))
16843 && !CJS_WRAPPER_LOCALS.contains(&key)
16844 && global_object_binding(key).is_some()
16845 {
16846 return true;
16847 }
16848 // `key in <builtin namespace/prototype>`: membership matches what a property
16849 // read would yield. `String.prototype.indexOf` (and the rest of the builtin
16850 // prototype methods) resolve as callable thunks via `namespace_property`, so
16851 // `'indexOf' in String.prototype` must report true (get-intrinsic probes this
16852 // with the `in` operator before reading the intrinsic).
16853 if let Some(JsObj::Builtin(ns)) = with_host(|h| h.get(obj).cloned()) {
16854 return !matches!(namespace_property(&ns, key), Value::Undef);
16855 }
16856 // An integer index of a typed array / Buffer is an own property, and lives
16857 // in the hidden element array rather than the property map — the same
16858 // question `hasOwnProperty` answers, through the same helper. Only a hit
16859 // short-circuits: a non-index key like `'length'` must still fall through
16860 // to the ordinary chain lookup below.
16861 if crate::stdlib::typedarray::has_index(obj, key) == Some(true) {
16862 return true;
16863 }
16864 if with_host(|h| host::lookup_chain(h, obj, key)).is_some() {
16865 return true;
16866 }
16867 if with_host(|h| host::lookup_accessor(h, obj, key)).is_some() {
16868 return true;
16869 }
16870 // A member patched onto the receiver's intrinsic prototype. The READ
16871 // resolves it, so without this `Array.prototype.at = f` made `[].at` a
16872 // function while `'at' in []` stayed false.
16873 if !key.starts_with('#') && inherited_builtin_static(obj, key).is_some() {
16874 return true;
16875 }
16876 if with_host(|h| match h.get(obj) {
16877 Some(JsObj::Object(p)) => p.contains_key(key),
16878 Some(JsObj::Array(items)) => {
16879 key == "length"
16880 || key
16881 .parse::<usize>()
16882 .map(|i| i < items.len() && !h.is_hole(obj, i))
16883 .unwrap_or(false)
16884 // A non-index own property (`arr.foo`, `arr[sym]`) lives in the
16885 // side table, and `in` must see it.
16886 || h.fn_prop(obj, key).is_some()
16887 }
16888 Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => h.fn_prop(obj, key).is_some(),
16889 // A RegExp's `lastIndex` is an OWN property in node. Here it lives in
16890 // the `RegExpObj` struct rather than a property map, so nothing above
16891 // can see it.
16892 Some(JsObj::RegExp(_)) => key == "lastIndex" || h.fn_prop(obj, key).is_some(),
16893 _ => false,
16894 }) {
16895 return true;
16896 }
16897 // An INHERITED builtin prototype method. These are not objects on the
16898 // prototype chain — they are synthesized by the read path from the
16899 // intrinsic table — so neither `lookup_chain` nor the property map above
16900 // can see them, and `'toString' in {}`, `'push' in []` and `'then' in
16901 // Promise.resolve()` all answered false. That last one is the standard
16902 // thenable test, so the `in` operator disagreed with what a read gives for
16903 // every builtin method of every builtin kind.
16904 inherited_builtin_method(obj, key)
16905}
16906
16907/// Whether a READ of `key` on `obj` would resolve to an inherited builtin
16908/// prototype method. Asked by `in` and `hasOwnProperty`'s negative case; it
16909/// performs no read, so a getter cannot fire.
16910/// A property a script MONKEY-PATCHED onto the intrinsic prototype `obj`
16911/// inherits from (`Array.prototype.at = impl`, `Object.prototype.foo = 1`), or
16912/// `None`.
16913///
16914/// The intrinsic prototypes are namespace handles rather than real objects on
16915/// the chain, so an assignment onto one lands in `builtin_statics` and no
16916/// ordinary chain walk can see it. This is the read side: the receiver's own
16917/// constructor's prototype first, then `Object.prototype`, mirroring
16918/// `inherited_method_owner`'s two-step.
16919pub(crate) fn inherited_builtin_static(obj: &Value, key: &str) -> Option<Value> {
16920 if with_host(|h| h.has_null_proto(obj)) {
16921 return None;
16922 }
16923 let ctor = match wrapped_primitive(obj).as_ref().and_then(wrapper_ctor_of) {
16924 Some(c) => Some(c),
16925 None if is_arguments(obj) => Some("Object"),
16926 None => with_host(|h| default_ctor_name(h, obj)),
16927 };
16928 // Only the side table is consulted, never the real prototype OBJECT's map:
16929 // `String.prototype` and friends are materialized with their intrinsic
16930 // members present, so reading their maps here would re-route every ordinary
16931 // `"a".toString()` through this path — which recursed until the stack blew.
16932 // `set_property` mirrors a write onto a real intrinsic prototype INTO this
16933 // table precisely so the read side can stay this narrow.
16934 let on = |c: &str| with_host(|h| h.builtin_static(&format!("{c}.prototype"), key));
16935 let found = ctor.and_then(on).or_else(|| on("Object"))?;
16936 // Restoring a saved intrinsic (`const orig = Array.prototype.join; …;
16937 // Array.prototype.join = orig`) stores the SYNTHESIZED thunk for this very
16938 // name back into the table. Dispatching to it would re-enter this lookup
16939 // and recurse until the stack blew, so a thunk that is already this key's
16940 // own intrinsic reports nothing and the ordinary builtin path answers.
16941 let self_thunk = with_host(
16942 |h| matches!(h.get(&found), Some(JsObj::Builtin(s)) if s.starts_with("@proto:") && s.ends_with(&format!(":{key}"))),
16943 );
16944 (!self_thunk).then_some(found)
16945}
16946
16947/// Whether `recv` carries `key` as an OWN property — the guard on
16948/// [`inherited_builtin_static`], since an own property shadows anything
16949/// patched onto a prototype.
16950fn has_own_for_shadow(recv: &Value, key: &str) -> bool {
16951 with_host(|h| {
16952 if h.fn_prop(recv, key).is_some() || h.own_accessor(recv, key).is_some() {
16953 return true;
16954 }
16955 match h.get(recv) {
16956 Some(JsObj::Object(p)) => p.contains_key(key),
16957 // An ELIDED index owns nothing — the whole point of a hole is that
16958 // the lookup continues up the chain — so it must not count as a
16959 // shadow here or an inherited value at that index stays invisible.
16960 Some(JsObj::Array(items)) => {
16961 key == "length" || {
16962 key.parse::<usize>()
16963 .is_ok_and(|i| i < items.len() && !h.is_hole(recv, i))
16964 }
16965 }
16966 _ => false,
16967 }
16968 })
16969}
16970
16971fn inherited_builtin_method(obj: &Value, key: &str) -> bool {
16972 if with_host(|h| h.has_null_proto(obj)) {
16973 return false;
16974 }
16975 if let Some(tag) = crate::stdlib::native_tag(obj) {
16976 if crate::stdlib::instance_has_method(&tag, key) {
16977 return true;
16978 }
16979 }
16980 inherited_method_owner(obj, key).is_some()
16981}
16982
16983/// Whether `recv`'s intrinsic prototype is still on its chain — that is,
16984/// whether `Array.prototype`'s methods are still reachable from an array.
16985///
16986/// A builtin's methods are synthesized from the receiver's KIND rather than
16987/// found on a chain, so replacing the prototype could not take them away:
16988/// `Object.setPrototypeOf(a, {})` left `a.join` a function where node reports
16989/// `undefined`, and `Object.setPrototypeOf(a, null)` did too. The exotic
16990/// storage is unaffected either way — `Array.isArray`, `a.length` and `a[0]`
16991/// all still answer, as they do in node.
16992///
16993/// The overwhelmingly common case is the DEFAULT link, which is recorded as no
16994/// link at all, so this answers true after one map probe and allocates nothing.
16995pub(crate) fn own_intrinsic_reachable_pub(recv: &Value) -> bool {
16996 own_intrinsic_reachable(recv)
16997}
16998
16999fn own_intrinsic_reachable(recv: &Value) -> bool {
17000 // A BOXED primitive needs no special case here: its methods resolve through
17001 // `inherited_method_owner`, which applies the wrapper rule itself.
17002 with_host(|h| default_ctor_name(h, recv)).map_or(true, |c| intrinsic_reachable(recv, c))
17003}
17004
17005/// Whether the intrinsic prototype for `ctor` is still on `recv`'s chain.
17006fn intrinsic_reachable(recv: &Value, ctor: &str) -> bool {
17007 let own = Some(ctor);
17008 let mut cur = recv.clone();
17009 for _ in 0..100 {
17010 let explicit = with_host(|h| h.proto_of(&cur));
17011 let Some(p) = explicit else {
17012 // No explicit link: the implicit prototype is this object's own
17013 // kind's, which is what `recv` is asking about only while `cur` is
17014 // still `recv` itself.
17015 if with_host(|h| h.has_null_proto(&cur)) {
17016 return false;
17017 }
17018 let implicit = with_host(|h| default_ctor_name(h, &cur));
17019 // Every implicit prototype chain ends at `Object.prototype`, so a
17020 // question about `Object` is answered yes by any of them.
17021 return implicit == own || ctor == "Object";
17022 };
17023 if with_host(|h| h.is_null(&p)) {
17024 return false;
17025 }
17026 let hit = with_host(|h| {
17027 own.is_some_and(|c| {
17028 matches!(h.get(&p), Some(JsObj::Builtin(ns)) if *ns == format!("{c}.prototype"))
17029 || h.intrinsic_proto_ctor(&p) == Some(c)
17030 || (c == "Object" && h.object_proto() == p)
17031 })
17032 });
17033 if hit {
17034 return true;
17035 }
17036 // A CLASS prototype object is not linked to the builtin its class
17037 // extends — the `extends` relationship is recorded on the class value —
17038 // so the walk has to cross over there or `class D extends Array {}` ends
17039 // it, and every inherited method of every subclass instance vanishes.
17040 if let Some(builtin) = with_host(|h| {
17041 h.class_owning_proto(&p)
17042 .and_then(|c| h.class_builtin_ancestor(&c))
17043 .map(|b| h.callable_name(&b))
17044 }) {
17045 if own == Some(builtin.as_str()) || ctor == "Object" {
17046 return true;
17047 }
17048 }
17049 cur = p;
17050 }
17051 false
17052}
17053
17054/// The intrinsic prototypes actually ON `recv`'s explicit chain, nearest first
17055/// — the complement of [`intrinsic_reachable`], which asks about one known
17056/// constructor.
17057///
17058/// `Object.create(Array.prototype)` is an ordinary object whose chain reaches
17059/// `Array.prototype`, and node resolves the whole of `Array.prototype` through
17060/// it: `o.push(1)` works, because those methods are generic over their receiver
17061/// (which is also why `Array.prototype.push.call({length: 0}, 1)` already
17062/// worked here). Deciding the owner from the receiver's KIND alone made every
17063/// one of them `undefined` — the same "methods come from the kind, not the
17064/// chain" mistake as the detachment case, in the opposite direction.
17065pub(crate) fn chain_intrinsic_ctors_pub(recv: &Value) -> Vec<&'static str> {
17066 chain_intrinsic_ctors(recv)
17067}
17068
17069fn chain_intrinsic_ctors(recv: &Value) -> Vec<&'static str> {
17070 with_host(|h| chain_intrinsic_ctors_h(h, recv))
17071}
17072
17073/// [`chain_intrinsic_ctors`] against an already-held host borrow, for the
17074/// callers that are inside one — `can_write_prop` takes `&JsHost`, so going
17075/// back through `with_host` there aborts the process on a double borrow.
17076pub(crate) fn chain_intrinsic_ctors_h(h: &host::JsHost, recv: &Value) -> Vec<&'static str> {
17077 let mut out: Vec<&'static str> = Vec::new();
17078 let mut cur = recv.clone();
17079 for _ in 0..100 {
17080 let Some(p) = h.proto_of(&cur) else {
17081 break;
17082 };
17083 if h.is_null(&p) {
17084 break;
17085 }
17086 let name = match h.get(&p) {
17087 Some(JsObj::Builtin(ns)) => ns.strip_suffix(".prototype").map(str::to_string),
17088 _ => h.intrinsic_proto_ctor(&p).map(str::to_string),
17089 };
17090 if let Some(n) = name {
17091 if let Some(c) = crate::arity::PROTO_MEMBERS
17092 .iter()
17093 .map(|(k, _)| *k)
17094 .find(|k| *k == n)
17095 {
17096 if !out.contains(&c) {
17097 out.push(c);
17098 }
17099 }
17100 }
17101 cur = p;
17102 }
17103 out
17104}
17105
17106/// The constructor whose prototype defines `key` for `obj` — its own if that
17107/// prototype has it, otherwise `Object` — or `None` when neither does.
17108///
17109/// Used both by `in` and by the READ, so the two cannot disagree about which
17110/// prototype a name comes from. `new Map().toString` is `Map.prototype`'s and
17111/// `new Map().hasOwnProperty` is `Object.prototype`'s.
17112pub(crate) fn inherited_method_owner_pub(obj: &Value, key: &str) -> Option<&'static str> {
17113 inherited_method_owner(obj, key)
17114}
17115
17116fn inherited_method_owner(obj: &Value, key: &str) -> Option<&'static str> {
17117 if with_host(|h| h.has_null_proto(obj)) {
17118 return None;
17119 }
17120 // The generated prototype-member table, which unlike the arity table knows
17121 // about the ACCESSORS — `size` on a Map, `source` on a RegExp, `description`
17122 // on a Symbol are members but not functions — and about `constructor`.
17123 // A BOXED primitive reports its wrapper's constructor, not `Object` —
17124 // `'description' in Object(Symbol())` is true. The box is an ordinary
17125 // object carrying the primitive in a slot, so the ctor comes from what it
17126 // holds rather than from the box itself.
17127 let ctor = match wrapped_primitive(obj).as_ref().and_then(wrapper_ctor_of) {
17128 Some(c) => Some(c),
17129 // An `arguments` object is ARRAY-BACKED here so that indices, `length`,
17130 // spread and `for-of` work, but node's is an exotic that inherits from
17131 // `Object.prototype` — `typeof arguments.map` is `undefined`. Reporting
17132 // its backing kind would hand it the whole `Array.prototype`.
17133 None if is_arguments(obj) => Some("Object"),
17134 None => with_host(|h| default_ctor_name(h, obj)),
17135 };
17136 let on_proto = |c: &str| {
17137 crate::arity::PROTO_MEMBERS
17138 .binary_search_by(|(k, _)| (*k).cmp(c))
17139 .ok()
17140 .is_some_and(|i| {
17141 crate::arity::PROTO_MEMBERS[i]
17142 .1
17143 .iter()
17144 .any(|m| m.strip_prefix('+').unwrap_or(m) == key)
17145 })
17146 };
17147 // `PROTO_MEMBERS` is generated from the prototypes' STRING keys, so a
17148 // well-known symbol member is absent from it. For an object whose CHAIN
17149 // reaches an intrinsic prototype the intrinsic table has to be consulted as
17150 // well, or `[...Object.create(Array.prototype)]` finds no `Symbol.iterator`
17151 // at all. It is deliberately NOT consulted for the receiver's own kind:
17152 // there a thunk would be minted for every `@@` member the table names,
17153 // including ones whose dispatch has no implementation for that receiver,
17154 // and `[...buffer]` then failed with `@@iterator is not a function`.
17155 //
17156 // It is narrowed further to an ORDINARY object: a natively-tagged receiver
17157 // (a typed array, a Buffer) is linked to a real intrinsic prototype too,
17158 // and minting a thunk there produced `@@iterator is not a function` for
17159 // `[...new Uint8Array(ab)]` — those kinds reach their iterator by their own
17160 // fast path, which the table entry would shadow.
17161 let plain = with_host(|h| h.kind_of(obj)) == Some(ObjKind::Object)
17162 && crate::stdlib::native_tag(obj).is_none();
17163 let on_proto_or_symbol =
17164 |c: &str| on_proto(c) || (plain && builtin_meta(&format!("@proto:{c}:{key}")).is_some());
17165 // Each candidate is only an answer while ITS prototype is still on the
17166 // receiver's chain. The two are asked separately: replacing an array's
17167 // prototype with a plain object takes `Array.prototype`'s methods away and
17168 // leaves `Object.prototype`'s, since the replacement inherits from it.
17169 if let Some(c) = ctor.filter(|c| on_proto(c) && intrinsic_reachable(obj, c)) {
17170 return Some(c);
17171 }
17172 // An intrinsic prototype the receiver's chain passes THROUGH, which its own
17173 // kind does not account for.
17174 if let Some(c) = chain_intrinsic_ctors(obj)
17175 .into_iter()
17176 .find(|c| on_proto_or_symbol(c))
17177 {
17178 return Some(c);
17179 }
17180 // Everything else inherits `Object.prototype`'s.
17181 if on_proto("Object") && intrinsic_reachable(obj, "Object") {
17182 return Some("Object");
17183 }
17184 None
17185}
17186
17187/// `structuredClone` — a deep copy of plain data (objects/arrays/primitives).
17188/// `structuredClone` — the HTML structured-clone algorithm's shape: a deep copy
17189/// that preserves the *reference graph*. Two properties pointing at the same
17190/// object clone to two properties pointing at the same clone, and a cycle clones
17191/// to a cycle instead of recursing forever. `seen` maps each source heap index
17192/// to its clone, which is what buys both.
17193/// The rendering node puts in a `DataCloneError` for a value the structured
17194/// clone algorithm refuses, or `None` when the value IS cloneable.
17195///
17196/// Refusing at all is the point: these used to be copied through by reference,
17197/// so `structuredClone({f: () => 1})` handed back an object sharing the
17198/// original's function and `structuredClone(new WeakMap())` returned the very
17199/// same WeakMap. Node throws on every one of them.
17200fn clone_refusal(v: &Value) -> Option<String> {
17201 let kind = with_host(|h| h.kind_of(v))?;
17202 let render = |ctor: &str| Some(format!("#<{ctor}>"));
17203 match kind {
17204 // A function renders as its SOURCE TEXT here, which each FuncDef
17205 // keeps as a span into its script (`JsHost::func_source`).
17206 ObjKind::Func | ObjKind::Class | ObjKind::BoundFunc | ObjKind::BoundMethod => {
17207 Some(with_host(|h| h.str_of(v)))
17208 }
17209 ObjKind::Builtin if with_host(|h| host::is_callable(h, v)) => {
17210 Some(with_host(|h| h.str_of(v)))
17211 }
17212 ObjKind::Symbol => Some(with_host(|h| h.str_of(v))),
17213 ObjKind::Promise => render("Promise"),
17214 ObjKind::Generator => Some("[object Generator]".to_string()),
17215 // A proxy is refused by its TARGET's shape: a callable one renders like
17216 // the function it wraps, everything else as a plain object.
17217 ObjKind::Proxy => Some(if with_host(|h| host::is_callable(h, v)) {
17218 with_host(|h| h.str_of(v))
17219 } else {
17220 "#<Object>".to_string()
17221 }),
17222 ObjKind::Map if with_host(|h| matches!(h.get(v), Some(JsObj::Map { weak: true, .. }))) => {
17223 render("WeakMap")
17224 }
17225 ObjKind::Set if with_host(|h| matches!(h.get(v), Some(JsObj::Set { weak: true, .. }))) => {
17226 render("WeakSet")
17227 }
17228 _ => match crate::stdlib::native_tag(v).as_deref() {
17229 Some(t @ ("WeakRef" | "FinalizationRegistry")) => render(t),
17230 _ => None,
17231 },
17232 }
17233}
17234
17235/// `structuredClone(value[, { transfer }])`.
17236///
17237/// Everything in `transfer` must be an `ArrayBuffer`, and each one is DETACHED
17238/// after the clone — its bytes belong to the copy. The option used to be
17239/// ignored entirely, so the source buffer stayed usable where node leaves it
17240/// with zero length.
17241fn structured_clone(args: Vec<Value>) -> Result<Value, String> {
17242 let list: Vec<Value> = match args.get(1).filter(|v| !matches!(v, Value::Undef)) {
17243 Some(opts) => {
17244 let t = get_property(opts, "transfer")?;
17245 if matches!(t, Value::Undef) {
17246 Vec::new()
17247 } else {
17248 host::iter_all(&t)?
17249 }
17250 }
17251 None => Vec::new(),
17252 };
17253 for item in &list {
17254 if crate::stdlib::native_tag(item).as_deref() != Some("ArrayBuffer") {
17255 return Err(host::dom_error(
17256 "DataCloneError",
17257 "Found invalid value in transferList.",
17258 ));
17259 }
17260 // The Buffer pool is marked untransferable.
17261 if crate::stdlib::typedarray::is_untransferable(item) {
17262 return Err(host::dom_error(
17263 "DataCloneError",
17264 "Cannot transfer object of unsupported type.",
17265 ));
17266 }
17267 }
17268 let out = deep_clone(&arg0(&args))?;
17269 for item in &list {
17270 crate::stdlib::typedarray::detach_buffer(item);
17271 }
17272 Ok(out)
17273}
17274
17275pub(crate) fn deep_clone(v: &Value) -> Result<Value, String> {
17276 deep_clone_seen(v, &mut std::collections::HashMap::new())
17277}
17278
17279fn deep_clone_seen(
17280 v: &Value,
17281 seen: &mut std::collections::HashMap<u32, Value>,
17282) -> Result<Value, String> {
17283 let idx = match v {
17284 Value::Obj(i) => *i,
17285 _ => return Ok(v.clone()),
17286 };
17287 if let Some(done) = seen.get(&idx) {
17288 return Ok(done.clone());
17289 }
17290 if crate::stdlib::typedarray::is_detached(v) {
17291 return Err(host::dom_error(
17292 "DataCloneError",
17293 "An ArrayBuffer is detached and could not be cloned.",
17294 ));
17295 }
17296 if let Some(render) = clone_refusal(v) {
17297 return Err(host::dom_error(
17298 "DataCloneError",
17299 &format!("{render} could not be cloned."),
17300 ));
17301 }
17302 // A REGEXP is cloned, not shared: it carries a mutable `lastIndex`, so
17303 // handing back the same object let a write through the clone move the
17304 // original's match cursor.
17305 if let Some((src, flags)) = with_host(|h| match h.get(v) {
17306 Some(JsObj::RegExp(r)) => Some((r.source.clone(), r.flags.clone())),
17307 _ => None,
17308 }) {
17309 let args = with_host(|h| vec![h.new_str(src), h.new_str(flags)]);
17310 let out = regexp_ctor(&args, false)?;
17311 seen.insert(idx, out.clone());
17312 return Ok(out);
17313 }
17314 Ok(match with_host(|h| h.get(v).cloned()) {
17315 Some(JsObj::Array(items)) => {
17316 // Register the (empty) clone BEFORE recursing so a self-reference
17317 // resolves to it.
17318 let out = with_host(|h| h.new_array(Vec::new()));
17319 seen.insert(idx, out.clone());
17320 let mut cloned: Vec<Value> = Vec::with_capacity(items.len());
17321 for x in &items {
17322 cloned.push(deep_clone_seen(x, seen)?);
17323 }
17324 with_host(|h| {
17325 if let Some(JsObj::Array(a)) = h.get_mut(&out) {
17326 *a = cloned;
17327 }
17328 // A sparse source clones to an equally sparse array: the clone
17329 // walks own properties, so a hole is nothing to copy.
17330 h.copy_holes(v, &out, Some);
17331 });
17332 out
17333 }
17334 Some(JsObj::Object(_)) => {
17335 let out = with_host(|h| h.new_object(IndexMap::new()));
17336 seen.insert(idx, out.clone());
17337 // Own ENUMERABLE string keys, read THROUGH any accessor: the clone
17338 // walked the property map, where an accessor stores nothing, so
17339 // `structuredClone({get p(){return 1}})` silently lost `p`. A symbol
17340 // key and a non-enumerable one are dropped, as node drops them.
17341 let is_error = with_host(|h| h.error_to_string(v)).is_some();
17342 let proto = clone_proto(v);
17343 let keeps_proto = !matches!(proto, CloneProto::Plain);
17344 // An ERROR clones its name, message and stack and NOTHING else —
17345 // node drops any other own property, even an enumerable one.
17346 let keys: Vec<String> = if is_error {
17347 // An ERROR clones its name, message and stack and NOTHING else —
17348 // node drops any other own property, even an enumerable one.
17349 ["name", "message", "stack"]
17350 .iter()
17351 .filter(|k| has_property(v, k).unwrap_or(false))
17352 .map(|k| (*k).to_string())
17353 .collect()
17354 } else if keeps_proto {
17355 // A preserved exotic keeps EVERY own property, including the
17356 // non-enumerable ones and the internal slots — a Date's time
17357 // value, an ArrayBuffer's `byteLength` and byte store, a typed
17358 // array's view. The enumerable-only walk dropped all of those,
17359 // so a cloned Date read `Invalid Date` and a cloned
17360 // ArrayBuffer had no `byteLength`.
17361 with_host(|h| match h.get(v) {
17362 Some(JsObj::Object(p)) => p.keys().cloned().collect(),
17363 _ => Vec::new(),
17364 })
17365 } else {
17366 with_host(|h| h.own_enum_key_names(v))
17367 };
17368 let mut cloned: IndexMap<String, Value> = IndexMap::new();
17369 for k in keys {
17370 // An internal slot is read straight out of the map: it is not a
17371 // property, so a `[[Get]]` would not find it.
17372 let val = if k.starts_with("@@") {
17373 match with_host(|h| match h.get(v) {
17374 Some(JsObj::Object(p)) => p.get(&k).cloned(),
17375 _ => None,
17376 }) {
17377 Some(val) => val,
17378 None => continue,
17379 }
17380 } else {
17381 get_property(v, &k)?
17382 };
17383 cloned.insert(k, deep_clone_seen(&val, seen)?);
17384 }
17385 // The prototype survives only for the exotics the algorithm knows —
17386 // a Date, an Error, a typed array, a boxed primitive. A USER class
17387 // instance becomes a plain object, which is what node produces;
17388 // keeping every prototype made `structuredClone(new K())
17389 // instanceof K` true.
17390 with_host(|h| {
17391 if let Some(JsObj::Object(p)) = h.get_mut(&out) {
17392 *p = cloned;
17393 }
17394 match &proto {
17395 CloneProto::Same => {
17396 if let Some(p) = h.proto_of(v) {
17397 h.set_proto(&out, p);
17398 }
17399 }
17400 CloneProto::Ctor(c) => {
17401 h.ensure_error_protos();
17402 let p = h.error_proto(c).or_else(|| h.ensure_ctor_proto(c));
17403 if let Some(p) = p {
17404 h.set_proto(&out, p);
17405 }
17406 // A Buffer clones to a plain `Uint8Array`, so the native
17407 // tag has to change with the prototype — left alone,
17408 // `Buffer.isBuffer` still answered true for the clone.
17409 // A Buffer clones to a plain `Uint8Array`, so the native
17410 // tag has to change with the prototype — left alone,
17411 // `Buffer.isBuffer` answered true for the clone and the
17412 // brand stayed `[object Object]`. A typed array is
17413 // tagged `TypedArray` and names its element type in
17414 // `@@kind`; `@@native = "Uint8Array"` matches no arm.
17415 if c == "Uint8Array" {
17416 let tag = h.new_str("TypedArray");
17417 let kind = h.new_str("Uint8Array");
17418 if let Some(JsObj::Object(p)) = h.get_mut(&out) {
17419 p.insert("@@native".into(), tag);
17420 p.insert("@@kind".into(), kind);
17421 }
17422 }
17423 }
17424 CloneProto::Plain => {}
17425 }
17426 h.copy_prop_attrs(v, &out);
17427 });
17428 out
17429 }
17430 // Map/Set are structured types: clone the entries, keep the kind.
17431 Some(JsObj::Map { entries, weak }) => {
17432 let out = with_host(|h| {
17433 h.alloc(JsObj::Map {
17434 entries: IndexMap::new(),
17435 weak,
17436 })
17437 });
17438 seen.insert(idx, out.clone());
17439 let pairs: Vec<(Value, Value)> = entries.values().cloned().collect();
17440 for (k, val) in pairs {
17441 let ck = deep_clone_seen(&k, seen)?;
17442 let cv = deep_clone_seen(&val, seen)?;
17443 let _ = map_method(&out, "set", vec![ck, cv]);
17444 }
17445 out
17446 }
17447 Some(JsObj::Set { entries, weak }) => {
17448 let out = with_host(|h| {
17449 h.alloc(JsObj::Set {
17450 entries: IndexMap::new(),
17451 weak,
17452 })
17453 });
17454 seen.insert(idx, out.clone());
17455 let vals: Vec<Value> = entries.values().cloned().collect();
17456 for x in vals {
17457 let cx = deep_clone_seen(&x, seen)?;
17458 let _ = set_method(&out, "add", vec![cx]);
17459 }
17460 out
17461 }
17462 // A string, a BigInt and a boxed primitive are immutable enough to
17463 // share; anything left is a value type.
17464 _ => v.clone(),
17465 })
17466}
17467
17468/// Whether a cloned object keeps the source's prototype.
17469///
17470/// The structured clone algorithm reproduces the exotics it knows and turns
17471/// everything else into a plain object — so a `Date` clones to a `Date` and a
17472/// user class instance clones to an `Object`.
17473fn clone_proto(v: &Value) -> CloneProto {
17474 // An ERROR clones to the BUILT-IN class its `name` selects, so a subclass
17475 // flattens: `structuredClone(new (class E extends Error{})('m'))` reports
17476 // `Error`, not `E`.
17477 if with_host(|h| h.error_to_string(v)).is_some() {
17478 let name = get_property(v, "name")
17479 .map(|n| with_host(|h| h.str_of(&n)))
17480 .unwrap_or_else(|_| "Error".into());
17481 let class = if host::ERROR_NAMES.contains(&name.as_str()) {
17482 name
17483 } else {
17484 "Error".to_string()
17485 };
17486 return CloneProto::Ctor(class);
17487 }
17488 match crate::stdlib::native_tag(v).as_deref() {
17489 // A Buffer is not reproduced as a Buffer: node hands back a plain
17490 // `Uint8Array` over the same bytes.
17491 Some("Buffer") => CloneProto::Ctor("Uint8Array".into()),
17492 Some(_) => CloneProto::Same,
17493 // A boxed primitive keeps its wrapper; anything else — a user class
17494 // instance included — becomes a plain object.
17495 None if wrapped_primitive(v).is_some() => CloneProto::Same,
17496 None => CloneProto::Plain,
17497 }
17498}
17499
17500/// Which prototype a clone gets: the source's, a named builtin's, or none.
17501enum CloneProto {
17502 Same,
17503 Ctor(String),
17504 Plain,
17505}
17506
17507// ══ Promises, timers, microtasks (event-loop-driven) ═════════════════════════
17508
17509/// A short `Name: message` string for an error value (used when an await
17510/// rejection unwinds as a thrown error).
17511pub fn error_string(h: &host::JsHost, v: &Value) -> String {
17512 if let Some(JsObj::Object(props)) = h.get(v) {
17513 let name = props
17514 .get("name")
17515 .map(|x| h.str_of(x))
17516 .or_else(|| host::lookup_chain(h, v, "name").map(|x| h.str_of(&x)))
17517 .unwrap_or_else(|| "Error".into());
17518 if let Some(m) = props.get("message") {
17519 return format!("{name}: {}", h.str_of(m));
17520 }
17521 return name;
17522 }
17523 h.str_of(v)
17524}
17525
17526/// 27.2.5.3 `thenFinally`/`catchFinally`: `PromiseResolve(result).then(() =>
17527/// value)`, or `() => { throw reason }` on the reject path.
17528///
17529/// Returning the carried value directly — what this used to do — skipped both
17530/// halves. A promise returned by the callback was never awaited, so the
17531/// ordinary async-cleanup shape
17532///
17533/// ```text
17534/// work().finally(() => closeConnection()).then(next)
17535/// ```
17536///
17537/// ran `next` before the connection had closed. And the chain settled three
17538/// microtask ticks early, which is observable in ordering against any other
17539/// chain, not just against a timer.
17540///
17541/// A rejection from the callback's own promise wins over the carried value, so
17542/// no reject handler is attached here: it propagates on its own.
17543fn finally_chain(result: Value, carried: Value, rethrow: bool) -> Value {
17544 // PromiseResolve (27.2.4.7) returns an argument that is already a promise
17545 // UNCHANGED. Wrapping it anyway costs the extra tick that resolving with a
17546 // thenable takes to adopt it, which showed up as a callback returning a
17547 // rejected promise settling one tick late against every other chain.
17548 let p = match with_host(|h| h.promise_id(&result)) {
17549 Some(_) => result,
17550 None => {
17551 let fresh = with_host(|h| h.new_promise());
17552 if let Some(pid) = with_host(|h| h.promise_id(&fresh)) {
17553 host::resolve_promise_val(pid, result);
17554 }
17555 fresh
17556 }
17557 };
17558 let cell = with_host(|h| h.new_array(vec![carried]));
17559 let idx = match cell {
17560 Value::Obj(i) => i,
17561 _ => 0,
17562 };
17563 let tag = if rethrow { "finrethrow" } else { "finret" };
17564 let thunk = make_builtin(format!("@@{tag}:{idx}"));
17565 host::promise_then(&p, thunk, Value::Undef)
17566}
17567
17568fn make_builtin(name: String) -> Value {
17569 with_host(|h| h.alloc(JsObj::Builtin(name)))
17570}
17571
17572/// `[[GetPrototypeOf]]` (10.1.1) — the answer `Object.getPrototypeOf`,
17573/// `Reflect.getPrototypeOf` and a `__proto__` READ all have to agree on.
17574///
17575/// `__proto__` used to answer from `JsHost::proto_of` alone, which records only
17576/// an EXPLICIT link, so an object on the default prototype reported `null`:
17577/// `({}).__proto__ === Object.prototype` was false while
17578/// `Object.getPrototypeOf({}) === Object.prototype` was true. One function, so
17579/// the three cannot drift apart again.
17580pub fn prototype_of(v: &Value) -> Value {
17581 // Constructor-side inheritance: `Buffer extends Uint8Array`, so
17582 // `Object.getPrototypeOf(Buffer)` is the `Uint8Array` constructor itself,
17583 // not `Function.prototype`. This is the class-side half of the subclass
17584 // link — the instance-side half is `Buffer.prototype`'s `[[Prototype]]`.
17585 if matches!(with_host(|h| h.get(v).cloned()), Some(JsObj::Builtin(ref n)) if n == "Buffer") {
17586 return with_host(|h| h.alloc(JsObj::Builtin("Uint8Array".into())));
17587 }
17588 // A singleton is an instance of its class: `performance`'s prototype is
17589 // `Performance.prototype`, `crypto`'s is `Crypto.prototype`.
17590 if let Some(JsObj::Builtin(n)) = with_host(|h| h.get(v).cloned()) {
17591 if let Some(class) = crate::stdlib::singleton_class(&n) {
17592 if let Some(p) = with_host(|h| h.ensure_ctor_proto(class)) {
17593 return p;
17594 }
17595 }
17596 }
17597 // The NativeError constructors inherit from `Error` (20.5.6.2: their
17598 // `[[Prototype]]` is %Error%), so `Object.getPrototypeOf(RangeError) ===
17599 // Error`. They reported `null`.
17600 if matches!(
17601 with_host(|h| h.get(v).cloned()),
17602 Some(JsObj::Builtin(ref n)) if matches!(
17603 n.as_str(),
17604 "EvalError" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError"
17605 | "URIError" | "AggregateError"
17606 )
17607 ) {
17608 return with_host(|h| h.alloc(JsObj::Builtin("Error".into())));
17609 }
17610 // Constructor-side inheritance for a `class B extends A` (ClassDefinition
17611 // 15.7.14 step 6.d: the constructor's `[[Prototype]]` is the parent
17612 // CONSTRUCTOR, not `Function.prototype`). Statics already resolved through
17613 // `ClassVal.parent`, but the link itself was invisible, so
17614 // `Object.getPrototypeOf(B) === A` read false and any library walking the
17615 // constructor chain — rather than calling a static — saw a base class.
17616 // A base class keeps the default answer below (`Function.prototype`).
17617 if let Some(JsObj::Class(c)) = with_host(|h| h.get(v).cloned()) {
17618 if let Some(parent) = c.parent {
17619 return parent;
17620 }
17621 }
17622 // `Object.create(null)` and friends really do have a null prototype.
17623 if with_host(|h| h.has_null_proto(v)) {
17624 return with_host(|h| h.null());
17625 }
17626 // `Object.prototype` is the CHAIN ROOT, so its own prototype is `null`. It
17627 // reported itself, because the fallback below answers by constructor name
17628 // and a plain object's is `Object` — an infinite chain to anything walking
17629 // it.
17630 if with_host(|h| h.strict_eq(v, &h.object_proto())) {
17631 return with_host(|h| h.null());
17632 }
17633 // Every OTHER builtin prototype namespace (`Array.prototype`,
17634 // `Function.prototype`, …) inherits from `Object.prototype`; the fallback
17635 // would send it back to a namespace handle for its own constructor.
17636 if matches!(
17637 with_host(|h| h.get(v).cloned()),
17638 Some(JsObj::Builtin(ref n)) if n.ends_with(".prototype")
17639 ) {
17640 return with_host(|h| h.object_proto());
17641 }
17642 if let Some(p) = with_host(|h| h.proto_of(v)) {
17643 return p;
17644 }
17645 // A builtin exotic with no explicit `[[Prototype]]` link reports its
17646 // constructor's prototype namespace (`Object.getPrototypeOf([]) ===
17647 // Array.prototype`), which `strict_eq` compares by name. A plain object
17648 // reports the one real `Object.prototype` object.
17649 with_host(|h| {
17650 h.ensure_native_protos();
17651 match default_ctor_name(h, v) {
17652 Some("Object") => h.object_proto(),
17653 // `String`/`Number`/`Boolean` own REAL prototype objects, so a
17654 // primitive must report that object and not a fresh namespace
17655 // thunk — otherwise `Object.getPrototypeOf(1) === Number.prototype`
17656 // compares a thunk against the real object and reads false.
17657 Some(c) => h
17658 .native_proto(c)
17659 .unwrap_or_else(|| h.alloc(JsObj::Builtin(format!("{c}.prototype")))),
17660 // A builtin FUNCTION (`Error`, `Math.max`, `parseInt`) is an ordinary
17661 // function object whose `[[Prototype]]` is `Function.prototype`.
17662 None if h.type_of(v) == "function" => h
17663 .native_proto("Function")
17664 .unwrap_or_else(|| h.alloc(JsObj::Builtin("Function.prototype".into()))),
17665 None => h.null(),
17666 }
17667 })
17668}
17669
17670/// `new Promise((resolve, reject) => …)` — run the executor synchronously with
17671/// internal resolve/reject functions.
17672/// A fresh promise built through the SPECIES constructor, when a `Promise`
17673/// static was reached through a subclass.
17674///
17675/// `class P extends Promise {}` makes `P.resolve(1)` a `P`, because every
17676/// combinator builds its result with `this` (27.2.4.x). They all allocated a
17677/// plain promise, so nothing a subclass produced was an instance of it. The
17678/// executor is a no-op: the result is settled through its promise id, which is
17679/// what the ordinary path does too.
17680fn promise_species_create() -> Result<Option<Value>, String> {
17681 let Some(ctor) = host::current_static_this() else {
17682 return Ok(None);
17683 };
17684 if !matches!(
17685 with_host(|h| h.kind_of(&ctor)),
17686 Some(ObjKind::Class) | Some(ObjKind::Func)
17687 ) {
17688 return Ok(None);
17689 }
17690 let species = match get_property(&ctor, "@@species") {
17691 Ok(Value::Undef) => ctor,
17692 Ok(s) if with_host(|h| h.is_null(&s)) => return Ok(None),
17693 Ok(s) => s,
17694 Err(_) => ctor,
17695 };
17696 if !matches!(
17697 with_host(|h| h.kind_of(&species)),
17698 Some(ObjKind::Class) | Some(ObjKind::Func)
17699 ) {
17700 return Ok(None);
17701 }
17702 let noop = make_builtin("@@pnoop".to_string());
17703 let p = host::construct(&species, vec![noop])?;
17704 // Only usable if the subclass really produced a promise; a constructor that
17705 // returned something else has no id to settle.
17706 Ok(with_host(|h| h.promise_id(&p)).map(|_| p))
17707}
17708
17709/// The species constructor of a promise RECEIVER — what `then`/`catch`/`finally`
17710/// build their result with (`SpeciesConstructor(p, %Promise%)`, 27.2.5.4 step 3).
17711///
17712/// Distinct from `promise_species_create`, which answers for a STATIC reached
17713/// through a subclass. Here the subclass comes from the receiver itself, so
17714/// `P.resolve(1).then(f)` is also a `P`.
17715pub fn promise_species_from(recv: &Value) -> Result<Option<Value>, String> {
17716 // A chain lookup: a Promise receiver resolves through the stdlib funnel,
17717 // which has no `constructor` entry of its own.
17718 let ctor = with_host(|h| host::lookup_chain(h, recv, "constructor")).unwrap_or(Value::Undef);
17719 if !matches!(
17720 with_host(|h| h.kind_of(&ctor)),
17721 Some(ObjKind::Class) | Some(ObjKind::Func)
17722 ) {
17723 return Ok(None);
17724 }
17725 let species = match get_property(&ctor, "@@species") {
17726 Ok(Value::Undef) => ctor,
17727 Ok(s) if with_host(|h| h.is_null(&s)) => return Ok(None),
17728 Ok(s) => s,
17729 Err(_) => ctor,
17730 };
17731 if !matches!(
17732 with_host(|h| h.kind_of(&species)),
17733 Some(ObjKind::Class) | Some(ObjKind::Func)
17734 ) {
17735 return Ok(None);
17736 }
17737 let noop = make_builtin("@@pnoop".to_string());
17738 let p = host::construct(&species, vec![noop])?;
17739 Ok(with_host(|h| h.promise_id(&p)).map(|_| p))
17740}
17741
17742fn new_promise(executor: Value) -> Result<Value, String> {
17743 // 27.2.3.1 step 2: a non-callable executor throws before any promise exists.
17744 if !with_host(|h| host::is_callable(h, &executor)) {
17745 let shown = no_side_effects_string(&executor);
17746 return Err(host::type_error(&format!(
17747 "Promise resolver {shown} is not a function"
17748 )));
17749 }
17750 let p = with_host(|h| h.new_promise());
17751 let id = with_host(|h| h.promise_id(&p).unwrap());
17752 let res = make_builtin(format!("@@presolve:{id}"));
17753 let rej = make_builtin(format!("@@preject:{id}"));
17754 if let Err(e) = host::invoke(&executor, vec![res, rej], None) {
17755 // A throw in the executor rejects the promise.
17756 let ev = host::take_exc_or_error(&e);
17757 host::reject_promise_val(id, ev);
17758 }
17759 Ok(p)
17760}
17761
17762/// `Promise.resolve(v)` for stdlib callers that need to hand back an
17763/// already-settled promise.
17764pub fn promise_resolve_pub(v: Value) -> Result<Value, String> {
17765 promise_resolve(v)
17766}
17767
17768fn promise_resolve(v: Value) -> Result<Value, String> {
17769 if let Some(p) = promise_species_create()? {
17770 let id = with_host(|h| h.promise_id(&p).unwrap());
17771 host::resolve_promise_val(id, v);
17772 return Ok(p);
17773 }
17774 Ok(host::promise_of(&v))
17775}
17776fn promise_reject(v: Value) -> Result<Value, String> {
17777 let p = match promise_species_create()? {
17778 Some(p) => p,
17779 None => with_host(|h| h.new_promise()),
17780 };
17781 let id = with_host(|h| h.promise_id(&p).unwrap());
17782 host::reject_promise_val(id, v);
17783 Ok(p)
17784}
17785
17786/// `Promise.withResolvers()` — a fresh pending promise paired with its own
17787/// resolve/reject continuations (the same `@@presolve`/`@@preject` thunks the
17788/// executor receives), returned as a plain `{ promise, resolve, reject }` object.
17789/// A fresh pending promise paired with the thunk that resolves it, for stdlib
17790/// callers that hand the resolver to an event listener.
17791pub fn pending_promise_with_resolver() -> (Value, Value) {
17792 let p = with_host(|h| h.new_promise());
17793 let id = with_host(|h| h.promise_id(&p).unwrap());
17794 let resolve = make_builtin(format!("@@presolve:{id}"));
17795 (p, resolve)
17796}
17797
17798/// `RegExp.escape(s)` (22.2.4.2) — a string that matches `s` literally.
17799///
17800/// The rule is not "backslash the syntax characters": it also escapes a LEADING
17801/// ASCII alphanumeric, so the result can be concatenated after a `\` or a `{`
17802/// without the two running together, and it escapes the punctuation that is
17803/// meaningful inside a character class or a group name.
17804fn regexp_escape(args: Vec<Value>) -> Result<Value, String> {
17805 let v = arg0(&args);
17806 if !matches!(v, Value::Str(_)) && !with_host(|h| matches!(h.get(&v), Some(JsObj::Str(_)))) {
17807 return Err(host::type_error("input argument must be a string"));
17808 }
17809 let s = with_host(|h| h.str_of(&v));
17810 // Punctuation that is escaped by CODE POINT rather than with a backslash.
17811 // Measured against node over the whole ASCII range, not taken from a list:
17812 // `-` and `=` are here, `$` and `*` are syntax characters and are not.
17813 const OTHER_PUNCTUATORS: &str = " !\"#%&',-:;<=>@`~";
17814 const SYNTAX: &str = "^$\\.*+?()[]{}|/";
17815 let mut out = String::with_capacity(s.len());
17816 for (i, c) in s.chars().enumerate() {
17817 // A leading ASCII alphanumeric, and only a leading one.
17818 if i == 0 && c.is_ascii_alphanumeric() {
17819 out.push_str(&format!("\\x{:02x}", c as u32));
17820 continue;
17821 }
17822 if SYNTAX.contains(c) {
17823 out.push('\\');
17824 out.push(c);
17825 continue;
17826 }
17827 match c {
17828 '\t' => out.push_str("\\t"),
17829 '\n' => out.push_str("\\n"),
17830 '\u{b}' => out.push_str("\\v"),
17831 '\u{c}' => out.push_str("\\f"),
17832 '\r' => out.push_str("\\r"),
17833 _ if OTHER_PUNCTUATORS.contains(c) || is_regex_escape_space(c) => {
17834 let n = c as u32;
17835 if n <= 0xff {
17836 out.push_str(&format!("\\x{n:02x}"));
17837 } else {
17838 out.push_str(&format!("\\u{n:04x}"));
17839 }
17840 }
17841 _ => out.push(c),
17842 }
17843 }
17844 Ok(with_host(|h| h.new_str(out)))
17845}
17846
17847/// The WhiteSpace and LineTerminator code points `RegExp.escape` spells out.
17848/// Deliberately NOT `char::is_whitespace`: U+180E and U+200B are whitespace to
17849/// Unicode but not to ECMAScript, and node leaves both alone.
17850fn is_regex_escape_space(c: char) -> bool {
17851 matches!(
17852 c,
17853 '\u{a0}' | '\u{1680}' | '\u{2000}'
17854 ..='\u{200a}'
17855 | '\u{2028}'
17856 | '\u{2029}'
17857 | '\u{202f}'
17858 | '\u{205f}'
17859 | '\u{3000}'
17860 | '\u{feff}'
17861 )
17862}
17863
17864/// `Error.isError(v)` (20.5.2.1) — a brand check for `[[ErrorData]]`, so an
17865/// object that merely INHERITS from `Error.prototype` is not one.
17866fn error_is_error(args: Vec<Value>) -> Result<Value, String> {
17867 let v = arg0(&args);
17868 Ok(Value::Bool(with_host(|h| has_error_data(h, &v))))
17869}
17870
17871/// Whether `v` carries `[[ErrorData]]` — the slot `Error.isError` (20.5.2.1)
17872/// and `Object.prototype.toString`'s step 9 both test.
17873///
17874/// The brand is the OWN `stack` an error is built with (a `DOMException`
17875/// carries `@@domName` instead); a plain `Object.create(Error.prototype)` has
17876/// neither, which is why inheriting from an error prototype does not make a
17877/// value an error. Shared so the two cannot disagree — branding by a chain
17878/// lookup for `name`/`message` made `Object.create(Error.prototype)` report
17879/// `[object Error]` where node says `[object Object]`, while `Error.isError`
17880/// on the same value already said false.
17881pub(crate) fn has_error_data(h: &host::JsHost, v: &Value) -> bool {
17882 match h.get(v) {
17883 Some(JsObj::Object(p)) => {
17884 p.contains_key("stack") || p.contains_key("@@stackRaw") || p.contains_key("@@domName")
17885 }
17886 _ => false,
17887 }
17888}
17889
17890/// `Promise.try(fn, ...args)` (27.2.4.6) — call `fn` and settle the promise with
17891/// what it does, so a SYNCHRONOUS throw becomes a rejection instead of
17892/// propagating. `Promise.resolve().then(fn)` is the shape it replaces, and it
17893/// costs a tick that this does not.
17894fn promise_try(args: Vec<Value>) -> Result<Value, String> {
17895 let f = arg0(&args);
17896 // A non-callable argument REJECTS, it does not throw: `Promise.try(5)`
17897 // returns a rejected promise, so the surrounding `try` never sees it.
17898 if !with_host(|h| host::is_callable(h, &f)) {
17899 // Node names the TYPE alongside the value — `number 5 is not a
17900 // function` — which the ordinary call-site message does not. A plain
17901 // object and a symbol name only the type; `null` names both.
17902 let shown = with_host(|h| {
17903 let kind = h.type_of(&f);
17904 match kind {
17905 "undefined" => "undefined".to_string(),
17906 "symbol" | "bigint" => kind.to_string(),
17907 "object" if h.is_null(&f) => "object null".to_string(),
17908 "object" => "object".to_string(),
17909 "string" => format!("string \"{}\"", h.str_of(&f)),
17910 _ => format!("{kind} {}", h.str_of(&f)),
17911 }
17912 });
17913 let p = with_host(|h| h.new_promise());
17914 let id = with_host(|h| h.promise_id(&p).unwrap());
17915 let reject = make_builtin(format!("@@preject:{id}"));
17916 let err =
17917 with_host(|h| synth_error(h, &host::type_error(&format!("{shown} is not a function"))));
17918 host::invoke(&reject, vec![err], None)?;
17919 return Ok(p);
17920 }
17921 let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
17922 let p = with_host(|h| h.new_promise());
17923 let id = with_host(|h| h.promise_id(&p).unwrap());
17924 let resolve = make_builtin(format!("@@presolve:{id}"));
17925 let reject = make_builtin(format!("@@preject:{id}"));
17926 let promise = p;
17927 match host::invoke(&f, rest, None) {
17928 Ok(v) => {
17929 host::invoke(&resolve, vec![v], None)?;
17930 }
17931 Err(e) => {
17932 // The thrown VALUE, not a re-synthesis of its rendering: a callback
17933 // that throws a `TypeError` must reject with that object, and
17934 // rebuilding it from the message string flattened it to a plain
17935 // `Error` whose message was the rendered `Uncaught TypeError: t`.
17936 let err =
17937 with_host(|h| h.exc.clone()).unwrap_or_else(|| with_host(|h| synth_error(h, &e)));
17938 with_host(|h| {
17939 h.error = None;
17940 h.exc = None;
17941 h.throw_site = None;
17942 });
17943 host::invoke(&reject, vec![err], None)?;
17944 }
17945 }
17946 Ok(promise)
17947}
17948
17949fn promise_with_resolvers() -> Result<Value, String> {
17950 let p = with_host(|h| h.new_promise());
17951 let id = with_host(|h| h.promise_id(&p).unwrap());
17952 let resolve = make_builtin(format!("@@presolve:{id}"));
17953 let reject = make_builtin(format!("@@preject:{id}"));
17954 let mut props: IndexMap<String, Value> = IndexMap::new();
17955 props.insert("promise".into(), p);
17956 props.insert("resolve".into(), resolve);
17957 props.insert("reject".into(), reject);
17958 Ok(with_host(|h| h.new_object(props)))
17959}
17960
17961/// A promise already rejected with `e` — what every combinator hands back when
17962/// the ITERABLE misbehaves.
17963///
17964/// 27.2.4.1 step 4 catches an abrupt completion from the iteration and rejects
17965/// rather than letting it propagate, so `Promise.all(badIterable)` returns a
17966/// rejected promise. Throwing synchronously meant a `.catch()` never attached
17967/// and the caller saw the error at the call site instead.
17968fn rejected_promise(e: String) -> Value {
17969 let p = with_host(|h| h.new_promise());
17970 let id = with_host(|h| h.promise_id(&p).unwrap());
17971 let reject = make_builtin(format!("@@preject:{id}"));
17972 let err = with_host(|h| h.exc.clone()).unwrap_or_else(|| with_host(|h| synth_error(h, &e)));
17973 with_host(|h| {
17974 h.error = None;
17975 h.exc = None;
17976 h.throw_site = None;
17977 });
17978 let _ = host::invoke(&reject, vec![err], None);
17979 p
17980}
17981
17982#[derive(Clone, Copy)]
17983enum AllMode {
17984 All,
17985 AllSettled,
17986}
17987
17988/// `Promise.all` / `Promise.allSettled`.
17989fn promise_all(args: Vec<Value>, mode: AllMode) -> Result<Value, String> {
17990 let items = match host::iter_all_for_builtin(&arg0(&args)) {
17991 Ok(v) => v,
17992 Err(e) => return Ok(rejected_promise(e)),
17993 };
17994 // 27.2.4.1 step 3: the combinator builds its result with `this`, so on a
17995 // subclass the promise it hands back is an instance of that subclass.
17996 let result = match promise_species_create()? {
17997 Some(p) => p,
17998 None => with_host(|h| h.new_promise()),
17999 };
18000 let rid = with_host(|h| h.promise_id(&result).unwrap());
18001 let n = items.len();
18002 if n == 0 {
18003 let empty = with_host(|h| h.new_array(Vec::new()));
18004 host::resolve_promise_val(rid, empty);
18005 return Ok(result);
18006 }
18007 // Shared mutable accumulator via Rc<RefCell<…>>.
18008 let slots = std::rc::Rc::new(std::cell::RefCell::new(vec![Value::Undef; n]));
18009 let remaining = std::rc::Rc::new(std::cell::RefCell::new(n));
18010 for (i, it) in items.into_iter().enumerate() {
18011 let ap = host::promise_of(&it);
18012 let aid = with_host(|h| h.promise_id(&ap).unwrap());
18013 let slots = slots.clone();
18014 let remaining = remaining.clone();
18015 host::subscribe_native(
18016 aid,
18017 Box::new(move |state, val| {
18018 let settled = match mode {
18019 AllMode::All => {
18020 if state == host::PromiseState::Rejected {
18021 host::reject_promise_val(rid, val);
18022 return Ok(());
18023 }
18024 val
18025 }
18026 AllMode::AllSettled => with_host(|h| {
18027 let mut m: IndexMap<String, Value> = IndexMap::new();
18028 if state == host::PromiseState::Rejected {
18029 m.insert("status".into(), h.new_str("rejected"));
18030 m.insert("reason".into(), val);
18031 } else {
18032 m.insert("status".into(), h.new_str("fulfilled"));
18033 m.insert("value".into(), val);
18034 }
18035 h.new_object(m)
18036 }),
18037 };
18038 slots.borrow_mut()[i] = settled;
18039 let mut r = remaining.borrow_mut();
18040 *r -= 1;
18041 if *r == 0 {
18042 let arr = with_host(|h| h.new_array(slots.borrow().clone()));
18043 host::resolve_promise_val(rid, arr);
18044 }
18045 Ok(())
18046 }),
18047 );
18048 }
18049 Ok(result)
18050}
18051
18052/// `Promise.race` (first to settle wins) / `Promise.any` (first to fulfill wins).
18053fn promise_race(args: Vec<Value>, any: bool) -> Result<Value, String> {
18054 let items = match host::iter_all_for_builtin(&arg0(&args)) {
18055 Ok(v) => v,
18056 Err(e) => return Ok(rejected_promise(e)),
18057 };
18058 // Built with `this`, as every combinator is (27.2.4.5 / 27.2.4.3).
18059 let result = match promise_species_create()? {
18060 Some(p) => p,
18061 None => with_host(|h| h.new_promise()),
18062 };
18063 let rid = with_host(|h| h.promise_id(&result).unwrap());
18064 let n = items.len();
18065 // `Promise.any` of an empty iterable: remainingElementsCount drops to 0
18066 // right after the loop (27.2.4.3.1 step 8.d), so it rejects at once.
18067 if any && n == 0 {
18068 host::reject_promise_val(rid, promise_any_rejection(Vec::new()));
18069 return Ok(result);
18070 }
18071 let errors = std::rc::Rc::new(std::cell::RefCell::new(vec![Value::Undef; n]));
18072 let remaining = std::rc::Rc::new(std::cell::RefCell::new(n));
18073 for (i, it) in items.into_iter().enumerate() {
18074 let ap = host::promise_of(&it);
18075 let aid = with_host(|h| h.promise_id(&ap).unwrap());
18076 let errors = errors.clone();
18077 let remaining = remaining.clone();
18078 host::subscribe_native(
18079 aid,
18080 Box::new(move |state, val| {
18081 if any {
18082 if state == host::PromiseState::Fulfilled {
18083 host::resolve_promise_val(rid, val);
18084 } else {
18085 errors.borrow_mut()[i] = val;
18086 let mut r = remaining.borrow_mut();
18087 *r -= 1;
18088 if *r == 0 {
18089 // All rejected → AggregateError carrying every reason.
18090 let agg = promise_any_rejection(errors.borrow().clone());
18091 host::reject_promise_val(rid, agg);
18092 }
18093 }
18094 } else if state == host::PromiseState::Rejected {
18095 host::reject_promise_val(rid, val);
18096 } else {
18097 host::resolve_promise_val(rid, val);
18098 }
18099 Ok(())
18100 }),
18101 );
18102 }
18103 Ok(result)
18104}
18105
18106/// The `AggregateError` a `Promise.any` rejects with. V8 builds it inside the
18107/// builtin with no JavaScript frames captured, so its `stack` is the header
18108/// line alone — which is also why `util.inspect` brackets it
18109/// (`[AggregateError: All promises were rejected] { [errors]: [...] }`).
18110fn promise_any_rejection(reasons: Vec<Value>) -> Value {
18111 let reasons = with_host(|h| h.new_array(reasons));
18112 let msg = with_host(|h| h.new_str("All promises were rejected"));
18113 let agg = make_error_inner("AggregateError", &[reasons, msg]);
18114 with_host(|h| {
18115 let header = h.new_str("AggregateError: All promises were rejected".to_string());
18116 if let Some(JsObj::Object(p)) = h.get_mut(&agg) {
18117 p.insert("stack".into(), header);
18118 p.shift_remove("@@stackRaw");
18119 }
18120 });
18121 agg
18122}
18123
18124/// `.then` / `.catch` / `.finally` on a promise.
18125fn promise_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
18126 match name {
18127 "then" => Ok(host::promise_then(
18128 recv,
18129 args.first().cloned().unwrap_or(Value::Undef),
18130 args.get(1).cloned().unwrap_or(Value::Undef),
18131 )),
18132 "catch" => Ok(host::promise_then(
18133 recv,
18134 Value::Undef,
18135 args.first().cloned().unwrap_or(Value::Undef),
18136 )),
18137 "finally" => {
18138 let cb = arg0(&args);
18139 // 27.2.5.3 step 3: a non-callable `onFinally` is handed to `then`
18140 // as BOTH handlers, and `then` ignores a non-callable one — so the
18141 // value or reason simply passes through. Building the thunks
18142 // regardless meant `p.finally(null)` tried to call `null`.
18143 if !with_host(|h| host::is_callable(h, &cb)) {
18144 return Ok(host::promise_then(recv, cb.clone(), cb));
18145 }
18146 let i = match cb {
18147 Value::Obj(i) => i,
18148 _ => 0,
18149 };
18150 let pass = make_builtin(format!("@@finpass:{i}"));
18151 let throw = make_builtin(format!("@@finthrow:{i}"));
18152 Ok(host::promise_then(recv, pass, throw))
18153 }
18154 _ => Err(host::type_error(&format!(
18155 "promise.{name} is not a function"
18156 ))),
18157 }
18158}
18159
18160fn enqueue_microtask(next_tick: bool, cb: Value, args: Vec<Value>) {
18161 with_host(|h| {
18162 if next_tick {
18163 h.queue_nexttick(cb, args);
18164 } else {
18165 h.queue_micro(cb, args);
18166 }
18167 });
18168}
18169
18170/// `setTimeout`/`setInterval`/`setImmediate` — register a macrotask and return
18171/// the handle object Node returns (`Timeout` for the first two, `Immediate` for
18172/// the third), carrying `ref`/`unref`/`hasRef`/`refresh`.
18173///
18174/// `setInterval` schedules a *repeating* timer: the loop re-arms it each time it
18175/// fires, so it runs until cleared and — being referenced — holds the process
18176/// open exactly as in Node.
18177fn schedule_timer(name: &str, args: Vec<Value>) -> Result<Value, String> {
18178 let cb = arg0(&args);
18179 let delay = if name == "setImmediate" {
18180 -1.0 // before any timeout
18181 } else {
18182 timeout_duration(args.get(1))?
18183 };
18184 let extra = if name == "setImmediate" {
18185 args.get(1..).map(|s| s.to_vec()).unwrap_or_default()
18186 } else {
18187 args.get(2..).map(|s| s.to_vec()).unwrap_or_default()
18188 };
18189 let interval = (name == "setInterval").then_some(delay);
18190 let id = with_host(|h| h.add_timer(delay, cb, extra, interval));
18191 let tag = if name == "setImmediate" {
18192 "Immediate"
18193 } else {
18194 "Timeout"
18195 };
18196 Ok(crate::stdlib::timers::new_handle(id, tag))
18197}
18198
18199thread_local! {
18200 static WARNED_NEGATIVE_TIMEOUT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
18201 static WARNED_NAN_TIMEOUT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
18202}
18203
18204/// The `Timeout` constructor's duration (lib/internal/timers.js): `undefined`
18205/// is 1, anything else is `after * 1`, and whatever is not in
18206/// `[1, TIMEOUT_MAX]` becomes 1 — so `setTimeout(f, 0)` and `setTimeout(f, 1)`
18207/// share one list and fire in the order they were set. Out-of-range values
18208/// warn as node does: an overflow every time, a negative number and a NaN once
18209/// per process.
18210fn timeout_duration(after: Option<&Value>) -> Result<f64, String> {
18211 const TIMEOUT_MAX: f64 = 2_147_483_647.0;
18212 let after = match after {
18213 None | Some(Value::Undef) => return Ok(1.0),
18214 Some(v) => host::to_number_value(v)?,
18215 };
18216 if (1.0..=TIMEOUT_MAX).contains(&after) {
18217 return Ok(after);
18218 }
18219 let shown = host::fmt_number(after);
18220 let warn = |name: &str, what: &str| {
18221 crate::stdlib::process::emit_warning(
18222 name,
18223 None,
18224 &format!("{shown} {what}\nTimeout duration was set to 1."),
18225 None,
18226 )
18227 };
18228 let first = |flag: &'static std::thread::LocalKey<std::cell::Cell<bool>>| {
18229 !flag.with(|f| f.replace(true))
18230 };
18231 if after > TIMEOUT_MAX {
18232 warn(
18233 "TimeoutOverflowWarning",
18234 "does not fit into a 32-bit signed integer.",
18235 );
18236 } else if after < 0.0 {
18237 if first(&WARNED_NEGATIVE_TIMEOUT) {
18238 warn("TimeoutNegativeWarning", "is a negative number.");
18239 }
18240 } else if after.is_nan() && first(&WARNED_NAN_TIMEOUT) {
18241 warn("TimeoutNaNWarning", "is not a number.");
18242 }
18243 Ok(1.0)
18244}
18245
18246/// `Math.f16round(x)` — `x` rounded to the nearest IEEE 754 binary16 value
18247/// (roundTiesToEven), returned as a double. A binary16 has 10 explicit
18248/// mantissa bits, a minimum normal exponent of -14 (below which the spacing is
18249/// fixed at the subnormal quantum 2^-24) and a largest finite value of 65504;
18250/// anything that rounds past it is an infinity of the same sign.
18251fn f16_round(x: f64) -> f64 {
18252 if !x.is_finite() || x == 0.0 {
18253 return x;
18254 }
18255 let a = x.abs();
18256 // Unbiased binary exponent of `a`; a double subnormal is far below the
18257 // binary16 range and lands in the subnormal quantum all the same.
18258 let exp = ((a.to_bits() >> 52) & 0x7ff) as i32 - 1023;
18259 let quantum = 2f64.powi(exp.max(-14) - 10);
18260 // `a / quantum` is exact (a power-of-two scaling), so this is the only
18261 // rounding step.
18262 let r = (a / quantum).round_ties_even() * quantum;
18263 let r = if r > 65504.0 { f64::INFINITY } else { r };
18264 r.copysign(x)
18265}
18266
18267/// `JSON.stringify` steps 4.b: the PropertyList a replacer ARRAY selects. Only
18268/// a String or Number element (primitive or wrapper) names a key, in
18269/// `ToString` form; every other element is ignored, and a key already listed
18270/// is not listed twice, so `["a", "a"]` emits `a` once. `IsArray` sees through
18271/// a Proxy, and the elements are read with `[[Get]]`, so its traps run.
18272fn json_property_list(replacer: Value) -> Result<Option<Vec<String>>, String> {
18273 // V8 asks `IsArray` before `IsCallable`, so a revoked proxy throws here.
18274 if !is_array(&replacer)? || with_host(|h| host::is_callable(h, &replacer)) {
18275 return Ok(None);
18276 }
18277 let len = host::to_number_value(&get_property(&replacer, "length")?)?;
18278 let mut list: Vec<String> = Vec::new();
18279 for i in 0..(len.max(0.0) as usize) {
18280 let v = get_property(&replacer, &i.to_string())?;
18281 let named = with_host(|h| {
18282 h.as_str(&v).is_some()
18283 || matches!(v, Value::Int(_) | Value::Float(_))
18284 || matches!(h.get(&v), Some(JsObj::Object(p))
18285 if p.get("@@primitive").is_some_and(|p| {
18286 h.as_str(p).is_some() || matches!(p, Value::Int(_) | Value::Float(_))
18287 }))
18288 });
18289 if !named {
18290 continue;
18291 }
18292 let item = host::to_string_value(&v)?;
18293 let item = with_host(|h| h.str_of(&item));
18294 if !list.contains(&item) {
18295 list.push(item);
18296 }
18297 }
18298 Ok(Some(list))
18299}
18300
18301/// `JSON.stringify` steps 5-8: the indentation `gap`, or `None` for the compact
18302/// form. A Number or String wrapper is unwrapped first; a string gives its
18303/// first ten code units; a number gives that many spaces, at most ten.
18304///
18305/// The number arm follows V8 (`JsonStringifier::InitializeGap`) rather than
18306/// the spec's `ToIntegerOrInfinity`-then-`< 1` test: V8 enables the multi-line
18307/// form for ANY value above zero and truncates only afterwards, so
18308/// `JSON.stringify({a: 1}, null, 0.5)` is `{\n"a": 1\n}` — line breaks with an
18309/// empty indent — in node.
18310fn json_gap(space: Value) -> Result<Option<String>, String> {
18311 let space = match wrapped_primitive(&space) {
18312 Some(p) if with_host(|h| h.as_str(&p).is_some()) => host::to_string_value(&space)?,
18313 Some(Value::Int(_) | Value::Float(_)) => Value::Float(host::to_number_value(&space)?),
18314 _ => space,
18315 };
18316 if let Value::Int(_) | Value::Float(_) = space {
18317 let n = with_host(|h| h.to_number(&space));
18318 // `n > 0.0` is false for NaN, which V8's `std::min` also keeps.
18319 return Ok((n > 0.0).then(|| " ".repeat(n.min(10.0) as usize)));
18320 }
18321 Ok(with_host(|h| h.as_str(&space))
18322 .filter(|s| !s.is_empty())
18323 .map(|s| crate::utf16::Units::of(&s).slice(0, 10)))
18324}
18325
18326/// Whether the core-module function keyed `ns` owns a `prototype` in node.
18327pub(crate) fn core_function_prototyped(ns: &str) -> bool {
18328 crate::core_arity::CORE_PROTOTYPED
18329 .binary_search(&ns)
18330 .is_ok()
18331}
18332
18333/// The `prototype` object of a core-module function: `{ constructor: fn }`
18334/// (non-enumerable), made once per function.
18335fn core_function_prototype(ns: &str) -> Value {
18336 thread_local! {
18337 static PROTOS: std::cell::RefCell<std::collections::HashMap<String, Value>> =
18338 std::cell::RefCell::new(std::collections::HashMap::new());
18339 }
18340 if let Some(p) = PROTOS.with(|m| m.borrow().get(ns).cloned()) {
18341 return p;
18342 }
18343 let proto = with_host(|h| {
18344 let ctor = h.alloc(JsObj::Builtin(ns.to_string()));
18345 let mut m = IndexMap::new();
18346 m.insert("constructor".to_string(), ctor);
18347 let p = h.new_object(m);
18348 h.hide_prop(&p, "constructor");
18349 p
18350 });
18351 PROTOS.with(|m| m.borrow_mut().insert(ns.to_string(), proto.clone()));
18352 proto
18353}