Skip to main content

quickjs/
properties.rs

1//! Properties and atoms: the `JS_GetPropertyInternal` family, `JS_DefineProperty*`,
2//! `JS_DeleteProperty*`, and the atom table's C surface.
3//!
4//! # The flags are a bitfield, and getting one bit wrong is silent
5//!
6//! `JS_PROP_*` is sixteen bits with three meanings layered on one integer: the low three are
7//! the attributes, bits 4–5 say whether the property is a plain value or an accessor pair,
8//! and bits 8–13 say *which descriptor fields the caller supplied* — the same
9//! "present or absent" distinction `Object.defineProperty`'s descriptor object carries. A
10//! definition that ignores the "present" bits turns `{value: 1}` into `{value: undefined,
11//! get: undefined, set: undefined}` and so destroys an accessor the caller meant to keep.
12//! [`crate::cdefs::prop`] names them all, and every function below translates them once.
13//!
14//! # Owners, once
15//!
16//! The rule is the reference's, and it is not uniform: `JS_GetProperty*` answers a new
17//! reference, `JS_SetProperty*` **consumes** the value it is given, and
18//! `JS_DefinePropertyValue*` consumes it too. `JS_DefineProperty` (the one taking both a value
19//! and a getter/setter) consumes only what the flags say it uses. This module says which is
20//! which at every function rather than leaving it to be inferred.
21
22use core::ffi::{c_char, c_int};
23
24use engine::Value;
25use engine::interp::Signal;
26use engine::object::PropertyKey;
27
28use crate::atoms::Atom;
29use crate::cdefs::{Bool, JSPropertyDescriptor, JSPropertyEnum, prop};
30use crate::conversions::{arg, c_text};
31use crate::jsvalue::{self, JsValue};
32use crate::runtime::{self, JsContext, JsRuntime};
33use crate::value_helpers::jsvalue_of;
34
35/// `JS_PROP_THROW` / `JS_PROP_THROW_STRICT`: what a failed store does.
36const PROP_THROW: c_int = 1 << 14;
37/// `JS_PROP_THROW_STRICT`.
38const PROP_THROW_STRICT: c_int = 1 << 15;
39
40/// `JS_GPN_STRING_MASK`.
41pub const GPN_STRING_MASK: c_int = 1 << 0;
42/// `JS_GPN_SYMBOL_MASK`.
43pub const GPN_SYMBOL_MASK: c_int = 1 << 1;
44/// `JS_GPN_PRIVATE_MASK`.
45pub const GPN_PRIVATE_MASK: c_int = 1 << 2;
46/// `JS_GPN_ENUM_ONLY`: only the enumerable properties.
47pub const GPN_ENUM_ONLY: c_int = 1 << 4;
48/// `JS_GPN_SET_ENUM`: fill in `JSPropertyEnum::is_enumerable`.
49pub const GPN_SET_ENUM: c_int = 1 << 5;
50
51// ---------------------------------------------------------------------------
52// Atoms
53// ---------------------------------------------------------------------------
54
55/// `JS_NewAtomLen`: intern `len` bytes as an atom.
56///
57/// # Safety
58///
59/// `str` must point at `len` readable bytes.
60#[unsafe(no_mangle)]
61pub unsafe extern "C" fn JS_NewAtomLen(
62    ctx: *mut JsContext,
63    str: *const c_char,
64    len: usize,
65) -> Atom {
66    let Some(context) = (unsafe { ctx.as_ref() }) else {
67        return crate::atoms::ATOM_NULL;
68    };
69    if str.is_null() && len != 0 {
70        return crate::atoms::ATOM_NULL;
71    }
72    let bytes: &[u8] = if len == 0 {
73        &[]
74    } else {
75        // SAFETY: the caller guarantees `len` readable bytes.
76        unsafe { core::slice::from_raw_parts(str.cast::<u8>(), len) }
77    };
78    let text = String::from_utf8_lossy(bytes);
79    with_atoms(context, |table| table.intern(&text))
80}
81
82/// `JS_NewAtom`: intern a NUL-terminated string.
83///
84/// # Safety
85///
86/// `str` must be null or NUL-terminated.
87#[unsafe(no_mangle)]
88pub unsafe extern "C" fn JS_NewAtom(ctx: *mut JsContext, str: *const c_char) -> Atom {
89    // SAFETY: the caller guarantees a NUL-terminated string.
90    let text = unsafe { c_text(str) };
91    let Some(context) = (unsafe { ctx.as_ref() }) else {
92        return crate::atoms::ATOM_NULL;
93    };
94    with_atoms(context, |table| table.intern(&text))
95}
96
97/// `JS_NewAtomUInt32`: intern an unsigned 32-bit index.
98#[unsafe(no_mangle)]
99///
100/// # Safety
101///
102/// `ctx` must be a live context.
103pub unsafe extern "C" fn JS_NewAtomUInt32(ctx: *mut JsContext, number: u32) -> Atom {
104    let Some(context) = (unsafe { ctx.as_ref() }) else {
105        return crate::atoms::ATOM_NULL;
106    };
107    let text = number.to_string();
108    with_atoms(context, |table| table.intern(&text))
109}
110
111/// `JS_DupAtom`: keep an atom alive.
112///
113/// This engine's atoms are indices into a table that lives as long as the runtime, so there
114/// is no count to raise — but the *value* has to be valid, which is what the `ATOM_NULL`
115/// check is for.
116#[unsafe(no_mangle)]
117pub extern "C" fn JS_DupAtom(_ctx: *mut JsContext, atom: Atom) -> Atom {
118    atom
119}
120
121/// `JS_FreeAtom`: release an atom.
122///
123/// A no-op for the same reason [`JS_DupAtom`] is: atoms outlive every caller here, and
124/// invalidating one would make a module's static `JSAtom` unusable on its second call.
125#[unsafe(no_mangle)]
126pub extern "C" fn JS_FreeAtom(_ctx: *mut JsContext, _atom: Atom) {}
127
128/// `JS_FreeAtomRT`: [`JS_FreeAtom`]'s runtime-level spelling.
129#[unsafe(no_mangle)]
130pub extern "C" fn JS_FreeAtomRT(_rt: *mut JsRuntime, _atom: Atom) {}
131
132/// `JS_AtomToValue`: the atom's text as a string value, or `undefined` for `ATOM_NULL`.
133#[unsafe(no_mangle)]
134///
135/// # Safety
136///
137/// `ctx` must be a live context.
138pub unsafe extern "C" fn JS_AtomToValue(ctx: *mut JsContext, atom: Atom) -> JsValue {
139    let Some(context) = (unsafe { ctx.as_ref() }) else {
140        return jsvalue::EXCEPTION;
141    };
142    // The reference answers `JS_UNDEFINED` for the null atom rather than throwing, and a
143    // caller that walks a property list depends on that.
144    let Some(text) = with_atoms(context, |table| table.text(atom).map(str::to_string)) else {
145        return jsvalue_of(Value::Undefined);
146    };
147    context.with_current_interp(|interp| jsvalue_of(interp.string(text)))
148}
149
150/// `JS_AtomToString`: [`JS_AtomToValue`] under its other name.
151#[unsafe(no_mangle)]
152///
153/// # Safety
154///
155/// `ctx` must be a live context.
156pub unsafe extern "C" fn JS_AtomToString(ctx: *mut JsContext, atom: Atom) -> JsValue {
157    // SAFETY: the caller's contract is `JS_AtomToValue`'s.
158    unsafe { JS_AtomToValue(ctx, atom) }
159}
160
161/// `JS_AtomToCStringLen`: the atom's text as a `js_malloc` block.
162///
163/// # Safety
164///
165/// `plen` must be null or writable.
166#[unsafe(no_mangle)]
167pub unsafe extern "C" fn JS_AtomToCStringLen(
168    ctx: *mut JsContext,
169    plen: *mut usize,
170    atom: Atom,
171) -> *mut c_char {
172    if !plen.is_null() {
173        // SAFETY: the caller guarantees a writable pointer.
174        unsafe { *plen = 0 };
175    }
176    let Some(context) = (unsafe { ctx.as_ref() }) else {
177        return std::ptr::null_mut();
178    };
179    let Some(text) = with_atoms(context, |table| table.text(atom).map(str::to_string)) else {
180        return std::ptr::null_mut();
181    };
182    // SAFETY: `alloc_raw_zeroed` gives a zeroed block, so the terminator is already written.
183    let block = unsafe { crate::alloc::alloc_raw_zeroed(text.len() + 1) };
184    if block.is_null() {
185        return std::ptr::null_mut();
186    }
187    // SAFETY: the block holds `text.len() + 1` writable bytes.
188    unsafe { std::ptr::copy_nonoverlapping(text.as_ptr(), block, text.len()) };
189    if !plen.is_null() {
190        // SAFETY: the caller guarantees a writable pointer.
191        unsafe { *plen = text.len() };
192    }
193    block.cast()
194}
195
196/// `JS_ValueToAtom`: the atom for a value's property key.
197///
198/// # Safety
199///
200/// `val` must be a live `JSValue`.
201#[unsafe(no_mangle)]
202pub unsafe extern "C" fn JS_ValueToAtom(ctx: *mut JsContext, val: JsValue) -> Atom {
203    let Some(context) = (unsafe { ctx.as_ref() }) else {
204        return crate::atoms::ATOM_NULL;
205    };
206    let Some(value) = (unsafe { arg(val) }) else {
207        return crate::atoms::ATOM_NULL;
208    };
209    // A symbol is not an atom in this table, and the reference would answer an atom for its
210    // description — which is a lie about identity. Answering `ATOM_NULL` instead is caught by
211    // every caller's own null check.
212    if matches!(value, Value::Symbol(_)) {
213        return crate::atoms::ATOM_NULL;
214    }
215    match context.with_current_interp(|interp| interp.checked_to_string(&value)) {
216        Ok(text) => with_atoms(context, |table| table.intern(&text)),
217        Err(signal) => {
218            let _ = runtime::result_value(context, Err(signal));
219            crate::atoms::ATOM_NULL
220        }
221    }
222}
223
224/// Run `f` with this context's runtime atom table.
225///
226/// The table hangs off the runtime, so a context with no runtime (which cannot exist, but the
227/// type does not say so) answers the default rather than panicking — a C caller must never be
228/// able to make the library abort.
229pub(crate) fn with_atoms<R>(
230    context: &JsContext,
231    f: impl FnOnce(&mut crate::atoms::AtomTable) -> R,
232) -> R {
233    // SAFETY: the runtime pointer is live for as long as the context, which is the invariant
234    // `JS_NewContext`/`JS_FreeRuntime` maintain.
235    let runtime = unsafe { context.runtime().as_ref() };
236    match runtime {
237        Some(runtime) => f(&mut runtime.atoms.borrow_mut()),
238        None => {
239            // A context without a runtime cannot intern anything, and answering a throwaway
240            // table keeps the caller's `intern` total.
241            let mut scratch = crate::atoms::AtomTable::new();
242            f(&mut scratch)
243        }
244    }
245}
246
247/// The `PropertyKey` an atom addresses.
248fn atom_key(context: &JsContext, atom: Atom) -> Option<PropertyKey> {
249    with_atoms(context, |table| table.text(atom).map(PropertyKey::from))
250}
251
252/// The text an atom addresses, for the modules that only need a name.
253pub(crate) fn atom_text(context: &JsContext, atom: Atom) -> Option<String> {
254    with_atoms(context, |table| table.text(atom).map(str::to_string))
255}
256
257// ---------------------------------------------------------------------------
258// Getting
259// ---------------------------------------------------------------------------
260
261/// `JS_GetPropertyStr`: read `this_obj[name]`.
262///
263/// Exported from [`crate::objects`] already; this alias exists so that a reader looking for
264/// the whole family finds it named here too. It is not re-exported as a symbol.
265///
266/// `JS_GetPropertyUint32`: read `this_obj[idx]`.
267///
268/// # Safety
269///
270/// `this_obj` must be a live `JSValue`.
271#[unsafe(no_mangle)]
272pub unsafe extern "C" fn JS_GetPropertyUint32(
273    ctx: *mut JsContext,
274    this_obj: JsValue,
275    idx: u32,
276) -> JsValue {
277    let Some(context) = (unsafe { ctx.as_ref() }) else {
278        return jsvalue::EXCEPTION;
279    };
280    let Some(target) = (unsafe { arg(this_obj) }) else {
281        return runtime::throw_error(context, "TypeError", "not an object");
282    };
283    let key = PropertyKey::from(idx.to_string());
284    let result = context.with_current_interp(|interp| interp.read_field_key(&target, &key));
285    runtime::result_value(context, result)
286}
287
288/// `JS_GetPropertyInternal`: the general read, with an explicit receiver.
289///
290/// `receiver` is what an inherited getter sees as `this`. The reference passes `obj` for the
291/// ordinary case; a caller that wants a different receiver (a proxy's own trap does) passes
292/// something else, which is why this exists separately from `JS_GetPropertyStr`.
293///
294/// # Safety
295///
296/// `obj` and `receiver` must be live `JSValue`s.
297#[unsafe(no_mangle)]
298pub unsafe extern "C" fn JS_GetPropertyInternal(
299    ctx: *mut JsContext,
300    obj: JsValue,
301    atom: Atom,
302    receiver: JsValue,
303    throw_ref_error: Bool,
304) -> JsValue {
305    let Some(context) = (unsafe { ctx.as_ref() }) else {
306        return jsvalue::EXCEPTION;
307    };
308    let Some(target) = (unsafe { arg(obj) }) else {
309        return runtime::throw_error(context, "TypeError", "not an object");
310    };
311    let Some(key) = atom_key(context, atom) else {
312        return jsvalue::UNDEFINED;
313    };
314    let receiver = if receiver.is_null() {
315        None
316    } else {
317        unsafe { arg(receiver) }
318    };
319    let result = context.with_current_interp(|interp| {
320        let object = match &target {
321            Value::Object(object) => object.clone(),
322            // A primitive is read through `ToObject`, so `"ab".length` works; the receiver
323            // stays the primitive, which is what an inherited getter has to see.
324            other => interp.object_from(other)?,
325        };
326        let read = interp.get_property_key_for(&object, receiver.as_ref(), &key)?;
327        match read {
328            Some(value) => Ok(value),
329            None if throw_ref_error != 0 => {
330                Err(interp.type_error(format!("property '{key}' is not defined")))
331            }
332            None => Ok(Value::Undefined),
333        }
334    });
335    runtime::result_value(context, result)
336}
337
338/// `JS_HasProperty`: whether `this_obj` has `prop` (own or inherited).
339///
340/// # Safety
341///
342/// `this_obj` must be a live `JSValue`.
343#[unsafe(no_mangle)]
344pub unsafe extern "C" fn JS_HasProperty(
345    ctx: *mut JsContext,
346    this_obj: JsValue,
347    prop: Atom,
348) -> c_int {
349    let Some(context) = (unsafe { ctx.as_ref() }) else {
350        return -1;
351    };
352    let Some(target) = (unsafe { arg(this_obj) }) else {
353        runtime::throw_error(context, "TypeError", "not an object");
354        return -1;
355    };
356    let Some(key) = atom_key(context, prop) else {
357        return 0;
358    };
359    let result = context.with_current_interp(|interp| {
360        let object = match &target {
361            Value::Object(object) => object.clone(),
362            other => interp.object_from(other)?,
363        };
364        // `HasProperty`, not `HasOwnProperty`: the prototype chain counts, which is what
365        // `"length" in []` asks about.
366        let found = interp.has_property_key(&object, &key)?;
367        Ok(c_int::from(found))
368    });
369    match result {
370        Ok(answer) => answer,
371        Err(signal) => {
372            let _ = runtime::result_value(context, Err(signal));
373            -1
374        }
375    }
376}
377
378// ---------------------------------------------------------------------------
379// Setting
380// ---------------------------------------------------------------------------
381
382/// `JS_SetPropertyStr` lives in `crate::objects`. The numbered spellings are here.
383///
384/// `JS_SetPropertyUint32`: `this_obj[idx] = val`, consuming `val`'s reference.
385///
386/// # Safety
387///
388/// `this_obj` must be a live `JSValue`, and `val` a live one whose reference this call
389/// consumes.
390#[unsafe(no_mangle)]
391pub unsafe extern "C" fn JS_SetPropertyUint32(
392    ctx: *mut JsContext,
393    this_obj: JsValue,
394    idx: u32,
395    val: JsValue,
396) -> c_int {
397    set_indexed(ctx, this_obj, idx.to_string(), val, 0)
398}
399
400/// `JS_SetPropertyInt64`: the same for a 64-bit index.
401///
402/// # Safety
403///
404/// As [`JS_SetPropertyUint32`].
405#[unsafe(no_mangle)]
406pub unsafe extern "C" fn JS_SetPropertyInt64(
407    ctx: *mut JsContext,
408    this_obj: JsValue,
409    idx: i64,
410    val: JsValue,
411) -> c_int {
412    set_indexed(ctx, this_obj, idx.to_string(), val, 0)
413}
414
415/// `JS_SetPropertyInternal`: the general store.
416///
417/// `flags` carries `JS_PROP_THROW` when a refusal should be a `TypeError`; `this_obj`
418/// is the receiver an inherited setter sees, and is `obj` in every ordinary call.
419///
420/// # Safety
421///
422/// `obj` and `this_obj` must be live `JSValue`s; `val`'s reference is consumed.
423#[unsafe(no_mangle)]
424pub unsafe extern "C" fn JS_SetPropertyInternal(
425    ctx: *mut JsContext,
426    obj: JsValue,
427    atom: Atom,
428    val: JsValue,
429    this_obj: JsValue,
430    flags: c_int,
431) -> c_int {
432    let Some(context) = (unsafe { ctx.as_ref() }) else {
433        return -1;
434    };
435    let Some(target) = (unsafe { arg(obj) }) else {
436        unsafe { runtime::release(val) };
437        runtime::throw_error(context, "TypeError", "not an object");
438        return -1;
439    };
440    let Some(value) = (unsafe { arg(val) }) else {
441        runtime::throw_error(context, "TypeError", "not a value");
442        return -1;
443    };
444    // The C API consumes the reference it was handed, whatever happens next.
445    // SAFETY: the caller's contract.
446    unsafe { runtime::release(val) };
447    let Some(key) = atom_key(context, atom) else {
448        runtime::throw_error(context, "TypeError", "invalid atom");
449        return -1;
450    };
451    let receiver = if this_obj.is_null() {
452        None
453    } else {
454        unsafe { arg(this_obj) }
455    };
456    let on_failure = if flags & PROP_THROW != 0 {
457        engine::interp::DeleteFailure::Throw
458    } else {
459        engine::interp::DeleteFailure::Ignore
460    };
461    let strict = flags & PROP_THROW_STRICT != 0;
462    let result = context.with_current_interp(|interp| {
463        let object = match &target {
464            Value::Object(object) => object.clone(),
465            other => interp.object_from(other)?,
466        };
467        let accepted = interp.set_property_with_key_receiver(
468            &object,
469            &key,
470            value,
471            receiver.as_ref(),
472            on_failure,
473        )?;
474        // A refused store is `-1` only when the caller asked for the throw; otherwise it is
475        // a silent no-op that still answers "not accepted", which is what `0`/`-1` split on.
476        if accepted || !(on_failure == engine::interp::DeleteFailure::Throw || strict) {
477            Ok(0)
478        } else {
479            Ok(-1)
480        }
481    });
482    match result {
483        Ok(answer) => answer,
484        Err(signal) => {
485            let _ = runtime::result_value(context, Err(signal));
486            -1
487        }
488    }
489}
490
491/// The shared body of `JS_SetPropertyUint32`/`Int64`.
492fn set_indexed(
493    ctx: *mut JsContext,
494    this_obj: JsValue,
495    key: String,
496    val: JsValue,
497    flags: c_int,
498) -> c_int {
499    let Some(context) = (unsafe { ctx.as_ref() }) else {
500        return -1;
501    };
502    let Some(target) = (unsafe { arg(this_obj) }) else {
503        // SAFETY: the C API consumes the value's reference even on the failure path.
504        unsafe { runtime::release(val) };
505        runtime::throw_error(context, "TypeError", "not an object");
506        return -1;
507    };
508    let Some(value) = (unsafe { arg(val) }) else {
509        runtime::throw_error(context, "TypeError", "not a value");
510        return -1;
511    };
512    // SAFETY: the C API consumes the reference it was handed.
513    unsafe { runtime::release(val) };
514    let result = context.with_current_interp(|interp| {
515        let object = match &target {
516            Value::Object(object) => object.clone(),
517            other => interp.object_from(other)?,
518        };
519        interp.set_property(&object, &key, value)?;
520        let _ = flags;
521        Ok(0)
522    });
523    match result {
524        Ok(answer) => answer,
525        Err(signal) => {
526            let _ = runtime::result_value(context, Err(signal));
527            -1
528        }
529    }
530}
531
532// ---------------------------------------------------------------------------
533// Defining
534// ---------------------------------------------------------------------------
535
536/// Translate `JS_PROP_*` into an engine `Property`.
537///
538/// The "present" bits matter: a definition that supplies only `value` must leave `getter` and
539/// `setter` alone, and one that supplies `get`/`set` must not create a data property. Returns
540/// `None` for a flag set this layer cannot express, which the caller reports as a `TypeError`
541/// rather than guessing.
542fn property_from_flags(
543    context: &JsContext,
544    flags: c_int,
545    value: Option<Value>,
546    getter: Option<Value>,
547    setter: Option<Value>,
548) -> Option<engine::object::Property> {
549    let _ = context;
550    let configurable = flags & c_int::from(prop::CONFIGURABLE) != 0;
551    let writable = flags & c_int::from(prop::WRITABLE) != 0;
552    let enumerable = flags & c_int::from(prop::ENUMERABLE) != 0;
553    // `JS_PROP_GETSET` (bit 4) says the property is an accessor; its absence plus a supplied
554    // value says it is a data property.
555    let is_accessor = flags & (1 << 4) != 0 || (flags & (1 << 11) != 0) || (flags & (1 << 12) != 0);
556    Some(if is_accessor {
557        engine::object::Property {
558            value: None,
559            getter,
560            setter,
561            writable: false,
562            enumerable,
563            configurable,
564        }
565    } else {
566        engine::object::Property {
567            value: value.or(Some(Value::Undefined)),
568            getter: None,
569            setter: None,
570            writable,
571            enumerable,
572            configurable,
573        }
574    })
575}
576
577/// `JS_DefinePropertyValue`: define a data property, consuming `val`.
578///
579/// # Safety
580///
581/// `this_obj` must be a live `JSValue`; `val`'s reference is consumed.
582#[unsafe(no_mangle)]
583pub unsafe extern "C" fn JS_DefinePropertyValue(
584    ctx: *mut JsContext,
585    this_obj: JsValue,
586    prop: Atom,
587    val: JsValue,
588    flags: c_int,
589) -> c_int {
590    let Some(context) = (unsafe { ctx.as_ref() }) else {
591        return -1;
592    };
593    let Some(key) = atom_key(context, prop) else {
594        unsafe { runtime::release(val) };
595        runtime::throw_error(context, "TypeError", "invalid atom");
596        return -1;
597    };
598    define_value(context, this_obj, key, val, flags)
599}
600
601/// `JS_DefinePropertyValueStr`: the same, keyed by a string.
602///
603/// # Safety
604///
605/// `this_obj` a live `JSValue`, `name` NUL-terminated; `val`'s reference is consumed.
606#[unsafe(no_mangle)]
607pub unsafe extern "C" fn JS_DefinePropertyValueStr(
608    ctx: *mut JsContext,
609    this_obj: JsValue,
610    name: *const c_char,
611    val: JsValue,
612    flags: c_int,
613) -> c_int {
614    let Some(context) = (unsafe { ctx.as_ref() }) else {
615        return -1;
616    };
617    // SAFETY: the caller guarantees a NUL-terminated string.
618    let key = PropertyKey::from(unsafe { c_text(name) });
619    define_value(context, this_obj, key, val, flags)
620}
621
622/// `JS_DefinePropertyValueUint32`: the same, keyed by an index.
623///
624/// # Safety
625///
626/// As [`JS_DefinePropertyValueStr`].
627#[unsafe(no_mangle)]
628pub unsafe extern "C" fn JS_DefinePropertyValueUint32(
629    ctx: *mut JsContext,
630    this_obj: JsValue,
631    idx: u32,
632    val: JsValue,
633    flags: c_int,
634) -> c_int {
635    let Some(context) = (unsafe { ctx.as_ref() }) else {
636        return -1;
637    };
638    define_value(
639        context,
640        this_obj,
641        PropertyKey::from(idx.to_string()),
642        val,
643        flags,
644    )
645}
646
647/// `JS_DefinePropertyValueInt64`: the same, keyed by a 64-bit index.
648///
649/// # Safety
650///
651/// As [`JS_DefinePropertyValueStr`].
652#[unsafe(no_mangle)]
653pub unsafe extern "C" fn JS_DefinePropertyValueInt64(
654    ctx: *mut JsContext,
655    this_obj: JsValue,
656    idx: i64,
657    val: JsValue,
658    flags: c_int,
659) -> c_int {
660    let Some(context) = (unsafe { ctx.as_ref() }) else {
661        return -1;
662    };
663    define_value(
664        context,
665        this_obj,
666        PropertyKey::from(idx.to_string()),
667        val,
668        flags,
669    )
670}
671
672/// `JS_DefinePropertyValueValue`: the same, keyed by a value (`ToPropertyKey` on it).
673///
674/// # Safety
675///
676/// Both values must be live; `prop`'s and `val`'s references are consumed.
677#[unsafe(no_mangle)]
678pub unsafe extern "C" fn JS_DefinePropertyValueValue(
679    ctx: *mut JsContext,
680    this_obj: JsValue,
681    prop: JsValue,
682    val: JsValue,
683    flags: c_int,
684) -> c_int {
685    let Some(context) = (unsafe { ctx.as_ref() }) else {
686        return -1;
687    };
688    let Some(key_value) = (unsafe { arg(prop) }) else {
689        unsafe {
690            runtime::release(prop);
691            runtime::release(val);
692        }
693        runtime::throw_error(context, "TypeError", "not a value");
694        return -1;
695    };
696    // SAFETY: the C API consumes the key's reference.
697    unsafe { runtime::release(prop) };
698    match context.with_current_interp(|interp| interp.propkey(&key_value)) {
699        Ok(key) => define_value(context, this_obj, key, val, flags),
700        Err(signal) => {
701            // SAFETY: the value's reference is consumed even on this path.
702            unsafe { runtime::release(val) };
703            let _ = runtime::result_value(context, Err(signal));
704            -1
705        }
706    }
707}
708
709/// The shared body of the `JS_DefinePropertyValue*` family.
710fn define_value(
711    context: &JsContext,
712    this_obj: JsValue,
713    key: PropertyKey,
714    val: JsValue,
715    flags: c_int,
716) -> c_int {
717    let Some(target) = (unsafe { arg(this_obj) }) else {
718        // SAFETY: the reference is consumed whatever happens.
719        unsafe { runtime::release(val) };
720        runtime::throw_error(context, "TypeError", "not an object");
721        return -1;
722    };
723    let Some(value) = (unsafe { arg(val) }) else {
724        runtime::throw_error(context, "TypeError", "not a value");
725        return -1;
726    };
727    // SAFETY: the C API consumes the reference.
728    unsafe { runtime::release(val) };
729    let Some(property) = property_from_flags(context, flags, Some(value), None, None) else {
730        runtime::throw_error(context, "TypeError", "unsupported property flags");
731        return -1;
732    };
733    let result = context.with_current_interp(|interp| {
734        let object = match &target {
735            Value::Object(object) => object.clone(),
736            other => interp.object_from(other)?,
737        };
738        let accepted = interp.object_define_own_property(&object, &key, property)?;
739        Ok(if accepted { 0 } else { -1 })
740    });
741    match result {
742        Ok(answer) => answer,
743        Err(signal) => {
744            let _ = runtime::result_value(context, Err(signal));
745            -1
746        }
747    }
748}
749
750/// `JS_DefineProperty`: define an accessor and/or a value in one call.
751///
752/// Only the fields the flags say are present are used, which is what lets a caller change a
753/// property's attributes without touching what it holds.
754///
755/// # Safety
756///
757/// `this_obj` must be live; `val`, `getter` and `setter` are read, and the ones the flags
758/// name are consumed.
759#[unsafe(no_mangle)]
760pub unsafe extern "C" fn JS_DefineProperty(
761    ctx: *mut JsContext,
762    this_obj: JsValue,
763    prop: Atom,
764    val: JsValue,
765    getter: JsValue,
766    setter: JsValue,
767    flags: c_int,
768) -> c_int {
769    let Some(context) = (unsafe { ctx.as_ref() }) else {
770        return -1;
771    };
772    let Some(key) = atom_key(context, prop) else {
773        unsafe {
774            runtime::release(val);
775            runtime::release(getter);
776            runtime::release(setter);
777        }
778        runtime::throw_error(context, "TypeError", "invalid atom");
779        return -1;
780    };
781    define_property(context, this_obj, key, val, getter, setter, flags)
782}
783
784/// `JS_DefinePropertyGetSet`: the accessor-only spelling.
785///
786/// # Safety
787///
788/// As [`JS_DefineProperty`]; `getter` and `setter`'s references are consumed.
789#[unsafe(no_mangle)]
790pub unsafe extern "C" fn JS_DefinePropertyGetSet(
791    ctx: *mut JsContext,
792    this_obj: JsValue,
793    prop: Atom,
794    getter: JsValue,
795    setter: JsValue,
796    flags: c_int,
797) -> c_int {
798    let Some(context) = (unsafe { ctx.as_ref() }) else {
799        return -1;
800    };
801    let Some(key) = atom_key(context, prop) else {
802        unsafe {
803            runtime::release(getter);
804            runtime::release(setter);
805        }
806        runtime::throw_error(context, "TypeError", "invalid atom");
807        return -1;
808    };
809    // The accessor convention is `flags | JS_PROP_GETSET`, and the value is "not present" so
810    // the property is an accessor and stays one.
811    let flags = flags | (1 << 4) | (1 << 11) | (1 << 12);
812    define_property(
813        context,
814        this_obj,
815        key,
816        jsvalue::UNDEFINED,
817        getter,
818        setter,
819        flags,
820    )
821}
822
823/// The shared body of [`JS_DefineProperty`] and [`JS_DefinePropertyGetSet`].
824fn define_property(
825    context: &JsContext,
826    this_obj: JsValue,
827    key: PropertyKey,
828    val: JsValue,
829    getter: JsValue,
830    setter: JsValue,
831    flags: c_int,
832) -> c_int {
833    let Some(target) = (unsafe { arg(this_obj) }) else {
834        unsafe {
835            runtime::release(val);
836            runtime::release(getter);
837            runtime::release(setter);
838        }
839        runtime::throw_error(context, "TypeError", "not an object");
840        return -1;
841    };
842    // A field is read only when its "present" bit is set; releasing an absent one is wrong
843    // because the caller passed `JS_UNDEFINED` for it, which owns no reference anyway.
844    let has_value = flags & (1 << 13) != 0 || flags & (1 << 4) == 0;
845    let has_get = flags & (1 << 11) != 0;
846    let has_set = flags & (1 << 12) != 0;
847    let value = if has_value {
848        let decoded = unsafe { arg(val) };
849        // SAFETY: the C API consumes what it uses.
850        unsafe { runtime::release(val) };
851        decoded
852    } else {
853        None
854    };
855    let getter = if has_get {
856        let decoded = unsafe { arg(getter) };
857        // SAFETY: as above.
858        unsafe { runtime::release(getter) };
859        decoded
860    } else {
861        None
862    };
863    let setter = if has_set {
864        let decoded = unsafe { arg(setter) };
865        // SAFETY: as above.
866        unsafe { runtime::release(setter) };
867        decoded
868    } else {
869        None
870    };
871    let Some(property) = property_from_flags(context, flags, value, getter, setter) else {
872        runtime::throw_error(context, "TypeError", "unsupported property flags");
873        return -1;
874    };
875    let result = context.with_current_interp(|interp| {
876        let object = match &target {
877            Value::Object(object) => object.clone(),
878            other => interp.object_from(other)?,
879        };
880        let accepted = interp.object_define_own_property(&object, &key, property)?;
881        Ok(if accepted { 0 } else { -1 })
882    });
883    match result {
884        Ok(answer) => answer,
885        Err(signal) => {
886            let _ = runtime::result_value(context, Err(signal));
887            -1
888        }
889    }
890}
891
892// ---------------------------------------------------------------------------
893// Deleting
894// ---------------------------------------------------------------------------
895
896/// `JS_DeleteProperty`: delete `obj[prop]`.
897///
898/// `flags` may carry `JS_PROP_THROW`, in which case the reference answers `-1` for a refused
899/// delete *and* raises a `TypeError` in strict mode. `true` is `1`, `false` is `0`.
900///
901/// # Safety
902///
903/// `obj` must be a live `JSValue`.
904#[unsafe(no_mangle)]
905pub unsafe extern "C" fn JS_DeleteProperty(
906    ctx: *mut JsContext,
907    obj: JsValue,
908    prop: Atom,
909    flags: c_int,
910) -> c_int {
911    let Some(context) = (unsafe { ctx.as_ref() }) else {
912        return -1;
913    };
914    let Some(key) = atom_key(context, prop) else {
915        return 0;
916    };
917    delete_key(context, obj, key, flags)
918}
919
920/// `JS_DeletePropertyInt64`: the same, keyed by an index.
921///
922/// # Safety
923///
924/// As [`JS_DeleteProperty`].
925#[unsafe(no_mangle)]
926pub unsafe extern "C" fn JS_DeletePropertyInt64(
927    ctx: *mut JsContext,
928    obj: JsValue,
929    idx: i64,
930    flags: c_int,
931) -> c_int {
932    let Some(context) = (unsafe { ctx.as_ref() }) else {
933        return -1;
934    };
935    delete_key(context, obj, PropertyKey::from(idx.to_string()), flags)
936}
937
938/// The shared body of the two deletes.
939fn delete_key(context: &JsContext, obj: JsValue, key: PropertyKey, flags: c_int) -> c_int {
940    let Some(target) = (unsafe { arg(obj) }) else {
941        runtime::throw_error(context, "TypeError", "not an object");
942        return -1;
943    };
944    let throw = flags & PROP_THROW != 0;
945    let result = context.with_current_interp(|interp| {
946        let object = match &target {
947            Value::Object(object) => object.clone(),
948            other => interp.object_from(other)?,
949        };
950        let deleted = interp.delete_property_key(&object, &key)?;
951        // A refused delete is a `TypeError` in strict mode and a `false` result in sloppy
952        // mode; the reference's `-1` is the strict path.
953        if !deleted && throw {
954            return Err(interp.type_error(format!("cannot delete property '{key}'")));
955        }
956        Ok(c_int::from(deleted))
957    });
958    match result {
959        Ok(answer) => answer,
960        Err(signal) => {
961            let _ = runtime::result_value(context, Err(signal));
962            -1
963        }
964    }
965}
966
967// ---------------------------------------------------------------------------
968// Own properties
969// ---------------------------------------------------------------------------
970
971/// `JS_GetOwnPropertyNames`: `ptab`/`plen` filled with the object's own keys.
972///
973/// The block is one allocation holding `len` `JSPropertyEnum`s, so
974/// `JS_FreePropertyEnum(ctx, tab, len)` can release it as one — which is what the reference
975/// does and what every caller assumes.
976///
977/// # Safety
978///
979/// `ptab` and `plen` must be writable, `obj` a live `JSValue`.
980#[unsafe(no_mangle)]
981pub unsafe extern "C" fn JS_GetOwnPropertyNames(
982    ctx: *mut JsContext,
983    ptab: *mut *mut JSPropertyEnum,
984    plen: *mut u32,
985    obj: JsValue,
986    flags: c_int,
987) -> c_int {
988    if !ptab.is_null() {
989        // SAFETY: the caller guarantees a writable pointer.
990        unsafe { *ptab = std::ptr::null_mut() };
991    }
992    if !plen.is_null() {
993        // SAFETY: as above.
994        unsafe { *plen = 0 };
995    }
996    let Some(context) = (unsafe { ctx.as_ref() }) else {
997        return -1;
998    };
999    let Some(target) = (unsafe { arg(obj) }) else {
1000        runtime::throw_error(context, "TypeError", "not a value");
1001        return -1;
1002    };
1003    let entries = context.with_current_interp(|interp| {
1004        let object = match &target {
1005            Value::Object(object) => object.clone(),
1006            other => interp.object_from(other)?,
1007        };
1008        let keys = interp.object_own_property_keys(&object)?;
1009        let mut entries: Vec<(Atom, bool)> = Vec::new();
1010        for key in keys {
1011            let is_symbol = key.is_symbol();
1012            // `JS_GPN_*_MASK` selects which kinds are reported. The reference's default
1013            // (no mask set) is strings *and* symbols, which is what `Reflect.ownKeys` gives.
1014            let any_mask = flags & (GPN_STRING_MASK | GPN_SYMBOL_MASK | GPN_PRIVATE_MASK);
1015            let wanted = if any_mask == 0 {
1016                true
1017            } else if is_symbol {
1018                flags & GPN_SYMBOL_MASK != 0
1019            } else {
1020                flags & GPN_STRING_MASK != 0
1021            };
1022            if !wanted {
1023                continue;
1024            }
1025            let property = interp.object_get_own_property(&object, &key)?;
1026            let enumerable = property.as_ref().is_some_and(|p| p.enumerable);
1027            if flags & GPN_ENUM_ONLY != 0 && !enumerable {
1028                continue;
1029            }
1030            // A symbol key has no atom, and this layer's atom table has no symbol entries, so
1031            // it is reported under its description — which is the only thing a C caller can
1032            // do with it anyway (`JS_AtomToString` is the only reader).
1033            let text = match &key {
1034                PropertyKey::String(text) => text.to_string_lossy().into_owned(),
1035                PropertyKey::Symbol(symbol) => symbol.to_display_string(),
1036            };
1037            let atom = with_atoms(context, |table| table.intern(&text));
1038            entries.push((atom, enumerable));
1039        }
1040        Ok(entries)
1041    });
1042    let entries = match entries {
1043        Ok(entries) => entries,
1044        Err(signal) => {
1045            let _ = runtime::result_value(context, Err(signal));
1046            return -1;
1047        }
1048    };
1049    if entries.is_empty() {
1050        return 0;
1051    }
1052    let size = entries.len() * core::mem::size_of::<JSPropertyEnum>();
1053    // SAFETY: `alloc_raw_zeroed` gives `size` zeroed, 8-aligned bytes.
1054    let block = unsafe { crate::alloc::alloc_raw_zeroed(size) };
1055    if block.is_null() {
1056        runtime::throw_error(context, "InternalError", "out of memory");
1057        return -1;
1058    }
1059    // SAFETY: the block is `entries.len()` `JSPropertyEnum`s.
1060    let table = block.cast::<JSPropertyEnum>();
1061    for (index, (atom, enumerable)) in entries.iter().enumerate() {
1062        // SAFETY: `index` is in range.
1063        unsafe {
1064            table.add(index).write(JSPropertyEnum {
1065                is_enumerable: if flags & GPN_SET_ENUM != 0 {
1066                    c_int::from(*enumerable)
1067                } else {
1068                    0
1069                },
1070                atom: *atom,
1071            });
1072        }
1073    }
1074    if !ptab.is_null() {
1075        // SAFETY: the caller guarantees a writable pointer.
1076        unsafe { *ptab = table };
1077    }
1078    if !plen.is_null() {
1079        // SAFETY: as above.
1080        unsafe { *plen = entries.len() as u32 };
1081    }
1082    0
1083}
1084
1085/// `JS_FreePropertyEnum`: release what [`JS_GetOwnPropertyNames`] allocated.
1086///
1087/// # Safety
1088///
1089/// `tab` must come from `JS_GetOwnPropertyNames` with the same `len`, and not be used again.
1090#[unsafe(no_mangle)]
1091pub unsafe extern "C" fn JS_FreePropertyEnum(
1092    _ctx: *mut JsContext,
1093    tab: *mut JSPropertyEnum,
1094    _len: u32,
1095) {
1096    // SAFETY: the caller's contract; the allocator checks the header before freeing.
1097    unsafe { crate::alloc::free_raw(tab.cast()) }
1098}
1099
1100/// `JS_GetOwnProperty`: a complete descriptor for `obj[prop]`.
1101///
1102/// # Safety
1103///
1104/// `desc` must be writable, `obj` a live `JSValue`.
1105#[unsafe(no_mangle)]
1106pub unsafe extern "C" fn JS_GetOwnProperty(
1107    ctx: *mut JsContext,
1108    desc: *mut JSPropertyDescriptor,
1109    obj: JsValue,
1110    prop: Atom,
1111) -> c_int {
1112    let Some(context) = (unsafe { ctx.as_ref() }) else {
1113        return -1;
1114    };
1115    let Some(target) = (unsafe { arg(obj) }) else {
1116        runtime::throw_error(context, "TypeError", "not a value");
1117        return -1;
1118    };
1119    let Some(key) = atom_key(context, prop) else {
1120        return 0;
1121    };
1122    let found = context.with_current_interp(|interp| {
1123        let object = match &target {
1124            Value::Object(object) => object.clone(),
1125            other => interp.object_from(other)?,
1126        };
1127        interp.object_get_own_property(&object, &key)
1128    });
1129    let property = match found {
1130        Ok(Some(property)) => property,
1131        Ok(None) => return 0,
1132        Err(signal) => {
1133            let _ = runtime::result_value(context, Err(signal));
1134            return -1;
1135        }
1136    };
1137    if desc.is_null() {
1138        return 1;
1139    }
1140    let mut flags = 0;
1141    if property.configurable {
1142        flags |= c_int::from(prop::CONFIGURABLE);
1143    }
1144    if property.writable {
1145        flags |= c_int::from(prop::WRITABLE);
1146    }
1147    if property.enumerable {
1148        flags |= c_int::from(prop::ENUMERABLE);
1149    }
1150    // `JS_PROP_GETSET` for an accessor; a data property leaves the bit clear.
1151    let is_accessor =
1152        property.getter.is_some() || property.setter.is_some() || property.value.is_none();
1153    if is_accessor {
1154        flags |= 1 << 4;
1155    }
1156    let descriptor = JSPropertyDescriptor {
1157        flags,
1158        value: property
1159            .value
1160            .as_ref()
1161            .map(|v| jsvalue_of(v.clone()))
1162            .unwrap_or(jsvalue::UNDEFINED),
1163        getter: property
1164            .getter
1165            .as_ref()
1166            .map(|v| jsvalue_of(v.clone()))
1167            .unwrap_or(jsvalue::UNDEFINED),
1168        setter: property
1169            .setter
1170            .as_ref()
1171            .map(|v| jsvalue_of(v.clone()))
1172            .unwrap_or(jsvalue::UNDEFINED),
1173    };
1174    // SAFETY: the caller guarantees a writable pointer.
1175    unsafe { desc.write(descriptor) };
1176    1
1177}
1178
1179// ---------------------------------------------------------------------------
1180// Prototype and extensibility
1181// ---------------------------------------------------------------------------
1182
1183/// `JS_GetPrototype`: `[[GetPrototypeOf]]`, or `null` for an object with none.
1184///
1185/// # Safety
1186///
1187/// `val` must be a live `JSValue`.
1188#[unsafe(no_mangle)]
1189pub unsafe extern "C" fn JS_GetPrototype(ctx: *mut JsContext, val: JsValue) -> JsValue {
1190    let Some(context) = (unsafe { ctx.as_ref() }) else {
1191        return jsvalue::EXCEPTION;
1192    };
1193    let Some(value) = (unsafe { arg(val) }) else {
1194        return runtime::throw_error(context, "TypeError", "not a value");
1195    };
1196    let result = context.with_current_interp(|interp| {
1197        let object = match &value {
1198            Value::Object(object) => object.clone(),
1199            other => interp.object_from(other)?,
1200        };
1201        Ok(match interp.object_prototype_of(&object)? {
1202            Some(proto) => Value::Object(proto),
1203            None => Value::Null,
1204        })
1205    });
1206    runtime::result_value(context, result)
1207}
1208
1209/// `JS_SetPrototype`: `[[SetPrototypeOf]]`, answering `-1` for a refused cycle.
1210///
1211/// # Safety
1212///
1213/// `obj` and `proto_val` must be live `JSValue`s.
1214#[unsafe(no_mangle)]
1215pub unsafe extern "C" fn JS_SetPrototype(
1216    ctx: *mut JsContext,
1217    obj: JsValue,
1218    proto_val: JsValue,
1219) -> c_int {
1220    let Some(context) = (unsafe { ctx.as_ref() }) else {
1221        return -1;
1222    };
1223    let Some(target) = (unsafe { arg(obj) }) else {
1224        runtime::throw_error(context, "TypeError", "not an object");
1225        return -1;
1226    };
1227    let proto = match unsafe { arg(proto_val) } {
1228        Some(Value::Object(object)) => Some(object),
1229        Some(Value::Null) => None,
1230        _ => {
1231            runtime::throw_error(context, "TypeError", "prototype must be an object or null");
1232            return -1;
1233        }
1234    };
1235    let result = context.with_current_interp(|interp| {
1236        let object = match &target {
1237            Value::Object(object) => object.clone(),
1238            other => interp.object_from(other)?,
1239        };
1240        let accepted = interp.object_set_prototype_of(&object, proto)?;
1241        Ok(if accepted { 0 } else { -1 })
1242    });
1243    match result {
1244        Ok(answer) => answer,
1245        Err(signal) => {
1246            let _ = runtime::result_value(context, Err(signal));
1247            -1
1248        }
1249    }
1250}
1251
1252/// `JS_IsExtensible`: whether new properties may be added.
1253///
1254/// # Safety
1255///
1256/// `obj` must be a live `JSValue`.
1257#[unsafe(no_mangle)]
1258pub unsafe extern "C" fn JS_IsExtensible(ctx: *mut JsContext, obj: JsValue) -> c_int {
1259    let Some(context) = (unsafe { ctx.as_ref() }) else {
1260        return -1;
1261    };
1262    let Some(target) = (unsafe { arg(obj) }) else {
1263        runtime::throw_error(context, "TypeError", "not a value");
1264        return -1;
1265    };
1266    let result = context.with_current_interp(|interp| {
1267        let object = match &target {
1268            Value::Object(object) => object.clone(),
1269            other => interp.object_from(other)?,
1270        };
1271        let extensible = interp.object_is_extensible(&object)?;
1272        Ok(c_int::from(extensible))
1273    });
1274    match result {
1275        Ok(answer) => answer,
1276        Err(signal) => {
1277            let _ = runtime::result_value(context, Err(signal));
1278            -1
1279        }
1280    }
1281}
1282
1283/// `JS_PreventExtensions`: make the object non-extensible.
1284///
1285/// # Safety
1286///
1287/// `obj` must be a live `JSValue`.
1288#[unsafe(no_mangle)]
1289pub unsafe extern "C" fn JS_PreventExtensions(ctx: *mut JsContext, obj: JsValue) -> c_int {
1290    let Some(context) = (unsafe { ctx.as_ref() }) else {
1291        return -1;
1292    };
1293    let Some(target) = (unsafe { arg(obj) }) else {
1294        runtime::throw_error(context, "TypeError", "not a value");
1295        return -1;
1296    };
1297    let result = context.with_current_interp(|interp| {
1298        let object = match &target {
1299            Value::Object(object) => object.clone(),
1300            other => interp.object_from(other)?,
1301        };
1302        let accepted = interp.object_prevent_extensions(&object)?;
1303        Ok(if accepted { 0 } else { -1 })
1304    });
1305    match result {
1306        Ok(answer) => answer,
1307        Err(signal) => {
1308            let _ = runtime::result_value(context, Err(signal));
1309            -1
1310        }
1311    }
1312}
1313
1314/// `JS_SetConstructorBit`: whether `new` is allowed on a function object.
1315///
1316/// # Safety
1317///
1318/// `func_obj` must be a live `JSValue`.
1319#[unsafe(no_mangle)]
1320pub unsafe extern "C" fn JS_SetConstructorBit(
1321    ctx: *mut JsContext,
1322    func_obj: JsValue,
1323    val: Bool,
1324) -> Bool {
1325    let Some(context) = (unsafe { ctx.as_ref() }) else {
1326        return 0;
1327    };
1328    let Some(Value::Object(object)) = (unsafe { arg(func_obj) }) else {
1329        runtime::throw_error(context, "TypeError", "not an object");
1330        return 0;
1331    };
1332    if !object.is_callable() {
1333        runtime::throw_error(context, "TypeError", "not a function");
1334        return 0;
1335    }
1336    object.set_constructible(val != 0);
1337    1
1338}
1339
1340/// `JS_SetIsHTMLDDA`: mark the object as `document.all`-like.
1341///
1342/// No engine here produces such an object — it exists for a browser's fault-tolerance
1343/// requirements — and pretending otherwise would need a `[[IsHTMLDDA]]` slot in the engine.
1344/// The function exists so a module referencing it links; it reports success and does nothing,
1345/// which is visible only to a script that tests `if (obj)`, and no such script can exist here
1346/// without the object that has the slot.
1347///
1348/// # Safety
1349///
1350/// `obj` must be a live `JSValue`.
1351#[unsafe(no_mangle)]
1352pub unsafe extern "C" fn JS_SetIsHTMLDDA(_ctx: *mut JsContext, _obj: JsValue) {}
1353
1354/// `JS_SetUncatchableException`: prevent `try`/`catch` from seeing the pending exception.
1355///
1356/// Sets the interpreter's unwind mode: while it is on, a throw walks past every `catch` on
1357/// the stack. It is cleared when the next outermost evaluation starts, so the flag applies
1358/// to the exception the caller is about to raise and not to the program's whole future —
1359/// which is how the reference's single `ctx->is_uncatchable` flag behaves too (it is reset
1360/// on every `JS_Throw*`).
1361///
1362/// The same flag is what an interrupt sets, so a host that stops a runaway loop with
1363/// `JS_SetInterruptHandler` gets the reference's behaviour: the script cannot swallow the
1364/// abort.
1365///
1366/// # Safety
1367///
1368/// `ctx` must be a live context.
1369#[unsafe(no_mangle)]
1370pub unsafe extern "C" fn JS_SetUncatchableException(ctx: *mut JsContext, flag: Bool) {
1371    let Some(context) = (unsafe { ctx.as_ref() }) else {
1372        return;
1373    };
1374    // The *standing request*, not the active mode: the host sets this and then evaluates,
1375    // so the throw that evaluation raises is the one it applies to.
1376    context.with_current_interp(|interp| interp.uncatchable_next = flag != 0);
1377}
1378
1379/// A helper used by [`JS_Throw`]-family conversions that need `Signal`.
1380#[allow(dead_code)]
1381fn signal_of(interp: &engine::Interp<'_>, message: &str) -> Signal {
1382    interp.type_error(message)
1383}