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            descriptor_fields: None,
565        }
566    } else {
567        engine::object::Property {
568            value: value.or(Some(Value::Undefined)),
569            getter: None,
570            setter: None,
571            writable,
572            enumerable,
573            configurable,
574            descriptor_fields: None,
575        }
576    })
577}
578
579/// `JS_DefinePropertyValue`: define a data property, consuming `val`.
580///
581/// # Safety
582///
583/// `this_obj` must be a live `JSValue`; `val`'s reference is consumed.
584#[unsafe(no_mangle)]
585pub unsafe extern "C" fn JS_DefinePropertyValue(
586    ctx: *mut JsContext,
587    this_obj: JsValue,
588    prop: Atom,
589    val: JsValue,
590    flags: c_int,
591) -> c_int {
592    let Some(context) = (unsafe { ctx.as_ref() }) else {
593        return -1;
594    };
595    let Some(key) = atom_key(context, prop) else {
596        unsafe { runtime::release(val) };
597        runtime::throw_error(context, "TypeError", "invalid atom");
598        return -1;
599    };
600    define_value(context, this_obj, key, val, flags)
601}
602
603/// `JS_DefinePropertyValueStr`: the same, keyed by a string.
604///
605/// # Safety
606///
607/// `this_obj` a live `JSValue`, `name` NUL-terminated; `val`'s reference is consumed.
608#[unsafe(no_mangle)]
609pub unsafe extern "C" fn JS_DefinePropertyValueStr(
610    ctx: *mut JsContext,
611    this_obj: JsValue,
612    name: *const c_char,
613    val: JsValue,
614    flags: c_int,
615) -> c_int {
616    let Some(context) = (unsafe { ctx.as_ref() }) else {
617        return -1;
618    };
619    // SAFETY: the caller guarantees a NUL-terminated string.
620    let key = PropertyKey::from(unsafe { c_text(name) });
621    define_value(context, this_obj, key, val, flags)
622}
623
624/// `JS_DefinePropertyValueUint32`: the same, keyed by an index.
625///
626/// # Safety
627///
628/// As [`JS_DefinePropertyValueStr`].
629#[unsafe(no_mangle)]
630pub unsafe extern "C" fn JS_DefinePropertyValueUint32(
631    ctx: *mut JsContext,
632    this_obj: JsValue,
633    idx: u32,
634    val: JsValue,
635    flags: c_int,
636) -> c_int {
637    let Some(context) = (unsafe { ctx.as_ref() }) else {
638        return -1;
639    };
640    define_value(
641        context,
642        this_obj,
643        PropertyKey::from(idx.to_string()),
644        val,
645        flags,
646    )
647}
648
649/// `JS_DefinePropertyValueInt64`: the same, keyed by a 64-bit index.
650///
651/// # Safety
652///
653/// As [`JS_DefinePropertyValueStr`].
654#[unsafe(no_mangle)]
655pub unsafe extern "C" fn JS_DefinePropertyValueInt64(
656    ctx: *mut JsContext,
657    this_obj: JsValue,
658    idx: i64,
659    val: JsValue,
660    flags: c_int,
661) -> c_int {
662    let Some(context) = (unsafe { ctx.as_ref() }) else {
663        return -1;
664    };
665    define_value(
666        context,
667        this_obj,
668        PropertyKey::from(idx.to_string()),
669        val,
670        flags,
671    )
672}
673
674/// `JS_DefinePropertyValueValue`: the same, keyed by a value (`ToPropertyKey` on it).
675///
676/// # Safety
677///
678/// Both values must be live; `prop`'s and `val`'s references are consumed.
679#[unsafe(no_mangle)]
680pub unsafe extern "C" fn JS_DefinePropertyValueValue(
681    ctx: *mut JsContext,
682    this_obj: JsValue,
683    prop: JsValue,
684    val: JsValue,
685    flags: c_int,
686) -> c_int {
687    let Some(context) = (unsafe { ctx.as_ref() }) else {
688        return -1;
689    };
690    let Some(key_value) = (unsafe { arg(prop) }) else {
691        unsafe {
692            runtime::release(prop);
693            runtime::release(val);
694        }
695        runtime::throw_error(context, "TypeError", "not a value");
696        return -1;
697    };
698    // SAFETY: the C API consumes the key's reference.
699    unsafe { runtime::release(prop) };
700    match context.with_current_interp(|interp| interp.propkey(&key_value)) {
701        Ok(key) => define_value(context, this_obj, key, val, flags),
702        Err(signal) => {
703            // SAFETY: the value's reference is consumed even on this path.
704            unsafe { runtime::release(val) };
705            let _ = runtime::result_value(context, Err(signal));
706            -1
707        }
708    }
709}
710
711/// The shared body of the `JS_DefinePropertyValue*` family.
712fn define_value(
713    context: &JsContext,
714    this_obj: JsValue,
715    key: PropertyKey,
716    val: JsValue,
717    flags: c_int,
718) -> c_int {
719    let Some(target) = (unsafe { arg(this_obj) }) else {
720        // SAFETY: the reference is consumed whatever happens.
721        unsafe { runtime::release(val) };
722        runtime::throw_error(context, "TypeError", "not an object");
723        return -1;
724    };
725    let Some(value) = (unsafe { arg(val) }) else {
726        runtime::throw_error(context, "TypeError", "not a value");
727        return -1;
728    };
729    // SAFETY: the C API consumes the reference.
730    unsafe { runtime::release(val) };
731    let Some(property) = property_from_flags(context, flags, Some(value), None, None) else {
732        runtime::throw_error(context, "TypeError", "unsupported property flags");
733        return -1;
734    };
735    let result = context.with_current_interp(|interp| {
736        let object = match &target {
737            Value::Object(object) => object.clone(),
738            other => interp.object_from(other)?,
739        };
740        let accepted = interp.object_define_own_property(&object, &key, property)?;
741        Ok(if accepted { 0 } else { -1 })
742    });
743    match result {
744        Ok(answer) => answer,
745        Err(signal) => {
746            let _ = runtime::result_value(context, Err(signal));
747            -1
748        }
749    }
750}
751
752/// `JS_DefineProperty`: define an accessor and/or a value in one call.
753///
754/// Only the fields the flags say are present are used, which is what lets a caller change a
755/// property's attributes without touching what it holds.
756///
757/// # Safety
758///
759/// `this_obj` must be live; `val`, `getter` and `setter` are read, and the ones the flags
760/// name are consumed.
761#[unsafe(no_mangle)]
762pub unsafe extern "C" fn JS_DefineProperty(
763    ctx: *mut JsContext,
764    this_obj: JsValue,
765    prop: Atom,
766    val: JsValue,
767    getter: JsValue,
768    setter: JsValue,
769    flags: c_int,
770) -> c_int {
771    let Some(context) = (unsafe { ctx.as_ref() }) else {
772        return -1;
773    };
774    let Some(key) = atom_key(context, prop) else {
775        unsafe {
776            runtime::release(val);
777            runtime::release(getter);
778            runtime::release(setter);
779        }
780        runtime::throw_error(context, "TypeError", "invalid atom");
781        return -1;
782    };
783    define_property(context, this_obj, key, val, getter, setter, flags)
784}
785
786/// `JS_DefinePropertyGetSet`: the accessor-only spelling.
787///
788/// # Safety
789///
790/// As [`JS_DefineProperty`]; `getter` and `setter`'s references are consumed.
791#[unsafe(no_mangle)]
792pub unsafe extern "C" fn JS_DefinePropertyGetSet(
793    ctx: *mut JsContext,
794    this_obj: JsValue,
795    prop: Atom,
796    getter: JsValue,
797    setter: JsValue,
798    flags: c_int,
799) -> c_int {
800    let Some(context) = (unsafe { ctx.as_ref() }) else {
801        return -1;
802    };
803    let Some(key) = atom_key(context, prop) else {
804        unsafe {
805            runtime::release(getter);
806            runtime::release(setter);
807        }
808        runtime::throw_error(context, "TypeError", "invalid atom");
809        return -1;
810    };
811    // The accessor convention is `flags | JS_PROP_GETSET`, and the value is "not present" so
812    // the property is an accessor and stays one.
813    let flags = flags | (1 << 4) | (1 << 11) | (1 << 12);
814    define_property(
815        context,
816        this_obj,
817        key,
818        jsvalue::UNDEFINED,
819        getter,
820        setter,
821        flags,
822    )
823}
824
825/// The shared body of [`JS_DefineProperty`] and [`JS_DefinePropertyGetSet`].
826fn define_property(
827    context: &JsContext,
828    this_obj: JsValue,
829    key: PropertyKey,
830    val: JsValue,
831    getter: JsValue,
832    setter: JsValue,
833    flags: c_int,
834) -> c_int {
835    let Some(target) = (unsafe { arg(this_obj) }) else {
836        unsafe {
837            runtime::release(val);
838            runtime::release(getter);
839            runtime::release(setter);
840        }
841        runtime::throw_error(context, "TypeError", "not an object");
842        return -1;
843    };
844    // A field is read only when its "present" bit is set; releasing an absent one is wrong
845    // because the caller passed `JS_UNDEFINED` for it, which owns no reference anyway.
846    let has_value = flags & (1 << 13) != 0 || flags & (1 << 4) == 0;
847    let has_get = flags & (1 << 11) != 0;
848    let has_set = flags & (1 << 12) != 0;
849    let value = if has_value {
850        let decoded = unsafe { arg(val) };
851        // SAFETY: the C API consumes what it uses.
852        unsafe { runtime::release(val) };
853        decoded
854    } else {
855        None
856    };
857    let getter = if has_get {
858        let decoded = unsafe { arg(getter) };
859        // SAFETY: as above.
860        unsafe { runtime::release(getter) };
861        decoded
862    } else {
863        None
864    };
865    let setter = if has_set {
866        let decoded = unsafe { arg(setter) };
867        // SAFETY: as above.
868        unsafe { runtime::release(setter) };
869        decoded
870    } else {
871        None
872    };
873    let Some(property) = property_from_flags(context, flags, value, getter, setter) else {
874        runtime::throw_error(context, "TypeError", "unsupported property flags");
875        return -1;
876    };
877    let result = context.with_current_interp(|interp| {
878        let object = match &target {
879            Value::Object(object) => object.clone(),
880            other => interp.object_from(other)?,
881        };
882        let accepted = interp.object_define_own_property(&object, &key, property)?;
883        Ok(if accepted { 0 } else { -1 })
884    });
885    match result {
886        Ok(answer) => answer,
887        Err(signal) => {
888            let _ = runtime::result_value(context, Err(signal));
889            -1
890        }
891    }
892}
893
894// ---------------------------------------------------------------------------
895// Deleting
896// ---------------------------------------------------------------------------
897
898/// `JS_DeleteProperty`: delete `obj[prop]`.
899///
900/// `flags` may carry `JS_PROP_THROW`, in which case the reference answers `-1` for a refused
901/// delete *and* raises a `TypeError` in strict mode. `true` is `1`, `false` is `0`.
902///
903/// # Safety
904///
905/// `obj` must be a live `JSValue`.
906#[unsafe(no_mangle)]
907pub unsafe extern "C" fn JS_DeleteProperty(
908    ctx: *mut JsContext,
909    obj: JsValue,
910    prop: Atom,
911    flags: c_int,
912) -> c_int {
913    let Some(context) = (unsafe { ctx.as_ref() }) else {
914        return -1;
915    };
916    let Some(key) = atom_key(context, prop) else {
917        return 0;
918    };
919    delete_key(context, obj, key, flags)
920}
921
922/// `JS_DeletePropertyInt64`: the same, keyed by an index.
923///
924/// # Safety
925///
926/// As [`JS_DeleteProperty`].
927#[unsafe(no_mangle)]
928pub unsafe extern "C" fn JS_DeletePropertyInt64(
929    ctx: *mut JsContext,
930    obj: JsValue,
931    idx: i64,
932    flags: c_int,
933) -> c_int {
934    let Some(context) = (unsafe { ctx.as_ref() }) else {
935        return -1;
936    };
937    delete_key(context, obj, PropertyKey::from(idx.to_string()), flags)
938}
939
940/// The shared body of the two deletes.
941fn delete_key(context: &JsContext, obj: JsValue, key: PropertyKey, flags: c_int) -> c_int {
942    let Some(target) = (unsafe { arg(obj) }) else {
943        runtime::throw_error(context, "TypeError", "not an object");
944        return -1;
945    };
946    let throw = flags & PROP_THROW != 0;
947    let result = context.with_current_interp(|interp| {
948        let object = match &target {
949            Value::Object(object) => object.clone(),
950            other => interp.object_from(other)?,
951        };
952        let deleted = interp.delete_property_key(&object, &key)?;
953        // A refused delete is a `TypeError` in strict mode and a `false` result in sloppy
954        // mode; the reference's `-1` is the strict path.
955        if !deleted && throw {
956            return Err(interp.type_error(format!("cannot delete property '{key}'")));
957        }
958        Ok(c_int::from(deleted))
959    });
960    match result {
961        Ok(answer) => answer,
962        Err(signal) => {
963            let _ = runtime::result_value(context, Err(signal));
964            -1
965        }
966    }
967}
968
969// ---------------------------------------------------------------------------
970// Own properties
971// ---------------------------------------------------------------------------
972
973/// `JS_GetOwnPropertyNames`: `ptab`/`plen` filled with the object's own keys.
974///
975/// The block is one allocation holding `len` `JSPropertyEnum`s, so
976/// `JS_FreePropertyEnum(ctx, tab, len)` can release it as one — which is what the reference
977/// does and what every caller assumes.
978///
979/// # Safety
980///
981/// `ptab` and `plen` must be writable, `obj` a live `JSValue`.
982#[unsafe(no_mangle)]
983pub unsafe extern "C" fn JS_GetOwnPropertyNames(
984    ctx: *mut JsContext,
985    ptab: *mut *mut JSPropertyEnum,
986    plen: *mut u32,
987    obj: JsValue,
988    flags: c_int,
989) -> c_int {
990    if !ptab.is_null() {
991        // SAFETY: the caller guarantees a writable pointer.
992        unsafe { *ptab = std::ptr::null_mut() };
993    }
994    if !plen.is_null() {
995        // SAFETY: as above.
996        unsafe { *plen = 0 };
997    }
998    let Some(context) = (unsafe { ctx.as_ref() }) else {
999        return -1;
1000    };
1001    let Some(target) = (unsafe { arg(obj) }) else {
1002        runtime::throw_error(context, "TypeError", "not a value");
1003        return -1;
1004    };
1005    let entries = context.with_current_interp(|interp| {
1006        let object = match &target {
1007            Value::Object(object) => object.clone(),
1008            other => interp.object_from(other)?,
1009        };
1010        let keys = interp.object_own_property_keys(&object)?;
1011        let mut entries: Vec<(Atom, bool)> = Vec::new();
1012        for key in keys {
1013            let is_symbol = key.is_symbol();
1014            // `JS_GPN_*_MASK` selects which kinds are reported. The reference's default
1015            // (no mask set) is strings *and* symbols, which is what `Reflect.ownKeys` gives.
1016            let any_mask = flags & (GPN_STRING_MASK | GPN_SYMBOL_MASK | GPN_PRIVATE_MASK);
1017            let wanted = if any_mask == 0 {
1018                true
1019            } else if is_symbol {
1020                flags & GPN_SYMBOL_MASK != 0
1021            } else {
1022                flags & GPN_STRING_MASK != 0
1023            };
1024            if !wanted {
1025                continue;
1026            }
1027            let property = interp.object_get_own_property(&object, &key)?;
1028            let enumerable = property.as_ref().is_some_and(|p| p.enumerable);
1029            if flags & GPN_ENUM_ONLY != 0 && !enumerable {
1030                continue;
1031            }
1032            // A symbol key has no atom, and this layer's atom table has no symbol entries, so
1033            // it is reported under its description — which is the only thing a C caller can
1034            // do with it anyway (`JS_AtomToString` is the only reader).
1035            let text = match &key {
1036                PropertyKey::String(text) => text.to_string_lossy().into_owned(),
1037                PropertyKey::Symbol(symbol) => symbol.to_display_string(),
1038            };
1039            let atom = with_atoms(context, |table| table.intern(&text));
1040            entries.push((atom, enumerable));
1041        }
1042        Ok(entries)
1043    });
1044    let entries = match entries {
1045        Ok(entries) => entries,
1046        Err(signal) => {
1047            let _ = runtime::result_value(context, Err(signal));
1048            return -1;
1049        }
1050    };
1051    if entries.is_empty() {
1052        return 0;
1053    }
1054    let size = entries.len() * core::mem::size_of::<JSPropertyEnum>();
1055    // SAFETY: `alloc_raw_zeroed` gives `size` zeroed, 8-aligned bytes.
1056    let block = unsafe { crate::alloc::alloc_raw_zeroed(size) };
1057    if block.is_null() {
1058        runtime::throw_error(context, "InternalError", "out of memory");
1059        return -1;
1060    }
1061    // SAFETY: the block is `entries.len()` `JSPropertyEnum`s.
1062    let table = block.cast::<JSPropertyEnum>();
1063    for (index, (atom, enumerable)) in entries.iter().enumerate() {
1064        // SAFETY: `index` is in range.
1065        unsafe {
1066            table.add(index).write(JSPropertyEnum {
1067                is_enumerable: if flags & GPN_SET_ENUM != 0 {
1068                    c_int::from(*enumerable)
1069                } else {
1070                    0
1071                },
1072                atom: *atom,
1073            });
1074        }
1075    }
1076    if !ptab.is_null() {
1077        // SAFETY: the caller guarantees a writable pointer.
1078        unsafe { *ptab = table };
1079    }
1080    if !plen.is_null() {
1081        // SAFETY: as above.
1082        unsafe { *plen = entries.len() as u32 };
1083    }
1084    0
1085}
1086
1087/// `JS_FreePropertyEnum`: release what [`JS_GetOwnPropertyNames`] allocated.
1088///
1089/// # Safety
1090///
1091/// `tab` must come from `JS_GetOwnPropertyNames` with the same `len`, and not be used again.
1092#[unsafe(no_mangle)]
1093pub unsafe extern "C" fn JS_FreePropertyEnum(
1094    _ctx: *mut JsContext,
1095    tab: *mut JSPropertyEnum,
1096    _len: u32,
1097) {
1098    // SAFETY: the caller's contract; the allocator checks the header before freeing.
1099    unsafe { crate::alloc::free_raw(tab.cast()) }
1100}
1101
1102/// `JS_GetOwnProperty`: a complete descriptor for `obj[prop]`.
1103///
1104/// # Safety
1105///
1106/// `desc` must be writable, `obj` a live `JSValue`.
1107#[unsafe(no_mangle)]
1108pub unsafe extern "C" fn JS_GetOwnProperty(
1109    ctx: *mut JsContext,
1110    desc: *mut JSPropertyDescriptor,
1111    obj: JsValue,
1112    prop: Atom,
1113) -> c_int {
1114    let Some(context) = (unsafe { ctx.as_ref() }) else {
1115        return -1;
1116    };
1117    let Some(target) = (unsafe { arg(obj) }) else {
1118        runtime::throw_error(context, "TypeError", "not a value");
1119        return -1;
1120    };
1121    let Some(key) = atom_key(context, prop) else {
1122        return 0;
1123    };
1124    let found = context.with_current_interp(|interp| {
1125        let object = match &target {
1126            Value::Object(object) => object.clone(),
1127            other => interp.object_from(other)?,
1128        };
1129        interp.object_get_own_property(&object, &key)
1130    });
1131    let property = match found {
1132        Ok(Some(property)) => property,
1133        Ok(None) => return 0,
1134        Err(signal) => {
1135            let _ = runtime::result_value(context, Err(signal));
1136            return -1;
1137        }
1138    };
1139    if desc.is_null() {
1140        return 1;
1141    }
1142    let mut flags = 0;
1143    if property.configurable {
1144        flags |= c_int::from(prop::CONFIGURABLE);
1145    }
1146    if property.writable {
1147        flags |= c_int::from(prop::WRITABLE);
1148    }
1149    if property.enumerable {
1150        flags |= c_int::from(prop::ENUMERABLE);
1151    }
1152    // `JS_PROP_GETSET` for an accessor; a data property leaves the bit clear.
1153    let is_accessor =
1154        property.getter.is_some() || property.setter.is_some() || property.value.is_none();
1155    if is_accessor {
1156        flags |= 1 << 4;
1157    }
1158    let descriptor = JSPropertyDescriptor {
1159        flags,
1160        value: property
1161            .value
1162            .as_ref()
1163            .map(|v| jsvalue_of(v.clone()))
1164            .unwrap_or(jsvalue::UNDEFINED),
1165        getter: property
1166            .getter
1167            .as_ref()
1168            .map(|v| jsvalue_of(v.clone()))
1169            .unwrap_or(jsvalue::UNDEFINED),
1170        setter: property
1171            .setter
1172            .as_ref()
1173            .map(|v| jsvalue_of(v.clone()))
1174            .unwrap_or(jsvalue::UNDEFINED),
1175    };
1176    // SAFETY: the caller guarantees a writable pointer.
1177    unsafe { desc.write(descriptor) };
1178    1
1179}
1180
1181// ---------------------------------------------------------------------------
1182// Prototype and extensibility
1183// ---------------------------------------------------------------------------
1184
1185/// `JS_GetPrototype`: `[[GetPrototypeOf]]`, or `null` for an object with none.
1186///
1187/// # Safety
1188///
1189/// `val` must be a live `JSValue`.
1190#[unsafe(no_mangle)]
1191pub unsafe extern "C" fn JS_GetPrototype(ctx: *mut JsContext, val: JsValue) -> JsValue {
1192    let Some(context) = (unsafe { ctx.as_ref() }) else {
1193        return jsvalue::EXCEPTION;
1194    };
1195    let Some(value) = (unsafe { arg(val) }) else {
1196        return runtime::throw_error(context, "TypeError", "not a value");
1197    };
1198    let result = context.with_current_interp(|interp| {
1199        let object = match &value {
1200            Value::Object(object) => object.clone(),
1201            other => interp.object_from(other)?,
1202        };
1203        Ok(match interp.object_prototype_of(&object)? {
1204            Some(proto) => Value::Object(proto),
1205            None => Value::Null,
1206        })
1207    });
1208    runtime::result_value(context, result)
1209}
1210
1211/// `JS_SetPrototype`: `[[SetPrototypeOf]]`, answering `-1` for a refused cycle.
1212///
1213/// # Safety
1214///
1215/// `obj` and `proto_val` must be live `JSValue`s.
1216#[unsafe(no_mangle)]
1217pub unsafe extern "C" fn JS_SetPrototype(
1218    ctx: *mut JsContext,
1219    obj: JsValue,
1220    proto_val: JsValue,
1221) -> c_int {
1222    let Some(context) = (unsafe { ctx.as_ref() }) else {
1223        return -1;
1224    };
1225    let Some(target) = (unsafe { arg(obj) }) else {
1226        runtime::throw_error(context, "TypeError", "not an object");
1227        return -1;
1228    };
1229    let proto = match unsafe { arg(proto_val) } {
1230        Some(Value::Object(object)) => Some(object),
1231        Some(Value::Null) => None,
1232        _ => {
1233            runtime::throw_error(context, "TypeError", "prototype must be an object or null");
1234            return -1;
1235        }
1236    };
1237    let result = context.with_current_interp(|interp| {
1238        let object = match &target {
1239            Value::Object(object) => object.clone(),
1240            other => interp.object_from(other)?,
1241        };
1242        let accepted = interp.object_set_prototype_of(&object, proto)?;
1243        // This is the *throwing* form: the reference calls `JS_SetPrototypeInternal` with
1244        // `throw_flag` set, so a refusal — the operation itself fails quietly — surfaces as
1245        // a `TypeError`. Answering a bare `-1` left the caller with an error code and no
1246        // exception to describe it.
1247        if !accepted {
1248            return Err(interp.type_error("circular prototype chain"));
1249        }
1250        Ok(0)
1251    });
1252    match result {
1253        Ok(answer) => answer,
1254        Err(signal) => {
1255            let _ = runtime::result_value(context, Err(signal));
1256            -1
1257        }
1258    }
1259}
1260
1261/// `JS_IsExtensible`: whether new properties may be added.
1262///
1263/// # Safety
1264///
1265/// `obj` must be a live `JSValue`.
1266#[unsafe(no_mangle)]
1267pub unsafe extern "C" fn JS_IsExtensible(ctx: *mut JsContext, obj: JsValue) -> c_int {
1268    let Some(context) = (unsafe { ctx.as_ref() }) else {
1269        return -1;
1270    };
1271    let Some(target) = (unsafe { arg(obj) }) else {
1272        runtime::throw_error(context, "TypeError", "not a value");
1273        return -1;
1274    };
1275    let result = context.with_current_interp(|interp| {
1276        let object = match &target {
1277            Value::Object(object) => object.clone(),
1278            other => interp.object_from(other)?,
1279        };
1280        let extensible = interp.object_is_extensible(&object)?;
1281        Ok(c_int::from(extensible))
1282    });
1283    match result {
1284        Ok(answer) => answer,
1285        Err(signal) => {
1286            let _ = runtime::result_value(context, Err(signal));
1287            -1
1288        }
1289    }
1290}
1291
1292/// `JS_PreventExtensions`: make the object non-extensible.
1293///
1294/// # Safety
1295///
1296/// `obj` must be a live `JSValue`.
1297#[unsafe(no_mangle)]
1298pub unsafe extern "C" fn JS_PreventExtensions(ctx: *mut JsContext, obj: JsValue) -> c_int {
1299    let Some(context) = (unsafe { ctx.as_ref() }) else {
1300        return -1;
1301    };
1302    let Some(target) = (unsafe { arg(obj) }) else {
1303        runtime::throw_error(context, "TypeError", "not a value");
1304        return -1;
1305    };
1306    let result = context.with_current_interp(|interp| {
1307        let object = match &target {
1308            Value::Object(object) => object.clone(),
1309            other => interp.object_from(other)?,
1310        };
1311        let accepted = interp.object_prevent_extensions(&object)?;
1312        Ok(if accepted { 0 } else { -1 })
1313    });
1314    match result {
1315        Ok(answer) => answer,
1316        Err(signal) => {
1317            let _ = runtime::result_value(context, Err(signal));
1318            -1
1319        }
1320    }
1321}
1322
1323/// `JS_SetConstructorBit`: whether `new` is allowed on a function object.
1324///
1325/// # Safety
1326///
1327/// `func_obj` must be a live `JSValue`.
1328#[unsafe(no_mangle)]
1329pub unsafe extern "C" fn JS_SetConstructorBit(
1330    ctx: *mut JsContext,
1331    func_obj: JsValue,
1332    val: Bool,
1333) -> Bool {
1334    let Some(context) = (unsafe { ctx.as_ref() }) else {
1335        return 0;
1336    };
1337    let Some(Value::Object(object)) = (unsafe { arg(func_obj) }) else {
1338        runtime::throw_error(context, "TypeError", "not an object");
1339        return 0;
1340    };
1341    if !object.is_callable() {
1342        runtime::throw_error(context, "TypeError", "not a function");
1343        return 0;
1344    }
1345    object.set_constructible(val != 0);
1346    1
1347}
1348
1349/// `JS_SetIsHTMLDDA`: mark the object as `document.all`-like.
1350///
1351/// No engine here produces such an object — it exists for a browser's fault-tolerance
1352/// requirements — and pretending otherwise would need a `[[IsHTMLDDA]]` slot in the engine.
1353/// The function exists so a module referencing it links; it reports success and does nothing,
1354/// which is visible only to a script that tests `if (obj)`, and no such script can exist here
1355/// without the object that has the slot.
1356///
1357/// # Safety
1358///
1359/// `obj` must be a live `JSValue`.
1360#[unsafe(no_mangle)]
1361pub unsafe extern "C" fn JS_SetIsHTMLDDA(_ctx: *mut JsContext, _obj: JsValue) {}
1362
1363/// `JS_SetUncatchableException`: prevent `try`/`catch` from seeing the pending exception.
1364///
1365/// Sets the interpreter's unwind mode: while it is on, a throw walks past every `catch` on
1366/// the stack. It is cleared when the next outermost evaluation starts, so the flag applies
1367/// to the exception the caller is about to raise and not to the program's whole future —
1368/// which is how the reference's single `ctx->is_uncatchable` flag behaves too (it is reset
1369/// on every `JS_Throw*`).
1370///
1371/// The same flag is what an interrupt sets, so a host that stops a runaway loop with
1372/// `JS_SetInterruptHandler` gets the reference's behaviour: the script cannot swallow the
1373/// abort.
1374///
1375/// # Safety
1376///
1377/// `ctx` must be a live context.
1378#[unsafe(no_mangle)]
1379pub unsafe extern "C" fn JS_SetUncatchableException(ctx: *mut JsContext, flag: Bool) {
1380    let Some(context) = (unsafe { ctx.as_ref() }) else {
1381        return;
1382    };
1383    // The *standing request*, not the active mode: the host sets this and then evaluates,
1384    // so the throw that evaluation raises is the one it applies to.
1385    context.with_current_interp(|interp| interp.uncatchable_next = flag != 0);
1386}
1387
1388/// A helper used by [`JS_Throw`]-family conversions that need `Signal`.
1389#[allow(dead_code)]
1390fn signal_of(interp: &engine::Interp<'_>, message: &str) -> Signal {
1391    interp.type_error(message)
1392}